Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **Reader access: gaps left after the US1 session work** — Verification codes are now consumed atomically: a `code-consumed:` marker written with `onlyIfNew` lets exactly one of several concurrent submissions of a code create a session (spec 005 RA-002), replacing delete-first; `@netlify/blobs` 6 → 11 for conditional writes. The Mailgun client now passes `username: 'api'`, without which sends fail authentication. `reader-retention` used named imports `@netlify/blobs` does not export and had no schedule; it now uses the store API and runs `@daily`, and its skipped test is enabled. `/api/reader/chapters/:chapterId` was missing from `public/_redirects`, which Netlify applies before `netlify.toml`, so chapter requests returned `index.html`. Added a test that bundles every Netlify function and checks every redirect target exists.
- **Reader access: re-verifying on a registered device no longer hits the device limit** — `createSession` counted the reader's existing session on the same device towards `MAX_CONCURRENT_DEVICES`. A reader already signed in on two devices therefore got `409 device_limit_exceeded` when re-verifying on one of them, even though that session is replaced in place under the same storage key. The same-device session is now left out of the count. A regression test is in `tests/session/device-limit-tests.test.ts`. (The wider session test-suite repair landed separately in PR #653.)
- **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.
Expand Down
32 changes: 16 additions & 16 deletions netlify/__tests__/reader-retention.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
const mockBlobStore = new Map<string, string>();
const mockDeletedKeys = new Set<string>();

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();
Expand Down
13 changes: 9 additions & 4 deletions netlify/functions/reader-retention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -55,22 +58,24 @@ export default async function handler(req: Request): Promise<Response> {
// 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);
const deleteAfter = new Date(record.deleteAfter);

// 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);
}
Expand Down
12 changes: 11 additions & 1 deletion netlify/lib/blobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,18 @@

import { getStore as getNetlifyStore } from '@netlify/blobs';

/** Result of a write; `modified` is false when a condition prevented it. */
export interface BlobWriteResult {
modified: boolean;
etag?: string;
}

export interface BlobStore {
set(key: string, value: string): Promise<void>;
/**
* With `onlyIfNew`, Netlify Blobs applies the write only when the key does
* not exist yet, and reports `modified: false` otherwise.
*/
set(key: string, value: string, options?: { onlyIfNew?: boolean }): Promise<BlobWriteResult | void>;
get(key: string): Promise<string | null>;
delete(key: string): Promise<void>;
list?(options?: { prefix?: string }): Promise<string[]>;
Expand Down
5 changes: 3 additions & 2 deletions netlify/lib/reader-access/mailer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ export interface MailerConfig {
const DEFAULT_FROM = 'noreply@thisonetimeonacidcom.com';

export class MailgunMailer {
private mg: ReturnType<typeof Mailgun>;
private mg: ReturnType<InstanceType<typeof Mailgun>['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;
}
Expand Down
12 changes: 7 additions & 5 deletions netlify/lib/reader-access/session-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
deleteSession,
listSessionsByEmail,
getCode,
deleteCode,
consumeCode,
incrementCodeAttempts,
} from './store';
import { verifyCode, isCodeExpired, isCodeLimited } from './codes';
Expand Down Expand Up @@ -535,9 +535,9 @@ export class SessionCreationError extends Error {
*
* 1. Look up the stored code; missing, expired or locked → 401
* 2. Compare the code hash; a wrong code records an attempt → 401
* 3. Consume the code before any session is written, so a replayed
* request finds no code (Blobs has no compare-and-swap, so this is
* delete-first rather than a true atomic consume)
* 3. Consume the code atomically before any session is written: a
* conditional (onlyIfNew) marker write lets exactly one of several
* concurrent requests for the same code through; the rest get 401
* 4. If this device already has a session, rotate it: new token, old
* token index removed, fresh 30-day window (no device slot consumed)
* 5. Otherwise create a new session, enforcing the device limit (409)
Expand Down Expand Up @@ -565,7 +565,9 @@ export async function createSessionFromVerification(
throw new SessionCreationError('verification_failed', 401);
}

await deleteCode(normalisedEmail);
if (!(await consumeCode(normalisedEmail, stored.codeHash))) {
throw new SessionCreationError('verification_failed', 401);
}

const deviceId = generateDeviceFingerprint(fingerprint);
const existing = await getSession(normalisedEmail, deviceId);
Expand Down
28 changes: 28 additions & 0 deletions netlify/lib/reader-access/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,34 @@ export async function deleteCode(email: string): Promise<void> {
await getStore().delete(buildCodeKey(email));
}

/**
* Atomically consume a verified code (spec 005 RA-002: "consume at most
* once, atomically").
*
* Writes a marker keyed by a hash of the code's salted hash, which is unique
* per issued code, using `onlyIfNew`. Netlify Blobs applies that condition
* server-side, so when two requests redeem the same code at once exactly one
* write reports `modified: true`. The code record is then deleted.
*
* @returns true for the single caller that consumed the code, false if
* another request already did
*/
export async function consumeCode(email: string, codeHash: string): Promise<boolean> {
const key = `code-consumed:${hashSha256(codeHash)}`;
const result = await getStore().set(
key,
JSON.stringify({ consumedAt: new Date().toISOString() }),
{ onlyIfNew: true }
);
// @netlify/blobs 11 always returns a WriteResult; a bare mock may not.
if (result && result.modified === false) {
return false;
}
// Best effort: the marker already blocks reuse if this delete fails.
await deleteCode(email).catch(() => undefined);
return true;
}

// ---------------------------------------------------------------------------
// Recovery attempts (restored from spec 005, RA-T048)
// ---------------------------------------------------------------------------
Expand Down
Loading
Loading