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.

180 lines (178 loc) • 8.93 kB
import { assert, panic } from "../../assertions.js"; import { writeCookies } from "../../cookies.js"; import { sessionConfig } from "../config.js"; import { makePlatform } from "../platform.js"; import { assertCanChange, clearPendingAuth, makeSessionDataCookie, makeSessionTokenCookie, readPendingAuthToken, readSessionToken } from "../session.js"; import { authError, isAuthenticatorNotInPlan, isUserLimitReached } from "./utils.js"; //#region src/auth/methods/authenticator.ts /** * Starts enrolling an authenticator app, for a sign-in that asked to set one up * or for a signed-in visitor adding one. * * `otpauthUri` is what an authenticator app reads. `qrPngBase64` is that same * URI as a PNG for `<img src="data:image/png;base64,…">`, so a page can show * the QR code without a QR library. Neither one enrols anybody. * {@link confirmAuthenticatorSetup} does that, once it accepts a first code. * * Call it again to hand back a fresh QR code, for a visitor who lost the first * one. Only the newest one enrols them. */ async function startAuthenticatorSetup() { assertCanChange("auth.startAuthenticatorSetup"); const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupInit(readPendingAuthToken() ?? readSessionToken()); if (!result.ok) { if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message); if (result.status === 401) return authError("notAuthenticated", result.message); if (result.status === 429) return authError("tooManyAttempts", result.message); if (result.status >= 500) panic(`Expected authenticator setup to start, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } return { success: true, data: result.data }; } /** * Enrols the authenticator app on its first code and signs the visitor in. * * This is the only call that returns the backup codes, and it returns them * once. Nothing fetches them again, so render them before leaving the page. */ async function confirmAuthenticatorSetup(details) { assertCanChange("auth.confirmAuthenticatorSetup"); const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupComplete(readPendingAuthToken() ?? readSessionToken(), details.code); if (!result.ok) { if (isUserLimitReached(result)) return authError("userLimitReached", result.message); if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message); 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 authenticator setup to finish, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } const { session, backupCodes } = result.data; writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({ user: session.user }, session.jwt)]); clearPendingAuth(); return { success: true, data: { user: session.user, backupCodes } }; } /** * Skips enrolment and finishes the sign-in, for a visitor whose app offers an * authenticator without requiring one. Only the `setupOptional` step. * * Later sign-ins stop asking. */ async function skipAuthenticatorSetup() { assertCanChange("auth.skipAuthenticatorSetup"); const result = await makePlatform(sessionConfig().applicationId).authenticatorSetupDismiss(readPendingAuthToken() ?? readSessionToken()); if (!result.ok) { if (isUserLimitReached(result)) return authError("userLimitReached", result.message); if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message); if (result.status === 401) return authError("notAuthenticated", result.message); if (result.status === 429) return authError("tooManyAttempts", result.message); if (result.status >= 500) panic(`Expected to skip authenticator setup, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } const { session } = result.data; assert(session, "Expected a session from skipping setup, but got none"); writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({ user: session.user }, session.jwt)]); clearPendingAuth(); return { success: true, data: session.user }; } /** * Finishes a sign-in that stopped at the `verify` step, with the code the * visitor's authenticator app shows or one of their backup codes. * * Each backup code works once. */ async function verifyAuthenticator(credentials) { assertCanChange("auth.verifyAuthenticator"); const result = await makePlatform(sessionConfig().applicationId).authenticatorVerify(readPendingAuthToken() ?? readSessionToken(), "code" in credentials ? { totpCode: credentials.code } : { backupCode: credentials.backupCode }); if (!result.ok) { if (isUserLimitReached(result)) return authError("userLimitReached", result.message); if (isAuthenticatorNotInPlan(result)) return authError("secondFactorNotEnabled", result.message); 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 authenticator, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } 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: session.user }; } /** * Emails the signed-in visitor the code that {@link resetAuthenticator} and * {@link removeAuthenticator} ask for. * * Both change how the visitor signs in, so both want a code from their inbox * on top of being signed in. */ async function sendAuthenticatorResetCode() { assertCanChange("auth.sendAuthenticatorResetCode"); const result = await makePlatform(sessionConfig().applicationId).authenticatorSendResetCode(readSessionToken()); 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 reset code to be emailed, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } return { success: true, data: null }; } /** * Unpairs the visitor's authenticator app so they can enrol a new one with * {@link startAuthenticatorSetup}, after a lost or replaced phone. * * `code` is the one {@link sendAuthenticatorResetCode} emailed. */ async function resetAuthenticator(details) { assertCanChange("auth.resetAuthenticator"); const result = await makePlatform(sessionConfig().applicationId).authenticatorReset(readSessionToken(), 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 the authenticator to be reset, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } return { success: true, data: null }; } /** * Turns the visitor's authenticator app off entirely. * * `code` is the one {@link sendAuthenticatorResetCode} emailed. An app that * requires an authenticator will ask them to set one up again on their next * sign-in. */ async function removeAuthenticator(details) { assertCanChange("auth.removeAuthenticator"); const result = await makePlatform(sessionConfig().applicationId).authenticatorRemove(readSessionToken(), 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 the authenticator to be removed, but got ${result.status}: ` + result.message); throw new Error(`${result.message}. Check SOFTR_APPLICATION_ID and that the app allows an authenticator app.`); } return { success: true, data: null }; } //#endregion export { confirmAuthenticatorSetup, removeAuthenticator, resetAuthenticator, sendAuthenticatorResetCode, skipAuthenticatorSetup, startAuthenticatorSetup, verifyAuthenticator };