# Signet

Party-based sequential document signing for a 1 vCPU / 1 GB Alpine box. Native C
(kcgi + libpq + hiredis + libpng), lighttpd, PostgreSQL, Redis, `qpdf`, `pdfinfo`.
Optional detached timestamps use libcurl + OpenSSL libcrypto. No containers or
language runtimes in production.

**Development status:** sequential signing, worker-owned release and render-job
recovery have fresh isolated-development tests; see
`.scratch/roadmap/ticket-11.md`. Fail-closed identity is covered by
`.scratch/roadmap/ticket-13.md`; frozen PIM/DAM revision inputs and immutable
proof caching are verified in `.scratch/roadmap/ticket-12.md`.
Full production acceptance is incomplete; in particular, aggregate resource
budget20 and real browser/signing acceptance remain open. A controlled native
beta is installed as described below, not certified for all admitted workloads.

The client is marked **BETA** and no longer asks users to supply a username or
groups. Normal login must be supplied by the deployment's trusted authentication
service; the inline sign-in state does not install one. The owner has requested a
controlled beta while unfinished sections stay tracked, on **maa-1** through
Minci's commit → CI run → deploy workflow, with all Signet work merged to main.
The beta is deployed at **https://sign.saikrupagas.com/** behind the existing SSO.
Native Minci pipeline281 deployed commit `df5fafa`; OpenRC services, isolated AOF
Redis/database, configured server groups and initial recovery checks are in place.
Real human browser login/signing and full native acceptance are not yet verified.
DAM writes and optional TSA are disabled. See
[the beta rollout queue](.scratch/beta-release/README.md).

```
browser (vanilla JS, pdf.js)           lighttpd ── /dam/  WebDAV (seals, fonts)
   <img usemap> + <map>/<area>    ──►     │
                                          ├─ /api      kfcgi ► signet-api ──► PostgreSQL
                                          └─ /pim-api  kfcgi ► pim-api          ▲
                                                           │ LPUSH              │
                                                         Redis ── BRPOPLPUSH ► signetd ► pdfinfo, qpdf
                                                                                 └ reads /var/lib/signatures (only it can)
```

## Workflow

| Status | Meaning | Mode |
| :-- | :-- | :-- |
| `DRAFT` | Drafter places imprints, picks series and parties | edit |
| `PENDING` | Submitted. Imprints flattened; waiting for first party to sign | preview |
| `CORRECTION_REQUIRED` | A party sent it back with a comment; drafter edits again. All sign-offs voided | edit |
| `DISAPPROVED` | Terminal; sent back by a signing party | preview |
| `RELEASED` | Last party signed. Worker rendered final copy + audit page with full event history → `final.pdf`, SHA-256 stored | preview |

Parties sign strictly one after another. A party with a signature zone overlays
the signer's enrolled facsimile (drawn or uploaded in the browser) onto the
stamped copy; a check-only party signs off without adding an image.
The worker renders `final.pdf` only after the last sign-off. At submit, the
drafter assigns one signer per party from the organisation. Signature imprints
create zones where signers place their facsimiles.

**Signature collections:** Signers can draw/upload labelled PNG facsimiles in
**My signatures**, or enrol their first one when signing. The first ready image
becomes the default; adding another never replaces it. Choose the signature in
the document's **Signature to use** picker, or use **Use as default** for future
sign-offs. Each decision records its chosen ID, so later default changes cannot
alter queued work. Uploads are at most 1 MiB; up to 32 ready/pending variants per
user. Invalid PNGs are reported without displacing an existing default. If an
activation is pending after a queue interruption, **Retry activation** requeues
the same immutable reference (`POST /api/me/facsimile/retry`); it does not upload
or replace an image.

Originals live at `/var/lib/signatures/<UUID>.png` (0600, worker only). Existing
`<username>.png` files and enrolled metadata remain supported by migration;
never overwrite them once enrolled. An admin can add a labelled variant for a
user with `POST /api/facsimiles` (`user`, `label`, `file`). No API serves original
signature images. Enrolled variants cannot be replaced/deleted; add a new one.

