fix(user-flow): persona-audit fixes — ban replay, locked-upload data loss, host UX, admin session

Follows the perf + security + user-flow work with a role/persona audit (guest, host,
admin, projector) and fixes across three review rounds. Highlights:

HIGH
- Ban now replays on reconnect. A ban isn't a soft-delete, and the `user-hidden` SSE has
  no replay, so a client that missed it (esp. the unattended diashow) kept cycling a
  banned user's slides. New `uploads_hidden_at` (migration 013) + `hidden_user_ids` in
  /feed/delta; feed + diashow evict those users. Applied even on a truncated delta.

MEDIUM
- Locked-upload data loss: a photo staged offline during a lock/release was purged as a
  terminal 4xx and lost when the host reopened. New reversible `uploads_locked` error code;
  the queue keeps the blob and auto-resumes on the `event-opened` SSE.
- Reopen after release now warns (ConfirmSheet) that it revokes the published keepsake.
- Host "forgotten-PIN" badge updates live (`pin-reset-requested` was broadcast but never
  in KNOWN_EVENTS / subscribed); host page also refetches on `pin-reset` so a two-host
  race can't hand out a conflicting PIN.
- Ban modal copy fixed (read-only ban, not "session ended"); Degradieren/Sperren/Entsperren
  hidden on peer-host rows for non-admins (they always 403'd).
- Host dashboard shows live keepsake generation progress / ready state + link to /export.
- Admin JWT moved to sessionStorage (§11.1) to bound exposure on shared devices.

Export generation guard (H1 from the prior round, hardened): per-(event,type) `release_seq`
(migration 012) with seq-guarded claim/finalize/mark_failed/update_progress, per-generation
temp/final paths, download follows `file_path`, prune only strictly-older generations.

LOW: diashow coalesces upload-processed (avoids self-rate-limit); event-closed reconciles
galleryReleased; /recover gains a forgot-PIN request + drops a stale cached PIN on 401;
delta `>=` tie-break + 429 retry; misc copy/labels.

Adds e2e: ban-replay, upload-lock-code, and rewrites export-reopen-rerelease with a
data-completeness test. Reconciles USER_JOURNEYS §9/§11.

Verified: cargo build clean, 40 unit tests, svelte-check 0 errors, 33 frontend unit
tests, 155 e2e passing on chromium-desktop.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
fabi
2026-07-13 21:06:28 +02:00
parent 641174717c
commit 36fe59caa5
28 changed files with 1185 additions and 302 deletions

View File

@@ -13,17 +13,24 @@ test.describe('Auth — admin login', () => {
await login.login(ADMIN_PASSWORD);
await page.waitForURL('**/admin', { timeout: 10_000 });
// Admin JWT should now be in localStorage (admin uses the same key, just with role=admin in the payload)
const role = await page.evaluate(() => {
const token = localStorage.getItem('eventsnap_jwt');
if (!token) return null;
try {
return JSON.parse(atob(token.split('.')[1])).role;
} catch {
return null;
}
// The admin JWT lands in sessionStorage (USER_JOURNEYS §11.1) — NOT localStorage — so the
// elevated credential doesn't survive a tab/browser close on a shared "event laptop".
const stores = await page.evaluate(() => {
const decodeRole = (t: string | null) => {
if (!t) return null;
try {
return JSON.parse(atob(t.split('.')[1])).role;
} catch {
return null;
}
};
return {
sessionRole: decodeRole(sessionStorage.getItem('eventsnap_jwt')),
localToken: localStorage.getItem('eventsnap_jwt')
};
});
expect(role).toBe('admin');
expect(stores.sessionRole).toBe('admin');
expect(stores.localToken, 'admin token must not persist in localStorage').toBeNull();
});
test('wrong password → error, no token written', async ({ page }) => {

View File

@@ -0,0 +1,58 @@
/**
* Regression guard — a ban must replay in the reconnect delta so a client that missed the
* ephemeral `user-hidden` SSE (most acutely the unattended diashow projector) still evicts
* the banned user's already-loaded slides instead of cycling them all night.
*
* A ban is NOT a soft-delete (no `upload.deleted_at`), so it never appears in the delta's
* `deleted_ids`. The fix: `uploads_hidden_at` stamps when a user became hidden, and
* `/feed/delta` returns `hidden_user_ids` for users hidden since the client's cursor. The
* client (feed + diashow) evicts all uploads from those users.
*/
import { test, expect } from '../../fixtures/test';
import { seedUpload } from '../../helpers/seed';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
async function feedDelta(jwt: string, since: string): Promise<any> {
const res = await fetch(`${BASE}/api/v1/feed/delta?since=${encodeURIComponent(since)}`, {
headers: { Authorization: `Bearer ${jwt}` },
});
expect(res.status).toBe(200);
return res.json();
}
test.describe('Realtime — ban replays in the reconnect delta (H1 audit fix)', () => {
test('a ban since the cursor is in hidden_user_ids; a ban before it is not', async ({
host,
guest,
api,
}) => {
const g = await guest('BanReplayGuest');
await seedUpload(g.jwt, { caption: 'to be hidden' });
// Cursor BEFORE the ban — this is the "last-seen" point a disconnected client holds.
const before = await feedDelta(host.jwt, '2000-01-01T00:00:00Z');
const cursorBefore: string = before.server_time;
expect(before.hidden_user_ids).not.toContain(g.userId); // not hidden yet
// Ban the guest (read-only ban; content hidden everywhere).
await api.banUser(host.jwt, g.userId);
// A delta from the pre-ban cursor MUST surface the ban so the client can evict.
const afterBan = await feedDelta(host.jwt, cursorBefore);
expect(afterBan.hidden_user_ids, 'ban replayed to a client that missed the live event').toContain(
g.userId
);
// And a delta from a cursor AFTER the ban must NOT re-surface it (the `>= since` filter
// means a client already past the ban isn't told again forever).
const cursorAfter: string = afterBan.server_time;
const afterCursor = await feedDelta(host.jwt, cursorAfter);
expect(afterCursor.hidden_user_ids).not.toContain(g.userId);
// Unban clears the timestamp, so a fresh ban later would replay again.
await api.unbanUser(host.jwt, g.userId);
const afterUnban = await feedDelta(host.jwt, '2000-01-01T00:00:00Z');
expect(afterUnban.hidden_user_ids).not.toContain(g.userId);
});
});

View File

@@ -1,36 +1,37 @@
/**
* Re-review regression guard — Chain #2 ("export corruption on reopen→re-release").
* Regression guard — reopen→re-release export integrity + the stale-keepsake data-loss fix (H1).
*
* Bug that was fixed: `spawn_export_jobs` ran the worker unconditionally and the
* worker wrote a FIXED temp path (`Gallery.zip.tmp` / `viewer_tmp_{event}`).
* The new reopen→re-release flow could therefore spawn a second worker while the
* first was still running — two workers stomping the same temp file → a corrupt
* keepsake ZIP served to guests.
* Two related bugs on this path:
*
* The fix: `claim_job` is an atomic `UPDATE ... WHERE status='pending'`; a worker
* that doesn't win the claim bails without touching the temp file. The re-enqueue
* `ON CONFLICT DO UPDATE ... WHERE status <> 'running'` leaves an in-flight job
* alone. Net: exactly one worker per (event,type).
* (1) Temp-file race: a second worker spawned by a re-release could stomp the first
* worker's FIXED temp path → a corrupt/truncated keepsake ZIP.
*
* This test seeds real uploads, releases, then churns reopen→re-release (stressing
* the claim guard), waits for the export to settle, and asserts the produced ZIP is
* INTACT (passes `unzip -t`) with exactly one entry per upload — plus that no
* export_job row is left stuck `running`. A temp-file race would corrupt/truncate
* the archive or drop entries, failing these assertions.
* (2) Stale keepsake (silent data loss): a worker from the PRIOR release, still streaming a
* snapshot taken BEFORE a reopen, would finish and unconditionally re-flip
* `export_*_ready = TRUE` on an archive that predated the reopen — so uploads added
* during the reopen window were permanently missing from a "ready" keepsake.
*
* Note on scope: a Dockerised export over small fixtures completes in well under a
* second, so this cannot *deterministically* force two workers to overlap in time.
* It stresses the claim/ON-CONFLICT guard under rapid churn and hard-checks archive
* integrity; the atomic single-worker guarantee itself is additionally proven by
* code review + SQL PREPARE. Together they cover the regression.
* The fix: a per-(event,type) generation counter `release_seq`, bumped on every (re)release.
* A worker captures the seq it claimed and writes per-generation temp/final paths
* (`Gallery.<seq>.zip`); its finalize and ready-flag flip are guarded by `release_seq`, so a
* superseded worker discards its output instead of resurrecting a stale keepsake. The
* download follows the current `done` row's `file_path`, never a fixed name.
*
* Coverage:
* - churn integrity: rapid reopen→re-release yields exactly one INTACT ZIP, no stuck jobs.
* - completeness: an upload added during the reopen window IS present in the re-released
* keepsake (the direct data-loss regression).
* - supersession: a re-release SUPERSEDES an in-flight (running) job — it bumps the
* generation and regenerates, rather than leaving the stale worker to finalize.
*/
import { test, expect } from '../../fixtures/test';
import { Client } from 'pg';
import { execFileSync } from 'node:child_process';
import { writeFileSync, mkdtempSync } from 'node:fs';
import { writeFileSync, mkdtempSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { seedUpload } from '../../helpers/seed';
import { uploadRaw } from '../../helpers/upload-client';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
const SLUG = 'e2e-test-event';
@@ -68,9 +69,43 @@ async function mintTicket(jwt: string): Promise<string> {
return (await res.json()).ticket;
}
test.describe('Flow re-review — reopen→re-release export integrity (#2)', () => {
async function waitExportDone(jwt: string) {
await expect
.poll(async () => {
const s = await exportStatus(jwt);
return s.released === true && s.zip?.status === 'done' && s.html?.status === 'done';
}, { timeout: 60_000, intervals: [500] })
.toBe(true);
}
/** Download the current ZIP keepsake and return its (non-directory) entry names. */
async function downloadZipEntries(jwt: string): Promise<string[]> {
const ticket = await mintTicket(jwt);
const res = await fetch(BASE + '/api/v1/export/zip?ticket=' + encodeURIComponent(ticket));
expect(res.status).toBe(200);
const bytes = Buffer.from(await res.arrayBuffer());
expect(bytes.subarray(0, 2).toString('latin1')).toBe('PK'); // ZIP magic — not a stomped file
const dir = mkdtempSync(join(tmpdir(), 'es-zip-'));
const zipPath = join(dir, 'Gallery.zip');
writeFileSync(zipPath, bytes);
execFileSync('unzip', ['-t', zipPath], { stdio: 'pipe' }); // CRC integrity; throws on corruption
return execFileSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' })
.split('\n')
.map((l) => l.trim())
.filter((l) => l.length > 0 && !l.endsWith('/'));
}
async function zipReleaseSeq(): Promise<number> {
const [row] = await pgQuery<{ release_seq: string }>(
`SELECT ej.release_seq FROM export_job ej JOIN event e ON e.id = ej.event_id
WHERE e.slug = '${SLUG}' AND ej.type = 'zip'`
);
return Number(row.release_seq);
}
test.describe('Flow re-review — reopen→re-release export integrity + stale-keepsake (H1)', () => {
// The real export job runs image processing; give it head-room over the tiny fixtures.
test.setTimeout(90_000);
test.setTimeout(120_000);
test('rapid release/reopen/re-release yields exactly one INTACT ZIP and no stuck jobs', async ({
host,
@@ -84,8 +119,6 @@ test.describe('Flow re-review — reopen→re-release export integrity (#2)', ()
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
// Post-release uploads must be rejected (belt-and-suspenders on top of the lock).
const { uploadRaw } = await import('../../helpers/upload-client');
const { readFileSync } = await import('node:fs');
const rejected = await uploadRaw(host.jwt, readFileSync(join(process.cwd(), 'fixtures', 'media', 'sample.jpg')), {
filename: 'late.jpg',
contentType: 'image/jpeg',
@@ -101,16 +134,9 @@ test.describe('Flow re-review — reopen→re-release export integrity (#2)', ()
expect(rel.status).toBe(204);
}
// Wait for the export to settle: both jobs done and the ZIP marked ready.
await expect
.poll(async () => {
const s = await exportStatus(host.jwt);
return s.released === true && s.zip?.status === 'done' && s.html?.status === 'done';
}, { timeout: 60_000, intervals: [500] })
.toBe(true);
await waitExportDone(host.jwt);
// No export_job may be left stuck 'running' (would mean a worker that never
// completed — the failure mode the claim guard exists to avoid).
// No export_job may be left stuck 'running'.
const jobs = await pgQuery<{ type: string; status: string }>(
`SELECT ej.type::text AS type, ej.status::text AS status
FROM export_job ej JOIN event e ON e.id = ej.event_id
@@ -119,80 +145,74 @@ test.describe('Flow re-review — reopen→re-release export integrity (#2)', ()
expect(jobs.length).toBe(2);
for (const j of jobs) expect(j.status, `${j.type} job status`).toBe('done');
// Download the ZIP and prove it is INTACT — a temp-file race would corrupt or
// truncate it. `unzip -t` verifies every entry's CRC; a non-zero exit throws.
const ticket = await mintTicket(host.jwt);
const res = await fetch(BASE + '/api/v1/export/zip?ticket=' + encodeURIComponent(ticket));
expect(res.status).toBe(200);
const bytes = Buffer.from(await res.arrayBuffer());
// ZIP local-file-header magic — a stomped/half-written file fails this immediately.
expect(bytes.subarray(0, 2).toString('latin1')).toBe('PK');
const dir = mkdtempSync(join(tmpdir(), 'es-zip-'));
const zipPath = join(dir, 'Gallery.zip');
writeFileSync(zipPath, bytes);
// Integrity: `unzip -t` exits 0 only if all CRCs check out and the archive is whole.
execFileSync('unzip', ['-t', zipPath], { stdio: 'pipe' });
// Completeness: exactly one entry per seeded upload — no entry lost to a stomped
// temp file, none duplicated by a second worker.
const listing = execFileSync('unzip', ['-Z1', zipPath], { encoding: 'utf8' })
.split('\n')
.map((l) => l.trim())
.filter((l) => l.length > 0 && !l.endsWith('/'));
// Exactly one entry per seeded upload — no entry lost to a stomped temp file, none
// duplicated by a second worker.
const listing = await downloadZipEntries(host.jwt);
expect(listing.length, `zip entries:\n${listing.join('\n')}`).toBe(N_UPLOADS);
});
test('re-release does NOT disturb an in-flight (running) export job — the anti-race guard', async ({
test('an upload added during the reopen window IS present in the re-released keepsake (H1)', async ({
host,
}) => {
// Deterministic proof of the fix, independent of export timing. We simulate a worker
// that is still mid-export by pinning the zip job to `running` with a sentinel
// progress value, then drive reopen→re-release. The fix's
// ON CONFLICT ... DO UPDATE ... WHERE export_job.status <> 'running'
// must leave that row untouched (and the freshly-spawned worker's
// claim_job: UPDATE ... WHERE status = 'pending'
// finds nothing to claim, so it bails without racing the temp file).
// Release an initial keepsake of 3 uploads.
for (let i = 0; i < 3; i++) await seedUpload(host.jwt, { caption: `orig ${i}` });
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
await waitExportDone(host.jwt);
expect((await downloadZipEntries(host.jwt)).length).toBe(3);
// Reopen (invalidates the release) → add a 4th upload while unlocked → re-release.
expect((await post('/api/v1/host/event/open', host.jwt)).status).toBe(204);
await seedUpload(host.jwt, { caption: 'added-during-reopen' });
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
await waitExportDone(host.jwt);
// The re-released keepsake MUST contain all 4 — the stale-keepsake bug would have left
// the download at the pre-reopen snapshot of 3, silently dropping the new upload.
const listing = await downloadZipEntries(host.jwt);
expect(listing.length, `zip entries:\n${listing.join('\n')}`).toBe(4);
});
test('re-release SUPERSEDES an in-flight (running) export — bumps the generation', async ({
host,
}) => {
// Deterministic proof of the generation guard, independent of export timing. We pin the
// zip job to `running` with a sentinel to mimic a worker from a prior release that is
// still mid-export, then drive reopen→re-release.
//
// On the OLD code (unconditional ON CONFLICT DO UPDATE) the row would be reset to
// pending/progress=0 and a second worker would claim and run concurrently — so the
// sentinel below would be wiped. This assertion therefore fails on the bug and passes
// on the fix.
// OLD behavior (the bug): the re-enqueue left a `running` row alone, so the stale worker
// would eventually finalize and re-flip the ready flag on its pre-reopen snapshot.
// NEW behavior (the fix): the re-enqueue bumps `release_seq` and resets the row, so the
// stale generation is superseded — its sentinel is wiped and a fresh worker regenerates.
await seedUpload(host.jwt, { caption: 'a' });
await seedUpload(host.jwt, { caption: 'b' });
// Release and let the first export fully finish so no real worker is active.
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
await expect
.poll(async () => {
const s = await exportStatus(host.jwt);
return s.zip?.status === 'done' && s.html?.status === 'done';
}, { timeout: 60_000, intervals: [500] })
.toBe(true);
await waitExportDone(host.jwt);
const seqBefore = await zipReleaseSeq();
// Simulate an in-flight worker owning the zip job, with a sentinel we can check.
// Simulate an in-flight worker owning the zip job at the current generation.
await pgQuery(
`UPDATE export_job ej SET status = 'running', progress_pct = 77
FROM event e
WHERE e.id = ej.event_id AND e.slug = '${SLUG}' AND ej.type = 'zip'`
);
// Reopen (clears release + ready flags, does NOT touch job rows) then re-release.
// Reopen (clears release + ready flags; does NOT touch job rows) then re-release.
expect((await post('/api/v1/host/event/open', host.jwt)).status).toBe(204);
expect((await post('/api/v1/host/gallery/release', host.jwt)).status).toBe(204);
// Give any spawned worker a beat to attempt (and, correctly, bail) its claim.
await new Promise((r) => setTimeout(r, 750));
// The guard must have preserved the 'running' sentinel — untouched by both the
// re-enqueue and the bailing worker.
const [row] = await pgQuery<{ status: string; progress_pct: number }>(
`SELECT ej.status::text AS status, ej.progress_pct
// The fresh generation must settle to done at a HIGHER release_seq — proving the stale
// running row was superseded (not left to finalize) and the sentinel is gone.
await waitExportDone(host.jwt);
const [row] = await pgQuery<{ status: string; progress_pct: number; release_seq: string }>(
`SELECT ej.status::text AS status, ej.progress_pct, ej.release_seq
FROM export_job ej JOIN event e ON e.id = ej.event_id
WHERE e.slug = '${SLUG}' AND ej.type = 'zip'`
);
expect(row.status, 'zip job status').toBe('running');
expect(Number(row.progress_pct), 'zip job sentinel progress').toBe(77);
expect(row.status, 'zip job status').toBe('done');
expect(Number(row.progress_pct), 'zip job progress').toBe(100);
expect(Number(row.release_seq), 'release_seq advanced past the superseded generation').toBeGreaterThan(
seqBefore
);
});
});

View File

@@ -0,0 +1,54 @@
/**
* Regression guard — a locked/released event rejects uploads with the DISTINCT error code
* `uploads_locked` (not the generic `forbidden`), so the offline upload queue can tell this
* REVERSIBLE 403 apart from a permanent one (banned / quota). On `uploads_locked` the client
* KEEPS the queued blob and retries when the host reopens; a permanent 403 purges it. Before
* this, a photo staged during a lock was purged and lost the moment the host reopened.
*/
import { test, expect } from '../../fixtures/test';
import { uploadRaw } from '../../helpers/upload-client';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const SAMPLE = () => readFileSync(join(process.cwd(), 'fixtures', 'media', 'sample.jpg'));
test.describe('Upload — locked event uses a distinct, reversible 403 (audit fix)', () => {
test('closed event → 403 uploads_locked; reopen → upload succeeds', async ({ host, api }) => {
// Close the event: uploads are locked for everyone.
await api.closeEvent(host.jwt);
const locked = await uploadRaw(host.jwt, SAMPLE(), {
filename: 'during-lock.jpg',
contentType: 'image/jpeg',
});
expect(locked.status).toBe(403);
const lockedBody = await locked.json();
// The distinct code is what tells the client to KEEP the blob (reversible), not purge it.
expect(lockedBody.error).toBe('uploads_locked');
// Reopen → the same upload now goes through (the queued blob would have survived).
await api.openEvent(host.jwt);
const ok = await uploadRaw(host.jwt, SAMPLE(), {
filename: 'after-reopen.jpg',
contentType: 'image/jpeg',
});
expect(ok.status, 'upload succeeds once the host reopens').toBeLessThan(300);
});
test('released gallery → 403 uploads_locked (also reversible via reopen)', async ({ host }) => {
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
const rel = await fetch(`${BASE}/api/v1/host/gallery/release`, {
method: 'POST',
headers: { Authorization: `Bearer ${host.jwt}` },
});
expect(rel.status).toBe(204);
const rejected = await uploadRaw(host.jwt, SAMPLE(), {
filename: 'after-release.jpg',
contentType: 'image/jpeg',
});
expect(rejected.status).toBe(403);
const body = await rejected.json();
expect(body.error).toBe('uploads_locked');
});
});