Skip to content

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

Auth

@hamur/auth keeps the signed-in user in a session, answers that session to the browser, guards pages and data, and signs users in with a password, an OAuth provider, OpenID Connect, an AT Protocol account, a passkey or an emailed link. It has no dependency and works with every UI library. This guide builds a login with each of them. Every file below is in landing/samples/auth/ in the repository and is type-checked with the rest of the docs. The exact signatures are in the @hamur/auth reference; the core helpers it builds on are in Sessions and security.

Setup

Add @hamur/auth to the app's dependencies the way hamur and the adapter were added (Getting started), list it in modules and make the app key. The module seals the session with it, and so do OAuth, passkeys and the email tokens:

sh
hamur create-key --env

hamur create-key --env writes HAMUR_KEY=<32 random bytes, base64url> to .env. In production, set HAMUR_KEY in the environment of every instance, with the same value on all of them. A built server without it does not start. Under hamur dev the module writes a key to .env for you when none is set. To rotate it, put the new key first: HAMUR_KEY=<new>,<old>.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  modules: ["@hamur/auth"],
  auth: {
    session: { maxAge: 60 * 60 * 24 * 30, idleTimeout: 60 * 60 * 24 * 7 },
    loadStrategy: "server-first",
    redirect: { login: "/login", home: "/" },
    webauthn: { rpID: "example.com", rpName: "Example" },
  },
});
KeyDefault
auth.session.maxAge7 daysseconds from the session's creation
auth.session.idleTimeoutnoneseconds without a request after which the session reads as empty
auth.session.storagefalsea storage mount that keeps the data, so the cookie holds only an id and a session can be revoked (Sessions and security)
auth.session.name, password, cookie__Host-hamur-auth, the app key, HttpOnly; Secure; SameSite=Lax; Path=/the options of useSession
auth.loadStrategy"server-first"where useUserSession reads the session first
auth.redirect.login, auth.redirect.home/login, /where the guards send a visitor
auth.oauth.<provider>the provider's keys, below
auth.webauthnrpID, rpName and origins of the passkey handlers, below

A wrong value is a build error that names the key. The session cookie is named __Host-hamur-auth: a browser refuses a __Host- cookie from anyone but the host itself, so a page on a sibling subdomain cannot plant a session of its own and sign a visitor in to the attacker's account.

Type the session by adding to three empty interfaces. User is what session.user holds, UserSession adds fields beside it, and SecureSessionData is kept in the session and never leaves the server:

ts
declare module "@hamur/auth" {
  interface User {
    id: string;
    name: string;
    role: "admin" | "member";
  }
  interface UserSession {
    loggedInAt: number;
  }
  interface SecureSessionData {
    accessToken: string;
  }
}

export {};

Reading and writing the session

All functions are in @hamur/auth/server and take the event of a handler:

Function
getUserSession(event)the session's data and its id; { id } alone when there is none
setUserSession(event, data)merges data into the session: plain objects merge by key, arrays and other values replace
replaceUserSession(event, data)writes data as the whole session; a data without user logs the user out
clearUserSession(event)empties the session and deletes its cookie
requireUserSession(event)the session when it has a user, else a 401 Unauthorized

When a write changes user, the session gets a new id in the same write, so the id after a login or a change of role is never the one before it. You need no regenerate(). secure is for what only the server may read, such as a provider's access token: the session endpoint and the page payload leave it out.

The browser reads the session from GET <baseURL>_hamur/auth/session, which answers {} for a visitor without one, private, no-store, with Vary: Cookie. Two hooks let a server plugin change it. auth:session:fetch runs before that answer and may add fields to the public session, or throw to refuse it; auth:session:clear runs in clearUserSession with the session and its id, so an app that keeps an index of sessions by user can drop the entry:

ts
import { createError, definePlugin, useStorage } from "hamur/server";
import { findUserByName } from "./users.ts";

declare module "@hamur/auth" {
  interface UserSession {
    roles?: string[];
  }
}

export default definePlugin((server) => {
  server.hooks.hook("auth:session:fetch", async (session) => {
    if (!session.user) return;
    const record = await findUserByName(session.user.name);
    if (!record) throw createError({ status: 403, message: "Account removed" });
    session.roles = [record.role];
  });
  server.hooks.hook("auth:session:clear", async (session) => {
    if (session.user) await useStorage("session-index").removeItem(`${session.user.id}:${session.id}`);
  });
});

useUserSession and AuthState

Each UI library has an entry, @hamur/auth/react, /vue, /preact, /svelte, /solid and /html, with the same two names. useUserSession() gives { ready, loggedIn, user, session, fetch, clear }: ready is false until the session was read, on the server or by a fetch, fetch() reads it again and clear() logs out. The values come in the shape of the library:

LibraryValues
react, preactplain values; the component renders again when they change
vueComputedRefs
sveltea store: $session.user, $session.loggedIn, and session.clear()
solidAccessors
htmlthe server's values; fetch() reloads the page and clear() logs out, then reloads