Organisation seals, stamps and logos remain separate PIM image attributes
(`seal`, `accounts_stamp`, `logo`, etc.) referencing DAM-relative files. Nested
paths such as `organisations/ACME/seals/company.png` are supported; folder names
organise files; they do not provide access control. Signature originals must not go in DAM.

Serial numbers come from a **series** (`SKGA/SCNREPLY/{date:%Y%m%d}/{seq:02}`,
counter restarts daily). The number is allocated on first submit and never
changes across corrections. `serial` and `date` imprints print it anywhere on
the page; a **template** (base PDF + layout + route + series) makes that
repeatable.

## Optional external timestamps

Released documents can obtain detached, validated RFC3161 evidence without
changing the PDF or blocking release: four total attempts within one hour.
**Signed at** remains Signet's server-recorded sign-off time; **Externally
timestamped at** is the separately verified TSA time. A later timestamp proves
existence by its issuance, not the earlier sign-off, identity or consent.
This is **not PAdES B-T** or a certificate-based PDF signature. It is disabled
without a configured HTTPS endpoint and explicit TSA trust; scheduling uses the
existing system cron facility, not another resident Signet daemon.
See [setup, evidence download, limits and checks](docs/timestamps.md).

## Imprints

`<area shape coords data-type data-ref …>` in the page's `<map>` is the state.
`data-coords` keeps natural-pixel coordinates; `coords` is rescaled on resize.

| type | ref / property | rendered from |
| :-- | :-- | :-- |
| `pim_text` | PIM attribute key | `HGET <org>:metadata <key>` in Redis, never from the client |
| `pim_image` | PIM image key | `HGET <org>:images <key>` → DAM path (PNG with alpha, JPEG) |
| `signature_zone` | party name | signer places an enrolled facsimile at sign-off |
| `date` | – | document date, `format` = strftime |
| `serial` | – | allocated serial number |

Text options: `prefix`, `font` (a `.ttf` in the DAM; the browser loads the
same file via `@font-face`), `align`. Text is sized to 70 % of the box height
and shrunk to fit the width, identically in `www/app.js` and `src/render.c`.
Shapes: `rect` (rectangle) and `circle` (clipped using 4-Bezier PDF path
approximation for smooth round seals).

Pixels → points: `pdf_x = x / ref_w * page_w_pt` (same for y, width, height),
page sizes from `pdfinfo -f 1 -l N`. The overlay PDF is written by
`src/pdfw.c` (TrueType embedding, PNG alpha as SMask, circular clipping) and
merged with `qpdf --overlay`.

## Install (Alpine)

The following is an unverified deployment outline, not a production-ready
runbook. Resolve the gaps in `HANDOFF.md` §4 first. Identity now fails closed,
but the trusted proxy boundary, DAM writer policy and native resource safety
still require deployment verification.

```sh
apk add build-base pkgconf kcgi-dev hiredis-dev libpq-dev libpng-dev zlib-dev curl-dev openssl-dev \
        lighttpd lighttpd-mod_webdav postgresql16 redis qpdf poppler-utils
make && make install

addgroup -S signet
adduser -S -G signet -H signet        # API
adduser -S -G signet -H signetd       # worker
install -d -o signet  -g signet -m 2770 /var/lib/signet
install -d -o signetd -m 0700 /var/lib/signatures      # <UUID>.png (legacy <username>.png), 0600

createuser signet; createuser signetd; createdb -O signet signet
psql -U signet -d signet -f sql/schema.sql
psql -U signet -d signet -c "GRANT SELECT, UPDATE ON documents TO signetd;
  GRANT SELECT, INSERT ON doc_events TO signetd; GRANT USAGE ON SEQUENCE doc_events_id_seq TO signetd;
  GRANT SELECT ON doc_decisions TO signetd; GRANT SELECT, UPDATE ON facsimiles TO signetd;
  GRANT SELECT, INSERT, UPDATE ON document_timestamps TO signetd;"

cp etc/init.d/* /etc/init.d/ && rc-update add signet-api && rc-update add signet-pim && rc-update add signetd
cp etc/lighttpd-signet.conf /etc/lighttpd/   # and include it
$EDITOR /etc/signet/signet.conf               # groups → roles, paths, fonts
```

