Skip to content

feat(security): require Turnstile on event registration - #672

Merged
sydevs-bot merged 2 commits into
mainfrom
claude/fix-turnstile-on-registration
Sep 2, 2026
Merged

sydevs-bot merged 2 commits into
mainfrom
claude/fix-turnstile-on-registration

Conversation

@sydevs-bot

Copy link
Copy Markdown
Contributor

Summary

POST /api/events/:id/register was the last public write path without a captcha. Event submissions and user messages have required one since #625; this adds turnstile: true to the registrations create policy, so the write guard now demands a solved x-turnstile-token header on client-originated registration writes.

The core change is one line. The rest is the contract that has to ship with it.

⚠ This is a breaking change for any client not sending the header — which is why it waited. The Atlas widget began sending it in sydevs/SahajAtlasWeb#182, now merged and closed. Turning this on first would have refused every real registration; that ordering was the ticket's own instruction and is the reason #629 sat blocked.

The two refusals are different, and a client must treat them differently

Outcome Status errors[0].code What a client does
Missing, forged, expired or replayed token 403 captcha_failed Reset the challenge, retry with a freshly solved token
Our secret unset, or Cloudflare unreachable 500 captcha_unavailable Retry later — never a pass

Tokens are single-use, so Cloudflare's timeout-or-duplicate (a replay) is refused exactly like a forgery. A client that retries with the same token reads its second 403 as a persistent rejection — hence the explicit note in both the OpenAPI parameter description and the rule doc.

The 500 is deliberate and is never softened to a pass. A captcha gate that silently disables itself when its secret is missing is worse than no gate, because nothing surfaces the misconfiguration. verifyTurnstileToken already fails closed; this change simply puts registrations behind it.

A unit spec for the policy map, which nothing covered

DEFAULT_WRITE_GUARD_POLICIES is the public write surface, and no test pinned it before this PR. That matters more than for a normal config object, because the map fails open in one direction: an absent knob means "don't run that check". A dropped turnstile: true therefore does not break a build, fail a type-check, or throw at boot — it silently reopens a captcha-free public write path while the entire suite stays green.

tests/unit/write-guard-policies.spec.ts asserts every public create path requires Turnstile, and it goes red on exactly that removal.

Verification — the new assertions were made to fail before being kept

Per .claude/rules/tests.md, the defect was reintroduced at the site that would really cause it — reverting registrations.create to { urlScanFields: ['questions'] }:

Tests  1 failed | 4 passed (5)
  → tests/unit/write-guard-policies.spec.ts:24
     expect(DEFAULT_WRITE_GUARD_POLICIES[slug]?.create?.turnstile).toBe(true)
     Received: undefined

Restored, and green again. The spec also pins two things that are correctly absent, so a future reader does not "fix" them: the registration URL scan survives alongside the captcha (the captcha stops bulk automation, the URL scan stops a human typing a link into a free-text answer), and users.create deliberately carries no Turnstile — those rows are upserted by the register endpoint's own internal call, which has already passed the registrations gate, so requiring a token there would demand two solves for one registration.

Test results

  • lint ✓ · typecheck ✓ · typecheck:tests ✓
  • Unit ✓ 118 files / 1539 tests

