Skip to content

fix(event): deliver report-issue submissions instead of alerting - #135

Merged
Ardnived merged 6 commits into
mainfrom
fix/report-form-delivery
Aug 8, 2026
Merged

Ardnived merged 6 commits into
mainfrom
fix/report-form-delivery

Conversation

@Ardnived

@Ardnived Ardnived commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Summary

  • The report-issue form validated, passed a real Turnstile challenge, then window.alert(JSON.stringify(payload)) and showed the localized "sent" confirmation. Nothing reached any server — while ERROR_POLICY routes viewers to this CTA as the designated last resort on server / config / unknown failures. It now POSTs to SahajCloud's shared POST /api/contact-admin (feat(api): add a captcha-gated contact-admin endpoint SahajCloud#602, merged in its PR #612).
  • The thank-you screen is now derived from mutation.isSuccess and nothing else. That matters more than the wiring: the endpoint answers 502 rather than a false 200 when the email itself fails, so a resolved, zod-parsed { ok: true } is the only thing that means delivered.
  • A failure keeps the typed message, says what happened, and carries [email protected] — this form is often reached because the network already failed, so it needs a route that still works.

The endpoint contract I implemented against

Read from SahajCloud's merged source (src/endpoints/contactAdmin.ts, src/endpoints/responseTypes.ts, src/payload.config.ts on main), not from issue #602 — the ticket left the path as "implementer's call" between a root endpoint and a collection one. It landed root-registered, so the path is /api/contact-admin.

Body { message 10..5000 trimmed, email? ≤254, subject? ≤200, turnstileToken ≤2048, context?: { path ≤500, hostUrl ≤500, locale ≤20, error ≤2000, userAgent ≤500 } }
Token In the body — the endpoint verifies it server-side against siteverify before doing any email work
Success { ok: true } (nothing persisted; the email is the deliverable)
Failures 403 + code: 'captcha_failed' (forged / expired / replayed), 500 verification unreachable, 502 email send failed, 400 validation, 403 auth (no code)

Deployment confirmed, not assumed: an unauthenticated POST to https://cloud.sydevelopers.com/api/contact-admin returns 403 ("not allowed to perform this action") where a bogus sibling path returns 404.

Changes

  • src/config/api/mutate.ts — contactAdmin beside createRegistration: same requestJson helper, zod-parsed response, and a ContactRefusedError carrying the endpoint's machine-readable code. Maps our ReportContext onto the endpoint's (pageUrl → hostUrl), drops client (the server derives the service name from the authenticated API key, so sending our cached copy would be a second, forgeable source for the same row), and clamps each context value to the endpoint's own bound — an over-long one is a 400 for the whole report, and the user agent is the realistic offender.
  • src/types/payload/contact-types.ts + package.json — SahajCloud's root responseTypes.ts is a different file from the Events one types:cms already syncs, so it gains a third curl. ContactAdminErrorCode is therefore typed from the contract: a pnpm types:cms that adds or renames a code fails the build at the consumer instead of silently degrading to the generic sentence.
  • src/hooks/use-turnstile.ts — additive reset(). A Turnstile token is single-use and the endpoint redeems it during verification, before it attempts the mail. So after a 502 the token in hand is already spent, and retrying with it would be refused as a replay for the life of the form. The form resets on every failure, not just the 403.
  • src/components/organisms/ReportIssueForm/ReportIssueForm.tsx — the mutation, the honest failure state, networkMode: 'always' (see below), Cancel disabled mid-flight.
  • Two new common keys across all ten locales.

Verification

  • Lint ✓ · Typecheck ✓ · Unit lane ✓ 845 tests / 77 files · Production build + pnpm size ✓ (check.sh --full)
  • /simplify, /code-review and /security-review all run; findings triaged below.
  • The new jsdom spec was falsified before being trusted: reintroducing the bug (submitted also true on isError) turns it red on 2 assertions.

What the reviews caught

The blocking one, flagged independently by both reviewers: React Query's default networkMode: 'online' pauses a mutation fired while the browser is offline — no request, no throw, no onError. On this form of all forms that made the honest failure state unreachable exactly when it is needed (a spinner that never resolves), and the paused mutation outlives the modal, so the client resumes it on reconnect — a viewer who gave up and sent a second report would have had both delivered. Fixed with networkMode: 'always'.

Also fixed: the response .parse() moved out of the request's catch in both mutations (a ZodError's .errors are { message, code }, the same shape a refusal body has, so schema drift was being re-cast as a server refusal carrying a zod issue code — and its spec asserted only .rejects.toThrow(), which passed either way); hasOwnProperty on the refusal-copy lookup (code is a cast over a z.string()); .max(254) on the email field so an over-long address fails inline instead of 400ing the whole report; Cancel disabled mid-flight; and the generic failure no longer says "please try again" while Send is inert awaiting a fresh challenge.

