From 50d1c30ee282780656df5e86eef6d06a56563991 Mon Sep 17 00:00:00 2001
From: baron unread
Date: Sun, 11 Oct 2026 01:48:26 +0200
Subject: [PATCH 1/8] Replace Cap proof-of-work with Cloudflare Turnstile
(#304)
Drops capjs-core, the widget, the WASM solver, the /api/cap routes and
RL_CAP. Signup, password reset and the landing shortener now send a
Turnstile token in x-turnstile-token, verified against siteverify (action
bound to the form, fail closed). TURNSTILE_SECRET_KEY unset disables the
check; the site key is served by /api/config. CSP allows
challenges.cloudflare.com and loses wasm-unsafe-eval and blob workers.
Co-Authored-By: Claude Sonnet 5.5
---
.dev.vars.example | 14 +-
.dev.vars.playwright | 2 +-
.github/workflows/test.yml | 2 +-
AGENTS.md | 17 +-
THIRD_PARTY_LICENSES.md | 21 +-
bun.lock | 149 +-----------
docs/rate-limiting.md | 112 ++++-----
package.json | 3 -
prod.secrets.env.example | 8 +-
src/app/components/hero-shortener.tsx | 8 +-
src/app/lib/anon-links.ts | 4 +-
src/app/lib/cap.ts | 228 ------------------
src/app/lib/shorten-anon.ts | 8 +-
.../lib/{cap-retry.ts => turnstile-retry.ts} | 25 +-
src/app/lib/turnstile.ts | 148 ++++++++++++
src/app/routes/auth.tsx | 35 +--
src/shared/types.ts | 10 +-
src/worker/better-auth.ts | 20 +-
src/worker/cap-unused-dep-stub.ts | 15 --
src/worker/cap.ts | 176 --------------
src/worker/env.ts | 10 +-
src/worker/index.ts | 15 +-
src/worker/rate-limit.ts | 14 +-
src/worker/routes/auth.ts | 1 +
src/worker/routes/cap.ts | 60 -----
src/worker/routes/shorten.ts | 15 +-
src/worker/security-headers.ts | 23 +-
src/worker/turnstile.ts | 65 +++++
tests/cap-loader.test.ts | 144 -----------
tests/e2e/production/csp.pw.ts | 65 +++--
tests/e2e/qr-generator.pw.ts | 14 +-
...-retry.test.ts => turnstile-retry.test.ts} | 43 ++--
tests/worker/cap-disabled.worker.ts | 65 -----
tests/worker/cap-rate-limit.worker.ts | 100 --------
tests/worker/cap.worker.ts | 219 -----------------
tests/worker/no-email-signup.worker.ts | 2 +-
tests/worker/support.ts | 18 +-
tests/worker/turnstile-disabled.worker.ts | 32 +++
tests/worker/turnstile.worker.ts | 112 +++++++++
vite.config.ts | 8 -
wrangler.jsonc | 36 +--
41 files changed, 581 insertions(+), 1485 deletions(-)
delete mode 100644 src/app/lib/cap.ts
rename src/app/lib/{cap-retry.ts => turnstile-retry.ts} (66%)
create mode 100644 src/app/lib/turnstile.ts
delete mode 100644 src/worker/cap-unused-dep-stub.ts
delete mode 100644 src/worker/cap.ts
delete mode 100644 src/worker/routes/cap.ts
create mode 100644 src/worker/turnstile.ts
delete mode 100644 tests/cap-loader.test.ts
rename tests/{cap-retry.test.ts => turnstile-retry.test.ts} (58%)
delete mode 100644 tests/worker/cap-disabled.worker.ts
delete mode 100644 tests/worker/cap-rate-limit.worker.ts
delete mode 100644 tests/worker/cap.worker.ts
create mode 100644 tests/worker/turnstile-disabled.worker.ts
create mode 100644 tests/worker/turnstile.worker.ts
diff --git a/.dev.vars.example b/.dev.vars.example
index 641c1ca7..8481f327 100644
--- a/.dev.vars.example
+++ b/.dev.vars.example
@@ -34,13 +34,13 @@ SENTRY_DSN=
# proxies to it. Leave blank to skip the proxy.
BLOG_ORIGIN_URL=http://localhost:3000
-# Cap proof-of-work (#98). In production this is `openssl rand -hex 32`; the
-# fixed value here is deliberate, so the real challenge/solve/redeem loop runs
-# instead of the disabled path. Note .dev.vars.playwright sets its own: that
-# is the file the browser suite reads, and a value only here would leave every
-# e2e signup on the disabled path. The disabled path has its own worker test,
-# which needs no browser to prove it.
-CAP_SECRET=dev-only-cap-secret-not-a-real-one-0000000000000000
+# Cloudflare Turnstile (#304). These are Cloudflare's published test keys
+# (always pass), so the real widget and verify loop run locally with no
+# account. In production, create a widget in the Cloudflare dashboard and set
+# TURNSTILE_SITE_KEY as a var in wrangler.jsonc and TURNSTILE_SECRET_KEY as a
+# secret. Leave the secret blank to turn the check off.
+TURNSTILE_SITE_KEY=1x00000000000000000000AA
+TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA
# Google sign-in. Leave all three blank to hide the "Continue with Google"
# button. For local dev, `bun run dev` starts the emulate google service
diff --git a/.dev.vars.playwright b/.dev.vars.playwright
index ecd97843..4a277217 100644
--- a/.dev.vars.playwright
+++ b/.dev.vars.playwright
@@ -24,7 +24,7 @@ CF_DEV_ENV=instant
# the file the browser suite actually reads: CLOUDFLARE_ENV=playwright makes
# wrangler prefer it, so a secret only in .dev.vars leaves every e2e signup
# running the disabled path while looking like it covers the real one.
-CAP_SECRET=playwright-only-cap-secret-32-chars-min
+TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA
# Google sign-in. The local emulate google service, started by the resend
# webServer in playwright.config.ts (resend on 4000, google on 4001).
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 57d462e4..d48d2eae 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -67,7 +67,7 @@ jobs:
key: node_modules-${{ runner.os }}-${{ hashFiles('bun.lock') }}
- name: Install dependencies
run: bun install --frozen-lockfile
- # Worker tests read secrets (BETTER_AUTH_SECRET, CAP_SECRET, ...) out of
+ # Worker tests read secrets (BETTER_AUTH_SECRET, TURNSTILE_SECRET_KEY, ...) out of
# the ambient miniflare env, which wrangler builds from .dev.vars. Without
# it those bindings are empty, so auth/rate-limit code 500s instead of
# behaving: same reason the old single-job workflow copied this before
diff --git a/AGENTS.md b/AGENTS.md
index 371fc130..7f092e10 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -210,13 +210,14 @@ analyticsDays }`). Slugs on the **shared** domain are always random (every
one left ownerless would have no plan, no billing and nobody who could
delete it. Settings names each org in the confirmation first. Orgs the
account only belongs to are untouched.
-- **Bot protection**: Cap proof-of-work (`src/worker/cap.ts`, routes at
- `/api/cap/:scope/{challenge,redeem}`) guards signup and password reset. The
- token rides in an `x-cap-token` header and is spent in `hooks.before`. No
- third party sees the visitor: `capjs-core` runs in this Worker, the widget
- is bundled from npm, and the WASM solver is a same-origin Vite asset. Unset
- `CAP_SECRET` disables it. See `docs/rate-limiting.md` for all three layers
- (WAF rules, Workers limiters, Cap) and the dashboard rules to apply by hand.
+- **Bot protection**: Cloudflare Turnstile (`src/worker/turnstile.ts`) guards
+ signup, password reset and the landing shortener. The token rides in an
+ `x-turnstile-token` header and is verified against `siteverify` in
+ `hooks.before`. The one third party that sees the visitor is Cloudflare,
+ via `challenges.cloudflare.com` (allowed in the CSP). `TURNSTILE_SITE_KEY`
+ is a var served by `/api/config`; unset `TURNSTILE_SECRET_KEY` disables the
+ check. See `docs/rate-limiting.md` for all three layers (WAF rules, Workers
+ limiters, Turnstile) and the dashboard rules to apply by hand.
- **KV keys**: `slug:{slug}` (shared host), `slug:{host}:{slug}` (custom domain),
`domain:{host}`. D1 is authoritative; KV is the redirect hot path. Clicks are
recorded via `waitUntil` after the redirect is sent, and store only
@@ -289,7 +290,7 @@ and vars live in `wrangler.jsonc`; local dev reads everything from `.dev.vars`
`BETTER_AUTH_SECRET`, `SUPERADMIN_EMAIL`, `RESEND_API_KEY`, `MAIL_FROM`,
`APP_URL`, `APP_HOST`, `POLAR_ACCESS_TOKEN`/`POLAR_WEBHOOK_SECRET`/
`POLAR_PRO_PRODUCT_ID`/`POLAR_HOBBY_PRODUCT_ID`, `CF_API_TOKEN`/`CF_ZONE_ID`,
-`SENTRY_DSN`.
+`TURNSTILE_SITE_KEY`/`TURNSTILE_SECRET_KEY`, `SENTRY_DSN`.
## Layout
diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md
index 3b7e6a59..c985a6f0 100644
--- a/THIRD_PARTY_LICENSES.md
+++ b/THIRD_PARTY_LICENSES.md
@@ -170,28 +170,9 @@ SOFTWARE.
## Apache License 2.0
-`@cap.js/wasm`, `@cap.js/widget`, `capjs-core`, `drizzle-orm`, `posthog-js`
+`drizzle-orm`, `posthog-js`
(dual Apache-2.0/MIT; see below for the vendored MIT-licensed portions)
-### @cap.js/wasm, @cap.js/widget, capjs-core
-
-```text
-Copyright 2025 Tiago
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License. (Full Apache License 2.0 text below, under
-drizzle-orm.)
-```
-
### drizzle-orm
```
diff --git a/bun.lock b/bun.lock
index 131dc04b..16164a44 100644
--- a/bun.lock
+++ b/bun.lock
@@ -9,8 +9,6 @@
"@better-auth/cimd": "1.7.6",
"@better-auth/mcp": "1.7.6",
"@better-auth/oauth-provider": "1.7.6",
- "@cap.js/wasm": "^0.0.8",
- "@cap.js/widget": "^0.1.58",
"@fontsource-variable/figtree": "^5.3.0",
"@fontsource/jetbrains-mono": "^5.3.0",
"@hono/mcp": "^0.3.2",
@@ -28,7 +26,6 @@
"blobatar": "^2.7.0",
"browser-image-compression": "^2.0.2",
"canvas-confetti": "^1.9.4",
- "capjs-core": "0.1.3",
"cmdk": "^1.1.1",
"cn": "0.4.0",
"d3-geo": "^3.1.1",
@@ -163,10 +160,6 @@
"@better-fetch/fetch": ["@better-fetch/fetch@1.3.2", "", {}, "sha512-Gs7n99b5tqUC6cQAPbV0uED3IraHB6xQbHLQ/C3l7ZFafHScOx9pQ+DYmP5blbLFShVWLqxNUlI9wi4xU/X+ow=="],
- "@cap.js/wasm": ["@cap.js/wasm@0.0.8", "", {}, "sha512-rX+4/v2sz4GKLnygXHOS89O7c4GM2qNQcDJP6Y2cyGwoKjg83bsfWHt1TWr9GBzHpFADvju5fvLWYds21nS8sA=="],
-
- "@cap.js/widget": ["@cap.js/widget@0.1.58", "", {}, "sha512-snNjlYZLx1XddDH7DPZF9uedynSXTPPeRl/nExDlMjw0pCHiu/Fm1NKjRcT4HmqpOBf0TZRvio1HhkTMWg9p9A=="],
-
"@clack/core": ["@clack/core@1.5.1", "", { "dependencies": { "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ=="],
"@clack/prompts": ["@clack/prompts@1.8.1", "", { "dependencies": { "@clack/core": "1.5.1", "fast-string-width": "^3.0.2", "fast-wrap-ansi": "^0.2.0", "sisteransi": "^1.0.5" } }, "sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ=="],
@@ -375,16 +368,6 @@
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.4", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="],
- "@inversifyjs/common": ["@inversifyjs/common@1.3.3", "", {}, "sha512-ZH0wrgaJwIo3s9gMCDM2wZoxqrJ6gB97jWXncROfYdqZJv8f3EkqT57faZqN5OTeHWgtziQ6F6g3L8rCvGceCw=="],
-
- "@inversifyjs/core": ["@inversifyjs/core@1.3.4", "", { "dependencies": { "@inversifyjs/common": "1.3.3", "@inversifyjs/reflect-metadata-utils": "0.2.3" } }, "sha512-gCCmA4BdbHEFwvVZ2elWgHuXZWk6AOu/1frxsS+2fWhjEk2c/IhtypLo5ytSUie1BCiT6i9qnEo4bruBomQsAA=="],
-
- "@inversifyjs/reflect-metadata-utils": ["@inversifyjs/reflect-metadata-utils@0.2.3", "", { "peerDependencies": { "reflect-metadata": "0.2.2" } }, "sha512-d3D0o9TeSlvaGM2I24wcNw/Aj3rc4OYvHXOKDC09YEph5fMMiKd6fq1VTQd9tOkDNWvVbw+cnt45Wy9P/t5Lvw=="],
-
- "@javascript-obfuscator/escodegen": ["@javascript-obfuscator/escodegen@2.3.1", "", { "dependencies": { "@javascript-obfuscator/estraverse": "^5.3.0", "esprima": "^4.0.1", "esutils": "^2.0.2", "optionator": "^0.8.1" }, "optionalDependencies": { "source-map": "~0.6.1" } }, "sha512-Z0HEAVwwafOume+6LFXirAVZeuEMKWuPzpFbQhCEU9++BMz0IwEa9bmedJ+rMn/IlXRBID9j3gQ0XYAa6jM10g=="],
-
- "@javascript-obfuscator/estraverse": ["@javascript-obfuscator/estraverse@5.4.0", "", {}, "sha512-CZFX7UZVN9VopGbjTx4UXaXsi9ewoM1buL0kY7j1ftYdSs7p2spv9opxFjHlQ/QGTgh4UqufYqJJ0WKLml7b6w=="],
-
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -773,8 +756,6 @@
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
- "@types/minimatch": ["@types/minimatch@3.0.5", "", {}, "sha512-Klz949h02Gz2uZCMGwDUSDS1YBlTdDDgbWHi+81l29tQALUtvz4rAYi5uoVhE5Lagoq6DeqAUlbrHvW/mXDgdQ=="],
-
"@types/node": ["@types/node@26.6.3", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg=="],
"@types/qrcode": ["@types/qrcode@1.5.6", "", { "dependencies": { "@types/node": "*" } }, "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw=="],
@@ -789,8 +770,6 @@
"@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
- "@types/validator": ["@types/validator@13.15.10", "", {}, "sha512-T8L6i7wCuyoK8A/ZeLYt1+q0ty3Zb9+qbSSvrIVitzT3YjZqkTZ40IbRsPanlB4h1QB3JVL1SYCdR6ngtFYcuA=="],
-
"@typescript-eslint/types": ["@typescript-eslint/types@8.64.0", "", {}, "sha512-qjhfuTfLXjA4IOzXvz0rTjT01BqEiIgPoUeMwiEjnaHKJMTNo8rH5pYW1a2L/0Dnux2fPC85AeyJoWaGa8WxTA=="],
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
@@ -851,7 +830,7 @@
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
- "acorn": ["acorn@8.15.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg=="],
+ "acorn": ["acorn@8.17.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="],
"acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
@@ -867,22 +846,12 @@
"aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
- "array-differ": ["array-differ@3.0.0", "", {}, "sha512-THtfYS6KtME/yIAhKjZ2ul7XI96lQGHRputJQHO80LAWQnuGP4iCIN8vdMRboGbIEYBwU33q8Tch1os2+X0kMg=="],
-
- "array-union": ["array-union@2.1.0", "", {}, "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw=="],
-
- "arrify": ["arrify@2.0.1", "", {}, "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug=="],
-
- "assert": ["assert@2.1.0", "", { "dependencies": { "call-bind": "^1.0.2", "is-nan": "^1.3.2", "object-is": "^1.1.5", "object.assign": "^4.1.4", "util": "^0.12.5" } }, "sha512-eLHpSK/Y4nhMJ07gDaAzoX/XAKS8PSaojml3M0DM4JpV1LAi5JOJ/p6H/XWrl8L+DzVEvVCW1z3vWAaB9oTsQw=="],
-
"assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],
"astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="],
"atomically": ["atomically@2.1.1", "", { "dependencies": { "stubborn-fs": "^2.0.0", "when-exit": "^2.1.4" } }, "sha512-P4w9o2dqARji6P7MHprklbfiArZAWvo07yW7qs3pdljb3BWr12FIB7W+p0zJiuiVsUpRO0iZn1kFFcpPegg0tQ=="],
- "available-typed-arrays": ["available-typed-arrays@1.0.7", "", { "dependencies": { "possible-typed-array-names": "^1.0.0" } }, "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ=="],
-
"balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.43", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-AjYpR78kDWAY3Efj+cDTFH9t9SCoL7OoTp1BOb0mQV7S+6CiLwnWM3FyxhJtdPufDFKzmCSFoUncKjWgJEZTCQ=="],
@@ -913,8 +882,6 @@
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
- "call-bind": ["call-bind@1.0.9", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "get-intrinsic": "^1.3.0", "set-function-length": "^1.2.2" } }, "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ=="],
-
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
@@ -925,24 +892,12 @@
"canvas-confetti": ["canvas-confetti@1.9.4", "", {}, "sha512-yxQbJkAVrFXWNbTUjPqjF7G+g6pDotOUHGbkZq2NELZUMDpiJ85rIEazVb8GTaAptNW2miJAXbs1BtioA251Pw=="],
- "capjs-core": ["capjs-core@0.1.3", "", { "dependencies": { "esbuild": "^0.28.0" }, "optionalDependencies": { "javascript-obfuscator": "^4.2.2" } }, "sha512-ys5ZYtLDFkKqGJZUG237sOcCrbaDb2bCjp3f6mP484fLU195bMcn6aD6P3BmxLAIYK1dHJltLggEfgsMvVzhMQ=="],
-
"chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],
- "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
-
- "chance": ["chance@1.1.13", "", {}, "sha512-V6lQCljcLznE7tUYUM9EOAnnKXbctE6j/rdQkYOHIWbfGQbrzTsAXNW9CdU5XCo4ArXQCj/rb6HgxPlmGJcaUg=="],
-
- "char-regex": ["char-regex@1.0.2", "", {}, "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw=="],
-
- "charenc": ["charenc@0.0.2", "", {}, "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA=="],
-
"citty": ["citty@0.2.2", "", {}, "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w=="],
"cjs-module-lexer": ["cjs-module-lexer@1.2.3", "", {}, "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ=="],
- "class-validator": ["class-validator@0.14.3", "", { "dependencies": { "@types/validator": "^13.15.3", "libphonenumber-js": "^1.11.1", "validator": "^13.15.20" } }, "sha512-rXXekcjofVN1LTOSw+u4u9WXVEUvNBVjORW154q/IdmYWy1nMbOU9aNtZB0t8m+FJQ9q91jlr2f9CwwUFdFMRA=="],
-
"cliui": ["cliui@6.0.0", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="],
"cmdk": ["cmdk@1.1.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="],
@@ -955,8 +910,6 @@
"commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
- "concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
-
"conf": ["conf@15.1.0", "", { "dependencies": { "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "atomically": "^2.0.3", "debounce-fn": "^6.0.0", "dot-prop": "^10.0.0", "env-paths": "^3.0.0", "json-schema-typed": "^8.0.1", "semver": "^7.7.2", "uint8array-extras": "^1.5.0" } }, "sha512-Uy5YN9KEu0WWDaZAVJ5FAmZoaJt9rdK6kH+utItPyGsCqCgaTKkrmZx3zoE0/3q6S3bcp3Ihkk+ZqPxWxFK5og=="],
"confbox": ["confbox@0.2.4", "", {}, "sha512-ysOGlgTFbN2/Y6Cg3Iye8YKulHw+R2fNXHrgSmXISQdMnomY6eNDprVdW9R5xBguEqI954+S6709UyiO7B+6OQ=="],
@@ -979,8 +932,6 @@
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
- "crypt": ["crypt@0.0.2", "", {}, "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow=="],
-
"css-select": ["css-select@6.0.0", "", { "dependencies": { "boolbase": "^1.0.0", "css-what": "^7.0.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "nth-check": "^2.1.1" } }, "sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw=="],
"css-tree": ["css-tree@3.2.1", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="],
@@ -1049,10 +1000,6 @@
"deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
- "define-data-property": ["define-data-property@1.1.4", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
-
- "define-properties": ["define-properties@1.2.1", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
-
"defu": ["defu@6.1.7", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="],
"delaunator": ["delaunator@5.1.0", "", { "dependencies": { "robust-predicates": "^3.0.2" } }, "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ=="],
@@ -1125,8 +1072,6 @@
"espree": ["espree@11.2.0", "", { "dependencies": { "acorn": "^8.16.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^5.0.1" } }, "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw=="],
- "esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="],
-
"esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="],
"esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
@@ -1185,8 +1130,6 @@
"flatted": ["flatted@3.4.2", "", {}, "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA=="],
- "for-each": ["for-each@0.3.5", "", { "dependencies": { "is-callable": "^1.2.7" } }, "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg=="],
-
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"framer-motion": ["framer-motion@13.4.4", "", { "dependencies": { "motion-dom": "^13.4.4", "motion-utils": "^13.3.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-lbsZO95NGbulo6apz70zEt6Vxf/anoRwQI2ECEc/EQYWO5CGbITtl7plDW8P/VXgXw6e8wrbhH4a9i+ygke0Mg=="],
@@ -1197,8 +1140,6 @@
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
- "generator-function": ["generator-function@2.0.1", "", {}, "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g=="],
-
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
@@ -1217,14 +1158,8 @@
"graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
- "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
-
- "has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
-
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
- "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="],
-
"hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
"hermes-estree": ["hermes-estree@0.25.1", "", {}, "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw=="],
@@ -1249,34 +1184,18 @@
"internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
- "inversify": ["inversify@6.1.4", "", { "dependencies": { "@inversifyjs/common": "1.3.3", "@inversifyjs/core": "1.3.4" } }, "sha512-PbxrZH/gTa1fpPEEGAjJQzK8tKMIp5gRg6EFNJlCtzUcycuNdmhv3uk5P8Itm/RIjgHJO16oQRLo9IHzQN51bA=="],
-
"ip-address": ["ip-address@10.7.2", "", {}, "sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
- "is-arguments": ["is-arguments@1.2.0", "", { "dependencies": { "call-bound": "^1.0.2", "has-tostringtag": "^1.0.2" } }, "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA=="],
-
- "is-buffer": ["is-buffer@1.1.6", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="],
-
- "is-callable": ["is-callable@1.2.7", "", {}, "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA=="],
-
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
- "is-generator-function": ["is-generator-function@1.1.2", "", { "dependencies": { "call-bound": "^1.0.4", "generator-function": "^2.0.0", "get-proto": "^1.0.1", "has-tostringtag": "^1.0.2", "safe-regex-test": "^1.1.0" } }, "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA=="],
-
"is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
- "is-nan": ["is-nan@1.3.2", "", { "dependencies": { "call-bind": "^1.0.0", "define-properties": "^1.1.3" } }, "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w=="],
-
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
- "is-regex": ["is-regex@1.2.1", "", { "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g=="],
-
- "is-typed-array": ["is-typed-array@1.1.15", "", { "dependencies": { "which-typed-array": "^1.1.16" } }, "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ=="],
-
"is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="],
"isbot": ["isbot@5.2.1", "", {}, "sha512-dJ+LpKyClQZ7NG+j3OensC/mAZkGpukE9YUrgPYvAZj2doVL0edfDgywTUh5CXa0o+nW9a1V9e5+CJTX8+SxRw=="],
@@ -1285,14 +1204,10 @@
"iso-3166-1": ["iso-3166-1@2.1.1", "", {}, "sha512-RZxXf8cw5Y8LyHZIwIRvKw8sWTIHh2/txBT+ehO0QroesVfnz3JNFFX4i/OC/Yuv2bDIVYrHna5PMvjtpefq5w=="],
- "javascript-obfuscator": ["javascript-obfuscator@4.2.2", "", { "dependencies": { "@javascript-obfuscator/escodegen": "2.3.1", "@javascript-obfuscator/estraverse": "5.4.0", "acorn": "8.15.0", "assert": "2.1.0", "chalk": "4.1.2", "chance": "1.1.13", "class-validator": "0.14.3", "commander": "12.1.0", "conf": "15.0.2", "eslint-scope": "8.4.0", "eslint-visitor-keys": "4.2.1", "fast-deep-equal": "3.1.3", "inversify": "6.1.4", "js-string-escape": "1.0.1", "md5": "2.3.0", "mkdirp": "3.0.1", "multimatch": "5.0.0", "process": "0.11.10", "reflect-metadata": "0.2.2", "source-map-support": "0.5.21", "string-template": "1.0.0", "stringz": "2.1.0", "tslib": "2.8.1" }, "bin": { "javascript-obfuscator": "bin/javascript-obfuscator" } }, "sha512-+7oXAUnFCA6vS0omIGHcWpSr67dUBIF7FKGYSXyzxShSLqM6LBgdugWKFl0XrYtGWyJMGfQR5F4LL85iCefkRA=="],
-
"jiti": ["jiti@2.7.0", "", { "bin": "lib/jiti-cli.mjs" }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
"jose": ["jose@6.2.12", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="],
- "js-string-escape": ["js-string-escape@1.0.1", "", {}, "sha512-Smw4xcfIQ5LVjAOuJCvN/zIodzA/BBSsluuoSykP+lUvScIi4U6RJLfwHet5cxFnCswUjISV8oAXaqaJDY3chg=="],
-
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
@@ -1341,8 +1256,6 @@
"levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
- "libphonenumber-js": ["libphonenumber-js@1.13.10", "", {}, "sha512-xJxrdqvbl2rtn2MaUJrUejz8J7/uZNC0V77oks2LxYrO/+ZtVpRmz+fEQMuu6VusnEB1fmpByiLS1WXecOnAnw=="],
-
"lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
@@ -1379,8 +1292,6 @@
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
- "md5": ["md5@2.3.0", "", { "dependencies": { "charenc": "0.0.2", "crypt": "0.0.2", "is-buffer": "~1.1.6" } }, "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g=="],
-
"mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="],
"media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="],
@@ -1399,8 +1310,6 @@
"minimatch": ["minimatch@10.2.5", "", { "dependencies": { "brace-expansion": "^5.0.5" } }, "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg=="],
- "mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
-
"module-details-from-path": ["module-details-from-path@1.0.4", "", {}, "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w=="],
"morphicons": ["morphicons@1.7.1", "", { "peerDependencies": { "react": ">=18", "react-native": ">=0.71", "react-native-svg": ">=14", "svelte": ">=5", "vue": ">=3.3" }, "optionalPeers": ["react", "react-native", "react-native-svg", "svelte", "vue"] }, "sha512-q5ylxy5/d7vBg0OAzanlooXf05PekovMYDuuQVpr6vAQZxl99lrJbaIi+jJ32PXQf9WEEaDO2pbNBsx1ZhEnFQ=="],
@@ -1413,8 +1322,6 @@
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
- "multimatch": ["multimatch@5.0.0", "", { "dependencies": { "@types/minimatch": "^3.0.3", "array-differ": "^3.0.0", "array-union": "^2.1.0", "arrify": "^2.0.1", "minimatch": "^3.0.4" } }, "sha512-ypMKuglUrZUD99Tk2bUQ+xNQj43lPEfAeX2o9cTteAmShXy2VHDJpuwu1o0xqoKCt9jLVAvwyFKdLTPXKAfJyA=="],
-
"nanoid": ["nanoid@3.3.18", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="],
"nanostores": ["nanostores@1.4.0", "", {}, "sha512-i0tloweeudshAEuddpDxcg9Ik6pkPfVsHIgKyf143JrgG7/MOh0+q7BypdLXZPoOP7fOYt1eTcwGkyiVmhJFkA=="],
@@ -1433,12 +1340,6 @@
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
- "object-is": ["object-is@1.1.6", "", { "dependencies": { "call-bind": "^1.0.7", "define-properties": "^1.2.1" } }, "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q=="],
-
- "object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
-
- "object.assign": ["object.assign@4.1.7", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0", "has-symbols": "^1.1.0", "object-keys": "^1.1.1" } }, "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw=="],
-
"obug": ["obug@2.1.4", "", {}, "sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
@@ -1487,8 +1388,6 @@
"portless": ["portless@0.15.6", "", { "os": [ "linux", "win32", "darwin", ], "bin": { "portless": "dist/cli.js" } }, "sha512-uOAwWLF32rmyEGFASzSO0VOaqb/AQxFCCzyZbPGd82UNNOfIEvc09zy92nroNibE5HNfzV4oVB0ObKbPXgkM9A=="],
- "possible-typed-array-names": ["possible-typed-array-names@1.1.0", "", {}, "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg=="],
-
"postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="],
"posthog-js": ["posthog-js@1.434.15", "", { "dependencies": { "@posthog/browser-common": "^0.9.0", "@posthog/core": "^1.55.2", "@posthog/types": "^1.412.4", "core-js": "^3.49.0", "dompurify": "^3.4.13", "fflate": "^0.4.8", "preact": "^10.29.3", "query-selector-shadow-dom": "^1.0.1", "web-vitals": "^6.2.1", "web-vitals-soft-navs": "npm:web-vitals@6.2.1" }, "peerDependencies": { "@types/react": ">=16.8.0", "react": ">=16.8.0" }, "optionalPeers": ["@types/react", "react"] }, "sha512-ZfBkNrQiFr1Q43G3dR0USzTRdfx+6gKPebyoWDmKnLUhG3yRgYjLH914J6ifEDRnH+RaGOx7rsWKxKcvaSJXHg=="],
@@ -1497,8 +1396,6 @@
"prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
- "process": ["process@0.11.10", "", {}, "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A=="],
-
"prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="],
"proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="],
@@ -1537,8 +1434,6 @@
"react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
- "reflect-metadata": ["reflect-metadata@0.2.2", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
-
"require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
@@ -1559,8 +1454,6 @@
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
- "safe-regex-test": ["safe-regex-test@1.1.0", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "is-regex": "^1.2.1" } }, "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw=="],
-
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"sax": ["sax@1.6.1", "", {}, "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q=="],
@@ -1583,8 +1476,6 @@
"set-cookie-parser": ["set-cookie-parser@3.1.2", "", {}, "sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw=="],
- "set-function-length": ["set-function-length@1.2.2", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="],
-
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shadow-plugin": ["shadow-plugin@2.1.1", "", {}, "sha512-V4MwWPNzna/Zq6lIjT7vWAHf5uSCVDPkFG5m1cXs9WTtLGeLA3/NAtjJxxY3lYwBiA9O8+g/yLfC+c+P4qk4yw=="],
@@ -1621,12 +1512,8 @@
"std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="],
- "string-template": ["string-template@1.0.0", "", {}, "sha512-SLqR3GBUXuoPP5MmYtD7ompvXiG87QjT6lzOszyXjTM86Uu7At7vNnt2xgyTLq5o9T4IxTYFyGxcULqpsmsfdg=="],
-
"string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
- "stringz": ["stringz@2.1.0", "", { "dependencies": { "char-regex": "^1.0.2" } }, "sha512-KlywLT+MZ+v0IRepfMxRtnSvDCMc3nR1qqCs3m/qIbSOWkNZYT8XHQA31rS3TnKp0c5xjZu3M4GY/2aRKSi/6A=="],
-
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"stubborn-fs": ["stubborn-fs@2.0.0", "", { "dependencies": { "stubborn-utils": "^1.0.1" } }, "sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA=="],
@@ -1637,7 +1524,7 @@
"sugar-high": ["sugar-high@2.5.0", "", { "peerDependencies": { "gpu-lexer": ">=0.0.2" }, "optionalPeers": ["gpu-lexer"] }, "sha512-SPusUAqHpkpAxwGO6bVRegBq/Y6ZYkkZFR18VeH02pqk/l9hHJnc7MQf5Quyo54UQj1jU8u5zUDvj5zBJbA0rQ=="],
- "supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
+ "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],
"svgo": ["svgo@4.1.0", "", { "dependencies": { "commander": "^11.1.0", "css-select": "^6.0.0", "css-tree": "^3.0.1", "css-what": "^7.0.0", "csso": "^5.0.5", "picocolors": "^1.1.1", "sax": "1.6.1" }, "bin": { "svgo": "bin/svgo.js" } }, "sha512-bkxnTg1kSU0guhIBmibA6UUhrQmPVA1XsQLN+ylCd+UWzbnLkySOcXpyk1mrl05f+pcaCx2eHb+sp6BgMZWX+Q=="],
@@ -1693,14 +1580,10 @@
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
- "util": ["util@0.12.5", "", { "dependencies": { "inherits": "^2.0.3", "is-arguments": "^1.0.4", "is-generator-function": "^1.0.7", "is-typed-array": "^1.1.3", "which-typed-array": "^1.1.2" } }, "sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA=="],
-
"uzip": ["uzip@0.20201231.0", "", {}, "sha512-OZeJfZP+R0z9D6TmBgLq2LHzSSptGMGDGigGiEe0pr8UBe/7fdflgHlHBNDASTXB5jnFuxHpNaJywSg8YFeGng=="],
"valibot": ["valibot@1.5.0", "", { "peerDependencies": { "typescript": ">=5" }, "optionalPeers": ["typescript"] }, "sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ=="],
- "validator": ["validator@13.15.35", "", {}, "sha512-TQ5pAGhd5whStmqWvYF4OjQROlmv9SMFVt37qoCBdqRffuuklWYQlCNnEs2ZaIBD1kZRNnikiZOS1eqgkar0iw=="],
-
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"vite": ["vite@8.3.1", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.9", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA=="],
@@ -1717,8 +1600,6 @@
"which-module": ["which-module@2.0.1", "", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="],
- "which-typed-array": ["which-typed-array@1.1.22", "", { "dependencies": { "available-typed-arrays": "^1.0.7", "call-bind": "^1.0.9", "call-bound": "^1.0.4", "for-each": "^0.3.5", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-tostringtag": "^1.0.2" } }, "sha512-fvO4ExWMFsqyhG3AiPAObMuY1lxaqgYcxbc49CNdWDDECOJNgQyvsOWVwbZc+qf3rzRtxojBK+CMEv0Ld5CYpw=="],
-
"why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],
"word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
@@ -1777,8 +1658,6 @@
"@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
- "@javascript-obfuscator/escodegen/optionator": ["optionator@0.8.3", "", { "dependencies": { "deep-is": "~0.1.3", "fast-levenshtein": "~2.0.6", "levn": "~0.3.0", "prelude-ls": "~1.1.2", "type-check": "~0.3.2", "word-wrap": "~1.2.3" } }, "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA=="],
-
"@jridgewell/gen-mapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@jridgewell/remapping/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
@@ -1787,8 +1666,6 @@
"@poppinss/colors/kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
- "@poppinss/dumper/supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="],
-
"@posthog/browser-common/@posthog/core": ["@posthog/core@1.55.1", "", { "dependencies": { "@posthog/types": "^1.412.3" } }, "sha512-S76bSbCHGVC8oQa1zyue6A6WzkNf1Ue4oRvfvBNLRnFM3UoWnpWnQ4T/4IzrIEtVCQYv1OI7gk8uL8/U6Tuu7w=="],
"@sentry/node/@sentry/conventions": ["@sentry/conventions@0.16.0", "", {}, "sha512-fO9PLmHdVURcSPUpWCItWAtgKiMwGdJHbovoSEyLplX5sxs2ugvI4CBPTrkkgqhObnZOD0CnWBKDzSVQYBKEyQ=="],
@@ -1833,20 +1710,8 @@
"eslint/find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
- "espree/acorn": ["acorn@8.17.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="],
-
"import-in-the-middle/cjs-module-lexer": ["cjs-module-lexer@2.2.0", "", {}, "sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ=="],
- "javascript-obfuscator/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
-
- "javascript-obfuscator/conf": ["conf@15.0.2", "", { "dependencies": { "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "atomically": "^2.0.3", "debounce-fn": "^6.0.0", "dot-prop": "^10.0.0", "env-paths": "^3.0.0", "json-schema-typed": "^8.0.1", "semver": "^7.7.2", "uint8array-extras": "^1.5.0" } }, "sha512-JBSrutapCafTrddF9dH3lc7+T2tBycGF4uPkI4Js+g4vLLEhG6RZcFi3aJd5zntdf5tQxAejJt8dihkoQ/eSJw=="],
-
- "javascript-obfuscator/eslint-scope": ["eslint-scope@8.4.0", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg=="],
-
- "javascript-obfuscator/eslint-visitor-keys": ["eslint-visitor-keys@4.2.1", "", {}, "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ=="],
-
- "multimatch/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
-
"negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="],
"oxlint-plugin-react-doctor/oxc-parser": ["oxc-parser@0.148.0", "", { "dependencies": { "@oxc-project/types": "^0.148.0" }, "optionalDependencies": { "@oxc-parser/binding-android-arm-eabi": "0.148.0", "@oxc-parser/binding-android-arm64": "0.148.0", "@oxc-parser/binding-darwin-arm64": "0.148.0", "@oxc-parser/binding-darwin-x64": "0.148.0", "@oxc-parser/binding-freebsd-x64": "0.148.0", "@oxc-parser/binding-linux-arm-gnueabihf": "0.148.0", "@oxc-parser/binding-linux-arm-musleabihf": "0.148.0", "@oxc-parser/binding-linux-arm64-gnu": "0.148.0", "@oxc-parser/binding-linux-arm64-musl": "0.148.0", "@oxc-parser/binding-linux-ppc64-gnu": "0.148.0", "@oxc-parser/binding-linux-riscv64-gnu": "0.148.0", "@oxc-parser/binding-linux-riscv64-musl": "0.148.0", "@oxc-parser/binding-linux-s390x-gnu": "0.148.0", "@oxc-parser/binding-linux-x64-gnu": "0.148.0", "@oxc-parser/binding-linux-x64-musl": "0.148.0", "@oxc-parser/binding-openharmony-arm64": "0.148.0", "@oxc-parser/binding-win32-arm64-msvc": "0.148.0", "@oxc-parser/binding-win32-ia32-msvc": "0.148.0", "@oxc-parser/binding-win32-x64-msvc": "0.148.0" } }, "sha512-syxUKHeUll89RIABQADcI7sikYrwyssvA6gj4phSSIPezKVM8yMaLAiLLSc7fmzVvrwybfFGFbW5zme9sX87rg=="],
@@ -1925,12 +1790,6 @@
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="],
- "@javascript-obfuscator/escodegen/optionator/levn": ["levn@0.3.0", "", { "dependencies": { "prelude-ls": "~1.1.2", "type-check": "~0.3.2" } }, "sha512-0OO4y2iOHix2W6ujICbKIaEQXvFQHue65vUG3pb5EUomzPI90z9hsA1VsO/dbIIpC53J8gxM9Q4Oho0jrCM/yA=="],
-
- "@javascript-obfuscator/escodegen/optionator/prelude-ls": ["prelude-ls@1.1.2", "", {}, "sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w=="],
-
- "@javascript-obfuscator/escodegen/optionator/type-check": ["type-check@0.3.2", "", { "dependencies": { "prelude-ls": "~1.1.2" } }, "sha512-ZCmOJdvOWDBYJlzAoFkC+Q0+bUyEOS1ltgp1MGU03fqHG+dbi9tBFU2Rd9QKiDZFAYrhPh2JUf7rZRIuHRKtOg=="],
-
"@tailwindcss/node/lightningcss/lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
"@tailwindcss/node/lightningcss/lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],
@@ -2017,8 +1876,6 @@
"eslint/find-up/locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
- "multimatch/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
-
"oxlint-plugin-react-doctor/oxc-parser/@oxc-parser/binding-android-arm-eabi": ["@oxc-parser/binding-android-arm-eabi@0.148.0", "", { "os": "android", "cpu": "arm" }, "sha512-pHASv9g5pASxb7akHERZNSkrEqPhFaUix98o7d9hbTpolnnFWl7UiRrcMhCsV1+iVO4/cJwKsbKRJTFNs2tdBQ=="],
"oxlint-plugin-react-doctor/oxc-parser/@oxc-parser/binding-android-arm64": ["@oxc-parser/binding-android-arm64@0.148.0", "", { "os": "android", "cpu": "arm64" }, "sha512-sg/6Ez0KdAygsu0POELux9wN1Po2CP93WY8eNl4DBKIGprsd4QSHBXOb471Pu9i2OCD5sLkISSb2agZEhVn2Zw=="],
@@ -2209,8 +2066,6 @@
"eslint/find-up/locate-path/p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
- "multimatch/minimatch/brace-expansion/balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
-
"@cloudflare/vitest-pool-workers/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.2", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw=="],
"@cloudflare/vitest-pool-workers/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.2", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw=="],
diff --git a/docs/rate-limiting.md b/docs/rate-limiting.md
index 2ce50d94..e9604c56 100644
--- a/docs/rate-limiting.md
+++ b/docs/rate-limiting.md
@@ -7,11 +7,11 @@ why all three exist.
| ----------------------- | ---------------------------------- | ----------------------- | ---------------------- |
| WAF rate limiting rules | Cloudflare edge, before the Worker | Globally, per zone | Floods |
| Workers Rate Limiting | Inside the Worker | Per Cloudflare location | Bursts from one caller |
-| Cap proof-of-work | Visitor's browser | Per attempt | Slow, distributed bots |
+| Cloudflare Turnstile | Visitor's browser | Per attempt | Slow, distributed bots |
-A rate limit is a ceiling. Cap is a price. Neither replaces the other: a bot
-that stays politely under every limit pays nothing to a ceiling, and a flood
-from ten thousand addresses pays little to a price.
+A rate limit is a ceiling. Turnstile is a gate. Neither replaces the other: a bot
+that stays politely under every limit gets through a ceiling, and a flood
+from ten thousand addresses gets through a gate unless each one is challenged.
## Layer 1: WAF rate limiting rules (dashboard)
@@ -24,7 +24,7 @@ no billable invocation. Unlike the Workers limiters below, the counters are
global rather than per-location.
Add them at **Security → WAF → Rate limiting rules** on the `rdyrct.com` zone.
-All three rules target auth/Cap paths, which only ever get hit on that zone
+Both rules target auth paths, which only ever get hit on that zone
(the shared redirect host from `SHARED_LINK_HOST`, e.g. `rdyr.cc`, only ever
serves redirects), so there is nothing to add on its zone for these.
@@ -47,23 +47,7 @@ can go well past any single one. This catches that without punishing a person
whose corporate NAT shares an address: one sign-up costs a handful of
requests, so 60 is a bot and 20 was a family.
-### Rule 2: proof-of-work challenges
-
-| Field | Value |
-| --------------- | ---------------------------------------------- |
-| Name | `cap-challenges` |
-| Expression | `(http.request.uri.path contains "/api/cap/")` |
-| Characteristics | IP |
-| Period | 1 minute |
-| Requests | 60 |
-| Action | Managed challenge |
-| Duration | 1 minute |
-
-Higher, because issuing a challenge is cheap for us and expensive for the
-caller, which is the whole asymmetry Cap rests on. The point is only to stop
-someone farming challenges to solve offline in bulk.
-
-### Rule 3: password reset
+### Rule 2: password reset
| Field | Value |
| --------------- | --------------------------------------------------------------- |
@@ -96,14 +80,13 @@ enforcement.
These are the production numbers. The dev and test environments in
`wrangler.jsonc` deliberately run several of them looser (`RL_AUTH_PUBLIC`,
-`RL_CAP`, `RL_EMAIL`, `RL_EMAIL_RECIPIENT`), because the e2e suite signs up
+`RL_EMAIL`, `RL_EMAIL_RECIPIENT`), because the e2e suite signs up
dozens of times a minute from one address and rate limiting the test run
proves nothing about the feature.
| Binding | Limit | Keyed by | Guards |
| -------------------- | ------- | ----------------- | ----------------------------- |
| `RL_AUTH_PUBLIC` | 30/min | IP, path | `/api/auth/*` |
-| `RL_CAP` | 120/min | IP, path | `/api/cap/*` (#98) |
| `RL_EMAIL` | 10/min | IP, path | Anything that sends mail |
| `RL_EMAIL_RECIPIENT` | 4/min | Recipient address | One inbox, many callers (#50) |
| `RL_WRITE_FREE` | 90/min | User | Writes on a free plan |
@@ -115,54 +98,49 @@ proves nothing about the feature.
These are set for the person having trouble, not for the bot: someone who
mistypes a password, retries a signup or pastes six links in a row must never
-meet a wall, because a wall reads as the product being broken. `RL_CAP` is the
-clearest case: one sign-up spends a challenge and a redeem, its retry spends
-two more, and when that budget runs out the browser cannot solve the puzzle at
-all, so the form says "could not verify you are human" instead of "wait a
-minute". It has its own generous counter for that reason. Only
+meet a wall, because a wall reads as the product being broken. Only
`RL_EMAIL_RECIPIENT` stays tight, because it is the one that bounds what an
inbox can be made to receive however many callers aim at it. The real
-ceilings are the WAF rules above and the CPU Cap charges per attempt.
+ceilings are the WAF rules above and the Turnstile challenge on each attempt.
`period` accepts only 10 or 60, so every one of these caps a rate, not a
daily total. Closing that gap needs a durable counter; see the follow-up on
#50.
-## Layer 3: Cap proof-of-work (#98)
-
-Self-hosted, Apache 2.0, and no third party ever sees the visitor. The
-challenge is issued by our Worker, solved in the visitor's browser, and
-verified by our Worker.
-
-**Where it applies.** Signup and password-reset requests. Not login: a bot
-with correct credentials is not the threat model, and it would tax every real
-visitor on every visit.
-
-**How it looks.** It does not. The widget is created off-screen and driven
-directly, and solving starts on the form's first keystroke, so the work
-overlaps the typing. Nobody ticks a box.
-
-**The secret.** `CAP_SECRET`, from `openssl rand -hex 32`. With it unset the
-check is skipped entirely, which is what keeps local dev quiet. capjs-core
-refuses a secret under 16 bytes by throwing, so a too-short one takes signup
-down rather than running unprotected: fail-closed, which for a security
-control is the right way round, but worth knowing before you paste something
-short.
-
-**What it costs a visitor.** 12 challenges at difficulty 3, measured on a
-laptop: about 25ms with the WASM solver, about 130ms without. The WASM path
-needs `'wasm-unsafe-eval'` in `script-src`, which permits WebAssembly
-compilation and nothing else, and the module is a same-origin Vite asset.
-Cap's solver also runs in a Web Worker built from a `blob:` URL, hence
-`worker-src 'self' blob:`. Both are asserted in
-`tests/e2e/production/csp.pw.ts`, because a blocked solver fails silently:
-signup would look fine and be completely unprotected.
-
-**What it does not do.** KV is eventually consistent, so a redeemed token
-presented to two locations at once has a small replay window. That is an
-acceptable ceiling for a captcha, whose job is to price bulk attempts rather
-than to guarantee exactly-once. Making it airtight would mean a Durable
-Object per nonce, which costs more than the replay is worth.
+## Layer 3: Cloudflare Turnstile (#304)
+
+Free, and run by Cloudflare. The visitor's browser loads the Turnstile script
+from `challenges.cloudflare.com` and solves a challenge there, so Cloudflare
+sees the visitor; this is the one third party that does. The Worker never
+sees the challenge: it sends the token to Cloudflare's `siteverify` and
+believes the answer. `siteverify` burns the token, so a replay fails with no
+state of ours.
+
+**Where it applies.** Signup, password reset and the landing page shortener.
+Not login: a bot with correct credentials is not the threat model, and it
+would tax every real visitor on every visit. Each form renders the widget with
+its own `action`, and the Worker refuses a token whose action is not the one
+it expects, so a token earned on one form cannot open another.
+
+**How it looks.** Mostly it does not: the widget is `interaction-only`, solved
+on the form's first keystroke. If Cloudflare wants a click, the widget shows
+itself in the corner of the page.
+
+**Keys.** Create a widget at dash.cloudflare.com → Turnstile. Set the site key
+as the `TURNSTILE_SITE_KEY` var in `wrangler.jsonc` (it is public; `/api/config`
+hands it to the browser) and the secret as `TURNSTILE_SECRET_KEY`. With the
+secret unset the check is skipped entirely, which is what keeps local dev and
+self-hosting quiet. A secret with no site key refuses every request instead:
+the browser has no widget to render, and that is better than a form that looks
+protected and is not. Cloudflare publishes test keys that always pass; they are
+what `.dev.vars.example` and the e2e run use.
+
+**CSP.** `script-src`, `connect-src` and `frame-src` allow
+`https://challenges.cloudflare.com`, asserted in
+`tests/e2e/production/csp.pw.ts`.
+
+**If Cloudflare is unreachable** `siteverify` fails closed: signup and reset
+are refused until it answers.
## Monitoring
@@ -178,8 +156,8 @@ WAF rule activity appears under Security → Events, filtered by the rule name.
deleting it, so the counters keep running and you can see what it would have
caught.
-**Cap is blocking real people.** Unset `CAP_SECRET`
-(`bunx wrangler secret delete CAP_SECRET`). The check disables itself and
+**Turnstile is blocking real people.** Unset `TURNSTILE_SECRET_KEY`
+(`bunx wrangler secret delete TURNSTILE_SECRET_KEY`). The check disables itself and
both guarded flows, signup and password reset, return to exactly their
previous behaviour. No deploy needed.
diff --git a/package.json b/package.json
index 76423b47..4ea2dadb 100644
--- a/package.json
+++ b/package.json
@@ -37,8 +37,6 @@
"@better-auth/cimd": "1.7.6",
"@better-auth/mcp": "1.7.6",
"@better-auth/oauth-provider": "1.7.6",
- "@cap.js/wasm": "^0.0.8",
- "@cap.js/widget": "^0.1.58",
"@fontsource-variable/figtree": "^5.3.0",
"@fontsource/jetbrains-mono": "^5.3.0",
"@hono/mcp": "^0.3.2",
@@ -56,7 +54,6 @@
"blobatar": "^2.7.0",
"browser-image-compression": "^2.0.2",
"canvas-confetti": "^1.9.4",
- "capjs-core": "0.1.3",
"cmdk": "^1.1.1",
"cn": "0.4.0",
"d3-geo": "^3.1.1",
diff --git a/prod.secrets.env.example b/prod.secrets.env.example
index 6f461c07..59cb63c6 100644
--- a/prod.secrets.env.example
+++ b/prod.secrets.env.example
@@ -29,11 +29,13 @@ POLAR_WEBHOOK_SECRET=
# permission Zone → SSL and Certificates → Edit, scoped to your zone (custom domains)
CF_API_TOKEN=
-# Cap proof-of-work in front of signup and password reset (#98).
-# Generate with: openssl rand -hex 32
+# Cloudflare Turnstile in front of signup, password reset and the landing
+# shortener (#304). dash.cloudflare.com → Turnstile → Add widget (managed
+# mode, your app host). Put the site key in `vars` in wrangler.jsonc as
+# TURNSTILE_SITE_KEY; the secret goes here.
# Leave unset and the check is skipped entirely, so this is the one thing
# standing between the signup form and a bot.
-CAP_SECRET=
+TURNSTILE_SECRET_KEY=
# Google sign-in (#194). Create an OAuth 2.0 client at
# console.cloud.google.com → APIs & Services → Credentials, with authorized
diff --git a/src/app/components/hero-shortener.tsx b/src/app/components/hero-shortener.tsx
index 178fa8fc..bec38dbb 100644
--- a/src/app/components/hero-shortener.tsx
+++ b/src/app/components/hero-shortener.tsx
@@ -31,7 +31,7 @@ import { CopyButton } from "../ui/copy-button";
import { BusyContent } from "../ui/spinner";
import { useToast } from "../ui/toast";
import { copyToClipboard } from "../lib/clipboard";
-import { useCap } from "../lib/cap";
+import { useTurnstile } from "../lib/turnstile";
import {
MAX_ANON_LINKS,
rememberAnonLink,
@@ -178,7 +178,7 @@ function MadeLinks({ made }: { made: StoredAnonLink[] }) {
export function HeroShortener() {
const toast = useToast();
- const cap = useCap("anon-link");
+ const turnstile = useTurnstile("anon-link");
const [destination, setDestination] = useState("");
const [busy, setBusy] = useState(false);
// Seeded from storage, so a reload keeps what this browser already made
@@ -195,7 +195,7 @@ export function HeroShortener() {
if (!canSubmit) return;
setBusy(true);
try {
- const link = await shortenAnonymously(destination, cap.guarded);
+ const link = await shortenAnonymously(destination, turnstile.guarded);
// Stored before anything is rendered, and the store decides what the
// list now is: a visitor who signs up in another tab must still be
// able to claim it, and the cap is enforced in one place.
@@ -213,7 +213,7 @@ export function HeroShortener() {
onSubmit={submit}
// Priming here, not on mount: the proof-of-work runs while they type,
// and someone who never uses the form never pays for it.
- onInput={cap.prime}
+ onInput={turnstile.prime}
// No native validation: errors in this app go to toasts, and a browser
// validity bubble is neither a toast nor dismissible by us. It also
// silently refuses to submit, which reads as a dead button. The server
diff --git a/src/app/lib/anon-links.ts b/src/app/lib/anon-links.ts
index 60a45a04..5a820314 100644
--- a/src/app/lib/anon-links.ts
+++ b/src/app/lib/anon-links.ts
@@ -29,8 +29,8 @@ const KEY = "rdyrct:anon-links:v3";
/**
* How many links one browser may make without an account.
*
- * A product limit, not a security one: abuse is already handled by the Cap
- * proof-of-work and RL_ANON_LINK, both of which a browser cannot talk its
+ * A product limit, not a security one: abuse is already handled by Turnstile
+ * and RL_ANON_LINK, both of which a browser cannot talk its
* way past. One link is enough to show that shortening works, and the second
* one is where trying it becomes signing up. It frees up as the link expires,
* and claiming at signup clears it entirely.
diff --git a/src/app/lib/cap.ts b/src/app/lib/cap.ts
deleted file mode 100644
index 77688d85..00000000
--- a/src/app/lib/cap.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * Cap on the client (#98): proof-of-work, solved without a checkbox.
- *
- * Cap ships a visible widget, but its element also exposes `solve()`, so we
- * keep the element out of sight and drive it ourselves: work starts when the
- * visitor first touches the form and the token is usually ready by the time
- * they submit. Nobody clicks anything, and nobody waits on a spinner they
- * did not ask for.
- *
- * Everything is served from our own origin. The widget is bundled from npm
- * rather than pulled from Cap's CDN, and the WASM solver comes through Vite
- * as a hashed asset, so `script-src 'self'` and `connect-src 'self'` already
- * cover both. Loading either from a CDN would hand back the third-party
- * runtime dependency that is the whole reason we chose Cap over Turnstile.
- *
- * A failure here never blocks the form. The token goes to the server, the
- * server decides: an empty one is rejected when CAP_SECRET is set and
- * ignored when it is not, which is what keeps local dev and CI quiet.
- */
-import { useCallback, useRef } from "react";
-import wasmUrl from "@cap.js/wasm/browser/cap_wasm_bg.wasm?url";
-import { CAP_TOKEN_HEADER } from "@/shared/types";
-import { retryOnCapFailure } from "./cap-retry";
-
-export type CapScope = "signup" | "password-reset" | "anon-link";
-
-/** Runs a Cap-guarded request, re-solving once if the token is refused. */
-export type CapGuard = (run: (headers: Record) => Promise) => Promise;
-
-/** How long to wait for a solve before giving up and submitting without one. */
-const SOLVE_TIMEOUT_MS = 20_000;
-
-/**
- * How long a solved token is reused before it is thrown away and solved
- * again. Comfortably under the ten minutes the Worker keeps a redeemed token,
- * so a form filled slowly still submits with something the server will
- * accept.
- */
-const TOKEN_FRESH_MS = 4 * 60 * 1000;
-
-type CapElement = HTMLElement & {
- solve: () => Promise<{ token?: string }>;
- reset: () => void;
-};
-
-let loading: Promise | null = null;
-
-/**
- * Loads the widget once, on demand, so it stays out of the initial bundle.
- *
- * A failed load is not remembered. The promise used to be cached whatever it
- * settled to, so one bad fetch (a dev server restarting under an open tab, a
- * dropped connection, a chunk that 404s after a deploy) poisoned every solve
- * for the life of that tab: the form then said "could not verify you are
- * human" forever, and only a reload fixed it. Now the next attempt tries
- * again.
- */
-declare global {
- interface Window {
- /** Where @cap.js/widget fetches its WASM solver from. Read once, at the
- * widget's module-eval time, so it has to be set before that import. */
- CAP_CUSTOM_WASM_URL?: string;
- }
-}
-
-function loadCap(): Promise {
- loading ??= (async () => {
- // Read at module-eval time by the widget, so it has to be set first, or
- // it fetches the WASM from jsdelivr and trips the CSP.
- window.CAP_CUSTOM_WASM_URL = wasmUrl;
- await import("@cap.js/widget");
- })().catch((cause: unknown) => {
- loading = null;
- throw cause;
- });
- return loading;
-}
-
-/**
- * The widget for one scope, made once and left in the document.
- *
- * This is the shape Cap's own `Cap` class uses, and the reason matters: the
- * element's `disconnectedCallback` aborts its AbortController, and every
- * `await` inside the widget's `solve()` is followed by
- * `if (signal?.aborted || !this.#speculative) return;`. So a widget removed
- * while it is working makes `solve()` resolve **undefined**: no token, no
- * throw, no error event. The old code created a throwaway element per solve
- * and removed it in a `finally`, which is exactly how to hit that path, and
- * an undefined result became an empty token, no `x-cap-token` header, and
- * "could not verify you are human" in front of somebody trying to sign up.
- */
-const widgets = new Map();
-
-/** One solve at a time per widget. `solve()` opens with
- * `if (this.#solving) return;`, so a second concurrent call on the same
- * element resolves undefined too. Callers share the in-flight promise
- * instead. */
-const solving = new Map>();
-
-async function widgetFor(scope: CapScope): Promise {
- await loadCap();
- const existing = widgets.get(scope);
- if (existing?.isConnected) return existing;
-
- // SAFETY: loadCap() above imported @cap.js/widget, which defines the
- // "cap-widget" custom element, so createElement returns an upgraded widget
- // with solve() on it rather than an unknown element.
- const el = document.createElement("cap-widget") as CapElement;
- el.setAttribute("data-cap-api-endpoint", `/api/cap/${scope}/`);
- el.setAttribute("aria-hidden", "true");
- el.style.display = "none";
- // The widget dispatches its own "error" event, and with nothing listening
- // it surfaces as an unhandled error: an aborted solve would otherwise look
- // like a page crash. Failure is reported by resolving with "".
- el.addEventListener("error", (event) => event.stopPropagation());
- document.documentElement.appendChild(el);
- widgets.set(scope, el);
- return el;
-}
-
-/** Throws the widget away, for the cases where its internal state is not
- * worth trusting: it is rebuilt on the next attempt. */
-function discardWidget(scope: CapScope): void {
- widgets.get(scope)?.remove();
- widgets.delete(scope);
-}
-
-/**
- * Solves one challenge and resolves with the token, or "" if this browser
- * could not produce one.
- *
- * "" is deliberate rather than an exception: a visitor whose browser cannot
- * run the puzzle should still be able to submit and be answered by the
- * server, instead of meeting a form that refuses to do anything.
- *
- * A solve that comes back without a token is retried once on a fresh widget.
- * The silent-undefined paths above are all transient (an abort, a solve
- * already running), so the second attempt is usually the one that works, and
- * a second failure is a real one worth reporting.
- */
-function solveCap(scope: CapScope): Promise {
- const inFlight = solving.get(scope);
- if (inFlight) return inFlight;
-
- const attempt = (async () => {
- try {
- for (let tries = 0; tries < 2; tries++) {
- const el = await widgetFor(scope);
- // Single-use tokens: whatever this widget still holds from the last
- // solve has been spent, and reset() clears it along with the timer
- // that would have cleared it later.
- el.reset();
- const result = await Promise.race([
- el.solve(),
- new Promise((resolve) => setTimeout(() => resolve(null), SOLVE_TIMEOUT_MS)),
- ]);
- if (result?.token) return result.token;
- // Either it timed out, or it returned without one. Both leave state
- // this widget cannot be trusted with, so the retry gets a new one.
- discardWidget(scope);
- }
- return "";
- } catch {
- discardWidget(scope);
- return "";
- } finally {
- solving.delete(scope);
- }
- })();
-
- solving.set(scope, attempt);
- return attempt;
-}
-
-/** The header a solved token travels in, ready to spread into fetch options. */
-function capHeaders(token: string): Record {
- return token ? { [CAP_TOKEN_HEADER]: token } : {};
-}
-
-/**
- * A token for one form.
- *
- * `prime()` is safe to call on every keystroke and starts the work once;
- * hang it on the form's first focus so the puzzle is solving while the
- * visitor types. `headers()` awaits whatever that produced, so a fast
- * typist waits and everyone else does not.
- *
- * A token is single-use, so the primed promise is cleared once spent: a
- * form submitted twice (a failed signup, then a corrected one) solves
- * again rather than replaying a token the server has already burned.
- */
-export function useCap(scope: CapScope) {
- const pending = useRef<{ token: Promise; primedAt: number } | null>(null);
-
- const prime = useCallback(() => {
- // Discarded once stale, not just once spent. The server keeps a redeemed
- // token for ten minutes; the browser was holding one forever, so filling
- // the form and submitting after a distraction failed with "could not
- // verify you are human" and no way to tell why. Re-solving costs about
- // 25ms.
- const held = pending.current;
- if (held && Date.now() - held.primedAt < TOKEN_FRESH_MS) return;
- pending.current = { token: solveCap(scope), primedAt: Date.now() };
- }, [scope]);
-
- const headers = useCallback(async () => {
- prime();
- const token = await pending.current!.token;
- // Single-use: a second submit has to solve again rather than replay a
- // token the server has already burned.
- pending.current = null;
- // An empty token means the puzzle never got solved here: the widget or
- // its WASM did not load, or it ran out of time. The request still goes
- // (the server decides, and Cap may be off entirely), but this is the one
- // place that knows the difference between "we could not run the check"
- // and "the server refused it", and saying so beats reading the network
- // tab of somebody else's browser.
- if (!token) console.warn("cap_solve_failed", scope);
- return capHeaders(token);
- }, [prime, scope]);
-
- const guarded = useCallback(
- (run: (headers: Record) => Promise) => retryOnCapFailure(run, headers),
- [headers],
- );
-
- return { prime, headers, guarded };
-}
diff --git a/src/app/lib/shorten-anon.ts b/src/app/lib/shorten-anon.ts
index 1e1b3ca3..4ed7ba55 100644
--- a/src/app/lib/shorten-anon.ts
+++ b/src/app/lib/shorten-anon.ts
@@ -7,8 +7,8 @@
*/
import { useQuery } from "@tanstack/react-query";
import { api } from "./api";
-import type { CapGuard } from "./cap";
-import { CAP_TOKEN_HEADER } from "@/shared/types";
+import type { TurnstileGuard } from "./turnstile";
+import { TURNSTILE_TOKEN_HEADER } from "@/shared/types";
export type AnonLink = { slug: string; url: string; claimToken: string; expiresAt: number };
@@ -21,12 +21,12 @@ export type AnonLink = { slug: string; url: string; claimToken: string; expiresA
*/
export async function shortenAnonymously(
destination: string,
- guarded: CapGuard,
+ guarded: TurnstileGuard,
): Promise {
return guarded((headers) =>
api("/shorten", {
method: "POST",
- body: { destination, capToken: headers[CAP_TOKEN_HEADER] ?? "" },
+ body: { destination, turnstileToken: headers[TURNSTILE_TOKEN_HEADER] ?? "" },
}),
);
}
diff --git a/src/app/lib/cap-retry.ts b/src/app/lib/turnstile-retry.ts
similarity index 66%
rename from src/app/lib/cap-retry.ts
rename to src/app/lib/turnstile-retry.ts
index 863cefb6..4c1da2fa 100644
--- a/src/app/lib/cap-retry.ts
+++ b/src/app/lib/turnstile-retry.ts
@@ -1,33 +1,32 @@
/**
- * The one rule that decides whether a Cap-guarded request gets a second go.
+ * The one rule that decides whether a Turnstile-guarded request gets a second go.
*
- * Its own module so it can be tested: cap.ts imports the WASM solver as a
- * `?url` asset, which bun's test runner cannot resolve.
+ * Its own module so it can be tested without loading the Turnstile script.
*/
-import { CAP_FAILED_CODE } from "@/shared/types";
+import { TURNSTILE_FAILED_CODE } from "@/shared/types";
/** Either shape a refusal arrives in: an ApiError carrying `.code`, or the
* `{ error }` better-auth resolves with instead of throwing. */
-type CapRefusal = { code?: string; error?: { code?: string } } | null | undefined;
+type TurnstileRefusal = { code?: string; error?: { code?: string } } | null | undefined;
/**
- * Whether a refusal is the Worker turning down a Cap token.
+ * Whether a refusal is the Worker turning down a Turnstile token.
*
* Two shapes reach here, and both have to be read. better-auth resolves with
* `{ error }` on the object rather than throwing; api() rejects with an
* ApiError carrying `.code`. Reading only the first is what made the retry
* below dead code for every api() caller.
*/
-export function isCapFailure(result: T): boolean {
+export function isTurnstileFailure(result: T): boolean {
// SAFETY: this reads two optional fields off whatever arrived. Both shapes
// are this app's own (an ApiError, and the { error } better-auth resolves
// with); anything else carries neither field and reads as undefined.
- const refusal = result as CapRefusal;
- return refusal?.code === CAP_FAILED_CODE || refusal?.error?.code === CAP_FAILED_CODE;
+ const refusal = result as TurnstileRefusal;
+ return refusal?.code === TURNSTILE_FAILED_CODE || refusal?.error?.code === TURNSTILE_FAILED_CODE;
}
/**
- * Runs a Cap-guarded request, and if the Worker refuses the token, solves a
+ * Runs a Turnstile-guarded request, and if the Worker refuses the token, solves a
* fresh one and runs it exactly once more.
*
* A token can be refused for reasons the browser cannot see coming: it
@@ -41,15 +40,15 @@ export function isCapFailure(result: T): boolean {
* human" in front of somebody who had done nothing wrong, on the one path
* where retrying always would have worked.
*/
-export async function retryOnCapFailure(
+export async function retryOnTurnstileFailure(
run: (headers: Record) => Promise,
headers: () => Promise>,
): Promise {
try {
const first = await run(await headers());
- if (!isCapFailure(first)) return first;
+ if (!isTurnstileFailure(first)) return first;
} catch (error) {
- if (!isCapFailure(error)) throw error;
+ if (!isTurnstileFailure(error)) throw error;
}
return run(await headers());
}
diff --git a/src/app/lib/turnstile.ts b/src/app/lib/turnstile.ts
new file mode 100644
index 00000000..dd36ffc3
--- /dev/null
+++ b/src/app/lib/turnstile.ts
@@ -0,0 +1,148 @@
+/**
+ * Cloudflare Turnstile on the client (#304).
+ *
+ * The widget renders `interaction-only`: invisible unless Cloudflare wants a
+ * click, in which case it shows itself in the corner. Work starts when the
+ * visitor first touches the form, so the token is usually ready by the time
+ * they submit.
+ *
+ * A failure here never blocks the form. The token goes to the server, the
+ * server decides: an empty one is rejected when TURNSTILE_SECRET_KEY is set
+ * and ignored when it is not.
+ */
+import { useCallback, useRef } from "react";
+import { TURNSTILE_TOKEN_HEADER } from "@/shared/types";
+import { useConfig } from "./hooks";
+import { retryOnTurnstileFailure } from "./turnstile-retry";
+
+export type TurnstileScope = "signup" | "password-reset" | "anon-link";
+
+/** Runs a Turnstile-guarded request, re-solving once if the token is refused. */
+export type TurnstileGuard = (
+ run: (headers: Record) => Promise,
+) => Promise;
+
+const SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
+
+/** How long to wait for a token before submitting without one. */
+const SOLVE_TIMEOUT_MS = 20_000;
+
+/** Tokens expire after 300s at Cloudflare; discard ours well before. */
+const TOKEN_FRESH_MS = 4 * 60 * 1000;
+
+interface TurnstileApi {
+ render: (
+ container: HTMLElement,
+ options: {
+ sitekey: string;
+ action: string;
+ appearance: "interaction-only";
+ callback: (token: string) => void;
+ "error-callback": () => void;
+ "timeout-callback": () => void;
+ },
+ ) => string;
+ remove: (widgetId: string) => void;
+}
+
+declare global {
+ interface Window {
+ turnstile?: TurnstileApi;
+ }
+}
+
+let loading: Promise | null = null;
+
+/** Loads Cloudflare's script once, on demand. A failed load is not
+ * remembered, so one dropped connection does not poison the tab. */
+function loadScript(): Promise {
+ loading ??= new Promise((resolve, reject) => {
+ const script = document.createElement("script");
+ script.src = SCRIPT_URL;
+ script.async = true;
+ script.onload = () =>
+ window.turnstile ? resolve(window.turnstile) : reject(new Error("turnstile missing"));
+ script.onerror = () => reject(new Error("turnstile failed to load"));
+ document.head.appendChild(script);
+ }).catch((cause: unknown) => {
+ loading = null;
+ throw cause;
+ });
+ return loading;
+}
+
+/** Resolves with a token, or "" if this browser could not produce one. "" is
+ * deliberate rather than an exception: the server decides what an empty
+ * token means. */
+async function solve(siteKey: string, scope: TurnstileScope): Promise {
+ let container: HTMLElement | null = null;
+ let widgetId: string | null = null;
+ let turnstile: TurnstileApi | null = null;
+ try {
+ turnstile = await loadScript();
+ const host = document.createElement("div");
+ // Empty while invisible; if Cloudflare asks for a click, it appears here.
+ host.style.cssText = "position:fixed;right:16px;bottom:16px;z-index:60";
+ document.body.appendChild(host);
+ container = host;
+ return await new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(""), SOLVE_TIMEOUT_MS);
+ const done = (token: string) => {
+ clearTimeout(timer);
+ resolve(token);
+ };
+ widgetId = turnstile!.render(host, {
+ sitekey: siteKey,
+ action: scope,
+ appearance: "interaction-only",
+ callback: done,
+ "error-callback": () => done(""),
+ "timeout-callback": () => done(""),
+ });
+ });
+ } catch {
+ return "";
+ } finally {
+ if (widgetId) turnstile?.remove(widgetId);
+ container?.remove();
+ }
+}
+
+/**
+ * A token for one form.
+ *
+ * `prime()` is safe to call on every keystroke and starts the work once;
+ * hang it on the form's first input. `headers()` awaits whatever that
+ * produced, so a fast typist waits and everyone else does not.
+ *
+ * A token is single-use, so the primed promise is cleared once spent: a form
+ * submitted twice solves again rather than replaying a burned token.
+ */
+export function useTurnstile(scope: TurnstileScope) {
+ const siteKey = useConfig().data?.turnstileSiteKey;
+ const pending = useRef<{ token: Promise; primedAt: number } | null>(null);
+
+ const prime = useCallback(() => {
+ if (!siteKey) return;
+ const held = pending.current;
+ if (held && Date.now() - held.primedAt < TOKEN_FRESH_MS) return;
+ pending.current = { token: solve(siteKey, scope), primedAt: Date.now() };
+ }, [scope, siteKey]);
+
+ const headers = useCallback(async (): Promise> => {
+ prime();
+ const token = (await pending.current?.token) ?? "";
+ pending.current = null;
+ // The one place that knows "we could not run the check" from "the server
+ // refused it".
+ if (siteKey && !token) console.warn("turnstile_solve_failed", scope);
+ return token ? { [TURNSTILE_TOKEN_HEADER]: token } : {};
+ }, [prime, scope, siteKey]);
+
+ const guarded = useCallback(
+ (run) => retryOnTurnstileFailure(run, headers),
+ [headers],
+ );
+
+ return { prime, headers, guarded };
+}
diff --git a/src/app/routes/auth.tsx b/src/app/routes/auth.tsx
index 2d55de50..071cad11 100644
--- a/src/app/routes/auth.tsx
+++ b/src/app/routes/auth.tsx
@@ -11,7 +11,7 @@ import { friendlyAuthError } from "../lib/auth-errors";
import posthog from "../lib/posthog";
import { FUNNEL, SIGNUP_FAILED, USER_SIGNED_UP, googleSignupUrl } from "../lib/funnel";
import { useShake } from "../lib/use-shake";
-import { useCap } from "../lib/cap";
+import { useTurnstile } from "../lib/turnstile";
import { useCurrentUser, useConfig } from "../lib/hooks";
import { storedAnonLinks } from "../lib/anon-links";
import { readAuthHint } from "../lib/user-cache";
@@ -357,7 +357,7 @@ function AuthFormView({
next: string;
onSubmit: (email: string, password: string) => void;
onForgot: (email: string) => void;
- /** Starts the Cap proof-of-work (#98). Idempotent, so a per-keystroke
+ /** Starts the Turnstile challenge (#304). Idempotent, so a per-keystroke
* handler is fine; it fires once and the work overlaps the typing. */
onFirstInput: () => void;
}) {
@@ -507,8 +507,8 @@ interface SubmitDeps {
qc: QueryClient;
navigate: ReturnType;
next: string;
- /** Runs a Cap-guarded request, re-solving once if the token is refused. */
- capGuarded: (run: (headers: Record) => Promise) => Promise;
+ /** Runs a Turnstile-guarded request, re-solving once if the token is refused. */
+ turnstileGuarded: (run: (headers: Record) => Promise) => Promise;
}
async function trySignIn(email: string, password: string, deps: SubmitDeps) {
@@ -533,11 +533,11 @@ async function trySignUp(
password: string,
deps: SubmitDeps & { emailEnabled: boolean },
) {
- // Cap's proof-of-work token (#98). Solved while the visitor was typing,
+ // Turnstile token (#304). Solved while the visitor was typing,
// spent here, and required by the Worker before an account exists. Through
// the guard, so a token the server has forgotten is solved again rather
// than shown to somebody as an error.
- const { error: signUpError } = await deps.capGuarded((headers) =>
+ const { error: signUpError } = await deps.turnstileGuarded((headers) =>
authClient.signUp.email({ email, password, name: email.split("@")[0] }, { headers }),
);
if (signUpError) {
@@ -618,7 +618,7 @@ function useForgotPassword(
toast: ReturnType,
emailEnabled: boolean,
) {
- const resetCap = useCap("password-reset");
+ const resetTurnstile = useTurnstile("password-reset");
const [forgotBusy, setForgotBusy] = useState(false);
const submitForgot = async (email: string) => {
@@ -629,8 +629,8 @@ function useForgotPassword(
setForgotBusy(true);
try {
// Cheap to abuse and it sends mail, which is why #50 needed a
- // per-recipient cap. Cap prices the attempt instead (#98).
- const { error: resetError } = await resetCap.guarded((headers) =>
+ // per-recipient cap. Turnstile gates the attempt instead (#304).
+ const { error: resetError } = await resetTurnstile.guarded((headers) =>
authClient.requestPasswordReset({ email, redirectTo: "/reset-password" }, { headers }),
);
if (resetError) {
@@ -688,9 +688,9 @@ function useAuthFlow(mode: "login" | "signup") {
const [verifyPhase, setVerifyPhase] = useState<"idle" | "success" | "leaving">("idle");
const shake = useShake();
// Two scopes, two tokens: one minted for signup must not be spendable on a
- // password reset, so Cap binds the scope into the signature. The reset one
+ // password reset, so the scope is bound into the token (Turnstile action). The reset one
// lives in useForgotPassword, which is the only thing that spends it.
- const signupCap = useCap("signup");
+ const signupTurnstile = useTurnstile("signup");
// Treated as on until the config answers: the only wrong guess is showing a
// code screen, which the server never sends to, and config is cached.
const emailEnabled = useConfig().data?.emailEnabled ?? true;
@@ -753,7 +753,14 @@ function useAuthFlow(mode: "login" | "signup") {
authPasswordRef.current = password;
setBusy(true);
try {
- const deps = { goVerify, failSubmit, qc, navigate, next, capGuarded: signupCap.guarded };
+ const deps = {
+ goVerify,
+ failSubmit,
+ qc,
+ navigate,
+ next,
+ turnstileGuarded: signupTurnstile.guarded,
+ };
await (mode === "login"
? trySignIn(email, password, deps)
: trySignUp(email, password, { ...deps, emailEnabled }));
@@ -843,7 +850,7 @@ function useAuthFlow(mode: "login" | "signup") {
* the visitor types, instead of stalling the submit. Signup only: a
* password reset is rare enough that a short wait on submit is fine, and
* priming it would tax everyone who came to log in. */
- primeSignupCap: signupCap.prime,
+ primeSignupTurnstile: signupTurnstile.prime,
};
}
@@ -887,7 +894,7 @@ function AuthPage({ mode }: { mode: "login" | "signup" }) {
shake={flow.shake}
next={flow.next}
onSubmit={flow.submit}
- onFirstInput={flow.primeSignupCap}
+ onFirstInput={flow.primeSignupTurnstile}
onForgot={(email) => {
flow.setAuthEmail(email);
flow.setView("forgot");
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 53030ccf..855d21f7 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,13 +1,13 @@
import { oneOf } from "./lookup";
-/** Carries a solved Cap token (#98) on the requests that need one. A header,
+/** Carries a solved Turnstile token (#304) on the requests that need one. A header,
* not a body field, because better-auth validates each endpoint's body
* against its own schema. */
-export const CAP_TOKEN_HEADER = "x-cap-token";
+export const TURNSTILE_TOKEN_HEADER = "x-turnstile-token";
-/** What the Worker answers when a Cap token is missing, expired, or already
+/** What the Worker answers when a Turnstile token is missing, expired, or already
* spent. The browser retries once with a fresh one rather than showing it. */
-export const CAP_FAILED_CODE = "CAP_FAILED";
+export const TURNSTILE_FAILED_CODE = "TURNSTILE_FAILED";
/** Anything that survives a round trip through JSON: what a request or
* response body is, before anyone has checked it means what it should. */
@@ -286,6 +286,8 @@ export interface AppConfig {
emailEnabled: boolean;
/** Whether Google sign-in is configured and the button should show. */
googleEnabled: boolean;
+ /** Turnstile site key, public by design. Absent: no check on this instance. */
+ turnstileSiteKey?: string;
}
/** The org's fresh link-quota count, plus when it was read. The timestamp
diff --git a/src/worker/better-auth.ts b/src/worker/better-auth.ts
index 63dd18ee..974eebd1 100644
--- a/src/worker/better-auth.ts
+++ b/src/worker/better-auth.ts
@@ -20,20 +20,20 @@ import { emailConfigured, sendEmail } from "./email";
import { renderEmail } from "./email-layout";
import { hashPassword, verifyPassword } from "./password";
import { uid } from "./util";
-import { spendToken, type CapScope } from "./cap";
+import { spendToken, type TurnstileScope } from "./turnstile";
import { storeUserAvatar, deleteUserAvatar } from "./storage";
import { createOwnedOrg } from "./plan";
import { defaultOrgName } from "@/shared/org-name";
-import { CAP_FAILED_CODE, CAP_TOKEN_HEADER } from "@/shared/types";
+import { TURNSTILE_FAILED_CODE, TURNSTILE_TOKEN_HEADER } from "@/shared/types";
import { mcpResource, fetchClientMetadataResource } from "./mcp-oauth";
-/** better-auth paths that must carry a solved Cap token, and the scope the
- * token has to have been minted for. Keyed by `ctx.path`, which is relative
+/** better-auth paths that must carry a Turnstile token, and the scope the
+ * token has to have been rendered for. Keyed by `ctx.path`, which is relative
* to /api/auth. */
-const CAP_GUARDED_PATHS = {
+const TURNSTILE_GUARDED_PATHS = {
"/sign-up/email": "signup",
"/request-password-reset": "password-reset",
-} satisfies Record;
+} satisfies Record;
/**
* Gives an account an organization if it has none.
@@ -536,22 +536,22 @@ function buildAuth(env: Env) {
// response instead of running the endpoint. Both guards use that to
// answer exactly as the real path would while doing nothing (#53).
before: createAuthMiddleware(async (ctx) => {
- // Cap (#98) sits in front of the two paths a bot actually wants:
+ // Turnstile (#304) sits in front of the two paths a bot actually wants:
// creating accounts, and making us send mail. Not login, where a bot
// with correct credentials is not the threat and every real visitor
// would pay the tax.
- const capScope = lookup(CAP_GUARDED_PATHS, ctx.path);
+ const capScope = lookup(TURNSTILE_GUARDED_PATHS, ctx.path);
if (capScope) {
// In a header, not the body: better-auth validates each endpoint's
// body against its own schema, and an extra key there is at the
// mercy of that schema.
- const token = ctx.headers?.get(CAP_TOKEN_HEADER) ?? "";
+ const token = ctx.headers?.get(TURNSTILE_TOKEN_HEADER) ?? "";
if (!(await spendToken(env, capScope, token)))
// A code, not just a message: the browser retries this once with
// a freshly solved token, and matching on prose to decide that
// would break the first time the wording changed.
throw new APIError("BAD_REQUEST", {
- code: CAP_FAILED_CODE,
+ code: TURNSTILE_FAILED_CODE,
message: "Could not verify you are human. Reload the page and try again.",
});
}
diff --git a/src/worker/cap-unused-dep-stub.ts b/src/worker/cap-unused-dep-stub.ts
deleted file mode 100644
index 6bddca0e..00000000
--- a/src/worker/cap-unused-dep-stub.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Stands in for `esbuild` and `javascript-obfuscator` in the bundle (#98).
- *
- * capjs-core imports both, lazily and inside a try/catch, only to build the
- * script for its browser-instrumentation mode. We do not use that mode: it
- * fingerprints the visitor to spot automation, which is the exact thing we
- * rejected Turnstile for, and proof-of-work needs neither package.
- *
- * The bundler does not know that. It followed the dynamic imports and emitted
- * a 5 MB javascript-obfuscator chunk into the Worker, along with a direct-eval
- * warning, for code that never runs. Aliasing both here throws on import
- * instead, which is precisely what capjs-core's own try/catch expects: it
- * records the tool as unavailable and carries on.
- */
-throw new Error("capjs-core instrumentation is not enabled in this app (#98)");
diff --git a/src/worker/cap.ts b/src/worker/cap.ts
deleted file mode 100644
index 132f9992..00000000
--- a/src/worker/cap.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-/**
- * Cap: proof-of-work challenges, issued and verified by this Worker (#98).
- *
- * A rate limit is a ceiling; this is a price. It catches the distributed,
- * low-and-slow bot that stays politely under every limit, by making each
- * attempt cost real CPU in the caller's browser.
- *
- * `capjs-core` is stateless, so there is no Cap server to run: challenges
- * are signed with CAP_SECRET and verified against that signature. The only
- * state we keep is the single-use nonce, in the KV namespace we already
- * have.
- *
- * Instrumentation is deliberately off. That mode fingerprints the browser to
- * spot automation, which is the exact thing we rejected Turnstile for, and it
- * pulls esbuild and javascript-obfuscator in at runtime to build the probe
- * script. Proof-of-work needs neither.
- */
-import { HTTPException } from "hono/http-exception";
-import { generateChallenge, validateChallenge } from "capjs-core";
-import type { Env } from "./env";
-import { keyedDigest } from "./rate-limit";
-
-/** Namespaces the challenge so a token minted for signup cannot be spent on
- * password reset. Cap binds this into the signature. */
-export type CapScope = "signup" | "password-reset" | "anon-link";
-
-/** How long a solved token stays spendable. Long enough to finish typing a
- * form, short enough that a harvested one is worthless. */
-const TOKEN_TTL_MS = 10 * 60 * 1000;
-/** How long an unsolved challenge stays valid. */
-const CHALLENGE_TTL_MS = 5 * 60 * 1000;
-
-/**
- * Work the client must do. Cap's defaults (50 challenges of difficulty 4)
- * take multiple seconds on a phone, which is a tax on the honest visitor
- * for no extra deterrence. These land around 200-400ms on a laptop while
- * still making bulk automation pay per attempt.
- */
-const CHALLENGE_COUNT = 12;
-const CHALLENGE_SIZE = 24;
-const CHALLENGE_DIFFICULTY = 3;
-
-/** Off unless CAP_SECRET is set, matching SENTRY_DSN and friends: local dev,
- * CI and e2e stay quiet rather than breaking signup. */
-export function capEnabled(env: Env): boolean {
- return !!env.CAP_SECRET;
-}
-
-/**
- * capjs-core refuses a secret under 16 bytes, and it refuses it by throwing
- * at the moment a challenge is issued rather than at startup. Unhandled, that
- * reached the top of the Worker as a 500 with a library stack trace in it.
- *
- * Checked here so the failure is ours and legible. It must stay a failure:
- * treating an unusable secret as "no secret" would fall through to the
- * disabled path and leave signup looking configured and completely
- * unprotected, which is the one outcome worse than being down.
- */
-const MIN_SECRET_BYTES = 16;
-
-function capSecretUsable(env: Env): boolean {
- return new TextEncoder().encode(env.CAP_SECRET ?? "").length >= MIN_SECRET_BYTES;
-}
-
-/** Throws when Cap is switched on with a secret it cannot use. */
-function assertCapUsable(env: Env): void {
- if (!capEnabled(env) || capSecretUsable(env)) return;
- console.error("cap_misconfigured", "CAP_SECRET is shorter than 16 bytes");
- throw new HTTPException(503, {
- message: "Verification is unavailable. Try again shortly.",
- });
-}
-
-export async function issueChallenge(env: Env, scope: CapScope) {
- assertCapUsable(env);
- return generateChallenge(env.CAP_SECRET!, {
- challengeCount: CHALLENGE_COUNT,
- challengeSize: CHALLENGE_SIZE,
- challengeDifficulty: CHALLENGE_DIFFICULTY,
- expiresMs: CHALLENGE_TTL_MS,
- scope,
- });
-}
-
-/**
- * Marks a challenge signature spent, and reports whether it was already.
- *
- * KV is eventually consistent, so a token presented to two colocations at
- * once can pass twice: the write has not propagated yet. That is a real
- * ceiling and it is an acceptable one for a captcha, whose job is to price
- * bulk attempts rather than to guarantee exactly-once. Making it airtight
- * would mean a Durable Object per nonce, which costs more than the replay
- * is worth.
- */
-async function consumeNonce(env: Env, signatureHex: string, ttlMs: number): Promise {
- const key = `cap:${signatureHex}`;
- if (await env.LINKS.get(key)) return false;
- // KV's floor is 60s; a shorter TTL is rejected outright.
- await env.LINKS.put(key, "1", { expirationTtl: Math.max(60, Math.ceil(ttlMs / 1000)) });
- return true;
-}
-
-export async function verifySolution(
- env: Env,
- scope: CapScope,
- body: { token: string; solutions: number[] },
-) {
- return validateChallenge(env.CAP_SECRET!, body, {
- scope,
- tokenTtlMs: TOKEN_TTL_MS,
- consumeNonce: (signatureHex, ttlMs) => consumeNonce(env, signatureHex, ttlMs),
- // Signed, not stored. Cap's default token is a random string the server
- // has to remember, and remembering it here meant a KV write at /redeem
- // read back by the form submit a second later. KV is eventually
- // consistent: that read missed often enough that signup failed for
- // real people, and re-solving lost the same race (#98).
- signToken: ({ expires }) => signToken(env, scope, expires),
- });
-}
-
-/** Compares two same-length strings without leaking where they differ. */
-function equalsConstantTime(a: string, b: string): boolean {
- if (a.length !== b.length) return false;
- let diff = 0;
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
- return diff === 0;
-}
-
-/** `expires.signature`, signed with CAP_SECRET so any colocation can check it
- * without shared state. */
-async function signToken(env: Env, scope: CapScope, expires: number): Promise {
- return `${expires}.${await keyedDigest(env.CAP_SECRET!, `cap:${scope}:${expires}`)}`;
-}
-
-/**
- * Checks the token a form submitted, and burns it.
- *
- * The signature is the whole check, so a valid token is accepted whatever KV
- * knows. KV only records that a token was spent, to turn away a replay: a
- * lookup that misses because the write has not propagated lets one extra
- * submit through within the ten-minute window, which is the direction this
- * should fail in.
- */
-export async function spendToken(env: Env, scope: CapScope, token: string): Promise {
- const outcome = await checkToken(env, scope, token);
- // The caller is told nothing beyond "no", because the reason tells a bot
- // which knob to turn. The log is where somebody holding a support report
- // finds out which of five different failures they are looking at: without
- // it, "could not verify you are human" is the same sentence for a missing
- // token, an expired one, a replayed one, and a wrong secret.
- if (outcome !== "ok") console.warn("cap_refused", scope, outcome);
- return outcome === "ok";
-}
-
-type CapOutcome = "ok" | "missing" | "malformed" | "expired" | "bad_signature" | "already_spent";
-
-async function checkToken(env: Env, scope: CapScope, token: string): Promise {
- if (!capEnabled(env)) return "ok";
- // Set but unusable is not the same as unset: refuse rather than wave the
- // request through on a check that can never have run.
- assertCapUsable(env);
- if (!token) return "missing";
-
- const [expires] = token.split(".");
- const expiresAt = Number(expires);
- if (!expiresAt) return "malformed";
- if (expiresAt < Date.now()) return "expired";
- if (!equalsConstantTime(token, await signToken(env, scope, expiresAt))) return "bad_signature";
-
- const key = `cap:spent:${scope}:${token}`;
- if (await env.LINKS.get(key)) return "already_spent";
- await env.LINKS.put(key, "1", {
- expirationTtl: Math.max(60, Math.ceil((expiresAt - Date.now()) / 1000)),
- });
- return "ok";
-}
diff --git a/src/worker/env.ts b/src/worker/env.ts
index 4356db9d..a4581b58 100644
--- a/src/worker/env.ts
+++ b/src/worker/env.ts
@@ -21,10 +21,6 @@ export interface Env {
(#225), one instance, flushed to D1 on a ~10 s alarm */
CLICK_BUFFER: DurableObjectNamespace;
RL_AUTH_PUBLIC: RateLimit;
- /* Cap's challenge and redeem endpoints (#98), on their own budget: issuing
- a challenge is cheap for us and the proof-of-work is what costs the
- caller, so this must never be the thing a person meets. */
- RL_CAP: RateLimit;
RL_EMAIL: RateLimit;
RL_EMAIL_RECIPIENT: RateLimit;
RL_WRITE_FREE: RateLimit;
@@ -76,8 +72,10 @@ export interface Env {
// Any other value (including unset) calls the real API, or fails closed.
CF_DEV_ENV?: string;
- /* bot protection: Cap proof-of-work (#98). Unset disables the check. */
- CAP_SECRET?: string; // secret, `openssl rand -hex 32`
+ /* bot protection: Cloudflare Turnstile (#304). Secret unset disables the
+ check. */
+ TURNSTILE_SITE_KEY?: string; // var, public
+ TURNSTILE_SECRET_KEY?: string; // secret
/* click buffer: flush interval in ms, e2e only. Unset means 10 s. */
CLICK_FLUSH_MS?: string; // var
diff --git a/src/worker/index.ts b/src/worker/index.ts
index 631e3ffb..6d75f82b 100644
--- a/src/worker/index.ts
+++ b/src/worker/index.ts
@@ -28,7 +28,6 @@ import { avatarRoutes } from "./routes/avatars";
import { adminRoutes } from "./routes/admin";
import { billingRoutes, handlePolarWebhook } from "./routes/billing";
import { domainRoutes } from "./routes/domains";
-import { capRoutes } from "./routes/cap";
import { revalidateOnRedirect } from "./risk";
import { sweepAbusiveOrgs } from "./abuse";
import { evlogMiddleware } from "./evlog";
@@ -200,7 +199,7 @@ async function resolveLink(
// Redirect-only, same as a custom domain: no API, no SPA. SHARED_LINK_HOST
// must not fall through to the full app, or it would also serve
-// /api/auth/* and /api/cap/*, unprotected by the WAF rules that are only
+// /api/auth/*, unprotected by the WAF rules that are only
// ever added to APP_HOST's zone (see docs/rate-limiting.md).
async function resolveSharedLinkHost(c: Context): Promise {
const path = new URL(c.req.url).pathname;
@@ -309,18 +308,8 @@ app.on(
(c) => getAuth(c.env).handler(c.req.raw),
);
-// Cap (#98): public, and necessarily so, since it guards signup itself.
-// Same public rate limit as the auth routes it protects.
-app.post("/api/cap/*", async (c, next) => {
- const log = c.get("log");
- log.set({ route: c.req.path });
- const limited = await enforcePublicAuthRateLimit(c);
- return limited ?? next();
-});
-app.route("/api/cap", capRoutes);
-
// The landing page's anonymous shortener (Direction A of #96): public by
-// definition, and gated by Cap plus its own rate-limit namespace rather than
+// definition, and gated by Turnstile plus its own rate-limit namespace rather than
// by a session.
app.route("/api/shorten", shortenRoutes);
diff --git a/src/worker/rate-limit.ts b/src/worker/rate-limit.ts
index 192fc170..5ad48155 100644
--- a/src/worker/rate-limit.ts
+++ b/src/worker/rate-limit.ts
@@ -9,7 +9,6 @@ const RATE_LIMIT_WINDOW_SECONDS = 60;
export type RateLimitGroup =
| "auth"
- | "cap"
| "email"
| "write"
| "qr_upload"
@@ -124,14 +123,8 @@ async function recipientKey(request: Request, secret: string): Promise env.RL_AUTH_PUBLIC,
- cap: (env) => env.RL_CAP,
email: (env) => env.RL_EMAIL,
-} satisfies Record<"auth" | "cap" | "email", (env: Env) => RateLimit>;
+} satisfies Record<"auth" | "email", (env: Env) => RateLimit>;
export async function enforcePublicAuthRateLimit(c: Context): Promise {
const group = publicAuthGroup(c.req.path);
@@ -185,7 +177,7 @@ export async function enforcePublicAuthRateLimit(c: Context): Promise | null {
+): Exclude | null {
if (/^\/api\/billing\/(?:checkout|portal)$/.test(path)) return "checkout";
if (method === "POST" && /^\/api\/orgs\/[^/]+\/qr-logo\/?$/.test(path)) return "qr_upload";
if (/^\/api\/orgs\/[^/]+\/domains(?:\/|$)/.test(path)) return "domain";
diff --git a/src/worker/routes/auth.ts b/src/worker/routes/auth.ts
index d82a5027..aa7534a4 100644
--- a/src/worker/routes/auth.ts
+++ b/src/worker/routes/auth.ts
@@ -108,5 +108,6 @@ userRoutes.get("/config", (c) => {
linkHost: sharedLinkHost(c.env),
emailEnabled: emailConfigured(c.env),
googleEnabled: Boolean(c.env.GOOGLE_CLIENT_ID && c.env.GOOGLE_CLIENT_SECRET),
+ turnstileSiteKey: c.env.TURNSTILE_SITE_KEY || undefined,
} satisfies AppConfig);
});
diff --git a/src/worker/routes/cap.ts b/src/worker/routes/cap.ts
deleted file mode 100644
index 63e7511d..00000000
--- a/src/worker/routes/cap.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * The two public endpoints Cap's widget talks to (#98).
- *
- * Public by design: they sit in front of signup, so requiring a session
- * would defeat the point. They are covered by the same public auth rate
- * limit as /api/auth/*, and issuing a challenge is cheap while solving one
- * is not, which is the asymmetry the whole scheme rests on.
- */
-import { Hono } from "hono";
-import { optionalText, parseOptionalBody } from "../schemas";
-import * as v from "valibot";
-import type { JsonValue } from "../../shared/types";
-import type { AppEnv } from "../env";
-import { capEnabled, issueChallenge, verifySolution, type CapScope } from "../cap";
-
-const SCOPES: readonly CapScope[] = ["signup", "password-reset", "anon-link"];
-
-/** The scope rides in the path, not the body: Cap's widget builds its own
- * request bodies and only lets us choose the endpoint prefix. */
-function readScope(value: JsonValue): CapScope | null {
- return SCOPES.find((s) => s === value) ?? null;
-}
-
-/** What the redeem route reads off its request body. A solution set that is
- * not a list of numbers is not a solution set. */
-const redeemBodySchema = v.object({
- token: optionalText,
- solutions: v.optional(v.fallback(v.nullable(v.array(v.number())), null), null),
-});
-
-export const capRoutes = new Hono();
-
-capRoutes.post("/:scope/challenge", async (c) => {
- const log = c.get("log");
- log.set({ cap: { scope: c.req.param("scope") } });
- if (!capEnabled(c.env)) return c.json({ disabled: true });
- const scope = readScope(c.req.param("scope"));
- if (!scope) return c.json({ message: "Unknown scope" }, 400);
- return c.json(await issueChallenge(c.env, scope));
-});
-
-capRoutes.post("/:scope/redeem", async (c) => {
- const log = c.get("log");
- log.set({ cap: { scope: c.req.param("scope") } });
- if (!capEnabled(c.env)) return c.json({ disabled: true });
- const scope = readScope(c.req.param("scope"));
- const body = parseOptionalBody(redeemBodySchema, await c.req.json().catch(() => ({})));
- if (!scope || !body.token || !body.solutions)
- return c.json({ success: false, message: "Malformed solution" }, 400);
-
- const result = await verifySolution(c.env, scope, {
- token: body.token,
- solutions: body.solutions,
- });
- // The reason is deliberately not echoed: it tells a bot which knob to
- // turn, and tells a person nothing they can act on.
- if (!result.success) return c.json({ success: false }, 400);
-
- return c.json({ success: true, token: result.token, expires: result.expires });
-});
diff --git a/src/worker/routes/shorten.ts b/src/worker/routes/shorten.ts
index 8dba44c4..97460e40 100644
--- a/src/worker/routes/shorten.ts
+++ b/src/worker/routes/shorten.ts
@@ -9,8 +9,7 @@
*
* This is an unauthenticated write path, which is the most abused endpoint
* shape there is, so it does not ship alone:
- * - Cap proof-of-work (#98) on the "anon-link" scope, so each attempt costs
- * the caller real CPU.
+ * - Turnstile (#304) on the "anon-link" scope, so a bot has to pass a challenge.
* - Its own rate-limit namespace, not the one guarding auth: a flood here
* must not lock anybody out of signing in.
* - Destination scoring (#68) after the response, same as a real link.
@@ -30,8 +29,8 @@ import { jsonBodyLimit } from "../body-limit";
import { assertNotShortener } from "../abuse";
import { publishLink, resolveSlug, unpublishLink } from "../kv";
import { scoreAndRecord } from "../risk";
-import { spendToken } from "../cap";
-import { CAP_FAILED_CODE } from "@/shared/types";
+import { spendToken } from "../turnstile";
+import { TURNSTILE_FAILED_CODE } from "@/shared/types";
import { isValidHttpUrl, linkUrl, normalizeUrl, randomSlug, uid } from "../util";
import { publicClientKey, rateLimitAllows } from "../rate-limit";
import { insertLinkWithinLimit, orgPlan } from "../plan";
@@ -42,7 +41,7 @@ const ANON_LINK_TTL_MS = 24 * 60 * 60 * 1000;
/** What the anonymous shortener reads off its request body. */
const shortenBodySchema = v.object({
destination: optionalText,
- capToken: optionalText,
+ turnstileToken: optionalText,
});
export const shortenRoutes = new Hono();
@@ -65,12 +64,12 @@ shortenRoutes.post("/", async (c) => {
await c.req.json().catch(() => ({})),
);
- if (!(await spendToken(c.env, "anon-link", body.capToken)))
+ if (!(await spendToken(c.env, "anon-link", body.turnstileToken)))
// Coded so the browser can solve again and retry once, rather than
// showing somebody an error they cannot act on.
throw new HTTPException(400, {
message: "Could not verify you are human. Reload the page and try again.",
- cause: { code: CAP_FAILED_CODE },
+ cause: { code: TURNSTILE_FAILED_CODE },
});
if (!body.destination.trim())
@@ -290,7 +289,7 @@ export async function claimAnonLink(
createdAt: Date.now(),
};
- // Through the same cap-guarded insert every other link goes through, not a
+ // Through the same plan-guarded insert every other link goes through, not a
// raw one: claiming is still creating a link in somebody's organization,
// and an org one under its limit must not be able to take ten.
const { limits } = await orgPlan(db, orgId);
diff --git a/src/worker/security-headers.ts b/src/worker/security-headers.ts
index ba9cfeae..297b6bf3 100644
--- a/src/worker/security-headers.ts
+++ b/src/worker/security-headers.ts
@@ -26,6 +26,8 @@ const POSTHOG = "https://*.posthog.com";
const SENTRY =
"https://*.ingest.sentry.io https://*.ingest.de.sentry.io https://*.ingest.us.sentry.io";
const STATS = "https://stats.brnr.dev";
+// Turnstile (#304): its script, and the iframe the challenge renders in.
+const TURNSTILE = "https://challenges.cloudflare.com";
/**
* The theme bootstrap in index.html, allowed by its own sha256 rather than
@@ -60,15 +62,9 @@ const THEME_INIT_HASH = "'sha256-FWT0zAeXgLYQzK+k6AJ0ya6gTIN/5TC8uQ3OB6H8w6A='";
// so a deployed Worker cannot ship 'unsafe-inline' through a misread var.
// The tradeoff is that e2e exercises a marginally looser policy than
// production; everything except this one directive is identical.
-// 'wasm-unsafe-eval' is for Cap's solver (#98). WebAssembly.compile() counts
-// as script evaluation, so `script-src 'self'` refuses it outright and the
-// widget falls back to a pure-JS solver. This directive exists precisely to
-// allow WASM without allowing eval() or inline script: it buys back the fast
-// path on the phones that need it most, and grants nothing else. The module
-// itself is a same-origin Vite asset, never a CDN.
const SCRIPT_SRC = import.meta.env.DEV
- ? `script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' ${POSTHOG} ${STATS}`
- : `script-src 'self' ${THEME_INIT_HASH} 'wasm-unsafe-eval' ${POSTHOG} ${STATS}`;
+ ? `script-src 'self' 'unsafe-inline' ${POSTHOG} ${STATS} ${TURNSTILE}`
+ : `script-src 'self' ${THEME_INIT_HASH} ${POSTHOG} ${STATS} ${TURNSTILE}`;
const CSP = [
"default-src 'self'",
@@ -76,15 +72,8 @@ const CSP = [
"style-src 'self' 'unsafe-inline'",
`img-src 'self' data: ${POSTHOG}`,
"font-src 'self'",
- // Cap (#98) solves its proof-of-work in a Web Worker built from a Blob
- // URL, and with no worker-src the browser falls through child-src to
- // default-src 'self', which refuses blob:. Everything else about Cap is
- // same-origin: the widget is bundled from npm and its WASM ships as a
- // Vite asset, so nothing here opens a door to a third party. The cost is
- // that a script which already ran could spawn a worker from a string it
- // built, which script-src 'self' still gates on getting there first.
- "worker-src 'self' blob:",
- `connect-src 'self' ${POSTHOG} ${SENTRY} ${STATS}`,
+ `connect-src 'self' ${POSTHOG} ${SENTRY} ${STATS} ${TURNSTILE}`,
+ `frame-src ${TURNSTILE}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
diff --git a/src/worker/turnstile.ts b/src/worker/turnstile.ts
new file mode 100644
index 00000000..313dae0e
--- /dev/null
+++ b/src/worker/turnstile.ts
@@ -0,0 +1,65 @@
+/**
+ * Cloudflare Turnstile in front of signup, password reset and the anonymous
+ * shortener (#304).
+ *
+ * The browser solves the challenge and hands us a single-use token; we ask
+ * Cloudflare's siteverify whether it is good. Siteverify also burns the
+ * token, so there is no state of our own to keep.
+ */
+import type { Env } from "./env";
+
+/** Binds the widget to the form it was rendered for: siteverify echoes the
+ * `action` back, so a token earned on one form cannot open another. */
+export type TurnstileScope = "signup" | "password-reset" | "anon-link";
+
+const SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
+
+/** Off unless TURNSTILE_SECRET_KEY is set, matching SENTRY_DSN and friends:
+ * self-hosters and local dev run without it. Keyed on the secret, not the
+ * site key: a secret with no site key must refuse every request, never
+ * quietly turn the check off. */
+export function turnstileEnabled(env: Env): boolean {
+ return !!env.TURNSTILE_SECRET_KEY;
+}
+
+interface SiteverifyResponse {
+ success: boolean;
+ action?: string;
+ "error-codes"?: string[];
+}
+
+/**
+ * Checks the token a form submitted.
+ *
+ * The caller is told nothing beyond "no", because the reason tells a bot
+ * which knob to turn; the log is where a support report finds out whether it
+ * was a missing token, a replay, or a wrong secret.
+ */
+export async function spendToken(env: Env, scope: TurnstileScope, token: string): Promise {
+ if (!turnstileEnabled(env)) return true;
+ if (!token) {
+ console.warn("turnstile_refused", scope, "missing");
+ return false;
+ }
+
+ let result: SiteverifyResponse;
+ try {
+ const res = await fetch(SITEVERIFY_URL, {
+ method: "POST",
+ // No remoteip: it is optional, and we do not hand visitor addresses to
+ // anyone we do not have to.
+ body: new URLSearchParams({ secret: env.TURNSTILE_SECRET_KEY!, response: token }),
+ });
+ // SAFETY: siteverify documents this JSON shape; success is the only field
+ // read without a fallback, and a missing one reads as a refusal.
+ result = (await res.json()) as SiteverifyResponse;
+ } catch (cause) {
+ // Fail closed: an unreachable verifier is no reason to let bots in.
+ console.error("turnstile_unreachable", cause);
+ return false;
+ }
+
+ const ok = result.success === true && result.action === scope;
+ if (!ok) console.warn("turnstile_refused", scope, result["error-codes"]?.join(",") ?? "action");
+ return ok;
+}
diff --git a/tests/cap-loader.test.ts b/tests/cap-loader.test.ts
deleted file mode 100644
index 591bf6cb..00000000
--- a/tests/cap-loader.test.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { describe, expect, test } from "bun:test";
-
-/**
- * The widget loader's caching rule, which is the whole bug this file exists
- * for: a load that fails must not be remembered.
- *
- * `loading ??= makePromise()` kept whatever the first attempt settled to. One
- * bad fetch (a dev server restarting under an open tab, a chunk that 404s
- * after a deploy, a dropped connection) therefore poisoned every later solve
- * in that tab: the form said "could not verify you are human" on every
- * attempt from then on, and nothing but a reload cleared it.
- *
- * The loader itself imports the widget and a WASM asset, so this tests the
- * caching rule against the same shape rather than the module: bun's test
- * runner cannot resolve `?url` asset imports.
- */
-function makeLoader(load: () => Promise) {
- let loading: Promise | null = null;
- return () => {
- loading ??= load().catch((error: Error) => {
- loading = null;
- throw error;
- });
- return loading;
- };
-}
-
-describe("loading the proof-of-work widget", () => {
- test("loads once and reuses it", async () => {
- let calls = 0;
- const loadCap = makeLoader(async () => {
- calls++;
- });
-
- await loadCap();
- await loadCap();
- await loadCap();
-
- expect(calls).toBe(1);
- });
-
- test("tries again after a failure instead of failing forever", async () => {
- let calls = 0;
- const loadCap = makeLoader(async () => {
- calls++;
- if (calls === 1) throw new Error("chunk 404");
- });
-
- await expect(loadCap()).rejects.toThrow("chunk 404");
- // The attempt that used to inherit the first one's failure for the life
- // of the tab.
- await loadCap();
-
- expect(calls).toBe(2);
- });
-
- test("goes back to reusing one load once it succeeds", async () => {
- let calls = 0;
- const loadCap = makeLoader(async () => {
- calls++;
- if (calls === 1) throw new Error("offline");
- });
-
- await expect(loadCap()).rejects.toThrow("offline");
- await loadCap();
- await loadCap();
-
- expect(calls).toBe(2);
- });
-});
-
-/**
- * The two rules that keep a solve from silently producing nothing.
- *
- * Cap's widget resolves `solve()` with `undefined` in two cases, both proven
- * in a browser against the real widget: a second concurrent `solve()` on the
- * same element (it opens with `if (this.#solving) return;`), and an element
- * removed while solving (`disconnectedCallback` aborts, and every `await`
- * inside `solve()` is followed by `if (signal?.aborted) return;`). Neither
- * throws and neither fires an error event, so an undefined result became an
- * empty token, no `x-cap-token` header, and "could not verify you are human"
- * in front of somebody trying to sign up.
- *
- * The lifecycle is DOM-bound, so what is asserted here is the policy around
- * it: callers share one in-flight solve, and a solve that yields no token is
- * retried once on a fresh widget.
- */
-function makeSolver(solve: (attempt: number) => Promise<{ token?: string } | null>) {
- let inFlight: Promise | null = null;
- let built = 0;
- const run = () => {
- inFlight ??= (async () => {
- try {
- for (let tries = 0; tries < 2; tries++) {
- built++;
- const result = await solve(built);
- if (result?.token) return result.token;
- }
- return "";
- } finally {
- inFlight = null;
- }
- })();
- return inFlight;
- };
- return { run, widgets: () => built };
-}
-
-describe("solving a challenge", () => {
- test("two callers at once share one solve rather than racing the widget", async () => {
- const solver = makeSolver(async () => ({ token: "t" }));
-
- const [a, b] = await Promise.all([solver.run(), solver.run()]);
-
- expect([a, b]).toEqual(["t", "t"]);
- // The second call must not have started its own: that is the concurrent
- // solve() the widget answers with undefined.
- expect(solver.widgets()).toBe(1);
- });
-
- test("retries once on a fresh widget when a solve comes back empty", async () => {
- // What an aborted solve looks like from here: no token, no error.
- const solver = makeSolver(async (attempt) => (attempt === 1 ? undefined : { token: "t" }));
-
- expect(await solver.run()).toBe("t");
- expect(solver.widgets()).toBe(2);
- });
-
- test("gives up after the second empty solve instead of looping", async () => {
- const solver = makeSolver(async () => undefined);
-
- expect(await solver.run()).toBe("");
- expect(solver.widgets()).toBe(2);
- });
-
- test("a later solve starts fresh once the first has settled", async () => {
- const solver = makeSolver(async () => ({ token: "t" }));
-
- await solver.run();
- await solver.run();
-
- expect(solver.widgets()).toBe(2);
- });
-});
diff --git a/tests/e2e/production/csp.pw.ts b/tests/e2e/production/csp.pw.ts
index 2847bd9f..16c60ff1 100644
--- a/tests/e2e/production/csp.pw.ts
+++ b/tests/e2e/production/csp.pw.ts
@@ -2,11 +2,6 @@ import { expect, test } from "@playwright/test";
import { collectCspViolations, cspViolations, scriptIsBlocked } from "../csp";
import { visitLegalPages } from "../pages";
-/** The Cap widget element, once its custom element has been defined. */
-interface CapWidget extends HTMLElement {
- solve: () => Promise<{ token?: string }>;
-}
-
/**
* These run against `vite preview`, i.e. the built worker and built assets,
* because that is the only place the production Content-Security-Policy is in
@@ -34,7 +29,7 @@ test("the built worker serves the production CSP", async ({ page }) => {
// no 'unsafe-inline', which is the whole point of naming it by hash.
const scriptSrc = csp?.split(";").find((part) => part.trim().startsWith("script-src"));
expect(scriptSrc?.trim()).toBe(
- "script-src 'self' 'sha256-FWT0zAeXgLYQzK+k6AJ0ya6gTIN/5TC8uQ3OB6H8w6A=' 'wasm-unsafe-eval' https://*.posthog.com https://stats.brnr.dev",
+ "script-src 'self' 'sha256-FWT0zAeXgLYQzK+k6AJ0ya6gTIN/5TC8uQ3OB6H8w6A=' https://*.posthog.com https://stats.brnr.dev https://challenges.cloudflare.com",
);
const connectSrc = csp?.split(";").find((part) => part.trim().startsWith("connect-src"));
expect(connectSrc?.trim()).toBe(
@@ -60,48 +55,44 @@ test("the inlined theme bootstrap survives the production CSP", async ({ browser
});
/**
- * Cap's proof-of-work (#98) is the part of this app most likely to be
- * strangled by our own policy, and it fails quietly: the widget catches its
- * own errors, so a blocked Worker or a refused WebAssembly.compile() would
- * leave signup apparently fine and completely unprotected.
- *
- * So this asserts the mechanism, not just the absence of complaints. The
- * solver runs in a Worker built from a blob: URL (worker-src) and compiles a
- * same-origin WASM module (script-src 'wasm-unsafe-eval'). Both were blocked
- * by the policy as it stood before this feature; the measured cost of losing
- * the WASM path is roughly 5x on solve time.
+ * Turnstile (#304) is the part of this app most likely to be strangled by our
+ * own policy, and it fails quietly: a blocked script or iframe leaves signup
+ * looking fine with no token to send. So this asserts the mechanism, not just
+ * the absence of complaints: the script loads from challenges.cloudflare.com
+ * and the widget, rendered with Cloudflare's always-pass test key, hands back
+ * a token, with no CSP violation along the way.
*/
-test("Cap solves a challenge under the production CSP", async ({ page }) => {
+test("Turnstile solves a challenge under the production CSP", async ({ page }) => {
await page.goto("/signup");
- // The widget only loads once the visitor touches the form, which is the
- // whole point: no cost to anyone who does not sign up.
// /signup is prerendered, so an input typed before hydration finishes never
- // reaches the handler that starts the widget (the solve then happens at
- // submit instead). Type again until the handler is there.
+ // reaches the handler that starts the widget. Type again until it is there.
let attempt = 0;
await expect(async () => {
attempt += 1;
await page.getByRole("textbox").first().fill(`csp-probe-${attempt}@example.com`);
- await page.waitForFunction(() => !!customElements.get("cap-widget"), null, { timeout: 3_000 });
+ await page.waitForFunction(() => !!window.turnstile, null, { timeout: 3_000 });
}).toPass({ timeout: 20_000 });
- const solved = await page.evaluate(async () => {
- // SAFETY: the line above waited for customElements to define
- // "cap-widget", so createElement returns an upgraded widget with solve()
- // on it rather than an unknown element.
- const el = document.createElement("cap-widget") as CapWidget;
- el.setAttribute("data-cap-api-endpoint", "/api/cap/signup/");
- el.style.cssText = "position:absolute;width:1px;height:1px;opacity:0";
- document.body.appendChild(el);
- try {
- return (await el.solve())?.token ?? "";
- } finally {
- el.remove();
- }
- });
+ const token = await page.evaluate(
+ (siteKey) =>
+ new Promise((resolve) => {
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ window.turnstile?.render(host, {
+ sitekey: siteKey,
+ action: "signup",
+ appearance: "interaction-only",
+ callback: resolve,
+ "error-callback": () => resolve(""),
+ "timeout-callback": () => resolve(""),
+ });
+ setTimeout(() => resolve(""), 15_000);
+ }),
+ "1x00000000000000000000AA",
+ );
- expect(solved).not.toBe("");
+ expect(token).not.toBe("");
expect(await cspViolations(page)).toEqual([]);
});
diff --git a/tests/e2e/qr-generator.pw.ts b/tests/e2e/qr-generator.pw.ts
index 01d41eef..dad7ea22 100644
--- a/tests/e2e/qr-generator.pw.ts
+++ b/tests/e2e/qr-generator.pw.ts
@@ -20,8 +20,7 @@ declare global {
*/
/** Records every POST the page makes, so "nothing leaves the browser" can be
- * asserted rather than asserted about. Cap's own challenge and redeem are the
- * one exception, and only when somebody asks for a trackable link. */
+ * asserted rather than asserted about. */
function watchPosts(page: Page): string[] {
const posted: string[] = [];
page.on("request", (r) => {
@@ -30,17 +29,10 @@ function watchPosts(page: Page): string[] {
return posted;
}
-/** Application POSTs other than Cap proving the visitor is human. */
+/** POSTs to the app's own origin. */
function appPosts(page: Page, posted: string[]): string[] {
const appOrigin = new URL(page.url()).origin;
- return posted.filter((url) => {
- const request = new URL(url);
- return (
- request.origin === appOrigin &&
- request.pathname !== "/api/cap/challenge" &&
- request.pathname !== "/api/cap/redeem"
- );
- });
+ return posted.filter((url) => new URL(url).origin === appOrigin);
}
/**
diff --git a/tests/cap-retry.test.ts b/tests/turnstile-retry.test.ts
similarity index 58%
rename from tests/cap-retry.test.ts
rename to tests/turnstile-retry.test.ts
index 0e55e487..a3572881 100644
--- a/tests/cap-retry.test.ts
+++ b/tests/turnstile-retry.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from "bun:test";
-import { CAP_FAILED_CODE } from "@/shared/types";
-import { isCapFailure, retryOnCapFailure } from "@/app/lib/cap-retry";
+import { TURNSTILE_FAILED_CODE } from "@/shared/types";
+import { isTurnstileFailure, retryOnTurnstileFailure } from "@/app/lib/turnstile-retry";
/**
- * The second go at a refused Cap token (#98).
+ * The second go at a refused Turnstile token (#304).
*
* A token is single use and short lived, so a refusal is routine: it expired,
* the server already burned it, or it forgot it. The visitor did none of that
@@ -25,68 +25,71 @@ function refusals(...results: unknown[]) {
const sent: string[] = [];
let call = 0;
const run = async (headers: Record) => {
- sent.push(headers["x-cap-token"] ?? "");
+ sent.push(headers["x-turnstile-token"] ?? "");
const result = results[call++];
if (result instanceof Error) throw result;
return result;
};
let token = 0;
- const headers = async () => ({ "x-cap-token": `token-${++token}` });
+ const headers = async () => ({ "x-turnstile-token": `token-${++token}` });
return { run, headers, sent };
}
describe("recognizing a refused token", () => {
test("reads better-auth's returned error", () => {
- expect(isCapFailure({ error: { code: CAP_FAILED_CODE } })).toBe(true);
+ expect(isTurnstileFailure({ error: { code: TURNSTILE_FAILED_CODE } })).toBe(true);
});
test("reads the thrown ApiError", () => {
- expect(isCapFailure(new ApiError(CAP_FAILED_CODE))).toBe(true);
+ expect(isTurnstileFailure(new ApiError(TURNSTILE_FAILED_CODE))).toBe(true);
});
test("leaves anything else alone", () => {
- expect(isCapFailure(new ApiError("slug_taken"))).toBe(false);
- expect(isCapFailure({ error: { code: "rate_limited" } })).toBe(false);
- expect(isCapFailure({ slug: "abc" })).toBe(false);
- expect(isCapFailure(null)).toBe(false);
+ expect(isTurnstileFailure(new ApiError("slug_taken"))).toBe(false);
+ expect(isTurnstileFailure({ error: { code: "rate_limited" } })).toBe(false);
+ expect(isTurnstileFailure({ slug: "abc" })).toBe(false);
+ expect(isTurnstileFailure(null)).toBe(false);
});
});
-describe("running a Cap-guarded request", () => {
+describe("running a Turnstile-guarded request", () => {
test("passes the first answer through, with one token", async () => {
const { run, headers, sent } = refusals({ slug: "abc" });
- expect(await retryOnCapFailure(run, headers)).toEqual({ slug: "abc" });
+ expect(await retryOnTurnstileFailure(run, headers)).toEqual({ slug: "abc" });
expect(sent).toEqual(["token-1"]);
});
test("solves again when the token comes back thrown", async () => {
- const { run, headers, sent } = refusals(new ApiError(CAP_FAILED_CODE), { slug: "abc" });
+ const { run, headers, sent } = refusals(new ApiError(TURNSTILE_FAILED_CODE), { slug: "abc" });
- expect(await retryOnCapFailure(run, headers)).toEqual({ slug: "abc" });
+ expect(await retryOnTurnstileFailure(run, headers)).toEqual({ slug: "abc" });
// A fresh token, not the one the server already spent.
expect(sent).toEqual(["token-1", "token-2"]);
});
test("solves again when the token comes back returned", async () => {
- const { run, headers, sent } = refusals({ error: { code: CAP_FAILED_CODE } }, { slug: "abc" });
+ const { run, headers, sent } = refusals(
+ { error: { code: TURNSTILE_FAILED_CODE } },
+ { slug: "abc" },
+ );
- expect(await retryOnCapFailure(run, headers)).toEqual({ slug: "abc" });
+ expect(await retryOnTurnstileFailure(run, headers)).toEqual({ slug: "abc" });
expect(sent).toEqual(["token-1", "token-2"]);
});
test("raises anything that is not about the token, without a second attempt", async () => {
const { run, headers, sent } = refusals(new ApiError("slug_taken"), { slug: "abc" });
- await expect(retryOnCapFailure(run, headers)).rejects.toThrow("slug_taken");
+ await expect(retryOnTurnstileFailure(run, headers)).rejects.toThrow("slug_taken");
expect(sent).toEqual(["token-1"]);
});
test("stops at two, so a real refusal reaches the screen", async () => {
- const refused = new ApiError(CAP_FAILED_CODE);
+ const refused = new ApiError(TURNSTILE_FAILED_CODE);
const { run, headers, sent } = refusals(refused, refused, { slug: "abc" });
- await expect(retryOnCapFailure(run, headers)).rejects.toThrow(CAP_FAILED_CODE);
+ await expect(retryOnTurnstileFailure(run, headers)).rejects.toThrow(TURNSTILE_FAILED_CODE);
expect(sent).toEqual(["token-1", "token-2"]);
});
});
diff --git a/tests/worker/cap-disabled.worker.ts b/tests/worker/cap-disabled.worker.ts
deleted file mode 100644
index dd8bf00b..00000000
--- a/tests/worker/cap-disabled.worker.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { beforeEach, expect, it } from "vitest";
-import { reset } from "cloudflare:test";
-import { applyTestMigrations, captureEmails, fetchWorker, overrideEnv } from "./support";
-import { spendToken } from "../../src/worker/cap";
-
-/**
- * Cap with no CAP_SECRET set (#98): the gate is off and signup works exactly
- * as it did before, which is what keeps local dev, CI and the e2e run from
- * needing a secret.
- *
- * Its own file because getAuth() memoizes one auth instance per isolate, and
- * that instance closes over the env that built it. A test sharing a file with
- * the enabled cases would inherit the enabled hook no matter which env it
- * passed. Bindings are stable in production, so nothing here is a product
- * defect: it is the cost of that cache, paid in test layout.
- */
-beforeEach(async () => {
- reset();
- await applyTestMigrations();
- captureEmails({ mx: "deliverable" });
-});
-
-it("lets signup through untouched when no secret is configured", async () => {
- const res = await fetchWorker(
- new Request("http://localhost/api/auth/sign-up/email", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
- email: "nosecret@example.com",
- password: "a-good-password-1",
- name: "probe",
- }),
- }),
- overrideEnv({ BETTER_AUTH_SECRET: "test-secret", CAP_SECRET: undefined }),
- );
- expect(res.status).toBe(200);
-});
-
-it("refuses a challenge when the secret is too short to use", async () => {
- // capjs-core refuses a secret under 16 bytes by throwing, and it throws
- // when a challenge is issued rather than at startup. Which way that falls
- // is the point: a secret that is set but unusable must take the Cap route
- // down, never fall through to the disabled path and leave signup looking
- // configured and completely unprotected. `capEnabled` only asks whether
- // the secret is set, so "set but unusable" is exactly the gap between the
- // two, and it is answered by us rather than by a library stack trace
- // reaching the top of the Worker.
- const res = await fetchWorker(
- new Request("http://localhost/api/cap/signup/challenge", { method: "POST" }),
- overrideEnv({ BETTER_AUTH_SECRET: "test-secret", CAP_SECRET: "tooshort" }),
- );
-
- expect(res.status).toBe(503);
-});
-
-it("refuses to spend a token when the secret is too short to use", async () => {
- // The other half: the check that decides whether a signup is let through
- // must not answer "ok" on a secret no challenge could have been signed
- // with. Called directly rather than through signup, because getAuth()
- // memoizes one auth instance per isolate (see above) and the first test in
- // this file already built one with Cap disabled.
- await expect(
- spendToken(overrideEnv({ CAP_SECRET: "tooshort" }), "signup", "1.deadbeef"),
- ).rejects.toThrow();
-});
diff --git a/tests/worker/cap-rate-limit.worker.ts b/tests/worker/cap-rate-limit.worker.ts
deleted file mode 100644
index 397c8db6..00000000
--- a/tests/worker/cap-rate-limit.worker.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { createExecutionContext, reset, waitOnExecutionContext } from "cloudflare:test";
-import worker from "../../src/worker";
-import type { Env } from "../../src/worker/env";
-import {
- applyTestMigrations,
- exhaustedLimit,
- openLimit,
- overrideEnv,
- recordingLimit,
-} from "./support";
-import type { JsonValue } from "../../src/shared/types";
-
-/**
- * Cap's endpoints spend their own budget, not signup's (#98).
- *
- * They were briefly counted against RL_AUTH_PUBLIC, which is the worst place
- * for them: a person fills the form, the widget asks for a challenge, the
- * counter is out, and the browser can produce no token at all. What they then
- * see is "could not verify you are human", which reads as an accusation
- * rather than as "wait a minute" — and the built-in retry spends two more
- * requests against the same exhausted budget, so it never helps.
- *
- * The counters are asserted through stub bindings rather than by spending
- * real ones: Cloudflare's per-location counters do not reset between cases.
- */
-
-async function post(testEnv: Env, path: string, body: JsonValue = {}): Promise {
- const ctx = createExecutionContext();
- const res = await worker.fetch(
- new Request(`http://localhost${path}`, {
- method: "POST",
- headers: { "content-type": "application/json", "cf-connecting-ip": "203.0.113.7" },
- body: JSON.stringify(body),
- }),
- testEnv,
- ctx,
- );
- await waitOnExecutionContext(ctx);
- return res;
-}
-
-const CAP_ON = (overrides: Partial) =>
- overrideEnv({
- BETTER_AUTH_SECRET: "test-secret",
- CAP_SECRET: "cap-test-secret-long-enough-to-be-accepted",
- ...overrides,
- });
-
-beforeEach(applyTestMigrations);
-afterEach(reset);
-
-describe("the budget Cap spends", () => {
- it("keeps issuing challenges when the signup budget is gone", async () => {
- // The case that took signup down: somebody who has been trying to log in
- // must still be able to prove they are human.
- const res = await post(
- CAP_ON({ RL_AUTH_PUBLIC: exhaustedLimit(), RL_CAP: openLimit() }),
- "/api/cap/signup/challenge",
- );
- expect(res.status).toBe(200);
- });
-
- it("refuses when its own budget is gone", async () => {
- const res = await post(
- CAP_ON({ RL_AUTH_PUBLIC: openLimit(), RL_CAP: exhaustedLimit() }),
- "/api/cap/signup/challenge",
- );
- expect(res.status).toBe(429);
- expect(res.headers.get("x-ratelimit-group")).toBe("cap");
- });
-
- it("counts a challenge and a redeem separately, per caller", async () => {
- const keys: string[] = [];
- const env = CAP_ON({ RL_AUTH_PUBLIC: openLimit(), RL_CAP: recordingLimit(keys) });
-
- await post(env, "/api/cap/signup/challenge");
- await post(env, "/api/cap/signup/redeem", { token: "x", solutions: [] });
-
- expect(keys).toHaveLength(2);
- expect(new Set(keys).size).toBe(2);
- // The caller is a keyed digest, never the address itself.
- for (const key of keys) {
- expect(key.startsWith("cap:")).toBe(true);
- expect(key).not.toContain("203.0.113.7");
- }
- });
-
- it("leaves the auth routes on the auth budget", async () => {
- // Sign-up is not the example here: it sends mail, so it spends the email
- // budget. Sign-in is the plain auth case.
- const res = await post(
- CAP_ON({ RL_AUTH_PUBLIC: exhaustedLimit(), RL_CAP: openLimit() }),
- "/api/auth/sign-in/email",
- { email: "someone@example.com", password: "a-good-password-1" },
- );
- expect(res.status).toBe(429);
- expect(res.headers.get("x-ratelimit-group")).toBe("auth");
- });
-});
diff --git a/tests/worker/cap.worker.ts b/tests/worker/cap.worker.ts
deleted file mode 100644
index c194399e..00000000
--- a/tests/worker/cap.worker.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { beforeEach, describe, expect, it } from "vitest";
-import { env } from "cloudflare:workers";
-import { reset } from "cloudflare:test";
-import { applyTestMigrations, captureEmails, fetchWorker, jsonBody, overrideEnv } from "./support";
-import type { JsonValue } from "../../src/shared/types";
-
-/** What /api/cap/:scope/challenge answers with. */
-interface Challenge {
- token: string;
- challenge: { c: number; s: number; d: number };
-}
-
-/** What /api/cap/:scope/redeem answers with. */
-interface Redeemed {
- success?: boolean;
- token?: string;
-}
-
-/**
- * Cap, the proof-of-work gate in front of signup and password reset (#98).
- *
- * The browser side (widget, Web Worker, WASM, CSP) is asserted in
- * tests/e2e/production/csp.pw.ts and exercised by every signup scenario,
- * because CAP_SECRET is set in .dev.vars.example. What is left for here is
- * the part a browser cannot show: that a forged, reused, or absent token is
- * refused, and that an unset secret disables the gate instead of breaking
- * the form.
- */
-
-// capjs-core refuses a secret under 16 bytes, and refuses it by throwing
-// inside the challenge route. That is fail-closed, which is the right way
-// round for a security control, but it does mean a too-short CAP_SECRET
-// takes signup down rather than quietly running unprotected.
-const CAP_ON = () =>
- overrideEnv({
- BETTER_AUTH_SECRET: "test-secret",
- CAP_SECRET: "cap-test-secret-long-enough-to-be-accepted",
- });
-
-function capPost(path: string, body: JsonValue, testEnv = CAP_ON()) {
- return fetchWorker(
- new Request(`http://localhost/api/cap/${path}`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- }),
- testEnv,
- );
-}
-
-/** Brute-forces one Cap challenge the way the browser's worker does: find a
- * nonce whose sha256(salt + nonce) starts with the target prefix. */
-async function solve(salt: string, target: string): Promise {
- for (let nonce = 0; ; nonce++) {
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(salt + nonce));
- const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
- if (hex.startsWith(target)) return nonce;
- }
-}
-
-/**
- * Cap's salt/target derivation, copied because the package does not export
- * it. Salts are never sent: both sides derive them from the token, so a test
- * that wants to solve a real challenge has to derive them too.
- *
- * Copying it does couple this test to Cap's internals, which is why it is
- * only here and not in src: if they change the PRNG, redeem starts returning
- * 400 and these tests fail loudly rather than quietly testing nothing.
- */
-function prng(seed: string, length: number): string {
- let hash = 2166136261;
- for (let i = 0; i < seed.length; i++) {
- hash ^= seed.charCodeAt(i);
- hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
- }
- let state = hash >>> 0;
- let result = "";
- while (result.length < length) {
- state ^= state << 13;
- state ^= state >>> 17;
- state ^= state << 5;
- state >>>= 0;
- result += state.toString(16).padStart(8, "0");
- }
- return result.substring(0, length);
-}
-
-async function solveAll(token: string, spec: { c: number; s: number; d: number }) {
- const solutions: number[] = [];
- for (let i = 1; i <= spec.c; i++) {
- solutions.push(await solve(prng(`${token}${i}`, spec.s), prng(`${token}${i}d`, spec.d)));
- }
- return solutions;
-}
-
-function signUp(email: string, headers: Record = {}, testEnv = CAP_ON()) {
- return fetchWorker(
- new Request("http://localhost/api/auth/sign-up/email", {
- method: "POST",
- headers: { "content-type": "application/json", ...headers },
- body: JSON.stringify({ email, password: "a-good-password-1", name: "probe" }),
- }),
- testEnv,
- );
-}
-
-beforeEach(async () => {
- reset();
- await applyTestMigrations();
- captureEmails({ mx: "deliverable" });
-});
-
-describe("issuing and redeeming", () => {
- it("mints a challenge, and redeems a correct solution for a token", async () => {
- const challenge = await jsonBody(await capPost("signup/challenge", {}));
- expect(challenge.challenge.c).toBeGreaterThan(0);
-
- const redeemed = await jsonBody(
- await capPost("signup/redeem", {
- token: challenge.token,
- solutions: await solveAll(challenge.token, challenge.challenge),
- }),
- );
-
- expect(redeemed.success).toBe(true);
- expect(redeemed.token).toBeTruthy();
- });
-
- it("refuses a wrong solution", async () => {
- const challenge = await jsonBody(await capPost("signup/challenge", {}));
- const res = await capPost("signup/redeem", {
- token: challenge.token,
- solutions: Array.from({ length: challenge.challenge?.c ?? 12 }, () => 1),
- });
- expect(res.status).toBe(400);
- });
-
- it("refuses a scope nobody offers", async () => {
- expect((await capPost("admin/challenge", {})).status).toBe(400);
- });
-});
-
-describe("spending a token at signup", () => {
- async function mintToken(scope = "signup") {
- const challenge = await jsonBody(await capPost(`${scope}/challenge`, {}));
- const redeemed = await jsonBody(
- await capPost(`${scope}/redeem`, {
- token: challenge.token,
- solutions: await solveAll(challenge.token, challenge.challenge),
- }),
- );
- if (!redeemed.token) throw new Error("redeem answered without a token");
- return redeemed.token;
- }
-
- it("accepts a freshly redeemed token", async () => {
- const res = await signUp("fresh@example.com", { "x-cap-token": await mintToken() });
- expect(res.status).toBe(200);
- });
-
- it("refuses the same token twice, so a harvested one is worth one attempt", async () => {
- const token = await mintToken();
- expect((await signUp("first@example.com", { "x-cap-token": token })).status).toBe(200);
-
- const replay = await signUp("second@example.com", { "x-cap-token": token });
- expect(replay.status).toBe(400);
- // And the second account was never created.
- const { results } = await env.DB.prepare("select email from user").all();
- expect(results.map((r) => r.email)).not.toContain("second@example.com");
- });
-
- it("accepts a token KV has never heard of", async () => {
- // The regression this guards: the redeemed token used to be a random
- // string written to KV at redeem and read back here. KV is eventually
- // consistent, so that read missed and real signups were told to prove
- // they were human again, forever. Emptying KV stands in for a write that
- // has not propagated; a signed token does not care.
- const token = await mintToken();
- for (const key of (await env.LINKS.list()).keys) await env.LINKS.delete(key.name);
- expect((await signUp("unpropagated@example.com", { "x-cap-token": token })).status).toBe(200);
- });
-
- it("refuses a missing token", async () => {
- expect((await signUp("notoken@example.com")).status).toBe(400);
- });
-
- it("refuses a forged token", async () => {
- const res = await signUp("forged@example.com", { "x-cap-token": "deadbeef:cafe" });
- expect(res.status).toBe(400);
- });
-
- it("refuses a token minted for another scope", async () => {
- // The whole point of binding a scope into the signature: a token earned
- // on the password-reset form must not open the signup door.
- const res = await signUp("crossed@example.com", {
- "x-cap-token": await mintToken("password-reset"),
- });
- expect(res.status).toBe(400);
- });
-});
-
-describe("with no CAP_SECRET", () => {
- // Explicitly cleared, not merely left out: the ambient binding is built
- // from .dev.vars, which now sets CAP_SECRET so the browser tests run the
- // real loop. Inheriting it here would test the enabled path twice and the
- // disabled path never.
- const CAP_OFF = () => overrideEnv({ BETTER_AUTH_SECRET: "test-secret", CAP_SECRET: undefined });
-
- // The matching signup case lives in cap-disabled.worker.ts: getAuth()
- // caches its instance per isolate, so the hook closes over whichever env
- // built it first. Harmless in production, where bindings never change,
- // but it means the disabled path needs a file of its own to be tested.
-
- it("reports the challenge endpoint as disabled rather than erroring", async () => {
- const res = await capPost("signup/challenge", {}, CAP_OFF());
- expect(res.status).toBe(200);
- expect(await res.json()).toEqual({ disabled: true });
- });
-});
diff --git a/tests/worker/no-email-signup.worker.ts b/tests/worker/no-email-signup.worker.ts
index 5d45b437..d0c5407b 100644
--- a/tests/worker/no-email-signup.worker.ts
+++ b/tests/worker/no-email-signup.worker.ts
@@ -16,7 +16,7 @@ it("signs up without verification and sends no email", async () => {
const mail = captureEmails({ mx: "deliverable" });
const env = overrideEnv({
BETTER_AUTH_SECRET: "test-secret",
- CAP_SECRET: undefined,
+ TURNSTILE_SECRET_KEY: undefined,
RESEND_API_KEY: undefined,
});
diff --git a/tests/worker/support.ts b/tests/worker/support.ts
index 579f3f28..3cfe5e57 100644
--- a/tests/worker/support.ts
+++ b/tests/worker/support.ts
@@ -172,18 +172,18 @@ export async function resetClicks(): Promise {
// Env with a non-empty auth secret, independent of the ambient .dev.vars, so
// sign-in's rate-limit key derivation has a key to HMAC with.
/**
- * The default binding for worker tests: a known BETTER_AUTH_SECRET, and Cap
- * explicitly off.
+ * The default binding for worker tests: a known BETTER_AUTH_SECRET, and
+ * Turnstile explicitly off.
*
- * Cap has to be cleared rather than merely unmentioned, because the ambient
- * binding is built from .dev.vars, which sets CAP_SECRET so the browser tests
- * exercise the real proof-of-work loop (#98). Inheriting it here would make
- * every signup in every worker test fail the Cap check first and report 400,
- * hiding whatever that test was actually about. Tests that want Cap on say so:
- * see cap.worker.ts.
+ * It has to be cleared rather than merely unmentioned, because the ambient
+ * binding is built from .dev.vars, which sets TURNSTILE_SECRET_KEY so the
+ * browser tests run the real check (#304). Inheriting it here would make
+ * every signup in every worker test fail the check first and report 400,
+ * hiding whatever that test was actually about. Tests that want it on say so:
+ * see turnstile.worker.ts.
*/
export const authEnv = () =>
- overrideEnv({ BETTER_AUTH_SECRET: "test-secret", CAP_SECRET: undefined });
+ overrideEnv({ BETTER_AUTH_SECRET: "test-secret", TURNSTILE_SECRET_KEY: undefined });
/**
* Drive one request through the real worker and wait for anything it
diff --git a/tests/worker/turnstile-disabled.worker.ts b/tests/worker/turnstile-disabled.worker.ts
new file mode 100644
index 00000000..e622d59d
--- /dev/null
+++ b/tests/worker/turnstile-disabled.worker.ts
@@ -0,0 +1,32 @@
+import { beforeEach, expect, it } from "vitest";
+import { reset } from "cloudflare:test";
+import { applyTestMigrations, captureEmails, fetchWorker, overrideEnv } from "./support";
+
+/**
+ * With no TURNSTILE_SECRET_KEY the gate is off and signup works as it did
+ * before, which keeps local dev, self-hosting and CI from needing a key.
+ *
+ * Its own file because getAuth() memoizes one auth instance per isolate, and
+ * that instance closes over the env that built it.
+ */
+beforeEach(async () => {
+ reset();
+ await applyTestMigrations();
+ captureEmails({ mx: "deliverable" });
+});
+
+it("lets signup through untouched when no secret is configured", async () => {
+ const res = await fetchWorker(
+ new Request("http://localhost/api/auth/sign-up/email", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ email: "nosecret@example.com",
+ password: "a-good-password-1",
+ name: "probe",
+ }),
+ }),
+ overrideEnv({ BETTER_AUTH_SECRET: "test-secret", TURNSTILE_SECRET_KEY: undefined }),
+ );
+ expect(res.status).toBe(200);
+});
diff --git a/tests/worker/turnstile.worker.ts b/tests/worker/turnstile.worker.ts
new file mode 100644
index 00000000..a2ca1674
--- /dev/null
+++ b/tests/worker/turnstile.worker.ts
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { env } from "cloudflare:workers";
+import { reset } from "cloudflare:test";
+import { applyTestMigrations, captureEmails, fetchWorker, overrideEnv } from "./support";
+import { spendToken } from "../../src/worker/turnstile";
+
+/**
+ * Turnstile in front of signup (#304). The browser side (script, iframe, CSP)
+ * is asserted in tests/e2e/production/csp.pw.ts and exercised by every e2e
+ * signup. What is left here is what a browser cannot show: a refused, wrong-
+ * action, absent or unverifiable token is turned away, and an unset secret
+ * switches the gate off.
+ *
+ * Cloudflare's siteverify is stubbed; the stub records what we sent it.
+ */
+const ON = () =>
+ overrideEnv({ BETTER_AUTH_SECRET: "test-secret", TURNSTILE_SECRET_KEY: "test-turnstile-secret" });
+
+let sent: URLSearchParams[] = [];
+
+/** Makes siteverify answer `answer`, or fail like an unreachable network. */
+type Siteverify = { success: boolean; action?: string; "error-codes"?: string[] };
+
+function siteverify(answer: Siteverify | Error) {
+ const real = globalThis.fetch;
+ vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
+ const url = input instanceof Request ? input.url : String(input);
+ if (!url.includes("challenges.cloudflare.com")) return real(input, init);
+ sent.push(new URLSearchParams(String(init?.body)));
+ if (answer instanceof Error) throw answer;
+ return Response.json(answer);
+ });
+}
+
+function signUp(email: string, headers: Record = {}) {
+ return fetchWorker(
+ new Request("http://localhost/api/auth/sign-up/email", {
+ method: "POST",
+ headers: { "content-type": "application/json", ...headers },
+ body: JSON.stringify({ email, password: "a-good-password-1", name: "probe" }),
+ }),
+ ON(),
+ );
+}
+
+beforeEach(async () => {
+ sent = [];
+ reset();
+ await applyTestMigrations();
+ captureEmails({ mx: "deliverable" });
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe("spending a token", () => {
+ it("accepts a token siteverify approves for this scope", async () => {
+ siteverify({ success: true, action: "signup" });
+ expect(await spendToken(ON(), "signup", "good")).toBe(true);
+ expect(sent[0]?.get("secret")).toBe("test-turnstile-secret");
+ expect(sent[0]?.get("response")).toBe("good");
+ // No visitor address goes to Cloudflare.
+ expect(sent[0]?.has("remoteip")).toBe(false);
+ });
+
+ it("refuses a token siteverify rejects", async () => {
+ siteverify({ success: false, "error-codes": ["timeout-or-duplicate"] });
+ expect(await spendToken(ON(), "signup", "spent")).toBe(false);
+ });
+
+ it("refuses a token earned on another form", async () => {
+ siteverify({ success: true, action: "password-reset" });
+ expect(await spendToken(ON(), "signup", "crossed")).toBe(false);
+ });
+
+ it("refuses a missing token without asking Cloudflare", async () => {
+ siteverify({ success: true, action: "signup" });
+ expect(await spendToken(ON(), "signup", "")).toBe(false);
+ expect(sent).toHaveLength(0);
+ });
+
+ it("refuses when siteverify is unreachable", async () => {
+ siteverify(new Error("network down"));
+ expect(await spendToken(ON(), "signup", "any")).toBe(false);
+ });
+
+ it("is off, and asks nobody, when no secret is set", async () => {
+ siteverify({ success: false });
+ const off = overrideEnv({ TURNSTILE_SECRET_KEY: undefined });
+ expect(await spendToken(off, "signup", "")).toBe(true);
+ expect(sent).toHaveLength(0);
+ });
+});
+
+describe("at signup", () => {
+ it("creates the account for an approved token", async () => {
+ siteverify({ success: true, action: "signup" });
+ const res = await signUp("fresh@example.com", { "x-turnstile-token": "good" });
+ expect(res.status).toBe(200);
+ });
+
+ it("refuses without a token, and creates no account", async () => {
+ siteverify({ success: true, action: "signup" });
+ const res = await signUp("notoken@example.com");
+ expect(res.status).toBe(400);
+ const { results } = await env.DB.prepare("select email from user").all();
+ expect(results.map((r) => r.email)).not.toContain("notoken@example.com");
+ });
+
+ it("refuses a token siteverify rejects", async () => {
+ siteverify({ success: false });
+ expect((await signUp("bad@example.com", { "x-turnstile-token": "bad" })).status).toBe(400);
+ });
+});
diff --git a/vite.config.ts b/vite.config.ts
index 08cee0ac..869aae2b 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -75,14 +75,6 @@ export default defineConfig(async () => ({
// mirror the tsconfig "@/*" path for runtime imports (app and worker)
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
- // capjs-core reaches for these two only in its instrumentation mode,
- // which we do not use. Left alone, the bundler follows the dynamic
- // imports and ships a 5 MB javascript-obfuscator chunk in the Worker.
- // See src/worker/cap-unused-dep-stub.ts.
- esbuild: fileURLToPath(new URL("./src/worker/cap-unused-dep-stub.ts", import.meta.url)),
- "javascript-obfuscator": fileURLToPath(
- new URL("./src/worker/cap-unused-dep-stub.ts", import.meta.url),
- ),
// qrcode's package.json "browser" field remaps its own main entry to a
// canvas/document-based build with no toBuffer, and no DOM to draw
// into anyway; the Worker always wants the pure-JS server build (#139,
diff --git a/wrangler.jsonc b/wrangler.jsonc
index d8b03744..c4c8b436 100644
--- a/wrangler.jsonc
+++ b/wrangler.jsonc
@@ -177,8 +177,8 @@
// Set for the person who is having trouble, not for the bot. Somebody who
// mistypes a password, retries a signup, or pastes six links in a row must
// never meet a wall, because they read it as the product being broken and
- // they are right. The ceilings that matter for abuse are elsewhere: Cap
- // charges CPU per attempt (#98), RL_EMAIL_RECIPIENT bounds what one inbox
+ // they are right. The ceilings that matter for abuse are elsewhere: Turnstile
+ // challenges each attempt (#304), RL_EMAIL_RECIPIENT bounds what one inbox
// can be made to receive, and the WAF rules in docs/rate-limiting.md sit in
// front of all of it.
"ratelimits": [
@@ -192,24 +192,11 @@
"period": 60,
},
},
- // Cap's own endpoints (#98). Separate from RL_AUTH_PUBLIC and much
- // higher: one sign-up spends a challenge and a redeem, its retry spends
- // two more, and several people behind one office address are ordinary.
- // The proof-of-work prices these, not this counter, which is only here so
- // a script cannot farm challenges to solve offline in bulk.
- {
- "name": "RL_CAP",
- "namespace_id": "14011",
- "simple": {
- "limit": 120,
- "period": 60,
- },
- },
{
// Per caller, per path. Raised from 3: a signup that goes wrong costs
// a send each time somebody retries, and three of those inside a minute
- // is a person having a bad day, not a bot. Cap already prices each
- // attempt in CPU (#98), so this does not have to be the tight one.
+ // is a person having a bad day, not a bot. Turnstile already challenges each
+ // attempt (#304), so this does not have to be the tight one.
"name": "RL_EMAIL",
"namespace_id": "14002",
"simple": {
@@ -269,7 +256,7 @@
// own namespace, not RL_AUTH_PUBLIC: a flood at the landing form must not
// lock anybody out of signing in. Generous enough that a person trying a
// few links never notices, tight enough that farming short links from one
- // address is not worth the Cap proof-of-work each one already costs.
+ // address is not worth the Turnstile challenge each one already costs.
{
"name": "RL_ANON_LINK",
"namespace_id": "14010",
@@ -330,6 +317,8 @@
// env vars aren't inherited from the top-level "vars": left unset
// (capture no-ops) so e2e never calls out to Sentry.
"SENTRY_DSN": "",
+ // Cloudflare's published test site key: always passes, no account.
+ "TURNSTILE_SITE_KEY": "1x00000000000000000000AA",
},
"kv_namespaces": [
{
@@ -413,17 +402,6 @@
"period": 60,
},
},
- {
- // Higher again than production's: local dev and the e2e run have no
- // cf-connecting-ip, so every caller on the machine shares one key
- // and one budget.
- "name": "RL_CAP",
- "namespace_id": "24011",
- "simple": {
- "limit": 600,
- "period": 60,
- },
- },
{
"name": "RL_EMAIL",
"namespace_id": "24002",
From 6c70e069a18649c0174c3663b33441cac60e138e Mon Sep 17 00:00:00 2001
From: baron unread
Date: Sun, 11 Oct 2026 01:59:24 +0200
Subject: [PATCH 2/8] Regenerate evlog map after removing Cap routes
Co-Authored-By: Claude Sonnet 5.5
---
evlog.map.json | 307 ++++++++++++++++---------------------------------
1 file changed, 101 insertions(+), 206 deletions(-)
diff --git a/evlog.map.json b/evlog.map.json
index fc608c26..1c68dc03 100644
--- a/evlog.map.json
+++ b/evlog.map.json
@@ -1,6 +1,6 @@
{
"version": 1,
- "generatedAt": "2026-10-05T12:11:01.432Z",
+ "generatedAt": "2026-10-10T23:59:21.770Z",
"cliVersion": "0.6.3",
"ruleSetVersion": 1,
"framework": "hono",
@@ -14,7 +14,7 @@
"path": "*",
"file": "src/worker/index.ts",
"handler": {
- "line": 436,
+ "line": 506,
"column": 0
},
"id": "cfc6426d0697",
@@ -25,14 +25,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -49,7 +49,7 @@
"path": "/",
"file": "src/worker/routes/mcp.ts",
"handler": {
- "line": 692,
+ "line": 696,
"column": 0
},
"id": "0d9557579aed",
@@ -119,7 +119,7 @@
"path": "/",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 162,
+ "line": 163,
"column": 0
},
"id": "4350f835247a",
@@ -146,7 +146,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -356,7 +356,7 @@
"path": "/",
"file": "src/worker/routes/shorten.ts",
"handler": {
- "line": 51,
+ "line": 50,
"column": 0
},
"id": "0554bedfef79",
@@ -383,7 +383,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/shorten.ts",
- "line": 99
+ "line": 98
}
}
},
@@ -400,7 +400,7 @@
"path": "/.well-known/oauth-authorization-server",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "74a5acf06050",
@@ -408,9 +408,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -419,6 +416,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -435,7 +435,7 @@
"path": "/.well-known/oauth-authorization-server",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "edeb8346dcd8",
@@ -443,9 +443,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -454,6 +451,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -470,7 +470,7 @@
"path": "/.well-known/oauth-authorization-server/api/auth",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "c6931ce216c6",
@@ -478,9 +478,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -489,6 +486,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -505,7 +505,7 @@
"path": "/.well-known/oauth-authorization-server/api/auth",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "2120851fa5bc",
@@ -513,9 +513,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -524,6 +521,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -540,7 +540,7 @@
"path": "/.well-known/oauth-protected-resource",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "098fd485d307",
@@ -548,9 +548,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -559,6 +556,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -575,7 +575,7 @@
"path": "/.well-known/oauth-protected-resource",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "4b628f392fad",
@@ -583,9 +583,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -594,6 +591,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -610,7 +610,7 @@
"path": "/.well-known/oauth-protected-resource/api/mcp",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "739186e00a75",
@@ -618,9 +618,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -629,6 +626,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -645,7 +645,7 @@
"path": "/.well-known/oauth-protected-resource/api/mcp",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "f77d2f980787",
@@ -653,9 +653,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -664,6 +661,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -680,7 +680,7 @@
"path": "/.well-known/openid-configuration",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "6f46cf3a8d4d",
@@ -691,14 +691,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -715,7 +715,7 @@
"path": "/.well-known/openid-configuration",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "b218f10e83af",
@@ -726,14 +726,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -750,7 +750,7 @@
"path": "/.well-known/openid-configuration/api/auth",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "ec47298398d2",
@@ -758,9 +758,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -769,6 +766,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -785,7 +785,7 @@
"path": "/.well-known/openid-configuration/api/auth",
"file": "src/worker/index.ts",
"handler": {
- "line": 244,
+ "line": 298,
"column": 0
},
"id": "74cb514d40a8",
@@ -793,9 +793,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -804,6 +801,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -1036,7 +1036,7 @@
"path": "/:linkId",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 310,
+ "line": 315,
"column": 0
},
"id": "e1ca5e8b260a",
@@ -1063,7 +1063,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -1080,7 +1080,7 @@
"path": "/:linkId",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 240,
+ "line": 245,
"column": 0
},
"id": "8e8fff5d79b1",
@@ -1107,7 +1107,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -1124,7 +1124,7 @@
"path": "/:linkId/rescore",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 265,
+ "line": 270,
"column": 0
},
"id": "a60e23e051c8",
@@ -1151,7 +1151,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -1161,76 +1161,6 @@
},
"score": 100
},
- {
- "framework": "hono",
- "kind": "api",
- "method": "POST",
- "path": "/:scope/challenge",
- "file": "src/worker/routes/cap.ts",
- "handler": {
- "line": 33,
- "column": 0
- },
- "id": "a90f76dc45d7",
- "checks": {
- "structured-errors": {
- "status": "n/a"
- },
- "audit": {
- "status": "n/a"
- },
- "error-handling": {
- "status": "n/a"
- },
- "wide-event": {
- "status": "pass"
- },
- "context": {
- "status": "pass"
- }
- },
- "suggestions": {},
- "sensitivity": {
- "level": "none",
- "reasons": []
- },
- "score": 100
- },
- {
- "framework": "hono",
- "kind": "api",
- "method": "POST",
- "path": "/:scope/redeem",
- "file": "src/worker/routes/cap.ts",
- "handler": {
- "line": 42,
- "column": 0
- },
- "id": "920145bab597",
- "checks": {
- "structured-errors": {
- "status": "n/a"
- },
- "audit": {
- "status": "n/a"
- },
- "error-handling": {
- "status": "n/a"
- },
- "wide-event": {
- "status": "pass"
- },
- "context": {
- "status": "pass"
- }
- },
- "suggestions": {},
- "sensitivity": {
- "level": "none",
- "reasons": []
- },
- "score": 100
- },
{
"framework": "hono",
"kind": "api",
@@ -1238,7 +1168,7 @@
"path": "/:slug",
"file": "src/worker/index.ts",
"handler": {
- "line": 421,
+ "line": 491,
"column": 0
},
"id": "4542fd0856a5",
@@ -1249,14 +1179,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -1273,7 +1203,7 @@
"path": "/:token",
"file": "src/worker/routes/orgs.ts",
"handler": {
- "line": 1231,
+ "line": 1232,
"column": 0
},
"id": "c8b0bedaf935",
@@ -1308,7 +1238,7 @@
"path": "/:token/accept",
"file": "src/worker/routes/orgs.ts",
"handler": {
- "line": 1289,
+ "line": 1290,
"column": 0
},
"id": "d4b536c251be",
@@ -1343,7 +1273,7 @@
"path": "/anonymous",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 404,
+ "line": 409,
"column": 0
},
"id": "4c455e704c8e",
@@ -1370,7 +1300,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -1387,7 +1317,7 @@
"path": "/anonymous/:id",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 429,
+ "line": 434,
"column": 0
},
"id": "a8b1ad6c6690",
@@ -1414,7 +1344,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -1431,7 +1361,7 @@
"path": "/api/*",
"file": "src/worker/index.ts",
"handler": {
- "line": 312,
+ "line": 356,
"column": 0
},
"id": "74a1ccacc4b3",
@@ -1442,14 +1372,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -1466,7 +1396,7 @@
"path": "/api/auth/*",
"file": "src/worker/index.ts",
"handler": {
- "line": 216,
+ "line": 270,
"column": 0
},
"id": "e75aa52c874e",
@@ -1474,9 +1404,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -1485,6 +1412,9 @@
},
"audit": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -1501,7 +1431,7 @@
"path": "/api/auth/*",
"file": "src/worker/index.ts",
"handler": {
- "line": 216,
+ "line": 270,
"column": 0
},
"id": "2d4af6eb10f7",
@@ -1509,9 +1439,6 @@
"structured-errors": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
@@ -1520,47 +1447,15 @@
},
"audit": {
"status": "pass"
- }
- },
- "suggestions": {},
- "sensitivity": {
- "level": "high",
- "reasons": ["auth: path says \"auth\""]
- },
- "score": 100
- },
- {
- "framework": "hono",
- "kind": "api",
- "method": "POST",
- "path": "/api/cap/*",
- "file": "src/worker/index.ts",
- "handler": {
- "line": 259,
- "column": 0
- },
- "id": "3d9ce45013d9",
- "checks": {
- "structured-errors": {
- "status": "n/a"
- },
- "audit": {
- "status": "n/a"
},
"error-handling": {
- "status": "n/a"
- },
- "wide-event": {
- "status": "pass"
- },
- "context": {
"status": "pass"
}
},
"suggestions": {},
"sensitivity": {
- "level": "none",
- "reasons": []
+ "level": "high",
+ "reasons": ["auth: path says \"auth\""]
},
"score": 100
},
@@ -1571,7 +1466,7 @@
"path": "/api/webhooks/polar",
"file": "src/worker/index.ts",
"handler": {
- "line": 273,
+ "line": 317,
"column": 0
},
"id": "bbed5d59d114",
@@ -1582,14 +1477,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -1650,7 +1545,7 @@
"path": "/checkout",
"file": "src/worker/routes/billing.ts",
"handler": {
- "line": 49,
+ "line": 56,
"column": 0
},
"id": "ec65818b4193",
@@ -1685,7 +1580,7 @@
"path": "/clicks",
"file": "src/worker/routes/shorten.ts",
"handler": {
- "line": 146,
+ "line": 145,
"column": 0
},
"id": "4203806a8f62",
@@ -1712,7 +1607,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/shorten.ts",
- "line": 99
+ "line": 98
}
}
},
@@ -1729,7 +1624,7 @@
"path": "/config",
"file": "src/worker/routes/auth.ts",
"handler": {
- "line": 100,
+ "line": 103,
"column": 0
},
"id": "8ef063442579",
@@ -1896,7 +1791,7 @@
"path": "/orgs/:orgId/suspend",
"file": "src/worker/routes/admin-links.ts",
"handler": {
- "line": 349,
+ "line": 354,
"column": 0
},
"id": "06abb4f07afe",
@@ -1923,7 +1818,7 @@
"message": "changes state with no audit record — the project records audit events elsewhere",
"evidence": {
"file": "src/worker/routes/admin-links.ts",
- "line": 210
+ "line": 215
}
}
},
@@ -1940,7 +1835,7 @@
"path": "/portal",
"file": "src/worker/routes/billing.ts",
"handler": {
- "line": 78,
+ "line": 87,
"column": 0
},
"id": "b391b630274c",
@@ -1975,7 +1870,7 @@
"path": "/pricing.md",
"file": "src/worker/index.ts",
"handler": {
- "line": 409,
+ "line": 479,
"column": 0
},
"id": "c01fb33007bf",
@@ -1986,14 +1881,14 @@
"audit": {
"status": "n/a"
},
- "error-handling": {
- "status": "n/a"
- },
"wide-event": {
"status": "pass"
},
"context": {
"status": "pass"
+ },
+ "error-handling": {
+ "status": "pass"
}
},
"suggestions": {},
@@ -2054,7 +1949,7 @@
"path": "/user",
"file": "src/worker/routes/auth.ts",
"handler": {
- "line": 92,
+ "line": 95,
"column": 0
},
"id": "72d6ba945cf1",
From 5599b9225d071964ca53f73f7fcf06841a7ef243 Mon Sep 17 00:00:00 2001
From: baron unread
Date: Mon, 26 Oct 2026 16:33:31 +0100
Subject: [PATCH 3/8] Turnstile: satisfy React Doctor and fallow, and fix the
CSP e2e
- siteverify's response is checked for res.ok before its body is read
(React Doctor's one finding).
- Drop the unused turnstileEnabled export, and un-export keyedDigest and
latestOtp, which only their own files use now (fallow).
- The production CSP spec loaded Turnstile through the signup form, which
needs /api/config, which needs a migrated database the preview server
never has. It now adds Cloudflare's script itself, so it still proves
script-src and frame-src admit the script and the challenge iframe.
- Two sentences in the docs that Style Doctor flagged.
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 2 +-
docs/rate-limiting.md | 6 +++---
src/worker/rate-limit.ts | 2 +-
src/worker/turnstile.ts | 19 +++++++++++--------
tests/e2e/production/csp.pw.ts | 18 +++++++++---------
tests/e2e/resend.ts | 2 +-
6 files changed, 26 insertions(+), 23 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index d3c47af7..4e549ff7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -302,7 +302,7 @@ Shell writes to repo files are sandboxed; edit through the editor tools, not
- Data layer: `api()` + `ApiError` (`.status`, `.code`) in `src/app/lib/api.ts`;
TanStack Query hooks in `src/app/lib/hooks.ts`.
- **Strict CSP** on published pages, everything self-contained: no remote fonts,
- images, scripts, or fetches. Icons via `lucide-react`; art via inline CSS/SVG. The one remote image is Fazier's launch badge in the landing footer, allowed in img-src for rdyrct.com's build only (their verifier needs their own image). Cloudflare Turnstile's script and challenge iframe are allowed in script-src and frame-src only when `TURNSTILE_SITE_KEY` is set.
+ images, scripts, or fetches. Icons via `lucide-react`; art via inline CSS/SVG. The one remote image is Fazier's launch badge in the landing footer, allowed in img-src for rdyrct.com's build only (their verifier needs their own image). script-src and frame-src admit Cloudflare Turnstile's script and challenge iframe only when `TURNSTILE_SITE_KEY` is set.
- Email: `sendEmail()` (`src/worker/email.ts`) uses the Resend HTTP API via plain
`fetch`, with `RESEND_BASE_URL` pointing at the emulator in dev. Keep it: the
Resend SDK can't repoint its base URL, which would break the emulator flow.
diff --git a/docs/rate-limiting.md b/docs/rate-limiting.md
index 5e525d66..5383b39b 100644
--- a/docs/rate-limiting.md
+++ b/docs/rate-limiting.md
@@ -147,9 +147,9 @@ whose action is not the one it expects, so a token earned on one form cannot
open another. Cloudflare's test secret never echoes an action, so that one
check is skipped when `siteverify` says it answered with a testing key.
-**How it looks.** Mostly it does not: the widget is `interaction-only`,
-started on the form's first keystroke. If Cloudflare wants a click, the
-widget shows itself in the corner of the page.
+**How it looks.** It does not, unless Cloudflare wants a click. The widget
+is `interaction-only` and starts on the form's first keystroke; when
+Cloudflare asks for a click, it shows itself in the corner of the page.
**Keys.** Create a widget at dash.cloudflare.com → Turnstile, with
`rdyrct.com` as its hostname. Set both keys as secrets, `TURNSTILE_SITE_KEY`
diff --git a/src/worker/rate-limit.ts b/src/worker/rate-limit.ts
index 5b9f60c0..9a70be38 100644
--- a/src/worker/rate-limit.ts
+++ b/src/worker/rate-limit.ts
@@ -77,7 +77,7 @@ function hex(bytes: ArrayBuffer): string {
/** Keyed HMAC over `value`. The digest is the only form an identifier takes
* once it leaves the request: what ends up in a rate-limit counter is never
* the address itself. */
-export async function keyedDigest(secret: string, value: string): Promise {
+async function keyedDigest(secret: string, value: string): Promise {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
diff --git a/src/worker/turnstile.ts b/src/worker/turnstile.ts
index 89d6e785..7c8d399b 100644
--- a/src/worker/turnstile.ts
+++ b/src/worker/turnstile.ts
@@ -19,14 +19,6 @@ const SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverif
* hold the form open. A timeout counts as unreachable, so it refuses. */
const SITEVERIFY_TIMEOUT_MS = 10_000;
-/** Off unless TURNSTILE_SECRET_KEY is set, matching SENTRY_DSN and friends:
- * self-hosters run without it. Keyed on the secret, not the site key: a
- * secret with no site key must refuse every request, never quietly turn the
- * check off. */
-export function turnstileEnabled(env: Env): boolean {
- return !!env.TURNSTILE_SECRET_KEY;
-}
-
/** The fields of siteverify's answer this file reads. */
const siteverifySchema = v.object({
success: v.boolean(),
@@ -47,6 +39,12 @@ async function siteverify(secret: string, token: string): Promise element, it is
+ * held to the same script-src as the app's own loader.
*/
test("Turnstile solves a challenge under the production CSP", async ({ page }) => {
await page.goto("/signup");
-
- // /signup is prerendered, so an input typed before hydration finishes never
- // reaches the handler that starts the widget. Type again until it is there.
- let attempt = 0;
- await expect(async () => {
- attempt += 1;
- await page.getByRole("textbox").first().fill(`csp-probe-${attempt}@example.com`);
- await page.waitForFunction(() => !!window.turnstile, null, { timeout: 3_000 });
- }).toPass({ timeout: 20_000 });
+ await page.addScriptTag({
+ url: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",
+ });
+ await page.waitForFunction(() => !!window.turnstile, null, { timeout: 15_000 });
const token = await page.evaluate(
(siteKey) =>
diff --git a/tests/e2e/resend.ts b/tests/e2e/resend.ts
index b18b8fa3..8c30986d 100644
--- a/tests/e2e/resend.ts
+++ b/tests/e2e/resend.ts
@@ -60,7 +60,7 @@ export async function subjectsSentTo(page: Page, email: string): Promise (isRecord(item) ? String(item.subject ?? "") : ""));
}
-export async function latestOtp(page: Page, email: string) {
+async function latestOtp(page: Page, email: string) {
let otp = "";
await expect
.poll(async () => {
From 34c3376f3349e7ebfe61b8bcc748595de6b2a80d Mon Sep 17 00:00:00 2001
From: baron unread
Date: Mon, 26 Oct 2026 17:28:53 +0100
Subject: [PATCH 4/8] Turnstile: both keys or neither, CSP on APP_HOST only,
wait for config
From the cold review of #314:
- A site key with no secret used to serve the key and skip the check, so
the forms looked protected and were not. Either key without the other
is now "misconfigured" (turnstileMode): /api/config serves no site key,
every guarded route refuses, and the Worker logs
turnstile_misconfigured. Docs tell operators to set both in one
`wrangler secret bulk` call.
- The CSP allowed challenges.cloudflare.com on every host. It now does
only when the request host is APP_HOST and both keys are set
(turnstileAllowed), so custom domains and the shared link host never
allow it, as the docs said. The production-preview e2e pins its own
APP_HOST so it still sees the policy that ships.
- A form submitted before /api/config answered went out with no token,
and its retry did too. headers() now waits for the config through
ensureQueryData; a failed fetch is not cached, so the retry asks again.
New e2e: sign-up with /api/config held back 6s still gets through.
- The test-key allowance is decided by comparing our own secret with
Cloudflare's published test secrets, not by trusting siteverify's
result_with_testing_key.
- Per-route worker tests for sign-up, reset, /api/reports and
/api/shorten: approved, missing, siteverify success:false (with the
right action, so only `success` can refuse it) and wrong action. Every
new guard is mutation-tested.
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 11 +-
README.md | 22 +-
docs/rate-limiting.md | 29 ++-
playwright.config.ts | 5 +-
prod.secrets.env.example | 7 +-
src/app/lib/hooks.ts | 15 +-
src/app/lib/turnstile.ts | 37 ++-
src/worker/index.ts | 6 +-
src/worker/routes/auth.ts | 5 +-
src/worker/security-headers.ts | 21 +-
src/worker/turnstile.ts | 60 +++--
tests/e2e/auth.pw.ts | 17 ++
tests/worker/no-email-signup.worker.ts | 1 +
tests/worker/security-headers.worker.ts | 25 +-
tests/worker/turnstile-disabled.worker.ts | 10 +-
tests/worker/turnstile.worker.ts | 285 ++++++++++++++--------
16 files changed, 374 insertions(+), 182 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 4e549ff7..bb54ae27 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -261,10 +261,11 @@ Shell writes to repo files are sandboxed; edit through the editor tools, not
`hooks.before`), the landing shortener (`/api/shorten`) and the report
form (`/api/reports`), each form with its own `action`. Cloudflare is the
one third party that sees the visitor, and only on those forms. Both keys
- are secrets: `TURNSTILE_SITE_KEY` reaches the browser through
- `/api/config` and adds `challenges.cloudflare.com` to the CSP; unset
- `TURNSTILE_SECRET_KEY` switches the check off, and a copy with neither
- never loads Cloudflare's script. Dev, CI and e2e use Cloudflare's
+ are secrets, set together (`turnstileMode`): with both, `/api/config`
+ serves the site key and the CSP admits `challenges.cloudflare.com` on
+ `APP_HOST`; with neither, the check is off and the browser never loads
+ Cloudflare's script; with one, every guarded form is refused and
+ `turnstile_misconfigured` is logged. Dev, CI and e2e use Cloudflare's
always-pass test keys. See `docs/rate-limiting.md` for all three layers
(WAF rules, Workers limiters, Turnstile) and the dashboard rules to apply
by hand.
@@ -302,7 +303,7 @@ Shell writes to repo files are sandboxed; edit through the editor tools, not
- Data layer: `api()` + `ApiError` (`.status`, `.code`) in `src/app/lib/api.ts`;
TanStack Query hooks in `src/app/lib/hooks.ts`.
- **Strict CSP** on published pages, everything self-contained: no remote fonts,
- images, scripts, or fetches. Icons via `lucide-react`; art via inline CSS/SVG. The one remote image is Fazier's launch badge in the landing footer, allowed in img-src for rdyrct.com's build only (their verifier needs their own image). script-src and frame-src admit Cloudflare Turnstile's script and challenge iframe only when `TURNSTILE_SITE_KEY` is set.
+ images, scripts, or fetches. Icons via `lucide-react`; art via inline CSS/SVG. The one remote image is Fazier's launch badge in the landing footer, allowed in img-src for rdyrct.com's build only (their verifier needs their own image). script-src and frame-src admit Cloudflare Turnstile's script and challenge iframe only on `APP_HOST` and only when both Turnstile keys are set.
- Email: `sendEmail()` (`src/worker/email.ts`) uses the Resend HTTP API via plain
`fetch`, with `RESEND_BASE_URL` pointing at the emulator in dev. Keep it: the
Resend SDK can't repoint its base URL, which would break the emulator flow.
diff --git a/README.md b/README.md
index ea26b1dc..c2094a3e 100644
--- a/README.md
+++ b/README.md
@@ -122,17 +122,17 @@ Commit the rewritten `wrangler.jsonc` to your fork. After that, `bun run deploy`
Everything else is optional. Each piece says what it adds:
-| Setting | Adds |
-| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
-| `RESEND_API_KEY`, `MAIL_FROM` | Email: sign-up verification codes, password reset, invites, notices. Without it, sign-up skips verification (see below). |
-| `POLAR_*` | Selling Hobby and Pro plans. Without it, nobody is capped and billing is hidden. |
-| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | "Continue with Google". |
-| `CF_API_TOKEN`, `CF_ZONE_ID` | Customers' own domains through Cloudflare for SaaS. |
-| `SHARED_LINK_HOST` | A second, shorter host for new shared-domain links. |
-| `TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | Cloudflare Turnstile in front of sign-up, password reset and the report form. Cloudflare then sees those visitors. |
-| `WEB_RISK_API_KEY` | Google Web Risk as a second destination check. A listed destination puts its link on hold. |
-| `SENTRY_DSN` | Error reports to your Sentry project. |
-| `SITE_NAME` | The name every tab shows, such as "Acme links". Without it, tabs show your copy's host. |
+| Setting | Adds |
+| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `RESEND_API_KEY`, `MAIL_FROM` | Email: sign-up verification codes, password reset, invites, notices. Without it, sign-up skips verification (see below). |
+| `POLAR_*` | Selling Hobby and Pro plans. Without it, nobody is capped and billing is hidden. |
+| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | "Continue with Google". |
+| `CF_API_TOKEN`, `CF_ZONE_ID` | Customers' own domains through Cloudflare for SaaS. |
+| `SHARED_LINK_HOST` | A second, shorter host for new shared-domain links. |
+| `TURNSTILE_SITE_KEY`, `TURNSTILE_SECRET_KEY` | Cloudflare Turnstile in front of sign-up, password reset and the report form. Set both in one `wrangler secret bulk` call: one without the other refuses those forms. Cloudflare then sees those visitors. |
+| `WEB_RISK_API_KEY` | Google Web Risk as a second destination check. A listed destination puts its link on hold. |
+| `SENTRY_DSN` | Error reports to your Sentry project. |
+| `SITE_NAME` | The name every tab shows, such as "Acme links". Without it, tabs show your copy's host. |
**With no email provider and no Google sign-in, accounts are not verified and passwords cannot be reset.** That is fine for a private instance and not recommended for a public one. The admin console says so while it is true.
diff --git a/docs/rate-limiting.md b/docs/rate-limiting.md
index 5383b39b..c4ac96b7 100644
--- a/docs/rate-limiting.md
+++ b/docs/rate-limiting.md
@@ -144,8 +144,9 @@ its UTM builder (`/api/shorten`), and the abuse report form
threat model, and it would tax every real visitor on every visit. Each form
renders the widget with its own `action`, and the Worker refuses a token
whose action is not the one it expects, so a token earned on one form cannot
-open another. Cloudflare's test secret never echoes an action, so that one
-check is skipped when `siteverify` says it answered with a testing key.
+open another. Cloudflare's test secrets never echo an action, so that one
+check is skipped when our own configured secret is one of Cloudflare's
+published test secrets. `siteverify`'s own say-so is never trusted for this.
**How it looks.** It does not, unless Cloudflare wants a click. The widget
is `interaction-only` and starts on the form's first keystroke; when
@@ -157,19 +158,25 @@ and `TURNSTILE_SECRET_KEY` (`prod.secrets.env.example`). The site key is
public, since `/api/config` hands it to the browser, but it is a secret
rather than a var in `wrangler.jsonc` so a fork does not inherit ours.
-With the secret unset the Worker skips the check, and with the site key unset
-the browser never loads Cloudflare's script: that is a self-hosted copy that
-leaves both blank. A secret with no site key refuses every guarded request,
-because the browser has no widget to render, and a form that looks protected
-and is not is the worse failure. Cloudflare publishes test keys that always
-pass; `.dev.vars.local.example` and the e2e run use them.
+**Set both or neither, in one call.** Put both keys in `prod.secrets.env` and
+run `bunx wrangler secret bulk prod.secrets.env` once, so no deploy ever sees
+one without the other. With neither set the check is off and the browser
+never loads Cloudflare's script: that is a self-hosted copy that leaves both
+blank. With only one set the Worker treats Turnstile as misconfigured: it
+serves no site key, refuses every guarded form, and logs
+`turnstile_misconfigured`. A lone site key would render a widget whose token
+nobody checks, and a lone secret would have no widget to produce a token;
+either way a form that looks protected and is not is the worse failure.
+Cloudflare publishes test keys that always pass; `.dev.vars.local.example`
+and the e2e run use them.
**CSP.** `script-src` and `frame-src` allow
-`https://challenges.cloudflare.com` only on the app host, and only when
-`TURNSTILE_SITE_KEY` is set (`turnstileAllowed` in
+`https://challenges.cloudflare.com` only when the request host is `APP_HOST`
+and both keys are set (`turnstileAllowed` in
`src/worker/security-headers.ts`). A custom domain, the shared link host and a
copy without the keys never allow it. Asserted in
-`tests/e2e/production/csp.pw.ts` and `tests/worker/security-headers.worker.ts`.
+`tests/e2e/production/csp.pw.ts`, `tests/worker/security-headers.worker.ts`
+and `tests/worker/turnstile.worker.ts`.
**If Cloudflare is unreachable** `siteverify` fails closed: the guarded
forms are refused until it answers.
diff --git a/playwright.config.ts b/playwright.config.ts
index 12f0cb1b..d51642c4 100644
--- a/playwright.config.ts
+++ b/playwright.config.ts
@@ -80,7 +80,10 @@ export default defineConfig({
// Vite's inline React Refresh preamble, so only this one serves the
// policy that actually ships. The build is part of the command so the
// suite can never assert against a stale dist/.
- command: `bun run build && bunx vite preview --port ${previewPort} --strictPort`,
+ // APP_HOST is pinned to the preview's own host (a later line in a
+ // .dev.vars wins): the CSP only allows Turnstile on APP_HOST, and the
+ // copied .dev.vars names the dev server's host instead.
+ command: `bun run build && printf '\\nAPP_HOST=localhost:${previewPort}\\nAPP_URL=${previewUrl}\\n' >> dist/rdyrct/.dev.vars && bunx vite preview --port ${previewPort} --strictPort`,
url: previewUrl,
reuseExistingServer: false,
timeout: 180_000,
diff --git a/prod.secrets.env.example b/prod.secrets.env.example
index 17d4d3c1..9fd4e5ec 100644
--- a/prod.secrets.env.example
+++ b/prod.secrets.env.example
@@ -33,9 +33,10 @@ CF_API_TOKEN=
# shortener and the report form (#304). dash.cloudflare.com → Turnstile →
# Add widget (managed mode, your app host as the hostname). The site key is
# public (the browser gets it from /api/config) but lives here rather than in
-# wrangler.jsonc so a fork does not inherit it. Set both or neither: leave
-# both blank and the check is off and the browser never loads Cloudflare's
-# script; a secret with no site key refuses every guarded form.
+# wrangler.jsonc so a fork does not inherit it. Set both or neither, in this
+# one bulk call: leave both blank and the check is off and the browser never
+# loads Cloudflare's script; either key without the other refuses every
+# guarded form and logs turnstile_misconfigured.
TURNSTILE_SITE_KEY=
TURNSTILE_SECRET_KEY=
diff --git a/src/app/lib/hooks.ts b/src/app/lib/hooks.ts
index 3f23a4f7..2a66d68a 100644
--- a/src/app/lib/hooks.ts
+++ b/src/app/lib/hooks.ts
@@ -97,12 +97,15 @@ export function useShellUser(): CurrentUser | null {
}
// Deployment config (e.g. appHost for DNS instructions) — static per deploy.
-export const useConfig = () =>
- useQuery({
- queryKey: ["config"],
- queryFn: () => api("/config"),
- staleTime: Infinity,
- });
+/** Shared by useConfig and anything that must wait for the answer outside
+ * a render, such as the Turnstile guard. */
+export const configQuery = {
+ queryKey: ["config"],
+ queryFn: () => api("/config"),
+ staleTime: Infinity,
+};
+
+export const useConfig = () => useQuery(configQuery);
// The host shared-domain links display, copy, and redirect through. Falls
// back to the current origin's host while config is still loading.
diff --git a/src/app/lib/turnstile.ts b/src/app/lib/turnstile.ts
index 8c59f116..f58c6c5d 100644
--- a/src/app/lib/turnstile.ts
+++ b/src/app/lib/turnstile.ts
@@ -11,8 +11,9 @@
* and ignored when it is not.
*/
import { useCallback, useRef } from "react";
+import { useQueryClient } from "@tanstack/react-query";
import { TURNSTILE_TOKEN_HEADER } from "@/shared/types";
-import { useConfig } from "./hooks";
+import { configQuery, useConfig } from "./hooks";
import { retryOnTurnstileFailure } from "./turnstile-retry";
export type TurnstileScope = "signup" | "password-reset" | "anon-link" | "report";
@@ -119,25 +120,41 @@ async function solve(siteKey: string, scope: TurnstileScope): Promise {
* submitted twice solves again rather than replaying a burned token.
*/
export function useTurnstile(scope: TurnstileScope) {
- const siteKey = useConfig().data?.turnstileSiteKey;
+ const qc = useQueryClient();
+ const loadedSiteKey = useConfig().data?.turnstileSiteKey;
const pending = useRef<{ token: Promise; primedAt: number } | null>(null);
- const prime = useCallback(() => {
- if (!siteKey) return;
- const held = pending.current;
- if (held && Date.now() - held.primedAt < TOKEN_FRESH_MS) return;
- pending.current = { token: solve(siteKey, scope), primedAt: Date.now() };
- }, [scope, siteKey]);
+ const startSolve = useCallback(
+ (siteKey: string | undefined) => {
+ if (!siteKey) return;
+ const held = pending.current;
+ if (held && Date.now() - held.primedAt < TOKEN_FRESH_MS) return;
+ pending.current = { token: solve(siteKey, scope), primedAt: Date.now() };
+ },
+ [scope],
+ );
+
+ /** Starts early when the config is already here; headers() catches up
+ * when it is not. */
+ const prime = useCallback(() => startSolve(loadedSiteKey), [startSolve, loadedSiteKey]);
const headers = useCallback(async (): Promise> => {
- prime();
+ // A form submitted before /api/config answered must not go out without
+ // a token, so wait for it here. A failed fetch is not cached, so the
+ // retry after a refusal asks again instead of failing for the whole
+ // page load.
+ const siteKey = await qc
+ .ensureQueryData(configQuery)
+ .then((config) => config.turnstileSiteKey)
+ .catch(() => undefined);
+ startSolve(siteKey);
const token = (await pending.current?.token) ?? "";
pending.current = null;
// The one place that knows "we could not run the check" from "the server
// refused it".
if (siteKey && !token) console.warn("turnstile_solve_failed", scope);
return token ? { [TURNSTILE_TOKEN_HEADER]: token } : {};
- }, [prime, scope, siteKey]);
+ }, [qc, startSolve, scope]);
const guarded = useCallback(
(run) => retryOnTurnstileFailure(run, headers),
diff --git a/src/worker/index.ts b/src/worker/index.ts
index 55a3c07b..20a26604 100644
--- a/src/worker/index.ts
+++ b/src/worker/index.ts
@@ -55,7 +55,7 @@ import { PRERENDERED_PUBLIC_PATHS } from "../shared/page-meta";
import { RDYRCT_SITE } from "../shared/site";
import { canonicalSpaPath } from "../shared/spa-routes";
import { enforcePublicAuthRateLimit, enforceSignedApiRateLimit } from "./rate-limit";
-import { applySecurityHeaders } from "./security-headers";
+import { applySecurityHeaders, turnstileAllowed } from "./security-headers";
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./db/schema";
import {
@@ -112,7 +112,7 @@ app.onError((err, c) => {
// more than just a machine-readable `code` (e.g. same_destination_match's
// matchedLinkId/matchedLink) straight through to the caller.
const respond = (body: ErrorBody, status: ContentfulStatusCode) =>
- applySecurityHeaders(c.json(body, status), !!c.env.TURNSTILE_SITE_KEY);
+ applySecurityHeaders(c.json(body, status), turnstileAllowed(c.env, c.req.url));
// Attach the error to the wide event so it reaches Sentry Logs with the
// request context already accumulated. withSentry still captures the
// exception as a Sentry Issue for alerting.
@@ -149,7 +149,7 @@ app.onError((err, c) => {
// while it isn't.
app.use("*", async (c, next) => {
await next();
- c.res = applySecurityHeaders(c.res, !!c.env.TURNSTILE_SITE_KEY);
+ c.res = applySecurityHeaders(c.res, turnstileAllowed(c.env, c.req.url));
});
/* ---------------- redirect hot path ---------------- */
diff --git a/src/worker/routes/auth.ts b/src/worker/routes/auth.ts
index aa7534a4..78e51f88 100644
--- a/src/worker/routes/auth.ts
+++ b/src/worker/routes/auth.ts
@@ -6,6 +6,7 @@ import { alias } from "drizzle-orm/sqlite-core";
import * as schema from "../db/schema";
import type { AppEnv } from "../env";
import { sharedLinkHost } from "../util";
+import { servedSiteKey } from "../turnstile";
import { requireUser } from "../guards";
import { jsonBodyLimit } from "../body-limit";
import type { AppConfig, CurrentUser } from "@/shared/types";
@@ -108,6 +109,8 @@ userRoutes.get("/config", (c) => {
linkHost: sharedLinkHost(c.env),
emailEnabled: emailConfigured(c.env),
googleEnabled: Boolean(c.env.GOOGLE_CLIENT_ID && c.env.GOOGLE_CLIENT_SECRET),
- turnstileSiteKey: c.env.TURNSTILE_SITE_KEY || undefined,
+ // Only when the check is on: a lone site key would render a widget
+ // whose token nobody checks.
+ turnstileSiteKey: servedSiteKey(c.env),
} satisfies AppConfig);
});
diff --git a/src/worker/security-headers.ts b/src/worker/security-headers.ts
index 40e2009f..05aeba6d 100644
--- a/src/worker/security-headers.ts
+++ b/src/worker/security-headers.ts
@@ -28,11 +28,14 @@
*
* Cloudflare Turnstile (#304) is the one source decided per request rather
* than per build: its script and the iframe its challenge runs in come from
- * challenges.cloudflare.com, allowed only when the deployment serves a
- * TURNSTILE_SITE_KEY, which is the only time the browser loads it. A
- * self-hosted copy without the keys never allows it.
+ * challenges.cloudflare.com, allowed only on the app's own host (APP_HOST)
+ * and only when Turnstile is on (both keys set), which is the only time the
+ * browser loads it. See turnstileAllowed(). A custom domain, the shared link
+ * host and a self-hosted copy without the keys never allow it.
*/
import { POSTHOG_CONFIGURED, RDYRCT_SITE } from "../shared/site";
+import type { Env } from "./env";
+import { turnstileMode } from "./turnstile";
const POSTHOG = POSTHOG_CONFIGURED ? "https://*.posthog.com" : "";
const SENTRY =
@@ -115,8 +118,7 @@ const CSP_WITH_TURNSTILE = buildCsp(TURNSTILE);
*
* The copy is cheap: the body is handed over by reference, never read.
*
- * `turnstile` adds challenges.cloudflare.com: pass whether TURNSTILE_SITE_KEY
- * is set.
+ * `turnstile` adds challenges.cloudflare.com: pass turnstileAllowed().
*/
export function applySecurityHeaders(res: Response, turnstile = false): Response {
const out = new Response(res.body, res);
@@ -134,3 +136,12 @@ export function applySecurityHeaders(res: Response, turnstile = false): Response
out.headers.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
return out;
}
+
+/**
+ * Whether this response may allow Turnstile in its CSP: the check is on, and
+ * the request is for the app itself. Link hosts (custom domains, the shared
+ * link host) serve redirects and the disabled page, which never load it.
+ */
+export function turnstileAllowed(env: Env, url: string): boolean {
+ return turnstileMode(env) === "on" && new URL(url).host === env.APP_HOST.toLowerCase();
+}
diff --git a/src/worker/turnstile.ts b/src/worker/turnstile.ts
index 7c8d399b..ac8753dc 100644
--- a/src/worker/turnstile.ts
+++ b/src/worker/turnstile.ts
@@ -24,10 +24,36 @@ const siteverifySchema = v.object({
success: v.boolean(),
action: v.optional(v.string()),
"error-codes": v.optional(v.array(v.string()), []),
- metadata: v.optional(v.object({ result_with_testing_key: v.optional(v.boolean()) })),
});
type SiteverifyAnswer = v.InferOutput;
+/** Cloudflare's published test secrets (always pass, always fail, already
+ * spent). None of them echoes an action. Matched against our own secret,
+ * never against anything siteverify says about itself. */
+const TEST_SECRETS: ReadonlySet = new Set([
+ "1x0000000000000000000000000000000AA",
+ "2x0000000000000000000000000000000AA",
+ "3x0000000000000000000000000000000AA",
+]);
+
+/**
+ * Whether Turnstile is on for this deployment. Both keys or neither: one
+ * without the other is a deployment that looks protected and is not, so it
+ * is "misconfigured", which refuses every guarded form and serves no site
+ * key. Set both in one `wrangler secret bulk` call so no deploy sees half.
+ */
+export function turnstileMode(env: Env): "on" | "off" | "misconfigured" {
+ const site = !!env.TURNSTILE_SITE_KEY;
+ const secret = !!env.TURNSTILE_SECRET_KEY;
+ if (site && secret) return "on";
+ return site || secret ? "misconfigured" : "off";
+}
+
+/** The site key the browser should render, only when the check is on. */
+export function servedSiteKey(env: Env): string | undefined {
+ return turnstileMode(env) === "on" ? env.TURNSTILE_SITE_KEY : undefined;
+}
+
/** Asks Cloudflare about one token. null when it did not answer in a shape we
* can read, which the caller treats as a refusal. */
async function siteverify(secret: string, token: string): Promise {
@@ -54,39 +80,45 @@ async function siteverify(secret: string, token: string): Promise {
- if (!env.TURNSTILE_SECRET_KEY) return true;
+ const mode = turnstileMode(env);
+ if (mode === "off") return true;
+ if (mode === "misconfigured") {
+ console.error(
+ "turnstile_misconfigured",
+ "set both TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY, or neither",
+ );
+ return false;
+ }
if (!token) {
console.warn("turnstile_refused", scope, "missing");
return false;
}
// Fail closed: an unreachable verifier is no reason to let bots in.
- const answer = await siteverify(env.TURNSTILE_SECRET_KEY, token);
+ const secret = env.TURNSTILE_SECRET_KEY ?? "";
+ const answer = await siteverify(secret, token);
if (!answer) return false;
- const ok = answer.success && actionMatches(answer, scope);
+ const ok = answer.success && actionMatches(answer, scope, secret);
if (!ok) console.warn("turnstile_refused", scope, answer["error-codes"].join(",") || "action");
return ok;
}
diff --git a/tests/e2e/auth.pw.ts b/tests/e2e/auth.pw.ts
index 9bd1c8ff..b8d6f3b7 100644
--- a/tests/e2e/auth.pw.ts
+++ b/tests/e2e/auth.pw.ts
@@ -27,6 +27,23 @@ test("a new account gets one welcome email once its address is verified", async
.toHaveLength(1);
});
+test("a sign-up sent before /api/config answers still carries a Turnstile token", async ({
+ page,
+}) => {
+ // The site key arrives with /api/config. A form submitted before that used
+ // to go out with no token, be refused, retry with no token again, and fail.
+ await page.route("**/api/config", async (route) => {
+ await new Promise((resolve) => setTimeout(resolve, 6_000));
+ await route.continue();
+ });
+ const email = `slow-config-${Date.now()}@gmail.com`;
+ await submitSignup(page, email, "test-password-123");
+
+ await expect(page.getByRole("heading", { name: "Enter your code" })).toBeVisible({
+ timeout: 40_000,
+ });
+});
+
test.describe("authentication forms", () => {
for (const token of [null, "fresh-signup-session"]) {
test(`no-mail signup counts completion only with a fresh session (${token ? "new" : "duplicate"})`, async ({
diff --git a/tests/worker/no-email-signup.worker.ts b/tests/worker/no-email-signup.worker.ts
index d0c5407b..b4b769d4 100644
--- a/tests/worker/no-email-signup.worker.ts
+++ b/tests/worker/no-email-signup.worker.ts
@@ -16,6 +16,7 @@ it("signs up without verification and sends no email", async () => {
const mail = captureEmails({ mx: "deliverable" });
const env = overrideEnv({
BETTER_AUTH_SECRET: "test-secret",
+ TURNSTILE_SITE_KEY: undefined,
TURNSTILE_SECRET_KEY: undefined,
RESEND_API_KEY: undefined,
});
diff --git a/tests/worker/security-headers.worker.ts b/tests/worker/security-headers.worker.ts
index 4e88a90c..9ed9ab0f 100644
--- a/tests/worker/security-headers.worker.ts
+++ b/tests/worker/security-headers.worker.ts
@@ -1,8 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { env } from "cloudflare:workers";
import { reset } from "cloudflare:test";
-import { applySecurityHeaders } from "../../src/worker/security-headers";
-import { applyTestMigrations, fetchWorker } from "./support";
+import { applySecurityHeaders, turnstileAllowed } from "../../src/worker/security-headers";
+import { applyTestMigrations, fetchWorker, overrideEnv } from "./support";
const HEADER_NAMES = [
"content-security-policy",
@@ -92,3 +92,24 @@ describe("security headers (#21)", () => {
expectSecurityHeaders(res);
});
});
+
+describe("Turnstile in the CSP (#304)", () => {
+ const keys = { TURNSTILE_SITE_KEY: "site", TURNSTILE_SECRET_KEY: "secret" };
+ const at = (overrides: Parameters[0]) =>
+ overrideEnv({ APP_HOST: "rdyrct.com", ...overrides });
+
+ it("is allowed on the app host when both keys are set", () => {
+ expect(turnstileAllowed(at(keys), "https://rdyrct.com/signup")).toBe(true);
+ });
+
+ it("is never allowed on a link host", () => {
+ expect(turnstileAllowed(at(keys), "https://rdyr.cc/abc")).toBe(false);
+ expect(turnstileAllowed(at(keys), "https://go.example.com/abc")).toBe(false);
+ });
+
+ it("is not allowed with either key missing", () => {
+ const url = "https://rdyrct.com/signup";
+ expect(turnstileAllowed(at({ ...keys, TURNSTILE_SECRET_KEY: undefined }), url)).toBe(false);
+ expect(turnstileAllowed(at({ ...keys, TURNSTILE_SITE_KEY: undefined }), url)).toBe(false);
+ });
+});
diff --git a/tests/worker/turnstile-disabled.worker.ts b/tests/worker/turnstile-disabled.worker.ts
index e622d59d..6e2a10ba 100644
--- a/tests/worker/turnstile-disabled.worker.ts
+++ b/tests/worker/turnstile-disabled.worker.ts
@@ -3,7 +3,7 @@ import { reset } from "cloudflare:test";
import { applyTestMigrations, captureEmails, fetchWorker, overrideEnv } from "./support";
/**
- * With no TURNSTILE_SECRET_KEY the gate is off and signup works as it did
+ * With neither Turnstile key the gate is off and signup works as it did
* before, which keeps local dev, self-hosting and CI from needing a key.
*
* Its own file because getAuth() memoizes one auth instance per isolate, and
@@ -15,7 +15,7 @@ beforeEach(async () => {
captureEmails({ mx: "deliverable" });
});
-it("lets signup through untouched when no secret is configured", async () => {
+it("lets signup through untouched when neither key is configured", async () => {
const res = await fetchWorker(
new Request("http://localhost/api/auth/sign-up/email", {
method: "POST",
@@ -26,7 +26,11 @@ it("lets signup through untouched when no secret is configured", async () => {
name: "probe",
}),
}),
- overrideEnv({ BETTER_AUTH_SECRET: "test-secret", TURNSTILE_SECRET_KEY: undefined }),
+ overrideEnv({
+ BETTER_AUTH_SECRET: "test-secret",
+ TURNSTILE_SITE_KEY: undefined,
+ TURNSTILE_SECRET_KEY: undefined,
+ }),
);
expect(res.status).toBe(200);
});
diff --git a/tests/worker/turnstile.worker.ts b/tests/worker/turnstile.worker.ts
index 150e6847..69eac3da 100644
--- a/tests/worker/turnstile.worker.ts
+++ b/tests/worker/turnstile.worker.ts
@@ -14,18 +14,20 @@ import { spendToken } from "../../src/worker/turnstile";
*
* Cloudflare's siteverify is stubbed; the stub records what we sent it.
*/
+/** Turnstile on, with a real-looking (not Cloudflare's test) secret, so the
+ * action check runs. APP_HOST is the host these requests go to. */
const ON = () =>
- overrideEnv({ BETTER_AUTH_SECRET: "test-secret", TURNSTILE_SECRET_KEY: "test-turnstile-secret" });
+ overrideEnv({
+ BETTER_AUTH_SECRET: "test-secret",
+ APP_HOST: "localhost",
+ TURNSTILE_SITE_KEY: "test-site-key",
+ TURNSTILE_SECRET_KEY: "test-turnstile-secret",
+ });
let sent: URLSearchParams[] = [];
/** Makes siteverify answer `answer`, or fail like an unreachable network. */
-type Siteverify = {
- success: boolean;
- action?: string;
- "error-codes"?: string[];
- metadata?: { result_with_testing_key?: boolean };
-};
+type Siteverify = { success: boolean; action?: string; "error-codes"?: string[] };
function siteverify(answer: Siteverify | Error | "not json") {
const real = globalThis.fetch;
@@ -39,17 +41,6 @@ function siteverify(answer: Siteverify | Error | "not json") {
});
}
-function signUp(email: string, headers: Record = {}) {
- return fetchWorker(
- new Request("http://localhost/api/auth/sign-up/email", {
- method: "POST",
- headers: { "content-type": "application/json", ...headers },
- body: JSON.stringify({ email, password: "a-good-password-1", name: "probe" }),
- }),
- ON(),
- );
-}
-
beforeEach(async () => {
sent = [];
reset();
@@ -94,20 +85,32 @@ describe("spending a token", () => {
expect(await spendToken(ON(), "signup", "no-action")).toBe(false);
});
- it("accepts Cloudflare's test keys, which never echo an action", async () => {
- // What siteverify really answers for the always-pass test secret that
- // dev, CI and e2e run on.
- siteverify({ success: true, "error-codes": [], metadata: { result_with_testing_key: true } });
- expect(await spendToken(ON(), "signup", "XXXX.DUMMY.TOKEN.XXXX")).toBe(true);
+ // Cloudflare's always-pass test secret, which dev, CI and e2e run on.
+ const TEST_KEYS = () =>
+ overrideEnv({
+ TURNSTILE_SITE_KEY: "1x00000000000000000000AA",
+ TURNSTILE_SECRET_KEY: "1x0000000000000000000000000000000AA",
+ });
+
+ it("accepts Cloudflare's test secret, which never echoes an action", async () => {
+ // What siteverify really answers for that secret.
+ siteverify({ success: true, "error-codes": [] });
+ expect(await spendToken(TEST_KEYS(), "signup", "XXXX.DUMMY.TOKEN.XXXX")).toBe(true);
});
- it("refuses a test-key answer that says no", async () => {
- siteverify({
- success: false,
- "error-codes": ["invalid-input-response"],
- metadata: { result_with_testing_key: true },
- });
- expect(await spendToken(ON(), "signup", "XXXX.DUMMY.TOKEN.XXXX")).toBe(false);
+ it("refuses a test-secret answer that says no", async () => {
+ siteverify({ success: false, "error-codes": ["invalid-input-response"] });
+ expect(await spendToken(TEST_KEYS(), "signup", "XXXX.DUMMY.TOKEN.XXXX")).toBe(false);
+ });
+
+ it("does not take siteverify's word that a test key answered", async () => {
+ // Our secret is a real one, so an answer claiming to come from a test
+ // key still has to name the action.
+ siteverify({ success: true });
+ vi.mocked(globalThis.fetch).mockImplementationOnce(async () =>
+ Response.json({ success: true, metadata: { result_with_testing_key: true } }),
+ );
+ expect(await spendToken(ON(), "signup", "claims-test")).toBe(false);
});
it("refuses when siteverify answers something that is not its JSON", async () => {
@@ -115,119 +118,178 @@ describe("spending a token", () => {
expect(await spendToken(ON(), "signup", "any")).toBe(false);
});
- it("is off, and asks nobody, when no secret is set", async () => {
+ it("is off, and asks nobody, when neither key is set", async () => {
siteverify({ success: false });
- const off = overrideEnv({ TURNSTILE_SECRET_KEY: undefined });
+ const off = overrideEnv({ TURNSTILE_SITE_KEY: undefined, TURNSTILE_SECRET_KEY: undefined });
expect(await spendToken(off, "signup", "")).toBe(true);
expect(sent).toHaveLength(0);
});
-});
-describe("at signup", () => {
- it("creates the account for an approved token", async () => {
+ it("refuses everything, and asks nobody, with only one of the two keys", async () => {
siteverify({ success: true, action: "signup" });
- const res = await signUp("fresh@example.com", { "x-turnstile-token": "good" });
- expect(res.status).toBe(200);
+ const siteOnly = overrideEnv({ TURNSTILE_SITE_KEY: "k", TURNSTILE_SECRET_KEY: undefined });
+ const secretOnly = overrideEnv({ TURNSTILE_SITE_KEY: undefined, TURNSTILE_SECRET_KEY: "s" });
+ expect(await spendToken(siteOnly, "signup", "good")).toBe(false);
+ expect(await spendToken(secretOnly, "signup", "good")).toBe(false);
+ expect(sent).toHaveLength(0);
});
+});
- it("refuses without a token, and creates no account", async () => {
- siteverify({ success: true, action: "signup" });
- const res = await signUp("notoken@example.com");
- expect(res.status).toBe(400);
- const { results } = await env.DB.prepare("select email from user").all();
- expect(results.map((r) => r.email)).not.toContain("notoken@example.com");
- });
+/** One guarded request per route, carrying `token` the way that form does. */
+const post = (path: string, body: Record, headers: Record = {}) =>
+ fetchWorker(
+ new Request(`http://localhost${path}`, {
+ method: "POST",
+ headers: { "content-type": "application/json", ...headers },
+ body: JSON.stringify(body),
+ }),
+ ON(),
+ );
+const byHeader = (token?: string): Record =>
+ token ? { "x-turnstile-token": token } : {};
+const byBody = (token?: string): Record => (token ? { turnstileToken: token } : {});
- it("refuses a token siteverify rejects", async () => {
- siteverify({ success: false });
- expect((await signUp("bad@example.com", { "x-turnstile-token": "bad" })).status).toBe(400);
- });
-});
+const ROUTES = [
+ {
+ name: "sign-up",
+ action: "signup",
+ ok: 200,
+ send: (token?: string) =>
+ post(
+ "/api/auth/sign-up/email",
+ {
+ email: `probe-${crypto.randomUUID()}@example.com`,
+ password: "a-good-password-1",
+ name: "probe",
+ },
+ byHeader(token),
+ ),
+ },
+ {
+ name: "password reset",
+ action: "password-reset",
+ ok: 200,
+ send: (token?: string) =>
+ post(
+ "/api/auth/request-password-reset",
+ { email: "someone@example.com", redirectTo: "/reset-password" },
+ byHeader(token),
+ ),
+ },
+ {
+ name: "the report form",
+ action: "report",
+ ok: 201,
+ send: (token?: string) =>
+ post("/api/reports", { link: "sale", reason: "phishing", ...byBody(token) }),
+ },
+ {
+ name: "the anonymous shortener",
+ action: "anon-link",
+ ok: 201,
+ send: (token?: string) =>
+ post("/api/shorten", { destination: "https://example.com/scripted", ...byBody(token) }),
+ },
+] as const;
-describe("at password reset", () => {
- const requestReset = (headers: Record = {}) =>
- fetchWorker(
- new Request("http://localhost/api/auth/request-password-reset", {
- method: "POST",
- headers: { "content-type": "application/json", ...headers },
- body: JSON.stringify({ email: "someone@example.com", redirectTo: "/reset-password" }),
- }),
- ON(),
- );
+describe.each(ROUTES)("$name", ({ action, ok, send }) => {
+ it("goes through with a token approved for this form", async () => {
+ siteverify({ success: true, action });
+ expect((await send("good")).status).toBe(ok);
+ });
it("refuses without a token", async () => {
- siteverify({ success: true, action: "password-reset" });
- expect((await requestReset()).status).toBe(400);
+ siteverify({ success: true, action });
+ expect((await send()).status).toBe(400);
});
- it("refuses a token earned on the signup form", async () => {
- siteverify({ success: true, action: "signup" });
- expect((await requestReset({ "x-turnstile-token": "crossed" })).status).toBe(400);
+ it("refuses a token siteverify says no to", async () => {
+ // The right action, so only `success` can be what refuses it.
+ siteverify({ success: false, action, "error-codes": ["timeout-or-duplicate"] });
+ expect((await send("spent")).status).toBe(400);
});
- it("goes through with a token for this form", async () => {
- siteverify({ success: true, action: "password-reset" });
- expect((await requestReset({ "x-turnstile-token": "good" })).status).toBe(200);
+ it("refuses a token rendered for another form", async () => {
+ siteverify({ success: true, action: action === "signup" ? "report" : "signup" });
+ expect((await send("crossed")).status).toBe(400);
});
});
-describe("the public forms outside better-auth", () => {
- const post = (path: string, body: Record) =>
- fetchWorker(
- new Request(`http://localhost${path}`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(body),
- }),
- ON(),
- );
- const report = (turnstileToken?: string) =>
- post("/api/reports", {
- link: "sale",
- reason: "phishing",
- ...(turnstileToken && { turnstileToken }),
- });
- const shorten = (turnstileToken?: string) =>
- post("/api/shorten", {
- destination: "https://example.com/scripted",
- ...(turnstileToken && { turnstileToken }),
+describe("what a refusal leaves behind", () => {
+ it("creates no account at sign-up", async () => {
+ siteverify({ success: false });
+ await post("/api/auth/sign-up/email", {
+ email: "notoken@example.com",
+ password: "a-good-password-1",
+ name: "probe",
});
+ const { results } = await env.DB.prepare("select email from user").all();
+ expect(results.map((r) => r.email)).not.toContain("notoken@example.com");
+ });
- it("refuses a report without a token, and stores nothing", async () => {
- siteverify({ success: true, action: "report" });
- const res = await report();
- expect(res.status).toBe(400);
+ it("stores no report, and says why in a code the browser retries on", async () => {
+ siteverify({ success: false });
+ const res = await post("/api/reports", { link: "sale", reason: "phishing" });
expect(await res.json()).toMatchObject({ code: "TURNSTILE_FAILED" });
const stored = await env.DB.prepare("select count(*) as n from link_reports").first<{
n: number;
}>();
expect(stored?.n).toBe(0);
});
+});
- it("takes a report with a token for the report form", async () => {
- siteverify({ success: true, action: "report" });
- expect((await report("good")).status).toBe(201);
+describe("a site key with no secret", () => {
+ const SITE_ONLY = () =>
+ overrideEnv({
+ BETTER_AUTH_SECRET: "test-secret",
+ APP_HOST: "localhost",
+ TURNSTILE_SITE_KEY: "test-site-key",
+ TURNSTILE_SECRET_KEY: undefined,
+ });
+
+ it("serves no site key, so no browser renders a widget nobody checks", async () => {
+ const res = await fetchWorker(new Request("http://localhost/api/config"), SITE_ONLY());
+ expect(await res.json()).not.toHaveProperty("turnstileSiteKey");
});
- it("refuses an anonymous link without a token", async () => {
- siteverify({ success: true, action: "anon-link" });
- const res = await shorten();
+ it("refuses the guarded forms and logs why", async () => {
+ siteverify({ success: true, action: "report" });
+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});
+ const res = await fetchWorker(
+ new Request("http://localhost/api/reports", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ link: "sale", reason: "phishing", turnstileToken: "good" }),
+ }),
+ SITE_ONLY(),
+ );
expect(res.status).toBe(400);
- expect(await res.json()).toMatchObject({ code: "TURNSTILE_FAILED" });
+ expect(logged).toHaveBeenCalledWith("turnstile_misconfigured", expect.any(String));
});
- it("refuses an anonymous link with a token from another form", async () => {
- siteverify({ success: true, action: "report" });
- expect((await shorten("crossed")).status).toBe(400);
+ it("allows nothing from Cloudflare in the CSP", async () => {
+ const res = await fetchWorker(new Request("http://localhost/no-such-page"), SITE_ONLY());
+ expect(res.headers.get("content-security-policy")).not.toContain("challenges.cloudflare.com");
+ });
+
+ it("serves the site key once both are set", async () => {
+ const res = await fetchWorker(new Request("http://localhost/api/config"), ON());
+ expect(await res.json()).toMatchObject({ turnstileSiteKey: "test-site-key" });
});
});
describe("the Content-Security-Policy", () => {
- const cspWith = async (siteKey: string | undefined) =>
+ const cspAt = async (url: string, keys: { site?: string; secret?: string }) =>
(
await fetchWorker(
- new Request("http://localhost/no-such-page"),
- overrideEnv({ BETTER_AUTH_SECRET: "test-secret", TURNSTILE_SITE_KEY: siteKey }),
+ new Request(url, { redirect: "manual" }),
+ overrideEnv({
+ BETTER_AUTH_SECRET: "test-secret",
+ APP_HOST: "localhost",
+ SHARED_LINK_HOST: "rdyr.cc",
+ TURNSTILE_SITE_KEY: keys.site,
+ TURNSTILE_SECRET_KEY: keys.secret,
+ }),
)
).headers.get("content-security-policy") ?? "";
const directive = (csp: string, name: string) =>
@@ -235,15 +297,24 @@ describe("the Content-Security-Policy", () => {
.split(";")
.map((part) => part.trim())
.find((part) => part.startsWith(`${name} `)) ?? "";
+ const BOTH = { site: "1x00000000000000000000AA", secret: "1x0000000000000000000000000000000AA" };
- it("allows Turnstile's script and iframe when a site key is served", async () => {
- const csp = await cspWith("1x00000000000000000000AA");
+ it("allows Turnstile's script and iframe on the app host when it is on", async () => {
+ const csp = await cspAt("http://localhost/no-such-page", BOTH);
expect(directive(csp, "script-src")).toContain("https://challenges.cloudflare.com");
expect(directive(csp, "frame-src")).toBe("frame-src https://challenges.cloudflare.com");
});
+ it("never allows it on the shared link host or a custom domain", async () => {
+ for (const url of ["http://rdyr.cc/some-slug", "http://go.example.com/some-slug"]) {
+ const csp = await cspAt(url, BOTH);
+ expect(csp, url).toContain("script-src 'self'");
+ expect(csp, url).not.toContain("challenges.cloudflare.com");
+ }
+ });
+
it("allows nothing from Cloudflare on a copy without the keys", async () => {
- const csp = await cspWith(undefined);
+ const csp = await cspAt("http://localhost/no-such-page", {});
expect(csp).not.toContain("challenges.cloudflare.com");
expect(directive(csp, "frame-src")).toBe("");
});
From d007c76cfb2f31639977c7147508b9b2e6a8e1b5 Mon Sep 17 00:00:00 2001
From: baron unread
Date: Mon, 26 Oct 2026 17:45:30 +0100
Subject: [PATCH 5/8] Turnstile: pass fallow 3.34.1 after the dependency bump
#373 moved fallow to 3.34.1, which follows lazyRouteComponent names, so
the unused-export suppressions on LoginPage, SignupPage, ReportPage and
UtmBuilderPage are stale. It also scores headers() in useTurnstile over
the CRAP threshold; the config wait, the token hand-off and the warning
move into small module functions with no change in behaviour (the
slow-config e2e still passes).
Co-Authored-By: Claude Opus 5.5
---
src/app/lib/turnstile.ts | 59 ++++++++++++++++++++++++----------
src/app/routes/auth.tsx | 4 ---
src/app/routes/report.tsx | 3 --
src/app/routes/utm-builder.tsx | 3 --
4 files changed, 42 insertions(+), 27 deletions(-)
diff --git a/src/app/lib/turnstile.ts b/src/app/lib/turnstile.ts
index f58c6c5d..b9a4b9c7 100644
--- a/src/app/lib/turnstile.ts
+++ b/src/app/lib/turnstile.ts
@@ -10,8 +10,8 @@
* server decides: an empty one is rejected when TURNSTILE_SECRET_KEY is set
* and ignored when it is not.
*/
-import { useCallback, useRef } from "react";
-import { useQueryClient } from "@tanstack/react-query";
+import { type RefObject, useCallback, useRef } from "react";
+import { type QueryClient, useQueryClient } from "@tanstack/react-query";
import { TURNSTILE_TOKEN_HEADER } from "@/shared/types";
import { configQuery, useConfig } from "./hooks";
import { retryOnTurnstileFailure } from "./turnstile-retry";
@@ -109,6 +109,41 @@ async function solve(siteKey: string, scope: TurnstileScope): Promise {
}
}
+/**
+ * The site key, waiting for /api/config if it has not answered yet. A form
+ * submitted before then must not go out without a token. A failed fetch is
+ * not cached, so the retry after a refusal asks again instead of failing for
+ * the whole page load.
+ */
+async function siteKeyWhenReady(qc: QueryClient): Promise {
+ try {
+ return (await qc.ensureQueryData(configQuery)).turnstileSiteKey;
+ } catch {
+ return undefined;
+ }
+}
+
+type Pending = { token: Promise; primedAt: number } | null;
+
+/** Takes the primed token, if any. Single-use, so the slot is cleared: a form
+ * submitted twice solves again rather than replaying a burned token. */
+async function takeToken(pending: RefObject): Promise {
+ const token = (await pending.current?.token) ?? "";
+ pending.current = null;
+ return token;
+}
+
+/** The one place that knows "we could not run the check" from "the server
+ * refused it". */
+function warnIfUnsolved(siteKey: string | undefined, token: string, scope: TurnstileScope) {
+ if (siteKey && !token) console.warn("turnstile_solve_failed", scope);
+}
+
+/** The header a guarded request carries, or none without a token. */
+function tokenHeader(token: string): Record {
+ return token ? { [TURNSTILE_TOKEN_HEADER]: token } : {};
+}
+
/**
* A token for one form.
*
@@ -122,7 +157,7 @@ async function solve(siteKey: string, scope: TurnstileScope): Promise {
export function useTurnstile(scope: TurnstileScope) {
const qc = useQueryClient();
const loadedSiteKey = useConfig().data?.turnstileSiteKey;
- const pending = useRef<{ token: Promise; primedAt: number } | null>(null);
+ const pending = useRef(null);
const startSolve = useCallback(
(siteKey: string | undefined) => {
@@ -139,21 +174,11 @@ export function useTurnstile(scope: TurnstileScope) {
const prime = useCallback(() => startSolve(loadedSiteKey), [startSolve, loadedSiteKey]);
const headers = useCallback(async (): Promise> => {
- // A form submitted before /api/config answered must not go out without
- // a token, so wait for it here. A failed fetch is not cached, so the
- // retry after a refusal asks again instead of failing for the whole
- // page load.
- const siteKey = await qc
- .ensureQueryData(configQuery)
- .then((config) => config.turnstileSiteKey)
- .catch(() => undefined);
+ const siteKey = await siteKeyWhenReady(qc);
startSolve(siteKey);
- const token = (await pending.current?.token) ?? "";
- pending.current = null;
- // The one place that knows "we could not run the check" from "the server
- // refused it".
- if (siteKey && !token) console.warn("turnstile_solve_failed", scope);
- return token ? { [TURNSTILE_TOKEN_HEADER]: token } : {};
+ const token = await takeToken(pending);
+ warnIfUnsolved(siteKey, token, scope);
+ return tokenHeader(token);
}, [qc, startSolve, scope]);
const guarded = useCallback(
diff --git a/src/app/routes/auth.tsx b/src/app/routes/auth.tsx
index 3df9d745..c9d643a1 100644
--- a/src/app/routes/auth.tsx
+++ b/src/app/routes/auth.tsx
@@ -909,9 +909,5 @@ function AuthPage({ mode }: { mode: "login" | "signup" }) {
);
}
-// main.tsx names these as strings for lazyRouteComponent, which static
-// analysis cannot follow.
-// fallow-ignore-next-line unused-export
export const LoginPage = () => ;
-// fallow-ignore-next-line unused-export
export const SignupPage = () => ;
diff --git a/src/app/routes/report.tsx b/src/app/routes/report.tsx
index 20f5c3c5..cd7d87c6 100644
--- a/src/app/routes/report.tsx
+++ b/src/app/routes/report.tsx
@@ -23,9 +23,6 @@ const REASON_LABELS = {
const reasonFrom = (value: string): ReportReason =>
REPORT_REASONS.find((r) => r === value) ?? "phishing";
-// main.tsx names this export as a string, for lazyRouteComponent, which
-// static analysis can't follow.
-// fallow-ignore-next-line unused-export
export function ReportPage() {
const { authed } = useAudience();
const toast = useToast();
diff --git a/src/app/routes/utm-builder.tsx b/src/app/routes/utm-builder.tsx
index c4415125..9edca4dd 100644
--- a/src/app/routes/utm-builder.tsx
+++ b/src/app/routes/utm-builder.tsx
@@ -376,9 +376,6 @@ function Builder() {
);
}
-// main.tsx names this export as a string, for lazyRouteComponent, which
-// static analysis can't follow.
-// fallow-ignore-next-line unused-export
export function UtmBuilderPage() {
const { ctaTo, ctaLabel } = useAudience();
return (
From e94e0d11701f4d1d665aeec27d43dd813406ae30 Mon Sep 17 00:00:00 2001
From: baron unread
Date: Mon, 26 Oct 2026 18:17:48 +0100
Subject: [PATCH 6/8] Privacy: name Cloudflare Turnstile and the forms it
checks
Co-Authored-By: Claude Opus 5.5
---
src/app/routes/privacy.tsx | 22 +++++++++++++---------
src/shared/page-meta.ts | 6 +++---
2 files changed, 16 insertions(+), 12 deletions(-)
diff --git a/src/app/routes/privacy.tsx b/src/app/routes/privacy.tsx
index bd60b0e3..43e308a5 100644
--- a/src/app/routes/privacy.tsx
+++ b/src/app/routes/privacy.tsx
@@ -18,7 +18,7 @@ export function PrivacyPage() {
@@ -71,6 +71,10 @@ export function PrivacyPage() {
Sentry for our legitimate interest in keeping the service secure and reliable. Sentry does
not set a cookie in rdyrct. We check where links point against Google's list of
unsafe sites for our legitimate interest in keeping phishing and malware off the service.
+ When you sign up, reset a password, shorten a link from the home page, build a UTM link,
+ or report a link, Cloudflare Turnstile reads signals from your browser and connection to
+ check that a person, not a script, sent the form. We use it for our legitimate interest in
+ keeping automated sign-ups and abuse off the service.
@@ -94,14 +98,14 @@ export function PrivacyPage() {
Sub-processors
We rely on a small number of sub-processors to run the service: Cloudflare (hosting, the
- D1 database, and KV storage), Resend (transactional email), Polar (billing, acting as
- merchant of record), PostHog, EU region (product usage analytics), Sentry (technical error
- monitoring), and Google (Web Risk). Google receives the destination address of a link when
- the link is created or edited, when we check it again each week, and when its traffic
- jumps, and checks it against Google's list of unsafe sites. It receives nothing about
- you or the people who click the link. Some may process data outside the EU/EEA; where they
- do, transfers are covered by the appropriate safeguards, such as the EU Standard
- Contractual Clauses.
+ D1 database, KV storage, and the Turnstile check on forms), Resend (transactional email),
+ Polar (billing, acting as merchant of record), PostHog, EU region (product usage
+ analytics), Sentry (technical error monitoring), and Google (Web Risk). Google receives
+ the destination address of a link when the link is created or edited, when we check it
+ again each week, and when its traffic jumps, and checks it against Google's list of
+ unsafe sites. It receives nothing about you or the people who click the link. Some may
+ process data outside the EU/EEA; where they do, transfers are covered by the appropriate
+ safeguards, such as the EU Standard Contractual Clauses.
diff --git a/src/shared/page-meta.ts b/src/shared/page-meta.ts
index abbfe976..18641f52 100644
--- a/src/shared/page-meta.ts
+++ b/src/shared/page-meta.ts
@@ -316,7 +316,7 @@ Short.io beats rdyrct on price and free-plan size. rdyrct is the better pick whe
"What rdyrct stores and what it does not: click analytics keep country, referrer, device and time, never an IP address or a precise location.",
markdown: `# Privacy policy
-This policy explains what rdyrct collects, why, the legal basis for it, and how you can exercise your rights. Last updated 25 October 2026.
+This policy explains what rdyrct collects, why, the legal basis for it, and how you can exercise your rights. Last updated 26 October 2026.
## Data controller
@@ -330,7 +330,7 @@ If you accept analytics, PostHog records product events tied to your account. It
## Why we process it
-We process account and organization data to provide the service, send transactional email, and provide click analytics. The session cookie is necessary to sign you in. PostHog runs only with your consent, which you can withdraw at any time from Cookie settings. We ask again after six months. We process technical error reports to keep the service secure and reliable. We check where links point against Google's list of unsafe sites to keep phishing and malware off the service.
+We process account and organization data to provide the service, send transactional email, and provide click analytics. The session cookie is necessary to sign you in. PostHog runs only with your consent, which you can withdraw at any time from Cookie settings. We ask again after six months. We process technical error reports to keep the service secure and reliable. We check where links point against Google's list of unsafe sites to keep phishing and malware off the service. When you sign up, reset a password, shorten a link from the home page, build a UTM link, or report a link, Cloudflare Turnstile reads signals from your browser and connection to check that a person, not a script, sent the form, to keep automated sign-ups and abuse off the service.
## Cookies
@@ -338,7 +338,7 @@ rdyrct sets a necessary session cookie. If you accept analytics, PostHog also se
## Sub-processors
-We use Cloudflare for hosting and storage, Resend for transactional email, Polar for billing, PostHog EU for product analytics, Sentry for error monitoring, and Google Web Risk to check links. Google receives the destination address of a link when the link is created or edited, when we check it again each week, and when its traffic jumps, and checks it against Google's list of unsafe sites. It receives nothing about you or the people who click the link.
+We use Cloudflare for hosting, storage, and the Turnstile check on forms, Resend for transactional email, Polar for billing, PostHog EU for product analytics, Sentry for error monitoring, and Google Web Risk to check links. Google receives the destination address of a link when the link is created or edited, when we check it again each week, and when its traffic jumps, and checks it against Google's list of unsafe sites. It receives nothing about you or the people who click the link.
## Retention and rights
From 8f077595e3ae74d594af827039ca145d1049be84 Mon Sep 17 00:00:00 2001
From: baron unread
Date: Mon, 26 Oct 2026 18:27:38 +0100
Subject: [PATCH 7/8] Remove the WebMCP demo teleprompter script
It was a recording aid, not documentation.
Co-Authored-By: Claude Opus 5.5
---
docs/webmcp-demo-script.md | 64 --------------------------------------
1 file changed, 64 deletions(-)
delete mode 100644 docs/webmcp-demo-script.md
diff --git a/docs/webmcp-demo-script.md b/docs/webmcp-demo-script.md
deleted file mode 100644
index 64b1af1a..00000000
--- a/docs/webmcp-demo-script.md
+++ /dev/null
@@ -1,64 +0,0 @@
-▶ One continuous teleprompter scroll. Never pause it (Cap resets to the top).
-At each GAP: stop talking, run the tool call, keep your eyes on the page.
-The blank runway keeps the scroll drifting so you land on the next line
-when you resume. Cut the dead silence in the edit, and speed or jump-cut
-anything that shows a prompt being typed or text streaming in.
-
----
-
-I'm baronunread. This is my WebMCP entry. I didn't build a new app for it. I took rdyrct, a link shortener and QR generator my team already uses, and gave it to browser agents.
-
-Nothing changed underneath. No new backend, no plugin. Each page registers its own WebMCP tools.
-
-I'm driving it from ChatGPT, in cowork mode. ChatGPT reads the page and calls the tools it finds there.
-
-We're not signed in, and we don't need to be yet. The marketing pages bring their own tools. So first, let's ask what rdyrct costs.
-
- - - - - - GAP: get_rdyrct_pricing runs on the logged-out page. Stay
- silent. ChatGPT answers with the real plans and limits. Resume when
- the answer is on screen. - - - - -
-
-No account, no scraping. The page handed ChatGPT the real plan numbers. Now let's have it make something. A QR code for the Devpost page.
-
- - - - - - GAP: create_qr_code fires on the logged-out page. Stay
- silent. A QR code comes back as an image. If it retries once, let
- it, that's fine. Resume when the code is on screen. - - - - -
-
-There it is, a real QR code as an image, still no account. And if I want to style it, I ask ChatGPT to open the generator and make it green.
-
- - - - - - GAP: ChatGPT navigates to the QR generator on its own,
- then calls generate_qr_code. Stay silent. The value and the color
- fill into the fields, the preview updates. Resume when it does. - - - - -
-
-Same tools, one page over. ChatGPT walked onto the generator, typed the value and the color into the fields, and the code redrew. Everything so far, without signing in.
-
- - - - - - GAP: sign in to rdyrct in the cloud browser now. Cut this
- whole stretch from the video. Resume once the dashboard has loaded
- and you're signed in. - - - - -
-
-Signed in now, so the app's tools come into play too. This is my own organization on production, so the click numbers you'll see are small, but they're real.
-
-Let's ask ChatGPT to shorten the Devpost page and title it WebMCP Challenge.
-
- - - - - - GAP: create_link runs. Stay silent. The Links page opens
- with the new row. Resume when it shows. - - - - -
-
-A real tracked link. ChatGPT didn't fill out a form. rdyrct gave it a create-link tool, and the app jumped to the Links page on its own.
-
-Next, let's ask it for my analytics over the last thirty days, and which links are dead.
-
- - - - - - GAP: get_analytics runs, link_health focus. Stay silent.
- The Analytics page opens, and ChatGPT reads back the no-click links.
- Resume when it does. - - - - -
-
-Total clicks, top links, countries, referrers, devices, and never an IP address, plus the links that haven't been clicked. So let's ask it to find one of those and get rid of it.
-
- - - - - - GAP: find_links searches, then delete_link removes the one
- I name. Stay silent. The Links page updates without that row. Resume
- when it's gone. - - - - -
-
-Searched by name, deleted by slug, and the short link stops redirecting.
-
-So that's rdyrct with WebMCP. Same product, same permissions, but every one of those tools is also a sentence you can say to an agent. Nine tools, registered straight from the pages, no new backend.
-
-Thanks for watching.
From b2ed89abea5a3753b501efb9af3549a3ceb1929d Mon Sep 17 00:00:00 2001
From: baron unread
Date: Mon, 26 Oct 2026 19:23:09 +0100
Subject: [PATCH 8/8] Turnstile: show the challenge in the form, above its
submit button
With a key that forces an interactive challenge, the widget sat pinned to
the bottom-right corner of the viewport, far from the form, its Italian
label clipped, while the submit button just spun.
- Every guarded form (sign-up, password reset, the landing shortener,
the UTM builder, the report form) has a TurnstileSlot directly above
its submit button, and solve() renders into it. The fixed corner stays
only as a fallback for a form with no slot.
- The idle slot is out of the flow (absolute, zero size), so it adds no
row and no gap, even while the invisible widget solves inside it.
display: contents was not enough: the widget's own wrapper became a
flex item and moved the form down by a gap for that second.
- When Cloudflare wants a click, the slot becomes a full-width row
clipped to the inputs' radius, and the widget renders at size
"flexible", or "compact" where the slot is under Turnstile's 300px
minimum (the UTM card at 390px). It follows the app's theme
(data-theme, which a stored choice can set against the OS) and the
page's language, so the label fits on one line.
- The button stays pressable while a challenge shows: a press queues the
submission, which goes ahead by itself once the box is ticked. While it
waits, the button says "Tick the box above" instead of spinning, and a
polite status line says the same to a screen reader. The 20s give-up
timer pauses while a person is expected to click.
- New e2e (turnstile-slot.pw.ts): each form has one slot, straight
before its submit control, and its height never changes from load
until 3s after the widget runs. Mutation-tested: removing a slot and
going back to display: contents both fail it.
Co-Authored-By: Claude Opus 5.5
---
src/app/components/hero-link-bar.tsx | 30 +++--
src/app/components/hero-shortener.tsx | 11 +-
src/app/components/turnstile-slot.tsx | 44 ++++++++
src/app/lib/theme.ts | 8 +-
src/app/lib/turnstile.ts | 153 ++++++++++++++++++++------
src/app/routes/auth.tsx | 41 +++++--
src/app/routes/report.tsx | 9 +-
src/app/routes/utm-builder.tsx | 44 +++++---
tests/e2e/turnstile-slot.pw.ts | 124 +++++++++++++++++++++
9 files changed, 394 insertions(+), 70 deletions(-)
create mode 100644 src/app/components/turnstile-slot.tsx
create mode 100644 tests/e2e/turnstile-slot.pw.ts
diff --git a/src/app/components/hero-link-bar.tsx b/src/app/components/hero-link-bar.tsx
index fa4b8b9f..6984f564 100644
--- a/src/app/components/hero-link-bar.tsx
+++ b/src/app/components/hero-link-bar.tsx
@@ -20,6 +20,7 @@ import { CopyButton } from "../ui/copy-button";
import { BusyContent } from "../ui/spinner";
import { useToast } from "../ui/toast";
import { copyToClipboard } from "../lib/clipboard";
+import { CHALLENGE_LABEL } from "../lib/turnstile";
import { cn } from "../ui/cn";
// A QR code is useful only once a link exists. Keeping the renderer behind
@@ -59,6 +60,7 @@ export function HeroBar({
busy,
title,
again = false,
+ waiting = false,
}: {
prefix: ReactNode;
input: InputHTMLAttributes;
@@ -69,6 +71,9 @@ export function HeroBar({
title?: string;
/** A link has been made already, so the field asks for the next one. */
again?: boolean;
+ /** A submission waits on the Turnstile challenge above the bar; `busy`
+ * is then false, since the button says so instead of spinning. */
+ waiting?: boolean;
}) {
return (
@@ -96,19 +101,30 @@ export function HeroBar({
className="h-9 rounded-lg sm:w-auto"
>
- Shorten it
-
- ↵
-
+
);
}
+/** "Shorten it" with its Enter hint, or what is left to do while a
+ * submission waits on the Turnstile challenge. */
+function ShortenLabel({ waiting }: { waiting: boolean }) {
+ if (waiting) return CHALLENGE_LABEL;
+ return (
+ <>
+ Shorten it
+
+ ↵
+
+ >
+ );
+}
+
/** The shared domain as the bar's prefix: what the slug will follow. */
export function HostPrefix({ host }: { host: string }) {
return (
diff --git a/src/app/components/hero-shortener.tsx b/src/app/components/hero-shortener.tsx
index 5e7cab19..6b988c8f 100644
--- a/src/app/components/hero-shortener.tsx
+++ b/src/app/components/hero-shortener.tsx
@@ -19,7 +19,8 @@ import { errorMessage } from "@/app/lib/error-message";
import { ArrowRight } from "@/app/ui/icons";
import { buttonClass } from "../ui/button-class";
import { useToast } from "../ui/toast";
-import { useTurnstile } from "../lib/turnstile";
+import { guardedButton, useTurnstile } from "../lib/turnstile";
+import { TurnstileSlot } from "./turnstile-slot";
import { useConfig } from "../lib/hooks";
import {
MAX_ANON_LINKS,
@@ -149,11 +150,13 @@ function useAnonShortener() {
canSubmit,
submit,
prime: turnstile.prime,
+ challenge: turnstile.challenge,
+ button: guardedButton(busy, turnstile.challenge),
};
}
export function HeroShortener() {
- const { destination, setDestination, busy, made, atCap, canSubmit, submit, prime } =
+ const { destination, setDestination, button, made, atCap, canSubmit, submit, prime, challenge } =
useAnonShortener();
// The shared domain the slug will follow. This card only exists on
// rdyrct.com, whose shared host is rdyr.cc, so that stands in until the
@@ -174,6 +177,7 @@ export function HeroShortener() {
noValidate
className={HERO_CARD}
>
+ }
input={{
@@ -183,7 +187,8 @@ export function HeroShortener() {
onChange: (e) => setDestination(e.target.value),
}}
disabled={!canSubmit}
- busy={busy}
+ busy={button.spinning}
+ waiting={button.waiting}
again={made.length > 0}
/>
diff --git a/src/app/components/turnstile-slot.tsx b/src/app/components/turnstile-slot.tsx
new file mode 100644
index 00000000..0a21c1da
--- /dev/null
+++ b/src/app/components/turnstile-slot.tsx
@@ -0,0 +1,44 @@
+import type { TurnstileChallenge } from "../lib/turnstile";
+import { cn } from "../ui/cn";
+
+/**
+ * Where Cloudflare's challenge appears, directly above a guarded form's
+ * submit button (#304).
+ *
+ * Takes no space while the widget is invisible, which is nearly always: the
+ * slot is out of the flow (absolute, zero size), so it is not a flex item
+ * and adds no row and no gap to the form, even while Cloudflare's invisible
+ * widget sits inside it solving. (`display: contents` was not enough: the
+ * widget's own wrapper then became a flex item and pushed the form down by a
+ * gap for the second the solve took.) When Cloudflare does want a click, the
+ * slot becomes a full-width row and the widget fills it, clipped to the
+ * inputs' corner radius so it reads as one of the form's fields rather than
+ * something pinned on. Line height 0 drops the few pixels of baseline space
+ * an inline iframe would otherwise leave under it.
+ */
+export function TurnstileSlot({
+ challenge,
+ className,
+}: {
+ challenge: TurnstileChallenge;
+ /** Extra classes while the challenge shows, for a parent with no gap. */
+ className?: string;
+}) {
+ return (
+ <>
+
+ {/* Absolutely positioned (sr-only), so it is not a flex item either. */}
+
+ {challenge.needsClick ? "Cloudflare needs one click to check you are human." : ""}
+
+ >
+ );
+}
diff --git a/src/app/lib/theme.ts b/src/app/lib/theme.ts
index 13ef59e5..32c46916 100644
--- a/src/app/lib/theme.ts
+++ b/src/app/lib/theme.ts
@@ -4,7 +4,9 @@ type Theme = "dark" | "light";
const listeners = new Set<() => void>();
-function current(): Theme {
+/** The theme the page is in now: the visitor's choice if they made one,
+ * else their OS's (index.html decides before paint). */
+export function currentTheme(): Theme {
return document.documentElement.dataset.theme === "dark" ? "dark" : "light";
}
@@ -23,7 +25,7 @@ function apply(next: Theme) {
}
function toggle() {
- const next: Theme = current() === "light" ? "dark" : "light";
+ const next: Theme = currentTheme() === "light" ? "dark" : "light";
// No view transition here: dark and light are near-opposite flat colors,
// so any crossfade between them (soft or instant-cut) reads as a wrong
@@ -42,7 +44,7 @@ export function useTheme(): [Theme, () => void] {
listeners.add(cb);
return () => listeners.delete(cb);
},
- current,
+ currentTheme,
(): Theme => "light",
);
return [theme, toggle];
diff --git a/src/app/lib/turnstile.ts b/src/app/lib/turnstile.ts
index b9a4b9c7..b8232204 100644
--- a/src/app/lib/turnstile.ts
+++ b/src/app/lib/turnstile.ts
@@ -2,18 +2,21 @@
* Cloudflare Turnstile on the client (#304).
*
* The widget renders `interaction-only`: invisible unless Cloudflare wants a
- * click, in which case it shows itself in the corner. Work starts when the
- * visitor first touches the form, so the token is usually ready by the time
- * they submit.
+ * click. When it does, the challenge appears in the form's own slot
+ * (`TurnstileSlot`, just above the submit button) at the form's width and in
+ * the app's theme, and `needsClick` tells the button to say so. Work starts
+ * when the visitor first touches the form, so the token is usually ready by
+ * the time they submit.
*
* A failure here never blocks the form. The token goes to the server, the
* server decides: an empty one is rejected when TURNSTILE_SECRET_KEY is set
* and ignored when it is not.
*/
-import { type RefObject, useCallback, useRef } from "react";
+import { type RefObject, useCallback, useMemo, useRef, useState } from "react";
import { type QueryClient, useQueryClient } from "@tanstack/react-query";
import { TURNSTILE_TOKEN_HEADER } from "@/shared/types";
import { configQuery, useConfig } from "./hooks";
+import { currentTheme } from "./theme";
import { retryOnTurnstileFailure } from "./turnstile-retry";
export type TurnstileScope = "signup" | "password-reset" | "anon-link" | "report";
@@ -38,14 +41,26 @@ interface TurnstileApi {
sitekey: string;
action: string;
appearance: "interaction-only";
+ size: "flexible" | "compact";
+ theme: "light" | "dark";
+ language: string;
callback: (token: string) => void;
"error-callback": () => void;
"timeout-callback": () => void;
+ "before-interactive-callback": () => void;
+ "after-interactive-callback": () => void;
},
) => string;
remove: (widgetId: string) => void;
}
+/** Where a form shows the challenge, and whether one is waiting for a click.
+ * Pass it to `TurnstileSlot` and to the form's submit button. */
+export interface TurnstileChallenge {
+ slotRef: RefObject;
+ needsClick: boolean;
+}
+
declare global {
interface Window {
turnstile?: TurnstileApi;
@@ -72,40 +87,110 @@ function loadScript(): Promise {
return loading;
}
+/** Turnstile's flexible size will not go narrower than this. */
+const FLEXIBLE_MIN_WIDTH = 300;
+
+/** Full width when the slot has room for it, else Cloudflare's compact size
+ * (150px wide), so a narrow form on a phone never has a widget poking out of
+ * it. The slot is `display: contents` until the challenge shows, so it is
+ * measured through its parent's content box. */
+function sizeFor(slot: HTMLElement | null): "flexible" | "compact" {
+ const parent = slot?.parentElement;
+ if (!parent) return "flexible";
+ const style = getComputedStyle(parent);
+ const width = parent.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
+ return width >= FLEXIBLE_MIN_WIDTH ? "flexible" : "compact";
+}
+
+/** What a guarded form's submit button says while a submission waits on
+ * Cloudflare's click, in place of its spinner: one thing is left to do. */
+export const CHALLENGE_LABEL = "Tick the box above";
+
+/**
+ * How a guarded form's submit button behaves. It stays pressable while a
+ * challenge shows: a press queues the submission, which goes ahead by itself
+ * once the box is ticked, so no press is lost. While a submission waits on
+ * that click, the button stops spinning and says what is left to do.
+ */
+export function guardedButton(busy: boolean, challenge: TurnstileChallenge) {
+ const waiting = busy && challenge.needsClick;
+ return { waiting, spinning: busy && !waiting, disabled: busy };
+}
+
+/** A host for the widget when the form has no slot: the bottom-right corner,
+ * which is far from the form, so every guarded form should have a slot. */
+function cornerHost(): HTMLElement {
+ const host = document.createElement("div");
+ host.style.cssText = "position:fixed;right:16px;bottom:16px;z-index:60";
+ document.body.appendChild(host);
+ return host;
+}
+
+interface SolveOptions {
+ siteKey: string;
+ scope: TurnstileScope;
+ /** The form's slot, or null to fall back to the corner. */
+ slot: HTMLElement | null;
+ /** Called with true when Cloudflare shows the challenge, false when done. */
+ onInteractive: (waiting: boolean) => void;
+}
+
+/** Renders the widget and resolves with its token, or "" on an error or when
+ * nothing answers in SOLVE_TIMEOUT_MS. The timer stops while a challenge is on
+ * screen: a person reading it is not a failure. */
+function renderForToken(turnstile: TurnstileApi, host: HTMLElement, opts: SolveOptions) {
+ let widgetId: string | null = null;
+ const token = new Promise((resolve) => {
+ let timer = setTimeout(() => resolve(""), SOLVE_TIMEOUT_MS);
+ const done = (value: string) => {
+ clearTimeout(timer);
+ resolve(value);
+ };
+ widgetId = turnstile.render(host, {
+ sitekey: opts.siteKey,
+ action: opts.scope,
+ appearance: "interaction-only",
+ size: sizeFor(opts.slot),
+ theme: currentTheme(),
+ // The page's language, not the browser's: everything around the widget
+ // is English, and a longer translation wraps inside its fixed height.
+ language: document.documentElement.lang || "en",
+ callback: done,
+ "error-callback": () => done(""),
+ "timeout-callback": () => done(""),
+ "before-interactive-callback": () => {
+ clearTimeout(timer);
+ opts.onInteractive(true);
+ },
+ "after-interactive-callback": () => {
+ opts.onInteractive(false);
+ timer = setTimeout(() => resolve(""), SOLVE_TIMEOUT_MS);
+ },
+ });
+ });
+ return { token, widgetId: () => widgetId };
+}
+
/** Resolves with a token, or "" if this browser could not produce one. "" is
* deliberate rather than an exception: the server decides what an empty
* token means. */
-async function solve(siteKey: string, scope: TurnstileScope): Promise {
- let container: HTMLElement | null = null;
- let widgetId: string | null = null;
+async function solve(opts: SolveOptions): Promise {
+ let corner: HTMLElement | null = null;
let turnstile: TurnstileApi | null = null;
+ let widgetId: () => string | null = () => null;
try {
turnstile = await loadScript();
- const host = document.createElement("div");
- // Empty while invisible; if Cloudflare asks for a click, it appears here.
- host.style.cssText = "position:fixed;right:16px;bottom:16px;z-index:60";
- document.body.appendChild(host);
- container = host;
- return await new Promise((resolve) => {
- const timer = setTimeout(() => resolve(""), SOLVE_TIMEOUT_MS);
- const done = (token: string) => {
- clearTimeout(timer);
- resolve(token);
- };
- widgetId = turnstile!.render(host, {
- sitekey: siteKey,
- action: scope,
- appearance: "interaction-only",
- callback: done,
- "error-callback": () => done(""),
- "timeout-callback": () => done(""),
- });
- });
+ const host = opts.slot ?? (corner = cornerHost());
+ const rendered = renderForToken(turnstile, host, opts);
+ widgetId = rendered.widgetId;
+ return await rendered.token;
} catch {
return "";
} finally {
- if (widgetId) turnstile?.remove(widgetId);
- container?.remove();
+ opts.onInteractive(false);
+ const id = widgetId();
+ if (id) turnstile?.remove(id);
+ corner?.remove();
}
}
@@ -158,13 +243,17 @@ export function useTurnstile(scope: TurnstileScope) {
const qc = useQueryClient();
const loadedSiteKey = useConfig().data?.turnstileSiteKey;
const pending = useRef(null);
+ const slotRef = useRef(null);
+ const [needsClick, setNeedsClick] = useState(false);
const startSolve = useCallback(
(siteKey: string | undefined) => {
if (!siteKey) return;
const held = pending.current;
if (held && Date.now() - held.primedAt < TOKEN_FRESH_MS) return;
- pending.current = { token: solve(siteKey, scope), primedAt: Date.now() };
+ const slot = slotRef.current;
+ const token = solve({ siteKey, scope, slot, onInteractive: setNeedsClick });
+ pending.current = { token, primedAt: Date.now() };
},
[scope],
);
@@ -186,5 +275,7 @@ export function useTurnstile(scope: TurnstileScope) {
[headers],
);
- return { prime, headers, guarded };
+ const challenge = useMemo(() => ({ slotRef, needsClick }), [needsClick]);
+
+ return { prime, headers, guarded, challenge };
}
diff --git a/src/app/routes/auth.tsx b/src/app/routes/auth.tsx
index c9d643a1..b9636f02 100644
--- a/src/app/routes/auth.tsx
+++ b/src/app/routes/auth.tsx
@@ -17,7 +17,13 @@ import {
googleSignupUrl,
} from "../lib/funnel";
import { useShake } from "../lib/use-shake";
-import { useTurnstile } from "../lib/turnstile";
+import {
+ type TurnstileChallenge,
+ CHALLENGE_LABEL,
+ guardedButton,
+ useTurnstile,
+} from "../lib/turnstile";
+import { TurnstileSlot } from "../components/turnstile-slot";
import { useCurrentUser, useConfig } from "../lib/hooks";
import { storedAnonLinks } from "../lib/anon-links";
import { readAuthHint } from "../lib/user-cache";
@@ -49,15 +55,18 @@ function ForgotView({
initialEmail,
sent,
busy,
+ challenge,
onSubmit,
onBack,
}: {
initialEmail: string;
sent: boolean;
busy: boolean;
+ challenge: TurnstileChallenge;
onSubmit: (email: string) => void;
onBack: () => void;
}) {
+ const button = guardedButton(busy, challenge);
const toast = useToast();
const { register, handleSubmit, getValues } = useForm({
resolver: valibotResolver(forgotSchema),
@@ -83,8 +92,11 @@ function ForgotView({
-