Skip to content

feat(api)!: async user-messages intake with deep spam screening - #653

Merged
Ardnived merged 19 commits into
mainfrom
feat/async-user-messages
Aug 31, 2026
Merged

Ardnived merged 19 commits into
mainfrom
feat/async-user-messages

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • POST /api/contact-admin becomes the user-messages collection: accept fast, screen deeply in a job.
  • Screening adds an MX lookup, a repeat-sender window, and duplicate-body detection before delivery.
  • Messages are retained briefly and swept nightly — delivered 7 days, spam 90, failed never.

Breaking change

POST /api/contact-admin is deleted. Clients create through POST /api/user-messages. Three things move on the wire, so SahajAtlasWeb needs the matching change alongside this merge:

Before After
Turnstile token JSON body x-turnstile-token header
Success 200 { ok: true } 201 { doc, message }
Error code errors[].code errors[].data.code

Also: email becomes senderEmail. Safe to cut over in one step — the Atlas widget is pre-release and no third-party host embeds it yet.

Tracked client-side by sydevs/SahajAtlasWeb#171, which must land alongside this. Note the trap recorded there: asRefusal is shared with the registration mutation, and POST /api/events/{id}/register still emits errors[].code at the top level — so the client has to accept both positions, not switch.

Changes

  • src/collections/UserMessages/ — the collection, its status/verdict vocabulary, and the create hooks.
  • src/jobs/ScreenUserMessages/ — MX + disposable re-check, the two history counts, delivery.
  • src/jobs/PurgeUserMessages/ — the nightly retention sweep (04:00 UTC, nightly queue).
  • src/plugins/access/config/ — RESTRICTED_COLLECTIONS + a create-only grant for sahaj-atlas-client.
  • src/plugins/writeGuard/policies.ts — the anti-spam policy that replaces the endpoint's hand-rolled gate.

Migration

  • New migration: src/migrations/20260826_214829_add_user_messages.ts
  • Impact: adds the user_messages table + status enum; adds two task-slug enum values via ADD VALUE, not a drop-and-recreate. up contains zero destructive statements.
  • Reversible: yes — down drops the new table and column, which is the correct reversal.

Decisions worth reviewing

  • Access is tighter than event-submissions. user-messages is granted by no manager role — reading one takes the admin bypass. That is deliberate: these are unscreened messages from strangers about anything at all.
  • Persistence is a change of stance. feat(api): add a captcha-gated contact-admin endpoint #602 deliberately stored nothing. Retention is what buys that back, and the 7-day floor is load-bearing: shorten it below the 24-hour screening windows and the history checks count against deleted rows and silently pass everything. Pinned by a unit test.
  • No spam-scoring dependency. spamscanner is BUSL-1.1; the small alternatives are abandonware; bayes/natural need a corpus we don't have; obscenity detects profanity, which would flag an angry-but-genuine bug report. Duplicate-body hashing replaces it — exact, no tuning.
  • hasMxRecords is duplicated on purpose (~38 lines) so the two intakes stay independent; the verdict wording was never shareable. Cost stated in the file: an MX bug needs fixing twice.
  • No length bound on senderEmail. Payload's email field has no maxLength option, so the 254-char cap the old endpoint enforced is not carried over. Raised by the security pass and removed at the maintainer's request — an over-long but well-formed address is a storage concern, not an exploitable one.

Two things found while shipping

  • ALLOW_POST_FOR is necessary but not sufficient. Tier 2 of filterSpec hides any path whose collection is in no project, so both public intakes' POSTs are x-internal — event-submissions has been in that state since feat(events): public event submissions, screening pipeline & write-guard plugin #625. Asserted for both, and .claude/rules/openapi.md now says what would actually change it.
  • .claude/rules/access.md was misleading. It said a collection in no project is reachable only by explicit-permission users; step 5 of its own permission flow says the opposite (no project ⇒ shared). RESTRICTED_COLLECTIONS exists because of that and went unmentioned. Rewritten.

