@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
287 lines (285 loc) • 10.8 kB
JavaScript
import { panic } from "../assertions.js";
import { expireCookie, expireOtherCopy, readRequestCookies, serializeCookie, writeCookies } from "../cookies.js";
import { sessionConfig } from "./config.js";
import { makePlatform } from "./platform.js";
import { userSchema } from "./user.js";
import { getRequestProtocol } from "@tanstack/react-start/server";
import { z } from "zod";
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
//#region src/auth/session.ts
const SESSION_TOKEN = "session_token";
const SESSION_DATA = "session_data";
const PENDING_AUTH = "pending_auth";
const SSO_BINDING = "softr_sso_binding";
const SESSION_DATA_TTL_SECONDS = 300;
/**
* How long a visitor has to answer a second factor. The platform expires the
* challenge token itself. This only decides how long the browser carries it.
*/
const PENDING_AUTH_TTL_SECONDS = 600;
/** How long a visitor has to finish signing in at their identity provider. */
const SSO_BINDING_TTL_SECONDS = 600;
/**
* A browser refuses a `__Host-` cookie unless it is `Secure`, `Path=/` and free
* of `Domain` — that last clause is the one worth having, since it stops a
* sibling host planting a cookie of this name for us to honour.
*/
const HOST_PREFIX = "__Host-";
function requestIsSecure() {
return getRequestProtocol() === "https";
}
function sessionCookieName(base, secure) {
return secure ? HOST_PREFIX + base : base;
}
function sessionCookie(base) {
const secure = requestIsSecure();
return {
name: sessionCookieName(base, secure),
secure
};
}
/**
* Runs `fn` with `token` standing in for the request's session cookie, so that
* every datasource call inside it acts as that visitor.
*
* For requests that carry who they are somewhere other than the cookie: an MCP
* call authenticates with a bearer token and has no cookie at all.
*/
function withSessionToken(token, fn) {
return standIn.run({ token }, fn);
}
/**
* The visitor of the token that {@link withSessionToken} stands in, fetched once
* per scope. `undefined` outside one, where the request middleware has already
* resolved the visitor.
*/
function readStandInUser() {
const scope = standIn.getStore();
if (scope === void 0) return void 0;
scope.user ??= makePlatform(sessionConfig().applicationId).session(scope.token).then((result) => result.ok ? result.data.user : panic(result.message));
return scope.user;
}
/**
* The visitor, fetched from the platform now and not from the 5-minute session
* cache. A write checks its filter with this visitor. So a user who just lost a
* value, for example a team, cannot write through the old one.
*/
async function readFreshUser() {
const standIn$1 = readStandInUser();
if (standIn$1 !== void 0) return standIn$1;
const token = readSessionToken();
if (token === null) return null;
const result = await makePlatform(sessionConfig().applicationId).session(token);
return result.ok ? result.data.user : panic(result.message);
}
/** The platform token this request carries, or `null`. */
function readSessionToken() {
const scope = standIn.getStore();
if (scope !== void 0) return scope.token;
const { name } = sessionCookie(SESSION_TOKEN);
return openEnvelope(readRequestCookies()[name], SESSION_TOKEN);
}
/** The cached visitor for `sessionToken`, or `null` on any kind of miss. */
function readSessionData(sessionToken) {
const { name } = sessionCookie(SESSION_DATA);
const payload = parseSessionData(openEnvelope(readRequestCookies()[name], SESSION_DATA));
if (payload === null) return null;
if (payload.exp <= Math.floor(Date.now() / 1e3)) return null;
if (payload.tb !== tokenBinding(sessionToken)) return null;
return { user: payload.user };
}
/**
* The token cookie, after a deletion of any copy from before `allowEmbedding`
* changed. Both would be sent, and the old one could be read instead.
*/
function makeSessionTokenCookie(token) {
const { name, secure } = sessionCookie(SESSION_TOKEN);
return [...expireOtherCopy(name, secure), serializeCookie(name, sealEnvelope(token, SESSION_TOKEN), {
maxAge: sessionConfig().sessionMaxAge,
secure
})];
}
function makeSessionDataCookie(session, sessionToken) {
const { name, secure } = sessionCookie(SESSION_DATA);
const payload = {
user: session.user,
exp: Math.floor(Date.now() / 1e3) + SESSION_DATA_TTL_SECONDS,
tb: tokenBinding(sessionToken)
};
return serializeCookie(name, sealEnvelope(JSON.stringify(payload), SESSION_DATA), {
maxAge: SESSION_DATA_TTL_SECONDS,
secure
});
}
/**
* The challenge token from a sign-in that stopped at a second factor, or
* `null`.
*
* It is a bearer credential scoped to the authenticator endpoints, so it stays
* sealed in the jar the way a session token does, instead of passing through
* the app.
*/
function readPendingAuthToken() {
const { name } = sessionCookie(PENDING_AUTH);
return openEnvelope(readRequestCookies()[name], PENDING_AUTH);
}
function makePendingAuthCookie(token) {
const { name, secure } = sessionCookie(PENDING_AUTH);
return serializeCookie(name, sealEnvelope(token, PENDING_AUTH), {
maxAge: PENDING_AUTH_TTL_SECONDS,
secure
});
}
/** Drops an outstanding challenge without touching the session. */
function clearPendingAuth() {
clearCookies([PENDING_AUTH]);
}
/**
* Ties a single sign-on round trip to the browser that started it. The
* platform checks its token against the one the identity provider sends back,
* so a response started in another browser can't sign this one in.
*
* Cross-site, because a SAML identity provider posts its answer from its own
* site, and a Lax cookie is not sent with that.
*
* Not partitioned, unlike the session cookies of an embedded app. An identity
* provider refuses to load in an iframe, so single sign-on only ever runs top
* level, where a partition adds nothing.
*/
function makeSsoBindingCookie(binding) {
const { name, secure } = sessionCookie(SSO_BINDING);
return serializeCookie(name, sealEnvelope(JSON.stringify(binding), SSO_BINDING), {
maxAge: SSO_BINDING_TTL_SECONDS,
secure,
crossSite: true
});
}
/** The binding this browser holds, or `null`. */
function readSsoBinding() {
const { name } = sessionCookie(SSO_BINDING);
const json = openEnvelope(readRequestCookies()[name], SSO_BINDING);
if (json === null) return null;
try {
const binding = ssoBindingSchema.safeParse(JSON.parse(json));
return binding.success ? binding.data : null;
} catch {
return null;
}
}
/** Single use: every answer from the identity provider spends it. */
function clearSsoBinding() {
clearCookies([SSO_BINDING]);
}
/**
* Writes rather than returns: a forgotten list would leave the session live.
*/
function clearSession() {
clearCookies([
SESSION_TOKEN,
SESSION_DATA,
PENDING_AUTH
]);
}
/**
* Drops the cached visitor and leaves the session signed in, so the next
* request needing a visitor re-reads one from the platform.
*
* For a mutation to what the visitor's own record holds — their name, their
* groups — which the cache would otherwise answer stale for up to five minutes.
*/
function clearSessionData() {
clearCookies([SESSION_DATA]);
}
const standIn = new AsyncLocalStorage();
const sessionDataSchema = z.object({
user: userSchema.nullable(),
exp: z.number(),
tb: z.string()
});
const ssoBindingSchema = z.object({
bindingToken: z.string(),
returnPath: z.string()
});
/**
* Both spellings on https: a jar can hold both pairs across a move between
* schemes, and the one left behind would revive if the scheme changed back.
*/
function clearCookies(bases) {
const secure = requestIsSecure();
writeCookies(bases.flatMap((base) => secure ? [sessionCookieName(base, secure), base] : [base]).flatMap((name) => expireCookie(name, secure)));
}
/**
* Over the plaintext token, never the cookie value: that is resealed with a
* fresh iv on every write, so a binding over its bytes would be a permanent
* cache miss.
*/
function tokenBinding(sessionToken) {
if (sessionToken === null) return "anonymous";
return createHash("sha256").update(sessionToken).digest("base64url");
}
function parseSessionData(json) {
if (json === null) return null;
let payload;
try {
payload = JSON.parse(json);
} catch {
return null;
}
const data = sessionDataSchema.safeParse(payload);
return data.success ? data.data : null;
}
const IV_BYTES = 12;
const TAG_BYTES = 16;
/** Iv + one byte of ciphertext + tag. Anything shorter is not ours. */
const MIN_ENVELOPE_BYTES = IV_BYTES + TAG_BYTES + 1;
/**
* `Buffer.from(…, "base64url")` skips stray characters rather than throwing.
*/
const BASE64URL = /^[A-Za-z0-9_-]+$/;
/**
* One key for both cookies. The application id goes in with the secret so a
* cookie from staging is inert in production even when the two share a secret.
*/
function sessionKey() {
const { applicationId, sessionSecret } = sessionConfig();
return createHash("sha256").update(Buffer.from(sessionSecret, "hex")).update(applicationId).digest();
}
/**
* `base64url(iv ‖ ct ‖ tag)`, sealed with AES-256-GCM — an AEAD, so opening
* throws on a single flipped bit and needs no separate signature. The iv must
* be fresh per seal: nonce reuse under one key leaks the payloads and the
* authentication subkey.
*
* The purpose is bound in as additional authenticated data rather than by
* giving each cookie a key of its own: one key, and a `session_data` value
* moved into the token slot then fails to open at all instead of opening into
* a later field check.
*/
function sealEnvelope(payload, purpose) {
const iv = randomBytes(IV_BYTES);
const cipher = createCipheriv("aes-256-gcm", sessionKey(), iv);
cipher.setAAD(Buffer.from(purpose));
const sealed = Buffer.concat([cipher.update(payload, "utf8"), cipher.final()]);
return Buffer.concat([
iv,
sealed,
cipher.getAuthTag()
]).toString("base64url");
}
/** `null` for anything that is not one of ours, with no reason attached. */
function openEnvelope(raw, purpose) {
if (!raw || !BASE64URL.test(raw)) return null;
try {
const bytes = Buffer.from(raw, "base64url");
if (bytes.length < MIN_ENVELOPE_BYTES) return null;
const decipher = createDecipheriv("aes-256-gcm", sessionKey(), bytes.subarray(0, IV_BYTES));
decipher.setAAD(Buffer.from(purpose));
decipher.setAuthTag(bytes.subarray(bytes.length - TAG_BYTES));
return Buffer.concat([decipher.update(bytes.subarray(IV_BYTES, bytes.length - TAG_BYTES)), decipher.final()]).toString("utf8");
} catch {
return null;
}
}
//#endregion
export { clearPendingAuth, clearSession, clearSessionData, clearSsoBinding, makePendingAuthCookie, makeSessionDataCookie, makeSessionTokenCookie, makeSsoBindingCookie, readFreshUser, readPendingAuthToken, readSessionData, readSessionToken, readSsoBinding, readStandInUser, withSessionToken };