Skip to content

Verify a caller on another server

For: a developer of a second server, such as a files service, that must know who calls it.

What it does: the second server checks the credential of each request with @authtempo/verify. A session JWT verifies with no call to the auth app.

  1. Add the package to the second server: pnpm --filter my-app add @authtempo/verify.
  2. Make one verifier with the issuer and the audience of the second server.
  3. Add api-token to accept when scripts call the server with an API token.
  4. Set checkSessionEnd: true when a sign-out must end access at once.
  5. In each request, call verifier.verifyRequest(request).
    • A rate_limited failure means that the live check is over its limit. Answer 429.
    • Any other failure means that the auth app did not answer. Answer 503.
    • A null value means no valid credential. Answer verifier.unauthorized({ invalidToken }).
    • Set invalidToken to true when the request holds a bearer. The 401 then names invalid_token.
The second server
import { readBearer } from "@authtempo/core/credentials";
import { createVerifier, type VerifierOptions } from "@authtempo/verify";
/**
* A files server that is not the auth app. It knows the person of each
* request from the session JWT of the app, or from an API token of a script.
*/
export function createFilesServer(fetch?: VerifierOptions["fetch"]) {
const verifier = createVerifier({
// baseURL plus basePath of the auth app: the iss of its tokens.
issuer: "https://api.example.com/auth",
// The jwtMint.audience entry of this server.
audience: "https://files.example.com",
accept: ["session-jwt", "api-token"],
// A sign-out ends access at once: one live check per request.
checkSessionEnd: true,
// Tests pass the auth app in process. A deploy passes nothing.
...(fetch ? { fetch } : {}),
});
return {
async fetch(request: Request): Promise<Response> {
const r = await verifier.verifyRequest(request);
if (!r.ok) {
// The live check of this session is over its limit: try again in a minute.
// Any other failure: the auth app did not answer. Not "sign in again".
const status = r.code === "rate_limited" ? 429 : 503;
return Response.json({ error: r.code }, { status });
}
// The verifier reads the bearer only, never a cookie: a refused credential is the bearer.
// invalidToken tells the client so. A Basic header is no bearer.
if (r.value === null)
return verifier.unauthorized({ invalidToken: readBearer(request) !== null });
const owner =
r.value.kind === "session-jwt"
? r.value.email
: r.value.kind === "api-token"
? r.value.user.email
: null;
return Response.json({ owner });
},
};
}
The second server as a test
import { createAuth } from "@authtempo/core";
import { DEFAULT_COOKIE_NAME } from "@authtempo/core/credentials";
import { describe, expect, it } from "vitest";
import { API, call, harness, signIn } from "../support/harness.ts";
import { createFilesServer } from "./verify-caller.ts";
type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
function setup(wrap: (inner: Fetch) => Fetch = (inner) => inner) {
const h = harness();
const auth = createAuth({
baseURL: API,
trustedOrigins: [],
secret: h.secret,
storage: h.storage,
mail: h.mail,
jwtMint: { audience: "https://files.example.com" },
});
// The files server reads the key set and the live check of the API in process.
const files = createFilesServer(wrap((input, init) => auth.handle(new Request(input, init))));
const at = (bearer?: string) =>
files.fetch(
new Request("https://files.example.com/doc", {
headers: bearer ? { authorization: `Bearer ${bearer}` } : {},
}),
);
return { h, auth, at };
}
async function sessionJwt(auth: ReturnType<typeof setup>["auth"], cookie: string): Promise<string> {
const res = await call(auth, "GET", "/auth/token", undefined, { cookie });
return ((await res.json()) as { token: string }).token;
}
describe("verify a caller on another server", () => {
it("knows the person of a session JWT and of an API token, and refuses no credential", async () => {
const { h, auth, at } = setup();
const cookie = await signIn(auth, h, "ada@example.com");
expect(await (await at(await sessionJwt(auth, cookie))).json()).toEqual({
owner: "ada@example.com",
});
const created = (await (
await call(auth, "POST", "/auth/tokens", { name: "ci" }, { cookie })
).json()) as { token: string };
expect(await (await at(created.token)).json()).toEqual({ owner: "ada@example.com" });
const none = await at();
expect(none.status).toBe(401);
});
it("refuses a session JWT after the sign-out", async () => {
const { h, auth, at } = setup();
const cookie = await signIn(auth, h, "ada@example.com");
const jwt = await sessionJwt(auth, cookie);
await call(auth, "POST", "/auth/sign-out", {}, { cookie });
const refused = await at(jwt);
expect(refused.status).toBe(401);
expect(refused.headers.get("www-authenticate")).toContain('error="invalid_token"');
});
it("names invalid_token only for a refused bearer", async () => {
const files = createFilesServer();
const challenge = async (headers: Record<string, string>) =>
(await files.fetch(new Request("https://files.example.com/doc", { headers }))).headers.get(
"www-authenticate",
);
// A ts_ bearer is a kind that this server does not accept: refused with no call.
expect(await challenge({ authorization: "Bearer ts_refused" })).toBe(
'Bearer error="invalid_token"',
);
// The verifier reads no cookie, so a cookie beside the bearer does not change the answer.
expect(
await challenge({
authorization: "Bearer ts_refused",
cookie: `${DEFAULT_COOKIE_NAME}=ts_x`,
}),
).toBe('Bearer error="invalid_token"');
// Basic is no bearer, so the 401 names no invalid token.
expect(await challenge({ authorization: "Basic YTpi" })).toBe("Bearer");
});
it("answers 429 when the live check is over its limit, and 503 when the auth app does not answer", async () => {
let live: "limited" | "down" = "limited";
const { h, auth, at } = setup((inner) => async (input, init) => {
if (!String(input instanceof Request ? input.url : input).endsWith("/token/live"))
return inner(input, init);
if (live === "down") throw new TypeError("fetch failed");
return Response.json({ error: "rate_limited" }, { status: 429 });
});
const jwt = await sessionJwt(auth, await signIn(auth, h, "ada@example.com"));
expect((await at(jwt)).status).toBe(429);
live = "down";
expect((await at(jwt)).status).toBe(503);
});
});
  • The verifier reads the bearer header only, never the session cookie.
  • The key set lives for the max-age of its answer, 300 seconds from core. An unknown key reads it again at most once per 30 seconds.
  • An API token costs one call to the auth app per request, unless cache.apiTokenSeconds keeps the answer.
  • The live check counts on token-live:session:<sessionId>, 120 per minute (Limits).
  • A null value for a good token: the audience of the verifier is not a jwtMint.audience entry. Or the clock of the server is wrong.
  • rate_limited: the live check of one session passed 120 per minute.
  • unauthorized: the live route refused the bearer. The verifier answers null for it.