From 45b8f7296c343bdc94b86ccdcc0eadcc350fcbac Mon Sep 17 00:00:00 2001 From: Darko Bozhinovski Date: Thu, 22 Aug 2024 17:47:37 +0200 Subject: [PATCH 1/5] feat: adds astro and solid customUI integrations --- .../with-thirdpartyemailpassword/README.md | 34 ++ .../astro.config.mjs | 11 + .../with-thirdpartyemailpassword/package.json | 28 ++ .../public/favicon.svg | 9 + .../src/auth/Auth.ts | 246 ++++++++++ .../src/auth/STBEConfig.ts | 54 +++ .../src/auth/STFEConfig.ts | 16 + .../src/auth/appInfo.json | 6 + .../src/auth/superTokensHelper.ts | 304 +++++++++++++ .../with-thirdpartyemailpassword/src/env.d.ts | 1 + .../src/layouts/Root.astro | 142 ++++++ .../src/pages/auth/[...path]/[...route].ts | 23 + .../src/pages/auth/[...route].ts | 19 + .../src/pages/auth/callback/[...path].astro | 15 + .../src/pages/auth/sessioninfo.ts | 19 + .../src/pages/dashboard.astro | 39 ++ .../src/pages/index.astro | 81 ++++ .../src/pages/nonauth.astro | 8 + .../tsconfig.json | 3 + .../with-thirdpartyemailpassword/README.md | 34 ++ .../with-thirdpartyemailpassword/index.html | 13 + .../solidjs/with-thirdpartyemailpassword/npm | 0 .../with-thirdpartyemailpassword/package.json | 24 + .../public/vite.svg | 1 + .../with-thirdpartyemailpassword/server.ts | 105 +++++ .../with-thirdpartyemailpassword/src/App.css | 132 ++++++ .../with-thirdpartyemailpassword/src/Auth.tsx | 427 ++++++++++++++++++ .../src/Dashboard.tsx | 53 +++ .../src/assets/solid.svg | 1 + .../src/config/supertokens.ts | 23 + .../src/index.css | 68 +++ .../src/index.tsx | 22 + .../src/vite-env.d.ts | 1 + .../tsconfig.app.json | 28 ++ .../tsconfig.json | 11 + .../tsconfig.node.json | 13 + .../vite.config.ts | 9 + .../with-thirdpartyemailpassword/README.md | 2 +- 38 files changed, 2024 insertions(+), 1 deletion(-) create mode 100644 examples/astro/with-thirdpartyemailpassword/README.md create mode 100644 examples/astro/with-thirdpartyemailpassword/astro.config.mjs create mode 100644 examples/astro/with-thirdpartyemailpassword/package.json create mode 100644 examples/astro/with-thirdpartyemailpassword/public/favicon.svg create mode 100644 examples/astro/with-thirdpartyemailpassword/src/auth/Auth.ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json create mode 100644 examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/env.d.ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/layouts/Root.astro create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/auth/callback/[...path].astro create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/dashboard.astro create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/index.astro create mode 100644 examples/astro/with-thirdpartyemailpassword/src/pages/nonauth.astro create mode 100644 examples/astro/with-thirdpartyemailpassword/tsconfig.json create mode 100644 examples/solidjs/with-thirdpartyemailpassword/README.md create mode 100644 examples/solidjs/with-thirdpartyemailpassword/index.html create mode 100644 examples/solidjs/with-thirdpartyemailpassword/npm create mode 100644 examples/solidjs/with-thirdpartyemailpassword/package.json create mode 100644 examples/solidjs/with-thirdpartyemailpassword/public/vite.svg create mode 100644 examples/solidjs/with-thirdpartyemailpassword/server.ts create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/App.css create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/assets/solid.svg create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/index.css create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/index.tsx create mode 100644 examples/solidjs/with-thirdpartyemailpassword/src/vite-env.d.ts create mode 100644 examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json create mode 100644 examples/solidjs/with-thirdpartyemailpassword/tsconfig.json create mode 100644 examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json create mode 100644 examples/solidjs/with-thirdpartyemailpassword/vite.config.ts diff --git a/examples/astro/with-thirdpartyemailpassword/README.md b/examples/astro/with-thirdpartyemailpassword/README.md new file mode 100644 index 00000000..058bb769 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/README.md @@ -0,0 +1,34 @@ +![SuperTokens banner](https://raw.githubusercontent.com/supertokens/supertokens-logo/master/images/Artboard%20%E2%80%93%2027%402x.png) + +# SuperTokens ThirdPartyEmailPassword Demo app for Astro + +This demo app demonstrates the following use cases: + +- Social Login / Sign up +- Email & Password login +- Logout +- Session management & Calling APIs + +## Project setup + +Use `npm` to install the project dependencies: + +```bash +npm install +``` + +## Run the demo app + +```bash +npm run dev +``` + +The app will start on `http://localhost:4321` + +## Author + +Created with :heart: by the folks at supertokens.com. + +## License + +This project is licensed under the Apache 2.0 license. diff --git a/examples/astro/with-thirdpartyemailpassword/astro.config.mjs b/examples/astro/with-thirdpartyemailpassword/astro.config.mjs new file mode 100644 index 00000000..10cbcfb1 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/astro.config.mjs @@ -0,0 +1,11 @@ +import { defineConfig } from "astro/config"; + +import node from "@astrojs/node"; + +// https://astro.build/config +export default defineConfig({ + output: "server", + adapter: node({ + mode: "standalone" + }) +}); \ No newline at end of file diff --git a/examples/astro/with-thirdpartyemailpassword/package.json b/examples/astro/with-thirdpartyemailpassword/package.json new file mode 100644 index 00000000..f3d186ec --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/package.json @@ -0,0 +1,28 @@ +{ + "name": "astro-supertokens", + "type": "module", + "version": "0.0.1", + "scripts": { + "dev": "astro dev", + "start": "astro dev", + "build": "astro check && astro build", + "preview": "astro preview", + "astro": "astro" + }, + "dependencies": { + "@astrojs/check": "^0.9.2", + "@astrojs/node": "^8.3.3", + "astro": "^4.14.2", + "jsonwebtoken": "^9.0.2", + "jwks-rsa": "^3.1.0", + "micromatch": "^4.0.7", + "supertokens-node": "^20.0.2", + "supertokens-web-js": "^0.13.0", + "typescript": "^5.5.4" + }, + "devDependencies": { + "@types/micromatch": "^4.0.9", + "prettier": "^3.3.3", + "prettier-plugin-astro": "^0.14.1" + } +} diff --git a/examples/astro/with-thirdpartyemailpassword/public/favicon.svg b/examples/astro/with-thirdpartyemailpassword/public/favicon.svg new file mode 100644 index 00000000..f157bd1c --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/public/favicon.svg @@ -0,0 +1,9 @@ + + + + diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/Auth.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/Auth.ts new file mode 100644 index 00000000..201bc2fb --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/Auth.ts @@ -0,0 +1,246 @@ +import { signOut, signUp } from "supertokens-web-js/recipe/emailpassword"; +import { doesEmailExist } from "supertokens-web-js/recipe/emailpassword"; +import { signIn } from "supertokens-web-js/recipe/emailpassword"; +import { getAuthorisationURLWithQueryParamsAndSetState } from "supertokens-web-js/recipe/thirdparty"; +import { signInAndUp } from "supertokens-web-js/recipe/thirdparty"; + +export async function handleCallback() { + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if ( + response.createdNewRecipeUser && + response.user.loginMethods.length === 1 + ) { + // sign up successful + } else { + // sign in successful + } + window.location.assign("/dashboard"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert( + "No email provided by social login. Please use another form of login", + ); + window.location.assign("/"); // redirect back to login page + } + } catch (err: any) { + console.log(err); + + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function googleSignInClicked() { + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "google", + + // This is where Google should redirect the user back after login or error. + // This URL goes on the Google's dashboard as well. + frontendRedirectURI: "http://localhost:4321/auth/callback/google", + }); + + /* + Example value of authUrl: https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&include_granted_scopes=true&response_type=code&client_id=1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com&state=5a489996a28cafc83ddff&redirect_uri=https%3A%2F%2Fsupertokens.io%2Fdev%2Foauth%2Fredirect-to-app&flowName=GeneralOAuthFlow + */ + + // we redirect the user to google for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function githubSignInClicked() { + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "github", + + // This is where Google should redirect the user back after login or error. + // This URL goes on the Google's dashboard as well. + frontendRedirectURI: "http://localhost:4321/auth/callback/github", + }); + + /* + Example value of authUrl: https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&access_type=offline&include_granted_scopes=true&response_type=code&client_id=1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com&state=5a489996a28cafc83ddff&redirect_uri=https%3A%2F%2Fsupertokens.io%2Fdev%2Foauth%2Fredirect-to-app&flowName=GeneralOAuthFlow + */ + + // we redirect the user to google for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function signInClicked(email: string, password: string) { + try { + let response = await signIn({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax). + window.alert(formField.error); + } + }); + } else if (response.status === "WRONG_CREDENTIALS_ERROR") { + window.alert("Email password combination is incorrect."); + } else if (response.status === "SIGN_IN_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in was not allowed. + window.alert(response.reason); + } else { + // sign in successful. The session tokens are automatically handled by + // the frontend SDK. + window.location.href = "/dashboard"; + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function checkEmail(email: string) { + try { + let response = await doesEmailExist({ + email, + }); + + if (response.doesExist) { + window.alert("Email already exists. Please sign in instead"); + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function signUpClicked(email: string, password: string) { + try { + let response = await signUp({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + // one of the input formFields failed validation + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax), + // or the email is not unique. + window.alert(formField.error); + } else if (formField.id === "password") { + // Password validation failed. + // Maybe it didn't match the password strength + window.alert(formField.error); + } + }); + } else if (response.status === "SIGN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign up was not allowed. + window.alert(response.reason); + } else { + // sign up successful. The session tokens are automatically handled by + // the frontend SDK. + window.location.href = "/dashboard"; + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function signOutClicked() { + try { + await signOut(); + window.location.href = "/"; + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +export async function getSessionInfo() { + try { + let response = await fetch("/auth/sessioninfo", { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }); + + if (response.status === 200) { + let data = await response.json(); + return data; + } else { + window.alert("Oops! Something went wrong."); + } + } catch (err: any) { + window.alert("Oops! Something went wrong."); + } +} diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts new file mode 100644 index 00000000..9c3bbcaa --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts @@ -0,0 +1,54 @@ +import ThirdPartyNode from "supertokens-node/recipe/thirdparty"; +import EmailPasswordNode from "supertokens-node/recipe/emailpassword"; + +import SessionNode from "supertokens-node/recipe/session"; +import appInfo from "./appInfo.json"; +import { type TypeInput } from "supertokens-node/types"; + +export const initBE = (): TypeInput => { + return { + framework: "custom", + supertokens: { + // https://try.supertokens.com is for demo purposes. Replace this with the address of your core instance (sign up on supertokens.com), or self host a core. + connectionURI: "https://try.supertokens.com", + // apiKey: , + }, + appInfo, + recipeList: [ + EmailPasswordNode.init(), + ThirdPartyNode.init({ + // We have provided you with development keys which you can use for testing. + // IMPORTANT: Please replace them with your own OAuth keys for production use. + signInAndUpFeature: { + providers: [ + { + config: { + thirdPartyId: "google", + clients: [ + { + clientId: + "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", + clientSecret: "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", + }, + ], + }, + }, + { + config: { + thirdPartyId: "github", + clients: [ + { + clientId: "467101b197249757c71f", + clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", + }, + ], + }, + }, + ], + }, + }), + SessionNode.init(), + ], + isInServerlessEnv: true, + }; +}; diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts new file mode 100644 index 00000000..fce7220d --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts @@ -0,0 +1,16 @@ +import ThirdPartyWebJs from "supertokens-web-js/recipe/thirdparty"; +import EmailPasswordWebJs from "supertokens-web-js/recipe/emailpassword"; +import SessionWebJs from "supertokens-web-js/recipe/session"; +import appInfo from "./appInfo.json"; +import { type SuperTokensConfig } from "supertokens-web-js/types"; + +export const initFE = (): SuperTokensConfig => { + return { + appInfo, + recipeList: [ + ThirdPartyWebJs.init(), + EmailPasswordWebJs.init(), + SessionWebJs.init(), + ], + }; +}; diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json b/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json new file mode 100644 index 00000000..dc55aece --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json @@ -0,0 +1,6 @@ +{ + "appName": "Astro-ST-demo", + "apiDomain": "http://localhost:4321", + "apiBasePath": "/auth", + "websiteDomain": "http://localhost:4321" +} diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts new file mode 100644 index 00000000..337e5852 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts @@ -0,0 +1,304 @@ +import { + PreParsedRequest, + CollectingResponse, + middleware, + errorHandler, +} from "supertokens-node/framework/custom/index.js"; +import Session, { + type SessionContainer, + type VerifySessionOptions, +} from "supertokens-node/recipe/session/index.js"; +import SessionRecipe from "supertokens-node/lib/build/recipe/session/recipe.js"; +import { availableTokenTransferMethods } from "supertokens-node/lib/build/recipe/session/constants.js"; +import { getToken } from "supertokens-node/lib/build/recipe/session/cookieAndHeaders.js"; +import { parseJWTWithoutSignatureVerification } from "supertokens-node/lib/build/recipe/session/jwt.js"; +import { serialize } from "cookie"; +import JsonWebToken from "jsonwebtoken"; +import type { JwtHeader, JwtPayload, SigningKeyCallback } from "jsonwebtoken"; +import jwksClient from "jwks-rsa"; +import appInfo from "./appInfo.json"; + +type HTTPMethod = "post" | "get" | "delete" | "put" | "options" | "trace"; + +const client = jwksClient({ + jwksUri: `${appInfo.apiDomain}${appInfo.apiBasePath}/jwt/jwks.json`, +}); + +function getAccessToken(request: Request): string | undefined { + return getCookieFromRequest(request)["sAccessToken"]; +} + +function getPublicKey(header: JwtHeader, callback: SigningKeyCallback) { + client.getSigningKey(header.kid, (err, key) => { + if (err) { + callback(err); + } else { + const signingKey = key?.getPublicKey(); + callback(null, signingKey); + } + }); +} + +async function verifyToken(token: string): Promise { + return new Promise((resolve, reject) => { + JsonWebToken.verify(token, getPublicKey, {}, (err, decoded) => { + if (err) { + reject(err); + } else { + resolve(decoded as JwtPayload); + } + }); + }); +} + +export function handleAuthAPIRequest(AstroResponse: typeof Response) { + const stMiddleware = middleware((req) => { + return createPreParsedRequest(req); + }); + + return async function handleCall(req: Request) { + const baseResponse = new CollectingResponse(); + + const { handled, error } = await stMiddleware(req, baseResponse); + + if (error) { + throw error; + } + if (!handled) { + return new AstroResponse("Not found", { status: 404 }); + } + + for (const respCookie of baseResponse.cookies) { + baseResponse.headers.append( + "Set-Cookie", + serialize(respCookie.key, respCookie.value, { + domain: respCookie.domain, + expires: new Date(respCookie.expires), + httpOnly: respCookie.httpOnly, + path: respCookie.path, + sameSite: respCookie.sameSite, + secure: respCookie.secure, + }), + ); + } + + return new AstroResponse(baseResponse.body, { + headers: baseResponse.headers, + status: baseResponse.statusCode, + }); + }; +} + +function getCookieFromRequest(request: Request) { + const cookies: Record = {}; + const cookieHeader = request.headers.get("Cookie"); + if (cookieHeader) { + const cookieStrings = cookieHeader.split(";"); + for (const cookieString of cookieStrings) { + const [name, value] = cookieString.trim().split("="); + cookies[name] = decodeURIComponent(value); + } + } + return cookies; +} + +function getQueryFromRequest(request: Request) { + const query: Record = {}; + const url = new URL(request.url); + const searchParams = url.searchParams; + searchParams.forEach((value, key) => { + query[key] = value; + }); + return query; +} + +function createPreParsedRequest(request: Request): PreParsedRequest { + return new PreParsedRequest({ + cookies: getCookieFromRequest(request), + url: request.url as string, + method: request.method as HTTPMethod, + query: getQueryFromRequest(request), + headers: request.headers, + getFormBody: async () => { + return await request.formData(); + }, + getJSONBody: async () => { + return await request.json(); + }, + }); +} + +async function getSessionDetails( + preParsedRequest: PreParsedRequest, + options?: VerifySessionOptions, + userContext?: Record, +): Promise<{ + session: SessionContainer | undefined; + hasToken: boolean; + hasInvalidClaims: boolean; + baseResponse: CollectingResponse; + AstroResponse?: Response; +}> { + const baseResponse = new CollectingResponse(); + const recipe = (SessionRecipe as any).default.instance; + const tokenTransferMethod = recipe.config.getTokenTransferMethod({ + req: preParsedRequest, + forCreateNewSession: false, + userContext, + }); + const transferMethods = + tokenTransferMethod === "any" + ? availableTokenTransferMethods + : [tokenTransferMethod]; + const hasToken = transferMethods.some((transferMethod) => { + const token = getToken(preParsedRequest, "access", transferMethod); + if (!token) { + return false; + } + try { + parseJWTWithoutSignatureVerification(token); + return true; + } catch { + return false; + } + }); + + try { + const session = await Session.getSession( + preParsedRequest, + baseResponse, + options, + userContext, + ); + return { + session, + hasInvalidClaims: false, + hasToken, + baseResponse, + }; + } catch (err) { + if (Session.Error.isErrorFromSuperTokens(err)) { + return { + hasToken, + hasInvalidClaims: err.type === Session.Error.INVALID_CLAIMS, + session: undefined, + baseResponse, + AstroResponse: new Response("Authentication required", { + status: err.type === Session.Error.INVALID_CLAIMS ? 403 : 401, + }), + }; + } else { + throw err; + } + } +} + +/** + * A helper function to retrieve session details on the server side. + * + * NOTE: This function does not use the getSession function from the supertokens-node SDK + * because getSession can update the access token. These updated tokens would not be + * propagated to the client side, as request interceptors do not run on the server side. + */ +export async function getSessionForSSR(astroRequest: Request): Promise<{ + accessTokenPayload: JwtPayload | undefined; + hasToken: boolean; + error: Error | undefined; +}> { + const accessToken = getAccessToken(astroRequest); + const hasToken = !!accessToken; + try { + if (accessToken) { + const decoded = await verifyToken(accessToken); + return { accessTokenPayload: decoded, hasToken, error: undefined }; + } + return { accessTokenPayload: undefined, hasToken, error: undefined }; + } catch (error) { + if (error instanceof JsonWebToken.TokenExpiredError) { + return { accessTokenPayload: undefined, hasToken, error: undefined }; + } + return { accessTokenPayload: undefined, hasToken, error: error as Error }; + } +} + +export async function withSession( + astroRequest: Request, + handler: ( + error: Error | undefined, + session: SessionContainer | undefined, + ) => Promise, + options?: VerifySessionOptions, + userContext?: Record, +): Promise { + try { + let baseRequest = createPreParsedRequest(astroRequest); + const { session, AstroResponse, baseResponse } = await getSessionDetails( + baseRequest, + options, + userContext, + ); + + if (AstroResponse !== undefined) { + return AstroResponse; + } + + let userResponse: Response; + + try { + userResponse = await handler(undefined, session); + } catch (err) { + await errorHandler()( + err, + baseRequest, + baseResponse, + (errorHandlerError: Error) => { + if (errorHandlerError) { + throw errorHandlerError; + } + }, + ); + + // The headers in the userResponse are set twice from baseResponse, but the resulting response contains unique headers. + userResponse = new Response(baseResponse.body, { + status: baseResponse.statusCode, + headers: baseResponse.headers, + }); + } + + let didAddCookies = false; + let didAddHeaders = false; + + for (const respCookie of baseResponse.cookies) { + didAddCookies = true; + userResponse.headers.append( + "Set-Cookie", + serialize(respCookie.key, respCookie.value, { + domain: respCookie.domain, + expires: new Date(respCookie.expires), + httpOnly: respCookie.httpOnly, + path: respCookie.path, + sameSite: respCookie.sameSite, + secure: respCookie.secure, + }), + ); + } + + baseResponse.headers.forEach((value: string, key: string) => { + didAddHeaders = true; + userResponse.headers.set(key, value); + }); + if (didAddCookies || didAddHeaders) { + if (!userResponse.headers.has("Cache-Control")) { + // This is needed for production deployments with Vercel + userResponse.headers.set( + "Cache-Control", + "no-cache, no-store, max-age=0, must-revalidate", + ); + } + } + + return userResponse; + } catch (error) { + return await handler(error as Error, undefined); + } +} diff --git a/examples/astro/with-thirdpartyemailpassword/src/env.d.ts b/examples/astro/with-thirdpartyemailpassword/src/env.d.ts new file mode 100644 index 00000000..e16c13c6 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/astro/with-thirdpartyemailpassword/src/layouts/Root.astro b/examples/astro/with-thirdpartyemailpassword/src/layouts/Root.astro new file mode 100644 index 00000000..58f54067 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/layouts/Root.astro @@ -0,0 +1,142 @@ +--- + +--- + + + + + + + + Astro + + +
+ +
+ + + + + + diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts new file mode 100644 index 00000000..cdf5590f --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts @@ -0,0 +1,23 @@ +import SuperTokens from "supertokens-node"; +import { initBE } from "../../../auth/STBEConfig"; +import type { APIRoute } from "astro"; +import { handleAuthAPIRequest } from "../../../auth/superTokensHelper"; + +const handleCall = handleAuthAPIRequest(Response); + +export const ALL: APIRoute = async ({ params, request }) => { + SuperTokens.init(initBE()); + + if (params.path === "callback") { + console.log("callback"); + } + + try { + return await handleCall(request); + } catch (error) { + console.error(error); + return new Response(JSON.stringify({ error: "Internal server error" }), { + status: 500, + }); + } +}; diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts new file mode 100644 index 00000000..45f1275a --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts @@ -0,0 +1,19 @@ +import SuperTokens from "supertokens-node"; +import { initBE } from "../../auth/STBEConfig"; +import type { APIRoute } from "astro"; +import { handleAuthAPIRequest } from "../../auth/superTokensHelper"; + +const handleCall = handleAuthAPIRequest(Response); + +export const ALL: APIRoute = async ({ params, request }) => { + SuperTokens.init(initBE()); + + try { + return await handleCall(request); + } catch (error) { + console.error(error); + return new Response(JSON.stringify({ error: "Internal server error" }), { + status: 500, + }); + } +}; diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/callback/[...path].astro b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/callback/[...path].astro new file mode 100644 index 00000000..c3a1c504 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/callback/[...path].astro @@ -0,0 +1,15 @@ +--- +import Root from "../../../layouts/Root.astro"; +--- + + Redirecting... + + diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts new file mode 100644 index 00000000..67a154e4 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts @@ -0,0 +1,19 @@ +import { type APIRoute } from "astro"; +import { withSession } from "../../auth/superTokensHelper"; + +export const GET: APIRoute = async ({ params, request }) => { + return withSession(request, async (err, session) => { + if (err) { + return new Response(JSON.stringify(err), { status: 500 }); + } + + return new Response( + JSON.stringify({ + note: "Fetch any data from your application for authenticated user after using verifySession middleware", + userId: session!.getUserId(), + sessionHandle: session!.getHandle(), + accessTokenPayload: session!.getAccessTokenPayload(), + }), + ); + }); +}; diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/dashboard.astro b/examples/astro/with-thirdpartyemailpassword/src/pages/dashboard.astro new file mode 100644 index 00000000..3477739f --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/dashboard.astro @@ -0,0 +1,39 @@ +--- +import Root from "../layouts/Root.astro"; + +import { getSessionForSSR } from "../auth/superTokensHelper"; + +const { hasToken } = await getSessionForSSR(Astro.request); + +if (!hasToken) { + return Astro.redirect("/"); +} +--- + + +

Astro + SuperTokens | Dashboard

+
+
+ + +
+
+
+ + diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/index.astro b/examples/astro/with-thirdpartyemailpassword/src/pages/index.astro new file mode 100644 index 00000000..c66acf10 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/index.astro @@ -0,0 +1,81 @@ +--- +import Root from "../layouts/Root.astro"; + +import { getSessionForSSR } from "../auth/superTokensHelper"; + +const { hasToken } = await getSessionForSSR(Astro.request); + +if (hasToken) { + return Astro.redirect("/dashboard"); +} +--- + + +

Astro + SuperTokens

+
+
+ + +
+ + +
+
+ +
+
+
+ + diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/nonauth.astro b/examples/astro/with-thirdpartyemailpassword/src/pages/nonauth.astro new file mode 100644 index 00000000..df8a7b29 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/nonauth.astro @@ -0,0 +1,8 @@ +--- +import Root from "../layouts/Root.astro"; +--- + + +

Astro + SuperTokens | Non-Auth

+

We don't care about auth on this page

+
diff --git a/examples/astro/with-thirdpartyemailpassword/tsconfig.json b/examples/astro/with-thirdpartyemailpassword/tsconfig.json new file mode 100644 index 00000000..77da9dd0 --- /dev/null +++ b/examples/astro/with-thirdpartyemailpassword/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "astro/tsconfigs/strict" +} \ No newline at end of file diff --git a/examples/solidjs/with-thirdpartyemailpassword/README.md b/examples/solidjs/with-thirdpartyemailpassword/README.md new file mode 100644 index 00000000..e57d784a --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/README.md @@ -0,0 +1,34 @@ +![SuperTokens banner](https://raw.githubusercontent.com/supertokens/supertokens-logo/master/images/Artboard%20%E2%80%93%2027%402x.png) + +# SuperTokens ThirdPartyEmailPassword Demo app for SolidJS + +This demo app demonstrates the following use cases: + +- Social Login / Sign up +- Email & Password login +- Logout +- Session management & Calling APIs + +## Project setup + +Use `npm` to install the project dependencies: + +```bash +npm install +``` + +## Run the demo app + +```bash +npm run dev +``` + +The app will start on `http://localhost:3000` + +## Author + +Created with :heart: by the folks at supertokens.com. + +## License + +This project is licensed under the Apache 2.0 license. diff --git a/examples/solidjs/with-thirdpartyemailpassword/index.html b/examples/solidjs/with-thirdpartyemailpassword/index.html new file mode 100644 index 00000000..70217370 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/index.html @@ -0,0 +1,13 @@ + + + + + + + Vite + Solid + TS + + +
+ + + diff --git a/examples/solidjs/with-thirdpartyemailpassword/npm b/examples/solidjs/with-thirdpartyemailpassword/npm new file mode 100644 index 00000000..e69de29b diff --git a/examples/solidjs/with-thirdpartyemailpassword/package.json b/examples/solidjs/with-thirdpartyemailpassword/package.json new file mode 100644 index 00000000..9ea2f426 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/package.json @@ -0,0 +1,24 @@ +{ + "name": "e005-solid-supertokens", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "preview": "vite preview" + }, + "dependencies": { + "@solidjs/router": "^0.13.6", + "cors": "^2.8.5", + "express": "^4.19.2", + "solid-js": "^1.8.17", + "supertokens-node": "^18.0.1", + "supertokens-web-js": "^0.12.0" + }, + "devDependencies": { + "typescript": "^5.2.2", + "vite": "^5.3.1", + "vite-plugin-solid": "^2.10.2" + } +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/public/vite.svg b/examples/solidjs/with-thirdpartyemailpassword/public/vite.svg new file mode 100644 index 00000000..e7b8dfb1 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/examples/solidjs/with-thirdpartyemailpassword/server.ts b/examples/solidjs/with-thirdpartyemailpassword/server.ts new file mode 100644 index 00000000..f90ed970 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/server.ts @@ -0,0 +1,105 @@ +import express from "express"; +import cors from "cors"; +import supertokens from "supertokens-node"; +import { verifySession } from "supertokens-node/recipe/session/framework/express"; +import { + middleware, + errorHandler, + SessionRequest, +} from "supertokens-node/framework/express"; +import Session from "supertokens-node/recipe/session"; +import EmailPassword from "supertokens-node/recipe/emailpassword"; +import ThirdParty from "supertokens-node/recipe/thirdparty"; + +supertokens.init({ + framework: "express", + supertokens: { + connectionURI: "https://try.supertokens.com", + }, + appInfo: { + appName: "Hacking With SuperTokens", + apiDomain: "http://localhost:3001", + websiteDomain: "http://localhost:3000", + apiBasePath: "", + websiteBasePath: "/", + }, + recipeList: [ + EmailPassword.init(), + ThirdParty.init({ + // We have provided you with development keys which you can use for testing. + // IMPORTANT: Please replace them with your own OAuth keys for production use. + signInAndUpFeature: { + providers: [ + { + config: { + thirdPartyId: "google", + clients: [ + { + clientId: + "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", + clientSecret: "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", + }, + ], + }, + }, + { + config: { + thirdPartyId: "github", + clients: [ + { + clientId: "467101b197249757c71f", + clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", + }, + ], + }, + }, + { + config: { + thirdPartyId: "apple", + clients: [ + { + clientId: "4398792-io.supertokens.example.service", + additionalConfig: { + keyId: "7M48Y4RYDL", + privateKey: + "-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----", + teamId: "YWQCXGJRJL", + }, + }, + ], + }, + }, + ], + }, + }), + Session.init(), // initializes session features + ], +}); + +const app = express(); + +app.use( + cors({ + origin: "http://localhost:3000", + allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()], + methods: ["GET", "PUT", "POST", "DELETE"], + credentials: true, + }) +); + +app.use(middleware()); + +app.get("/sessioninfo", verifySession(), async (req: SessionRequest, res) => { + let session = req.session; + res.send({ + sessionHandle: session!.getHandle(), + userId: session!.getUserId(), + accessTokenPayload: session!.getAccessTokenPayload(), + }); +}); + +// In case of session related errors, this error handler +// returns 401 to the client. +app.use(errorHandler()); + +app.listen(3001, () => console.log(`API Server listening on port 3001`)); diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/App.css b/examples/solidjs/with-thirdpartyemailpassword/src/App.css new file mode 100644 index 00000000..285ccf33 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/App.css @@ -0,0 +1,132 @@ +:root { + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; + + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; + + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +a { + font-weight: 500; + color: #646cff; + text-decoration: inherit; +} +a:hover { + color: #535bf2; +} + +body { + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; +} + +h1 { + font-size: 3.2em; + line-height: 1.1; +} + +button { + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; + color: rgba(255, 255, 255, 0.87); +} +button:hover { + border-color: #646cff; +} +button:focus, +button:focus-visible { + outline: 4px auto -webkit-focus-ring-color; +} + +@media (prefers-color-scheme: light) { + :root { + color: #213547; + background-color: #ffffff; + } + a:hover { + color: #747bff; + } + button { + background-color: #f9f9f9; + } +} + +.form-wrap { + display: flex; + flex-direction: column; + gap: 1em; + max-width: 320px; +} + +.form-wrap input { + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + border: 1px solid #646cff; + border-radius: 8px; + padding: 0.6em 1em; + font-size: 1em; + font-family: inherit; +} + +div.wrapper { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1em; + height: 100vh; + width: 100vw; + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; + + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; + + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +div.wrapper header { + height: 80px; + background: #ff9933; + display: flex; + align-items: center; + justify-content: center; +} + +div.wrapper main { + flex-grow: 1; + display: flex; + align-items: center; + justify-content: center; + min-width: 60%; +} + +div.wrapper footer { + height: 60px; + background: #1f1f1f; + display: flex; + align-items: center; + justify-content: center; +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx b/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx new file mode 100644 index 00000000..e9227b57 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx @@ -0,0 +1,427 @@ +import { + doesEmailExist, + signIn, + signUp, +} from "supertokens-web-js/recipe/emailpassword"; +import { getAuthorisationURLWithQueryParamsAndSetState } from "supertokens-web-js/recipe/thirdparty"; +import { createSignal, onMount, Show } from "solid-js"; +import "./App.css"; +import { superTokensInit } from "./config/supertokens"; +import { useNavigate } from "@solidjs/router"; +import { signInAndUp } from "supertokens-web-js/recipe/thirdparty"; + +async function handleGoogleCallback(navigate: (path: string) => void) { + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if ( + response.createdNewRecipeUser && + response.user.loginMethods.length === 1 + ) { + console.log("sign up successful, google"); + } else { + console.log("sign in successful, google"); + } + // window.location.assign("/home"); + navigate("/dashboard/"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert( + "No email provided by social login. Please use another form of login" + ); + navigate("/auth"); // redirect back to login page + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function googleSignInClicked() { + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "google", + + // This is where Google should redirect the user back after login or error. + // This URL goes on the Google's dashboard as well. + frontendRedirectURI: "http://localhost:3000/auth/callback/google", + }); + + // we redirect the user to google for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function handleGitHubCallback(navigate: (path: string) => void) { + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if ( + response.createdNewRecipeUser && + response.user.loginMethods.length === 1 + ) { + console.log("sign up successful, github"); + } else { + console.log("sign in successful, github"); + } + // window.location.assign("/home"); + navigate("/dashboard/"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert( + "No email provided by social login. Please use another form of login" + ); + navigate("/auth"); // redirect back to login page + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function githubSignInClicked() { + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "github", + + // This is where Google should redirect the user back after login or error. + // This URL goes on the Google's dashboard as well. + frontendRedirectURI: "http://localhost:3000/auth/callback/github", + }); + + // we redirect the user to google for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function handleAppleCallback(navigate: (path: string) => void) { + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if ( + response.createdNewRecipeUser && + response.user.loginMethods.length === 1 + ) { + console.log("sign up successful, apple"); + } else { + console.log("sign in successful, apple"); + } + // window.location.assign("/home"); + navigate("/dashboard/"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert( + "No email provided by social login. Please use another form of login" + ); + navigate("/auth"); // redirect back to login page + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function appleSignInClicked() { + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "apple", + + frontendRedirectURI: "http://localhost:3000/auth/callback/apple", // This is an example callback URL on your frontend. You can use another path as well. + redirectURIOnProviderDashboard: + "http://localhost:3000/auth/callback/apple", // This URL goes on the Apple's dashboard + }); + + // we redirect the user to apple for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function signUpClicked( + email: string, + password: string, + navigate: (path: string) => void +) { + try { + let response = await signUp({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + // one of the input formFields failed validaiton + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax), + // or the email is not unique. + window.alert(formField.error); + } else if (formField.id === "password") { + // Password validation failed. + // Maybe it didn't match the password strength + window.alert(formField.error); + } + }); + } else if (response.status === "SIGN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign up was not allowed. + window.alert(response.reason); + } else { + // sign up successful. The session tokens are automatically handled by + // the frontend SDK. + navigate("/dashboard/"); + } + } catch (err: any) { + console.log(err); + + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function checkEmail(email: string) { + try { + let response = await doesEmailExist({ + email, + }); + + return response; + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +async function signInClicked( + email: string, + password: string, + navigate: (path: string) => void +) { + try { + let response = await signIn({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax). + window.alert(formField.error); + } + }); + } else if (response.status === "WRONG_CREDENTIALS_ERROR") { + window.alert("Email password combination is incorrect."); + } else if (response.status === "SIGN_IN_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in was not allowed. + window.alert(response.reason); + } else { + // sign in successful. The session tokens are automatically handled by + // the frontend SDK. + navigate("/dashboard/"); + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } + } +} + +function Auth() { + const navigate = useNavigate(); + superTokensInit(); + const [showOAuthLoading] = createSignal( + (() => { + if (window.location.pathname === "/auth/callback/google") { + return "Google"; + } + + if (window.location.pathname === "/auth/callback/github") { + return "GitHub"; + } + + if (window.location.pathname === "/auth/callback/apple") { + return "Apple"; + } + + return false; + })() + ); + + onMount(() => { + if (window.location.pathname === "/auth/callback/google") { + handleGoogleCallback(navigate); + } + + if (window.location.pathname === "/auth/callback/github") { + handleGitHubCallback(navigate); + } + + if (window.location.pathname === "/auth/callback/apple") { + handleAppleCallback(navigate); + } + }); + + const [email, setEmail] = createSignal(""); + const [password, setPassword] = createSignal(""); + + const handleSignUpClicked = async () => { + const res = await checkEmail(email()); + if (!res?.doesExist) { + signUpClicked(email(), password(), navigate); + } else { + window.alert("Email already exists. Please sign in instead"); + } + }; + + const handleSignInClicked = async () => { + const res = await checkEmail(email()); + if (res?.doesExist) { + signInClicked(email(), password(), navigate); + } else { + window.alert("Email does not exist. Please sign up instead"); + } + }; + + const handleGoogleSignInClicked = async () => { + googleSignInClicked(); + }; + + const handleGithubSignInClicked = async () => { + githubSignInClicked(); + }; + + const handleAppleSignInClicked = async () => { + appleSignInClicked(); + }; + + return ( +
+
+ + Logging-in via {showOAuthLoading()}, please wait... + + + setEmail((e.target as HTMLInputElement).value)} + /> + setPassword((e.target as HTMLInputElement).value)} + /> + + + + + + +
+
+ ); +} + +export default Auth; diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx b/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx new file mode 100644 index 00000000..1c1847da --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx @@ -0,0 +1,53 @@ +import { Show, createEffect, createSignal } from "solid-js"; +import "./App.css"; +import { superTokensInit } from "./config/supertokens"; +import Session from "supertokens-web-js/recipe/session"; +import { useNavigate } from "@solidjs/router"; + +function Dashboard() { + const navigate = useNavigate(); + superTokensInit(); + + const [loading, setLoading] = createSignal(true); + + const getSessionInfo = async () => { + const response = await fetch("http://localhost:3001/sessioninfo", { + headers: { + "Content-Type": "application/json", + }, + method: "GET", + credentials: "include", + }); + + const data = await response.json(); + + alert(JSON.stringify(data)); + }; + + async function signOut() { + await Session.signOut(); + navigate("/"); + } + + createEffect(async () => { + if (await Session.doesSessionExist()) { + setLoading(false); + } else { + navigate("/"); + } + }); + + return ( +
+
+ Loading... + + + + +
+
+ ); +} + +export default Dashboard; diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/assets/solid.svg b/examples/solidjs/with-thirdpartyemailpassword/src/assets/solid.svg new file mode 100644 index 00000000..025aa303 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/assets/solid.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts b/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts new file mode 100644 index 00000000..3479f02d --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts @@ -0,0 +1,23 @@ +import SuperTokens from "supertokens-web-js"; +import Session from "supertokens-web-js/recipe/session"; +import EmailPassword from "supertokens-web-js/recipe/emailpassword"; +import ThirdParty from "supertokens-web-js/recipe/thirdparty"; + +let initialized = false; + +export const superTokensInit = () => { + if (initialized) { + return; + } + + SuperTokens.init({ + appInfo: { + apiDomain: "http://localhost:3001", + apiBasePath: "", + appName: "Hacking With SuperTokens", + }, + recipeList: [Session.init(), EmailPassword.init(), ThirdParty.init()], + }); + + initialized = true; +}; diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/index.css b/examples/solidjs/with-thirdpartyemailpassword/src/index.css new file mode 100644 index 00000000..6119ad9a --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/index.css @@ -0,0 +1,68 @@ +:root { + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; + + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; + + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +a { + font-weight: 500; + color: #646cff; + text-decoration: inherit; +} +a:hover { + color: #535bf2; +} + +body { + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; +} + +h1 { + font-size: 3.2em; + line-height: 1.1; +} + +button { + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; +} +button:hover { + border-color: #646cff; +} +button:focus, +button:focus-visible { + outline: 4px auto -webkit-focus-ring-color; +} + +@media (prefers-color-scheme: light) { + :root { + color: #213547; + background-color: #ffffff; + } + a:hover { + color: #747bff; + } + button { + background-color: #f9f9f9; + } +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx b/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx new file mode 100644 index 00000000..beafb07f --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx @@ -0,0 +1,22 @@ +/* @refresh reload */ +import { render } from "solid-js/web"; +import { Router, Route } from "@solidjs/router"; + +import "./index.css"; +import Auth from "./Auth"; +import Dashboard from "./Dashboard"; + +const root = document.getElementById("root"); + +render( + () => ( + + + + + + + + ), + root! +); diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/vite-env.d.ts b/examples/solidjs/with-thirdpartyemailpassword/src/vite-env.d.ts new file mode 100644 index 00000000..11f02fe2 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json new file mode 100644 index 00000000..348fb418 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2020", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json new file mode 100644 index 00000000..ea9d0cd8 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.node.json" + } + ] +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json new file mode 100644 index 00000000..3afdd6e3 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "strict": true, + "noEmit": true + }, + "include": ["vite.config.ts"] +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts b/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts new file mode 100644 index 00000000..75e21324 --- /dev/null +++ b/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from "vite"; +import solid from "vite-plugin-solid"; + +export default defineConfig({ + plugins: [solid()], + server: { + port: 3000, + }, +}); diff --git a/examples/vuejs/with-thirdpartyemailpassword/README.md b/examples/vuejs/with-thirdpartyemailpassword/README.md index dd9c4e9c..58e24f5e 100644 --- a/examples/vuejs/with-thirdpartyemailpassword/README.md +++ b/examples/vuejs/with-thirdpartyemailpassword/README.md @@ -20,7 +20,7 @@ npm install ## Run the demo app -This compiles and serves the React app and starts the backend API server on port 3001. +This compiles and serves the Vue app and starts the backend API server on port 3001. ```bash npm run dev From bcd327348ae381f55d5a8fc4089da8fc4b4e3923 Mon Sep 17 00:00:00 2001 From: Darko Bozhinovski Date: Fri, 23 Aug 2024 14:39:45 +0200 Subject: [PATCH 2/5] feat: updates README --- examples/solidjs/with-thirdpartyemailpassword/README.md | 1 + examples/solidjs/with-thirdpartyemailpassword/package.json | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/examples/solidjs/with-thirdpartyemailpassword/README.md b/examples/solidjs/with-thirdpartyemailpassword/README.md index e57d784a..f2370e3d 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/README.md +++ b/examples/solidjs/with-thirdpartyemailpassword/README.md @@ -28,6 +28,7 @@ The app will start on `http://localhost:3000` ## Author Created with :heart: by the folks at supertokens.com. +Built live on [Hacking with SuperTokens 005 and 006](https://www.youtube.com/watch?v=ovjTQ-20fk0). ## License diff --git a/examples/solidjs/with-thirdpartyemailpassword/package.json b/examples/solidjs/with-thirdpartyemailpassword/package.json index 9ea2f426..5fa05e00 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/package.json +++ b/examples/solidjs/with-thirdpartyemailpassword/package.json @@ -4,7 +4,9 @@ "version": "0.0.0", "type": "module", "scripts": { - "dev": "vite", + "dev": "concurrently --kill-others \"npm run dev-server\" \"npm run dev-client\"", + "dev-client": "vite", + "dev-server": "tsx server.ts", "build": "tsc -b && vite build", "preview": "vite preview" }, @@ -17,6 +19,8 @@ "supertokens-web-js": "^0.12.0" }, "devDependencies": { + "concurrently": "^8.2.2", + "tsx": "^4.17.0", "typescript": "^5.2.2", "vite": "^5.3.1", "vite-plugin-solid": "^2.10.2" From 7edc2a87865387249ab07d1bb58d9af14e88b324 Mon Sep 17 00:00:00 2001 From: Darko Bozhinovski Date: Fri, 23 Aug 2024 15:04:22 +0200 Subject: [PATCH 3/5] feat: build n lint --- bundle/website.js | 2 +- .../with-thirdpartyemailpassword/package.json | 52 +++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/bundle/website.js b/bundle/website.js index 365c5839..935479c6 100644 --- a/bundle/website.js +++ b/bundle/website.js @@ -1 +1 @@ -var supertokensWebsite;(()=>{"use strict";var e,t={9895:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){e.done?o(e.value):new n((function(t){t(e.value)})).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",i),e.addToWaiting(i);var a=setTimeout(i,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r=a+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),i.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],s=0;;){var i=r.keySync(s);if(null===i)break;o.push(i),s++}for(var u=!1,c=0;c{Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);void 0===r?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var r=n.pop();e.locked.set(t,n),void 0!==r&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()}},2225:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{Object.defineProperty(t,"__esModule",{value:!0}),t.OverrideableBuilder=void 0;var r=n(2225),o=function(){function e(e){this.layers=[e],this.proxies=[]}return e.prototype.override=function(e){for(var t=(0,r.getProxyObject)(this.layers[0]),n=e(t,this),o=0,s=Object.keys(this.layers[0]);o=0;--o){var s=e.layers[o][n];if(null!=s)return s.bind(e.result).apply(void 0,r)}}},c=this,l=0;l{t.__esModule=!0,function(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}(n(7874))},3438:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1] ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!0}]:[2,{isValid:!1,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}])}))}))}}},excludes:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!1,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]:[2,{isValid:!0}])}))}))}}},includesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}]))}))}))}}},includesAny:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.some((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToIncludeAtLeastOneOf:e,actualValue:t}}]))}))}))}}},excludesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return!u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]))}))}))}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveArrayClaim=i},2663:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrimitiveClaim=void 0;var r=n(2519),o=function(){function e(e){var t=this;this.validators={hasValue:function(e,n,o){void 0===n&&(n=t.defaultMaxAgeInSeconds);var s=r.default.getReferenceOrThrow().dateProvider;return{id:void 0!==o?o:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(s.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?{isValid:!1,reason:{message:"expired",ageInSeconds:a,maxAgeInSeconds:n}}:i!==e?{isValid:!1,reason:{message:"wrong value",expectedValue:e,actualValue:i}}:{isValid:!0}}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveClaim=o},6398:function(e,t){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.STGeneralError=void 0;var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isSuperTokensGeneralError=!0,n}return r(t,e),t.isThisError=function(e){return!0===e.isSuperTokensGeneralError},t}(Error);t.STGeneralError=o},788:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw c;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.url,userContext:{}})];case 14:return s.sent(),[4,I(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(p.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 16:return v=s.sent(),[4,I(!1)];case 17:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);case 18:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 19:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,I(!1)];case 20:return"NOT_EXISTS"!==s.sent().status?[3,23]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 21:return s.sent(),[4,h.removeToken()];case 22:s.sent(),s.label=23;case 23:return[7];case 24:return[4,I(!1)];case 25:return"NOT_EXISTS"===(b=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):b.status!==e.status||"EXISTS"===b.status&&"EXISTS"===e.status&&b.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):[3,2];case 26:return[2]}}))}))}function y(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function T(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function I(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,M(v)];case 1:return t=o.sent(),[4,h.doesTokenExists()];case 2:return o.sent()&&void 0!==t?((0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists"),[2,{status:"EXISTS",lastAccessTokenUpdate:t}]):[3,3];case 3:return t?((0,d.logDebugMessage)("getLocalSessionState: returning NOT_EXISTS since frontToken was cleared but lastAccessTokenUpdate exists"),[2,{status:"NOT_EXISTS"}]):[3,4];case 4:return n={status:"MAY_EXIST"},e?((0,d.logDebugMessage)("getLocalSessionState: trying to refresh"),[4,S(n)]):[3,7];case 5:return"RETRY"!==(r=o.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):((0,d.logDebugMessage)("getLocalSessionState: Retrying post refresh"),[4,I(e)]);case 6:return[2,o.sent()];case 7:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function R(e){switch(e){case"access":return m;case"refresh":return b}}function D(e,t){var n=R(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),E(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),E(n,t,0))}function E(e,t,n){var r="Fri, 31 Dec 9999 23:59:59 GMT";n!==Number.MAX_SAFE_INTEGER&&(r=new Date(n).toUTCString());var o=p.config.sessionTokenFrontendDomain;return"localhost"===o||o===c.default.getReferenceOrThrow().windowHandler.location.getHostName()?u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax"))}function x(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,M(R(e))]}))}))}function M(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function A(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,x("access")];case 1:return n=o.sent(),[4,x("refresh")];case 2:return r=o.sent(),!t&&void 0===n||void 0===r?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"):e.has("Authorization")?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.set("Authorization","Bearer ".concat(t?r:n))),[2]}}))}))}function C(e){return o(this,void 0,void 0,(function(){var n,r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(n=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,D("refresh",n)]);case 1:s.sent(),s.label=2;case 2:return null===(r=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,D("access",r)]);case 3:s.sent(),s.label=4;case 4:return null===(o=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+o),[4,h.setItem(o)]);case 5:s.sent(),(0,t.updateClockSkewUsingFrontToken)({frontToken:o,responseHeaders:e.headers}),s.label=6;case 6:return null===(i=e.headers.get("anti-csrf"))?[3,9]:[4,I(!0)];case 7:return"EXISTS"!==(a=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(a.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("saveLastAccessTokenUpdate: called"),e=Date.now().toString(),(0,d.logDebugMessage)("saveLastAccessTokenUpdate: setting "+e),[4,E(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[4,E("sIRTFrontend","",0)];case 2:return t.sent(),[2]}}))}))}function O(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; "+w+"=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,I(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function P(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("setAntiCSRF: called: "+e),void 0===e?[3,2]:[4,E(w,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,E(w,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function H(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,M(k)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function F(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function U(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,I(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,H()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function q(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setFrontToken: called"),[4,H()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=F(t).up,r=F(e).up,JSON.stringify(n)!==JSON.stringify(r)&&y()),void 0!==e?[3,3]:[4,E(k,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,E(k,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function N(e,t,n){if(null!=n){var r="remove"!==n;(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary wasLoggedIn: ".concat(e," frontTokenExistsAfter: ").concat(r," status: ").concat(t)),e?r||(t===p.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),p.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),p.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.onUnauthorisedResponse=S,t.onTokenUpdate=y,t.onInvalidClaimResponse=T,t.getLocalSessionState=I,t.getStorageNameForToken=R,t.setToken=D,t.getTokenForHeaderAuth=x,t.saveLastAccessTokenUpdate=_,t.setAntiCSRF=P,t.getFrontToken=U,t.setFrontToken=q,t.fireSessionUpdateEventsIfNecessary=N,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=F(t),o=p.recipeImpl.calculateClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: the access token payload wasn't updated or is being removed, skipping clock skew update")}},7874:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.logDebugMessage=t.disableLogging=t.enableLogging=void 0;var r=n(5204),o=!1;t.enableLogging=function(){o=!0},t.disableLogging=function(){o=!1},t.logDebugMessage=function(e){o&&console.log("".concat("com.supertokens",' {t: "').concat((new Date).toISOString(),'", message: "').concat(e,'", supertokens-website-ver: "').concat(r.package_version,'"}'))}},291:(e,t)=>{function n(e){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(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isAnIpAddress=void 0,t.isAnIpAddress=n;function r(e,t){void 0===t&&(t=!1),e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");var o=new URL(e);return t?o.hostname.startsWith("localhost")||n(o.hostname)?"http://"+o.host:"https://"+o.host:o.protocol+"//"+o.host}catch(e){}if(e.startsWith("/"))throw new Error("Please provide a valid domain name");if(0===e.indexOf(".")&&(e=e.substr(1)),(-1!==e.indexOf(".")||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://")){e="https://"+e;try{return new URL(e),r(e,!0)}catch(e){}}throw new Error("Please provide a valid domain name")}t.default=function(e){var t=this;this.getAsStringDangerous=function(){return t.value},this.value=r(e)}},7158:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});function n(e){e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");return"/"===(e=new URL(e).pathname).charAt(e.length-1)?e.substr(0,e.length-1):e}catch(e){}if((function(e){if(-1===e.indexOf(".")||e.startsWith("/"))return!1;try{return-1!==new URL(e).hostname.indexOf(".")}catch(e){}try{return-1!==new URL("http://"+e).hostname.indexOf(".")}catch(e){}return!1}(e)||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://"))return n(e="http://"+e);"/"!==e.charAt(0)&&(e="/"+e);try{return new URL("http://example.com"+e),n("http://example.com"+e)}catch(e){throw new Error("Please provide a valid URL path")}}t.default=function e(t){var r=this;this.startsWith=function(e){return r.value.startsWith(e.value)},this.appendPath=function(t){return new e(r.value+t.value)},this.getAsStringDangerous=function(){return r.value},this.value=n(t)}},9583:function(e,t){var n,r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=0;n--)if(e.history[n]==t)return e.history[n]},this.reset=function(){e.history=[]},this.waitForEvent=function(t,n){return void 0===n&&(n=7e3),r(e,void 0,void 0,(function(){var e,r=this;return o(this,(function(o){return e=Date.now(),[2,new Promise((function(o){var s=r;!function r(){var i=s.getEventByLastEventByName(t);void 0===i?Date.now()-e>n?o(void 0):setTimeout(r,1e3):o(i)}()}))]}))}))}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e}();t.ProcessState=s},3112:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw r;return[4,e.postAPIHook({action:"SIGN_OUT",requestInit:n.requestInit,url:n.url,fetchResponse:r.clone(),userContext:t.userContext})];case 4:return s.sent(),[4,r.clone().json()];case 5:if("GENERAL_ERROR"===(o=s.sent()).status)throw(0,c.logDebugMessage)("doRequest: Throwing general error"),a=void 0===o.message?"No Error Message Provided":o.message,new l.STGeneralError(a);return[2]}}))}))},getInvalidClaimsFromResponse:function(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return"body"in e.response?[4,e.response.clone().json()]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t="string"==typeof e.response.data?JSON.parse(e.response.data):e.response.data,n.label=3;case 3:return[2,t.claimValidationErrors]}}))}))},getGlobalClaimValidators:function(e){return e.claimValidatorsAddedByOtherRecipes},validateClaims:function(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,a,u,c,l;return s(this,(function(s){switch(s.label){case 0:return[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 1:t=s.sent(),n=0,r=e.claimValidators,s.label=2;case 2:return n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.CookieHandlerReference=void 0;var r=n(6570),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.cookieHandler=t(r.defaultCookieHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensCookieHandler must be initialized before calling this method.");return e.instance},e}();t.CookieHandlerReference=o,t.default=o},2946:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProvider=void 0;var r=n(7860),o=function(){function e(){this.clockSkewInMillis=0,this.thresholdInSeconds=7}return e.init=function(){if(void 0===e.instance){e.instance=new e;var t=r.default.getReferenceOrThrow().windowHandler.localStorage.getItemSync(e.CLOCK_SKEW_KEY),n=null!==t?parseInt(t,10):0;e.instance.setClientClockSkewInMillis(n)}},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("DateProvider must be initialized before calling this method.");return e.instance},e.prototype.getThresholdInSeconds=function(){return this.thresholdInSeconds},e.prototype.setThresholdInSeconds=function(e){this.thresholdInSeconds=e},e.prototype.setClientClockSkewInMillis=function(t){this.clockSkewInMillis=Math.abs(t)>=1e3*this.thresholdInSeconds?t:0,r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){return this.clockSkewInMillis},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.DateProvider=o},2519:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(2946),o=function(){function e(e){void 0!==e?this.dateProvider=e():(r.DateProvider.init(),this.dateProvider=r.DateProvider.getReferenceOrThrow())}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensDateProvider must be initialized before calling this method.");return e.instance},e}();t.DateProviderReference=o,t.default=o},2652:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.LockFactoryReference=void 0;var r=n(9895),o=function(){function e(e){this.lockFactory=e}return e.init=function(t,n){void 0===this.instance&&(this.instance=new e(null!=t?t:function(e){return function(){return Promise.resolve(new r.default(e))}}(n)))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensLockReference must be initialized before calling this method.");return e.instance},e}();t.LockFactoryReference=o,t.default=o},2582:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SessionClaimValidatorStore=void 0;var n=function(){function e(){}return e.claimValidatorsAddedByOtherRecipes=[],e.addClaimValidatorFromOtherRecipe=function(t){e.claimValidatorsAddedByOtherRecipes.push(t)},e.getClaimValidatorsAddedByOtherRecipes=function(){return e.claimValidatorsAddedByOtherRecipes},e}();t.SessionClaimValidatorStore=n,t.default=n},1936:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.WindowHandlerReference=void 0;var r=n(1936),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.windowHandler=t(r.defaultWindowHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensWindowHandler must be initialized before calling this method.");return e.instance},e}();t.WindowHandlerReference=o,t.default=o},5204:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.supported_fdi=t.package_version=void 0,t.package_version="20.0.0",t.supported_fdi=["1.16","1.17","1.18","1.19"]},9291:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{if(!n){var i=1/0;for(l=0;l=s)&&Object.keys(r.O).every((e=>r.O[e](n[u])))?n.splice(u--,1):(a=!1,s0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[n,o,s]},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={624:0};r.O.j=t=>0===e[t];var t=(t,n)=>{var o,s,[i,a,u]=n,c=0;if(i.some((t=>0!==e[t]))){for(o in a)r.o(a,o)&&(r.m[o]=a[o]);if(u)var l=u(r)}for(t&&t(n);c{"use strict";var e,t={9895:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){e.done?o(e.value):new n((function(t){t(e.value)})).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",i),e.addToWaiting(i);var a=setTimeout(i,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r=a+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),i.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],s=0;;){var i=r.keySync(s);if(null===i)break;o.push(i),s++}for(var u=!1,c=0;c{Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);void 0===r?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var r=n.pop();e.locked.set(t,n),void 0!==r&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()}},2225:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{Object.defineProperty(t,"__esModule",{value:!0}),t.OverrideableBuilder=void 0;var r=n(2225),o=function(){function e(e){this.layers=[e],this.proxies=[]}return e.prototype.override=function(e){for(var t=(0,r.getProxyObject)(this.layers[0]),n=e(t,this),o=0,s=Object.keys(this.layers[0]);o=0;--o){var s=e.layers[o][n];if(null!=s)return s.bind(e.result).apply(void 0,r)}}},c=this,l=0;l{t.__esModule=!0,function(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}(n(7874))},3438:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1] ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!0}]:[2,{isValid:!1,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}])}))}))}}},excludes:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!1,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]:[2,{isValid:!0}])}))}))}}},includesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}]))}))}))}}},includesAny:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.some((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToIncludeAtLeastOneOf:e,actualValue:t}}]))}))}))}}},excludesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return!u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]))}))}))}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveArrayClaim=i},2663:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrimitiveClaim=void 0;var r=n(2519),o=function(){function e(e){var t=this;this.validators={hasValue:function(e,n,o){void 0===n&&(n=t.defaultMaxAgeInSeconds);var s=r.default.getReferenceOrThrow().dateProvider;return{id:void 0!==o?o:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(s.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?{isValid:!1,reason:{message:"expired",ageInSeconds:a,maxAgeInSeconds:n}}:i!==e?{isValid:!1,reason:{message:"wrong value",expectedValue:e,actualValue:i}}:{isValid:!0}}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveClaim=o},6398:function(e,t){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.STGeneralError=void 0;var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isSuperTokensGeneralError=!0,n}return r(t,e),t.isThisError=function(e){return!0===e.isSuperTokensGeneralError},t}(Error);t.STGeneralError=o},788:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw c;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.url,userContext:{}})];case 14:return s.sent(),[4,I(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(p.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 16:return v=s.sent(),[4,I(!1)];case 17:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);case 18:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 19:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,I(!1)];case 20:return"NOT_EXISTS"!==s.sent().status?[3,23]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 21:return s.sent(),[4,h.removeToken()];case 22:s.sent(),s.label=23;case 23:return[7];case 24:return[4,I(!1)];case 25:return"NOT_EXISTS"===(b=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):b.status!==e.status||"EXISTS"===b.status&&"EXISTS"===e.status&&b.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):[3,2];case 26:return[2]}}))}))}function y(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function T(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function I(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,x(v)];case 1:return t=o.sent(),[4,h.doesTokenExists()];case 2:return o.sent()&&void 0!==t?((0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists"),[2,{status:"EXISTS",lastAccessTokenUpdate:t}]):[3,3];case 3:return t?((0,d.logDebugMessage)("getLocalSessionState: returning NOT_EXISTS since frontToken was cleared but lastAccessTokenUpdate exists"),[2,{status:"NOT_EXISTS"}]):[3,4];case 4:return n={status:"MAY_EXIST"},e?((0,d.logDebugMessage)("getLocalSessionState: trying to refresh"),[4,S(n)]):[3,7];case 5:return"RETRY"!==(r=o.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):((0,d.logDebugMessage)("getLocalSessionState: Retrying post refresh"),[4,I(e)]);case 6:return[2,o.sent()];case 7:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function R(e){switch(e){case"access":return m;case"refresh":return b}}function D(e,t){var n=R(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),E(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),E(n,t,0))}function E(e,t,n){var r="Fri, 31 Dec 9999 23:59:59 GMT";n!==Number.MAX_SAFE_INTEGER&&(r=new Date(n).toUTCString());var o=p.config.sessionTokenFrontendDomain;return"localhost"===o||o===c.default.getReferenceOrThrow().windowHandler.location.getHostName()?u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax"))}function M(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,x(R(e))]}))}))}function x(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function A(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,M("access")];case 1:return n=o.sent(),[4,M("refresh")];case 2:return r=o.sent(),!t&&void 0===n||void 0===r?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"):e.has("Authorization")?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.set("Authorization","Bearer ".concat(t?r:n))),[2]}}))}))}function C(e){return o(this,void 0,void 0,(function(){var n,r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(n=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,D("refresh",n)]);case 1:s.sent(),s.label=2;case 2:return null===(r=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,D("access",r)]);case 3:s.sent(),s.label=4;case 4:return null===(o=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+o),[4,h.setItem(o)]);case 5:s.sent(),(0,t.updateClockSkewUsingFrontToken)({frontToken:o,responseHeaders:e.headers}),s.label=6;case 6:return null===(i=e.headers.get("anti-csrf"))?[3,9]:[4,I(!0)];case 7:return"EXISTS"!==(a=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(a.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("saveLastAccessTokenUpdate: called"),e=Date.now().toString(),(0,d.logDebugMessage)("saveLastAccessTokenUpdate: setting "+e),[4,E(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[4,E("sIRTFrontend","",0)];case 2:return t.sent(),[2]}}))}))}function O(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; "+k+"=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,I(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function P(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("setAntiCSRF: called: "+e),void 0===e?[3,2]:[4,E(k,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,E(k,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function H(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,x(w)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function F(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function U(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,I(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,H()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function q(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setFrontToken: called"),[4,H()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=F(t).up,r=F(e).up,JSON.stringify(n)!==JSON.stringify(r)&&y()),void 0!==e?[3,3]:[4,E(w,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,E(w,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function N(e,t,n){if(null!=n){var r="remove"!==n;(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary wasLoggedIn: ".concat(e," frontTokenExistsAfter: ").concat(r," status: ").concat(t)),e?r||(t===p.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),p.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),p.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.onUnauthorisedResponse=S,t.onTokenUpdate=y,t.onInvalidClaimResponse=T,t.getLocalSessionState=I,t.getStorageNameForToken=R,t.setToken=D,t.getTokenForHeaderAuth=M,t.saveLastAccessTokenUpdate=_,t.setAntiCSRF=P,t.getFrontToken=U,t.setFrontToken=q,t.fireSessionUpdateEventsIfNecessary=N,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=F(t),o=p.recipeImpl.calculateClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: the access token payload wasn't updated or is being removed, skipping clock skew update")}},7874:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.logDebugMessage=t.disableLogging=t.enableLogging=void 0;var r=n(5204),o=!1;t.enableLogging=function(){o=!0},t.disableLogging=function(){o=!1},t.logDebugMessage=function(e){o&&console.log("".concat("com.supertokens",' {t: "').concat((new Date).toISOString(),'", message: "').concat(e,'", supertokens-website-ver: "').concat(r.package_version,'"}'))}},291:(e,t)=>{function n(e){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(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isAnIpAddress=void 0,t.isAnIpAddress=n;function r(e,t){void 0===t&&(t=!1),e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");var o=new URL(e);return t?o.hostname.startsWith("localhost")||n(o.hostname)?"http://"+o.host:"https://"+o.host:o.protocol+"//"+o.host}catch(e){}if(e.startsWith("/"))throw new Error("Please provide a valid domain name");if(0===e.indexOf(".")&&(e=e.substr(1)),(-1!==e.indexOf(".")||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://")){e="https://"+e;try{return new URL(e),r(e,!0)}catch(e){}}throw new Error("Please provide a valid domain name")}t.default=function(e){var t=this;this.getAsStringDangerous=function(){return t.value},this.value=r(e)}},7158:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});function n(e){e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");return"/"===(e=new URL(e).pathname).charAt(e.length-1)?e.substr(0,e.length-1):e}catch(e){}if((function(e){if(-1===e.indexOf(".")||e.startsWith("/"))return!1;try{return-1!==new URL(e).hostname.indexOf(".")}catch(e){}try{return-1!==new URL("http://"+e).hostname.indexOf(".")}catch(e){}return!1}(e)||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://"))return n(e="http://"+e);"/"!==e.charAt(0)&&(e="/"+e);try{return new URL("http://example.com"+e),n("http://example.com"+e)}catch(e){throw new Error("Please provide a valid URL path")}}t.default=function e(t){var r=this;this.startsWith=function(e){return r.value.startsWith(e.value)},this.appendPath=function(t){return new e(r.value+t.value)},this.getAsStringDangerous=function(){return r.value},this.value=n(t)}},9583:function(e,t){var n,r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=0;n--)if(e.history[n]==t)return e.history[n]},this.reset=function(){e.history=[]},this.waitForEvent=function(t,n){return void 0===n&&(n=7e3),r(e,void 0,void 0,(function(){var e,r=this;return o(this,(function(o){return e=Date.now(),[2,new Promise((function(o){var s=r;!function r(){var i=s.getEventByLastEventByName(t);void 0===i?Date.now()-e>n?o(void 0):setTimeout(r,1e3):o(i)}()}))]}))}))}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e}();t.ProcessState=s},3112:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw r;return[4,e.postAPIHook({action:"SIGN_OUT",requestInit:n.requestInit,url:n.url,fetchResponse:r.clone(),userContext:t.userContext})];case 4:return s.sent(),[4,r.clone().json()];case 5:if("GENERAL_ERROR"===(o=s.sent()).status)throw(0,c.logDebugMessage)("doRequest: Throwing general error"),a=void 0===o.message?"No Error Message Provided":o.message,new l.STGeneralError(a);return[2]}}))}))},getInvalidClaimsFromResponse:function(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return"body"in e.response?[4,e.response.clone().json()]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t="string"==typeof e.response.data?JSON.parse(e.response.data):e.response.data,n.label=3;case 3:return[2,t.claimValidationErrors]}}))}))},getGlobalClaimValidators:function(e){return e.claimValidatorsAddedByOtherRecipes},validateClaims:function(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,a,u,l,d,f,g;return s(this,(function(s){switch(s.label){case 0:n=0,s.label=1;case 1:return++n<100?[4,h.default.getReferenceOrThrow().lockFactory()]:[3,20];case 2:return r=s.sent(),(0,c.logDebugMessage)("validateClaims: trying to acquire claim refresh lock"),[4,r.acquireLock(p)];case 3:if(!s.sent())return[3,18];s.label=4;case 4:return s.trys.push([4,,15,17]),[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 5:t=s.sent(),(0,c.logDebugMessage)("validateClaims: claim refresh lock acquired"),o=0,i=e.claimValidators,s.label=6;case 6:return o0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.CookieHandlerReference=void 0;var r=n(6570),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.cookieHandler=t(r.defaultCookieHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensCookieHandler must be initialized before calling this method.");return e.instance},e}();t.CookieHandlerReference=o,t.default=o},2946:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProvider=void 0;var r=n(7860),o=function(){function e(){this.clockSkewInMillis=0,this.thresholdInSeconds=7}return e.init=function(){if(void 0===e.instance){e.instance=new e;var t=r.default.getReferenceOrThrow().windowHandler.localStorage.getItemSync(e.CLOCK_SKEW_KEY),n=null!==t?parseInt(t,10):0;e.instance.setClientClockSkewInMillis(n)}},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("DateProvider must be initialized before calling this method.");return e.instance},e.prototype.getThresholdInSeconds=function(){return this.thresholdInSeconds},e.prototype.setThresholdInSeconds=function(e){this.thresholdInSeconds=e},e.prototype.setClientClockSkewInMillis=function(t){this.clockSkewInMillis=Math.abs(t)>=1e3*this.thresholdInSeconds?t:0,r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){return this.clockSkewInMillis},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.DateProvider=o},2519:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(2946),o=function(){function e(e){void 0!==e?this.dateProvider=e():(r.DateProvider.init(),this.dateProvider=r.DateProvider.getReferenceOrThrow())}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensDateProvider must be initialized before calling this method.");return e.instance},e}();t.DateProviderReference=o,t.default=o},2652:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.LockFactoryReference=void 0;var r=n(9895),o=function(){function e(e){this.lockFactory=e}return e.init=function(t,n){void 0===this.instance&&(this.instance=new e(null!=t?t:function(e){return function(){return Promise.resolve(new r.default(e))}}(n)))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensLockReference must be initialized before calling this method.");return e.instance},e}();t.LockFactoryReference=o,t.default=o},2582:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SessionClaimValidatorStore=void 0;var n=function(){function e(){}return e.claimValidatorsAddedByOtherRecipes=[],e.addClaimValidatorFromOtherRecipe=function(t){e.claimValidatorsAddedByOtherRecipes.push(t)},e.getClaimValidatorsAddedByOtherRecipes=function(){return e.claimValidatorsAddedByOtherRecipes},e}();t.SessionClaimValidatorStore=n,t.default=n},1936:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.WindowHandlerReference=void 0;var r=n(1936),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.windowHandler=t(r.defaultWindowHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensWindowHandler must be initialized before calling this method.");return e.instance},e}();t.WindowHandlerReference=o,t.default=o},5204:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.supported_fdi=t.package_version=void 0,t.package_version="20.0.1",t.supported_fdi=["1.16","1.17","1.18","1.19","2.0","3.0"]},9291:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{if(!n){var i=1/0;for(l=0;l=s)&&Object.keys(r.O).every((e=>r.O[e](n[u])))?n.splice(u--,1):(a=!1,s0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[n,o,s]},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={624:0};r.O.j=t=>0===e[t];var t=(t,n)=>{var o,s,[i,a,u]=n,c=0;if(i.some((t=>0!==e[t]))){for(o in a)r.o(a,o)&&(r.m[o]=a[o]);if(u)var l=u(r)}for(t&&t(n);c Date: Fri, 23 Aug 2024 15:24:28 +0200 Subject: [PATCH 4/5] fix: resets website.js from 0.13 From 78293b48a1b1d9313610d97ddc2ea8d2beb5a5c1 Mon Sep 17 00:00:00 2001 From: rishabhpoddar Date: Fri, 23 Aug 2024 22:14:20 +0530 Subject: [PATCH 5/5] removes changes from bundle --- bundle/website.js | 2 +- .../astro.config.mjs | 10 +- .../with-thirdpartyemailpassword/package.json | 52 +- .../src/auth/Auth.ts | 387 +++++----- .../src/auth/STBEConfig.ts | 88 +-- .../src/auth/STFEConfig.ts | 12 +- .../src/auth/appInfo.json | 8 +- .../src/auth/superTokensHelper.ts | 432 +++++------ .../src/pages/auth/[...path]/[...route].ts | 24 +- .../src/pages/auth/[...route].ts | 18 +- .../src/pages/auth/sessioninfo.ts | 26 +- .../tsconfig.json | 4 +- .../with-thirdpartyemailpassword/index.html | 22 +- .../with-thirdpartyemailpassword/server.ts | 152 ++-- .../with-thirdpartyemailpassword/src/App.css | 172 ++--- .../with-thirdpartyemailpassword/src/Auth.tsx | 718 +++++++++--------- .../src/Dashboard.tsx | 76 +- .../src/config/supertokens.ts | 24 +- .../src/index.css | 84 +- .../src/index.tsx | 20 +- .../tsconfig.app.json | 48 +- .../tsconfig.json | 18 +- .../tsconfig.node.json | 22 +- .../vite.config.ts | 8 +- 24 files changed, 1177 insertions(+), 1250 deletions(-) diff --git a/bundle/website.js b/bundle/website.js index 935479c6..365c5839 100644 --- a/bundle/website.js +++ b/bundle/website.js @@ -1 +1 @@ -var supertokensWebsite;(()=>{"use strict";var e,t={9895:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){e.done?o(e.value):new n((function(t){t(e.value)})).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",i),e.addToWaiting(i);var a=setTimeout(i,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r=a+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),i.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],s=0;;){var i=r.keySync(s);if(null===i)break;o.push(i),s++}for(var u=!1,c=0;c{Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);void 0===r?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var r=n.pop();e.locked.set(t,n),void 0!==r&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()}},2225:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{Object.defineProperty(t,"__esModule",{value:!0}),t.OverrideableBuilder=void 0;var r=n(2225),o=function(){function e(e){this.layers=[e],this.proxies=[]}return e.prototype.override=function(e){for(var t=(0,r.getProxyObject)(this.layers[0]),n=e(t,this),o=0,s=Object.keys(this.layers[0]);o=0;--o){var s=e.layers[o][n];if(null!=s)return s.bind(e.result).apply(void 0,r)}}},c=this,l=0;l{t.__esModule=!0,function(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}(n(7874))},3438:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1] ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!0}]:[2,{isValid:!1,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}])}))}))}}},excludes:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!1,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]:[2,{isValid:!0}])}))}))}}},includesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}]))}))}))}}},includesAny:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.some((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToIncludeAtLeastOneOf:e,actualValue:t}}]))}))}))}}},excludesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return!u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]))}))}))}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveArrayClaim=i},2663:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrimitiveClaim=void 0;var r=n(2519),o=function(){function e(e){var t=this;this.validators={hasValue:function(e,n,o){void 0===n&&(n=t.defaultMaxAgeInSeconds);var s=r.default.getReferenceOrThrow().dateProvider;return{id:void 0!==o?o:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(s.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?{isValid:!1,reason:{message:"expired",ageInSeconds:a,maxAgeInSeconds:n}}:i!==e?{isValid:!1,reason:{message:"wrong value",expectedValue:e,actualValue:i}}:{isValid:!0}}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveClaim=o},6398:function(e,t){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.STGeneralError=void 0;var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isSuperTokensGeneralError=!0,n}return r(t,e),t.isThisError=function(e){return!0===e.isSuperTokensGeneralError},t}(Error);t.STGeneralError=o},788:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw c;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.url,userContext:{}})];case 14:return s.sent(),[4,I(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(p.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 16:return v=s.sent(),[4,I(!1)];case 17:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);case 18:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 19:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,I(!1)];case 20:return"NOT_EXISTS"!==s.sent().status?[3,23]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 21:return s.sent(),[4,h.removeToken()];case 22:s.sent(),s.label=23;case 23:return[7];case 24:return[4,I(!1)];case 25:return"NOT_EXISTS"===(b=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):b.status!==e.status||"EXISTS"===b.status&&"EXISTS"===e.status&&b.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):[3,2];case 26:return[2]}}))}))}function y(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function T(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function I(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,x(v)];case 1:return t=o.sent(),[4,h.doesTokenExists()];case 2:return o.sent()&&void 0!==t?((0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists"),[2,{status:"EXISTS",lastAccessTokenUpdate:t}]):[3,3];case 3:return t?((0,d.logDebugMessage)("getLocalSessionState: returning NOT_EXISTS since frontToken was cleared but lastAccessTokenUpdate exists"),[2,{status:"NOT_EXISTS"}]):[3,4];case 4:return n={status:"MAY_EXIST"},e?((0,d.logDebugMessage)("getLocalSessionState: trying to refresh"),[4,S(n)]):[3,7];case 5:return"RETRY"!==(r=o.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):((0,d.logDebugMessage)("getLocalSessionState: Retrying post refresh"),[4,I(e)]);case 6:return[2,o.sent()];case 7:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function R(e){switch(e){case"access":return m;case"refresh":return b}}function D(e,t){var n=R(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),E(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),E(n,t,0))}function E(e,t,n){var r="Fri, 31 Dec 9999 23:59:59 GMT";n!==Number.MAX_SAFE_INTEGER&&(r=new Date(n).toUTCString());var o=p.config.sessionTokenFrontendDomain;return"localhost"===o||o===c.default.getReferenceOrThrow().windowHandler.location.getHostName()?u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax"))}function M(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,x(R(e))]}))}))}function x(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function A(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,M("access")];case 1:return n=o.sent(),[4,M("refresh")];case 2:return r=o.sent(),!t&&void 0===n||void 0===r?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"):e.has("Authorization")?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.set("Authorization","Bearer ".concat(t?r:n))),[2]}}))}))}function C(e){return o(this,void 0,void 0,(function(){var n,r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(n=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,D("refresh",n)]);case 1:s.sent(),s.label=2;case 2:return null===(r=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,D("access",r)]);case 3:s.sent(),s.label=4;case 4:return null===(o=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+o),[4,h.setItem(o)]);case 5:s.sent(),(0,t.updateClockSkewUsingFrontToken)({frontToken:o,responseHeaders:e.headers}),s.label=6;case 6:return null===(i=e.headers.get("anti-csrf"))?[3,9]:[4,I(!0)];case 7:return"EXISTS"!==(a=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(a.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("saveLastAccessTokenUpdate: called"),e=Date.now().toString(),(0,d.logDebugMessage)("saveLastAccessTokenUpdate: setting "+e),[4,E(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[4,E("sIRTFrontend","",0)];case 2:return t.sent(),[2]}}))}))}function O(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; "+k+"=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,I(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function P(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("setAntiCSRF: called: "+e),void 0===e?[3,2]:[4,E(k,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,E(k,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function H(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,x(w)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function F(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function U(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,I(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,H()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function q(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setFrontToken: called"),[4,H()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=F(t).up,r=F(e).up,JSON.stringify(n)!==JSON.stringify(r)&&y()),void 0!==e?[3,3]:[4,E(w,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,E(w,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function N(e,t,n){if(null!=n){var r="remove"!==n;(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary wasLoggedIn: ".concat(e," frontTokenExistsAfter: ").concat(r," status: ").concat(t)),e?r||(t===p.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),p.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),p.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.onUnauthorisedResponse=S,t.onTokenUpdate=y,t.onInvalidClaimResponse=T,t.getLocalSessionState=I,t.getStorageNameForToken=R,t.setToken=D,t.getTokenForHeaderAuth=M,t.saveLastAccessTokenUpdate=_,t.setAntiCSRF=P,t.getFrontToken=U,t.setFrontToken=q,t.fireSessionUpdateEventsIfNecessary=N,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=F(t),o=p.recipeImpl.calculateClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: the access token payload wasn't updated or is being removed, skipping clock skew update")}},7874:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.logDebugMessage=t.disableLogging=t.enableLogging=void 0;var r=n(5204),o=!1;t.enableLogging=function(){o=!0},t.disableLogging=function(){o=!1},t.logDebugMessage=function(e){o&&console.log("".concat("com.supertokens",' {t: "').concat((new Date).toISOString(),'", message: "').concat(e,'", supertokens-website-ver: "').concat(r.package_version,'"}'))}},291:(e,t)=>{function n(e){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(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isAnIpAddress=void 0,t.isAnIpAddress=n;function r(e,t){void 0===t&&(t=!1),e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");var o=new URL(e);return t?o.hostname.startsWith("localhost")||n(o.hostname)?"http://"+o.host:"https://"+o.host:o.protocol+"//"+o.host}catch(e){}if(e.startsWith("/"))throw new Error("Please provide a valid domain name");if(0===e.indexOf(".")&&(e=e.substr(1)),(-1!==e.indexOf(".")||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://")){e="https://"+e;try{return new URL(e),r(e,!0)}catch(e){}}throw new Error("Please provide a valid domain name")}t.default=function(e){var t=this;this.getAsStringDangerous=function(){return t.value},this.value=r(e)}},7158:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});function n(e){e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");return"/"===(e=new URL(e).pathname).charAt(e.length-1)?e.substr(0,e.length-1):e}catch(e){}if((function(e){if(-1===e.indexOf(".")||e.startsWith("/"))return!1;try{return-1!==new URL(e).hostname.indexOf(".")}catch(e){}try{return-1!==new URL("http://"+e).hostname.indexOf(".")}catch(e){}return!1}(e)||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://"))return n(e="http://"+e);"/"!==e.charAt(0)&&(e="/"+e);try{return new URL("http://example.com"+e),n("http://example.com"+e)}catch(e){throw new Error("Please provide a valid URL path")}}t.default=function e(t){var r=this;this.startsWith=function(e){return r.value.startsWith(e.value)},this.appendPath=function(t){return new e(r.value+t.value)},this.getAsStringDangerous=function(){return r.value},this.value=n(t)}},9583:function(e,t){var n,r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=0;n--)if(e.history[n]==t)return e.history[n]},this.reset=function(){e.history=[]},this.waitForEvent=function(t,n){return void 0===n&&(n=7e3),r(e,void 0,void 0,(function(){var e,r=this;return o(this,(function(o){return e=Date.now(),[2,new Promise((function(o){var s=r;!function r(){var i=s.getEventByLastEventByName(t);void 0===i?Date.now()-e>n?o(void 0):setTimeout(r,1e3):o(i)}()}))]}))}))}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e}();t.ProcessState=s},3112:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw r;return[4,e.postAPIHook({action:"SIGN_OUT",requestInit:n.requestInit,url:n.url,fetchResponse:r.clone(),userContext:t.userContext})];case 4:return s.sent(),[4,r.clone().json()];case 5:if("GENERAL_ERROR"===(o=s.sent()).status)throw(0,c.logDebugMessage)("doRequest: Throwing general error"),a=void 0===o.message?"No Error Message Provided":o.message,new l.STGeneralError(a);return[2]}}))}))},getInvalidClaimsFromResponse:function(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return"body"in e.response?[4,e.response.clone().json()]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t="string"==typeof e.response.data?JSON.parse(e.response.data):e.response.data,n.label=3;case 3:return[2,t.claimValidationErrors]}}))}))},getGlobalClaimValidators:function(e){return e.claimValidatorsAddedByOtherRecipes},validateClaims:function(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,a,u,l,d,f,g;return s(this,(function(s){switch(s.label){case 0:n=0,s.label=1;case 1:return++n<100?[4,h.default.getReferenceOrThrow().lockFactory()]:[3,20];case 2:return r=s.sent(),(0,c.logDebugMessage)("validateClaims: trying to acquire claim refresh lock"),[4,r.acquireLock(p)];case 3:if(!s.sent())return[3,18];s.label=4;case 4:return s.trys.push([4,,15,17]),[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 5:t=s.sent(),(0,c.logDebugMessage)("validateClaims: claim refresh lock acquired"),o=0,i=e.claimValidators,s.label=6;case 6:return o0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.CookieHandlerReference=void 0;var r=n(6570),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.cookieHandler=t(r.defaultCookieHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensCookieHandler must be initialized before calling this method.");return e.instance},e}();t.CookieHandlerReference=o,t.default=o},2946:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProvider=void 0;var r=n(7860),o=function(){function e(){this.clockSkewInMillis=0,this.thresholdInSeconds=7}return e.init=function(){if(void 0===e.instance){e.instance=new e;var t=r.default.getReferenceOrThrow().windowHandler.localStorage.getItemSync(e.CLOCK_SKEW_KEY),n=null!==t?parseInt(t,10):0;e.instance.setClientClockSkewInMillis(n)}},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("DateProvider must be initialized before calling this method.");return e.instance},e.prototype.getThresholdInSeconds=function(){return this.thresholdInSeconds},e.prototype.setThresholdInSeconds=function(e){this.thresholdInSeconds=e},e.prototype.setClientClockSkewInMillis=function(t){this.clockSkewInMillis=Math.abs(t)>=1e3*this.thresholdInSeconds?t:0,r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){return this.clockSkewInMillis},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.DateProvider=o},2519:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(2946),o=function(){function e(e){void 0!==e?this.dateProvider=e():(r.DateProvider.init(),this.dateProvider=r.DateProvider.getReferenceOrThrow())}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensDateProvider must be initialized before calling this method.");return e.instance},e}();t.DateProviderReference=o,t.default=o},2652:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.LockFactoryReference=void 0;var r=n(9895),o=function(){function e(e){this.lockFactory=e}return e.init=function(t,n){void 0===this.instance&&(this.instance=new e(null!=t?t:function(e){return function(){return Promise.resolve(new r.default(e))}}(n)))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensLockReference must be initialized before calling this method.");return e.instance},e}();t.LockFactoryReference=o,t.default=o},2582:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SessionClaimValidatorStore=void 0;var n=function(){function e(){}return e.claimValidatorsAddedByOtherRecipes=[],e.addClaimValidatorFromOtherRecipe=function(t){e.claimValidatorsAddedByOtherRecipes.push(t)},e.getClaimValidatorsAddedByOtherRecipes=function(){return e.claimValidatorsAddedByOtherRecipes},e}();t.SessionClaimValidatorStore=n,t.default=n},1936:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.WindowHandlerReference=void 0;var r=n(1936),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.windowHandler=t(r.defaultWindowHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensWindowHandler must be initialized before calling this method.");return e.instance},e}();t.WindowHandlerReference=o,t.default=o},5204:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.supported_fdi=t.package_version=void 0,t.package_version="20.0.1",t.supported_fdi=["1.16","1.17","1.18","1.19","2.0","3.0"]},9291:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{if(!n){var i=1/0;for(l=0;l=s)&&Object.keys(r.O).every((e=>r.O[e](n[u])))?n.splice(u--,1):(a=!1,s0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[n,o,s]},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={624:0};r.O.j=t=>0===e[t];var t=(t,n)=>{var o,s,[i,a,u]=n,c=0;if(i.some((t=>0!==e[t]))){for(o in a)r.o(a,o)&&(r.m[o]=a[o]);if(u)var l=u(r)}for(t&&t(n);c{"use strict";var e,t={9895:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){e.done?o(e.value):new n((function(t){t(e.value)})).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",i),e.addToWaiting(i);var a=setTimeout(i,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,s,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r=a+"-"+t,null===(s=n.getItemSync(r))?[2]:(c=JSON.parse(s)).id!==this.id?[3,2]:[4,i.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),i.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],s=0;;){var i=r.keySync(s);if(null===i)break;o.push(i),s++}for(var u=!1,c=0;c{Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,n){var r=e.locked.get(t);void 0===r?void 0===n?e.locked.set(t,[]):e.locked.set(t,[n]):void 0!==n&&(r.unshift(n),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise((function(n,r){e.isLocked(t)?e.addToLocked(t,n):(e.addToLocked(t),n())}))},this.unlock=function(t){var n=e.locked.get(t);if(void 0!==n&&0!==n.length){var r=n.pop();e.locked.set(t,n),void 0!==r&&setTimeout(r,0)}else e.locked.delete(t)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return n.getInstance()}},2225:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n{Object.defineProperty(t,"__esModule",{value:!0}),t.OverrideableBuilder=void 0;var r=n(2225),o=function(){function e(e){this.layers=[e],this.proxies=[]}return e.prototype.override=function(e){for(var t=(0,r.getProxyObject)(this.layers[0]),n=e(t,this),o=0,s=Object.keys(this.layers[0]);o=0;--o){var s=e.layers[o][n];if(null!=s)return s.bind(e.result).apply(void 0,r)}}},c=this,l=0;l{t.__esModule=!0,function(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}(n(7874))},3438:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1] ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!0}]:[2,{isValid:!1,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}])}))}))}}},excludes:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:t.includes(e)?[2,{isValid:!1,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]:[2,{isValid:!0}])}))}))}}},includesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToInclude:e,actualValue:t}}]))}))}))}}},includesAny:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.some((function(e){return u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToIncludeAtLeastOneOf:e,actualValue:t}}]))}))}))}}},excludesAll:function(e,n,i){void 0===n&&(n=t.defaultMaxAgeInSeconds);var a=s.default.getReferenceOrThrow().dateProvider;return{id:void 0!==i?i:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(a.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?[2,{isValid:!1,reason:{message:"expired",ageInSeconds:r,maxAgeInSeconds:n}}]:(u=new Set(t),[2,(c=e.every((function(e){return!u.has(e)})))?{isValid:c}:{isValid:c,reason:{message:"wrong value",expectedToNotInclude:e,actualValue:t}}]))}))}))}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveArrayClaim=i},2663:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PrimitiveClaim=void 0;var r=n(2519),o=function(){function e(e){var t=this;this.validators={hasValue:function(e,n,o){void 0===n&&(n=t.defaultMaxAgeInSeconds);var s=r.default.getReferenceOrThrow().dateProvider;return{id:void 0!==o?o:t.id,refresh:function(e){return t.refresh(e)},shouldRefresh:function(e,r){if(void 0!==n&&n ".concat(s.getThresholdInSeconds()));return void 0===t.getValueFromPayload(e,r)||void 0!==n&&e[t.id].tn?{isValid:!1,reason:{message:"expired",ageInSeconds:a,maxAgeInSeconds:n}}:i!==e?{isValid:!1,reason:{message:"wrong value",expectedValue:e,actualValue:i}}:{isValid:!0}}}}},this.id=e.id,this.refresh=e.refresh,this.defaultMaxAgeInSeconds=e.defaultMaxAgeInSeconds}return e.prototype.getValueFromPayload=function(e,t){return void 0!==e[this.id]?e[this.id].v:void 0},e.prototype.getLastFetchedTime=function(e,t){return void 0!==e[this.id]?e[this.id].t:void 0},e}();t.PrimitiveClaim=o},6398:function(e,t){var n,r=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.STGeneralError=void 0;var o=function(e){function t(t){var n=e.call(this,t)||this;return n.isSuperTokensGeneralError=!0,n}return r(t,e),t.isThisError=function(e){return!0===e.isSuperTokensGeneralError},t}(Error);t.STGeneralError=o},788:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw c;return[4,p.config.postAPIHook({action:"REFRESH_SESSION",fetchResponse:c.clone(),requestInit:u.requestInit,url:u.url,userContext:{}})];case 14:return s.sent(),[4,I(!1)];case 15:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED"}]):(p.config.onHandleEvent({action:"REFRESH_SESSION",userContext:{}}),(0,d.logDebugMessage)("onUnauthorisedResponse: Sending RETRY signal"),[2,{result:"RETRY"}]);case 16:return v=s.sent(),[4,I(!1)];case 17:return"NOT_EXISTS"===s.sent().status?((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so returning session expired"),[2,{result:"SESSION_EXPIRED",error:v}]):((0,d.logDebugMessage)("onUnauthorisedResponse: sending API_ERROR"),[2,{result:"API_ERROR",error:v}]);case 18:return[4,t.releaseLock("REFRESH_TOKEN_USE")];case 19:return s.sent(),(0,d.logDebugMessage)("onUnauthorisedResponse: Released lock"),[4,I(!1)];case 20:return"NOT_EXISTS"!==s.sent().status?[3,23]:((0,d.logDebugMessage)("onUnauthorisedResponse: local session doesn't exist, so removing anti-csrf and sFrontToken"),[4,g.removeToken()]);case 21:return s.sent(),[4,h.removeToken()];case 22:s.sent(),s.label=23;case 23:return[7];case 24:return[4,I(!1)];case 25:return"NOT_EXISTS"===(b=s.sent()).status?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and local session doesn't exist, so sending SESSION_EXPIRED"),[2,{result:"SESSION_EXPIRED"}]):b.status!==e.status||"EXISTS"===b.status&&"EXISTS"===e.status&&b.lastAccessTokenUpdate!==e.lastAccessTokenUpdate?((0,d.logDebugMessage)("onUnauthorisedResponse: lock acquired failed and retrying early because pre and post lastAccessTokenUpdate don't match"),[2,{result:"RETRY"}]):[3,2];case 26:return[2]}}))}))}function y(){(0,d.logDebugMessage)("onTokenUpdate: firing ACCESS_TOKEN_PAYLOAD_UPDATED event"),p.config.onHandleEvent({action:"ACCESS_TOKEN_PAYLOAD_UPDATED",userContext:{}})}function T(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,p.recipeImpl.getInvalidClaimsFromResponse({response:e,userContext:{}})];case 1:return(t=n.sent())&&p.config.onHandleEvent({action:"API_INVALID_CLAIM",claimValidationErrors:t,userContext:{}}),[3,3];case 2:return n.sent(),[3,3];case 3:return[2]}}))}))}function I(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("getLocalSessionState: called"),[4,M(v)];case 1:return t=o.sent(),[4,h.doesTokenExists()];case 2:return o.sent()&&void 0!==t?((0,d.logDebugMessage)("getLocalSessionState: returning EXISTS since both frontToken and lastAccessTokenUpdate exists"),[2,{status:"EXISTS",lastAccessTokenUpdate:t}]):[3,3];case 3:return t?((0,d.logDebugMessage)("getLocalSessionState: returning NOT_EXISTS since frontToken was cleared but lastAccessTokenUpdate exists"),[2,{status:"NOT_EXISTS"}]):[3,4];case 4:return n={status:"MAY_EXIST"},e?((0,d.logDebugMessage)("getLocalSessionState: trying to refresh"),[4,S(n)]):[3,7];case 5:return"RETRY"!==(r=o.sent()).result?((0,d.logDebugMessage)("getLocalSessionState: return NOT_EXISTS in case error from backend"+r.result),[2,{status:"NOT_EXISTS"}]):((0,d.logDebugMessage)("getLocalSessionState: Retrying post refresh"),[4,I(e)]);case 6:return[2,o.sent()];case 7:return(0,d.logDebugMessage)("getLocalSessionState: returning: "+n.status),[2,n]}}))}))}function R(e){switch(e){case"access":return m;case"refresh":return b}}function D(e,t){var n=R(e);return""!==t?((0,d.logDebugMessage)("setToken: saved ".concat(e," token into cookies")),E(n,t,Date.now()+31536e5)):((0,d.logDebugMessage)("setToken: cleared ".concat(e," token from cookies")),E(n,t,0))}function E(e,t,n){var r="Fri, 31 Dec 9999 23:59:59 GMT";n!==Number.MAX_SAFE_INTEGER&&(r=new Date(n).toUTCString());var o=p.config.sessionTokenFrontendDomain;return"localhost"===o||o===c.default.getReferenceOrThrow().windowHandler.location.getHostName()?u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax")):u.default.getReferenceOrThrow().cookieHandler.setCookie("".concat(e,"=").concat(t,";expires=").concat(r,";domain=").concat(o,";path=/;samesite=").concat(p.config.isInIframe?"none;secure":"lax"))}function x(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){return[2,M(R(e))]}))}))}function M(e){return o(this,void 0,void 0,(function(){var t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return n="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return t=n+s.sent(),(r=t.split("; "+e+"=")).length>=2&&void 0!==(o=r.pop())?[2,o.split(";").shift()]:[2,void 0]}}))}))}function A(e,t){return void 0===t&&(t=!1),o(this,void 0,void 0,(function(){var n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setTokenHeaders: adding existing tokens as header"),[4,x("access")];case 1:return n=o.sent(),[4,x("refresh")];case 2:return r=o.sent(),!t&&void 0===n||void 0===r?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: token for header based auth not found"):e.has("Authorization")?(0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: Authorization header defined by the user, not adding"):((0,d.logDebugMessage)("setAuthorizationHeaderIfRequired: added authorization header"),e.set("Authorization","Bearer ".concat(t?r:n))),[2]}}))}))}function C(e){return o(this,void 0,void 0,(function(){var n,r,o,i,a;return s(this,(function(s){switch(s.label){case 0:return(0,d.logDebugMessage)("saveTokensFromHeaders: Saving updated tokens from the response headers"),null===(n=e.headers.get("st-refresh-token"))?[3,2]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new refresh token"),[4,D("refresh",n)]);case 1:s.sent(),s.label=2;case 2:return null===(r=e.headers.get("st-access-token"))?[3,4]:((0,d.logDebugMessage)("saveTokensFromHeaders: saving new access token"),[4,D("access",r)]);case 3:s.sent(),s.label=4;case 4:return null===(o=e.headers.get("front-token"))?[3,6]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting sFrontToken: "+o),[4,h.setItem(o)]);case 5:s.sent(),(0,t.updateClockSkewUsingFrontToken)({frontToken:o,responseHeaders:e.headers}),s.label=6;case 6:return null===(i=e.headers.get("anti-csrf"))?[3,9]:[4,I(!0)];case 7:return"EXISTS"!==(a=s.sent()).status?[3,9]:((0,d.logDebugMessage)("saveTokensFromHeaders: Setting anti-csrf token"),[4,g.setItem(a.lastAccessTokenUpdate,i)]);case 8:s.sent(),s.label=9;case 9:return[2]}}))}))}function _(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("saveLastAccessTokenUpdate: called"),e=Date.now().toString(),(0,d.logDebugMessage)("saveLastAccessTokenUpdate: setting "+e),[4,E(v,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[4,E("sIRTFrontend","",0)];case 2:return t.sent(),[2]}}))}))}function O(){return o(this,void 0,void 0,(function(){function e(){return o(this,void 0,void 0,(function(){var e,t,n,r,o;return s(this,(function(s){switch(s.label){case 0:return t="; ",[4,u.default.getReferenceOrThrow().cookieHandler.getCookie()];case 1:return e=t+s.sent(),(n=e.split("; "+w+"=")).length>=2&&void 0!==(r=n.pop())?void 0===(o=r.split(";").shift())?[2,null]:[2,o]:[2,null]}}))}))}var t;return s(this,(function(n){switch(n.label){case 0:return(0,d.logDebugMessage)("getAntiCSRFToken: called"),[4,I(!0)];case 1:return"EXISTS"!==n.sent().status?((0,d.logDebugMessage)("getAntiCSRFToken: Returning because local session state != EXISTS"),[2,null]):[4,e()];case 2:return t=n.sent(),(0,d.logDebugMessage)("getAntiCSRFToken: returning: "+t),[2,t]}}))}))}function P(e){return o(this,void 0,void 0,(function(){return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("setAntiCSRF: called: "+e),void 0===e?[3,2]:[4,E(w,e,Number.MAX_SAFE_INTEGER)];case 1:return t.sent(),[3,4];case 2:return[4,E(w,"",0)];case 3:t.sent(),t.label=4;case 4:return[2]}}))}))}function H(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontTokenFromCookie: called"),[4,M(k)];case 1:return[2,void 0===(e=t.sent())?null:e]}}))}))}function F(e){return JSON.parse(decodeURIComponent(escape(atob(e))))}function U(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return(0,d.logDebugMessage)("getFrontToken: called"),[4,I(!0)];case 1:return"EXISTS"!==t.sent().status?((0,d.logDebugMessage)("getFrontToken: Returning because sIRTFrontend != EXISTS"),[2,null]):[4,H()];case 2:return e=t.sent(),(0,d.logDebugMessage)("getFrontToken: returning: "+e),[2,e]}}))}))}function q(e){return o(this,void 0,void 0,(function(){var t,n,r;return s(this,(function(o){switch(o.label){case 0:return(0,d.logDebugMessage)("setFrontToken: called"),[4,H()];case 1:return null!==(t=o.sent())&&void 0!==e&&(n=F(t).up,r=F(e).up,JSON.stringify(n)!==JSON.stringify(r)&&y()),void 0!==e?[3,3]:[4,E(k,"",0)];case 2:return o.sent(),[3,5];case 3:return[4,E(k,e,Number.MAX_SAFE_INTEGER)];case 4:o.sent(),o.label=5;case 5:return[2]}}))}))}function N(e,t,n){if(null!=n){var r="remove"!==n;(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary wasLoggedIn: ".concat(e," frontTokenExistsAfter: ").concat(r," status: ").concat(t)),e?r||(t===p.config.sessionExpiredStatusCode?((0,d.logDebugMessage)("onUnauthorisedResponse: firing UNAUTHORISED event"),p.config.onHandleEvent({action:"UNAUTHORISED",sessionExpiredOrRevoked:!0,userContext:{}})):((0,d.logDebugMessage)("onUnauthorisedResponse: firing SIGN_OUT event"),p.config.onHandleEvent({action:"SIGN_OUT",userContext:{}}))):r&&((0,d.logDebugMessage)("onUnauthorisedResponse: firing SESSION_CREATED event"),p.config.onHandleEvent({action:"SESSION_CREATED",userContext:{}}))}else(0,d.logDebugMessage)("fireSessionUpdateEventsIfNecessary returning early because the front token was not updated")}t.onUnauthorisedResponse=S,t.onTokenUpdate=y,t.onInvalidClaimResponse=T,t.getLocalSessionState=I,t.getStorageNameForToken=R,t.setToken=D,t.getTokenForHeaderAuth=x,t.saveLastAccessTokenUpdate=_,t.setAntiCSRF=P,t.getFrontToken=U,t.setFrontToken=q,t.fireSessionUpdateEventsIfNecessary=N,t.updateClockSkewUsingFrontToken=function(e){var t=e.frontToken,n=e.responseHeaders;if((0,d.logDebugMessage)("updateClockSkewUsingFrontToken: frontToken: "+t),null!=t&&"remove"!==t){var r=F(t),o=p.recipeImpl.calculateClockSkewInMillis({accessTokenPayload:r.up,responseHeaders:n});f.default.getReferenceOrThrow().dateProvider.setClientClockSkewInMillis(o),(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: Client clock synchronized successfully")}else(0,d.logDebugMessage)("updateClockSkewUsingFrontToken: the access token payload wasn't updated or is being removed, skipping clock skew update")}},7874:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.logDebugMessage=t.disableLogging=t.enableLogging=void 0;var r=n(5204),o=!1;t.enableLogging=function(){o=!0},t.disableLogging=function(){o=!1},t.logDebugMessage=function(e){o&&console.log("".concat("com.supertokens",' {t: "').concat((new Date).toISOString(),'", message: "').concat(e,'", supertokens-website-ver: "').concat(r.package_version,'"}'))}},291:(e,t)=>{function n(e){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(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.isAnIpAddress=void 0,t.isAnIpAddress=n;function r(e,t){void 0===t&&(t=!1),e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");var o=new URL(e);return t?o.hostname.startsWith("localhost")||n(o.hostname)?"http://"+o.host:"https://"+o.host:o.protocol+"//"+o.host}catch(e){}if(e.startsWith("/"))throw new Error("Please provide a valid domain name");if(0===e.indexOf(".")&&(e=e.substr(1)),(-1!==e.indexOf(".")||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://")){e="https://"+e;try{return new URL(e),r(e,!0)}catch(e){}}throw new Error("Please provide a valid domain name")}t.default=function(e){var t=this;this.getAsStringDangerous=function(){return t.value},this.value=r(e)}},7158:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});function n(e){e=e.trim();try{if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("converting to proper URL");return"/"===(e=new URL(e).pathname).charAt(e.length-1)?e.substr(0,e.length-1):e}catch(e){}if((function(e){if(-1===e.indexOf(".")||e.startsWith("/"))return!1;try{return-1!==new URL(e).hostname.indexOf(".")}catch(e){}try{return-1!==new URL("http://"+e).hostname.indexOf(".")}catch(e){}return!1}(e)||e.startsWith("localhost"))&&!e.startsWith("http://")&&!e.startsWith("https://"))return n(e="http://"+e);"/"!==e.charAt(0)&&(e="/"+e);try{return new URL("http://example.com"+e),n("http://example.com"+e)}catch(e){throw new Error("Please provide a valid URL path")}}t.default=function e(t){var r=this;this.startsWith=function(e){return r.value.startsWith(e.value)},this.appendPath=function(t){return new e(r.value+t.value)},this.getAsStringDangerous=function(){return r.value},this.value=n(t)}},9583:function(e,t){var n,r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=0;n--)if(e.history[n]==t)return e.history[n]},this.reset=function(){e.history=[]},this.waitForEvent=function(t,n){return void 0===n&&(n=7e3),r(e,void 0,void 0,(function(){var e,r=this;return o(this,(function(o){return e=Date.now(),[2,new Promise((function(o){var s=r;!function r(){var i=s.getEventByLastEventByName(t);void 0===i?Date.now()-e>n?o(void 0):setTimeout(r,1e3):o(i)}()}))]}))}))}}return e.getInstance=function(){return null==e.instance&&(e.instance=new e),e.instance},e}();t.ProcessState=s},3112:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]=300)throw r;return[4,e.postAPIHook({action:"SIGN_OUT",requestInit:n.requestInit,url:n.url,fetchResponse:r.clone(),userContext:t.userContext})];case 4:return s.sent(),[4,r.clone().json()];case 5:if("GENERAL_ERROR"===(o=s.sent()).status)throw(0,c.logDebugMessage)("doRequest: Throwing general error"),a=void 0===o.message?"No Error Message Provided":o.message,new l.STGeneralError(a);return[2]}}))}))},getInvalidClaimsFromResponse:function(e){return o(this,void 0,void 0,(function(){var t;return s(this,(function(n){switch(n.label){case 0:return"body"in e.response?[4,e.response.clone().json()]:[3,2];case 1:return t=n.sent(),[3,3];case 2:t="string"==typeof e.response.data?JSON.parse(e.response.data):e.response.data,n.label=3;case 3:return[2,t.claimValidationErrors]}}))}))},getGlobalClaimValidators:function(e){return e.claimValidatorsAddedByOtherRecipes},validateClaims:function(e){return o(this,void 0,void 0,(function(){var t,n,r,o,i,a,u,c,l;return s(this,(function(s){switch(s.label){case 0:return[4,this.getAccessTokenPayloadSecurely({userContext:e.userContext})];case 1:t=s.sent(),n=0,r=e.claimValidators,s.label=2;case 2:return n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.CookieHandlerReference=void 0;var r=n(6570),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.cookieHandler=t(r.defaultCookieHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensCookieHandler must be initialized before calling this method.");return e.instance},e}();t.CookieHandlerReference=o,t.default=o},2946:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProvider=void 0;var r=n(7860),o=function(){function e(){this.clockSkewInMillis=0,this.thresholdInSeconds=7}return e.init=function(){if(void 0===e.instance){e.instance=new e;var t=r.default.getReferenceOrThrow().windowHandler.localStorage.getItemSync(e.CLOCK_SKEW_KEY),n=null!==t?parseInt(t,10):0;e.instance.setClientClockSkewInMillis(n)}},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("DateProvider must be initialized before calling this method.");return e.instance},e.prototype.getThresholdInSeconds=function(){return this.thresholdInSeconds},e.prototype.setThresholdInSeconds=function(e){this.thresholdInSeconds=e},e.prototype.setClientClockSkewInMillis=function(t){this.clockSkewInMillis=Math.abs(t)>=1e3*this.thresholdInSeconds?t:0,r.default.getReferenceOrThrow().windowHandler.localStorage.setItemSync(e.CLOCK_SKEW_KEY,String(t))},e.prototype.getClientClockSkewInMillis=function(){return this.clockSkewInMillis},e.prototype.now=function(){return Date.now()+this.getClientClockSkewInMillis()},e.CLOCK_SKEW_KEY="__st_clockSkewInMillis",e}();t.DateProvider=o},2519:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DateProviderReference=void 0;var r=n(2946),o=function(){function e(e){void 0!==e?this.dateProvider=e():(r.DateProvider.init(),this.dateProvider=r.DateProvider.getReferenceOrThrow())}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensDateProvider must be initialized before calling this method.");return e.instance},e}();t.DateProviderReference=o,t.default=o},2652:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.LockFactoryReference=void 0;var r=n(9895),o=function(){function e(e){this.lockFactory=e}return e.init=function(t,n){void 0===this.instance&&(this.instance=new e(null!=t?t:function(e){return function(){return Promise.resolve(new r.default(e))}}(n)))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensLockReference must be initialized before calling this method.");return e.instance},e}();t.LockFactoryReference=o,t.default=o},2582:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SessionClaimValidatorStore=void 0;var n=function(){function e(){}return e.claimValidatorsAddedByOtherRecipes=[],e.addClaimValidatorFromOtherRecipe=function(t){e.claimValidatorsAddedByOtherRecipes.push(t)},e.getClaimValidatorsAddedByOtherRecipes=function(){return e.claimValidatorsAddedByOtherRecipes},e}();t.SessionClaimValidatorStore=n,t.default=n},1936:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{Object.defineProperty(t,"__esModule",{value:!0}),t.WindowHandlerReference=void 0;var r=n(1936),o=function(){function e(e){var t=function(e){return e};void 0!==e&&(t=e),this.windowHandler=t(r.defaultWindowHandlerImplementation)}return e.init=function(t){void 0===e.instance&&(e.instance=new e(t))},e.getReferenceOrThrow=function(){if(void 0===e.instance)throw new Error("SuperTokensWindowHandler must be initialized before calling this method.");return e.instance},e}();t.WindowHandlerReference=o,t.default=o},5204:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.supported_fdi=t.package_version=void 0,t.package_version="20.0.0",t.supported_fdi=["1.16","1.17","1.18","1.19"]},9291:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{u(r.next(e))}catch(e){s(e)}}function a(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}u((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]{if(!n){var i=1/0;for(l=0;l=s)&&Object.keys(r.O).every((e=>r.O[e](n[u])))?n.splice(u--,1):(a=!1,s0&&e[l-1][2]>s;l--)e[l]=e[l-1];e[l]=[n,o,s]},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{var e={624:0};r.O.j=t=>0===e[t];var t=(t,n)=>{var o,s,[i,a,u]=n,c=0;if(i.some((t=>0!==e[t]))){for(o in a)r.o(a,o)&&(r.m[o]=a[o]);if(u)var l=u(r)}for(t&&t(n);c { - if (formField.id === "email") { - // Email validation failed (for example incorrect email syntax). - window.alert(formField.error); + try { + let response = await signIn({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax). + window.alert(formField.error); + } + }); + } else if (response.status === "WRONG_CREDENTIALS_ERROR") { + window.alert("Email password combination is incorrect."); + } else if (response.status === "SIGN_IN_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in was not allowed. + window.alert(response.reason); + } else { + // sign in successful. The session tokens are automatically handled by + // the frontend SDK. + window.location.href = "/dashboard"; + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); } - }); - } else if (response.status === "WRONG_CREDENTIALS_ERROR") { - window.alert("Email password combination is incorrect."); - } else if (response.status === "SIGN_IN_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign in was not allowed. - window.alert(response.reason); - } else { - // sign in successful. The session tokens are automatically handled by - // the frontend SDK. - window.location.href = "/dashboard"; - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); } - } } export async function checkEmail(email: string) { - try { - let response = await doesEmailExist({ - email, - }); + try { + let response = await doesEmailExist({ + email, + }); - if (response.doesExist) { - window.alert("Email already exists. Please sign in instead"); - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + if (response.doesExist) { + window.alert("Email already exists. Please sign in instead"); + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } export async function signUpClicked(email: string, password: string) { - try { - let response = await signUp({ - formFields: [ - { - id: "email", - value: email, - }, - { - id: "password", - value: password, - }, - ], - }); - - if (response.status === "FIELD_ERROR") { - // one of the input formFields failed validation - response.formFields.forEach((formField) => { - if (formField.id === "email") { - // Email validation failed (for example incorrect email syntax), - // or the email is not unique. - window.alert(formField.error); - } else if (formField.id === "password") { - // Password validation failed. - // Maybe it didn't match the password strength - window.alert(formField.error); + try { + let response = await signUp({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + // one of the input formFields failed validation + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax), + // or the email is not unique. + window.alert(formField.error); + } else if (formField.id === "password") { + // Password validation failed. + // Maybe it didn't match the password strength + window.alert(formField.error); + } + }); + } else if (response.status === "SIGN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign up was not allowed. + window.alert(response.reason); + } else { + // sign up successful. The session tokens are automatically handled by + // the frontend SDK. + window.location.href = "/dashboard"; + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); } - }); - } else if (response.status === "SIGN_UP_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign up was not allowed. - window.alert(response.reason); - } else { - // sign up successful. The session tokens are automatically handled by - // the frontend SDK. - window.location.href = "/dashboard"; - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); } - } } export async function signOutClicked() { - try { - await signOut(); - window.location.href = "/"; - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + await signOut(); + window.location.href = "/"; + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } export async function getSessionInfo() { - try { - let response = await fetch("/auth/sessioninfo", { - method: "GET", - headers: { - "Content-Type": "application/json", - }, - }); - - if (response.status === 200) { - let data = await response.json(); - return data; - } else { - window.alert("Oops! Something went wrong."); + try { + let response = await fetch("/auth/sessioninfo", { + method: "GET", + headers: { + "Content-Type": "application/json", + }, + }); + + if (response.status === 200) { + let data = await response.json(); + return data; + } else { + window.alert("Oops! Something went wrong."); + } + } catch (err: any) { + window.alert("Oops! Something went wrong."); } - } catch (err: any) { - window.alert("Oops! Something went wrong."); - } } diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts index 9c3bbcaa..6aa82926 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/STBEConfig.ts @@ -6,49 +6,49 @@ import appInfo from "./appInfo.json"; import { type TypeInput } from "supertokens-node/types"; export const initBE = (): TypeInput => { - return { - framework: "custom", - supertokens: { - // https://try.supertokens.com is for demo purposes. Replace this with the address of your core instance (sign up on supertokens.com), or self host a core. - connectionURI: "https://try.supertokens.com", - // apiKey: , - }, - appInfo, - recipeList: [ - EmailPasswordNode.init(), - ThirdPartyNode.init({ - // We have provided you with development keys which you can use for testing. - // IMPORTANT: Please replace them with your own OAuth keys for production use. - signInAndUpFeature: { - providers: [ - { - config: { - thirdPartyId: "google", - clients: [ - { - clientId: - "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", - clientSecret: "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", - }, - ], - }, - }, - { - config: { - thirdPartyId: "github", - clients: [ - { - clientId: "467101b197249757c71f", - clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", - }, - ], - }, - }, - ], + return { + framework: "custom", + supertokens: { + // https://try.supertokens.com is for demo purposes. Replace this with the address of your core instance (sign up on supertokens.com), or self host a core. + connectionURI: "https://try.supertokens.com", + // apiKey: , }, - }), - SessionNode.init(), - ], - isInServerlessEnv: true, - }; + appInfo, + recipeList: [ + EmailPasswordNode.init(), + ThirdPartyNode.init({ + // We have provided you with development keys which you can use for testing. + // IMPORTANT: Please replace them with your own OAuth keys for production use. + signInAndUpFeature: { + providers: [ + { + config: { + thirdPartyId: "google", + clients: [ + { + clientId: + "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", + clientSecret: "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", + }, + ], + }, + }, + { + config: { + thirdPartyId: "github", + clients: [ + { + clientId: "467101b197249757c71f", + clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", + }, + ], + }, + }, + ], + }, + }), + SessionNode.init(), + ], + isInServerlessEnv: true, + }; }; diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts index fce7220d..56326bdc 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/STFEConfig.ts @@ -5,12 +5,8 @@ import appInfo from "./appInfo.json"; import { type SuperTokensConfig } from "supertokens-web-js/types"; export const initFE = (): SuperTokensConfig => { - return { - appInfo, - recipeList: [ - ThirdPartyWebJs.init(), - EmailPasswordWebJs.init(), - SessionWebJs.init(), - ], - }; + return { + appInfo, + recipeList: [ThirdPartyWebJs.init(), EmailPasswordWebJs.init(), SessionWebJs.init()], + }; }; diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json b/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json index dc55aece..97c72116 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/appInfo.json @@ -1,6 +1,6 @@ { - "appName": "Astro-ST-demo", - "apiDomain": "http://localhost:4321", - "apiBasePath": "/auth", - "websiteDomain": "http://localhost:4321" + "appName": "Astro-ST-demo", + "apiDomain": "http://localhost:4321", + "apiBasePath": "/auth", + "websiteDomain": "http://localhost:4321" } diff --git a/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts b/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts index 337e5852..1b34bba2 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts +++ b/examples/astro/with-thirdpartyemailpassword/src/auth/superTokensHelper.ts @@ -1,13 +1,10 @@ import { - PreParsedRequest, - CollectingResponse, - middleware, - errorHandler, + PreParsedRequest, + CollectingResponse, + middleware, + errorHandler, } from "supertokens-node/framework/custom/index.js"; -import Session, { - type SessionContainer, - type VerifySessionOptions, -} from "supertokens-node/recipe/session/index.js"; +import Session, { type SessionContainer, type VerifySessionOptions } from "supertokens-node/recipe/session/index.js"; import SessionRecipe from "supertokens-node/lib/build/recipe/session/recipe.js"; import { availableTokenTransferMethods } from "supertokens-node/lib/build/recipe/session/constants.js"; import { getToken } from "supertokens-node/lib/build/recipe/session/cookieAndHeaders.js"; @@ -21,176 +18,168 @@ import appInfo from "./appInfo.json"; type HTTPMethod = "post" | "get" | "delete" | "put" | "options" | "trace"; const client = jwksClient({ - jwksUri: `${appInfo.apiDomain}${appInfo.apiBasePath}/jwt/jwks.json`, + jwksUri: `${appInfo.apiDomain}${appInfo.apiBasePath}/jwt/jwks.json`, }); function getAccessToken(request: Request): string | undefined { - return getCookieFromRequest(request)["sAccessToken"]; + return getCookieFromRequest(request)["sAccessToken"]; } function getPublicKey(header: JwtHeader, callback: SigningKeyCallback) { - client.getSigningKey(header.kid, (err, key) => { - if (err) { - callback(err); - } else { - const signingKey = key?.getPublicKey(); - callback(null, signingKey); - } - }); + client.getSigningKey(header.kid, (err, key) => { + if (err) { + callback(err); + } else { + const signingKey = key?.getPublicKey(); + callback(null, signingKey); + } + }); } async function verifyToken(token: string): Promise { - return new Promise((resolve, reject) => { - JsonWebToken.verify(token, getPublicKey, {}, (err, decoded) => { - if (err) { - reject(err); - } else { - resolve(decoded as JwtPayload); - } + return new Promise((resolve, reject) => { + JsonWebToken.verify(token, getPublicKey, {}, (err, decoded) => { + if (err) { + reject(err); + } else { + resolve(decoded as JwtPayload); + } + }); }); - }); } export function handleAuthAPIRequest(AstroResponse: typeof Response) { - const stMiddleware = middleware((req) => { - return createPreParsedRequest(req); - }); + const stMiddleware = middleware((req) => { + return createPreParsedRequest(req); + }); - return async function handleCall(req: Request) { - const baseResponse = new CollectingResponse(); + return async function handleCall(req: Request) { + const baseResponse = new CollectingResponse(); - const { handled, error } = await stMiddleware(req, baseResponse); + const { handled, error } = await stMiddleware(req, baseResponse); - if (error) { - throw error; - } - if (!handled) { - return new AstroResponse("Not found", { status: 404 }); - } + if (error) { + throw error; + } + if (!handled) { + return new AstroResponse("Not found", { status: 404 }); + } - for (const respCookie of baseResponse.cookies) { - baseResponse.headers.append( - "Set-Cookie", - serialize(respCookie.key, respCookie.value, { - domain: respCookie.domain, - expires: new Date(respCookie.expires), - httpOnly: respCookie.httpOnly, - path: respCookie.path, - sameSite: respCookie.sameSite, - secure: respCookie.secure, - }), - ); - } + for (const respCookie of baseResponse.cookies) { + baseResponse.headers.append( + "Set-Cookie", + serialize(respCookie.key, respCookie.value, { + domain: respCookie.domain, + expires: new Date(respCookie.expires), + httpOnly: respCookie.httpOnly, + path: respCookie.path, + sameSite: respCookie.sameSite, + secure: respCookie.secure, + }) + ); + } - return new AstroResponse(baseResponse.body, { - headers: baseResponse.headers, - status: baseResponse.statusCode, - }); - }; + return new AstroResponse(baseResponse.body, { + headers: baseResponse.headers, + status: baseResponse.statusCode, + }); + }; } function getCookieFromRequest(request: Request) { - const cookies: Record = {}; - const cookieHeader = request.headers.get("Cookie"); - if (cookieHeader) { - const cookieStrings = cookieHeader.split(";"); - for (const cookieString of cookieStrings) { - const [name, value] = cookieString.trim().split("="); - cookies[name] = decodeURIComponent(value); + const cookies: Record = {}; + const cookieHeader = request.headers.get("Cookie"); + if (cookieHeader) { + const cookieStrings = cookieHeader.split(";"); + for (const cookieString of cookieStrings) { + const [name, value] = cookieString.trim().split("="); + cookies[name] = decodeURIComponent(value); + } } - } - return cookies; + return cookies; } function getQueryFromRequest(request: Request) { - const query: Record = {}; - const url = new URL(request.url); - const searchParams = url.searchParams; - searchParams.forEach((value, key) => { - query[key] = value; - }); - return query; + const query: Record = {}; + const url = new URL(request.url); + const searchParams = url.searchParams; + searchParams.forEach((value, key) => { + query[key] = value; + }); + return query; } function createPreParsedRequest(request: Request): PreParsedRequest { - return new PreParsedRequest({ - cookies: getCookieFromRequest(request), - url: request.url as string, - method: request.method as HTTPMethod, - query: getQueryFromRequest(request), - headers: request.headers, - getFormBody: async () => { - return await request.formData(); - }, - getJSONBody: async () => { - return await request.json(); - }, - }); + return new PreParsedRequest({ + cookies: getCookieFromRequest(request), + url: request.url as string, + method: request.method as HTTPMethod, + query: getQueryFromRequest(request), + headers: request.headers, + getFormBody: async () => { + return await request.formData(); + }, + getJSONBody: async () => { + return await request.json(); + }, + }); } async function getSessionDetails( - preParsedRequest: PreParsedRequest, - options?: VerifySessionOptions, - userContext?: Record, + preParsedRequest: PreParsedRequest, + options?: VerifySessionOptions, + userContext?: Record ): Promise<{ - session: SessionContainer | undefined; - hasToken: boolean; - hasInvalidClaims: boolean; - baseResponse: CollectingResponse; - AstroResponse?: Response; + session: SessionContainer | undefined; + hasToken: boolean; + hasInvalidClaims: boolean; + baseResponse: CollectingResponse; + AstroResponse?: Response; }> { - const baseResponse = new CollectingResponse(); - const recipe = (SessionRecipe as any).default.instance; - const tokenTransferMethod = recipe.config.getTokenTransferMethod({ - req: preParsedRequest, - forCreateNewSession: false, - userContext, - }); - const transferMethods = - tokenTransferMethod === "any" - ? availableTokenTransferMethods - : [tokenTransferMethod]; - const hasToken = transferMethods.some((transferMethod) => { - const token = getToken(preParsedRequest, "access", transferMethod); - if (!token) { - return false; - } - try { - parseJWTWithoutSignatureVerification(token); - return true; - } catch { - return false; - } - }); + const baseResponse = new CollectingResponse(); + const recipe = (SessionRecipe as any).default.instance; + const tokenTransferMethod = recipe.config.getTokenTransferMethod({ + req: preParsedRequest, + forCreateNewSession: false, + userContext, + }); + const transferMethods = tokenTransferMethod === "any" ? availableTokenTransferMethods : [tokenTransferMethod]; + const hasToken = transferMethods.some((transferMethod) => { + const token = getToken(preParsedRequest, "access", transferMethod); + if (!token) { + return false; + } + try { + parseJWTWithoutSignatureVerification(token); + return true; + } catch { + return false; + } + }); - try { - const session = await Session.getSession( - preParsedRequest, - baseResponse, - options, - userContext, - ); - return { - session, - hasInvalidClaims: false, - hasToken, - baseResponse, - }; - } catch (err) { - if (Session.Error.isErrorFromSuperTokens(err)) { - return { - hasToken, - hasInvalidClaims: err.type === Session.Error.INVALID_CLAIMS, - session: undefined, - baseResponse, - AstroResponse: new Response("Authentication required", { - status: err.type === Session.Error.INVALID_CLAIMS ? 403 : 401, - }), - }; - } else { - throw err; + try { + const session = await Session.getSession(preParsedRequest, baseResponse, options, userContext); + return { + session, + hasInvalidClaims: false, + hasToken, + baseResponse, + }; + } catch (err) { + if (Session.Error.isErrorFromSuperTokens(err)) { + return { + hasToken, + hasInvalidClaims: err.type === Session.Error.INVALID_CLAIMS, + session: undefined, + baseResponse, + AstroResponse: new Response("Authentication required", { + status: err.type === Session.Error.INVALID_CLAIMS ? 403 : 401, + }), + }; + } else { + throw err; + } } - } } /** @@ -201,104 +190,89 @@ async function getSessionDetails( * propagated to the client side, as request interceptors do not run on the server side. */ export async function getSessionForSSR(astroRequest: Request): Promise<{ - accessTokenPayload: JwtPayload | undefined; - hasToken: boolean; - error: Error | undefined; + accessTokenPayload: JwtPayload | undefined; + hasToken: boolean; + error: Error | undefined; }> { - const accessToken = getAccessToken(astroRequest); - const hasToken = !!accessToken; - try { - if (accessToken) { - const decoded = await verifyToken(accessToken); - return { accessTokenPayload: decoded, hasToken, error: undefined }; - } - return { accessTokenPayload: undefined, hasToken, error: undefined }; - } catch (error) { - if (error instanceof JsonWebToken.TokenExpiredError) { - return { accessTokenPayload: undefined, hasToken, error: undefined }; + const accessToken = getAccessToken(astroRequest); + const hasToken = !!accessToken; + try { + if (accessToken) { + const decoded = await verifyToken(accessToken); + return { accessTokenPayload: decoded, hasToken, error: undefined }; + } + return { accessTokenPayload: undefined, hasToken, error: undefined }; + } catch (error) { + if (error instanceof JsonWebToken.TokenExpiredError) { + return { accessTokenPayload: undefined, hasToken, error: undefined }; + } + return { accessTokenPayload: undefined, hasToken, error: error as Error }; } - return { accessTokenPayload: undefined, hasToken, error: error as Error }; - } } export async function withSession( - astroRequest: Request, - handler: ( - error: Error | undefined, - session: SessionContainer | undefined, - ) => Promise, - options?: VerifySessionOptions, - userContext?: Record, + astroRequest: Request, + handler: (error: Error | undefined, session: SessionContainer | undefined) => Promise, + options?: VerifySessionOptions, + userContext?: Record ): Promise { - try { - let baseRequest = createPreParsedRequest(astroRequest); - const { session, AstroResponse, baseResponse } = await getSessionDetails( - baseRequest, - options, - userContext, - ); + try { + let baseRequest = createPreParsedRequest(astroRequest); + const { session, AstroResponse, baseResponse } = await getSessionDetails(baseRequest, options, userContext); - if (AstroResponse !== undefined) { - return AstroResponse; - } + if (AstroResponse !== undefined) { + return AstroResponse; + } - let userResponse: Response; + let userResponse: Response; - try { - userResponse = await handler(undefined, session); - } catch (err) { - await errorHandler()( - err, - baseRequest, - baseResponse, - (errorHandlerError: Error) => { - if (errorHandlerError) { - throw errorHandlerError; - } - }, - ); + try { + userResponse = await handler(undefined, session); + } catch (err) { + await errorHandler()(err, baseRequest, baseResponse, (errorHandlerError: Error) => { + if (errorHandlerError) { + throw errorHandlerError; + } + }); - // The headers in the userResponse are set twice from baseResponse, but the resulting response contains unique headers. - userResponse = new Response(baseResponse.body, { - status: baseResponse.statusCode, - headers: baseResponse.headers, - }); - } + // The headers in the userResponse are set twice from baseResponse, but the resulting response contains unique headers. + userResponse = new Response(baseResponse.body, { + status: baseResponse.statusCode, + headers: baseResponse.headers, + }); + } - let didAddCookies = false; - let didAddHeaders = false; + let didAddCookies = false; + let didAddHeaders = false; - for (const respCookie of baseResponse.cookies) { - didAddCookies = true; - userResponse.headers.append( - "Set-Cookie", - serialize(respCookie.key, respCookie.value, { - domain: respCookie.domain, - expires: new Date(respCookie.expires), - httpOnly: respCookie.httpOnly, - path: respCookie.path, - sameSite: respCookie.sameSite, - secure: respCookie.secure, - }), - ); - } + for (const respCookie of baseResponse.cookies) { + didAddCookies = true; + userResponse.headers.append( + "Set-Cookie", + serialize(respCookie.key, respCookie.value, { + domain: respCookie.domain, + expires: new Date(respCookie.expires), + httpOnly: respCookie.httpOnly, + path: respCookie.path, + sameSite: respCookie.sameSite, + secure: respCookie.secure, + }) + ); + } - baseResponse.headers.forEach((value: string, key: string) => { - didAddHeaders = true; - userResponse.headers.set(key, value); - }); - if (didAddCookies || didAddHeaders) { - if (!userResponse.headers.has("Cache-Control")) { - // This is needed for production deployments with Vercel - userResponse.headers.set( - "Cache-Control", - "no-cache, no-store, max-age=0, must-revalidate", - ); - } - } + baseResponse.headers.forEach((value: string, key: string) => { + didAddHeaders = true; + userResponse.headers.set(key, value); + }); + if (didAddCookies || didAddHeaders) { + if (!userResponse.headers.has("Cache-Control")) { + // This is needed for production deployments with Vercel + userResponse.headers.set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); + } + } - return userResponse; - } catch (error) { - return await handler(error as Error, undefined); - } + return userResponse; + } catch (error) { + return await handler(error as Error, undefined); + } } diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts index cdf5590f..4573028b 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...path]/[...route].ts @@ -6,18 +6,18 @@ import { handleAuthAPIRequest } from "../../../auth/superTokensHelper"; const handleCall = handleAuthAPIRequest(Response); export const ALL: APIRoute = async ({ params, request }) => { - SuperTokens.init(initBE()); + SuperTokens.init(initBE()); - if (params.path === "callback") { - console.log("callback"); - } + if (params.path === "callback") { + console.log("callback"); + } - try { - return await handleCall(request); - } catch (error) { - console.error(error); - return new Response(JSON.stringify({ error: "Internal server error" }), { - status: 500, - }); - } + try { + return await handleCall(request); + } catch (error) { + console.error(error); + return new Response(JSON.stringify({ error: "Internal server error" }), { + status: 500, + }); + } }; diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts index 45f1275a..11b1eaf2 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/[...route].ts @@ -6,14 +6,14 @@ import { handleAuthAPIRequest } from "../../auth/superTokensHelper"; const handleCall = handleAuthAPIRequest(Response); export const ALL: APIRoute = async ({ params, request }) => { - SuperTokens.init(initBE()); + SuperTokens.init(initBE()); - try { - return await handleCall(request); - } catch (error) { - console.error(error); - return new Response(JSON.stringify({ error: "Internal server error" }), { - status: 500, - }); - } + try { + return await handleCall(request); + } catch (error) { + console.error(error); + return new Response(JSON.stringify({ error: "Internal server error" }), { + status: 500, + }); + } }; diff --git a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts index 67a154e4..1b6b1482 100644 --- a/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts +++ b/examples/astro/with-thirdpartyemailpassword/src/pages/auth/sessioninfo.ts @@ -2,18 +2,18 @@ import { type APIRoute } from "astro"; import { withSession } from "../../auth/superTokensHelper"; export const GET: APIRoute = async ({ params, request }) => { - return withSession(request, async (err, session) => { - if (err) { - return new Response(JSON.stringify(err), { status: 500 }); - } + return withSession(request, async (err, session) => { + if (err) { + return new Response(JSON.stringify(err), { status: 500 }); + } - return new Response( - JSON.stringify({ - note: "Fetch any data from your application for authenticated user after using verifySession middleware", - userId: session!.getUserId(), - sessionHandle: session!.getHandle(), - accessTokenPayload: session!.getAccessTokenPayload(), - }), - ); - }); + return new Response( + JSON.stringify({ + note: "Fetch any data from your application for authenticated user after using verifySession middleware", + userId: session!.getUserId(), + sessionHandle: session!.getHandle(), + accessTokenPayload: session!.getAccessTokenPayload(), + }) + ); + }); }; diff --git a/examples/astro/with-thirdpartyemailpassword/tsconfig.json b/examples/astro/with-thirdpartyemailpassword/tsconfig.json index 77da9dd0..418a1a1d 100644 --- a/examples/astro/with-thirdpartyemailpassword/tsconfig.json +++ b/examples/astro/with-thirdpartyemailpassword/tsconfig.json @@ -1,3 +1,3 @@ { - "extends": "astro/tsconfigs/strict" -} \ No newline at end of file + "extends": "astro/tsconfigs/strict" +} diff --git a/examples/solidjs/with-thirdpartyemailpassword/index.html b/examples/solidjs/with-thirdpartyemailpassword/index.html index 70217370..d29a34b4 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/index.html +++ b/examples/solidjs/with-thirdpartyemailpassword/index.html @@ -1,13 +1,13 @@ - + - - - - - Vite + Solid + TS - - -
- - + + + + + Vite + Solid + TS + + +
+ + diff --git a/examples/solidjs/with-thirdpartyemailpassword/server.ts b/examples/solidjs/with-thirdpartyemailpassword/server.ts index f90ed970..854f4c8e 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/server.ts +++ b/examples/solidjs/with-thirdpartyemailpassword/server.ts @@ -2,100 +2,96 @@ import express from "express"; import cors from "cors"; import supertokens from "supertokens-node"; import { verifySession } from "supertokens-node/recipe/session/framework/express"; -import { - middleware, - errorHandler, - SessionRequest, -} from "supertokens-node/framework/express"; +import { middleware, errorHandler, SessionRequest } from "supertokens-node/framework/express"; import Session from "supertokens-node/recipe/session"; import EmailPassword from "supertokens-node/recipe/emailpassword"; import ThirdParty from "supertokens-node/recipe/thirdparty"; supertokens.init({ - framework: "express", - supertokens: { - connectionURI: "https://try.supertokens.com", - }, - appInfo: { - appName: "Hacking With SuperTokens", - apiDomain: "http://localhost:3001", - websiteDomain: "http://localhost:3000", - apiBasePath: "", - websiteBasePath: "/", - }, - recipeList: [ - EmailPassword.init(), - ThirdParty.init({ - // We have provided you with development keys which you can use for testing. - // IMPORTANT: Please replace them with your own OAuth keys for production use. - signInAndUpFeature: { - providers: [ - { - config: { - thirdPartyId: "google", - clients: [ - { - clientId: - "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", - clientSecret: "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", - }, - ], + framework: "express", + supertokens: { + connectionURI: "https://try.supertokens.com", + }, + appInfo: { + appName: "Hacking With SuperTokens", + apiDomain: "http://localhost:3001", + websiteDomain: "http://localhost:3000", + apiBasePath: "", + websiteBasePath: "/", + }, + recipeList: [ + EmailPassword.init(), + ThirdParty.init({ + // We have provided you with development keys which you can use for testing. + // IMPORTANT: Please replace them with your own OAuth keys for production use. + signInAndUpFeature: { + providers: [ + { + config: { + thirdPartyId: "google", + clients: [ + { + clientId: + "1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com", + clientSecret: "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", + }, + ], + }, + }, + { + config: { + thirdPartyId: "github", + clients: [ + { + clientId: "467101b197249757c71f", + clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", + }, + ], + }, + }, + { + config: { + thirdPartyId: "apple", + clients: [ + { + clientId: "4398792-io.supertokens.example.service", + additionalConfig: { + keyId: "7M48Y4RYDL", + privateKey: + "-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----", + teamId: "YWQCXGJRJL", + }, + }, + ], + }, + }, + ], }, - }, - { - config: { - thirdPartyId: "github", - clients: [ - { - clientId: "467101b197249757c71f", - clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd", - }, - ], - }, - }, - { - config: { - thirdPartyId: "apple", - clients: [ - { - clientId: "4398792-io.supertokens.example.service", - additionalConfig: { - keyId: "7M48Y4RYDL", - privateKey: - "-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----", - teamId: "YWQCXGJRJL", - }, - }, - ], - }, - }, - ], - }, - }), - Session.init(), // initializes session features - ], + }), + Session.init(), // initializes session features + ], }); const app = express(); app.use( - cors({ - origin: "http://localhost:3000", - allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()], - methods: ["GET", "PUT", "POST", "DELETE"], - credentials: true, - }) + cors({ + origin: "http://localhost:3000", + allowedHeaders: ["content-type", ...supertokens.getAllCORSHeaders()], + methods: ["GET", "PUT", "POST", "DELETE"], + credentials: true, + }) ); app.use(middleware()); app.get("/sessioninfo", verifySession(), async (req: SessionRequest, res) => { - let session = req.session; - res.send({ - sessionHandle: session!.getHandle(), - userId: session!.getUserId(), - accessTokenPayload: session!.getAccessTokenPayload(), - }); + let session = req.session; + res.send({ + sessionHandle: session!.getHandle(), + userId: session!.getUserId(), + accessTokenPayload: session!.getAccessTokenPayload(), + }); }); // In case of session related errors, this error handler diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/App.css b/examples/solidjs/with-thirdpartyemailpassword/src/App.css index 285ccf33..0f650a48 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/src/App.css +++ b/examples/solidjs/with-thirdpartyemailpassword/src/App.css @@ -1,132 +1,132 @@ :root { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - line-height: 1.5; - font-weight: 400; + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; + font-weight: 500; + color: #646cff; + text-decoration: inherit; } a:hover { - color: #535bf2; + color: #535bf2; } body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; } h1 { - font-size: 3.2em; - line-height: 1.1; + font-size: 3.2em; + line-height: 1.1; } button { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; - color: rgba(255, 255, 255, 0.87); + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; + color: rgba(255, 255, 255, 0.87); } button:hover { - border-color: #646cff; + border-color: #646cff; } button:focus, button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; + outline: 4px auto -webkit-focus-ring-color; } @media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } + :root { + color: #213547; + background-color: #ffffff; + } + a:hover { + color: #747bff; + } + button { + background-color: #f9f9f9; + } } .form-wrap { - display: flex; - flex-direction: column; - gap: 1em; - max-width: 320px; + display: flex; + flex-direction: column; + gap: 1em; + max-width: 320px; } .form-wrap input { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - border: 1px solid #646cff; - border-radius: 8px; - padding: 0.6em 1em; - font-size: 1em; - font-family: inherit; + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + border: 1px solid #646cff; + border-radius: 8px; + padding: 0.6em 1em; + font-size: 1em; + font-family: inherit; } div.wrapper { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 1em; - height: 100vh; - width: 100vw; - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - line-height: 1.5; - font-weight: 400; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1em; + height: 100vh; + width: 100vw; + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } div.wrapper header { - height: 80px; - background: #ff9933; - display: flex; - align-items: center; - justify-content: center; + height: 80px; + background: #ff9933; + display: flex; + align-items: center; + justify-content: center; } div.wrapper main { - flex-grow: 1; - display: flex; - align-items: center; - justify-content: center; - min-width: 60%; + flex-grow: 1; + display: flex; + align-items: center; + justify-content: center; + min-width: 60%; } div.wrapper footer { - height: 60px; - background: #1f1f1f; - display: flex; - align-items: center; - justify-content: center; + height: 60px; + background: #1f1f1f; + display: flex; + align-items: center; + justify-content: center; } diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx b/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx index e9227b57..a6257632 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx +++ b/examples/solidjs/with-thirdpartyemailpassword/src/Auth.tsx @@ -1,8 +1,4 @@ -import { - doesEmailExist, - signIn, - signUp, -} from "supertokens-web-js/recipe/emailpassword"; +import { doesEmailExist, signIn, signUp } from "supertokens-web-js/recipe/emailpassword"; import { getAuthorisationURLWithQueryParamsAndSetState } from "supertokens-web-js/recipe/thirdparty"; import { createSignal, onMount, Show } from "solid-js"; import "./App.css"; @@ -11,417 +7,387 @@ import { useNavigate } from "@solidjs/router"; import { signInAndUp } from "supertokens-web-js/recipe/thirdparty"; async function handleGoogleCallback(navigate: (path: string) => void) { - try { - const response = await signInAndUp(); - - if (response.status === "OK") { - console.log(response.user); - if ( - response.createdNewRecipeUser && - response.user.loginMethods.length === 1 - ) { - console.log("sign up successful, google"); - } else { - console.log("sign in successful, google"); - } - // window.location.assign("/home"); - navigate("/dashboard/"); - } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign in / up was not allowed. - window.alert(response.reason); - } else { - // SuperTokens requires that the third party provider - // gives an email for the user. If that's not the case, sign up / in - // will fail. - - // As a hack to solve this, you can override the backend functions to create a fake email for the user. - - window.alert( - "No email provided by social login. Please use another form of login" - ); - navigate("/auth"); // redirect back to login page - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if (response.createdNewRecipeUser && response.user.loginMethods.length === 1) { + console.log("sign up successful, google"); + } else { + console.log("sign in successful, google"); + } + // window.location.assign("/home"); + navigate("/dashboard/"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert("No email provided by social login. Please use another form of login"); + navigate("/auth"); // redirect back to login page + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } async function googleSignInClicked() { - try { - const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ - thirdPartyId: "google", - - // This is where Google should redirect the user back after login or error. - // This URL goes on the Google's dashboard as well. - frontendRedirectURI: "http://localhost:3000/auth/callback/google", - }); - - // we redirect the user to google for auth. - window.location.assign(authUrl); - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "google", + + // This is where Google should redirect the user back after login or error. + // This URL goes on the Google's dashboard as well. + frontendRedirectURI: "http://localhost:3000/auth/callback/google", + }); + + // we redirect the user to google for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } async function handleGitHubCallback(navigate: (path: string) => void) { - try { - const response = await signInAndUp(); - - if (response.status === "OK") { - console.log(response.user); - if ( - response.createdNewRecipeUser && - response.user.loginMethods.length === 1 - ) { - console.log("sign up successful, github"); - } else { - console.log("sign in successful, github"); - } - // window.location.assign("/home"); - navigate("/dashboard/"); - } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign in / up was not allowed. - window.alert(response.reason); - } else { - // SuperTokens requires that the third party provider - // gives an email for the user. If that's not the case, sign up / in - // will fail. - - // As a hack to solve this, you can override the backend functions to create a fake email for the user. - - window.alert( - "No email provided by social login. Please use another form of login" - ); - navigate("/auth"); // redirect back to login page - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if (response.createdNewRecipeUser && response.user.loginMethods.length === 1) { + console.log("sign up successful, github"); + } else { + console.log("sign in successful, github"); + } + // window.location.assign("/home"); + navigate("/dashboard/"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert("No email provided by social login. Please use another form of login"); + navigate("/auth"); // redirect back to login page + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } async function githubSignInClicked() { - try { - const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ - thirdPartyId: "github", - - // This is where Google should redirect the user back after login or error. - // This URL goes on the Google's dashboard as well. - frontendRedirectURI: "http://localhost:3000/auth/callback/github", - }); - - // we redirect the user to google for auth. - window.location.assign(authUrl); - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "github", + + // This is where Google should redirect the user back after login or error. + // This URL goes on the Google's dashboard as well. + frontendRedirectURI: "http://localhost:3000/auth/callback/github", + }); + + // we redirect the user to google for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } async function handleAppleCallback(navigate: (path: string) => void) { - try { - const response = await signInAndUp(); - - if (response.status === "OK") { - console.log(response.user); - if ( - response.createdNewRecipeUser && - response.user.loginMethods.length === 1 - ) { - console.log("sign up successful, apple"); - } else { - console.log("sign in successful, apple"); - } - // window.location.assign("/home"); - navigate("/dashboard/"); - } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign in / up was not allowed. - window.alert(response.reason); - } else { - // SuperTokens requires that the third party provider - // gives an email for the user. If that's not the case, sign up / in - // will fail. - - // As a hack to solve this, you can override the backend functions to create a fake email for the user. - - window.alert( - "No email provided by social login. Please use another form of login" - ); - navigate("/auth"); // redirect back to login page - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + const response = await signInAndUp(); + + if (response.status === "OK") { + console.log(response.user); + if (response.createdNewRecipeUser && response.user.loginMethods.length === 1) { + console.log("sign up successful, apple"); + } else { + console.log("sign in successful, apple"); + } + // window.location.assign("/home"); + navigate("/dashboard/"); + } else if (response.status === "SIGN_IN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in / up was not allowed. + window.alert(response.reason); + } else { + // SuperTokens requires that the third party provider + // gives an email for the user. If that's not the case, sign up / in + // will fail. + + // As a hack to solve this, you can override the backend functions to create a fake email for the user. + + window.alert("No email provided by social login. Please use another form of login"); + navigate("/auth"); // redirect back to login page + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } async function appleSignInClicked() { - try { - const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ - thirdPartyId: "apple", - - frontendRedirectURI: "http://localhost:3000/auth/callback/apple", // This is an example callback URL on your frontend. You can use another path as well. - redirectURIOnProviderDashboard: - "http://localhost:3000/auth/callback/apple", // This URL goes on the Apple's dashboard - }); - - // we redirect the user to apple for auth. - window.location.assign(authUrl); - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + const authUrl = await getAuthorisationURLWithQueryParamsAndSetState({ + thirdPartyId: "apple", + + frontendRedirectURI: "http://localhost:3000/auth/callback/apple", // This is an example callback URL on your frontend. You can use another path as well. + redirectURIOnProviderDashboard: "http://localhost:3000/auth/callback/apple", // This URL goes on the Apple's dashboard + }); + + // we redirect the user to apple for auth. + window.location.assign(authUrl); + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } -async function signUpClicked( - email: string, - password: string, - navigate: (path: string) => void -) { - try { - let response = await signUp({ - formFields: [ - { - id: "email", - value: email, - }, - { - id: "password", - value: password, - }, - ], - }); - - if (response.status === "FIELD_ERROR") { - // one of the input formFields failed validaiton - response.formFields.forEach((formField) => { - if (formField.id === "email") { - // Email validation failed (for example incorrect email syntax), - // or the email is not unique. - window.alert(formField.error); - } else if (formField.id === "password") { - // Password validation failed. - // Maybe it didn't match the password strength - window.alert(formField.error); +async function signUpClicked(email: string, password: string, navigate: (path: string) => void) { + try { + let response = await signUp({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + // one of the input formFields failed validaiton + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax), + // or the email is not unique. + window.alert(formField.error); + } else if (formField.id === "password") { + // Password validation failed. + // Maybe it didn't match the password strength + window.alert(formField.error); + } + }); + } else if (response.status === "SIGN_UP_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign up was not allowed. + window.alert(response.reason); + } else { + // sign up successful. The session tokens are automatically handled by + // the frontend SDK. + navigate("/dashboard/"); + } + } catch (err: any) { + console.log(err); + + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); } - }); - } else if (response.status === "SIGN_UP_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign up was not allowed. - window.alert(response.reason); - } else { - // sign up successful. The session tokens are automatically handled by - // the frontend SDK. - navigate("/dashboard/"); - } - } catch (err: any) { - console.log(err); - - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); } - } } async function checkEmail(email: string) { - try { - let response = await doesEmailExist({ - email, - }); - - return response; - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); + try { + let response = await doesEmailExist({ + email, + }); + + return response; + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); + } } - } } -async function signInClicked( - email: string, - password: string, - navigate: (path: string) => void -) { - try { - let response = await signIn({ - formFields: [ - { - id: "email", - value: email, - }, - { - id: "password", - value: password, - }, - ], - }); - - if (response.status === "FIELD_ERROR") { - response.formFields.forEach((formField) => { - if (formField.id === "email") { - // Email validation failed (for example incorrect email syntax). - window.alert(formField.error); +async function signInClicked(email: string, password: string, navigate: (path: string) => void) { + try { + let response = await signIn({ + formFields: [ + { + id: "email", + value: email, + }, + { + id: "password", + value: password, + }, + ], + }); + + if (response.status === "FIELD_ERROR") { + response.formFields.forEach((formField) => { + if (formField.id === "email") { + // Email validation failed (for example incorrect email syntax). + window.alert(formField.error); + } + }); + } else if (response.status === "WRONG_CREDENTIALS_ERROR") { + window.alert("Email password combination is incorrect."); + } else if (response.status === "SIGN_IN_NOT_ALLOWED") { + // the reason string is a user friendly message + // about what went wrong. It can also contain a support code which users + // can tell you so you know why their sign in was not allowed. + window.alert(response.reason); + } else { + // sign in successful. The session tokens are automatically handled by + // the frontend SDK. + navigate("/dashboard/"); + } + } catch (err: any) { + if (err.isSuperTokensGeneralError === true) { + // this may be a custom error message sent from the API by you. + window.alert(err.message); + } else { + window.alert("Oops! Something went wrong."); } - }); - } else if (response.status === "WRONG_CREDENTIALS_ERROR") { - window.alert("Email password combination is incorrect."); - } else if (response.status === "SIGN_IN_NOT_ALLOWED") { - // the reason string is a user friendly message - // about what went wrong. It can also contain a support code which users - // can tell you so you know why their sign in was not allowed. - window.alert(response.reason); - } else { - // sign in successful. The session tokens are automatically handled by - // the frontend SDK. - navigate("/dashboard/"); - } - } catch (err: any) { - if (err.isSuperTokensGeneralError === true) { - // this may be a custom error message sent from the API by you. - window.alert(err.message); - } else { - window.alert("Oops! Something went wrong."); } - } } function Auth() { - const navigate = useNavigate(); - superTokensInit(); - const [showOAuthLoading] = createSignal( - (() => { - if (window.location.pathname === "/auth/callback/google") { - return "Google"; - } - - if (window.location.pathname === "/auth/callback/github") { - return "GitHub"; - } - - if (window.location.pathname === "/auth/callback/apple") { - return "Apple"; - } - - return false; - })() - ); - - onMount(() => { - if (window.location.pathname === "/auth/callback/google") { - handleGoogleCallback(navigate); - } + const navigate = useNavigate(); + superTokensInit(); + const [showOAuthLoading] = createSignal( + (() => { + if (window.location.pathname === "/auth/callback/google") { + return "Google"; + } + + if (window.location.pathname === "/auth/callback/github") { + return "GitHub"; + } + + if (window.location.pathname === "/auth/callback/apple") { + return "Apple"; + } + + return false; + })() + ); + + onMount(() => { + if (window.location.pathname === "/auth/callback/google") { + handleGoogleCallback(navigate); + } - if (window.location.pathname === "/auth/callback/github") { - handleGitHubCallback(navigate); - } + if (window.location.pathname === "/auth/callback/github") { + handleGitHubCallback(navigate); + } - if (window.location.pathname === "/auth/callback/apple") { - handleAppleCallback(navigate); - } - }); + if (window.location.pathname === "/auth/callback/apple") { + handleAppleCallback(navigate); + } + }); - const [email, setEmail] = createSignal(""); - const [password, setPassword] = createSignal(""); + const [email, setEmail] = createSignal(""); + const [password, setPassword] = createSignal(""); - const handleSignUpClicked = async () => { - const res = await checkEmail(email()); - if (!res?.doesExist) { - signUpClicked(email(), password(), navigate); - } else { - window.alert("Email already exists. Please sign in instead"); - } - }; - - const handleSignInClicked = async () => { - const res = await checkEmail(email()); - if (res?.doesExist) { - signInClicked(email(), password(), navigate); - } else { - window.alert("Email does not exist. Please sign up instead"); - } - }; - - const handleGoogleSignInClicked = async () => { - googleSignInClicked(); - }; - - const handleGithubSignInClicked = async () => { - githubSignInClicked(); - }; - - const handleAppleSignInClicked = async () => { - appleSignInClicked(); - }; - - return ( -
-
- - Logging-in via {showOAuthLoading()}, please wait... - - - setEmail((e.target as HTMLInputElement).value)} - /> - setPassword((e.target as HTMLInputElement).value)} - /> - - - - - - -
-
- ); + const handleSignUpClicked = async () => { + const res = await checkEmail(email()); + if (!res?.doesExist) { + signUpClicked(email(), password(), navigate); + } else { + window.alert("Email already exists. Please sign in instead"); + } + }; + + const handleSignInClicked = async () => { + const res = await checkEmail(email()); + if (res?.doesExist) { + signInClicked(email(), password(), navigate); + } else { + window.alert("Email does not exist. Please sign up instead"); + } + }; + + const handleGoogleSignInClicked = async () => { + googleSignInClicked(); + }; + + const handleGithubSignInClicked = async () => { + githubSignInClicked(); + }; + + const handleAppleSignInClicked = async () => { + appleSignInClicked(); + }; + + return ( +
+
+ Logging-in via {showOAuthLoading()}, please wait... + + setEmail((e.target as HTMLInputElement).value)} + /> + setPassword((e.target as HTMLInputElement).value)} + /> + + + + + + +
+
+ ); } export default Auth; diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx b/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx index 1c1847da..f6bc3c62 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx +++ b/examples/solidjs/with-thirdpartyemailpassword/src/Dashboard.tsx @@ -5,49 +5,49 @@ import Session from "supertokens-web-js/recipe/session"; import { useNavigate } from "@solidjs/router"; function Dashboard() { - const navigate = useNavigate(); - superTokensInit(); - - const [loading, setLoading] = createSignal(true); - - const getSessionInfo = async () => { - const response = await fetch("http://localhost:3001/sessioninfo", { - headers: { - "Content-Type": "application/json", - }, - method: "GET", - credentials: "include", - }); + const navigate = useNavigate(); + superTokensInit(); + + const [loading, setLoading] = createSignal(true); - const data = await response.json(); + const getSessionInfo = async () => { + const response = await fetch("http://localhost:3001/sessioninfo", { + headers: { + "Content-Type": "application/json", + }, + method: "GET", + credentials: "include", + }); - alert(JSON.stringify(data)); - }; + const data = await response.json(); - async function signOut() { - await Session.signOut(); - navigate("/"); - } + alert(JSON.stringify(data)); + }; - createEffect(async () => { - if (await Session.doesSessionExist()) { - setLoading(false); - } else { - navigate("/"); + async function signOut() { + await Session.signOut(); + navigate("/"); } - }); - - return ( -
-
- Loading... - - - - -
-
- ); + + createEffect(async () => { + if (await Session.doesSessionExist()) { + setLoading(false); + } else { + navigate("/"); + } + }); + + return ( +
+
+ Loading... + + + + +
+
+ ); } export default Dashboard; diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts b/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts index 3479f02d..739ae642 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts +++ b/examples/solidjs/with-thirdpartyemailpassword/src/config/supertokens.ts @@ -6,18 +6,18 @@ import ThirdParty from "supertokens-web-js/recipe/thirdparty"; let initialized = false; export const superTokensInit = () => { - if (initialized) { - return; - } + if (initialized) { + return; + } - SuperTokens.init({ - appInfo: { - apiDomain: "http://localhost:3001", - apiBasePath: "", - appName: "Hacking With SuperTokens", - }, - recipeList: [Session.init(), EmailPassword.init(), ThirdParty.init()], - }); + SuperTokens.init({ + appInfo: { + apiDomain: "http://localhost:3001", + apiBasePath: "", + appName: "Hacking With SuperTokens", + }, + recipeList: [Session.init(), EmailPassword.init(), ThirdParty.init()], + }); - initialized = true; + initialized = true; }; diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/index.css b/examples/solidjs/with-thirdpartyemailpassword/src/index.css index 6119ad9a..279fff56 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/src/index.css +++ b/examples/solidjs/with-thirdpartyemailpassword/src/index.css @@ -1,68 +1,68 @@ :root { - font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; - line-height: 1.5; - font-weight: 400; + font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; + line-height: 1.5; + font-weight: 400; - color-scheme: light dark; - color: rgba(255, 255, 255, 0.87); - background-color: #242424; + color-scheme: light dark; + color: rgba(255, 255, 255, 0.87); + background-color: #242424; - font-synthesis: none; - text-rendering: optimizeLegibility; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; + font-synthesis: none; + text-rendering: optimizeLegibility; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } a { - font-weight: 500; - color: #646cff; - text-decoration: inherit; + font-weight: 500; + color: #646cff; + text-decoration: inherit; } a:hover { - color: #535bf2; + color: #535bf2; } body { - margin: 0; - display: flex; - place-items: center; - min-width: 320px; - min-height: 100vh; + margin: 0; + display: flex; + place-items: center; + min-width: 320px; + min-height: 100vh; } h1 { - font-size: 3.2em; - line-height: 1.1; + font-size: 3.2em; + line-height: 1.1; } button { - border-radius: 8px; - border: 1px solid transparent; - padding: 0.6em 1.2em; - font-size: 1em; - font-weight: 500; - font-family: inherit; - background-color: #1a1a1a; - cursor: pointer; - transition: border-color 0.25s; + border-radius: 8px; + border: 1px solid transparent; + padding: 0.6em 1.2em; + font-size: 1em; + font-weight: 500; + font-family: inherit; + background-color: #1a1a1a; + cursor: pointer; + transition: border-color 0.25s; } button:hover { - border-color: #646cff; + border-color: #646cff; } button:focus, button:focus-visible { - outline: 4px auto -webkit-focus-ring-color; + outline: 4px auto -webkit-focus-ring-color; } @media (prefers-color-scheme: light) { - :root { - color: #213547; - background-color: #ffffff; - } - a:hover { - color: #747bff; - } - button { - background-color: #f9f9f9; - } + :root { + color: #213547; + background-color: #ffffff; + } + a:hover { + color: #747bff; + } + button { + background-color: #f9f9f9; + } } diff --git a/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx b/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx index beafb07f..ebfb37f2 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx +++ b/examples/solidjs/with-thirdpartyemailpassword/src/index.tsx @@ -9,14 +9,14 @@ import Dashboard from "./Dashboard"; const root = document.getElementById("root"); render( - () => ( - - - - - - - - ), - root! + () => ( + + + + + + + + ), + root! ); diff --git a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json index 348fb418..28bb9e70 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json +++ b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.app.json @@ -1,28 +1,28 @@ { - "compilerOptions": { - "composite": true, - "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", - "target": "ES2020", - "useDefineForClassFields": true, - "module": "ESNext", - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "skipLibCheck": true, + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", + "target": "ES2020", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "resolveJsonModule": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true - }, - "include": ["src"] + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] } diff --git a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json index ea9d0cd8..41ccf0f7 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json +++ b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.json @@ -1,11 +1,11 @@ { - "files": [], - "references": [ - { - "path": "./tsconfig.app.json" - }, - { - "path": "./tsconfig.node.json" - } - ] + "files": [], + "references": [ + { + "path": "./tsconfig.app.json" + }, + { + "path": "./tsconfig.node.json" + } + ] } diff --git a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json index 3afdd6e3..9277af59 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json +++ b/examples/solidjs/with-thirdpartyemailpassword/tsconfig.node.json @@ -1,13 +1,13 @@ { - "compilerOptions": { - "composite": true, - "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", - "skipLibCheck": true, - "module": "ESNext", - "moduleResolution": "bundler", - "allowSyntheticDefaultImports": true, - "strict": true, - "noEmit": true - }, - "include": ["vite.config.ts"] + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "skipLibCheck": true, + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "strict": true, + "noEmit": true + }, + "include": ["vite.config.ts"] } diff --git a/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts b/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts index 75e21324..8cb1f085 100644 --- a/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts +++ b/examples/solidjs/with-thirdpartyemailpassword/vite.config.ts @@ -2,8 +2,8 @@ import { defineConfig } from "vite"; import solid from "vite-plugin-solid"; export default defineConfig({ - plugins: [solid()], - server: { - port: 3000, - }, + plugins: [solid()], + server: { + port: 3000, + }, });