From 271c6dfffdea0460c1ce8a6ef0a4c78444a64245 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 11:46:15 +0000 Subject: [PATCH 1/2] fix(reader-access): make session suites pass under Vitest listSessionsByEmail treated @netlify/blobs list() as returning string[], but it resolves to { blobs: [{ key, etag }], directories }. Correct the BlobStore type and read keys from blobs[].key. The suite mocks encoded the same wrong shape and ignored the prefix, so sessions for every email in a file counted against each reader's device limit. Session service fixes found while making the suites honest: - Device limit ignores the session being replaced on the same device and expired sessions, so re-verifying on a known device or after expiry is not refused with 409. - createSession serialises its check-then-write per email so concurrent verifications in one instance cannot exceed the limit. - Creation no longer opens the renewal coalescing window; only an earlier renewal does, so first activity after sign-in extends it. - Expiry tolerance boundary is half-open (exactly at tolerance = expired). Tests: shared in-memory Blobs helper that honours prefix and the real list() shape; session.test.ts exercises the real store instead of an auto-mocked one; awaited .rejects assertions; rate-limit state reset between tests; timing checks use warm-up, batching and interleaved medians (thresholds unchanged); corrected fixtures and assertions that contradicted the spec (rolling window, base64url tokens, empty tokens). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZhriKj5xS1hQnwWGg4 --- netlify/lib/blobs.ts | 11 +- netlify/lib/reader-access/session-service.ts | 130 ++++++++++++------ netlify/lib/reader-access/store.ts | 16 +-- tests/helpers/in-memory-blob-store.ts | 48 +++++++ tests/performance/session-latency.test.ts | 18 +-- .../device-limit-integration.test.ts | 27 +--- tests/reader-access/device-limit.test.ts | 27 +--- tests/reader-access/session-audit.test.ts | 33 ++--- .../session-renewal-integration.test.ts | 22 ++- tests/reader-access/session-renewal.test.ts | 20 +-- .../reader-access/session-timestamps.test.ts | 20 +-- tests/session/device-limit-tests.test.ts | 67 ++++++--- tests/session/security.test.ts | 104 +++++++------- tests/session/session-create.test.ts | 19 +-- tests/session/session-expiry.test.ts | 24 ++-- tests/session/session-logout.test.ts | 24 ++-- tests/session/session-persistence.test.ts | 24 ++-- tests/session/session-renewal.test.ts | 34 +++-- tests/session/session.test.ts | 57 +++++--- 19 files changed, 401 insertions(+), 324 deletions(-) create mode 100644 tests/helpers/in-memory-blob-store.ts diff --git a/netlify/lib/blobs.ts b/netlify/lib/blobs.ts index 5a94ba36..0a137532 100644 --- a/netlify/lib/blobs.ts +++ b/netlify/lib/blobs.ts @@ -14,11 +14,20 @@ import { getStore as getNetlifyStore } from '@netlify/blobs'; +/** + * Shape returned by `Store.list()` in `@netlify/blobs` (non-paginated). + * `list()` resolves to an object of entries, not to an array of keys. + */ +export interface BlobListResult { + blobs: Array<{ key: string; etag: string }>; + directories: string[]; +} + export interface BlobStore { set(key: string, value: string): Promise; get(key: string): Promise; delete(key: string): Promise; - list?(options?: { prefix?: string }): Promise; + list(options?: { prefix?: string }): Promise; } /** diff --git a/netlify/lib/reader-access/session-service.ts b/netlify/lib/reader-access/session-service.ts index fb5bc737..28977fd9 100644 --- a/netlify/lib/reader-access/session-service.ts +++ b/netlify/lib/reader-access/session-service.ts @@ -31,6 +31,46 @@ import { CLOCK_SKEW_TOLERANCE_MS, } from './session-config'; +/** + * Whether a stored session currently holds one of the reader's device slots: + * not terminated and not yet past its expiry. Expired sessions keep + * `status: 'active'` in storage, so the expiry has to be checked here too. + */ +function isSessionActive(session: Session, now: Date): boolean { + return ( + session.status === 'active' && + session.terminatedAt === null && + new Date(session.expiresAt).getTime() > now.getTime() + ); +} + +/** Tail of the pending createSession chain for each reader, keyed by email. */ +const emailLocks = new Map>(); + +/** + * Run `task` after every earlier task queued for the same reader has settled. + * + * This removes the check-then-write race in createSession within one function + * instance. It cannot coordinate separate instances: that needs conditional + * writes in the storage layer. + */ +async function withEmailLock(email: string, task: () => Promise): Promise { + const key = email.toLowerCase(); + const previous = emailLocks.get(key) ?? Promise.resolve(); + const run = previous.then(task, task); + const tail = run.catch(() => undefined); + emailLocks.set(key, tail); + + try { + return await run; + } finally { + // Drop the entry once nothing newer has queued behind this task. + if (emailLocks.get(key) === tail) { + emailLocks.delete(key); + } + } +} + /** * Create a new session after email verification. * @@ -71,42 +111,48 @@ export async function createSession( // Generate device fingerprint hash const deviceId = generateDeviceFingerprint(deviceFingerprint); - // Check concurrent device limit (T006b) - const activeSessions = await listSessionsByEmail(email); - const activeCount = activeSessions.filter( - (s) => s.status === 'active' && s.terminatedAt === null - ).length; - - if (activeCount >= MAX_CONCURRENT_DEVICES) { - // Device limit exceeded - const error = new Error('Device limit exceeded'); - (error as any).statusCode = 409; - (error as any).errorCode = 'device_limit_exceeded'; - throw error; - } - - // Generate cryptographically secure session token - const sessionId = generateSessionToken(); - - // Create session record with 30-day expiry - const now = new Date(); - const expiresAt = new Date(now.getTime() + SESSION_LIFETIME_DAYS * 24 * 60 * 60 * 1000); - - const session: Session = { - sessionId, - email, - deviceId, - createdAt: now.toISOString(), - expiresAt: expiresAt.toISOString(), - renewedAt: now.toISOString(), - terminatedAt: null, - status: 'active', - }; + // Serialise check-then-write per reader so concurrent verifications in this + // instance cannot all pass the device-limit check before any of them writes. + return withEmailLock(email, async () => { + // Check concurrent device limit (T006b). + // A session on this same device is about to be replaced (same storage key), + // so it does not use up a slot: re-verifying on a known device never adds one. + const now = new Date(); + const activeSessions = await listSessionsByEmail(email); + const activeCount = activeSessions.filter( + (s) => s.deviceId !== deviceId && isSessionActive(s, now) + ).length; + + if (activeCount >= MAX_CONCURRENT_DEVICES) { + // Device limit exceeded + const error = new Error('Device limit exceeded'); + (error as any).statusCode = 409; + (error as any).errorCode = 'device_limit_exceeded'; + throw error; + } + + // Generate cryptographically secure session token + const sessionId = generateSessionToken(); + + // Create session record with 30-day expiry + const expiresAt = new Date(now.getTime() + SESSION_LIFETIME_DAYS * 24 * 60 * 60 * 1000); + + const session: Session = { + sessionId, + email, + deviceId, + createdAt: now.toISOString(), + expiresAt: expiresAt.toISOString(), + renewedAt: now.toISOString(), + terminatedAt: null, + status: 'active', + }; - // Store in Blobs (strong consistency) - await storeSession(session); + // Store in Blobs (strong consistency) + await storeSession(session); - return session; + return session; + }); } /** @@ -214,8 +260,9 @@ export async function validateSession( const now = new Date(); const timeUntilExpiry = expiresAt.getTime() - now.getTime(); - if (timeUntilExpiry < -CLOCK_SKEW_TOLERANCE_MS) { - // Session expired (beyond clock skew tolerance) + if (timeUntilExpiry <= -CLOCK_SKEW_TOLERANCE_MS) { + // Session expired: the tolerance window is half-open, so a session that is + // exactly CLOCK_SKEW_TOLERANCE_MS past expiry is already rejected. return { isValid: false, reason: 'expired_session', @@ -288,11 +335,15 @@ export async function renewSession(email: string, deviceId: string): Promise { const sessions = await listSessionsByEmail(email); - return sessions.filter((s) => s.status === 'active' && s.terminatedAt === null).length; + const now = new Date(); + return sessions.filter((s) => isSessionActive(s, now)).length; } /** diff --git a/netlify/lib/reader-access/store.ts b/netlify/lib/reader-access/store.ts index 47c4012c..39b552d4 100644 --- a/netlify/lib/reader-access/store.ts +++ b/netlify/lib/reader-access/store.ts @@ -162,8 +162,9 @@ export async function deleteSession(email: string, deviceId: string): Promise { // Build prefix for all sessions for this email const prefix = buildSessionKey(email, ''); - // List all keys starting with prefix - // Note: This assumes Blobs supports list() with prefix filtering - // If not available, we may need to store a separate session index - const keys = await (store as any).list?.({ prefix }); - - if (!keys) { - // Fallback: return empty array if list() not available - return []; - } + const { blobs } = await store.list({ prefix }); + const keys = blobs.map((blob) => blob.key); // Fetch each session in parallel const sessions = await Promise.all( diff --git a/tests/helpers/in-memory-blob-store.ts b/tests/helpers/in-memory-blob-store.ts new file mode 100644 index 00000000..2970b49d --- /dev/null +++ b/tests/helpers/in-memory-blob-store.ts @@ -0,0 +1,48 @@ +/** + * In-memory stand-in for `netlify/lib/blobs` in Vitest suites. + * + * It mirrors the `@netlify/blobs` behaviour the session layer depends on: + * `list({ prefix })` filters keys by prefix and resolves to + * `{ blobs: [{ key, etag }], directories }`, not to a bare array of keys. + * + * Usage (vi.mock factories are hoisted, so import the helper inside them): + * + * vi.mock('../../netlify/lib/blobs', async () => + * (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() + * ); + * + * Call `resetInMemoryBlobStore()` in `beforeEach` to isolate tests. + */ + +import type { BlobListResult, BlobStore } from '../../netlify/lib/blobs'; + +const entries = new Map(); + +const store: BlobStore = { + async get(key) { + return entries.has(key) ? (entries.get(key) as string) : null; + }, + async set(key, value) { + entries.set(key, value); + }, + async delete(key) { + entries.delete(key); + }, + async list(options = {}): Promise { + const prefix = options.prefix ?? ''; + const blobs = Array.from(entries.keys()) + .filter((key) => key.startsWith(prefix)) + .map((key) => ({ key, etag: `"${key.length}-${entries.get(key)?.length ?? 0}"` })); + return { blobs, directories: [] }; + }, +}; + +/** Remove every entry from the shared in-memory store. */ +export function resetInMemoryBlobStore(): void { + entries.clear(); +} + +/** Module shape matching `netlify/lib/blobs`, for use as a vi.mock factory result. */ +export function inMemoryBlobsModule(): { getStore: () => BlobStore } { + return { getStore: () => store }; +} diff --git a/tests/performance/session-latency.test.ts b/tests/performance/session-latency.test.ts index e54f9dad..2286ccd9 100644 --- a/tests/performance/session-latency.test.ts +++ b/tests/performance/session-latency.test.ts @@ -10,23 +10,16 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, validateSession, renewSession, terminateSession } from '../../netlify/lib/reader-access/session-service'; import { PERFORMANCE_TARGETS, } from '../../netlify/lib/reader-access/session-config'; -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Performance Profiling - T113', () => { const baseEmail = `perf-test-${Date.now()}`; @@ -39,6 +32,7 @@ describe('Session Performance Profiling - T113', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('Session creation latency', () => { diff --git a/tests/reader-access/device-limit-integration.test.ts b/tests/reader-access/device-limit-integration.test.ts index dc5e1cc9..040a44a2 100644 --- a/tests/reader-access/device-limit-integration.test.ts +++ b/tests/reader-access/device-limit-integration.test.ts @@ -4,21 +4,12 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; -// Mock Netlify environment -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: ({ prefix }: { prefix: string }) => - Promise.resolve(Array.from(store.keys()).filter((k) => k.startsWith(prefix))), - store, // Export for test access - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Device Limit Integration Tests - T043 & T044', () => { const testEmail = 'reader@example.com'; @@ -26,13 +17,7 @@ describe('Device Limit Integration Tests - T043 & T044', () => { beforeEach(async () => { vi.clearAllMocks(); - - // Clear mock store for clean test state - const { getStore } = await import('../../netlify/lib/blobs'); - const store = getStore(); - if (store && (store as any).store) { - (store as any).store.clear(); - } + resetInMemoryBlobStore(); }); describe('T043: Device limit enforcement workflow', () => { diff --git a/tests/reader-access/device-limit.test.ts b/tests/reader-access/device-limit.test.ts index c2013911..ec5edaac 100644 --- a/tests/reader-access/device-limit.test.ts +++ b/tests/reader-access/device-limit.test.ts @@ -4,21 +4,12 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; -// Mock Netlify environment -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: ({ prefix }: { prefix: string }) => - Promise.resolve(Array.from(store.keys()).filter((k) => k.startsWith(prefix))), - store, // Export for test access - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Device Limit Enforcement - T041 & T042', () => { const testEmail = 'reader@example.com'; @@ -26,13 +17,7 @@ describe('Device Limit Enforcement - T041 & T042', () => { beforeEach(async () => { vi.clearAllMocks(); - - // Clear mock store for clean test state - const { getStore } = await import('../../netlify/lib/blobs'); - const store = getStore(); - if (store && (store as any).store) { - (store as any).store.clear(); - } + resetInMemoryBlobStore(); }); describe('T041: Device count query', () => { diff --git a/tests/reader-access/session-audit.test.ts b/tests/reader-access/session-audit.test.ts index d57ce788..5dab8d4e 100644 --- a/tests/reader-access/session-audit.test.ts +++ b/tests/reader-access/session-audit.test.ts @@ -6,20 +6,12 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; -// Mock Netlify environment -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, // Export for test access - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Audit Trail - T034-T035', () => { const testEmail = 'reader@example.com'; @@ -28,6 +20,8 @@ describe('Session Audit Trail - T034-T035', () => { const testIpAddress = '192.168.1.1'; beforeEach(() => { + + resetInMemoryBlobStore(); vi.clearAllMocks(); }); @@ -213,24 +207,27 @@ describe('Session Audit Trail - T034-T035', () => { // Create session const created = await createSession(testEmail, testCode, fingerprint); - const store = getStore().store; - const keyAfterCreate = Array.from(store.keys())[0]; + const store = getStore(); + const { blobs } = await store.list({ prefix: 'session:' }); + expect(blobs).toHaveLength(1); + const keyAfterCreate = blobs[0].key; + const readStored = async () => JSON.parse((await store.get(keyAfterCreate))!); // Verify session stored with timestamps - const storedAfterCreate = JSON.parse(store.get(keyAfterCreate)!); + const storedAfterCreate = await readStored(); expect(storedAfterCreate.createdAt).toBe(created.createdAt); expect(storedAfterCreate.renewedAt).toBe(created.renewedAt); expect(storedAfterCreate.terminatedAt).toBeNull(); // Renew and verify storage updated const renewed = await renewSession(testEmail, created.deviceId); - const storedAfterRenewal = JSON.parse(store.get(keyAfterCreate)!); + const storedAfterRenewal = await readStored(); expect(storedAfterRenewal.renewedAt).toBe(renewed.renewedAt); expect(storedAfterRenewal.terminatedAt).toBeNull(); // Terminate and verify storage updated await terminateSession(testEmail, created.deviceId); - const storedAfterTermination = JSON.parse(store.get(keyAfterCreate)!); + const storedAfterTermination = await readStored(); expect(storedAfterTermination.terminatedAt).toBeTruthy(); expect(storedAfterTermination.status).toBe('terminated'); }); diff --git a/tests/reader-access/session-renewal-integration.test.ts b/tests/reader-access/session-renewal-integration.test.ts index 59aea10f..d062a3a2 100644 --- a/tests/reader-access/session-renewal-integration.test.ts +++ b/tests/reader-access/session-renewal-integration.test.ts @@ -7,24 +7,20 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, validateSession, renewSession, getSessionProperties } from '../../netlify/lib/reader-access/session-service'; import { updateSession } from '../../netlify/lib/reader-access/store'; -// Mock Blobs store -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, // Export for test access - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('E2E: Seamless Session Renewal Over 25+ Simulated Days - T026', () => { + beforeEach(() => { + resetInMemoryBlobStore(); + }); + const testEmail = 'reader@example.com'; const testFingerprint = { userAgent: 'Mozilla/5.0...', diff --git a/tests/reader-access/session-renewal.test.ts b/tests/reader-access/session-renewal.test.ts index 3d3542ac..d7f5a77c 100644 --- a/tests/reader-access/session-renewal.test.ts +++ b/tests/reader-access/session-renewal.test.ts @@ -11,6 +11,7 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, renewSession, @@ -25,19 +26,10 @@ import { } from '../../netlify/lib/reader-access/session-config'; import type { Session } from '../../netlify/lib/reader-access/session'; -// Mock Blobs store -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, // Export for test access - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Renewal - T021-T025', () => { const testEmail = 'reader@example.com'; @@ -48,6 +40,8 @@ describe('Session Renewal - T021-T025', () => { }; beforeEach(() => { + + resetInMemoryBlobStore(); vi.clearAllMocks(); }); diff --git a/tests/reader-access/session-timestamps.test.ts b/tests/reader-access/session-timestamps.test.ts index c88af4fd..c1cdedec 100644 --- a/tests/reader-access/session-timestamps.test.ts +++ b/tests/reader-access/session-timestamps.test.ts @@ -6,20 +6,12 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; -// Mock Netlify environment -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, // Export for test access - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Timestamps - T031-T033', () => { const testEmail = 'reader@example.com'; @@ -28,6 +20,8 @@ describe('Session Timestamps - T031-T033', () => { const testIpAddress = '192.168.1.1'; beforeEach(() => { + + resetInMemoryBlobStore(); vi.clearAllMocks(); }); diff --git a/tests/session/device-limit-tests.test.ts b/tests/session/device-limit-tests.test.ts index a6c70b9f..031102ae 100644 --- a/tests/session/device-limit-tests.test.ts +++ b/tests/session/device-limit-tests.test.ts @@ -6,22 +6,15 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, getActiveSessionCount, terminateSession } from '../../netlify/lib/reader-access/session-service'; -import { listSessionsByEmail } from '../../netlify/lib/reader-access/store'; +import { listSessionsByEmail, updateSession } from '../../netlify/lib/reader-access/store'; import { MAX_CONCURRENT_DEVICES } from '../../netlify/lib/reader-access/session-config'; -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Device Limit Enforcement - T099-T102 (US4)', () => { const testEmailBase = `reader-device-limit-${Date.now()}`; @@ -29,6 +22,7 @@ describe('Device Limit Enforcement - T099-T102 (US4)', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('T099: Device counting', () => { @@ -117,9 +111,9 @@ describe('Device Limit Enforcement - T099-T102 (US4)', () => { } // Next attempt should fail - expect(async () => { - await createSession(testEmail, testCode, devices[MAX_CONCURRENT_DEVICES]); - }).rejects.toThrow(); + await expect( + createSession(testEmail, testCode, devices[MAX_CONCURRENT_DEVICES]) + ).rejects.toThrow('Device limit exceeded'); }); it('should return 409 Conflict when limit exceeded', async () => { @@ -242,6 +236,47 @@ describe('Device Limit Enforcement - T099-T102 (US4)', () => { }); }); + describe('Re-verification and expiry', () => { + it('should allow re-verifying on a device that already holds a slot at the limit', async () => { + const testEmail = `${testEmailBase}-reverify`; + const device1 = { userAgent: 'Device1', ipAddress: '192.168.1.1', timezone: 'UTC' }; + const device2 = { userAgent: 'Device2', ipAddress: '192.168.1.2', timezone: 'UTC' }; + + const first = await createSession(testEmail, testCode, device1); + await createSession(testEmail, testCode, device2); + + // Same device again (e.g. cookie cleared): replaces its own session, adds no device + const again = await createSession(testEmail, testCode, device1); + + expect(again.deviceId).toBe(first.deviceId); + expect(again.sessionId).not.toBe(first.sessionId); + expect(await getActiveSessionCount(testEmail)).toBe(MAX_CONCURRENT_DEVICES); + }); + + it('should not count expired sessions against the device limit', async () => { + const testEmail = `${testEmailBase}-expired-slot`; + const devices = Array.from({ length: MAX_CONCURRENT_DEVICES + 1 }, (_, i) => ({ + userAgent: `Device${i + 1}`, + ipAddress: `192.168.1.${i + 1}`, + timezone: 'UTC', + })); + + const sessions = []; + for (let i = 0; i < MAX_CONCURRENT_DEVICES; i++) { + sessions.push(await createSession(testEmail, testCode, devices[i])); + } + + // Expiry leaves status 'active' in storage; it must still free the slot + await updateSession(testEmail, sessions[0].deviceId, { + expiresAt: new Date(Date.now() - 60_000).toISOString(), + }); + + expect(await getActiveSessionCount(testEmail)).toBe(MAX_CONCURRENT_DEVICES - 1); + const newSession = await createSession(testEmail, testCode, devices[MAX_CONCURRENT_DEVICES]); + expect(newSession.sessionId).toBeTruthy(); + }); + }); + describe('Edge cases', () => { it('should handle exact limit boundary', async () => { const testEmail = `${testEmailBase}-boundary`; diff --git a/tests/session/security.test.ts b/tests/session/security.test.ts index 5be366c6..a1b61af0 100644 --- a/tests/session/security.test.ts +++ b/tests/session/security.test.ts @@ -9,6 +9,32 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { constantTimeTokenCompare, isValidSessionToken } from '../../netlify/lib/reader-access/crypto'; import { checkRateLimit, getRateLimitStatus, resetRateLimit, RATE_LIMIT_PRESETS } from '../../netlify/lib/reader-access/rate-limiter'; +/** + * Median time (ns) of one call for each function. JIT warm-up runs first, each + * sample times a batch of calls, and samples alternate between the functions, + * so timer resolution, GC pauses and bursts of load from parallel test workers + * affect every function equally instead of skewing one of them. + */ +function medianCallTimesNs(fns: Array<() => unknown>, samples = 200, batch = 50): number[] { + for (const fn of fns) { + for (let i = 0; i < samples * batch; i++) fn(); + } + + const timings: number[][] = fns.map(() => []); + for (let i = 0; i < samples; i++) { + fns.forEach((fn, index) => { + const start = process.hrtime.bigint(); + for (let j = 0; j < batch; j++) fn(); + timings[index].push(Number(process.hrtime.bigint() - start) / batch); + }); + } + + return timings.map((series) => { + series.sort((a, b) => a - b); + return series[Math.floor(series.length / 2)]; + }); +} + describe('Session Security - Constant-Time Comparison', () => { describe('constantTimeTokenCompare', () => { it('should return true for matching tokens', () => { @@ -29,7 +55,9 @@ describe('Session Security - Constant-Time Comparison', () => { }); it('should handle empty string tokens', () => { - expect(constantTimeTokenCompare('', '')).toBe(true); + // An empty token is never a valid credential, so two empty values must + // not "match" (a blank stored token would otherwise accept a blank cookie). + expect(constantTimeTokenCompare('', '')).toBe(false); expect(constantTimeTokenCompare('', 'token')).toBe(false); expect(constantTimeTokenCompare('token', '')).toBe(false); }); @@ -37,49 +65,17 @@ describe('Session Security - Constant-Time Comparison', () => { it('should use constant-time comparison (no timing leaks)', () => { // Measure comparison time for correct vs incorrect tokens const correctToken = 'a'.repeat(43); // base64url token length - const wrongShorter = 'b'.repeat(10); - const wrongLonger = 'c'.repeat(100); const wrongSameLength = 'x'.repeat(43); - // Run multiple times to get statistical average - const iterations = 1000; - const timings: Record = { - correct: [], - wrongShorter: [], - wrongLonger: [], - wrongSameLength: [], - }; - - for (let i = 0; i < iterations; i++) { - const start1 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, correctToken); - const time1 = Number(process.hrtime.bigint() - start1); - timings.correct.push(time1); - - const start2 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, wrongShorter); - const time2 = Number(process.hrtime.bigint() - start2); - timings.wrongShorter.push(time2); - - const start3 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, wrongLonger); - const time3 = Number(process.hrtime.bigint() - start3); - timings.wrongLonger.push(time3); - - const start4 = process.hrtime.bigint(); - constantTimeTokenCompare(correctToken, wrongSameLength); - const time4 = Number(process.hrtime.bigint() - start4); - timings.wrongSameLength.push(time4); - } - - // Calculate averages - const avgCorrect = timings.correct.reduce((a, b) => a + b, 0) / iterations; - const avgWrongSameLength = - timings.wrongSameLength.reduce((a, b) => a + b, 0) / iterations; + // Median per-call time after warm-up (see medianCallTimesNs) + const [medianCorrect, medianWrongSameLength] = medianCallTimesNs([ + () => constantTimeTokenCompare(correctToken, correctToken), + () => constantTimeTokenCompare(correctToken, wrongSameLength), + ]); // For same-length tokens, timing should be nearly identical (constant-time) - const timingRatio = Math.max(avgCorrect, avgWrongSameLength) / - Math.min(avgCorrect, avgWrongSameLength); + const timingRatio = Math.max(medianCorrect, medianWrongSameLength) / + Math.min(medianCorrect, medianWrongSameLength); // Allow up to 1.5x variance for constant-time comparison expect(timingRatio).toBeLessThan(1.5); @@ -88,7 +84,8 @@ describe('Session Security - Constant-Time Comparison', () => { describe('isValidSessionToken', () => { it('should validate correct token format', () => { - const validToken = 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoxMjM0NTY3ODk='; // 48 chars base64 + // Same shape generateSessionToken() emits: 32 random bytes, base64url, no '=' padding + const validToken = 'q2Zf8Jt0vXyLr5N1sA9bKc3WmE7uHdP4oGiTzQx6YlU'; expect(isValidSessionToken(validToken)).toBe(true); }); @@ -127,8 +124,12 @@ describe('Session Security - Constant-Time Comparison', () => { describe('Session Security - Rate Limiting', () => { beforeEach(() => { - // Reset rate limit store before each test + // Reset the module-level rate limit store: every test reuses these identifiers vi.clearAllMocks(); + const { keyPrefix } = RATE_LIMIT_PRESETS.SESSION_CREATION; + for (const id of ['test@example.com', 'user1@example.com', 'user2@example.com']) { + resetRateLimit(id, keyPrefix); + } }); describe('checkRateLimit', () => { @@ -278,16 +279,15 @@ describe('Session Security - Timing Attack Resistance', () => { tokens.push('a'.repeat(40 + i)); // Varying lengths } - const timings: number[] = []; - - tokens.forEach(token => { - const start = process.hrtime.bigint(); - // Try to compare with another token of same length - const reference = 'x'.repeat(token.length); - constantTimeTokenCompare(token, reference); - const duration = Number(process.hrtime.bigint() - start); - timings.push(duration); - }); + // Median per-call time for each length (see medianCallTimesNs) + const timings: number[] = medianCallTimesNs( + tokens.map((token) => { + const reference = 'x'.repeat(token.length); + return () => constantTimeTokenCompare(token, reference); + }), + 50, + 50 + ); // Check variance in timing (should be low for constant-time) const avg = timings.reduce((a, b) => a + b, 0) / timings.length; diff --git a/tests/session/session-create.test.ts b/tests/session/session-create.test.ts index b5a2f5ba..1665b94d 100644 --- a/tests/session/session-create.test.ts +++ b/tests/session/session-create.test.ts @@ -6,23 +6,15 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, getActiveSessionCount } from '../../netlify/lib/reader-access/session-service'; import { storeSession, getSession, listSessionsByEmail } from '../../netlify/lib/reader-access/store'; import { SESSION_LIFETIME_DAYS } from '../../netlify/lib/reader-access/session-config'; -// Mock Netlify Blobs -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Creation - T078 (US1)', () => { const testEmail = `reader-create-${Date.now()}@example.com`; @@ -35,6 +27,7 @@ describe('Session Creation - T078 (US1)', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('Session creation basics', () => { diff --git a/tests/session/session-expiry.test.ts b/tests/session/session-expiry.test.ts index 51cff7cc..1f42653a 100644 --- a/tests/session/session-expiry.test.ts +++ b/tests/session/session-expiry.test.ts @@ -6,21 +6,14 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, validateSession, renewSession } from '../../netlify/lib/reader-access/session-service'; import { SESSION_LIFETIME_DAYS, CLOCK_SKEW_TOLERANCE_MS } from '../../netlify/lib/reader-access/session-config'; -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Expiry - T083 (US2)', () => { const testEmail = `reader-expiry-${Date.now()}@example.com`; @@ -33,6 +26,7 @@ describe('Session Expiry - T083 (US2)', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('Expiry calculation precision', () => { @@ -196,9 +190,11 @@ describe('Session Expiry - T083 (US2)', () => { const renewed = await renewSession(testEmail, current.deviceId); - const createdTime = new Date(renewed.createdAt).getTime(); + // Rolling window: each renewal sets expiresAt = renewedAt + 30 days. + // (Measuring from createdAt grows by the elapsed time on every renewal.) + const renewedTime = new Date(renewed.renewedAt).getTime(); const expiresTime = new Date(renewed.expiresAt).getTime(); - const windowSize = expiresTime - createdTime; + const windowSize = expiresTime - renewedTime; // Should still be ~30 days expect(Math.abs(windowSize - thirtyDaysInMs)).toBeLessThan(2000); diff --git a/tests/session/session-logout.test.ts b/tests/session/session-logout.test.ts index 09d13df0..9ba82060 100644 --- a/tests/session/session-logout.test.ts +++ b/tests/session/session-logout.test.ts @@ -6,21 +6,14 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, terminateSession, validateSession } from '../../netlify/lib/reader-access/session-service'; import { getSession } from '../../netlify/lib/reader-access/store'; -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Logout - T103 (US5)', () => { const testEmail = `reader-logout-${Date.now()}@example.com`; @@ -33,6 +26,7 @@ describe('Session Logout - T103 (US5)', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('Basic termination', () => { @@ -168,9 +162,9 @@ describe('Session Logout - T103 (US5)', () => { describe('Error cases', () => { it('should throw when terminating non-existent session', async () => { - expect(async () => { - await terminateSession('nonexistent@example.com', 'nonexistent-device'); - }).rejects.toThrow(); + await expect( + terminateSession('nonexistent@example.com', 'nonexistent-device') + ).rejects.toThrow('Session not found'); }); }); diff --git a/tests/session/session-persistence.test.ts b/tests/session/session-persistence.test.ts index 21c40902..29c4748b 100644 --- a/tests/session/session-persistence.test.ts +++ b/tests/session/session-persistence.test.ts @@ -6,21 +6,14 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, validateSession } from '../../netlify/lib/reader-access/session-service'; import { getSession, updateSession } from '../../netlify/lib/reader-access/store'; -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Persistence - T079 (US1)', () => { const testEmail = `reader-persist-${Date.now()}@example.com`; @@ -33,6 +26,7 @@ describe('Session Persistence - T079 (US1)', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('Session retrieval', () => { @@ -185,9 +179,9 @@ describe('Session Persistence - T079 (US1)', () => { }); it('should not throw on missing session', async () => { - expect(async () => { - await getSession('nonexistent@example.com', 'nonexistent-device'); - }).not.toThrow(); + await expect( + getSession('nonexistent@example.com', 'nonexistent-device') + ).resolves.toBeNull(); }); }); }); diff --git a/tests/session/session-renewal.test.ts b/tests/session/session-renewal.test.ts index f56ed46d..f283a2ee 100644 --- a/tests/session/session-renewal.test.ts +++ b/tests/session/session-renewal.test.ts @@ -6,21 +6,14 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; import { createSession, renewSession } from '../../netlify/lib/reader-access/session-service'; import { SESSION_LIFETIME_DAYS } from '../../netlify/lib/reader-access/session-config'; -vi.mock('../../netlify/lib/blobs', () => { - const store = new Map(); - return { - getStore: () => ({ - get: (key: string) => Promise.resolve(store.get(key) || null), - set: (key: string, value: string) => Promise.resolve(store.set(key, value)), - delete: (key: string) => Promise.resolve(store.delete(key)), - list: () => Promise.resolve(Array.from(store.keys())), - store, - }), - }; -}); +// In-memory Netlify Blobs that honours list({ prefix }) like the real store. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Renewal - T082 (US2)', () => { const testEmail = `reader-renew-${Date.now()}@example.com`; @@ -33,6 +26,7 @@ describe('Session Renewal - T082 (US2)', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); describe('Basic renewal', () => { @@ -74,6 +68,10 @@ describe('Session Renewal - T082 (US2)', () => { it('should change expiresAt timestamp from original', async () => { const created = await createSession(testEmail, testCode, fingerprint); + + // Let the clock move so the renewed expiry can differ at ms resolution + await new Promise((resolve) => setTimeout(resolve, 10)); + const renewed = await renewSession(testEmail, created.deviceId); expect(renewed.expiresAt).not.toBe(created.expiresAt); @@ -145,9 +143,9 @@ describe('Session Renewal - T082 (US2)', () => { describe('Error cases', () => { it('should throw when renewing non-existent session', async () => { - expect(async () => { - await renewSession('nonexistent@example.com', 'nonexistent-device'); - }).rejects.toThrow(); + await expect( + renewSession('nonexistent@example.com', 'nonexistent-device') + ).rejects.toThrow('Session not found'); }); it('should throw when renewing terminated session', async () => { @@ -157,9 +155,9 @@ describe('Session Renewal - T082 (US2)', () => { const created = await createSession(testEmail, testCode, fingerprint); await terminateSession(testEmail, created.deviceId); - expect(async () => { - await renewSession(testEmail, created.deviceId); - }).rejects.toThrow(); + await expect(renewSession(testEmail, created.deviceId)).rejects.toThrow( + 'Cannot renew terminated session' + ); }); }); diff --git a/tests/session/session.test.ts b/tests/session/session.test.ts index db29f81c..abd59b46 100644 --- a/tests/session/session.test.ts +++ b/tests/session/session.test.ts @@ -16,10 +16,19 @@ import { } from '../../netlify/lib/reader-access/session-service'; import { FingerprintInput } from '../../netlify/lib/reader-access/session'; import { generateSessionToken } from '../../netlify/lib/reader-access/crypto'; -import { SESSION_LIFETIME_DAYS } from '../../netlify/lib/reader-access/session-config'; - -// Mock store operations -vi.mock('../../netlify/lib/reader-access/store'); +import { + SESSION_LIFETIME_DAYS, + CLOCK_SKEW_TOLERANCE_MS, +} from '../../netlify/lib/reader-access/session-config'; +import { updateSession } from '../../netlify/lib/reader-access/store'; +import { resetInMemoryBlobStore } from '../helpers/in-memory-blob-store'; + +// Exercise the real store against an in-memory Netlify Blobs. Auto-mocking +// the store module made every function return undefined, so createSession +// called `.filter` on undefined. +vi.mock('../../netlify/lib/blobs', async () => + (await import('../helpers/in-memory-blob-store')).inMemoryBlobsModule() +); describe('Session Service - Core Operations', () => { const testEmail = 'reader@example.com'; @@ -32,6 +41,7 @@ describe('Session Service - Core Operations', () => { beforeEach(() => { vi.clearAllMocks(); + resetInMemoryBlobStore(); }); afterEach(() => { @@ -112,18 +122,23 @@ describe('Session Service - Core Operations', () => { const correctToken = testSession.sessionId; const wrongToken = 'wrong' + 'x'.repeat(correctToken.length - 5); - const start1 = process.hrtime.bigint(); - await validateSession(correctToken, testEmail, testSession.deviceId); - const end1 = process.hrtime.bigint(); - - const start2 = process.hrtime.bigint(); - await validateSession(wrongToken, testEmail, testSession.deviceId); - const end2 = process.hrtime.bigint(); + // Median of many runs after warm-up: a single cold call mostly measures + // JIT compilation and timer noise rather than the comparison itself. + const medianValidationNs = async (token: string): Promise => { + const timings: number[] = []; + for (let i = 0; i < 250; i++) { + const start = process.hrtime.bigint(); + await validateSession(token, testEmail, testSession.deviceId); + if (i >= 50) timings.push(Number(process.hrtime.bigint() - start)); + } + timings.sort((a, b) => a - b); + return timings[Math.floor(timings.length / 2)]; + }; // Timing should be similar (constant-time) // Note: This is a statistical test; exact timing varies by CPU - const timing1 = Number(end1 - start1); - const timing2 = Number(end2 - start2); + const timing1 = await medianValidationNs(correctToken); + const timing2 = await medianValidationNs(wrongToken); const timingRatio = Math.max(timing1, timing2) / Math.min(timing1, timing2); // Allow up to 2x variance (should be much closer in constant-time impl) @@ -145,14 +160,13 @@ describe('Session Service - Core Operations', () => { }); it('should reject expired session', async () => { - // Create session with past expiry - const expiredSession = { - ...testSession, - expiresAt: new Date(Date.now() - 1000).toISOString(), - }; + // Persist a past expiry (beyond clock skew tolerance) so validation sees it + await updateSession(testEmail, testSession.deviceId, { + expiresAt: new Date(Date.now() - CLOCK_SKEW_TOLERANCE_MS - 1000).toISOString(), + }); const result = await validateSession( - expiredSession.sessionId, + testSession.sessionId, testEmail, testSession.deviceId ); @@ -188,6 +202,11 @@ describe('Session Service - Core Operations', () => { }); it('should coalesce rapid renewals (prevent thundering herd)', async () => { + // Creation does not open a coalescing window, and a renewal in the same + // millisecond as creation is indistinguishable from none, so let the + // clock move before the first renewal. + await new Promise((resolve) => setTimeout(resolve, 10)); + // First renewal const first = await renewSession(testEmail, testSession.deviceId); From cf9ea7d77bb9c1c666ad4d4740ce79dd76a82770 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 11:48:09 +0000 Subject: [PATCH 2/2] docs(changelog): record reader session Vitest fixes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CADHZhriKj5xS1hQnwWGg4 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 334268ab..41da55fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **Specification 006 reader session suites under Vitest** — `listSessionsByEmail` now reads `@netlify/blobs` `list()` results as `{ blobs: [{ key }] }` instead of a bare key array, which made every session creation fail in production. The device limit ignores the session being replaced on the same device and expired sessions, and concurrent creation is serialised per email within an instance. Creation no longer opens the renewal coalescing window, and the clock-skew boundary is half-open. Session test mocks now share an in-memory Blobs helper that honours `prefix`. - **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