Sessions and security
This page covers what the core gives you: sessions and cookies, sealed values, tokens, CSRF, CORS, limits and the browser's security headers and Content Security Policy. Signing users in, with passwords, OAuth, passkeys or emailed links, is Auth; what a handler may return is Data security.
Sessions
useSession(event, options) returns { id, data, update(patch), regenerate(), clear() }. The session is stored in a cookie, sealed with AES-GCM, so the server keeps nothing and a tampered or expired cookie reads as an empty session.
import { createError, defineHandler, useSession } from "hamur/server";
const password = process.env.SESSION_PASSWORD as string;
const nameInput = {
"~standard": {
version: 1 as const,
vendor: "docs",
validate: (value: unknown) => {
const name = (value as { name?: unknown } | undefined)?.name;
return typeof name === "string" && name ? { value: { name } } : { issues: [{ message: "name is required", path: ["name"] }] };
},
},
};
export const login = defineHandler({
route: "/api/login",
method: "POST",
input: nameInput,
async handler({ name }: { name: string }, { event }) {
if (name.length > 64) throw createError({ status: 400, message: "name is too long" });
const session = await useSession(event, { password, maxAge: 60 * 60 * 24 * 7 });
await session.regenerate();
await session.update({ user: name });
return { id: session.id };
},
});
| Option | Meaning |
|---|---|
password | at least 32 characters, or useSession throws; optional: without it the session is sealed with the app key HAMUR_KEY (see below). A list of up to 8 rotates the password: the first seals, every entry opens |
name | the cookie name; by default __Host-hamur-session, which a sibling subdomain cannot plant, or hamur-session when cookie sets a domain, a path other than / or secure: false |
maxAge | seconds from the session's creation until it reads as empty; also the cookie's Max-Age. Without it the cookie lasts for the browser session |
cookie | domain, path, httpOnly, secure, sameSite, partitioned; the defaults are path=/, HttpOnly, Secure and SameSite=Lax. A Secure cookie is not stored by a browser on http:// except on localhost, so a dev host on plain http needs cookie: { secure: false } |
storage | a storage mount that keeps the data; the cookie then holds only a sealed id (Storage sessions) |
idleTimeout | seconds without a request after which the session reads as empty (Idle timeout) |
header | a request header name: the sealed value travels in that header and no cookie is used (Header sessions) |
import { createError, defineHandler, useSession } from "hamur/server";
const password = process.env.SESSION_PASSWORD as string;
export const me = defineHandler({
route: "/api/me",
method: "GET",
async handler(_, { event }) {
const session = await useSession<{ user?: string }>(event, { password });
if (!session.data.user) throw createError({ status: 401, message: "Not signed in" });
return { user: session.data.user };
},
});
Nothing is written until the first update. update(patch) merges the patch into data and sets the cookie. Calls to update and clear run one after another, in call order. clear() gives the session a new id, empties it and deletes the cookie.
import { defineHandler, useSession } from "hamur/server";
const password = process.env.SESSION_PASSWORD as string;
export const logout = defineHandler({
route: "/api/logout",
method: "POST",
async handler(_, { event }) {
const session = await useSession(event, { password });
await session.clear();
return null;
},
});
A cookie is at most 4096 bytes: update and regenerate throw an error that names the cookie when the sealed session would be larger. Keep the data small and store an id of a record, not the record, or keep the data in a store (Storage sessions). Expiry counts from creation, not from the last update; idleTimeout adds a limit from the last use. Call regenerate() on every login and every change of privilege, and start from clean data with regenerate({ data: {} }). A user-and-password login, OAuth, passkeys and magic links are in Auth, which keeps the signed-in user for you.
The app key
password is optional. Without it useSession seals the cookie with the app key, HAMUR_KEY, the one secret that Hamur uses wherever an API is given none: sessions, seal, csrf, signed cookies, and everything in @hamur/auth. Each use derives a key of its own from it, so a value made for one use never opens as another. hamur create-key --env writes a new key to .env; in production set HAMUR_KEY in the environment of every instance. It is one key, 32 bytes in base64 or base64url, or a comma-separated list of at most 8: HAMUR_KEY=<new>,<old> seals with the first and opens with every entry, which is how a key is rotated without signing anyone out. A built server with a malformed key does not start. With no key, hamur dev makes one for the process and warns once, so sealed values do not survive a restart, and a built server throws HAMUR_KEY is not set; run hamur create-key --env, or set it in the deployment at the first call that needs it. The key is never in a bundle, in the runtime config or in a payload.
Rotating the password
To replace a password without signing anyone out, put the new one first and keep the old one: password: [env.SESSION_PASSWORD_NEW, env.SESSION_PASSWORD_OLD]. New cookies are sealed with the first entry; a cookie sealed with any listed entry still opens. session.rotated is true when the request's cookie opened with an entry other than the first, and the cookie is sealed again with the first entry on the next update (await session.update({}) does it at once). Once the old cookies have expired (maxAge), drop the old entry; a cookie sealed with a password that is no longer listed reads as an empty session. A list holds 1 to 8 passwords of at least 32 characters each, else useSession throws a TypeError, and a second useSession for the same cookie name in one request must pass the same list in the same order.
Storage sessions
With storage the cookie holds only the sealed id and the data lives in a storage mount under <name>:<id>, so a session can be larger than a cookie and can be revoked: remove its key from the mount and that session is logged out. maxAge or idleTimeout is then required, and sets the ttl of the stored key. The mount named session defaults to fs at .data/sessions on bun, node and under hamur dev, to cloudflare-kv (binding SESSION) on cloudflare when the wrangler config declares it, and to nothing on vercel and netlify, where you set storage.session yourself. Mount redis, db or sqlite where revocation must be immediate everywhere: on Cloudflare KV, a request at another location can still read a session for about a minute after its logout, and a key takes one write per second.
import { defineHandler, useSession, useStorage } from "hamur/server";
const options = { storage: "session", maxAge: 60 * 60 * 24 * 30, idleTimeout: 60 * 60 * 24 * 7 };
export const login = defineHandler({
route: "/api/login",
method: "POST",
async handler({ name }: { name: string }, { event }) {
const session = await useSession<{ user?: string }>(event, options);
await session.regenerate({ data: { user: name } });
return { id: session.id };
},
});
export const revoke = (sessionId: string) => useStorage("session").removeItem(`__Host-hamur-session:${sessionId}`);
The store is read once, at the first useSession of a request. A request that only reads writes nothing, and every update, regenerate and clear of a request lands in one write before the response is sent. A cookie session cannot be revoked: its seal is valid until it expires.
Idle timeout
idleTimeout (seconds) ends a session that has not been used for that long, however far maxAge is. A read after more than half of it has passed seals the session again, so a client that keeps using the seal it is given refreshes at most once per half interval. With a cookie session the refresh sets the cookie again with the data the request loaded; with a storage session it only issues a new seal and writes nothing. Whichever of maxAge and idleTimeout ends first wins.
Header sessions
header moves the sealed value from a cookie to a request header, for a client that has no cookies, such as a mobile app or a script. The server reads the value from that header and writes the new one to the same response header, with an empty value when the client must drop it. No cookie is read, set or deleted.
import { defineHandler, useSession } from "hamur/server";
export const token = defineHandler({
route: "/api/token",
method: "POST",
async handler({ name }: { name: string }, { event }) {
const session = await useSession<{ user?: string }>(event, { header: "x-session", maxAge: 60 * 60 });
await session.update({ user: name });
return { ok: true };
},
});
The header is a bearer token and not an ambient credential, so the origin check still judges the request as for any other and csrf() is not needed. A route that answers other origins must list the header in the CORS exposeHeaders. An answer that carries a session header is Cache-Control: private, no-store and is never stored by a cache. The name must not be one that has a meaning of its own (cookie, authorization, host, cache-control, and others), and a header seal does not open as a cookie seal.
Flash values
session.flash(key, value) keeps a value for the next request and session.consumeFlash(key) returns it once: the request that consumes it removes it, so the request after gets undefined. A message set before a redirect is on the next page. The second type parameter of useSession types the keys.
import { defineHandler, sendRedirect, useSession } from "hamur/server";
type Flash = { notice: string };
export const save = defineHandler({
route: "/settings/save",
method: "POST",
raw: true,
async handler(_, { event }) {
const session = await useSession<{}, Flash>(event);
await session.flash("notice", "Settings saved");
return sendRedirect(event, "/settings", 303);
},
});
export const notice = defineHandler({
method: "GET",
async handler(_, { event }) {
const session = await useSession<{}, Flash>(event);
return { notice: (await session.consumeFlash("notice")) ?? null };
},
});
The value is stored as the session data is, so a Date, Map, Set or BigInt comes back as it went in; one that cannot be stored (a function) throws at the flash call with its path. A flash counts toward the 4096 bytes of a cookie session, regenerate() keeps it and clear() drops it. In a cookie session two requests that carry the same cookie both receive the flash; a storage session consumes it key by key.
Protecting a page and its data
A route middleware (app/middleware) and a load run in the browser on a navigation, and a user can skip both. A route middleware does not guard data, and neither does a load: a redirect from them steers a visitor, it stops no request. The handler must check, on every call, whoever calls it. The page's own chunk is public, as it always was; what is secret is the data, and the data is behind handlers.
Put the check in a middleware and list it where the data is read. One defineMiddleware object does both jobs:
import { defineMiddleware, redirect } from "hamur/app";
import { getSession } from "../utils/auth.ts";
export const requireLogin = defineMiddleware<{}, { user: string }>(async ({ event, next }) => {
const session = await getSession(event);
if (!session.data.user) throw redirect("/login");
return next({ context: { user: session.data.user } });
});
| Guard | Where | Document without a session | With one |
|---|---|---|---|
a path in the request list: { route: "/admin/**", handler: requireLogin } | middleware of defineServer | the middleware throws redirect("/login"): a 302, and no page HTML; with createError({ status: 401 }) a 401 with the error page, JSON for Accept: application/json | 200 |
the handler itself: middleware: [requireLogin] | the definition | its endpoint answers with the error, the row never read | the row |
a load calling a handler that holds the guard | x.load.ts | the handler's status or redirect becomes the document's, before any page HTML | 200 |
| a route middleware that redirects | app/middleware, named in the page's meta | a 302 on the server; in the browser a navigation to the target | the page |
The first row protects the document: it runs before the router and any render, and no client can skip it. A client navigation sends no document request, so the first row does not run for it; that is why the second row is the one that counts. It refuses each call, a kept parent() data and an expired session included:
import { defineHandler } from "hamur/server";
import { requireLogin } from "./guards/login.ts";
export const listUsers = defineHandler({
method: "GET",
middleware: [requireLogin],
handler: () => [{ id: 1, name: "ada" }],
});
For the redirect a visitor sees on a navigation, name a route middleware in the page's meta: it asks the shared state the same question through a handler, as Forms and login shows. It is a convenience for the visitor and nothing more. A guard in useAsyncData is not one either: in a streamed render it runs after the shell was sent, so the status can no longer change.
CSRF
csrf(event, { secret, session }) protects a form post. secret is at least 32 characters and throws a TypeError when it is shorter; without it the tokens are signed with a key derived from the app key HAMUR_KEY. On a safe method (GET, HEAD, OPTIONS, TRACE, QUERY) it returns the token and sets it in a cookie. A cross-origin QUERY is allowed only when CORS methods lists it. On any other method it checks that the cookie token and the token the request sends are the same, and throws a 403 Invalid CSRF token when they are not. The request sends the token in the x-csrf-token header or in the _csrf field of a form body.
import { csrf, defineHandler, readBody, useSession } from "hamur/server";
const password = process.env.SESSION_PASSWORD as string;
const secret = process.env.CSRF_SECRET as string;
export const account = defineHandler({
route: "/account",
method: "*",
raw: true,
async handler(_, { event }) {
const session = await useSession(event, { password });
const token = await csrf(event, { secret, session });
if (event.method === "GET") {
return `<form method="post"><input type="hidden" name="_csrf" value="${token}"><button>Save</button></form>`;
}
const form = await readBody<Record<string, string>>(event);
return { saved: Object.keys(form ?? {}).filter((key) => key !== "_csrf") };
},
});
Always pass session, the awaited result of useSession. The token is then bound to the session, so a token issued for one session is rejected for another. regenerate() gives the session a new id and keeps its data, and clear() gives it a new id and empties it; either one invalidates every older token. Call regenerate() on login, as the login sample above does, so the tokens and the session id from before the login stop working. A visitor who gets a form also gets a session cookie. Fetching the token with useFetch("/api/csrf") works on a direct load too: the session and CSRF cookies the route sets while the page renders on the server are sent with the page. Without session, the token is signed with the secret alone, and any token that was ever issued is valid for every visitor, which lets a sibling subdomain plant a matching cookie and field.
On https the cookie is named __Host-hamur-csrf and is Secure; the browser refuses to set it from a sibling subdomain, and a plain hamur-csrf cookie is ignored. On plain http the name is hamur-csrf and the first request logs a warning. Tokens last 24 hours.
Cookies
setCookie, getCookie and deleteCookie write and read plain cookies. Three more features cover a value that must not be forged, a value that is too large, and a name the browser protects.
Signed cookies. setCookie(event, name, value, { signed: true }) writes <value>.<MAC>: an HMAC-SHA-256 of the name and the value under the app key, so a visitor can read the value but cannot change it, and a value copied to another cookie does not verify. getSignedCookie(event, name) returns the value, or undefined for a cookie that is missing, unsigned or changed. A string or a list in signed uses those secrets instead, the first signing and every one verifying. A signed cookie is tamper-proof, not secret: use seal for a value the browser must not read.
import { defineHandler, getSignedCookie, setCookie } from "hamur/server";
export const login = defineHandler({
route: "/api/login",
method: "POST",
raw: true,
handler(_, { event }) {
setCookie(event, "__Host-sid", "ada", { signed: true, secure: true, httpOnly: true, sameSite: "lax" });
return { ok: true };
},
});
export const me = defineHandler({
route: "/api/me",
method: "GET",
raw: true,
async handler(_, { event }) {
return { user: (await getSignedCookie(event, "__Host-sid")) ?? null };
},
});
Chunked cookies. A cookie is at most 4096 bytes. setChunkedCookie(event, name, value) splits a larger value over name=chunks-2, name.0 and name.1, getChunkedCookie joins them and deleteChunkedCookie removes all of them. A value can need at most two chunks (6144 bytes together, so the cookie header of a request stays under the 8 KiB that nginx accepts by default); anything larger belongs in a session store. Cookie sessions use these functions on their own when their seal passes 4096 bytes. Signed cookies and chunks do not combine.
import { defineHandler, deleteChunkedCookie, getChunkedCookie, setChunkedCookie } from "hamur/server";
export const save = defineHandler({
route: "/api/draft",
method: "POST",
raw: true,
handler(_, { event }) {
setChunkedCookie(event, "draft", JSON.stringify({ title: "x".repeat(5000) }), { httpOnly: true, secure: true, sameSite: "lax" });
return { ok: true };
},
});
export const read = defineHandler({
route: "/api/draft",
method: "GET",
raw: true,
handler(_, { event }) {
return { draft: getChunkedCookie(event, "draft") ?? null };
},
});
export const discard = defineHandler({
route: "/api/draft",
method: "DELETE",
raw: true,
handler(_, { event }) {
deleteChunkedCookie(event, "draft");
return { ok: true };
},
});
Prefixes. A cookie name that starts with __Host- or __Secure- is checked by name, because the browser drops one that breaks the rules: __Host- needs secure: true, path: "/" and no domain, and __Secure- needs secure: true. Otherwise the call throws. A __Host- cookie can be set only by the host itself, so a sibling subdomain cannot plant one: the session, CSRF and OAuth cookies of Hamur use that name.
Sealing a value
seal(value, { purpose, ttl }) encrypts a value into a URL-safe string, and unseal(sealed, { purpose }) opens it. Use them for a value that leaves the server and must come back unchanged and unread: an invite link, a reset token, a value in a hidden field. The key is the app key, and purpose is bound to the seal, so a seal made for an invite does not open as anything else. unseal gives undefined for anything malformed, tampered with, expired or made for another purpose, and never throws for its input. A purpose that starts with hamur- is reserved.
import { createError, defineHandler, seal, unseal } from "hamur/server";
interface Invite {
email: string;
team: string;
}
export const invite = defineHandler({
method: "POST",
async handler({ email, team }: Invite) {
const token = await seal({ email, team }, { purpose: "invite", ttl: 60 * 60 * 24 * 3 });
return { link: `https://app.example/join?token=${token}` };
},
});
export const join = defineHandler({
method: "POST",
async handler({ token }: { token: string }) {
const invite = await unseal<Invite>(token, { purpose: "invite" });
if (!invite) throw createError({ status: 400, message: "This invite has expired" });
return { team: invite.team };
},
});
A single-use link needs more than a seal, which can be replayed until it expires: createAuthToken and consumeAuthToken of @hamur/auth count each token once.
JWT, basic and bearer auth
For an API that other programs call, Hamur signs and verifies JSON Web Tokens on Web Crypto, the same on every preset. verifyJWT accepts only the algorithms you list, never none, and checks exp, nbf, iss, aud and sub when you give them. A string or bytes key is an HMAC secret and nothing else, at least as long as the hash, and a key binds its algorithm, so an RSA key never verifies an HS256 token. With { jwksUri } the keys of a provider are fetched over https, cached and refreshed when a token names a key it does not have. requireJWT(event, options) reads the authorization: Bearer header (or a cookie you name) and gives the claims, or a 401.
import { defineHandler, requireJWT, signJWT, useRuntimeConfig } from "hamur/server";
const secret = () => String(useRuntimeConfig().jwtSecret);
export const token = defineHandler({
route: "/api/token",
method: "POST",
async handler() {
return { token: await signJWT({ scope: "read" }, secret(), { alg: "HS256", expiresIn: 900, issuer: "https://api.example", audience: "web", subject: "ada" }) };
},
});
export const data = defineHandler({
route: "/api/data",
method: "GET",
async handler(_, { event }) {
const claims = await requireJWT(event, { key: secret(), algorithms: ["HS256"], issuer: "https://api.example", audience: "web" });
return { sub: claims.sub };
},
});
export const partner = defineHandler({
route: "/api/partner",
method: "GET",
async handler(_, { event }) {
const claims = await requireJWT(event, { key: { jwksUri: "https://idp.example/.well-known/jwks.json" }, algorithms: ["RS256"], issuer: "https://idp.example" });
return { sub: claims.sub };
},
});
requireBasicAuth and basicAuth check HTTP Basic credentials. The password is compared as digests in constant time, and { runtimeConfig } reads it from the runtime config; a key that is not set is a 500, never a pass. requireBearerToken checks a bearer token against a secret, a list of them or a function. The same checks exist as the route rule basicAuth for a path and the files under it.
import { defineHandler, defineServer, requireBearerToken } from "hamur/server";
import { metricsAuth } from "./metrics-auth.ts";
export const feed = defineHandler({
route: "/api/feed",
method: "GET",
async handler(_, { event }) {
await requireBearerToken(event, { token: { runtimeConfig: "feedToken" } });
return { items: [] };
},
});
export default defineServer({ middleware: [{ route: "/metrics", handler: metricsAuth }] });
A route rule matches a path the way the page router reads it: an empty segment is kept, and it matches only a last **. With "/admin/**": { basicAuth } and "/admin/help": { basicAuth: false }, a page app/pages/admin/[...path].tsx serves /admin//help, /admin/help// and /admin/%2Fhelp, and each of them asks for the password; only /admin/help itself is open. The same holds for ipRestriction, rateLimit, headers, redirect and every other rule key. On Netlify, Cloudflare and a static build, the headers and redirect of a rule also go into the platform's _headers and _redirects files, which the platform matches itself and may read // as /; basicAuth, ipRestriction and rateLimit never go there and run in the server only.
A password that is a shared secret in a header is for a metrics endpoint or a webhook, not for people: sign people in with Auth.
CORS
handleCors(event, options) answers a preflight request and sets the CORS headers. Return its result from a request middleware: it is a 204 response for a preflight and undefined for anything else, so the request goes on. List the middleware in the middleware of defineServer in server/index.ts.
import { defineMiddleware, handleCors } from "hamur/server";
export const cors = defineMiddleware(({ event }) =>
handleCors(event, {
origin: ["https://app.example.com"],
methods: ["GET", "POST"],
credentials: true,
maxAge: 600,
}),
);
| Option | Meaning |
|---|---|
origin | "*" (default), one origin, a list of origins and patterns, or a function that gets the request's Origin. A pattern is a RegExp that matches the whole origin: it must start with ^ and end with $ and must not use the g or y flag |
methods | allowed methods; the default is GET, HEAD, PUT, PATCH, POST, DELETE |
headers | allowed request headers; by default the requested ones are echoed |
credentials | allow credentials; it cannot be combined with origin: "*" |
maxAge | seconds a preflight answer may be cached |
exposeHeaders | response headers the page may read, such as the header of a header session |
An origin matches only when scheme, host and port all match. To allow every subdomain of your own site with credentials, write a pattern that pins the scheme: ^https: before the host, as below. A pattern with credentials that does not start with ^https: logs a warning, since it would also allow http:// pages whose traffic anyone on the network can change.
import { defineMiddleware, handleCors } from "hamur/server";
export const cors = defineMiddleware(({ event }) =>
handleCors(event, {
origin: [/^https:\/\/[a-z0-9-]+\.example\.com$/],
credentials: true,
exposeHeaders: ["x-session"],
maxAge: 600,
}),
);
The route rule cors does the same for every path under a pattern, ahead of server middleware; cors: true uses the defaults. When a request ends in an error, the CORS headers are copied onto the error response, so the browser can read it.
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
routeRules: {
"/api/**": { cors: { origin: "https://app.example.com", credentials: true, maxAge: 600 } },
},
});
Rate limit
rateLimit({ limit, window }) is a request step that counts requests per key in a fixed window of window seconds and refuses those above limit with a 429 Too Many Requests and a Retry-After. Every answer it lets through carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. List it in the middleware of defineServer with a route, in handlerMiddleware, or on one handler as defineMiddleware({ server: rateLimit(…) }). A handler call is POST <baseURL>_hamur/fn/<id>, which no path names, so the step on the handler is how a handler is limited; the login handler of Auth limits per address and email. The route rule rateLimit: { limit, window, key? } runs the same count for every request under a pattern, after static files and the CORS preflight.
import { defineServer } from "hamur/server";
import { internalOnly } from "./internal-only.ts";
import { limitApi } from "./limit-api.ts";
import { limitSearch } from "./limit-search.ts";
export default defineServer({
middleware: [
{ route: "/api/**", handler: limitApi },
{ route: "/api/search", handler: limitSearch },
{ route: "/admin/**", handler: internalOnly },
],
});
key is what a count is kept for: "ip" (the default) counts per client address, "fingerprint" per getRequestFingerprint(event), and a function returns any string, such as the address and the email of a login. getRequestFingerprint is the hash of the parts of the request you choose (ip, method, path, userAgent), so a limit can be more than the address alone. The key text is hashed before it becomes a storage key, so an email never reaches storage.
The count is only as good as two settings:
- The client address.
getRequestIPis the address the platform reports. Behind a proxy that you control, setserver.requestIP: { xForwardedFor: true, trustedHops: <the number of proxies> }, or every request is the proxy's. One setting servesrateLimit,ipRestriction, the fingerprint and Turnstile. A request without a readable address counts under one key and logs a warning once. - The storage. Counts live on the storage mount
ratelimit, in memory when the config mounts none, so each process counts alone (each isolate, on Workers). Mountstorage.ratelimitonredis,dborsqliteto count across instances; the cloudflare, vercel and netlify builds warn while it is in memory.
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
server: { requestIP: { xForwardedFor: true, trustedHops: 1 } },
storage: { ratelimit: { driver: "redis", url: { runtimeConfig: "redisUrl" } } },
runtimeConfig: { redisUrl: "" },
routeRules: {
"/api/**": { rateLimit: { limit: 100, window: 60 } },
"/api/login": { rateLimit: { limit: 5, window: 60, key: "fingerprint" } },
"/internal/**": { ipRestriction: { allow: ["10.0.0.0/8"] } },
"/upload/**": { bodyLimit: 10 * 1024 * 1024, timeout: 120 },
"/api/report": { timeout: 15 },
},
});
IP restriction
ipRestriction({ allow?, deny? }) refuses requests by client address with a 403 Forbidden. An entry is a range (10.0.0.0/8, 2001:db8::/32) or one address. deny is read first; when allow is given, an address outside it is refused. IPv4-mapped IPv6 addresses compare as the IPv4 address they hold. It is listed like rateLimit, and the route rule ipRestriction checks every request under a pattern, before static files and before basicAuth. isIPInRange(ip, cidr) is the same match on its own.
The check fails closed: a request without an address, or with one that does not parse, is refused, even by a list that only denies. An entry that is not a range, or an empty allow, throws when the step is made, so a typo is a failed start and not an open door. The static preset fails a build that has the rule, since it has no server; the other platform presets fail one with a prerendered page under it and warn for a file in public/, which the platform serves without asking the app.
Request size and time
server.maxBodySize limits what a handler, readBody and readFormData read. The route rule bodyLimit (bytes) replaces it for a pattern, up to server.maxRequestBodySize: a body above it is a 413, and a declared content-length above it is refused before a byte is read. assertBodySize(event, limit) does the same for the next read of one handler.
The route rule timeout (seconds) and the timeout of defineHandler end a request that runs too long: the handler's ctx.signal aborts at the limit or when the client leaves, and the answer is a 504 Gateway Timeout whether or not the handler honours the signal; a body that is streaming is errored and closed. A handler's own value wins over the rule. Pass the signal on to what the handler calls, as the sample does, so the work stops too.
import { defineHandler } from "hamur/server";
export const report = defineHandler({
method: "POST",
timeout: 15,
async handler(_, { signal }) {
const response = await fetch("https://reports.example/build", { signal });
return response.json();
},
});
On vercel and netlify the build warns when a limit is above what the platform allows (4.5 MB of body on vercel, the function's duration), since the platform ends the request first.
Turnstile
verifyTurnstile(event, token, options?) asks Cloudflare whether a Turnstile token is valid and returns { success, errorCodes, … }. Check .success: the function never throws for a bad token, and a call that fails (a network error, a timeout, an answer that is not JSON) is success: false with internal-error, so a Cloudflare outage refuses sign-ups instead of letting everything through. With action or hostname, a valid token made for another action or host is refused too. The secret is runtimeConfig.turnstileSecretKey (HAMUR_TURNSTILE_SECRET_KEY at run time); a missing one throws. The widget on the page is Cloudflare's: it adds a cf-turnstile-response field to the form, which your handler passes in as token.
import { createError, defineHandler, verifyTurnstile } from "hamur/server";
export const signup = defineHandler({
route: "/api/signup",
method: "POST",
async handler({ email, token }: { email: string; token: string }, { event }) {
const verdict = await verifyTurnstile(event, token, { action: "signup", hostname: "app.example" });
if (!verdict.success) throw createError({ status: 400, message: "Captcha failed" });
return { welcome: email };
},
});
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
runtimeConfig: { turnstileSecretKey: "" },
});
Security defaults
Every answer of the server carries three headers, unless the answer already has a header of that name:
| Header | Value |
|---|---|
X-Content-Type-Options | nosniff |
Referrer-Policy | strict-origin-when-cross-origin |
X-Frame-Options | SAMEORIGIN |
A handler's or middleware's setHeader(event, "x-frame-options", "DENY") wins, and so does a proxied upstream's header. For one path, a route rule's headers replaces a header with a string or removes it with false. For the whole app, server.securityHeaders takes false (no headers) or an object merged over the three:
// hamur.config.ts
export default defineConfig({
server: { securityHeaders: { "permissions-policy": "camera=()" } },
routeRules: { "/embed/**": { headers: { "x-frame-options": false } } },
});
The static, vercel, netlify and cloudflare presets write the same headers into the files the platform serves. On Cloudflare a rule's false or string replaces the default in those files too. On Netlify and with the static preset the host joins the values of every matching block, so a rule cannot remove or replace a default header there: the build warns, and server.securityHeaders with that header set to false leaves it to your rules. The server's own answers always follow the rule.
The server also refuses a cross-origin form post. A POST, PUT, PATCH or DELETE with no Content-Type, or with application/x-www-form-urlencoded, multipart/form-data or text/plain, gets a 403 Cross-origin request blocked when Sec-Fetch-Site says another site sent it or, without that header, when Origin names another host. Same-origin requests, JSON requests, requests from curl or a server, in-process $fetch and paths whose route rule has cors all pass. An identity provider that posts its callback form to your app needs its origin listed on the callback's route, so it can post there and nowhere else:
// hamur.config.ts
export default defineConfig({
routeRules: { "/auth/apple": { originCheck: { allow: ["https://appleid.apple.com"] } } },
});
server.originCheck.allow lists origins for every route.
server.originCheck: false turns the check off. It does not replace csrf(); both can run.
Header keys
server.securityHeaders also takes typed keys, beside header names. They are written after the defaults, so a header name for the same header wins:
| Key | Header | |
|---|---|---|
hsts | Strict-Transport-Security | off by default; true is max-age=63072000 and nothing else; { maxAge, includeSubDomains, preload } for more. Not sent under hamur dev |
permissionsPolicy | Permissions-Policy | { camera: [], geolocation: ["self", "https://maps.example"] } is camera=(), geolocation=(self "https://maps.example"); each value is "self", "*" or an origin |
crossOriginOpenerPolicy | Cross-Origin-Opener-Policy | "same-origin", "same-origin-allow-popups", "noopener-allow-popups", "unsafe-none" or false |
crossOriginEmbedderPolicy | Cross-Origin-Embedder-Policy | "require-corp", "credentialless", "unsafe-none" or false |
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
server: {
securityHeaders: {
hsts: { maxAge: 63072000, includeSubDomains: true, preload: true },
permissionsPolicy: { camera: [], geolocation: ["self", "https://maps.example"] },
crossOriginOpenerPolicy: "same-origin",
crossOriginEmbedderPolicy: "credentialless",
},
},
});
includeSubDomains is opt-in. It tells browsers to use https for every subdomain of the host for the whole maxAge, two years here, including a subdomain that another team runs on plain http and a staging host you forgot. Add it only when every subdomain serves https, and add preload (which needs a maxAge of at least a year and includeSubDomains) only when you mean to submit the domain to the browsers' preload list, which is hard to undo. The header is written whatever the request's scheme, since a server behind a TLS proxy without server.trustProxy sees http:, and browsers ignore it over plain http.
Content Security Policy
A Content Security Policy tells the browser which scripts and resources a page may load, so a script that an attacker injected is refused. server.csp makes Hamur write the policy for every HTML document it answers, error pages included, and handle the part that is hard by hand: the inline scripts that Hamur and your UI library write themselves. It is off by default (false). A document that already has a content-security-policy header from your code keeps it and gets none from Hamur.
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
server: {
csp: {
mode: "auto",
directives: {
"img-src": ["'self'", "data:", "https://images.example"],
"connect-src": ["'self'", "https://api.example"],
"style-src": ["'self'"],
},
report: true,
},
},
});
The base policy, which directives merges over:
| Directive | Value |
|---|---|
default-src | 'self' |
script-src | 'self', plus the nonce or hashes of the page |
style-src | 'self' 'unsafe-inline' |
img-src | 'self' data: |
object-src | 'none' |
base-uri | 'self' |
frame-ancestors | 'self', the same as the default X-Frame-Options: SAMEORIGIN |
directives replaces the list of a directive you name and removes one set to false; a new name is added after the base ones. A value with ;, , or a control character fails at load, so one entry cannot become two directives. script-src cannot be removed, emptied or set to 'none', since the page's own scripts are added to it. style-src keeps 'unsafe-inline' because every UI library writes style="…" attributes, which a nonce cannot allow; an app that writes none removes it with "style-src": ["'self'"], as the sample does, and the nonce or hash of the page is then added to style-src too.
Modes
The mode says how a page's own inline scripts are allowed:
| Mode | How | Pages |
|---|---|---|
nonce | a random nonce per request goes on every script and in the policy | the page answers cache-control: no-store and cannot be prerendered |
hash | the policy lists the SHA-256 of each inline script that Hamur or the adapter wrote: the import map, the useHead scripts and the library's own | the page is buffered whole, so the header can go before the body; it can be cached and prerendered |
auto (default) | hash for a prerendered page and for a page under a swr or cache rule, nonce for every other page | each page gets the mode that keeps it cacheable |
The hashes are recorded where the scripts are written and never found by scanning the output, so a script injected through v-html, dangerouslySetInnerHTML, {@html} or stored content gets no hash and the browser refuses it. A script whose text you build from request data is allowed by its hash as it would be by a nonce: keep data in a JSON script, not in code.
Where the policy goes. A page the server answers carries it in the Content-Security-Policy header, which a cache keeps with the page. A prerendered page is a file, so it carries <meta http-equiv="Content-Security-Policy"> first in <head>. A meta policy cannot hold frame-ancestors, report-uri, report-to or sandbox, so those directives go into a second policy in a header written for the prerendered files: the bun and node servers send it with the files they serve, and the static, cloudflare and netlify presets write it into the /* block of _headers beside the security headers, as below (vercel writes it as a route that only static files reach). So a prerendered page is still protected against framing by frame-ancestors 'self'. Reports from a prerendered page cover that second policy only, since a meta policy cannot report.
/*
x-content-type-options: nosniff
referrer-policy: strict-origin-when-cross-origin
x-frame-options: SAMEORIGIN
content-security-policy: frame-ancestors 'self'
A reportOnly policy cannot be a meta, so a prerendered page then carries no policy and the build warns once. hamur dev sends the policy as Content-Security-Policy-Report-Only always, since its overlay and reload script are inline; a build enforces it.
'strict-dynamic' and styles
With 'strict-dynamic' (default strictDynamic: true) a browser ignores 'self' and host sources for scripts and trusts only what a nonce or hash allows, plus what those scripts load. On a nonce page the entry script and the modulepreload links carry the nonce, and the chunks the entry imports are trusted by propagation. A hash page can only allow an external script through its integrity attribute, so 'strict-dynamic' there needs Subresource Integrity, which hash and auto switch on for you (below). strictDynamic: false leaves it off everywhere.
A nonce is also written on stylesheet links and inline <style> tags, and added to style-src when it holds no 'unsafe-inline'. In hash mode inline styles are not hashed: with a style-src that has no 'unsafe-inline', a useHead style on a hash page is blocked. Use nonce mode, or keep 'unsafe-inline' in style-src, if you add styles that way.
Your own policy
To write the whole policy yourself, set event.context.nonce in a request middleware (the middleware list of defineServer) and send the header. Hamur writes the nonce on the import map, the payload and entry scripts, each modulepreload link and each useHead script without a nonce of its own, and adds <meta property="csp-nonce"> so the client's preload links get it too.
import { createNonce, defineMiddleware, setHeader } from "hamur/server";
export const csp = defineMiddleware(({ event }) => {
const nonce = createNonce();
event.context.nonce = nonce;
setHeader(event, "content-security-policy", `script-src 'nonce-${nonce}' 'strict-dynamic'`);
});
A page with a nonce answers cache-control: no-store, even when a route rule sets cache-control for its path, so no cache serves one nonce to every visitor; hamur dev warns about such a rule. A prerendered page cannot carry a nonce, and hamur generate fails such a path. For prerendered pages, allow the import map by its sha256-… source instead of a nonce.
Subresource Integrity
build.sri ("sha256", "sha384" or "sha512"; default false) records the digest of every client script and stylesheet in the build and writes it as integrity on the entry <script type="module">, each modulepreload and stylesheet link, the preload links the client adds, and in an integrity section of the import map, so the browser refuses a file whose bytes changed after the build. app.crossOrigin ("anonymous" or "use-credentials"; default false, "anonymous" when build.sri is on) adds crossorigin to the same tags; set it when the files come from another origin.
// hamur.config.ts
export default defineConfig({
build: { sri: "sha384" },
});
With server.csp in hash or auto mode, a hash page lists the digests of its entry and modulepreload links in script-src with 'strict-dynamic', and build.sri defaults to "sha384"; build.sri: false there fails at load unless server.csp.strictDynamic is false. A useHead script or modulepreload that names one of the build's files gets its integrity and joins the list too; under 'strict-dynamic' any other external script without a listed integrity, such as a useHead script from another site on a hash page, is refused. Safari loads such a page from Safari 18.2 on (WebKit bug 270784, fixed in 282577@main); earlier releases block the entry script.
A CDN or proxy that rewrites scripts or stylesheets (minifies them, injects code) breaks every integrity check: serve the build's files as they are.
Violation reports
report: true adds report-uri <baseURL>_hamur/reports; report-to hamur to the policy and a Reporting-Endpoints header beside it, and mounts the endpoint, which accepts both the application/reports+json and the application/csp-report bodies that browsers send. Each report is logged at warn with the blocked directive, the blocked URL and the page (origin and path; the query is dropped, since it may hold a token), and passed to the client:report hook as { type: "csp", … } (Observability). A report body above 16 384 bytes answers 413, and an instance takes at most 100 reports per second, counted apart from the client error reports. A report comes unauthenticated from any site, so treat the log as a hint and not a record. Start a new policy with reportOnly: true and report: true, read what it would have blocked, then enforce it.
Trusted Types
trustedTypes: true (or { policies: ["dompurify"] }) adds require-trusted-types-for 'script'; trusted-types hamur <the adapter's policies> <yours>. The browser then refuses a string written to an HTML or script sink (innerHTML, a script's src or text, an on* attribute) unless it comes from a named policy, which turns most DOM-based XSS into an error. Hamur's own client writes go through one policy, hamur, which the core creates and nothing else can reach.
import { defineConfig } from "hamur";
export default defineConfig({
framework: "react",
build: { sri: "sha384" },
server: {
csp: { mode: "hash", trustedTypes: { policies: ["dompurify"] }, reportOnly: true },
},
});
What it guards, and what it does not:
- Your code and every library's, except the policies the directive lists. React and Preact accept
TrustedHTMLindangerouslySetInnerHTMLand create no policy: write HTML through a policy of your own and list its name inpolicies. - Vue creates a pass-through policy named
vue, and Svelte one namedsvelte-trusted-html; the adapter lists them for you. Both only return the string they get, so they do not guard what goes through them: Svelte's{@html}is not protected by Trusted Types, and Vue'sv-htmlis a plaininnerHTMLassignment, which the directive blocks unless the value is aTrustedHTMLfrom a policy of your own. - Solid is not supported.
solid-jsassigns its compiled templates toinnerHTMLwithout a policy, so every page would throw;server.csp.trustedTypeswith@hamur/adapter-solidfails at load withserver.csp.trustedTypes is not supported with @hamur/adapter-solid: solid-js assigns template strings to innerHTML without a Trusted Types policy. @hamur/adapter-htmlmarkup anduseHeadscript content pass through thehamurpolicy unchanged, as the server wrote them: an html component escapes what it interpolates, and what you put into auseHeadscript runs as your own code.- A
<script>element rendered by React or Preact on the client is not supported under the directive (a server-rendered one hydrates fine). Add scripts withuseHead({ script }). hamur devsends the policy Report-Only and logs a warning for each violation.