Dismissed: the barrel-vs-direct import of @/config/api (zero eager-graph delta — App.tsx already imports it statically — and it mirrors RegistrationForm); clamping message (the endpoint's bound is 5000, identical to REPORT_MESSAGE_MAX); the unreachable mutation.isPending submit guard (kept — the Button atom's disabled || isLoading makes it unreachable today, and a double-POST means two emails).

Security

The carry-forward from 368e1f7 is satisfied server-side, and I verified it rather than assuming it. ReportContext.error is the thrown message — attacker-influenceable, capped at 500 chars. SahajCloud's ContactAdminEmail.tsx renders it (and every context value) as a JSX child via React Email, with no dangerouslySetInnerHTML anywhere in ContactAdminEmail.tsx / EmailLayout.tsx / sendContactAdmin.ts — so it is escaped, not interpolated. Nothing on our side builds HTML or a URL from it; the only anchor is a literal mailto:, now carrying a comment so the next person to prefill ?body= reaches for encodeURIComponent.

Confirmed clean: the host-page redaction survives the mapping (hostPageUrl() sends origin+path, never href, so a host's own reset token or #access_token can't ride along); the Turnstile token stays in the body and is never logged or put in a query string; no cookie/storage read; the API key travels only as the Authorization header.

⚠️ Before this ships — two things outside this diff

  1. VITE_TURNSTILE_SITE_KEY must be the real production key. .env ships Cloudflare's always-passes test key by design. That cost nothing while submit was an alert; it now decides whether the captcha in front of an email sender is real. Two silent failure modes: both sides on test keys → the gate is a no-op relay; only one side → every report 403s and the only symptom is a sentence in the viewer's face. Confirm the Pages var and that SahajCloud's TURNSTILE_SECRET_KEY is its matching pair.
  2. Server-side abuse controls. Both gates on this endpoint are public by construction (the client API key is in the bundle, the site key is public), so no client-side control can bound it. Worth confirming SahajCloud has per-key/per-IP rate limiting and checks the hostname in the siteverify response, not just success.

Noted as a follow-up, not done here: context.error is free-form text and a browser-built message can itself embed a URL, re-introducing what hostPageUrl() strips. It is capped at 500 chars and already leaves via Sentry on the same path, so this diff isn't the first exit — but stripping absolute URLs in buildReportContext would close it. src/lib/report.ts is owned by a sibling ticket (#108), so I kept my change there to a stale-comment fix.

Manual verification still needed

The unit lane mocks at the SDK boundary, so no real POST has been made — the API keys in .env.local and demo.html were both found dead in earlier verification, and browser access is owned by a sibling this wave. A human should, once:

  1. Open the widget with a live API key, trigger the report modal (settings cog, or an error CTA), submit, and confirm an email arrives at [email protected] with Reply-To set and the details block populated (service, locale, path, host page, user agent).
  2. Confirm the host page's Origin passes assertClientOriginAllowed for that client — this is the one gate no local test can exercise.
  3. Submit with DevTools offline to see the failure alert rather than a hanging spinner.

Closes #103
Closes #80

🤖 Generated with Claude Code

Ardnived and others added 5 commits August 7, 2026 19:29
Wires SahajCloud's shared POST /api/contact-admin (sydevs/SahajCloud#602,
merged in its PR #612) into the data layer beside createRegistration: the
same requestJson helper, a zod-parsed { ok: true } response, and a
ContactRefusedError carrying the endpoint's machine-readable code so a
captcha rejection can be told apart from a server failure.

The endpoint's root responseTypes.ts is a DIFFERENT file from the Events one
`types:cms` already syncs, so the script gains a third curl and the union is
typed from the contract rather than hand-copied.

Refs #103, #80

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The form validated, passed a real Turnstile challenge, then
window.alert(JSON.stringify(payload)) and showed the localized "sent"
confirmation. Nothing reached any server — while ERROR_POLICY routes viewers
to this CTA as the last resort on server/config/unknown failures.

Submit now POSTs the real mutation, and the thank-you screen is derived from
`mutation.isSuccess` alone. That matters more than the wiring: the endpoint
answers 502 rather than a false 200 when the mail itself fails, so a resolved
promise is the only thing that means delivered.