Behaviour change to note

The 500 for an unavailable captcha now carries code: "captcha_unavailable". The deleted endpoint deliberately suppressed it ("a public caller must not learn whether the secret is unset or Cloudflare is down"). The shared write-guard has always exposed it for event-submissions, so this aligns the two rather than adding a special case — flagging it because #602 called that suppression a pinned contract.

Test Results

  • Unit: 1497 passed (113 files) — includes 11 new
  • Integration: 129 passed across the 5 specs touching this change (40 new); re-verified after merging origin/main
  • Typecheck (src/ + tests): ✓
  • Lint: ✓ No errors
  • Migration validator: 4 pass, 2 warns — both DROPs are in down, verified
  • CI: green on 58d6609d (both Lint, Test & Smoke and the Railway preview)

origin/main is merged in — #651 landed /api/atlas/sitemap mid-flight and conflicted with this branch across four rule docs plus payload.config.ts. Worth knowing: a conflicted PR runs no CI at all, silently, because there is no merge commit to run against. That's now documented in AGENTS.md with the one-command diagnostic.

Three assertions were checked by breaking the thing they guard, since each could otherwise pass vacuously: removing systemFieldAccess makes the forged-field tests fail; lowering the retention constant fails the window invariant; loosening the verdict guard delivers a message that should be spam.

Manual verification

  1. POST /api/user-messages with a client key + x-turnstile-token → 201, row appears under User Messages as Checking with the right Client.
  2. Run the screening queue → flips to Delivered, email captured by Ethereal.
  3. Repeat with a mailinator.com sender → Marked Spam; post the same body twice → duplicate verdict.
  4. Sign in as a non-admin manager → User Messages absent from the nav, direct URL refused.

Closes #632

🤖 Generated with Claude Code

