Skip to content

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

@hamur/auth

The first-party auth module. Add it to modules and set its options under the auth config key. It keeps the signed-in user in a session on core useSession, answers that session at <baseURL>_hamur/auth/session, and lets server plugins add to it or reject it.

ts
// hamur.config.ts
export default defineConfig({
  modules: ["@hamur/auth"],
  auth: { session: { maxAge: 60 * 60 * 24 * 30, storage: "session" } },
});

default

The module, as defineModule({ meta: { name: "auth", configKey: "auth" } }). Its setup checks the options (a wrong value is a build error naming the key), refuses @hamur/auth/server in client code, adds the session endpoint and its hooks, and checks auth.session.storage against the mounts of the build's preset.

The session is sealed with the app key HAMUR_KEY. A built server without one does not start: @hamur/auth needs HAMUR_KEY (run hamur create-key --env, or set it in the deployment). On cloudflare, vercel and netlify, where the server plugins run at the first request, that request answers the error. Under hamur dev, with no HAMUR_KEY in the environment and no line of <rootDir>/.env that sets it to a value, the module writes a new key to .env (in place of an empty HAMUR_KEY=, else appended) and logs Wrote HAMUR_KEY to .env once; when git does not ignore .env it also warns .env holds HAMUR_KEY and is not ignored by git; add .env to .gitignore. auth.session.password replaces the app key for the user session only (the check at start is then skipped).

AuthConfig, AuthSessionConfig, AuthLoadStrategy

ts
interface AuthConfig {
  session?: {
    name?: string;                 // default "__Host-hamur-auth", else "hamur-auth"
    password?: Secret;             // default the app key HAMUR_KEY
    maxAge?: number;               // default 604800 (7 days)
    idleTimeout?: number;
    storage?: string | false;      // a storage mount; default false, the sealed cookie
    cookie?: Omit<CookieOptions, "maxAge" | "expires">;
  };
  loadStrategy?: "server-first" | "client-only" | "none";  // AuthLoadStrategy, default "server-first"
  redirect?: { login?: string; home?: string };             // defaults "/login", "/"
  oauth?: { [provider: string]: { clientId?: Secret; clientSecret?: Secret; redirectURL?: string; [key: string]: Secret | undefined } };
  webauthn?: { rpID?: string; rpName?: string; origins?: string[] };
}

The options are those of useSession. maxAge and idleTimeout are whole seconds of at least 1: auth.session.maxAge must be a positive integer of seconds (got "7d"). password is a string of at least 32 characters or { runtimeConfig: "<key>" }; a literal logs auth.session.password is a literal in the config file, which ends up in the repository; use { runtimeConfig: "<key>" } at build. cookie values are checked as well (auth.session.cookie.sameSite must be "lax", "strict" or "none" (got "Loose")), and sameSite: "none" with secure: false fails. An unknown key fails with auth.session has no "ttl" (it takes: name, password, maxAge, idleTimeout, storage, cookie).

The cookie is named __Host-hamur-auth when cookie keeps secure, path "/" and no domain (the defaults), else hamur-auth; a given name is used as written. A browser refuses a __Host- cookie from anyone but the host itself, so a page on a sibling subdomain cannot plant its own session cookie and sign a visitor in to the attacker's account. cookie.domain shares the session with every subdomain, and every subdomain can then plant one too: set it only when you trust every subdomain and whatever content they serve. A __Host- name with such a cookie fails the build: auth.session.name "__Host-sid" needs auth.session.cookie with secure, path "/" and no domain. A session larger than one cookie is split into __Host-hamur-auth.0 and .1; with storage the data is kept under __Host-hamur-auth:<id>.

loadStrategy says where useUserSession gets the session first. "server-first" reads it in the server render and sends it in the page's payload, so the first paint and the hydration already know the user; "client-only" never reads it on the server and fetches it after hydration; "none" never fetches on its own, the app calls fetch(). Another value fails: auth.loadStrategy must be "server-first", "client-only" or "none" (got "lazy"). A page answered from a prerender, swr or cache route rule is shared by every visitor and its render has no cookie, so even under "server-first" it reads no session and its client fetches after hydration; such a page shows AuthState's placeholder and no user data in its HTML.

redirect.login is where requireUser and the auth route middleware send a logged-out visitor, redirect.home where guest sends a logged-in one. Both are app paths without a query or a hash, under baseURL like any redirect(): auth.redirect.login must be an app path such as "/login" (got "https://x"), auth.redirect.login must be a path without a query or a hash (got "/sign-in?from=app").

storage names a mount the build must resolve on its preset: a storage.<name> of the config, or session where the preset gives it a default (fs on bun, node and static and under hamur dev, cloudflare-kv on cloudflare with a kv_namespaces entry of binding SESSION). Otherwise the build fails: auth.session.storage "session" has no mount on the vercel preset; set storage.session, and on cloudflare …; add a kv_namespaces entry with binding "SESSION" to the wrangler config, or set storage.session.