For an existing database, read `sql/migrations/README.md` before upgrading;
legacy pending documents must not be backfilled from current PIM/DAM data.

Enable Redis AOF (`appendonly yes`). The deployment's trusted forward-auth proxy must overwrite
`Remote-User` / `Remote-Groups` on every request. The deployment administrator
chooses and manages the authentication provider; Signet only consumes forwarded
identity and maps configured groups to roles. Both forwarded groups and role
configuration use comma-separated complete names: `Counter Staff, Manager` is
two groups, not three whitespace-separated words. Matching is case-sensitive.

On non-loopback deployments, the account menu reuses the same deployment-owned
ES module as Movements, served same-origin at `/js/auth-ui.js` (on maa-1,
lighttpd aliases `/js/` to `/etc/lighttpd/js/`). It must register
`<sso-user-button>` and own the provider logout URL; do not copy it into Signet.
Open the username menu and choose **Sign Out** to use the provider's logout page.
This ends the shared SSO session, not just access to Signet. If the module cannot
load, Signet retains the username/roles and reports unavailable account controls.
Loopback development keeps its test-identity clearing link without loading SSO UI.

## Develop / test

```sh
podman build -t signet-dev .
podman run -d --init --name signet -p 127.0.0.1:8080:8080 signet-dev
podman exec signet /src/test/e2e.sh     # API + worker end to end
podman exec signet /src/test/e2e.sh render-contract  # failure/replay/queue regression
open http://localhost:8080              # isolated dev only; explicit identity required
```

Use `--init` for this multi-process dev stack to reap orphan processes. The
startup shell keeps worker and lighttpd as siblings: lighttpd must not inherit
the long-lived worker as its child and wait for it during graceful restart. Existing
containers retain their data on restart; demo seeds/config do not overwrite
existing files. Removing a container still requires a backup/persistence plan.

Development has no implicit admin identity or authentication-server dependency.
For browser testing, set an explicit identity in the browser console and reload:

```js
localStorage.signetDevIdentity = JSON.stringify({ user: 'asha', groups: 'clerks' });
location.reload();
```

`podman exec signet sh /src/test/e2e.sh identity-contract` checks both APIs and
configurable identities/roles. It restarts test API processes and must run only
in the isolated dev container. Production must overwrite forwarded headers and
prevent direct backend access; the browser dev selector is not authentication.

### Failure logs

API-emitted 4xx/5xx write a failure summary to stderr and syslog LOCAL0: method,
normalized route, validated actor, status, and `site=function:line`. UUIDs and
unknown path components are redacted; bodies, tokens, raw URLs and backend error
text are omitted. Database diagnostics retain SQLSTATE. Resolve a site against
the matching source/build. Successful requests are quiet.

Development uses foreground kfcgi supervisors (`-d`), so `podman logs signet`
actually captures API stderr, including without `/dev/log`. On an explicitly
disposable stack, run the real capture regression where the Podman CLI works:

```sh
SIGNET_LOGGING_TEST_DISPOSABLE=yes sh test/logging-dev.sh disposable-container
```

The test temporarily installs a syslog receiver and isolated failure fixtures;
it refuses to replace an existing `/dev/log`. The full E2E includes its native
API/syslog checks. See `.scratch/api-logging.md` for scope and evidence.
Production must configure and verify persistent LOCAL0.warning-and-above capture,
permissions and rotation. Web-server/proxy rejections before API dispatch and
PostgreSQL's own logs are separate; native/OpenRC acceptance remains open.

