Skip to content

Private previewMost of the architecture is written. First public release in 2027.

Data security

Everything a page needs reaches the browser in one of three ways: the answer of a handler, the payload that a server render writes into the HTML, and the HTML itself. Each is readable by the visitor, by a script on the page and by anyone who reads the page source. This guide is about keeping what must not leave the server out of all three. Auth says who the visitor is and Sessions and security protects the request; here the question is what you hand back.

The rules, each with a section below:

  1. A handler returns a DTO: a plain object with exactly the fields the caller may see, never a row.
  2. A handler checks who asks, on every call. A load does not: it runs in the browser on a navigation and a user can skip it.
  3. One module reads the database and checks the session before it does.
  4. Mark what must never leave with taint, so a mistake fails instead of leaking.
  5. Keep server code out of the client build with the import guards.
  6. A production error says nothing but what you chose to say.

Handlers return DTOs, and load is not a guard

A handler is a public endpoint: whatever it returns goes to whoever called it, as JSON from POST <baseURL>_hamur/fn/<id> and, when it has a route, from that route too. The id is in the client bundle. A handler that returns a database row sends every column, the ones added next year included.

Return a data transfer object: an object you build field by field, so a new column is never sent by accident. Give the handler an output schema as a second line of defence. It runs on what the handler returns, on every call (over the wire, in process and during the server render), and what the schema returns is what leaves, so a schema that strips keys strips them. A refusal is a masked 500 and the server logs the reason; it is never a 400, since the caller did nothing wrong.

A load calls handlers and shows their data; it decides nothing. It runs on the server for the first render and in the browser for each navigation after it, and a user can skip it, call the handler directly or read its URL out of the bundle. The check is in the handler or in its middleware (Handlers): requireUserSession(event) for a visitor, and a role check as Auth shows. A redirect from a load steers a visitor and stops no request.

ts
import { defineHandler } from "hamur/server";
import { schema } from "../forms/server/utils/schema.ts";
import { getAccount, getPost, listMyPosts, type AccountDTO, type PostDTO } from "./dal.ts";

const postOutput = schema<PostDTO>({ type: "object", properties: { id: { type: "string" }, title: { type: "string" }, body: { type: "string" }, mine: { type: "boolean" } } }, (value) => {
  const { id, title, body, mine } = value as PostDTO;
  return { value: { id, title, body, mine } };
});

const accountOutput = schema<AccountDTO>({ type: "object", properties: { id: { type: "string" }, name: { type: "string" }, email: { type: "string" } } }, (value) => {
  const { id, name, email } = value as AccountDTO;
  return { value: { id, name, email } };
});

export const post = defineHandler({
  method: "GET",
  output: postOutput,
  handler: ({ id }: { id: string }, { event }) => getPost(event, id),
});

export const myPosts = defineHandler({
  method: "GET",
  handler: (_, { event }) => listMyPosts(event),
});

export const account = defineHandler({
  method: "GET",
  output: accountOutput,
  handler: (_, { event }) => getAccount(event),
});

post and account have an output that builds the DTO again from what the handler returned. myPosts has none: it relies on the data access layer below, which already returns DTOs. Both are fine; use the schema where a column is likely to be added or a handler is written by someone who does not know the table.

A data access layer

Put every read of the database in one module, server/utils/dal.ts. Each function takes the event, asks who the visitor is, checks what the visitor may see, and returns a DTO. Handlers call the layer and nothing else touches the tables, so there is one place where the checks live and one place to read in a review.

ts
import "hamur/server-only";
import { requireUserSession } from "@hamur/auth/server";
import { createError, taint, type HamurEvent } from "hamur/server";
import { db, type PostRow } from "./db.ts";

export interface PostDTO {
  id: string;
  title: string;
  body: string;
  mine: boolean;
}

export interface AccountDTO {
  id: string;
  name: string;
  email: string;
}

const toPostDTO = (row: PostRow, userId: string): PostDTO => ({ id: row.id, title: row.title, body: row.body, mine: row.authorId === userId });

export async function getPost(event: HamurEvent, id: string): Promise<PostDTO> {
  const { user } = await requireUserSession(event);
  const row = await db.posts.get(id);
  if (!row || (row.draft && row.authorId !== user.id && user.role !== "admin")) throw createError({ status: 404, message: "Post not found" });
  taint(row, "post row");
  return toPostDTO(row, user.id);
}

export async function listMyPosts(event: HamurEvent): Promise<PostDTO[]> {
  const { user } = await requireUserSession(event);
  return (await db.posts.byAuthor(user.id)).map((row) => toPostDTO(row, user.id));
}