AuthState renders its placeholder until ready, then its children with { loggedIn, user, clear }. A page that shows who is signed in shows the placeholder in a prerendered file and the user once the session is read, with no flash of the wrong state. html has no AuthState: its pages do not render again in the browser.

tsx
import { AuthState, useUserSession } from "@hamur/auth/react";

export function UserMenu() {
  const { loggedIn, user, clear } = useUserSession();
  return loggedIn ? (
    <button type="button" onClick={() => void clear()}>
      Log out {user?.name}
    </button>
  ) : (
    <a href="/login">Log in</a>
  );
}

export function Welcome() {
  return (
    <AuthState placeholder={<p>Loading session</p>}>
      {({ loggedIn, user }) => <p>{loggedIn ? `Welcome ${user?.name}` : "Logged out"}</p>}
    </AuthState>
  );
}

The other libraries have the same two names:

tsx
import { AuthState, useUserSession } from "@hamur/auth/preact";

export function UserMenu() {
  const { loggedIn, user, clear } = useUserSession();
  return loggedIn ? (
    <button type="button" onClick={() => void clear()}>
      Log out {user?.name}
    </button>
  ) : (
    <a href="/login">Log in</a>
  );
}

export function Welcome() {
  return (
    <AuthState placeholder={<p>Loading session</p>}>
      {({ loggedIn, user }) => <p>{loggedIn ? `Welcome ${user?.name}` : "Logged out"}</p>}
    </AuthState>
  );
}
tsx
import { AuthState, useUserSession } from "@hamur/auth/solid";

export function UserMenu() {
  const { loggedIn, user, clear } = useUserSession();
  return (
    <div>
      {loggedIn() ? (
        <button type="button" onClick={() => void clear()}>
          Log out {user()?.name}
        </button>
      ) : (
        <a href="/login">Log in</a>
      )}
    </div>
  );
}

export function Welcome() {
  return (
    <AuthState placeholder={<p>Loading session</p>}>
      {({ loggedIn, user }) => <p>{loggedIn ? `Welcome ${user?.name}` : "Logged out"}</p>}
    </AuthState>
  );
}
vue
<script setup lang="ts">
import { AuthState, useUserSession } from "@hamur/auth/vue";

const { loggedIn, user, clear } = useUserSession();
</script>

<template>
  <button v-if="loggedIn" type="button" @click="clear()">Log out {{ user?.name }}</button>
  <a v-else href="/login">Log in</a>
  <AuthState>
    <template #placeholder><p>Loading session</p></template>
    <template #default="state"><p>{{ state.loggedIn ? `Welcome ${state.user?.name}` : "Logged out" }}</p></template>
  </AuthState>
</template>
svelte
<script lang="ts">
  import { AuthState, useUserSession } from "@hamur/auth/svelte";

  const session = useUserSession();
</script>