webauthn is the relying party of the passkey handlers: rpID the host the passkeys belong to (each of origins must be it or below it: auth.webauthn.rpID "example.com" is not the host or a parent domain of origin "https://other.example"), rpName the name the browser shows (default the rpID), origins where a response may come from (default https://<rpID>).

Route middleware auth and guest

The module adds two route middleware; an app file app/middleware/auth.ts or guest.ts replaces the module's.

ts
export const meta = { middleware: ["auth"] };   // app/pages/admin.tsx
export const meta = { middleware: ["guest"] };  // app/pages/login.tsx

auth sends a logged-out navigation to auth.redirect.login with ?redirect=<the app path asked for> (/login?redirect=%2Fadmin). guest sends a logged-in navigation to the redirect query when it is an app path (it starts with one / not followed by / or \, and has no control character), else to auth.redirect.home, so /login?redirect=https://evil.example lands on /. Both read the store of useUserSession; in the browser, when the session was not read yet, they fetch it first; a failed fetch fails the navigation with its error. In the server render they decide only when the render read the session ("server-first", a page under no prerender, swr or cache rule). They steer navigation and protect no data: guard the data with requireUser. After a login, the page calls fetch() and navigates to its own URL again; guest then sends it on.

ts
const session = useUserSession();
async function login() {
  await $fetch("/login", { method: "POST", body: form });
  await session.fetch();
  await navigateTo(route.fullPath, { replace: true });
}

User, UserSession, SecureSessionData, UserSessionData, PublicUserSession

ts
declare module "@hamur/auth" {
  interface User { name: string }
  interface UserSession { loggedInAt: number }
  interface SecureSessionData { accessToken: string }
}
type UserSessionData = UserSession & { user?: User; secure?: SecureSessionData };
type PublicUserSession = Omit<UserSessionData, "secure">;

An app types its session by augmenting the three empty interfaces. secure never leaves the server: the session endpoint answers PublicUserSession, without secure and without the session id.

auth:session:fetch, auth:session:clear

Server hooks, typed on ServerHooks:

ts
"auth:session:fetch": (session: PublicUserSession, event: HamurEvent) => void | Promise<void>;
"auth:session:clear": (session: UserSessionData & { id: string }, event: HamurEvent) => void | Promise<void>;

auth:session:fetch runs before GET <baseURL>_hamur/auth/session answers a session that has keys; a plugin may add fields to session, and an error it throws is the answer (createError({ status: 403, message: "Banned" }) answers 403). auth:session:clear runs in clearUserSession, before the session is cleared, with its id, so an app that keeps an index of sessions by user can drop it.

ts
export default definePlugin((server) => {
  server.hooks.hook("auth:session:fetch", async (session) => {
    if (session.user) session.roles = await rolesOf(session.user);
  });
});

<baseURL>_hamur/auth/session

GET answers the public session as JSON ({} when there is none), with cache-control: private, no-store and Vary: Cookie. DELETE calls clearUserSession and answers 204 with the cookie deleted. DELETE is under the origin check: a cross-site request answers 403 Cross-origin request blocked, so another site cannot log a user out.

@hamur/auth/server

Each function runs on core useSession with the auth.session options, so a request has one user session.

getUserSession, UserSessionData

ts
function getUserSession(event: HamurEvent): Promise<UserSessionData & { id: string }>

The session's data and its id; { id } alone when there is none.

setUserSession

ts
function setUserSession(event: HamurEvent, data: Partial<UserSessionData>): Promise<UserSessionData>

Merges data deeply into the session: plain objects merge by key, arrays and other values replace. When the write changes user (key order aside), the session gets a new id in the same write, so the id after a login or a privilege change is never the one before it.

The user session is read-only in WebSocket hooks, which reach only the upgrade event after the socket opened: there setUserSession, replaceUserSession and clearUserSession throw @hamur/auth: the user session is read-only in WebSocket hooks; write it in an HTTP request. A request step before the upgrade can still write.

replaceUserSession

ts
function replaceUserSession(event: HamurEvent, data: UserSessionData): Promise<UserSessionData>

Writes data as the whole session (keys it does not hold are dropped), with a new id when user changed, so a data without user logs the user out. Calls made together in one request run one after another, each on what the one before wrote.

clearUserSession

ts
function clearUserSession(event: HamurEvent): Promise<void>

Calls the auth:session:clear hook, then clears the session and deletes its cookie.

requireUserSession

ts
function requireUserSession(event: HamurEvent, options?: { status?: number; message?: string }): Promise<UserSessionData & { user: User; id: string }>

The session when it has a user; otherwise throws createError({ status: 401, message: "Unauthorized" }), or the status and message given.

ts
export const login = defineHandler({
  method: "POST",
  async handler({ email, password }, { event }) {
    const user = await checkLogin(email, password);
    await setUserSession(event, { user: { name: user.name }, secure: { userId: user.id } });
  },
});

createAuthToken, consumeAuthToken, AuthTokenOptions

ts
function createAuthToken(event: HamurEvent, options: { purpose: string; data: unknown; ttl?: number }): Promise<string>
function consumeAuthToken<T = unknown>(event: HamurEvent, token: string, purpose: string): Promise<T>

Tokens for email verification and magic links. createAuthToken seals data (with the app key, so it cannot be read or changed) for one purpose (1 to 111 visible ASCII characters) and ttl seconds (a positive integer, default 900); the token is base64url with dots, safe in a URL. consumeAuthToken returns data once, and spends the token before it returns, so call it only when the request is ready to finish (on the POST, not the GET a link opens): a token that is malformed, changed, expired, already used or made for another purpose throws the same 400 Token expired or already used, so the answer tells nothing more. A verify-email token does not open as magic-link. A bad purpose or ttl is a TypeError.

Single use counts on the session storage mount (increment of auth-token:<id>), under the same rule as the passkey handlers: redis, db or sqlite without encrypt, or memory or fs on bun and node, where the server logs the one-process warning at start. An app with a server file that imports consumeAuthToken from @hamur/auth/server fails the build otherwise: @hamur/auth: single-use tokens need an atomic increment; the "session" mount uses cloudflare-kv on the cloudflare preset; mount storage.session on redis, db or sqlite (…; the "session" mount has encrypt, whose increment is not atomic; …), and without a mount @hamur/auth: consumeAuthToken needs the session storage mount for single-use tokens; set storage.session. A mount made at run time is checked at the first call (a 500 with the same message). On cloudflare, mount storage.session on db over D1.

Hamur sends no mail. A magic link, with your own mailer:

ts
// server/magic-link.ts, exported from server/index.ts
const isAppPath = (path: unknown): path is string => typeof path === "string" && /^\/(?![/\\])/.test(path) && !/[\x00-\x1f\x7f]/.test(path);

export const sendLink = defineHandler({
  method: "POST",
  async handler({ email, next }: { email: string; next?: string }, { event }) {
    const user = await users.byEmail(email);
    if (user) {
      const token = await createAuthToken(event, { purpose: "magic-link", data: { userId: user.id, next: isAppPath(next) ? next : "/" } });
      await mailer.send(user.email, `https://app.example/auth/link?token=${encodeURIComponent(token)}`);
    }
    return { sent: true };   // the same answer whether or not the address has an account
  },
});

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

export const confirmLink = defineHandler({
  route: "/auth/link", method: "GET", raw: true,
  handler(input, { event }) {
    const token = String(getQuery(event).token ?? "");
    const field = TOKEN.test(token) ? token : "";   // never write the raw query into the page
    return new Response(`<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 link = defineHandler({
  route: "/auth/link", method: "POST", raw: true,
  async handler(input, { event }) {
    const token = String((await readFormData(event)).get("token") ?? "");
    const { userId, next } = await consumeAuthToken<{ userId: string; next: string }>(event, token, "magic-link");
    await setUserSession(event, { user: { id: userId } });
    return Response.redirect(new URL(next, getRequestURL(event)), 303);
  },
});

Consume on a 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. So the link opens a page whose button posts the token, and the POST consumes it, once the handler is ready to finish the sign-in or the verification.

Keep next an app path (/ and then not / or \) before you seal it, so the link cannot send a user to another site; seal the user id or the address to verify in data, never read it from the link's query.

oauthHandler, OAuthHandlerOptions, OAuthTokens, OAuthError

ts
function oauthHandler(options: {
  authorizationURL: string; tokenURL: string; userURL?: string;
  clientId: Secret; clientSecret?: Secret;
  scope: string[];
  issuer?: string;
  tokenAuth?: "client_secret_basic" | "client_secret_post" | "none";   // default "client_secret_basic"
  responseMode?: "query" | "form_post";                                // default "query"
  pkce?: boolean;                                                      // default true
  authorizationParams?: Record<string, string>;
  redirectURL?: string;
  mapUser?(profile: unknown, tokens: OAuthTokens): unknown;
  onSuccess(event: HamurEvent, result: { user: unknown; tokens: OAuthTokens }): unknown;
  onError?(event: HamurEvent, error: OAuthError): unknown;
}): (input: unknown, ctx: HandlerContext) => Promise<unknown>

The OAuth 2 authorization-code flow with PKCE and state, as the body of a raw handler. The callback must be the same route as the start.

ts
// server/auth.ts, exported from server/index.ts
export const sso = defineHandler({
  route: "/auth/sso", method: "GET", raw: true,
  handler: oauthHandler({
    authorizationURL: "https://idp.example/authorize",
    tokenURL: "https://idp.example/token",
    userURL: "https://idp.example/userinfo",
    clientId: { runtimeConfig: "ssoClientId" },
    clientSecret: { runtimeConfig: "ssoClientSecret" },
    scope: ["openid", "email"],
    async onSuccess(event, { user }) {
      await setUserSession(event, { user: { email: (user as { email: string }).email } });
    },
  }),
});
  • Start, a request without code or error: 302 to authorizationURL with response_type=code, client_id, redirect_uri, scope (space-joined, left out when empty), a random state, and with pkce an S256 code_challenge. state and the verifier go in the cookie __Host-hamur-oauth-<h>, sealed with the app key, <h> the first 16 hex characters of the SHA-256 of the route's path (/auth/github is __Host-hamur-oauth-08cd8795e41c13e4): Max-Age=600; Path=/; HttpOnly; Secure; SameSite=Lax, never Domain, so a sibling subdomain cannot plant a flow of its own. Under hamur dev on plain http it is hamur-oauth-<h> without Secure.
  • redirect_uri is redirectURL, else the route's absolute URL from getRequestURL (so server.trustProxy applies). Set redirectURL in production.
  • Callback: the cookie is deleted on every answer. Only the cookie of the route's own name is read. A missing or wrong state, or a cookie from another route, answers 400 Invalid OAuth state. With issuer, the iss parameter must equal it, error callbacks included, else 400 OAuth issuer mismatch. A provider error calls onError(event, { error, description }), else answers 401 OAuth error: <error> (the code cut to letters, digits, _, . and -, at most 64; the description, without control characters and cut to 256, is logged, never sent). The code is then exchanged with the verifier, within 10 s for the headers and the body: no answer is 502 OAuth provider did not answer, a refusal or an answer without access_token is 401 OAuth token request failed. With userURL the profile is fetched with the access token, and mapUser shapes it. onSuccess's value is the answer; undefined redirects to auth.redirect.home.
  • tokenAuth: client_secret_basic sends authorization: Basic with the id and secret form-encoded first, so a secret holding :, + or % arrives intact; client_secret_post sends both in the body; none sends client_id only and needs pkce (TypeError: oauthHandler tokenAuth "none" needs pkce). The other two need clientSecret.
  • responseMode: "form_post": the provider posts the callback cross-site, so declare method: "*" (a GET starts, a POST is the callback) and list the provider's origin (that of authorizationURL) in the route rule originCheck.allow of the route. The cookie is then SameSite=None, which needs https under hamur dev too (set devServer.https; on plain http the start throws a TypeError saying so). A start that the origin check would refuse the provider's post to (no rule listing it, no cors rule, not in server.originCheck.allow, and the check not turned off) throws @hamur/auth: oauthHandler with responseMode "form_post" needs routeRules["/auth/sso"].originCheck.allow to list the provider's origin.
  • Two flows started in two tabs share one cookie, so the earlier one ends with 400 Invalid OAuth state.

OAuthTokens is the token answer as the provider sent it: { access_token, token_type, expires_in?, refresh_token?, scope?, id_token?, [key]: unknown }. OAuthError is { error: string; description?: string }.

oauthOIDC, OAuthOIDCOptions

ts
function oauthOIDC(options: {
  issuer: string;                            // an https URL
  clientId: Secret;
  clientSecret?: Secret;                     // without it the client is public: PKCE and no secret
  scope?: string[];                          // default ["openid", "profile", "email"]; "openid" is added when missing
  audiences?: string[];                      // audiences the ID token may name besides clientId; default none
  onSuccess(event: HamurEvent, result: { user: JWTPayload; tokens: OAuthTokens }): unknown;
  onError?(event: HamurEvent, error: OAuthError): unknown;
}): (input: unknown, ctx: HandlerContext) => Promise<unknown>

Sign-in with any OpenID Connect provider, as the body of a raw handler: oauthHandler with the provider's endpoints read from its discovery document and the ID token verified. user is the ID token's claims.

ts
// server/auth.ts, exported from server/index.ts
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: { sub: user.sub, email: user.email } });
    },
  }),
});
  • Discovery: <issuer>/.well-known/openid-configuration (a trailing / of the issuer dropped first), read only at the start and before the code exchange (a provider error reaches onError even while discovery is down), and kept in memory and in the cache storage mount for an hour, so two sign-ins, or many at once, fetch it once. Its issuer must equal the configured one exactly, else 502 OIDC discovery issuer mismatch. authorization_endpoint, token_endpoint and jwks_uri must be https URLs, the …_supported lists lists of strings, authorization_response_iss_parameter_supported a boolean, and the signing algorithms must name one Hamur verifies; any other document, or an answer that is not a 2xx JSON object, is 502 OIDC discovery failed, and no answer within 10 s is 502 OAuth provider did not answer.
  • Start: as oauthHandler, with PKCE and a random nonce kept in the flow cookie beside state. When the document says authorization_response_iss_parameter_supported: true, the callback needs iss equal to the issuer (400 OAuth issuer mismatch).
  • Client authentication: client_secret_basic when the document's token_endpoint_auth_methods_supported is absent or lists it, else client_secret_post when listed; without clientSecret, none when the list is absent or lists it. Otherwise 502 OIDC provider supports no client authentication Hamur offers.
  • ID token (OIDC Core §3.1.3.7), verified against jwks_uri with a 60 s clock tolerance: signed with an algorithm the document lists in id_token_signing_alg_values_supported (RS256 when the field is absent) other than an HMAC one; iss the issuer; aud holding clientId, every other audience in audiences; azp, when present, equal to clientId, and present when there is more than one audience; exp and iat present; sub a non-empty string; nonce the one the start sent. A failure answers 401 Invalid ID token: <claim>: malformed, alg, signature, exp, nbf, iss, aud, azp, iat, sub or nonce.

oauthAtproto, OAuthAtprotoOptions, AtprotoClientMetadata, AtprotoResult

ts
function oauthAtproto(options: {
  clientMetadata?: Partial<AtprotoClientMetadata>;   // fields of the served client metadata, e.g. client_name, logo_uri
  scope?: string[];                                  // default ["atproto"]; "atproto" is added when missing
  onSuccess(event: HamurEvent, result: { did: string; handle: string; tokens: OAuthTokens; dpopKey: JsonWebKey }): unknown;
  onError?(event: HamurEvent, error: OAuthError): unknown;
}): (input: unknown, ctx: HandlerContext) => Promise<unknown>

Sign-in with an AT Protocol (Bluesky) account, as the body of a raw GET handler. The start takes the handle as ?handle=, resolves it to a DID, its DID document, its PDS and the PDS's authorization server, sends a pushed authorization request with PKCE and a DPoP proof, and redirects there; the callback exchanges the code with a DPoP proof and calls onSuccess. The tokens are bound to dpopKey, a private ES256 JWK made for this sign-in: store it beside them, since every request with the tokens needs a proof signed with it.

ts
// server/auth.ts, exported from server/index.ts
export const bluesky = defineHandler({
  route: "/auth/bluesky", method: "GET", raw: true,
  handler: oauthAtproto({
    clientMetadata: { client_name: "My app" },
    async onSuccess(event, { did, handle }) {
      await setUserSession(event, { user: { did, handle } });
    },
  }),
});
  • Client metadata: when a route of the app is an oauthAtproto call, the module serves GET <baseURL>_hamur/auth/atproto/client-metadata.json, whose URL is the client_id: redirect_uris the URLs of those routes, scope every call's scopes, token_endpoint_auth_method: "none" and dpop_bound_access_tokens: true, with the calls' clientMetadata over the defaults (the first call wins a field; client_id and those two stay). A route with a parameter (/auth/:provider) is not listed, so write the route literally. Without such a route the URL answers 404.
  • Resolution: https://<handle>/.well-known/atproto-did (no DNS TXT lookup), the DID document from https://plc.directory/<did> or, for did:web, https://<host>/.well-known/did.json, whose alsoKnownAs must hold at://<handle> (else 401 AT Protocol handle does not match its DID), then the PDS's /.well-known/oauth-protected-resource and the authorization server's /.well-known/oauth-authorization-server, whose issuer must be its origin.
  • Every host is the user's input, so each request is checked first: the handle must be a domain name of at least two labels (no IP address, no port, no .local, .localhost, .arpa, .internal, .invalid, .onion, .alt or .example), every URL https: on the default port with such a host, no redirect is followed, and each answer must come within 5 s and 64 KB. On the bun, node, vercel and netlify presets the host is also looked up once, refused when any address is private, loopback, link-local, CGNAT, unique-local, multicast, reserved or a documentation range (IPv4 inside NAT64, 6to4 and IPv4-mapped addresses included), and the request connects to the address that was checked, so a DNS answer that changes in between is never used. On cloudflare there is no DNS API: the name rules are the only guard there. A URL from a remote document longer than 2048 characters also fails. Every such failure answers 400 AT Protocol handle could not be resolved; the reason is logged at debug and never sent.
  • DPoP: a use_dpop_nonce error is sent again once with the server's DPoP-Nonce. The callback needs iss equal to the authorization server (400 OAuth issuer mismatch), and the token answer's sub must be the DID (401 AT Protocol handle does not match its DID); a refused token request, or a token answer whose token_type is not DPoP or whose scope lacks atproto, is 401 OAuth token request failed.

oauthGitHub, oauthGoogle, … the provider presets, OAuthPresetOptions

ts
function oauthGitHub(options: {
  onSuccess(event: HamurEvent, result: { user: Record<string, unknown>; tokens: OAuthTokens }): unknown;
  onError?(event: HamurEvent, error: OAuthError): unknown;
  scope?: string[];                          // replaces the provider's default scopes
  authorizationParams?: Record<string, string>;
  redirectURL?: string;
  clientId?: Secret;                         // default auth.oauth.github.clientId, else { runtimeConfig: "oauthGithubClientId" }
  clientSecret?: Secret;                     // default auth.oauth.github.clientSecret, else { runtimeConfig: "oauthGithubClientSecret" }
}): (input: unknown, ctx: HandlerContext) => Promise<unknown>

oauthHandler with a provider's URLs, default scopes and client authentication filled in. The provider's keys come from the call, then auth.oauth.<provider> of the config. The module declares oauth<Provider>ClientId and oauth<Provider>ClientSecret in runtimeConfig (the provider's file name with its first letter upper-cased: oauthGithubClientId), so HAMUR_OAUTH_GITHUB_CLIENT_ID and HAMUR_OAUTH_GITHUB_CLIENT_SECRET set them at run time. When the id is still empty at the first request, the answer is 500 and the log says @hamur/auth: oauthGitHub needs auth.oauth.github.clientId or HAMUR_OAUTH_GITHUB_CLIENT_ID.

ts
export const github = defineHandler({
  route: "/auth/github", method: "GET", raw: true,
  handler: oauthGitHub({
    async onSuccess(event, { user }) {
      await setUserSession(event, { user: { login: user.login as string } });
    },
  }),
});

user is the provider's profile as it sends it, taken out of its envelope where it has one (data for x, the first of data for twitch and kick, user for zendesk and vk, data.viewer for linear, data.user for tiktok, data.customer for shopifyCustomer, the authenticate answer's user for workos, the verified id_token claims for azureb2c); an envelope without a user answers 401 OAuth token request failed.

ExportProvider keysDefault scopesVariables
oauthGitHubnoneHAMUR_OAUTH_GITHUB_CLIENT_ID, HAMUR_OAUTH_GITHUB_CLIENT_SECRET
oauthGoogleopenid email profileHAMUR_OAUTH_GOOGLE_CLIENT_ID, HAMUR_OAUTH_GOOGLE_CLIENT_SECRET
oauthMicrosofttenant (default common)User.ReadHAMUR_OAUTH_MICROSOFT_CLIENT_ID, HAMUR_OAUTH_MICROSOFT_CLIENT_SECRET
oauthAppleteamId, keyId, privateKey (a secret, default { runtimeConfig: "oauthApplePrivateKey" }); no clientSecretname emailHAMUR_OAUTH_APPLE_CLIENT_ID, HAMUR_OAUTH_APPLE_PRIVATE_KEY
oauthDiscordidentify emailHAMUR_OAUTH_DISCORD_CLIENT_ID, HAMUR_OAUTH_DISCORD_CLIENT_SECRET
oauthGitLabbaseURL (default https://gitlab.com)read_userHAMUR_OAUTH_GITLAB_CLIENT_ID, HAMUR_OAUTH_GITLAB_CLIENT_SECRET
oauthAtlassianread:meHAMUR_OAUTH_ATLASSIAN_CLIENT_ID, HAMUR_OAUTH_ATLASSIAN_CLIENT_SECRET
oauthAuth0domain (required)openid profile emailHAMUR_OAUTH_AUTH0_CLIENT_ID, HAMUR_OAUTH_AUTH0_CLIENT_SECRET
oauthAuthentikdomain (required)openid profile emailHAMUR_OAUTH_AUTHENTIK_CLIENT_ID, HAMUR_OAUTH_AUTHENTIK_CLIENT_SECRET
oauthBattleDotNetopenidHAMUR_OAUTH_BATTLEDOTNET_CLIENT_ID, HAMUR_OAUTH_BATTLEDOTNET_CLIENT_SECRET
oauthBoxnoneHAMUR_OAUTH_BOX_CLIENT_ID, HAMUR_OAUTH_BOX_CLIENT_SECRET
oauthDropboxaccount_info.readHAMUR_OAUTH_DROPBOX_CLIENT_ID, HAMUR_OAUTH_DROPBOX_CLIENT_SECRET
oauthFacebookpublic_profile emailHAMUR_OAUTH_FACEBOOK_CLIENT_ID, HAMUR_OAUTH_FACEBOOK_CLIENT_SECRET
oauthGiteabaseURL (default https://gitea.com)read:userHAMUR_OAUTH_GITEA_CLIENT_ID, HAMUR_OAUTH_GITEA_CLIENT_SECRET
oauthHerokuidentityHAMUR_OAUTH_HEROKU_CLIENT_ID, HAMUR_OAUTH_HEROKU_CLIENT_SECRET
oauthKeycloakserverURL, realm (required)openidHAMUR_OAUTH_KEYCLOAK_CLIENT_ID, HAMUR_OAUTH_KEYCLOAK_CLIENT_SECRET
oauthKickuser:readHAMUR_OAUTH_KICK_CLIENT_ID, HAMUR_OAUTH_KICK_CLIENT_SECRET
oauthLineopenid profileHAMUR_OAUTH_LINE_CLIENT_ID, HAMUR_OAUTH_LINE_CLIENT_SECRET
oauthLinearreadHAMUR_OAUTH_LINEAR_CLIENT_ID, HAMUR_OAUTH_LINEAR_CLIENT_SECRET
oauthLinkedInopenid profile emailHAMUR_OAUTH_LINKEDIN_CLIENT_ID, HAMUR_OAUTH_LINKEDIN_CLIENT_SECRET
oauthMastodonbaseURL (default https://mastodon.social)read:accountsHAMUR_OAUTH_MASTODON_CLIENT_ID, HAMUR_OAUTH_MASTODON_CLIENT_SECRET
oauthOktadomain (required)openid profile emailHAMUR_OAUTH_OKTA_CLIENT_ID, HAMUR_OAUTH_OKTA_CLIENT_SECRET
oauthOrydomain (required)openid emailHAMUR_OAUTH_ORY_CLIENT_ID, HAMUR_OAUTH_ORY_CLIENT_SECRET
oauthOsuidentifyHAMUR_OAUTH_OSU_CLIENT_ID, HAMUR_OAUTH_OSU_CLIENT_SECRET
oauthPayPalopenid profile emailHAMUR_OAUTH_PAYPAL_CLIENT_ID, HAMUR_OAUTH_PAYPAL_CLIENT_SECRET
oauthPolaropenid emailHAMUR_OAUTH_POLAR_CLIENT_ID, HAMUR_OAUTH_POLAR_CLIENT_SECRET
oauthRiotGamesopenidHAMUR_OAUTH_RIOTGAMES_CLIENT_ID, HAMUR_OAUTH_RIOTGAMES_CLIENT_SECRET
oauthRobloxopenid profileHAMUR_OAUTH_ROBLOX_CLIENT_ID, HAMUR_OAUTH_ROBLOX_CLIENT_SECRET
oauthSalesforcebaseURL (default https://login.salesforce.com)openid profile emailHAMUR_OAUTH_SALESFORCE_CLIENT_ID, HAMUR_OAUTH_SALESFORCE_CLIENT_SECRET
oauthSeznamidentityHAMUR_OAUTH_SEZNAM_CLIENT_ID, HAMUR_OAUTH_SEZNAM_CLIENT_SECRET
oauthSlackopenid email profileHAMUR_OAUTH_SLACK_CLIENT_ID, HAMUR_OAUTH_SLACK_CLIENT_SECRET
oauthSpotifyuser-read-emailHAMUR_OAUTH_SPOTIFY_CLIENT_ID, HAMUR_OAUTH_SPOTIFY_CLIENT_SECRET
oauthTwitchuser:read:emailHAMUR_OAUTH_TWITCH_CLIENT_ID, HAMUR_OAUTH_TWITCH_CLIENT_SECRET
oauthXusers.read tweet.readHAMUR_OAUTH_X_CLIENT_ID, HAMUR_OAUTH_X_CLIENT_SECRET
oauthYandexlogin:info login:emailHAMUR_OAUTH_YANDEX_CLIENT_ID, HAMUR_OAUTH_YANDEX_CLIENT_SECRET
oauthZendesksubdomain (required)readHAMUR_OAUTH_ZENDESK_CLIENT_ID, HAMUR_OAUTH_ZENDESK_CLIENT_SECRET
oauthZitadeldomain (required)openid profile emailHAMUR_OAUTH_ZITADEL_CLIENT_ID, HAMUR_OAUTH_ZITADEL_CLIENT_SECRET
oauthAzureB2Ctenant, policy (required)openid offline_accessHAMUR_OAUTH_AZUREB2C_CLIENT_ID, HAMUR_OAUTH_AZUREB2C_CLIENT_SECRET
oauthCloudflareteamName (required), clientId as text (required; it is part of the URLs)openid email profileHAMUR_OAUTH_CLOUDFLARE_CLIENT_SECRET
oauthCognitodomain (required)openid email profileHAMUR_OAUTH_COGNITO_CLIENT_ID, HAMUR_OAUTH_COGNITO_CLIENT_SECRET
oauthHubSpotoauthHAMUR_OAUTH_HUBSPOT_CLIENT_ID, HAMUR_OAUTH_HUBSPOT_CLIENT_SECRET
oauthInstagraminstagram_business_basicHAMUR_OAUTH_INSTAGRAM_CLIENT_ID, HAMUR_OAUTH_INSTAGRAM_CLIENT_SECRET
oauthLiveChatnoneHAMUR_OAUTH_LIVECHAT_CLIENT_ID, HAMUR_OAUTH_LIVECHAT_CLIENT_SECRET
oauthShopifyCustomershopId (required)openid email customer-account-api:fullHAMUR_OAUTH_SHOPIFY_CUSTOMER_CLIENT_ID, HAMUR_OAUTH_SHOPIFY_CUSTOMER_CLIENT_SECRET
oauthStravaread (sent comma-joined)HAMUR_OAUTH_STRAVA_CLIENT_ID, HAMUR_OAUTH_STRAVA_CLIENT_SECRET
oauthTikTokthe client id is the client keyuser.info.basic (sent comma-joined)HAMUR_OAUTH_TIKTOK_CLIENT_ID, HAMUR_OAUTH_TIKTOK_CLIENT_SECRET
oauthVKno clientSecret (VK ID, a public client)vkid.personal_info emailHAMUR_OAUTH_VK_CLIENT_ID
oauthWeChatthe client id is the AppIDsnsapi_loginHAMUR_OAUTH_WECHAT_CLIENT_ID, HAMUR_OAUTH_WECHAT_CLIENT_SECRET
oauthWorkOSnone; provider=authkitHAMUR_OAUTH_WORKOS_CLIENT_ID, HAMUR_OAUTH_WORKOS_CLIENT_SECRET
oauthXsuaadomain (required)openidHAMUR_OAUTH_XSUAA_CLIENT_ID, HAMUR_OAUTH_XSUAA_CLIENT_SECRET

The variables are HAMUR_ and the upper snake case of the runtime-config key oauth<Provider><Key> (02 §5), which splits a capital from a capitalised word: oauthXClientId is HAMUR_OAUTH_X_CLIENT_ID, not HAMUR_OAUTH_XCLIENT_ID.

A required key that is missing throws when the handler is defined: @hamur/auth: oauthAuth0 needs auth.oauth.auth0.domain.

Apple posts its callback: declare the route with method: "*". The module adds routeRules["/auth/apple"] = { originCheck: { allow: ["https://appleid.apple.com"] } } for you, on that route only, when the route has no parameter and its definition is written handler: oauthApple({ … }) with oauthApple imported by name from @hamur/auth/server in the same file. Write the rule yourself for a route with a parameter (/auth/:provider; a rule on /auth/* would let Apple post to every route beside it, so give Apple its own route), for a wrapped handler (handler: wrap(oauthApple({ … }))) and for an oauthApple imported through a file of your own; without it the start throws the form_post message above. A rule you write on the same pattern wins over the module's, so list Apple's origin in it if it sets originCheck. The client secret is an ES256 JWT signed with privateKey (the .p8 file, PKCS #8 PEM), valid for an hour and reused until 5 minutes before it ends. user is the id_token's claims, verified against Apple's keys (a failure answers 401 Invalid ID token: <claim>), with name: { firstName, lastName } from the first sign-in, which Apple posts unsigned.

oauthSteam({ onSuccess, onError?, redirectURL? }) is OpenID 2.0, not OAuth, and takes no client id. user is { steamId, claimedId }. A state sealed in the flow cookie __Host-hamur-oauth-<h> travels in openid.return_to as ?hamur_state=; the callback needs it (400 Invalid OAuth state), then an id_res assertion from Steam's endpoint whose claimed_id equals identity and whose openid.signed lists op_endpoint, claimed_id, identity, return_to, response_nonce and assoc_handle, and Steam's is_valid:true for the assertion sent back unchanged; anything else is 401 Steam OpenID check failed. A cancel at Steam calls onError(event, { error: "cancel" }).

webAuthnRegister, webAuthnAuthenticate, WebAuthnCredential, WebAuthnRegisterOptions, WebAuthnAuthenticateOptions, WebAuthnUser, WebAuthnCredentialDescriptor, WebAuthnUserVerification, WebAuthnAlgorithm

ts
interface WebAuthnCredential {
  id: string; userHandle: string; publicKey: JsonWebKey; algorithm: -8 | -19 | -7 | -257;   // WebAuthnAlgorithm
  counter: number; transports?: string[]; backupEligible: boolean; backedUp: boolean; userVerified: boolean;
}

function webAuthnRegister(options: {
  validateUser?(user: { userName: string; displayName?: string }, event: HamurEvent): unknown;
  getUserHandle?(event: HamurEvent, userName: string): Promise<string | undefined>;
  excludeCredentials?(event: HamurEvent, userName: string): Promise<{ id: string; transports?: string[] }[]>;
  userVerification?: "required" | "preferred" | "discouraged";   // default "preferred"
  onSuccess(event: HamurEvent, result: { credential: WebAuthnCredential; user: { userName: string; displayName?: string; userHandle: string } }): unknown;
}): (input: unknown, ctx: HandlerContext) => Promise<unknown>

function webAuthnAuthenticate(options: {
  getCredential(event: HamurEvent, id: string): Promise<WebAuthnCredential | undefined>;
  allowCredentials?(event: HamurEvent, userName: string): Promise<{ id: string; transports?: string[] }[]>;
  userVerification?: "required" | "preferred" | "discouraged";
  onSuccess(event: HamurEvent, result: { credential: WebAuthnCredential; counter: number; backedUp: boolean }): unknown;
}): (input: unknown, ctx: HandlerContext) => Promise<unknown>

Passkey registration and sign-in, each the body of a raw POST handler that takes JSON in two steps: { step: "options", user? } answers the options to pass to navigator.credentials.create() or .get() (as JSON), and { step: "verify", response } takes the credential's toJSON(), verifies it and calls onSuccess, whose value is the answer (undefined answers { verified: true }). Any other body is 400 Invalid WebAuthn request.

ts
// server/passkey.ts, exported from server/index.ts
export const passkey = defineHandler({
  route: "/auth/passkey", method: "POST", raw: true,
  handler: webAuthnRegister({
    validateUser: async (user, event) => {
      const existing = await users.byName(user.userName);
      if (existing && (await getUserSession(event)).user?.name !== user.userName) throw createError({ status: 401, message: "Sign in to add a passkey" });
    },
    getUserHandle: async (event, userName) => (await users.byName(userName))?.handle,
    async onSuccess(event, { credential, user }) {
      await credentials.insert(credential);   // a unique id: refuse a duplicate here
      await setUserSession(event, { user: { name: user.userName } });
    },
  }),
});
  • The relying party comes from auth.webauthn: rpID, and the expected origins origins or https://<rpID>. Without rpID it is the request's host, and only a host a server.allowedHosts list names (the default true names none; a host outside the list answers 400 WebAuthn verification failed: origin). A built server whose app has one of these handlers and neither setting does not start: @hamur/auth: webauthn needs auth.webauthn.rpID or server.allowedHosts in production. hamur dev takes the request's host, and with rpID also accepts the request's own origin when its host is rpID or below it (rpID: "localhost" on http://localhost:3000).
  • Options. A 32-byte challenge, the algorithms EdDSA (-8), Ed25519 (-19), ES256 (-7) and RS256 (-257), attestation: "none", a 60 s timeout and residentKey: "preferred". Registration needs user: { userName, displayName? } (strings of 1 to 256 characters); sign-in takes user: { userName } to offer that account's allowCredentials, or nothing for a discoverable sign-in.
  • Who may add a passkey. user.id, the user handle, is getUserHandle's answer for an existing account (so one account keeps one handle), else 32 random bytes. The userName comes from the browser, so getUserHandle and excludeCredentials are called only after validateUser returned: for an existing account it must throw unless the request's user session is that account, and for a new account when the name is taken. getUserHandle without validateUser throws when the handler is made. onSuccess gets the handle from the sealed challenge, never from the browser.
  • The challenge is sealed in the flow cookie __Host-hamur-webauthn-<h> (/auth/passkey is __Host-hamur-webauthn-5b4e7758ae274a7b): Max-Age=300; Path=/; HttpOnly; Secure; SameSite=Strict, no Domain, read by that name only (under hamur dev on http, hamur-webauthn-<h> without Secure). Each challenge verifies once: the verify step counts it with increment on the session storage mount, so a captured cookie and response cannot be replayed.
  • The session mount must give an atomic increment: redis, db or sqlite without encrypt, or memory or fs on bun and node (one process: the server logs @hamur/auth: single-use tokens and challenges count on the "session" mount (fs) in this process only; run one process, or mount storage.session on redis, db or sqlite at start). Otherwise the build fails, and a mount made at run time fails the first call (a 500): @hamur/auth: single-use challenges need an atomic increment; the "session" mount uses cloudflare-kv on the cloudflare preset; mount storage.session on redis, db or sqlite, …; the "session" mount has encrypt, whose increment is not atomic; …, and without a mount @hamur/auth: webAuthnAuthenticate needs the session storage mount for single-use challenges; set storage.session.
  • Verify answers 400 WebAuthn verification failed: <check> naming the first check that failed: type, challenge, origin (also for crossOrigin: true or a topOrigin), attestation, rpIdHash, userPresence, userVerification (when "required"), backupState, credentialId (registration: no attested credential, or its id is not rawId), algorithm, credential (sign-in: not in the allowCredentials sent, or getCredential found none), userHandle (another account's, or none in a discoverable sign-in), signature, signCount (the counter did not grow; two zeros pass). Attestation none and packed self attestation are checked; any other format is taken as none. Sign-in also fails backupState when the BE flag differs from the stored backupEligible. Store counter and backedUp from sign-in's onSuccess in the credential. excludeCredentials needs validateUser (else a TypeError when the handler is made). The transports sent and stored keep only usb, nfc, ble, smart-card, hybrid and internal.

@hamur/auth/middleware

requireUser

ts
const requireUser: FunctionMiddleware<{}, { user: User; session: UserSessionData & { user: User; id: string } }>

A defineMiddleware that calls requireUserSession(event) and continues with { user, session } on the context. One object guards the three places:

ts
// server/index.ts: documents and routes by path, before the router and any render
export default defineServer({ middleware: [{ route: "/admin/**", handler: requireUser }, { route: "/ws", handler: requireUser }] });

// server/admin.ts: the data, on every call
export const listUsers = defineHandler({ method: "GET", middleware: [requireUser], handler: (_, ctx) => usersOf(ctx.context.user) });
  • In a request list, a logged-out GET or HEAD that prefers HTML (Accept ranks text/html above application/json) answers 302 to auth.redirect.login?redirect=<path and query>, under baseURL; any other request, a WebSocket upgrade included, answers 401 Unauthorized. An error other than the missing user (a storage failure, an unset password key) propagates as it is.
  • In a handler's middleware it answers 401, whatever the request prefers, and types ctx.context.user.
  • On a WebSocket route the request step runs before the upgrade: without a session the upgrade answers 401 and no socket opens; with one, peer.context.user and peer.context.session are set in open.

Its file holds only imports and the one export const, so a client build that loads it through a handler's middleware drops its server part.

@hamur/auth/react, @hamur/auth/vue, @hamur/auth/preact, @hamur/auth/svelte, @hamur/auth/solid, @hamur/auth/html

One entry per adapter, each exporting useUserSession, useWebAuthn and, except html, AuthState. They read one store per app: started from the payload of the server render, filled by a fetch of GET <baseURL>_hamur/auth/session after hydration when the render did not read the session, and changed by fetch() and clear(). A client navigation keeps it.

useUserSession()

useUserSession() gives { ready, loggedIn, user, session, fetch, clear }. ready is false until the session was read, on the server or by a fetch; user is session.user or null; session is the public session or null when it is empty. fetch() calls GET once, without retry; a failure (a network error or a non-2xx answer) rejects and leaves the state as it was. clear() calls DELETE, then shows the logged-out state; it rejects when the request fails.

LibraryValues
react, preactplain values; the component renders again when they change
vueComputedRefs
sveltea store: $session.user, $session.loggedIn, and session.clear() beside subscribe
solidAccessors
htmlthe server's values, ready true only when the server read the session; fetch() reloads the page and clear() calls DELETE, then reloads
tsx
const { loggedIn, user, clear } = useUserSession();
return loggedIn ? <button onClick={clear}>Log out {user.name}</button> : <a href="/login">Log in</a>;

useWebAuthn, WebAuthn, WebAuthnOptions, WebAuthnUser

ts
useWebAuthn(options: { registerEndpoint: string; authenticateEndpoint: string }): {
  isSupported;
  register(user: { userName: string; displayName?: string }): Promise<unknown>;
  authenticate(userName?: string): Promise<unknown>;
}

The browser side of webAuthnRegister and webAuthnAuthenticate: the two endpoints are the routes of those handlers. register(user) posts { step: "options", user }, passes the answer to navigator.credentials.create(), posts { step: "verify", response } with the credential as JSON and resolves with the answer of the verify step (the value of the handler's onSuccess, or { verified: true }). authenticate(userName?) does the same with navigator.credentials.get(); without a name the options carry no user and the sign-in is discoverable. The calls convert with PublicKeyCredential.parseCreationOptionsFromJSON, parseRequestOptionsFromJSON and credential.toJSON() where the browser has them, else with the same base64url conversion of challenge, user.id, the credential ids and the response fields. A refused step rejects with the FetchError of its answer (400, WebAuthn verification failed: origin); a browser refusal (the user cancelled) rejects with the browser's DOMException, and a null credential with Error: WebAuthn registration returned no credential or WebAuthn sign-in returned no credential. register and authenticate do not touch the session store: call useUserSession().fetch() after one resolves.

isSupported is window.isSecureContext && typeof PublicKeyCredential === "function". It is false in the server render and on the first client render, so hydration agrees, then the browser's answer.

LibraryisSupported
react, preacta boolean; the component renders again when it changes
vuea Ref<boolean>
sveltea store: $isSupported
solidan Accessor<boolean>
htmla boolean read when useWebAuthn is called; an html page has no client render, so call it from a handler or after app:mounted
tsx
const passkey = useWebAuthn({ registerEndpoint: "/passkey/register", authenticateEndpoint: "/passkey/login" });
return passkey.isSupported && <button onClick={() => void passkey.authenticate()}>Sign in with a passkey</button>;

AuthState, AuthStateSlot, UserSessionState, UserSession

AuthState renders its placeholder until ready, then its children with { loggedIn, user, clear } (AuthStateSlot). The placeholder is the placeholder prop in react, preact and solid (AuthStateProps), and the placeholder slot or snippet in vue and svelte; the children are a function in react, preact and solid, the default slot in vue and the children snippet in svelte. html has no AuthState, since its pages do not render again on the client. UserSessionState is the state without the two functions, UserSession what useUserSession returns.

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