Protect a route

You need: auth composed. That is the whole prerequisite.

One import, one middleware

Routing and verification is what the middleware resolves, entitlements is the gate that stacks after it, and adding a route is where a handler comes from.

import { requireAuth } from "@pithy-sh/auth";

app.get("/notes", requireAuth(), async (c) => {
  const rows = await c.var.db.app
    .selectFrom("notes")
    .where("authorId", "=", c.var.auth.userId)
    .selectAll()
    .execute();
  return c.json({ notes: rows });
});

c.var.auth carries the resolved identity — the user id, and the session and device ids. It is null until a verification strategy sets it, and requireAuth() is what turns that null into a 401 before your handler runs.

So inside the handler it is not null, and you are not writing a check. The type says so too: a handler chained after requireAuth() on the same route reads c.var.auth as a filled AuthContext, so c.var.auth.userId compiles with no ?. and no !.

The narrowing reaches only the handlers chained after the guard on that route. A separate app.use("/notes", requireAuth()) refuses the same requests and narrows nothing, because a type does not carry from one statement to the next. A function that takes the handler’s context types it Context<PithyHonoEnv & SignedInEnv>, with SignedInEnv from @pithy-sh/auth. A route that has to hand c to a function taking plain Context<PithyHonoEnv> stacks requireAuthUnnarrowed() from @pithy-sh/auth/src/http/middleware instead: the same check, with no narrowing.

Every other capability gates the same way

None of them validates a token. They all read the same identity seam, which is why adding payments or storage later needs no auth wiring from you: the seam is already filled.

That is also what makes the absence coherent. With auth not composed, the seam is null and those routes deny — a defined behavior rather than a crash.

Gating on an entitlement

app.get("/reports", requireAuth(), requireEntitlement("pro"), handler);

Identity first, then entitlement. You cannot ask what somebody is entitled to before you know who they are.

requireEntitlement lives in core rather than in the payments package, on purpose: a route should be able to say what it requires without importing the capability that provides it. With no provider composed, the seam denies — a gate with no provider fails closed rather than standing open.

That creates one failure worth knowing about. A Worker gating on entitlements while composing no provider is not broken, it is silently paywalled shut, and the runtime cannot tell that mistake from a legitimately unentitled user. So the CLI answers it instead: pithy doctor and pithy dev compare the gates in your source against what the Worker composes, and say so at startup rather than leaving you a fleet of production 403s.

Name the entitlement key, never a product. pro, not pro_monthly — that is the distinction the whole payments model rests on.

The full stack, in order

app.post(
  "/reports",
  describeRoute({
    summary: "File a report.",
    verification: ["bearer", "session"],
    responses: { 201: Report },
  }),
  requireAuth(),
  requireEntitlement("pro"),
  validate("json", CreateReport),
  handler,
);

Description, identity, entitlement, request contract, handler. The order is not cosmetic. describeRoute comes first because it carries what the OpenAPI document reads, and does nothing when it runs unless it declares a power or a rateLimit. Each of those installs a gate there, ahead of the guards below it.

A validator ahead of a gate turns a 401 into a 400 — and tells an unauthenticated caller which requests were well-formed. On an admin surface that is an oracle rather than a courtesy.

Never parse input inside a handler. A handler takes typed values, so the route signature carries the whole contract and a reader can see what a route accepts without reading its body. validate applies the one failure hook, so a bad request renders as validation/invalid_input through the same error path as everything else — one failure format, whatever failed — and it leaves the schema where the OpenAPI document can read it.

Stacking a humanity check

Turnstile is not a verification strategy. A strategy answers who is this; a humanity check answers is this a human. Different questions, so it stacks on top rather than replacing anything:

app.use("/signup", turnstile());

A public signup route that still requires a token is a coherent thing, and it is only expressible because the two are kept apart.

Where you accept a cookie session, a state-changing route wants the same-origin gate beside the auth one:

app.post("/organizations", describeRoute({ … }), requireAuth(), requireSameOrigin(), validate("json", …), handler);