A failure keeps the typed message, states what happened, and offers the
address the endpoint mails anyway — this form is often reached BECAUSE the
network already failed. The captcha resets on every failure, not just the
403: a Turnstile token is single-use and the endpoint redeems it during
verification, before it tries to send, so after a 502 the token in hand is
already spent and retrying it would be refused for the life of the form.

Closes #103
Closes #80

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- one generic `asRefusal` for both mutations instead of a helper, a wrapper
  and a hand-rolled copy of the wrapper — the next coded endpoint now has one
  spelling to inherit rather than whichever it lands beside
- useTurnstile tracks the widget id in the ref alone; the effect-local copy
  and the identity check in cleanup guarded a state `cancelled` already
  excludes
- the refusal copy goes through a total Record over the synced code union
  (as RegistrationForm does), so an ADDED code fails the build instead of
  silently taking the generic sentence
- corrected two comments that overclaimed: the clamp docblock (path/locale
  really are belt-and-braces; userAgent/error are the foreign input), and
  useTurnstile's useCallback rationale

Refs #103

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The blocking one: React Query's default networkMode PAUSES a mutation fired
while the browser is offline — no request, no throw, no onError. On this form
of all forms, that made the honest failure state unreachable exactly when it
is needed, leaving a spinner that never resolves; and the paused mutation
outlives the modal, so the client resumes it on reconnect and a viewer who
gave up and sent a second report gets both delivered. `networkMode: 'always'`.

Also:
- the zod parse of a response moves OUT of the request's catch in both
  mutations. A ZodError's `.errors` are `{ message, code }` — the same shape a
  refusal body has — so schema drift was being re-cast as a server refusal
  carrying a zod issue code. Its spec asserted only `.rejects.toThrow()`,
  which passed either way; it now pins the identity.
- Cancel is disabled mid-flight (as RegistrationForm does): closing during the
  POST unmounted the form, so the viewer never learned whether it arrived.
- the refusal-copy lookup uses hasOwnProperty: `code` is a cast over a
  z.string(), so a bare index walks Object.prototype.
- the email field carries the endpoint's own .max(254), so an over-long
  address fails inline instead of 400ing the whole report.
- the generic failure no longer says "please try again" while Send is inert
  awaiting a fresh challenge; it says try again once the check has refreshed.

And a jsdom spec for the join the SSR lane cannot reach: the story props
short-circuit both derivations, so the previous specs stayed green with the
bug restored. This one drives a real submit through a mocked SDK and covers
resolve, 502, captcha reset, and the 403 copy. Verified it fails when the
bug is reintroduced.

Refs #103

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- data-layer: the second mutation, why the Turnstile token is a BODY field,
  why the response parse sits outside the request's catch, and the two
  contract files (separate because they are separate upstream — a new root
  endpoint needs a new curl rather than appearing by magic)
- tests: the third jsdom spec, and the lesson it carries — a spec that can
  only reach a state through the door the STORY uses is covering the door
- environment + CLAUDE.md: VITE_TURNSTILE_SITE_KEY stopped being decorative
  the moment the form began delivering real mail

Refs #103

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Deploying sahajatlas-design with  Cloudflare Pages  Cloudflare Pages

Latest commit: 56c6b0d
Status: ✅  Deploy successful!
Preview URL: https://5d51ed06.sahajatlas-design.pages.dev
Branch Preview URL: https://fix-report-form-delivery.sahajatlas-design.pages.dev

View logs

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying sahajatlas with  Cloudflare Pages  Cloudflare Pages

Latest commit: 9326e3b
Status: ✅  Deploy successful!
Preview URL: https://6b78e192.sahajatlas.pages.dev
Branch Preview URL: https://fix-report-form-delivery.sahajatlas.pages.dev

View logs

One conflict, in .claude/rules/tests.md: this branch and #101 each added a
fourth jsdom spec to the same list, and both bumped its count to "Three".
Kept both entries, corrected the count to Four, and fixed #101's "least
optional of the three" to match. The ordinal in the report-form entry
still reads correctly — with sanitize.test.ts second, it is the third
cautionary tale.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Ardnived
Ardnived merged commit a2cf111 into main Aug 8, 2026
4 checks passed
@Ardnived
Ardnived deleted the fix/report-form-delivery branch August 8, 2026 04:00
Ardnived added a commit that referenced this pull request Aug 11, 2026
* fix(build): pin smoke discovery to the head commit's deploy

`pick()` gates the HOST, never which BUILD that host serves. Cloudflare
publishes two per project — the per-deployment alias and a stable branch
alias — and both cleared the gate, so the lane could go green having
smoke-tested the previous commit.

