@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.
// 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
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.
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.
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
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:
"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.
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
function getUserSession(event: HamurEvent): Promise<UserSessionData & { id: string }>
The session's data and its id; { id } alone when there is none.
setUserSession
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
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
function clearUserSession(event: HamurEvent): Promise<void>
Calls the auth:session:clear hook, then clears the session and deletes its cookie.
requireUserSession
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.
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
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:
// 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
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.
// 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
codeorerror: 302 toauthorizationURLwithresponse_type=code,client_id,redirect_uri,scope(space-joined, left out when empty), a randomstate, and withpkcean S256code_challenge.stateand 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/githubis__Host-hamur-oauth-08cd8795e41c13e4):Max-Age=600; Path=/; HttpOnly; Secure; SameSite=Lax, neverDomain, so a sibling subdomain cannot plant a flow of its own. Underhamur devon plain http it ishamur-oauth-<h>withoutSecure. redirect_uriisredirectURL, else the route's absolute URL fromgetRequestURL(soserver.trustProxyapplies). SetredirectURLin 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 400Invalid OAuth state. Withissuer, theissparameter must equal it, error callbacks included, else 400OAuth issuer mismatch. A providererrorcallsonError(event, { error, description }), else answers 401OAuth 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 502OAuth provider did not answer, a refusal or an answer withoutaccess_tokenis 401OAuth token request failed. WithuserURLthe profile is fetched with the access token, andmapUsershapes it.onSuccess's value is the answer;undefinedredirects toauth.redirect.home. tokenAuth:client_secret_basicsendsauthorization: Basicwith the id and secret form-encoded first, so a secret holding:,+or%arrives intact;client_secret_postsends both in the body;nonesendsclient_idonly and needspkce(TypeError: oauthHandler tokenAuth "none" needs pkce). The other two needclientSecret.responseMode: "form_post": the provider posts the callback cross-site, so declaremethod: "*"(aGETstarts, aPOSTis the callback) and list the provider's origin (that ofauthorizationURL) in the route ruleoriginCheck.allowof the route. The cookie is thenSameSite=None, which needs https underhamur devtoo (setdevServer.https; on plain http the start throws aTypeErrorsaying so). A start that the origin check would refuse the provider's post to (no rule listing it, nocorsrule, not inserver.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
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.
// 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 providererrorreachesonErroreven while discovery is down), and kept in memory and in thecachestorage mount for an hour, so two sign-ins, or many at once, fetch it once. Itsissuermust equal the configured one exactly, else 502OIDC discovery issuer mismatch.authorization_endpoint,token_endpointandjwks_urimust be https URLs, the…_supportedlists lists of strings,authorization_response_iss_parameter_supporteda boolean, and the signing algorithms must name one Hamur verifies; any other document, or an answer that is not a 2xx JSON object, is 502OIDC discovery failed, and no answer within 10 s is 502OAuth provider did not answer. - Start: as
oauthHandler, with PKCE and a randomnoncekept in the flow cookie besidestate. When the document saysauthorization_response_iss_parameter_supported: true, the callback needsissequal to the issuer (400OAuth issuer mismatch). - Client authentication:
client_secret_basicwhen the document'stoken_endpoint_auth_methods_supportedis absent or lists it, elseclient_secret_postwhen listed; withoutclientSecret,nonewhen the list is absent or lists it. Otherwise 502OIDC provider supports no client authentication Hamur offers. - ID token (OIDC Core §3.1.3.7), verified against
jwks_uriwith a 60 s clock tolerance: signed with an algorithm the document lists inid_token_signing_alg_values_supported(RS256when the field is absent) other than an HMAC one;issthe issuer;audholdingclientId, every other audience inaudiences;azp, when present, equal toclientId, and present when there is more than one audience;expandiatpresent;suba non-empty string;noncethe one the start sent. A failure answers 401Invalid ID token: <claim>:malformed,alg,signature,exp,nbf,iss,aud,azp,iat,subornonce.
oauthAtproto, OAuthAtprotoOptions, AtprotoClientMetadata, AtprotoResult
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.
// 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
oauthAtprotocall, the module servesGET <baseURL>_hamur/auth/atproto/client-metadata.json, whose URL is theclient_id:redirect_uristhe URLs of those routes,scopeevery call's scopes,token_endpoint_auth_method: "none"anddpop_bound_access_tokens: true, with the calls'clientMetadataover the defaults (the first call wins a field;client_idand 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 fromhttps://plc.directory/<did>or, fordid:web,https://<host>/.well-known/did.json, whosealsoKnownAsmust holdat://<handle>(else 401AT Protocol handle does not match its DID), then the PDS's/.well-known/oauth-protected-resourceand the authorization server's/.well-known/oauth-authorization-server, whoseissuermust 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,.altor.example), every URLhttps: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 400AT Protocol handle could not be resolved; the reason is logged atdebugand never sent. - DPoP: a
use_dpop_nonceerror is sent again once with the server'sDPoP-Nonce. The callback needsissequal to the authorization server (400OAuth issuer mismatch), and the token answer'ssubmust be the DID (401AT Protocol handle does not match its DID); a refused token request, or a token answer whosetoken_typeis notDPoPor whosescopelacksatproto, is 401OAuth token request failed.
oauthGitHub, oauthGoogle, … the provider presets, OAuthPresetOptions
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.
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.
| Export | Provider keys | Default scopes | Variables |
|---|---|---|---|
oauthGitHub | none | HAMUR_OAUTH_GITHUB_CLIENT_ID, HAMUR_OAUTH_GITHUB_CLIENT_SECRET | |
oauthGoogle | openid email profile | HAMUR_OAUTH_GOOGLE_CLIENT_ID, HAMUR_OAUTH_GOOGLE_CLIENT_SECRET | |
oauthMicrosoft | tenant (default common) | User.Read | HAMUR_OAUTH_MICROSOFT_CLIENT_ID, HAMUR_OAUTH_MICROSOFT_CLIENT_SECRET |
oauthApple | teamId, keyId, privateKey (a secret, default { runtimeConfig: "oauthApplePrivateKey" }); no clientSecret | name email | HAMUR_OAUTH_APPLE_CLIENT_ID, HAMUR_OAUTH_APPLE_PRIVATE_KEY |
oauthDiscord | identify email | HAMUR_OAUTH_DISCORD_CLIENT_ID, HAMUR_OAUTH_DISCORD_CLIENT_SECRET | |
oauthGitLab | baseURL (default https://gitlab.com) | read_user | HAMUR_OAUTH_GITLAB_CLIENT_ID, HAMUR_OAUTH_GITLAB_CLIENT_SECRET |
oauthAtlassian | read:me | HAMUR_OAUTH_ATLASSIAN_CLIENT_ID, HAMUR_OAUTH_ATLASSIAN_CLIENT_SECRET | |
oauthAuth0 | domain (required) | openid profile email | HAMUR_OAUTH_AUTH0_CLIENT_ID, HAMUR_OAUTH_AUTH0_CLIENT_SECRET |
oauthAuthentik | domain (required) | openid profile email | HAMUR_OAUTH_AUTHENTIK_CLIENT_ID, HAMUR_OAUTH_AUTHENTIK_CLIENT_SECRET |
oauthBattleDotNet | openid | HAMUR_OAUTH_BATTLEDOTNET_CLIENT_ID, HAMUR_OAUTH_BATTLEDOTNET_CLIENT_SECRET | |
oauthBox | none | HAMUR_OAUTH_BOX_CLIENT_ID, HAMUR_OAUTH_BOX_CLIENT_SECRET | |
oauthDropbox | account_info.read | HAMUR_OAUTH_DROPBOX_CLIENT_ID, HAMUR_OAUTH_DROPBOX_CLIENT_SECRET | |
oauthFacebook | public_profile email | HAMUR_OAUTH_FACEBOOK_CLIENT_ID, HAMUR_OAUTH_FACEBOOK_CLIENT_SECRET | |
oauthGitea | baseURL (default https://gitea.com) | read:user | HAMUR_OAUTH_GITEA_CLIENT_ID, HAMUR_OAUTH_GITEA_CLIENT_SECRET |
oauthHeroku | identity | HAMUR_OAUTH_HEROKU_CLIENT_ID, HAMUR_OAUTH_HEROKU_CLIENT_SECRET | |
oauthKeycloak | serverURL, realm (required) | openid | HAMUR_OAUTH_KEYCLOAK_CLIENT_ID, HAMUR_OAUTH_KEYCLOAK_CLIENT_SECRET |
oauthKick | user:read | HAMUR_OAUTH_KICK_CLIENT_ID, HAMUR_OAUTH_KICK_CLIENT_SECRET | |
oauthLine | openid profile | HAMUR_OAUTH_LINE_CLIENT_ID, HAMUR_OAUTH_LINE_CLIENT_SECRET | |
oauthLinear | read | HAMUR_OAUTH_LINEAR_CLIENT_ID, HAMUR_OAUTH_LINEAR_CLIENT_SECRET | |
oauthLinkedIn | openid profile email | HAMUR_OAUTH_LINKEDIN_CLIENT_ID, HAMUR_OAUTH_LINKEDIN_CLIENT_SECRET | |
oauthMastodon | baseURL (default https://mastodon.social) | read:accounts | HAMUR_OAUTH_MASTODON_CLIENT_ID, HAMUR_OAUTH_MASTODON_CLIENT_SECRET |
oauthOkta | domain (required) | openid profile email | HAMUR_OAUTH_OKTA_CLIENT_ID, HAMUR_OAUTH_OKTA_CLIENT_SECRET |
oauthOry | domain (required) | openid email | HAMUR_OAUTH_ORY_CLIENT_ID, HAMUR_OAUTH_ORY_CLIENT_SECRET |
oauthOsu | identify | HAMUR_OAUTH_OSU_CLIENT_ID, HAMUR_OAUTH_OSU_CLIENT_SECRET | |
oauthPayPal | openid profile email | HAMUR_OAUTH_PAYPAL_CLIENT_ID, HAMUR_OAUTH_PAYPAL_CLIENT_SECRET | |
oauthPolar | openid email | HAMUR_OAUTH_POLAR_CLIENT_ID, HAMUR_OAUTH_POLAR_CLIENT_SECRET | |
oauthRiotGames | openid | HAMUR_OAUTH_RIOTGAMES_CLIENT_ID, HAMUR_OAUTH_RIOTGAMES_CLIENT_SECRET | |
oauthRoblox | openid profile | HAMUR_OAUTH_ROBLOX_CLIENT_ID, HAMUR_OAUTH_ROBLOX_CLIENT_SECRET | |
oauthSalesforce | baseURL (default https://login.salesforce.com) | openid profile email | HAMUR_OAUTH_SALESFORCE_CLIENT_ID, HAMUR_OAUTH_SALESFORCE_CLIENT_SECRET |
oauthSeznam | identity | HAMUR_OAUTH_SEZNAM_CLIENT_ID, HAMUR_OAUTH_SEZNAM_CLIENT_SECRET | |
oauthSlack | openid email profile | HAMUR_OAUTH_SLACK_CLIENT_ID, HAMUR_OAUTH_SLACK_CLIENT_SECRET | |
oauthSpotify | user-read-email | HAMUR_OAUTH_SPOTIFY_CLIENT_ID, HAMUR_OAUTH_SPOTIFY_CLIENT_SECRET | |
oauthTwitch | user:read:email | HAMUR_OAUTH_TWITCH_CLIENT_ID, HAMUR_OAUTH_TWITCH_CLIENT_SECRET | |
oauthX | users.read tweet.read | HAMUR_OAUTH_X_CLIENT_ID, HAMUR_OAUTH_X_CLIENT_SECRET | |
oauthYandex | login:info login:email | HAMUR_OAUTH_YANDEX_CLIENT_ID, HAMUR_OAUTH_YANDEX_CLIENT_SECRET | |
oauthZendesk | subdomain (required) | read | HAMUR_OAUTH_ZENDESK_CLIENT_ID, HAMUR_OAUTH_ZENDESK_CLIENT_SECRET |
oauthZitadel | domain (required) | openid profile email | HAMUR_OAUTH_ZITADEL_CLIENT_ID, HAMUR_OAUTH_ZITADEL_CLIENT_SECRET |
oauthAzureB2C | tenant, policy (required) | openid offline_access | HAMUR_OAUTH_AZUREB2C_CLIENT_ID, HAMUR_OAUTH_AZUREB2C_CLIENT_SECRET |
oauthCloudflare | teamName (required), clientId as text (required; it is part of the URLs) | openid email profile | HAMUR_OAUTH_CLOUDFLARE_CLIENT_SECRET |
oauthCognito | domain (required) | openid email profile | HAMUR_OAUTH_COGNITO_CLIENT_ID, HAMUR_OAUTH_COGNITO_CLIENT_SECRET |
oauthHubSpot | oauth | HAMUR_OAUTH_HUBSPOT_CLIENT_ID, HAMUR_OAUTH_HUBSPOT_CLIENT_SECRET | |
oauthInstagram | instagram_business_basic | HAMUR_OAUTH_INSTAGRAM_CLIENT_ID, HAMUR_OAUTH_INSTAGRAM_CLIENT_SECRET | |
oauthLiveChat | none | HAMUR_OAUTH_LIVECHAT_CLIENT_ID, HAMUR_OAUTH_LIVECHAT_CLIENT_SECRET | |
oauthShopifyCustomer | shopId (required) | openid email customer-account-api:full | HAMUR_OAUTH_SHOPIFY_CUSTOMER_CLIENT_ID, HAMUR_OAUTH_SHOPIFY_CUSTOMER_CLIENT_SECRET |
oauthStrava | read (sent comma-joined) | HAMUR_OAUTH_STRAVA_CLIENT_ID, HAMUR_OAUTH_STRAVA_CLIENT_SECRET | |
oauthTikTok | the client id is the client key | user.info.basic (sent comma-joined) | HAMUR_OAUTH_TIKTOK_CLIENT_ID, HAMUR_OAUTH_TIKTOK_CLIENT_SECRET |
oauthVK | no clientSecret (VK ID, a public client) | vkid.personal_info email | HAMUR_OAUTH_VK_CLIENT_ID |
oauthWeChat | the client id is the AppID | snsapi_login | HAMUR_OAUTH_WECHAT_CLIENT_ID, HAMUR_OAUTH_WECHAT_CLIENT_SECRET |
oauthWorkOS | none; provider=authkit | HAMUR_OAUTH_WORKOS_CLIENT_ID, HAMUR_OAUTH_WORKOS_CLIENT_SECRET | |
oauthXsuaa | domain (required) | openid | HAMUR_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
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.
// 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 originsoriginsorhttps://<rpID>. WithoutrpIDit is the request's host, and only a host aserver.allowedHostslist names (the defaulttruenames none; a host outside the list answers 400WebAuthn 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 devtakes the request's host, and withrpIDalso accepts the request's own origin when its host isrpIDor below it (rpID: "localhost"onhttp://localhost:3000). - Options. A 32-byte challenge, the algorithms EdDSA (-8), Ed25519 (-19), ES256 (-7) and RS256 (-257),
attestation: "none", a 60 s timeout andresidentKey: "preferred". Registration needsuser: { userName, displayName? }(strings of 1 to 256 characters); sign-in takesuser: { userName }to offer that account'sallowCredentials, or nothing for a discoverable sign-in. - Who may add a passkey.
user.id, the user handle, isgetUserHandle's answer for an existing account (so one account keeps one handle), else 32 random bytes. TheuserNamecomes from the browser, sogetUserHandleandexcludeCredentialsare called only aftervalidateUserreturned: 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.getUserHandlewithoutvalidateUserthrows when the handler is made.onSuccessgets the handle from the sealed challenge, never from the browser. - The challenge is sealed in the flow cookie
__Host-hamur-webauthn-<h>(/auth/passkeyis__Host-hamur-webauthn-5b4e7758ae274a7b):Max-Age=300; Path=/; HttpOnly; Secure; SameSite=Strict, noDomain, read by that name only (underhamur devon http,hamur-webauthn-<h>withoutSecure). Each challenge verifies once: the verify step counts it withincrementon thesessionstorage mount, so a captured cookie and response cannot be replayed. - The
sessionmount must give an atomic increment:redis,dborsqlitewithoutencrypt, ormemoryorfson 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 sqliteat 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 forcrossOrigin: trueor atopOrigin),attestation,rpIdHash,userPresence,userVerification(when"required"),backupState,credentialId(registration: no attested credential, or its id is notrawId),algorithm,credential(sign-in: not in theallowCredentialssent, orgetCredentialfound none),userHandle(another account's, or none in a discoverable sign-in),signature,signCount(the counter did not grow; two zeros pass). Attestationnoneandpackedself attestation are checked; any other format is taken asnone. Sign-in also failsbackupStatewhen the BE flag differs from the storedbackupEligible. StorecounterandbackedUpfrom sign-in'sonSuccessin the credential.excludeCredentialsneedsvalidateUser(else aTypeErrorwhen the handler is made). Thetransportssent and stored keep onlyusb,nfc,ble,smart-card,hybridandinternal.
@hamur/auth/middleware
requireUser
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:
// 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
GETorHEADthat prefers HTML (Acceptrankstext/htmlaboveapplication/json) answers 302 toauth.redirect.login?redirect=<path and query>, underbaseURL; any other request, a WebSocket upgrade included, answers 401Unauthorized. An error other than the missing user (a storage failure, an unset password key) propagates as it is. - In a handler's
middlewareit answers 401, whatever the request prefers, and typesctx.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.userandpeer.context.sessionare set inopen.
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.
| Library | Values |
|---|---|
| react, preact | plain values; the component renders again when they change |
| vue | ComputedRefs |
| svelte | a store: $session.user, $session.loggedIn, and session.clear() beside subscribe |
| solid | Accessors |
| html | the server's values, ready true only when the server read the session; fetch() reloads the page and clear() calls DELETE, then reloads |
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
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.
| Library | isSupported |
|---|---|
| react, preact | a boolean; the component renders again when it changes |
| vue | a Ref<boolean> |
| svelte | a store: $isSupported |
| solid | an Accessor<boolean> |
| html | a boolean read when useWebAuthn is called; an html page has no client render, so call it from a handler or after app:mounted |
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.
<AuthState placeholder={<p>Loading session</p>}>
{({ loggedIn, user }) => <p>{loggedIn ? `Welcome ${user.name}` : "Logged out"}</p>}
</AuthState>
<AuthState>
{#snippet children({ loggedIn, user })}<p>{loggedIn ? `Welcome ${user.name}` : "Logged out"}</p>{/snippet}
{#snippet placeholder()}<p>Loading session</p>{/snippet}
</AuthState>