diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2b9f603..44abb01 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,3 +16,13 @@ jobs: - run: npm ci - run: npm run check - run: npm audit --omit=dev --audit-level=high + - run: npx playwright install --with-deps chromium + - run: npm run test:browser + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: always() + with: + name: synthetic-browser-evidence + path: | + playwright-report/ + test-results/ + retention-days: 7 diff --git a/.gitignore b/.gitignore index 549853d..0a6bd28 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ node_modules/ *.tsbuildinfo coverage/ .local-data/ + +playwright-report/ +test-results/ diff --git a/.prettierignore b/.prettierignore index 1c83ea7..7db356b 100644 --- a/.prettierignore +++ b/.prettierignore @@ -2,3 +2,6 @@ node_modules package-lock.json next-env.d.ts + +playwright-report +test-results diff --git a/README.md b/README.md index 73205a8..727626b 100644 --- a/README.md +++ b/README.md @@ -51,14 +51,25 @@ The hero is an abstract CSS silhouette, not an example processing result. ## Privacy and deliberate prototype limits -Images are kept only in process-private memory, never in public/static paths or -on disk. The single-process store holds at most 12 portraits, with at most two -upload/processing operations at once. Admission happens before any request-body -read, and invalid options are rejected before admission. Every portrait expires -no later than the owning session (24 hours from session creation), so late-session -uploads have a shorter remaining lifetime. Expiry blocks access; owned timers remove -records and links when due. Server restart clears everything. Timers are subject -to runtime scheduling; read-time expiration is immediate. +Images are retained in a private local filesystem directory, `.local-data` by +default (or an operator-selected `COMMONLIGHT_DATA_DIR` outside all served/build paths). The +root is owner-only and files are 0600; do not put this directory in a static file +server, shared drive or source control. Storage is not encrypted by this app. Filesystem behavior is qualified on the +Linux runner; macOS and Windows persistence are not yet qualified. +Only a single local server is supported, with at most 12 portraits and two +upload/processing operations. Admission precedes request-body reads. + +Every portrait expires no later than its owning session (24 hours from session +creation), so late-session uploads have shorter lifetimes. Reads fail after expiry. +Running-server maintenance removes expired files approximately once per minute, +and each storage operation cleans expired records. If the server is stopped, +expired bytes remain private on disk until its next storage access. Deletion is +ordinary filesystem deletion, not a claim of secure erase from backups or SSDs. + +Original and derived bytes survive a restart. Complete staged records are +atomically renamed into place; sharing/revocation metadata uses atomic file +replacement under a filesystem lock. Unknown versions, malformed state and unsafe +paths fail closed without an in-memory fallback or destructive rebuild. Private access requires an expiring server-issued HttpOnly/SameSite=Strict session cookie. Public links use distinct random capabilities and cannot access originals @@ -67,27 +78,29 @@ Sharing is an explicit second action; unguessability is not a substitute for subject consent. Revocation cannot erase copies viewers have already downloaded. Gallery links are local and useful only on the same reachable local server. -Reloading loses review controls. Download anything to keep before leaving. A -cancelled/disconnected upload that finished just before cancellation may remain -private until expiry. Aborted processing that observes cancellation before commit -cannot store or publish its result. No processing ever publishes automatically. +Reloading restores saved portraits and their review/revoke/delete controls through +an authenticated private listing. Retain the same browser cookie: clearing it or +letting it expire loses owner access. Downloads are needed for longer retention. +A cancelled/disconnected upload that finished before cancellation may still exist +privately; reload recovers it. Cancellation observed before storage publication +removes staged files. No processing publishes a public link automatically. ## Architecture and future integrations - `lib/contracts.ts`: size, consent, options, client response decoders. - `lib/processor.ts`: `PortraitProcessor` and deterministic Sharp implementation. -- `lib/store.ts`: `PortraitStore`, bounded ephemeral memory adapter, short sessions. +- `lib/store.ts`: storage/session contracts and in-memory unit-test adapter. +- `lib/local-store.ts`: versioned private files, atomic updates, expiry and locks. - `lib/service.ts`: processing admission, cancellation fence, creation/publication. - `lib/http.ts` and `app/api`: loopback/origin enforcement, auth and bounded bodies. - `lib/camera.ts`: camera permission/stream ownership and cleanup. - `app/page.tsx`: capture, review and separate publication user experience. A hosted processor can implement `PortraitProcessor`; a private object store plus -transactional metadata store can implement `PortraitStore`. Neither is configured. +transactional metadata store can implement `PortraitStore`. Remote adapters are not configured. Before deployment: supply authorized identity/storage, review provider consent and retention, add durable cancellation/job reconciliation, rate limits and deployment -resource boundaries, and run real-browser acceptance. Never expose the memory -adapter through multiple workers/serverless instances or remove loopback guards +resource boundaries, and run real-browser acceptance. Do not run this local prototype through multiple workers/serverless instances or remove loopback guards without revisiting the threat model. ## Verify @@ -99,9 +112,13 @@ npm run check Unit and route integration tests cover dimensions/encoding, metadata, deterministic output, input/consent rejection, ownership, expiry, sharing/revocation/deletion, concurrency reservations, cancellation and delayed camera permission cleanup. -Real-browser camera/focus/navigation/mobile visual testing is separately required; -this environment prohibited localhost browser access, so it is **not claimed**. -See `docs/plans/portrait-baseline/` for current acceptance and limitations. +`npm run test:browser` adds hosted Chromium checks for synthetic upload, reload, +actual server restart, owner recovery, explicit sharing/revocation, repeated and +interrupted requests, fake-camera cleanup/capture, keyboard use and mobile bounds. +CI installs Chromium and uploads synthetic traces/screenshots; no real photos are +used. Local browser access is prohibited in the development environment, so +browser execution evidence must come from the hosted run before acceptance. +See `docs/plans/durable-local-studio/` for current acceptance and limitations. ## Visual reference @@ -117,3 +134,12 @@ execution (Apache-2.0/MIT), Sharp raster decoding/encoding (Apache-2.0; its bund native dependencies carry their own notices), ESLint/TypeScript/React Hooks/Next plugins own static checks; Prettier formatting. Versions and integrity are locked in package-lock.json. Maintain with tests/build and dependency audit; a clean audit is not a security guarantee. + +`proper-lockfile` (MIT) owns cross-process local mutation exclusion. Playwright +(Apache-2.0) owns hosted browser tests; its browser binaries are installed only in +the hosted runner. The browser harness sets a command-scoped telemetry opt-out. + +The supported Next `distDir` is defined once in `lib/storage-paths.ts` and used by +Next configuration and privacy containment. Both configured paths and resolved +symlink paths are checked against public/static/build output roots. Do not bypass +that shared configuration or serve the private directory through another server. diff --git a/app/api/portraits/[id]/route.ts b/app/api/portraits/[id]/route.ts index 521380e..cdf6585 100644 --- a/app/api/portraits/[id]/route.ts +++ b/app/api/portraits/[id]/route.ts @@ -14,7 +14,7 @@ export const runtime = "nodejs"; type Context = { params: Promise<{ id: string }> }; export async function GET(request: NextRequest, context: Context) { try { - const identity = owner(request); + const identity = await owner(request); const { id } = await context.params; const kind = request.nextUrl.searchParams.get("kind"); if (kind !== "original" && kind !== "preview" && kind !== "processed") @@ -23,7 +23,7 @@ export async function GET(request: NextRequest, context: Context) { "invalid", "Choose original, preview or processed.", ); - const portrait = state.service.store.owned(id, identity); + const portrait = await state.service.store.owned(id, identity); return kind === "original" ? originalDownload(portrait.original, portrait.originalFormat) : jpeg(portrait[kind]); @@ -34,7 +34,7 @@ export async function GET(request: NextRequest, context: Context) { export async function POST(request: NextRequest, context: Context) { try { mutation(request); - const identity = owner(request); + const identity = await owner(request); const { id } = await context.params; let data: unknown; try { @@ -50,9 +50,9 @@ export async function POST(request: NextRequest, context: Context) { "consent" in data && Object.keys(data).every((k) => ["action", "consent"].includes(k)) ) - return json(state.service.publish(id, identity, data.consent)); + return json(await state.service.publish(id, identity, data.consent)); if (data.action === "revoke" && Object.keys(data).length === 1) { - state.service.store.revoke(id, identity); + await state.service.store.revoke(id, identity); return json({ revoked: true }); } throw new AppError(400, "invalid", "Invalid action."); @@ -63,9 +63,9 @@ export async function POST(request: NextRequest, context: Context) { export async function DELETE(request: NextRequest, context: Context) { try { mutation(request); - const identity = owner(request); + const identity = await owner(request); const { id } = await context.params; - state.service.store.delete(id, identity); + await state.service.store.delete(id, identity); return json({ deleted: true }); } catch (e) { return failure(e); diff --git a/app/api/portraits/route.ts b/app/api/portraits/route.ts index 0ce3b8d..ab3b930 100644 --- a/app/api/portraits/route.ts +++ b/app/api/portraits/route.ts @@ -6,7 +6,7 @@ export const runtime = "nodejs"; export async function POST(request: NextRequest) { try { mutation(request); - const identity = owner(request); + const identity = await owner(request); let options: unknown; try { options = JSON.parse( @@ -19,7 +19,10 @@ export async function POST(request: NextRequest) { await state.service.create( () => boundedBody(request), decodeOptions(options), - { token: identity, expiresAt: state.sessions.expiresAt(identity) }, + { + token: identity, + expiresAt: await state.sessions.expiresAt(identity), + }, request.signal, ), 201, @@ -28,3 +31,12 @@ export async function POST(request: NextRequest) { return failure(e); } } + +export async function GET(request: NextRequest) { + try { + const identity = await owner(request); + return json(await state.service.store.list(identity)); + } catch (error) { + return failure(error); + } +} diff --git a/app/api/public/[token]/route.ts b/app/api/public/[token]/route.ts index 8db8491..df0e37a 100644 --- a/app/api/public/[token]/route.ts +++ b/app/api/public/[token]/route.ts @@ -8,7 +8,7 @@ export async function GET( try { localOnly(request); const { token } = await context.params; - return jpeg(state.service.store.published(token).processed); + return jpeg((await state.service.store.published(token)).processed); } catch (e) { return failure(e); } diff --git a/app/api/session/route.ts b/app/api/session/route.ts index 26a8fea..411904a 100644 --- a/app/api/session/route.ts +++ b/app/api/session/route.ts @@ -1,20 +1,20 @@ import { NextRequest } from "next/server"; import { state } from "@/lib/service"; import { failure, json, mutation } from "@/lib/http"; -import { RETENTION_MS } from "@/lib/contracts"; +import { RETENTION_MS, AppError } from "@/lib/contracts"; export const runtime = "nodejs"; export async function POST(request: NextRequest) { try { mutation(request); const existing = request.cookies.get("commonlight_session")?.value; try { - state.sessions.require(existing); + await state.sessions.require(existing); return json({ ready: true }); - } catch { - /* Expired sessions get new bounded capabilities. */ + } catch (error) { + if (!(error instanceof AppError) || error.status !== 401) throw error; } const response = json({ ready: true }); - response.cookies.set("commonlight_session", state.sessions.create(), { + response.cookies.set("commonlight_session", await state.sessions.create(), { httpOnly: true, sameSite: "strict", secure: new URL(request.url).protocol === "https:", diff --git a/app/gallery/[token]/page.tsx b/app/gallery/[token]/page.tsx index a23bdc0..ab64f29 100644 --- a/app/gallery/[token]/page.tsx +++ b/app/gallery/[token]/page.tsx @@ -8,7 +8,7 @@ export default async function Gallery({ }) { const { token } = await params; try { - state.service.store.published(token); + await state.service.store.published(token); } catch { notFound(); } diff --git a/app/globals.css b/app/globals.css index 83a5693..4d40b49 100644 --- a/app/globals.css +++ b/app/globals.css @@ -573,3 +573,20 @@ footer { scroll-behavior: auto; } } +.saved-portraits { + margin: 20px 0 28px; + padding: 20px; + border: 1px solid var(--line); + border-radius: 12px; +} +.saved-portraits > span { + display: block; + font: 11px monospace; + letter-spacing: 0.1em; + margin-bottom: 12px; + color: var(--accent); +} +.saved-portraits button[aria-pressed="true"] { + border-color: var(--accent); + color: var(--accent); +} diff --git a/app/page.tsx b/app/page.tsx index a7a6a00..f219ae2 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -6,6 +6,7 @@ import { MAX_UPLOAD_BYTES, decodePublication, decodeResult, + decodePortraitList, } from "@/lib/contracts"; type Result = ReturnType; async function checked(response: Response) { @@ -35,6 +36,8 @@ export default function Studio() { [notice, setNotice] = useState(""); const [result, setResult] = useState(null), [link, setLink] = useState(""); + const [saved, setSaved] = useState>([]); + const [recovering, setRecovering] = useState(true); const video = useRef(null), controller = useRef(new CameraController()); const request = useRef(null), @@ -73,9 +76,104 @@ export default function Studio() { window.removeEventListener("pagehide", onPageHide); }; }, []); + useEffect(() => { + let pending: AbortController | undefined; + async function recover() { + pending?.abort(); + const abort = new AbortController(); + pending = abort; + const current = ++generation.current; + try { + const response = await fetch("/api/portraits", { + signal: abort.signal, + }); + if (response.status === 401) { + if ( + !abort.signal.aborted && + mounted.current && + current === generation.current + ) { + setSaved([]); + setResult(null); + setLink(""); + } + return; + } + const portraits = decodePortraitList(await checked(response)); + if ( + !abort.signal.aborted && + mounted.current && + current === generation.current + ) { + setSaved(portraits); + const portrait = portraits[0]; + if (!portrait) { + setResult(null); + setLink(""); + } + if (portrait) { + setResult(portrait); + setLink( + portrait.token + ? `${location.origin}/gallery/${portrait.token}` + : "", + ); + setNotice( + `Restored ${portraits.length} saved portrait${portraits.length === 1 ? "" : "s"} in this private session.`, + ); + } + } + } catch (error) { + if ( + !abort.signal.aborted && + mounted.current && + current === generation.current + ) + setError( + error instanceof Error + ? error.message + : "Could not restore private portraits.", + ); + } finally { + if ( + !abort.signal.aborted && + mounted.current && + current === generation.current + ) + setRecovering(false); + } + } + void recover(); + const onHide = () => pending?.abort(); + const onShow = (event: PageTransitionEvent) => { + if (event.persisted) { + setRecovering(true); + void recover(); + } + }; + window.addEventListener("pagehide", onHide); + window.addEventListener("pageshow", onShow); + return () => { + pending?.abort(); + window.removeEventListener("pagehide", onHide); + window.removeEventListener("pageshow", onShow); + }; + }, []); useEffect(() => { if (result) heading.current?.focus(); }, [result]); + function selectSaved( + portrait: ReturnType[number], + ) { + if (busy || recovering) return; + stopCamera(); + setResult(portrait); + setLink( + portrait.token ? `${location.origin}/gallery/${portrait.token}` : "", + ); + setShareConsent(false); + setError(""); + } function choose(selected: File | null) { setError(""); if (!selected) return; @@ -160,7 +258,7 @@ export default function Studio() { ); } async function run(action: (signal: AbortSignal) => Promise) { - if (lock.current) return; + if (lock.current || recovering) return; lock.current = true; setBusy(true); setError(""); @@ -207,6 +305,7 @@ export default function Studio() { ); if (!signal.aborted && mounted.current) { setResult(data); + setSaved((current) => [...current, data]); setLink(""); setShareConsent(false); setNotice( @@ -241,6 +340,11 @@ export default function Studio() { ); if (!signal.aborted && mounted.current) { setLink(`${location.origin}/gallery/${data.token}`); + setSaved((current) => + current.map((item) => + item.id === result.id ? { ...item, token: data.token } : item, + ), + ); setNotice( "Link sharing is on. Anyone with the link can view and save this portrait.", ); @@ -261,6 +365,13 @@ export default function Studio() { if (!signal.aborted && mounted.current) { setLink(""); setShareConsent(false); + setSaved((current) => + current.map((item) => + item.id === result.id + ? { id: item.id, expiresAt: item.expiresAt } + : item, + ), + ); setNotice( "Link revoked. Previously downloaded copies cannot be recalled.", ); @@ -277,6 +388,7 @@ export default function Studio() { }), ); if (!signal.aborted && mounted.current) { + setSaved((current) => current.filter((item) => item.id !== result.id)); setResult(null); setLink(""); setShareConsent(false); @@ -351,8 +463,44 @@ export default function Studio() { )}

- {busy ? "Working on your request…" : notice} + {recovering + ? "Restoring your private studio…" + : busy + ? "Working on your request…" + : notice}

+ {saved.length > 0 && ( + + )} {!result ? (
@@ -395,7 +543,7 @@ export default function Studio() { { setConsent(e.target.checked); if (!e.target.checked) stopCamera(); @@ -413,14 +561,14 @@ export default function Studio() {

@@ -530,9 +684,9 @@ export default function Studio() { private.

- Expires {new Date(result.expiresAt).toLocaleString()}. - Server restart also removes it. Anyone holding a shared link - can save a copy. + Expires {new Date(result.expiresAt).toLocaleString()}. This + deadline remains the same after a restart. Anyone holding a + shared link can save a copy.

@@ -542,7 +696,7 @@ export default function Studio() { setShareConsent(e.target.checked)} /> @@ -551,7 +705,7 @@ export default function Studio() {