Auth
The auth module covers the authentication lifecycle: password hashing and verification, passwordless login by a code in the mail, server-side sessions with opaque tokens, one-time tokens for email verification and password reset, and OAuth providers. It holds no state and knows no framework: storage is an AuthDbAdapter, and the cookie that carries a session token belongs to the framework adapter or to your code.
Storage is an AuthDbAdapter: implement it against your schema, or run on @loewen-digital/flatdb with createFlatdbAuthAdapter from @loewen-digital/fullstack/auth/flatdb. The Auth on flatdb guide covers that setup locally and on Cloudflare Workers, with the session module on the cookie driver and the SvelteKit adapter.
Import
import { createAuth } from '@loewen-digital/fullstack/auth'Setup
createAuth(config, { db }) takes the lifetimes and the adapter. Every option has a default; the adapter is required.
import { createAuth, type AuthDbAdapter, type AuthUser } from '@loewen-digital/fullstack/auth'
declare const db: AuthDbAdapter // yours, or createFlatdbAuthAdapter(...) from the guide
const auth = createAuth({ sessionTtl: 7 * 24 * 3600 }, { db })Passwords and login
Registration is yours: hash the password and store the user with its passwordHash where the adapter's findUserByEmail finds it again. Login verifies the hash and opens a session. The session's token is opaque; it goes into an httpOnly cookie (setAuthCookie in SvelteKit) and is the only thing the browser holds. The store holds only its SHA-256 hash, so a backup or a bucket listing of the sessions logs nobody in.
async function register(email: string, password: string) {
const passwordHash = await auth.hashPassword(password)
// store { email, passwordHash } in your users table or collection
return { email, passwordHash }
}
async function login(email: string, password: string) {
const user = await db.findUserByEmail(email)
if (!user?.passwordHash || !(await auth.verifyPassword(password, user.passwordHash))) {
return null
}
return auth.createSession(user) // { id, userId, token, expiresAt, createdAt }
}Hashing is scrypt through node:crypto; the parameters travel in the hash. createSession deletes the user's expired sessions before it inserts the new one (decision 0002), so the sessions of a user who comes back stay bounded without a scheduled job. What the others leave behind takes a sweep.
The current user
validateSession(token) returns the AuthSession behind a token, or null when the token is unknown or expired; an expired session is deleted on the way. The session carries the user id, the user record is one adapter call away. Its token is the one you presented, so destroySession(session.token) works on what validateSession returned.
async function currentUser(token: string | undefined) {
const session = token ? await auth.validateSession(token) : null
return session ? db.findUserById(session.userId) : null
}Signed in while in use
By default a session ends sessionTtl after the login, however often it is used. With sessionExtendAfter a session that is validated gets a new expiry, sessionTtl from that moment, so a user who keeps coming back stays signed in and one who stays away for sessionTtl is signed out.
const sliding = createAuth(
{ sessionTtl: 30 * 24 * 3600, sessionExtendAfter: 24 * 3600 }, // at most one write per session and day
{ db },
)
async function sessionForRequest(token: string) {
const { session, extended } = await sliding.touchSession(token)
// extended: the store holds a later expiry now; send the cookie again so it lives as long
return { session, sendCookieAgain: extended }
}sessionExtendAfter is the shortest time between two writes: a session is extended when its login or its last extension lies at least that many seconds back, and every validation in between only reads. 0 writes on every validation. validateSession extends the same way; touchSession also says that it did, which is what the SvelteKit and fetch adapters ask to send the auth cookie again. The Nuxt, Remix and Astro adapters extend the session and leave the cookie to you. A session that has run out is not brought back, and an expiry never moves earlier: after a shorter sessionTtl the sessions that are out keep the end they were given. There is no upper limit to how long a session that stays in use can live (decision 0028).
A write that fails does not fail the request. The session was found and is valid, only its later expiry could not be stored: touchSession and validateSession answer it as the store holds it, with extended: false, so the adapters send no refresh cookie for that request, and the error goes to onError of the config (default console.error). The next validation tries again (decision 0030).
Logout
destroySession(token) ends one session. destroyUserSessions(userId) ends every session of the user, the caller's included: logout on every device, or the response to a stolen cookie.
async function logout(token: string) {
await auth.destroySession(token) // then clear the cookie
}
async function logoutEverywhere(userId: string | number) {
await auth.destroyUserSessions(userId) // every device; clear the caller's cookie too
}Email verification and password reset
Both mint a one-time token, hand it to your send function together with the address, and consume it later. A token works once and expires after emailVerificationTtl or passwordResetTtl. Sending a new one replaces the user's earlier tokens of that type, so only the latest link works: a verification mail to a previous address cannot verify the current one. A token that is presented is deleted, consumed or expired, so nothing piles up for active users. Only the mail carries the token; the store holds its SHA-256 hash.
A password reset revokes every session of the user: a reset is the recovery path after a takeover, and a session the attacker opened must not survive it. It returns the user, so the browser that reset the password gets a fresh session from createSession; or send it to login.
async function sendMail(to: string, subject: string, text: string) {
// mail.send({ to, subject, text }) from @loewen-digital/fullstack/mail, or any transport
}
async function startVerification(user: AuthUser) {
await auth.sendVerificationEmail(user, (email, token) =>
sendMail(email, 'Verify your email', `https://example.com/verify?token=${token}`),
)
}
async function finishVerification(token: string) {
const user = await auth.verifyEmail(token) // AuthUser | null; marks the email verified
return user !== null
}
async function startReset(user: AuthUser) {
await auth.sendPasswordResetEmail(user, (email, token) =>
sendMail(email, 'Reset your password', `https://example.com/reset?token=${token}`),
)
}
async function finishReset(token: string, newPassword: string) {
const user = await auth.resetPassword(token, newPassword) // AuthUser | null; every session of the user is gone
return user ? auth.createSession(user) : null // a fresh session for this browser, its cookie via setAuthCookie
}Login by e-mail code
Passwordless login without a link: the user asks for a code, gets six digits by mail and types them into the browser that asked. A link would open in the mail app's browser, and the session cookie would land there. sendLoginCode and verifyLoginCode need loginCodeSecret in the config and throw without it.
const codes = createAuth({ loginCodeSecret: process.env.LOGIN_CODE_SECRET! }, { db })
async function requestCode(email: string) {
const user = await db.findUserByEmail(email)
// Answer the same either way, so the response does not tell which addresses have an account.
if (!user) return
await codes.sendLoginCode(user, (to, code) => sendMail(to, 'Your login code', `${code} is your code. It works for 10 minutes.`))
}
async function loginWithCode(email: string, code: string) {
const user = await db.findUserByEmail(email)
if (!user || (await codes.verifyLoginCode(user, code)) === null) return null
return codes.createSession(user) // session.token goes into the auth cookie
}What keeps six digits safe:
- Per user. The code is looked up by user, never by its value, so two users holding the same digits cannot log in as each other.
- One at a time, once. Sending a new code replaces the user's earlier one. A code that verifies is deleted; so is one found expired, after
loginCodeTtl(10 minutes). - Five attempts. Every
verifyLoginCodecounts againstloginCodeAttempts, the right code included, and the count is taken before the code is compared. With the fifth the code is deleted: after five wrong codes the right one fails too, until a new code is sent. - Not in the store. A random token's SHA-256 is safe to store; a six-digit code's is not, since a million values are tried in an instant. The store holds the code's HMAC under
loginCodeSecret, so reading the store does not give the code away. Keep the secret where the store is not: an environment secret, not a document. Changing it invalidates the codes that are out.
What stays yours: rate limit the endpoint that sends codes, per address and per client (security), or anyone can fill a mailbox; and limit the endpoint that verifies them, because the attempt count is exact only where the adapter counts atomically. The flatdb adapter reads, adds one and writes, so guesses that arrive in the same instant can share a count.
Other one-time tokens
The same mechanism is open for your own flows (invitations, magic links). verifyToken returns the user id and consumes the token.
async function invite(user: AuthUser) {
return auth.generateToken(user.id, 'invite', 3600) // type + TTL in seconds
}
async function acceptInvite(token: string) {
return auth.verifyToken(token, 'invite') // string | number | null
}Expired sessions and tokens
The module tidies up after the user it is dealing with: createSession removes that user's expired sessions, an expired session or token is deleted when it is presented, and a new token replaces the earlier one of its type. What an account leaves behind that does not come back stays in the store: its last sessions and up to one token per type, expired, until the account is deleted.
sweep() removes all of that: every session and every one-time token that has expired, login codes included, whoever it belongs to. It answers how many.
async function tidyUp() {
const { sessions, tokens } = await auth.sweep() // { sessions: 12, tokens: 3 }
return sessions + tokens
}- When it runs is yours. Nothing in the module calls it. Call it from what runs on a schedule, or after a sign-in where nothing does: the app is awake then anyway.
- What has not expired is untouched. A session or token is valid up to and including its
expiresAt, here as everywhere else in the module. - The adapter does the work.
sweep()needsdeleteExpiredon the adapter and throws without it: zeros would read as "nothing had expired" (decision 0040). The flatdb adapter has it.
OAuth
oauthProvider(name, config) builds a provider; google and github are built in. Redirect the browser to getAuthorizationUrl(state), keep state in the session, and on the callback hand code and the returned state to handleCallback. It returns the provider's tokens and a normalized user; finding or creating your own user and calling createSession is yours.
const github = auth.oauthProvider('github', {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
redirectUri: 'https://example.com/auth/github/callback',
})
function startGithubLogin() {
const state = crypto.randomUUID() // store it in the session, compare it on return
return { state, url: github.getAuthorizationUrl(state) }
}
async function finishGithubLogin(code: string, state: string) {
const { tokens, user } = await github.handleCallback(code, state)
// user: { id, email?, name?, avatarUrl?, raw }; find or create your user, then auth.createSession(...)
return { tokens, user }
}Config options
createAuth(config, deps) reads these; all lifetimes are seconds. It throws on a loginCodeLength outside 6 to 12, a loginCodeAttempts below 1, and a sessionExtendAfter that is negative, not below sessionTtl, or set with an adapter that has no updateSessionExpiry.
| Option | Type | Default | Description |
|---|---|---|---|
sessionTtl | number | 604800 | Lifetime of a session (7 days) |
sessionExtendAfter | number | none | Extend a validated session to sessionTtl from now once this many seconds have passed since its login or last extension; unset, a session ends sessionTtl after the login |
onError | (error: unknown) => void | console.error | Called with what the store threw while a session was being extended; the session is answered as it is, with extended: false |
emailVerificationTtl | number | 86400 | Lifetime of an email verification token (24 hours) |
passwordResetTtl | number | 3600 | Lifetime of a password reset token (1 hour) |
loginCodeSecret | string | none | Secret the login codes are stored under; required for sendLoginCode and verifyLoginCode |
loginCodeTtl | number | 600 | Lifetime of a login code (10 minutes) |
loginCodeLength | number | 6 | Digits of a login code, 6 to 12 |
loginCodeAttempts | number | 5 | Verifications a login code allows before it is deleted, the right one included |
| Dependency | Type | Description |
|---|---|---|
db | AuthDbAdapter | Storage for users, sessions and tokens (required) |
The adapter
AuthDbAdapter is the whole storage contract. AuthUser needs id, email, passwordHash and emailVerifiedAt; everything else on your user record is invisible to auth.
| Method | Purpose |
|---|---|
findUserByEmail(email), findUserById(id) | Users, null when absent |
createSession(data), findSession(token), deleteSession(token), deleteExpiredSessions(userId), deleteUserSessions(userId) | Sessions: deleteUserSessions runs on a password reset and from destroyUserSessions |
updateSessionExpiry(token, expiresAt) | Optional, required for sessionExtendAfter: a later expiresAt on the session with that token hash. It updates the session that is there and creates none |
deleteExpired(now) | Optional, required for sweep: remove every session and every one-time token that ended before now, of all users, and answer how many of each, { sessions, tokens }. What ends at now or later stays |
createToken(data), findToken(token, type), deleteToken(id), deleteTokens(userId, type) | One-time tokens: deleteTokens runs before a new one is issued, deleteToken when one is presented |
findUserToken(userId, type), countTokenAttempt(id) | Login codes: the user's one token of a type, and attempts + 1 on it, returning the new count or null when the token is gone. Increment atomically where the store can |
updateUserPassword(id, passwordHash), markEmailVerified(id) | Writes to the user |
Session and one-time tokens reach the adapter hashed: createSession and createToken receive the SHA-256 hash of the raw token in token, and findSession, deleteSession and findToken are called with the same hash. The adapter stores and compares what it gets and never sees a raw token, so nothing that reads the store can log in or reset a password (decision 0011). hashToken(raw) from @loewen-digital/fullstack/auth computes the stored value when your own code has to find the record behind a token. A login code reaches createToken as its HMAC, with attempts: 0 for the adapter to store (decision 0018).
@loewen-digital/fullstack/auth/flatdb ships createFlatdbAuthAdapter({ users, sessions, tokens }) for flatdb collections; the guide has the schemas.