### Browser regressions

Optional browser regressions use externally installed Playwright Core and Chrome
on the development machine only (no production or runtime JS dependency):

```sh
PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs node test/signing-flow.mjs
PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs node test/render-progress.mjs
PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs node test/upload-browser.mjs
node test/upload-client.mjs  # standalone browser-helper contract; development only
```

Set `CHROME_PATH` for a non-default Chrome location and `SIGNET_URL` for a server
other than localhost:8080. Tests create synthetic documents and use explicit dev
identity headers; never run them against production.

## Limits (v1)

* Fonts must be TrueType with `glyf` outlines. No complex-script shaping
  (Tamil, Devanagari …); Latin, digits and symbols such as ₹ work when the
  font has them.
* **Signatures are facsimiles** (enrolled or placed by admin); the approval
  evidence is the audit page plus `doc_events`. No cryptographic PDF signature
  (PAdES).
* **At most one signature zone per party.** Multiple signings per party
  (countersigning, witness) are not supported. Placement stays within the zone,
  preserves the facsimile's aspect ratio and must meet the fitted image's minimum
  dimensions. Decision comments are limited to 4096 UTF-8 bytes; all accepted
  comments/events appear in the paginated audit without history truncation.
* **Imprints are organisation-bound and frozen at submit.** The server resolves
  referenced PIM text/image attributes and copies image/font bytes (including
  the audit font). Worker retries and sign-offs use only that revision's content;
  correction/resubmit creates a new snapshot while retaining serial/date.
  Frozen assets total at most16MiB per revision; imprint text including prefix
  is limited to1023 UTF-8 bytes. Missing/damaged inputs fail closed; restore exact
  verified bytes/permissions rather than replacing them from the live DAM.
* **PDF files still accept up to32MiB.** The browser uses authenticated256KiB
  application-level chunks; incomplete drafts cannot be read, edited or submitted.
  Exact retries never replace acknowledged bytes. Before kcgi buffering, API/PIM
  bodies are capped at16KiB, except multipart/form-data at1100KiB. Large JSON/PNG
  fields must use multipart (for curl: `--form 'json=<layout.json'`); large PDF
  clients must use the chunk protocol in `.scratch/bounded-uploads.md`. This
  prevents dense URL-encoded/plain-text forms amplifying per-field allocations;
  tests/evidence are in `.scratch/bounded-parsers.md`. Small multipart uploads and
  template creation remain supported; DAM/WebDAV's transport limit is unchanged.
  Install migration003, API/browser and lighttpd changes together; see the upgrade
  precautions in `sql/migrations/README.md`. This source change is not installed
  on the preserved development preview.
* **Layout metadata is bounded.** Document-save JSON accepts at most1MiB;
  submit also rejects stored layout/route exceeding1MiB before snapshot cloning.
  Multipart transport overhead counts toward the separate HTTP cap. These are
  not whole-runtime memory bounds.
* **External commands have a deadline.** pdfinfo/qpdf must finish within30s;
  timeout kills the command group. Worker jobs record a retryable render failure;
  callers fail closed when a required command does not complete successfully.
  PDF creation checks its header; it does not run pdfinfo on the uploaded body.
  Linux also kills the direct command child when its API/worker caller dies.
  This is not a memory/CPU quota or whole-service crash-containment guarantee.
  `sh test/command-contract.sh` runs the standalone development regression.
* **Resource/deployment acceptance remains open.** The two-max-file upload
  counterexample is locally repaired, not a native peak-load certificate. Parser
  amplification, rendering children, simultaneous image/font decoding and shared
  database impact still require containment/measurement before production or
  coexistence with other mission-critical services.
* Rotated source pages are handled by swapping the page size; unusual
  CropBox offsets are left to qpdf's overlay fitting.
