Skip to content

refactor(user-messages): let jsonSchema own the JSON columns' shape and types - #660

Merged
Ardnived merged 1 commit into
feat/async-user-messagesfrom
claude/user-messages-review-fixes
Aug 31, 2026
Merged

Ardnived merged 1 commit into
feat/async-user-messagesfrom
claude/user-messages-review-fixes

Conversation

@sydevs-bot

Copy link
Copy Markdown
Contributor

Your review on #653, implemented. Stacked onto feat/async-user-messages rather than pushed to it, because I can only push to claude/*. Merge this into your branch and it disappears into #653.

Local gate green: lint, typecheck, typecheck:tests, 1497 unit tests, and generate:types is idempotent.

What changed

Your comment Done
jsonSchema for context ✅ open schema — validateContext deleted
jsonSchema for screeningResult ✅ closed schema, verdict enum from MESSAGE_VERDICTS
types.ts shouldn't exist ✅ deleted; 3 consumers read the generated type
minLength instead of a validator ✅ plus MESSAGE_MIN and MESSAGE_MAX inline, as you asked
verdict function → typed hash ✅ MESSAGE_VERDICT_NOTES
Banner['type'] instead of Severity ✅ Severity + BANNER_TYPE both gone
notesOf unnecessary ✅ now value?.notes ?? []
bodyHash.ts — fold or generalise ✅ folded into prepareUserMessage
Drop the 4000-char cap ✅ gone

