Repository navigation
fix(api): stop refusing a visitor's email answer as a URL - #919
Conversation
A public submission whose authored form asks for an email address was refused with `urls_not_allowed` whenever that address sat on a common TLD. `URL_PATTERN`'s third arm matches `[a-z0-9-]+\.(com|net|org|…)`, which every ordinary address satisfies, and `URL_EXEMPT_KEYS` covers only the five keys the client writes about itself. Measured against the real pattern, 8 of 12 common providers were refused; `co.uk`, `mail.ru`, `web.de` and `posteo.de` passed, so it looked random from the outside. The atlas's report-issue form is live on this path and its email field is required, so the visitor could not clear the offending value — the form was a dead end for most people. The scan is correct to look at free-text answers and wrong to look at an address, so the exemption goes where the authored block types are known. `urlScannablePairs` takes the extra keys to skip, and the intake hook supplies them from the form. Keyed on the block type, not a reserved name: the operator chooses every field name, so renaming the question in the admin must not change how a submission against it is judged. Exempt is not unchecked. An authored email answer now runs through `checkEmailAllowed` — format plus the disposable-domain list — so a link typed into that field is still refused, as `invalid_email` rather than `urls_not_allowed`. That check is the stricter question for an address, and it reaches an answer the write-guard's `emailFields` never covered, since that policy names `senderEmail` and `proposed.contactEmail` alone. Not the alternative fix of having the atlas send the address only once, as `senderEmail`: that repairs one caller and leaves the next operator who adds an email question to the Contact Form broken again, silently, while losing the operator's view of the question they asked. The existing unit case is extended rather than relaxed — it passed with the defect present because its fixture carried no `email` pair. Closes #899 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TWacYZUdLp8kawLD6FtAHT
Review pass over the branch. Six findings, each from a reviewer: `EMAIL_FIELD_BLOCKS` moves to `src/lib/submissions/`, where `Forms` and `UserSubmissions` both read it. Both encode one fact — which authored block holds an address a person types — and a block type added to one and not the other fails silently in the #899 direction: `Forms` keeps accepting the form while the intake stops exempting its answer. Typed against the generated block union, so a plugin rename fails `tsc` at the declaration. `emailFieldNames` drops its two `unknown` casts. `Form['fields']` is a discriminated union, so `'name' in block` narrows to the arms that have one, and the casts were silencing the only check that would catch the discriminator moving. `flatMap` is what lets the narrowing survive the filter. `alsoExempt` is `readonly string[]`, not `Iterable<string>`. A bare `string` satisfies the latter, so `urlScannablePairs(data, 'email')` type-checked and would have exempted five single letters. The merged `Set` goes with it: two `has`/`includes` calls over 0-2 entries need no allocation per submission. The answer is trimmed before the address check. `checkEmailAllowed` passes `''` and nullish, but not `' '`, so a whitespace-only answer to an optional email question would newly 400 where it used to be stored. Both anti-spam throws go through one `refuse`, which carries the offending field. `checkEmailAllowed`'s message names no key, and a form may ask for more than one address, so the 400 was unactionable where the URL scan's self-naming message is not. Comments trimmed to the why they carry, and the measurement moved out of three code comments into the commit that explains the change. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TWacYZUdLp8kawLD6FtAHT
Three surfaces describe behaviour this branch changed: the client contract's `urls_not_allowed` paragraph, the intake's coverage row, and the `src/lib/` inventory, which now names the second shared submissions list. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TWacYZUdLp8kawLD6FtAHT
|
🚅 Deployed to the SahajCloud-pr-919 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
This matches #899's size: one exemption, one compensating check, three doc rows. src/lib/submissions/formBlocks.ts earns its file — Forms requires an email block at save time and the intake exempts its answer at submit time, so the list in either owner would be a cross-owner import (src/AGENTS.md rule 4).
The one argument against this PR existing is that #921's lookbehind makes the plumbing unnecessary, and the body overstates it ("kill this class in all four consumers at once"). A narrowed pattern leaves the local part colliding: [email protected] still matches the bare-domain arm at offset 0, where a left lookbehind cannot reach. #921 agrees the exemption stays wanted. So alsoExempt is load-bearing after #921 — worth correcting in the body.
Findings
- should-fix —
fieldreaches the error data here and nowhere else on this endpoint.prepareUserSubmission.ts:246 - consider — the doc row names one of the two codes the address check raises.
api-clients.md:178
What was checked
Read whole: prepareUserSubmission.ts, submissionData.ts, antiSpamGuard.ts, writeGuardPlugin.ts + policies.ts, validateFormAction.ts, formBlocks.ts. Tickets #899, #920, #921.
checkEmailAllowedpasses nullish and'', so an unanswered optional question is unaffected.emailFieldNamesandalsoExemptare one list, so no key is exempted unchecked.- The exemption opens no link path to the
URL_EXEMPT_KEYSrenderer: an exempted value must parse as an address first. - Consumer side,
sydevs/SahajAtlasWeb:reportSenderEmailsends the first email block's answer assenderEmailtoo, so the guard already checked that value — no new refusal for the live form.UserSubmissionErrorCodecarries both email codes, and refusals readerrors[].data.code, so the added key is additive.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The intake hook puts `field` in the error data; the write guard raised the same codes and dropped it. Its URL-scan loop already composed the policy path to replace the indexed leaf key, so the intent was there and the value died in `throwFailure` — invisible to the type-checker and to every existing spec. One endpoint, one error shape: a client reading `errors[0].data` should not have to know which of the two refusers answered. `api-clients.md` documented the key from neither. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013XxB19HyZgcFKBVfwYf8HB
The exemption's row named `invalid_email` alone. `checkEmailAllowed` has a second arm on the same call, and `disposable_email` is the half this branch makes newly reachable: an answer not also sent as `senderEmail` had no disposable-domain check before, so the compensating check was described as narrower than it is. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013XxB19HyZgcFKBVfwYf8HB
|
Both review findings adopted. Nothing rebutted, nothing to ask.
The review body's third point stands as well: the Gate: lint, both typechecks, 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Ardnived
left a comment
There was a problem hiding this comment.
Our approach feels a bit dis-unified and inelegant. Take a step back and consider the entire form / submission validation flow. Do we need to be verifying the email in both places? Can we make our approach easier to understand and with less custom code by using Zod? Can we avoid adding the new formBlocks.ts file?
A reviewer asked whether the new `src/lib/submissions/formBlocks.ts` could be avoided. It can: `Forms` keeps the local `EMAIL_BLOCKS` it already had, and the intake compares `block.blockType === 'email'` directly. Both comparisons are against the generated block union, so a plugin rename still fails `tsc` at each site — the type safety the shared module bought survives without it. What the module also bought was a single home for a one-element list, so a block type added to one site and not the other no longer fails the compiler. That risk is hypothetical and cheap to re-fix; a file and a `src/AGENTS.md` paragraph for it were not worth their weight. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013CjkchJMsX8vqep4VUpLnd
|
Asking: rebuild the intake as one form-derived Zod schema — keys, lengths and per-block checks in one pass? That replaces 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
|
@sydevs-bot Go ahead and expand the ticket to "rebuild the intake as one form-derived Zod schema — keys, lengths and per-block checks in one pass". Implement in this PR. |
The key allow-list, the length caps and the per-block content checks were three walks over the same `submissionData` pairs. They are now one schema, composed from the submission's type and its form's own blocks: every allowed key carries its own value schema, so a block type's check is a row in `valueSchemaFor` rather than a fourth pass, and the `email` arm is the exemption #899 needed rather than an argument threaded through a scan. `checkContent` is the client-write half, so a manager's triage note is still unscreened. A shape refusal still reports every problem at once and still outranks a content refusal — a refused key's value was never meant to be judged — and both envelopes keep the code and field a client reads. Asked for in review: #919 (comment) Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dnp88uTfovjpmmswhugaT7
|
Adopted in 5f1e72a. #899 carries the scope. One schema, not three walks.
Gate: lint, both typechecks, 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
One `error` option on a string schema answers for every failure it raises, so a length failure could silently start reading "must be text" — the message an integrator acts on, with no assertion on it. `AntiSpamResult` replaces the inferred parameter type at the issue bridge. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Dnp88uTfovjpmmswhugaT7
`still URL-scans an address question authored as a text block` asserted that `[email protected]` in a `text` block raises `urls_not_allowed`. #922 removed that outcome everywhere: the bare-domain arm no longer reads the domain half of an address as a link. #919 landed the case on top of it, so `main` is red at f823484 too — the failure is not this branch's, and fixing it here is what the handler does with one. The property under test is the branch, not the value: a block the author made `text` gets the URL scan, while an `email` one gets the address check. `see example.com` carries that, and is the same input the `email`-block case above judges `invalid_email`, so the pair reads as one contrast keyed on block type. Reintroducing a `text` exemption in `valueSchemaFor` turns the case red, so it is not vacuous. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_0136exQRmeiDqDAMeS3tj9t9
Summary
emailanswer is no longer URL-scanned; it is checked as an address instead.Change outline
The intake hook already loads the form, so it is the one place that knows what each pair asked for. The key allow-list, the length caps and the content checks are one schema built from the submission's type and that form's blocks — every allowed key carries its own value schema.
Behaviour —
prepareUserSubmission's client-write gateBehaviour —
submissionDataSchema, the one boundsubmissionDataSchema({ type, formFields, checkContent }) src/collections/UserSubmissions/submissionData.ts per allowed key → valueSchemaFor(key, blockType, checkContent) length cap # VALUE_MAX_LENGTHS[key] ?? DEFAULT + blockType 'email' → checkEmailAllowed(value.trim(), key) # invalid_email | disposable_email + URL_EXEMPT_KEYS → no content check # a crash report names its page + everything else → checkNoUrls({ [key]: value }) # urls_not_allowed one superRefine walks the pairs # entry cap, missing/over-long/unknown key, duplicateBehaviour — the write guard's own refusals, for the same codes
Contract — what a client observes
docs/rules/api-clients.md§POST /api/user-submissions:Nothing else a client observes changed with the refactor: the same four codes, the same
field, and a malformed blob still reports every shape problem at once.Files — one fact, two owners, no new module
Formsrequires an email block at save time; the schema judges its answer at submit time. Both name theemailblock type where they use it, against the generated block union, so a plugin rename failstscat both sites. The sharedsrc/lib/submissions/formBlocks.tsthis branch first added was dropped in review (7b73dee);AuthoredBlock— the arms ofForm['fields']that name a field — is derived from the generated union instead, so there is still nothing to keep in sync.Preview
emailanswer as a pairContract impact
sydevs/SahajAtlasWebis the live consumer: its report-issue form sends the authored email answer as asubmissionDatapair (src/lib/report-form.ts), which is what #899 refused. Nothing to change there — that behaviour was already correct. No copied contract file moved, so no sync PR follows.errors[0].data.fieldis additive: a refusal readserrors[].data.code, and no consumer reads a key that was never sent.Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(2314 passed)user-submissions-create.int(35 passed)Each new assertion was seen red against the defect, reintroduced at the site that caused it:
valueSchemaFordrops itsemailarminvalid_email,disposable_email)checkEmailAllowedloop (pre-refactor)invalid_emailcasethrowFailuredropsfieldwrite-guard-error-shapecasesthrowFailure(result)without the policy-path overrideproposed#1forproposedFixture pre-mortem. The renamed-field form assumes a
formsdoc can carry anemailblock under an operator-chosen name alongside atextarea. Verified against the generatedFormunion insrc/payload-types.ts(theemailarm declares a requiredname) and againstvalidateFormAction, which requires a contact form to hold both block kinds.Manual verification
Against the preview, with a published client key:
POST /api/user-submissions—type: 'contact', the preview's contact form id,senderEmail: "[email protected]",submissionData: [{field:"email",value:"[email protected]"},{field:"message",value:"hello"}]→ 201.messageset tosee example.com→ 400urls_not_allowed,data.field: "message".emailpair set tosee example.com→ 400invalid_email,data.field: "email".senderEmailset tonot-an-address→ 400invalid_email,data.field: "senderEmail"— the guard's own refusal, which carried no field before.Steps 1–4 were run against the preview before the refactor commit. The refactor changes no response, but a re-run after it has not happened yet.
Notes for reviewer
The unification was asked for in review and lands here, in 5f1e72a, with #899's acceptance criteria expanded to match. Two deliberate limits on it:
submissionDatais a Payload array field, not a JSON column, so nojsonSchemacan gate it and Ajv never sees it. What the schema owns is each key's own rules; the walk over the pairs lives in onesuperRefineso a malformed blob still reports every problem at once.checkEmailAllowedandcheckNoUrlsstay the one definition of each check. The schema calls them per key rather than restating a format or a pattern, so the write guard and the screening jobs still agree with the intake.Two findings I did not fix here, each filed separately rather than widening this PR:
URL_PATTERN's bare-domain arm could be narrowed instead (a left lookbehind for@…), filed as fix(anti-spam): the URL pattern's bare-domain arm matches an email address #921. It does not make theemailarm unnecessary:[email protected]matches the bare-domain arm at offset 0 — in the local part, where a left lookbehind cannot reach — measured against the real pattern. The ticket chose to leave the pattern alone, and it is shared with the write guard, theusersname policy and the screening job, so it is its own change with its own review.ScreenSubmissions, wherescreenProposalContentwalks every string leaf ofproposedwith no exemption, so a proposal naming[email protected], awebsiteor anonlineUrlcan be given the terminalspamverdict. That one loses data silently, unlike fix(api): stop refusing a visitor's email answer as a URL #899's visible 400.Dismissed review findings:
textblock is still URL-scanned. True, and deliberate —text/textareais where the message body lives, so exempting it would disable the scan. Acceptance criterion 4 asks for block-type keying.createFormhelper. Five inline form creates predate this branch; refactoring them is not this PR's job, and a single-use helper buys nothing.Detail
Why the exemption and not the caller. Having the atlas send the address only as
senderEmailfixes one caller in one line, and leaves the next operator who adds an email question to the Contact Form broken again, silently — while losing the operator's view of the question they asked.Why this loses no protection. The exempted answer is not unchecked:
checkEmailAllowedruns zod's format check and mailchecker's disposable-domain list on it. That list is already resident on this request, because the write guard runs the same function onsenderEmail— so the new call site adds one regex test and a Set lookup, no I/O. It also reaches an answer the write-guard policy never covered:emailFieldsthere namessenderEmailandproposed.contactEmailalone.Why the check lives in the hook, not the write-guard policy. A policy path is a literal dotted string resolved against incoming
data, and no path spells "the pair whosefieldequals the form's email block name". Putting it there would mean aformsread inside the plugin'sbeforeValidateon every public write, or restating operator-chosen names in a const.policies.ts' ⚠ already explains this for the URL half; it now says the email half lives there too.Why the content checks are client-only.
checkContentisfromClient. A manager pasting a link into a triage note is not spam, and a manager's write is not a public write — the same split the hook had before, now one flag instead of anifaround two calls.No per-block-type dispatch table. Of the plugin's twelve block types, only
emailwants a different check:date,stateandcountrystore codes that trip no arm of the pattern, and a checkbox's value is non-string, which the value schema refuses as "must be text" before any content check.valueSchemaForis that one row and a default, rather than a table of eleven defaults.Why
disposable_emailis the newly reachable half. The format arm is what a link trips, so it is the one #899 is about. The disposable arm reaches an answer the guard never judged: its policy namessenderEmailandproposed.contactEmail, so an address a caller sends only as asubmissionDatapair had no disposable-domain check at the intake before this branch.Shape outranks content. A refused key's value was never meant to be judged, so
refuseraises everysubmission_data_invalidmessage joined before it looks at a content problem. That is the order the three walks produced, kept deliberately rather than inherited — issue order inside one pass would otherwise let a URL on the first pair outrank an unknown key on the second.Follow-up not filed as a ticket.
src/jobs/DeliverSubmissions/formAnswers.ts' docblock predicts its named-field walk moving tosrc/lib/submissions/"when the intake's scan classifier consumes the same walk". This branch is that classifier, and it shares only the block-type list, not the walk. Consolidating the three walks (formAnswers,validateFormAction, this hook) is a behaviour-free refactor across three owners — worth doing, worth its own PR, and your call whether you want one.Measurement behind the bug. Against the real pattern, 8 of 12 common providers were refused:
gmail.com,yahoo.com,hotmail.com,outlook.com,icloud.com,example.org,protonmail.com,gmx.net.co.uk,mail.ru,web.deandposteo.depassed, which is why the failure looked random from the outside.Review pass. No
pr-review-toolkitis available to a routine, so the pass was/simplify(four lenses) plus/code-review high.comment-lintis clean. The security review did not run:securityReview.triggerPatterndoes not match any changed path, the write-guard plugin included. The refactor commit has had no adversarial review pass of its own.Closes #899
🤖 Generated with Claude Code
https://claude.ai/code/session_01Dnp88uTfovjpmmswhugaT7