Use authtempo with Elysia
For: a developer of an Elysia app on Bun.
What it does: the app serves the routes of authtempo under /auth, and sends a person with no session to the sign-in page. It also verifies the caller of a route. No package of Elysia is needed: Elysia takes the web request.
Before you start
Section titled “Before you start”- Bun 1.4 or newer.
- A working setup from a getting started tutorial.
- Add the packages:
pnpm --filter my-app add @authtempo/core @authtempo/verify elysia. - Copy
withOriginfrom the code below. Bun gives a path only for a Host that does not parse. - Mount core:
.all("/auth/*", ({ request }) => auth.handle(withOrigin(request, env.BASE_URL))). - In a
resolvehook, callreadGateof@authtempo/core/bindingswith thepathof the context. - In
onBeforeHandle, answergate.redirectwhen it is not null. No page code runs then. - Read
gate.sessionin a page. The hook sends the renewed cookie after the sliding refresh. - For a route that a script calls, check the caller with the verify package.
import { createAuth, createMemoryAdapter, type MailPort } from "@authtempo/core";import { readGate } from "@authtempo/core/bindings";import { createVerifier } from "@authtempo/verify";import { Elysia } from "elysia";
export interface AppEnv { BASE_URL: string; AUTH_SECRET: string; mail: MailPort; /** Called with each text that the rule tests, and at each page run. The test counts them. */ trace?: ((event: "rule" | "page", text: string) => void) | undefined;}
/** * The request on the app's own origin: the Host header, else the origin of * BASE_URL. The app builds it, so the origin never comes from a request line * in absolute form, whatever the runtime does. Bun gives the path only for a * Host that does not parse ("a b"): that request also gets the BASE_URL origin. */export function withOrigin(request: Request, baseURL: string): Request { const fallback = new URL(baseURL); const parsed = URL.canParse(request.url) ? new URL(request.url) : null; const protocol = parsed?.protocol ?? fallback.protocol; let origin = fallback.origin; const host = request.headers.get("host"); if (host && URL.canParse(`${protocol}//${host}`)) origin = new URL(`${protocol}//${host}`).origin; const path = parsed ? `${parsed.pathname}${parsed.search}` : request.url; // Join as text: a path that starts with "//" is a path here, not a host. const url = new URL(`${origin}${path}`); // The common case: the URL is already on that origin, and the request passes unchanged. if (parsed?.href === url.href) return request; const init = { method: request.method, headers: request.headers, body: request.body }; return new Request(url, { ...init, duplex: "half" } as RequestInit);}
/** * The texts that the rule tests. Elysia's router matches the raw path: no * decode ("/%61ccount" is not "/account"), and with case ("/ACCOUNT" is not * "/account"). It runs "/account" for "/account/" (strictPath is off by * default), so the rule also tests the path with its trailing slashes cut. */function forms(path: string): string[] { return [path, path.replace(/\/+$/, "") || "/"];}
/** * The Elysia app. Warning: the memory adapter keeps rows in this process only. * Use the D1 or the Postgres adapter in production. */export function createApp(env: AppEnv) { const auth = createAuth({ baseURL: env.BASE_URL, secret: env.AUTH_SECRET, trustedOrigins: [env.BASE_URL], storage: createMemoryAdapter(), mail: env.mail, }); // An exact rule covers one route only. For a route with a parameter, use // p === "/account" || p.startsWith("/account/"). const gateOptions = { auth, protect: (p: string) => forms(p).some((form) => { env.trace?.("rule", form); return form === "/account"; }), signInPath: "/sign-in", }; // /files takes a ts_ bearer or an API token in the Authorization header, never the // cookie: one call to the auth app each. Here the auth app is this process; // another server passes no fetch. const verifier = createVerifier({ issuer: `${env.BASE_URL}/auth`, accept: ["session-token", "api-token"], fetch: (input, init) => auth.handle(new Request(input, init)), }); return ( new Elysia() // The gate of each matched route, with the path as the router matched it. // It reads no session for a route of core, and names no body, so Elysia // parses none: core reads the body as it came. .resolve(async ({ request, path, set }) => { const gate = await readGate(gateOptions, withOrigin(request, env.BASE_URL), path); // After a sliding refresh, renew the cookie, or the browser drops it early. if (gate.cookie) set.headers["set-cookie"] = gate.cookie; return { gate }; }) // A person with no session on /account goes to the sign-in page. No page code runs. .onBeforeHandle(({ gate }) => gate.redirect ?? undefined) // Every route of core under /auth, the default basePath. Each Set-Cookie line passes unchanged. .all("/auth/*", ({ request }) => auth.handle(withOrigin(request, env.BASE_URL))) .get("/account", ({ gate, path, status }) => { env.trace?.("page", path); if (!gate.session) return status(401, { error: "unauthorized" }); return { email: gate.session.user.email }; }) .get("/files", async ({ request, path }) => { env.trace?.("page", path); const r = await verifier.verifyRequest(withOrigin(request, env.BASE_URL)); // The auth app did not answer: try again later, not "sign in again". if (!r.ok) return Response.json({ error: r.code }, { status: 503 }); if (r.value === null) return verifier.unauthorized(); const owner = r.value.kind === "session-token" || r.value.kind === "api-token" ? r.value.user.email : null; return Response.json({ owner }); }) );}import { createClient } from "@authtempo/client";import type { MailMessage } from "@authtempo/core";import { describe, expect, it, vi } from "vitest";import { type AppEnv, createApp, withOrigin } from "../src/app.js";
const BASE = "http://localhost:3000";
function setup() { const sent: MailMessage[] = []; const rule: string[] = []; const pages: string[] = []; const env: AppEnv = { BASE_URL: BASE, AUTH_SECRET: "0123456789abcdef0123456789abcdef", mail: { async send(m) { sent.push(m); }, }, trace: (event, text) => (event === "rule" ? rule : pages).push(text), }; return { app: createApp(env), sent, rule, pages };}
describe("the Elysia example (plan 11d2)", () => { it("signs a person in with the plain client, reads the session, and verifies the caller of /files", async () => { const { app, sent } = setup(); let cookie = ""; let lines: string[] = []; const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input, init); const headers = new Headers(req.headers); headers.set("origin", BASE); if (cookie) headers.set("cookie", cookie); const res = await app.handle(new Request(req, { headers })); const set = res.headers.get("set-cookie"); if (set) cookie = set.includes("Max-Age=0") ? "" : (set.split(";")[0] ?? ""); lines = res.headers.getSetCookie(); return res; }) as typeof globalThis.fetch; const client = createClient({ baseURL: BASE, fetch, credentials: "omit" }); expect((await app.handle(new Request(`${BASE}/files`))).status).toBe(401); // A POST to core: the sign-in works only if Elysia left the body for core. expect((await client.magicLink.request({ email: "ada@example.com" })).ok).toBe(true); const token = /token=([A-Za-z0-9_-]+)/.exec(sent.at(-1)?.text ?? "")?.[1] ?? ""; expect((await client.magicLink.verify({ token })).ok).toBe(true); // The Set-Cookie line of core passes unchanged: one line, the session cookie. expect(lines).toHaveLength(1); expect(lines[0]?.startsWith("__Host-tempo_session=ts_")).toBe(true); const account = await app.handle(new Request(`${BASE}/account`, { headers: { cookie } })); expect(await account.json()).toEqual({ email: "ada@example.com" }); // The verifier reads the Authorization header only: the cookie is no credential at /files. expect((await app.handle(new Request(`${BASE}/files`, { headers: { cookie } }))).status).toBe( 401, ); const bearer = `Bearer ${cookie.slice(cookie.indexOf("=") + 1)}`; const files = await app.handle( new Request(`${BASE}/files`, { headers: { authorization: bearer } }), ); expect(await files.json()).toEqual({ owner: "ada@example.com" }); });
it("renews the session cookie on the page's answer, and passes core's one clear line at the sign-out", async () => { vi.useFakeTimers({ toFake: ["Date"] }); try { const { app, sent } = setup(); const json = { "content-type": "application/json", origin: BASE }; const post = (path: string, body: unknown, cookie = "") => app.handle( new Request(`${BASE}${path}`, { method: "POST", headers: { ...json, cookie }, body: JSON.stringify(body), }), ); await post("/auth/magic-link/request", { email: "ada@example.com" }); const token = /token=([A-Za-z0-9_-]+)/.exec(sent.at(-1)?.text ?? "")?.[1] ?? ""; const verified = await post("/auth/magic-link/verify", { token }); const cookie = verified.headers.getSetCookie()[0]?.split(";")[0] ?? ""; // Past the sliding refresh: the gate renews the session, and the page's answer carries the cookie. vi.setSystemTime(Date.now() + 8 * 86_400_000); const page = await app.handle(new Request(`${BASE}/account`, { headers: { cookie } })); expect(page.status).toBe(200); const lines = page.headers.getSetCookie(); expect(lines).toHaveLength(1); expect(lines[0]?.startsWith("__Host-tempo_session=ts_")).toBe(true); const out = await post("/auth/sign-out", {}, cookie); expect(out.headers.getSetCookie()).toHaveLength(1); expect(out.headers.getSetCookie()[0]).toContain("Max-Age=0"); } finally { vi.useRealTimers(); } });
it("sends a person with no session on /account to the sign-in page, and runs no page", async () => { const { app, pages } = setup(); const res = await app.handle(new Request(`${BASE}/account?tab=keys`)); expect(res.status).toBe(307); expect(res.headers.get("location")).toBe(`${BASE}/sign-in?next=%2Faccount%3Ftab%3Dkeys`); expect(pages).toEqual([]); });
// Elysia matches the raw path with case: "/%61ccount" and "/ACCOUNT" match no route (404). // It runs "/account" for "/account/", and the gate tests the path with the slash cut (307). it.each([ ["/%61ccount", 404], ["/ACCOUNT", 404], ["/account/", 307], // Elysia removes one trailing slash only. ["/account//", 404], // Bun and the URL parser resolve dot segments before the router: "/account/." is "/account/". ["/account/.", 307], ["/account/..", 404], ["/auth/../account", 307], ])( "answers %s with no cookie under an exact rule with %i, and runs no page", async (path, status) => { const { app, pages } = setup(); const res = await app.handle(new Request(`${BASE}${path}`)); expect(res.status).toBe(status); expect(pages).toEqual([]); }, );
it("answers /%61uth/session with 404: no route of core and no page runs, and the rule gets no text", async () => { const { app, rule, pages } = setup(); const res = await app.handle(new Request(`${BASE}/%61uth/session`)); expect([307, 401, 404]).toContain(res.status); expect(res.status).toBe(404); expect(pages).toEqual([]); expect(rule).toEqual([]); });
it("gives the rule the path as the router matched it, and the path with its trailing slashes removed", async () => { const { app, rule } = setup(); await app.handle(new Request(`${BASE}/account/`)); expect(rule).toEqual(["/account/", "/account"]); });
it("takes the origin of the redirect from Host, not from the request URL", async () => { const { app } = setup(); // An absolute-form request line names another origin; the Host header names the app. const res = await app.handle( new Request("http://evil.example/account", { headers: { host: "app.example:8080" } }), ); expect(res.status).toBe(307); expect(res.headers.get("location")).toBe("http://app.example:8080/sign-in?next=%2Faccount"); });
it("keeps a path that starts with // on the app's origin", () => { const url = new URL(withOrigin(new Request(`${BASE}//evil.example/account`), BASE).url); expect(url.origin).toBe(BASE); expect(url.pathname).toBe("//evil.example/account"); });
it("gives no 500 for a Host header that does not parse", async () => { const { app } = setup(); const page = await app.handle(new Request(`${BASE}/account`, { headers: { host: "a b" } })); expect(page.status).toBe(307); const core = await app.handle( new Request(`${BASE}/auth/session`, { headers: { host: "a b" } }), ); expect(core.status).toBe(401); });});How it behaves
Section titled “How it behaves”- The rule gets the
pathof the context: the raw path as Elysia’s router matched it. - Elysia does not decode the path, and compares with case. So
/%61ccountand/ACCOUNTmatch no route and get a 404. - Elysia runs
/accountfor/account/, becausestrictPathis off by default. So the rule also tests the path with its trailing slashes cut. - Bun resolves
.and..in the path before the router runs, so/account/.gets the redirect. Elysia removes one trailing slash only, so/account//gets a 404. - An exact rule covers one route only. For a route with a parameter, use
p === "/account" || p.startsWith("/account/"). - The router does not decode
/%61uth/sessionto a path of core, so no page and no route of core runs. It gets a 404. withOriginbuilds the URL of each request from the Host header, so the origin never comes from a request line in absolute form.- A Host that does not parse gets the origin of
BASE_URL, so the app answers no 500. On Bun, such a request has a path only as its URL. - A route of core returns the answer of core, so each Set-Cookie line passes unchanged.
- The hooks name no body, so Elysia reads no body. Core reads the body as it came.
- The verifier reads the Authorization header only, never the session cookie. An API token costs one call to the auth app per request.
- The tests run the app on Node through
app.handle, and on Bun 1.4.3 with raw request lines.
If it fails
Section titled “If it fails”origin_not_trusted: the page posts from an origin that is notBASE_URL.unauthorized: no session, or no valid bearer at/files.