export async function getAccount(event: HamurEvent): Promise<AccountDTO> {
  const { user } = await requireUserSession(event);
  const row = await db.accounts.get(user.id);
  if (!row) throw createError({ status: 404, message: "Account not found" });
  taint(row.passwordHash, "password hash");
  taint(row.apiToken, "API token");
  return { id: row.id, name: row.name, email: row.email };
}
  • requireUserSession(event) is the first line of every function. The layer does not trust that its caller did the check.
  • A row the visitor may not see answers 404, the same as a row that does not exist, so the answer does not tell a visitor which ids are taken. A role check that is the visitor's to know, such as an admin page, answers 403.
  • The functions return PostDTO and AccountDTO, types with no field a visitor may not see. The row types stay in db.ts.
  • taint marks the raw row and the secrets of a row. If a later edit returns the row, or puts the hash into a DTO, the render fails instead of sending it.

The layer is server code. Name it so the import guards know: a file under server/, or a .server.ts file, or one that imports hamur/server-only, can never be bundled for the browser. The sample imports the marker as its first line, which keeps the layer out of the client build even if it moves to a folder the build does not know as server.

taint

taint(value, message) marks a value that must never reach the browser. The payload serializer refuses it wherever it meets it: load data, useAsyncData results, useState, the module payload, the public env script, and the answer of a handler over the wire, a public route's JSON included. A hit fails the render or the call with a 500. In development the message is <message>: <path> must not reach the client, naming the path of the value (session token: payload.data.index.user.token must not reach the client); in production the answer is the masked Internal Server Error, and the server log keeps the full text.

ts
import { definePlugin, taint, useRuntimeConfig } from "hamur/server";

export default definePlugin(() => {
  const key = String(useRuntimeConfig().stripeKey ?? "");
  if (key.length >= 8) taint(key, "Stripe secret key");
});

What it does and does not catch:

  • An object is marked by identity, for the life of the process. A copy of it, { ...row }, passes. Taint the row you read and build the DTO from fields, and the copy is the DTO.
  • A string (at least 8 characters, else a TypeError) is marked by value, so an equal string made somewhere else is refused too, but a substring, a changed-case copy or a derived value is not. It is kept for the current request, or for the whole process when taint runs outside a request, which is where a secret read at start belongs.
  • Storage, sessions, seal and task inputs are not checked: the server may store a tainted value. Only what is sent is.

taint is a net under the DTO rule and not a replacement for it.

Keep server code out of the client

A page's modules and everything they import are bundled for the browser and readable there. The client build fails, naming the file, the reason and the chain of imports, when client code reaches a .server.ts file, anything under server/ (a handler reaches the client only as a stub, through #server), a folder named server, hamur/server, a node: or bun: specifier, a module that imports hamur/server-only, or a specifier in build.importProtection.client.deny. The error is raised at build time, in hamur dev too, so a leak is a red build and not a production incident. Add the packages that must never reach the browser to importProtection:

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  build: { importProtection: { client: { deny: ["pg", /^@internal\//] } } },
});

serverOnly() and clientOnly() of hamur/app drop the other side's code from a file that both sides import. The API reference has the exact rules and messages.

Environment follows the same line. Only runtimeConfig.public and the variables that start with HAMUR_PUBLIC_ reach the browser; every other key of runtimeConfig stays on the server. Under hamur dev, a private runtime-config value of eight characters or more that appears in a page's payload logs a warning, once per page and key. Do not put a secret under public.

Errors say nothing

An error that is not a createError is logged in full on the server. The visitor gets the status text (Internal Server Error, Conflict) and no data, in the HTML of a rendered page and in the payload alike; only hamur dev shows the real message and stack. So a database error, a stack trace and a path never leave the server by accident.

A createError is the opposite: its message and data are for the visitor. Write them for a visitor, and leave out what the error is about: Wrong email or password, not No user with the email a@b.test. Never put a row, a token or an internal id in data.

A payload audit

The page's payload is the one thing the server writes that no handler's output covers. Before a release, load each page signed out, signed in as a member and signed in as an admin, open the page source, and read the <script type="application/json" id="__hamur_payload"> element. Then:

  1. Search it for a value that must not be there: an email address of another user, a hash, a token, an internalNotes column. Search for the strings, not the keys.
  2. Check that every load and every useAsyncData call returns what the page shows and no more. A pick option of useAsyncData keeps only named top-level keys.
  3. Check that useState holds no secret and no per-user data on a page that is cached; the state is part of the page.
  4. Check that the data of every createError is safe to show.
  5. Check runtimeConfig: every secret is outside public. Hamur sends public and nothing else.
  6. Check that a page under a prerender, swr or cache rule shows nothing about a user. It is rendered once for everybody.
  7. Check the head: a useHead value built from a row or from the session is written into the HTML as it is.
  8. Read the source of the build output for the client: search the .output/public JavaScript for the names of your secrets, and for server/ paths.
  9. Taint what is left: the raw rows, the keys, the tokens. The next time one slips into a DTO, the render fails.

useRequestHeaders() without names includes cookie and authorization; render only what the page may show.