AgendaViva's sessions are opened by a script. In this lesson they'll be opened by whoever proves they own an account, and with that lib/placeholder-user.ts will disappear, which we've been warning since 06-01 could never be published.
A sign-in form is easy to write and easy to write badly. It works just as well with plaintext passwords, saying "that email doesn't exist" or letting someone try a million combinations: the flaws don't show until someone exploits them. That's why every section starts from a specific attack and explains which decision stops it. We repeat the warning from 08-01: before production, a professional review. And if you have no reason to manage passwords yourself, 08-03 explains how to delegate them.
- Storing passwords without knowing them
A password isn't stored or encrypted: what's stored is a hash that can't be reversed. Three conditions set a good password hash apart from a SHA-256:
- It's deliberately slow. A SHA-256 can be computed billions of times per second on a graphics card; with the database stolen, ordinary passwords fall in hours. An algorithm that takes a couple of tenths of a second doesn't bother whoever signs in and ruins whoever is guessing.
- It uses memory. Graphics cards have lots of compute and little memory per core.
- It has a salt, a random value per password. Two people with the same password get different hashes, and precomputed tables are useless.
The OWASP guide recommends Argon2id; if it isn't available, scrypt. These are the real options in Next.js:
| Option | Assessment |
|---|---|
argon2 or @node-rs/argon2 (npm) |
Argon2id. They're native modules: you have to include the binary for the deployment platform |
crypto.argon2, from Node.js |
Argon2id with no dependencies, but it exists only since Node 24.7, and Next.js supports 20.9 onward |
crypto.scrypt, from Node.js |
scrypt with no dependencies, in every version Next.js supports |
| bcrypt | Only for systems that already use it: it ignores anything beyond 72 bytes |
We choose scrypt: it's in the recommendation, it adds nothing to install or compile and it works on any Node deployment. Of the configurations OWASP considers equivalent, we take N=2¹⁵, r=8, p=3, which uses 32 MiB per computation. The N=2¹⁷ one uses 128 MiB; with several sign-ins at once, a small server would run out of memory.
// lib/security/passwords.ts — no 'server-only': seeding uses it too
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'
const KEY_LENGTH = 32
const COST = { N: 2 ** 15, r: 8, p: 3 }
type Cost = typeof COST
function derive(password: string, salt: Buffer, cost: Cost): Promise<Buffer> {
return new Promise((resolve, reject) => {
const options = { ...cost, maxmem: 256 * cost.N * cost.r }
scrypt(password.normalize('NFKC'), salt, KEY_LENGTH, options, (error, key) => {
if (error) reject(error)
else resolve(key)
})
})
}
// scrypt$32768$8$3$salt$key
export async function hashPassword(password: string): Promise<string> {
const salt = randomBytes(16)
const key = await derive(password, salt, COST)
const { N, r, p } = COST
return ['scrypt', N, r, p, salt.toString('base64url'), key.toString('base64url')].join('$')
}
// With null it does the same work and returns false: see section 4
export async function verifyPassword(
password: string,
stored: string | null,
): Promise<boolean> {
if (stored === null) {
await derive(password, randomBytes(16), COST)
return false
}
const [algorithm, N, r, p, salt, key] = stored.split('$')
if (algorithm !== 'scrypt') throw new Error('Unknown password format')
const expected = Buffer.from(key, 'base64url')
const cost = { N: Number(N), r: Number(r), p: Number(p) }
const computed = await derive(password, Buffer.from(salt, 'base64url'), cost)
return computed.length === expected.length && timingSafeEqual(computed, expected)
}- The parameters are stored alongside the hash. The day you raise the cost, or move to Argon2id, old passwords can still be checked and are updated on sign-in (exercise 2).
maxmemmust be set: Node's default limit is 32 MiB and scrypt needs roughly128 * N * r, which already reaches it here.- The callback version works on another thread.
scryptSyncwould block the entire server during each sign-in. normalize('NFKC'): anécan arrive as one character or as two, depending on the keyboard. Without normalizing, the same password would fail from another device.- It isn't trimmed or lowercased. A trailing space may be intentional.
1.1. Which passwords to accept
Current guidelines (NIST SP 800-63B, which OWASP adopts) have changed from what you still see around: length instead of composition. Forcing a symbol produces Summer2028!. Without a second factor, fewer than 15 characters is considered weak; the maximum should be at least 64, so that passphrases fit. Periodic changes aren't required, and passwords that appear in known breaches are rejected. There are lists, and a service (Pwned Passwords) you query by sending only the first five characters of the hash. Always allow pasting: doing otherwise punishes people who use a password manager.
// lib/schemas/limits.ts (added)
export const PASSWORD_LIMITS = { min: 15, max: 128 }
// lib/schemas/account.ts
import * as z from 'zod'
import { PASSWORD_LIMITS } from '@/lib/schemas/limits'
import { text } from '@/lib/schemas/common'
const INVALID_EMAIL = 'Enter a valid email address.'
const { min, max } = PASSWORD_LIMITS
const email = z
.string(INVALID_EMAIL)
.trim()
.toLowerCase()
.pipe(z.email(INVALID_EMAIL).max(254, INVALID_EMAIL))
export const signInSchema = z.object({
email,
password: z.string().min(1).max(max), // The password isn't judged on sign-in
})
export const signUpSchema = z.object({
name: text({ min: 2, max: 80 }),
email,
})
export const passwordSchema = z.object({
password: z
.string()
.min(min, `Use at least ${min} characters. A phrase is a good idea.`)
.max(max, `Use no more than ${max} characters.`),
})The maximum stops someone from sending a megabyte to make us work. And the minimum isn't in signInSchema: if it's ever raised, anyone with an old password must still be able to sign in.
- The tables
// lib/db/schema.ts
// In users. Nullable: some accounts have no password (08-03)
passwordHash: text('password_hash'),
// Added
export const emailLinks = pgTable('email_links', {
id: text('id').primaryKey(), // The hash of the token sent
purpose: text('purpose', { enum: ['sign-up', 'recovery'] }).notNull(),
email: text('email').notNull(),
name: text('name'),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
})
export const attempts = pgTable('attempts', {
key: text('key').primaryKey(),
uses: integer('uses').notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
})// scripts/seed-data.ts (added)
export const DEV_PASSWORD = 'for local development only'
// scripts/seed.ts (imports hashPassword with a relative path)
await tx.delete(schema.attempts)
// …
const passwordHash = await hashPassword(DEV_PASSWORD)
await tx
.insert(schema.users)
.values(users.map((user) => ({ ...user, passwordHash })))From now on, no select() without columns on users: the full row contains the hash. Even if your ORM allowed it, don't include it in a type either: User still doesn't have that field, and the two functions that need it ask for it by name.
- Slowing down attempts
However slow the algorithm is, anyone who can try without limit eventually guesses the most common passwords. And there's an attack more frequent than guessing: trying pairs leaked from other sites, once each. You have to count in a shared store (07-03); since ours is PostgreSQL and there are few sign-ins, a table will do.
// lib/data/attempts.ts
import 'server-only'
import { lte, sql } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { attempts } from '@/lib/db/schema'
export interface RateLimit {
key: string
max: number
seconds: number
}
// Counts one use and says whether it's allowed. A single statement: no race
export async function consumeAttempt({ key, max, seconds }: RateLimit): Promise<boolean> {
const db = await getDb()
const expired = sql`${attempts.expiresAt} <= now()`
const [row] = await db
.insert(attempts)
.values({ key, uses: 1, expiresAt: sql`now() + make_interval(secs => ${seconds})` })
.onConflictDoUpdate({
target: attempts.key,
set: {
uses: sql`case when ${expired} then 1 else ${attempts.uses} + 1 end`,
expiresAt: sql`case when ${expired} then excluded.expires_at else ${attempts.expiresAt} end`,
},
})
.returning({ uses: attempts.uses })
return row.uses <= max
}
export async function deleteExpiredAttempts(): Promise<void> {
const db = await getDb()
await db.delete(attempts).where(lte(attempts.expiresAt, sql`now()`))
}// lib/security/ip.ts
import 'server-only'
import { headers } from 'next/headers'
import { readEnv } from '@/lib/env'
// The address recorded by the last trusted proxy (04-05)
export async function getIp(): Promise<string> {
const { trustedProxies } = readEnv()
const list = ((await headers()).get('x-forwarded-for') ?? '')
.split(',')
.map((value) => value.trim())
.filter(Boolean)
return (trustedProxies > 0 && list.at(-trustedProxies)) || 'unknown'
}
// lib/env.ts: TRUSTED_PROXIES: integerWithDefault(1, 0, 5) → trustedProxies// lib/security/rate-limits.ts
import 'server-only'
import { consumeAttempt, type RateLimit } from '@/lib/data/attempts'
import { hashToken } from '@/lib/security/tokens'
const WINDOW = 15 * 60
export function signInLimits(email: string, ip: string): RateLimit[] {
const account = hashToken(email) // We don't store email addresses in the table
return [
{ key: `sign-in:${account}:${ip}`, max: 10, seconds: WINDOW },
{ key: `sign-in-ip:${ip}`, max: 60, seconds: WINDOW },
{ key: `sign-in-account:${account}`, max: 100, seconds: WINDOW },
]
}
export function signUpLimits(email: string, ip: string): RateLimit[] {
return [
{ key: `sign-up:${hashToken(email)}`, max: 3, seconds: 60 * 60 },
{ key: `sign-up-ip:${ip}`, max: 20, seconds: 60 * 60 },
]
}
export async function withinLimits(limits: RateLimit[]): Promise<boolean> {
const results = await Promise.all(limits.map(consumeAttempt))
return results.every(Boolean)
}There are three counters because each one covers the gap left by the others. The account-and-IP pair stops someone who keeps going after one person; the IP, someone trying many accounts; the account, an attack spread across many addresses. The third is deliberately the highest: with a low maximum, locking someone out would be as easy as getting their password wrong five times. That's also why no account is ever "disabled": you just wait.
TRUSTED_PROXIES says how many of your own proxies sit in front, counting from the end of the header. If there are none, the header is written by the visitor: set it to 0 and all traffic will share the "unknown" quota, which is bad but not misleading. Volume limits are also set on the load balancer or the platform.
Add deleteExpiredAttempts and the deletion of expired links to cleanAuth, from 08-01.
- Not revealing who has an account
"There's no account with that email" is convenient, and it answers anyone who asks whether a given person uses a given service. On a cultural events guide it seems harmless; on other websites it reveals an illness or an affiliation, and on all of them it helps clean up email lists. There are three places where it leaks:
| Where | Leak | Response |
|---|---|---|
| Sign-in | Different messages | Just one: "The email or password is incorrect" |
| Sign-in | Different timing: with no account, the hash isn't computed | Always compute it, even if in vain |
| Sign-up | "That email is already in use" | Always reply the same and tell the rest by email |
The second one is verifyPassword(password, null): it derives a key with a random salt and discards it. The difference between 5 and 190 milliseconds can be measured from outside with no effort.
The third one shapes the sign-up design. If the form asked for the password and created the account on the spot, it would have to say whether it already existed. And there'd be another problem: anyone could register someone else's email with their own password and wait for the owner to confirm it. We'll do it in two steps, and the password is chosen in the second one, once access to the email has been proved.
sequenceDiagram
participant P as Person
participant S as Next.js
participant C as Email
P->>S: name and email
S-->>P: "If the email address is valid, you'll receive a message"
alt no account
S->>C: link with token, valid for one hour
else account already exists
S->>C: "You already have an account: sign in or recover your password"
end
P->>S: opens the link (GET: consumes nothing)
P->>S: chooses a password (POST with the token)
S->>S: consumes the token, creates the account and the session
- The account data
// lib/data/accounts.ts
import 'server-only'
import { and, eq, gt, lte } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { emailLinks, users } from '@/lib/db/schema'
import { generateToken, hashToken } from '@/lib/security/tokens'
const ONE_HOUR = 60 * 60 * 1000
export async function findCredentials(email: string) {
const db = await getDb()
const [row] = await db
.select({ id: users.id, passwordHash: users.passwordHash })
.from(users)
.where(eq(users.email, email))
.limit(1)
return row ?? null
}
export async function createSignUpLink(email: string, name: string): Promise<string> {
const token = generateToken()
const db = await getDb()
await db.insert(emailLinks).values({
id: hashToken(token),
purpose: 'sign-up',
email,
name,
expiresAt: new Date(Date.now() + ONE_HOUR),
})
return token
}
// Consumes the link and creates the account: both or neither
export async function redeemSignUp(
token: string,
passwordHash: string,
): Promise<string | null> {
const db = await getDb()
return db.transaction(async (tx) => {
const [link] = await tx
.delete(emailLinks)
.where(
and(
eq(emailLinks.id, hashToken(token)),
eq(emailLinks.purpose, 'sign-up'),
gt(emailLinks.expiresAt, new Date()),
),
)
.returning({ email: emailLinks.email, name: emailLinks.name })
if (!link) return null
const [user] = await tx
.insert(users)
.values({ name: link.name ?? 'No name', email: link.email, passwordHash })
.onConflictDoNothing({ target: users.email })
.returning({ id: users.id })
return user?.id ?? null
})
}
export async function deleteExpiredLinks(): Promise<void> {
const db = await getDb()
await db.delete(emailLinks).where(lte(emailLinks.expiresAt, new Date()))
}DELETE … RETURNING consumes and checks at the same time: two simultaneous submissions of the same link can't both use it. The role isn't written: the column's default value, visitor, sets it. It never comes from a form.
// lib/tasks/sign-up-link.ts
import 'server-only'
import { sendEmail } from '@/lib/mail'
import { createSignUpLink, findCredentials } from '@/lib/data/accounts'
import { SITE_NAME, SITE_URL } from '@/lib/site'
export async function sendSignUpLink(email: string, name: string): Promise<void> {
const key = `sign-up:${crypto.randomUUID()}` // One per request; retries repeat it
const signInUrl = new URL('/sign-in', SITE_URL).href
if (await findCredentials(email)) {
await sendEmail({
to: email,
subject: `You already have an account on ${SITE_NAME}`,
text: `Someone asked to sign up with this email address, which already has an account.\n\nSign in at ${signInUrl}. If it wasn't you, you don't need to do anything.`,
key,
})
return
}
const link = new URL('/sign-up/confirm', SITE_URL)
link.searchParams.set('token', await createSignUpLink(email, name))
await sendEmail({
to: email,
subject: `Finish signing up for ${SITE_NAME}`,
text: `Choose your password at this link, valid for one hour:\n\n${link.href}\n\nIf it wasn't you, you don't need to do anything.`,
key,
})
}The link uses SITE_URL, not the Host header (04-05). Anyone able to change it would receive the token on their own server: it's a well-known attack against password recovery. The name isn't included in the text either: a stranger wrote it, and it would be a way of sending messages to third parties under our sender address.
- Where to go back to
Since 04-05 we've promised /sign-in?returnTo=/events/jazz-night. Anyone can write that value in a link, and if we obey it blindly, agendaviva.example/sign-in?returnTo=https://lookalike.example takes the victim, after signing in on the genuine site, to a copy that asks for the password again. It's an open redirect.
// lib/destination.ts — neutral
const BASE = 'https://internal.invalid'
// Only paths on this site; anything else goes to the default destination
export function safeDestination(value: unknown, fallback = '/'): string {
if (typeof value !== 'string' || !value.startsWith('/') || value.length > 500) {
return fallback
}
try {
const url = new URL(value, BASE)
if (url.origin !== BASE || url.pathname.startsWith('//')) return fallback
return url.pathname + url.search
} catch {
return fallback
}
}
export function signInPath(returnTo: string): string {
return `/sign-in?returnTo=${encodeURIComponent(returnTo)}`
}Checking that it starts with / isn't enough: //lookalike.example and /\lookalike.example also start that way, and the browser reads them as another domain. That's why it's interpreted by the same parser the browser will use, and the origin is compared. The second condition covers a twisted case: /.//lookalike.example belongs to this origin, but its normalized path is //lookalike.example.
- The actions
// actions/account.ts
'use server'
import { redirect } from 'next/navigation'
import * as z from 'zod'
import { findCredentials, redeemSignUp } from '@/lib/data/accounts'
import { safeDestination } from '@/lib/destination'
import { passwordSchema, signInSchema, signUpSchema } from '@/lib/schemas/account'
import { type FormState, readTextFields } from '@/lib/forms'
import { hashPassword, verifyPassword } from '@/lib/security/passwords'
import { getIp } from '@/lib/security/ip'
import { signInLimits, signUpLimits, withinLimits } from '@/lib/security/rate-limits'
import { isPossibleToken } from '@/lib/security/tokens'
import { createSession, endSession, getCurrentUser } from '@/lib/session'
import { audit } from '@/lib/tasks/audit'
import { afterResponse } from '@/lib/tasks/after-response'
import { sendSignUpLink } from '@/lib/tasks/sign-up-link'
export type SignInState = FormState<'email' | 'password'>
export type SignUpState = FormState<'name' | 'email'>
export type PasswordState = FormState<'password'>
const BAD_CREDENTIALS = 'The email or password is incorrect.'
const TOO_MANY = 'Too many attempts. Please wait a few minutes.'
export async function signIn(
returnTo: string,
_previous: SignInState,
formData: FormData,
): Promise<SignInState> {
const fields = readTextFields(formData, ['email', 'password'])
const reject = (message: string): SignInState => ({
status: 'error',
message,
errors: {},
values: { email: fields.email, password: '' }, // The password never comes back
})
const result = signInSchema.safeParse(fields)
if (!result.success) return reject(BAD_CREDENTIALS)
const { email, password } = result.data
if (!(await withinLimits(signInLimits(email, await getIp())))) {
return reject(TOO_MANY)
}
const account = await findCredentials(email)
const correct = await verifyPassword(password, account?.passwordHash ?? null)
if (!account || !correct) return reject(BAD_CREDENTIALS)
await createSession(account.id)
audit(account.id, 'session.started', account.id)
redirect(safeDestination(returnTo))
}
export async function signOut(): Promise<void> {
const user = await getCurrentUser()
await endSession()
if (user) audit(user.id, 'session.ended', user.id)
redirect('/')
}
export async function requestSignUp(
_previous: SignUpState,
formData: FormData,
): Promise<SignUpState> {
const values = readTextFields(formData, ['name', 'email'])
const result = signUpSchema.safeParse(values)
if (!result.success) {
const { fieldErrors } = z.flattenError(result.error)
return { status: 'error', message: 'Check the fields.', errors: fieldErrors, values }
}
const { name, email } = result.data
if (!(await withinLimits(signUpLimits(email, await getIp())))) {
return { status: 'error', message: TOO_MANY, errors: {}, values }
}
// Everything that depends on whether the account exists happens after responding
afterResponse('sign-up link', () => sendSignUpLink(email, name))
return { status: 'success', message: "If the email address is valid, you'll receive a message in a few minutes." }
}
export async function completeSignUp(
token: string,
_previous: PasswordState,
formData: FormData,
): Promise<PasswordState> {
const reject = (message: string, password?: string[]): PasswordState => ({
status: 'error',
message,
errors: { password },
values: { password: '' },
})
const result = passwordSchema.safeParse(readTextFields(formData, ['password']))
if (!result.success) {
return reject('Choose a different password.', z.flattenError(result.error).fieldErrors.password)
}
const limit = { key: `redeem-ip:${await getIp()}`, max: 20, seconds: 15 * 60 }
if (!(await withinLimits([limit]))) return reject(TOO_MANY)
const userId =
typeof token === 'string' && isPossibleToken(token)
? await redeemSignUp(token, await hashPassword(result.data.password))
: null
if (!userId) return reject('The link has expired or has already been used. Start signing up again.')
await createSession(userId)
audit(userId, 'account.created', userId)
redirect('/')
}- The limit is checked before the password. It also protects the CPU: each attempt costs two tenths of a second and 32 MiB.
returnToandtokenarrive fixed withbind, and they're still checked: anyone can call the action with other values (06-01). Thetypeofisn't redundant, because the TypeScript type doesn't exist on the network.- In sign-up, the only thing that takes the same time for everyone is doing nothing. That's why the lookup and the sending go in
after. If sending fails, the person will try again: it's an acceptable loss. createSessionrotates the token (08-01).- Failed sign-ins don't log the email or the password. People often type their password into the email field.
Add session.started, session.ended and account.created to AuditedAction.
- The pages
// app/(account)/layout.tsx
import { Header } from '@/components/header'
export default function AccountLayout({ children }: LayoutProps<'/'>) {
return (
<>
<Header />
<main className="mx-auto w-full max-w-sm flex-1 px-4 py-16">{children}</main>
</>
)
}
// app/(account)/sign-in/page.tsx
import { Suspense } from 'react'
import Link from 'next/link'
import { redirect } from 'next/navigation'
import { safeDestination } from '@/lib/destination'
import { getCurrentUser } from '@/lib/session'
import { SignInForm } from './_components/sign-in-form'
type Props = PageProps<'/sign-in'>
export default function SignInPage({ searchParams }: Props) {
return (
<>
<h1 className="mb-6 text-2xl font-bold">Sign in</h1>
<Suspense fallback={<div aria-hidden className="h-56" />}>
<SignInContent searchParams={searchParams} />
</Suspense>
<p className="mt-4">
Don't have an account? <Link href="/sign-up" className="underline">Sign up</Link>
</p>
</>
)
}
async function SignInContent({ searchParams }: Pick<Props, 'searchParams'>) {
const returnTo = safeDestination((await searchParams).returnTo)
if (await getCurrentUser()) redirect(returnTo)
return <SignInForm returnTo={returnTo} />
}// app/(account)/sign-in/_components/sign-in-form.tsx
'use client'
import { useActionState } from 'react'
import { signIn } from '@/actions/account'
import { SubmitButton } from '@/components/submit-button'
import { Field } from '@/components/field'
import { FormMessage } from '@/components/form-message'
import { INITIAL_STATE } from '@/lib/forms'
export function SignInForm({ returnTo }: { returnTo: string }) {
const [state, formAction] = useActionState(signIn.bind(null, returnTo), INITIAL_STATE)
const email = state.status === 'error' ? state.values.email : ''
return (
<form action={formAction}>
<FormMessage state={state} />
<Field label="Email">
{(a) => <input {...a} type="email" name="email" autoComplete="username" defaultValue={email} required />}
</Field>
<Field label="Password">
{(a) => <input {...a} type="password" name="password" autoComplete="current-password" required />}
</Field>
<SubmitButton pendingText="Signing in…" className="border px-3">Sign in</SubmitButton>
</form>
)
}autoComplete with username, current-password and new-password is what lets password managers fill in and suggest. /sign-up has the same shape, with name and email and the requestSignUp action. The confirmation page only reads the token and hands it to the form:
// app/(account)/sign-up/confirm/page.tsx, inside its <Suspense>
async function ConfirmContent({ searchParams }: Pick<Props, 'searchParams'>) {
const { token } = await searchParams
if (typeof token !== 'string') return <p>The link we emailed you is missing.</p>
return <PasswordForm token={token} /> // completeSignUp.bind(null, token)
}Opening the link consumes nothing. Many email systems visit links before the person does, to scan for threats; if the GET confirmed, a bot would complete the sign-up. A GET doesn't write.
// components/account-menu.tsx
import Link from 'next/link'
import { signOut } from '@/actions/account'
import { SubmitButton } from '@/components/submit-button'
import { getCurrentUser } from '@/lib/session'
export async function AccountMenu() {
const user = await getCurrentUser()
if (!user) return <Link href="/sign-in">Sign in</Link>
return (
<div className="flex gap-4">
<Link href="/my-bookings">{user.name}</Link>
<form action={signOut}>
<SubmitButton pendingText="Signing out…">Sign out</SubmitButton>
</form>
</div>
)
}Signing out is a form for the same reason: with a link, an image on another website could end sessions, and so could <Link> prefetching. Writing or deleting the cookie in an action makes Next.js discard what the router had stored, so the header refreshes on its own.
- Goodbye to the placeholder user
// lib/session.ts (added; imports redirect and signInPath)
// For pages: if there's no session, go sign in and then come back
export async function requireUser(returnTo: string): Promise<SessionUser> {
const user = await getCurrentUser()
if (!user) redirect(signInPath(returnTo))
return user
}Delete lib/placeholder-user.ts and the PLACEHOLDER_ORGANIZER_ID constant, and let TypeScript show you every place:
| Where | Before | Now |
|---|---|---|
MyBookingsPage |
getPlaceholderUser() |
requireUser('/my-bookings') |
dashboard/events, new, edit, @upcoming, @occupancy |
getPlaceholderOrganizer() or the constant |
requireUser('/dashboard…'), with its path |
actions/bookings.ts, events.ts, images.ts |
getPlaceholderUser()… |
getCurrentUser(), and a response if it's null |
EventBooking |
getPlaceholderUser() |
getCurrentUser(): it's also shown without a session |
// actions/bookings.ts, at the start of bookSpots
const values = readTextFields(formData, ['spots'])
const user = await getCurrentUser()
if (!user) {
return { status: 'error', message: 'Sign in to book.', errors: {}, values }
}
// event-booking.tsx
const user = await getCurrentUser()
const [booking, availability] = await Promise.all([
user ? getBooking(user.id, event.id) : null,
getAvailability(event.slug),
])
if (!booking && (!availability || event.endsAt <= new Date())) return null
if (!user) {
return (
<Link href={signInPath(`/events/${event.slug}`)} className="underline">
Sign in to book
</Link>
)
}In pages you redirect; in actions you reply. If the session expires while someone is filling in a long form, a redirect would throw away what they'd written. In cancelMyBooking, which doesn't return state, an error is thrown, which the list already knows how to show.
The application knows who everyone is, and it doesn't yet check what they can do: a freshly created account gets into /dashboard and creates events. Don't publish it until 08-04.
Sign in with [email protected] and the development password, book, sign out. Sign up with a made-up example.com address, copy the link from the terminal and choose a password. Repeat the sign-up with [email protected]: the website says the same thing and the email is different. Fail eleven times in a row and watch the limit kick in.
- Password recovery, in outline
The piece is already there: it's another emailLinks row, with purpose: 'recovery'. These are the rules for building it:
/sign-in/recoverasks for the email and always replies the same. With limits, and the sending inafter.- The link is short-lived (15-60 minutes), is used once, and requesting another invalidates the earlier ones.
- The new-password form consumes the token in the same transaction that changes the hash.
- All of that account's sessions are deleted, along with the other pending links.
- There's no automatic sign-in: the person is sent to
/sign-in. - The change is notified by email. That's how someone who didn't request it finds out.
No secret questions: the answers can be found out. And remember that whoever controls the email controls the account; if that isn't acceptable in your case, you need a second factor.
Common Mistakes and Tips
- Hashing passwords with SHA-256, with or without salt.
scryptSyncor synchronous bcrypt in an action: it blocks the server.- Returning the password in
valuesto refill the field. - Responding faster if the account doesn't exist.
- "That email is already registered."
- Creating the account with a password before confirming the email.
- Confirming with a
GET. - Obeying
returnTowithout checking it, or only checking that it starts with/. - Locking the account after five failures: it's a way of harassing others.
- Counting attempts in memory with several instances.
- Taking the first value of
x-forwarded-for. - Accepting the role from a form field.
- Changing the password and leaving the other sessions alive.
Exercises
Exercise 1: signing out the other sessions
Write the changePassword action, which asks for the current password and the new one. It must hold up against someone who finds a computer with the session open, and lock out anyone who was signed in on another device. The data function is changeHash(userId, hash).
Solution
// Practice only
export async function changePassword(
_previous: PasswordChangeState,
formData: FormData,
): Promise<PasswordChangeState> {
const user = await getCurrentUser()
if (!user) return reject('Please sign in.')
const limit = { key: `password-change:${user.id}`, max: 5, seconds: 15 * 60 }
if (!(await withinLimits([limit]))) return reject(TOO_MANY)
const { current, replacement } = readTextFields(formData, ['current', 'replacement'])
if (!(await verifyPassword(current, await readHash(user.id)))) {
return reject('The current password is incorrect.')
}
const result = passwordSchema.safeParse({ password: replacement })
if (!result.success) return reject('The new password is too short.')
await changeHash(user.id, await hashPassword(replacement))
await endOtherSessions(user.id)
await createSession(user.id)
return { status: 'success', message: "Password changed. We've signed you out of your other sessions." }
}Asking for the current password is what stops someone who sits down at another person's computer. The limit is per account: here we already know who it is. createSession also rotates the person's own session. What's missing is the email notification and limiting the length of current.
Exercise 2: raising the cost without bothering anyone
Two years from now, COST falls short. How do you update the old hashes if nobody knows the passwords? Write needsRehash(stored) and say where it's called.
Solution
// lib/security/passwords.ts — practice only
export function needsRehash(stored: string): boolean {
const { N, r, p } = COST
return !stored.startsWith(`scrypt$${N}$${r}$${p}$`)
}
// In signIn, after checking that it's correct
if (account.passwordHash && needsRehash(account.passwordHash)) {
await changeHash(account.id, await hashPassword(password))
}The only moment you have the password is at sign-in. It's updated there, within the request and not in after, so as not to keep the password in memory longer than necessary. Anyone who doesn't sign in again will keep the old one; after a while, you can delete it and ask them to recover it. While two costs coexist, timing gives something away: an old account responds faster than a nonexistent one.
Exercise 3: reviewing a sign-in
Find the problems.
export async function login(formData: FormData) {
const { email, password, returnTo } = Object.fromEntries(formData)
const [user] = await db.select().from(users).where(eq(users.email, email))
if (!user) throw new Error('No such user')
if (user.password !== sha256(password)) throw new Error(`Wrong password: ${password}`)
(await cookies()).set('user', JSON.stringify(user))
redirect(returnTo)
}Solution
- It says whether the user exists, through the message and through the timing.
- SHA-256 without salt, compared with
!==. - It writes the password into the error message, which ends up in the logs.
- The cookie contains the whole user, with its hash, readable and editable: changing the
roleby hand makes you an administrator. - No attributes on the cookie.
- Open redirect.
- No attempt limit or validation;
Object.fromEntriescan yield files. - It throws exceptions for something expected: in production the person will see a generic error.
- And a syntax detail: without a semicolon, the line starting with
(joins the previous one and is interpreted as a call.
Conclusion
Passwords are stored as a slow hash, with a salt and with their parameters. Sign-in gives a single message, takes the same time with or without an account and counts attempts per person, per address and per both. Sign-up reveals nothing because the conversation moves to email, and the password is chosen by whoever has proved they receive it. Signing in rotates the session and returns to a checked path. AgendaViva no longer has placeholder users.
All of this is a responsibility that might not need to be yours. Many people prefer to sign in with an account they already have, and many organizations prefer not to hold passwords. In Signing In with External Providers you'll see how to trust someone else to say who someone is, and with how much caution.
