Skip to content

fix(comments): verify Turnstile tokens server-side on comment submission - #1854

Merged
ascorbic merged 2 commits into
emdash-cms:mainfrom
swissky:fix/comments-turnstile-verification
Jul 9, 2026
Merged

ascorbic merged 2 commits into
emdash-cms:mainfrom
swissky:fix/comments-turnstile-verification

Conversation

@swissky

@swissky swissky commented Jul 7, 2026

Copy link
Copy Markdown
Member

What does this PR do?

The CommentForm component renders the Turnstile widget and submits its token as turnstileToken, but the public POST /_emdash/api/comments/:collection/:contentId endpoint 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):

  • When 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.
  • Verification fails closed: a missing token, a failed verification, and a siteverify transport error all reject with 403 TURNSTILE_FAILED. The check runs after the free anti-spam checks (honeypot, rate limit) so obvious spam never triggers a siteverify subrequest.
  • Without a configured secret key the behavior is unchanged (backward compatible) — the token is ignored as before.
  • createCommentBody now accepts the turnstileToken field the form was already sending (it was previously stripped by the schema).
  • The form now resets the Turnstile widget after failed submissions too, not just successful ones — tokens are single-use, so a retry after a server rejection needs a fresh challenge.
  • Documents the new env var in the configuration reference and on the turnstileSiteKey prop.

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

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main. (n/a — no admin UI changes; server error messages are English-only by convention)
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: (n/a — bug fix)

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Cursor + Fable 5

Screenshots / test output

✓ tests/integration/astro/comments-turnstile.test.ts (5 tests)
  ✓ rejects a submission without a token when a secret is configured
  ✓ rejects a submission whose token fails siteverify
  ✓ accepts a submission whose token passes siteverify
  ✓ fails closed when siteverify itself errors
  ✓ ignores the token when no secret is configured (backward compatible)

Test Files  1 passed (1)
     Tests  5 passed (5)

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-bot

changeset-bot Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 27a852a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 16 packages
Name Type
emdash Patch
@emdash-cms/cloudflare Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/fixture-perf-site Patch
@emdash-cms/perf-demo-site Patch
@emdash-cms/cache-demo-site Patch
@emdash-cms/do-demo-site Patch
@emdash-cms/do-solo-demo-site Patch
@emdash-cms/admin Patch
@emdash-cms/auth Patch
@emdash-cms/blocks Patch
@emdash-cms/gutenberg-to-portable-text Patch
@emdash-cms/x402 Patch
create-emdash Patch
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

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

@pkg-pr-new

pkg-pr-new Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1854

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1854

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1854

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1854

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1854

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1854

emdash

npm i https://pkg.pr.new/emdash@1854

create-emdash

npm i https://pkg.pr.new/create-emdash@1854

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1854

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1854

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1854

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1854

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1854

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1854

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1854

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1854

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1854

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1854

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1854

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1854

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1854

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1854

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1854

commit: 27a852a

@emdashbot emdashbot Bot left a comment

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.

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.env access matches the documented env-var fallback pattern.
  • IP forwarding uses extractRequestMeta, which already consults CF-Connecting-IP / trusted proxy headers, so remoteip is forwarded only from trustworthy sources.
  • CSRF: the public comment route is covered by checkPublicCsrf (Origin or X-EmDash-Request), and the form already sends the custom header.
  • createCommentBody now accepts turnstileToken without 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-48

    The fetch to 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 an AbortController timeout and clear it in a finally block.

    	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:203

    The catch block handles network errors but does not reset Turnstile. The PR moved the reset before the res.ok branch so retries after HTTP failures get a fresh token, but a fetch that 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 the catch block 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:127

    The passing-token test does not exercise the remote-IP forwarding path: the test request has no trusted proxy headers and no cf object, so extractRequestMeta returns ip: null and the route never sends remoteip to siteverify. The PR description claims "secret + token + remote IP reach siteverify", but only the first two are asserted. Add a dedicated test case that supplies trustedProxyHeaders: ["x-forwarded-for"] in emdash.config and an X-Forwarded-For header on the request, then assert that the siteverify body includes remoteip.

    	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",
    		});
    	});
    

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jul 7, 2026
… 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.
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 7, 2026
@swissky

swissky commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

All three review findings addressed in 27a852a:

  • siteverify timeout: the subrequest now uses AbortSignal.timeout(10_000) (same pattern as the WordPress import fetchers), so a slow/unresponsive siteverify API fails closed quickly instead of hanging the comment POST until the runtime kills it.
  • Turnstile reset on network errors: the widget reset moved into the finally block, so thrown fetches (offline, DNS failure) also produce a fresh single-use token for the retry — not just HTTP-level failures.
  • IP-forwarding test: added a dedicated case that sets trustedProxyHeaders: ["x-forwarded-for"] on the config plus an X-Forwarded-For header on the request, and asserts the siteverify body includes remoteip: "203.0.113.45".

All 6 tests green, lint 0 diagnostics, typecheck clean.

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks!

@ascorbic
ascorbic merged commit e4e76f5 into emdash-cms:main Jul 9, 2026
45 checks passed
@emdashbot emdashbot Bot mentioned this pull request Jul 9, 2026
@swissky
swissky deleted the fix/comments-turnstile-verification branch September 10, 2026 06:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Comments: Turnstile widget is rendered but its token is never verified server-side

2 participants