UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

68 lines (66 loc) • 2.88 kB
import { assert, panic } from "../../assertions.js"; import { writeCookies } from "../../cookies.js"; import { sessionConfig } from "../config.js"; import { makePlatform } from "../platform.js"; import { clearPendingAuth, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken } from "../session.js"; import { authError } from "./utils.js"; //#region src/auth/methods/emailCode2fa.ts /** * Finishes a sign-in that answered `emailCodeRequired`, with the code emailed * to the visitor. * * A `signedIn` result means the visitor is signed in. An app that also asks for * an authenticator app answers `authenticatorRequired` instead, naming the step * to send them to next. */ async function verifyEmailCode(details) { const result = await makePlatform(sessionConfig().applicationId).emailCodeVerify(readPendingAuthToken(), details.code); if (!result.ok) { if (result.status === 400 || result.status === 401) return authError("invalidCode", result.message); if (result.status === 429) return authError("tooManyAttempts", result.message); if (result.status >= 500) panic(`Expected to verify the emailed code, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app asks for an emailed code at sign-in.`); } if (result.data.status === "MFA_REQUIRED") { const { mfa } = result.data; assert(mfa, "Expected a challenge from verification, but got none"); writeCookies([makePendingAuthCookie(mfa.challengeToken)]); return { success: true, data: { status: "authenticatorRequired", step: mfa.action === "VERIFICATION_REQUIRED" ? "verify" : mfa.action === "SETUP_REQUIRED" ? "setup" : "setupOptional" } }; } const { session } = result.data; assert(session, "Expected a session from verification, but got none"); writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({ user: session.user }, session.jwt)]); clearPendingAuth(); return { success: true, data: { status: "signedIn", user: session.user } }; } /** * Emails the code for {@link verifyEmailCode} again. Asking again within a * short wait sends nothing and still succeeds. */ async function resendEmailCode() { const result = await makePlatform(sessionConfig().applicationId).emailCodeResend(readPendingAuthToken()); if (!result.ok) { if (result.status === 401) return authError("notAuthenticated", result.message); if (result.status === 429) return authError("tooManyAttempts", result.message); if (result.status >= 500) panic(`Expected the code to be emailed again, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app asks for an emailed code at sign-in.`); } return { success: true, data: null }; } //#endregion export { resendEmailCode, verifyEmailCode };