Not done, with reasons on their threads: the two "override Input" comments (no such slot exists — Field, Cell, Filter, Label, Error, Diff, Description, beforeInput, afterInput, and 20 components use the same wrapper), the Tailwind one (not a dependency of this repo), and emailSchema (module-scope so it's built once).

Three things to look at

1. I could not run the integration suite, and I changed one of its tests. No local Postgres. user-message-screening.int.spec.ts had a case that wrote verdict: 'something-we-never-wrote' to prove the read-side guard re-screens. The schema now refuses that write, so its setup is unreachable — I rewrote it to assert the refusal, which is the stronger property. This is the one change most likely to turn CI red, and the assertion (.rejects.toThrow()) is reasoned from the documented behaviour rather than observed. The read-side guard isScreeningResult is deliberately kept, for rows written before the schema or by SQL.

2. additionalProperties: true on context, not { type: 'string' } — a TypeScript constraint, not a preference. I tried the bounded version I proposed on the thread. It generates [k: string]: string, and TypeScript then demands every named property be assignable to it; they're all optional, so string | undefined isn't, and payload-types.ts stops compiling. So the per-unknown-key size bound is gone: maxProperties: 20 caps the key count and the five named keys carry maxLength, but an unknown key's value is unbounded. By your own criterion — "if it lets us simplify" — the bound didn't, so it went. Recorded in the docblock rather than hidden.

3. No migration. jsonSchema, minLength and maxLength are validation and codegen only; the columns are unchanged.

How the generated types came out, and the one thing I nearly lost

UserMessage['screeningResult'] is now the full shape — verdict as the six-member union, notes, diagnostic, screenedAt — and UserMessage['context'] is the five named optional keys plus [k: string]: unknown, so forward-compatibility survives in the type as well as at runtime.

Consumers reach both by indexed access (NonNullable<UserMessage['context']>) rather than by the generated interface's URI-derived name, matching src/lib/clients/embedMetadata.ts.

⚠ My first attempt silently dropped the per-key documentation. I wrote the key docs as /** … */ TS comments inside the schema literal, which are not JSON Schema and vanish. They're now description fields, which Payload renders into the generated JSDoc — so path, hostUrl, locale, error and userAgent still explain themselves at the three call sites that read them. This was the exact risk I flagged on the types.ts thread as needing checking after generate:types; it needed checking, and it was wrong the first time.

The stale Cloudflare Workers warnings in translationsField.ts and subtitles.ts are not touched here — they're unrelated files and belong in #659.

🤖 Written by the sydevs autonomous loop — see what this is


🤖 Generated with Claude Code

https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC


Generated by Claude Code

…nd types

Applies the review on #653. The JSON fields now carry a `jsonSchema`, which
Payload compiles to a write-time validator AND generates the field's type from —
so `types.ts`'s `UserMessageContext` and `screening.ts`'s
`UserMessageScreeningResult` are gone rather than kept in agreement by eye.

- `context`: open schema (unknown keys still pass, per the intake contract);
  `validateContext` and its serialized-length cap deleted.
- `screeningResult`: closed schema, `verdict` enum derived from
  MESSAGE_VERDICTS so the runtime list and stored contract cannot drift.
- `message`: built-in `minLength`/`maxLength` replace the composed validator;
  both bounds inline.
- `messageVerdictNote` becomes the `MESSAGE_VERDICT_NOTES` record.
- `UserMessageStatus`: `Severity`/`BANNER_TYPE` collapse into `Banner`'s own
  type; the defensive `notesOf` filter goes, the schema having closed the hole.
- `normalizedBodyHash` folds into its one consumer, `prepareUserMessage`.

Per-key documentation survives as JSON Schema `description`, which Payload
renders into the generated type's JSDoc.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC
@railway-app

railway-app Bot commented Aug 29, 2026

Copy link
Copy Markdown

This PR was not deployed automatically as @sydevs-bot does not have access to the Railway project.

In order to get automatic PR deploys, please add @sydevs-bot to your workspace on Railway.

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

⚠ Green on this PR will mean less than usual — read before merging. Railway's bot above says it: @sydevs-bot has no access to the Railway project, so this PR gets no preview deployment. Two consequences that aren't obvious from that message:

  • Nothing builds the app. AGENTS.md is explicit that GitHub Actions does not build — the Next.js build happens on Railway's preview deploy. No preview, no build. A Module not found of the kind feat(access): add embed metadata and canonical ownership to Clients #633 hit would not be caught here.
  • The smoke lane skips, and still reports green. get-railway-preview-url.ts exits cleanly with no preview and both smoke steps are skipped — .claude/rules/tests.md records exactly this ("a skipped smoke lane is not a passing one"; CI emits a ::warning).

So the Lint, Test & Smoke check here covers lint + typecheck + unit + integration, and not the build or the smoke specs.

Why I think that's acceptable rather than blocking: merging this into feat/async-user-messages puts the code on a branch Railway does deploy (it is building #653 right now), so the build and smoke run before any of it reaches main — one step later than usual, not skipped. The residual risk is a build error surfacing on #653 instead of here.

The one client component I touched is UserMessageStatus.tsx, and the change reduces its bundle surface rather than widening it: the @/collections/UserMessages/screening value import is gone, replaced by a types-only @/payload-types import that compiles away. tests/unit/client-bundle-safety.spec.ts ran and passed.

Granting @sydevs-bot Railway workspace access would close this for every future PR from that account — your call whether it's worth it.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@Ardnived Ardnived self-assigned this Aug 30, 2026
@Ardnived
Ardnived merged commit bbe6a8b into feat/async-user-messages Aug 31, 2026
1 check passed
Ardnived added a commit that referenced this pull request Aug 31, 2026
* refactor(emails): rename the contact-admin send path to user messages

The intake is becoming a `user-messages` collection screened by a job, so
the email path is named for what it carries rather than for the endpoint
that used to own it:

- `sendContactAdmin` -> `sendUserMessage`
- `ContactAdminEmail` -> `UserMessageEmail` (plus `buildContactDetails`
  -> `buildUserMessageDetails` and the two exported types)
- `ContactAdminContext` -> `UserMessageContext`, relocated out of
  `endpoints/responseTypes.ts` into the collection that will store it

Also corrects the template footer, which promised "nothing about this
message is stored; this email is the only record". That was true under
#602 and is about to be false — a copy is kept for screening and triage,
then purged. What the sender is told about their own data is not
bookkeeping trivia, so it changes with the behaviour.

`CONTACT_EMAIL` is untouched: it is the public support address, not part
of this intake.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(user-messages): async intake with deep spam screening

Replaces the synchronous send inside `POST /api/contact-admin` with a
persisted collection plus a screening job, applying the shape
`ScreenEventSubmissions` established to a second public intake.

Intake moves onto the collection seam — API clients create through the
built-in `POST /api/user-messages` — which is what earns it the usage
plugin's origin enforcement and the write-guard's anti-spam policy
instead of hand-rolling both.

Screening runs what the request path could not afford: an MX lookup
(fail-open), a disposable-list re-check, how many messages this sender
sent in the last 24h, and whether this exact body arrived before. Clean
messages are emailed and marked `delivered`; the rest are kept as `spam`
for triage.

The failure story survives async delivery. A send failure marks the row
`failed` *before* rethrowing — the job runner gives each task an isolated
transactionID, so that write commits and the row is visible immediately,
while the throw still earns a retry that re-attempts the send.

Access is deliberately tighter than event-submissions: `user-messages` is
in RESTRICTED_COLLECTIONS and granted by NO manager role, so reading one
takes the admin bypass. `sahaj-atlas-client` holds create only.

Two things are duplicated on purpose, both noted in the code: this job
owns its copy of `hasMxRecords` (the two intakes stay independent, and
the verdict *wording* was never shareable), and `screening.ts` writes its
own notes rather than reusing the event-submission ones.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(user-messages): nightly retention sweep

Persisting messages was accepted on the understanding that they do not
accumulate, so the retention policy ships with the intake rather than
being deferred.

Delivered messages are deleted after 7 days — short enough to nearly keep
#602's "nothing is stored" promise, long enough that the two 24-hour
screening windows still have history to count against. That lower bound
is the load-bearing part: shorten it past the window and the
repeat-sender and duplicate-body checks would silently pass everything.

Spam is kept 90 days, because a sender's history is what makes a pattern
visible, and `failed` is never swept — it is the one state where deleting
the row destroys the only record that a message went undelivered.

Runs at 04:00 UTC on the existing `nightly` queue, after the 02:00/03:00
sweeps. Note that `monthly` has no autoRun entry, so a task scheduled
there would never fire.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(api)!: replace POST /api/contact-admin with the user-messages intake

BREAKING CHANGE: `POST /api/contact-admin` is gone. Clients create through
`POST /api/user-messages` instead. Three things move on the wire:

- the Turnstile token goes in the `x-turnstile-token` HEADER, not the body
  (the write-guard reads it there — it is transport metadata, not document
  data);
- the response is Payload's `{ doc, message }` at 201, not `{ ok: true }`;
- the machine code moves from `errors[].code` to `errors[].data.code`,
  which is where Payload's `formatErrors` puts an APIError's `data`.

Safe to cut over in one step: the Atlas widget is still pre-release and no
third-party host embeds it yet. SahajAtlasWeb needs the matching change.

Deletes with it: the `ContactAdmin*` types in `endpoints/responseTypes.ts`,
the hand-authored OpenAPI path + schemas, and `antiSpamErrorResponse` —
whose only production consumer was that handler. `parseBody`, `checkNoUrls`
and `verifyTurnstileOrFail` all have other consumers and stay.

`atlas/seo` is now the ONLY root endpoint, so every doc that used
contact-admin as the canonical example is re-pointed. `.claude/rules/
endpoints.md` keeps the story rather than erasing it: "stored nowhere and
owned by nothing" was true only because the endpoint chose not to store
anything, and that is the trap — ask whether a resource is genuinely
ownerless or merely unpersisted before reaching for the root.

`responseTypes.ts` stays put despite now serving one endpoint; client repos
sync it by a stable raw GitHub URL.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(lib): move antiSpamGuard out of lib/endpoints

Its consumers are now the write-guard plugin and the two screening jobs —
not a single endpoint, since `contactAdmin` became a collection. Leaving
it under `endpoints/` would have made the folder name a lie for the next
reader.

`requireActiveClient` / `parseBody` / `parseQuery` stay: those are still
genuinely endpoint helpers.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(migrations): add user_messages table and status enum

Generated by `db:migrations:create`, unedited. Validated:

- `up` is purely additive — 0 DROP statements. The two the validator
  flags are both in `down`, reversing the new table, which is correct.
- The task-slug enums gain their values via `ADD VALUE ... BEFORE`, not
  the drop-and-recreate that a value *rename* would have produced.
- `client_id` / `user_id` are `ON DELETE set null`: deleting a client or
  a registrant must not destroy the message they relayed or sent.
- Indexes land on `sender_email` and `body_hash` — the two columns the
  screening job's history counts look up by.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* test(user-messages): cover the intake, screening, and retention

Three integration lanes plus a unit lane. Three of the assertions were
checked by breaking the thing they guard, because each could otherwise
pass vacuously:

- the field-access tests forge `screeningResult` and `deliveredAt`, not
  `status` — status is defended twice (field access AND the prepare hook
  overwrites it), so it cannot isolate the guard. Removing
  `systemFieldAccess` makes both fail; with it, both stick as stripped.
- the intake spec runs `overrideAccess: false` with a real published
  client. The override the sibling event-submissions spec uses skips
  field access entirely, so a spec using it could not tell a stripped
  field from an accepted one.
- the retention/window invariant (delivered retention must outlive the
  screening window, or the history checks count against deleted rows and
  silently pass everything) fails when the constant is lowered.

Two findings recorded rather than papered over:

- The screening spec's fixtures originally shared one message body and
  seven cases failed on the duplicate-body check. That was the check
  working; `seed()` now varies the body unless a case names one.
- `ALLOW_POST_FOR` turns out to be necessary but NOT sufficient: tier 2
  hides any path whose collection is in no project, so both public
  intakes' POSTs are `x-internal`. The test asserts the real behaviour
  for both, and `.claude/rules/openapi.md` now says what would actually
  change it.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* chore(admin): regenerate the import map for UserMessageStatus

The status banner is registered as a field `components.Field`, which the
admin import map has to resolve at runtime. Generated, not hand-edited.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor: simplify per /simplify pass

Three cleanups, no behaviour change:

- `screen()` returned its verdict from five places, three of which
  hand-carried the diagnostic via a repeated spread and two of which
  correctly omitted it — a shape a reader has to verify rather than read.
  One `settle()` exit now carries it wherever it has been set.
- `screen()` took `messageId` alongside the `message` it came from.
- `context`'s validator was inline while `message`'s was extracted; both
  are named functions now.

Reuse angle found nothing to reuse: no shared hash or name-from-email
helper exists, and `hasMxRecords`'s duplication is the recorded decision.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(user-messages): validate a restored verdict against the real set

`isScreeningResult` asserted `value is UserMessageScreeningResult` while
checking only that `verdict` was a string — an assertion wider than its
check, which the compiler then propagates.

The review that raised this described the wrong failure (notes filled
with `undefined` via `messageVerdictNote`); that cannot happen, because
the note is only ever composed from a freshly computed verdict, never
from the restored one. The real consequence is worse and is now pinned
by a test: a `failed` row whose stored verdict is unrecognisable was
TRUSTED, so screening was skipped and a disposable-address message got
delivered. Loosening the guard makes that test fail with
`expected 'delivered' to be 'spam'`.

`MESSAGE_VERDICTS` is now a runtime list with the type derived from it —
the same shape as `USER_MESSAGE_STATUSES` — because a value read back out
of a JSON column needs something to check against.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(user-messages): restore the 254-char bound on the sender address

Found by the security pass, as a parity gap rather than a vulnerability.

The endpoint this collection replaces bounded `email` at 254 via Zod, and
its OpenAPI schema published that. Payload's `email` field has **no**
`maxLength` option — the option is absent from `EmailField`, present only
on text-shaped fields — so moving the intake onto a collection dropped
the bound silently, leaving an unbounded string on a public write path.

Restored as a validator composing Payload's own `email` check, the same
shape `message` already uses. Tested in both directions so it cannot pass
by rejecting everything.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: sync Turnstile and access docs with the collection move

Docs-sync sweep of the branch diff turned up three stale spots and one
that was misleading before this branch:

- DEPLOYMENT.md quoted a log line operators grep for,
  `contactAdmin: Turnstile verification could not be completed`, which no
  longer exists — the guard logs under `antiSpamGuard:` now. Both it and
  .env.example also described the secret as belonging to one endpoint;
  it covers the whole public write surface, via a header.
- `.claude/rules/access.md` said a collection in no project is reachable
  only by explicit-permission users. That is the opposite of what step 5
  of its own permission flow says: no project means SHARED, i.e.
  implicitly readable by every role. `RESTRICTED_COLLECTIONS` exists
  precisely because of that, and the section never mentioned it — which
  is a trap for anyone adding a collection that holds personal data.
  Rewritten with the two knobs and how they compose.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs: state the root-endpoint criterion, not the count

PR #651 adds `/api/atlas/sitemap` as another root endpoint, so wording
that asserted "exactly one" / "the only root endpoint" would have been
false the moment either PR merged, whichever went first — and would have
collided textually in the same paragraphs.

The durable point was never the count: it is that "unpersisted" is not
"ownerless", which is what #632 demonstrated by deleting an endpoint whose
only claim to being ownerless was that it chose not to store anything.
That survives any number of siblings.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Revert "fix(user-messages): restore the 254-char bound on the sender address"

Removed at the user's request. The bound was raised by the security pass
as a parity gap rather than a vulnerability — an over-long address is a
storage concern, not an exploitable one — and Payload's `email` field
still rejects anything that isn't a well-formed address.

This reverts d8f5a2b, including its test.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(ci): a conflicted PR runs no CI, and nothing says so

Cost ~30 minutes of this session. `main` moved under this branch (#651),
the PR went CONFLICTING, and GitHub silently stopped scheduling runs — a
`pull_request` workflow runs against the merge commit, and a conflicted
PR has none. Nothing surfaces that: `gh pr checks` showed only Railway
(which kept deploying, since it builds the branch head, not the merge),
`gh run list --branch` was empty, and no job appeared failed. It reads
exactly like a stuck scheduler, so the instinct is to wait, or to
close/reopen the PR — neither of which touches the cause.

Documents the one-command diagnostic
(`gh pr view <n> --json mergeable,mergeStateStatus`) in AGENTS.md, and
puts it as a precondition in the finalize pipeline's CI-watch step, which
is where the workflow actually meets it.

Two traps recorded with it: a green run can be STALE (it predates `main`
moving, so a conflicted PR looks tested — check the run's `head_sha`),
and docs conflict far more readily than code, because sibling feature PRs
edit the same paragraph of the same rules file even when they share no
functions. Hence the advice to write shared rule docs as a criterion
rather than a count.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* fix(e2e): name the stale-preview-admin case instead of a bare 403

The smoke lane's `ensureAdmin` bootstraps a preview by logging in and, on
failure, calling Payload's `first-register`. Payload returns Forbidden from
`first-register` as soon as the auth collection holds any document, so once a
preview has been seeded the only 403 it can produce means "an admin already
exists that PREVIEW_ADMIN_PASSWORD does not open" — the opposite of what the
raw error reads like.

That is the state this PR's preview is in. Its Postgres has been up since
2026-08-26T22:47Z and the first smoke run seeded [email protected] with
the password that was still hardcoded in this file; #656 then moved the
credential to the PREVIEW_ADMIN_PASSWORD secret (created 2026-08-27T17:35Z),
and a preview's volume outlives its deploys, so the seeded admin kept the old
value. Login fails on the new secret, first-register is Forbidden, and all five
auth-dependent smoke specs die on a Payload stack that says only "You are not
allowed to perform this action".

#656's own CI could not catch this: the preview-URL discovery step found no
preview on #656, #657 or #658, so the smoke lane skipped there and this branch
is the only place the change has ever run.

Report the real cause and the remedy, drop the getter's stale pointer at the
Railway service variables (nothing server-side reads that name), and record in
AGENTS.md that the secret is stable per preview rather than rotatable on its
own. This does not turn the lane green — the preview database still has to be
reset so it can be seeded again — but it stops the failure from reading as a
registration bug.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor(user-messages): let jsonSchema own the JSON columns' shape and types (#660)

Applies the review on #653. The JSON fields now carry a `jsonSchema`, which
Payload compiles to a write-time validator AND generates the field's type from —
so `types.ts`'s `UserMessageContext` and `screening.ts`'s
`UserMessageScreeningResult` are gone rather than kept in agreement by eye.

- `context`: open schema (unknown keys still pass, per the intake contract);
  `validateContext` and its serialized-length cap deleted.
- `screeningResult`: closed schema, `verdict` enum derived from
  MESSAGE_VERDICTS so the runtime list and stored contract cannot drift.
- `message`: built-in `minLength`/`maxLength` replace the composed validator;
  both bounds inline.
- `messageVerdictNote` becomes the `MESSAGE_VERDICT_NOTES` record.
- `UserMessageStatus`: `Severity`/`BANNER_TYPE` collapse into `Banner`'s own
  type; the defensive `notesOf` filter goes, the schema having closed the hole.
- `normalizedBodyHash` folds into its one consumer, `prepareUserMessage`.

Per-key documentation survives as JSON Schema `description`, which Payload
renders into the generated type's JSDoc.


Claude-Session: https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC

Co-authored-by: Claude <[email protected]>

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Devindra <[email protected]>
Co-authored-by: SYDevelopers Bot <[email protected]>
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…nd types (#660)

Applies the review on #653. The JSON fields now carry a `jsonSchema`, which
Payload compiles to a write-time validator AND generates the field's type from —
so `types.ts`'s `UserMessageContext` and `screening.ts`'s
`UserMessageScreeningResult` are gone rather than kept in agreement by eye.

- `context`: open schema (unknown keys still pass, per the intake contract);
  `validateContext` and its serialized-length cap deleted.
- `screeningResult`: closed schema, `verdict` enum derived from
  MESSAGE_VERDICTS so the runtime list and stored contract cannot drift.
- `message`: built-in `minLength`/`maxLength` replace the composed validator;
  both bounds inline.
- `messageVerdictNote` becomes the `MESSAGE_VERDICT_NOTES` record.
- `UserMessageStatus`: `Severity`/`BANNER_TYPE` collapse into `Banner`'s own
  type; the defensive `notesOf` filter goes, the schema having closed the hole.
- `normalizedBodyHash` folds into its one consumer, `prepareUserMessage`.

Per-key documentation survives as JSON Schema `description`, which Payload
renders into the generated type's JSDoc.


Claude-Session: https://claude.ai/code/session_01Jry6g9kMG1UQ63N99vABAC

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants