# ASM — remaining work

Everything the audit found that is still outstanding, ordered by what unblocks
the most. Each item says what "done" means, so it can be checked rather than
felt.

Infrastructure items (TLS, backups, `SITE_URL`, secrets) are in the README's
_Going to production_; they are deployment configuration, not code, and are not
repeated here.

---

## 1. Structured logging — `[x] DONE`

Failures currently go to `console.error` with a hand-written context tag. No
levels, no request correlation, no machine-readable output, and the tags are
inconsistent between call sites.

**Done when:** one `log` module with levels; every existing `console.error` in
`src/` routes through it; output is JSON in production and readable in
development; nothing logs a password, token, session id or raw email body.

`src/lib/log.ts`. Eleven call sites converted to stable event names
(`submission.store_failed`, not a sentence) so a drain can count and alert on
them. Keys matching `pass|secret|token|session|hash|salt|…` are redacted and
anything email-shaped is masked — including inside an error's own message, which
matters because a Prisma error carries the failing query _and its parameters_.
Stacks are kept in development and dropped in production.

The one remaining `console.error` is in `src/app/error.tsx`, a Client Component
that cannot import a `server-only` module. Correct as it stands.

## 2. Email delivery — `[x] DONE`

The largest functional gap. A contributor whose piece is approved or rejected is
never told. Contact messages queue in `/idara` and reach no inbox.

**Done when:** a transport module with an SMTP driver and a no-op driver for
development; the submission decision path sends the writer a bilingual
approval/rejection; a delivery failure is logged and **never** rolls back the
editorial decision that triggered it.

`src/lib/mail/`. Six templates, all bilingual with a plain-text part. Five
notifications now fire:

| when                      | to          | template                                |
| ------------------------- | ----------- | --------------------------------------- |
| a submission arrives      | the writer  | acknowledgement with tracking reference |
| a submission arrives      | the editors | new item in the queue                   |
| approved                  | the writer  | published, with a link to the piece     |
| rejected                  | the writer  | decision, with the editorial note       |
| changes requested         | the writer  | what is needed, quoting the reference   |
| a contact message arrives | the editors | who wrote, and the subject              |

`deliver()` **never throws**: an editor approving a piece is making an editorial
decision, and a bounced notification must not surface as a content failure. The
inverse risk — a contributor waiting on a verdict reached weeks ago because an
SMTP password expired — is covered by an `EmailDelivery` row per attempt, so
"was the writer told?" is a database question.

The driver is derived from whether `SMTP_HOST` is set, not configured
separately, so there is no second switch to disagree with the credentials beside
it. Blank means render, record as SKIPPED, send nothing — which is what CI gets,
and is why no test can mail a real person.

## 3. An administrator account — `[x] DONE`

`ADMIN` holds `user.manage`, and **no account holds `ADMIN`**. The permission is
currently unreachable by anyone, which makes item 4 unusable before it is built.

**Done when:** the seed can create an administrator from `SEED_ADMIN_*`, on the
same create-only terms as the other accounts; `tests/roles.test.mjs` covers it.

Done, as a SEPARATE account rather than by promoting the editor: the credential
used every day should not also be the one that can create users. `roles` now
asserts an administrator exists _and_ that `user.manage` is held by some active
account — a permission nobody can exercise is indistinguishable from a missing
feature until the day it is needed.

## 4. User management screen — `[x] DONE`

Creating, deactivating or re-roling an account means editing the database.

**Done when:** `/idara/users` lists accounts and allows create, role change and
deactivate; gated on `user.manage`; every change is audited; an administrator
cannot demote or deactivate their own last administrator account.

All of it, plus two things the work surfaced:

- **Accounts are deactivated, never deleted.** Every audit entry, review and
  upload points at a user; deleting one turns "who approved this?" into
  "someone, once" across the whole history.
- **Deactivation revokes live sessions immediately.** An account closed because
  someone left that keeps working until the cookie expires is not closed.

No password reset here, deliberately: an administrator who could set another
person's password could act under their name, and the audit log would show that
person doing it.

## Bug classes found and closed — `[x] DONE`

Building item 4 produced three bugs of my own. Each was fixed where it happened
**and** audited for other instances, because one occurrence of a class is rarely
the only one.

