From aae0b392f80132ef5d4dbed91280ce22b3c78d3b Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 12 Oct 2026 01:29:57 +0200 Subject: [PATCH] =?UTF-8?q?docs(docs):=20Step=208=20analysis=20rev=202=20?= =?UTF-8?q?=E2=80=94=2047=20challenger=20findings=20folded=20(keyless=20de?= =?UTF-8?q?code=20child,=20write=20order,=20purge=20queue=20+=20grace,=20d?= =?UTF-8?q?ownload=20under=20RLS,=20narrowed=20schema);=20chore(memory):?= =?UTF-8?q?=20TODO=208.x?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/tasks/TODO.md | 12 +- docs/development/STEP8_FILES_ANALYSIS.md | 893 ++++++++++++----------- 2 files changed, 477 insertions(+), 428 deletions(-) diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 805b54f7..b12acae0 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -126,13 +126,13 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 7.8 tests: config, authStore (fake client), locale sync, forms, guards, shell, dashboard, account; i18n parity; pgTAP 009 (PGlite + real stack 280/280); root check + docker build green; headless e2e vs local stack 20/20 (signup via Mailpit, recovery, logout, mobile) - [x] 7.9 docs (IDENTITY.md, SUPABASE.md, CLAUDE.md, CHANGELOG, plan note); memory BDR-041, LRN-047, EVAL-015, journal; gates: verifier ECARTS(2) → open-redirect fix + contract CHECK → CONFORME 16/16; security PASS (MEDIUM fixed, 3 LOW closed, TOTP enforcement = documented gap). User validated 2026-10-12; user action still open: `.env.example` += `APP_AUTH_PROVIDERS=` (file edit denied here) - [ ] 7.10 follow-ups kept by the user (2026-10-12), each owned by a later step: MFA mandatory before any sensitive admin feature (has_mfa helper + enrolment UI, IDENTITY.md §4; first admin screen); professional verification distinct from the SIRET format check (Step 11); real tests of Google and Apple once the provider ids exist (config.toml env(), APP_AUTH_PROVIDERS); integration of the report tool into the signed-in /app space (Step 14 gating); mockup elements not built yet listed in docs/design/README.md (bell, avatar photo → Step 8, stat tiles, tabs, mobile tab bar) -- [ ] Step 8 — files foundation + Supabase Storage (analysis 2026-10-12 on chore/step-08-files-analysis: docs/development/STEP8_FILES_ANALYSIS.md; 3 plan-challengers; AWAITING USER DECISIONS D1–D8 + go; nothing implemented). User brief: 8 private buckets closed by default, quarantine + server validation, allowlist SVG, avatar in Mon compte (upload/preview/replace/delete/header), JPEG/PNG/WebP ≤ 5 MB resized + metadata stripped, no SVG avatar, service role never in the browser, portable self-hosted → managed, allowed + denied access tests +- [ ] Step 8 — files foundation + Supabase Storage (analysis 2026-10-12 on chore/step-08-files-analysis: docs/development/STEP8_FILES_ANALYSIS.md; 3 plan-challengers (47 findings folded, rev 2); AWAITING USER DECISIONS D1–D9 + go; nothing implemented). User brief: 8 private buckets closed by default, quarantine + server validation, allowlist SVG, avatar in Mon compte (upload/preview/replace/delete/header), JPEG/PNG/WebP ≤ 5 MB resized + metadata stripped, no SVG avatar, service role never in the browser, portable self-hosted → managed, allowed + denied access tests - [x] 8.0 analysis: facts (existing bucket + policy pattern, sanitiser, edge runtime off, CSP, deploy), design (assets table authority, server-built keys, quarantine prefix, worker `faunosteo_worker` with sharp + pdf sanitiser, storage.objects policies through assets, Storage API signing under RLS, sweeper/reconcile, backups file volume + restic, managed migration by rows), 10 security answers, scope, tests, risks, D1–D8 - - [ ] 8.1 migration 20261012100000_files_foundation (enums, assets, 7 buckets, helpers, avatars policies, RPCs, profiles.avatar_asset_id, revokes) + pgTAP 010 allowed/denied + policy census + types regen - - [ ] 8.2 apps/worker: loop, claim/complete/reject, image processor (sharp), svg processor (@faunosteo/pdf), sweeper, reconcile/migrate commands, Dockerfile + compose service + .env.worker.example, fixtures tests, local-stack integration test - - [ ] 8.3 packages/supabase assets service (begin/upload/confirm/remove/fetchOwnAsset/signedUrlFor + TTL table, closed failure kinds) - - [ ] 8.4 app: avatar block in Mon compte (picker, preview, save, processing, delete), UserBadge photo, top bar avatar (D3), authStore URL cache, i18n, tests; design toolchain + impeccable detect - - [ ] 8.5 docs: STORAGE.md (model, keys, statuses, worker ops, backup/restore runbook, managed migration), DEPLOY.md (worker, env file, CSP), SUPABASE.md, CLAUDE.md, CHANGELOG, plan note (worker early); CI jobs + - [ ] 8.1 migration 20261012100000_files_foundation (asset_status, assets, 7 buckets, avatar predicates, avatars policies, purge queue + triggers, storage ceiling, 9 RPCs, revokes) + pgTAP 010 allowed/denied + policy census (one bucket literal per policy) + 001 census + types regen + - [ ] 8.2 apps/worker: keyed I/O loop + keyless decode child (sharp, 20 s SIGKILL), lease claim, PUT→complete→DELETE order, sweeper (purge queue + quarantine by key), watchdog, Dockerfile + compose service (read-only, cpus 1, internal network) + .env.worker.example, fixtures tests with time/RSS asserts, local-stack integration test + - [ ] 8.3 packages/supabase assets service (begin/upload/confirm/remove/fetchOwnAvatar/downloadAvatar, closed failure kinds; no signed URL) + - [ ] 8.4 app: avatar block in Mon compte (picker, canvas ≤1024 JPEG transport, preview, save, processing, supersede, delete), UserBadge photo, top bar avatar (D3), authStore blob URL, i18n, tests; design toolchain + impeccable detect + - [ ] 8.5 docs: STORAGE.md (model, keys, statuses, purge/grace rules, reconciliation query, backup ordering + invariant, managed migration runbook), DEPLOY.md (worker, env file, network, CSP connect-src), SUPABASE.md, CLAUDE.md, CHANGELOG, plan note (worker early, SVG processor → Step 13); CI jobs - [ ] 8.6 verify: root check, PGlite + real stack pgTAP, types, docker builds (app + worker), real-stack e2e (sign allowed/denied), gates verifier + security; memory; stop for user validation - [ ] Release 0.2.0 (branch release/0.2.0 = Steps 3–6, version.txt + package versions 0.2.0, CHANGELOG [0.2.0] 2026-10-11): deploy-trigger check done 2026-10-12 (CI = branches main/develop only, no tag trigger, no deploy job, docker job builds `faunosteo:ci` locally; hooks push only; DEPLOY.md deploy = manual on the VPS). Default 0.2.0 build carries NO sheet (SHEET_BUNDLE=none) → the live local tool must not be redeployed from main without `--build-arg SHEET_BUNDLE=draft`. Finish via /release-candidate (finish + tag span, tag push on explicit go); CHANGELOG back-merge conflict expected (Unreleased Step 7 above [0.2.0]). Awaiting the user's go. --- diff --git a/docs/development/STEP8_FILES_ANALYSIS.md b/docs/development/STEP8_FILES_ANALYSIS.md index 1801d58d..681748ea 100644 --- a/docs/development/STEP8_FILES_ANALYSIS.md +++ b/docs/development/STEP8_FILES_ANALYSIS.md @@ -1,9 +1,12 @@ # Step 8 — Files foundation and Supabase Storage: technical analysis -Status: proposal for the owner's decision, 2026-10-12. Nothing implemented. -Applies the owner's brief of 2026-10-12 (Step 7 closed; hosting = self-hosted -Supabase first, managed later; eight private buckets; quarantine + server -validation; avatar as first consumer; service role never in the browser). +Status: proposal for the owner's decision, 2026-10-12, revision 2 after three +independent plan challenges (correctness, robustness, simplicity: 47 +findings, folded in; the changes are listed in I.3). Nothing implemented. +Applies the owner's brief of 2026-10-12 (Step 7 closed; hosting = +self-hosted Supabase first, managed later; eight private buckets closed by +default; quarantine + server validation; avatar as first consumer; service +role never in the browser). Part I states the facts the design rests on. Part II is the proposed design. Part III answers the ten security questions of the brief. Part IV lists the @@ -17,25 +20,44 @@ exact scope, the tests, the risks and the decisions the owner has to take. | Area | State | |---|---| -| Storage | One bucket, `anatomical-sheet-assets` (migration `20261009100000`): private, SVG only, 20 MiB cap, content-addressed keys `.svg`, SELECT policy through the sheet (`private.can_read_sheet_asset_object`), no API write policy, operator upload script with the service key, `confirm_sheet_asset_upload` RPC (service role). pgTAP 006 (28 checks) runs on the PGlite shim and on the real stack. | -| Storage API | `storage-api v1.79.36` in the local stack (same image family as a self-hosted deployment). Signed URLs, signed upload URLs and RLS on `storage.objects` are available; image transformation needs `imgproxy`, absent here and a paid add-on on managed. | -| Profiles | `avatar_asset_id` was deliberately deferred to this step (comment in `20261008100100_profiles.sql`). | -| Shell UI | `UserBadge` (monogram) in the sidebar and the drawer; the top bar holds only the language switch; "Mon compte" = stacked sections, `PersonalInfoForm` first. The validated mockup shows the avatar with "Modifier la photo" inside the Profil section and an avatar + name in the top bar. | -| SVG sanitiser | `packages/pdf/src/svg/sanitize.ts`: allowlist of elements and attributes, `href` / `url()` kept in-document, backslash refused, caps 20 000 elements / depth 64 / 256 `` / `stdDeviation` 100, DOM Level 2 on `@xmldom/xmldom`, `SvgRejectedError`. Browser-free. | -| Edge runtime | Disabled in `config.toml`. `BACKEND_ARCHITECTURE.md` §6: self-hosted Edge Functions are hand-deployed; first steps lean on SQL. C3: PostgreSQL-backed jobs before a queue. C12: the sanitiser runs between upload and publication, never "on upload". | +| Storage | One bucket, `anatomical-sheet-assets` (migration `20261009100000`): private, SVG only, 20 MiB cap, content-addressed keys `.svg`, SELECT policy through the sheet (`private.can_read_sheet_asset_object`), no API write policy, operator upload script with the service key, `confirm_sheet_asset_upload` RPC (service role). pgTAP 006 (28 checks) runs on the PGlite shim and on the real stack; pgTAP 001 pins the exact list of `private` functions `authenticated` may execute. | +| Storage API | `storage-api v1.79.36` locally (same image family as self-hosted). Verified on the client library (storage-js 2.117): an upload with the user JWT and `upsert: false` needs only an INSERT policy on `storage.objects`, evaluated on `bucket_id` and `name`; the bucket MIME check runs before RLS on the multipart part type (the browser's `File.type`, not sniffed); `createSignedUrl` evaluates the SELECT policy as the caller and answers 400 when denied; a signed upload URL is checked at signing time only and stays valid two hours. Image transformation needs `imgproxy`, absent here and a paid add-on on managed. | +| Profiles | `avatar_asset_id` was deferred to this step (comment in `20261008100100_profiles.sql`). | +| Shell UI | `UserBadge` (monogram) in the sidebar and the drawer; the top bar holds only the language switch; "Mon compte" = stacked sections, `PersonalInfoForm` first. The validated mockup shows the avatar with "Modifier la photo" inside the Profil section and an avatar + name in the top bar. Production CSP: `default-src 'self'`, `img-src 'self' data: blob:`. | +| SVG sanitiser | `packages/pdf/src/svg/{parse,sanitize,view}.ts`: `parseSvg` refuses DOCTYPE / ENTITY, `sanitizeSvgRoot` = allowlist of elements and attributes, in-document `href` / `url(#)` only, backslash refused, caps 20 000 elements / depth 64 / 256 `` / `stdDeviation` 100; `cleanSvgRoot` chains both. Hostile fixtures already covered by `packages/pdf/tests/security.test.ts` (script, `on*`, `javascript:`, external image, CSS escapes, ENTITY, 257 ``, `horse.svg` unchanged). Not exported from the package index; serialisation drops the XML declaration (byte change). | +| Edge runtime | Disabled in `config.toml`. `BACKEND_ARCHITECTURE.md` §6; C3: PostgreSQL-backed jobs before a queue; C12: the sanitiser runs between upload and publication. | | Worker | The plan creates `apps/worker` at Step 19 (notifications). Files processing needs server-side code before that. | -| Deploy | No backend in production yet. The VPS `.env` is documented as non-sensitive. CSP: `default-src 'self'`, `img-src 'self' data: blob:` (a Supabase origin would be blocked for both API calls and images). | -| Tests | pgTAP on PGlite + real stack; app vitest on happy-dom; Step 7 added a headless e2e script against the local stack (scratchpad, Mailpit). | +| Deploy | No backend in production yet. The VPS `.env` is documented as non-sensitive. The VPS is shared by several SaaS (BDR-035). | +| sharp 0.35.5 | No install script, Node ≥ 20.9, prebuilt `linuxmusl-x64`. `rotate()` with no angle auto-orients from EXIF; output strips all metadata by default and converts through the embedded ICC profile to sRGB; `failOn` defaults to `warning` (stricter than `error`); `limitInputPixels` is enforced before `metadata()` returns. | +| Tests | pgTAP on PGlite + real stack; app vitest on happy-dom; Step 7 added a headless e2e script against the local stack. PostgREST `max_rows = 1000` caps set-returning RPCs. | ### I.2 Corrections to the plan's Step 8 text - "RPC `issue_signed_url(asset_id)`" cannot exist in SQL: signing needs the - Storage API's secret. The Storage API signs a URL only after evaluating the - SELECT policy of `storage.objects` as the caller, so the access check and - the signature live in one place already. The design uses it directly. + Storage API's secret. The Storage API signs only after the SELECT policy + passes, so the check and the signature already live in one place. For an + owner-only avatar, Step 8 does not sign at all (II.6). - "Edge Function or SQL-only sanitizer": SQL cannot parse XML or decode - images safely; Edge Functions cannot load a native image library and are - hand-deployed on self-hosted. A containerised worker is the fit (II.1). + images; a containerised worker is the fit (II.1). +- "Upload a hostile SVG as a sheet asset and verify it is rewritten": no user + can upload a sheet asset before Step 13, so this manual check moves there + with the processor (D6). + +### I.3 Changes after the challenges (revision 2) + +Decoder isolated from the service key and bounded by a hard deadline; +write order PUT clean → commit → delete quarantine; `uploaded` rows +superseded by a new upload instead of a blocking unique index; purge queue +with a grace period longer than a backup run (the backup invariant was +false otherwise); every quarantine leftover auto-purged (signed upload URLs +can land bytes after the row moved on); client-side downscale as transport +(current phones exceed a 24 MP cap); owner-only avatar read by `download` +under RLS, no signed URL, no bearer token; schema narrowed to the one kind +that has rules (no multi-kind dispatcher, no derived-bucket trigger, no +unread columns); avatar pointer derived by a unique index instead of a +profile column + trigger; SVG processor, `migrate` and `reconcile` +commands, backup tooling and restore drill moved out of Step 8 (runbook +text stays); policy census pins one bucket literal per policy. --- @@ -45,386 +67,407 @@ exact scope, the tests, the risks and the decisions the owner has to take. ```text Browser (anon key + user JWT) + │ pick file → decode → canvas downscale (transport) → JPEG blob │ begin_avatar_upload (RPC) ─► assets row pending_upload + quarantine key │ PUT object (Storage API, INSERT policy = that key, that row, that user) │ confirm_asset_upload (RPC) ─► status uploaded │ poll own assets row ─► clean | rejected - │ createSignedUrl(object_key, 3600) (Storage API, SELECT policy) ─► + │ download(object_key) (Storage API, SELECT policy) ─► blob URL ─► ▼ Supabase (self-hosted compose, later managed) - PostgREST ─ public.assets, RPCs, private helpers Storage API ─ 8 private buckets + PostgREST ─ public.assets, RPCs, private helpers Storage API ─ 8 private buckets ▲ - │ claim_asset_jobs / complete_asset_job / reject_asset_job (RPC, service role) - │ GET quarantine object, PUT clean object, DELETE quarantine (service role) -apps/worker (container faunosteo_worker, outbound only, no port) - processors: image (sharp) · svg (@faunosteo/pdf allowlist) - sweeper: purge objects of deleted/rejected rows, abandoned uploads, stale jobs - operator commands: reconcile, migrate + │ claim_avatar_jobs / complete_avatar_job / reject_avatar_job (service role) + │ claim_purges / ack_purge (service role) + │ GET quarantine, PUT clean, DELETE objects (service role) +apps/worker — container faunosteo_worker, outbound only, no port + keyed I/O loop ──stdin/stdout──► unkeyed decode child (sharp), 20 s deadline, SIGKILL + sweeper: purge queue (row-driven), quarantine leftovers (key-driven) ``` -Why a worker and not Edge Functions: Edge Functions on the self-hosted stack -run in a separate `edge-runtime` container, are deployed by hand, cannot -load `sharp` (native), and the config keeps them off. Why not SQL: no image -decoding, no XML parsing. The worker is one Node 24 container with the -service key in its own env file, no inbound port, the same code against the -local stack, the VPS stack and a managed project (URL + key change only). -It is the `apps/worker` the plan creates at Step 19; it arrives earlier with -one job family, Step 19 adds its own. +Why a worker: image validation needs a native decoder on the server side, +behind the service key, with a hard resource bound. Postgres cannot read +object bytes; a client-side re-encode is not validation (a polyglot +passes); pg_net or a webhook would give the worker an inbound port. Edge +Functions would be one more container on self-hosted too, hand-deployed, +and on managed they decode in WASM under a CPU and memory budget not sized +for photos (`sharp` is native and cannot run there). The worker is one Node +24 container, the same code against the local stack, the VPS and a managed +project (URL + key only). It is the `apps/worker` of plan Step 19, arriving +early with one job family; Step 19 extends it. -Dependency added: `sharp` (0.35.x, libvips, prebuilt `linuxmusl-x64` -package, no install script, Node ≥ 20.9). It decodes JPEG / PNG / WebP, -resizes, re-encodes, and drops metadata by default. The only widely -maintained option that does all four in Node; pure-JS stacks cover PNG only -or are unmaintained. +Dependency added: `sharp` 0.35.x (libvips). The only maintained Node +library that decodes JPEG / PNG / WebP, resizes, re-encodes and strips +metadata; pure-JS alternatives cover PNG only or are unmaintained. The +worker imports no workspace package, so Node 24 runs its TypeScript +directly (type stripping), no bundler, no `tsx`. ### II.2 Buckets -All eight private (`public = false`). Created by one migration with -`on conflict (id) do update` so the migration converges on the local stack, -the VPS and managed alike. `file_size_limit` and `allowed_mime_types` on the -bucket are a first filter on what the Storage API accepts, never a proof of -content. +All eight private. One migration, `on conflict (id) do update`, so it +converges on the local stack, the VPS and managed alike. -| Bucket | Kind(s) | Owning domain and step | Step 8 state | -|---|---|---|---| -| `avatars` | profile_avatar | Identity (self) | **open**: SELECT + INSERT policies through `assets` | -| `logos` | organization_logo | Organizations, Step 10 | closed, no policy | -| `professional-documents` | professional_document | Verification, Step 9 | closed | -| `client-files` | client_file | Clients, Step 12 | closed | -| `animal-files` | animal_file | Animals, Step 12 | closed | -| `report-files` | report_file | PDF artifacts, Step 15 | closed | -| `anatomical-sheet-assets` | anatomical_sheet_asset | Sheets (existing policy kept) | unchanged | -| `imports` | import_file | Imports, Step 24 | closed | +| Bucket | Owning domain and step | Step 8 state | +|---|---|---| +| `avatars` | Identity (self) | **open**: SELECT + INSERT policies through `assets`, 5 MiB, image/jpeg · png · webp | +| `logos` | Organizations, Step 10 | closed, no policy, no cap yet | +| `professional-documents` | Verification, Step 9 | closed | +| `client-files` | Clients, Step 12 | closed | +| `animal-files` | Animals, Step 12 | closed | +| `report-files` | PDF artifacts, Step 15 | closed | +| `anatomical-sheet-assets` | Sheets (existing policy, kept) | unchanged | +| `imports` | Imports, Step 24 | closed | -"Closed" = the bucket row exists, RLS on `storage.objects` has no policy -naming it, so `anon` and `authenticated` can neither list, read, upload, -update nor delete. Only the service role touches it. A pgTAP census pins -the exact policy count per bucket, so a later step cannot open a bucket by -accident without changing the test. +"Closed" = the bucket row exists with `public = false`, no policy on +`storage.objects` names it, so `anon` and `authenticated` can neither list, +read, upload, update nor delete; only the service role can. Caps and MIME +lists of closed buckets are set by their own step. A pgTAP census asserts +that every `storage.objects` policy pins exactly one bucket literal +(`bucket_id = '…'`), counts them per bucket (2 on `avatars`, 1 on +`anatomical-sheet-assets`, 0 elsewhere) and pins the total, so a generic +policy naming no bucket cannot open the others. Open point (D2): the brief names the sheet bucket `anatomical-sheets`; the -repository already has `anatomical-sheet-assets` with its policy, its -operator script, its tests and its seed. Recommendation: keep the existing -name and record the deviation; a rename costs a migration, a re-upload and -touches Step 13 for no behaviour. +repository already has `anatomical-sheet-assets` with policy, operator +script, tests and seed. Recommendation: keep the name, record the deviation. -Proposed caps (closed buckets get the final value at their own step): - -| Bucket | Size | Declared types | -|---|---|---| -| avatars | 5 MiB | image/jpeg, image/png, image/webp | -| logos | 2 MiB | image/jpeg, image/png, image/webp | -| professional-documents | 20 MiB | application/pdf, image/jpeg, image/png | -| client-files, animal-files | 20 MiB | pdf + the three image types | -| report-files | 50 MiB | application/pdf | -| anatomical-sheet-assets | 20 MiB (existing) | image/svg+xml | -| imports | 50 MiB | application/pdf, application/json, text/csv | - -### II.3 `public.assets` — the authority on every user file +### II.3 `public.assets` and the RPCs One row per file, created before the bytes exist, kept after they are gone -(status `deleted`) until the sweeper has purged the object. +(status `deleted`) until the purge queue has been served. ```sql -create type public.asset_kind as enum ( - 'profile_avatar', 'organization_logo', 'professional_document', - 'client_file', 'animal_file', 'report_file', 'anatomical_sheet_asset', 'import_file'); -create type public.asset_status as enum ( - 'pending_upload', 'uploaded', 'processing', 'clean', 'rejected', 'deleted'); +create type public.asset_status as enum + ('pending_upload', 'uploaded', 'clean', 'rejected', 'deleted'); create table public.assets ( - id uuid primary key default gen_random_uuid(), - owner_id uuid not null references public.profiles (id) on delete cascade, - kind public.asset_kind not null, - bucket_id text not null, -- derived from kind, checked by trigger - resource_id uuid, -- profile id for avatars - object_key text not null unique, -- final key, server-built - quarantine_key text, -- upload key, null once purged - status public.asset_status not null default 'pending_upload', - declared_mime text not null, - declared_size integer not null check (declared_size between 1 and 52428800), - original_filename text check (char_length(original_filename) <= 120), -- display only - detected_mime text, - byte_size integer, - sha256 text check (sha256 ~ '^[0-9a-f]{64}$'), - width integer, - height integer, - rejection_reason text, -- closed codes, see II.6 - attempts smallint not null default 0, - locked_at timestamptz, - created_at timestamptz not null default now(), - updated_at timestamptz not null default now(), - processed_at timestamptz, - deleted_at timestamptz, - purged_at timestamptz -- object removed by the sweeper + id uuid primary key default gen_random_uuid(), + owner_id uuid not null references public.profiles (id) on delete cascade, + kind text not null check (kind in ('profile_avatar')), -- extended per step + bucket_id text not null check (bucket_id = 'avatars'), -- extended with kind + object_key text not null unique, -- final key, server-built + quarantine_key text, -- upload key, null once purged + status public.asset_status not null default 'pending_upload', + declared_mime text not null, + declared_size integer not null check (declared_size between 1 and 5242880), + byte_size integer, -- clean output + sha256 text check (sha256 ~ '^[0-9a-f]{64}$'), + rejection_reason text, -- closed codes, II.7 + attempts smallint not null default 0, + locked_at timestamptz, -- lease, II.8 + created_at timestamptz not null default now(), + updated_at timestamptz not null default now() ); --- one avatar in flight per account -create unique index assets_one_avatar_in_flight - on public.assets (owner_id) where kind = 'profile_avatar' and status in ('pending_upload','uploaded','processing'); - -alter table public.profiles add column avatar_asset_id uuid references public.assets (id); +-- "the" avatar of an account = its single clean row (no profile column, no trigger) +create unique index assets_one_clean_avatar + on public.assets (owner_id) where kind = 'profile_avatar' and status = 'clean'; +create index assets_claimable on public.assets (created_at) where status = 'uploaded'; ``` Privileges: `revoke all` from API roles, `grant select` to `authenticated`, RLS `assets_select_own` (`owner_id = auth.uid()`). No INSERT / UPDATE / -DELETE policy: every write is an RPC. `profiles.avatar_asset_id` is not in -the column grant: only the server sets it, and a trigger checks that it -points to a `clean` `profile_avatar` of the same profile. - -RPCs (security definer, `set search_path = ''`, authorisation before any -lookup, EXECUTE revoked from PUBLIC, granted per role, audited through -`private.log_event` where the state is sensitive): +DELETE policy: every write is an RPC (security definer, `search_path = ''`, +authorisation before lookup, EXECUTE revoked from PUBLIC, granted per role, +`private.log_event` on sensitive transitions). pgTAP 001's census of +`private` functions executable by `authenticated` is updated for the two +new predicates. | RPC | Role | Effect | |---|---|---| -| `begin_avatar_upload(declared_mime, declared_size, original_filename)` | authenticated | caps (type in list, size ≤ 5 MiB), rate (≤ 10 rows created in the last hour), replaces a stale `pending_upload` of the same account; inserts the row with `object_key = profiles///avatar.webp` and `quarantine_key = quarantine///upload`; returns `{asset_id, bucket_id, quarantine_key}` | -| `confirm_asset_upload(asset_id)` | authenticated | own row, `pending_upload` → checks the object exists at `quarantine_key` with `metadata->>'size'` ≤ cap → `uploaded` | -| `remove_avatar()` | authenticated | clears `profiles.avatar_asset_id`, marks the asset `deleted`; logs `asset.avatar_removed` | -| `claim_asset_jobs(limit)` | service_role | `uploaded` → `processing` with `for update skip locked`, `locked_at`, `attempts + 1`; returns the rows | -| `complete_asset_job(asset_id, result)` | service_role | `processing` → `clean` with detected fields; for an avatar: sets `profiles.avatar_asset_id`, marks the previous avatar asset `deleted`, in the same transaction; logs `asset.avatar_set` | -| `reject_asset_job(asset_id, reason)` | service_role | `processing` → `rejected`; logs `asset.rejected` | -| `reclaim_stale_jobs()` | service_role | `processing` older than 10 min → `uploaded` while `attempts < 3`, else `rejected (processing_error)` | -| `list_purgeable_assets()` / `mark_asset_purged(asset_id)` | service_role | rows whose object must go (`deleted`, `rejected`, abandoned `pending_upload` > 24 h, `clean` with a quarantine key still present) | +| `begin_avatar_upload(declared_mime, declared_size)` | authenticated | locks the caller's `profiles` row (`for update`, serialises a double click); rate: ≤ 10 rows of the caller created in the last hour, all statuses counted → `rate_limited`; global ceiling: sum of `declared_size` of non-deleted rows < `private.storage_ceiling()` → `storage_full`; caps (type in the list, size ≤ 5 MiB); supersedes any `pending_upload` / `uploaded` row of the caller (→ `deleted`, enqueued for purge); inserts the row with `object_key = profiles///avatar.webp`, `quarantine_key = quarantine///upload`; returns `{asset_id, bucket_id, quarantine_key}` | +| `confirm_asset_upload(asset_id)` | authenticated | own row, `pending_upload`, a `storage.objects` row exists at `(bucket_id, quarantine_key)` with `metadata->>'size'` ≤ cap → `uploaded`. Kept as an explicit client signal: the worker never has to guess from Storage API internals whether a PUT finished | +| `remove_avatar()` | authenticated | every `profile_avatar` row of the caller not already `deleted` / `rejected` (clean and in flight) → `deleted`; logs `asset.avatar_removed` | +| `claim_avatar_jobs(max_jobs)` | service_role | `uploaded` rows with `locked_at is null or locked_at < now() - 10 min` and `attempts < 3`, `for update skip locked`, oldest first → sets `locked_at`, `attempts + 1`, returns the rows; a row at its 3rd expired lease becomes `rejected (processing_error)` instead. VOLATILE (a STABLE function runs read-only through PostgREST) | +| `complete_avatar_job(asset_id, byte_size, sha256)` | service_role | guard `status = 'uploaded'` (a superseded row is not completed: the worker then deletes what it wrote) → marks the caller's previous `clean` avatar `deleted` (enqueued), sets the row `clean`; one transaction; logs `asset.avatar_set` | +| `reject_avatar_job(asset_id, reason)` | service_role | guard `uploaded` → `rejected` with a closed code; logs `asset.rejected` | +| `mark_quarantine_purged(asset_id)` | service_role | nulls `quarantine_key` after the worker deleted the quarantine object of a `clean` row | +| `claim_purges(max_items)` / `ack_purge(purge_id)` | service_role | the purge queue, II.9 | Why `assets` does not absorb `anatomical_sheet_assets`: that table is content-addressed and sheet-scoped (BDR-032/034) with its own confirmed -upload path; merging would rewrite a validated model for no gain. The SVG -processor of the worker will serve it at Step 13 through a -`sanitization_status` added then. +upload path; the kinds that join `assets` later (logos, documents, client +and animal files, report files, imports) extend the `kind` CHECK and add a +predicate branch at their step. The profile pointer is derived by the +unique index rather than the pre-announced `profiles.avatar_asset_id` +column: no cross-table write, no trigger, three fewer tests; a column can be +added additively when a public profile needs a join (D5). ### II.4 Object keys -- Final: `///`. Avatar: - `profiles///avatar.webp`. The name is fixed per kind; - the user's filename never enters a key (it is stored, length-capped and - control-character-free, for display only). +- Final: `profiles///avatar.webp`. The name is fixed per + kind; the user's filename never reaches the server. - Quarantine: `quarantine///upload` in the same bucket. No API role can read it: the SELECT predicate only matches the - `object_key` of `clean` rows, the INSERT predicate only the + `object_key` of a `clean` row, the INSERT predicate only the `quarantine_key` of the caller's `pending_upload` row. -- Keys are built by the RPC from uuids; the policies compare whole strings - (no prefix match, no `storage.foldername()` so the PGlite shim and the real - stack evaluate the same expression). +- Keys are built by the RPC from uuids; the policies compare whole strings, + no prefix match, no `storage.foldername()`, so the PGlite shim and the real + stack evaluate the same expression. The asset id in the key lets the + sweeper classify a leftover without a row. - Sheet assets keep `.svg` (shared drawings, immutable versions). - Avatars are per-account and mutable: a hash key would need reference - counting for nothing. -### II.5 Upload, processing, display (avatar) +### II.5 Upload and processing (avatar) -1. Browser pre-checks (feedback only): size ≤ 5 MiB, magic bytes of - JPEG / PNG / WebP, the file decodes (`createImageBitmap`). Preview from - `URL.createObjectURL`, shown in the circle with `object-fit: cover`, - nothing uploaded yet. -2. "Enregistrer" → `begin_avatar_upload` → row + keys. -3. `storage.from('avatars').upload(quarantine_key, file, { upsert: false })` - with the user JWT. The INSERT policy on `storage.objects` accepts only - `(bucket_id = 'avatars', name = quarantine_key)` for a `pending_upload` - row owned by `auth.uid()`. +1. Browser: `File.size` ≤ 20 MiB (sanity), `createImageBitmap` decodes it + (else `unsupported_type`), draw on a canvas with the longest side capped + at 1024 px, `toBlob('image/jpeg', 0.9)`. This is transport only (phones + produce 24 MP / 8 MiB photos; a 1024 px JPEG weighs ~150 KB); the server + re-decodes and re-encodes regardless. The preview shows that blob in the + circle with `object-fit: cover`. Nothing uploaded yet. +2. "Enregistrer la photo" → `begin_avatar_upload('image/jpeg', blob.size)`. +3. `storage.from('avatars').upload(quarantine_key, blob, { upsert: false, contentType: 'image/jpeg' })` + with the user JWT. The INSERT policy accepts only + `(bucket_id = 'avatars', name = quarantine_key)` of a `pending_upload` + row owned by `auth.uid()`; `upsert` would need UPDATE and SELECT rights + the plan withholds on purpose. 4. `confirm_asset_upload(asset_id)` → `uploaded`. -5. Worker loop (every 2 s, backoff to 15 s when idle): `claim_asset_jobs(1)` - → download the quarantine object with the service client → processor. -6. Image processor: detect the type from bytes (JPEG `FF D8 FF`, PNG - 8-byte signature, WebP `RIFF….WEBP`); any other → `not_an_image`. - `sharp(bytes, { limitInputPixels: 24e6, failOn: 'error', animated: false })` - → header check (`metadata()`: format matches the magic, 64 ≤ sides ≤ 8192) - → `.rotate()` (applies EXIF orientation, then EXIF is dropped) - → `.resize(512, 512, { fit: 'cover', position: 'centre' })` - → `.webp({ quality: 82 })`, no `withMetadata()` → EXIF, XMP, IPTC and ICC - are gone. Output: one 512 × 512 WebP, sha256, byte size. -7. Worker uploads the clean bytes at `object_key` (service client), deletes - the quarantine object, calls `complete_asset_job` (clean + profile - pointer + previous avatar marked `deleted`, one transaction). On a - processor refusal: `reject_asset_job(reason)` and the quarantine object - is deleted. -8. Browser polls its own `assets` row (1 s, up to 30 s): `clean` → refresh - the profile and the signed URL; `rejected` → message from the closed - reason code; still `processing` after 30 s → "toujours en cours" with a - retry on next visit. -9. Display: `createSignedUrl(object_key, 3600)` with the user JWT. The - Storage API evaluates the SELECT policy, then signs. The URL is cached in - the auth store with its expiry and renewed five minutes before. Used as - `` in `UserBadge` (sidebar, drawer), the account section and, - if the owner approves D3, the top bar. +5. Worker loop, fixed 2 s interval: `claim_avatar_jobs(1)` → GET the + quarantine object (service client, 30 s timeout on every network call). +6. Decode child: the I/O process spawns `decode.ts` with an empty + environment (no key, `PATH` only), feeds the bytes on stdin, reads the + result on stdout, kills it with SIGKILL after 20 s. The child: type from + magic bytes (JPEG `FF D8 FF`, PNG 8-byte signature, WebP `RIFF….WEBP`), + `sharp(bytes, { limitInputPixels: 16_777_216 })` with default `failOn`, + `sharp.cache(false)`, `sharp.concurrency(1)`, `metadata()` (format matches + the magic; 64 ≤ sides ≤ 4096; the pixel-limit error maps to + `dimensions`), `.rotate()`, `.resize(512, 512, { fit: 'cover', + position: 'centre' })`, `.webp({ quality: 82 })`, no `withMetadata()`: + EXIF, XMP, IPTC and the ICC profile are not copied (colours converted to + sRGB through the profile first). Output: one 512 × 512 WebP, sha256, + byte size. Data after a PNG `IEND` is ignored by the decoder and absent + from the output. +7. I/O process: PUT the clean bytes at `object_key` (`upsert: true`, + `contentType: 'image/webp'`; idempotent on retry) → `complete_avatar_job` + (commit) → DELETE the quarantine object → `mark_quarantine_purged`. A + refusal → `reject_avatar_job(reason)`; the quarantine object is + enqueued for purge by the status trigger. A `complete` refused by the + guard (row superseded) → the worker deletes the clean object it wrote. +8. Browser polls its own row (1 s, up to 30 s): `clean` → download the + photo; `rejected` → message from the closed code; still `uploaded` after + 30 s → "Traitement en cours, revenez dans un instant"; on the next visit + the account page loads any in-flight row and shows the same state. The + save button is disabled while a row of the caller is in flight; a new + pick supersedes it. -Why no client-side resize before upload: the server re-encodes anyway and -is the boundary; a second pipeline would duplicate the crop rule and could -drift. The 5 MiB cap keeps the upload short. +Crash matrix (the retry is idempotent at every point): -### II.6 Rejection codes (closed set, phrased by i18n) +| Worker dies | Row | Objects | Recovery | +|---|---|---|---| +| before PUT clean | `uploaded`, lease set | quarantine | lease expires (10 min) → re-claim | +| after PUT clean, before complete | same | quarantine + clean | re-claim, PUT again (`upsert`), complete | +| after complete, before DELETE quarantine | `clean`, `quarantine_key` set | both | sweeper: quarantine leftovers of `clean` rows, then `mark_quarantine_purged` | +| 3rd lease expired | `rejected (processing_error)` | enqueued | purge queue | -`not_an_image`, `unsupported_type`, `too_large`, `decode_failed`, -`dimensions` (too small or too large), `svg_rejected`, `processing_error`. -The raw library message never reaches the row nor the screen; it is logged -by the worker with the asset id only. +### II.6 Read path (owner-only, no signed URL) -### II.7 SVG processor (anatomical sheets) +`storage.from('avatars').download(object_key)` with the user JWT: the +Storage API evaluates the SELECT policy, the bytes come back, the app keeps +a `URL.createObjectURL(blob)` in the auth store (revoked on change or sign +out) and uses it as `` in `UserBadge`, the account section and, if +D3 is accepted, the top bar. One download of ~30 KB per session; the +production CSP already allows `blob:` images, `connect-src` must name the +Supabase origin (already required by Step 7's API calls). -Same worker, kind `anatomical_sheet_asset`: parse with `@xmldom/xmldom` -(parse errors fatal), `sanitizeSvgRoot` from `@faunosteo/pdf` (allowlist + -caps), serialise, 20 MiB cap in and out, refusal → `svg_rejected`. The -removed element and attribute names are kept in the result (never values). -In Step 8 there is no user producer: uploads into the sheet bucket stay -operator-only until the editor step (17) and the database sheets step (13) -open a signed upload path with `sanitization_status` on -`anatomical_sheet_assets`. The processor is tested on hostile fixtures and -through the worker with the service key, so the boundary exists before the -producer does (D6). +Why not a signed URL: in Step 8 nobody but the owner reads the avatar, and a +signed URL is a bearer token that keeps serving after `remove_avatar` until +it expires. Signed URLs arrive with the first kind shared with other users +(documents, Step 9): issued by the Storage API after the SELECT policy, TTL +per kind, `download` flag for documents, query strings dropped from the +proxy access logs. + +### II.7 Rejection codes (closed set, phrased by i18n) + +Row codes: `unsupported_type`, `decode_failed`, `dimensions`, +`processing_error`. Client-side failure kinds (never rows): `too_large`, +`unsupported_type`, `rate_limited`, `storage_full`, `network`, `unknown`. +The raw library or supabase-js error never reaches a row or the screen; the +worker logs an allowlist of fields (asset id, code, duration) with control +characters escaped (LRN-044). ### II.8 Worker runtime and operations -- `apps/worker` (`@faunosteo/worker`): TypeScript, Node 24, deps - `@supabase/supabase-js`, `sharp`, `@faunosteo/pdf` (sanitiser), - `@xmldom/xmldom`. No DB driver: every database access is an RPC through - PostgREST with the service key, so one credential and one transport, and a - managed project needs no open database port. +- `apps/worker` (`@faunosteo/worker`): TypeScript run by Node 24, deps + `@supabase/supabase-js` and `sharp` only. No DB driver: every database + access is an RPC through PostgREST with the service key (one credential, + one transport; a managed project needs no open database port). +- Two processes in one container: the keyed I/O loop and the unkeyed decode + child per job (II.5 step 6). A decoder exploit lands in a process with no + key, no file access beyond stdin/stdout and a 20 s life; it can reach + Kong with anonymous rights only, which is what any browser has. - Container `faunosteo_worker` (compose service `worker`): non-root, - `read_only: true` + `tmpfs /tmp`, `mem_limit: 512m`, `pids_limit`, no - published port, `restart: unless-stopped`, healthcheck = heartbeat file - refreshed each loop. Env file `.env.worker` (`SUPABASE_URL`, + `read_only: true` + `tmpfs /tmp`, `mem_limit: 512m`, `cpus: 1`, + `pids_limit: 64`, no published port, attached to the Supabase compose + network only (`internal`, Kong reachable, nothing else; a host firewall + rule would not filter container egress), `restart: unless-stopped`. A + watchdog exits the process when one loop iteration exceeds 60 s so the + restart policy fires (Docker never restarts an `unhealthy` container on + its own). Env file `.env.worker` (`SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, `WORKER_ID`), `chmod 600`, separate from the - app `.env` which DEPLOY.md keeps non-sensitive. Egress limited to the - Supabase host (documented firewall rule). -- One job at a time, `sharp.concurrency(1)`; time is bounded by the input - caps (≤ 5 MiB, ≤ 24 MP), not by a kill switch; a crashed run is reclaimed - by `reclaim_stale_jobs` (max 3 attempts). -- Sweeper every 10 min: purge objects of `deleted` / `rejected` rows and of - abandoned uploads, remove quarantine leftovers of `clean` rows, mark - `purged_at`. Objects with no row (orphans from a crash between PUT and - RPC) are only reported; `pnpm worker reconcile --apply` deletes them after - an operator reads the dry run. -- Local dev: `pnpm worker:dev` against the local stack (service key from - `supabase status`, typed into the shell as SUPABASE.md §8 already does). -- Logging: structured lines, asset id and reason codes only; never bytes, - names or user email. + app `.env`, excluded from any backup copy of env files, readable through + `docker inspect` by the `docker` group (documented). +- Fairness: one in-flight avatar per account (begin supersedes), oldest + first → no account can queue more than one job. +- Sweeper every 10 min, two sources: (a) the purge queue (row-driven, II.9); + (b) key-driven: list `quarantine/` of the bucket, parse the asset id, + delete any object older than 3 h whose row is not `pending_upload` / + `uploaded` (covers bytes landed through a signed upload URL or a slow PUT + after the row moved on; the 3 h grace exceeds the 2 h validity of such a + URL). No operator step, no `--apply`. +- `sharp` updates: a Renovate / dependabot rule on the worker package, + not a manual chore. +- Local dev: `pnpm worker:dev` against the local stack (service key typed + into the shell as SUPABASE.md §8 already does). -### II.9 Orphans on replacement and deletion +### II.9 Purge queue, orphans, replacement, deletion -| Event | Row state | Object state | Who cleans | +`private.object_purge_queue(id, bucket_id, object_name, not_before, +enqueued_at)` fed by triggers on `assets`: a transition to `deleted` or +`rejected` enqueues `object_key` and `quarantine_key`; a row DELETE (account +cascade) enqueues them too. `not_before` = now + 48 h for the final key of a +`deleted` row (longer than any backup run, II.10), now + 1 h for quarantine +keys and rejected uploads. The sweeper calls `claim_purges(max_items)`, +deletes each object (a missing object is a success), `ack_purge(id)`. The +only automated deletions are those two sources; a `clean` row's `object_key` +is never deleted (test). + +| Event | Row | Object | Cleanup | |---|---|---|---| -| New avatar clean | new `clean`, previous `deleted` (same transaction) | previous object still present | sweeper (purge, idempotent) | -| `remove_avatar()` | `deleted`, `profiles.avatar_asset_id = null` | present until purge | sweeper | -| Upload never confirmed | `pending_upload` | maybe present | sweeper after 24 h | -| Worker dies after PUT clean, before `complete` | `processing` → reclaimed | clean object present | retry: `upsert: true` on the same deterministic key, then `complete` | -| Worker dies after `complete`, before quarantine DELETE | `clean`, `quarantine_key` set | quarantine present | sweeper (quarantine leftovers of clean rows) | -| Account deleted (Step 26) | rows cascade | objects orphaned | reconcile; Step 26 will mark then purge before dropping rows | +| New avatar clean | new `clean`, previous `deleted` (same transaction) | previous object kept 48 h | queue | +| `remove_avatar()` | clean and in-flight rows `deleted` | kept 48 h | queue | +| New pick while in flight | superseded row `deleted` | its bytes, if any | queue; a `complete` for it is refused | +| Upload never confirmed | `pending_upload` superseded or expired by the next begin / after 24 h | maybe present | queue | +| Bytes landed after the row moved on | none or not pending | present | key-driven sweep after 3 h | +| Account deleted (Step 26) | rows cascade | enqueued by the DELETE trigger | queue | -Access is always cut by the row: a `deleted` or `rejected` row matches no -read predicate, whatever the object's fate. The object lifetime is an -eventual-consistency concern handled by the sweeper and verified by -`reconcile` (lists objects vs rows per bucket, dry run by default). +Access is cut by the row: a `deleted` or `rejected` row matches no read +predicate, and no URL outlives the policy check in Step 8 (download, not +signing). Object lifetime is eventual, bounded by the grace periods. + +Reconciliation (operator, documented in STORAGE.md, not a tool): one SQL +anti-join between `storage.objects` and `assets` (same database) lists +objects without a row and rows without an object per bucket; sheet assets +are checked against `anatomical_sheet_assets`. Reading only; deletions stay +row-driven. ### II.10 Backups and restore on the VPS (self-hosted) - Storage backend `file` on a named volume `faunosteo_supabase_storage` - (kept across renames, BDR-035). One VPS, one disk, no extra service. The - S3 backend (Scaleway Object Storage) remains available when the volume - outgrows the disk or a second host appears: copy the files, change the - backend env, rows unchanged. -- Backup order: database first (`pg_dump` of the whole instance, the - `storage` schema included), files second (restic snapshot of the volume - to Scaleway Object Storage, encrypted, 7 daily / 4 weekly / 6 monthly). - Dumping the rows first guarantees every row in the dump has its file in - the snapshot; files newer than the dump are extra and show up in - `reconcile` as orphans. -- Restore: stop the worker, restore the database, restore the volume, start - the stack, run `pnpm worker reconcile` (dry run), decide on the report. -- Runbook delivered by this step (`docs/development/STORAGE.md`, pointer in - DEPLOY.md); the owner runs it. Claude never runs a backup, restore or - transfer tool. A restore drill on the local stack is part of the manual - validation. + (kept across renames, BDR-035), on a filesystem separate from the + PostgreSQL volume with a quota, and a disk-usage alert: the VPS hosts + other products, a full disk would take PostgreSQL down with it. The S3 + backend (Scaleway Object Storage) remains the alternative when the volume + outgrows the disk: copy the files, change the backend env, rows unchanged. +- Global ceiling: `private.storage_ceiling()` (constant, 10 GiB to start) + checked by `begin_avatar_upload` on top of the per-account rate. +- Backup order: database dump first (whole instance, `storage` schema + included), files second. With the 48 h purge grace, every `clean` row of + the dump still has its object in the snapshot, provided the snapshot runs + within 48 h of the dump (the invariant the restore checks: every `clean` + row has an object). +- Restore: stop the worker, start the database, restore the dump, restore + the volume, start the rest, run the reconciliation query, start the + worker. Files newer than the dump have no row and are invisible to the + Storage API (it lists from `storage.objects`); the directory listing of + the volume against `storage.objects` finds them. +- Tooling (restic to Scaleway Object Storage, encrypted, dump in the same + run, write-only key with retention pruned from another host, the + Supabase secrets `JWT_SECRET` / `POSTGRES_PASSWORD` in the encrypted set, + `.env.worker` never in a plaintext copy) and the restore drill belong to + the self-hosted deployment runbook (plan Step 27 "backup/restore + rehearsal"). Step 8 writes the ordering, the invariant and the backend + choice in `STORAGE.md`; the owner runs every backup or restore command. -### II.11 Migration to managed Supabase +### II.11 Migration to managed Supabase (runbook, no tool in Step 8) -- Schema: the same migrations (`supabase db push`); buckets and policies - are SQL and apply on managed. The `storage` schema itself is never dumped - into managed: `storage.objects` rows are re-created by the uploads. -- Objects: operator command `pnpm worker migrate --from --to ` - (two service keys from env), driven by `assets` and - `anatomical_sheet_assets`: for every `clean` / confirmed row, download, - verify sha256, upload at the same key, verify; report. Then `reconcile` - on the destination. Everything is verifiable because every object has a - row with its hash. -- Worker and app: change `SUPABASE_URL` / keys. No code change. -- Not used on purpose because managed meters or lacks them: image - transformations (imgproxy), Edge Functions, Realtime. +Order: freeze writes (stop the worker, maintenance notice); migrate the +schema (`supabase db push`, buckets and policies are SQL; the `storage` +schema itself is never dumped into managed); migrate the data rows +(`auth.users` through the Supabase auth migration path, then `public`: +profiles, roles, sheets, `assets`); copy the objects driven by the rows +(`assets` and `anatomical_sheet_assets`: for every `clean` / confirmed row, +download, verify sha256, upload at the same key, verify; paginate by keyset, +PostgREST caps a set at 1000 rows); run the reconciliation query on the +destination; switch `SUPABASE_URL` and the keys of the app and the worker; +resume. The service key of a self-hosted stack is a long-lived JWT: revoking +it means rotating `JWT_SECRET` (every key and session); documented, and a +reason to prefer managed secret keys once there. ### II.12 UI (follows the validated mockup, no redesign) - Mon compte → Informations personnelles: avatar circle (photo, else the - monogram) with "Modifier la photo" under it, as drawn. Picking a file - shows the local preview in the circle with "Enregistrer la photo" / - "Annuler"; after saving, the circle shows a "Traitement en cours…" state + monogram from `UserBadge`) with "Modifier la photo" under it, as drawn. + Picking a file shows the local preview in the circle with "Enregistrer la + photo" / "Annuler"; after saving, the circle shows "Traitement en cours…" until the row is `clean`; "Supprimer la photo" appears when a photo - exists. Errors use `account.avatar.error.`. + exists (one confirmation). Errors use `account.avatar.error.`. - `UserBadge` (sidebar + drawer): photo when present, monogram otherwise. - Top bar (D3): the mockup shows avatar + name with a chevron on desktop and the avatar alone on mobile; Step 7 shipped the bar without a user element. Proposal: add the avatar (and the name on desktop) as a link to Mon - compte, no dropdown yet (the menu's content is undefined). Decision for - the owner. + compte, no dropdown (its content is undefined). Decision for the owner. - Dashboard unchanged (the mockup shows no avatar in the content area). -- Accepted inputs: JPEG, PNG, WebP; never SVG for avatars. +- Accepted inputs at the picker: JPEG, PNG, WebP; never SVG for avatars. + What the browser cannot decode is refused there with `unsupported_type`; + what it decodes is sent as JPEG and judged again by the worker. --- ## Part III — The ten security questions -1. **Access control**: the `assets` row is the authority. `storage.objects` - policies call `private.can_read_object(uid, bucket, name)` / - `private.can_upload_object(uid, bucket, name)` which look the key up in - `assets` (status, owner, kind) and dispatch per kind to the owning - domain's helper. Step 8 implements the `profile_avatar` branch (owner - only); every other kind returns false. Buckets without policy are - unreachable by API roles. -2. **No cross-user access**: the read predicate requires a `clean` row - whose `owner_id = auth.uid()` (avatar branch) and whose `object_key` - equals the requested name; keys contain the owner's uuid but the policy - never trusts the path, only the row. Listing is denied the same way - (SELECT policy). pgTAP: Bob reads nothing of Alice, cannot upload at her - key, cannot confirm her row, cannot sign her URL (real-stack e2e). -3. **Keys**: server-built from uuids by the RPC - (`profiles///avatar.webp`, `quarantine///upload`), - canonical file name per kind, user filename never in a key, policies - compare whole strings. -4. **Signed URLs**: issued by the Storage API after the SELECT policy, with - the user's JWT; TTL per kind in one table (`profile_avatar: 3600 s`), - cached client-side until five minutes before expiry; no `download` - flag, no transform, no public URL. A signed URL is a bearer token until - expiry: accepted for a 512 px avatar, documented; documents (Step 9) get - 60 s and `download`. -5. **Quarantine**: upload lands under `quarantine/` with the row in +1. **Access control**: the `assets` row is the authority. The two policies + on `storage.objects` are bucket-scoped + (`bucket_id = 'avatars' and private.can_read_avatar_object(uid, name)`, + same for upload) and look the key up in `assets` (status, owner, kind). + A bucket without policy is unreachable by API roles; the census pins one + bucket literal per policy and the counts. +2. **No cross-user access**: the read predicate requires a `clean` row with + `owner_id = auth.uid()` whose `object_key` equals the requested name; the + path is never trusted, only the row. Listing is denied the same way. + pgTAP: Bob reads nothing of Alice, cannot upload at her key, cannot + confirm her row; real-stack e2e: Bob's `download` of Alice's key → 400. +3. **Keys**: server-built from uuids by the RPC, canonical file name per + kind, no user filename anywhere, whole-string comparison in the policies. +4. **Signed URLs**: not used in Step 8. An owner-only avatar is read by + `download` under RLS and shown through a blob URL, so no bearer token + exists and a removed avatar stops being readable at the row flip. When a + shared kind arrives (documents, Step 9): Storage API signing after the + SELECT policy, TTL per kind (60 s and `download` for documents), query + strings dropped from access logs, the row cuts signing and the purge cuts + serving. +5. **Quarantine**: upload lands under `quarantine/` with the row `pending_upload` → `uploaded`; no API role can read it; only the worker - (service key) reads it, writes the clean bytes under the final key, - deletes the quarantine object. Status machine and every transition are - RPCs; the browser cannot set `clean`. -6. **Dangerous SVG**: the existing allowlist sanitiser (elements, - attributes, in-document `href` / `url(#)` only, no backslash, no - `