{#if $session.loggedIn}
  <button type="button" onclick={() => session.clear()}>Log out {$session.user?.name}</button>
{:else}
  <a href="/login">Log in</a>
{/if}

<AuthState>
  {#snippet children({ loggedIn, user })}<p>{loggedIn ? `Welcome ${user?.name}` : "Logged out"}</p>{/snippet}
  {#snippet placeholder()}<p>Loading session</p>{/snippet}
</AuthState>

loadStrategy

auth.loadStrategy says where the session is read first:

Value
"server-first" (default)the server render reads it and puts it in the page payload, so the first paint and the hydration already know the user
"client-only"the server never reads it; the browser fetches it after hydration
"none"nothing is fetched on its own; the app calls fetch()

A page answered from a prerender, swr or cache route rule is shared by every visitor. Its render has no cookie, so even under "server-first" it reads no session, its HTML holds no user data, and its client fetches the session after hydration. AuthState shows the placeholder there until then.

Guards

Three things guard a user's pages and data, and only one of them guards data.

GuardWhereWhat it does
the auth and guest route middlewaremeta = { middleware: ["auth"] } of a pagesteers a navigation: auth sends a logged-out visitor to auth.redirect.login?redirect=<path>, guest sends a logged-in one away from the login page
requireUser in a request listmiddleware of defineServer, with a routerefuses the document request and a WebSocket upgrade: a logged-out page request is a 302 to the login page, anything else a 401
requireUser on a handlermiddleware or handlerMiddlewarerefuses every call to the data with a 401, whoever calls it

guest sends a logged-in visitor to the redirect query when it is an app path (it starts with one /, not // or /\), else to auth.redirect.home, so /login?redirect=https://evil.example lands on /. A route middleware runs in the browser, where a user can skip it, and so does a load: neither guards data. Put the check in the handler, as Sessions and security and Data security say. requireUser is one object that does all three jobs: it sets { user, session } on the context.

tsx
import { useState, type FormEvent } from "react";
import { useUserSession } from "@hamur/auth/react";
import { $fetch, navigateTo, type PageMeta } from "hamur/app";

export const meta = { middleware: ["guest"] } satisfies PageMeta;

export default function Login() {
  const session = useUserSession();
  const [error, setError] = useState("");

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    try {
      await $fetch("/auth/login", { method: "POST", body: { email: form.get("email"), password: form.get("password") } });
      await session.fetch();
      await navigateTo(location.pathname + location.search, { replace: true });
    } catch {
      setError("Wrong email or password");
    }
  }

  return (
    <main>
      <h1>Log in</h1>
      <form onSubmit={(event) => void submit(event)}>
        <input name="email" type="email" autoComplete="username" required />
        <input name="password" type="password" autoComplete="current-password" required />
        {error ? <p role="alert">{error}</p> : null}
        <button>Log in</button>
      </form>
      <a href="/auth/github?redirect=%2Faccount">Sign in with GitHub</a>
    </main>
  );
}

A role check

The role is checked where the data is read, in a middleware, never in a load: a load runs in the browser on a navigation and a user can skip it. requireAdmin reads the user that requireUser put on the context and throws a 403 for a visitor who is not an admin. It fails closed: no user is no admin.

ts
import type { User } from "@hamur/auth";
import { createError, defineMiddleware } from "hamur/server";

export const requireAdmin = defineMiddleware<{ user?: User }>(({ context }) => {
  if (context.user?.role !== "admin") throw createError({ status: 403, message: "Forbidden" });
});

List both on each handler, in this order. ctx.context.user is typed from the list, so a handler that leaves requireUser out does not compile:

ts
import { requireUser } from "@hamur/auth/middleware";
import { defineHandler } from "hamur/server";
import { requireAdmin } from "./guards.ts";
import { listUserRecords } from "./users.ts";

export const listUsers = defineHandler({
  method: "GET",
  middleware: [requireUser, requireAdmin],
  async handler(_, { context }) {
    const asked = context.user.id;
    return (await listUserRecords()).map(({ id, name, role }) => ({ id, name, role, you: id === asked }));
  },
});

A door whose every handler is for admins, a layer for example, lists the pair in handlerMiddleware. It runs around every handler that door exports, before the handler's own list, and an app that re-exports one of them cannot strip it:

ts
import { requireUser } from "@hamur/auth/middleware";
import { defineServer } from "hamur/server";
import { requireAdmin } from "./guards.ts";

export { listUsers } from "./admin.ts";

export default defineServer({ handlerMiddleware: [requireUser, requireAdmin] });

The app's door lists the same two in its request list for the documents under /admin, so a logged-out visitor is sent to the login page and a member gets a 403 before any page HTML:

ts
import { requireUser } from "@hamur/auth/middleware";
import { defineServer } from "hamur/server";
import { requireAdmin } from "./guards.ts";

export { listUsers } from "./admin.ts";
export { login, register } from "./login.ts";
export { logout } from "./logout.ts";

export default defineServer({
  middleware: [
    { route: "/account/**", handler: requireUser },
    { route: "/admin/**", handler: requireUser },
    { route: "/admin/**", handler: requireAdmin },
  ],
});

Passwords

hashPassword(password) writes one string format on every preset, $pbkdf2-sha256$i=600000$<salt>$<hash> (PBKDF2-HMAC-SHA-256 at the OWASP count, a random salt), so a hash made on one preset verifies on any other. verifyPassword(hash, password) compares in constant time and returns false for a string it cannot read. needsRehash(hash) is true for a hash with fewer iterations than configured, another algorithm than configured, a $scrypt$ string from nuxt-auth-utils, or a string it cannot read, and never for a stronger one. The login pattern is: verify, then hash again and store when needsRehash says so, then write the session. A password is hashed as UTF-8 of its NFC form and may be up to 4096 bytes.

The limit is a middleware in a file of its own, since a middleware cannot be declared in a handler file:

ts
import { defineMiddleware, getRequestIP, rateLimit } from "hamur/server";

export const attempts = defineMiddleware({
  server: rateLimit({
    limit: 5,
    window: 60,
    key: ({ event, input }) => `${getRequestIP(event) ?? "unknown"}|${String((input as { email?: unknown } | undefined)?.email ?? "").toLowerCase()}`,
  }),
});
ts
import { setUserSession } from "@hamur/auth/server";
import { createError, defineHandler, hashPassword, needsRehash, verifyPassword } from "hamur/server";
import { attempts } from "./attempts.ts";
import { schema } from "../forms/server/utils/schema.ts";
import { findUserByEmail, newHandle, savePasswordHash, saveUser } from "./users.ts";

const credentials = schema<{ email: string; password: string }>(
  { type: "object", properties: { email: { type: "string" }, password: { type: "string" } }, required: ["email", "password"] },
  (value) => {
    const { email, password } = (value ?? {}) as { email?: unknown; password?: unknown };
    return typeof email === "string" && email && typeof password === "string" && password
      ? { value: { email, password } }
      : { issues: [{ message: "Enter an email and a password" }] };
  },
);

let decoy: Promise<string> | undefined;

export const login = defineHandler({
  route: "/auth/login",
  method: "POST",
  middleware: [attempts],
  input: credentials,
  async handler({ email, password }, { event }) {
    const user = await findUserByEmail(email);
    const hash = user?.passwordHash ?? (await (decoy ??= hashPassword("not a password")));
    const valid = await verifyPassword(hash, password);
    if (!user?.passwordHash || !valid) throw createError({ status: 401, message: "Wrong email or password" });
    if (needsRehash(hash)) await savePasswordHash(user.id, await hashPassword(password));
    await setUserSession(event, { user: { id: user.id, name: user.name, role: user.role }, loggedInAt: Date.now() });
    return { ok: true };
  },
});

export const register = defineHandler({
  route: "/auth/register",
  method: "POST",
  middleware: [attempts],
  input: credentials,
  async handler({ email, password }, { event }) {
    if (await findUserByEmail(email)) throw createError({ status: 409, message: "That email is taken" });
    const user = { id: crypto.randomUUID(), email, name: email.split("@")[0]!, role: "member" as const, handle: newHandle(), passwordHash: await hashPassword(password) };
    await saveUser(user);
    await setUserSession(event, { user: { id: user.id, name: user.name, role: user.role }, loggedInAt: Date.now() });
    return { ok: true };
  },
});

Three details of the sample matter:

  • rateLimit on the login handler. Each attempt costs a hash, and anyone can start one. The key is the address and the email together, so one address cannot lock out an account for everybody, and an attacker is counted per account. The step runs before the input is checked. Sessions and security has the options and the storage a limit across instances needs.
  • The decoy hash. A login for an unknown address verifies against a hash made for the purpose, so the answer takes the same time and says the same thing, Wrong email or password, whether or not the account exists.
  • A user without a password (one that signed up with OAuth) has no passwordHash and cannot log in with one.

To use Argon2id on the bun preset, set server.passwordHash. Hashes of the two algorithms verify side by side, and needsRehash moves the old ones over at their next login:

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  preset: "bun",
  server: { passwordHash: { algorithm: "argon2id" } },
});

server.passwordHash.iterations raises the PBKDF2 count (600 000 to 10 000 000).

On Cloudflare Workers. Workers refuse more than 100 000 PBKDF2 iterations in Web Crypto, so on the cloudflare presets Hamur computes the same function in JavaScript, and a hash costs CPU time on every login and every sign-up. The measured wall-clock time of one verify at 600 000 iterations under a local workerd was about 0.6 s (median of 20 requests, 2026-09-01). A Workers Free plan, with 10 ms of CPU per request, cannot hash or verify a password at this count, with any implementation. Use a Workers Paid plan, whose default CPU limit is 30 s per request, and raise limits.cpu_ms in the wrangler config if the CPU time your Worker reports for a login comes near it. The iteration count is not lowered on any preset. Where the plan does not fit, sign users in with OAuth or passkeys, which hash nothing.

OAuth

oauth<Provider>(options) is the body of a raw GET handler. A request without code or error starts the flow and redirects to the provider with PKCE and a random state. The provider returns to the same route, and the handler exchanges the code, fetches the profile and calls your onSuccess(event, { user, tokens }). What onSuccess returns is the answer, and undefined redirects to auth.redirect.home. The callback URL is the route itself, so register https://<your host>/auth/github with the provider and set redirectURL in production, since the default comes from the request.

The flow's state and verifier live in the cookie __Host-hamur-oauth-<h>, sealed with the app key, HttpOnly, Secure, for ten minutes and never with a Domain, so a sibling subdomain cannot plant a flow of its own. A missing or wrong state is a 400 Invalid OAuth state. Two flows started in two tabs share one cookie, and the earlier one ends with that error.

The id and secret of each provider come from the call, then auth.oauth.<name>, then the runtime config. The module declares oauth<Name>ClientId and oauth<Name>ClientSecret for every provider, so HAMUR_OAUTH_GITHUB_CLIENT_ID and HAMUR_OAUTH_GITHUB_CLIENT_SECRET set them at run time and no secret goes into the repository. A required key that is missing throws when the handler is defined (@hamur/auth: oauthAuth0 needs auth.oauth.auth0.domain).

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  modules: ["@hamur/auth"],
  auth: {
    oauth: {
      github: { redirectURL: "https://app.example/auth/github" },
      microsoft: { tenant: "organizations" },
      auth0: { domain: "example.eu.auth0.com" },
    },
  },
});