⚠ The integration lane could not run locally — this sandbox has no PostgreSQL (DATABASE_URL unset, 127.0.0.1:5432 refused; the gap #663 tracks). CI is the first thing to execute the four new integration cases, and they are the ones that exercise the gate end to end rather than reading the config back. Worth a look at the CI result rather than the local gate above.

What changed, file by file
File Change
src/plugins/writeGuard/policies.ts turnstile: true on registrations.create. Module docblock updated — it previously said registrations "deliberately carry no turnstile yet", which is now false
src/plugins/openapi/customEndpoints.ts The x-turnstile-token header as a required parameter; 403 extended with captcha_failed; a new 500 documenting captcha_unavailable
tests/int/event-registration.int.spec.ts verifyTurnstileToken mocked; callRegister sends a valid token by default and takes a header override; four new cases — missing header, Cloudflare rejection, unverifiable, and that a refused captcha creates no registrant
tests/unit/write-guard-policies.spec.ts New — see above
docs/rules/api-clients.md New "Every public write path requires Turnstile" section under Security, with the refusal table
tests/COVERAGE.md Events row notes the captcha coverage

The register endpoint itself is unchanged: registerForEvent already surfaces APIError status and code verbatim, so the guard's refusal reaches the client correctly with no endpoint edit — as the ticket predicted.

What I did NOT verify

The ticket's closing note — "worth confirming the captcha doesn't measurably depress registration completion before making it permanent" — is a production-analytics question this PR cannot answer. Flagging it as still open rather than silently closed.

Closes #629

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


🤖 Generated with Claude Code

https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L


Generated by Claude Code

`POST /api/events/:id/register` was the last public write path without a
captcha. Event submissions and user messages have required one since #625;
this adds `turnstile: true` to the `registrations` create policy, so the
write guard now demands a solved `x-turnstile-token` header on
client-originated registration writes.

The ordering mattered and is why this waited: the flip is breaking for any
client not sending the header, so the Atlas widget had to send it first
(sydevs/SahajAtlasWeb#182, merged). Turning this on before that would have
refused every real registration.

Two refusals, deliberately distinct, both now documented on the endpoint:
403 `captcha_failed` for a missing, forged, expired or replayed token, which
a client retries with a freshly solved one; 500 `captcha_unavailable` when
our secret is unset or Cloudflare is unreachable. The second is never a pass
— a captcha gate that silently disables itself is worse than no gate,
because nothing surfaces the misconfiguration.

Adds a unit spec pinning the policy map, which nothing covered before. That
map fails OPEN in one direction: an absent knob means "skip that check", so
a dropped `turnstile: true` reopens a captcha-free public write path without
breaking a build, a type-check or any other test. The spec goes red on
exactly that removal.

Closes #629

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

railway-app Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

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

Service Status Web Updated (UTC)
SahajCloud ✅ Success (View Logs) Sep 1, 2026 at 9:14 pm
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-672 September 1, 2026 21:01 Destroyed
Three CI failures, three different causes, only one of which was a bad
test.

1. `client-origin-enforcement.int.spec.ts` calls the register endpoint
   directly and sent no token, so the new gate refused it with a 403 where
   it asserted 201. That spec is about origins, so it now mocks the
   verifier permanently valid and sends a token from `clientReq`.

2. My own "no `x-turnstile-token` header" case passed for the wrong reason
   and then failed for the right one. The mock returned success whatever it
   was handed, so the token's absence could not matter — the endpoint
   answered 201. The stub now mirrors siteverify: an empty token is
   `missing-input-response`, a rejection. This is the trap the repo's own
   rule warns about, arriving from the other direction — the assertion was
   sound and the fixture made it unfalsifiable.

3. "creates no registrant when the captcha is refused" was a wrong
   expectation about behaviour this PR does not own, and it found something
   worth keeping. `registerForEvent` upserts the `users` row and then
   creates the registration with no transaction around the pair, so a
   refused captcha stops the registration and leaves the user row. That is
   pre-existing — the `questions` validation 400 already did the same — and
   the fix is a transaction around both writes, which is a change to the
   endpoint's shape rather than a policy flip. Split in two: the captcha
   assertion now checks no REGISTRATION is created, and a second case
   documents the orphan row explicitly so the gap is recorded rather than
   asserted away.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01F2BczvDrd7opTwedpZHZ6L
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-672 September 1, 2026 21:11 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

CI went red on the first push; fixed in 14119b8. One of the three failures found a real gap that this PR does not close, and I want your view on whether it gets its own ticket.

The gap

registerForEvent upserts the registrant users row and then creates the registration, with no transaction around the pair. The write guard fires on registrations.create — so a refused captcha stops the registration and leaves the user row behind.

It is not caused by this change. Any late failure already did it: the questions validation 400 that has been in the suite all along leaves the same orphan. The captcha just makes it trivial to reach on purpose — an attacker with no valid token can still mint users rows one request at a time.

I did not fix it here. The fix is a transaction around both writes, which changes the endpoint's shape and does not belong in a one-line policy flip; and the obvious shortcut is wrong in a way worth writing down:

⚠ Do not add turnstile: true to users.create. The upsert forwards the same client req with the same header, so the token would be verified twice — and Cloudflare tokens are single-use. The second check would see timeout-or-duplicate and refuse every real registration.

The spec now records the behaviour instead of asserting it away, with a docblock saying to flip it when a transaction lands. Say the word and I'll file the ticket.

The other two failures, and the fixture trap behind one of them

client-origin-enforcement.int.spec.ts — mine to fix. It calls the register endpoint directly and sent no token, so the new gate refused it 403 where it asserted 201. That spec is about origins, so it now mocks the verifier permanently valid and sends a token from clientReq.

My own "no x-turnstile-token header" case passed for the wrong reason, then failed for the right one. The mock returned { success: true } whatever it was handed, so the token's absence could not matter — the endpoint answered 201. The stub now mirrors siteverify: an empty token is missing-input-response.

That is the repo's own "a spec is not finished until it has failed" rule arriving from the other direction. The assertion was sound; the fixture made it unfalsifiable. Locally it would have gone green and proved nothing — CI caught it only because a sibling spec broke.

Why local validation could not have caught any of this: this sandbox has no PostgreSQL (DATABASE_URL unset, 127.0.0.1:5432 refused — the gap #663 tracks), so the integration lane runs first on CI. The Tier-2 gate was green through all three failures, which is exactly what that lane is blind to.

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


Generated by Claude Code

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-672 — 14119b88 Deployed Sep 1, 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.

Require Turnstile on the event registration endpoint

3 participants