Skip to content

Mount authtempo on any other stack

For: a developer on a stack that this site gives no page of its own.

What it does: this page names the part of authtempo that fits each kind of stack. Core speaks the web request and response, so most stacks need one line.

  1. A runtime that speaks the web request: Bun, Deno, Cloudflare Workers, or a framework that gives you a Request. Call auth.handle(request) for each path under /auth, as the sample below does.
  2. A Node server on http: use the Express package or the Fastify package. Their toWebRequest and sendWebResponse show the conversion for another Node framework.
  3. A front end with no package: Angular, Qwik, Lit, or plain JavaScript. Use the client package, and subscribe to client.store for the session.
  4. A server that must know the caller: use the verify package in any runtime.
  5. A native or desktop app: use the handoff package.
  6. A protected page: call readGate of @authtempo/core/bindings with the path that your router matched.
One fetch handler
import type { Auth } from "@authtempo/core";
/**
* The request with a full URL. Bun builds `request.url` from the Host header,
* and a Host that does not parse ("a b") gives the path only. The origin of
* `auth.baseURL` then replaces it, so a bad Host gets no 500.
*/
function withOrigin(request: Request, baseURL: string): Request {
if (URL.canParse(request.url)) return request;
// Join as text: a path that starts with "//" is a path here, not a host.
const url = new URL(`${new URL(baseURL).origin}${request.url}`);
const init = { method: request.method, headers: request.headers, body: request.body };
return new Request(url, { ...init, duplex: "half" } as RequestInit);
}
/**
* One fetch handler for any runtime that speaks the web Request and Response:
* `Bun.serve({ fetch })`, `Deno.serve(fetch)`, or `export default { fetch }` on Workers.
* It matches the raw path of `request.url`, the path that core's router reads:
* no decode, with case, and no trailing slash cut. An exact match covers one path only.
*/
export function createFetchHandler(auth: Auth): (request: Request) => Promise<Response> {
return async (incoming) => {
const request = withOrigin(incoming, auth.baseURL);
const url = new URL(request.url);
// RFC 8414 and RFC 9728 put the metadata at the origin root.
if (url.pathname.startsWith("/.well-known/")) return auth.wellKnown(request);
if (url.pathname.startsWith("/auth/")) return auth.handle(request);
if (url.pathname === "/me") {
const session = await auth.session(request);
if (!session) return Response.json({ error: "unauthorized" }, { status: 401 });
const res = Response.json({ email: session.user.email });
// After a sliding refresh, renew the cookie, or the browser drops it early.
const renewed = auth.sessionCookie(request, session);
if (renewed) res.headers.set("set-cookie", renewed);
return res;
}
return new Response("not found", { status: 404 });
};
}
The handler as a test
import { createAuth } from "@authtempo/core";
import { describe, expect, it } from "vitest";
import { API, harness, signIn } from "../support/harness.ts";
import { createFetchHandler } from "./other-stacks.ts";
// Bun builds request.url from the Host header. A Host that does not parse ("a b")
// gives the path only, as this request does.
class PathOnlyRequest extends Request {
override get url() {
return new URL(super.url).pathname;
}
}
describe("mount authtempo on any other stack", () => {
it("serves core, the well-known documents, and an app route from one fetch handler", async () => {
const h = harness();
const auth = createAuth({
baseURL: API,
trustedOrigins: [],
secret: h.secret,
storage: h.storage,
mail: h.mail,
});
const fetch = createFetchHandler(auth);
expect((await fetch(new Request(`${API}/auth/session`))).status).toBe(401);
expect((await fetch(new Request(`${API}/me`))).status).toBe(401);
const cookie = await signIn(auth, h, "ada@example.com");
const me = await fetch(new Request(`${API}/me`, { headers: { cookie } }));
expect(await me.json()).toEqual({ email: "ada@example.com" });
expect((await fetch(new Request(`${API}/other`))).status).toBe(404);
});
it("matches the raw path: an escape, another case, or a trailing slash reaches no page", async () => {
const h = harness();
const auth = createAuth({
baseURL: API,
trustedOrigins: [],
secret: h.secret,
storage: h.storage,
mail: h.mail,
});
const fetch = createFetchHandler(auth);
const cookie = await signIn(auth, h, "ada@example.com");
for (const path of ["/%6De", "/ME", "/me/", "/%61uth/session"]) {
const res = await fetch(new Request(`${API}${path}`, { headers: { cookie } }));
expect(res.status, path).toBe(404);
}
});
it("answers no 500 for a request whose URL is a path only: the origin of baseURL", async () => {
const h = harness();
const auth = createAuth({
baseURL: API,
trustedOrigins: [],
secret: h.secret,
storage: h.storage,
mail: h.mail,
});
const fetch = createFetchHandler(auth);
expect((await fetch(new PathOnlyRequest(`${API}/me`))).status).toBe(401);
expect((await fetch(new PathOnlyRequest(`${API}/auth/session`))).status).toBe(401);
// A path that starts with "//" stays a path on the origin of baseURL: no route of core.
const twoSlashes = new PathOnlyRequest(`${API}//evil.example/auth/session`, {
headers: { host: "a b" },
});
expect((await fetch(twoSlashes)).status).toBe(404);
});
});
  • auth.handle answers every route of core, with its cookies and its CORS headers. Return its answer unchanged, so each Set-Cookie line reaches the browser.
  • The sample matches the raw path of request.url, the path that core’s router reads. It does not decode, keeps the case, and cuts no trailing slash.
  • So /%6De, /ME, and /me/ reach no page, and /%61uth/session reaches no route of core. Each gets a 404.
  • A router that decodes the path, folds the case, or cuts a trailing slash runs a page for more than one text. Test the rule on each of those forms.
  • A path that your router decodes to a path of core must never run a page.
  • An exact rule covers one route only. For a route with a parameter, use a prefix rule.
  • Take the origin of a redirect from the Host header. When the Host does not parse, use new URL(auth.baseURL).origin, as withOrigin of the sample does.
  • Never take the origin from a request line in absolute form. Bun 1.4 builds request.url from the Host header.
  • A page that reads the session sends the renewed cookie that auth.sessionCookie answers.