Candidates now carry provenance and are ranked: the deployment named by
our own check run for this SHA (its `details_url` ends in the deployment
UUID, whose first 8 chars ARE the alias) beats a deploy-shaped URL from a
per-SHA source, which beats a branch alias. A Cloudflare comment naming
some other commit is refused outright — that is the observed defect, not
a hypothetical: on PR #135 the comment still linked `9326e3b`'s deploy
while the head was `56c6b0d`.

Also wires `failure` through `main()`. It was computed in `discover()`
and dropped on the floor, so `timeoutStatus` never saw it and the
`failed` status — added by #132's code review precisely so a broken build
is not reported as a slow one — was unreachable in production while its
unit spec passed.

Closes #138

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

* test(build): pin URL provenance, and record the third smoke invariant

Eleven cases over `deploymentAlias` / `provenanceOf` / `pickPreview`,
built on PR #135's real data so the fixture names the defect rather than
paraphrasing it. The host gate is re-asserted at the strongest tier as
well as the weakest: ranking chooses AMONG urls `pick()` accepts and must
never reach past it.

tests.md gains the third invariant — a green Smoke check means the specs
ran against THIS commit — and loses #132's "known gap, deliberately still
open", whose precondition (does the check-run summary carry a per-commit
URL?) is now answered: yes, on all of #133-#137.

It also records why a passing unit spec did not stop `failed` being
unreachable: the defect was in the wiring, which no pure test can see.

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

* fix(build): close the gaps /security-review found

Three Low findings, all about the new attestation trusting something
self-declared:

- The deployment id was read from any check run admitted by NAME, and a
  name is self-declared. An installed App with `checks:write` could call
  itself "Cloudflare Pages: sahajatlas" and choose the `details_url` we
  derive the expected host from. It could never aim us off-host — pick()
  decides that — but it could steer selection between builds of our own
  site, which is the defect this ticket closes. Now gated on the app slug,
  matching source 1's "both the context AND the author".
- The bare project host is PRODUCTION, not a preview. It clears pick(),
  isn't deploy-shaped, and so sat on the `alias` floor beside a branch
  alias — but this script only runs for a PR head, so production is never
  the right answer. Refused outright.
- `includes(shortSha)` matched a 7-hex prefix anywhere, including inside a
  longer hex run, so a stale comment could be called "naming the head" on
  a coincidence. Now a whole-token match, built only from a real hex
  prefix so a bogus PR_HEAD_SHA degrades instead of throwing.

Also softens the tests.md headline, which promised more than the `alias`
floor delivers, and corrects the "exactly one run" comment: filter=latest
is one run per check NAME, which is unique per APP, not globally — which
is exactly why the slug gate matters.

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

* fix(build): close the gaps /code-review found

Two High, four Medium, three Low. The two that mattered most were both
things this PR had asserted and not checked:

- The summary DENIED the URL it had just refused. `refused` reached the
  poll log but never `main()`, so at timeout `absent` read "no check run,
  no deployment, no bot comment" while the line above named the URL we
  declined — and ci.yml routes `absent` to "INVESTIGATE, don't re-run". It
  now rides into `explain()`. It deliberately does NOT reach
  `timeoutStatus`: another commit's URL is not evidence that this one
  built, so it must not soften `absent` into "re-run".
- `\b<sha>\b` rejected every LONGER spelling of the same commit (`56c6b0d1`,
  the full 40 hex). Since that predicate now gates the URL harvest and not
  just the evidence, source 4 would have died wholesale the day Cloudflare
  printed one more digit. Only the left boundary is anchored now.

- Deploy-shape is read at BOTH scopes. Reading it only for per-SHA sources
  left one comment's two URLs indistinguishable, so Cloudflare's table
  order decided which won — this ticket's own defect, one level down. New
  `claimed` tier: below the check run, above a branch alias.
- The slug gate now guards every CONCLUSION drawn from a check run, not
  just `deployment`. An impostor could still set `failure`, and `failed`
  tells the reader "re-running cannot help" — a red check nobody can clear.
  URLs stay on the name-only path; `pick()` bounds those.
- The header's "the only URLs this refuses are X" was false four ways.
  Replaced with the enumeration, and the top-line "take the first we find"
  corrected. MEMORY.md warns about exactly this class of scope claim.
- `deploymentAlias` took the FIRST uuid while its doc said "ending in";
  the production-host refusal read a module-level slug instead of the
  passed host; the poll line dropped evidence whenever it had a refusal.

`waitingLine` is exported and specced, per the lesson this PR itself added
to tests.md — the wiring is where every one of these lived.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <[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.

fix(event): deliver report-issue submissions instead of alerting feat(widget): submit issue reports to the SahajCloud endpoint

1 participant