Skip to content

Use authtempo with NestJS

For: a developer of a NestJS 12 app on the Express adapter.

What it does: the app serves the routes of authtempo under /auth through the Express package, @authtempo/express. A person with no session goes to the sign-in page, and a guard verifies the caller of a route with the verify package.

  1. Add the packages: pnpm --filter my-app add @authtempo/core @authtempo/express @authtempo/verify.
  2. Mount core after NestFactory.create: app.use("/auth", authHandler(getAuth)).
  3. Protect paths: app.use(authSession({ auth: getAuth, protect, signInPath: "/sign-in" })).
  4. Read the session in a route with getSession(res), and take res with @Res({ passthrough: true }).
  5. Make a guard that calls verifier.verifyRequest(toWebRequest(req)).
  6. Throw UnauthorizedException for a null value, and ServiceUnavailableException for a failure.
  7. Put the guard on a route with @UseGuards(new CallerGuard(getVerifier)).
src/app.ts
import "reflect-metadata";
import { type Auth, createAuth, createMemoryAdapter, type MailPort } from "@authtempo/core";
import { authHandler, authSession, getSession, toWebRequest } from "@authtempo/express";
import { createVerifier, type Verifier } from "@authtempo/verify";
import {
type CanActivate,
Controller,
type ExecutionContext,
Get,
type INestApplication,
Module,
Req,
Res,
ServiceUnavailableException,
UnauthorizedException,
UseGuards,
} from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { ExpressAdapter } from "@nestjs/platform-express";
import express, { type Request as ExpressRequest, type Response as ExpressResponse } from "express";
export interface AppEnv {
/** The public origin of the app, read at the first request. */
baseURL: () => 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;
/** True for a path that needs a session. Default: the exact path "/account". */
protect?: ((path: string) => boolean) | undefined;
}
// A user can have no address (authtempo plan 12i), so the caller's email can be null.
type WithCaller = ExpressRequest & { caller?: { email: string | null } };
/** A guard that knows the caller from a ts_ bearer or an API token in the Authorization header. */
class CallerGuard implements CanActivate {
constructor(private readonly verifier: () => Verifier) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest<WithCaller>();
const r = await this.verifier().verifyRequest(toWebRequest(req));
// The auth app did not answer: 503, not "sign in again".
if (!r.ok) throw new ServiceUnavailableException(r.code);
if (r.value === null) throw new UnauthorizedException();
if (r.value.kind === "session-token" || r.value.kind === "api-token")
req.caller = { email: r.value.user.email };
return true;
}
}
/**
* The Nest app, before `listen`. Warning: the memory adapter keeps rows in
* this process only. Use the Postgres adapter in production.
*/
export async function createApp(env: AppEnv): Promise<INestApplication> {
let auth: Auth | null = null;
const getAuth = (): Auth => {
auth ??= createAuth({
baseURL: env.baseURL(),
secret: env.AUTH_SECRET,
trustedOrigins: [env.baseURL()],
storage: createMemoryAdapter(),
mail: env.mail,
});
return auth;
};
let verifier: Verifier | null = null;
const getVerifier = (): Verifier => {
verifier ??= createVerifier({
issuer: `${env.baseURL()}/auth`,
accept: ["session-token", "api-token"],
// The auth app is this process; another server passes no fetch.
fetch: (input, init) => getAuth().handle(new Request(input, init)),
});
return verifier;
};
@Controller()
class AccountController {
// The page of a signed-in person. The middleware of the Express package sent anyone else to /sign-in.
@Get("account")
account(@Req() req: ExpressRequest, @Res({ passthrough: true }) res: ExpressResponse) {
env.trace?.("page", req.path);
return { email: getSession(res)?.user.email ?? null };
}
// A route for scripts: the guard reads the Authorization header, never the cookie.
@Get("files")
@UseGuards(new CallerGuard(getVerifier))
files(@Req() req: WithCaller) {
env.trace?.("page", req.path);
return { owner: req.caller?.email ?? null };
}
}
@Module({ controllers: [AccountController] })
class AppModule {}
// Express routes without case by default: "/myaccount" would run the page of
// "/myAccount", which a rule with a capital letter misses. So the router
// compares case too. Set it on an Express app of our own, before Nest gets it:
// Express reads it when it makes the router, and the constructor of
// ExpressAdapter already calls use(), so a set after NestFactory.create does nothing.
const server = express();
server.set("case sensitive routing", true);
const app = await NestFactory.create(AppModule, new ExpressAdapter(server), { logger: false });
// Every route of core under /auth, through the Express binding.
app.use("/auth", authHandler(getAuth));
// The session of every page, and /account for a signed-in person only. Express
// matches without case and with an optional trailing slash, and the
// middleware tests those forms too. An exact rule covers one route only.
app.use(
authSession({
auth: getAuth,
protect: (p) => {
env.trace?.("rule", p);
return env.protect ? env.protect(p) : p === "/account";
},
signInPath: "/sign-in",
}),
);
return app;
}
The sign-in and the rules as a test
import { request as httpRequest } from "node:http";
import type { AddressInfo } from "node:net";
import { createClient } from "@authtempo/client";
import type { MailMessage } from "@authtempo/core";
import type { INestApplication } from "@nestjs/common";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createApp } from "../src/app.js";
const sent: MailMessage[] = [];
let rule: string[] = [];
let pages: string[] = [];
let base = "";
let app: INestApplication;
/** One request with a raw path and a raw Host header, as a browser or a script sends it. */
function send(path: string, headers: Record<string, string> = {}) {
const { port } = new URL(base);
return new Promise<{ status: number; location: string | undefined }>((resolve, reject) => {
const req = httpRequest({ host: "127.0.0.1", port, path, headers }, (res) => {
res.resume();
res.on("end", () => resolve({ status: res.statusCode ?? 0, location: res.headers.location }));
});
req.on("error", reject);
req.end();
});
}
describe("the NestJS example (plan 11d2)", () => {
beforeAll(async () => {
app = await createApp({
baseURL: () => base,
AUTH_SECRET: "0123456789abcdef0123456789abcdef",
mail: {
async send(m) {
sent.push(m);
},
},
trace: (event, text) => (event === "rule" ? rule : pages).push(text),
});
await app.listen(0, "127.0.0.1");
base = `http://127.0.0.1:${(app.getHttpServer().address() as AddressInfo).port}`;
});
afterAll(async () => {
await app.close();
});
it("mounts core with the Express binding, and a guard verifies the caller of /files", async () => {
let cookie = "";
let lines: string[] = [];
const jarFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const headers = new Headers(init?.headers);
headers.set("origin", base);
if (cookie) headers.set("cookie", cookie);
const res = await fetch(input, { ...init, 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: jarFetch, credentials: "omit" });
expect((await fetch(`${base}/files`)).status).toBe(401);
// A POST to core: core runs before Nest's body parsers and reads the raw body.
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 fetch(`${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 fetch(`${base}/files`, { headers: { cookie } })).status).toBe(401);
const bearer = `Bearer ${cookie.slice(cookie.indexOf("=") + 1)}`;
const files = await fetch(`${base}/files`, { headers: { authorization: bearer } });
expect(await files.json()).toEqual({ owner: "ada@example.com" });
});
it("sends a person with no session on /account to the sign-in page, and runs no page", async () => {
pages = [];
const res = await send("/account?tab=keys");
expect(res.status).toBe(307);
expect(res.location).toBe(`${base}/sign-in?next=%2Faccount%3Ftab%3Dkeys`);
expect(pages).toEqual([]);
});
// Express matches the raw path: "/%61ccount" matches no route (404). It matches
// without case and with a trailing slash, and the middleware tests those forms (307).
it.each([
["/%61ccount", 404],
["/ACCOUNT", 307],
["/account/", 307],
// The middleware removes every trailing slash, so it fails closed for "/account//".
["/account//", 307],
// Node and Express do not resolve dot segments: no route matches.
["/account/.", 404],
["/account/..", 404],
])(
"answers %s with no cookie under an exact rule with %i, and runs no page",
async (path, status) => {
pages = [];
const res = await send(path);
expect(res.status).toBe(status);
expect(pages).toEqual([]);
},
);
it("answers /%61uth/session with 404, and the rule gets only the text the router matched", async () => {
pages = [];
rule = [];
const res = await send("/%61uth/session");
expect([307, 401, 404]).toContain(res.status);
expect(res.status).toBe(404);
expect(pages).toEqual([]);
expect(rule.length).toBeGreaterThan(0);
// The raw path and its case forms: never the decoded "/auth/session".
expect(new Set(rule)).toEqual(new Set(["/%61uth/session"]));
});
it("gives no 500 for a Host header that does not parse: the origin of baseURL", async () => {
const page = await send("/account", { host: "a b" });
expect(page.status).toBe(307);
expect(page.location).toBe(`${base}/sign-in?next=%2Faccount`);
expect((await send("/auth/session", { host: "a b" })).status).toBe(401);
expect((await send("/files", { host: "a b" })).status).toBe(401);
});
it("takes the origin of the redirect from Host, not from an absolute-form request line", async () => {
const res = await send("http://evil.example/account");
expect(res.status).toBe(307);
expect(res.location).toBe(`${base}/sign-in?next=%2Faccount`);
});
});
describe("the NestJS example with a rule that has a capital letter (plan 11d2)", () => {
it("runs no page of /myAccount for /myaccount or /MYACCOUNT: the router compares case", async () => {
const runs: string[] = [];
const caseApp = await createApp({
baseURL: () => base,
AUTH_SECRET: "0123456789abcdef0123456789abcdef",
mail: { async send() {} },
protect: (p) => p.startsWith("/myAccount"),
});
// A route of the app at /myAccount, on the same Express instance.
caseApp
.getHttpAdapter()
.get("/myAccount", (req: { path: string }, res: { json: (v: unknown) => void }) => {
runs.push(req.path);
res.json({ page: "myAccount" });
});
await caseApp.listen(0, "127.0.0.1");
const port = (caseApp.getHttpServer().address() as AddressInfo).port;
try {
for (const path of ["/myaccount", "/MYACCOUNT"]) {
const res = await fetch(`http://127.0.0.1:${port}${path}`, { redirect: "manual" });
expect(res.status, path).toBe(404);
}
expect(runs).toEqual([]);
// The route itself is protected: no session gives the redirect.
const own = await fetch(`http://127.0.0.1:${port}/myAccount`, { redirect: "manual" });
expect(own.status).toBe(307);
expect(runs).toEqual([]);
} finally {
await caseApp.close();
}
});
});
  • Nest 12 runs on Express 5, so the middleware of the Express package is the gate.
  • The rule gets the raw path as Express matched it. Express does not decode it, so /%61ccount matches no route and gets a 404.
  • Express matches without case by default, and with an optional trailing slash. The middleware tests those forms too, so /ACCOUNT and /account/ get the redirect.
  • The app sets case sensitive routing on its own Express app, and passes it to Nest with new ExpressAdapter(server). Then /myaccount does not run the page of /myAccount.
  • 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/session to a path of core. The rule gets /%61uth/session, no page matches, and the answer is a 404.
  • The origin of the redirect comes from the Host header, never from a request line in absolute form.
  • A Host that does not parse gets the origin of baseURL, so the app answers no 500.
  • Each Set-Cookie line of core passes unchanged.
  • The app mounts core before Nest registers its body parsers at listen, so core reads the raw body. If core runs after a parser, the Express package writes the parsed body again.
  • The guard is an instance, so Nest needs no emitDecoratorMetadata for it.
  • Nest needs the legacy decorators: experimentalDecorators in the tsconfig, and oxc.decorator.legacy in the vitest config.
  • The verifier reads the Authorization header only, never the session cookie.