@ultimat3/auth
v31.58.0
Published
Sessions, passwords, OAuth, MFA and api keys — resolved to one Actor
Downloads
31,293
Maintainers
Readme
@ultimat3/auth 🔐
The output of authentication is an Actor from @ultimat3/core. Nothing downstream
authorizes on a session row, a user row or an api key — http, actions, jobs and MCP all read
ctx.actor and hand it to @ultimat3/policy. One authz system, never two.
bun add @ultimat3/auth · guide: Auth
import { defineAuth, login, oauthLogin, postgresAuthAdapter } from '@ultimat3/auth';
declare const email: string;
declare const password: string;
declare const ip: string;
export const auth = defineAuth({
adapter: postgresAuthAdapter(), // or memoryAuthAdapter(), or your Better Auth binding
session: { absoluteTtlMs: 30 * 864e5, idleTtlMs: 7 * 864e5 },
password: { minLength: 12 },
mfa: { issuer: 'Acme' }, // the authenticator app's name; `required` only as `false`
providers: ['github', 'google'], // REQUIRED to serve any OAuth route — the default is []
link: 'verified-email', // the default; `'never'` is the only other value
});
const { actor, token, cookie } = await login(auth, { email, password, ip });
// Or by handle, for an app whose users are `@ada`: `defineAuth({ handles })` names the lookup from
// a normalised handle to the auth user's id, and `register(auth, { id, ... })` links the two rows.
const byHandle = await login(auth, { handle: 'ada', password, ip });
// "Log in with GitHub" is a link to /auth/sso/github. These two routes are what serves it.
const { start, callback } = oauthLogin(auth);Rules
- Every login failure throws
loginFailed()fromrate-limit.ts. Never a specific message. - Session ids are opaque random tokens; only
sha256(secret)reaches the database. - Absolute and idle expiry are evaluated independently. Activity never moves the ceiling.
- PKCE is mandatory on every provider —
OAuthProvider.usesPkceis the literaltrue, sousesPkce: falsedoes not typecheck and there is no branch that skips the verifier. - Recovery codes, verification tokens and api keys are hashed at rest and single-use.
- A verification token is consumed only when its hash matches, in the same statement — the
store takes
(purpose, identifier, tokenHash). Consuming first and comparing afterwards made an unauthenticated wrong guess destroy the victim's live reset link. - Guards assert on the actor. They never evaluate a policy.
- A user's
scopescolumn reachesActor.scopes, so a human can hold a scope.permissionsis a different field andhasScope()does not read it. verifySessionwrites at most once peridleSlideMs, not once per request.- The lockout counts attempts against one identity, so it has to be one count.
AuthLimiteris async on every member and declares the policy it enforces;defineAuthrefuses a limiter that disagrees with the app's declaration. - An attempt is reserved before the KDF, never checked and recorded after it:
reserve(key)counts the guess in the step that admits it, so a concurrent burst spends the allowance as it arrives.refund(reservation)gives one back on success; a failure calls nothing.
The lockout across replicas
memoryAuthLimiter keeps its table in the process, so maxAttempts: 5 at replicas: 3 lets an
account survive 15 guesses and hides each replica's lockout from the other two. An app that runs
more than one process says so and brings a limiter that says the same:
import { type AuthAdapter, type AuthLimiter, defineAuth } from '@ultimat3/auth';
declare const adapter: AuthAdapter;
declare const myLimiter: AuthLimiter;
defineAuth({
adapter,
rateLimit: { maxAttempts: 5, scope: 'shared' }, // the whole fleet's allowance
limiter: myLimiter, // whose policy says exactly the same
});Auth.rateLimit is what an operator reads as "what this deployment enforces", so defineAuth
refuses any pairing that would make it a lie:
| Declared | Limiter's own policy | Result |
|---|---|---|
| scope: 'process' (default) | anything, same numbers | boots; the lockout is per replica |
| scope: 'shared' | scope: 'shared', same numbers | boots; one count for the fleet |
| scope: 'shared' | scope: 'process' | X_AUTH_LIMITER_NOT_SHARED |
| maxAttempts/windowMs/lockoutMs | any of the three different | X_AUTH_LIMITER_POLICY_MISMATCH |
The third bucket: one tenant
account:<email> and ip:<addr> were the only key shapes, so one tenant's misconfigured
integration hammering login from 400 addresses was capped by neither — each IP bucket allowed its
own quota, the account buckets protected individuals, and the shared limiter saturated behind
them. orgKey(orgId) is the third shape, reserved in login() once the address resolves to an org
and still before the KDF runs. A locked tenant answers X_ACCOUNT_LOCKED with no org id in it —
the id was looked up from the address the caller typed — and an attempt the tenant cap turns away
is not counted against the account or the address.
rateLimit.orgMaxAttempts is its own number, defaulting to maxAttempts * 20: a whole tenant
sharing five attempts is a denial of service against that tenant. A success on one member's
account clears the account window and deliberately not the tenant one — otherwise the traffic
that proves the tenant is alive is also the traffic that resets its cap. Pass orgLimiter to
defineAuth to share those counters across replicas; unlike limiter, it is not required under
scope: 'shared', because a tenant cap is a throughput ceiling and not a guessing allowance.
Service-to-service
verifyWorkloadToken is the one function, and it reads all three shapes because they are all the
same JWT: a Kubernetes projected service-account token, a SPIFFE JWT-SVID, and a cloud IMDS token.
It is also the shape RFC 8693's subject_token takes.
import { actorFromService, jwksClient, verifyWorkloadToken } from '@ultimat3/auth';
import { type Clock } from '@ultimat3/core';
declare const clock: Clock;
declare const token: string;
const { identity } = await verifyWorkloadToken({
token,
issuers: ['https://kubernetes.default.svc'],
audience: 'https://ledger.internal',
keys: jwksClient({ provider: 'k8s', jwksUri: 'https://kubernetes.default.svc/openid/v1/jwks' }),
clock,
});
const actor = actorFromService(identity); // kind: 'service', id: the caller's own subSignature first, then issuer, audience, exp and nbf. scope (space-delimited) or scp (an
array) become the actor's scopes; a token with neither carries none. There is no trusted-channel
exemption here — the token arrived in a header. The WorkloadToken also carries raw, the whole
decoded payload, read only after every check held — an issuer's own claim (tid, groups) is the
app's to judge. checkWorkloadToken is the same checks as a verdict naming the one that refused.
An external issuer's bearer, as a resolveToken
jwtBearerResolver is apiKeyResolver's twin for a JWT some other issuer minted — an IdP's token
an agent presents to the app's MCP endpoint or a bearer mount:
import { actorFromService, jwksClient, jwtBearerResolver } from '@ultimat3/auth';
const ISSUER = 'https://login.example.com/tenant-a/v2.0';
const keys = jwksClient({ provider: 'idp', jwksUri: `${ISSUER}/discovery/v2.0/keys` });
/** `resolveToken: resolveAgent` — on the mount, and on `defineAppMcp()`. */
export const resolveAgent = jwtBearerResolver({
keys: () => keys,
issuers: [ISSUER],
audience: 'api://ledger',
requiredScope: 'ledger.agent',
accept: (raw) => raw['tid'] === 'tenant-a',
actorOf: (token) => actorFromService(token.identity),
});| Presented | Answer |
|---|---|
| a token every check accepts | { actor: actorOf(token), scopes } — the token's scope/scp as a Set |
| bad signature or alg: none, wrong issuer or audience, expired, not yet valid, without requiredScope, refused by accept | null, plus one auth.jwt_bearer.refused log line naming the check — never a claim's value, never the token |
| a key set that cannot be read, or an unknown kid | null (check: 'key-set'): fail closed, and the two look the same |
| an accept or actorOf that throws | the throw — the app's bug, not a verdict |
keys is a THUNK read when a token arrives, so discovery opens no network at import; hold the
client and return it. The mount answers null as 401 X_UNAUTHENTICATED.
mTLS is out of scope. TLS termination is the mesh's job (axiom
7); the framework's part is reading a trusted
x-forwarded-client-cert through @ultimat3/http's trusted-proxy seam, which that package owns —
and only once the app declares configureHttp({ trustClientCertHeader: true }): trusting the
proxy's x-forwarded-for is not a promise that it strips a certificate header the client sent.
maxKeys is not compared — it bounds one process' table, not a limit. A custom limiter therefore
does not own its own configuration: the policy stays the app's single statement of the limits,
and the boot check is what keeps it true.
A shared limiter ships, As of 2026-10 — postgresAuthLimiter({ executor, clock, policy }),
one table (x_auth_lockouts), one row per key holding the instants still inside the window, so
the window still SLIDES across replicas and a take is ONE statement: forty concurrent guesses
against maxAttempts: 5 are admitted five times. Until it landed,
scope: 'shared' was a declaration nothing in the framework could satisfy while x new scaffolded
replicas: 2 — maxAttempts × 2 guesses per account. executor is a PgExecutor, anything
speaking query(text, values); never Bun.sql, whose .query is undefined.
import {
type AuthAdapter,
type AuthRateLimitPolicy,
DEFAULT_AUTH_RATE_LIMIT,
defineAuth,
orgRateLimit,
type PgExecutor,
postgresAuthLimiter,
} from '@ultimat3/auth';
import { type Clock, systemClock } from '@ultimat3/core';
import { db, type SqlFragment } from '@ultimat3/db';
declare const adapter: AuthAdapter;
const clock: Clock = systemClock;
// The client this process already opened, wrapped in one line.
const client = db();
const executor: PgExecutor = {
query: <R>(text: string, values: readonly unknown[]): Promise<readonly R[]> =>
client.query<R>({ text, values } satisfies SqlFragment),
};
const rateLimit: AuthRateLimitPolicy = { ...DEFAULT_AUTH_RATE_LIMIT, scope: 'shared' };
defineAuth({
adapter,
clock,
rateLimit,
limiter: postgresAuthLimiter({ executor, clock, policy: rateLimit }),
orgLimiter: postgresAuthLimiter({ executor, clock, policy: orgRateLimit(rateLimit) }),
});Both limiters share one table: the keys are prefixed (account:, ip:, org:) and every limit
travels as a statement parameter, so the tenant bucket's wider allowance cannot leak into the
account bucket's. It reports maxKeys: undefined — there is no in-process table to bound — and
the table does not forget on its own.
A limiter of your own implements the same five members:
| Member | Contract |
|---|---|
| reserve(key) | count one attempt atomically; X_ACCOUNT_LOCKED, counting nothing, while the key is locked; the attempt that fills the window is admitted and starts the lockout. Answers { key, atMs } |
| refund(reservation) | remove that ONE attempt, and lift a lockout the window no longer justifies |
| recordSuccess(key) | clear the key — its window and its lockout |
| lockedUntil(key) / reset() | the live deadline or null; drop everything |
| purgeExpired?() | only for a limiter backed by a table |
An app does not have to write any of that, As of 2026-08-22. The boot fills a seam and every
defineAuth in the process picks it up:
// The HOST's code, not an app's: `@ultimat3/cli`'s boot does exactly this. The installer is on
// `@ultimat3/auth/adapter` only (31.0.0) — the `.` barrel carries no setter.
import { type PgExecutor, postgresAuthLimiter } from '@ultimat3/auth';
import { installAuthLimiters } from '@ultimat3/auth/adapter';
import type { Clock } from '@ultimat3/core';
declare const bootExecutor: PgExecutor;
declare const bootClock: Clock;
// In the HOST, before the app's modules import.
installAuthLimiters((policy) =>
postgresAuthLimiter({ executor: bootExecutor, clock: bootClock, policy }),
);A factory and not a limiter, because the host runs before the app: defineAuth compares what a
limiter enforces against what the app declared, so a limiter built at boot on the framework
defaults would be X_AUTH_LIMITER_POLICY_MISMATCH for every app that tuned its numbers. The
factory is called once per bucket, with the resolved policy, so the two halves cannot disagree.
Precedence is defineAuth({ limiter }) → the installed factory → memoryAuthLimiter, and
resetAuthLimiters() (also @ultimat3/auth/adapter) puts the per-process default back. @ultimat3/cli's startServices calls it
on every boot, so a scaffolded app gets a fleet-wide lockout with nothing to remember.
The table does not forget on its own, and purgeAuthLimits() is the framework's reader for that:
it drops every key whose window has emptied and whose lockout has expired, measured against the
clock the host handed the limiter, and it sweeps only the WIDEST window installed — a sweep on a
narrower one deletes attempts another limiter is still counting, which hands a sprayer them back.
@ultimat3/jobs' purge() job is what calls it hourly; x dev and every role container declare
that sweep at boot.
Providers are a registry, not a union
OAuthProviderId is string, and registerOAuthProvider() is the one way a provider gets in —
the two built-ins go through the same call. Before 1.3.0 the id was keyof typeof
OAUTH_PROVIDERS over github | google | apple, so an enterprise OP was unrepresentable: the
constraint was a type, there was no runtime escape, and the only ways out were forking the package
or bypassing OAuth entirely and losing PKCE, the sealed handshake, issuer pinning and account
linking with it. There is still no unregister: registeredOAuthProviders() /
restoreOAuthProviders(providers) are test-only, the pair @ultimat3/testing's rerun seam uses.
import { discoverOAuthProvider, registerOAuthProvider } from '@ultimat3/auth';
// By hand, when you know the four endpoints:
registerOAuthProvider({
id: 'bigco-sso',
authorizeUrl: 'https://sso.bigco.test/oauth2/v1/authorize',
tokenUrl: 'https://sso.bigco.test/oauth2/v1/token',
userInfoUrl: 'https://sso.bigco.test/oauth2/v1/userinfo',
userEmailsUrl: null,
issuers: ['https://sso.bigco.test'],
jwksUri: 'https://sso.bigco.test/oauth2/v1/keys',
scopes: ['openid', 'email', 'profile'],
usesPkce: true, // the literal `true`; `false` does not typecheck, for anyone
usesNonce: true,
clientIdEnv: 'BIGCO_SSO_CLIENT_ID',
clientSecretEnv: 'BIGCO_SSO_CLIENT_SECRET',
});
// Or read them once at boot, from the issuer's own discovery document:
registerOAuthProvider(await discoverOAuthProvider({ id: 'bigco-sso', issuer: 'https://sso.bigco.test' }));| Call | Answers |
|---|---|
| registerOAuthProvider(provider) | the frozen provider; X_OAUTH_PROVIDER_DUPLICATE on a second claim of one id |
| providerFor(id) | the provider, or throws X_OAUTH_PROVIDER_UNKNOWN — never undefined |
| hasOAuthProvider(id) | whether the id is registered |
| BUILTIN_OAUTH_PROVIDER_IDS | the two shipped ids — the only list an anonymous refusal is built from, and it is named in the auth.oauth.refused log line, never in the response body |
| oauthProviderIds() | every registered id, live. NOT what defineAuth({ providers }) defaults to — that is [], so an app names what it enabled |
discoverOAuthProvider refuses a document with no jwks_uri: without a key set there is nothing
to check an id token's signature against, and the token-endpoint TLS exemption below is a thing a
caller declares, not one a provider inherits by omission. It refuses a document whose issuer is
not the one asked for, too (OIDC Discovery §4.3).
Public clients (As of 2026-10-18). tokenEndpointAuth on the provider — or on
discoverOAuthProvider({ tokenEndpointAuth }), or per exchange on credentials — says how the
client authenticates at the token endpoint:
| tokenEndpointAuth | Secret read from clientSecretEnv | Sent |
|---|---|---|
| absent / 'client_secret_post' | required (X_ENV_MISSING) | client_secret in the form body — the behaviour before the option |
| 'client_secret_basic' | required | Authorization: Basic base64(urlencode(id):urlencode(secret)); no client_secret in the body |
| 'none' | not read; a leftover value is ignored | no secret at all — client_id and the PKCE code_verifier only |
import { discoverOAuthProvider, registerOAuthProvider } from '@ultimat3/auth';
registerOAuthProvider(
await discoverOAuthProvider({
id: 'equipo',
issuer: 'https://sso.example.test',
tokenEndpointAuth: 'none', // needs EQUIPO_CLIENT_ID only
}),
);PKCE stays mandatory for all three: for a public client it is the only thing binding the code to the browser that started the flow.
SAML 2.0 is supported natively since 31.0.0 — see SSO: one IdentityProvider port, OIDC and SAML. No dependency: the XML reader, exclusive c14n and XML-DSig verification are this package's own, held to xmlsec-signed vectors.
Id token signatures
verifyIdToken({ keys }) is required to say where its trust comes from. There is no default,
because a default is what silently makes a second door as trusting as the first.
| keys | Means |
|---|---|
| 'token-endpoint-tls' | this token came off a TLS response from the provider's own token endpoint — the one case OIDC Core 3.1.3.7 exempts. Since 26.0.0 the login flow uses it only for a provider with no jwksUri, or when the app names it |
| a JwksKeySource | the signature is checked. providerJwks(providerFor(id)), or jwksClient({ provider, jwksUri }) |
The login flow verifies the signature by default (26.0.0). exchangeOAuthCode, and with it
completeOAuthLogin and oauthLogin's callback, checks the id token against the provider's
published key set (providerJwks, cached per provider, one fetch per TTL) whenever the provider has
a jwksUri — Google and every discovered provider do; GitHub issues no id token. The token-endpoint
exemption trusts every hop the response crossed (a TLS-inspecting proxy, a bad DNS answer); a
signature trusts only the provider. A bad signature is X_OAUTH_TOKEN_INVALID (400) and no session.
An IdP outage does not end every login. A failed refresh leaves a key already held answering for
one more hour past its TTL (JWKS_STALE_IF_ERROR_MS), logged auth.jwks.stale_served; past it,
X_OAUTH_EXCHANGE_FAILED. No fetch runs within 30 s of a failed one (JWKS_FAILURE_COOLDOWN_MS),
so a forged kid costs no request during an outage. Both are constants, not options.
| Where | Option | Default |
|---|---|---|
| exchangeOAuthCode(handshake, callback, { keys }) | keys?: IdTokenKeys | the provider's key set, else 'token-endpoint-tls' |
| completeOAuthLogin(auth, { idTokenKeys }) | idTokenKeys?: IdTokenKeys | same |
| oauthLogin(auth, { idTokenKeys }) | idTokenKeys?: (provider) => IdTokenKeys \| undefined — asked per callback; undefined = the default | same |
import { type Auth, oauthLogin } from '@ultimat3/auth';
declare const auth: Auth;
// An egress that cannot reach one provider's jwks_uri: name the exemption for that provider only.
// `undefined` keeps every other provider on the default — never `providerJwks(providerFor(id))`
// here, which throws for GitHub: it publishes no jwks_uri.
export const login = oauthLogin(auth, {
idTokenKeys: (provider) => (provider === 'bigco-sso' ? 'token-endpoint-tls' : undefined),
});import { providerFor, providerJwks, verifyIdToken } from '@ultimat3/auth';
import { type Clock } from '@ultimat3/core';
declare const clock: Clock;
declare const clientId: string;
declare const idToken: string;
declare const nonce: string;
const keys = providerJwks(providerFor('bigco-sso'));
const claims = await verifyIdToken({ provider: 'bigco-sso', idToken, clientId, nonce, clock, keys });crypto.subtle covers RS256 and ES256, so this costs no dependency. HS256 and alg: none are
refused before a key is even looked up — a symmetric algorithm verified against a public key set
is the classic algorithm-confusion forgery. Keys are cached by kid with a TTL and one unknown
kid triggers exactly one refetch, so a rotation heals itself.
Wire an unsolicited token — IdP-initiated login, response_mode=form_post, back-channel logout,
token exchange — to anything that does not check the signature and an attacker posts a
self-minted JWT with the right iss, your aud, a VP's sub and tomorrow's exp, and gets a
session. That is account takeover with no credential, and it is what this exists to stop.
What an SSO user is allowed to do
oauthLogin(auth, { resolveGrants }). Omit it and a first-time SSO user is created with
roles: [] and orgId: null — an actor every can() denies, and a tenant-scoped read that
throws before the query is built. SSO "works" and the person can do nothing until somebody runs
SQL, so the omission logs auth.oauth.user_created_without_grants rather than passing silently.
import { type Auth, oauthLogin } from '@ultimat3/auth';
declare const auth: Auth;
declare const directory: {
lookup(email: string | null): Promise<{ orgId: string; groups: readonly string[] }>;
};
declare function toRole(group: string): string;
oauthLogin(auth, {
resolveGrants: async (profile) => {
const member = await directory.lookup(profile.email);
return { orgId: member.orgId, roles: member.groups.map(toRole), scopes: [] };
},
});It is a seam and not a group-to-role table: which IdP group means which role is business convention and business convention never ships (axiom 8). What the framework owns is calling it on every login — so removing somebody from a group in the IdP takes effect at their next sign-in, rather than never. A seam that returns the stored answer writes nothing.
The profile is not all the IdP said. resolveGrants(profile, context) takes a second argument
(OAuthGrantContext) for an IdP that keeps authorization facts off the id token — groups,
entitlements, an allowed_oauth_apps claim served on /userinfo only:
import { defineAuth, memoryAuthAdapter, oauthLogin } from '@ultimat3/auth';
const auth = defineAuth({ adapter: memoryAuthAdapter(), providers: ['google'] });
export const { start, callback } = oauthLogin(auth, {
resolveGrants: async (_profile, context) => {
const claims = await context.userinfo();
const apps = Array.isArray(claims['allowed_oauth_apps']) ? claims['allowed_oauth_apps'] : [];
return apps.includes('ledger') ? { roles: ['member'] } : { roles: [] };
},
});| context. | What it is |
|---|---|
| provider | the provider id this login came through |
| tokens | the exchange's OAuthTokens, in flight — the framework stores none of them; keeping one is the app storing a credential |
| idTokenClaims | every claim of the VERIFIED id token, the ones OAuthProfile drops included (hd, groups); null without one |
| userinfo() | the provider's userinfo body, every claim, read with the access token — lazily (no call, no request) and at most once per login; none at all when the profile was already read off userinfo (GitHub), whose body it hands back. A body naming another sub is X_OAUTH_EXCHANGE_FAILED; so is a provider with no userinfo endpoint, and a failed read, which is not remembered |
MFA — TOTP and recovery codes
TOTP is pure functions over a secret and a clock; what is STORED goes through two writers and one
reader, As of 2026-10: the secret is sealed at rest, and a recovery code is consumed atomically.
import type { Auth } from '@ultimat3/auth';
import { enrolTotp, generateRecoveryCodes, saveTotpSecret } from '@ultimat3/auth';
declare const auth: Auth; // the `defineAuth` at the top — `enrolTotp` reads `auth.mfa.issuer`
declare const userId: string;
const enrolment = enrolTotp(auth, { account: '[email protected]' }); // issuer: auth.mfa.issuer
// enrolment.uri -> otpauth://… the QR code
await saveTotpSecret(auth, userId, enrolment.secret); // sealed, onto x_users
const recovery = generateRecoveryCodes(); // { codes, hashes } — show `codes` ONCE
await auth.adapter.updateUser(userId, { recoveryCodeHashes: recovery.hashes });Checking a code at sign-in is completeMfa (below) — it opens the secret, meters the guess and
refuses a spent code; an app does not call verifyTotp on a stored secret itself.
The secret at rest is sealed under the app's master key (purpose: 'auth:x_users.mfa_secret').
A TOTP seed is symmetric, so it cannot be a digest — and in the clear, a dump of x_users was
every enrolled user's second factor.
| | |
|---|---|
| write | saveTotpSecret(auth, userId, secret) — refuses a secret nothing can derive a code from (X_MFA_SECRET_INVALID), needs the master key (X_SEAL_KEY_MISSING) |
| read | openTotpSecret(stored) — refuses a value that is not sealed (X_MFA_SECRET_UNSEALED, fix x auth seal-mfa --json). There is no plaintext fallback, by decision: a fallback kept "for now" is a plaintext column forever |
| rows from before sealing | x auth seal-mfa once, or sealMfaSecrets({ adapter }) on an adapter of your own — idempotent, answers { sealed, alreadySealed, skipped }; each write is a compare-and-set (adapter.replaceMfaSecret), so a re-enrolment mid-run is skipped, never overwritten. x doctor reports how many are left |
| Call | Answers |
|---|---|
| enrolTotp(auth, { account, issuer?, secret? }) | { secret, uri, digits, periodSeconds } — issuer omitted is auth.mfa.issuer, secret omitted mints one |
| verifyTotp({ secret, code, at, drift?, usedSteps? }) | { ok, step }. step is the window the code belonged to, null on no match |
| TotpReplayGuard | one atomic method, claim(subject, step, at): Promise<boolean>: true the first time, false for a replay. A store that cannot answer rejects: a down database is a fault, never a wrong code |
| memoryTotpReplayGuard(drift?, maxSubjects?) | the in-process guard, { claim, isUsed, size }; isUsed is for a test. The default only where no host installed one |
| postgresTotpReplayGuard({ executor }) | the shared guard: x_totp_steps (SQL_TOTP_REPLAY_TABLE), one insert … on conflict do nothing per claim, purgeExpired(nowMs) for the sweep. A framework boot installs it |
| installTotpReplay(() => guard) (@ultimat3/auth/adapter) / resetTotpReplay() (both @ultimat3/auth/adapter) | the host's install point, beside installAuthLimiters. Precedence: defineAuth({ totpReplay }) → the installed factory → memory |
| generateRecoveryCodes(count = 10) | { codes, hashes }. codes is shown once and is never re-derivable |
| recoveryCodeHash(code) | what a code is stored and looked up as — dashes, spaces and case removed first. auth.adapter.consumeRecoveryCode(userId, hash) removes it in ONE statement and answers whether it was there, so two requests carrying one code cannot both redeem it |
| totpStep(at, stepSeconds?) / totpCode(secret, step, digits?) | the RFC 6238 halves, for a test that has to mint a valid code. totpCode throws X_MFA_SECRET_INVALID on a secret that decodes to zero bytes |
A secret the decoder cannot read verifies nothing, As of 2026-08. base32Decode answers
zero bytes for any character outside the alphabet and for '', and an HMAC keyed with zero bytes
is a valid HMAC — so totpCode used to hand back a six-digit code derived from no secret at all,
one stream every malformed row in the table verified against, computable by anyone. Three
answers now, and they differ because their callers do: verifyTotp returns { ok: false, step:
null } (a broken stored credential is the generic failure, the rule verifyAgainst follows for a
hash Bun cannot read — never a throw into the login path, never an oracle); totpCode throws
X_MFA_SECRET_INVALID, because there is no code an unreadable secret is entitled to; and
enrolTotp throws the same code on an imported secret, so a value nothing can ever check never
reaches the table. A minted secret is readable by construction. Note the direction of the failure:
a mfa_secret text not null default '' column now locks that account out of its second factor
instead of accepting a code nobody had to know — re-enrol it with enrolTotp(auth, { account }).
TOTP_DIGITS (6), TOTP_STEP_SECONDS (30) and TOTP_DRIFT_STEPS (±1 window) are exported so an
app's own copy of the parameters cannot disagree with the verifier's.
A step is remembered per subject, not globally: a code is valid for drift windows either
side of now, so without the guard the same six digits log in twice inside a minute. verifyTotp
answers { ok: false, step } — the step still named — when usedSteps already holds it, which is
how a replay is told apart from a wrong code.
The guard's table is bounded (DEFAULT_MAX_TOTP_SUBJECTS, 10,000), because a per-subject map
that only ever grows is one process' lifetime away from an OOM. A subject whose every remembered
step has fallen below the drift floor is forgotten — verifyTotp can never offer that step
again, so the entry answers exactly as a missing one — and only if that is not enough does the cap
evict live state, furthest from the live window first. The order is the guarantee: evicting a
subject makes a step they have already spent replayable, so the subject who just authenticated is
always the last one out.
mfa.required is accepted only as false, and that is deliberate. The field exists and is
typed as the literal false, so required: true is a compile error; a true that reaches
defineAuth from JavaScript or from JSON — where the type cannot — is refused at boot with
X_CONFIG_INVALID naming the key, never an unknown-key error and never a silent accept. Nothing
read it: both credential paths branch on user.mfaSecret alone, so an un-enrolled user was handed
a full session under a config that read as "this deployment requires a second factor". Enforcing it
at login() instead is a lockout — actorFromUser degrades only a user who HAS a secret, and this
package ships no enrolment route to send the rest to. Gate it in your own sign-in handler —
if (user.mfaSecret === null) send them to enrolTotp before you call createSession.
The second leg of login is completeMfa, As of 2026-10. login() and
completeOAuthLogin() throw X_MFA_REQUIRED before any session exists, and the error's
meta.challenge is what carries the proven first leg to the second: a value sealed under the
app's master key (x secrets init; X_SEAL_KEY_MISSING without one), naming the user, good for
MFA_CHALLENGE_TTL_MS (five minutes) on the server's clock. It is meta, never cause — the
problem document publishes cause — so the sign-in handler decides how it travels.
import { type Auth, completeMfa, login } from '@ultimat3/auth';
import { isUltimateError } from '@ultimat3/core';
declare const auth: Auth;
export async function signIn(email: string, password: string, ip: string) {
try {
return { session: await login(auth, { email, password, ip }) };
} catch (error) {
if (!isUltimateError(error) || error.code !== 'X_MFA_REQUIRED') throw error;
return { challenge: String(error.meta?.['challenge']) }; // a cookie, or your own body
}
}
export const secondFactor = (challenge: string, code: string, ip: string) =>
completeMfa(auth, challenge, code, { ip }); // what `login()` answers: actor, session, cookieThe built-in sign-in routes carry it for you: mfaPath, As of 2026-11. oauthLogin(auth)
and identityProviderRoutes(auth, …) own the callback, so there is no handler of yours to catch
X_MFA_REQUIRED in. Give them the path of your second-factor page:
import {
type Auth,
clearMfaChallengeCookie,
completeMfa,
oauthLogin,
readMfaChallenge,
} from '@ultimat3/auth';
declare const auth: Auth;
export const sso = oauthLogin(auth, { successPath: '/app', mfaPath: '/sign-in/mfa' });
/** The POST behind `/sign-in/mfa`: the challenge arrives in the cookie the callback set. */
export async function finishSso(request: Request, code: string): Promise<Response> {
const result = await completeMfa(auth, readMfaChallenge(request) ?? '', code);
const headers = new Headers({ location: '/app' });
headers.append('set-cookie', result.cookie);
headers.append('set-cookie', clearMfaChallengeCookie());
return new Response(null, { status: 303, headers });
}| mfaPath | An enrolled user's callback (OIDC redirect or SAML ACS) answers |
|---|---|
| set | 303 to mfaPath, Set-Cookie: __Host-x_mfa=<sealed challenge> — HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=300 — and the state cookie cleared. No session yet |
| omitted | 401 X_MFA_REQUIRED, no challenge anywhere; the auth.<oauth\|sso>.refused log line's fix is the mfaPath call above. That user cannot finish through these routes |
| not one normalised absolute path on this origin (//host, a scheme, ?, #, \, ..) | X_CONFIG_INVALID, at the call |
The challenge travels in that cookie and nowhere else: never the redirect URL, a response body or a
log line. Only an absent cookie is readMfaChallenge(request) === null: the reader opens nothing,
so an expired or tampered challenge comes back as the string it is, and completeMfa refuses it
(and null ?? '') like any other bad challenge.
One challenge cookie, both halves public, As of 2026-11-19. A sign-in handler of your own
(a password form over login()) carries its challenge in the same cookie the built-in callbacks
write, so one second-factor page serves every first leg:
| Export | What it is |
|---|---|
| mfaChallengeOf(error) | the sealed challenge of an X_MFA_REQUIRED, null for every other throw |
| mfaChallengeCookie(challenge) | the Set-Cookie line that holds it: __Host-x_mfa, HttpOnly; Secure; Path=/; SameSite=Lax, Max-Age the challenge's own five minutes |
| readMfaChallenge(request) | the held challenge as sent, unverified (expiry is completeMfa's), or null when no cookie came |
| clearMfaChallengeCookie() | the Set-Cookie line that drops it, sent with the response that finishes the second leg |
| MFA_CHALLENGE_COOKIE | the cookie's name, for a test that builds a cookie: header or asserts a Set-Cookie |
import { type Auth, login, mfaChallengeCookie, mfaChallengeOf } from '@ultimat3/auth';
declare const auth: Auth;
/** The first leg: a session, or the challenge held for `/sign-in/mfa`. */
export async function signIn(email: string, password: string, ip: string): Promise<Response> {
const headers = new Headers();
try {
headers.append('set-cookie', (await login(auth, { email, password, ip })).cookie);
headers.set('location', '/app');
} catch (error) {
const challenge = mfaChallengeOf(error);
if (challenge === null) throw error;
headers.append('set-cookie', mfaChallengeCookie(challenge));
headers.set('location', '/sign-in/mfa');
}
return new Response(null, { status: 303, headers });
}| completeMfa is given | Answer |
|---|---|
| a live challenge and the current code, or an unused recovery code | { actor, session, token, cookie }, mfaSatisfied: true |
| a wrong code, or one already spent | X_UNAUTHENTICATED; the guess stays counted |
| a value this app did not seal, an expired one, or one for an account now disabled or un-enrolled | X_UNAUTHENTICATED, one refusal for all of them |
| a guess past rateLimit.maxAttempts | X_ACCOUNT_LOCKED — the same account, address and tenant buckets a password guess spends |
A code guess is reserved before it is compared, so six digits are worth maxAttempts tries per
window. Repeating the first leg does not buy them back: a proven password with a second factor
still owed clears nothing — completeMfa is what clears the account's window. A spent step is
claimed through auth.totpReplay, once the code has verified, so a wrong guess never writes and a
lost claim is the same refusal. A booted process holds postgresTotpReplayGuard, so a code is good
once across every replica; with no host, the default is one process' memory. A guard that rejects is
a fault: it propagates, and the guess is not counted. defineAuth refuses a totpReplay with no
claim (X_CONFIG_INVALID). No route ships.
code is either the six digits or a recovery code: anything that is not six digits is hashed
and consumed through the adapter, metered exactly as a wrong digit string is, and gone after one
use. A stored secret that is not sealed is X_MFA_SECRET_UNSEALED (HTTP 500) before any guess is
counted — the deployment's fault, never the caller's.
Email verification and password reset
One issue/consume pair, two purposes. The token is mailed and only its sha256 is stored, and
consuming it is a single conditional statement — the hash is an argument to the consume, never
a comparison after one.
import {
consumeVerification,
issueVerification,
type MailSender,
memoryAuthAdapter,
type VerificationRuntime,
} from '@ultimat3/auth';
import { systemClock } from '@ultimat3/core';
declare const mail: MailSender; // the app wires @ultimat3/mail's `send` here
const runtime: VerificationRuntime = { store: memoryAuthAdapter(), clock: systemClock, mail };
const issued = await issueVerification(runtime, {
purpose: 'password-reset',
identifier: '[email protected]', // the address; also the store key
locale: 'en',
link: (token) => `https://acme.test/reset?token=${token}`,
});
const verification = await consumeVerification(runtime, {
purpose: 'password-reset',
identifier: '[email protected]',
token: issued.token, // in production this arrives off the link
});| Name | Is |
|---|---|
| VERIFICATION_PURPOSES | ['email-verify', 'password-reset'] — the two built in. VerificationPurpose is string (As of 2026-11): any declared name |
| defineVerificationPurpose({ name, template, ttlMs, identifier?, signIn? }) | { name, issue, consume } on the same code path — an invite, an email change, an account deletion. signIn: true declares the one purpose whose link signs its holder in (signInWithLink); absent, it never does. Twice or with no template: X_VERIFICATION_PURPOSE_INVALID. emailVerification and passwordReset are the built-in instances |
| defineMemberInvite({ name?, template, ttlMs }) | { purpose, invite, accept, revoke }: a single-use invite keyed on (tenant, address). accept consumes it under the signed-in account's own address, sets orgId/roles and rotates the session; revoke kills the link and, only where this flow granted it, the membership and that account's sessions; a revoke racing an accept wins. Every bad link is X_UNAUTHENTICATED; a member of another tenant is X_FORBIDDEN. Functions, not actions (tier 2): the app wraps each in its own action() — x g invite writes them |
| VERIFICATION_TEMPLATES | purpose → catalog key (auth.email-verify, auth.password-reset), never copy: the body lives in the app's i18n catalog |
| DEFAULT_VERIFICATION_TTL_MS | 24 h for email-verify, 1 h for password-reset — a reset link is a password |
| MailSender | the injected port: send(template, to, data, locale). @ultimat3/mail is tier 4 and this package is tier 2, so the app wires it |
| issueVerification(runtime, input) | { token, expiresAt }. The token comes back for a test or a CLI; production only ever mails it. to? names the recipient, and only on a purpose declared recipient: 'explicit' (the member invite: its identifier is tenant + address, not an address): mail goes to that to, never normalised, and it is required. On any other purpose, passwordReset and every sign-in purpose included, a to is X_CONFIG_INVALID before any row is written, so a request body spread into issue cannot redirect a reset link |
| consumeVerification(runtime, input) | the AuthVerification row, or X_UNAUTHENTICATED. Unknown, spent, expired and mismatched are one answer. Reads only { store, clock } of the runtime. An undeclared purpose on either door is X_VERIFICATION_PURPOSE_UNKNOWN |
One live token per (purpose, identifier). A wrong guess destroys nothing: the store's
takeVerification(purpose, identifier, tokenHash) matches before it consumes, so an
unauthenticated POST with any token cannot kill the victim's live link.
Signing in with a mailed link
As of 2026-11. signInWithLink(auth, { purpose, identifier, token, ip?, userAgent?, signUp? })
consumes a link issued under a purpose declared signIn: true and answers what login() answers.
With TOTP enrolled it answers X_MFA_REQUIRED and writes no session:
completeMfa(auth, challenge, code, { ip, userAgent }) finishes it, as after a password. ip and
userAgent go on the session the call writes: the link's, or with TOTP the second leg's.
Redemption needs the address as well as the token. The mailed URL carries the token only, so the page it opens asks for the address (prefilled where the same browser asked for the link) and posts both: an address in the URL lands in every log and referrer the link passes through.
| Case | Answer |
|---|---|
| valid link, no second factor | LoginResult, the session mfaSatisfied |
| valid link, TOTP enrolled | X_MFA_REQUIRED with meta.challenge; no session row. A fresh link never clears the count of wrong codes |
| a link already consumed (its own address and token), whatever that attempt ended in | X_UNAUTHENTICATED: the link is spent before anything else is read. A try with the wrong address consumes nothing, so the link stays live for the right one |
| unknown, expired, mismatched or another purpose's token | X_UNAUTHENTICATED, and a wrong guess leaves the mailed link live |
| no account at the address | X_UNAUTHENTICATED, and the link is spent: enabling signUp takes a freshly mailed one. With signUp: { id?, orgId?, roles?, scopes?, externalId? } a passwordless account is created verified: in the creating write on an adapter that stores CreateUserInput.emailVerifiedAt (both built-in ones do). An app adapter that drops it gets a second updateUser stamp; if that write fails the call is X_AUTH_WRITE_FAILED, the account exists unverified, and the next link is refused as one that never verified its address. signUp never changes an account that exists |
| a disabled account | X_UNAUTHENTICATED, naming nothing |
| an account that never verified its address | X_UNAUTHENTICATED, named: whoever registered it chose its password. A verification stamp alone leaves their credentials intact. Recovery requires an app-owned flow: consume a passwordReset to prove the inbox, keep the account disabled while clearing every credential and session, and atomically verify recovery still owns the disable before stamping and reopening. Coordinate every administrative disable with that ownership check; updateUser and enableUser do not provide it. If ownership is lost or cleanup fails, leave the account disabled |
| purpose is 'email-verify' or 'password-reset', is not declared signIn: true, or declares an identifier other than the exported normaliseEmail | X_CONFIG_INVALID, before the store is asked: the token stays live for its own job |
| purpose names nothing defineVerificationPurpose declared | X_VERIFICATION_PURPOSE_UNKNOWN, before the store is asked |
Passkeys — WebAuthn sign-in and digest-bound step-up
As of 2026-11. Verified by hand on Bun's WebCrypto — CBOR, COSE (ES256, RS256) and DER parsed in
this package, no WebAuthn dependency. Declared once: defineAuth({ passkeys: { rpId, origins } })
(X_CONFIG_INVALID at definition for an rp id that is not a bare host, or an origin not on it).
import { defineAuth, memoryAuthAdapter, passkeyLogin, passkeyStepUp } from '@ultimat3/auth';
import { newPasskey, getPasskey } from '@ultimat3/auth/client';
const auth = defineAuth({
adapter: memoryAuthAdapter(),
passkeys: { rpId: 'localhost', origins: ['http://localhost:3000'] },
});
const passkeys = passkeyLogin(auth);
declare const userId: string;
// Each server call sits in one of the app's own actions; its options travel to the browser as
// JSON, where the browser half (`@ultimat3/auth/client`, in an island) answers them.
const created = await newPasskey(await passkeys.registerOptions({ userId }));
if (created.status === 'ok') await passkeys.register({ userId, response: created.response });
const asserted = await getPasskey(await passkeys.loginOptions());
if (asserted.status === 'ok') {
const { actor, cookie } = await passkeys.login({ response: asserted.response });
}
// Step-up: the WebAuthn challenge is derived from a nonce, the user and a digest the SERVER
// computes from the action's input — a caller can only present what was asked for.
const erase = passkeyStepUp<{ readonly memberId: string }>(auth, {
ttlMs: 60_000,
digest: ({ input }) => `erase-member:v1:${input.memberId}`,
});| Export | What |
|---|---|
| passkeyLogin(auth) | { registerOptions({ userId }), register({ userId, response }), loginOptions(), login({ response, ip?, userAgent? }) } — login answers login()'s LoginResult, MFA-satisfied |
| renamePasskey(auth, { userId, id, label }) | the owner's passkey renamed (label: null clears it): the updated PasskeyCredential, or null when userId holds no passkey with that id. A label is 1-PASSKEY_LABEL_MAX (64) characters after trimming, then no control character or lone surrogate, else X_PASSKEY_LABEL_INVALID (422). Named right after register, or any time later An adapter with no renamePasskey member is X_PASSKEY_RENAME_UNSUPPORTED (501) |
| passkeyStepUp(auth, { digest, ttlMs? }) | { options({ userId, input }), verify({ userId, input, response }) }; verify answers the stored PasskeyEvidence or throws X_PASSKEY_STEP_UP_REQUIRED (no proof, a proof for other bytes, no passkey registered) |
| verifyPasskeyEvidence(evidence, { rpId, origins }) | true only when the row is a user-verified signature, by its own key, over the challenge its nonce, digest and user derive — no adapter, no clock: a separate process re-checks it |
| @ultimat3/auth/client | newPasskey, getPasskey, passkeysSupported: outcomes ok / cancelled / unsupported / failed, never a throw. Two modules, ~2.3 kB minified (client-bundle.test.ts) |
| testing a ceremony | softAuthenticator({ origin }) from @ultimat3/auth/soft-authenticator: real WebCrypto keys answering create / get — this package's own suites and an app's share the one implementation and the one path |
| PasskeyStore | the nine AuthAdapter members, and the optional renamePasskey, over x_passkeys (its label column added at every boot), x_passkey_challenges (sha256 of the challenge, TTL, taken by DELETE … RETURNING) and x_passkey_evidence; both adapters, one suite (passkey-store.test.ts, PGlite) |
Every ceremony checks clientDataJSON's type, the origin exactly, rpIdHash, UP and UV, the
signature under the stored key's algorithm, and a counter that must move forward unless both are
zero. Registration asks attestation: 'none' and trusts no statement. Which check failed is the
auth.passkey.refused log line; the code is X_PASSKEY_INVALID, X_PASSKEY_CHALLENGE_EXPIRED
(unknown, spent or late — one answer) or X_PASSKEY_STEP_UP_REQUIRED.
Authorization server
authorizationServer({ issuer, store, consentPath, lifetimes, scopes, … }) (As of 2026-11) — an
OAuth 2.1 server: authorization code + PKCE (S256 only), refresh rotation with replay revocation,
client_credentials, the device grant, RFC 7009/7662/7591/8414/8707/9207. routes go in
runtime.routes; the consent and device pages are the app's (readRequest/approve/deny,
readDevice/approveDevice/denyDevice); the consent page reads with
readRequest(url, { callerKey }) — every metadata-document fetch is metered, and an absent
callerKey shares one bucket with every other unkeyed read. oauthBearerResolver(server, { actor, resource? }) is
the resolveToken. resolve answers the token's grantId (the grant it was issued under — a user's consent, or a
client_credentials client's own — kept across refresh rotation); grants({ subject, clientId? })
lists a subject's unrevoked grants holding at least one stored token neither expired nor retired,
and revokeGrant({ subject, grantId }) ends one of them alone — counted once under racing calls
when the store implements revokeLiveGrant (the memory and Postgres stores do). Stores: memoryAuthServerStore(), postgresAuthServerStore({ executor })
over SQL_AUTH_SERVER_TABLES, which the boot applies. A code is spent only by a request that could
redeem it: client, PKCE verifier, redirect_uri and resource are checked on getCode before
takeCode marks it used, so a request without the verifier neither burns a login nor trips the
replay revocation. pollDevice(hash, clientId, at) stamps only the issuing client's poll. A client
authenticates only with its registered token_endpoint_auth_method (the other is invalid_client),
and gets refresh tokens only if its grantTypes list refresh_token (else refreshing is
unauthorized_client). registerClient — the app's own path — refuses a redirect URI, grant,
scope or resource that is empty or holds whitespace (X_AUTH_CLIENT_INVALID, naming the field):
the Postgres store keeps each list space-joined, so such a value would read back as a different
list. /oauth/register (registration: 'dynamic') is anonymous, so it is bounded: at most 10
redirect_uris of at most 2,048 characters each (else invalid_client_metadata, nothing stored),
scope deduplicated, and every bucket of this server keyed by network (ipKey: an IPv6 /64 is
one caller), registrations and metadata fetches alike. The client it writes has a d_ id
(registerClient's are c_), and purge deletes a d_ client created before the refresh idle
window that no grant, code or device code names; a c_ client is never purged. A metadata-document client carries
host, its client_id's host — the one thing on the consent page its author does not choose:
show it beside name. Full table and the rule each test holds:
wiki Auth.
| File | Job |
|---|---|
| authorization-server.ts | the factory and the consent calls |
| authorization-server-config.ts | options, screened once (X_AUTH_SERVER_INVALID) |
| authorization-server-request.ts | screening an authorize request — pure |
| authorization-server-clients.ts · -register.ts | metadata-document and registered clients, secrets · RFC 7591 |
| authorization-server-tokens.ts | opaque hashed tokens, PKCE, resolve |
| grant-authorization-code.ts · grant-client-credentials.ts · grant-device.ts | the grants |
| token-endpoints.ts | revocation, introspection |
| authorization-server-routes.ts · -wire.ts | the routes · the structural Route shape, forms, client auth, RFC 6749 JSON |
| authorization-server-store.ts · -postgres*.ts · -schema.ts | the contract + memory · Postgres · DDL |
| oauth-bearer-resolver.ts | grant → { actor, scopes }, per call |
Revocation, offboarding and access review
| Call | Blast radius |
|---|---|
| revokeSession(runtime, id) | one session |
| revokeOtherSessions(runtime, userId, keep) | every session but the caller's |
| revokeUserSessions(auth, userId, reason) | one person, their current session included |
| revokeOrgSessions(auth, orgId, reason) | one tenant, at 03:00, without touching another |
| revokeSessionsCreatedBefore(auth, at, reason) | everything minted under a rotated secret |
| disableUser(auth, userId, reason) | stamps disabledAt, kills the sessions and revokes the user's live api keys — { user, sessionsRevoked, apiKeysRevoked }. Re-enabling restores neither |
| listOrgUsers(auth, orgId, { role }) | the quarterly access review, as safe summaries — in byte (code-point) order of email on both adapters, whatever the database collation |
| findUsersByIds(auth.adapter, ids) | none: a read. The people a screen found elsewhere (a membership list, an audit trail), in one statement on postgresAuthAdapter (where id = any($1::uuid[])). Ordered by each id's first appearance in ids; an unknown id is absent, a repeated one answered once, [] reads nothing. More than MAX_USERS_BY_IDS (1000) ids, repeats counted, is X_AUTH_USER_IDS_TOO_MANY before any read (As of 2026-11) |
| updatePrivileges(auth, userId, patch, session?) | the grant, plus the session rotation it requires. A passwordHash change ends every OTHER session of that user (sessionsRevoked) — all of them when no session of theirs was passed, as in a reset |
Rotation (rotateSession, and updatePrivileges through it) mints a new id, never a new
lifetime: createdAt and absoluteExpiresAt carry over, so repeated grants cannot outlive the
original ceiling and revokeSessionsCreatedBefore still catches a rotated session. The rotated
cookie's Max-Age counts down to that ceiling. createSession accepts the same two instants and
clamps them — createdAt to now, the ceiling to createdAt + absoluteTtlMs — so they only shorten.
reason is a required argument on every revocation, for the reason crossTenant() requires one:
an incident review asks who killed these sessions and why, and a delete with no line answers
neither. Each one logs auth.revocation before it runs.
deleteSessionsForOrg joins through x_users and x_sessions deliberately does not gain an
org_id: a denormalised copy of the membership goes stale the moment somebody moves org, and a
stale row means the sweep leaves live exactly the sessions it was run to kill.
describeUser is an allow-list, never a delete-list — a column added to AuthUser later must not
appear in an admin response by default. No password hash, no TOTP secret, no recovery-code hash.
Adapter seam
AuthAdapter (adapter.ts) is the only persistence interface. Better Auth binds here — it is
an adapter implementation, not a dependency of this package.
| Driver | Use |
|---|---|
| postgresAuthAdapter(client?, clock?) | Postgres via @ultimat3/db (the PostgresAuthAdapter type) — the process client and systemClock by default; the clock stamps x_verifications.consumed_at |
| memoryAuthAdapter(clock?) | x new before a database exists, and every test in this package (the MemoryAuthAdapter type). Its clock — systemClock by default — stamps every instant it writes |
| your own | implement AuthAdapter; DDL in tables.ts shows what the columns mean |
An adapter stores and matches the address it is handed — it never folds case. x_users.email
is a plain case-sensitive text ... unique, so an adapter that lowercased found accounts Postgres
would not. Normalisation happens once, above the seam, in normaliseEmail (email.ts): trim and
lowercase, nothing else. Call it before findUserByEmail/createUser in any login route of your
own, and key any bucket of your own with it — accountKey does.
Every member of the seam is required — an adapter missing one is a compile error, never a runtime
refusal — except two, both As of 2026-11: getSessionWithUser(id) and findUsersByIds(ids).
getSessionWithUser(id) is the session and its user in ONE read,
{ session, user | null } or null. authenticate uses it when present and makes the two reads
it replaces (getSession, then findUserById) when not, so an adapter written before it still
binds. Both shipped adapters carry it; authAdapterConformance holds one that does to answering
exactly what the two reads answer.
For findUsersByIds(ids), call findUsersByIds(adapter, ids): it uses the member when present
and one findUserById per distinct id (8 at once) when not — the same bound, order and answer.
Both shipped adapters carry it; authAdapterConformance holds it. Rows come back by first
appearance with misses left out, so pair a row with its id by user.id, never by position. On
Postgres an id the uuid type refuses is absent, and any spelling it reads (either case, no
hyphens, braces) matches as findUserById does.
x_users gained two columns in 1.3.0 — scopes text[] and external_id text unique — plus an
org_id index.
The framework applies the whole schema at boot, upgrades included — As of 2026-09-23
(22.0.0). AUTH_TABLES (with AUTH_TABLE_NAMES) is a row of @ultimat3/cli's
FRAMEWORK_SCHEMA, which every boot applies in foreign-key order: create table if not exists,
then add column if not exists for what an older table lacks, so a database created on 1.2 is
brought up to date with no hand-run migration. There is nothing to paste: the per-table X_*_TABLE
constants and X_USERS_MIGRATION_1_3 are gone, and a hand-written migration that pasted them
should be deleted. They are still not entity() declarations, so x db gen does not see them.
Read the DDL from @ultimat3/auth/schema, a leaf — As of 2026-11-10. It exports
AUTH_TABLES, AUTH_TABLE_NAMES, AUTH_SERVER_TABLES, SQL_AUTH_SERVER_TABLES,
SQL_AUTH_LIMIT_TABLES, SQL_TOTP_REPLAY_TABLE and AUTH_LOCKOUTS_STORAGE, and imports no auth
runtime: 2 auth modules, not the barrel's 106, plus @ultimat3/db, whose tableDdl renders
x_auth_lockouts from AUTH_LOCKOUTS_STORAGE — tableStorage('x_auth_lockouts', { unlogged: false }),
LOGGED and stated, so every boot's alter … set logged converges a hand set unlogged and drift
compares the same value against pg_class (As of 2026-11-11). FRAMEWORK_SCHEMA reads the leaf
and already loads db, which took ROLE=migrate from 977 modules to 873. The . barrel exports the
same seven values, so a caller that also needs postgresAuthAdapter or a store keeps one import.
import { AUTH_TABLE_NAMES, AUTH_TABLES } from '@ultimat3/auth/schema';Sessions are not a write path
verifySession used to UPDATE x_sessions … RETURNING * on every authenticated request: one
request was a SELECT, a write and a second SELECT before the app's own first query. At 20k rps
that is 20k writes a second on one hot table, autovacuum falls behind, and the incident reads as
"the database is slow".
SessionPolicy.idleSlideMs — defaulting to idleTtlMs / 20 — is how far lastSeenAt may drift
before a request writes it forward. A second request inside that window issues no write at all. A
changed IP or user agent is still written immediately, because that is the row a device list and
an incident review read. The trade is bounded and explicit: idle expiry is now precise to within
one idleSlideMs.
One statement per authenticated request on postgresAuthAdapter (As of 2026-11-11, was 2):
getSessionWithUser joins x_sessions to x_users by the session id, and the secret half and
both clocks are checked on the row it returns exactly as verifySession checks them
(admitSession, one copy). A request that slides the idle window adds the one write above.
Counted on PGlite by authenticate-statements.test.ts. A hook that needs the session and the user
rather than an actor calls the same read: verifySessionWithUser(auth.sessions, auth.adapter, token)
answers { session, user } (user: null when the session outlived its user — delete the session and
refuse), one join on an adapter with getSessionWithUser, else verifySession then findUserById.
Revocation is unaffected, and deliberately so. authenticate re-reads the user row on every
request — in that same join — so a revoked role takes effect on the very next one with no token-expiry lag — a better
property than any claims-in-a-JWT design. Throttling the session write is safe; caching the user
row would not be, and nothing does.
Cookie
__Host-x_session, set by sessionCookie(token, policy). A rotated session keeps its
original ceiling, so its cookie takes the time left, not the full TTL:
sessionCookie(issued.token, policy, { maxAgeSeconds: remainingMaxAgeSeconds(issued.session, clock.now()) })
— what updatePrivileges already does for you.
An action sets any of these lines with @ultimat3/http's setCookie(line), As of 2026-11:
setCookie(sessionCookie(issued.token, policy)), or setCookie(signedIn.cookie) with what login()
answered. This package cannot call it (both are tier 2), so it answers the line and the caller sends
it. No attribute is respelled at the call site.
| Attribute | Attack it closes |
|---|---|
| HttpOnly | XSS reading document.cookie and exfiltrating the session |
| Secure | a network attacker lifting it off a plaintext request |
| SameSite=Lax | CSRF — the cookie is not attached to cross-site POSTs |
| __Host- + Path=/ + no Domain | a sibling subdomain overwriting it (session fixation) |
| Max-Age | a client keeping it past the server's absolute ceiling |
Every cookie this package writes — the session, its clearing line, the OAuth handshake and its
clearing line — is built by @ultimat3/core's serializeSetCookie, never spelled by hand
(bun run set-cookie-literals). As of 2026-10-06 the attributes are written Max-Age=…; Path=/
rather than Path=/; Max-Age=… — the same cookie to a browser, which gives attribute order no
meaning — and a cookie name that is not an RFC 6265 token is X_COOKIE_INVALID instead of a
line a browser would mangle.
Signing out
logout(auth, token) ends the session row. The response does the rest: append
signOutHeaders() to it.
import type { Auth } from '@ultimat3/auth';
import { logout, signOutHeaders } from '@ultimat3/auth';
declare const auth: Auth; // your defineAuth(...)
declare const token: string; // the session token the request carried
declare const ctx: { readonly headers: Headers }; // the request context
await logout(auth, token);
for (const [name, value] of signOutHeaders({ session: auth.sessions.policy })) {
ctx.headers.append(name, value);
}| Header | Why |
|---|---|
| set-cookie expiring the session cookie | only when session is passed — an app with its own cookie expires that itself |
| clear-site-data: "cache", "storage" (SIGN_OUT_CLEAR_SITE_DATA) | drops everything the previous principal left on the origin: the page store's IndexedDB, local storage, the service worker and its cached private pages. Never "cookies" — the same response sets the cookie that marks the browser signed out |
The browser acts on Clear-Site-Data only in a secure context (HTTPS, or localhost), which is
every deployed app and every x dev. The cost is one worker reinstall and re-precache per
sign-out: a PWA's offline cache does not outlive the person it was cached for. The realtime side of
the same fence is in packages/realtime/README.md (a principal change wipes
the previous scope's persisted rows and queued writes).
OAuth — log in with GitHub
oauthLogin(auth) is the flow. Two route descriptors, mounted at two fixed paths, composing
beginOAuth, the handshake cookie and completeOAuthLogin. Provider configs stay pure data —
importing oauth.ts performs no network I/O and reads no env.
Mount both in the app's own server through runtime.routes: apps/<app>/runtime.ts
exporting runtime (RuntimeOverrides). x dev and runRole both read that file and mount its
routes through the whole pipeline — configureAuthenticator, the rate limiter, the security
headers, the SIGTERM drain. Never a second Bun.serve beside the app: it stands on its own
socket, outside every one of those, and a login flow is the last surface that should run
unthrottled and unheadered.
// apps/web/runtime.ts
import {
type AuthRouteDescriptor,
defineAuth,
oauthLogin,
postgresAuthAdapter,
} from '@ultimat3/auth';
import type { ServeOptions } from '@ultimat3/cli/serve';
import type { Route } from '@ultimat3/http';
// The app's one `auth` — imported from wherever it declares it.
const auth = defineAuth({ adapter: postgresAuthAdapter(), providers: ['github'] });
const { start, callback } = oauthLogin(auth);
// A descriptor takes a bare `Request`: the pipeline's `UltimateRequest` carries it as `raw`.
const mounted = (leg: AuthRouteDescriptor): Route => ({
method: leg.method,
path: leg.path,
handler: (request) => leg.handle(request.raw),
// Verbatim: the SAML ACS (POST) declares `csrf: 'cookieless'` + `authenticate: () => null`,
// because the IdP answers with a cross-site form. Hand-copy `name`/`auth` a