Repository navigation
fix(comments): verify Turnstile tokens server-side on comment submission - #1854
Conversation
The CommentForm widget rendered Turnstile and submitted its token, but the public POST endpoint never verified it — bots POSTing directly to the API bypassed the challenge entirely (emdash-cms#1589). When a Turnstile secret key is configured (EMDASH_TURNSTILE_SECRET_KEY or TURNSTILE_SECRET_KEY), the route now verifies the token against Cloudflare's siteverify API before persisting and rejects submissions without a valid token (fails closed on siteverify errors too). Without a configured secret the behavior is unchanged. Also resets the Turnstile widget after failed submissions so a retry gets a fresh single-use token.
🦋 Changeset detectedLatest commit: 27a852a The changes in this PR will be included in the next version bump. This PR includes changesets to release 16 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
There was a problem hiding this comment.
The approach is correct and fits EmDash: public comment submissions were indeed skipping Turnstile verification, and fixing that with an opt-in EMDASH_TURNSTILE_SECRET_KEY env var preserves backward compatibility for sites that only render the widget without a secret. The change is well-placed in the handler chain (after honeypot/rate-limit) and the fail-closed semantics are right for missing tokens, failed siteverify responses, and thrown fetch errors.
What I checked:
import.meta.env/process.envaccess matches the documented env-var fallback pattern.- IP forwarding uses
extractRequestMeta, which already consultsCF-Connecting-IP/ trusted proxy headers, soremoteipis forwarded only from trustworthy sources. - CSRF: the public comment route is covered by
checkPublicCsrf(Origin orX-EmDash-Request), and the form already sends the custom header. createCommentBodynow acceptsturnstileTokenwithout widening the persistence surface (the token is verified, not stored).- The changeset is present and names the published package (
emdash).
Headline conclusion: the fix is sound, but there are two functional gaps — no timeout on the siteverify subrequest, and the form doesn't reset Turnstile on network errors — plus a test case that doesn't exercise the IP-forwarding path the PR description claims to cover. These should be addressed before merging.
Findings
-
[needs fixing]
packages/core/src/comments/turnstile.ts:44-48The
fetchto Cloudflare siteverify has no timeout/abort signal. If the siteverify API is slow or unresponsive, the comment POST will hang until the runtime terminates it, rather than failing closed quickly as the PR intends. Add anAbortControllertimeout and clear it in afinallyblock.const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 10_000); try { const res = await fetch(SITEVERIFY_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), signal: controller.signal, }); const data: { success?: boolean; "error-codes"?: string[] } = await res.json(); if (!data.success) { console.warn("[comments] Turnstile verification failed:", data["error-codes"] ?? []); } return data.success === true; } catch (error) { console.error( "[comments] Turnstile siteverify request failed:", error instanceof Error ? error.message : error, ); return false; } finally { clearTimeout(timeoutId); } -
[needs fixing]
packages/core/src/components/CommentForm.astro:203The
catchblock handles network errors but does not reset Turnstile. The PR moved the reset before theres.okbranch so retries after HTTP failures get a fresh token, but afetchthat throws (offline, DNS failure, etc.) still leaves the same single-use token in the form. A retry may then send an already-used token and fail siteverify. Reset the widget in thecatchblock too.} catch { // Reset Turnstile on network errors too — the token may or may not // have been consumed, and the next attempt needs a fresh challenge if (typeof window.turnstile !== "undefined") { window.turnstile.reset(); } statusEl.textContent = "Network error. Please try again."; statusEl.classList.add("ec-comment-form-error"); } finally { -
[suggestion]
packages/core/tests/integration/astro/comments-turnstile.test.ts:127The passing-token test does not exercise the remote-IP forwarding path: the test request has no trusted proxy headers and no
cfobject, soextractRequestMetareturnsip: nulland the route never sendsremoteipto siteverify. The PR description claims "secret + token + remote IP reach siteverify", but only the first two are asserted. Add a dedicated test case that suppliestrustedProxyHeaders: ["x-forwarded-for"]inemdash.configand anX-Forwarded-Forheader on the request, then assert that the siteverify body includesremoteip.it("forwards the trusted remote IP to siteverify", async () => { vi.stubEnv("EMDASH_TURNSTILE_SECRET_KEY", "test-secret"); const fetchSpy = stubSiteverify(true); const request = new Request("http://localhost/_emdash/api/comments/post/post-1", { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.45", }, body: JSON.stringify({ ...VALID_BODY, turnstileToken: "valid-token" }), }); const ctx = buildContext(db, request); // eslint-disable-next-line typescript/no-unsafe-type-assertion (locals as typeof ctx.locals).emdash.config = { trustedProxyHeaders: ["x-forwarded-for"] }; const res = await postComment(ctx); expect(res.status).toBe(201); expect(fetchSpy).toHaveBeenCalledOnce(); // eslint-disable-next-line typescript/no-unsafe-type-assertion const [url, init] = fetchSpy.mock.calls[0] as unknown as [string, { body: string }]; expect(JSON.parse(init.body)).toMatchObject({ secret: "test-secret", response: "valid-token", remoteip: "203.0.113.45", }); });
… test IP forwarding Review follow-ups: abort the siteverify subrequest after 10s so a slow Cloudflare API fails closed instead of hanging the comment POST, move the widget reset into finally so network errors also produce a fresh single-use token, and add a test asserting the trusted remote IP is forwarded to siteverify.
|
All three review findings addressed in 27a852a:
All 6 tests green, lint 0 diagnostics, typecheck clean. |
What does this PR do?
The
CommentFormcomponent renders the Turnstile widget and submits its token asturnstileToken, but the publicPOST /_emdash/api/comments/:collection/:contentIdendpoint never verified it — a bot POSTing directly to the API bypassed Turnstile entirely. The widget was decorative.This PR adds server-side verification, opt-in via configuration (mirroring how the secret side of Turnstile has to be operator-provided):
EMDASH_TURNSTILE_SECRET_KEY(fallback:TURNSTILE_SECRET_KEY) is set, the comment route verifies the submitted token against Cloudflare's siteverify API before persisting, forwarding the trusted client IP when available.403 TURNSTILE_FAILED. The check runs after the free anti-spam checks (honeypot, rate limit) so obvious spam never triggers a siteverify subrequest.createCommentBodynow accepts theturnstileTokenfield the form was already sending (it was previously stripped by the schema).turnstileSiteKeyprop.New integration test covers: missing token rejected without a siteverify call, forged token rejected, valid token accepted (secret + token + remote IP reach siteverify), siteverify transport error fails closed, and no-secret backward compatibility.
Closes #1589
Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain. (n/a — no admin UI changes; server error messages are English-only by convention)AI-generated code disclosure
Screenshots / test output