The gate arrives already bound to your Worker’s trusted origins by whichever capability resolved them — you get the decision rather than the material to rebuild it, because handing over the list is how a Worker ends up with two same-origin implementations free to disagree, and the weaker one is then its real policy.

A recent sign-in, for a route that can do lasting harm

Revealing a stored secret, changing who can see something, exporting a person’s data: a route like that should not open on a session that has been signed in all week. requireRecentSignIn gates it on a sign-in within the window the route names:

import { requireRecentSignIn } from "@pithy-sh/auth/src/http/recentSignIn";

app.post("/things/:id/secret", describeRoute({ … }), requireRecentSignIn({ maxAgeSeconds: 300, purpose: "things/secret_revealed" }), validate("param", ThingParams), handler);

A caller with no credential gets what requireAuth() answers, a 401. One who signed in too long ago gets 403 auth/recent_sign_in_required, and the refusal is audited with your purpose. A rotated session keeps its original sign-in time, so only a fresh sign-in passes. Require a recent sign-in has the window, the refusal, and how a web and a phone client answer it.

A rate limit, for a route a caller could hammer

A route says how often each caller may reach it on its own describeRoute, and declaring it installs the gate, after any power gate:

app.post(
  "/ingest",
  describeRoute({
    summary: "Record an event.",
    verification: ["bearer", "session"],
    responses: { 204: { description: "Recorded." } },
    rateLimit: { key: "user", limit: 20, period: 60 },
  }),
  requireAuth(),
  validate("json", Event),
  handler,
);

key: "user" counts each signed-in user, and key: "ip" counts each client address. period is 10 or 60 seconds, the only two Workers Rate Limiting accepts. Past the limit the route answers rate_limit/exceeded (429). A user limit belongs on a route only signed-in callers reach: one whose verification admits anyone but a bearer or session caller is refused when the Worker composes, naming the route, and a public route takes key: "ip". A caller with no credential on a user limit is counted against nothing and left to requireAuth(), which answers it. pithy worker sync writes the binding that enforces each limit, and a Worker missing one fails its first request naming it rather than serving the route unlimited.

Declaring a route public

A route with no strategy is not the same as a route with public. public is a positive declaration that this route is open on purpose, and it reads as one in review.

Nobody wrote a gate here and we decided this needs no gate look identical in code and are completely different facts.

describeRoute({ verification: "public", … }) is where that declaration is written, and it lands in the OpenAPI document as the operation’s x-pithy-verification, so a client author reads the same decision a reviewer does.

What a caller sees

401 — the credential is missing, expired or revoked. Sign in again. A mobile client rotates before its session expires, so a 401 means the session is gone.

403 — the caller is who they say and may not do this. Do not retry. The exception is a refusal for want of a recent sign-in, auth/recent_sign_in_required on a route you gated or auth/session_not_fresh on connecting a sign-in provider: sign in again, then retry once.

429 — rate_limit/exceeded: the caller passed the route’s limit. Back off and retry in a moment; the request itself was fine.

A client that treats those the same loops: it signs in or rotates a perfectly good session, gets another 403, and goes round again.

Test it signed in

A route behind requireAuth() is tested with a real session, not a stub. signInTestUser from @pithy-sh/auth/src/test-utils/signIn signs a user in inside the Workers test pool and hands back the headers to send:

import { env } from "cloudflare:test";
import { signInTestUser } from "@pithy-sh/auth/src/test-utils/signIn";

test("a signed-in caller lists their notes", async () => {
  const ada = await signInTestUser(env.DB, { email: "ada@example.com", secret: SESSION_SECRET });
  const res = await app.request("/notes", { headers: ada.headers }, env);
  expect(res.status).toBe(200);
});

Test your backend has what it takes and what it hands back.

Check it worked

  • The route answers for a signed-in caller, and a Workers test signed in with signInTestUser gets the same answer
  • It 401s with no credential, and with an expired one
  • With an entitlement gate: it 403s for somebody without the key, and pithy doctor reports no gap
  • With a validator: a malformed body gets a 400 carrying the failing field
ESC