From 5ba97d9a4e4b89c51ea86a0af557f882dcca5374 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 11:37:12 +0000 Subject: [PATCH 1/2] fix(reader-access): restore code storage so spec 005 functions build PR #635 (spec 006) rewrote netlify/lib/reader-access/store.ts for email + device sessions and removed the verification-code exports. reader-code-request, reader-verify and reader-chapter stopped bundling, reader-session called the new two-argument API with one argument (sign-out left the server session alive), and no test failed because handlers were never bundled. - Add netlify/lib/reader-access/code-store.ts for codes, sessionId access sessions and recovery attempts, under key prefixes distinct from spec 006. - Consume codes once with a Blobs onlyIfNew marker (RA-002); upgrade @netlify/blobs 6.5 -> 11.1.6 for conditional writes. - Store the hash of the code that is emailed; previously a second, unrelated code was hashed so no emailed code could verify. - Use timing-safe hash comparison; hash readerId with SHA-256. - Mailgun client: add username 'api' so sends authenticate. - Return contract states: 502 provider-failure, 429 limited, 401 request-pending; stop echoing internal error text. - reader-retention: use the store API and run @daily. - Route /api/reader/chapters/:chapterId to reader-chapter in public/_redirects (it fell through to index.html) and netlify.toml. - Add a test that bundles every function and checks redirect targets. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZdpaiuKYHLz2mX9por --- netlify.toml | 29 +- netlify/__tests__/reader-retention.test.ts | 32 +- netlify/functions/reader-chapter.ts | 16 +- netlify/functions/reader-code-request.ts | 78 ++-- netlify/functions/reader-retention.ts | 13 +- netlify/functions/reader-session.ts | 13 +- netlify/functions/reader-verify.ts | 191 +++----- netlify/lib/reader-access/code-store.ts | 154 ++++++ netlify/lib/reader-access/codes.ts | 15 +- netlify/lib/reader-access/mailer.ts | 5 +- package-lock.json | 493 +++++++++++++++++++- package.json | 3 +- public/_redirects | 1 + tests/reader-access/code-store.test.ts | 126 +++++ tests/reader-access/functions-build.test.ts | 74 +++ 15 files changed, 1024 insertions(+), 219 deletions(-) create mode 100644 netlify/lib/reader-access/code-store.ts create mode 100644 tests/reader-access/code-store.test.ts create mode 100644 tests/reader-access/functions-build.test.ts diff --git a/netlify.toml b/netlify.toml index f05af1d5..837be440 100644 --- a/netlify.toml +++ b/netlify.toml @@ -44,10 +44,33 @@ to = "/.netlify/functions/reader-chapters-list" status = 200 -# Phase 6: Chapter content delivery +# Phase 6: Chapter content delivery (must precede /chapters/:chapterId) [[redirects]] - from = "/api/reader/chapters/*" - to = "/.netlify/functions/reader-chapter-content/:splat" + from = "/api/reader/chapters/:chapterId/content" + to = "/.netlify/functions/reader-chapter-content" + status = 200 + +# Spec 005: protected chapter for a verified session (RA-T035) +[[redirects]] + from = "/api/reader/chapters/:chapterId" + to = "/.netlify/functions/reader-chapter" + status = 200 + +# Spec 005: the API path and the function file name differ, so the +# reader-:splat catch-all below cannot reach these three. +[[redirects]] + from = "/api/reader/code-requests" + to = "/.netlify/functions/reader-code-request" + status = 200 + +[[redirects]] + from = "/api/reader/verifications" + to = "/.netlify/functions/reader-verify" + status = 200 + +[[redirects]] + from = "/api/reader/session" + to = "/.netlify/functions/reader-session" status = 200 # Phase 6: Reading progress diff --git a/netlify/__tests__/reader-retention.test.ts b/netlify/__tests__/reader-retention.test.ts index 7546ce2a..641fa68d 100644 --- a/netlify/__tests__/reader-retention.test.ts +++ b/netlify/__tests__/reader-retention.test.ts @@ -9,25 +9,25 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest'; const mockBlobStore = new Map(); const mockDeletedKeys = new Set(); -vi.mock('@netlify/blobs', () => ({ - list: vi.fn(async ({ prefix }: { prefix: string }) => { - const keys = Array.from(mockBlobStore.keys()).filter((k) => - k.startsWith(prefix) - ); - return { - blobs: keys.map((key) => ({ key })), - }; - }), - get: vi.fn(async (key: string) => mockBlobStore.get(key) ?? null), - delete: vi.fn(async (key: string) => { - mockBlobStore.delete(key); - mockDeletedKeys.add(key); - }), -})); +vi.mock('@netlify/blobs', () => { + const store = { + list: vi.fn(async ({ prefix }: { prefix: string }) => ({ + blobs: Array.from(mockBlobStore.keys()) + .filter((k) => k.startsWith(prefix)) + .map((key) => ({ key })), + })), + get: vi.fn(async (key: string) => mockBlobStore.get(key) ?? null), + delete: vi.fn(async (key: string) => { + mockBlobStore.delete(key); + mockDeletedKeys.add(key); + }), + }; + return { getStore: vi.fn(() => store) }; +}); import handler from '../functions/reader-retention'; -describe.skip('Reader Retention Tests (RA-T050)', () => { +describe('Reader Retention Tests (RA-T050)', () => { beforeEach(() => { mockBlobStore.clear(); mockDeletedKeys.clear(); diff --git a/netlify/functions/reader-chapter.ts b/netlify/functions/reader-chapter.ts index 8364a289..c635061d 100644 --- a/netlify/functions/reader-chapter.ts +++ b/netlify/functions/reader-chapter.ts @@ -3,7 +3,7 @@ // Use edition manifest and session validation import { createJsonResponse, responses, createResponse } from '../lib/reader-access/responses'; -import { getSession, renewSession } from '../lib/reader-access/store'; +import { getAccessSession, renewAccessSession } from '../lib/reader-access/code-store'; import { parseSessionCookie, formatSessionCookie, createSessionCookie } from '../lib/reader-access/session-cookie'; import { EditionReader } from '../lib/reader-access/edition'; @@ -27,21 +27,21 @@ export default async function handler( // Parse session cookie const cookieHeader = req.headers.get('cookie'); - const sessionId = parseSessionCookie(cookieHeader); + const sessionId = parseSessionCookie(cookieHeader ?? undefined); if (!sessionId) { - return createJsonResponse(responses.invalid(), 401); + return createJsonResponse(responses.pending(), 401); } // Retrieve session - const session = await getSession(sessionId); + const session = await getAccessSession(sessionId); if (!session) { - return createJsonResponse(responses.invalid(), 401); + return createJsonResponse(responses.pending(), 401); } // Check if expired if (new Date(session.expiresAt) < new Date()) { - return createJsonResponse(responses.invalid(), 401); + return createJsonResponse(responses.pending(), 401); } // Load manifest and verify chapter is approved @@ -73,7 +73,7 @@ export default async function handler( const content = `

${reader.getChapter(chapterId)?.title}

Chapter content here...