Ardnived and others added 12 commits August 26, 2026 13:41
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]>
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]>
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]>
…take

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]>
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]>
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]>
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]>
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]>
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]>
`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]>
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 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]>
@railway-app

railway-app Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-653 environment in sahajcloud

Service Status Web Updated (UTC)
SahajCloud 🕒 Building (View Logs) Web Aug 31, 2026 at 4:52 pm

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-653 August 26, 2026 22:47 Destroyed
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]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-653 August 26, 2026 22:52 Destroyed
…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]>
Ardnived and others added 2 commits August 26, 2026 17:16
#651 landed `/api/atlas/sitemap` as a third root endpoint while this branch
was deleting `contactAdmin`, so both touched the same paragraphs of four
docs plus `payload.config.ts` and `responseTypes.ts`.

Resolved by taking both sides everywhere: the root-endpoint list keeps
`atlas/seo` and `atlas/sitemap` and drops `contact-admin`, and the note
about *why* it was dropped ("unpersisted is not ownerless") is kept, now
phrased against a third rather than a second endpoint. `responseTypes.ts`
is shared by both survivors again, which is its original justification.

Verified after resolution: lint, both typechecks, 1497 unit, and 92
integration across this branch's specs plus #651's new sitemap suite.

Refs #632

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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]>

@Ardnived Ardnived left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sydevs-bot Please review the comments in this review and respond accordingly. Fix issues and pushback as needed. There are a lot of review comments here that center around the effective use of typescript, removing unnecessary indirection, and improving hygiene for custom admin components. You should also analyze all other admin components along these lines and propose another ticket to resolve those inconsistencies and inefficiencies.

}
return true
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just use minLength as well as maxLength instead of adding a custom validator?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes — minLength exists on textarea and I should have used it. It's in the field's config table alongside maxLength, both "used by the default validation function".

One thing it loses, for you to weigh: the built-in measures value.length, the custom validator measures value.trim().length. So minLength: 10 accepts ten spaces, which the current code rejects. On a public intake that's exactly the junk worth refusing — but the write-guard's URL/email checks and the async screening both sit behind this, so it isn't the only line.

My recommendation: take minLength: MESSAGE_MIN and drop the validator. It deletes a composed-validator hazard (see the context thread — a custom validate replaces the built-in and it's easy to lose maxLength that way), and the whitespace case is worth less than the simplification. If you want the trim kept, it stays a composed validator and minLength goes in for the message only.

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


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go ahead with your recommendation, but also get rid of MESSAGE_MIN and just write the minimum inline

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done deal — minLength: 10 inline, validateMessage and MESSAGE_MIN both deleted. Checked the ripple: nothing outside this file referenced MESSAGE_MIN, and no test pins the custom "Tell us a little more…" copy, so Payload's default message takes over with nothing to update.

Two things that fall out, neither needing a decision from you:

  • The TextareaFieldValidation type import and textarea as validateTextarea from payload/shared both lose their last use and go too.
  • maxLength: MESSAGE_MAX keeps working — it was only ever at risk because a custom validate replaced the default that enforces it. Deleting the validator removes that hazard rather than creating one.

MESSAGE_MAX is now the same shape as MESSAGE_MIN was — a file-local constant with exactly one use, at line 143. Your reasoning applies to it identically; I've left it alone because you named only the one. Say if you want maxLength: 5000 inline too and it goes in the same edit.

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


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, put MESSAGE_MAX inline as well

Comment thread src/collections/UserMessages/types.ts Outdated

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need a separate file? I think PayloadCMS might already provide us with a type if we set jsonSchema for the context field. Investigate that

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — you're right, and the file can go. Setting jsonSchema on context generates UserMessage['context'] in payload-types.ts, so this is a second hand-maintained source of truth for a column Payload will describe itself.

Three consumers import it — jobs/ScreenUserMessages, emails/UserMessageEmail, lib/notifications/sendUserMessage — so the move is: put the five keys in the schema, delete types.ts, repoint those three at the generated type.

The one thing worth preserving is the per-key JSDoc — "Route the sender was on", "Absolute URL of the host page" — which is what makes the type readable at those three call sites. JSON Schema description should carry through as JSDoc in the generated file, since Payload generates via json-schema-to-typescript. I could not verify that here (no node_modules), so it's the thing to check by eye after pnpm generate:types: if the descriptions don't survive, this trades documentation for deduplication and is worth reconsidering.

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


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go ahead and implement this

Comment on lines +63 to +67
const BANNER_TYPE: Record<Severity, 'default' | 'error' | 'success'> = {
info: 'default',
error: 'error',
success: 'success',
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of having our own Severity type and them mapping it to the Banner's type, couldn't we just use Banner['type'] in COPY?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes — Severity and BANNER_TYPE both go. Key COPY and ICONS on Banner's own type and the mapping table disappears:

const COPY: Record<MessageStatus, { type: BannerProps['type']; message?: string }> = {
  screening: { type: 'default', message: '…' },
  delivered: { type: 'success', message: '…' },
  spam:      { type: 'error' },
  failed:    { type: 'error', message: '…' },
}

The only thing lost is the word info reading better than default for the screening state, which isn't worth a type and a lookup table.

One knock-on: the user-message-status--${severity} class name currently interpolates the severity. Nothing in styles.css uses those modifier classes — only the base .user-message-status — so that interpolation can go at the same time rather than quietly becoming --default.

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


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go ahead and implement this

Comment on lines +69 to +79
/**
* The stored value is JSON, so it can be anything a bad write left behind —
* render only real strings rather than trusting the column's declared type. A
* malformed row degrades to no notes instead of throwing the edit view.
*/
function notesOf(result: UserMessageScreeningResult | null | undefined): string[] {
const notes = result?.notes
return Array.isArray(notes)
? notes.filter((note): note is string => typeof note === 'string')
: []
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really necessary if we enforce a jsonSchema on the field?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Largely, yes — drop it to result?.notes ?? [].

With additionalProperties: false and notes: { type: 'array', items: { type: 'string' } } enforced on write, the only writer is ScreenUserMessages and it can no longer store a malformed value. This is a new collection with no existing rows, so there's no legacy data the schema didn't gate — which is the case that would normally justify keeping a runtime filter.

The honest caveat, so it's a decision rather than an oversight: a schema binds Payload writes, not the database. A migration or hand-run SQL could still put anything in the column, and this renders in the edit view, where a throw takes the whole document page down rather than one banner.

I'd still drop it. That residual risk applies to every field in the admin and we don't defend any of the others this way, so singling out this one is inconsistent rather than careful. ?? [] keeps the null case, which is real — a message that hasn't been screened yet.

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


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Go ahead and implement this


return (
<div className="field-type json read-only">
<FieldLabel label={label} path={name} />

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of redeclaring the <FieldLabel> within this custom component, we should only override the Input component instead of the entire Field component

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same answer as the collection-config thread: Input isn't one of the slots (Field, Cell, Filter, Label, Error, Diff, Description, beforeInput, afterInput), and Field is the only one that replaces the control.

On this file specifically: the <div className="field-type json read-only"> + FieldLabel here isn't incidental scaffolding — it's what makes the field align with every other field on the page, take the read-only treatment, and give the banner an accessible label. Removing it wouldn't yield a narrower component, it would yield an unlabelled banner floating outside the field grid.

Not adopting. If Payload adds a narrower slot, this and the 19 other components doing the same thing move together — #659 records it.

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


Generated by Claude Code

Comment thread src/lib/antiSpam/antiSpamGuard.ts Resolved
@sydevs-bot

Copy link
Copy Markdown
Contributor

You're right about the JSON fields, and I can't push the fix to this branch. Per-thread answers below; this is the summary and the one blocker.

Adopted (8): the whole jsonSchema cluster — context, screeningResult, types.ts, the verdict hash — plus minLength, Banner['type'], and dropping notesOf.

Pushed back (4), with evidence: the two "override Input" threads rest on a slot that does not exist; the CSS thread on a dependency this repo does not have; the bodyHash.ts and emailSchema threads are smaller than they look.

The blocker: this branch is feat/async-user-messages, and I can only push to claude/* — so I have not committed anything. Say the word and I'll open a stacked PR into this branch carrying the adopted changes; you'd merge it here in one click. I'd rather ask than open a PR you have to manage.

Follow-up ticket you asked for: #659. Its useful content turned out to be which of your four themes generalise — two do, two don't, and the numbers are in there.

The finding that settles most of the review — and a gotcha that would silently undo it

jsonSchema does both things you were reaching for. It compiles an Ajv write-time validator and generates the field's type into payload-types.ts. That is not inference — src/lib/registrations/questions.ts says so, and Registrations.questions + Clients.embedMetadata are working precedents in this repo.

Two comments in the tree say the opposite, and they are stale. translationsField.ts and subtitles.ts warn that Ajv's new Function() is blocked by Cloudflare Workers' V8 isolate (#317). questions.ts already records the correction: "fine on Railway/Node; the old comments warning it breaks under Cloudflare Workers predate the migration off Workers." DEPLOYMENT.md confirms Railway/Node. I've put correcting those in #659, because as long as they stand they will keep deterring exactly this change.

⚠ The gotcha: supplying validate replaces Payload's default validator — and the default validator is what runs the schema. So on context, adding jsonSchema beside the existing validateContext would silently do nothing; and deleting validateContext would drop the 4000-char serialized cap, which no JSON Schema keyword expresses. It has to compose the built-in, exactly as validateMessage already composes textarea from payload/shared. This is the same rule .claude/rules/collections.md states for maxLength.

One thing I could not verify from here and would check while implementing: that json is exported from payload/shared for that composition, and that generate:types renders the schema's description strings as JSDoc (so UserMessageContext's per-key docs survive the move). node_modules is not installed in this environment, so I read the published docs and this repo's own precedents rather than the library source — which also means I have run no lint, typecheck or test against any of this.

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


Generated by Claude Code

@sydevs-bot

Copy link
Copy Markdown
Contributor

⚠ This PR is conflicted, so no CI can run on it — and the green check above is stale. Found on a subscription wake, separate from the review replies.

The irony is worth a second: the conflicting file is the commit that documents this exact trap. 58d6609 docs(ci): a conflicted PR runs no CI, and nothing says so added 13 lines to .claude/skills/finalize-pr/SKILL.md, and main deleted that whole skill in #656 when the repo adopted the shared workflow plugin. Modify/delete — it's the only conflict.

The fix, and why I'm not doing it: resolution is to accept main's deletion. But I can only push to claude/* and this is feat/async-user-messages, so it's yours.

⚠ Don't let the 13 lines go with the file. They're real guidance and the plugin's copy (sydevs/claude-workflow → workflow/skills/finalize-pr/SKILL.md) does not have them — I checked; its section 8 is "Watch CI, fix, capped at 3" with nothing about conflicted PRs. Accepting the deletion cleanly deletes the warning about the failure that caused the deletion. Happy to open that port as a PR against claude-workflow if you want it — say the word.

Evidence — including the one claim in your PR body I checked and can confirm
origin/main   1707923  feat(email): replace Ethereal with Mailpit … (#657)
PR head       58d6609  docs(ci): a conflicted PR runs no CI, and nothing says so
merge-base    868b515  feat(api): an enumeration endpoint for sitemaps (#651)

git merge-tree --write-tree → exit 1, one conflict:

CONFLICT (modify/delete): .claude/skills/finalize-pr/SKILL.md
deleted in origin/main and modified in origin/feat/async-user-messages

Two commits landed on main after your merge-base: 80bcbe9 (#656, adopts the workflow plugin — the deletion) and 1707923 (#657).

Your "CI: green on 58d6609" claim is accurate — I checked rather than assuming, since it looked like a candidate for the stale-run trap. Lint, Test & Smoke ran at 2026-08-27T00:18:49Z and succeeded, and the head commit is timestamped 2026-08-27T00:17Z UTC. So it genuinely ran on this head.

It is nonetheless stale in the sense that matters: it predates both commits above, and no new Actions run can be scheduled while the merge commit is uncomputable. The only signal on the PR now is the Railway status from 2026-08-28T01:08Z, which stays green because Railway builds the branch head rather than the merge — exactly the asymmetry AGENTS.md records.

mergeable_state: dirty, confirmed against the API and reproduced locally.

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


Generated by Claude Code

Resolves one delete/modify conflict on .claude/skills/finalize-pr/SKILL.md:
main deleted it in #656 when the workflow skills moved to the sydevs/claude-workflow
plugin, while this branch had edited it. Taking main's deletion.

The edit itself was worth keeping and is not lost — it documents that a
conflicted PR schedules zero workflow runs, silently, so `gh run list` reads as
a stuck scheduler rather than a blocked merge. That has been ported to the
plugin's copy of finalize-pr, which is now the only copy.

Co-Authored-By: Claude Opus 5 <[email protected]>
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]>
@sydevs-bot

Copy link
Copy Markdown
Contributor

All six of those are already implemented — they're sitting in #660, waiting on you.

I opened it on 29 Aug against this branch, because I can only push to claude/*. Merging claude/user-messages-review-fixes into feat/async-user-messages makes it disappear into this PR.

Verified just now against ff48f661 rather than from memory:

Thread Asked On the branch
UserMessages.ts:70 jsonSchema for context ✅ — but not the variant you just approved; see below
UserMessages.ts:57 minLength, both bounds inline ✅ minLength: 10, maxLength: 5000, validateMessage + MESSAGE_MIN/MESSAGE_MAX gone
types.ts delete it, use the generated type ✅ file gone, 3 consumers on NonNullable<UserMessage['context']>
screening.ts:63 jsonSchema for screeningResult ✅ closed schema, verdict enum from MESSAGE_VERDICTS
screening.ts:89 verdict function → typed hash ✅ MESSAGE_VERDICT_NOTES
UserMessageStatus.tsx:67 Banner['type'] instead of Severity ✅ Severity and BANNER_TYPE both gone
UserMessageStatus.tsx:79 drop notesOf ✅ now value?.notes ?? []
bodyHash.ts fold into prepareUserMessage ✅ file gone

⚠ One of them is not what you approved, and it's the first one

You said "go ahead with your recommendation" on the context schema. My recommendation was the bounded version, and it is not buildable — I found that out implementing it, and shipped additionalProperties: true instead.

A typed additionalProperties generates [k: string]: string in payload-types.ts. TypeScript then requires every named property to be assignable to that index signature — and all five are optional, so string | undefined is not. The generated file stops compiling.

So the per-unknown-key size bound is gone. What remains is maxProperties: 20 plus maxLength: 2000 on each of the five named keys; an unknown key's value is unbounded. By your own criterion — "if it lets us simplify" — the bound didn't, so it went.

That reverses the exposure I raised on the thread and you accepted on that basis, so it's yours to re-decide rather than mine to quietly settle. Three ways to get a bound back, if you want one:

  1. Drop properties entirely, keep additionalProperties: { type: 'string', maxLength: 2000 } → a clean bounded Record<string, string>. Costs the five named keys and their generated JSDoc.
  2. Make the five keys required → they become string, assignable, and the bound compiles. Costs forward-compatibility for a partial context.
  3. Keep the open schema and re-add a composed validator for serialized size — which is the code we just deleted.

My preference is to leave it open as shipped and take the unbounded-unknown-key risk, since maxProperties: 20 still caps the row's shape. But it is a real reduction from what you signed off, so say if you'd rather have (1).


Nothing is blocked on me here. #660 is green on its own gate (lint, typecheck, typecheck:tests, 1497 unit) and mergeable_state: clean against this branch. The one thing I could not run is the integration suite — no local Postgres — and I changed user-message-screening.int.spec.ts, so that's the likeliest surprise when CI runs it here.

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


Generated by Claude Code

…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]>
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-653 August 31, 2026 16:52 Destroyed
@Ardnived
Ardnived merged commit 5a4035c into main Aug 31, 2026
1 of 2 checks passed
Ardnived added a commit that referenced this pull request Sep 5, 2026
)

Rewrites every in-scope prose file (67 of 69 flagged by the audit) into
strict Simplified Technical English and retires D1/Cloudflare Workers-era
debris three months after the Postgres/Railway migration. Tracked *.md
(excluding CLAUDE.md symlinks and the vendored .agents/skills/payload/
skill, left untouched pending ownership confirmation) drops from 770,090
to 600,797 chars (22%). The five hot-path files auto-imported every
session (AGENTS.md, docs/architecture.md, docs/environment.md,
docs/code-style.md, .claude/workflow.json) drop from 84,492 to 36,397
chars (57%).

Deleted (dead, zero referrers, grepped clean): seed-issues-report.md,
src/migrations/README.md (its one fact folded into src/migrations/AGENTS.md).

Merged: DEPLOYMENT.md + RAILWAY_RUNBOOK.md split by lifecycle (how it runs
today vs. provision-from-scratch/disaster-recovery), resolving their
D1-decommission contradiction — PR #468 (merged 2026-06-08) confirms the
Worker is gone, so the stale "Remaining (gated)" TODOs are removed, not
reworded.

Legacy debris fixed (D1/SQLite/Cloudflare-Workers-as-current retired):
migration-reviewer.md's whole persona rewritten for Postgres/Drizzle,
seeds/wemeditate/AGENTS.md's Dual-Database table corrected to Postgres,
src/globals/AGENTS.md's json_array() rationale corrected to Postgres's
real FUNC_MAX_ARGS=100 limit, docs/mcp-setup.md's cloudflare-docs row
drops Workers/D1. grep for D1|SQLite|Cloudflare Workers across
.claude/agents/, seeds/wemeditate/, src/globals/, docs/mcp-setup.md is
clean. README.md's stale `cd sy-devs-cms` corrected to `cd SahajCloud`.

Mandatory AGENTS.md fixes applied: dropped the nonexistent `pnpm
test:e2e`, replaced the broken dev-server.sh path with the
`/workflow:dev-server` skill, fixed the seeds/atlas/MIGRATION_PLAN.md:103
anchor (now resolves to `AGENTS.md#website-selection-rules-584`),
collapsed duplicate PR-workflow/test-tier prose into single pointers to
testing-reqs.md and the finalize-pr skill.