Sign in with GitHub, and the redirect query

A login link says where to go afterwards: /auth/github?redirect=/account. That value comes from the address bar, so it is an input of the attacker. The sample below checks it twice, as an app path (one /, not followed by / or \, no control character) when it is stored and again when it is used, and falls back to /. A target on another site is dropped. The target waits in a signed cookie, which the browser cannot forge and the flow cookie does not carry.

ts
import { oauthGitHub, setUserSession } from "@hamur/auth/server";
import { defineHandler, deleteCookie, getQuery, getSignedCookie, sendRedirect, setCookie } from "hamur/server";

const NEXT = "login-next";

const isAppPath = (path: unknown): path is string => typeof path === "string" && /^\/(?![/\\])/.test(path) && !/[\x00-\x1f\x7f]/.test(path);

const github = oauthGitHub({
  async onSuccess(event, { user, tokens }) {
    await setUserSession(event, {
      user: { id: String(user.id), name: String(user.login), role: "member" },
      secure: { accessToken: tokens.access_token },
      loggedInAt: Date.now(),
    });
    const next = await getSignedCookie(event, NEXT);
    deleteCookie(event, NEXT);
    return sendRedirect(event, isAppPath(next) ? next : "/");
  },
});

export const githubLogin = defineHandler({
  route: "/auth/github",
  method: "GET",
  raw: true,
  handler(input, ctx) {
    const { code, error, redirect } = getQuery(ctx.event);
    if (code === undefined && error === undefined) {
      setCookie(ctx.event, NEXT, isAppPath(redirect) ? redirect : "/", { signed: true, httpOnly: true, secure: true, sameSite: "lax", maxAge: 600 });
    }
    return github(input, ctx);
  },
});

Every provider

The presets below fill in the provider's URLs, default scopes and how it wants the client authenticated. Pass scope to replace the scopes. user is the profile as the provider sends it, taken out of its envelope where it has one. A key marked required throws when the handler is defined, until it is set.

Exportauth.oauth.<name>Keys besides clientId and clientSecretDefault scopes
oauthGitHubgithubnonenone
oauthGooglegooglenoneopenid email profile
oauthMicrosoftmicrosofttenant (default common)User.Read
oauthAppleappleteamId, keyId, privateKey (a secret, default { runtimeConfig: "oauthApplePrivateKey" }); no clientSecretname email
oauthDiscorddiscordnoneidentify email
oauthGitLabgitlabbaseURL (default https://gitlab.com)read_user
oauthAtlassianatlassiannoneread:me
oauthAuth0auth0domain (required)openid profile email
oauthAuthentikauthentikdomain (required)openid profile email
oauthBattleDotNetbattledotnetnoneopenid
oauthBoxboxnonenone
oauthDropboxdropboxnoneaccount_info.read
oauthFacebookfacebooknonepublic_profile email
oauthGiteagiteabaseURL (default https://gitea.com)read:user
oauthHerokuherokunoneidentity
oauthKeycloakkeycloakserverURL, realm (required)openid
oauthKickkicknoneuser:read
oauthLinelinenoneopenid profile
oauthLinearlinearnoneread
oauthLinkedInlinkedinnoneopenid profile email
oauthMastodonmastodonbaseURL (default https://mastodon.social)read:accounts
oauthOktaoktadomain (required)openid profile email
oauthOryorydomain (required)openid email
oauthOsuosunoneidentify
oauthPayPalpaypalnoneopenid profile email
oauthPolarpolarnoneopenid email
oauthRiotGamesriotgamesnoneopenid
oauthRobloxrobloxnoneopenid profile
oauthSalesforcesalesforcebaseURL (default https://login.salesforce.com)openid profile email
oauthSeznamseznamnoneidentity
oauthSlackslacknoneopenid email profile
oauthSpotifyspotifynoneuser-read-email
oauthTwitchtwitchnoneuser:read:email
oauthXxnoneusers.read tweet.read
oauthYandexyandexnonelogin:info login:email
oauthZendeskzendesksubdomain (required)read
oauthZitadelzitadeldomain (required)openid profile email
oauthAzureB2Cazureb2ctenant, policy (required)openid offline_access
oauthCloudflarecloudflareteamName (required), clientId as text (required; it is part of the URLs)openid email profile
oauthCognitocognitodomain (required)openid email profile
oauthHubSpothubspotnoneoauth
oauthInstagraminstagramnoneinstagram_business_basic
oauthLiveChatlivechatnonenone
oauthShopifyCustomershopifyCustomershopId (required)openid email customer-account-api:full
oauthStravastravanoneread (sent comma-joined)
oauthTikToktiktokthe client id is the client keyuser.info.basic (sent comma-joined)
oauthVKvkno clientSecret (VK ID, a public client)vkid.personal_info email
oauthWeChatwechatthe client id is the AppIDsnsapi_login
oauthWorkOSworkosnonenone; provider=authkit
oauthXsuaaxsuaadomain (required)openid

oauthSteam is OpenID 2.0, not OAuth, and takes no client id; its user is { steamId, claimedId }. The variable of each provider and the answer of each failure are in the reference.

Apple posts its callback to your route, from another site. Declare the route with method: "*". The module adds the originCheck rule that lets https://appleid.apple.com post there, for a route without a parameter whose handler is written handler: oauthApple({ … }) with oauthApple imported by name. Write the rule yourself for any other shape; without it the start throws an error that names the rule. oauthApple takes teamId, keyId and privateKey (the .p8 file) instead of a secret and signs the client secret itself.

ts
import { oauthAtproto, oauthAuth0, oauthGoogle, oauthOIDC, setUserSession } from "@hamur/auth/server";
import { defineHandler, useStorage } from "hamur/server";

export const google = defineHandler({
  route: "/auth/google",
  method: "GET",
  raw: true,
  handler: oauthGoogle({
    async onSuccess(event, { user }) {
      await setUserSession(event, { user: { id: String(user.sub), name: String(user.name), role: "member" } });
    },
  }),
});

export const auth0 = defineHandler({
  route: "/auth/auth0",
  method: "GET",
  raw: true,
  handler: oauthAuth0({
    async onSuccess(event, { user }) {
      await setUserSession(event, { user: { id: String(user.sub), name: String(user.name), role: "member" } });
    },
  }),
});

export const sso = defineHandler({
  route: "/auth/sso",
  method: "GET",
  raw: true,
  handler: oauthOIDC({
    issuer: "https://idp.example",
    clientId: { runtimeConfig: "ssoClientId" },
    clientSecret: { runtimeConfig: "ssoClientSecret" },
    async onSuccess(event, { user }) {
      await setUserSession(event, { user: { id: user.sub ?? "", name: String(user.name ?? user.email), role: "member" } });
    },
  }),
});

export const bluesky = defineHandler({
  route: "/auth/bluesky",
  method: "GET",
  raw: true,
  handler: oauthAtproto({
    clientMetadata: { client_name: "Example" },
    async onSuccess(event, { did, handle, tokens, dpopKey }) {
      await setUserSession(event, { user: { id: did, name: handle, role: "member" } });
      await useStorage("atproto").setItem(did, { accessToken: tokens.access_token, dpopKey });
    },
  }),
});

OpenID Connect

oauthOIDC({ issuer, clientId, clientSecret?, onSuccess }) signs in with any OpenID Connect provider. It reads the provider's discovery document (<issuer>/.well-known/openid-configuration, kept for an hour), runs the same flow with a nonce, and verifies the ID token before onSuccess: its signature against the provider's keys, iss, aud, azp, exp, iat, sub and nonce. user is the ID token's claims. A failure is a 401 Invalid ID token: <claim>. Without clientSecret the client is public and relies on PKCE alone. sso in the sample above is a complete call.

AT Protocol

oauthAtproto({ onSuccess }) signs in with a Bluesky or other AT Protocol account. The start takes ?handle= and resolves it to a DID, a server and its authorization server; the tokens are bound to a key made for this sign-in, and onSuccess gets it as dpopKey beside did, handle and tokens. Store the key with the tokens: every request made with them needs a proof signed with it, so treat the pair as a secret, in an encrypt storage mount for example. When a route of your app is an oauthAtproto call, the module serves <baseURL>_hamur/auth/atproto/client-metadata.json, whose URL is the client_id, so write the route literally (no :parameter).

The handle is the user's input, so every host Hamur looks up is checked first: a domain name, https on the default port, no redirect, an answer within 5 s and 64 KB, and on the bun, node, vercel and netlify presets no private or reserved address. Any failure is a 400 AT Protocol handle could not be resolved.

Passkeys

webAuthnRegister and webAuthnAuthenticate are the body of a raw POST handler each. They take JSON in two steps. { step: "options" } answers the options for the browser, and { step: "verify", response } verifies the credential and calls onSuccess. On the page, useWebAuthn({ registerEndpoint, authenticateEndpoint }) of the library's auth entry makes both calls and passes the browser's answer between them: register({ userName, displayName }) and authenticate(userName?). isSupported is false on the server and on the first client render, so hydration agrees, then the browser's answer. Neither call touches the session store: call useUserSession().fetch() after one resolves.

rpID is required. Set auth.webauthn.rpID to the host the passkeys belong to (example.com; each origin in origins must be it or below it). Without it the relying party is the request's host, and only a host that a server.allowedHosts list names is accepted, so a built server whose app has these handlers and neither setting does not start. A passkey made for one rpID never works for another, so choose it once.

validateUser must tie an existing userName to the logged-in user. The userName in the request comes from the browser. Without a check, anyone could register a passkey for somebody else's name and then sign in as them. getUserHandle and excludeCredentials are therefore called only after validateUser returned, and for a name that exists it must throw unless the request's session is that account. getUserHandle without validateUser throws when the handler is made. The handle that onSuccess gets comes from the sealed challenge, never from the browser.

ts
import { getUserSession, setUserSession, webAuthnAuthenticate, webAuthnRegister } from "@hamur/auth/server";
import { createError, defineHandler } from "hamur/server";
import { findCredential, findUserByHandle, findUserByName, saveCredential, saveUser } from "./users.ts";

export const passkeyRegister = defineHandler({
  route: "/auth/passkey/register",
  method: "POST",
  raw: true,
  handler: webAuthnRegister({
    userVerification: "required",
    async validateUser(user, event) {
      const existing = await findUserByName(user.userName);
      if (existing && (await getUserSession(event)).user?.name !== existing.name) throw createError({ status: 401, message: "Sign in to add a passkey" });
    },
    getUserHandle: async (_event, userName) => (await findUserByName(userName))?.handle,
    async onSuccess(event, { credential, user }) {
      await saveCredential(credential);
      const existing = await findUserByHandle(user.userHandle);
      const record = existing ?? { id: crypto.randomUUID(), email: `${user.userName}@passkey.invalid`, name: user.userName, role: "member" as const, handle: user.userHandle };
      if (!existing) await saveUser(record);
      await setUserSession(event, { user: { id: record.id, name: record.name, role: record.role }, loggedInAt: Date.now() });
    },
  }),
});

export const passkeyLogin = defineHandler({
  route: "/auth/passkey/login",
  method: "POST",
  raw: true,
  handler: webAuthnAuthenticate({
    userVerification: "required",
    getCredential: (_event, id) => findCredential(id),
    async onSuccess(event, { credential, counter, backedUp }) {
      Object.assign(credential, { counter, backedUp });
      const user = await findUserByHandle(credential.userHandle);
      if (!user) throw createError({ status: 401, message: "Unknown passkey" });
      await setUserSession(event, { user: { id: user.id, name: user.name, role: user.role }, loggedInAt: Date.now() });
    },
  }),
});
tsx
import { useState } from "react";
import { useUserSession, useWebAuthn } from "@hamur/auth/react";

export default function Passkey() {
  const passkey = useWebAuthn({ registerEndpoint: "/auth/passkey/register", authenticateEndpoint: "/auth/passkey/login" });
  const session = useUserSession();
  const [status, setStatus] = useState("");

  async function run(call: () => Promise<unknown>) {
    try {
      await call();
      await session.fetch();
      setStatus("Done");
    } catch (error) {
      setStatus(`Failed: ${(error as Error).message}`);
    }
  }

  if (!passkey.isSupported) return <p>This browser cannot use passkeys.</p>;
  return (
    <main>
      <h1>Passkeys</h1>
      <button type="button" onClick={() => void run(() => passkey.authenticate())}>
        Sign in with a passkey
      </button>
      <button type="button" onClick={() => void run(() => passkey.register({ userName: session.user?.name ?? "ada", displayName: "Ada" }))}>
        Add a passkey
      </button>
      <p>{status}</p>
    </main>
  );
}

Each challenge verifies once: the verify step counts it on the session storage mount, so a captured cookie and response cannot be replayed. The mount must give an atomic increment: redis, db or sqlite without encrypt, or memory or fs on bun and node, which count in one process only (the server logs a warning at start; run one process, or use redis). The build fails for cloudflare-kv, the default on Cloudflare, and for an encrypted mount; mount storage.session on db over D1 there. Store counter and backedUp from sign-in's onSuccess in the credential, as the sample does, and keep the credential id unique. Verification failures answer 400 WebAuthn verification failed: <check>, naming the first check that failed.

createAuthToken(event, { purpose, data, ttl? }) seals data into a token that is safe in a URL, for one purpose and ttl seconds (default 900). consumeAuthToken(event, token, purpose) returns the data once. A token that is malformed, changed, expired, used, or made for another purpose throws the same 400 Token expired or already used, so the answer tells an attacker nothing. A verify-email token does not open as magic-link. Hamur sends no mail: you pass the link to your own mailer.

ts
import { useRuntimeConfig } from "hamur/server";

export async function sendMail(to: string, subject: string, text: string): Promise<void> {
  const { mailApiKey } = useRuntimeConfig() as { mailApiKey?: string };
  const response = await fetch("https://mail.example/v1/send", {
    method: "POST",
    headers: { authorization: `Bearer ${mailApiKey ?? ""}`, "content-type": "application/json" },
    body: JSON.stringify({ from: "login@app.example", to, subject, text }),
  });
  if (!response.ok) throw new Error(`mail provider answered ${response.status}`);
}

The recipe has three handlers:

  1. sendLink looks the address up, creates a token holding the user id and the page to go to, and mails the link. It answers { sent: true } whether or not the address has an account, so it cannot be used to find out who is registered. It checks next as an app path before sealing it, so the link cannot send the user to another site. The link is built from a fixed origin, never from the request's Host header, which whoever sends the request chooses: a link built from it would let an attacker mail a victim a link to the attacker's own site.
  2. confirmLink, a GET, shows a page with a button. It never consumes the token.
  3. consumeLink, the POST of that button, consumes the token and writes the session.

Consume on the POST, never on the link's GET. consumeAuthToken spends the token before it returns, and mail scanners and link previews (Outlook Safe Links, Gmail, Slack) fetch every link in a message. A GET that consumes would spend the token before the user clicks it. The confirm page copies the token into a hidden field only when it looks like a token, so no raw query text is written into the page, and sends no-store and no-referrer.

ts
import { consumeAuthToken, createAuthToken, setUserSession } from "@hamur/auth/server";
import { defineHandler, getQuery, getRequestURL, readFormData } from "hamur/server";
import { sendMail } from "./mailer.ts";
import { findUserByEmail, listUserRecords } from "./users.ts";

const isAppPath = (path: unknown): path is string => typeof path === "string" && /^\/(?![/\\])/.test(path) && !/[\x00-\x1f\x7f]/.test(path);

const ORIGIN = "https://app.example";

const TOKEN = /^[\w.-]{1,4096}$/;

export const sendLink = defineHandler({
  route: "/auth/link/send",
  method: "POST",
  async handler({ email, next }: { email: string; next?: string }, { event }) {
    const user = await findUserByEmail(email);
    if (user) {
      const token = await createAuthToken(event, { purpose: "magic-link", data: { userId: user.id, next: isAppPath(next) ? next : "/" } });
      await sendMail(user.email, "Your sign-in link", `Sign in: ${ORIGIN}/auth/link?token=${encodeURIComponent(token)}`);
    }
    return { sent: true };
  },
});

export const confirmLink = defineHandler({
  route: "/auth/link",
  method: "GET",
  raw: true,
  handler(_, { event }) {
    const token = String(getQuery(event).token ?? "");
    const field = TOKEN.test(token) ? token : "";
    return new Response(`<!doctype html><form method="post"><input type="hidden" name="token" value="${field}"><button>Sign in</button></form>`, {
      headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer" },
    });
  },
});

export const consumeLink = defineHandler({
  route: "/auth/link",
  method: "POST",
  raw: true,
  async handler(_, { event }) {
    const token = String((await readFormData(event)).get("token") ?? "");
    const { userId, next } = await consumeAuthToken<{ userId: string; next: string }>(event, token, "magic-link");
    const user = (await listUserRecords()).find((record) => record.id === userId);
    if (!user) return new Response("Unknown user", { status: 400 });
    await setUserSession(event, { user: { id: user.id, name: user.name, role: user.role }, loggedInAt: Date.now() });
    return Response.redirect(new URL(next, getRequestURL(event)), 303);
  },
});

Seal the user id or the address to verify in data; never read either from the link's query. The single-use count has the same storage rule as passkeys: the session mount needs an atomic increment, and without a suitable mount the build fails with a message that names the mount.

Logout and cached pages

logout calls clearUserSession(event), which runs auth:session:clear, empties the session and deletes the cookie. In the browser, useUserSession().clear() sends DELETE <baseURL>_hamur/auth/session and shows the logged-out state. That endpoint is under the origin check, so another site cannot log a user out.

ts
import { clearUserSession } from "@hamur/auth/server";
import { defineHandler } from "hamur/server";

export const logout = defineHandler({
  route: "/auth/logout",
  method: "POST",
  async handler(_, { event }) {
    await clearUserSession(event);
    return { ok: true };
  },
});

A page for a logged-in visitor is never shared. A render that read a session answers Cache-Control: private, no-store with Vary: Cookie, whatever the route rule says, and the session endpoint answers the same. A page under a prerender, swr or cache rule is rendered once for everybody on a cache fork that carries no cookie unless varies names it (Storage and cache), so the module treats it as anonymous: it reads no session, the page holds no user data and a logout has nothing to remove from it. After clear(), the placeholder and the logged-out state are what such a page shows. Put what only a user may see on a page that is not cached, or fetch it from a handler after hydration.

One session on several subdomains

Two apps on app.example.com and api.example.com can share one login. Set the cookie's domain to the parent, give both apps the same name and the same key (HAMUR_KEY, or the same auth.session.password), and keep the other session options equal. A cookie with a domain is not a __Host- cookie, so the name becomes hamur-auth.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  modules: ["@hamur/auth"],
  auth: {
    session: {
      name: "hamur-auth",
      cookie: { domain: "example.com" },
    },
  },
});

Every subdomain can then plant a session cookie too. The __Host- protection is gone, so a page on any subdomain, including one you forgot, can sign a visitor in to an account of the attacker's. Share a session only when you trust every subdomain and whatever content they serve.

On the server, the request-bound $fetch (useFetch, a loader's ctx.fetch) forwards the request's cookie and authorization headers to your own app and to no other origin. A call to the sibling app is a call to another origin, so the cookie is forwarded by hand, and only the session cookie, not the visitor's others:

ts
import { $fetch, defineHandler, getRequestHeader } from "hamur/server";

const SESSION_COOKIE = /^hamur-auth(\.\d+)?=/;

export const billing = defineHandler({
  method: "GET",
  async handler(_, { event }) {
    const cookie = (getRequestHeader(event, "cookie") ?? "").split(/;\s*/).filter((pair) => SESSION_COOKIE.test(pair)).join("; ");
    return $fetch<{ plan: string }>("https://api.example.com/billing", { headers: cookie ? { cookie } : {} });
  },
});

In the browser, fetch(url, { credentials: "include" }) sends the cookie to the sibling, which must answer with CORS headers that allow the page's origin and credentials (CORS shows ^https: patterns).

Sessions and security has the core: sessions, CSRF, rate limits, CSP and the rest. Data security shows how to keep what a handler returns small. The @hamur/auth reference lists every export, option and error message.