import { createHash, randomBytes } from 'node:crypto' import { config } from '@stacksjs/config' import { db, enqueueAfterCommit, getDatabaseDialect, mutationCount, parseSqlDateTime, sqlDateTime } from '@stacksjs/database/runtime' import { mail, templateByName } from '@stacksjs/email' import { log } from '@stacksjs/logging' import { findAuthUserRowByEmail, normalizeAuthEmail } from './credential-user' import { authLinkBase } from './link-url' import { RateLimiter } from './rate-limiter' /** * Magic-link (passwordless) sign-in. * * Mirrors `password/reset.ts` where the concerns match (anti-enumeration, * single outstanding token per email, template-with-plaintext-fallback * delivery) and deliberately differs where they don't: * * - `token` at rest is SHA-256, not bcrypt: consume is one indexed * lookup, and the raw token carries 256 bits of entropy, so a fast * hash gives an offline attacker nothing. * - Consume is ATOMIC single-use: one conditional UPDATE claims the row; * concurrent requests race for one winner. GET never consumes - the * interstitial page POSTs, because mail scanners prefetch GETs and * would burn single-use links. */ export interface SendMagicLinkOptions { /** Relative path to land on after login. Absolute URLs are rejected. */ redirectTo?: string /** Multi-site: the site whose host the link should target. */ siteId?: number /** Override `config.auth.magicLink.expire` (minutes). */ ttlMinutes?: number /** * Provision a passwordless user when the email is unknown. The * parent-portal mode: families sign in by invitation, never register. */ createUser?: boolean } export type ConsumeMagicLinkResult = | { ok: true, userId: number, email: string, redirectTo: string } | { ok: false, reason: 'invalid' | 'expired' | 'used' | 'no-user' } function hashToken(raw: string): string { return createHash('sha256').update(raw).digest('hex') } function expireMinutes(): number { return config.auth.magicLink?.expire ?? 15 } function safeRedirect(candidate: string | null | undefined): string { const fallback = config.auth.magicLink?.redirectDefault ?? '/' // Browsers normalize backslashes and strip tabs/newlines before navigating. // Test the parsed destination, not just its relative-looking prefix. The // configured fallback must satisfy the same local-path contract. const isLocal = (value: unknown): value is string => { if (typeof value !== 'string' || !value.startsWith('/')) return false try { return new URL(value, 'https://stacks.invalid').origin === 'https://stacks.invalid' } catch { return false } } return isLocal(candidate) ? candidate : isLocal(fallback) ? fallback : '/' } async function linkBase(siteId: number | undefined): Promise { // Multi-site: the link must live on the site's canonical host, because the // session cookie the consume sets is host-scoped. if (siteId) { const primary = await db .selectFrom('site_domains') .where('site_id', '=', siteId) .where('is_primary', '=', true) .whereNotNull('verified_at') .select(['domain']) .executeTakeFirst() as { domain: string } | undefined if (primary?.domain) return `https://${primary.domain}` const site = await db .selectFrom('sites') .where('id', '=', siteId) .select(['subdomain']) .executeTakeFirst() as { subdomain: string } | undefined const base = (config as { sites?: { baseDomain?: string } }).sites?.baseDomain if (site?.subdomain && base) return `https://${site.subdomain}.${base}` } return authLinkBase() } /** * Issue and send a magic link. ALWAYS resolves void - unknown emails are a * silent no-op (unless `createUser`), so callers can answer a uniform * "check your email" without leaking which addresses exist. Callers gate * with their route's `.rateLimit()`; this adds a per-email limiter on top. */ export async function sendMagicLink(email: string, options: SendMagicLinkOptions = {}): Promise { const normalized = normalizeAuthEmail(email) const rateKey = `magic:${normalized}` if (await RateLimiter.isRateLimited(rateKey)) return await RateLimiter.recordFailedAttempt(rateKey) // Sending a sign-in credential must use current email ownership. A lagged // replica may retain an address the account has already removed. let user = await findAuthUserRowByEmail(normalized) if (!user && options.createUser) { // Passwordless provisioning: a user row with no password. The password // column is nullable in the default schema; password logins fail closed // for a null hash, so the only way into this account is a fresh link. await db .insertInto('users') .values({ email: normalized, name: normalized.split('@')[0], password: null, created_at: sqlDateTime(new Date()), updated_at: sqlDateTime(new Date()), } as never) .execute() user = await findAuthUserRowByEmail(normalized) } if (!user) return const userId = Number(user.id) if (!Number.isSafeInteger(userId) || userId <= 0) return const issued = await db.transaction(async () => { // Serialize even the first issue, when no token row exists to lock. // Recheck ownership before issuing against the earlier user lookup. let ownerQuery = db.primary.selectFrom('users') .where('id', '=', userId).select(['id', 'email']) if (getDatabaseDialect() !== 'sqlite') ownerQuery = ownerQuery.lockForUpdate() const owner = await ownerQuery.executeTakeFirst() if (!owner || normalizeAuthEmail(String(owner.email ?? '')) !== normalized) return undefined const raw = randomBytes(32).toString('base64url') const ttl = options.ttlMinutes ?? expireMinutes() const token = hashToken(raw) const expiresAt = sqlDateTime(new Date(Date.now() + ttl * 60_000)) // Replacement must not destroy the old credential if storing the new one // fails. Keep consumed history while allowing only one outstanding link. await db.deleteFrom('magic_link_tokens') .where('email', '=', normalized).whereNull('consumed_at').execute() await db.insertInto('magic_link_tokens').values({ email: normalized, user_id: userId, token, expires_at: expiresAt, redirect_to: safeRedirect(options.redirectTo), site_id: options.siteId ?? null, created_at: sqlDateTime(), updated_at: sqlDateTime(), } as never).execute() const stored = await db.primary.selectFrom('magic_link_tokens') .where('email', '=', normalized).whereNull('consumed_at') .select(['token', 'user_id']).execute() if (stored.length !== 1 || stored[0]?.token !== token || String(stored[0]?.user_id) !== String(userId)) throw new Error('[auth] Magic-link credential could not be stored.') return { raw, ttl } // Reserve SQLite's writer before reading the claim. External delivery // remains outside the transaction and its retry boundary. }, getDatabaseDialect() === 'sqlite' ? { sqliteMode: 'immediate', retries: 3 } : undefined) if (!issued) return const deliver = () => deliverMagicLink(normalized, issued.raw, issued.ttl, options.siteId) if (!enqueueAfterCommit(deliver)) await deliver() } async function deliverMagicLink(normalized: string, raw: string, ttl: number, siteId?: number): Promise { const base = await linkBase(siteId) const tpl = config.auth.magicLink?.url ?? '/auth/magic/{token}' const filled = tpl.replace('{token}', raw) const linkUrl = /^https?:\/\//.test(filled) ? filled : `${base}${filled.startsWith('/') ? '' : '/'}${filled}` const appName = config.app.name || 'Stacks' let html: string | undefined let text: string | undefined try { // `templateByName`, not `template`: this probes for a template the // application is not required to provide and falls back to the plain-text // email below when it is absent, so the name is deliberately not one the // registry has to know. const rendered = await templateByName('magic-link', { subject: `Sign in to ${appName}`, variables: { linkUrl, expireMinutes: ttl }, }) // template() swallows failures into empty strings; treat that as a miss // so the plain-text path below still carries the link. if (rendered.html || rendered.text) { html = rendered.html text = rendered.text } } catch { // Fall through to plain text. } try { await mail.sendOrFail({ // Account mail, not marketing: under `suppressionPolicy: 'transactional-allowed'` // it still reaches someone who unsubscribed from everything else. tag: 'transactional', to: normalized, subject: `Sign in to ${appName}`, ...(html ? { html } : {}), text: text || `Sign in to ${appName}: ${linkUrl}\n\nThis link works once and expires in ${ttl} minutes. If you didn't request it, ignore this email.`, }) } catch (error) { log.error(`Magic-link email to ${normalized} failed: ${(error as Error).message}`) } } /** * Atomically consume a raw token. Exactly one caller can win a given token: * the claim is a conditional UPDATE on (unconsumed AND unexpired), so two * concurrent consumes resolve to one `ok` and one `used`. * Use withMagicLink when issuing credentials so ownership remains locked * through the issuance transaction, not just through this claim. */ export async function consumeMagicLink(raw: string): Promise { const result = await withMagicLink(raw, async grant => grant) return result.ok ? result.value : result } /** * Claim a sign-in link and issue credentials under its current owner's lock. * The callback must perform database work only. Failed issuance rolls back * without reviving the single-use link; an enclosing rollback restores both. */ export async function withMagicLink( raw: string, complete: (grant: Extract) => Promise, ): Promise<{ ok: true, value: T } | Extract> { if (!raw || raw.length > 255) return { ok: false, reason: 'invalid' } const hashed = hashToken(raw) const pending = await db.primary.selectFrom('magic_link_tokens') .where('token', '=', hashed).select(['user_id', 'consumed_at', 'expires_at']).executeTakeFirst() if (!pending) return { ok: false, reason: 'invalid' } // Reject unusable grants before taking the account lock. A replay must not // wait behind an unrelated profile update; live grants are rechecked below. if (pending.consumed_at != null) return { ok: false, reason: 'used' } if ((parseSqlDateTime(pending.expires_at)?.getTime() ?? 0) <= Date.now()) return { ok: false, reason: 'expired' } const outcome = await db.transaction(async () => { // Same owner-first order as sending/replacing a link. Hold the row until // credential issuance commits, not merely until its email was checked. let ownerQuery = db.primary.selectFrom('users').where('id', '=', pending.user_id).select(['id', 'email']) if (getDatabaseDialect() !== 'sqlite') ownerQuery = ownerQuery.lockForUpdate() const owner = pending.user_id == null ? undefined : await ownerQuery.executeTakeFirst() const grant = await claimMagicLink(hashed) if (!grant.ok) return { result: grant } if (!owner || String(owner.id) !== String(grant.userId) || String(owner.email).trim().toLowerCase() !== grant.email.trim().toLowerCase()) return { result: { ok: false as const, reason: 'no-user' as const } } try { const value = await db.transaction(() => complete(grant)) return { result: { ok: true as const, value } } } catch (error) { return { error } } }) if ('error' in outcome) throw outcome.error return outcome.result } async function claimMagicLink(hashed: string): Promise { const now = sqlDateTime(new Date()) const claim = await db .updateTable('magic_link_tokens') .set({ consumed_at: now, updated_at: now }) .where('token', '=', hashed) .whereNull('consumed_at') .where('expires_at', '>', now) .execute() as unknown const updated = mutationCount(claim) const row = await db.primary .selectFrom('magic_link_tokens') .where('token', '=', hashed) .select(['user_id', 'email', 'expires_at', 'consumed_at', 'redirect_to']) .executeTakeFirst() as { user_id: number | null email: string expires_at: string consumed_at: string | null redirect_to: string | null } | undefined if (!row) return { ok: false, reason: 'invalid' } if (updated < 1) { // The claim missed: someone got here first, or it expired unconsumed. if (!row.consumed_at && (parseSqlDateTime(row.expires_at)?.getTime() ?? 0) <= Date.now()) return { ok: false, reason: 'expired' } return { ok: false, reason: 'used' } } // The UPDATE compared against the time captured before it acquired its // lock. A blocked claim or delayed read-back may finish after the deadline. // Parse again as well: SQLite text ordering does not validate a timestamp. if ((parseSqlDateTime(row.expires_at)?.getTime() ?? 0) <= Date.now()) return { ok: false, reason: 'expired' } if (!row.user_id) return { ok: false, reason: 'no-user' } return { ok: true, userId: Number(row.user_id), email: row.email, redirectTo: safeRedirect(row.redirect_to), } } /** Drop expired and long-consumed rows. For a daily janitor job. */ export async function pruneMagicLinkTokens(olderThanDays = 7): Promise { const cutoff = sqlDateTime(new Date(Date.now() - olderThanDays * 86_400_000)) await db .deleteFrom('magic_link_tokens') .where('expires_at', '<', cutoff) .execute() }