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.

221 lines (219 loc) • 8.14 kB
import { assert } from "../assertions.js"; import { logger } from "../logger.js"; import { softrConfig } from "../softr-config.js"; import { writeCookies } from "../cookies.js"; import { sessionConfig } from "./config.js"; import { makePlatform } from "./platform.js"; import { clearPendingAuth, clearSsoBinding, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, makeSsoBindingCookie, readSsoBinding } from "./session.js"; import { resolveReturnPath } from "./returnPath.js"; import { z } from "zod"; import { createMiddleware } from "@tanstack/react-start"; //#region src/auth/sso.ts const START_PATH = "/_softr/sso/start"; const OPEN_ID_CALLBACK_PATH = "/open-id/code"; const SAML_CALLBACK_PATH = "/saml/SSO"; const DEFAULT_SSO_PATH = "/sso-authentication"; /** * Where a link or button sends a visitor to sign in with single sign-on. They * come back to `returnPath` once signed in. Without one, they land where * `auth.guard.alreadyAuthenticated` in softr.json points, as after any sign-in. * * A full page load, not a router navigation: the visitor leaves the app for * their identity provider. * * @example * <a href={ssoSignInHref(toReturnPath(location).href)}>Continue with SSO</a> */ function ssoSignInHref(returnPath) { return returnPath ? `${START_PATH}?return=${encodeURIComponent(returnPath)}` : START_PATH; } /** * Starts single sign-on and finishes it when the identity provider answers. * Every other request passes through. * * The start is a GET the visitor's browser makes, so a link can begin it. The * identity provider answers OpenID Connect with a redirect, and SAML with a * form it posts from its own site. */ function ssoMiddleware() { return createMiddleware({ type: "request" }).server(async ({ next, request, pathname }) => { switch (pathname) { case START_PATH: if (request.method !== "GET") return methodNotAllowed("GET"); return await start(new URL(request.url)); case OPEN_ID_CALLBACK_PATH: { if (request.method !== "GET") return methodNotAllowed("GET"); const url = new URL(request.url); const code = url.searchParams.get("code"); const binding = readSsoBinding(); clearSsoBinding(); if (code === null) return toSsoPage({ error: "idp", returnPath: binding?.returnPath }); if (binding === null) return toSsoPage({ error: "expired" }); return await finish(await platform().signInWithOpenId({ code, state: url.searchParams.get("state") ?? "", ...binding }), binding.returnPath); } case SAML_CALLBACK_PATH: { if (request.method !== "POST") return methodNotAllowed("POST"); const form = await request.formData().catch(() => null); const samlResponse = form?.get("SAMLResponse"); const binding = readSsoBinding(); clearSsoBinding(); if (typeof samlResponse !== "string" || samlResponse === "") return toSsoPage({ error: "idp", returnPath: binding?.returnPath }); if (binding === null) return toSsoPage({ error: "expired" }); const relayState = form?.get("RelayState"); return await finish(await platform().signInWithSaml({ samlResponse, relayState: typeof relayState === "string" ? relayState : "", ...binding }), binding.returnPath); } default: return await next(); } }); } async function start(url) { const returnPath = resolveReturnPath(url.searchParams.get("return")); const result = await platform().ssoStart({ origin: url.origin, returnPath }); if (!result.ok) return toSsoPage({ ...failure(result), returnPath }); const started = result.data; const binding = makeSsoBindingCookie({ bindingToken: started.bindingToken, returnPath: started.returnPath }); if (started.protocol === "OPEN_ID") { assert(started.redirectUrl, "Expected where to send the visitor for OpenID sign-in, but got none"); writeCookies([binding]); return new Response(null, { status: 302, headers: { location: started.redirectUrl, "cache-control": "no-store" } }); } assert(started.formAction && started.samlRequest && started.relayState, "Expected the SAML request to post, but it came back incomplete"); writeCookies([binding]); return samlForm(started.formAction, started.samlRequest, started.relayState); } /** * `startedFor` is where the visitor wanted to go, so a retry after a failure * gets there. */ async function finish(result, startedFor) { if (!result.ok) return toSsoPage({ ...failure(result), returnPath: startedFor }); const { result: signIn, returnPath } = result.data; if (signIn.status === "MFA_REQUIRED") { const { mfa } = signIn; assert(mfa, "Expected a challenge from single sign-on, but got none"); writeCookies([makePendingAuthCookie(mfa.challengeToken)]); return toSsoPage({ authenticator: mfa.action === "VERIFICATION_REQUIRED" ? "verify" : mfa.action === "SETUP_REQUIRED" ? "setup" : "setupOptional", returnPath }); } const { session } = signIn; assert(session, "Expected a session from single sign-on, but got none"); writeCookies([...makeSessionTokenCookie(session.jwt), makeSessionDataCookie({ user: session.user }, session.jwt)]); clearPendingAuth(); return seeOther(resolveReturnPath(returnPath)); } const ssoErrorBodySchema = z.object({ code: z.string() }); function failure(result) { const body = ssoErrorBodySchema.safeParse(result.body); const code = body.success ? body.data.code : null; switch (code) { case "SSO_HOST_MISMATCH": return { error: "host" }; case "SSO_IDP_REJECTED": return { error: "idp" }; case "SSO_NOT_ENABLED": case "SSO_NOT_IN_PLAN": case "SSO_MISCONFIGURED": case "AUTHENTICATOR_NOT_IN_PLAN": return { error: "not-enabled" }; case "SSO_SIGN_UP_DISABLED": return { error: "sign-up-disabled" }; case "USER_DEACTIVATED": case "SIGN_IN_RESTRICTED": return { error: "restricted" }; case "SSO_BINDING_INVALID": return { error: "expired" }; default: logger.warn(`Single sign-on failed with ${result.status} ${code ?? "(no code)"}: ${result.message}`); return { error: "failed" }; } } /** * The app's SSO page, for a second factor or a failure. The return path rides * in the login page's redirect param. The page's "done" step, its "Try again" * and its login link all read it from there. Without the binding cookie there * is no path, and the visitor lands where any sign-in does. */ function toSsoPage(search) { const { routes } = softrConfig().auth; const params = new URLSearchParams(); if ("error" in search) params.set("error", search.error); else params.set("authenticator", search.authenticator); if (search.returnPath !== void 0) params.set(routes.login.redirectParam, resolveReturnPath(search.returnPath)); return seeOther(`${routes.sso?.path ?? DEFAULT_SSO_PATH}?${params}`); } function seeOther(location) { return new Response(null, { status: 303, headers: { location, "cache-control": "no-store" } }); } function methodNotAllowed(allowed) { return new Response(null, { status: 405, headers: { allow: allowed } }); } /** * SAML's POST binding: a form the browser posts to the identity provider. The * script submits it at once. Without scripts, the visitor presses the button. */ function samlForm(action, samlRequest, relayState) { const body = `<!doctype html> <html> <head><meta charset="utf-8"><meta name="robots" content="noindex"><title>Signing in…</title></head> <body> <form method="post" action="${escapeHtml(action)}"> <input type="hidden" name="SAMLRequest" value="${escapeHtml(samlRequest)}"> <input type="hidden" name="RelayState" value="${escapeHtml(relayState)}"> <noscript><button type="submit">Continue to sign in</button></noscript> </form> <script>document.forms[0].submit()<\/script> </body> </html>`; return new Response(body, { status: 200, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); } function escapeHtml(value) { return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); } function platform() { return makePlatform(sessionConfig().applicationId); } //#endregion export { ssoMiddleware, ssoSignInHref };