**An empty CSRF token.** All three account forms shipped `value=""`, so every
submission was silently rejected — and the lockout tests _passed_, because CSRF
was blocking the attempts rather than the rule under test. Audited every form in
`src/`: **25 forms, all carrying a real token, 0 other instances.**

**An assertion that passed vacuously.** `count() === 0` is true when a control is
absent _and_ when the row never rendered, so the suite reported "the control is
locked" about a row that was not on the page. Four such assertions existed; all
now go through `checkAbsent`, which treats a missing container as a FAILURE. A
negative control proves it: the naive form passes on a ghost row, the helper
does not.

**An ambiguous destructive selector.** `page.selectOption('select[name="role"]')`
matches every row's control as well as the form's; it hit the first and quietly
demoted a real editor account. Measured the actual match count for every
destructive selector in every suite — `/idara/users` was the only page with
ambiguity (3 role selects, 4 submit buttons), and the test now scopes to the
form, which resolves to exactly one. Cleanup also moved into `finally`, because
the failing run left accounts altered and broke the next one.

## 5. Settings screen — `[x] DONE`

Contact details, social links and the editor's name live in `SiteSetting` and are
changed by SQL. `setSetting` is written and has no caller.

**Done when:** `/idara/settings` edits every key in `DEFAULT_SETTINGS`, validated
through zod, audited, and the public pages pick the change up without a deploy.

All nine keys, validated per key rather than as a bag of strings — a contact
address that is not an email and a social link that is not a URL fail
differently, and saying which field is wrong is the point of validating.

Gated on `taxonomy.manage`, not `user.manage`: contact details are editorial
configuration, and the senior editor should not need an administrator to fix a
phone number. The assistant editor holds neither.

Three decisions the tests pin down:

- **A value equal to its default is deleted, not stored.** An explicit row
  agreeing with the fallback freezes that value forever — change the default in
  a later release and every install that once opened this form keeps the old one.
- **The editor profile is chosen from a list, never typed.** A mistyped slug
  resolves to no editor: the portrait falls back to the placeholder and nothing
  says why.
- **The audit entry records which keys changed, not their values.** A settings
  row can hold a contact address, and the audit log is read by more people than
  the settings form is.

`javascript:` is rejected — `new URL()` accepts it happily and these values are
rendered straight into an `href`.

## 6. Search index for scale — PostgreSQL implementation retired

The former PostgreSQL deployment used `pg_trgm` GIN indexes. Those indexes and
their 50,000-row benchmark are historical only; the cPanel/MySQL schema uses
portable substring matching and currently scans `SearchDocument`. Revisit a
MySQL-compatible search index or external search service if the archive grows
enough for those scans to become a measured bottleneck.

## 7. Deployment preflight — `[x] DONE`

`src/lib/env.ts` validates at boot, which is the right place, but a bad value is
found when the process starts rather than before it is deployed.

**Done when:** `npm run preflight` checks the production-critical configuration
and exits non-zero with a specific message for each problem.

`scripts/preflight.mts`. It does not import `src/lib/env.ts` on purpose — that
module throws on the first fault it finds, which would report one problem per
run. Every check here is independent, so a single run lists all of them.

It goes further than reading variables: it connects to the database, counts
applied migrations, checks an active administrator exists, **writes a probe file**
to prove `STORAGE_DIR` is genuinely writable, refuses a storage path inside
`public/`, and opens a socket to the SMTP host. FAIL means it will break or
leak; WARN means it will work and you probably do not want it — only FAIL sets a
non-zero exit, so it can gate a pipeline without blocking on judgement calls.

Verified in both directions: it fails on the current `localhost` SITE_URL and on
a storage path under `public/`, and passes with a real origin.

---

## Decided against, for now

**Password reset by email.** A self-service reset is an account-takeover surface
— it turns "control the mailbox" into "control the institution". With two or
three accounts the cheaper and safer answer is an administrator, which item 4
provides. Revisit when there are enough contributors that a person cannot do it.

**CSP nonce.** Would force every page to render dynamically and lose the ISR the
site is built on. See the README's _Known trade-offs_.

**English translations of the policy clauses.** Privacy, terms and editorial
standards are commitments the institution makes. An unreviewed machine rendering
that reads as authoritative is worse than none.