Traps preserved (compressed, never deleted): the conflicted-PR "zero CI"
diagnostic with its docs/why.md anchor and #632/#653 numbers; the Cache
Rule authorization-header predicate and root-endpoint fix; DB_QUERY_LOGGING
and TURNSTILE_SECRET_KEY footguns; storage.md's preview/prod asset-isolation
risk; the payload-cli silent-exit/hang ladder; the migration snapshot
out-of-order duplicate-re-emission trap; access.md's per-locale-roles
gotcha (#665); endpoints.md's root-endpoint hook gap; email.md's two-
token-URL-shapes bug; seeds/atlas/AGENTS.md's silent-rollback-on-trashed-
relation trap; the never-name-a-global-field-locales rule. The 2026-08-27
dated Admin Access exception is kept (still current).

Comment sweep: rewrote comments to STE in every file the audit flagged
as touched (route.ts's mandatory dead-comment deletions, r2NativeAdapter.ts,
Icon.tsx, scalarPlugin.ts, env/server.ts, localizedRolesAuth.ts, plus the
full tests/seeds/scripts/.claude/root-config/.github sweep — 227 files
total). Verified comment-only: every changed line in every .ts/.tsx/.mjs/
.cjs/.sh/.py file has an identical code portion before its comment marker;
zero functional changes. Deleted a dead `sharp` import and several doc-
duplicating/obvious comments (e.g. vitest.setup.ts's two narrate-the-
obvious lines).

Verification run as finisher: pnpm lint, typecheck, typecheck:tests, and
the full unit lane (1564 tests) all pass, plus targeted integration specs
for every touched collection/access path (events, regions, role-based-
access — 79 tests, live Postgres). ste-lint.py run on all 40 changed .md
files: hard violations cut from 169 to 118, concentrated in five already-
dense reference docs (admin-ui/api-clients/email/endpoints/openapi/
storage.md) where the prior compression pass already prioritized fidelity
over the linter's raw sentence-length cap; remaining flags are verified
domain terms (Railway's "Health Check", Zod's "Validate", literal HTTP
methods GET/DELETE, SQL "cascade delete", TS "type erasure") or residue
in those five files. rule-delta.mjs vs main on AGENTS.md/docs/rules/*.md/
migration-reviewer.md: 3 directives flagged REMOVED, all three verified
as de-bolded (not deleted) — "GET /api/events/geojson always excluded,
no opt-out" (api-clients.md) and the two CPU parallel-test-run rules
(testing-reqs.md) all still present as plain bullets/cells, content
identical. 1 flagged ADDED is the same pass-by-reference comment rule
gaining full-sentence bold (previously invisible to the tool since only
"Do not" was bold). Sequencing: PRs #692 (UNKNOWN), #686 (BLOCKED, not
CONFLICTING), #691 (CLEAN) show no current CONFLICTING/DIRTY state, so
this PR is not blocked today, though #692/#691 touch overlapping files
and should land or be watched. securityReview trigger paths (access/,
storage/, api routes, webhook scripts) all confirmed comment-only.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Ardnived pushed a commit that referenced this pull request Nov 5, 2026
…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
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]>

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-653 — bbe6a8ba Deployed Aug 31, 2026 by railway-app[bot]
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.

Make contact-admin asynchronous with deep spam screening

2 participants