commit ca65c9f29f06bcd1845e104ae380b6c24bff1f2a
parent a81028b8f4b2f78325f8e93c848515594594523a
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sat, 19 Sep 2026 03:12:36 +0530
parent a81028b8f4b2f78325f8e93c848515594594523a
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sat, 19 Sep 2026 03:12:36 +0530
Re-agree the domain model: parties, sign at sign-off, glossary split Records the 2026-09-19 design session: DocuSeal-style parties with one signer each, signature zones filled by the signer at sign-off, release rendered by the worker, organisation-bound PIM imprints, mandatory title, renamed statuses, template/series lifecycle. CONTEXT.md becomes the glossary only; HANDOFF.md takes the state and decisions; ADR 0001 and docs/REBUILD.md carry the reasoning and the plan for the code change, which is not yet made. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
5 files changed, 692 insertions(+), 184 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md @@ -1,7 +1,10 @@ # AGENTS.md — working rules for this repository -Read `CONTEXT.md` first (why things are the way they are, current state, open -work). `README.md` is the user-facing description and install guide. +Read `CONTEXT.md` first (the glossary — use its words), then `HANDOFF.md` +(current state, decisions and why, open work) and `docs/adr/`. `README.md` is +the user-facing description and install guide. The invariants below describe +the 2026-09-18 code; `docs/REBUILD.md` §10 lists which ones change with the +rebuild. ## Hard constraints (from the owner; do not relax without asking)
diff --git a/CONTEXT.md b/CONTEXT.md @@ -1,182 +1,73 @@ -# CONTEXT.md — handoff notes (state as of 2026-09-18) - -Signet is a maker-checker document stamping system: a clerk places text, -seals and signature boxes on a PDF in the browser; the server flattens them -into the PDF; approvers sign off level by level; the last sign-off releases a -print copy with an audit page and SHA-256. Built in one session from the -owner's "SYSTEM ARCHITECTURE & HANDOFF SPECIFICATION" plus the clarifications -recorded below. Rules for working here are in `AGENTS.md`. - -## 1. Status - -**Working and verified on Alpine 3.22 (podman):** - -* Clean build with `-Wall -Wextra`; `test/e2e.sh` → 36 checks, "all passed". -* Browser check done by hand: dashboard, edit mode (drag moves the `<area>`, - property panel, palette), submit, preview mode as approver (overlays sit - exactly on the stamped text; seal alpha correct; signature under red box). -* RSS: signet-api ≈ 2.8 MB ×2 (+ ~1 MB kcgi parser children), signetd 2.8 MB, - pim-api 2.4 MB, kfcgi 0.5 MB ×2 → ~17 MB of the 60 MB budget. - -**Not verified / never run:** OpenRC scripts, `etc/lighttpd-signet.conf` -(production config incl. WebDAV + CSP), real Authelia in front, `make install` -on a real host, JPEG embedding, TTF fonts other than DejaVuSans, rotated or -CropBox-offset source PDFs, `poly` areas, mode `all` with >1 approver, -template with a different page count, concurrent submits on one series. - -**Nothing is committed.** `git init` only; the owner has not asked for a commit. - -## 2. Decisions and their reasons - -| # | Decision | Why | -| :-- | :-- | :-- | -| D1 | **No groff.** Overlay PDF is written by `src/pdfw.c`; `qpdf --overlay` merges | `groff -Tpdf` = `gropdf` = Perl; `.PDFPIC` only embeds PDFs (PNG would need ImageMagick, alpha doubtful); spec's sample used `.h` which is not a request. Owner accepted ("others use recommended"). Owner's motive for troff was dynamic content → covered by `serial`/`date` imprints + series + templates | -| D2 | **Stamping at submit; approval = sign-off** | Owner, mid-build: "stamping is done immediately… checkers only then send a signal that the stamped document is okay, that is essentially the signing". Hence two files: `proof.pdf` (no signatures → maker) and `stamped.pdf` (with signatures → checkers) | -| D3 | **No `STAMPING`/`FAILED` status** | Owner rejected it. Async gap is expressed by `rendered_revision < revision`; failure by `render_error` + "Retry stamping" (`POST …/rerender`) | -| D4 | Statuses `DRAFT, PENDING_APPROVAL, CORRECTION_REQUIRED, CORRECTED, DISAPPROVED, APPROVED` | Owner prefers these over an umbrella REJECTED. `CORRECTED` behaves exactly like `PENDING_APPROVAL` (both in `PENDING` macro); it only flags a resubmission. Correction resets `current_level` to 1 and bumps `revision` | -| D5 | **Multi-level routes**: `{"levels":[{"approvers":[…],"mode":"any"|"all"}]}` per document | Owner: many approvers, same level or through levels, several per level | -| D6 | Signature ref = explicit username that must appear in the route; `level:N` refs dropped | With D2 the image is stamped before anyone approves, so "whoever approves level N" is unknowable | -| D7 | Release (audit page + hash) runs **synchronously in signet-api** at the last sign-off | Needs no secrets (stamped copy already exists), keeps APPROVED atomic with `final_sha256`. `stamped.pdf` is deleted on release, correction and disapproval | -| D8 | Fonts are DAM assets (`/dam/fonts/*.ttf`), used by browser (`FontFace`) and worker (embedded, Identity-H + ToUnicode) | Owner: "don't hardcode the font, both frontend and backend use the same font via the WebDAV path" | -| D9 | Series pattern `{date:<strftime>}` / `{seq:<width>}`, counter per (series, day), allocated at **first submit** | Owner's example `SKGA/SCNREPLY/20260909/01`. First-submit allocation is *my assumption* so abandoned drafts don't burn numbers — not yet confirmed | -| D10 | No maker free-text imprint | Owner: "don't want [that] feature for now" | -| D11 | Server never rasterises; preview = pdf.js rendering of the server-flattened PDF | ImageMagick needs Ghostscript for PDF (prohibited); gives maximal edit/preview code sharing | -| D12 | `imageMapResizer` replaced by `scaleArea()` + `ResizeObserver` (~10 lines) | Owner asked for a jQuery-less alternative; the overlay needs the resize hook anyway | -| D13 | Identity from request **headers** `Remote-User`/`Remote-Groups` (names configurable) | kcgi exposes `HTTP_*` headers via `r->reqs` but not arbitrary CGI vars like `REMOTE_USER` | -| D14 | Two OS users: `signet` (API, PIM) and `signetd` (worker, sole reader of `sig_dir`), shared group `signet`, `data_dir` mode 2770 | Privilege separation is the actual reason a worker still exists after D7 | -| D15 | yyjson 0.10.0 vendored; name "Signet" | Owner's choices | - -Terminology agreed with the owner: **proof** (maker's flattened copy), -**stamped copy** (checkers'), **sign-off** (an approval), **signature -facsimile** (the image; not a cryptographic signature), **release** (last -sign-off → `final.pdf`). - -## 3. Map of the code - -``` -src/conf.[ch] key = value config, inline "# comments", group-list helpers -src/util.[ch] run_cmd (fork/execvp, strict exit), SHA-256, file helpers, - is_uuid / is_safe_name / is_safe_relpath, utf8_next -src/db.[ch] lazy PG + Redis connections, db_q / db_do -src/ttf.[ch] bounds-checked TrueType reader: cmap 4/12, hmtx, metrics -src/pdfw.[ch] PDF writer: pages, Helvetica fallback, embedded TTF - (CIDFontType2, W array, ToUnicode), PNG→RGB+SMask (libpng - simplified API, ≤4 MP), JPEG passthrough -src/render.[ch] pdfinfo page sizes (+rot swap), bbox per shape, px→pt, - draw_text/draw_image, render_stamp (overlay + qpdf), - render_release (audit page + qpdf --pages), series_expand, - pim_lookup -src/http.[ch] kcgi helpers: identity/roles, fields, CSRF check, path - split, send_json/err/file -src/signet-api.c all endpoints (list at top of file), validation, - submit / decide transactions, release() -src/signetd.c BRPOPLPUSH loop → proof.pdf + stamped.pdf → PG update -pim/pim-api.c GET/POST /attrs, POST /resync (PG → Redis mirror) -pim/www/index.html one-page PIM editor -www/app.js whole client; sections: helpers, fonts, geometry, imprint - values, overlay, layout⇄DOM, renderPdf, side panel, doc - view, dashboard, series, boot -sql/schema.sql series, series_counters, templates, documents, - doc_decisions, doc_events, pim_attributes -etc/ signet.conf.example, lighttpd-signet.conf, init.d/* -test/ dev-up.sh (container entrypoint), lighttpd-dev.conf, - e2e.sh, make-fixtures.py, fixtures/ -``` - -Disk layout: `<data_dir>/docs/<uuid>/{source,proof,stamped,final}.pdf`, -`<data_dir>/templates/<uuid>.pdf`, `<dam_dir>/…`, `<sig_dir>/<user>.png`. - -Request flow for a submit: `save` (layout+route JSON validated, stored as -JSONB) → `submit` (tx: lock row, `check_submittable` — PIM refs resolvable, -DAM files exist, signers ∈ route, series present if `serial` imprint — allocate -serial, status/revision update, commit) → `LPUSH {"doc_id","revision"}` → -signetd renders both files → `rendered_revision = revision` → client polls -`GET /docs/<id>` every 1.2 s until then. - -Layout JSON (what `collectLayout()` emits, what `render.c` reads): - -```json -{"reference_width":1000,"reference_height":1414,"imprints":[ - {"page":1,"shape":"rect","type":"pim_text","ref":"org:gstin","prefix":"GSTIN: ", - "coords":[120,150,520,180],"ref_w":1000,"ref_h":1414,"font":"fonts/X.ttf","align":"left"}]} -``` - -`ref_w/ref_h` per imprint override the top-level reference size (pages can -differ). The client rasterises every page to 1000 px natural width. - -## 4. Known problems and gaps (most important first) - -1. **API errors are invisible.** `kfcgi` detaches and stderr goes nowhere, so - `db_q()` SQL errors vanish (cost two debugging rounds). Switch - `signet-api`/`pim-api` logging to `syslog(3)` (or have kfcgi run with a log - redirect) — do this before any further API work. -2. **Authelia ↔ lighttpd is unproven.** lighttpd has no native forward-auth; - the assumption is a proxy in front that sets and *overwrites* - `Remote-User`/`Remote-Groups`. If identity only arrives as CGI - `REMOTE_USER`, kcgi cannot see it → needs a lighttpd `setenv`/mod_magnet - shim or a patch. Header spoofing must be impossible in production. -3. **DAM WebDAV write access** is not restricted in `lighttpd-signet.conf` - (comment says "restrict at the proxy"). Decide and implement; anyone who - can PUT a seal or font changes what gets stamped. There is no DAM upload - UI — by design it's a network drive. -4. **No signature management.** Files are placed in `sig_dir` by hand - (`<username>.png`, owner `signetd`, 0600). A submit with a signer whose - file is missing fails in the worker (`render_error`), not at submit, - because the API may not look into `sig_dir`. -5. `circle`/`poly` are stamped via bounding box, no clipping. The editor - offers rect + circle only (circle only for images); `poly` is supported in - the model/backend but has no editor UI. -6. Rotated pages: handled only by swapping w/h from `pdfinfo`; untested. - Non-zero MediaBox origin / CropBox: relies on qpdf's overlay fitting. -7. No complex-script shaping (Tamil etc.). Latin + symbols (₹ if the font has - it). OTF/CFF fonts are rejected → Helvetica fallback with a log line; the - *browser* would still show the OTF, so edit ≠ proof in that case. Consider - filtering `/api/dam` fonts through `ttf_load`. -8. `GET /docs` caps at 200 rows, no pagination/search. No template delete or - edit, no series delete. `customer_id` is free text. -9. Uploads are held in memory by kcgi (limit 32 MB in code, 34 MB in - lighttpd). With 2–4 API workers this is the main threat to the RAM budget; - consider lowering the cap. -10. Redis AOF must be enabled in production (`appendonly yes`); not enforced. - If `LPUSH` fails after the submit commit the doc sits un-stamped until - someone presses "Retry stamping" (no automatic sweep in signetd). -11. `doc_events` is written but there is no UI for it. -12. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker, - `blob:` images, inline `style` attributes set via `h()`). - -## 5. Open questions for the owner - -* Confirm D9 (serial allocated at first submit, counter restarts daily). -* Should `title` be auto-derived from the serial always, or stay editable? -* Who may write to the DAM, and should fonts/seals be versioned or frozen - once a document referencing them is pending? -* Should approvers at level *n* see signature facsimiles of later levels in - the stamped copy (they do today)? -* Is a cryptographic PDF signature (PAdES) wanted later? Would need a new - allowed dependency. -* Fix `~/.ssh/known_hosts` line 47 so host `podman` works? (Not touched.) - -## 6. Suggested next steps - -1. syslog logging in both FastCGI programs (§4.1). -2. First commit (owner must ask) — everything is untracked. -3. Bring up on a real Alpine VM with OpenRC + Authelia; fix what §1 lists as - never run; settle §4.2 and §4.3. -4. e2e additions: mode `all` with two approvers, disapprove path, rerender - after a failed stamp (missing PIM value → add it → retry), draft delete, - JPEG seal, second font. -5. Signature enrolment flow (admin-only upload that hands the file to - signetd's directory without the API user being able to read it back). -6. Font list validation, pagination, `doc_events` timeline in the side panel. - -## 7. Dev environment facts - -* Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created - for this project; image `signet-dev`; a container named `signet` may still - be running on :8080 with throw-away data (DB is re-initialised per run). -* Alpine 3.22 packages used: `kcgi-dev`, `hiredis-dev`, `libpq-dev` - (headers in `/usr/include/postgresql`, found via `pkg-config`), - `postgresql16`, `redis` 8, `lighttpd` 1.4.85 + `lighttpd-mod_webdav`, - `qpdf` 12, `poppler-utils`, `font-dejavu` (test font). -* kfcgi flags: `-u` = socket owner (lighttpd), `-U` = process user (signet), - `-p /` = no chroot (we exec qpdf and link libpq dynamically). +# Signet + +A document signing register: a drafter prepares a document from a template, +the parties in its route sign one after another, and the last sign-off +releases a numbered print copy with an audit page. This file is the glossary. +Decisions (`Dn`) are in `HANDOFF.md` §2 and `docs/adr/`; the state of the code +is in `HANDOFF.md`. + +## Language + +### Roles and parties + +**Drafter**: the role that prepares a document — places imprints and signature zones, sets the route — and submits it. A role, not a person: the same user may also sign it (D16). _Avoid_: maker, clerk (spec-era words; `maker` survives in code and the `Remote-Groups` role name until renamed) + +**Party**: a named post in a template that must act on every document made from it (*Partner*, *Auditor*, *Manager*). Has at most one signature zone; a party with none is a **check-only party**. _Avoid_: level, approver, authorized signatory + +**Signer**: the user the drafter assigns to a party for one document. Exactly one per party. _Avoid_: checker, approver, submitter (DocuSeal's word) + +**Route**: the ordered list of parties, each with its signer, fixed by the drafter before submit. Parties act strictly one after another; a party cannot see the document until the party before it has signed off. + +**Organisation**: the entity a document is about; every document is bound to exactly one, chosen by the drafter. Its attributes fill the document's PIM imprints. _Avoid_: entity, org (code identifier), customer (D21) + +### Document lifecycle + +**Template**: a reusable starting point for documents: a base PDF, its imprints and signature zones, its parties, and the series it numbers from. A document copies all of it at creation and is unaffected by later edits to the template. Can be edited, retired, and (by an admin, once unlinked everywhere) deleted. _Avoid_: form, blank + +**Status**: where a document is in its life: `DRAFT` → `PENDING` → (`CORRECTION_REQUIRED` → `PENDING` …) → `RELEASED` or `DISAPPROVED` (D27). _Avoid_: state, stage; the old `PENDING_APPROVAL`/`CORRECTED`/`APPROVED` + +**Decision**: what a signer records: a **sign-off**, a **correction request**, or a **disapproval**. _Avoid_: reject, rejection (umbrella word; there is no `REJECTED` status, D4/D27) + +**Sign-off**: an approving decision. For a party with a zone it includes placing the signer's facsimile in the zone. Attests one specific stamped copy (one revision). _Avoid_: approval, approve (a document is *released*, not approved) + +**Correction request**: a decision that returns the document to the drafter for editing. Resubmitting creates a new revision and restarts the route (D17). + +**Disapproval**: a terminal decision, with a reason. The document keeps its serial and cannot be edited, resubmitted or deleted. _Avoid_: permanent rejection, decline (DocuSeal's word) + +**Release**: the render after the last sign-off producing `final.pdf` with the audit page and SHA-256. + +**Retire**: hide a template or series from drafters without deleting it. Retired series keep their pattern and counters forever. _Avoid_: archive, disable + +**Unlink**: remove a document's back-reference to its template. The document loses nothing (it is a self-contained copy). A template can be deleted by an admin only when no document links to it (D28). _Avoid_: detach + +### What goes on the page + +**Imprint**: one element the drafter places on a page: text from a PIM attribute, the serial or the document date (each with an optional fixed prefix such as `GSTIN: `), or a PIM image attribute. There is no free-text imprint (D10). Flattened at submit. _Avoid_: field (DocuSeal's word) + +**PIM**: Signet's local store of organisation attributes, a reduced mirror of the organisation's full product-information system (D23). Maintained by a `pim_admin` in the PIM editor. _Avoid_: master data, config + +**PIM attribute**: one named value of an organisation, either text (`gstin`, `bank_account`, `pan`) or an image (`seal`, `logo`, a product photo), imprinted by key so the same template serves every organisation. _Avoid_: PIM value, field + +**Seal**: an organisation's image attribute stamped as an imprint. _Avoid_: stamp (DocuSeal's word for a signer's mark) + +**Signature zone**: a rectangle the drafter reserves on a page for one party's signature, with a **minimum size**. The signer's facsimile must lie entirely inside it and be at least the minimum size. _Avoid_: signature box, max/min bounding box + +**Placement**: the rectangle a signer's facsimile occupies inside its zone. Automatic (largest fit that keeps the image's proportions) when the signer has an enrolled facsimile; chosen by hand otherwise. + +**Signature facsimile**: the image of a person's signature. Not a cryptographic signature. **Enrolled** once a user has signed for the first time or an admin has placed it; reused on later documents. _Avoid_: signature (alone), e-signature + +**Proof**: the drafter's flattened copy: imprints, no facsimiles. + +**Stamped copy**: the copy the current party sees: the proof plus the facsimiles of every party that has already signed off. Each sign-off adds one facsimile to it; nothing else is re-rendered. Deleted on release, correction request and disapproval. + +### Numbering and records + +**Series**: a numbering scheme (pattern with date and per-day sequence) that a template belongs to. _Avoid_: register, counter + +**Serial**: the document number allocated from a series at first submit (D9). Never reissued, even when the document is disapproved. + +**Document date**: the date of first submit. Fixed with the serial; the `date` imprint and the serial's date part both come from it, so a resubmit on a later day changes neither. + +**Event log**: the complete history of a document — created, each submit and resubmit, every decision with its reason — across all revisions. Printed in full on the audit page. _Avoid_: timeline, activity + +**Audit page**: the page(s) appended at release: document id, serial, title, organisation, the full event log, and the SHA-256 of the pages before it. The body pages carry no trace of corrections; the audit page is where the history shows (D26). _Avoid_: certificate, audit log (DocuSeal's word)
diff --git a/HANDOFF.md b/HANDOFF.md @@ -0,0 +1,188 @@ +# HANDOFF.md — state of the code and the decisions behind it + +Code as of 2026-09-18; model revised 2026-09-19. Vocabulary is in +`CONTEXT.md`; working rules in `AGENTS.md`; the rebuild to the revised model is +planned in `docs/REBUILD.md`. + +**The code still implements the 2026-09-18 model** (D2/D5/D6/D7: facsimiles +stamped at submit, levels with `any`/`all`, `customer_id`, old status names). +The 2026-09-19 model (D16–D29, `docs/adr/0001`) is agreed but not yet built; +§3 describes the code as it is, `CONTEXT.md` describes the model as agreed. + +## 1. Status + +**Working and verified on Alpine 3.22 (podman):** + +* Clean build with `-Wall -Wextra`; `test/e2e.sh` → 36 checks, "all passed". +* Browser check done by hand: dashboard, edit mode (drag moves the `<area>`, + property panel, palette), submit, preview mode as approver (overlays sit + exactly on the stamped text; seal alpha correct; signature under red box). +* RSS: signet-api ≈ 2.8 MB ×2 (+ ~1 MB kcgi parser children), signetd 2.8 MB, + pim-api 2.4 MB, kfcgi 0.5 MB ×2 → ~17 MB of the 60 MB budget. + +**Not verified / never run:** OpenRC scripts, `etc/lighttpd-signet.conf` +(production config incl. WebDAV + CSP), real Authelia in front, `make install` +on a real host, JPEG embedding, TTF fonts other than DejaVuSans, rotated or +CropBox-offset source PDFs, `poly` areas, mode `all` with >1 approver, +template with a different page count, concurrent submits on one series. + +**Nothing is committed.** `git init` only; the owner has not asked for a commit. + +## 2. Decisions and their reasons + +| # | Decision | Why | +| :-- | :-- | :-- | +| D1 | **No groff.** Overlay PDF is written by `src/pdfw.c`; `qpdf --overlay` merges | `groff -Tpdf` = `gropdf` = Perl; `.PDFPIC` only embeds PDFs (PNG would need ImageMagick, alpha doubtful); spec's sample used `.h` which is not a request. Owner accepted ("others use recommended"). Owner's motive for troff was dynamic content → covered by `serial`/`date` imprints + series + templates | +| D2 | *Superseded by D18.* Stamping at submit; approval = sign-off | Owner, mid-build: "stamping is done immediately… checkers only then send a signal that the stamped document is okay, that is essentially the signing". Hence two files: `proof.pdf` (no signatures → maker) and `stamped.pdf` (with signatures → checkers) | +| D3 | **No `STAMPING`/`FAILED` status** | Owner rejected it. Async gap is expressed by `rendered_revision < revision`; failure by `render_error` + "Retry stamping" (`POST …/rerender`) | +| D4 | *Superseded by D27.* Statuses `DRAFT, PENDING_APPROVAL, CORRECTION_REQUIRED, CORRECTED, DISAPPROVED, APPROVED` | Owner prefers these over an umbrella REJECTED. `CORRECTED` behaves exactly like `PENDING_APPROVAL` (both in `PENDING` macro); it only flags a resubmission. Correction resets `current_level` to 1 and bumps `revision` | +| D5 | *Superseded by D18.* Multi-level routes: `{"levels":[{"approvers":[…],"mode":"any"|"all"}]}` per document | Owner: many approvers, same level or through levels, several per level | +| D6 | *Superseded by D18.* Signature ref = explicit username that must appear in the route; `level:N` refs dropped | With D2 the image is stamped before anyone approves, so "whoever approves level N" is unknowable | +| D7 | *Superseded by D18.* Release (audit page + hash) runs synchronously in signet-api at the last sign-off | Needs no secrets (stamped copy already exists), keeps APPROVED atomic with `final_sha256`. `stamped.pdf` is deleted on release, correction and disapproval | +| D8 | Fonts are DAM assets (`/dam/fonts/*.ttf`), used by browser (`FontFace`) and worker (embedded, Identity-H + ToUnicode) | Owner: "don't hardcode the font, both frontend and backend use the same font via the WebDAV path" | +| D9 | Series pattern `{date:<strftime>}` / `{seq:<width>}`, counter per (series, day), serial and **document date** fixed at **first submit**; a disapproved document keeps its number (gap in the register); a resubmit keeps serial and date | Owner's example `SKGA/SCNREPLY/20260909/01`. Drafts never burn numbers. Confirmed by owner 2026-09-19 | +| D10 | No drafter free-text imprint | Owner: "don't want [that] feature for now" | +| D11 | Server never rasterises; preview = pdf.js rendering of the server-flattened PDF | ImageMagick needs Ghostscript for PDF (prohibited); gives maximal edit/preview code sharing | +| D12 | `imageMapResizer` replaced by `scaleArea()` + `ResizeObserver` (~10 lines) | Owner asked for a jQuery-less alternative; the overlay needs the resize hook anyway | +| D13 | Identity from request **headers** `Remote-User`/`Remote-Groups` (names configurable) | kcgi exposes `HTTP_*` headers via `r->reqs` but not arbitrary CGI vars like `REMOTE_USER` | +| D14 | Two OS users: `signet` (API, PIM) and `signetd` (worker, sole reader of `sig_dir`), shared group `signet`, `data_dir` mode 2770 | Privilege separation is the actual reason a worker still exists after D7 | +| D15 | yyjson 0.10.0 vendored; name "Signet" | Owner's choices | +| D16 | **No separation of duties**: the drafter may be a signer on their own document | Owner (2026-09-19): self-service is common — an authorized signatory builds a template, submits and signs it themselves to get a printable copy. Drafter/signer are roles, not people | +| D17 | A correction request voids **all** sign-offs of that revision; after resubmit every party signs again from the first | A sign-off attests one specific stamped copy; the copy changed. Owner confirmed 2026-09-19 | +| D18 | **Party model, DocuSeal-style** (`docs/adr/0001`): a template names parties; the drafter assigns one signer per party at submit; parties sign strictly one after another; the drafter reserves a signature zone, the signer fills it at sign-off with their own facsimile; release is rendered by the worker after the last sign-off. **Imprints are flattened once, at submit**; each sign-off overlays the facsimile onto the previous stamped copy, so the DAM is read only at submit and a mid-route seal/font change cannot reach a pending document | Owner 2026-09-19: "a document requires a signature of a signatory. Anyone [holding the post] can sign that box"; then "compare with DocuSeal and copy them". Replaces D2/D5/D6/D7. `any`/`all` and multi-approver levels are gone; "any partner" = the drafter picks which partner | +| D19 | At most **one zone per party**; check-only parties (no zone) exist; per-page names or initials are ordinary text imprints, not signatures | Owner 2026-09-19: initials-on-every-page is not an obvious case; "put [the] name … or place a partner text there" | +| D20 | **Enrolment at first signing**: a signer without an enrolled facsimile signs in the browser (draw/upload, as DocuSeal); the image is kept and reused; an admin may also place one | Owner 2026-09-19. Replaces the hand-copied `sig_dir` files of §4.4; the worker remains the sole reader of stored facsimiles (D14) | +| D21 | **No "customer" concept.** `customer_id` (free text on documents, a dashboard column, a side-panel field) is to be removed in the rebuild | Owner 2026-09-19: "I don't know how a customer got here, delete it" | +| D22 | **Title is mandatory**; the drafter must set it before submit. Replaces today's "blank → serial" default | Owner 2026-09-19 | +| D23 | **PIM is a deliberately reduced, local key/value mirror** (Redis) of the organisation's full PIM, which is too heavy to run beside Signet. **A document is bound to one organisation**, chosen by the drafter; PIM imprints reference an attribute *key* and resolve against that organisation at submit. Replaces today's literal `org:key` refs baked into the template | Owner 2026-09-19: "select an org and fetch all the gstin and bank account in the right places automatically" | +| D24 | **PIM is readable by everyone in the organisation.** No per-user redaction | Owner 2026-09-19. A redaction blacklist was considered and dropped the same day: it would have to reach the proof and the release, and "brings more problems than it solves" | +| D25 | **PIM attributes have a type: text or image.** An image attribute's value is a path on the DAM (the network drive stays the file store); the organisation's seal is its `seal` image attribute. Every image on a document comes through a PIM key, so templates stay organisation-independent | Owner 2026-09-19: "implement images feature in PIM now, not later". Replaces the drafter picking a DAM file by hand | +| D26 | **The audit page carries the whole event log**: creation, every submit, every correction request and disapproval with its reason, every sign-off, across all revisions | Owner 2026-09-19: the printed body is "squeaky clean", so the audit page is the only place the history shows | +| D27 | Statuses renamed to match the vocabulary: `DRAFT, PENDING, CORRECTION_REQUIRED, DISAPPROVED, RELEASED`. `CORRECTED` becomes a `RESUBMITTED` event, not a status | Owner 2026-09-19, on recommendation. Replaces D4 | +| D28 | **Templates are edited and retired, never silently deleted**; an admin may delete a template only after every document has been **unlinked** from it. **Series are retired, never deleted or re-patterned** once a serial has been issued | Owner 2026-09-19. Documents are self-contained copies, so unlinking loses nothing but the back-reference | +| D29 | **Latin script only** for now (no shaping). Imprint shapes: **rectangle and circle** (circle clips a round seal); `poly` dropped | Owner 2026-09-19 | + +## 3. Map of the code (2026-09-18 model) + +``` +src/conf.[ch] key = value config, inline "# comments", group-list helpers +src/util.[ch] run_cmd (fork/execvp, strict exit), SHA-256, file helpers, + is_uuid / is_safe_name / is_safe_relpath, utf8_next +src/db.[ch] lazy PG + Redis connections, db_q / db_do +src/ttf.[ch] bounds-checked TrueType reader: cmap 4/12, hmtx, metrics +src/pdfw.[ch] PDF writer: pages, Helvetica fallback, embedded TTF + (CIDFontType2, W array, ToUnicode), PNG→RGB+SMask (libpng + simplified API, ≤4 MP), JPEG passthrough +src/render.[ch] pdfinfo page sizes (+rot swap), bbox per shape, px→pt, + draw_text/draw_image, render_stamp (overlay + qpdf), + render_release (audit page + qpdf --pages), series_expand, + pim_lookup +src/http.[ch] kcgi helpers: identity/roles, fields, CSRF check, path + split, send_json/err/file +src/signet-api.c all endpoints (list at top of file), validation, + submit / decide transactions, release() +src/signetd.c BRPOPLPUSH loop → proof.pdf + stamped.pdf → PG update +pim/pim-api.c GET/POST /attrs, POST /resync (PG → Redis mirror) +pim/www/index.html one-page PIM editor +www/app.js whole client; sections: helpers, fonts, geometry, imprint + values, overlay, layout⇄DOM, renderPdf, side panel, doc + view, dashboard, series, boot +sql/schema.sql series, series_counters, templates, documents, + doc_decisions, doc_events, pim_attributes +etc/ signet.conf.example, lighttpd-signet.conf, init.d/* +test/ dev-up.sh (container entrypoint), lighttpd-dev.conf, + e2e.sh, make-fixtures.py, fixtures/ +``` + +Disk layout: `<data_dir>/docs/<uuid>/{source,proof,stamped,final}.pdf`, +`<data_dir>/templates/<uuid>.pdf`, `<dam_dir>/…`, `<sig_dir>/<user>.png`. + +Request flow for a submit: `save` (layout+route JSON validated, stored as +JSONB) → `submit` (tx: lock row, `check_submittable` — PIM refs resolvable, +DAM files exist, signers ∈ route, series present if `serial` imprint — allocate +serial, status/revision update, commit) → `LPUSH {"doc_id","revision"}` → +signetd renders both files → `rendered_revision = revision` → client polls +`GET /docs/<id>` every 1.2 s until then. + +Layout JSON (what `collectLayout()` emits, what `render.c` reads): + +```json +{"reference_width":1000,"reference_height":1414,"imprints":[ + {"page":1,"shape":"rect","type":"pim_text","ref":"org:gstin","prefix":"GSTIN: ", + "coords":[120,150,520,180],"ref_w":1000,"ref_h":1414,"font":"fonts/X.ttf","align":"left"}]} +``` + +`ref_w/ref_h` per imprint override the top-level reference size (pages can +differ). The client rasterises every page to 1000 px natural width. + +## 4. Known problems and gaps (most important first) + +1. **API errors are invisible.** `kfcgi` detaches and stderr goes nowhere, so + `db_q()` SQL errors vanish (cost two debugging rounds). Switch + `signet-api`/`pim-api` logging to `syslog(3)` (or have kfcgi run with a log + redirect) — do this before any further API work. +2. **Authelia ↔ lighttpd is unproven.** lighttpd has no native forward-auth; + the assumption is a proxy in front that sets and *overwrites* + `Remote-User`/`Remote-Groups`. If identity only arrives as CGI + `REMOTE_USER`, kcgi cannot see it → needs a lighttpd `setenv`/mod_magnet + shim or a patch. Header spoofing must be impossible in production. +3. **DAM WebDAV write access** is not restricted in `lighttpd-signet.conf` + (comment says "restrict at the proxy"). Decide and implement; anyone who + can PUT a seal or font changes what future submits stamp. There is no DAM + upload UI — by design it's a network drive. +4. **No signature management** (to be replaced by D20). Files are placed in `sig_dir` by hand + (`<username>.png`, owner `signetd`, 0600). A submit with a signer whose + file is missing fails in the worker (`render_error`), not at submit, + because the API may not look into `sig_dir`. +5. `circle`/`poly` are stamped via bounding box, no clipping. The editor + offers rect + circle only (circle only for images); `poly` is supported in + the model/backend but has no editor UI. (D29: drop `poly`, clip circles.) +6. Rotated pages: handled only by swapping w/h from `pdfinfo`; untested. + Non-zero MediaBox origin / CropBox: relies on qpdf's overlay fitting. +7. No complex-script shaping (Tamil etc.). Latin + symbols (₹ if the font has + it). OTF/CFF fonts are rejected → Helvetica fallback with a log line; the + *browser* would still show the OTF, so edit ≠ proof in that case. Consider + filtering `/api/dam` fonts through `ttf_load`. +8. `GET /docs` caps at 200 rows, no pagination/search. No template delete or + edit, no series delete (settled by D28). `customer_id` is free text + (removed by D21). +9. Uploads are held in memory by kcgi (limit 32 MB in code, 34 MB in + lighttpd). With 2–4 API workers this is the main threat to the RAM budget; + consider lowering the cap. +10. Redis AOF must be enabled in production (`appendonly yes`); not enforced. + If `LPUSH` fails after the submit commit the doc sits un-stamped until + someone presses "Retry stamping" (no automatic sweep in signetd). +11. `doc_events` is written but there is no UI for it (D26 prints it on the + audit page). +12. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker, + `blob:` images, inline `style` attributes set via `h()`). + +## 5. Open questions for the owner + +* Who may write to the DAM (operational only: with D18 a change affects + future submits, never a pending or signed document; no versioning needed). +* Is a cryptographic PDF signature (PAdES) wanted later? Would need a new + allowed dependency. +* Fix `~/.ssh/known_hosts` line 47 so host `podman` works? (Not touched.) + +## 6. Next steps + +1. **The rebuild to the 2026-09-19 model**: `docs/REBUILD.md`. +2. syslog logging in both FastCGI programs (§4.1) — first, it makes the + rebuild debuggable. +3. First commit (owner must ask) — everything is untracked. +4. Bring up on a real Alpine VM with OpenRC + Authelia; fix what §1 lists as + never run; settle §4.2 and §4.3. +5. Font list validation, pagination. + +## 7. Dev environment facts + +* Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created + for this project; image `signet-dev`; a container named `signet` may still + be running on :8080 with throw-away data (DB is re-initialised per run). +* Alpine 3.22 packages used: `kcgi-dev`, `hiredis-dev`, `libpq-dev` + (headers in `/usr/include/postgresql`, found via `pkg-config`), + `postgresql16`, `redis` 8, `lighttpd` 1.4.85 + `lighttpd-mod_webdav`, + `qpdf` 12, `poppler-utils`, `font-dejavu` (test font). +* kfcgi flags: `-u` = socket owner (lighttpd), `-U` = process user (signet), + `-p /` = no chroot (we exec qpdf and link libpq dynamically).
diff --git a/docs/REBUILD.md b/docs/REBUILD.md @@ -0,0 +1,381 @@ +# Rebuild plan: from the 2026-09-18 code to the 2026-09-19 model + +Written for whoever (or whichever model) does the code change. It assumes no +memory of the design session. Read, in this order: `CONTEXT.md` (vocabulary — +use those words in code, comments, UI and tests), `HANDOFF.md` §2 (decisions +D16–D29 and why), `docs/adr/0001-signers-sign-at-sign-off.md`, `AGENTS.md` +(hard constraints; they all still apply). Line numbers below refer to the +2026-09-18 code and will drift as you edit. + +## 0. What changes, in one paragraph + +A template names **parties** (ordered posts). The drafter binds the document to +one **organisation**, assigns one **signer** per party, reserves at most one +**signature zone** per party, and submits. The worker flattens the imprints +once into `proof.pdf` and copies it to `stamped.pdf`. Parties act strictly one +after another. A sign-off on a zone party carries a **placement** inside the +zone; the worker overlays that signer's **enrolled facsimile** onto +`stamped.pdf`. After the last party the worker overlays, appends the audit page +(the full event log) and writes `final.pdf`; only then does the status become +`RELEASED`. Signers without a facsimile enrol one in the browser before their +first sign-off. Nothing about the browser/worker text-fitting contract, +kcgi/kfcgi, qpdf, or the 60 MB budget changes. + +## 1. Scope guard — do not build these + +Parallel signing or `any`/`all`; more than one zone per party; per-page +initials; redaction; free-text imprints; `customer`; notifications of any kind; +PAdES; hand-picked DAM images on a document (all images come via PIM keys); +template versioning. If something seems to need one of these, stop and ask. + +## 2. Schema (`sql/schema.sql`) + +The DB is recreated on every dev run, so edit the schema in place; no +migration. + +```sql +CREATE TYPE doc_status AS ENUM ('DRAFT','PENDING','CORRECTION_REQUIRED', + 'DISAPPROVED','RELEASED'); + +-- series: + retired_at TIMESTAMPTZ +-- templates: + retired_at TIMESTAMPTZ; route_json becomes +-- {"parties":[{"name":"Partner","signer":"anil"}]} (signer = default, may be null) +-- documents: +-- - customer_id (D21) +-- + org_code VARCHAR(50) (D23; NOT NULL at submit, nullable in DRAFT) +-- - current_level → + current_party INTEGER NOT NULL DEFAULT 1 (1-based) +-- - rendered_revision → + render_seq INTEGER NOT NULL DEFAULT 0, +-- + rendered_seq INTEGER NOT NULL DEFAULT 0, +-- + render_kind VARCHAR(10) -- 'stamp'|'sign'|'release' +-- - approved_at → + released_at TIMESTAMPTZ +-- template_id stays nullable (unlink sets it NULL) +-- doc_decisions: level → party INTEGER; approver → signer; +-- + placement JSONB -- {"page":2,"coords":[x1,y1,x2,y2],"ref_w":1000,"ref_h":1414}, NULL for check-only +-- decision IN ('SIGNOFF','CORRECTION','DISAPPROVE') +-- doc_events.action values: CREATED, SUBMITTED, RESUBMITTED, STAMPED, +-- STAMP_FAILED, SIGNED, SIGN_FAILED, CORRECTION_REQUIRED, DISAPPROVED, +-- RELEASED, RELEASE_FAILED, RETRY, UNLINKED, ENROLLED +-- pim_attributes: + attr_type VARCHAR(5) NOT NULL DEFAULT 'text' CHECK (attr_type IN ('text','image')) +-- image value = DAM-relative path validated by is_safe_relpath +-- NEW facsimiles (username VARCHAR(100) PRIMARY KEY, enrolled_at TIMESTAMPTZ, +-- enrolled_by VARCHAR(100) NOT NULL, width INTEGER, height INTEGER) +-- metadata only; the PNG lives in sig_dir. width/height (pixels) are set by +-- the worker at enrol so the client can auto-fit a placement without ever +-- seeing the image. +``` + +`render_seq`/`rendered_seq` replace `revision`/`rendered_revision` as the +"worker is busy" gate (D3's pattern, generalised): the API increments +`render_seq` and sets `render_kind` whenever it enqueues a job (submit, +sign-off, release, retry); the worker sets `rendered_seq = seq` on success. +`revision` still counts submits and scopes decisions. + +Redis mirror (pim-api resync and writes): `HSET <org>:metadata <key> <value>` +for text, `HSET <org>:images <key> <path>` for images. Add `SADD pim:orgs <org>` +so the API can list organisations without touching PostgreSQL. + +## 3. Configuration (`etc/signet.conf.example`, `src/conf.c` users) + +* Roles: `role.drafter`, `role.signer`, `role.admin`, `role.pim_admin` + (rename from `maker`/`approver`; group names stay config-only). +* `sig_inbox = /var/lib/signet/sig-inbox` — directory owned `signetd:signet`, + mode `1730`: the API user can create files but not list the directory; + `signetd` moves files out. Add it to `make install` and `test/dev-up.sh`. +* Dev groups in `test/dev-up.sh` / `lighttpd-dev.conf`: `clerks` → drafter, + `management` → signer, `signet-admins` → admin + pim_admin. Keep the seeded + facsimiles for `ceo` and `manager` **and** seed matching `facsimiles` rows. + +## 4. Layout and route JSON (client ⇄ API ⇄ worker) + +```json +{"reference_width":1000,"reference_height":1414,"imprints":[ + {"page":1,"type":"pim_text","ref":"gstin","prefix":"GSTIN: ","coords":[120,150,520,180],"font":"fonts/X.ttf","align":"left"}, + {"page":1,"type":"serial","coords":[120,200,620,228]}, + {"page":1,"type":"date","coords":[700,150,900,178],"align":"right"}, + {"page":2,"type":"pim_image","ref":"seal","shape":"circle","coords":[300,1100,90]}, + {"page":2,"type":"signature_zone","party":"Partner","coords":[600,1050,850,1150],"min_w":120,"min_h":40}]} +``` + +```json +{"parties":[{"name":"Manager","signer":"manager"},{"name":"Partner","signer":"ceo"}]} +``` + +* Imprint types: `pim_text`, `pim_image`, `serial`, `date`, `signature_zone`. + `dam_image` and `signature` are gone. `ref` is a bare key; the organisation + comes from `documents.org_code`. Shapes: `rect`, `circle` (`poly` gone). +* `min_w`/`min_h` are in the imprint's natural pixels (same frame as `coords`). +* Party names: `is_safe_name`, unique within a route, 1–20 parties. + +## 5. API (`src/signet-api.c`) + +Endpoint list at the top of the file becomes: + +``` +GET /me → {user, roles:{drafter,signer,admin,pim_admin}, enrolled:bool} +GET /docs?scope=mine|pending|involved|all +POST /docs file=<pdf> | template_id=<uuid> +GET /docs/<id> +POST /docs/<id>/save json={title,org_code,series_code,layout,route} +POST /docs/<id>/submit +POST /docs/<id>/rerender (retry: re-enqueue render_kind) +POST /docs/<id>/decide decision=signoff|correction|disapprove, comment, placement=<json> +POST /docs/<id>/delete (drafts only) +POST /docs/<id>/unlink (admin) +GET /docs/<id>/file/<source|proof|stamped|final> +GET /templates POST /templates doc_id, name +POST /templates/<id>/retire (admin) POST /templates/<id>/delete (admin; 409 if any document links) +GET /series POST /series code, pattern (admin) POST /series/<code>/retire (admin) +GET /pim → {orgs:[…], attrs:{<org>:{text:{k:v},images:{k:path}}}} +GET /dam → {fonts:[…], images:[…]} (images for the PIM editor only) +POST /me/facsimile file=<png> (enrol self) POST /facsimiles user, file=<png> (admin) +``` + +Behaviour, by endpoint (only what changes): + +* **`/save`** ([:381](../src/signet-api.c:381)–[:398](../src/signet-api.c:398)): + validate `org_code` with `is_safe_name`; `check_layout` accepts the new + types, rejects `dam_image`/`signature`/`poly`, requires `party`, `min_w`, + `min_h` on zones and checks `min ≤ zone size`; `check_route` validates + parties (name, signer both `is_safe_name`); every zone's `party` must exist + in the route; at most one zone per party. Drop `customer_id`. +* **`/submit`** ([:420](../src/signet-api.c:420)–[:475](../src/signet-api.c:475)): + fail with a message when `title = ''` (D22), `org_code` is NULL, a + `pim_text` key is not in `HGET <org>:metadata`, a `pim_image` key is not in + `HGET <org>:images` or its file is missing under `dam_dir`, a party has no + signer, or the series is retired. Do **not** require signers to be enrolled + at submit (they enrol when they sign). Status → `PENDING`; `RESUBMITTED` + event instead of `SUBMITTED` when coming from `CORRECTION_REQUIRED`; + `current_party = 1`; `render_seq + 1`, `render_kind = 'stamp'`; enqueue + `{"doc_id","seq","kind":"stamp"}`. Serial, `doc_date` allocation unchanged + (invariant 8). +* **`/decide`** ([:580](../src/signet-api.c:580)–[:689](../src/signet-api.c:689)), + replace `CAN_DECIDE`: + `status = 'PENDING' AND rendered_seq = render_seq AND render_error IS NULL + AND route_json->'parties'->(current_party-1)->>'signer' = $user`. + Decisions are `signoff|correction|disapprove`; comment required unless + signoff. For signoff on a party **with a zone**: `placement` is required, + its page must equal the zone's page, its rectangle must lie inside the zone + and be ≥ `min_w × min_h` (compare in the zone's natural frame), and + `facsimiles.enrolled_at` for the signer must be non-NULL (else 409 + "enrol your signature first"). Insert the decision (with placement). Then: + * not the last party → `current_party + 1`; if the party had a zone: + `render_seq + 1`, `render_kind='sign'`, enqueue `kind:"sign"`; a + check-only sign-off enqueues nothing. + * last party → `render_seq + 1`, `render_kind='release'`, enqueue + `kind:"release"`; status stays `PENDING` until the worker finishes + (`RELEASED` is set by the worker). + * correction → `CORRECTION_REQUIRED`; disapprove → `DISAPPROVED`; both + unlink `stamped.pdf`, as today. + Delete `release()` ([:520](../src/signet-api.c:520)–[:575](../src/signet-api.c:575)) + from the API entirely: the worker owns it now (D18). +* **`/rerender`**: allowed for the drafter (kind `stamp`), the current/last + signer or admin (kinds `sign`/`release`): re-enqueue the stored + `render_kind` with `render_seq + 1`; log `RETRY`. +* **`/file/<kind>`** ([:713](../src/signet-api.c:713)): unchanged rule + (`admin || in_route || (is_drafter && kind != 'stamped')`), with `in_route` + now testing `route_json->'parties' @> [{"signer": $user}]`. `final` only + when `RELEASED`. +* **`/docs`** scope `pending` = documents whose current party's signer is me + and `rendered_seq = render_seq`; add a `waiting_on` column + (`current party name + signer`) for the dashboard instead of "Level". +* **`GET /docs/<id>`**: return `parties` as an array with each party's name, + signer, zone (if any) and its decision for this revision; `can_edit`, + `can_decide`, `needs_enrolment` (can_decide ∧ zone ∧ not enrolled), + `rendering` (`rendered_seq < render_seq`), and the full event log + (`doc_events` ordered by id) for the side panel. +* **Templates**: `POST /templates` copies `layout_json` and `route_json` + (party names and signers as defaults). `retire`/`delete` per D28; + `GET /templates` excludes retired unless admin and includes `linked` (count + of documents). `POST /docs/<id>/unlink` sets `template_id = NULL`, logs + `UNLINKED`. +* **Facsimiles**: `POST /me/facsimile` (any signer) and `POST /facsimiles` + (admin, `user` field) accept one PNG ≤ 1 MB, verify the PNG signature + bytes, write it to `<sig_inbox>/<user>.png.tmp` then rename to + `<sig_inbox>/<user>.png`, upsert `facsimiles (username, enrolled_by)` with + `enrolled_at = NULL`, and enqueue `{"kind":"enrol","user":…}`. The API + never opens `sig_dir` (invariant 5) and never reads the inbox back. + `GET /me.enrolled` = `enrolled_at IS NOT NULL`. + +## 6. Worker (`src/signetd.c`, `src/render.[ch]`) + +Job payload `{"doc_id","seq","kind"}` or `{"kind":"enrol","user"}`. A job is +stale (skip, return 0) unless `documents.render_seq = seq` — same idea as +today's revision check ([signetd.c:108](../src/signetd.c:108)). + +* `stamp`: `render_stamp()` on `source.pdf` → `proof.pdf`; then copy + `proof.pdf` → `stamped.pdf` (no facsimiles at this point). Drop + `with_signatures` and the `signature` imprint type from `render.c`; + `pim_text` resolves `HGET <org>:metadata`, `pim_image` resolves + `HGET <org>:images` then `dam_dir/<path>`. Set `rendered_seq`, log `STAMPED`. +* `sign`: read the latest `SIGNOFF` decision with a placement for this + revision; new `render_sign(ctx, stamped_in, out, png, placement)` draws one + PNG (from `<sig_dir>/<signer>.png`) at the placement rectangle on an empty + overlay and `qpdf --overlay`s it onto `stamped.pdf` (atomic `.tmp` + rename + as now). Fit the image inside the placement keeping proportions, centred. + Set `rendered_seq`, log `SIGNED`. +* `release`: do the `sign` step for the last decision if it has a placement, + then build the audit lines **in the worker** from `documents` (id, serial, + title, organisation, drafter) and `doc_events` (every row, all revisions, + `to_char(at) | actor | action | detail`, comments included), call + `render_release()`, compute the SHA-256 of the body as today, and in one + statement set `status='RELEASED', final_sha256, released_at, rendered_seq`. + Unlink `stamped.pdf`. Log `RELEASED`. On failure: `render_error`, + `RELEASE_FAILED`; the last signer or admin can retry. +* `enrol`: copy `<sig_inbox>/<user>.png` → `<sig_dir>/<user>.png` (owner + `signetd`, mode 0600, via a `.tmp` + rename), unlink the inbox file, set + `facsimiles.enrolled_at = now(), width, height` (from the PNG header), log + `ENROLLED` (`doc_id` NULL — make + `doc_events.doc_id` nullable, or keep a separate small log line; prefer the + nullable column). Validate with libpng before accepting (reuse the PNG + reader in `pdfw.c`); on a bad file delete it and leave `enrolled_at` NULL. +* Startup drain and `BRPOPLPUSH`/`LREM` discipline unchanged (invariant 7). + +`render_stamp` keeps clipping semantics for `circle` (HANDOFF §4.5 asks for +real clipping — do it now if cheap in `pdfw.c` with a clip path, otherwise +leave the bounding-box behaviour and say so). + +## 7. PIM (`pim/pim-api.c`, `pim/www/index.html`) + +* `attr_type` on write (`text` default, `image` requires a DAM-relative path + that passes `is_safe_relpath`); resync mirrors both hashes and `pim:orgs`. +* Editor: organisation selector (list + "new"), a type toggle per attribute, + and for images a picker fed by `GET /api/dam` images. +* Reads stay open to every authenticated user (D24). + +## 8. Client (`www/app.js`, `www/index.html`, `www/style.css`) + +Keep AGENTS.md invariants 1–3 exactly. Section by section +([app.js](../www/app.js) line refs from the 2026-09-18 file): + +* `TYPES` ([:13](../www/app.js:13)): `pim_text`, `pim_image`, `serial`, + `date`, `signature_zone`. Palette shows zones as "Signature zone"; the + props panel ([:402](../www/app.js:402)) offers a party dropdown (from the + route), `min_w`/`min_h` inputs, and for `pim_*` a key dropdown from + `app.pim.attrs[doc.org_code]`. Remove the `dam_image` picker. +* `imprintText` ([:166](../www/app.js:166)): resolve `pim_text` against the + document's organisation; when no organisation is chosen yet show the key in + brackets. +* Side panel ([:481](../www/app.js:481)–[:595](../www/app.js:595)): title + (required, submit button disabled while empty), organisation selector, + series, **parties editor** replacing `routeEditor` ([:437](../www/app.js:437)): + ordered rows of party name + signer username (prefilled from the template), + add/remove/reorder. Remove the customer field and the mode dropdown. +* Preview mode for the current signer: show earlier facsimiles (they are in + `stamped.pdf` already) and this party's zone as an outlined box. Decision + bar: **Sign off / Request correction / Disapprove**. For a zone party: + * `needs_enrolment` → open the enrolment dialog: a `<canvas>` signature pad + (pointer events, black stroke on transparent, export `toBlob('image/png')`) + or a PNG file input; `POST /me/facsimile`; poll `GET /me` until + `enrolled`, then continue. + * placement box inside the zone: starts at the auto fit — the largest + rectangle with the facsimile's aspect (`width/height` from `GET /me`) + centred in the zone — then draggable and resizable, constrained to the + zone and to `min_w × min_h`; the box is an `<area>` in the page map like + any other imprint (invariant 1). Submit `placement` with the sign-off. + If the auto fit cannot satisfy `min_w × min_h` (a tall facsimile in a + wide zone), show the box at the fit anyway and let the signer adjust; the + API's check is the authority. +* Dashboard ([:599](../www/app.js:599)): columns Document, Status, Drafter, + Waiting on, Created; scopes `mine | pending | involved | all` unchanged. + Show "rendering…" while `rendering`; show the retry button on + `render_error` to whoever may retry. +* History ([:471](../www/app.js:471)): render the event log from + `GET /docs/<id>` (HANDOFF §4.11). +* Polling ([:503](../www/app.js:503)): poll while `rendering`, not only after + submit (sign-offs and release render too). +* Series/templates admin views: retire buttons; template delete with the + linked count and the 409 message. + +## 9. Tests (`test/e2e.sh`) + +Rewrite the flow; keep the harness (`as`, `expect`). Cover, in this order: + +1. roles: `"drafter":true,"signer":false` for a clerk; series create needs + admin; series retire. +2. PIM: org `SKGA` with `gstin` (text) and `seal` (image → `seals/agency_seal.png`); + `GET /api/pim` lists orgs and both types. +3. draft from upload; save with title, org, parties `[Manager/manager, + Partner/ceo]`, imprints as in §4; save rejects: unknown zone party, two + zones for one party, `min` larger than the zone, `dam_image` type. +4. submit rejects: empty title; missing org; org without `gstin` (use a second + org); party without signer. Then submit ok → poll `rendering=false` → + serial `SKGA/SCNREPLY/<today>/01`; proof text has GSTIN, serial, date; + drafter gets 403 on `stamped`; other drafter gets 404. +5. decisions: `ceo` cannot decide yet (409); `manager` (check-only) signs off + with no placement → `current_party=2`, no render; `ceo` decide without + enrolment → 409 "enrol"; `POST /me/facsimile` with the fixture PNG → poll + `/me` enrolled; decide with placement outside the zone → 409; inside but + below `min` → 409; valid → poll → `pdfimages -list` on `stamped.pdf` + (fetched as `manager`, in route) shows one more image than the proof. + Since ceo is the last party this is also the release: poll → `RELEASED`, + `final_sha256` set, `final.pdf` text contains `SUBMITTED`, `SIGNED`, + `RELEASED` lines and the serial; `stamped.pdf` gone. +6. correction round on a second document: manager requests correction with a + comment → `CORRECTION_REQUIRED`; drafter saves and resubmits → + `RESUBMITTED` event, `revision=2`, `current_party=1`, same serial and + `doc_date`; manager and ceo sign again; final audit text contains the + correction comment (D26). +7. disapprove on a third document → `DISAPPROVED`, delete → 409, serial kept, + next document in the series gets `/03`. +8. self-service (D16): a user in both groups drafts a one-party document with + themselves as signer and releases it. +9. templates: create from a document; new document from template carries + parties and zones; retire hides it from the drafter; delete → 409 while + linked; admin unlinks the documents; delete → ok. +10. retry: worker failures are now hard to provoke from the API (every + reference is checked at submit and the DAM is read only then). Keep one + authorisation check — `rerender` is 403 for a user who is neither the + drafter, the current/last signer nor admin — and provoke a real failure + once by hand (e.g. `chmod 000` the seal inside the container between + save and submit) to see `render_error` + `RETRY` work end to end. + +Then the visual check from AGENTS.md (edit vs proof vs stamped, both pages), +plus: placement box and rendered facsimile coincide; earlier facsimile visible +to the next party; circle seal clipped if you implemented clipping. + +## 10. Documentation to update in the same change + +* `AGENTS.md` invariants: **4** → "…signer refs are party names that exist in + the route; placements are validated against the zone"; **5** → "Only + `signetd` reads `sig_dir`. `signet-api` touches a facsimile only transiently + in the enrolment request (writes it to `sig_inbox`, never reads it back) and + never opens `sig_dir`. Drafters never receive `stamped.pdf` unless they are + also a signer on that document"; **6** → "Imprints are flattened once, at + submit. Each sign-off overlays one facsimile; release is a worker job. + There is no `STAMPING` status; progress is `rendered_seq < render_seq`, + failure is `render_error`". Rename `maker`/`approver` wording throughout; + update the dev-groups note and the build/test commands if they change. +* `HANDOFF.md`: rewrite §3 (map, disk layout, request flow, JSON shapes) for + the new code; strike the superseded rows' *why* only if it no longer helps; + update §1 status and the e2e count; move §4 items 4, 5, 8, 11 to "done". +* `README.md`: user-facing flow (drafter → parties → release), enrolment, PIM + organisations. +* `CONTEXT.md`: only if a term changed meaning while building — say so + explicitly in the summary rather than silently editing. + +## 11. Suggested order of work + +Each step ends with a clean `-Wall -Wextra` build and a green (possibly +shorter) `e2e.sh`. + +1. Schema, config roles, `sig_inbox`, dev seeding; rename identifiers + (`maker_user` → `drafter_user`, statuses); API compiles with old logic + mostly intact; e2e reduced to what still holds. +2. `/save` + `/submit` validation for org, parties, zones, title; worker + `stamp` job with the new resolution; e2e steps 1–4. +3. `/decide` rewrite, worker `sign` and `release`, delete API `release()`; + e2e steps 5–8 minus enrolment (seed `enrolled_at` for `ceo`/`manager`). +4. Enrolment: inbox, `/me/facsimile`, worker `enrol`; e2e enrolment checks. +5. Templates/series lifecycle, unlink; PIM types and orgs; e2e step 9. +6. Client, all sections; visual check. +7. Docs (§10), full e2e, RSS measurement against the 60 MB budget. + +## 12. Acceptance + +* `test/e2e.sh` ends with "all passed" and covers every item in §9. +* A signer at party *n* can never fetch a document whose `current_party < n` + (404), and never sees a facsimile of party *> n* (there is none). +* Replacing a seal file on the DAM after submit does not change `stamped.pdf` + or `final.pdf` of a pending document. +* `grep -rn 'customer\|current_level\|PENDING_APPROVAL\|"any"\|maker' src www sql test etc` returns nothing. +* RSS of all processes ≤ 60 MB with two API workers.
diff --git a/docs/adr/0001-signers-sign-at-sign-off.md b/docs/adr/0001-signers-sign-at-sign-off.md @@ -0,0 +1,45 @@ +--- +status: accepted +date: 2026-09-19 +--- + +# Signers place their own facsimile at sign-off; routes are sequential parties + +The first build stamped every signature facsimile at submit time, so the +drafter had to name the exact user for each signature box and a level could be +"any of these approvers". Once the owner said a signature belongs to a *post* +(any partner may sign for "Partner"), that model could not tell the truth: the +page would carry one partner's facsimile while another partner actually signed. +We copied DocuSeal's shape instead. A template names **parties**; the drafter +assigns one **signer** per party at submit and reserves a **signature zone** +(rectangle plus minimum size) rather than placing a signature; parties act +strictly one after another; at sign-off the signer places their own facsimile +in the zone (automatically if already enrolled, otherwise by signing in the +browser, which enrols it); imprints are flattened once at submit, each +sign-off overlays one facsimile onto the previous stamped copy, and the worker +renders the release after the last one. + +## Considered options + +- **Keep stamp-at-submit and add `any`/`all` levels with holders** (the + 2026-09-18 code). Rejected: produces a document whose ink and audit page + disagree about who signed. +- **Levels of signatories, each with several holders.** Rejected in favour of + "the drafter picks the person": simpler, and identical to DocuSeal's + party → submitter assignment, at the cost that a signer who becomes + unavailable after submit needs a correction-and-resubmit. + +## Consequences + +- Release is asynchronous (the worker, sole reader of stored facsimiles, must + draw the last one); `APPROVED` reuses the `rendered_revision`/`render_error` + gap and "Retry" of D3. +- A party never sees a later party's facsimile, because it does not exist yet. +- The DAM (fonts, seals) is read only at submit, so a file replaced on the + network drive mid-route cannot change what a pending document shows; the + same protection the copied `source.pdf` already gives the base PDF. +- Signature enrolment is no longer a hand-copied file: the first signing + supplies the image, and it must reach the worker's store without the API + user being able to read it back later. +- `any`/`all`, `current_level`, multi-approver levels and username-referenced + signature boxes are removed from the model.
: asapien/signet