`; // Renew session - const renewedSession = await renewSession(sessionId); + const renewedSession = await renewAccessSession(sessionId); if (!renewedSession) { return createJsonResponse(responses.error('Failed to renew session'), 503); } @@ -97,6 +97,6 @@ export default async function handler( return response; } catch (err) { - return createJsonResponse(responses.error(err instanceof Error ? err.message : 'Unknown error'), 503); + return createJsonResponse(responses.error('Chapter is unavailable'), 503); } } diff --git a/netlify/functions/reader-code-request.ts b/netlify/functions/reader-code-request.ts index 66c10316..eed36204 100644 --- a/netlify/functions/reader-code-request.ts +++ b/netlify/functions/reader-code-request.ts @@ -1,78 +1,56 @@ // POST /api/reader/code-requests -// Create verification code and send via email -// Resend invalidates previous code for same email +// Create a verification code and send it by email. +// A resend replaces the previous code for the same email. +// Contract: .github/specs/005-reader-access/contracts/reader-access-functions.md import { createJsonResponse, responses } from '../lib/reader-access/responses'; import { createVerificationCode, generateCode } from '../lib/reader-access/codes'; -import { storeCode, deleteCode } from '../lib/reader-access/store'; +import { storeCode } from '../lib/reader-access/code-store'; import { MailgunMailer } from '../lib/reader-access/mailer'; const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; -export default async function handler( - req: Request -): Promise { +export default async function handler(req: Request): Promise { if (req.method !== 'POST') { - return new Response('{"state":"provider-failure"}', { status: 405, headers: { 'Content-Type': 'application/json' } }); + return createJsonResponse(responses.error('Method not allowed'), 405); } + let email: unknown; try { - // Parse request body - const body = await req.json(); - const { email } = body as Record; - - // Validate email - if (!email || typeof email !== 'string') { - return createJsonResponse(responses.invalid(), 400); - } - - if (!EMAIL_REGEX.test(email)) { - return createJsonResponse(responses.invalid(), 400); - } + ({ email } = (await req.json()) as Record); + } catch { + return createJsonResponse(responses.invalid(), 400); + } - // Delete previous code for this email (recovery: invalidate old) - await deleteCode(email).catch(() => { - // Ignore deletion errors - }); + if (typeof email !== 'string' || !EMAIL_REGEX.test(email)) { + return createJsonResponse(responses.invalid(), 400); + } - // Create new verification code - const code = generateCode(); - const verificationCode = createVerificationCode(); + try { + // The emailed code and the stored hash must come from the same value. + const plainCode = generateCode(); + const verificationCode = createVerificationCode(plainCode); - // Store code - await storeCode(email, { - codeHash: verificationCode.codeHash, - salt: verificationCode.salt, - createdAt: verificationCode.createdAt, - expiresAt: verificationCode.expiresAt, - attemptCount: verificationCode.attemptCount, - maxAttempts: verificationCode.maxAttempts, - }); + // Overwrites any earlier code, so a resend invalidates the previous one. + await storeCode(email, verificationCode); - // Send via Mailgun const mailer = new MailgunMailer({ apiKey: process.env.MAILGUN_API_KEY || '', domain: process.env.MAILGUN_DOMAIN || '', fromAddress: process.env.MAILGUN_FROM || 'noreply@thisonetimeonacidcom.com', }); - const emailResult = await mailer.sendVerificationCode(email, code, '10 minutes'); + const emailResult = await mailer.sendVerificationCode(email, plainCode, '10 minutes'); - // Return response based on email result if (emailResult.status === 'accepted') { - return createJsonResponse( - responses.received(verificationCode.expiresAt), - 202 - ); - } else if (emailResult.status === 'uncertain') { - return createJsonResponse(responses.uncertain(), 502); - } else { - return createJsonResponse(responses.invalid(), 400); + return createJsonResponse(responses.received(verificationCode.expiresAt), 202); } - } catch (err) { - if (err instanceof SyntaxError) { - return createJsonResponse(responses.invalid(), 400); + if (emailResult.status === 'uncertain') { + return createJsonResponse(responses.uncertain(), 502); } - return createJsonResponse(responses.error(err instanceof Error ? err.message : 'Unknown error'), 502); + return createJsonResponse(responses.error('The code could not be sent'), 502); + } catch { + // Never echo internal error text to the visitor. + return createJsonResponse(responses.error('The code could not be sent'), 502); } } diff --git a/netlify/functions/reader-retention.ts b/netlify/functions/reader-retention.ts index d171386a..8ad26516 100644 --- a/netlify/functions/reader-retention.ts +++ b/netlify/functions/reader-retention.ts @@ -14,7 +14,10 @@ * @handler daily scheduled background function */ -import { list, delete as deleteBlob, get } from '@netlify/blobs'; +import { getStore } from '@netlify/blobs'; + +// Netlify scheduled function: runs once a day (RA-T050). +export const config = { schedule: '@daily' }; interface ReaderAccessRecord { id: string; @@ -55,14 +58,16 @@ export default async function handler(req: Request): Promise { // Scan all records with prefix 'reader-access:' // Note: Netlify Blobs list() doesn't support filtering by value, // so we enumerate all and check delete_after locally + const store = getStore({ name: 'reader-access', consistency: 'strong' }); + try { - const { blobs } = await list({ + const { blobs } = await store.list({ prefix: 'reader-access:', }); for (const blob of blobs) { try { - const recordJson = await get(blob.key); + const recordJson = await store.get(blob.key, { type: 'text' }); if (!recordJson) continue; const record: ReaderAccessRecord = JSON.parse(recordJson); @@ -70,7 +75,7 @@ export default async function handler(req: Request): Promise { // If record has passed its delete_after window, delete it if (deleteAfter < now) { - await deleteBlob(blob.key); + await store.delete(blob.key); deletedCount++; deletedIds.push(record.id); } diff --git a/netlify/functions/reader-session.ts b/netlify/functions/reader-session.ts index 486db83a..f2545dff 100644 --- a/netlify/functions/reader-session.ts +++ b/netlify/functions/reader-session.ts @@ -2,7 +2,7 @@ // DELETE /api/reader/session — Sign out (end session, clear cookie) import { createJsonResponse, createSecureSessionResponse, responses } from '../lib/reader-access/responses'; -import { getSession, deleteSession } from '../lib/reader-access/store'; +import { getAccessSession, deleteAccessSession } from '../lib/reader-access/code-store'; import { parseSessionCookie, SESSION_COOKIE_NAME, @@ -15,14 +15,14 @@ export default async function handler( if (req.method === 'GET') { // Parse session cookie const cookieHeader = req.headers.get('cookie'); - const sessionId = parseSessionCookie(cookieHeader); + const sessionId = parseSessionCookie(cookieHeader ?? undefined); if (!sessionId) { return createSecureSessionResponse(responses.invalid(), 401); } // Retrieve session - const session = await getSession(sessionId); + const session = await getAccessSession(sessionId); if (!session) { return createSecureSessionResponse(responses.invalid(), 401); } @@ -36,7 +36,6 @@ export default async function handler( return createSecureSessionResponse( { state: 'verified', - sessionId, expiresAt: session.expiresAt, renewedAt: session.renewedAt, }, @@ -45,11 +44,11 @@ export default async function handler( } else if (req.method === 'DELETE') { // Parse session cookie (may not exist) const cookieHeader = req.headers.get('cookie'); - const sessionId = parseSessionCookie(cookieHeader); + const sessionId = parseSessionCookie(cookieHeader ?? undefined); // Delete session if exists (recovery: ignore errors) if (sessionId) { - await deleteSession(sessionId).catch(() => { + await deleteAccessSession(sessionId).catch(() => { // Ignore deletion errors (idempotent) }); } @@ -76,6 +75,6 @@ export default async function handler( }); return errorResponse; } catch (err) { - return createSecureSessionResponse(responses.error(err instanceof Error ? err.message : 'Unknown error'), 503); + return createSecureSessionResponse(responses.error('Session status is unavailable'), 503); } } diff --git a/netlify/functions/reader-verify.ts b/netlify/functions/reader-verify.ts index 2b8d790b..298704a0 100644 --- a/netlify/functions/reader-verify.ts +++ b/netlify/functions/reader-verify.ts @@ -1,19 +1,19 @@ // POST /api/reader/verifications -// Verify code (atomic consume); create/update session -// Recovery-first: if recovery succeeds first, fresh code continues -// Rate limiting: 5 verification attempts per email per minute +// Verify a code, consume it atomically, then start or renew a session. +// Contract: .github/specs/005-reader-access/contracts/reader-access-functions.md -import { createJsonResponse, createSecureSessionResponse, responses } from '../lib/reader-access/responses'; +import { createHash, randomBytes } from 'crypto'; +import { createSecureSessionResponse, responses } from '../lib/reader-access/responses'; import { verifyCode, isCodeExpired, isCodeLimited } from '../lib/reader-access/codes'; import { getCode, - deleteCode, - storeSession, + consumeCode, incrementCodeAttempts, - getSession, - renewSession, + getAccessSession, + renewAccessSession, + storeAccessSession, storeRecoveryAttempt, -} from '../lib/reader-access/store'; +} from '../lib/reader-access/code-store'; import { generateSessionId, createSessionCookie, @@ -23,152 +23,109 @@ import { import { checkRateLimit, resetRateLimit, RATE_LIMIT_PRESETS } from '../lib/reader-access/rate-limiter'; const RECOVERY_WINDOW_HOURS = 4; -const generateRecoveryId = () => Math.random().toString(36).substring(2, 15); -const getReaderId = (email: string) => Buffer.from(email).toString('base64'); - +const SESSION_DAYS = 30; const CODE_REGEX = /^\d{6}$/; -export default async function handler( - req: Request -): Promise { +/** One-way reader identifier; the plain email is never stored with a session. */ +export function getReaderId(email: string): string { + return createHash('sha256').update(email.trim().toLowerCase()).digest('hex'); +} + +function respond(body: Parameters[0], status: number) { + return createSecureSessionResponse(body, status); +} + +export default async function handler(req: Request): Promise { if (req.method !== 'POST') { - return new Response('{"state":"provider-failure"}', { status: 405, headers: { 'Content-Type': 'application/json' } }); + return respond(responses.error('Method not allowed'), 405); } + let email: unknown; + let code: unknown; try { - // Parse request body - const body = await req.json(); - const { email, code } = body as Record; - - // Validate inputs - if (!email || typeof email !== 'string') { - return createSecureSessionResponse(responses.invalid(), 400); - } + ({ email, code } = (await req.json()) as Record); + } catch { + return respond(responses.invalid(), 400); + } - if (!code || typeof code !== 'string' || !CODE_REGEX.test(code)) { - return createSecureSessionResponse(responses.invalid(), 400); - } + if (typeof email !== 'string' || !email) { + return respond(responses.invalid(), 400); + } + if (typeof code !== 'string' || !CODE_REGEX.test(code)) { + return respond(responses.invalid(), 400); + } - // T066: Check rate limiting (5 attempts per email per minute) - const rateLimitResult = checkRateLimit(email, RATE_LIMIT_PRESETS.EMAIL_VERIFICATION); - if (rateLimitResult.isLimited) { - // Return 429 Too Many Requests - const response = new Response( - JSON.stringify(responses.limited()), - { status: 429 } - ); - response.headers.set('Retry-After', rateLimitResult.resetAfterSeconds.toString()); - response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate'); - response.headers.set('X-Content-Type-Options', 'nosniff'); + try { + const rateLimit = checkRateLimit(email, RATE_LIMIT_PRESETS.EMAIL_VERIFICATION); + if (rateLimit.isLimited) { + const response = respond(responses.limited(), 429); + response.headers.set('Retry-After', rateLimit.resetAfterSeconds.toString()); return response; } - // Retrieve stored code const storedCode = await getCode(email); if (!storedCode) { - return createSecureSessionResponse(responses.invalid(), 400); + return respond(responses.invalid(), 400); } - - // Check if expired if (isCodeExpired(storedCode.expiresAt)) { - return createSecureSessionResponse(responses.expired(), 410); + return respond(responses.expired(), 410); } - - // Check if already limited (too many attempts) if (isCodeLimited(storedCode.attemptCount, storedCode.maxAttempts)) { - return createSecureSessionResponse(responses.used(), 410); + return respond(responses.limited(), 429); } - // Verify code hash - const isValid = verifyCode(code, storedCode.codeHash, storedCode.salt); - - if (!isValid) { - // Increment attempt count + if (!verifyCode(code, storedCode.codeHash, storedCode.salt)) { await incrementCodeAttempts(email); - return createSecureSessionResponse(responses.invalid(), 400); + return respond(responses.invalid(), 400); + } + + // RA-002: exactly one concurrent submission of a code may succeed. + if (!(await consumeCode(email, storedCode.codeId))) { + return respond(responses.used(), 410); } - // T066: Reset rate limit on successful verification resetRateLimit(email, RATE_LIMIT_PRESETS.EMAIL_VERIFICATION.keyPrefix); - // Code is valid: check for existing session and renew, or create new const now = new Date(); - const expiresAt = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000); - - // RA-T041: Check if user has active session in browser cookie - // If so, renew it; otherwise create new session - const cookieHeader = req.headers.get('cookie'); - const existingSessionId = parseSessionCookie(cookieHeader); - let sessionId = existingSessionId; - let isRenewal = false; - - if (existingSessionId) { - // Check if session is still valid - const existingSession = await getSession(existingSessionId); - if (existingSession && new Date(existingSession.expiresAt) > new Date()) { - // Renew existing session - isRenewal = true; - const renewedSession = await renewSession(existingSessionId); - if (renewedSession) { - sessionId = existingSessionId; - // Use the renewed expiry - expiresAt.setTime(new Date(renewedSession.expiresAt).getTime()); - } - } - } + const readerId = getReaderId(email); - // If no renewal, create new session - if (!isRenewal) { + // RA-T041: a fresh code on a browser with an active session renews it. + const existingSessionId = parseSessionCookie(req.headers.get('cookie') ?? undefined); + const existing = existingSessionId ? await getAccessSession(existingSessionId) : null; + const renewed = + existing && existing.readerId === readerId ? await renewAccessSession(existing.sessionId) : null; + + let sessionId: string; + let expiresAt: string; + if (renewed) { + sessionId = renewed.sessionId; + expiresAt = renewed.expiresAt; + } else { sessionId = generateSessionId(); - await storeSession({ + expiresAt = new Date(now.getTime() + SESSION_DAYS * 24 * 60 * 60 * 1000).toISOString(); + await storeAccessSession({ sessionId, - deviceId: '', // Can be populated from request fingerprinting if needed - chapterId: '', + readerId, createdAt: now.toISOString(), - expiresAt: expiresAt.toISOString(), + expiresAt, renewedAt: now.toISOString(), }); } - // Delete code (recovery: if this fails, session was already created) - await deleteCode(email).catch(() => { - // Ignore deletion errors (recovery-first) - }); - - // Create recovery attempt (RA-T048) - // Recovery window: 4 hours from code consumed time - const recoveryId = generateRecoveryId(); - const readerId = getReaderId(email); - const recoveryExpiresAt = new Date(now.getTime() + RECOVERY_WINDOW_HOURS * 60 * 60 * 1000); - + // RA-T048: record the recovery window. Failure here must not undo access. await storeRecoveryAttempt({ - recoveryId, + recoveryId: randomBytes(16).toString('hex'), readerId, initiatedAt: now.toISOString(), - expiresAt: recoveryExpiresAt.toISOString(), + expiresAt: new Date(now.getTime() + RECOVERY_WINDOW_HOURS * 60 * 60 * 1000).toISOString(), createdSessionId: sessionId, - raceOutcome: isRenewal ? 'renewal' : 'fresh', - }).catch(() => { - // If recovery attempt fails to store, session is still valid - // User can verify again if needed - }); - - // Create/update session cookie - const sessionCookie = createSessionCookie(sessionId); - const sessionCookieHeader = formatSessionCookie(sessionCookie); - - // Return 200 with response and Set-Cookie header (with security headers) - const response = createSecureSessionResponse( - responses.verified(sessionId, expiresAt.toISOString()), - 200 - ); - response.headers.set('Set-Cookie', sessionCookieHeader); + raceOutcome: renewed ? 'renewal' : 'fresh', + }).catch(() => undefined); + const response = respond(responses.verified(sessionId, expiresAt), 200); + response.headers.set('Set-Cookie', formatSessionCookie(createSessionCookie(sessionId))); return response; - } catch (err) { - if (err instanceof SyntaxError) { - return createSecureSessionResponse(responses.invalid(), 400); - } - return createSecureSessionResponse(responses.error(err instanceof Error ? err.message : 'Unknown error'), 502); + } catch { + return respond(responses.error('Verification is unavailable'), 502); } } diff --git a/netlify/lib/reader-access/code-store.ts b/netlify/lib/reader-access/code-store.ts new file mode 100644 index 00000000..7070a058 --- /dev/null +++ b/netlify/lib/reader-access/code-store.ts @@ -0,0 +1,154 @@ +/** + * Verification-code and access-session storage for spec 005 (reader access). + * + * Spec 006 rewrote `store.ts` around email + device sessions and removed the + * code storage that the spec 005 functions depend on. This module restores it + * as a separate file so the two specs no longer edit the same adapter. + * + * Key prefixes are distinct from spec 006 (`session::`): + * code: current VerificationCode for an email + * code-consumed: consume-once marker (written with onlyIfNew) + * access-session: session looked up by the opaque cookie value + * recovery: RecoveryAttempt (RA-T047/RA-T048) + * + * @see .github/specs/005-reader-access/data-model.md + */ + +import { getStore } from '@netlify/blobs'; + +const STORE_NAME = 'reader-access'; +const SESSION_DAYS = 30; + +export interface StoredCode { + /** Unique per issued code; used for the consume-once marker. */ + codeId: string; + codeHash: string; + salt: string; + createdAt: string; + expiresAt: string; + attemptCount: number; + maxAttempts: number; +} + +export interface AccessSession { + sessionId: string; + /** Hashed reader identifier; never the plain email (RA-008). */ + readerId: string; + createdAt: string; + expiresAt: string; + renewedAt: string; +} + +export interface StoredRecoveryAttempt { + recoveryId: string; + readerId: string; + initiatedAt: string; + expiresAt: string; + createdSessionId?: string; + raceOutcome?: 'recovery_first' | 'code_first' | 'concurrent' | 'renewal' | 'fresh'; +} + +function store() { + return getStore({ name: STORE_NAME, consistency: 'strong' }); +} + +/** Normalise so `Reader@Example.com` and `reader@example.com` share one code. */ +export function normaliseEmail(email: string): string { + return email.trim().toLowerCase(); +} + +const KEYS = { + code: (email: string) => `code:${normaliseEmail(email)}`, + consumed: (codeId: string) => `code-consumed:${codeId}`, + session: (sessionId: string) => `access-session:${sessionId}`, + recovery: (recoveryId: string) => `recovery:${recoveryId}`, +}; + +async function readJson(key: string): Promise { + const data = await store().get(key, { type: 'text' }); + return data ? (JSON.parse(data) as T) : null; +} + +async function writeJson(key: string, value: unknown): Promise { + await store().set(key, JSON.stringify(value)); +} + +// ---------------------------------------------------------------- codes + +/** Store the current code for an email, replacing any earlier one (resend). */ +export async function storeCode(email: string, code: StoredCode): Promise { + await writeJson(KEYS.code(email), code); +} + +export async function getCode(email: string): Promise { + return readJson(KEYS.code(email)); +} + +export async function incrementCodeAttempts(email: string): Promise { + const code = await getCode(email); + if (!code) return null; + code.attemptCount += 1; + await writeJson(KEYS.code(email), code); + return code; +} + +export async function deleteCode(email: string): Promise { + await store().delete(KEYS.code(email)); +} + +/** + * Atomically consume a code (RA-002: "consume at most once, atomically"). + * + * Writes a marker keyed by the code's id with `onlyIfNew`. Netlify Blobs + * applies that condition server-side, so when two requests redeem the same + * code at once exactly one write reports `modified: true`. + * + * @returns true for the single caller that consumed the code, false otherwise + */ +export async function consumeCode(email: string, codeId: string): Promise { + const result = await store().set( + KEYS.consumed(codeId), + JSON.stringify({ consumedAt: new Date().toISOString() }), + { onlyIfNew: true } + ); + if (!result.modified) { + return false; + } + // Best effort: the marker already blocks reuse if this delete fails. + await deleteCode(email).catch(() => undefined); + return true; +} + +// ------------------------------------------------------ access sessions + +export async function storeAccessSession(session: AccessSession): Promise { + await writeJson(KEYS.session(session.sessionId), session); +} + +/** Returns the session only while it is unexpired. */ +export async function getAccessSession(sessionId: string): Promise { + const session = await readJson(KEYS.session(sessionId)); + if (!session) return null; + return new Date(session.expiresAt) > new Date() ? session : null; +} + +/** Move expiry to thirty days from now (renewals have no overall ceiling). */ +export async function renewAccessSession(sessionId: string): Promise { + const session = await getAccessSession(sessionId); + if (!session) return null; + const now = new Date(); + session.renewedAt = now.toISOString(); + session.expiresAt = new Date(now.getTime() + SESSION_DAYS * 24 * 60 * 60 * 1000).toISOString(); + await writeJson(KEYS.session(sessionId), session); + return session; +} + +export async function deleteAccessSession(sessionId: string): Promise { + await store().delete(KEYS.session(sessionId)); +} + +// ------------------------------------------------------------- recovery + +export async function storeRecoveryAttempt(recovery: StoredRecoveryAttempt): Promise { + await writeJson(KEYS.recovery(recovery.recoveryId), recovery); +} diff --git a/netlify/lib/reader-access/codes.ts b/netlify/lib/reader-access/codes.ts index 5f56f455..94818e5d 100644 --- a/netlify/lib/reader-access/codes.ts +++ b/netlify/lib/reader-access/codes.ts @@ -2,9 +2,10 @@ // Six-digit numeric codes; stored hashed // Expire after 10 minutes; five wrong attempts to limit guessing -import { randomInt, scryptSync, randomBytes } from 'crypto'; +import { randomInt, scryptSync, randomBytes, randomUUID, timingSafeEqual } from 'crypto'; export interface VerificationCode { + codeId: string; // Unique id for the consume-once marker codeHash: string; // Salted hash; plain code never stored salt: string; // Base64-encoded salt for validation createdAt: string; // ISO timestamp @@ -41,17 +42,23 @@ export function verifyCode(plainCode: string, storedHash: string, salt: string): // Recalculate hash with same salt and compare (constant-time comparison) const saltBuffer = Buffer.from(salt, 'base64'); const { hash } = hashCode(plainCode, saltBuffer); - return hash === storedHash; + const actual = Buffer.from(hash, 'base64'); + const expected = Buffer.from(storedHash, 'base64'); + return actual.length === expected.length && timingSafeEqual(actual, expected); } -export function createVerificationCode(): VerificationCode { - const plainCode = generateCode(); +/** + * Build the stored record for a code. Pass the plain code that is emailed to + * the reader; otherwise a new one is generated and the caller cannot send it. + */ +export function createVerificationCode(plainCode: string = generateCode()): VerificationCode { const salt = randomBytes(SALT_BYTES); const { hash } = hashCode(plainCode, salt); const now = new Date(); const expiresAt = new Date(now.getTime() + CODE_EXPIRY_MINUTES * 60 * 1000); return { + codeId: randomUUID(), codeHash: hash, salt: salt.toString('base64'), createdAt: now.toISOString(), diff --git a/netlify/lib/reader-access/mailer.ts b/netlify/lib/reader-access/mailer.ts index b6b6d3cd..5b527b3f 100644 --- a/netlify/lib/reader-access/mailer.ts +++ b/netlify/lib/reader-access/mailer.ts @@ -20,13 +20,14 @@ export interface MailerConfig { const DEFAULT_FROM = 'noreply@thisonetimeonacidcom.com'; export class MailgunMailer { - private mg: ReturnType; + private mg: ReturnType['client']>; private domain: string; private fromAddress: string; constructor(config: MailerConfig) { const mailgun = new Mailgun(FormData); - this.mg = mailgun.client({ key: config.apiKey }); + // Mailgun uses basic auth with the fixed username 'api'. + this.mg = mailgun.client({ username: 'api', key: config.apiKey }); this.domain = config.domain; this.fromAddress = config.fromAddress || DEFAULT_FROM; } diff --git a/package-lock.json b/package-lock.json index 6fbdf68a..50d5007d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,7 @@ "@emotion/styled": "11.14.1", "@mui/icons-material": "9.5.0", "@mui/material": "9.5.0", - "@netlify/blobs": "^6.2.0", + "@netlify/blobs": "^11.1.6", "@phosphor-icons/react": "2.1.10", "@radix-ui/react-accordion": "1.3.1", "@radix-ui/react-alert-dialog": "1.2.1", @@ -79,6 +79,7 @@ "@vitejs/plugin-react": "6.2.1", "@vitest/coverage-v8": "1.6.1", "bats": "^1.11.0", + "esbuild": "0.28.2", "glob": "13.0.6", "gray-matter": "^4.0.3", "jest": "^30.5.2", @@ -822,6 +823,19 @@ "integrity": "sha512-snKqtPW01tN0ui7yu9rGv69aJXr/a/Ywvl11sUjNtEcRc+ng/mQriFL0wLXMef74iHa/EkftbDzU9F8iFbH+zg==", "license": "MIT" }, + "node_modules/@envelop/instrumentation": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@envelop/instrumentation/-/instrumentation-1.0.1.tgz", + "integrity": "sha512-FuexE2qd3Yc1Kh1DjTliwGxb9kyyv4ySBNnfJOxnQasVmGdcqX6AkkO5sIMxLWFRftp8PErOcIn2dQW/1RwytQ==", + "license": "MIT", + "dependencies": { + "@whatwg-node/promise-helpers": "^1.2.1", + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.28.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", @@ -1264,6 +1278,12 @@ "node": ">=18" } }, + "node_modules/@fastify/busboy": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.6.tgz", + "integrity": "sha512-UPXdyAMbz/gNvjS8HONpJR2TDaHM3wQKMtSRPFkoh2LTeRRtnm+ICVYKgBYkTwlPOVzDNynOd34EH8qapwfelQ==", + "license": "MIT" + }, "node_modules/@floating-ui/core": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", @@ -2705,12 +2725,76 @@ } }, "node_modules/@netlify/blobs": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/@netlify/blobs/-/blobs-6.5.0.tgz", - "integrity": "sha512-wRFlNnL/Qv3WNLZd3OT/YYqF1zb6iPSo8T31sl9ccL1ahBxW1fBqKgF4b1XL7Z+6mRIkatvcsVPkWBcO+oJMNA==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@netlify/blobs/-/blobs-11.1.6.tgz", + "integrity": "sha512-7CKpZs4WbMqMvHRxXpQw395X4YBw9keGy3yDr7+pXjAgHlDO7kdYv3chkBYRc78K6delj7Mrmn2NB1HK2E5DxQ==", + "license": "MIT", + "dependencies": { + "@netlify/dev-utils": "6.0.4", + "@netlify/otel": "^7.0.6", + "@netlify/runtime-utils": "3.0.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@netlify/dev-utils": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/@netlify/dev-utils/-/dev-utils-6.0.4.tgz", + "integrity": "sha512-VZgq2gqRLQual8P2v6B8/W1WgUNYJvVvgqCIbviPR/BcI6hKvxVBdAMjz+84eU3qpfMau1Bn2J70JDSQSNkNgg==", + "license": "MIT", + "dependencies": { + "@whatwg-node/server": "^0.11.0", + "ansis": "^4.1.0", + "atomically": "^2.0.3", + "chokidar": "^5.0.0", + "decache": "^4.6.2", + "dettle": "^1.0.5", + "dot-prop": "9.0.0", + "empathic": "^2.0.0", + "env-paths": "^3.0.0", + "parse-gitignore": "^2.0.0", + "semver": "^7.7.2" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@netlify/dev-utils/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@netlify/otel": { + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/@netlify/otel/-/otel-7.0.8.tgz", + "integrity": "sha512-sFKKABqvQN6VAtdEH/tBkdZUZUYkLSzWhzacjUWp40t694WuSo8YyhWQeG/LqYrxkqWyLAPjb2bYzla/euqmxQ==", + "license": "MIT", + "dependencies": { + "@opentelemetry/api": "1.9.1", + "@opentelemetry/core": "2.12.0", + "@opentelemetry/instrumentation": "^0.223.0", + "@opentelemetry/resources": "2.12.0", + "@opentelemetry/sdk-trace-node": "2.12.0" + }, + "engines": { + "node": ">=22.12.0" + } + }, + "node_modules/@netlify/runtime-utils": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@netlify/runtime-utils/-/runtime-utils-3.0.0.tgz", + "integrity": "sha512-OHo40+V3QZkR+UrDjqhN+LekrAby/dSSJxsvyYs9i88E/mSl3goB/ysoL+VYROm190egxmQyRYlHK7vL4GeHBQ==", "license": "MIT", "engines": { - "node": "^14.16.0 || >=16.0.0" + "node": ">=22.12.0" } }, "node_modules/@nodelib/fs.scandir": { @@ -2751,6 +2835,150 @@ "node": ">= 8" } }, + "node_modules/@opentelemetry/api": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", + "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/api-logs": { + "version": "0.223.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.223.2.tgz", + "integrity": "sha512-pKr/0bxkzNPhWKTqqSP2KtPVxqmC2oQrWjUjr4EDHrJCCiRkGIN52m2c7ILhCnQkYKmlTQBiESIEeyg0hlmotQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@opentelemetry/context-async-hooks": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.12.0.tgz", + "integrity": "sha512-iK/1nD7mmZVkuYjVjkdFBiCvzntJdFny1S3CYbUYyOq7V5enL6XX+gJ7eh965L1LnS11VA8mQ7Ej/ck04SB0MQ==", + "license": "Apache-2.0", + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/core": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.12.0.tgz", + "integrity": "sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/instrumentation": { + "version": "0.223.2", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.223.2.tgz", + "integrity": "sha512-2tRpOgQ91+wC2/h6IDt+dsQNuUlfUR+CVwABceAEtiWtON9JumZR6YQcYCsisNRTX942TnCjPDuBI0xxGgVLHQ==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api-logs": "0.223.2", + "import-in-the-middle": "^3.0.0", + "require-in-the-middle": "^8.0.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, + "node_modules/@opentelemetry/resources": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.12.0.tgz", + "integrity": "sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.12.0", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace/-/sdk-trace-2.12.0.tgz", + "integrity": "sha512-ImVuRQ6faOsTi1Wna88s2avgrrf/iDgXPigIeynkUhjstMuoQUDOJXgkez2j1mlU4btjXcXBGa+q7qKFYR3GsA==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.12.0", + "@opentelemetry/resources": "2.12.0", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-base": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.12.0.tgz", + "integrity": "sha512-JOERgZCxRM06FEJ5kEWxlSRChah6MmXDx3KwCruqEv/iEyLkTokCSemf2y1w8oIHtfrr8EVTpzebq/31vn2Cpg==", + "deprecated": "Use @opentelemetry/sdk-trace package", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/core": "2.12.0", + "@opentelemetry/resources": "2.12.0", + "@opentelemetry/sdk-trace": "2.12.0", + "@opentelemetry/semantic-conventions": "^1.29.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.3.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/sdk-trace-node": { + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.12.0.tgz", + "integrity": "sha512-9DufH1IlmQMoKAfot5y/FhTP1RnmhLb5K6eKmJO/bvzPjYwPAazoiAUbTZFdPbqxOXN0FEbhZx/e6SB1Og4jmg==", + "deprecated": "Use @opentelemetry/sdk-trace package", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/context-async-hooks": "2.12.0", + "@opentelemetry/core": "2.12.0", + "@opentelemetry/sdk-trace-base": "2.12.0" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": ">=1.0.0 <1.10.0" + } + }, + "node_modules/@opentelemetry/semantic-conventions": { + "version": "1.45.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.45.0.tgz", + "integrity": "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==", + "license": "Apache-2.0", + "engines": { + "node": ">=14" + } + }, "node_modules/@oxc-parser/binding-android-arm-eabi": { "version": "0.152.0", "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.152.0.tgz", @@ -7669,6 +7897,75 @@ "dev": true, "license": "MIT" }, + "node_modules/@whatwg-node/disposablestack": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@whatwg-node/disposablestack/-/disposablestack-0.0.6.tgz", + "integrity": "sha512-LOtTn+JgJvX8WfBVJtF08TGrdjuFzGJc4mkP8EdDI8ADbvO7kiexYep1o8dwnt0okb0jYclCDXF13xU7Ge4zSw==", + "license": "MIT", + "dependencies": { + "@whatwg-node/promise-helpers": "^1.0.0", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/fetch": { + "version": "0.10.13", + "resolved": "https://registry.npmjs.org/@whatwg-node/fetch/-/fetch-0.10.13.tgz", + "integrity": "sha512-b4PhJ+zYj4357zwk4TTuF2nEe0vVtOrwdsrNo5hL+u1ojXNhh1FgJ6pg1jzDlwlT4oBdzfSwaBwMCtFCsIWg8Q==", + "license": "MIT", + "dependencies": { + "@whatwg-node/node-fetch": "^0.8.3", + "urlpattern-polyfill": "^10.0.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/node-fetch": { + "version": "0.8.6", + "resolved": "https://registry.npmjs.org/@whatwg-node/node-fetch/-/node-fetch-0.8.6.tgz", + "integrity": "sha512-BDMdYFcerLQkwA2RTldxOqRCs6ZQD1S7UgP3pUdGUkcbgTrP/V5ko77ZkCww9DHmC4lpoYuwigGfQYj285gMvA==", + "license": "MIT", + "dependencies": { + "@fastify/busboy": "^3.1.1", + "@whatwg-node/disposablestack": "^0.0.6", + "@whatwg-node/promise-helpers": "^1.3.2", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@whatwg-node/promise-helpers": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@whatwg-node/promise-helpers/-/promise-helpers-1.3.2.tgz", + "integrity": "sha512-Nst5JdK47VIl9UcGwtv2Rcgyn5lWtZ0/mhRQ4G8NN2isxpq2TO30iqHzmwoJycjWuyUfg3GFXqP/gFHXeV57IA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/@whatwg-node/server": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@whatwg-node/server/-/server-0.11.0.tgz", + "integrity": "sha512-VSdkwnJRr8Yv9UgB2aXB3VUPWwd6Oqnn0hycFwhg9pZgWxJXb7JmhsiXe9tmpMwjHFxli12PGcz9aI63YYloGQ==", + "license": "MIT", + "dependencies": { + "@envelop/instrumentation": "^1.0.0", + "@whatwg-node/disposablestack": "^0.0.6", + "@whatwg-node/fetch": "^0.10.13", + "@whatwg-node/promise-helpers": "^1.3.2", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/agent-base": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", @@ -7723,6 +8020,15 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/ansis": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/ansis/-/ansis-4.5.0.tgz", + "integrity": "sha512-KwIVkfFfJSSzBmZhDGuTmkhWqTdyB5oNVzzznBJbBZ5bZtHiqSrcugRF0RKJKT4Ss3d7ZrcjnlFVDlQNmtWfWw==", + "license": "ISC", + "engines": { + "node": ">=14" + } + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -7788,6 +8094,16 @@ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "license": "MIT" }, + "node_modules/atomically": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/atomically/-/atomically-2.1.1.tgz", + "integrity": "sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ==", + "license": "MIT", + "dependencies": { + "stubborn-fs": "^2.0.0", + "when-exit": "^2.1.4" + } + }, "node_modules/axe-core": { "version": "4.14.0", "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.0.tgz", @@ -8154,6 +8470,14 @@ "node": ">= 0.4" } }, + "node_modules/callsite": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz", + "integrity": "sha512-0vdNRFXn5q+dtOqjfFtmtlI9N2eVZ7LMyEV2iKC5mEEFvSg/69Ml6b/WU2qF8W1nLRa0wiSrDT3Y5jOHZCwKPQ==", + "engines": { + "node": "*" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -8264,6 +8588,21 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/chokidar": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", + "license": "MIT", + "dependencies": { + "readdirp": "^5.0.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/ci-info": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", @@ -8284,7 +8623,6 @@ "version": "2.3.0", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.3.0.tgz", "integrity": "sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==", - "dev": true, "license": "MIT" }, "node_modules/class-variance-authority": { @@ -8610,6 +8948,15 @@ } } }, + "node_modules/decache": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/decache/-/decache-4.6.2.tgz", + "integrity": "sha512-2LPqkLeu8XWHU8qNCS3kcF6sCcb5zIzvWaAHYSvPfwhdd7mHuah29NssMzrTYyHN4F5oFy2ko9OBYxegtU0FEw==", + "license": "MIT", + "dependencies": { + "callsite": "^1.0.0" + } + }, "node_modules/decimal.js-light": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", @@ -8743,6 +9090,12 @@ "integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==", "license": "MIT" }, + "node_modules/dettle": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/dettle/-/dettle-1.0.5.tgz", + "integrity": "sha512-ZVyjhAJ7sCe1PNXEGveObOH9AC8QvMga3HJIghHawtG7mE4K5pW9nz/vDGAr/U7a3LWgdOzEE7ac9MURnyfaTA==", + "license": "MIT" + }, "node_modules/devlop": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", @@ -8798,6 +9151,33 @@ "csstype": "^3.0.2" } }, + "node_modules/dot-prop": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-9.0.0.tgz", + "integrity": "sha512-1gxPBJpI/pcjQhKgIU91II6Wkay+dLcN3M6rf2uwP8hRur3HtQXjVrdAK3sjC0piaEuxzMwjXChcETiJl47lAQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^4.18.2" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/dot-prop/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/dotenv": { "version": "17.4.2", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", @@ -8890,7 +9270,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/empathic/-/empathic-2.1.0.tgz", "integrity": "sha512-AnfC1ATldl49/cvZdLPDjBfrRNwbDO05aibiOtzQu3qtlbJtomNLhF30HEtn/7iBz50dlMECqATo3fG0LrdEgw==", - "dev": true, "license": "MIT", "engines": { "node": ">=14" @@ -8923,6 +9302,18 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/env-paths": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz", + "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/error-ex": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", @@ -9727,6 +10118,26 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/import-in-the-middle": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.6.0.tgz", + "integrity": "sha512-xRU7hI24S2FhucXtuZXn8EpcOjfVP6iiEQyR0USayPeaOroEmSsNlqnl95866iRdRtkHrd6Q/Z4D14R60au0+A==", + "license": "Apache-2.0", + "dependencies": { + "cjs-module-lexer": "^2.2.0", + "es-module-lexer": "^3.0.4", + "module-details-from-path": "^1.0.4" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/import-in-the-middle/node_modules/es-module-lexer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-3.0.5.tgz", + "integrity": "sha512-RNq2lKJw53c7z9QRHeiKeA6Ez0oikOqiBGdmxQhKDxEiOX1g5QJR4IoFVwicn8uCZcRWNrXC3NZaJihgK7aEbg==", + "license": "MIT" + }, "node_modules/import-local": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", @@ -12594,6 +13005,12 @@ "node": ">=16 || 14 >=14.17" } }, + "node_modules/module-details-from-path": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", + "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==", + "license": "MIT" + }, "node_modules/motion": { "version": "14.6.0", "resolved": "https://registry.npmjs.org/motion/-/motion-14.6.0.tgz", @@ -12974,6 +13391,15 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/parse-gitignore": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/parse-gitignore/-/parse-gitignore-2.0.0.tgz", + "integrity": "sha512-RmVuCHWsfu0QPNW+mraxh/xjQVw/lhUCUru8Zni3Ctq3AoMhpDTq0OVdKS6iesd6Kqb7viCV3isAL43dciOSog==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", @@ -13575,6 +14001,19 @@ "react-dom": ">=16.6.0" } }, + "node_modules/readdirp": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/recast": { "version": "0.23.21", "resolved": "https://registry.npmjs.org/recast/-/recast-0.23.21.tgz", @@ -13687,6 +14126,19 @@ "node": ">=0.10.0" } }, + "node_modules/require-in-the-middle": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz", + "integrity": "sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "module-details-from-path": "^1.0.3" + }, + "engines": { + "node": ">=9.3.0 || >=8.10.0 <9.0.0" + } + }, "node_modules/reselect": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.2.0.tgz", @@ -14759,6 +15211,21 @@ "dev": true, "license": "MIT" }, + "node_modules/stubborn-fs": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/stubborn-fs/-/stubborn-fs-2.0.0.tgz", + "integrity": "sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA==", + "license": "MIT", + "dependencies": { + "stubborn-utils": "^1.0.1" + } + }, + "node_modules/stubborn-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/stubborn-utils/-/stubborn-utils-1.0.2.tgz", + "integrity": "sha512-zOh9jPYI+xrNOyisSelgym4tolKTJCQd5GBhK0+0xJvcYDcwlOoxF/rnFKQ2KRZknXSG9jWAp66fwP6AxN9STg==", + "license": "MIT" + }, "node_modules/stylis": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.2.0.tgz", @@ -15203,6 +15670,12 @@ "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", "license": "MIT" }, + "node_modules/urlpattern-polyfill": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/urlpattern-polyfill/-/urlpattern-polyfill-10.1.0.tgz", + "integrity": "sha512-IGjKp/o0NL3Bso1PymYURCJxMPNAf/ILOpendP9f5B6e1rTJgdgiOvgfoT8VxCAdY+Wisb9uhGaJJf3yZ2V9nw==", + "license": "MIT" + }, "node_modules/use-callback-ref": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", @@ -15772,6 +16245,12 @@ "integrity": "sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==", "license": "Apache-2.0" }, + "node_modules/when-exit": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/when-exit/-/when-exit-2.1.5.tgz", + "integrity": "sha512-VGkKJ564kzt6Ms1dbgPP/yuIoQCrsFAnRbptpC5wOEsDaNsbCB2bnfnaA8i/vRs5tjUSEOtIuvl9/MyVsvQZCg==", + "license": "MIT" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/package.json b/package.json index 92c6d343..23071358 100644 --- a/package.json +++ b/package.json @@ -84,7 +84,7 @@ "tw-animate-css": "1.4.0", "vaul": "1.1.2", "mailgun.js": "^9.3.0", - "@netlify/blobs": "^6.2.0", + "@netlify/blobs": "^11.1.6", "form-data": "^4.0.0" }, "devDependencies": { @@ -98,6 +98,7 @@ "@vitejs/plugin-react": "6.2.1", "@vitest/coverage-v8": "1.6.1", "bats": "^1.11.0", + "esbuild": "0.28.2", "glob": "13.0.6", "gray-matter": "^4.0.3", "jest": "^30.5.2", diff --git a/public/_redirects b/public/_redirects index 4ac84475..d1d5e6c1 100644 --- a/public/_redirects +++ b/public/_redirects @@ -2,6 +2,7 @@ /api/reader/verifications /.netlify/functions/reader-verify 200 /api/reader/chapters /.netlify/functions/reader-chapters-list 200 /api/reader/chapters/:chapterId/content /.netlify/functions/reader-chapter-content/:chapterId 200 +/api/reader/chapters/:chapterId /.netlify/functions/reader-chapter 200 /api/reader/progress /.netlify/functions/reader-progress 200 /api/reader/analytics /.netlify/functions/reader-analytics 200 /api/reader/bookmarks /.netlify/functions/reader-bookmarks 200 diff --git a/tests/reader-access/code-store.test.ts b/tests/reader-access/code-store.test.ts new file mode 100644 index 00000000..f565c247 --- /dev/null +++ b/tests/reader-access/code-store.test.ts @@ -0,0 +1,126 @@ +/** + * Spec 005 code storage (RA-002) and the request → verify link. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; + +const blobs = new Map(); + +// In-memory stand-in that honours `onlyIfNew` the way Netlify Blobs does. +vi.mock('@netlify/blobs', () => ({ + getStore: () => ({ + get: async (key: string) => blobs.get(key) ?? null, + set: async (key: string, value: string, options?: { onlyIfNew?: boolean }) => { + if (options?.onlyIfNew && blobs.has(key)) { + return { modified: false }; + } + blobs.set(key, value); + return { modified: true, etag: 'etag' }; + }, + delete: async (key: string) => { + blobs.delete(key); + }, + }), +})); + +import { + storeCode, + getCode, + consumeCode, + incrementCodeAttempts, + storeAccessSession, + getAccessSession, + renewAccessSession, + deleteAccessSession, +} from '../../netlify/lib/reader-access/code-store'; +import { createVerificationCode, verifyCode } from '../../netlify/lib/reader-access/codes'; + +beforeEach(() => blobs.clear()); + +describe('createVerificationCode', () => { + it('stores a hash of the code that is emailed', () => { + const record = createVerificationCode('123456'); + expect(verifyCode('123456', record.codeHash, record.salt)).toBe(true); + expect(verifyCode('654321', record.codeHash, record.salt)).toBe(false); + }); + + it('gives each issued code its own id', () => { + expect(createVerificationCode('111111').codeId).not.toBe(createVerificationCode('111111').codeId); + }); +}); + +describe('code storage', () => { + it('normalises the email so case does not create a second code', async () => { + await storeCode('Reader@Example.com', createVerificationCode('123456')); + expect(await getCode('reader@example.com')).not.toBeNull(); + }); + + it('replaces the earlier code on resend', async () => { + const first = createVerificationCode('111111'); + const second = createVerificationCode('222222'); + await storeCode('a@b.co', first); + await storeCode('a@b.co', second); + expect((await getCode('a@b.co'))?.codeId).toBe(second.codeId); + }); + + it('counts wrong attempts', async () => { + await storeCode('a@b.co', createVerificationCode('123456')); + await incrementCodeAttempts('a@b.co'); + expect((await getCode('a@b.co'))?.attemptCount).toBe(1); + }); +}); + +describe('consumeCode (RA-002)', () => { + it('lets exactly one of two concurrent redemptions succeed', async () => { + const record = createVerificationCode('123456'); + await storeCode('a@b.co', record); + + const results = await Promise.all([ + consumeCode('a@b.co', record.codeId), + consumeCode('a@b.co', record.codeId), + ]); + + expect(results.filter(Boolean)).toHaveLength(1); + expect(await getCode('a@b.co')).toBeNull(); + }); + + it('refuses a code that was already consumed', async () => { + const record = createVerificationCode('123456'); + await storeCode('a@b.co', record); + expect(await consumeCode('a@b.co', record.codeId)).toBe(true); + expect(await consumeCode('a@b.co', record.codeId)).toBe(false); + }); +}); + +describe('access sessions', () => { + const now = Date.now(); + const session = { + sessionId: 'sid', + readerId: 'hash', + createdAt: new Date(now).toISOString(), + renewedAt: new Date(now).toISOString(), + expiresAt: new Date(now + 60_000).toISOString(), + }; + + it('returns an active session and hides an expired one', async () => { + await storeAccessSession(session); + expect(await getAccessSession('sid')).toEqual(session); + + await storeAccessSession({ ...session, expiresAt: new Date(now - 1).toISOString() }); + expect(await getAccessSession('sid')).toBeNull(); + }); + + it('renews expiry to thirty days ahead', async () => { + await storeAccessSession(session); + const renewed = await renewAccessSession('sid'); + const days = (new Date(renewed!.expiresAt).getTime() - Date.now()) / 86_400_000; + expect(days).toBeGreaterThan(29.9); + expect(days).toBeLessThanOrEqual(30); + }); + + it('ends the server session on sign-out', async () => { + await storeAccessSession(session); + await deleteAccessSession('sid'); + expect(await getAccessSession('sid')).toBeNull(); + }); +}); diff --git a/tests/reader-access/functions-build.test.ts b/tests/reader-access/functions-build.test.ts new file mode 100644 index 00000000..cd8e4a3f --- /dev/null +++ b/tests/reader-access/functions-build.test.ts @@ -0,0 +1,74 @@ +/** + * Build guard for Netlify Functions. + * + * Unit tests import library modules directly and mock @netlify/blobs, so a + * function that imports a missing export still passes them. PR #635 removed + * the code-storage exports from store.ts and four functions stopped building + * without any test failing. This suite bundles each function the way Netlify + * does and checks that every redirect points at a function that exists. + */ + +import { readdirSync, readFileSync, existsSync } from 'fs'; +import { join, resolve } from 'path'; +import { build } from 'esbuild'; +import { describe, it, expect } from 'vitest'; + +const ROOT = resolve(__dirname, '../..'); +const FUNCTIONS_DIR = join(ROOT, 'netlify/functions'); + +const functionFiles = readdirSync(FUNCTIONS_DIR).filter((f) => f.endsWith('.ts')); + +/** Function names referenced as `/.netlify/functions/` in a config file. */ +function referencedFunctions(file: string): string[] { + const text = readFileSync(join(ROOT, file), 'utf8'); + return [...text.matchAll(/\/\.netlify\/functions\/([a-z0-9-]+)/gi)] + .map((m) => m[1]) + // `reader-:splat` is a catch-all pattern, not a function name. + .filter((name) => !name.endsWith('-')); +} + +describe('Netlify functions build', () => { + it('finds functions to check', () => { + expect(functionFiles.length).toBeGreaterThan(0); + }); + + it.each(functionFiles)('%s bundles without errors', async (file) => { + const result = await build({ + entryPoints: [join(FUNCTIONS_DIR, file)], + bundle: true, + platform: 'node', + format: 'esm', + target: 'node24', + write: false, + logLevel: 'silent', + }).catch((error: { errors?: { text: string }[] }) => ({ + errors: error.errors ?? [{ text: String(error) }], + })); + + expect(result.errors.map((e) => e.text)).toEqual([]); + }, 30000); +}); + +describe('Reader API routing', () => { + it.each(['public/_redirects', 'netlify.toml'])( + 'every function named in %s exists', + (file) => { + const missing = referencedFunctions(file).filter( + (name) => !existsSync(join(FUNCTIONS_DIR, `${name}.ts`)) + ); + expect(missing).toEqual([]); + } + ); + + it('routes a protected chapter before the SPA fallback in public/_redirects', () => { + const lines = readFileSync(join(ROOT, 'public/_redirects'), 'utf8') + .split('\n') + .map((line) => line.trim().split(/\s+/)); + const chapter = lines.findIndex(([from]) => from === '/api/reader/chapters/:chapterId'); + const fallback = lines.findIndex(([from]) => from === '/*'); + + expect(chapter).toBeGreaterThanOrEqual(0); + expect(lines[chapter][1]).toBe('/.netlify/functions/reader-chapter'); + expect(chapter).toBeLessThan(fallback); + }); +}); From 6d6a9d81405b42338db7f49b3614a92a699a1774 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 11:38:40 +0000 Subject: [PATCH 2/2] docs(changelog): record spec 005 reader access build fix Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZdpaiuKYHLz2mX9por --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b18f19e..308b0f01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Specification 005 reader access functions did not build** — PR #635 removed the verification-code exports from `netlify/lib/reader-access/store.ts`, so `reader-code-request`, `reader-verify` and `reader-chapter` failed to bundle. Restored code storage in a separate `code-store.ts` with an atomic consume-once marker (`@netlify/blobs` 6 → 11 for conditional writes). Also fixed: the emailed code was never the one stored, the Mailgun client lacked `username: 'api'`, sign-out left the server session active, `reader-retention` used non-existent imports and had no schedule, and `/api/reader/chapters/:chapterId` fell through to `index.html`. Added a test that bundles every function and checks redirect targets. - **Corrupted package-lock.json** — The merge in `161ed46` truncated `package-lock.json` into invalid JSON, so `npm ci` failed with `EUSAGE` in every workflow. Regenerated the lockfile from the last valid copy (`7db390c`) with `npm install --package-lock-only --ignore-scripts`; `package.json` is unchanged. - **CI: Removed unused Playwright browser install from Vitest job** — The `Install Playwright browsers` step in `tests.yml` stalled on the runner's apt mirror (~20 s per package, 49 packages), causing both matrix jobs to time out at 20 minutes and the "No new test failures" comparison to fail closed. The Vitest suite runs in a plain Node environment and needs no browser binaries. Removing the step unblocks the Tests workflow without affecting test coverage. - **Netlify deployment configuration** — Removed duplicate `public/_redirects` file that conflicted with redirect rules defined in `netlify.toml`, resolving validation failures for header rules, redirect rules, and pages changed checks