From aea8902711bc544155dca260c9e4ec7ceda4cae0 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:42:42 +0200 Subject: [PATCH 1/7] docs(docs): anatomical sheet model spec (Step 4) + TODO plan --- .claude/tasks/TODO.md | 10 +- docs/development/ANATOMICAL_SHEET_MODEL.md | 270 +++++++++++++++++++++ 2 files changed, 279 insertions(+), 1 deletion(-) create mode 100644 docs/development/ANATOMICAL_SHEET_MODEL.md diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 1fcf7502..de7853a6 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -61,7 +61,15 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 3.8 CI: supabase job (start, db reset, test db, gen types diff); check job runs PGlite suite via pnpm -r - [x] 3.9 docs: docs/development/SUPABASE.md (start/reset/test/types/bootstrap owner), CLAUDE.md folder map + scopes, README pointer - [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006 -- [ ] Step 4 — sheet model + importer (next, on validation; ∥ Step 3 per plan) +- [ ] Step 4 — canonical anatomical sheet model (2026-10-08, branch feature/step-04-anatomical-sheet-model). Scope re-split: model + validation + persistence + tests here; legacy importer → official equine DRAFT + import report = next step (user: no full import yet, draft verified before publication). Spec: docs/development/ANATOMICAL_SHEET_MODEL.md + - [x] 4.0 context + spec: business §2.6–2.9/§7/§16/§17.3/§23, OPEN_QUESTIONS C1/C2/C8/C9/Q3/Q5/Q9, audit 07; ANATOMICAL_SHEET_MODEL.md written + - [ ] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability + - [ ] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS + - [ ] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish + - [ ] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test + - [ ] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG + - [ ] 4.6 verify: pnpm check (typecheck, test:run, lint, build), db:reset + db:test on real stack, fresh verifier + security gate; capitalize BDR/LRN/EVAL +- [ ] Step 4b — legacy importer → official equine sheet as DRAFT (document.json + legacy-id-map + IMPORT-REPORT.md for business verification), publication after user validation --- diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md new file mode 100644 index 00000000..025a881b --- /dev/null +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -0,0 +1,270 @@ +# Anatomical sheet model (Step 4) + +Status: Step 4 deliverable, 2026-10-08. Source of truth for the canonical +"fiche anatomique": the JSON document, its validation rules, the PostgreSQL +tables that persist it, and the lifecycle rules (versions, copies, deletion). +Decisions it applies: business architecture §2.6–§2.9, §7, §16, §17.3, +§23.2; `OPEN_QUESTIONS.md` C1, C2, C8, C9, Q3, Q5, Q9 as decided on +2026-10-08 (equine only, two SVG assets, import anomalies land in a draft, +manual report points confirmed). + +Out of scope here: the legacy importer and the official equine draft +(next step), the visual editor, cloud reports, community, booking. + +## 1. Two layers + +| Layer | Where | Role | +|---|---|---| +| Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). | +| Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. | + +The database stores the document as JSONB in +`anatomical_sheet_versions.content`. Zod is the shape contract at the +application boundary; SQL checks what only SQL can know (species of the +parent sheet, assets registered for the sheet, immutability, numbering) plus +the referential rules of §3 at publication time, so a browser cannot publish +a dangling document. + +## 2. Canonical document (schema_version 1) + +Every id is a **stable id**: `^[a-z0-9][a-z0-9_-]{0,63}$`, never derived +from a label, never changed by a translation. Vertebral region codes are +the one exception: `^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$`, because the +practitioner reads them as-is (`C`, `T`, `L`, `S`, `Cd`). Labels are `LocalizedText` +objects `{ fr, en }` (both required) or `LocalizedOptionalText` `{ fr?, en? }`. +Adding a locale later means adding an optional key, not a new field family. + +```text +AnatomicalSheetDocument +├─ schema_version: 1 +├─ species_id: stable id (row of public.species) +├─ name: LocalizedText display name of the sheet +├─ description: LocalizedOptionalText +├─ scope_disclaimer: LocalizedOptionalText legal scope text shown once per session and in the PDF +├─ attribution: { authors: string[], license: string | null, notes: string | null } +├─ vertebral_config: { regions: VertebralRegion[] } ORDERED; codes free (C/T/L/S/Cd for the horse) +│ VertebralRegion = { code, name: LocalizedText, count ≥ 1 } +├─ categories: AnnotationCategory[] { id, name: LocalizedText, color: '#rrggbb' | null } +├─ views: SheetView[] +│ main: { id, kind: 'main', name, svg_asset_id: uuid | null, view_box: ViewBox | null } +│ detail: { id, kind: 'detail', name, parent_view_id, svg_asset_id: uuid | null, view_box: ViewBox | null } +│ ViewBox = { min_x, min_y, width > 0, height > 0 } +├─ annotations: Annotation[] +│ common: { id, view_id, category_id, laterality, geometry: Geometry | null } +│ point | zone: + { name: LocalizedText, finding_zone_id: id | null, vertebral_region_code: code | null } +│ detail_trigger: + { name: LocalizedText | null, opens_view_id } +│ laterality ∈ unpaired | bilateral | left | right +│ Geometry = circle { cx, cy, r } | polygon { points: [x, y][] ≥ 3 } | path { d } +└─ finding_zones: FindingZone[] + FindingZone = { id, name: LocalizedText, categories: FindingCategory[] } + FindingCategory = { id, kind: dysfunction | observation | anamnesis | custom, name, description?, children: FindingNode[] } + FindingNode = { id, name, description?, requires_vet_referral?, sources?, children? } (recursive) + SourceRef = { type: manual | journal | database | web, citation, url? } +``` + +Why these shapes: + +- **Views are a tree**, not a `details.head` field. A detail view names its + parent; a `detail_trigger` annotation in the parent opens it. Nesting depth + is free (§7.3). `svg_asset_id` is nullable on a detail view: null means + "render the parent's asset with this `view_box`" (C9). The equine seed will + keep two assets (Q5), so both forms are exercised. +- **Laterality is explicit** on every annotation. `bilateral` = one drawing + stands for both sides, the report picks the side (today's behaviour); + `left` / `right` = the drawing shows one side; `unpaired` = no side. + Absence of attribute no longer carries meaning. +- **Spine regions are data.** `vertebral_config.regions` is an ordered list + with free codes (C1, Q3). An annotation that opens the vertebra picker + carries `vertebral_region_code`; no label parsing (`regionFromLabel` stays + in the importer). +- **Annotation → findings is one explicit field**, `finding_zone_id`. No + FR/EN matching at runtime (§23.2). Several annotations may share a zone; + a `detail_trigger` never has one (it is navigation, not an observation). +- **Finding categories carry a `kind`** so the three business buckets + (dysfonctions ostéopathiques, observations / motifs de consultation, + anamnèse / facteurs rapportés) are typed, and creators may add `custom` + ones (§7.4). Node ids are unique among siblings; a finding is referenced + by `(finding_zone_id, path[])` exactly as `Finding.path` does today, so + the Step 5 report adapter is a rename, not a re-keying. +- **Tree nodes are lean on input, total on output**: `description`, + `requires_vet_referral`, `sources`, `children` are optional in the JSON + and defaulted by the parser (612 leaves would otherwise carry four empty + keys each). Structural records (views, annotations) use explicit `null`. +- The parser is **strict**: unknown keys are rejected. A canonical document + must not silently carry fields no version of the schema defines. + +### 2.1 Validation tiers + +| Tier | Function | When | +|---|---|---| +| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | +| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` | +| Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below | + +`SheetIssue = { code, severity: 'error' | 'warning', path, message }`; the +path names the offending field (`annotations[0].category_id`), the later +entry for a duplicate, the item itself for `view.unreachable` and +`finding_zone.unreferenced`. + +Integrity rules (error unless stated): + +| Code | Rule | +|---|---| +| `view.main.count` | exactly one `main` view | +| `view.id.duplicate` | view ids unique | +| `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view | +| `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view | +| `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` | +| `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) | +| `annotation.view.missing` | `view_id` exists | +| `annotation.category.missing` | `category_id` exists | +| `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view | +| `annotation.finding_zone.missing` | `finding_zone_id` exists | +| `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` | +| `annotation.no_findings` (warning) | point / zone without `finding_zone_id` | +| `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness | +| `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) | +| `finding_zone.unreferenced` (warning) | zone no annotation points to | + +A draft may be saved with errors. Publishing a document with errors is +refused in TypeScript (`assertPublishable`) and in SQL +(`private.sheet_document_issues`), which re-checks every error-level rule +except the two recursive ones (parent cycle, sibling uniqueness) and adds +"every `svg_asset_id` is an asset of this sheet". + +## 3. Relational model + +```text +public.species reference data, seeded by the migration (equine) +public.anatomical_sheets identity, owner, visibility, status, provenance, current version +public.anatomical_sheet_versions numbered versions, status draft | published | deprecated, content jsonb +public.anatomical_sheet_assets SVG files, content-addressed (sha256), per sheet +audit.audit_logs every lifecycle event (private.log_event) +``` + +### `species` + +`id text` (stable id), `name_fr`, `name_en`, `sort_order`, `active`. Read by +any authenticated user; no write path through the API (platform step later). + +### `anatomical_sheets` + +| Column | Notes | +|---|---| +| `id uuid` | | +| `species_id` | FK species | +| `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets | +| `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) | +| `is_official boolean` | only a platform admin can create one; editable by platform admins | +| `visibility` | enum `sheet_visibility`: `private` \| `public` | +| `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) | +| `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source | +| `current_version_id` | latest published version (nullable while draft-only) | +| `archived_at`, `deleted_at`, `created_at`, `updated_at` | | + +### `anatomical_sheet_versions` + +| Column | Notes | +|---|---| +| `id uuid`, `sheet_id` | | +| `version_number int` | unique per sheet, assigned by the server (`max + 1`) | +| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | +| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | +| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` | +| `change_note text` | what changed in this version | +| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | +| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | + +Rules enforced by triggers (every role, including the table owner): + +- **One draft per sheet** (partial unique index, C8). +- **Published rows are immutable**: the only accepted UPDATE on a + `published` row is the transition to `deprecated` (status, `deprecated_at`, + `deprecated_by`); any other column change raises `42501`. A `deprecated` + row is frozen. +- **Deletion preconditions** (BEFORE DELETE): never a `published` row; never + the `current_version_id` of its sheet; never a version some sheet is + `based_on`; (reports: added when the table exists, §16). A `draft` has no + dependents and can be dropped by its editor. +- **Document ↔ row**: `content->>'species_id'` equals the sheet's species. + +### `anatomical_sheet_assets` + +`id uuid`, `sheet_id`, `sha256 text` (64 hex), `byte_size int`, +`content_type text` (`image/svg+xml` only for now), `file_name text`, +`created_by`, `created_at`. Unique `(sheet_id, sha256)`. Assets are +immutable and **content-addressed**: the bytes live in Storage under +`anatomical-sheet-assets/.svg` (bucket and policies arrive with the +importer step; until then the path is a convention, not a row). Two sheets +with the same SVG share one object; a copy of a sheet copies the metadata +rows only. Deleting an asset referenced by a version is refused (FK restrict +is not possible on a JSONB reference, so the delete RPC checks every +version's views). + +### 3.1 Lifecycle (RPCs, security definer, audited) + +| RPC | Actor | Effect | +|---|---|---| +| `create_anatomical_sheet(species_id, name, slug, description, visibility, official, document)` | any active user; `official = true` needs platform admin | sheet + draft v1 | +| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, content copied from `from_version_id` (default: current version); refused if a draft exists | +| `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | +| `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | +| `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | +| `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched | +| `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor | +| `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while any version has dependents | +| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | + +Direct table access for `authenticated`: SELECT through the policies below; +UPDATE of `content` / `change_note` on **own draft** rows (the future editor +autosaves with a PATCH); DELETE of own draft rows. Everything else is RPC. + +### 3.2 Access helpers (`private`, security definer) + +| Helper | True when | +|---|---| +| `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) | +| `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`) — grants and follows plug in here at the community step | + +Policies: + +| Table | SELECT | INSERT / UPDATE / DELETE | +|---|---|---| +| `species` | authenticated, `active` rows | none | +| `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | none (RPC) | +| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` and DELETE on own drafts; INSERT via RPC | +| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | + +`anon` gets nothing. Public discovery views for the public site come with +the community step (§17.4). + +## 4. What the model guarantees (acceptance criteria) + +| Criterion | Where it is proven | +|---|---| +| A sheet with several views and annotations explicitly linked to findings | `packages/domain/tests/fixtures/horse-slice.ts` (2 views, trigger, spine region, bilateral joint, 3 finding kinds); schema + integrity tests | +| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged | +| Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501`, for the editor, for a platform admin and for the owner role | +| New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves | +| Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged | +| Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` | +| Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets | +| Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack | +| Previous tests pass | root `pnpm check` | + +## 5. Decisions left to the user + +1. **Follow = permission to use a public sheet** (§2.9) is not yet modelled: + today every authenticated user can use any public active sheet. Grants + and follows will narrow `can_use_sheet` at the community step. +2. **Who may create sheets**: any active account for now. Should creation + wait for professional verification (Step 7)? +3. **Deprecation policy**: publishing v2 does not deprecate v1. Should it, + automatically, or stay a manual act? +4. **Table name `anatomical_sheet_assets` and the content-addressed Storage + layout** (`.svg`): confirm before the importer writes files. +5. **Official equine sheet owner**: platform-owned (`creator_user_id = null`, + `is_official = true`, edited by platform admins) or owned by the client's + account? +6. **Finding category kind naming**: `observation` collides with the report + "Observation" (OPEN_QUESTIONS C7). Alternative: `consultation_reason`. From 36812f4625ad3041acbd40cd14197ac3cfb6ebc8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:42:42 +0200 Subject: [PATCH 2/7] feat(domain): canonical anatomical sheet document, integrity rules, tests --- packages/domain/eslint.config.js | 20 + packages/domain/package.json | 32 ++ .../domain/src/anatomical-sheet/create.ts | 43 ++ packages/domain/src/anatomical-sheet/index.ts | 3 + .../domain/src/anatomical-sheet/schema.ts | 280 +++++++++++ .../domain/src/anatomical-sheet/validate.ts | 426 +++++++++++++++++ packages/domain/src/index.ts | 1 + .../tests/anatomical-sheet.schema.test.ts | 117 +++++ .../tests/anatomical-sheet.validate.test.ts | 426 +++++++++++++++++ packages/domain/tests/fixtures/horse-slice.ts | 443 ++++++++++++++++++ packages/domain/tsconfig.json | 21 + packages/domain/vitest.config.ts | 9 + pnpm-lock.yaml | 28 ++ 13 files changed, 1849 insertions(+) create mode 100644 packages/domain/eslint.config.js create mode 100644 packages/domain/package.json create mode 100644 packages/domain/src/anatomical-sheet/create.ts create mode 100644 packages/domain/src/anatomical-sheet/index.ts create mode 100644 packages/domain/src/anatomical-sheet/schema.ts create mode 100644 packages/domain/src/anatomical-sheet/validate.ts create mode 100644 packages/domain/src/index.ts create mode 100644 packages/domain/tests/anatomical-sheet.schema.test.ts create mode 100644 packages/domain/tests/anatomical-sheet.validate.test.ts create mode 100644 packages/domain/tests/fixtures/horse-slice.ts create mode 100644 packages/domain/tsconfig.json create mode 100644 packages/domain/vitest.config.ts diff --git a/packages/domain/eslint.config.js b/packages/domain/eslint.config.js new file mode 100644 index 00000000..242d5a31 --- /dev/null +++ b/packages/domain/eslint.config.js @@ -0,0 +1,20 @@ +import globals from 'globals' +import tseslint from 'typescript-eslint' + +export default tseslint.config( + { ignores: ['node_modules/**'] }, + { + files: ['**/*.ts'], + extends: [...tseslint.configs.recommended], + languageOptions: { + globals: { ...globals.node, ...globals.es2022 }, + }, + rules: { + '@typescript-eslint/no-explicit-any': 'warn', + '@typescript-eslint/no-unused-vars': [ + 'error', + { argsIgnorePattern: '^_' }, + ], + }, + }, +) diff --git a/packages/domain/package.json b/packages/domain/package.json new file mode 100644 index 00000000..9eee014e --- /dev/null +++ b/packages/domain/package.json @@ -0,0 +1,32 @@ +{ + "name": "@faunosteo/domain", + "version": "0.1.0", + "private": true, + "description": "Faunosteo pure domain model: canonical anatomical sheet document, Zod schemas and integrity rules", + "license": "MIT", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./anatomical-sheet": "./src/anatomical-sheet/index.ts" + }, + "scripts": { + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest", + "test:run": "vitest run", + "lint": "eslint . --max-warnings 0", + "build": "tsc -p tsconfig.json --noEmit" + }, + "dependencies": { + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^20.19.41", + "eslint": "^9.17.0", + "globals": "^15.14.0", + "typescript": "^5.7.2", + "typescript-eslint": "^8.19.0", + "vitest": "^3.2.7" + } +} diff --git a/packages/domain/src/anatomical-sheet/create.ts b/packages/domain/src/anatomical-sheet/create.ts new file mode 100644 index 00000000..cc61873d --- /dev/null +++ b/packages/domain/src/anatomical-sheet/create.ts @@ -0,0 +1,43 @@ +import { + AnatomicalSheetDocumentSchema, + SHEET_DOCUMENT_SCHEMA_VERSION, + type AnatomicalSheetDocument, + type LocalizedText, +} from './schema' + +export interface NewSheetDocumentParams { + species_id: string + name: LocalizedText +} + +export const MAIN_VIEW_ID = 'view-main' + +/** + * Starting point of a new sheet: shape-valid so it can be saved as a draft + * at once, but not publishable until the main view gets its SVG asset. + */ +export function createEmptySheetDocument( + params: NewSheetDocumentParams, +): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse({ + schema_version: SHEET_DOCUMENT_SCHEMA_VERSION, + species_id: params.species_id, + name: params.name, + description: {}, + scope_disclaimer: {}, + attribution: { authors: [], license: null, notes: null }, + vertebral_config: { regions: [] }, + categories: [], + views: [ + { + id: MAIN_VIEW_ID, + kind: 'main', + name: { fr: 'Vue principale', en: 'Main view' }, + svg_asset_id: null, + view_box: null, + }, + ], + annotations: [], + finding_zones: [], + }) +} diff --git a/packages/domain/src/anatomical-sheet/index.ts b/packages/domain/src/anatomical-sheet/index.ts new file mode 100644 index 00000000..0e850af9 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/index.ts @@ -0,0 +1,3 @@ +export * from './schema' +export * from './validate' +export * from './create' diff --git a/packages/domain/src/anatomical-sheet/schema.ts b/packages/domain/src/anatomical-sheet/schema.ts new file mode 100644 index 00000000..7bdaaf70 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/schema.ts @@ -0,0 +1,280 @@ +import { z } from 'zod' + +/** + * Canonical anatomical sheet document, schema_version 1. + * + * Shape contract of docs/development/ANATOMICAL_SHEET_MODEL.md §2. Every + * object is strict: a canonical document must not silently carry fields no + * version of the schema defines. Cross-references (view ids, zone ids…) are + * checked by validateSheetDocument, not here, so a draft with dangling + * references can still be saved. + */ + +export const SHEET_DOCUMENT_SCHEMA_VERSION = 1 + +/** Ids are never derived from labels, so translations never move them. */ +export const STABLE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/ + +export const StableIdSchema = z.string().regex(STABLE_ID_PATTERN) + +/** Region codes are free (C, T, L, S, Cd for the horse), case included. */ +export const RegionCodeSchema = z + .string() + .regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/) + +export const LocalizedTextSchema = z + .object({ fr: z.string().min(1), en: z.string().min(1) }) + .strict() + +export const LocalizedOptionalTextSchema = z + .object({ fr: z.string().optional(), en: z.string().optional() }) + .strict() + +export const VertebralRegionSchema = z + .object({ + code: RegionCodeSchema, + name: LocalizedTextSchema, + count: z.number().int().min(1), + }) + .strict() + +const HexColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/) + +export const AnnotationCategorySchema = z + .object({ + id: StableIdSchema, + name: LocalizedTextSchema, + color: HexColorSchema.nullable(), + }) + .strict() + +const CoordinateSchema = z.number().finite() + +export const ViewBoxSchema = z + .object({ + min_x: CoordinateSchema, + min_y: CoordinateSchema, + width: CoordinateSchema.positive(), + height: CoordinateSchema.positive(), + }) + .strict() + +/** Null asset on a detail view means "parent asset cropped by view_box". */ +const viewCommon = { + id: StableIdSchema, + name: LocalizedTextSchema, + svg_asset_id: z.string().uuid().nullable(), + view_box: ViewBoxSchema.nullable(), +} + +const MainViewSchema = z + .object({ ...viewCommon, kind: z.literal('main') }) + .strict() + +const DetailViewSchema = z + .object({ + ...viewCommon, + kind: z.literal('detail'), + parent_view_id: StableIdSchema, + }) + .strict() + +/** Views form a tree: a detail names its parent, any depth. */ +export const SheetViewSchema = z.discriminatedUnion('kind', [ + MainViewSchema, + DetailViewSchema, +]) + +const CircleSchema = z + .object({ + type: z.literal('circle'), + cx: CoordinateSchema, + cy: CoordinateSchema, + r: CoordinateSchema.positive(), + }) + .strict() + +const PolygonSchema = z + .object({ + type: z.literal('polygon'), + points: z.array(z.tuple([CoordinateSchema, CoordinateSchema])).min(3), + }) + .strict() + +const PathSchema = z + .object({ type: z.literal('path'), d: z.string().min(1) }) + .strict() + +export const GeometrySchema = z.discriminatedUnion('type', [ + CircleSchema, + PolygonSchema, + PathSchema, +]) + +/** Explicit on every annotation: absence no longer carries meaning. */ +export const LateralitySchema = z.enum([ + 'unpaired', + 'bilateral', + 'left', + 'right', +]) + +const annotationCommon = { + id: StableIdSchema, + view_id: StableIdSchema, + category_id: StableIdSchema, + laterality: LateralitySchema, + geometry: GeometrySchema.nullable(), +} + +/** Observable annotations link to findings through one explicit field. */ +const observableFields = { + ...annotationCommon, + name: LocalizedTextSchema, + finding_zone_id: StableIdSchema.nullable(), + vertebral_region_code: RegionCodeSchema.nullable(), +} + +const PointAnnotationSchema = z + .object({ ...observableFields, kind: z.literal('point') }) + .strict() + +const ZoneAnnotationSchema = z + .object({ ...observableFields, kind: z.literal('zone') }) + .strict() + +/** Navigation only: a trigger never carries findings. */ +const DetailTriggerAnnotationSchema = z + .object({ + ...annotationCommon, + kind: z.literal('detail_trigger'), + name: LocalizedTextSchema.nullable(), + opens_view_id: StableIdSchema, + }) + .strict() + +export const AnnotationSchema = z.discriminatedUnion('kind', [ + PointAnnotationSchema, + ZoneAnnotationSchema, + DetailTriggerAnnotationSchema, +]) + +export const SourceRefSchema = z + .object({ + type: z.enum(['manual', 'journal', 'database', 'web']), + citation: z.string().min(1), + url: z.string().url().optional(), + }) + .strict() + +export type SourceRef = z.infer +export type LocalizedText = z.infer +export type LocalizedOptionalText = z.infer + +/** Parsed node: every optional key of the authoring form is filled in. */ +export interface FindingNode { + id: string + name: LocalizedText + description: LocalizedOptionalText + requires_vet_referral: boolean + sources: SourceRef[] + children: FindingNode[] +} + +/** Authoring form: leaves stay lean, hundreds of them carry no empty keys. */ +export interface FindingNodeInput { + id: string + name: LocalizedText + description?: LocalizedOptionalText + requires_vet_referral?: boolean + sources?: SourceRef[] + children?: FindingNodeInput[] +} + +export const FindingNodeSchema: z.ZodType< + FindingNode, + z.ZodTypeDef, + FindingNodeInput +> = z.lazy(() => + z + .object({ + id: StableIdSchema, + name: LocalizedTextSchema, + description: LocalizedOptionalTextSchema.default({}), + requires_vet_referral: z.boolean().default(false), + sources: z.array(SourceRefSchema).default([]), + children: z.array(FindingNodeSchema).default([]), + }) + .strict(), +) + +/** Typed business buckets; creators may add their own as 'custom'. */ +export const FindingCategoryKindSchema = z.enum([ + 'dysfunction', + 'observation', + 'anamnesis', + 'custom', +]) + +export const FindingCategorySchema = z + .object({ + id: StableIdSchema, + kind: FindingCategoryKindSchema, + name: LocalizedTextSchema, + description: LocalizedOptionalTextSchema.default({}), + children: z.array(FindingNodeSchema), + }) + .strict() + +export const FindingZoneSchema = z + .object({ + id: StableIdSchema, + name: LocalizedTextSchema, + categories: z.array(FindingCategorySchema), + }) + .strict() + +const AttributionSchema = z + .object({ + authors: z.array(z.string().min(1)), + license: z.string().min(1).nullable(), + notes: z.string().min(1).nullable(), + }) + .strict() + +const VertebralConfigSchema = z + .object({ regions: z.array(VertebralRegionSchema) }) + .strict() + +export const AnatomicalSheetDocumentSchema = z + .object({ + schema_version: z.literal(SHEET_DOCUMENT_SCHEMA_VERSION), + species_id: StableIdSchema, + name: LocalizedTextSchema, + description: LocalizedOptionalTextSchema, + scope_disclaimer: LocalizedOptionalTextSchema, + attribution: AttributionSchema, + vertebral_config: VertebralConfigSchema, + categories: z.array(AnnotationCategorySchema), + views: z.array(SheetViewSchema), + annotations: z.array(AnnotationSchema), + finding_zones: z.array(FindingZoneSchema), + }) + .strict() + +export type AnatomicalSheetDocument = z.output< + typeof AnatomicalSheetDocumentSchema +> +export type AnatomicalSheetDocumentInput = z.input< + typeof AnatomicalSheetDocumentSchema +> +export type VertebralRegion = z.infer +export type AnnotationCategory = z.infer +export type ViewBox = z.infer +export type SheetView = z.infer +export type Geometry = z.infer +export type Laterality = z.infer +export type Annotation = z.infer +export type FindingCategoryKind = z.infer +export type FindingCategory = z.output +export type FindingZone = z.output diff --git a/packages/domain/src/anatomical-sheet/validate.ts b/packages/domain/src/anatomical-sheet/validate.ts new file mode 100644 index 00000000..473de443 --- /dev/null +++ b/packages/domain/src/anatomical-sheet/validate.ts @@ -0,0 +1,426 @@ +import type { + AnatomicalSheetDocument, + Annotation, + FindingNode, + SheetView, +} from './schema' + +/** + * Integrity tier of the sheet model (ANATOMICAL_SHEET_MODEL.md §2.1). + * + * The shape tier (Zod) accepts dangling references so drafts can be saved + * mid-edit; this tier lists every inconsistency for the editor and gates + * publication. Each rule is one function; codes are part of the contract + * shared with the SQL re-check (private.sheet_document_issues). + */ + +export type SheetIssueSeverity = 'error' | 'warning' + +export interface SheetIssue { + code: string + severity: SheetIssueSeverity + path: string + message: string +} + +type Rule = (doc: AnatomicalSheetDocument) => SheetIssue[] + +type ObservableAnnotation = Exclude +type TriggerAnnotation = Extract +type DetailView = Extract + +/** A sibling level of the finding tree: categories or node children. */ +interface FindingLevelItem { + id: string + children: readonly FindingNode[] +} + +function error(code: string, path: string, message: string): SheetIssue { + return { code, severity: 'error', path, message } +} + +function warning(code: string, path: string, message: string): SheetIssue { + return { code, severity: 'warning', path, message } +} + +/** Indexes of entries whose value already appeared earlier in the list. */ +function repeatedIndexes(values: readonly string[]): number[] { + const seen = new Set() + const repeated: number[] = [] + values.forEach((value, index) => { + if (seen.has(value)) repeated.push(index) + seen.add(value) + }) + return repeated +} + +function duplicateIssues( + values: readonly string[], + code: string, + pathOf: (index: number) => string, +): SheetIssue[] { + return repeatedIndexes(values).map((index) => + error(code, pathOf(index), `Duplicate id "${values[index]}"`), + ) +} + +function isObservable( + annotation: Annotation, +): annotation is ObservableAnnotation { + return annotation.kind !== 'detail_trigger' +} + +function isTrigger(annotation: Annotation): annotation is TriggerAnnotation { + return annotation.kind === 'detail_trigger' +} + +function viewsById(doc: AnatomicalSheetDocument): Map { + const byId = new Map() + for (const view of doc.views) if (!byId.has(view.id)) byId.set(view.id, view) + return byId +} + +/** Rendering starts from a single root drawing. */ +const checkMainViewCount: Rule = (doc) => { + const count = doc.views.filter((view) => view.kind === 'main').length + if (count === 1) return [] + return [ + error('view.main.count', 'views', `Expected 1 main view, found ${count}`), + ] +} + +const checkViewIdsUnique: Rule = (doc) => + duplicateIssues( + doc.views.map((view) => view.id), + 'view.id.duplicate', + (index) => `views[${index}].id`, + ) + +const checkViewParentsExist: Rule = (doc) => { + const byId = viewsById(doc) + return doc.views.flatMap((view, index) => + view.kind === 'detail' && !byId.has(view.parent_view_id) + ? [ + error( + 'view.parent.missing', + `views[${index}].parent_view_id`, + `Parent view "${view.parent_view_id}" does not exist`, + ), + ] + : [], + ) +} + +/** + * True when the parent chain loops before reaching the main view. A + * missing parent ends the walk: that case is view.parent.missing. + */ +function loopsBeforeMain(view: DetailView, byId: Map) { + const visited = new Set([view.id]) + let current: SheetView = view + while (current.kind === 'detail') { + const parent = byId.get(current.parent_view_id) + if (!parent) return false + if (visited.has(parent.id)) return true + visited.add(parent.id) + current = parent + } + return false +} + +const checkViewParentCycles: Rule = (doc) => { + const byId = viewsById(doc) + return doc.views.flatMap((view, index) => + view.kind === 'detail' && loopsBeforeMain(view, byId) + ? [ + error( + 'view.parent.cycle', + `views[${index}].parent_view_id`, + `Parent chain of "${view.id}" never reaches the main view`, + ), + ] + : [], + ) +} + +function isOpenedFromParent( + view: DetailView, + doc: AnatomicalSheetDocument, +): boolean { + return doc.annotations.some( + (annotation) => + isTrigger(annotation) && + annotation.opens_view_id === view.id && + annotation.view_id === view.parent_view_id, + ) +} + +/** A detail view nobody can open is dead content for the practitioner. */ +const checkViewsReachable: Rule = (doc) => { + const byId = viewsById(doc) + return doc.views.flatMap((view, index) => + view.kind === 'detail' && + byId.has(view.parent_view_id) && + !isOpenedFromParent(view, doc) + ? [ + error( + 'view.unreachable', + `views[${index}]`, + `No detail_trigger in "${view.parent_view_id}" opens "${view.id}"`, + ), + ] + : [], + ) +} + +/** Every view must have something to draw: its own asset or a crop. */ +function viewAssetIssue(view: SheetView, index: number): SheetIssue[] { + if (view.svg_asset_id !== null) return [] + if (view.kind === 'main') { + return [ + error( + 'view.asset.missing', + `views[${index}].svg_asset_id`, + `Main view "${view.id}" has no SVG asset`, + ), + ] + } + if (view.view_box !== null) return [] + return [ + error( + 'view.asset.missing', + `views[${index}].view_box`, + `Detail view "${view.id}" has neither an asset nor a view_box`, + ), + ] +} + +const checkViewAssets: Rule = (doc) => doc.views.flatMap(viewAssetIssue) + +/** Report points are keyed by annotation id across every view. */ +const checkAnnotationIdsUnique: Rule = (doc) => + duplicateIssues( + doc.annotations.map((annotation) => annotation.id), + 'annotation.id.duplicate', + (index) => `annotations[${index}].id`, + ) + +const checkAnnotationViews: Rule = (doc) => { + const byId = viewsById(doc) + return doc.annotations.flatMap((annotation, index) => + byId.has(annotation.view_id) + ? [] + : [ + error( + 'annotation.view.missing', + `annotations[${index}].view_id`, + `View "${annotation.view_id}" does not exist`, + ), + ], + ) +} + +const checkAnnotationCategories: Rule = (doc) => { + const ids = new Set(doc.categories.map((category) => category.id)) + return doc.annotations.flatMap((annotation, index) => + ids.has(annotation.category_id) + ? [] + : [ + error( + 'annotation.category.missing', + `annotations[${index}].category_id`, + `Category "${annotation.category_id}" does not exist`, + ), + ], + ) +} + +/** A trigger opens a direct child of the view it is drawn in. */ +function opensChildOfOwnView( + trigger: TriggerAnnotation, + byId: Map, +): boolean { + const target = byId.get(trigger.opens_view_id) + return target?.kind === 'detail' && target.parent_view_id === trigger.view_id +} + +const checkTriggerTargets: Rule = (doc) => { + const byId = viewsById(doc) + return doc.annotations.flatMap((annotation, index) => + isTrigger(annotation) && !opensChildOfOwnView(annotation, byId) + ? [ + error( + 'annotation.opens_view.invalid', + `annotations[${index}].opens_view_id`, + `"${annotation.opens_view_id}" is not a detail child of ` + + `"${annotation.view_id}"`, + ), + ] + : [], + ) +} + +const checkAnnotationFindingZones: Rule = (doc) => { + const ids = new Set(doc.finding_zones.map((zone) => zone.id)) + return doc.annotations.flatMap((annotation, index) => + isObservable(annotation) && + annotation.finding_zone_id !== null && + !ids.has(annotation.finding_zone_id) + ? [ + error( + 'annotation.finding_zone.missing', + `annotations[${index}].finding_zone_id`, + `Finding zone "${annotation.finding_zone_id}" does not exist`, + ), + ] + : [], + ) +} + +const checkAnnotationRegions: Rule = (doc) => { + const codes = new Set(doc.vertebral_config.regions.map((r) => r.code)) + return doc.annotations.flatMap((annotation, index) => + isObservable(annotation) && + annotation.vertebral_region_code !== null && + !codes.has(annotation.vertebral_region_code) + ? [ + error( + 'annotation.region.missing', + `annotations[${index}].vertebral_region_code`, + `Vertebral region "${annotation.vertebral_region_code}" ` + + 'is not configured', + ), + ] + : [], + ) +} + +/** Allowed in a draft, but a click on it would offer nothing to record. */ +const checkAnnotationsHaveFindings: Rule = (doc) => + doc.annotations.flatMap((annotation, index) => + isObservable(annotation) && annotation.finding_zone_id === null + ? [ + warning( + 'annotation.no_findings', + `annotations[${index}].finding_zone_id`, + `Annotation "${annotation.id}" is linked to no finding zone`, + ), + ] + : [], + ) + +const checkRegionCodesUnique: Rule = (doc) => + duplicateIssues( + doc.vertebral_config.regions.map((region) => region.code), + 'region.code.duplicate', + (index) => `vertebral_config.regions[${index}].code`, + ) + +const checkCategoryIdsUnique: Rule = (doc) => + duplicateIssues( + doc.categories.map((category) => category.id), + 'category.id.duplicate', + (index) => `categories[${index}].id`, + ) + +const checkFindingZoneIdsUnique: Rule = (doc) => + duplicateIssues( + doc.finding_zones.map((zone) => zone.id), + 'finding_zone.id.duplicate', + (index) => `finding_zones[${index}].id`, + ) + +/** + * Findings are addressed by (zone, path[]) as Finding.path does today, so + * ids only need to be unique among siblings, at every depth. + */ +function siblingIssues( + nodes: readonly FindingLevelItem[], + path: string, +): SheetIssue[] { + const own = duplicateIssues( + nodes.map((node) => node.id), + 'finding.id.duplicate', + (index) => `${path}[${index}].id`, + ) + const nested = nodes.flatMap((node, index) => + siblingIssues(node.children, `${path}[${index}].children`), + ) + return [...own, ...nested] +} + +const checkFindingSiblings: Rule = (doc) => + doc.finding_zones.flatMap((zone, index) => + siblingIssues(zone.categories, `finding_zones[${index}].categories`), + ) + +/** Allowed in a draft, but nothing on the drawing can reach this zone. */ +const checkFindingZonesReferenced: Rule = (doc) => { + const referenced = new Set( + doc.annotations.filter(isObservable).map((a) => a.finding_zone_id), + ) + return doc.finding_zones.flatMap((zone, index) => + referenced.has(zone.id) + ? [] + : [ + warning( + 'finding_zone.unreferenced', + `finding_zones[${index}]`, + `No annotation points to finding zone "${zone.id}"`, + ), + ], + ) +} + +const RULES: readonly Rule[] = [ + checkMainViewCount, + checkViewIdsUnique, + checkViewParentsExist, + checkViewParentCycles, + checkViewsReachable, + checkViewAssets, + checkAnnotationIdsUnique, + checkAnnotationViews, + checkAnnotationCategories, + checkTriggerTargets, + checkAnnotationFindingZones, + checkAnnotationRegions, + checkAnnotationsHaveFindings, + checkRegionCodesUnique, + checkCategoryIdsUnique, + checkFindingZoneIdsUnique, + checkFindingSiblings, + checkFindingZonesReferenced, +] + +/** Lists every integrity issue of a shape-valid document. */ +export function validateSheetDocument( + doc: AnatomicalSheetDocument, +): SheetIssue[] { + return RULES.flatMap((rule) => rule(doc)) +} + +/** Warnings never block publication; errors always do. */ +export function isPublishable(issues: readonly SheetIssue[]): boolean { + return !issues.some((issue) => issue.severity === 'error') +} + +export class SheetValidationError extends Error { + readonly issues: SheetIssue[] + + constructor(issues: SheetIssue[]) { + const errors = issues.filter((issue) => issue.severity === 'error') + super( + `Sheet document is not publishable: ${errors.length} error(s), ` + + `first: ${errors[0]?.code ?? 'none'}`, + ) + this.name = 'SheetValidationError' + this.issues = issues + } +} + +/** TypeScript-side publication gate, mirrored by SQL at publish time. */ +export function assertPublishable(doc: AnatomicalSheetDocument): void { + const issues = validateSheetDocument(doc) + if (!isPublishable(issues)) throw new SheetValidationError(issues) +} diff --git a/packages/domain/src/index.ts b/packages/domain/src/index.ts new file mode 100644 index 00000000..12ac5d72 --- /dev/null +++ b/packages/domain/src/index.ts @@ -0,0 +1 @@ +export * from './anatomical-sheet' diff --git a/packages/domain/tests/anatomical-sheet.schema.test.ts b/packages/domain/tests/anatomical-sheet.schema.test.ts new file mode 100644 index 00000000..3f7746ba --- /dev/null +++ b/packages/domain/tests/anatomical-sheet.schema.test.ts @@ -0,0 +1,117 @@ +import { + AnatomicalSheetDocumentSchema, + FindingNodeSchema, + StableIdSchema, + type AnatomicalSheetDocumentInput, +} from '../src' +import { horseSlice, horseSliceInput } from './fixtures/horse-slice' + +// Mutations deliberately break the typed shape, so the draft is untyped. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type LooseDoc = any +type Mutation = (doc: LooseDoc) => void + +/** Applies a mutation to the lean fixture and reports whether it parses. */ +function parsesAfter(mutate: Mutation): boolean { + const doc: LooseDoc = horseSliceInput() + mutate(doc) + return AnatomicalSheetDocumentSchema.safeParse(doc).success +} + +describe('AnatomicalSheetDocumentSchema', () => { + it('accepts the horse slice fixture', () => { + const result = AnatomicalSheetDocumentSchema.safeParse(horseSliceInput()) + expect(result.success).toBe(true) + }) + + it('accepts a parsed document again (output is valid input)', () => { + expect(AnatomicalSheetDocumentSchema.parse(horseSlice())).toEqual( + horseSlice(), + ) + }) + + const rejections: Array<[string, Mutation]> = [ + ['an unknown top-level key', (d) => (d.extra = true)], + ['an unknown nested key', (d) => (d.views[0].zoom = 2)], + ['a stable id with spaces', (d) => (d.annotations[0].id = 'Hip Joint')], + ['a stable id with an accent', (d) => (d.categories[0].id = 'É')], + ['an empty stable id', (d) => (d.finding_zones[0].id = '')], + ['schema_version 2', (d) => (d.schema_version = 2)], + ['a non-uuid svg_asset_id', (d) => (d.views[0].svg_asset_id = 'horse')], + [ + 'a polygon with 2 points', + (d) => + (d.annotations[1].geometry.points = [ + [0, 0], + [1, 1], + ]), + ], + ['a circle with r 0', (d) => (d.annotations[0].geometry.r = 0)], + ['a region count of 0', (d) => (d.vertebral_config.regions[0].count = 0)], + ['a missing en label', (d) => delete d.name.en], + [ + 'a detail view without parent_view_id', + (d) => delete d.views[1].parent_view_id, + ], + [ + 'a detail_trigger with finding_zone_id', + (d) => (d.annotations[3].finding_zone_id = 'hip'), + ], + [ + 'a finding category kind foo', + (d) => (d.finding_zones[0].categories[0].kind = 'foo'), + ], + ] + + it.each(rejections)('rejects %s', (_label, mutate) => { + expect(parsesAfter(mutate)).toBe(false) + }) +}) + +describe('StableIdSchema', () => { + it.each(['hip', 'c7-t1', 'view_main', '0'])('accepts %s', (id) => { + expect(StableIdSchema.safeParse(id).success).toBe(true) + }) + + it.each(['Hip Joint', 'É', '', '-hip', 'a'.repeat(65)])( + 'rejects %j', + (id) => { + expect(StableIdSchema.safeParse(id).success).toBe(false) + }, + ) +}) + +describe('FindingNodeSchema defaults', () => { + it('fills the optional keys of a lean node, recursively', () => { + const node = FindingNodeSchema.parse({ + id: 'articular', + name: { fr: 'Articulaire', en: 'Articular' }, + children: [{ id: 'flexion', name: { fr: 'Flexion', en: 'Flexion' } }], + }) + expect(node.description).toEqual({}) + expect(node.requires_vet_referral).toBe(false) + expect(node.sources).toEqual([]) + expect(node.children[0]).toEqual({ + id: 'flexion', + name: { fr: 'Flexion', en: 'Flexion' }, + description: {}, + requires_vet_referral: false, + sources: [], + children: [], + }) + }) + + it('keeps explicit values of the fixture', () => { + const doc = horseSlice() + const lameness = doc.finding_zones[0].categories[1].children[0] + expect(lameness.requires_vet_referral).toBe(true) + const trauma = doc.finding_zones[0].categories[2].children[0] + expect(trauma.sources).toHaveLength(1) + }) + + it('does not add default keys to the lean input', () => { + const input: AnatomicalSheetDocumentInput = horseSliceInput() + const leaf = input.finding_zones[2].categories[0].children[0] + expect(Object.keys(leaf)).toEqual(['id', 'name']) + }) +}) diff --git a/packages/domain/tests/anatomical-sheet.validate.test.ts b/packages/domain/tests/anatomical-sheet.validate.test.ts new file mode 100644 index 00000000..70c25436 --- /dev/null +++ b/packages/domain/tests/anatomical-sheet.validate.test.ts @@ -0,0 +1,426 @@ +import { + AnatomicalSheetDocumentSchema, + SheetValidationError, + assertPublishable, + createEmptySheetDocument, + isPublishable, + validateSheetDocument, + type AnatomicalSheetDocument, + type Annotation, + type SheetView, +} from '../src' +import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice' + +/** [code, path] pairs: what each rule test pins down. */ +function issuesOf(doc: AnatomicalSheetDocument): Array<[string, string]> { + return validateSheetDocument(doc).map((issue) => [issue.code, issue.path]) +} + +function mutated( + mutate: (doc: AnatomicalSheetDocument) => void, +): AnatomicalSheetDocument { + const doc = horseSlice() + mutate(doc) + return doc +} + +function point(id: string, fields: Partial = {}): Annotation { + return { + id, + kind: 'point', + view_id: 'view-main', + category_id: 'articulations', + laterality: 'bilateral', + geometry: null, + name: { fr: id, en: id }, + finding_zone_id: 'hip', + vertebral_region_code: null, + ...fields, + } as Annotation +} + +function trigger(id: string, viewId: string, opensViewId: string) { + return { + id, + kind: 'detail_trigger', + view_id: viewId, + category_id: 'cadrans-du-crane', + laterality: 'unpaired', + geometry: null, + name: null, + opens_view_id: opensViewId, + } satisfies Annotation +} + +function detailView(id: string, parentId: string) { + return { + id, + kind: 'detail', + name: { fr: id, en: id }, + parent_view_id: parentId, + svg_asset_id: HORSE_MAIN_ASSET_ID, + view_box: null, + } satisfies SheetView +} + +describe('validateSheetDocument on the horse slice', () => { + it('reports no error and no warning', () => { + expect(validateSheetDocument(horseSlice())).toEqual([]) + }) +}) + +describe('integrity rules (one mutation per code)', () => { + it('view.main.count', () => { + const doc = mutated((d) => { + d.views.push({ ...d.views[0], id: 'view-alt' }) + }) + expect(issuesOf(doc)).toEqual([['view.main.count', 'views']]) + }) + + it('view.main.count with no main view', () => { + const doc = mutated((d) => { + d.views = d.views.filter((view) => view.kind !== 'main') + }) + const codes = issuesOf(doc).map(([code]) => code) + expect(codes).toContain('view.main.count') + }) + + it('view.id.duplicate', () => { + const doc = mutated((d) => { + d.views.push(structuredClone(d.views[1])) + }) + expect(issuesOf(doc)).toEqual([['view.id.duplicate', 'views[2].id']]) + }) + + it('view.parent.missing', () => { + const doc = mutated((d) => { + d.views.push(detailView('view-orphan', 'view-ghost')) + }) + expect(issuesOf(doc)).toEqual([ + ['view.parent.missing', 'views[2].parent_view_id'], + ]) + }) + + it('view.parent.cycle (terminates on a two-view loop)', () => { + const doc = mutated((d) => { + d.views.push(detailView('view-a', 'view-b')) + d.views.push(detailView('view-b', 'view-a')) + d.annotations.push(trigger('open-a', 'view-b', 'view-a')) + d.annotations.push(trigger('open-b', 'view-a', 'view-b')) + }) + expect(issuesOf(doc)).toEqual([ + ['view.parent.cycle', 'views[2].parent_view_id'], + ['view.parent.cycle', 'views[3].parent_view_id'], + ]) + }) + + it('view.parent.cycle on a self-parent', () => { + const doc = mutated((d) => { + d.views.push(detailView('view-self', 'view-self')) + d.annotations.push(trigger('open-self', 'view-self', 'view-self')) + }) + expect(issuesOf(doc)).toEqual([ + ['view.parent.cycle', 'views[2].parent_view_id'], + ]) + }) + + it('view.unreachable', () => { + const doc = mutated((d) => { + d.annotations = d.annotations.filter((a) => a.id !== 'head-trigger') + }) + expect(issuesOf(doc)).toEqual([['view.unreachable', 'views[1]']]) + }) + + it('view.asset.missing on the main view', () => { + const doc = mutated((d) => { + d.views[0].svg_asset_id = null + }) + expect(issuesOf(doc)).toEqual([ + ['view.asset.missing', 'views[0].svg_asset_id'], + ]) + }) + + it('view.asset.missing on a detail view without asset nor view_box', () => { + const doc = mutated((d) => { + d.views[1].view_box = null + }) + expect(issuesOf(doc)).toEqual([['view.asset.missing', 'views[1].view_box']]) + }) + + it('annotation.id.duplicate (across views)', () => { + const doc = mutated((d) => { + d.annotations.push({ ...structuredClone(d.annotations[4]) }) + d.annotations[6].view_id = 'view-main' + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.id.duplicate', 'annotations[6].id'], + ]) + }) + + it('annotation.view.missing', () => { + const doc = mutated((d) => { + d.annotations.push(point('ghost', { view_id: 'view-ghost' })) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.view.missing', 'annotations[6].view_id'], + ]) + }) + + it('annotation.category.missing', () => { + const doc = mutated((d) => { + d.annotations[0].category_id = 'os' + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.category.missing', 'annotations[0].category_id'], + ]) + }) + + it('annotation.opens_view.invalid when the target is not a child', () => { + const doc = mutated((d) => { + d.annotations.push(trigger('loop', 'view-head', 'view-head')) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.opens_view.invalid', 'annotations[6].opens_view_id'], + ]) + }) + + it('annotation.opens_view.invalid when the target is main or absent', () => { + const doc = mutated((d) => { + d.annotations.push(trigger('to-main', 'view-main', 'view-main')) + d.annotations.push(trigger('to-ghost', 'view-main', 'view-ghost')) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.opens_view.invalid', 'annotations[6].opens_view_id'], + ['annotation.opens_view.invalid', 'annotations[7].opens_view_id'], + ]) + }) + + it('annotation.finding_zone.missing', () => { + const doc = mutated((d) => { + d.annotations.push(point('stifle', { finding_zone_id: 'stifle' })) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.finding_zone.missing', 'annotations[6].finding_zone_id'], + ]) + }) + + it('annotation.region.missing', () => { + const doc = mutated((d) => { + const cervical = d.annotations[1] + if (cervical.kind === 'detail_trigger') throw new Error('fixture') + cervical.vertebral_region_code = 'Q' + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.region.missing', 'annotations[1].vertebral_region_code'], + ]) + }) + + it('annotation.no_findings is a warning', () => { + const doc = mutated((d) => { + d.annotations.push(point('mandible', { finding_zone_id: null })) + }) + expect(issuesOf(doc)).toEqual([ + ['annotation.no_findings', 'annotations[6].finding_zone_id'], + ]) + expect(validateSheetDocument(doc)[0].severity).toBe('warning') + }) + + it('region.code.duplicate', () => { + const doc = mutated((d) => { + const regions = d.vertebral_config.regions + regions.push(structuredClone(regions[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['region.code.duplicate', 'vertebral_config.regions[5].code'], + ]) + }) + + it('category.id.duplicate', () => { + const doc = mutated((d) => { + d.categories.push(structuredClone(d.categories[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['category.id.duplicate', 'categories[4].id'], + ]) + }) + + it('finding_zone.id.duplicate', () => { + const doc = mutated((d) => { + d.finding_zones.push(structuredClone(d.finding_zones[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['finding_zone.id.duplicate', 'finding_zones[5].id'], + ]) + }) + + it('finding.id.duplicate among finding categories', () => { + const doc = mutated((d) => { + const categories = d.finding_zones[0].categories + categories.push(structuredClone(categories[0])) + }) + expect(issuesOf(doc)).toEqual([ + ['finding.id.duplicate', 'finding_zones[0].categories[3].id'], + ]) + }) + + it('finding.id.duplicate among nested children', () => { + const doc = mutated((d) => { + const articular = d.finding_zones[0].categories[0].children[0] + articular.children.push(structuredClone(articular.children[0])) + }) + expect(issuesOf(doc)).toEqual([ + [ + 'finding.id.duplicate', + 'finding_zones[0].categories[0].children[0].children[2].id', + ], + ]) + }) + + it('finding ids may repeat across different sibling arrays', () => { + const doc = mutated((d) => { + const hip = d.finding_zones[0].categories + hip[1].children.push(structuredClone(hip[0].children[0])) + }) + expect(issuesOf(doc)).toEqual([]) + }) + + it('finding_zone.unreferenced is a warning', () => { + const doc = mutated((d) => { + d.finding_zones.push({ + id: 'stifle', + name: { fr: 'Grasset', en: 'Stifle' }, + categories: [], + }) + }) + expect(issuesOf(doc)).toEqual([ + ['finding_zone.unreferenced', 'finding_zones[5]'], + ]) + expect(validateSheetDocument(doc)[0].severity).toBe('warning') + }) +}) + +describe('publication gate', () => { + it('accepts the fixture', () => { + expect(isPublishable(validateSheetDocument(horseSlice()))).toBe(true) + expect(() => assertPublishable(horseSlice())).not.toThrow() + }) + + it('accepts a document with warnings only', () => { + const doc = mutated((d) => { + d.annotations.push(point('mandible', { finding_zone_id: null })) + }) + expect(validateSheetDocument(doc)).toHaveLength(1) + expect(isPublishable(validateSheetDocument(doc))).toBe(true) + expect(() => assertPublishable(doc)).not.toThrow() + }) + + it('refuses a document with an error, exposing the issues', () => { + const doc = mutated((d) => { + d.views[0].svg_asset_id = null + }) + expect(isPublishable(validateSheetDocument(doc))).toBe(false) + let caught: unknown + try { + assertPublishable(doc) + } catch (thrown) { + caught = thrown + } + expect(caught).toBeInstanceOf(SheetValidationError) + const codes = (caught as SheetValidationError).issues.map((i) => i.code) + expect(codes).toEqual(['view.asset.missing']) + }) +}) + +describe('createEmptySheetDocument', () => { + const empty = () => + createEmptySheetDocument({ + species_id: 'equine', + name: { fr: 'Nouvelle fiche', en: 'New sheet' }, + }) + + it('is valid for the shape tier', () => { + expect(AnatomicalSheetDocumentSchema.safeParse(empty()).success).toBe(true) + expect(empty().views).toEqual([ + expect.objectContaining({ + id: 'view-main', + kind: 'main', + svg_asset_id: null, + view_box: null, + }), + ]) + }) + + it('is not publishable: the main view has no asset', () => { + const issues = validateSheetDocument(empty()) + expect(issues.map((issue) => issue.code)).toEqual(['view.asset.missing']) + expect(() => assertPublishable(empty())).toThrow(SheetValidationError) + }) +}) + +/** True for a { fr?, en? } label object, the only thing a translator edits. */ +function isLabel(value: unknown): value is Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const keys = Object.keys(value) + return keys.length > 0 && keys.every((key) => key === 'fr' || key === 'en') +} + +/** Rewrites every label with arbitrary strings, leaving all else intact. */ +function mapLabels( + value: unknown, + rewrite: (label: Record) => unknown, +): unknown { + if (isLabel(value)) return rewrite(value) + if (Array.isArray(value)) return value.map((v) => mapLabels(v, rewrite)) + if (value === null || typeof value !== 'object') return value + return Object.fromEntries( + Object.entries(value).map(([k, v]) => [k, mapLabels(v, rewrite)]), + ) +} + +/** Every id and reference: values of keys named id, *_id or code. */ +function collectIds(value: unknown, out: string[] = []): string[] { + if (Array.isArray(value)) value.forEach((v) => collectIds(v, out)) + else if (value !== null && typeof value === 'object') { + for (const [key, v] of Object.entries(value)) { + const isRef = key === 'id' || key.endsWith('_id') || key.endsWith('code') + if (isRef && typeof v === 'string') out.push(`${key}=${v}`) + else collectIds(v, out) + } + } + return out +} + +describe('ID stability under translation', () => { + it('keeps ids, references and validation output when labels change', () => { + const original = horseSlice() + let counter = 0 + const relabeled = AnatomicalSheetDocumentSchema.parse( + mapLabels(original, (label) => + Object.fromEntries( + Object.keys(label).map((locale) => [locale, `x${counter++}`]), + ), + ), + ) + expect(counter).toBeGreaterThan(50) + expect(JSON.stringify(relabeled)).not.toEqual(JSON.stringify(original)) + expect(collectIds(relabeled)).toEqual(collectIds(original)) + const strip = () => null + expect(mapLabels(relabeled, strip)).toEqual(mapLabels(original, strip)) + expect(validateSheetDocument(relabeled)).toEqual( + validateSheetDocument(original), + ) + }) + + it('keeps validation output identical on a broken document too', () => { + const broken = mutated((d) => { + d.annotations[0].category_id = 'os' + d.views[1].view_box = null + }) + const relabeled = mapLabels(broken, () => ({ fr: 'a', en: 'b' })) + expect(validateSheetDocument(relabeled as AnatomicalSheetDocument)).toEqual( + validateSheetDocument(broken), + ) + }) +}) diff --git a/packages/domain/tests/fixtures/horse-slice.ts b/packages/domain/tests/fixtures/horse-slice.ts new file mode 100644 index 00000000..4f05c2f1 --- /dev/null +++ b/packages/domain/tests/fixtures/horse-slice.ts @@ -0,0 +1,443 @@ +import { + AnatomicalSheetDocumentSchema, + type AnatomicalSheetDocument, + type AnatomicalSheetDocumentInput, + type FindingNodeInput, +} from '../../src' + +/** + * Reduced equine sheet built from the real assets: labels come from + * apps/app/public/species/equine/{Horse,Horse_head}.svg and from + * apps/app/src/domain/species/equine/pathologies.json. It exercises two + * views (one cropped detail), a trigger, a spine region, a bilateral joint, + * the three finding kinds, a two-level tree, a vet referral and a source. + * It references every finding zone, so it validates with zero issues. + */ + +export const HORSE_MAIN_ASSET_ID = '3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8' + +function leaf(id: string, fr: string, en: string): FindingNodeInput { + return { id, name: { fr, en } } +} + +const ANAMNESIS = { + id: 'anamnesis', + kind: 'anamnesis', + name: { + fr: 'Anamnèse / facteurs rapportés', + en: 'Anamnesis / reported factors', + }, + description: { + fr: "Facteurs rapportés par le propriétaire lors de l'anamnèse", + }, +} as const + +const OBSERVATIONS_NAME = { + fr: 'Observations / motifs de consultation', + en: 'Observations / consultation reasons', +} + +const DYSFUNCTIONS_NAME = { + fr: 'Dysfonctions ostéopathiques', + en: 'Osteopathic dysfunctions', +} + +const TRAUMA = leaf( + 'trauma-direct', + 'Traumatisme rapporté (choc, chute)', + 'Reported trauma (blow, fall)', +) + +const STRESS = leaf( + 'stress-context', + 'Contexte de stress / changement', + 'Stress / change context', +) + +const HIP_ZONE = { + id: 'hip', + name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, + categories: [ + { + id: 'hip-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + { + id: 'articular', + name: { + fr: 'Restrictions de mobilité articulaire', + en: 'Articular mobility restrictions', + }, + children: [ + leaf( + 'restriction-flexion', + 'Restriction en flexion', + 'Flexion restriction', + ), + leaf( + 'restriction-extension', + 'Restriction en extension', + 'Extension restriction', + ), + ], + }, + ], + }, + { + id: 'hip-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + { + ...leaf( + 'limb-lameness', + 'Boiterie rapportée (membre concerné)', + 'Reported lameness (affected limb)', + ), + requires_vet_referral: true, + }, + ], + }, + { + ...ANAMNESIS, + children: [ + { + ...TRAUMA, + sources: [ + { + type: 'manual', + citation: 'Legacy equine catalog (pathologies.json)', + }, + ], + }, + ], + }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const CERVICAL_ZONE = { + id: 'cervical', + name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' }, + categories: [ + { + id: 'cervical-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + { + id: 'muscular', + name: { + fr: 'Tensions musculaires paravertébrales', + en: 'Paravertebral muscle tensions', + }, + children: [ + leaf('splenius-tension', 'Tension du splénius', 'Splenius tension'), + ], + }, + ], + }, + { + id: 'cervical-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + { + ...leaf( + 'stumbling-proprioceptive', + 'Trébuchements / déficit proprioceptif rapporté', + 'Reported stumbling / proprioceptive deficit', + ), + requires_vet_referral: true, + }, + ], + }, + { ...ANAMNESIS, children: [TRAUMA] }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const C7_T1_ZONE = { + id: 'c7-t1', + name: { + fr: 'Charnière C7-T1 (cervico-thoracique)', + en: 'C7-T1 (Cervicothoracic)', + }, + categories: [ + { + id: 'c7-t1-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + leaf( + 'restriction-rotation', + 'Restriction en rotation', + 'Rotation restriction', + ), + ], + }, + { + id: 'c7-t1-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + leaf( + 'base-neck-stiffness', + "Raideur de la base de l'encolure", + 'Base-of-neck stiffness', + ), + ], + }, + { ...ANAMNESIS, children: [STRESS] }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const ATM_ZONE = { + id: 'atm', + name: { + fr: 'Articulation Temporo-Mandibulaire (ATM)', + en: 'Temporomandibular Joint (TMJ)', + }, + categories: [ + { + id: 'atm-dysfunctions', + kind: 'dysfunction', + name: { + fr: "Dysfonctions ostéopathiques de l'ATM", + en: 'Osteopathic TMJ dysfunctions', + }, + children: [ + leaf('masseter-tension', 'Tension du masséter', 'Masseter tension'), + ], + }, + { + id: 'atm-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + leaf( + 'bit-defense', + 'Réactions de défense au mors', + 'Defense reactions to bit', + ), + ], + }, + { + ...ANAMNESIS, + children: [ + leaf( + 'dental-context', + 'Suite de soin dentaire récent', + 'Post recent dental care', + ), + ], + }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const SPHENOID_ZONE = { + id: 'sphenoid', + name: { fr: 'Sphénoïde', en: 'Sphenoid' }, + categories: [ + { + id: 'ssb-dysfunctions', + kind: 'dysfunction', + name: DYSFUNCTIONS_NAME, + children: [ + { + id: 'physiological', + name: { + fr: 'Lésions physiologiques (SSB)', + en: 'Physiological lesions (SBS)', + }, + children: [ + leaf('torsion-right', 'Torsion droite', 'Right torsion'), + leaf('torsion-left', 'Torsion gauche', 'Left torsion'), + ], + }, + ], + }, + { + id: 'sphenoid-observations', + kind: 'observation', + name: OBSERVATIONS_NAME, + children: [ + leaf( + 'post-trauma-head', + 'Suite de traumatisme crânien', + 'Post head trauma', + ), + ], + }, + { ...ANAMNESIS, children: [TRAUMA, STRESS] }, + ], +} satisfies AnatomicalSheetDocumentInput['finding_zones'][number] + +const HORSE_SLICE_INPUT: AnatomicalSheetDocumentInput = { + schema_version: 1, + species_id: 'equine', + name: { fr: 'Cheval (extrait)', en: 'Horse (slice)' }, + description: { + fr: 'Extrait de la fiche équine pour les tests du modèle', + en: 'Equine sheet slice for model tests', + }, + scope_disclaimer: { + fr: + "Les éléments listés correspondent au périmètre légal de l'ostéopathie " + + 'animale : dysfonctions ostéopathiques palpées, observations cliniques ' + + "et motifs de consultation. Aucun diagnostic médical n'est posé. " + + 'Toute pathologie organique relève du vétérinaire.', + }, + attribution: { authors: ['Faunosteo'], license: 'MIT', notes: null }, + vertebral_config: { + regions: [ + { code: 'C', name: { fr: 'Cervicales', en: 'Cervical' }, count: 7 }, + { code: 'T', name: { fr: 'Thoraciques', en: 'Thoracic' }, count: 18 }, + { code: 'L', name: { fr: 'Lombaires', en: 'Lumbar' }, count: 6 }, + { code: 'S', name: { fr: 'Sacrées', en: 'Sacral' }, count: 5 }, + { code: 'Cd', name: { fr: 'Caudales', en: 'Caudal' }, count: 18 }, + ], + }, + categories: [ + { + id: 'articulations', + name: { fr: 'Articulations', en: 'Joints' }, + color: '#ff9500', + }, + { + id: 'zone-colonne', + name: { fr: 'Zone colonne', en: 'Spine zone' }, + color: '#e100ff', + }, + { + id: 'charnieres-vertebrales', + name: { fr: 'Charnières vertébrales', en: 'Vertebral junctions' }, + color: '#ff0000', + }, + { + id: 'cadrans-du-crane', + name: { fr: 'Cadrans du crâne', en: 'Skull quadrants' }, + color: '#1baa08', + }, + ], + views: [ + { + id: 'view-main', + kind: 'main', + name: { fr: 'Cheval entier', en: 'Whole horse' }, + svg_asset_id: HORSE_MAIN_ASSET_ID, + view_box: null, + }, + { + id: 'view-head', + kind: 'detail', + name: { fr: 'Tête', en: 'Head' }, + parent_view_id: 'view-main', + svg_asset_id: null, + view_box: { min_x: 60, min_y: 100, width: 500, height: 380 }, + }, + ], + annotations: [ + { + id: 'hip', + kind: 'point', + view_id: 'view-main', + category_id: 'articulations', + laterality: 'bilateral', + geometry: { type: 'circle', cx: 1516, cy: 695, r: 34 }, + name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, + finding_zone_id: 'hip', + vertebral_region_code: null, + }, + { + id: 'cervical-vertebrae', + kind: 'zone', + view_id: 'view-main', + category_id: 'zone-colonne', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [468, 276], + [489, 216], + [558, 248], + [586, 339], + [552, 461], + [524, 370], + ], + }, + name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' }, + finding_zone_id: 'cervical', + vertebral_region_code: 'C', + }, + { + id: 'hinge-c7-t1', + kind: 'point', + view_id: 'view-main', + category_id: 'charnieres-vertebrales', + laterality: 'unpaired', + geometry: { type: 'circle', cx: 840.17, cy: 399.08, r: 30 }, + name: { + fr: 'Charnière C7-T1 (cervico-thoracique)', + en: 'C7-T1 (Cervicothoracic)', + }, + finding_zone_id: 'c7-t1', + vertebral_region_code: null, + }, + { + id: 'head-trigger', + kind: 'detail_trigger', + view_id: 'view-main', + category_id: 'cadrans-du-crane', + laterality: 'unpaired', + geometry: { + type: 'polygon', + points: [ + [454, 332], + [429, 202], + [349, 154], + [234, 279], + [164, 384], + [234, 468], + ], + }, + name: null, + opens_view_id: 'view-head', + }, + { + id: 'atm', + kind: 'point', + view_id: 'view-head', + category_id: 'articulations', + laterality: 'bilateral', + geometry: { type: 'circle', cx: 384.94, cy: 314.02, r: 27 }, + name: { + fr: 'Articulation Temporo-Mandibulaire (ATM)', + en: 'Temporomandibular Joint (TMJ)', + }, + finding_zone_id: 'atm', + vertebral_region_code: null, + }, + { + id: 'sphenoid', + kind: 'point', + view_id: 'view-head', + category_id: 'cadrans-du-crane', + laterality: 'unpaired', + geometry: { type: 'circle', cx: 299, cy: 298, r: 27 }, + name: { fr: 'Sphénoïde', en: 'Sphenoid' }, + finding_zone_id: 'sphenoid', + vertebral_region_code: null, + }, + ], + finding_zones: [HIP_ZONE, CERVICAL_ZONE, C7_T1_ZONE, ATM_ZONE, SPHENOID_ZONE], +} + +/** Lean authoring form, as a creator or the importer would write it. */ +export function horseSliceInput(): AnatomicalSheetDocumentInput { + return structuredClone(HORSE_SLICE_INPUT) +} + +/** Parsed (total) document; a fresh copy so tests can mutate it freely. */ +export function horseSlice(): AnatomicalSheetDocument { + return AnatomicalSheetDocumentSchema.parse(horseSliceInput()) +} diff --git a/packages/domain/tsconfig.json b/packages/domain/tsconfig.json new file mode 100644 index 00000000..99d2ea87 --- /dev/null +++ b/packages/domain/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noImplicitReturns": true, + "skipLibCheck": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "isolatedModules": true, + "types": ["node", "vitest/globals"], + "noEmit": true + }, + "include": ["src", "tests"], + "exclude": ["node_modules"] +} diff --git a/packages/domain/vitest.config.ts b/packages/domain/vitest.config.ts new file mode 100644 index 00000000..f6374039 --- /dev/null +++ b/packages/domain/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + environment: 'node', + globals: true, + include: ['tests/**/*.test.ts'], + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 15fff537..2477e57b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -97,8 +97,36 @@ importers: specifier: ^3.2.7 version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0) + packages/domain: + dependencies: + zod: + specifier: ^3.24.1 + version: 3.25.76 + devDependencies: + '@types/node': + specifier: ^20.19.41 + version: 20.19.41 + eslint: + specifier: ^9.17.0 + version: 9.39.4(jiti@2.7.0) + globals: + specifier: ^15.14.0 + version: 15.15.0 + typescript: + specifier: ^5.7.2 + version: 5.9.3 + typescript-eslint: + specifier: ^8.19.0 + version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3) + vitest: + specifier: ^3.2.7 + version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0) + packages/supabase: dependencies: + '@faunosteo/domain': + specifier: workspace:* + version: link:../domain '@supabase/supabase-js': specifier: ^2.100.0 version: 2.117.3 From f4ceaf68f9a6dd62a54c71acf551171101df4940 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:42:43 +0200 Subject: [PATCH 3/7] feat(supabase): anatomical sheets, immutable versions, assets, lifecycle RPCs, RLS + pgTAP --- .../20261008110000_anatomical_sheets.sql | 1083 +++++++++++++++++ supabase/tests/005_anatomical_sheets.sql | 511 ++++++++ 2 files changed, 1594 insertions(+) create mode 100644 supabase/migrations/20261008110000_anatomical_sheets.sql create mode 100644 supabase/tests/005_anatomical_sheets.sql diff --git a/supabase/migrations/20261008110000_anatomical_sheets.sql b/supabase/migrations/20261008110000_anatomical_sheets.sql new file mode 100644 index 00000000..88ca7948 --- /dev/null +++ b/supabase/migrations/20261008110000_anatomical_sheets.sql @@ -0,0 +1,1083 @@ +-- Anatomical sheets: species reference, sheet identity, immutable published +-- versions, content-addressed assets, lifecycle RPCs. +-- Spec: docs/development/ANATOMICAL_SHEET_MODEL.md. Business architecture +-- §2.6–§2.9, §7, §16, §17.3. Forward-only: never edit once applied. +-- +-- The canonical document (views, annotations, finding tree) is JSONB in +-- anatomical_sheet_versions.content. Zod owns its shape; SQL owns what only +-- the database knows (species of the parent sheet, registered assets, +-- immutability, numbering) and re-checks the referential rules at +-- publication so a browser cannot publish a dangling document. + +-- --------------------------------------------------------------------------- +-- Species (reference data) +-- --------------------------------------------------------------------------- +create table public.species ( + id text primary key + constraint species_id_format check (id ~ '^[a-z0-9][a-z0-9_-]{0,63}$'), + name_fr text not null + constraint species_name_fr_length check (char_length(name_fr) between 1 and 80), + name_en text not null + constraint species_name_en_length check (char_length(name_en) between 1 and 80), + sort_order integer not null default 100, + active boolean not null default true, + created_at timestamptz not null default now() +); + +comment on table public.species is + 'Species a sheet can describe. Reference data seeded by migrations; no API write path.'; + +insert into public.species (id, name_fr, name_en, sort_order) +values ('equine', 'Cheval', 'Horse', 10) +on conflict (id) do nothing; + +-- --------------------------------------------------------------------------- +-- Enums +-- --------------------------------------------------------------------------- +create type public.sheet_visibility as enum ('private', 'public'); +create type public.sheet_status as enum ('active', 'archived', 'deleted'); +create type public.sheet_version_status as enum ('draft', 'published', 'deprecated'); + +-- --------------------------------------------------------------------------- +-- Sheets +-- --------------------------------------------------------------------------- +create table public.anatomical_sheets ( + id uuid primary key default gen_random_uuid(), + species_id text not null references public.species (id), + name text not null + constraint anatomical_sheets_name_length check (char_length(name) between 1 and 120), + slug text not null + constraint anatomical_sheets_slug_format check (slug ~ '^[a-z0-9][a-z0-9-]{1,79}$'), + description text not null default '' + constraint anatomical_sheets_description_length check (char_length(description) <= 2000), + -- null = platform-owned (official sheets, seeds). + creator_user_id uuid references public.profiles (id) on delete restrict, + is_official boolean not null default false, + visibility public.sheet_visibility not null default 'private', + status public.sheet_status not null default 'active', + -- Provenance of a copy. The copy survives the source (set null). + based_on_sheet_id uuid references public.anatomical_sheets (id) on delete set null, + based_on_version_id uuid, + current_version_id uuid, + archived_at timestamptz, + deleted_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint anatomical_sheets_owner check (is_official or creator_user_id is not null) +); + +comment on table public.anatomical_sheets is + 'Fiche anatomique identity: owner, visibility, status, provenance (based_on_*), current published version. Content lives in anatomical_sheet_versions.'; +comment on column public.anatomical_sheets.is_official is + 'Platform-owned sheet (creator null), created and edited by platform admins only.'; + +-- One slug per owner scope; platform-owned sheets share one scope. +create unique index anatomical_sheets_slug_owner_unique + on public.anatomical_sheets ( + coalesce(creator_user_id, '00000000-0000-0000-0000-000000000000'::uuid), slug + ) + where status <> 'deleted'; +create index anatomical_sheets_creator_idx + on public.anatomical_sheets (creator_user_id) where status <> 'deleted'; +create index anatomical_sheets_public_idx + on public.anatomical_sheets (species_id) where visibility = 'public' and status = 'active'; +create index anatomical_sheets_based_on_idx + on public.anatomical_sheets (based_on_version_id) where based_on_version_id is not null; + +create trigger anatomical_sheets_set_updated_at + before update on public.anatomical_sheets + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Versions +-- --------------------------------------------------------------------------- +create table public.anatomical_sheet_versions ( + id uuid primary key default gen_random_uuid(), + sheet_id uuid not null references public.anatomical_sheets (id) on delete cascade, + version_number integer not null + constraint anatomical_sheet_versions_number_positive check (version_number > 0), + status public.sheet_version_status not null default 'draft', + document_schema_version integer not null + constraint anatomical_sheet_versions_schema_known check (document_schema_version = 1), + content jsonb not null + constraint anatomical_sheet_versions_content_object check (jsonb_typeof(content) = 'object'), + change_note text not null default '' + constraint anatomical_sheet_versions_change_note_length check (char_length(change_note) <= 1000), + created_by uuid references public.profiles (id) on delete set null, + published_at timestamptz, + published_by uuid references public.profiles (id) on delete set null, + deprecated_at timestamptz, + deprecated_by uuid references public.profiles (id) on delete set null, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint anatomical_sheet_versions_number_unique unique (sheet_id, version_number), + -- The document declares its own schema version; both must agree. + constraint anatomical_sheet_versions_schema_matches + check ((content -> 'schema_version') = to_jsonb(document_schema_version)), + constraint anatomical_sheet_versions_published_stamped + check (status = 'draft' or published_at is not null), + constraint anatomical_sheet_versions_deprecated_stamped + check (status <> 'deprecated' or deprecated_at is not null) +); + +comment on table public.anatomical_sheet_versions is + 'Numbered versions of a sheet. content = canonical document (Zod schema in packages/domain). Published rows are immutable; drafts are editable by the sheet editors.'; + +-- At most one draft per sheet (OPEN_QUESTIONS C8). +create unique index anatomical_sheet_versions_one_draft + on public.anatomical_sheet_versions (sheet_id) where status = 'draft'; +create index anatomical_sheet_versions_published_idx + on public.anatomical_sheet_versions (sheet_id, version_number desc) where status = 'published'; + +alter table public.anatomical_sheets + add constraint anatomical_sheets_based_on_version_fkey + foreign key (based_on_version_id) references public.anatomical_sheet_versions (id) on delete set null, + add constraint anatomical_sheets_current_version_fkey + foreign key (current_version_id) references public.anatomical_sheet_versions (id) on delete restrict; + +create trigger anatomical_sheet_versions_set_updated_at + before update on public.anatomical_sheet_versions + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Assets (content-addressed SVG files, metadata only; bytes live in Storage +-- under anatomical-sheet-assets/.svg) +-- --------------------------------------------------------------------------- +create table public.anatomical_sheet_assets ( + id uuid primary key default gen_random_uuid(), + sheet_id uuid not null references public.anatomical_sheets (id) on delete cascade, + sha256 text not null + constraint anatomical_sheet_assets_sha256_format check (sha256 ~ '^[0-9a-f]{64}$'), + byte_size integer not null + constraint anatomical_sheet_assets_byte_size_positive check (byte_size > 0), + content_type text not null default 'image/svg+xml' + constraint anatomical_sheet_assets_content_type check (content_type in ('image/svg+xml')), + file_name text not null + constraint anatomical_sheet_assets_file_name_length check (char_length(file_name) between 1 and 255), + created_by uuid references public.profiles (id) on delete set null, + created_at timestamptz not null default now(), + constraint anatomical_sheet_assets_sheet_sha_unique unique (sheet_id, sha256) +); + +comment on table public.anatomical_sheet_assets is + 'SVG assets of a sheet, immutable and content-addressed (sha256). Referenced from the document views by id. Bytes in Storage, path derived from sha256.'; + +create index anatomical_sheet_assets_sheet_idx on public.anatomical_sheet_assets (sheet_id); + +-- --------------------------------------------------------------------------- +-- Guards (every role, table owner included) +-- --------------------------------------------------------------------------- + +-- Document ↔ row: the document must describe the sheet's species. +create or replace function private.check_sheet_version_document() +returns trigger +language plpgsql +set search_path = '' +as $$ +declare + v_species text; +begin + select species_id into v_species from public.anatomical_sheets where id = new.sheet_id; + if new.content ->> 'species_id' is distinct from v_species then + raise exception 'document species % does not match sheet species %', + new.content ->> 'species_id', v_species + using errcode = '23514'; + end if; + return new; +end; +$$; + +create trigger anatomical_sheet_versions_check_document + before insert or update of content, sheet_id on public.anatomical_sheet_versions + for each row execute function private.check_sheet_version_document(); + +-- Published rows are immutable: the only transition is published → deprecated +-- (status + deprecation stamps). Deprecated rows are frozen. A draft may +-- change content or become published, never deprecated directly. +create or replace function private.guard_sheet_version_update() +returns trigger +language plpgsql +set search_path = '' +as $$ +declare + v_same_core boolean; +begin + if new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then + raise exception 'sheet_id and version_number are immutable' using errcode = '42501'; + end if; + + if old.status = 'deprecated' then + raise exception 'deprecated version % is frozen', old.id using errcode = '42501'; + end if; + + if old.status = 'published' then + v_same_core := + new.content = old.content + and new.document_schema_version = old.document_schema_version + and new.change_note = old.change_note + and new.created_by is not distinct from old.created_by + and new.published_at = old.published_at + and new.published_by is not distinct from old.published_by + and new.created_at = old.created_at; + if new.status = 'deprecated' and v_same_core then + return new; + end if; + raise exception 'published version % is immutable', old.id using errcode = '42501'; + end if; + + -- old.status = 'draft' + if new.status = 'deprecated' then + raise exception 'a draft cannot be deprecated; delete it' using errcode = '55000'; + end if; + return new; +end; +$$; + +create trigger anatomical_sheet_versions_guard_update + before update on public.anatomical_sheet_versions + for each row execute function private.guard_sheet_version_update(); + +-- Dependents that block a physical delete (business architecture §16). +-- Reports join this check when their table exists. +create or replace function private.sheet_version_dependents(p_version_id uuid) +returns text[] +language sql +stable +security definer +set search_path = '' +as $$ + select array_remove(array[ + case when exists ( + select 1 from public.anatomical_sheets s where s.current_version_id = p_version_id + ) then 'current_version' end, + case when exists ( + select 1 from public.anatomical_sheets s + where s.based_on_version_id = p_version_id and s.status <> 'deleted' + ) then 'active_fork' end + ], null); +$$; + +create or replace function private.guard_sheet_version_delete() +returns trigger +language plpgsql +set search_path = '' +as $$ +declare + v_dependents text[]; +begin + if old.status = 'published' then + raise exception 'published version % cannot be deleted; deprecate it first', old.id + using errcode = '55000'; + end if; + v_dependents := private.sheet_version_dependents(old.id); + if coalesce(array_length(v_dependents, 1), 0) > 0 then + raise exception 'version % still has dependents: %', old.id, v_dependents + using errcode = '55000'; + end if; + return old; +end; +$$; + +create trigger anatomical_sheet_versions_guard_delete + before delete on public.anatomical_sheet_versions + for each row execute function private.guard_sheet_version_delete(); + +-- --------------------------------------------------------------------------- +-- Document referential checks (publication gate). Mirrors the error-level +-- rules of packages/domain validateSheetDocument that need no recursion. +-- --------------------------------------------------------------------------- +create or replace function private.append_issue(p_issues text[], p_code text) +returns text[] +language sql +immutable +set search_path = '' +as $$ + select case when p_issues @> array[p_code] then p_issues else p_issues || p_code end; +$$; + +create or replace function private.sheet_document_issues(p_doc jsonb) +returns text[] +language plpgsql +immutable +set search_path = '' +as $$ +declare + v_issues text[] := '{}'; + v_views jsonb := coalesce(p_doc -> 'views', '[]'::jsonb); + v_anns jsonb := coalesce(p_doc -> 'annotations', '[]'::jsonb); + v_cats jsonb := coalesce(p_doc -> 'categories', '[]'::jsonb); + v_zones jsonb := coalesce(p_doc -> 'finding_zones', '[]'::jsonb); + v_regs jsonb := coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb); + r record; +begin + if jsonb_typeof(v_views) <> 'array' or jsonb_typeof(v_anns) <> 'array' + or jsonb_typeof(v_cats) <> 'array' or jsonb_typeof(v_zones) <> 'array' + or jsonb_typeof(v_regs) <> 'array' then + return array['document.shape']; + end if; + + if (select count(*) from jsonb_array_elements(v_views) v where v ->> 'kind' = 'main') <> 1 then + v_issues := private.append_issue(v_issues, 'view.main.count'); + end if; + if exists (select 1 from jsonb_array_elements(v_views) v group by v ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'view.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_anns) a group by a ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'annotation.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_cats) c group by c ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'category.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_zones) z group by z ->> 'id' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'finding_zone.id.duplicate'); + end if; + if exists (select 1 from jsonb_array_elements(v_regs) g group by g ->> 'code' having count(*) > 1) then + v_issues := private.append_issue(v_issues, 'region.code.duplicate'); + end if; + + for r in + select v ->> 'id' as id, v ->> 'kind' as kind, v ->> 'parent_view_id' as parent, + v ->> 'svg_asset_id' as asset, v -> 'view_box' as view_box + from jsonb_array_elements(v_views) v + loop + if r.kind = 'detail' then + if not exists (select 1 from jsonb_array_elements(v_views) p where p ->> 'id' = r.parent) then + v_issues := private.append_issue(v_issues, 'view.parent.missing'); + elsif not exists ( + select 1 from jsonb_array_elements(v_anns) a + where a ->> 'kind' = 'detail_trigger' + and a ->> 'opens_view_id' = r.id and a ->> 'view_id' = r.parent + ) then + v_issues := private.append_issue(v_issues, 'view.unreachable'); + end if; + if r.asset is null and (r.view_box is null or jsonb_typeof(r.view_box) = 'null') then + v_issues := private.append_issue(v_issues, 'view.asset.missing'); + end if; + elsif r.asset is null then + v_issues := private.append_issue(v_issues, 'view.asset.missing'); + end if; + end loop; + + for r in + select a ->> 'kind' as kind, a ->> 'view_id' as view_id, a ->> 'category_id' as category_id, + a ->> 'opens_view_id' as opens, a ->> 'finding_zone_id' as zone, + a ->> 'vertebral_region_code' as region + from jsonb_array_elements(v_anns) a + loop + if not exists (select 1 from jsonb_array_elements(v_views) v where v ->> 'id' = r.view_id) then + v_issues := private.append_issue(v_issues, 'annotation.view.missing'); + end if; + if not exists (select 1 from jsonb_array_elements(v_cats) c where c ->> 'id' = r.category_id) then + v_issues := private.append_issue(v_issues, 'annotation.category.missing'); + end if; + if r.kind = 'detail_trigger' and not exists ( + select 1 from jsonb_array_elements(v_views) v + where v ->> 'id' = r.opens and v ->> 'kind' = 'detail' and v ->> 'parent_view_id' = r.view_id + ) then + v_issues := private.append_issue(v_issues, 'annotation.opens_view.invalid'); + end if; + if r.zone is not null and not exists ( + select 1 from jsonb_array_elements(v_zones) z where z ->> 'id' = r.zone + ) then + v_issues := private.append_issue(v_issues, 'annotation.finding_zone.missing'); + end if; + if r.region is not null and not exists ( + select 1 from jsonb_array_elements(v_regs) g where g ->> 'code' = r.region + ) then + v_issues := private.append_issue(v_issues, 'annotation.region.missing'); + end if; + end loop; + + return v_issues; +end; +$$; + +comment on function private.sheet_document_issues(jsonb) is + 'Error-level referential rules of the canonical document (codes shared with packages/domain). Empty array = publishable as far as SQL can tell.'; + +-- Every svg_asset_id used by a view must be an asset registered for the sheet. +create or replace function private.sheet_document_unknown_assets(p_sheet_id uuid, p_doc jsonb) +returns text[] +language sql +stable +security definer +set search_path = '' +as $$ + select coalesce(array_agg(v ->> 'svg_asset_id'), '{}') + from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v + where v ->> 'svg_asset_id' is not null + and not exists ( + select 1 from public.anatomical_sheet_assets a + where a.sheet_id = p_sheet_id and a.id::text = v ->> 'svg_asset_id' + ); +$$; + +-- --------------------------------------------------------------------------- +-- Access helpers (security definer, read the sheets bypassing their policies) +-- --------------------------------------------------------------------------- +create or replace function private.can_edit_sheet(p_user_id uuid, p_sheet_id uuid) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.anatomical_sheets s + where s.id = p_sheet_id + and s.status <> 'deleted' + and ( + (s.creator_user_id is not null and s.creator_user_id = p_user_id) + or (s.is_official and private.is_platform_admin(p_user_id)) + ) + ); +$$; + +-- Grants and follows (community step) will widen this predicate. +create or replace function private.can_use_sheet(p_user_id uuid, p_sheet_id uuid) +returns boolean +language sql +stable +security definer +set search_path = '' +as $$ + select exists ( + select 1 from public.anatomical_sheets s + where s.id = p_sheet_id + and s.status = 'active' + and (s.visibility = 'public' or private.can_edit_sheet(p_user_id, p_sheet_id)) + ); +$$; + +comment on function private.can_edit_sheet(uuid, uuid) is 'creator of a non-deleted sheet, or platform admin on an official sheet.'; +comment on function private.can_use_sheet(uuid, uuid) is 'active sheet that is public or editable by the user. Follows/grants plug in here later.'; + +grant execute on function private.can_edit_sheet(uuid, uuid) to authenticated; +grant execute on function private.can_use_sheet(uuid, uuid) to authenticated; + +-- --------------------------------------------------------------------------- +-- Internal helpers for the RPCs +-- --------------------------------------------------------------------------- +create or replace function private.require_actor() +returns uuid +language plpgsql +stable +set search_path = '' +as $$ +declare + v_actor uuid := auth.uid(); +begin + if v_actor is null then + raise exception 'authentication required' using errcode = '42501'; + end if; + return v_actor; +end; +$$; + +create or replace function private.require_sheet_editor(p_actor uuid, p_sheet_id uuid) +returns void +language plpgsql +stable +set search_path = '' +as $$ +begin + if not private.can_edit_sheet(p_actor, p_sheet_id) then + raise exception 'not an editor of sheet %', p_sheet_id using errcode = '42501'; + end if; +end; +$$; + +-- Inserts a draft with the next version number. The sheet row is locked so +-- two concurrent calls cannot pick the same number. +create or replace function private.insert_sheet_draft( + p_actor uuid, + p_sheet_id uuid, + p_content jsonb, + p_change_note text +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_number integer; + v_id uuid; +begin + perform 1 from public.anatomical_sheets where id = p_sheet_id for update; + if exists ( + select 1 from public.anatomical_sheet_versions + where sheet_id = p_sheet_id and status = 'draft' + ) then + raise exception 'sheet % already has a draft', p_sheet_id using errcode = '23505'; + end if; + select coalesce(max(version_number), 0) + 1 into v_number + from public.anatomical_sheet_versions where sheet_id = p_sheet_id; + + insert into public.anatomical_sheet_versions ( + sheet_id, version_number, status, document_schema_version, content, change_note, created_by + ) + values ( + p_sheet_id, v_number, 'draft', (p_content ->> 'schema_version')::integer, + p_content, coalesce(p_change_note, ''), p_actor + ) + returning id into v_id; + + perform private.log_event( + p_actor, 'anatomical_sheet_version.created', 'anatomical_sheet_version', v_id, null, null, + jsonb_build_object('sheet_id', p_sheet_id, 'version_number', v_number) + ); + return v_id; +end; +$$; + +-- Copies the asset rows of one sheet to another; returns old id → new id. +create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid) +returns jsonb +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_map jsonb := '{}'::jsonb; + v_new uuid; + r record; +begin + for r in + select id, sha256, byte_size, content_type, file_name + from public.anatomical_sheet_assets where sheet_id = p_from + loop + insert into public.anatomical_sheet_assets ( + sheet_id, sha256, byte_size, content_type, file_name, created_by + ) + values (p_to, r.sha256, r.byte_size, r.content_type, r.file_name, p_actor) + returning id into v_new; + v_map := v_map || jsonb_build_object(r.id::text, v_new::text); + end loop; + return v_map; +end; +$$; + +-- Rewrites views[].svg_asset_id through an old → new map. +create or replace function private.remap_document_assets(p_doc jsonb, p_map jsonb) +returns jsonb +language sql +immutable +set search_path = '' +as $$ + select jsonb_set( + p_doc, + '{views}', + coalesce(( + select jsonb_agg( + case + when v ->> 'svg_asset_id' is not null and p_map ? (v ->> 'svg_asset_id') + then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> (v ->> 'svg_asset_id'))) + else v + end + order by ord + ) + from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) with ordinality as t(v, ord) + ), '[]'::jsonb) + ); +$$; + +-- --------------------------------------------------------------------------- +-- RPCs (authenticated callers; every call audited) +-- --------------------------------------------------------------------------- +create or replace function public.create_anatomical_sheet( + species_id text, + name text, + slug text, + document jsonb, + description text default '', + visibility public.sheet_visibility default 'private', + official boolean default false +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_sheet uuid; +begin + if official and not private.is_platform_admin(v_actor) then + raise exception 'only platform admins create official sheets' using errcode = '42501'; + end if; + if not exists (select 1 from public.species s where s.id = species_id and s.active) then + raise exception 'unknown species %', species_id using errcode = 'P0002'; + end if; + + insert into public.anatomical_sheets ( + species_id, name, slug, description, creator_user_id, is_official, visibility + ) + values ( + species_id, name, slug, coalesce(description, ''), + case when official then null else v_actor end, official, visibility + ) + returning id into v_sheet; + + perform private.log_event( + v_actor, 'anatomical_sheet.created', 'anatomical_sheet', v_sheet, null, null, + jsonb_build_object('species_id', species_id, 'official', official, 'visibility', visibility) + ); + perform private.insert_sheet_draft(v_actor, v_sheet, document, 'Initial draft'); + return v_sheet; +end; +$$; + +create or replace function public.create_sheet_draft( + sheet_id uuid, + from_version_id uuid default null, + change_note text default '' +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_source uuid; + v_content jsonb; +begin + perform private.require_sheet_editor(v_actor, sheet_id); + select coalesce(from_version_id, s.current_version_id) into v_source + from public.anatomical_sheets s where s.id = sheet_id; + + select v.content into v_content + from public.anatomical_sheet_versions v + where v.id = v_source and v.sheet_id = create_sheet_draft.sheet_id and v.status <> 'draft'; + if v_content is null then + raise exception 'no published version to start from (sheet %)', sheet_id using errcode = 'P0002'; + end if; + return private.insert_sheet_draft(v_actor, sheet_id, v_content, change_note); +end; +$$; + +create or replace function public.publish_sheet_version(version_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_version public.anatomical_sheet_versions%rowtype; + v_issues text[]; +begin + select * into v_version from public.anatomical_sheet_versions where id = version_id for update; + if v_version.id is null then + raise exception 'unknown version %', version_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_version.sheet_id); + if v_version.status <> 'draft' then + raise exception 'version % is not a draft', version_id using errcode = '55000'; + end if; + + v_issues := private.sheet_document_issues(v_version.content); + if coalesce(array_length(v_issues, 1), 0) > 0 then + raise exception 'document not publishable: %', array_to_string(v_issues, ', ') + using errcode = '23514'; + end if; + v_issues := private.sheet_document_unknown_assets(v_version.sheet_id, v_version.content); + if coalesce(array_length(v_issues, 1), 0) > 0 then + raise exception 'document not publishable: view.asset.unknown %', array_to_string(v_issues, ', ') + using errcode = '23514'; + end if; + + update public.anatomical_sheet_versions + set status = 'published', published_at = now(), published_by = v_actor + where id = version_id; + update public.anatomical_sheets + set current_version_id = version_id + where id = v_version.sheet_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_version.published', 'anatomical_sheet_version', version_id, null, null, + jsonb_build_object('sheet_id', v_version.sheet_id, 'version_number', v_version.version_number) + ); + return version_id; +end; +$$; + +create or replace function public.deprecate_sheet_version(version_id uuid, reason text default null) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_version public.anatomical_sheet_versions%rowtype; + v_next uuid; +begin + select * into v_version from public.anatomical_sheet_versions where id = version_id for update; + if v_version.id is null then + raise exception 'unknown version %', version_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_version.sheet_id); + if v_version.status <> 'published' then + raise exception 'version % is not published', version_id using errcode = '55000'; + end if; + + update public.anatomical_sheet_versions + set status = 'deprecated', deprecated_at = now(), deprecated_by = v_actor + where id = version_id; + + -- The sheet's current version moves to the latest remaining published one. + select id into v_next from public.anatomical_sheet_versions + where sheet_id = v_version.sheet_id and status = 'published' + order by version_number desc limit 1; + update public.anatomical_sheets + set current_version_id = v_next + where id = v_version.sheet_id and current_version_id = version_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_version.deprecated', 'anatomical_sheet_version', version_id, null, null, + jsonb_build_object('sheet_id', v_version.sheet_id, 'reason', reason) + ); + return version_id; +end; +$$; + +create or replace function public.delete_sheet_version(version_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_sheet uuid; + v_number integer; +begin + select sheet_id, version_number into v_sheet, v_number + from public.anatomical_sheet_versions where id = version_id; + if v_sheet is null then + raise exception 'unknown version %', version_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_sheet); + + -- Preconditions (published, current, active fork) are raised by the delete guard. + delete from public.anatomical_sheet_versions where id = version_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_version.deleted', 'anatomical_sheet_version', version_id, null, null, + jsonb_build_object('sheet_id', v_sheet, 'version_number', v_number) + ); + return version_id; +end; +$$; + +create or replace function public.fork_anatomical_sheet( + source_version_id uuid, + name text, + slug text, + visibility public.sheet_visibility default 'private' +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_source public.anatomical_sheet_versions%rowtype; + v_species text; + v_sheet uuid; + v_map jsonb; +begin + select * into v_source from public.anatomical_sheet_versions where id = source_version_id; + if v_source.id is null then + raise exception 'unknown version %', source_version_id using errcode = 'P0002'; + end if; + if not private.can_use_sheet(v_actor, v_source.sheet_id) then + raise exception 'sheet % is not usable by the caller', v_source.sheet_id using errcode = '42501'; + end if; + if v_source.status <> 'published' then + raise exception 'only a published version can be copied' using errcode = '55000'; + end if; + + select species_id into v_species from public.anatomical_sheets where id = v_source.sheet_id; + insert into public.anatomical_sheets ( + species_id, name, slug, creator_user_id, visibility, based_on_sheet_id, based_on_version_id + ) + values (v_species, name, slug, v_actor, visibility, v_source.sheet_id, source_version_id) + returning id into v_sheet; + + v_map := private.copy_sheet_assets(v_actor, v_source.sheet_id, v_sheet); + perform private.log_event( + v_actor, 'anatomical_sheet.forked', 'anatomical_sheet', v_sheet, null, null, + jsonb_build_object('source_sheet_id', v_source.sheet_id, 'source_version_id', source_version_id) + ); + perform private.insert_sheet_draft( + v_actor, v_sheet, private.remap_document_assets(v_source.content, v_map), + 'Copied from version ' || v_source.version_number + ); + return v_sheet; +end; +$$; + +create or replace function private.set_sheet_status( + p_actor uuid, + p_sheet uuid, + p_from public.sheet_status, + p_to public.sheet_status, + p_action text +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_status public.sheet_status; +begin + perform private.require_sheet_editor(p_actor, p_sheet); + select status into v_status from public.anatomical_sheets where id = p_sheet for update; + if v_status <> p_from then + raise exception 'sheet % is % (expected %)', p_sheet, v_status, p_from using errcode = '55000'; + end if; + update public.anatomical_sheets + set status = p_to, + archived_at = case when p_to = 'archived' then now() when p_to = 'active' then null else archived_at end, + deleted_at = case when p_to = 'deleted' then now() else deleted_at end + where id = p_sheet; + perform private.log_event(p_actor, p_action, 'anatomical_sheet', p_sheet); + return p_sheet; +end; +$$; + +create or replace function public.archive_anatomical_sheet(sheet_id uuid) +returns uuid +language sql +security definer +set search_path = '' +as $$ + select private.set_sheet_status( + private.require_actor(), sheet_id, 'active', 'archived', 'anatomical_sheet.archived' + ); +$$; + +create or replace function public.restore_anatomical_sheet(sheet_id uuid) +returns uuid +language sql +security definer +set search_path = '' +as $$ + select private.set_sheet_status( + private.require_actor(), sheet_id, 'archived', 'active', 'anatomical_sheet.restored' + ); +$$; + +-- Soft delete. Refused while another sheet still derives from one of its +-- versions (§16: no active fork). Published versions stay in place. +create or replace function public.delete_anatomical_sheet(sheet_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_status public.sheet_status; +begin + perform private.require_sheet_editor(v_actor, sheet_id); + if exists ( + select 1 from public.anatomical_sheets f + where f.based_on_sheet_id = delete_anatomical_sheet.sheet_id and f.status <> 'deleted' + ) then + raise exception 'sheet % still has active copies; archive it instead', sheet_id + using errcode = '55000'; + end if; + select status into v_status from public.anatomical_sheets where id = sheet_id; + return private.set_sheet_status(v_actor, sheet_id, v_status, 'deleted', 'anatomical_sheet.deleted'); +end; +$$; + +create or replace function public.register_sheet_asset( + sheet_id uuid, + sha256 text, + byte_size integer, + file_name text +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_id uuid; +begin + perform private.require_sheet_editor(v_actor, sheet_id); + select id into v_id from public.anatomical_sheet_assets a + where a.sheet_id = register_sheet_asset.sheet_id and a.sha256 = register_sheet_asset.sha256; + if v_id is not null then + return v_id; + end if; + + insert into public.anatomical_sheet_assets (sheet_id, sha256, byte_size, file_name, created_by) + values (sheet_id, sha256, byte_size, file_name, v_actor) + returning id into v_id; + + perform private.log_event( + v_actor, 'anatomical_sheet_asset.registered', 'anatomical_sheet_asset', v_id, null, null, + jsonb_build_object('sheet_id', sheet_id, 'sha256', sha256, 'byte_size', byte_size) + ); + return v_id; +end; +$$; + +create or replace function public.delete_sheet_asset(asset_id uuid) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); + v_sheet uuid; +begin + select sheet_id into v_sheet from public.anatomical_sheet_assets where id = asset_id; + if v_sheet is null then + raise exception 'unknown asset %', asset_id using errcode = 'P0002'; + end if; + perform private.require_sheet_editor(v_actor, v_sheet); + if exists ( + select 1 from public.anatomical_sheet_versions v, + jsonb_array_elements(coalesce(v.content -> 'views', '[]'::jsonb)) w + where v.sheet_id = v_sheet and w ->> 'svg_asset_id' = asset_id::text + ) then + raise exception 'asset % is referenced by a version', asset_id using errcode = '55000'; + end if; + + delete from public.anatomical_sheet_assets where id = asset_id; + perform private.log_event( + v_actor, 'anatomical_sheet_asset.deleted', 'anatomical_sheet_asset', asset_id, null, null, + jsonb_build_object('sheet_id', v_sheet) + ); + return asset_id; +end; +$$; + +comment on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) is + 'Creates a sheet and its draft version 1 from a canonical document. official = true needs a platform admin.'; +comment on function public.create_sheet_draft(uuid, uuid, text) is + 'Opens the single draft of a sheet, copied from a published version (default: current). 23505 when a draft exists.'; +comment on function public.publish_sheet_version(uuid) is + 'Draft → published after the SQL referential checks; becomes the sheet current version. Earlier published versions stay published.'; +comment on function public.deprecate_sheet_version(uuid, text) is + 'Published → deprecated (still readable, not offered for new reports). Current version moves to the latest published one.'; +comment on function public.delete_sheet_version(uuid) is + 'Physical delete; refused (55000) for published rows, the current version, or a version with active copies.'; +comment on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_visibility) is + 'Personal copy of a published version: new sheet with based_on_* provenance, assets copied, draft v1. The source is not modified.'; +comment on function public.delete_anatomical_sheet(uuid) is + 'Soft delete (status deleted); refused while active copies derive from the sheet.'; + +-- --------------------------------------------------------------------------- +-- Privileges + RLS +-- --------------------------------------------------------------------------- +revoke all on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) from public, anon; +revoke all on function public.create_sheet_draft(uuid, uuid, text) from public, anon; +revoke all on function public.publish_sheet_version(uuid) from public, anon; +revoke all on function public.deprecate_sheet_version(uuid, text) from public, anon; +revoke all on function public.delete_sheet_version(uuid) from public, anon; +revoke all on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_visibility) from public, anon; +revoke all on function public.archive_anatomical_sheet(uuid) from public, anon; +revoke all on function public.restore_anatomical_sheet(uuid) from public, anon; +revoke all on function public.delete_anatomical_sheet(uuid) from public, anon; +revoke all on function public.register_sheet_asset(uuid, text, integer, text) from public, anon; +revoke all on function public.delete_sheet_asset(uuid) from public, anon; + +grant execute on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) to authenticated, service_role; +grant execute on function public.create_sheet_draft(uuid, uuid, text) to authenticated, service_role; +grant execute on function public.publish_sheet_version(uuid) to authenticated, service_role; +grant execute on function public.deprecate_sheet_version(uuid, text) to authenticated, service_role; +grant execute on function public.delete_sheet_version(uuid) to authenticated, service_role; +grant execute on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_visibility) to authenticated, service_role; +grant execute on function public.archive_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.restore_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.delete_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.register_sheet_asset(uuid, text, integer, text) to authenticated, service_role; +grant execute on function public.delete_sheet_asset(uuid) to authenticated, service_role; + +revoke all on public.species from public, anon, authenticated; +revoke all on public.anatomical_sheets from public, anon, authenticated; +revoke all on public.anatomical_sheet_versions from public, anon, authenticated; +revoke all on public.anatomical_sheet_assets from public, anon, authenticated; + +grant select on public.species to authenticated; +grant select on public.anatomical_sheets to authenticated; +-- Editors change the identity columns in place; status, provenance, ownership go through RPCs. +grant update (name, slug, description, visibility) on public.anatomical_sheets to authenticated; +grant select on public.anatomical_sheet_versions to authenticated; +-- Draft autosave: editors patch content and change_note; the guards keep +-- published rows frozen whatever the grant says. +grant update (content, change_note) on public.anatomical_sheet_versions to authenticated; +grant delete on public.anatomical_sheet_versions to authenticated; +grant select on public.anatomical_sheet_assets to authenticated; + +alter table public.species enable row level security; +alter table public.anatomical_sheets enable row level security; +alter table public.anatomical_sheet_versions enable row level security; +alter table public.anatomical_sheet_assets enable row level security; + +create policy species_select_active + on public.species + for select + to authenticated + using (active); + +create policy anatomical_sheets_select_usable_or_editable + on public.anatomical_sheets + for select + to authenticated + using ( + private.can_use_sheet((select auth.uid()), id) + or private.can_edit_sheet((select auth.uid()), id) + ); + +create policy anatomical_sheets_update_editor + on public.anatomical_sheets + for update + to authenticated + using (private.can_edit_sheet((select auth.uid()), id)) + with check (private.can_edit_sheet((select auth.uid()), id)); + +-- Published and deprecated versions follow the sheet visibility; drafts are +-- visible to editors only. +create policy anatomical_sheet_versions_select + on public.anatomical_sheet_versions + for select + to authenticated + using ( + (status <> 'draft' and private.can_use_sheet((select auth.uid()), sheet_id)) + or private.can_edit_sheet((select auth.uid()), sheet_id) + ); + +create policy anatomical_sheet_versions_update_own_draft + on public.anatomical_sheet_versions + for update + to authenticated + using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)) + with check (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); + +create policy anatomical_sheet_versions_delete_own_draft + on public.anatomical_sheet_versions + for delete + to authenticated + using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); + +create policy anatomical_sheet_assets_select + on public.anatomical_sheet_assets + for select + to authenticated + using ( + private.can_use_sheet((select auth.uid()), sheet_id) + or private.can_edit_sheet((select auth.uid()), sheet_id) + ); diff --git a/supabase/tests/005_anatomical_sheets.sql b/supabase/tests/005_anatomical_sheets.sql new file mode 100644 index 00000000..b7151985 --- /dev/null +++ b/supabase/tests/005_anatomical_sheets.sql @@ -0,0 +1,511 @@ +-- Anatomical sheets: schema contract, lifecycle (allowed path), immutability, +-- copies with provenance, deletion preconditions, invalid documents, every +-- denied path (other user, anon, direct writes, official sheets). +-- Counts are scoped to fixture ids: the real stack also carries seed rows. +begin; +select plan(95); + +-- --------------------------------------------------------------------------- +-- Fixtures +-- --------------------------------------------------------------------------- +insert into auth.users (id, email) values + ('20000000-0000-0000-0000-000000000001', 'root-sheets@test.local'), + ('20000000-0000-0000-0000-00000000000a', 'alice-sheets@test.local'), + ('20000000-0000-0000-0000-00000000000b', 'bob-sheets@test.local'); +select private.assign_platform_role(null, '20000000-0000-0000-0000-000000000001', 'owner'); + +-- A small but complete document: two views (detail without its own asset), +-- a trigger, a bilateral joint, a spine zone, one finding zone. +create function pg_temp.sheet_doc(p_asset uuid) +returns jsonb +language sql +as $$ + select jsonb_build_object( + 'schema_version', 1, + 'species_id', 'equine', + 'name', jsonb_build_object('fr', 'Cheval test', 'en', 'Test horse'), + 'description', '{}'::jsonb, + 'scope_disclaimer', '{}'::jsonb, + 'attribution', jsonb_build_object('authors', '[]'::jsonb, 'license', null, 'notes', null), + 'vertebral_config', jsonb_build_object('regions', jsonb_build_array( + jsonb_build_object('code', 'C', 'name', jsonb_build_object('fr', 'Cervicales', 'en', 'Cervical'), 'count', 7) + )), + 'categories', jsonb_build_array( + jsonb_build_object('id', 'articulations', 'name', jsonb_build_object('fr', 'Articulations', 'en', 'Joints'), 'color', null) + ), + 'views', jsonb_build_array( + jsonb_build_object('id', 'view-main', 'kind', 'main', + 'name', jsonb_build_object('fr', 'Vue principale', 'en', 'Main view'), + 'svg_asset_id', p_asset, 'view_box', null), + jsonb_build_object('id', 'view-head', 'kind', 'detail', 'parent_view_id', 'view-main', + 'name', jsonb_build_object('fr', 'Tête', 'en', 'Head'), + 'svg_asset_id', null, + 'view_box', jsonb_build_object('min_x', 60, 'min_y', 100, 'width', 500, 'height', 380)) + ), + 'annotations', jsonb_build_array( + jsonb_build_object('id', 'hip', 'kind', 'point', 'view_id', 'view-main', 'category_id', 'articulations', + 'laterality', 'bilateral', 'geometry', null, + 'name', jsonb_build_object('fr', 'Hanche', 'en', 'Hip joint'), + 'finding_zone_id', 'hip', 'vertebral_region_code', null), + jsonb_build_object('id', 'cervical', 'kind', 'zone', 'view_id', 'view-main', 'category_id', 'articulations', + 'laterality', 'unpaired', 'geometry', null, + 'name', jsonb_build_object('fr', 'Vertèbres cervicales', 'en', 'Cervical vertebrae'), + 'finding_zone_id', null, 'vertebral_region_code', 'C'), + jsonb_build_object('id', 'head-trigger', 'kind', 'detail_trigger', 'view_id', 'view-main', + 'category_id', 'articulations', 'laterality', 'unpaired', 'geometry', null, + 'name', null, 'opens_view_id', 'view-head') + ), + 'finding_zones', jsonb_build_array( + jsonb_build_object('id', 'hip', 'name', jsonb_build_object('fr', 'Hanche', 'en', 'Hip'), + 'categories', jsonb_build_array( + jsonb_build_object('id', 'hip-dysfunctions', 'kind', 'dysfunction', + 'name', jsonb_build_object('fr', 'Dysfonctions', 'en', 'Dysfunctions'), + 'children', jsonb_build_array( + jsonb_build_object('id', 'articular', 'name', jsonb_build_object('fr', 'Articulaire', 'en', 'Articular')) + )) + )) + ) + ); +$$; + +create table pg_temp.ids (key text primary key, id uuid not null); +create function pg_temp.id(p_key text) returns uuid language sql stable +as $$ select id from pg_temp.ids where key = p_key $$; +-- The fixtures are read while impersonating the API roles. +grant all on pg_temp.ids to anon, authenticated; +grant execute on function pg_temp.id(text), pg_temp.sheet_doc(uuid) to anon, authenticated; + +-- --------------------------------------------------------------------------- +-- 1. Schema contract +-- --------------------------------------------------------------------------- +select has_table('public', 'species', 'table species exists'); +select has_table('public', 'anatomical_sheets', 'table anatomical_sheets exists'); +select has_table('public', 'anatomical_sheet_versions', 'table anatomical_sheet_versions exists'); +select has_table('public', 'anatomical_sheet_assets', 'table anatomical_sheet_assets exists'); +select enum_has_labels('public', 'sheet_visibility', array['private', 'public'], 'sheet_visibility labels'); +select enum_has_labels('public', 'sheet_status', array['active', 'archived', 'deleted'], 'sheet_status labels'); +select enum_has_labels('public', 'sheet_version_status', array['draft', 'published', 'deprecated'], 'sheet_version_status labels'); +select is( + (select count(*) from public.species where id = 'equine' and active), 1::bigint, + 'species equine is seeded by the migration' +); +select ok( + (select bool_and(relrowsecurity) from pg_class + where oid in ('public.species'::regclass, 'public.anatomical_sheets'::regclass, + 'public.anatomical_sheet_versions'::regclass, 'public.anatomical_sheet_assets'::regclass)), + 'RLS enabled on the four tables' +); +select ok(not has_table_privilege('anon', 'public.anatomical_sheets', 'select'), 'anon cannot select sheets'); +select ok(not has_table_privilege('anon', 'public.anatomical_sheet_versions', 'select'), 'anon cannot select versions'); +select ok(not has_table_privilege('anon', 'public.species', 'select'), 'anon cannot select species'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheets', 'insert'), 'authenticated cannot insert sheets directly'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheets', 'delete'), 'authenticated cannot delete sheets directly'); +select ok(not has_column_privilege('authenticated', 'public.anatomical_sheets', 'status', 'update'), 'authenticated cannot update sheets.status'); +select ok(not has_column_privilege('authenticated', 'public.anatomical_sheets', 'is_official', 'update'), 'authenticated cannot update sheets.is_official'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_versions', 'insert'), 'authenticated cannot insert versions directly'); +select ok(not has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'status', 'update'), 'authenticated cannot update versions.status'); +select ok(has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'content', 'update'), 'authenticated may update versions.content (RLS: own draft)'); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_assets', 'insert'), 'authenticated cannot insert assets directly'); +select ok(not has_function_privilege('anon', 'public.publish_sheet_version(uuid)', 'execute'), 'anon cannot execute publish_sheet_version'); + +-- --------------------------------------------------------------------------- +-- 2. Alice creates a private sheet (draft v1), registers an asset, publishes +-- --------------------------------------------------------------------------- +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); + +insert into pg_temp.ids select 'sheet', public.create_anatomical_sheet( + 'equine', 'Mon cheval', 'mon-cheval', pg_temp.sheet_doc(null), 'perso' +); +select results_eq( + $$ select creator_user_id, status::text, visibility::text, current_version_id, is_official + from public.anatomical_sheets where id = pg_temp.id('sheet') $$, + $$ values ('20000000-0000-0000-0000-00000000000a'::uuid, 'active', 'private', null::uuid, false) $$, + 'created sheet: creator alice, active, private, no current version' +); +insert into pg_temp.ids select 'v1', id from public.anatomical_sheet_versions + where sheet_id = pg_temp.id('sheet') and version_number = 1; +select is( + (select status::text from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + 'draft', 'version 1 is a draft' +); +select throws_ok( + $$ select public.create_anatomical_sheet('unicorn', 'x', 'x-x', pg_temp.sheet_doc(null)) $$, + 'P0002', null, 'unknown species is refused' +); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Dup', 'mon-cheval', pg_temp.sheet_doc(null)) $$, + '23505', null, 'slug is unique per owner' +); + +-- Publishing a draft whose main view has no asset is refused with the rule code +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', 'document not publishable: view.asset.missing', 'publish refuses a main view without asset' +); + +insert into pg_temp.ids select 'asset', public.register_sheet_asset( + pg_temp.id('sheet'), repeat('a', 64), 142400, 'Horse.svg' +); +select is( + public.register_sheet_asset(pg_temp.id('sheet'), repeat('a', 64), 142400, 'Horse.svg'), + pg_temp.id('asset'), 'registering the same sha256 again returns the same asset' +); + +-- Draft autosave: direct UPDATE of content through the policy +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')), change_note = 'asset wired' + where id = pg_temp.id('v1'); +select is( + (select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + pg_temp.id('asset')::text, 'editor updated the draft content in place' +); + +-- Unknown asset uuid is refused at publish +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc('ffffffff-ffff-ffff-ffff-ffffffffffff') + where id = pg_temp.id('v1'); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', null, 'publish refuses a view pointing at an asset not registered for the sheet' +); +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1'); + +-- Document species must match the sheet species (trigger) +select throws_ok( + $$ update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{species_id}', '"canine"') + where id = pg_temp.id('v1') $$, + '23514', null, 'a document for another species is refused' +); +-- Dangling references are refused at publish +update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,finding_zone_id}', '"nowhere"') + where id = pg_temp.id('v1'); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', 'document not publishable: annotation.finding_zone.missing', + 'publish refuses an annotation pointing at a missing finding zone' +); +update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,1,id}', '"hip"') + where id = pg_temp.id('v1'); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '23514', 'document not publishable: annotation.id.duplicate', + 'publish refuses duplicate annotation ids' +); +update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1'); + +select lives_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + 'alice publishes version 1' +); +select results_eq( + $$ select status::text, published_by, published_at is not null + from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$, + $$ values ('published', '20000000-0000-0000-0000-00000000000a'::uuid, true) $$, + 'version 1 is published by alice' +); +select is( + (select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')), + pg_temp.id('v1'), 'sheet current version is v1' +); +select throws_ok( + $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, + '55000', null, 'publishing twice is refused' +); + +-- --------------------------------------------------------------------------- +-- 3. Published rows are immutable (editor, then table owner) +-- --------------------------------------------------------------------------- +-- Through the API role the policies hide published rows from UPDATE/DELETE: +-- the statement touches zero rows instead of raising. +update public.anatomical_sheet_versions set content = '{}'::jsonb where id = pg_temp.id('v1'); +select is( + (select content from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + pg_temp.sheet_doc(pg_temp.id('asset')), 'editor UPDATE of published content touches no row' +); +update public.anatomical_sheet_versions set change_note = 'x' where id = pg_temp.id('v1'); +select is( + (select change_note from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + 'asset wired', 'editor UPDATE of a published change note touches no row' +); +delete from public.anatomical_sheet_versions where id = pg_temp.id('v1'); +select is( + (select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v1')), + 1::bigint, 'editor DELETE of a published version touches no row' +); +reset role; +select throws_ok( + $$ update public.anatomical_sheet_versions + set content = pg_temp.sheet_doc(pg_temp.id('asset')) || '{"name":{"fr":"X","en":"X"}}' + where id = pg_temp.id('v1') $$, + '42501', null, 'even the table owner cannot change published content' +); +select throws_ok( + $$ update public.anatomical_sheet_versions set status = 'draft' where id = pg_temp.id('v1') $$, + '42501', null, 'a published version cannot go back to draft' +); +select throws_ok( + $$ update public.anatomical_sheet_versions set version_number = 9 where id = pg_temp.id('v1') $$, + '42501', null, 'version_number is immutable' +); +select throws_ok( + $$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$, + '55000', null, 'owner role cannot delete a published version either' +); + +-- --------------------------------------------------------------------------- +-- 4. New version leaves the old one intact +-- --------------------------------------------------------------------------- +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +create table pg_temp.v1_snapshot as + select * from public.anatomical_sheet_versions where id = pg_temp.id('v1'); + +insert into pg_temp.ids select 'v2', public.create_sheet_draft(pg_temp.id('sheet'), null, 'second edition'); +select results_eq( + $$ select version_number, status::text, change_note, content = (select content from pg_temp.v1_snapshot) + from public.anatomical_sheet_versions where id = pg_temp.id('v2') $$, + $$ values (2, 'draft', 'second edition', true) $$, + 'draft v2 starts from the current version content' +); +select throws_ok( + $$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, + '23505', null, 'one draft per sheet' +); +update public.anatomical_sheet_versions + set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{name,fr}', '"Cheval v2"') + where id = pg_temp.id('v2'); +select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v2')) $$, 'alice publishes v2'); +select is( + (select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')), + pg_temp.id('v2'), 'current version moved to v2' +); +select is( + (select count(*) from public.anatomical_sheet_versions v, pg_temp.v1_snapshot s + where v.id = s.id and v.content = s.content and v.status = s.status + and v.published_at = s.published_at and v.version_number = s.version_number + and v.change_note = s.change_note), + 1::bigint, 'v1 row is byte-identical after v2 was published' +); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('v2')) $$, + '55000', null, 'the current version cannot be deleted' +); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('v1')) $$, + '55000', null, 'a published version cannot be deleted before deprecation' +); + +-- --------------------------------------------------------------------------- +-- 5. Bob: private sheet invisible; public sheet usable; copy keeps provenance +-- --------------------------------------------------------------------------- +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'bob does not see the private sheet'); +select is((select count(*) from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet')), 0::bigint, 'bob does not see its versions'); +select is((select count(*) from public.anatomical_sheet_assets where sheet_id = pg_temp.id('sheet')), 0::bigint, 'bob does not see its assets'); +select throws_ok( + $$ select public.fork_anatomical_sheet(pg_temp.id('v2'), 'Copie', 'copie-bob') $$, + '42501', null, 'bob cannot copy a private sheet' +); +select throws_ok( + $$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, + '42501', null, 'bob cannot open a draft on alice sheet' +); +update public.anatomical_sheets set name = 'hijack' where id = pg_temp.id('sheet'); +select throws_ok( + $$ insert into public.anatomical_sheets (species_id, name, slug, creator_user_id) + values ('equine', 'direct', 'direct', '20000000-0000-0000-0000-00000000000b') $$, + '42501', null, 'bob cannot insert a sheet row directly' +); +select throws_ok( + $$ insert into public.anatomical_sheet_versions (sheet_id, version_number, document_schema_version, content) + values (pg_temp.id('sheet'), 9, 1, pg_temp.sheet_doc(null)) $$, + '42501', null, 'bob cannot insert a version row directly' +); + +-- alice makes the sheet public through the identity-column policy +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob update on alice sheet changed nothing'); +update public.anatomical_sheets set visibility = 'public' where id = pg_temp.id('sheet'); +insert into pg_temp.ids select 'v3', public.create_sheet_draft(pg_temp.id('sheet'), null, 'work in progress'); + +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'bob sees the public sheet'); +select results_eq( + $$ select version_number from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet') order by 1 $$, + $$ values (1), (2) $$, + 'bob sees the published versions, not the draft' +); +select is( + (select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v3') and content = '{}'::jsonb), + 0::bigint, 'bob cannot read the draft' +); +update public.anatomical_sheet_versions set content = '{"schema_version":1}'::jsonb where id = pg_temp.id('v3'); +select throws_ok( + $$ select public.fork_anatomical_sheet(pg_temp.id('v3'), 'Copie', 'copie-bob') $$, + '55000', null, 'only a published version can be copied' +); + +create table pg_temp.source_snapshot as + select s.updated_at as sheet_updated_at, s.current_version_id, v.content, v.updated_at as version_updated_at, + (select count(*) from public.anatomical_sheet_assets where sheet_id = s.id) as asset_count + from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.current_version_id + where s.id = pg_temp.id('sheet'); + +insert into pg_temp.ids select 'fork', public.fork_anatomical_sheet(pg_temp.id('v2'), 'Copie de Bob', 'copie-bob'); +select results_eq( + $$ select creator_user_id, based_on_sheet_id, based_on_version_id, species_id, visibility::text, is_official + from public.anatomical_sheets where id = pg_temp.id('fork') $$, + $$ values ('20000000-0000-0000-0000-00000000000b'::uuid, pg_temp.id('sheet'), pg_temp.id('v2'), 'equine', 'private', false) $$, + 'copy records provenance (source sheet + version) and belongs to bob' +); +insert into pg_temp.ids select 'fork-v1', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('fork'); +insert into pg_temp.ids select 'fork-asset', id from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork'); +select results_eq( + $$ select version_number, status::text, created_by from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1') $$, + $$ values (1, 'draft', '20000000-0000-0000-0000-00000000000b'::uuid) $$, + 'copy starts as draft v1 owned by bob' +); +select results_eq( + $$ select sha256, byte_size, id <> pg_temp.id('asset') from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork') $$, + $$ values (repeat('a', 64), 142400, true) $$, + 'asset rows are copied (same content, new id)' +); +select is( + (select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')), + pg_temp.id('fork-asset')::text, 'copied document points at the copied asset' +); +select is( + (select content #- '{views,0,svg_asset_id}' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')), + (select content #- '{views,0,svg_asset_id}' from pg_temp.source_snapshot), + 'copied document is otherwise identical to the source' +); + +-- bob edits his copy; the source stays untouched +update public.anatomical_sheet_versions + set content = jsonb_set(content, '{name,fr}', '"Ma copie"') where id = pg_temp.id('fork-v1'); +select lives_ok($$ select public.publish_sheet_version(pg_temp.id('fork-v1')) $$, 'bob publishes his copy'); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is( + (select count(*) from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.current_version_id, + pg_temp.source_snapshot snap + where s.id = pg_temp.id('sheet') and s.updated_at = snap.sheet_updated_at and s.current_version_id = snap.current_version_id + and v.content = snap.content and v.updated_at = snap.version_updated_at + and (select count(*) from public.anatomical_sheet_assets where sheet_id = s.id) = snap.asset_count), + 1::bigint, 'source sheet, version and assets are unchanged by the copy and its edits' +); + +-- --------------------------------------------------------------------------- +-- 6. Deprecation, deletion preconditions, archive, soft delete +-- --------------------------------------------------------------------------- +select lives_ok($$ select public.deprecate_sheet_version(pg_temp.id('v2'), 'superseded') $$, 'alice deprecates v2'); +select results_eq( + $$ select status::text, deprecated_by from public.anatomical_sheet_versions where id = pg_temp.id('v2') $$, + $$ values ('deprecated', '20000000-0000-0000-0000-00000000000a'::uuid) $$, + 'v2 is deprecated' +); +select is( + (select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')), + pg_temp.id('v1'), 'current version falls back to the latest published one (v1)' +); +update public.anatomical_sheet_versions set content = '{}'::jsonb where id = pg_temp.id('v2'); +select is( + (select content ->> 'schema_version' from public.anatomical_sheet_versions where id = pg_temp.id('v2')), + '1', 'a deprecated version is hidden from editor UPDATE' +); +reset role; +select throws_ok( + $$ update public.anatomical_sheet_versions set change_note = 'late edit' where id = pg_temp.id('v2') $$, + '42501', null, 'a deprecated version is frozen for the table owner too' +); +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('v2')) $$, + '55000', null, 'v2 cannot be deleted while bob copy derives from it' +); +select throws_ok( + $$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, + '55000', null, 'the sheet cannot be deleted while a copy is active' +); +select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives the sheet'); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'an archived sheet is no longer usable by others'); +select throws_ok( + $$ select public.delete_sheet_version(pg_temp.id('fork-v1')) $$, + '55000', null, 'bob cannot delete the published version of his copy' +); +select lives_ok($$ select public.delete_anatomical_sheet(pg_temp.id('fork')) $$, 'bob soft-deletes his copy'); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('fork')), 0::bigint, 'a deleted sheet is invisible to its creator'); + +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores the sheet'); +select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v2')) $$, 'deprecated v2 is deleted once no active copy depends on it'); +select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v2')), 0::bigint, 'v2 row is gone'); +select lives_ok($$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v3') $$, 'editor drops her own draft directly'); +select throws_ok( + $$ select public.delete_sheet_asset(pg_temp.id('asset')) $$, + '55000', null, 'an asset referenced by a version cannot be deleted' +); + +-- --------------------------------------------------------------------------- +-- 7. Official sheets: platform admins only +-- --------------------------------------------------------------------------- +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Officielle', 'officielle', pg_temp.sheet_doc(null), '', 'public', true) $$, + '42501', null, 'a plain user cannot create an official sheet' +); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-000000000001","role":"authenticated"}', true); +insert into pg_temp.ids select 'official', public.create_anatomical_sheet( + 'equine', 'Faunosteo / Cheval', 'faunosteo-cheval', pg_temp.sheet_doc(null), 'Fiche officielle', 'public', true +); +select results_eq( + $$ select creator_user_id, is_official, visibility::text from public.anatomical_sheets where id = pg_temp.id('official') $$, + $$ values (null::uuid, true, 'public') $$, + 'official sheet is platform-owned' +); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('official')), 1::bigint, 'alice sees the public official sheet'); +select is( + (select count(*) from public.anatomical_sheet_versions where sheet_id = pg_temp.id('official')), + 0::bigint, 'alice does not see the official draft' +); +select throws_ok( + $$ select public.create_sheet_draft(pg_temp.id('official')) $$, + '42501', null, 'alice cannot edit the official sheet' +); + +-- --------------------------------------------------------------------------- +-- 8. Anonymous +-- --------------------------------------------------------------------------- +set local role anon; +select set_config('request.jwt.claims', '', true); +select throws_ok($$ select * from public.species $$, '42501', null, 'anon cannot read species'); +select throws_ok($$ select * from public.anatomical_sheets $$, '42501', null, 'anon cannot read sheets'); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'x', 'x-x', '{}'::jsonb) $$, + '42501', null, 'anon cannot call create_anatomical_sheet' +); + +-- --------------------------------------------------------------------------- +-- 9. Audit trail +-- --------------------------------------------------------------------------- +reset role; +select results_eq( + $$ select action from audit.audit_logs + where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('fork'), pg_temp.id('asset')) + group by action order by action collate "C" $$, + $$ values ('anatomical_sheet.archived'), ('anatomical_sheet.created'), ('anatomical_sheet.deleted'), + ('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet_asset.registered'), + ('anatomical_sheet_version.created'), ('anatomical_sheet_version.deleted'), + ('anatomical_sheet_version.deprecated'), ('anatomical_sheet_version.published') $$, + 'every lifecycle step left an audit event' +); + +select * from finish(); +rollback; From 8cac8b1a68023eeb4e2a567782aee7e7add108f4 Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:42:44 +0200 Subject: [PATCH 4/7] feat(supabase): regenerated types, row aliases, publishSheetVersion gate, schema test --- packages/supabase/package.json | 1 + packages/supabase/src/anatomical-sheets.ts | 31 ++ packages/supabase/src/database.types.ts | 306 ++++++++++++++++++ packages/supabase/src/index.ts | 16 + .../supabase/tests/anatomical-sheets.test.ts | 74 +++++ .../supabase/tests/db/schema-types.test.ts | 90 +++++- 6 files changed, 510 insertions(+), 8 deletions(-) create mode 100644 packages/supabase/src/anatomical-sheets.ts create mode 100644 packages/supabase/tests/anatomical-sheets.test.ts diff --git a/packages/supabase/package.json b/packages/supabase/package.json index be08c258..5e899890 100644 --- a/packages/supabase/package.json +++ b/packages/supabase/package.json @@ -19,6 +19,7 @@ "build": "tsc -p tsconfig.json --noEmit" }, "dependencies": { + "@faunosteo/domain": "workspace:*", "@supabase/supabase-js": "^2.100.0" }, "devDependencies": { diff --git a/packages/supabase/src/anatomical-sheets.ts b/packages/supabase/src/anatomical-sheets.ts new file mode 100644 index 00000000..373979c6 --- /dev/null +++ b/packages/supabase/src/anatomical-sheets.ts @@ -0,0 +1,31 @@ +import { + AnatomicalSheetDocumentSchema, + assertPublishable, +} from '@faunosteo/domain' +import type { FaunosteoClient } from './client' + +/** + * Publication gate on the client side: the full Zod shape and every + * integrity rule run before the RPC, so the editor gets the complete issue + * list. The database re-checks the referential rules on its own + * (private.sheet_document_issues); this call never replaces that guard. + */ +export async function publishSheetVersion( + client: FaunosteoClient, + versionId: string, +): Promise { + const draft = await client + .from('anatomical_sheet_versions') + .select('content') + .eq('id', versionId) + .single() + if (draft.error) throw draft.error + + assertPublishable(AnatomicalSheetDocumentSchema.parse(draft.data.content)) + + const published = await client.rpc('publish_sheet_version', { + version_id: versionId, + }) + if (published.error) throw published.error + return published.data +} diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index dade293c..23461cc7 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -9,6 +9,230 @@ export type Json = export type Database = { public: { Tables: { + anatomical_sheet_assets: { + Row: { + byte_size: number + content_type: string + created_at: string + created_by: string | null + file_name: string + id: string + sha256: string + sheet_id: string + } + ComputedFields: never + Insert: { + byte_size: number + content_type?: string + created_at?: string + created_by?: string | null + file_name: string + id?: string + sha256: string + sheet_id: string + } + Update: { + byte_size?: number + content_type?: string + created_at?: string + created_by?: string | null + file_name?: string + id?: string + sha256?: string + sheet_id?: string + } + Relationships: [ + { + foreignKeyName: 'anatomical_sheet_assets_created_by_fkey' + columns: ['created_by'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheet_assets_sheet_id_fkey' + columns: ['sheet_id'] + isOneToOne: false + referencedRelation: 'anatomical_sheets' + referencedColumns: ['id'] + }, + ] + } + anatomical_sheet_versions: { + Row: { + change_note: string + content: NonNullable + created_at: string + created_by: string | null + deprecated_at: string | null + deprecated_by: string | null + document_schema_version: number + id: string + published_at: string | null + published_by: string | null + sheet_id: string + status: Database['public']['Enums']['sheet_version_status'] + updated_at: string + version_number: number + } + ComputedFields: never + Insert: { + change_note?: string + content: NonNullable + created_at?: string + created_by?: string | null + deprecated_at?: string | null + deprecated_by?: string | null + document_schema_version: number + id?: string + published_at?: string | null + published_by?: string | null + sheet_id: string + status?: Database['public']['Enums']['sheet_version_status'] + updated_at?: string + version_number: number + } + Update: { + change_note?: string + content?: NonNullable + created_at?: string + created_by?: string | null + deprecated_at?: string | null + deprecated_by?: string | null + document_schema_version?: number + id?: string + published_at?: string | null + published_by?: string | null + sheet_id?: string + status?: Database['public']['Enums']['sheet_version_status'] + updated_at?: string + version_number?: number + } + Relationships: [ + { + foreignKeyName: 'anatomical_sheet_versions_created_by_fkey' + columns: ['created_by'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheet_versions_deprecated_by_fkey' + columns: ['deprecated_by'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheet_versions_published_by_fkey' + columns: ['published_by'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheet_versions_sheet_id_fkey' + columns: ['sheet_id'] + isOneToOne: false + referencedRelation: 'anatomical_sheets' + referencedColumns: ['id'] + }, + ] + } + anatomical_sheets: { + Row: { + archived_at: string | null + based_on_sheet_id: string | null + based_on_version_id: string | null + created_at: string + creator_user_id: string | null + current_version_id: string | null + deleted_at: string | null + description: string + id: string + is_official: boolean + name: string + slug: string + species_id: string + status: Database['public']['Enums']['sheet_status'] + updated_at: string + visibility: Database['public']['Enums']['sheet_visibility'] + } + ComputedFields: never + Insert: { + archived_at?: string | null + based_on_sheet_id?: string | null + based_on_version_id?: string | null + created_at?: string + creator_user_id?: string | null + current_version_id?: string | null + deleted_at?: string | null + description?: string + id?: string + is_official?: boolean + name: string + slug: string + species_id: string + status?: Database['public']['Enums']['sheet_status'] + updated_at?: string + visibility?: Database['public']['Enums']['sheet_visibility'] + } + Update: { + archived_at?: string | null + based_on_sheet_id?: string | null + based_on_version_id?: string | null + created_at?: string + creator_user_id?: string | null + current_version_id?: string | null + deleted_at?: string | null + description?: string + id?: string + is_official?: boolean + name?: string + slug?: string + species_id?: string + status?: Database['public']['Enums']['sheet_status'] + updated_at?: string + visibility?: Database['public']['Enums']['sheet_visibility'] + } + Relationships: [ + { + foreignKeyName: 'anatomical_sheets_based_on_sheet_id_fkey' + columns: ['based_on_sheet_id'] + isOneToOne: false + referencedRelation: 'anatomical_sheets' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheets_based_on_version_fkey' + columns: ['based_on_version_id'] + isOneToOne: false + referencedRelation: 'anatomical_sheet_versions' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheets_creator_user_id_fkey' + columns: ['creator_user_id'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheets_current_version_fkey' + columns: ['current_version_id'] + isOneToOne: false + referencedRelation: 'anatomical_sheet_versions' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'anatomical_sheets_species_id_fkey' + columns: ['species_id'] + isOneToOne: false + referencedRelation: 'species' + referencedColumns: ['id'] + }, + ] + } profile_roles: { Row: { granted_at: string @@ -108,11 +332,76 @@ export type Database = { } Relationships: [] } + species: { + Row: { + active: boolean + created_at: string + id: string + name_en: string + name_fr: string + sort_order: number + } + ComputedFields: never + Insert: { + active?: boolean + created_at?: string + id: string + name_en: string + name_fr: string + sort_order?: number + } + Update: { + active?: boolean + created_at?: string + id?: string + name_en?: string + name_fr?: string + sort_order?: number + } + Relationships: [] + } } Views: { [_ in never]: never } Functions: { + archive_anatomical_sheet: { Args: { sheet_id: string }; Returns: string } + create_anatomical_sheet: { + Args: { + description?: string + document: Json + name: string + official?: boolean + slug: string + species_id: string + visibility?: Database['public']['Enums']['sheet_visibility'] + } + Returns: string + } + create_sheet_draft: { + Args: { + change_note?: string + from_version_id?: string + sheet_id: string + } + Returns: string + } + delete_anatomical_sheet: { Args: { sheet_id: string }; Returns: string } + delete_sheet_asset: { Args: { asset_id: string }; Returns: string } + delete_sheet_version: { Args: { version_id: string }; Returns: string } + deprecate_sheet_version: { + Args: { reason?: string; version_id: string } + Returns: string + } + fork_anatomical_sheet: { + Args: { + name: string + slug: string + source_version_id: string + visibility?: Database['public']['Enums']['sheet_visibility'] + } + Returns: string + } grant_platform_role: { Args: { role: Database['public']['Enums']['platform_role'] @@ -120,6 +409,17 @@ export type Database = { } Returns: string } + publish_sheet_version: { Args: { version_id: string }; Returns: string } + register_sheet_asset: { + Args: { + byte_size: number + file_name: string + sha256: string + sheet_id: string + } + Returns: string + } + restore_anatomical_sheet: { Args: { sheet_id: string }; Returns: string } revoke_platform_role: { Args: { reason?: string @@ -131,6 +431,9 @@ export type Database = { } Enums: { platform_role: 'owner' | 'admin' | 'moderator' | 'support' + sheet_status: 'active' | 'archived' | 'deleted' + sheet_version_status: 'draft' | 'published' | 'deprecated' + sheet_visibility: 'private' | 'public' } CompositeTypes: { [_ in never]: never @@ -259,6 +562,9 @@ export const Constants = { public: { Enums: { platform_role: ['owner', 'admin', 'moderator', 'support'], + sheet_status: ['active', 'archived', 'deleted'], + sheet_version_status: ['draft', 'published', 'deprecated'], + sheet_visibility: ['private', 'public'], }, }, } as const diff --git a/packages/supabase/src/index.ts b/packages/supabase/src/index.ts index b3ddf824..7738d67e 100644 --- a/packages/supabase/src/index.ts +++ b/packages/supabase/src/index.ts @@ -21,3 +21,19 @@ export type Profile = Tables<'profiles'> export type ProfileRole = Tables<'profile_roles'> /** owner | admin | moderator | support. Not a professional status. */ export type PlatformRole = Enums<'platform_role'> +export { publishSheetVersion } from './anatomical-sheets' + +/** Row of public.species. */ +export type Species = Tables<'species'> +/** Row of public.anatomical_sheets. */ +export type AnatomicalSheet = Tables<'anatomical_sheets'> +/** Row of public.anatomical_sheet_versions (content = canonical document). */ +export type AnatomicalSheetVersion = Tables<'anatomical_sheet_versions'> +/** Row of public.anatomical_sheet_assets. */ +export type AnatomicalSheetAsset = Tables<'anatomical_sheet_assets'> +/** private | public. */ +export type SheetVisibility = Enums<'sheet_visibility'> +/** active | archived | deleted. */ +export type SheetStatus = Enums<'sheet_status'> +/** draft | published | deprecated. */ +export type SheetVersionStatus = Enums<'sheet_version_status'> diff --git a/packages/supabase/tests/anatomical-sheets.test.ts b/packages/supabase/tests/anatomical-sheets.test.ts new file mode 100644 index 00000000..aec1e889 --- /dev/null +++ b/packages/supabase/tests/anatomical-sheets.test.ts @@ -0,0 +1,74 @@ +import { publishSheetVersion } from '../src' +import type { FaunosteoClient } from '../src' + +/** + * Stub of the two client calls publishSheetVersion makes. The real RPC is + * covered by supabase/tests/005_anatomical_sheets.sql; here the point is the + * order of the gate: no RPC call unless the document is publishable. + */ +function stubClient(content: unknown) { + const rpcCalls: unknown[] = [] + const client = { + from: () => ({ + select: () => ({ + eq: () => ({ + single: async () => ({ data: { content }, error: null }), + }), + }), + }), + rpc: async (name: string, args: unknown) => { + rpcCalls.push([name, args]) + return { data: 'published-id', error: null } + }, + } + return { client: client as unknown as FaunosteoClient, rpcCalls } +} + +const publishable = { + schema_version: 1, + species_id: 'equine', + name: { fr: 'Test', en: 'Test' }, + description: {}, + scope_disclaimer: {}, + attribution: { authors: [], license: null, notes: null }, + vertebral_config: { regions: [] }, + categories: [], + views: [ + { + id: 'view-main', + kind: 'main', + name: { fr: 'Vue', en: 'View' }, + svg_asset_id: '11111111-1111-4111-8111-111111111111', + view_box: null, + }, + ], + annotations: [], + finding_zones: [], +} + +describe('publishSheetVersion', () => { + it('calls the RPC once the document passes shape and integrity checks', async () => { + const { client, rpcCalls } = stubClient(publishable) + await expect(publishSheetVersion(client, 'v1')).resolves.toBe( + 'published-id', + ) + expect(rpcCalls).toEqual([['publish_sheet_version', { version_id: 'v1' }]]) + }) + + it('refuses a document with integrity errors before any RPC', async () => { + const { client, rpcCalls } = stubClient({ + ...publishable, + views: [{ ...publishable.views[0], svg_asset_id: null }], + }) + await expect(publishSheetVersion(client, 'v1')).rejects.toThrow( + /view\.asset\.missing/, + ) + expect(rpcCalls).toEqual([]) + }) + + it('refuses a document that does not match the schema', async () => { + const { client, rpcCalls } = stubClient({ schema_version: 2 }) + await expect(publishSheetVersion(client, 'v1')).rejects.toThrow() + expect(rpcCalls).toEqual([]) + }) +}) diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 75f48b3a..aff66993 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -20,6 +20,50 @@ type ColumnMap = { } const expectedColumns = { + anatomical_sheet_assets: [ + 'byte_size', + 'content_type', + 'created_at', + 'created_by', + 'file_name', + 'id', + 'sha256', + 'sheet_id', + ], + anatomical_sheet_versions: [ + 'change_note', + 'content', + 'created_at', + 'created_by', + 'deprecated_at', + 'deprecated_by', + 'document_schema_version', + 'id', + 'published_at', + 'published_by', + 'sheet_id', + 'status', + 'updated_at', + 'version_number', + ], + anatomical_sheets: [ + 'archived_at', + 'based_on_sheet_id', + 'based_on_version_id', + 'created_at', + 'creator_user_id', + 'current_version_id', + 'deleted_at', + 'description', + 'id', + 'is_official', + 'name', + 'slug', + 'species_id', + 'status', + 'updated_at', + 'visibility', + ], profile_roles: [ 'granted_at', 'granted_by', @@ -43,6 +87,7 @@ const expectedColumns = { 'timezone', 'updated_at', ], + species: ['active', 'created_at', 'id', 'name_en', 'name_fr', 'sort_order'], } as const satisfies ColumnMap // Compile-time: a column present in the type but absent from the list is an error. @@ -59,7 +104,26 @@ type FunctionArgs = { string)[] } const expectedFunctionArgs = { + archive_anatomical_sheet: ['sheet_id'], + create_anatomical_sheet: [ + 'description', + 'document', + 'name', + 'official', + 'slug', + 'species_id', + 'visibility', + ], + create_sheet_draft: ['change_note', 'from_version_id', 'sheet_id'], + delete_anatomical_sheet: ['sheet_id'], + delete_sheet_asset: ['asset_id'], + delete_sheet_version: ['version_id'], + deprecate_sheet_version: ['reason', 'version_id'], + fork_anatomical_sheet: ['name', 'slug', 'source_version_id', 'visibility'], grant_platform_role: ['role', 'target_user_id'], + publish_sheet_version: ['version_id'], + register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'], + restore_anatomical_sheet: ['sheet_id'], revoke_platform_role: ['reason', 'role', 'target_user_id'], } as const satisfies FunctionArgs @@ -78,6 +142,10 @@ interface ColumnRow { interface NameRow { name: string } +interface EnumRow { + name: string + labels: string[] +} interface FunctionRow { name: string args: string[] @@ -122,17 +190,23 @@ describe('database.types.ts matches the migrated schema', () => { expect(actual).toEqual(expected) }) - it('lists the enum labels in order', async () => { - const { rows } = await db.query( - `select e.enumlabel as name + it('lists every public enum with its labels in order', async () => { + const { rows } = await db.query( + `select t.typname as name, + array_agg(e.enumlabel order by e.enumsortorder) as labels from pg_enum e join pg_type t on t.oid = e.enumtypid join pg_namespace n on n.oid = t.typnamespace - where n.nspname = 'public' and t.typname = 'platform_role' - order by e.enumsortorder`, + where n.nspname = 'public' + group by t.typname order by t.typname`, ) - expect(rows.map((r) => r.name)).toEqual([ - ...Constants.public.Enums.platform_role, - ]) + const actual = Object.fromEntries(rows.map((r) => [r.name, r.labels])) + const expected = Object.fromEntries( + Object.entries(Constants.public.Enums).map(([name, labels]) => [ + name, + [...labels], + ]), + ) + expect(actual).toEqual(expected) }) it('lists exactly the public functions and their argument names', async () => { From 6966c54a2ed3d32538c6050ba4392416f73ecf5e Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:45:01 +0200 Subject: [PATCH 5/7] docs(docs): Step 4 sheet model in CLAUDE.md, SUPABASE.md, WORKSPACE, README, plan note, changelog --- CHANGELOG.md | 5 +++++ CLAUDE.md | 28 +++++++++++++++++++------ README.md | 1 + docs/development/IMPLEMENTATION_PLAN.md | 6 ++++++ docs/development/SUPABASE.md | 17 +++++++++++---- docs/development/WORKSPACE.md | 1 + packages/README.md | 6 +++--- 7 files changed, 51 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ee66cb9..6587c4cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added (SaaS migration, plan Steps 3–4) + +- **Supabase foundation** — local stack (`supabase/config.toml`), migrations (schemas `private` / `audit`, `profiles`, platform roles with audited RPCs), pgTAP suite run on PGlite (`pnpm test:run`) and on the real stack (`pnpm db:test`), `@faunosteo/supabase` typed client + generated types. No UI change. +- **Anatomical sheet model** — `@faunosteo/domain`: canonical sheet document (views tree, annotations with stable ids and explicit laterality, ordered vertebral regions, typed finding categories, explicit annotation → finding zone links, FR/EN labels) with integrity validation; tables `species`, `anatomical_sheets`, `anatomical_sheet_versions` (published rows immutable, one draft per sheet, deletion preconditions), `anatomical_sheet_assets`; lifecycle RPCs (create, draft, publish, deprecate, delete, fork with provenance, archive, assets) audited and under RLS. Spec: `docs/development/ANATOMICAL_SHEET_MODEL.md`. + ### Changed (SaaS migration, plan Step 2) - **pnpm workspace** — the application moved to `apps/app` (`@faunosteo/app`) with `git mv`; root commands (`pnpm typecheck|test:run|lint|build|dev`) delegate to the packages. `packages/` reserved, empty. CI workflow added (`.gitea/workflows/ci.yml`). diff --git a/CLAUDE.md b/CLAUDE.md index a00b3656..af91cb4e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,9 @@ writes conclusion, and exports an A4 PDF. PDF carries the full JSON state as a n attachment so importing it restores the session for a follow-up. SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase (PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and -audit log exist; the UI does not use the client yet (local-only flows unchanged). +audit log exist; Step 4 added the canonical anatomical sheet model (`packages/domain`, +tables `species`, `anatomical_sheets` / `_versions` / `_assets`). The UI does not use +the client yet (local-only flows unchanged). MVP species: equine only. Open-source MIT. --- @@ -43,8 +45,9 @@ MVP species: equine only. Open-source MIT. ## Build commands -pnpm workspace: `apps/app` = the private application, `packages/supabase` = -Supabase access layer (see `docs/development/WORKSPACE.md`). Every command +pnpm workspace: `apps/app` = the private application, `packages/domain` = pure +Zod domain model (anatomical sheet document), `packages/supabase` = Supabase +access layer (see `docs/development/WORKSPACE.md`). Every command below runs from the repository root and delegates to the packages. ```bash @@ -192,12 +195,15 @@ faunosteo/ ├─ eslint.config.js, index.html, package.json (@faunosteo/app) ├─ tsconfig*.json, vite.config.ts, vitest.config.ts │ (end of apps/app) +├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only) +│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules +│ └─ tests/{fixtures/horse-slice.ts,*.test.ts} ├─ packages/supabase/ ← @faunosteo/supabase -│ ├─ src/{index,client,database.types}.ts ← typed browser client + generated types -│ └─ tests/{client.test.ts,db/} ← PGlite harness, shim, pgTAP runner, schema↔types test +│ ├─ src/{index,client,database.types,anatomical-sheets}.ts ← typed client, generated types, publish gate +│ └─ tests/{client,anatomical-sheets}.test.ts, tests/db/ ← PGlite harness, shim, pgTAP runner, schema↔types test ├─ supabase/ │ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts -│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles +│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets │ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy ├─ packages/README.md ← shared packages index ├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker @@ -320,6 +326,16 @@ Database (Supabase) - A migration is never edited once applied. Each migration ships its pgTAP file with allowed AND denied cases, and a regenerated `database.types.ts`. - The browser holds the anon key only. `service_role` never appears in env.js, .env.example or code. +- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering. + +### Anatomical sheet model (packages/domain + migration 20261008110000) +- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs. +- Ids are stable slugs never derived from labels; labels are `{ fr, en }` objects. Annotation → findings is the + explicit `finding_zone_id`; vertebral regions are ordered data with free codes. No label matching at runtime. +- A published version is immutable (trigger, every role). Change = new draft (`create_sheet_draft`) then + `publish_sheet_version`. Integrity rule codes are shared by `validateSheetDocument` (TS) and + `private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table. +- Document schema change → bump `SHEET_DOCUMENT_SCHEMA_VERSION`, extend the SQL CHECK on `document_schema_version`. ### Component stubs - Scaffold stubs render
ComponentName placeholder
diff --git a/README.md b/README.md index 835cddb9..9a196ae2 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,7 @@ faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md) ├─ src/lib/ id, dates, assert utilities ├─ src/styles/ Tailwind v4 CSS + design tokens ├─ tests/unit/ vitest tests (apps/app/tests, incl. characterisation suite) +├─ packages/domain/ @faunosteo/domain: canonical anatomical sheet document (Zod) + integrity rules ├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness ├─ supabase/ CLI config, SQL migrations, local seed, pgTAP tests ├─ docker/ entrypoint.sh + nginx.conf diff --git a/docs/development/IMPLEMENTATION_PLAN.md b/docs/development/IMPLEMENTATION_PLAN.md index fcea9907..9e8a62e8 100644 --- a/docs/development/IMPLEMENTATION_PLAN.md +++ b/docs/development/IMPLEMENTATION_PLAN.md @@ -138,6 +138,12 @@ Tests: importer reproduces the Step 1 mapping table exactly; every audit 07 spec Manual validation: open IMPORT-REPORT.md: 27 annotations, 26 mapped, 1 detail trigger, 5 spine zones with region codes C/T/L/S/Cd, 9 bilateral, 2 views; diff document.json against docs/faunosteo-audit/anatomical-sheet-example.json for sanity. Definition of Done: seed document committed; packages/domain and packages/anatomy have no DOM import outside anatomy/dom/*; no runtime code imports zoneMatch outside legacy/. Risks: subtle divergences between parser and importer on the detail trigger (no name, category kept); Horse_head.svg id space overlaps if a future file reuses ids (mitigated by per-view id scoping in the importer). + Adjustment 2026-10-08 (user brief for Step 4): the step is split. Step 4 = model, validation, + persistence foundations and tests (packages/domain, migration 20261008110000_anatomical_sheets, + pgTAP 005, docs/development/ANATOMICAL_SHEET_MODEL.md). Step 4b = legacy importer producing the + official equine sheet as a DRAFT with an import report, published only after business review. + packages/anatomy is created at Step 4b. Labels use `{ fr, en }` objects, annotation→findings is + `finding_zone_id`, finding categories carry a `kind`; see the spec for the final field names. ``` ```text diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index ae9b6312..29ab6bdb 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -1,7 +1,8 @@ # Supabase: local stack, migrations, tests -Status: Step 3 deliverable, 2026-10-08. Covers the foundation only (profiles, -platform roles, audit log). Conventions: `BACKEND_ARCHITECTURE.md` §3–§9. +Status: Step 3 deliverable, extended at Step 4 (2026-10-08). Covers the +foundation (profiles, platform roles, audit log) and the anatomical sheet +tables (`ANATOMICAL_SHEET_MODEL.md`). Conventions: `BACKEND_ARCHITECTURE.md` §3–§9. ## 1. Layout @@ -11,13 +12,17 @@ supabase/ ├─ migrations/ forward-only SQL, _.sql │ ├─ 20261008100000_foundation.sql schemas private/audit, updated_at, audit log │ ├─ 20261008100100_profiles.sql profiles + auth.users trigger + RLS -│ └─ 20261008100200_platform_roles.sql platform_role, profile_roles, helpers, RPCs +│ ├─ 20261008100200_platform_roles.sql platform_role, profile_roles, helpers, RPCs +│ └─ 20261008110000_anatomical_sheets.sql species, sheets, immutable versions, assets, lifecycle RPCs ├─ seed.sql LOCAL dev accounts + first owner (never run in prod) └─ tests/ pgTAP, one file per concern, allowed AND denied paths packages/supabase/ ├─ src/client.ts createBrowserClient() (anon key, PKCE) ├─ src/database.types.ts `supabase gen types` output +├─ src/anatomical-sheets.ts publishSheetVersion(): Zod + integrity gate before the RPC └─ tests/db/ PGlite harness: runs the pgTAP files without Docker +packages/domain/ +└─ src/anatomical-sheet/ canonical sheet document (Zod), validateSheetDocument, createEmptySheetDocument ``` ## 2. Prerequisites @@ -89,7 +94,7 @@ Two runners, one SQL source of truth (`supabase/tests/*.sql`, pgTAP): | Command | Engine | Needs Docker | What runs | |---|---|---|---| -| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory | +| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory; publish gate | | `pnpm db:test` | `supabase test db` (pg_prove in the local stack) | yes | the same pgTAP files against the real Supabase image | `pnpm test:run` at the root runs the PGlite suite together with the app @@ -97,6 +102,10 @@ suite. The shim (`packages/supabase/tests/db/supabase-shim.sql`) recreates the API roles, `auth.users`, `auth.uid()` and the permissive default privileges of Supabase so that a forgotten `revoke` fails a test. +Two parity traps met so far: counts must be scoped to fixture ids (the real +stack carries `seed.sql` rows), and `order by` on text must pin +`collate "C"` (the real image sorts with a locale collation, PGlite with C). + How a test impersonates a user (same technique in both runners): ```sql diff --git a/docs/development/WORKSPACE.md b/docs/development/WORKSPACE.md index 0d2e68a3..7a17f3f3 100644 --- a/docs/development/WORKSPACE.md +++ b/docs/development/WORKSPACE.md @@ -13,6 +13,7 @@ faunosteo/ │ ├─ src/ public/ tests/ scripts/ index.html │ ├─ vite.config.ts vitest.config.ts tsconfig*.json eslint.config.js │ └─ package.json app dependencies and scripts +├─ packages/domain/ @faunosteo/domain: canonical anatomical sheet document (Zod) + integrity rules ├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL tests ├─ supabase/ Supabase CLI config, migrations, seed, pgTAP tests (docs/development/SUPABASE.md) ├─ docker/ nginx.conf, entrypoint.sh (unchanged) diff --git a/packages/README.md b/packages/README.md index e03e1ceb..7055acc2 100644 --- a/packages/README.md +++ b/packages/README.md @@ -8,11 +8,11 @@ Planned packages and the step that creates each one: | Package | Content | Created at | |---|---|---| -| `@faunosteo/domain` | Zod schemas: report document, anatomical sheet document, species, entitlement capabilities | Step 4 (sheet model) | -| `@faunosteo/anatomy` | SVG convention parser, legacy importer, renderer helpers, spine logic | Step 4 | +| `@faunosteo/domain` | Zod schemas: anatomical sheet document + integrity rules (**created**, Step 4); report document, entitlement capabilities later | Step 4 (sheet model) | +| `@faunosteo/anatomy` | SVG convention parser, legacy importer, renderer helpers, spine logic | Step 4b (importer) | | `@faunosteo/pdf` | export / import / attachment, render helpers | Step 6 (PDF v3) | | `@faunosteo/i18n` | FR/EN dictionaries (no React) + `useT` | first second consumer (public-web or worker) | -| `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite | **created**, Step 3 | +| `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite, sheet publish gate | **created**, Step 3 | | `@faunosteo/config` | runtime config resolution shared by app, public-web, worker | with public-web | | `@faunosteo/ui` | UI primitives and design tokens | only when public-web reuses them | From d3fa65af2994f61b4f56dba00bfc7a0828551f9e Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 23:59:39 +0200 Subject: [PATCH 6/7] fix(supabase): revoke PUBLIC EXECUTE on private helpers, audited visibility RPC, input caps, authz-first RPCs, +32 pgTAP checks --- .claude/memory/blockers.md | 9 + .claude/memory/decisions.md | 24 ++ .claude/memory/evals.md | 8 + .claude/memory/journal.md | 2 + .claude/memory/learnings.md | 21 ++ .claude/tasks/TODO.md | 12 +- docs/development/ANATOMICAL_SHEET_MODEL.md | 207 ++++++------ .../domain/src/anatomical-sheet/schema.ts | 8 +- .../tests/anatomical-sheet.schema.test.ts | 90 +++-- packages/supabase/src/database.types.ts | 10 + .../supabase/tests/db/schema-types.test.ts | 2 + .../20261008110000_anatomical_sheets.sql | 309 +++++++++++++----- ...261008110100_private_execute_hardening.sql | 28 ++ supabase/tests/001_schema.sql | 17 +- supabase/tests/005_anatomical_sheets.sql | 156 ++++++++- 15 files changed, 682 insertions(+), 221 deletions(-) create mode 100644 supabase/migrations/20261008110100_private_execute_hardening.sql diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index c21193b2..0632591f 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -58,3 +58,12 @@ Friction: `supabase start` → "permission denied … /var/run/docker.sock"; dae Root: host group membership; needs `sudo usermod -aG docker $USER` + re-login (user runs, not Claude). Workaround: PGlite harness (BDR-028) executes migrations + 81 pgTAP checks; CLI config parses (`supabase start` fails only at Docker inspect). Status: resolved 2026-10-08 (same day) — user added docker group; `supabase start` pulled postgres 17.11.0.004, applied 3 migrations + seed; `supabase test db` 81/81 after scoping counts to fixture ids (seed rows broke 6 absolute counts, PGlite had no seed); `gen types` adopted (CLI output unformatted → piped through prettier); REST script §8 matched expectations; `db reset` from zero OK. + +--- + +## BLK-007 | 2026-10-08 | Per-schema ALTER DEFAULT PRIVILEGES REVOKE is a no-op → private helpers kept PUBLIC EXECUTE + +Friction: Step 4 verifier + security gate both found every `private.*` function executable by `authenticated` (incl. definer helpers taking a caller-supplied actor: assign_platform_role, insert_sheet_draft). +Root: foundation ran `alter default privileges in schema private revoke execute on functions from public`; PostgreSQL adds per-schema defaults on top of the built-in PUBLIC EXECUTE, a per-schema REVOKE cannot remove it. Nothing reachable via API (PostgREST exposes public only, anon no USAGE on private) but the rule "EXECUTE revoked from public" was false. +Fix: explicit `revoke all on function private.f(args) from public` for every function (new migration 20261008110100 for the Step 3 helpers, inline for Step 4); pgTAP 001 census: anon executes nothing in private/audit, authenticated only the 7 policy predicates. +Status: resolved (commit on feature/step-04-anatomical-sheet-model). diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index f17ff41b..58a0cc70 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -255,3 +255,27 @@ Status: closed. CLI gen needs running stack. File written in generator format (Row/Insert/Update/Relationships/Functions/Enums/Constants). `schema-types.test.ts`: compile-time exhaustiveness (every Row column listed, every Args key listed) + runtime diff vs information_schema / pg_enum / pg_proc in PGlite; also pins RLS-on + no `using(true)` for every future public table. CI `db:types:check` diffs against real generator once Docker available; first real run may reformat (PostgrestVersion string) → regenerate + commit. Status: closed; column scalar types (uuid→string…) reviewed by hand, not executed. + +--- + +## BDR-030 | 2026-10-08 | Step 4 split: model + persistence now, importer → official equine DRAFT next + +User brief: no full equine import yet; first official horse sheet = draft, business content verified before publication. Plan Step 4 bundled model + importer. Split: Step 4 = packages/domain document + validation + migration + pgTAP + docs; Step 4b = legacy importer → draft + IMPORT-REPORT, publish on user go. packages/anatomy created at 4b. +Alt rejected: importer in same step → publishes seed v1 immutable before expert review (contradicts brief). +Status: closed (plan note added under Step 4). + +--- + +## BDR-031 | 2026-10-08 | Canonical sheet document shape (schema_version 1) + +Labels `{ fr, en }` objects (one LocalizedText, new locale = optional key) instead of name_fr/name_en pairs. Strict Zod objects (unknown key rejected). Structural records explicit `null`; finding tree nodes lean on input, `.default()` fills description/sources/children/requires_vet_referral (612 leaves). Views = tree (`parent_view_id`), detail `svg_asset_id` nullable = crop parent via `view_box` (C9). Annotation discriminated union point|zone|detail_trigger; `laterality` 4 values explicit (unpaired/bilateral/left/right); spine = `vertebral_region_code` → ordered `vertebral_config.regions` with free codes (C1/Q3); findings link = inline `finding_zone_id` (no separate map, no label matching); finding categories carry `kind` dysfunction|observation|anamnesis|custom; node ids unique among siblings so `(zone, path[])` addressing survives Step 5. Two tiers: shape (Zod, every save) vs integrity (`validateSheetDocument`, 17 coded rules, publish gate). +Alt rejected: name_fr/name_en flat (BDR-009 catalog style) → no locale extension; annotation_finding_map array → extra structure for a 1:N field; UUIDs as in-document ids → unreadable, legacy paths re-keyed. +Status: closed; category kind `observation` vs report Observation collision (C7) flagged to user. + +--- + +## BDR-032 | 2026-10-08 | Sheet persistence: trigger-enforced immutability, SQL publish re-check, content-addressed assets + +Tables species / anatomical_sheets / _versions / _assets. Published immutable via BEFORE UPDATE trigger (every role incl. owner; only published→deprecated with stamps); deprecated frozen; BEFORE DELETE trigger = preconditions (never published, never current, never base of active fork; reports join later) → no session flags, RPC just deletes. One draft per sheet (partial unique index, C8). Document↔row: CHECK `content->'schema_version' = to_jsonb(document_schema_version)`, trigger species match. `private.sheet_document_issues(jsonb)` re-checks the non-recursive error rules at publish + unknown asset ids → defense in depth, same codes as TS (BACKEND_ARCH "SQL doesn't re-implement Zod" kept for shape). Assets content-addressed (sha256, unique per sheet), Storage path `.svg` by convention, fork = metadata copy + `remap_document_assets`. Draft autosave = column-level UPDATE (content, change_note) policy on own draft (unaudited by design); identity (name/slug/description) column policy; visibility via audited `set_sheet_visibility` RPC and draft deletion via `delete_sheet_version` after gate review (sharing + deletion = sensitive state); `last_version_number` counter (no number reuse); content ≤ 2 MiB, byte_size ≤ 20 MiB, reason ≤ 500; `require_actor` refuses deactivated profiles; authz before lookup (unknown id = same 42501); fork copies only referenced assets. can_use_sheet = active ∧ (public ∨ editor) until grants/follows. Official sheet = creator null + is_official, platform admins edit. +Alt rejected: session-flag delete bypass (hacky); Zod-equivalent validation only in TS (browser not a boundary); per-sheet asset storage copy on fork (needs worker job). +Status: closed; names (`anatomical_sheet_assets`, storage layout, official ownership) listed for user confirmation. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 02aa2d67..86ae4ce7 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -56,3 +56,11 @@ Method: `supabase start` (postgres 17.11.0.004), `supabase test db`, `gen types Result: migrations + seed apply from zero; pgTAP 81/81 after fix; REST: alice 1 row, anon 42501, self-deactivate 42501 (column grant), self-grant 42501 (RPC message), cross-row PATCH 0 rows, owner grant → uuid, alice sees her role, owner reads 3 profiles; audit shows system bootstrap + owner grant. Anomalies: (1) 6 pgTAP counts assumed empty DB — seed rows on real stack (PGlite runs no seed) → scoped to fixture ids + neutralise foreign owners before last-owner test. (2) CLI gen output unformatted + `ComputedFields: never`, no `__InternalSupabase` → hand-written file replaced by generated+prettier; scripts pipe prettier. PGlite harness had hidden both: environment parity gap, not logic gap. Action: LRN-037 (tests must be seed-agnostic; generated files via deterministic formatter). BLK-006 resolved. + +## EVAL-008 | 2026-10-08 | Step 4 sheet model — domain tests, pgTAP both engines, fresh verifier + security gates + +Method: packages/domain 61 vitest (schema 29 + integrity 32, one per rule code); pgTAP 005 (127 checks) + 001 census on PGlite and real stack (`db reset`, `db test` 210/210, `gen types` diff clean); root check (typecheck, 356 tests, lint 0, build); fresh verifier (contract C1–C13) + security-auditor (semgrep 725 rules 0 findings + checklist). +Result: first gate pass → verifier ECARTS(5), security BLOCK(1): private EXECUTE not revoked (BLK-007), visibility change unaudited, 7 RPCs without non-editor denial test, doc/code mismatches, 75-line SQL function, `any` suppression in a test. All fixed same session: +32 pgTAP checks, hardening migration, visibility RPC, caps, authz-first, SQL check split in 4 functions, `set()/unset()` typed mutations. Second pass: fresh verifier (pending at write time). +Anomalies: 6 test-side fixes on first pgTAP run (RLS hides rows → "no change" asserts; data-modifying CTE; collation of `order by`; trigger name order decides errcode; audit list; pg_temp grants). Executor (opus) deviated usefully: RegionCode pattern separate from StableId. +Action: LRN-038/039/040, BLK-007. Keep the two-gate pass on every migration step. + diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 04f152b9..2bbaf8cf 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -178,3 +178,5 @@ SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domai Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pushed). Docker socket denied (BLK-006) → PGlite+pgtap harness (BDR-028). 3 migrations: foundation (private/audit, set_updated_at, append-only audit_logs, log_event), profiles (auth trigger, own-row RLS, column grants), platform_roles (4-value enum BDR-026, RPC-only writes audited BDR-027, helpers hierarchy). 81 pgTAP checks allowed+denied; packages/supabase (client PKCE, types in gen format BDR-029, schema↔types test); app env.supabase null-safe, lib/supabase.ts, entrypoint/env.example; CI supabase job; SUPABASE.md. 278+13 tests, typecheck/lint/build green. Not run: real stack, gen types, seed. LRN-035/036, EVAL-006. Next: user validation; Step 4 (sheet model) parallelizable; Docker access for real-stack proof. - Same day, Docker access granted by user: real stack up, pgTAP 81/81 after seed-agnostic fix, gen types adopted (prettier pipe), REST script verified, db reset OK. BLK-006 resolved, EVAL-007, LRN-037. Branch still awaiting user validation before finish. - Step 3 validated by user (session 4). chore/supabase-cli-gitignore finished into develop. Step 4 (sheet model) started on feature/step-04-anatomical-sheet-model. +- Step 4 (session 4): spec docs/development/ANATOMICAL_SHEET_MODEL.md; packages/domain (Zod doc strict, 17 integrity rules, 60 tests, opus executor); migration 20261008110000 (species, sheets, immutable versions, assets, 11 RPCs, RLS) + pgTAP 005 (95 checks); types regenerated on real stack (Docker now OK), pgTAP 176/176 real + PGlite; publishSheetVersion gate; docs synced. 5 commits on feature/step-04-anatomical-sheet-model. BDR-030/031/032, LRN-038/039. Verifier + security gates dispatched. Next: user validation, Step 4b importer → equine draft. +- Gates: verifier ECARTS(5) + security BLOCK(1) on first pass (private EXECUTE never revoked = BLK-007, foundation flaw). Fixed: hardening migration 20261008110100, explicit revokes + pgTAP census, set_sheet_visibility RPC, no direct draft DELETE, caps, authz-first, counter, asset copy scoped, SQL check split, url http(s) only. Real stack 210/210, root check green. Fresh verifier re-dispatched on the delta. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 8a3e34b9..fa8a9756 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -288,3 +288,24 @@ Apply: every migration; pin with pgTAP privilege checks. Real stack applies `seed.sql` before `supabase test db`; PGlite harness applies migrations only → absolute `count(*)` and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". `supabase gen types` (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both `db:types` and `db:types:check`, else CI diff flaps. Apply: any dual-runner test setup (shim vs real); any CI diff on generated code. + +--- + +## LRN-038 | 2026-10-08 | RLS filters, never raises: test "no change", and trigger guards under the owner role + +API-role UPDATE/DELETE on a row hidden by policy touches 0 rows silently → `throws_ok` wrong; assert the row unchanged afterwards (`is((select content ...), expected)`). Trigger-level immutability must be proven with `reset role` (table owner bypasses RLS). pgTAP `is()` cannot wrap a data-modifying CTE (`with u as (update …)` must be top level) → plain statement then a read. Triggers fire alphabetically by name: when two BEFORE triggers reject, the first name's errcode surfaces (species check 23514 before guard 42501) → pick test inputs that isolate the guard. +Apply: every RLS + trigger pgTAP file. + +--- + +## LRN-039 | 2026-10-08 | Dual-runner parity: pin collation, grant pg_temp fixtures to API roles + +Real Supabase image sorts text with a locale collation (`anatomical_sheet_asset…` before `anatomical_sheet.archived`), PGlite with C → `results_eq` on `order by text` flaps; pin `order by col collate "C"`. pg_temp tables/functions created as postgres are invisible to `set local role authenticated` → `grant all on pg_temp.t to anon, authenticated; grant execute on function pg_temp.f(...)`. jsonb equality check beats `(x->>'k')::int = n` in a CHECK (no cast error on garbage). +Apply: any pgTAP file with fixtures read while impersonating; any ordered results_eq (extends LRN-037). + +--- + +## LRN-040 | 2026-10-08 | Function privileges: revoke per function, pin with a pg_proc census + +`alter default privileges in schema X revoke execute on functions from public` does nothing (BLK-007). Pattern: every migration ends with `revoke all on function private.f(args) from public` per function + explicit grants; a pgTAP census (`has_function_privilege('anon'|'authenticated', p.oid, 'execute')` over pg_proc of private/audit, compared to an allowlist via `string_agg(... order by proname::text collate "C")`) fails the next omission. `results_eq` over `name`-typed columns vs text literals raises "could not determine which collation" on PGlite → compare one aggregated string. Trigger functions that call other private functions must be `security definer` once EXECUTE is revoked (the invoking API role no longer holds it). +Apply: every Supabase migration; the census is the backstop. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index de7853a6..24a2d08f 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -63,12 +63,12 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006 - [ ] Step 4 — canonical anatomical sheet model (2026-10-08, branch feature/step-04-anatomical-sheet-model). Scope re-split: model + validation + persistence + tests here; legacy importer → official equine DRAFT + import report = next step (user: no full import yet, draft verified before publication). Spec: docs/development/ANATOMICAL_SHEET_MODEL.md - [x] 4.0 context + spec: business §2.6–2.9/§7/§16/§17.3/§23, OPEN_QUESTIONS C1/C2/C8/C9/Q3/Q5/Q9, audit 07; ANATOMICAL_SHEET_MODEL.md written - - [ ] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability - - [ ] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS - - [ ] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish - - [ ] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test - - [ ] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG - - [ ] 4.6 verify: pnpm check (typecheck, test:run, lint, build), db:reset + db:test on real stack, fresh verifier + security gate; capitalize BDR/LRN/EVAL + - [x] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability + - [x] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS + - [x] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish + - [x] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test + - [x] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG + - [x] 4.6 verify: pnpm check green (61+17+278), db:reset + db:test 210/210 real stack, types in sync; verifier ECARTS(5) + security BLOCK(1) → all fixed (BLK-007 hardening migration, visibility RPC, +32 pgTAP, doc sync); BDR-030..032, LRN-038..040, EVAL-008 - [ ] Step 4b — legacy importer → official equine sheet as DRAFT (document.json + legacy-id-map + IMPORT-REPORT.md for business verification), publication after user validation --- diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md index 025a881b..53cdcfd7 100644 --- a/docs/development/ANATOMICAL_SHEET_MODEL.md +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -13,10 +13,10 @@ Out of scope here: the legacy importer and the official equine draft ## 1. Two layers -| Layer | Where | Role | -|---|---|---| -| Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). | -| Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. | +| Layer | Where | Role | +| ------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). | +| Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. | The database stores the document as JSONB in `anatomical_sheet_versions.content`. Zod is the shape contract at the @@ -95,11 +95,11 @@ Why these shapes: ### 2.1 Validation tiers -| Tier | Function | When | -|---|---|---| -| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | -| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` | -| Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below | +| Tier | Function | When | +| ---------- | ------------------------------------------ | ----------------------------------------------------------------------------- | +| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) | +| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` | +| Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below | `SheetIssue = { code, severity: 'error' | 'warning', path, message }`; the path names the offending field (`annotations[0].category_id`), the later @@ -108,23 +108,23 @@ entry for a duplicate, the item itself for `view.unreachable` and Integrity rules (error unless stated): -| Code | Rule | -|---|---| -| `view.main.count` | exactly one `main` view | -| `view.id.duplicate` | view ids unique | -| `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view | -| `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view | -| `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` | -| `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) | -| `annotation.view.missing` | `view_id` exists | -| `annotation.category.missing` | `category_id` exists | -| `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view | -| `annotation.finding_zone.missing` | `finding_zone_id` exists | -| `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` | -| `annotation.no_findings` (warning) | point / zone without `finding_zone_id` | -| `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness | -| `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) | -| `finding_zone.unreferenced` (warning) | zone no annotation points to | +| Code | Rule | +| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `view.main.count` | exactly one `main` view | +| `view.id.duplicate` | view ids unique | +| `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view | +| `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view | +| `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` | +| `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) | +| `annotation.view.missing` | `view_id` exists | +| `annotation.category.missing` | `category_id` exists | +| `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view | +| `annotation.finding_zone.missing` | `finding_zone_id` exists | +| `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` | +| `annotation.no_findings` (warning) | point / zone without `finding_zone_id` | +| `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness | +| `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) | +| `finding_zone.unreferenced` (warning) | zone no annotation points to | A draft may be saved with errors. Publishing a document with errors is refused in TypeScript (`assertPublishable`) and in SQL @@ -149,43 +149,46 @@ any authenticated user; no write path through the API (platform step later). ### `anatomical_sheets` -| Column | Notes | -|---|---| -| `id uuid` | | -| `species_id` | FK species | -| `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets | -| `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) | -| `is_official boolean` | only a platform admin can create one; editable by platform admins | -| `visibility` | enum `sheet_visibility`: `private` \| `public` | -| `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) | -| `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source | -| `current_version_id` | latest published version (nullable while draft-only) | -| `archived_at`, `deleted_at`, `created_at`, `updated_at` | | +| Column | Notes | +| ------------------------------------------------------- | ------------------------------------------------------------------------------------ | +| `id uuid` | | +| `species_id` | FK species | +| `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets | +| `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) | +| `is_official boolean` | only a platform admin can create one; editable by platform admins | +| `visibility` | enum `sheet_visibility`: `private` \| `public` | +| `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) | +| `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source | +| `current_version_id` | latest published version (nullable while draft-only) | +| `last_version_number` | monotonic counter: a deleted version's number is never reused | +| `archived_at`, `deleted_at`, `created_at`, `updated_at` | | ### `anatomical_sheet_versions` -| Column | Notes | -|---|---| -| `id uuid`, `sheet_id` | | -| `version_number int` | unique per sheet, assigned by the server (`max + 1`) | -| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | -| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | -| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` | -| `change_note text` | what changed in this version | -| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | -| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | +| Column | Notes | +| ----------------------------------------------------------- | ------------------------------------------------------------------------ | +| `id uuid`, `sheet_id` | | +| `version_number int` | unique per sheet, assigned by the server (`max + 1`) | +| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | +| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | +| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` and size ≤ 2 MiB | +| `change_note text` | what changed in this version | +| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | +| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | Rules enforced by triggers (every role, including the table owner): - **One draft per sheet** (partial unique index, C8). - **Published rows are immutable**: the only accepted UPDATE on a `published` row is the transition to `deprecated` (status, `deprecated_at`, - `deprecated_by`); any other column change raises `42501`. A `deprecated` - row is frozen. + `deprecated_by`); a change to any compared column (content, schema + version, number, sheet, note, authorship, timestamps) raises `42501` for + every role, table owner included. Through the API the row is simply + invisible to UPDATE (zero rows touched). A `deprecated` row is frozen. - **Deletion preconditions** (BEFORE DELETE): never a `published` row; never - the `current_version_id` of its sheet; never a version some sheet is - `based_on`; (reports: added when the table exists, §16). A `draft` has no - dependents and can be dropped by its editor. + the `current_version_id` of its sheet; never a version a non-deleted sheet + is `based_on`; (reports: added when the table exists, §16). A `draft` has + no dependents and is dropped by its editor through `delete_sheet_version`. - **Document ↔ row**: `content->>'species_id'` equals the sheet's species. ### `anatomical_sheet_assets` @@ -196,61 +199,72 @@ Rules enforced by triggers (every role, including the table owner): immutable and **content-addressed**: the bytes live in Storage under `anatomical-sheet-assets/.svg` (bucket and policies arrive with the importer step; until then the path is a convention, not a row). Two sheets -with the same SVG share one object; a copy of a sheet copies the metadata -rows only. Deleting an asset referenced by a version is refused (FK restrict -is not possible on a JSONB reference, so the delete RPC checks every -version's views). +with the same SVG share one object; a copy of a sheet copies only the +metadata rows its copied version references. Deleting an asset referenced by +a version is refused (FK restrict is not possible on a JSONB reference, so +`delete_sheet_asset` checks every version's views). Asset rows follow the +sheet's visibility, drafts included: the future Storage policy must +authorise through the sheet, never through a sha256 alone. ### 3.1 Lifecycle (RPCs, security definer, audited) -| RPC | Actor | Effect | -|---|---|---| -| `create_anatomical_sheet(species_id, name, slug, description, visibility, official, document)` | any active user; `official = true` needs platform admin | sheet + draft v1 | -| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, content copied from `from_version_id` (default: current version); refused if a draft exists | -| `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | -| `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | -| `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | -| `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched | -| `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor | -| `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while any version has dependents | -| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | +| RPC | Actor | Effect | +| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `create_anatomical_sheet(species_id, name, slug, document, description, visibility, official)` | any active account; `official = true` needs platform admin | sheet + draft v1 | +| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, content copied from `from_version_id` (default: current version); refused if a draft exists | +| `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | +| `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | +| `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | +| `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched | +| `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor | +| `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while a non-deleted copy derives from the sheet | +| `set_sheet_visibility(sheet_id, visibility)` | editor | private ↔ public, audited (sharing is sensitive state) | +| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) | +| `delete_sheet_asset(asset_id)` | editor | refused while any version references the asset | Direct table access for `authenticated`: SELECT through the policies below; -UPDATE of `content` / `change_note` on **own draft** rows (the future editor -autosaves with a PATCH); DELETE of own draft rows. Everything else is RPC. +UPDATE of `name` / `slug` / `description` on own sheets and of `content` / +`change_note` on **own draft** rows (the future editor autosaves with a +PATCH; the autosave itself is not audited, the publication is). Everything +else is RPC. Every RPC takes its actor from `auth.uid()`, refuses a +deactivated profile, checks `can_edit_sheet` before reading anything else +(unknown and foreign ids get the same `42501`), and calls +`private.log_event`. ### 3.2 Access helpers (`private`, security definer) -| Helper | True when | -|---|---| -| `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) | -| `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`) — grants and follows plug in here at the community step | +| Helper | True when | +| ------------------------------- | --------------------------------------------------------------------------------------------------------- | +| `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) | +| `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`), grants and follows plug in here at the community step | Policies: -| Table | SELECT | INSERT / UPDATE / DELETE | -|---|---|---| -| `species` | authenticated, `active` rows | none | -| `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | none (RPC) | -| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` and DELETE on own drafts; INSERT via RPC | -| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | +| Table | SELECT | INSERT / UPDATE / DELETE | +| --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ | +| `species` | authenticated, `active` rows | none | +| `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | UPDATE `name`, `slug`, `description` for editors; everything else RPC | +| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` on own drafts; INSERT and DELETE via RPC | +| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | -`anon` gets nothing. Public discovery views for the public site come with -the community step (§17.4). +`anon` gets nothing. Every `private` function has EXECUTE revoked from +PUBLIC; only the two predicates above are granted to `authenticated` +(pgTAP 001 keeps a census). Public discovery views for the public site come +with the community step (§17.4). ## 4. What the model guarantees (acceptance criteria) -| Criterion | Where it is proven | -|---|---| +| Criterion | Where it is proven | +| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | A sheet with several views and annotations explicitly linked to findings | `packages/domain/tests/fixtures/horse-slice.ts` (2 views, trigger, spine region, bilateral joint, 3 finding kinds); schema + integrity tests | -| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged | -| Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501`, for the editor, for a platform admin and for the owner role | -| New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves | -| Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged | -| Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` | -| Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets | -| Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack | -| Previous tests pass | root `pnpm check` | +| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged | +| Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501` for the table owner; zero rows touched through the API role | +| New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves | +| Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged | +| Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` | +| Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets | +| Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack | +| Previous tests pass | root `pnpm check` | ## 5. Decisions left to the user @@ -268,3 +282,12 @@ the community step (§17.4). account? 6. **Finding category kind naming**: `observation` collides with the report "Observation" (OPEN_QUESTIONS C7). Alternative: `consultation_reason`. +7. **Server-side shape validation**: SQL re-checks references, sizes and the + species, not the full Zod shape (ids pattern, enums, unknown keys). A + client calling the RPC directly can publish a shape-invalid document to + its own sheet. Options: a plpgsql shape check, or publication through an + Edge Function running the Zod schema (community step at the latest). +8. **Account erasure**: `creator_user_id` is `on delete restrict` and the + immutability guard blocks `set null` on `published_by` of published rows, + so deleting an `auth.users` row that owns sheets fails by design until the + retention step (§16) defines reassignment or anonymisation. diff --git a/packages/domain/src/anatomical-sheet/schema.ts b/packages/domain/src/anatomical-sheet/schema.ts index 7bdaaf70..19c304ad 100644 --- a/packages/domain/src/anatomical-sheet/schema.ts +++ b/packages/domain/src/anatomical-sheet/schema.ts @@ -159,11 +159,17 @@ export const AnnotationSchema = z.discriminatedUnion('kind', [ DetailTriggerAnnotationSchema, ]) +/** Documents are shared across users: only web links, never javascript: URLs. */ +const HttpUrlSchema = z + .string() + .url() + .refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected') + export const SourceRefSchema = z .object({ type: z.enum(['manual', 'journal', 'database', 'web']), citation: z.string().min(1), - url: z.string().url().optional(), + url: HttpUrlSchema.optional(), }) .strict() diff --git a/packages/domain/tests/anatomical-sheet.schema.test.ts b/packages/domain/tests/anatomical-sheet.schema.test.ts index 3f7746ba..0e7cfd1a 100644 --- a/packages/domain/tests/anatomical-sheet.schema.test.ts +++ b/packages/domain/tests/anatomical-sheet.schema.test.ts @@ -6,14 +6,25 @@ import { } from '../src' import { horseSlice, horseSliceInput } from './fixtures/horse-slice' -// Mutations deliberately break the typed shape, so the draft is untyped. -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type LooseDoc = any -type Mutation = (doc: LooseDoc) => void +type Tree = Record +type Mutation = (doc: Tree) => void + +/** Walks `path` inside a JSON tree; mutations break the typed shape on purpose. */ +function at(doc: Tree, path: (string | number)[]): Tree { + return path.reduce((node, key) => node[key] as Tree, doc) +} + +function set(doc: Tree, path: (string | number)[], value: unknown): void { + at(doc, path.slice(0, -1))[String(path.at(-1))] = value +} + +function unset(doc: Tree, path: (string | number)[]): void { + delete at(doc, path.slice(0, -1))[String(path.at(-1))] +} /** Applies a mutation to the lean fixture and reports whether it parses. */ function parsesAfter(mutate: Mutation): boolean { - const doc: LooseDoc = horseSliceInput() + const doc = horseSliceInput() as unknown as Tree mutate(doc) return AnatomicalSheetDocumentSchema.safeParse(doc).success } @@ -31,35 +42,70 @@ describe('AnatomicalSheetDocumentSchema', () => { }) const rejections: Array<[string, Mutation]> = [ - ['an unknown top-level key', (d) => (d.extra = true)], - ['an unknown nested key', (d) => (d.views[0].zoom = 2)], - ['a stable id with spaces', (d) => (d.annotations[0].id = 'Hip Joint')], - ['a stable id with an accent', (d) => (d.categories[0].id = 'É')], - ['an empty stable id', (d) => (d.finding_zones[0].id = '')], - ['schema_version 2', (d) => (d.schema_version = 2)], - ['a non-uuid svg_asset_id', (d) => (d.views[0].svg_asset_id = 'horse')], + ['an unknown top-level key', (d) => set(d, ['extra'], true)], + ['an unknown nested key', (d) => set(d, ['views', 0, 'zoom'], 2)], + [ + 'a stable id with spaces', + (d) => set(d, ['annotations', 0, 'id'], 'Hip Joint'), + ], + ['a stable id with an accent', (d) => set(d, ['categories', 0, 'id'], 'É')], + ['an empty stable id', (d) => set(d, ['finding_zones', 0, 'id'], '')], + ['schema_version 2', (d) => set(d, ['schema_version'], 2)], + [ + 'a non-uuid svg_asset_id', + (d) => set(d, ['views', 0, 'svg_asset_id'], 'horse'), + ], [ 'a polygon with 2 points', (d) => - (d.annotations[1].geometry.points = [ - [0, 0], - [1, 1], - ]), + set( + d, + ['annotations', 1, 'geometry', 'points'], + [ + [0, 0], + [1, 1], + ], + ), ], - ['a circle with r 0', (d) => (d.annotations[0].geometry.r = 0)], - ['a region count of 0', (d) => (d.vertebral_config.regions[0].count = 0)], - ['a missing en label', (d) => delete d.name.en], + [ + 'a circle with r 0', + (d) => set(d, ['annotations', 0, 'geometry', 'r'], 0), + ], + [ + 'a region count of 0', + (d) => set(d, ['vertebral_config', 'regions', 0, 'count'], 0), + ], + ['a missing en label', (d) => unset(d, ['name', 'en'])], [ 'a detail view without parent_view_id', - (d) => delete d.views[1].parent_view_id, + (d) => unset(d, ['views', 1, 'parent_view_id']), ], [ 'a detail_trigger with finding_zone_id', - (d) => (d.annotations[3].finding_zone_id = 'hip'), + (d) => set(d, ['annotations', 3, 'finding_zone_id'], 'hip'), + ], + [ + 'a javascript: source url', + (d) => + set( + d, + [ + 'finding_zones', + 0, + 'categories', + 2, + 'children', + 0, + 'sources', + 0, + 'url', + ], + 'javascript:alert(1)', + ), ], [ 'a finding category kind foo', - (d) => (d.finding_zones[0].categories[0].kind = 'foo'), + (d) => set(d, ['finding_zones', 0, 'categories', 0, 'kind'], 'foo'), ], ] diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 23461cc7..e6b1e77a 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -151,6 +151,7 @@ export type Database = { description: string id: string is_official: boolean + last_version_number: number name: string slug: string species_id: string @@ -170,6 +171,7 @@ export type Database = { description?: string id?: string is_official?: boolean + last_version_number?: number name: string slug: string species_id: string @@ -188,6 +190,7 @@ export type Database = { description?: string id?: string is_official?: boolean + last_version_number?: number name?: string slug?: string species_id?: string @@ -428,6 +431,13 @@ export type Database = { } Returns: string } + set_sheet_visibility: { + Args: { + sheet_id: string + visibility: Database['public']['Enums']['sheet_visibility'] + } + Returns: string + } } Enums: { platform_role: 'owner' | 'admin' | 'moderator' | 'support' diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index aff66993..815c1326 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -57,6 +57,7 @@ const expectedColumns = { 'description', 'id', 'is_official', + 'last_version_number', 'name', 'slug', 'species_id', @@ -125,6 +126,7 @@ const expectedFunctionArgs = { register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'], restore_anatomical_sheet: ['sheet_id'], revoke_platform_role: ['reason', 'role', 'target_user_id'], + set_sheet_visibility: ['sheet_id', 'visibility'], } as const satisfies FunctionArgs type MissingArgs = { diff --git a/supabase/migrations/20261008110000_anatomical_sheets.sql b/supabase/migrations/20261008110000_anatomical_sheets.sql index 88ca7948..f4dcdae5 100644 --- a/supabase/migrations/20261008110000_anatomical_sheets.sql +++ b/supabase/migrations/20261008110000_anatomical_sheets.sql @@ -59,6 +59,9 @@ create table public.anatomical_sheets ( based_on_sheet_id uuid references public.anatomical_sheets (id) on delete set null, based_on_version_id uuid, current_version_id uuid, + -- Monotonic counter: a deleted version's number is never reused. + last_version_number integer not null default 0 + constraint anatomical_sheets_last_version_nonneg check (last_version_number >= 0), archived_at timestamptz, deleted_at timestamptz, created_at timestamptz not null default now(), @@ -100,7 +103,9 @@ create table public.anatomical_sheet_versions ( document_schema_version integer not null constraint anatomical_sheet_versions_schema_known check (document_schema_version = 1), content jsonb not null - constraint anatomical_sheet_versions_content_object check (jsonb_typeof(content) = 'object'), + constraint anatomical_sheet_versions_content_object check (jsonb_typeof(content) = 'object') + -- Hostile or runaway documents stop here (2 MiB; the horse catalog is ~170 KiB). + constraint anatomical_sheet_versions_content_size check (pg_column_size(content) <= 2097152), change_note text not null default '' constraint anatomical_sheet_versions_change_note_length check (char_length(change_note) <= 1000), created_by uuid references public.profiles (id) on delete set null, @@ -149,7 +154,7 @@ create table public.anatomical_sheet_assets ( sha256 text not null constraint anatomical_sheet_assets_sha256_format check (sha256 ~ '^[0-9a-f]{64}$'), byte_size integer not null - constraint anatomical_sheet_assets_byte_size_positive check (byte_size > 0), + constraint anatomical_sheet_assets_byte_size_range check (byte_size between 1 and 20971520), content_type text not null default 'image/svg+xml' constraint anatomical_sheet_assets_content_type check (content_type in ('image/svg+xml')), file_name text not null @@ -172,6 +177,7 @@ create index anatomical_sheet_assets_sheet_idx on public.anatomical_sheet_assets create or replace function private.check_sheet_version_document() returns trigger language plpgsql +security definer set search_path = '' as $$ declare @@ -202,8 +208,8 @@ as $$ declare v_same_core boolean; begin - if new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then - raise exception 'sheet_id and version_number are immutable' using errcode = '42501'; + if new.id <> old.id or new.sheet_id <> old.sheet_id or new.version_number <> old.version_number then + raise exception 'id, sheet_id and version_number are immutable' using errcode = '42501'; end if; if old.status = 'deprecated' then @@ -260,6 +266,7 @@ $$; create or replace function private.guard_sheet_version_delete() returns trigger language plpgsql +security definer set search_path = '' as $$ declare @@ -295,7 +302,44 @@ as $$ select case when p_issues @> array[p_code] then p_issues else p_issues || p_code end; $$; -create or replace function private.sheet_document_issues(p_doc jsonb) +-- Uniqueness of the id-bearing collections. +create or replace function private.sheet_document_duplicate_issues(p_doc jsonb) +returns text[] +language plpgsql +immutable +set search_path = '' +as $$ +declare + v_issues text[] := '{}'; + r record; +begin + for r in + select * from (values + ('views', 'id', 'view.id.duplicate'), + ('annotations', 'id', 'annotation.id.duplicate'), + ('categories', 'id', 'category.id.duplicate'), + ('finding_zones', 'id', 'finding_zone.id.duplicate') + ) as t(collection, key, code) + loop + if exists ( + select 1 from jsonb_array_elements(coalesce(p_doc -> r.collection, '[]'::jsonb)) e + group by e ->> r.key having count(*) > 1 + ) then + v_issues := private.append_issue(v_issues, r.code); + end if; + end loop; + if exists ( + select 1 from jsonb_array_elements(coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb)) g + group by g ->> 'code' having count(*) > 1 + ) then + v_issues := private.append_issue(v_issues, 'region.code.duplicate'); + end if; + return v_issues; +end; +$$; + +-- View tree: one main view, parents exist, details reachable, something to draw. +create or replace function private.sheet_document_view_issues(p_doc jsonb) returns text[] language plpgsql immutable @@ -305,39 +349,14 @@ declare v_issues text[] := '{}'; v_views jsonb := coalesce(p_doc -> 'views', '[]'::jsonb); v_anns jsonb := coalesce(p_doc -> 'annotations', '[]'::jsonb); - v_cats jsonb := coalesce(p_doc -> 'categories', '[]'::jsonb); - v_zones jsonb := coalesce(p_doc -> 'finding_zones', '[]'::jsonb); - v_regs jsonb := coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb); r record; begin - if jsonb_typeof(v_views) <> 'array' or jsonb_typeof(v_anns) <> 'array' - or jsonb_typeof(v_cats) <> 'array' or jsonb_typeof(v_zones) <> 'array' - or jsonb_typeof(v_regs) <> 'array' then - return array['document.shape']; - end if; - if (select count(*) from jsonb_array_elements(v_views) v where v ->> 'kind' = 'main') <> 1 then v_issues := private.append_issue(v_issues, 'view.main.count'); end if; - if exists (select 1 from jsonb_array_elements(v_views) v group by v ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'view.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_anns) a group by a ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'annotation.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_cats) c group by c ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'category.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_zones) z group by z ->> 'id' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'finding_zone.id.duplicate'); - end if; - if exists (select 1 from jsonb_array_elements(v_regs) g group by g ->> 'code' having count(*) > 1) then - v_issues := private.append_issue(v_issues, 'region.code.duplicate'); - end if; - for r in select v ->> 'id' as id, v ->> 'kind' as kind, v ->> 'parent_view_id' as parent, - v ->> 'svg_asset_id' as asset, v -> 'view_box' as view_box + v ->> 'svg_asset_id' as asset, jsonb_typeof(v -> 'view_box') as view_box_type from jsonb_array_elements(v_views) v loop if r.kind = 'detail' then @@ -350,19 +369,37 @@ begin ) then v_issues := private.append_issue(v_issues, 'view.unreachable'); end if; - if r.asset is null and (r.view_box is null or jsonb_typeof(r.view_box) = 'null') then + if r.asset is null and coalesce(r.view_box_type, 'null') = 'null' then v_issues := private.append_issue(v_issues, 'view.asset.missing'); end if; elsif r.asset is null then v_issues := private.append_issue(v_issues, 'view.asset.missing'); end if; end loop; + return v_issues; +end; +$$; +-- Annotation references: view, category, trigger target, finding zone, region. +create or replace function private.sheet_document_annotation_issues(p_doc jsonb) +returns text[] +language plpgsql +immutable +set search_path = '' +as $$ +declare + v_issues text[] := '{}'; + v_views jsonb := coalesce(p_doc -> 'views', '[]'::jsonb); + v_cats jsonb := coalesce(p_doc -> 'categories', '[]'::jsonb); + v_zones jsonb := coalesce(p_doc -> 'finding_zones', '[]'::jsonb); + v_regs jsonb := coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb); + r record; +begin for r in select a ->> 'kind' as kind, a ->> 'view_id' as view_id, a ->> 'category_id' as category_id, a ->> 'opens_view_id' as opens, a ->> 'finding_zone_id' as zone, a ->> 'vertebral_region_code' as region - from jsonb_array_elements(v_anns) a + from jsonb_array_elements(coalesce(p_doc -> 'annotations', '[]'::jsonb)) a loop if not exists (select 1 from jsonb_array_elements(v_views) v where v ->> 'id' = r.view_id) then v_issues := private.append_issue(v_issues, 'annotation.view.missing'); @@ -387,14 +424,54 @@ begin v_issues := private.append_issue(v_issues, 'annotation.region.missing'); end if; end loop; - return v_issues; end; $$; +-- True when every id-bearing collection of the document is a JSON array. +create or replace function private.sheet_document_has_shape(p_doc jsonb) +returns boolean +language sql +immutable +set search_path = '' +as $$ + select jsonb_typeof(p_doc) = 'object' + and jsonb_typeof(coalesce(p_doc -> 'views', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'annotations', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'categories', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'finding_zones', '[]'::jsonb)) = 'array' + and jsonb_typeof(coalesce(p_doc -> 'vertebral_config' -> 'regions', '[]'::jsonb)) = 'array'; +$$; + +create or replace function private.sheet_document_issues(p_doc jsonb) +returns text[] +language sql +immutable +set search_path = '' +as $$ + select case + when not private.sheet_document_has_shape(p_doc) then array['document.shape'] + else private.sheet_document_view_issues(p_doc) + || private.sheet_document_duplicate_issues(p_doc) + || private.sheet_document_annotation_issues(p_doc) + end; +$$; + comment on function private.sheet_document_issues(jsonb) is 'Error-level referential rules of the canonical document (codes shared with packages/domain). Empty array = publishable as far as SQL can tell.'; +-- Asset ids referenced by the views of a document (lower-cased uuid text). +create or replace function private.sheet_document_asset_ids(p_doc jsonb) +returns text[] +language sql +immutable +set search_path = '' +as $$ + select coalesce(array_agg(distinct lower(v ->> 'svg_asset_id')), '{}') + from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v + where v ->> 'svg_asset_id' is not null; +$$; + -- Every svg_asset_id used by a view must be an asset registered for the sheet. create or replace function private.sheet_document_unknown_assets(p_sheet_id uuid, p_doc jsonb) returns text[] @@ -403,13 +480,12 @@ stable security definer set search_path = '' as $$ - select coalesce(array_agg(v ->> 'svg_asset_id'), '{}') - from jsonb_array_elements(coalesce(p_doc -> 'views', '[]'::jsonb)) v - where v ->> 'svg_asset_id' is not null - and not exists ( - select 1 from public.anatomical_sheet_assets a - where a.sheet_id = p_sheet_id and a.id::text = v ->> 'svg_asset_id' - ); + select coalesce(array_agg(ref), '{}') + from unnest(private.sheet_document_asset_ids(p_doc)) as ref + where not exists ( + select 1 from public.anatomical_sheet_assets a + where a.sheet_id = p_sheet_id and a.id::text = ref + ); $$; -- --------------------------------------------------------------------------- @@ -470,6 +546,10 @@ begin if v_actor is null then raise exception 'authentication required' using errcode = '42501'; end if; + -- A staff-deactivated account keeps no write access (profiles.active). + if not exists (select 1 from public.profiles p where p.id = v_actor and p.active) then + raise exception 'account is not active' using errcode = '42501'; + end if; return v_actor; end; $$; @@ -487,6 +567,24 @@ begin end; $$; +-- Same check through a version id; unknown and foreign versions get one answer. +create or replace function private.require_version_editor(p_actor uuid, p_version_id uuid) +returns void +language plpgsql +stable +security definer +set search_path = '' +as $$ +declare + v_sheet uuid; +begin + select sheet_id into v_sheet from public.anatomical_sheet_versions where id = p_version_id; + if v_sheet is null or not private.can_edit_sheet(p_actor, v_sheet) then + raise exception 'version % is not editable by the caller', p_version_id using errcode = '42501'; + end if; +end; +$$; + -- Inserts a draft with the next version number. The sheet row is locked so -- two concurrent calls cannot pick the same number. create or replace function private.insert_sheet_draft( @@ -504,6 +602,9 @@ declare v_number integer; v_id uuid; begin + if jsonb_typeof(p_content -> 'schema_version') is distinct from 'number' then + raise exception 'document.schema_version must be a number' using errcode = '23514'; + end if; perform 1 from public.anatomical_sheets where id = p_sheet_id for update; if exists ( select 1 from public.anatomical_sheet_versions @@ -511,8 +612,10 @@ begin ) then raise exception 'sheet % already has a draft', p_sheet_id using errcode = '23505'; end if; - select coalesce(max(version_number), 0) + 1 into v_number - from public.anatomical_sheet_versions where sheet_id = p_sheet_id; + update public.anatomical_sheets + set last_version_number = last_version_number + 1 + where id = p_sheet_id + returning last_version_number into v_number; insert into public.anatomical_sheet_versions ( sheet_id, version_number, status, document_schema_version, content, change_note, created_by @@ -531,8 +634,8 @@ begin end; $$; --- Copies the asset rows of one sheet to another; returns old id → new id. -create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid) +-- Copies the asset rows a document references to another sheet; returns old id → new id. +create or replace function private.copy_sheet_assets(p_actor uuid, p_from uuid, p_to uuid, p_doc jsonb) returns jsonb language plpgsql security definer @@ -545,7 +648,8 @@ declare begin for r in select id, sha256, byte_size, content_type, file_name - from public.anatomical_sheet_assets where sheet_id = p_from + from public.anatomical_sheet_assets + where sheet_id = p_from and id::text = any (private.sheet_document_asset_ids(p_doc)) loop insert into public.anatomical_sheet_assets ( sheet_id, sha256, byte_size, content_type, file_name, created_by @@ -571,8 +675,8 @@ as $$ coalesce(( select jsonb_agg( case - when v ->> 'svg_asset_id' is not null and p_map ? (v ->> 'svg_asset_id') - then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> (v ->> 'svg_asset_id'))) + when v ->> 'svg_asset_id' is not null and p_map ? lower(v ->> 'svg_asset_id') + then jsonb_set(v, '{svg_asset_id}', to_jsonb(p_map ->> lower(v ->> 'svg_asset_id'))) else v end order by ord @@ -668,11 +772,8 @@ declare v_version public.anatomical_sheet_versions%rowtype; v_issues text[]; begin + perform private.require_version_editor(v_actor, version_id); select * into v_version from public.anatomical_sheet_versions where id = version_id for update; - if v_version.id is null then - raise exception 'unknown version %', version_id using errcode = 'P0002'; - end if; - perform private.require_sheet_editor(v_actor, v_version.sheet_id); if v_version.status <> 'draft' then raise exception 'version % is not a draft', version_id using errcode = '55000'; end if; @@ -714,11 +815,11 @@ declare v_version public.anatomical_sheet_versions%rowtype; v_next uuid; begin - select * into v_version from public.anatomical_sheet_versions where id = version_id for update; - if v_version.id is null then - raise exception 'unknown version %', version_id using errcode = 'P0002'; + if char_length(reason) > 500 then + raise exception 'reason exceeds 500 characters' using errcode = '22023'; end if; - perform private.require_sheet_editor(v_actor, v_version.sheet_id); + perform private.require_version_editor(v_actor, version_id); + select * into v_version from public.anatomical_sheet_versions where id = version_id for update; if v_version.status <> 'published' then raise exception 'version % is not published', version_id using errcode = '55000'; end if; @@ -754,12 +855,9 @@ declare v_sheet uuid; v_number integer; begin + perform private.require_version_editor(v_actor, version_id); select sheet_id, version_number into v_sheet, v_number from public.anatomical_sheet_versions where id = version_id; - if v_sheet is null then - raise exception 'unknown version %', version_id using errcode = 'P0002'; - end if; - perform private.require_sheet_editor(v_actor, v_sheet); -- Preconditions (published, current, active fork) are raised by the delete guard. delete from public.anatomical_sheet_versions where id = version_id; @@ -791,14 +889,10 @@ declare v_map jsonb; begin select * into v_source from public.anatomical_sheet_versions where id = source_version_id; - if v_source.id is null then - raise exception 'unknown version %', source_version_id using errcode = 'P0002'; - end if; - if not private.can_use_sheet(v_actor, v_source.sheet_id) then - raise exception 'sheet % is not usable by the caller', v_source.sheet_id using errcode = '42501'; - end if; - if v_source.status <> 'published' then - raise exception 'only a published version can be copied' using errcode = '55000'; + -- One answer for "unknown", "not published" and "not usable": no existence oracle. + if v_source.id is null or v_source.status <> 'published' + or not private.can_use_sheet(v_actor, v_source.sheet_id) then + raise exception 'version % is not available for copy', source_version_id using errcode = '42501'; end if; select species_id into v_species from public.anatomical_sheets where id = v_source.sheet_id; @@ -808,7 +902,7 @@ begin values (v_species, name, slug, v_actor, visibility, v_source.sheet_id, source_version_id) returning id into v_sheet; - v_map := private.copy_sheet_assets(v_actor, v_source.sheet_id, v_sheet); + v_map := private.copy_sheet_assets(v_actor, v_source.sheet_id, v_sheet, v_source.content); perform private.log_event( v_actor, 'anatomical_sheet.forked', 'anatomical_sheet', v_sheet, null, null, jsonb_build_object('source_sheet_id', v_source.sheet_id, 'source_version_id', source_version_id) @@ -886,6 +980,8 @@ declare v_status public.sheet_status; begin perform private.require_sheet_editor(v_actor, sheet_id); + -- Lock before the copies check so a concurrent fork cannot slip in. + perform 1 from public.anatomical_sheets s where s.id = sheet_id for update; if exists ( select 1 from public.anatomical_sheets f where f.based_on_sheet_id = delete_anatomical_sheet.sheet_id and f.status <> 'deleted' @@ -898,6 +994,30 @@ begin end; $$; +-- Sharing is sensitive state: audited, never a direct column write. +create or replace function public.set_sheet_visibility(sheet_id uuid, visibility public.sheet_visibility) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_actor uuid := private.require_actor(); +begin + perform private.require_sheet_editor(v_actor, sheet_id); + update public.anatomical_sheets s + set visibility = set_sheet_visibility.visibility + where s.id = sheet_id and s.visibility <> set_sheet_visibility.visibility; + if found then + perform private.log_event( + v_actor, 'anatomical_sheet.visibility_changed', 'anatomical_sheet', sheet_id, null, null, + jsonb_build_object('visibility', visibility) + ); + end if; + return sheet_id; +end; +$$; + create or replace function public.register_sheet_asset( sheet_id uuid, sha256 text, @@ -943,14 +1063,12 @@ declare v_sheet uuid; begin select sheet_id into v_sheet from public.anatomical_sheet_assets where id = asset_id; - if v_sheet is null then - raise exception 'unknown asset %', asset_id using errcode = 'P0002'; + if v_sheet is null or not private.can_edit_sheet(v_actor, v_sheet) then + raise exception 'asset % is not editable by the caller', asset_id using errcode = '42501'; end if; - perform private.require_sheet_editor(v_actor, v_sheet); if exists ( - select 1 from public.anatomical_sheet_versions v, - jsonb_array_elements(coalesce(v.content -> 'views', '[]'::jsonb)) w - where v.sheet_id = v_sheet and w ->> 'svg_asset_id' = asset_id::text + select 1 from public.anatomical_sheet_versions v + where v.sheet_id = v_sheet and asset_id::text = any (private.sheet_document_asset_ids(v.content)) ) then raise exception 'asset % is referenced by a version', asset_id using errcode = '55000'; end if; @@ -978,10 +1096,38 @@ comment on function public.fork_anatomical_sheet(uuid, text, text, public.sheet_ 'Personal copy of a published version: new sheet with based_on_* provenance, assets copied, draft v1. The source is not modified.'; comment on function public.delete_anatomical_sheet(uuid) is 'Soft delete (status deleted); refused while active copies derive from the sheet.'; +comment on function public.set_sheet_visibility(uuid, public.sheet_visibility) is + 'private ↔ public. Audited; the only way to change sharing.'; -- --------------------------------------------------------------------------- -- Privileges + RLS -- --------------------------------------------------------------------------- +-- PostgreSQL grants EXECUTE to PUBLIC on every new function and a per-schema +-- ALTER DEFAULT PRIVILEGES cannot take that built-in default away: revoke it +-- explicitly on every private function (the policies need only the two +-- predicates granted above). +revoke all on function private.check_sheet_version_document() from public; +revoke all on function private.guard_sheet_version_update() from public; +revoke all on function private.guard_sheet_version_delete() from public; +revoke all on function private.sheet_version_dependents(uuid) from public; +revoke all on function private.append_issue(text[], text) from public; +revoke all on function private.sheet_document_duplicate_issues(jsonb) from public; +revoke all on function private.sheet_document_view_issues(jsonb) from public; +revoke all on function private.sheet_document_annotation_issues(jsonb) from public; +revoke all on function private.sheet_document_has_shape(jsonb) from public; +revoke all on function private.sheet_document_issues(jsonb) from public; +revoke all on function private.sheet_document_asset_ids(jsonb) from public; +revoke all on function private.sheet_document_unknown_assets(uuid, jsonb) from public; +revoke all on function private.can_edit_sheet(uuid, uuid) from public; +revoke all on function private.can_use_sheet(uuid, uuid) from public; +revoke all on function private.require_actor() from public; +revoke all on function private.require_sheet_editor(uuid, uuid) from public; +revoke all on function private.require_version_editor(uuid, uuid) from public; +revoke all on function private.insert_sheet_draft(uuid, uuid, jsonb, text) from public; +revoke all on function private.copy_sheet_assets(uuid, uuid, uuid, jsonb) from public; +revoke all on function private.remap_document_assets(jsonb, jsonb) from public; +revoke all on function private.set_sheet_status(uuid, uuid, public.sheet_status, public.sheet_status, text) from public; + revoke all on function public.create_anatomical_sheet(text, text, text, jsonb, text, public.sheet_visibility, boolean) from public, anon; revoke all on function public.create_sheet_draft(uuid, uuid, text) from public, anon; revoke all on function public.publish_sheet_version(uuid) from public, anon; @@ -991,6 +1137,7 @@ revoke all on function public.fork_anatomical_sheet(uuid, text, text, public.she revoke all on function public.archive_anatomical_sheet(uuid) from public, anon; revoke all on function public.restore_anatomical_sheet(uuid) from public, anon; revoke all on function public.delete_anatomical_sheet(uuid) from public, anon; +revoke all on function public.set_sheet_visibility(uuid, public.sheet_visibility) from public, anon; revoke all on function public.register_sheet_asset(uuid, text, integer, text) from public, anon; revoke all on function public.delete_sheet_asset(uuid) from public, anon; @@ -1003,6 +1150,7 @@ grant execute on function public.fork_anatomical_sheet(uuid, text, text, public. grant execute on function public.archive_anatomical_sheet(uuid) to authenticated, service_role; grant execute on function public.restore_anatomical_sheet(uuid) to authenticated, service_role; grant execute on function public.delete_anatomical_sheet(uuid) to authenticated, service_role; +grant execute on function public.set_sheet_visibility(uuid, public.sheet_visibility) to authenticated, service_role; grant execute on function public.register_sheet_asset(uuid, text, integer, text) to authenticated, service_role; grant execute on function public.delete_sheet_asset(uuid) to authenticated, service_role; @@ -1013,13 +1161,12 @@ revoke all on public.anatomical_sheet_assets from public, anon, authenticated; grant select on public.species to authenticated; grant select on public.anatomical_sheets to authenticated; --- Editors change the identity columns in place; status, provenance, ownership go through RPCs. -grant update (name, slug, description, visibility) on public.anatomical_sheets to authenticated; +-- Editors change the identity columns in place; visibility, status, provenance, ownership go through RPCs. +grant update (name, slug, description) on public.anatomical_sheets to authenticated; grant select on public.anatomical_sheet_versions to authenticated; -- Draft autosave: editors patch content and change_note; the guards keep -- published rows frozen whatever the grant says. grant update (content, change_note) on public.anatomical_sheet_versions to authenticated; -grant delete on public.anatomical_sheet_versions to authenticated; grant select on public.anatomical_sheet_assets to authenticated; alter table public.species enable row level security; @@ -1067,12 +1214,6 @@ create policy anatomical_sheet_versions_update_own_draft using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)) with check (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); -create policy anatomical_sheet_versions_delete_own_draft - on public.anatomical_sheet_versions - for delete - to authenticated - using (status = 'draft' and private.can_edit_sheet((select auth.uid()), sheet_id)); - create policy anatomical_sheet_assets_select on public.anatomical_sheet_assets for select diff --git a/supabase/migrations/20261008110100_private_execute_hardening.sql b/supabase/migrations/20261008110100_private_execute_hardening.sql new file mode 100644 index 00000000..15e79baf --- /dev/null +++ b/supabase/migrations/20261008110100_private_execute_hardening.sql @@ -0,0 +1,28 @@ +-- Harden EXECUTE on the private helpers created by the foundation, profiles +-- and platform-roles migrations. +-- +-- The foundation ran `alter default privileges in schema private revoke +-- execute on functions from public`. PostgreSQL applies per-schema default +-- privileges on top of the built-in defaults; a per-schema REVOKE cannot +-- remove the built-in EXECUTE for PUBLIC. Every function created since kept +-- it. Nothing was reachable through the API (PostgREST exposes `public` +-- only and anon has no USAGE on `private`), but the project rule is +-- "EXECUTE revoked from public, granted only to the roles that evaluate +-- it". This migration makes it true; pgTAP 001 pins it with a census. + +revoke all on function private.set_updated_at() from public; +revoke all on function private.reset_phone_verification() from public; +revoke all on function private.handle_new_auth_user() from public; +revoke all on function audit.reject_mutation() from public; + +-- Role predicates keep their explicit grant to authenticated (policies). +revoke all on function private.has_platform_role(uuid, public.platform_role[]) from public; +revoke all on function private.is_platform_owner(uuid) from public; +revoke all on function private.is_platform_admin(uuid) from public; +revoke all on function private.is_platform_moderator(uuid) from public; +revoke all on function private.is_support(uuid) from public; + +-- Owner-context helpers: RPCs and privileged SQL sessions only. +revoke all on function private.can_manage_platform_role(uuid, public.platform_role) from public; +revoke all on function private.assign_platform_role(uuid, uuid, public.platform_role) from public; +revoke all on function private.withdraw_platform_role(uuid, uuid, public.platform_role, text) from public; diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index ad7283bf..a2a12645 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -1,6 +1,6 @@ -- Schema contract: objects exist, RLS is on, API roles start from zero. begin; -select plan(24); +select plan(26); -- Schemas select has_schema('private', 'schema private exists'); @@ -51,5 +51,20 @@ select ok(not has_column_privilege('authenticated', 'public.profiles', 'active', select ok(not has_schema_privilege('anon', 'private', 'usage'), 'anon has no usage on schema private'); select ok(not has_function_privilege('anon', 'public.grant_platform_role(uuid, public.platform_role)', 'execute'), 'anon cannot execute grant_platform_role'); +-- Private helpers: EXECUTE revoked from everyone except the predicates the policies evaluate. +-- (has_function_privilege is true for any role while proacl is null, i.e. the built-in PUBLIC default.) +select is( + (select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname in ('private', 'audit') and has_function_privilege('anon', p.oid, 'execute')), + 0::bigint, 'anon can execute nothing in private/audit' +); +select is( + (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')), + 'can_edit_sheet,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', + 'authenticated executes only the policy predicates in private' +); + select * from finish(); rollback; diff --git a/supabase/tests/005_anatomical_sheets.sql b/supabase/tests/005_anatomical_sheets.sql index b7151985..7c44ba0f 100644 --- a/supabase/tests/005_anatomical_sheets.sql +++ b/supabase/tests/005_anatomical_sheets.sql @@ -3,7 +3,7 @@ -- denied path (other user, anon, direct writes, official sheets). -- Counts are scoped to fixture ids: the real stack also carries seed rows. begin; -select plan(95); +select plan(127); -- --------------------------------------------------------------------------- -- Fixtures @@ -106,7 +106,23 @@ select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_vers select ok(not has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'status', 'update'), 'authenticated cannot update versions.status'); select ok(has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'content', 'update'), 'authenticated may update versions.content (RLS: own draft)'); select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_assets', 'insert'), 'authenticated cannot insert assets directly'); -select ok(not has_function_privilege('anon', 'public.publish_sheet_version(uuid)', 'execute'), 'anon cannot execute publish_sheet_version'); +select ok( + not (has_column_privilege('authenticated', 'public.anatomical_sheets', 'visibility', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'creator_user_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'current_version_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'based_on_sheet_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'based_on_version_id', 'update') + or has_column_privilege('authenticated', 'public.anatomical_sheets', 'species_id', 'update')), + 'visibility, ownership, provenance, current version and species are not user-updatable' +); +select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_versions', 'delete'), 'authenticated cannot delete versions directly (RPC only)'); +select is( + (select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.prokind = 'f' + and not exists (select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e') + and has_function_privilege('anon', p.oid, 'execute')), + 0::bigint, 'anon can execute no public RPC' +); -- --------------------------------------------------------------------------- -- 2. Alice creates a private sheet (draft v1), registers an asset, publishes @@ -138,6 +154,17 @@ select throws_ok( '23505', null, 'slug is unique per owner' ); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Bad', 'bad-doc', '{"schema_version":"abc","species_id":"equine"}'::jsonb) $$, + '23514', null, 'a non-numeric schema_version is refused' +); +select throws_ok( + $$ update public.anatomical_sheet_versions + set content = jsonb_build_object('schema_version', 1, 'species_id', 'equine', 'pad', repeat('x', 2200000)) + where id = pg_temp.id('v1') $$, + '23514', null, 'a document over 2 MiB is refused' +); + -- Publishing a draft whose main view has no asset is refused with the rule code select throws_ok( $$ select public.publish_sheet_version(pg_temp.id('v1')) $$, @@ -196,6 +223,61 @@ select throws_ok( '23514', 'document not publishable: annotation.id.duplicate', 'publish refuses duplicate annotation ids' ); +create function pg_temp.publish_issue(p_doc jsonb) returns text language plpgsql as $$ +begin + update public.anatomical_sheet_versions set content = p_doc where id = pg_temp.id('v1'); + perform public.publish_sheet_version(pg_temp.id('v1')); + return 'published'; +exception when check_violation then + return sqlerrm; +end $$; +grant execute on function pg_temp.publish_issue(jsonb) to authenticated; +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,0,kind}', '"detail"')), + 'document not publishable: view.main.count, view.parent.missing', 'SQL gate: no main view' +); +select is( + pg_temp.publish_issue(pg_temp.sheet_doc(pg_temp.id('asset')) #- '{annotations,2}'), + 'document not publishable: view.unreachable', 'SQL gate: detail view without trigger' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,1,parent_view_id}', '"nowhere"')), + 'document not publishable: view.parent.missing, annotation.opens_view.invalid', 'SQL gate: dangling parent view' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,1,id}', '"view-main"')), + 'document not publishable: view.unreachable, view.id.duplicate, annotation.opens_view.invalid', 'SQL gate: duplicate view id' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,view_id}', '"nowhere"')), + 'document not publishable: annotation.view.missing', 'SQL gate: annotation on a missing view' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,category_id}', '"nowhere"')), + 'document not publishable: annotation.category.missing', 'SQL gate: missing category' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,1,vertebral_region_code}', '"Z"')), + 'document not publishable: annotation.region.missing', 'SQL gate: unknown vertebral region' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,2,opens_view_id}', '"view-main"')), + 'document not publishable: view.unreachable, annotation.opens_view.invalid', 'SQL gate: trigger opening a non-child view' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{vertebral_config,regions}', + '[{"code":"C","name":{"fr":"a","en":"a"},"count":7},{"code":"C","name":{"fr":"b","en":"b"},"count":7}]')), + 'document not publishable: region.code.duplicate', 'SQL gate: duplicate region code' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{finding_zones}', + '[{"id":"hip","name":{"fr":"a","en":"a"},"categories":[]},{"id":"hip","name":{"fr":"b","en":"b"},"categories":[]}]')), + 'document not publishable: finding_zone.id.duplicate', 'SQL gate: duplicate finding zone id' +); +select is( + pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views}', '"not-an-array"')), + 'document not publishable: document.shape', 'SQL gate: views not an array' +); update public.anatomical_sheet_versions set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1'); @@ -233,10 +315,9 @@ select is( (select change_note from public.anatomical_sheet_versions where id = pg_temp.id('v1')), 'asset wired', 'editor UPDATE of a published change note touches no row' ); -delete from public.anatomical_sheet_versions where id = pg_temp.id('v1'); -select is( - (select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v1')), - 1::bigint, 'editor DELETE of a published version touches no row' +select throws_ok( + $$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$, + '42501', null, 'editor has no DELETE privilege on versions (RPC only)' ); reset role; select throws_ok( @@ -331,8 +412,11 @@ select throws_ok( -- alice makes the sheet public through the identity-column policy select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob update on alice sheet changed nothing'); -update public.anatomical_sheets set visibility = 'public' where id = pg_temp.id('sheet'); +select lives_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'public') $$, 'alice makes the sheet public (audited RPC)'); insert into pg_temp.ids select 'v3', public.create_sheet_draft(pg_temp.id('sheet'), null, 'work in progress'); +insert into pg_temp.ids select 'asset-unused', public.register_sheet_asset( + pg_temp.id('sheet'), repeat('b', 64), 1000, 'Unused.svg' +); select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'bob sees the public sheet'); @@ -348,8 +432,25 @@ select is( update public.anatomical_sheet_versions set content = '{"schema_version":1}'::jsonb where id = pg_temp.id('v3'); select throws_ok( $$ select public.fork_anatomical_sheet(pg_temp.id('v3'), 'Copie', 'copie-bob') $$, - '55000', null, 'only a published version can be copied' + '42501', null, 'a draft cannot be copied (hidden from non-editors)' ); +update public.anatomical_sheets set name = 'hijack-public' where id = pg_temp.id('sheet'); +select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob cannot rename a public sheet he does not edit'); +-- Every editor-gated RPC refuses a non-editor, even on a public sheet +select throws_ok($$ select public.publish_sheet_version(pg_temp.id('v3')) $$, '42501', null, 'non-editor cannot publish'); +select throws_ok($$ select public.deprecate_sheet_version(pg_temp.id('v2'), 'x') $$, '42501', null, 'non-editor cannot deprecate'); +select throws_ok($$ select public.delete_sheet_version(pg_temp.id('v3')) $$, '42501', null, 'non-editor cannot delete a version'); +select throws_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot archive'); +select throws_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot restore'); +select throws_ok($$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot delete a sheet'); +select throws_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'private') $$, '42501', null, 'non-editor cannot change visibility'); +select throws_ok($$ select public.register_sheet_asset(pg_temp.id('sheet'), repeat('c', 64), 10, 'x.svg') $$, '42501', null, 'non-editor cannot register an asset'); +select throws_ok($$ select public.delete_sheet_asset(pg_temp.id('asset-unused')) $$, '42501', null, 'non-editor cannot delete an asset'); +select throws_ok($$ select public.publish_sheet_version(gen_random_uuid()) $$, '42501', null, 'unknown version gets the same answer as a foreign one'); +-- A platform admin is not an editor of a personal sheet +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-000000000001","role":"authenticated"}', true); +select throws_ok($$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, '42501', null, 'platform owner cannot edit a personal sheet'); +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); create table pg_temp.source_snapshot as select s.updated_at as sheet_updated_at, s.current_version_id, v.content, v.updated_at as version_updated_at, @@ -374,7 +475,7 @@ select results_eq( select results_eq( $$ select sha256, byte_size, id <> pg_temp.id('asset') from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork') $$, $$ values (repeat('a', 64), 142400, true) $$, - 'asset rows are copied (same content, new id)' + 'only the asset referenced by the copied version is copied (same content, new id)' ); select is( (select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')), @@ -434,6 +535,7 @@ select throws_ok( '55000', null, 'the sheet cannot be deleted while a copy is active' ); select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives the sheet'); +select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'the editor still reads her archived sheet'); select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'an archived sheet is no longer usable by others'); select throws_ok( @@ -447,14 +549,36 @@ select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-0000000 select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores the sheet'); select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v2')) $$, 'deprecated v2 is deleted once no active copy depends on it'); select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v2')), 0::bigint, 'v2 row is gone'); -select lives_ok($$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v3') $$, 'editor drops her own draft directly'); +select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v3')) $$, 'editor drops her own draft through the RPC'); +insert into pg_temp.ids select 'v4', public.create_sheet_draft(pg_temp.id('sheet'), null, 'after deletion'); +select is( + (select version_number from public.anatomical_sheet_versions where id = pg_temp.id('v4')), + 4, 'a deleted version number is never reused' +); +select lives_ok($$ select public.delete_sheet_asset(pg_temp.id('asset-unused')) $$, 'an unreferenced asset can be deleted'); select throws_ok( $$ select public.delete_sheet_asset(pg_temp.id('asset')) $$, '55000', null, 'an asset referenced by a version cannot be deleted' ); -- --------------------------------------------------------------------------- --- 7. Official sheets: platform admins only +-- 7. Deactivated account +-- --------------------------------------------------------------------------- +reset role; +update public.profiles set active = false where id = '20000000-0000-0000-0000-00000000000b'; +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true); +select throws_ok( + $$ select public.create_anatomical_sheet('equine', 'Nope', 'nope', pg_temp.sheet_doc(null)) $$, + '42501', null, 'a deactivated account cannot write' +); +reset role; +update public.profiles set active = true where id = '20000000-0000-0000-0000-00000000000b'; +set local role authenticated; +select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true); + +-- --------------------------------------------------------------------------- +-- 8. Official sheets: platform admins only -- --------------------------------------------------------------------------- select throws_ok( $$ select public.create_anatomical_sheet('equine', 'Officielle', 'officielle', pg_temp.sheet_doc(null), '', 'public', true) $$, @@ -481,7 +605,7 @@ select throws_ok( ); -- --------------------------------------------------------------------------- --- 8. Anonymous +-- 9. Anonymous -- --------------------------------------------------------------------------- set local role anon; select set_config('request.jwt.claims', '', true); @@ -493,15 +617,17 @@ select throws_ok( ); -- --------------------------------------------------------------------------- --- 9. Audit trail +-- 10. Audit trail -- --------------------------------------------------------------------------- reset role; select results_eq( $$ select action from audit.audit_logs - where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('fork'), pg_temp.id('asset')) + where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('v3'), pg_temp.id('fork'), + pg_temp.id('asset'), pg_temp.id('asset-unused')) group by action order by action collate "C" $$, $$ values ('anatomical_sheet.archived'), ('anatomical_sheet.created'), ('anatomical_sheet.deleted'), - ('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet_asset.registered'), + ('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet.visibility_changed'), + ('anatomical_sheet_asset.deleted'), ('anatomical_sheet_asset.registered'), ('anatomical_sheet_version.created'), ('anatomical_sheet_version.deleted'), ('anatomical_sheet_version.deprecated'), ('anatomical_sheet_version.published') $$, 'every lifecycle step left an audit event' From 5d32bed829060057d92e54a8770d74e49eb91b47 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 9 Oct 2026 00:05:39 +0200 Subject: [PATCH 7/7] docs(docs): sheet model spec matches the hardened code (counter, SQL-only codes, census, migration list) --- docs/development/ANATOMICAL_SHEET_MODEL.md | 37 ++++++++++++---------- docs/development/SUPABASE.md | 31 +++++++++--------- 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/docs/development/ANATOMICAL_SHEET_MODEL.md b/docs/development/ANATOMICAL_SHEET_MODEL.md index 53cdcfd7..35a8bd4a 100644 --- a/docs/development/ANATOMICAL_SHEET_MODEL.md +++ b/docs/development/ANATOMICAL_SHEET_MODEL.md @@ -127,10 +127,13 @@ Integrity rules (error unless stated): | `finding_zone.unreferenced` (warning) | zone no annotation points to | A draft may be saved with errors. Publishing a document with errors is -refused in TypeScript (`assertPublishable`) and in SQL -(`private.sheet_document_issues`), which re-checks every error-level rule -except the two recursive ones (parent cycle, sibling uniqueness) and adds -"every `svg_asset_id` is an asset of this sheet". +refused in TypeScript (`assertPublishable`) and in SQL: +`private.sheet_document_issues` re-checks every error-level rule except the +two recursive ones (parent cycle, sibling uniqueness) and reports +`document.shape` when an id-bearing collection is not an array; +`private.sheet_document_unknown_assets` adds `view.asset.unknown` when a +view points at an asset not registered for the sheet. Both run inside +`publish_sheet_version`. ## 3. Relational model @@ -165,16 +168,16 @@ any authenticated user; no write path through the API (platform step later). ### `anatomical_sheet_versions` -| Column | Notes | -| ----------------------------------------------------------- | ------------------------------------------------------------------------ | -| `id uuid`, `sheet_id` | | -| `version_number int` | unique per sheet, assigned by the server (`max + 1`) | -| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | -| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | -| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` and size ≤ 2 MiB | -| `change_note text` | what changed in this version | -| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | -| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | +| Column | Notes | +| ----------------------------------------------------------- | --------------------------------------------------------------------------- | +| `id uuid`, `sheet_id` | | +| `version_number int` | unique per sheet, assigned by the server from the sheet's monotonic counter | +| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` | +| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today | +| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` and size ≤ 2 MiB | +| `change_note text` | what changed in this version | +| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` | +| `published_at`, `deprecated_at`, `created_at`, `updated_at` | | Rules enforced by triggers (every role, including the table owner): @@ -211,7 +214,7 @@ authorise through the sheet, never through a sha256 alone. | RPC | Actor | Effect | | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `create_anatomical_sheet(species_id, name, slug, document, description, visibility, official)` | any active account; `official = true` needs platform admin | sheet + draft v1 | -| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft `max + 1`, content copied from `from_version_id` (default: current version); refused if a draft exists | +| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft (next counter value), content copied from `from_version_id` (default: current version); refused if a draft exists | | `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) | | `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) | | `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions | @@ -248,8 +251,8 @@ Policies: | `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) | `anon` gets nothing. Every `private` function has EXECUTE revoked from -PUBLIC; only the two predicates above are granted to `authenticated` -(pgTAP 001 keeps a census). Public discovery views for the public site come +PUBLIC; `authenticated` executes only the policy predicates (the two above +plus the five platform-role predicates of Step 3); pgTAP 001 keeps a census. Public discovery views for the public site come with the community step (§17.4). ## 4. What the model guarantees (acceptance criteria) diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 29ab6bdb..b137c74f 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -13,7 +13,8 @@ supabase/ │ ├─ 20261008100000_foundation.sql schemas private/audit, updated_at, audit log │ ├─ 20261008100100_profiles.sql profiles + auth.users trigger + RLS │ ├─ 20261008100200_platform_roles.sql platform_role, profile_roles, helpers, RPCs -│ └─ 20261008110000_anatomical_sheets.sql species, sheets, immutable versions, assets, lifecycle RPCs +│ ├─ 20261008110000_anatomical_sheets.sql species, sheets, immutable versions, assets, lifecycle RPCs +│ └─ 20261008110100_private_execute_hardening.sql EXECUTE revoked from PUBLIC on the Step 3 helpers ├─ seed.sql LOCAL dev accounts + first owner (never run in prod) └─ tests/ pgTAP, one file per concern, allowed AND denied paths packages/supabase/ @@ -51,23 +52,23 @@ pnpm db:reset # drop + replay every migration + seed from zero Local endpoints (`config.toml`): -| Service | URL | -|---|---| -| API (PostgREST, Auth, Storage) | `http://127.0.0.1:54321` | -| PostgreSQL | `postgresql://postgres:postgres@127.0.0.1:54322/postgres` | -| Studio | `http://127.0.0.1:54323` | -| Mail catcher (confirmation / OTP mails) | `http://127.0.0.1:54324` | +| Service | URL | +| --------------------------------------- | --------------------------------------------------------- | +| API (PostgREST, Auth, Storage) | `http://127.0.0.1:54321` | +| PostgreSQL | `postgresql://postgres:postgres@127.0.0.1:54322/postgres` | +| Studio | `http://127.0.0.1:54323` | +| Mail catcher (confirmation / OTP mails) | `http://127.0.0.1:54324` | `pnpm db:start` prints the `anon` and `service_role` keys. Only the anon key ever reaches the browser. Seed accounts (local only, password `LocalDev-only-password-1`): -| Email | Role | -|---|---| +| Email | Role | +| ----------------------- | ------------------------------------------- | | `owner@faunosteo.local` | platform owner (bootstrapped by `seed.sql`) | -| `alice@faunosteo.local` | plain user | -| `bob@faunosteo.local` | plain user | +| `alice@faunosteo.local` | plain user | +| `bob@faunosteo.local` | plain user | ## 4. Writing a migration @@ -92,10 +93,10 @@ RLS enabled, no `using (true)` / `with check (true)` policy for `anon` or Two runners, one SQL source of truth (`supabase/tests/*.sql`, pgTAP): -| Command | Engine | Needs Docker | What runs | -|---|---|---|---| -| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory; publish gate | -| `pnpm db:test` | `supabase test db` (pg_prove in the local stack) | yes | the same pgTAP files against the real Supabase image | +| Command | Engine | Needs Docker | What runs | +| -------------------------------------------- | ------------------------------------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------ | +| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory; publish gate | +| `pnpm db:test` | `supabase test db` (pg_prove in the local stack) | yes | the same pgTAP files against the real Supabase image | `pnpm test:run` at the root runs the PGlite suite together with the app suite. The shim (`packages/supabase/tests/db/supabase-shim.sql`) recreates