Cloudflare's Rate Limiting binding checks a locally cached count per edge machine and syncs it in the background. On production one keep-alive connection hits the limits almost exactly (120 pages, then 429s), but 300 requests on fresh parallel connections in 13 s all passed. Say so in DEPLOYMENT.md and the rate-limit.ts header instead of "overshoot slightly", and document a one-connection curl test for production. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
22 KiB
Deployment
Maintainer guide for the web app at https://jsonprism.poli0981.dev and for the desktop / Android releases. Contributors don't need any of this: local setup is in dev_env.md, Tauri details in TAURI-NOTES.md.
Quick reference
| Task | How |
|---|---|
| Deploy the web app | Merge or push to main. Cloudflare Workers Builds deploys it. |
| Check a deploy | GitHub Actions → Production smoke (runs on every push to main). |
| Roll back the web app | Dashboard → jsonprism Worker → Deployments, or npx wrangler rollback. |
| Preview locally | npm run preview:cf → http://localhost:8787 |
| Rotate the Turnstile secret | Rotate it on the widget, then update TURNSTILE_SECRET on the Worker. |
| Ship desktop + Android builds | Bump the versions, push a vX.Y.Z tag, publish the draft release. |
Architecture
browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
├─ /assets/* → static assets from dist/ (hashed bundles, no Worker)
└─ everything → worker/index.ts: per-client rate limit, then
else ├─ /api/* → answered here ──► Turnstile siteverify
└─ pages → ASSETS binding: dist/ with _headers,
_redirects, SPA fallback to index.html
-
One Cloudflare Worker,
jsonprism(Workers Paid plan), configured inwrangler.jsonc. -
Static assets: the Vite build in
dist/, served by Workers Static Assets withnot_found_handling: "single-page-application". -
Worker code runs first for every request except
/assets/*(run_worker_first: ["/*", "!/assets/*"]). It counts the request against a per-client rate limit, hands pages and public files to theASSETSbinding — which still applies_headers,_redirectsand the SPA fallback — and answers/api/*itself./assets/*holds the content-hashed bundles, most of each page load, and stays on the Worker-free path. Conversion never happens on the server.Route Code Response POST /api/turnstile/verifyworker/verify.ts,worker/turnstile.tsVerifies a Turnstile token — see Turnstile. GET /api/healthworker/index.ts{"ok":true,"service":"jsonprism"}any other /api/*worker/index.tsJSON 404 -
worker/index.tsmay only have a default export: workerd treats every named export of the entry module as an entrypoint. Put helpers in other modules. -
Responses the Worker builds itself (API answers, 429s) set their own headers (
worker/http.ts:no-store,nosniff,default-src 'none'); pages and assets get theirs frompublic/_headers. -
The Worker has its own
tsconfig.worker.json; its runtime and binding types come fromnpm run cf:types(wrangler types→ gitignoredworker-configuration.d.ts). -
compatibility_dateis pinned inwrangler.jsonc; move it deliberately and test withnpm run preview:cf.
Workers Builds (automatic deploys)
Configured in the Cloudflare dashboard (the jsonprism Worker →
Settings → Build), not in the repo:
| Setting | Value |
|---|---|
| Repository | poli0981/jsonPrism |
| Production branch | main |
| Build command | npm run build (may also be empty) |
| Deploy command | npx wrangler deploy |
| Non-production branch deploy command | npx wrangler preview |
| Root directory | repository root |
| Node.js | 26, from .nvmrc or the NODE_VERSION build variable |
wrangler.jsonc→build.commandrunsnpm run buildbefore everywrangler deploy,previewanddev, so a deploy works even with no build command in the dashboard (setting one only builds twice).- Workers Builds installs dependencies with
npm clean-installusing its own npm (10.9.2 at the time of writing). The lockfile must stay installable with that npm: a peer-dependency conflict fails the build at the install step (this keptmainundeployable before 2.0.0).
Previews (pull requests and other branches)
Non-production branches run npx wrangler preview, which publishes a
Worker Preview named
after the branch (<branch>-jsonprism.<subdomain>.workers.dev when workers.dev
is enabled) and reports it on the pull request.
-
Previews inherit no production vars or bindings.
wrangler.jsonc→previewsdeclares them again: separate rate-limit counters (namespace_id4202, 4204, 4206) and an emptyALLOWED_HOSTNAMES. Any binding added at the top level needs a preview-safe twin there, orwrangler previewfails with "missing apreviewsblock". -
Previews get no
TURNSTILE_SECRET(set one withnpx wrangler preview base-config secret putonly if you need the check on previews), and the production sitekey doesn't run on preview hostnames, so the human check reports "unavailable" and testers continue past it. Web Analytics never loads there. -
Every push to
mainbuilds and deploys. No GitHub Action deploys the web app, and GitHub holds no Cloudflare credentials. -
The build stamps the short commit (
WORKERS_CI_COMMIT_SHA) into<meta name="jsonprism-commit">and the header's version chip; the smoke workflow uses it to recognise the new deploy. -
A failed build leaves the previous version live. Build logs exist only in the dashboard (the Worker's build history).
-
Changes to
wrangler.jsonc(route, vars, bindings) apply on the next deploy. CI'snpm run cf:check(wrangler deploy --dry-run) catches config and bundling errors before merge.
Custom domain
routes: [{ "pattern": "jsonprism.poli0981.dev", "custom_domain": true }]: Cloudflare manages the DNS record and certificate for the hostname. Thepoli0981.devzone is on the same account.workers_dev: false— there is no*.workers.devURL.- Changing the hostname touches more than the route. Search the repo for
jsonprism.poli0981.dev(wrangler.jsoncroute andALLOWED_HOSTNAMES,src/lib/analytics.ts,src/lib/links.ts,index.html,public/,.github/pages-redirect/, the workflows, the legal docs), then update the Turnstile widget's hostnames and the Web Analytics site in the dashboard.
Secrets and variables
| Name | Kind | Where |
|---|---|---|
TURNSTILE_SECRET |
Secret | Worker → Settings → Variables and Secrets, or npx wrangler secret put TURNSTILE_SECRET. Never in the repo. |
ALLOWED_HOSTNAMES |
Variable | wrangler.jsonc → vars: comma-separated hostnames a Turnstile token may be issued on. |
SITE_LIMITER, API_LIMITER, VERIFY_LIMITER |
Bindings | wrangler.jsonc → ratelimits — see Rate limiting. |
- Plain variables added in the dashboard are replaced by
wrangler.jsoncvarson every deploy (keep_varsis off); secrets are kept. The sitekey needs no Worker variable — it is compiled into the frontend. - Without
TURNSTILE_SECRET,/api/turnstile/verifyanswers 503 and Workers Logs recordoutcome: "misconfigured"; a wrong secret also gives 503 (detail: "misconfigured-secret"). Users can still continue past the check, so nothing looks broken — watch the logs after changing it. - Locally,
.dev.vars(copied from.dev.vars.example) holds Cloudflare's always-pass test secret. With it the Worker also accepts loopback and plainhttporigins, becausewrangler devrewrites the request URL andOriginto the route host. That secret proves nothing, so nothing is lost.
Turnstile
- Widget: Cloudflare dashboard → Turnstile → the JSONPrism widget. The
sitekey
0x4AAAAAAFgqIzSPBs9hZJnXis public by design and lives insrc/lib/turnstile.ts; its secret isTURNSTILE_SECRET. - Hostname management: the widget's hostname list must contain
jsonprism.poli0981.dev— keep it in step withALLOWED_HOSTNAMES. Localhost doesn't need to be listed: onlocalhost/127.0.0.1the app uses Cloudflare's test sitekey instead. - What the Worker checks: an HTTPS
Originfrom an allowed hostname,Content-Type: application/json, a body of at most 4 KB, the rate limit, then Cloudflare siteverify (8 s timeout, one retry with the same idempotency key; the visitor IP is not sent). Tokens are rejected when their hostname is not allowed, their action is notgate, or they are older than 300 s. - Responses: 200 verified (with
verifiedUntil, 7 days ahead) · 400 bad JSON or token · 403 foreign origin or rejected token · 405 not POST · 413 body too large · 415 not JSON · 429 rate limited · 503 secret missing or Cloudflare unreachable. - Client behaviour: a pass is remembered for 7 days (
jsonprism.humanCheckin localStorage). 400/403 keep the Consent Gate closed; anything else (offline, blocked script, 429, 5xx, timeout) lets the user continue after a warning, because conversion never needs the network. - Rotating the secret: rotate it on the widget, then update
TURNSTILE_SECRETon the Worker straight away.
Web Analytics
- Cloudflare dashboard → Web Analytics → site
jsonprism.poli0981.dev. Tokenf1f718464e5a417997c84170ddbec2b6(public, insrc/lib/analytics.ts). - Manual beacon: the app adds
beacon.min.jsitself, and only when all of these hold — production hostname, Consent Gate accepted, "Anonymous usage analytics" on in the Appearance menu (on by default, off by default when the browser sends Global Privacy Control). Never in desktop or Android builds, local previews or dev. - Keep automatic injection OFF in the site's Web Analytics settings. Automatic setup adds the beacon to every page before consent and ignores the user's setting.
- The CSP already allows
static.cloudflareinsights.com(script) andcloudflareinsights.com(reports).
Zone settings to keep off
These zone features rewrite HTML or inject scripts the app doesn't expect; with
the strict CSP they break pages or fill the console with violations. Keep them
off for poli0981.dev (or at least for this hostname):
| Setting | Why |
|---|---|
| Rocket Loader | Rewrites the app's <script> tags and runs them through its own loader. |
| Email Address Obfuscation | Rewrites email addresses and injects a decoder script. |
| Web Analytics automatic injection | Loads the beacon without consent; the app loads it itself. |
HTML is also served with Cache-Control: no-cache, no-transform
(public/_headers) so Cloudflare shouldn't rewrite it, but don't rely on that
alone. Recheck these settings after any zone-wide change.
Static headers and redirects
Vite copies public/ into dist/; Workers Static Assets applies _headers and
_redirects to asset responses.
public/_headers:
| Header | Value |
|---|---|
Content-Security-Policy |
default-src 'self'; scripts from self, static.cloudflareinsights.com and challenges.cloudflare.com, plus 'wasm-unsafe-eval' (WebAssembly only, for bson's 64-bit math helper); connect-src self + cloudflareinsights.com; frame-src Turnstile; worker-src 'self'; object-src 'none', base-uri 'self', form-action 'self', frame-ancestors 'none', upgrade-insecure-requests. style-src keeps 'unsafe-inline' (CodeMirror, Radix and Sonner inject styles at runtime). |
Strict-Transport-Security |
max-age=31536000, deliberately without includeSubDomains |
X-Content-Type-Options, X-Frame-Options |
nosniff, DENY |
Referrer-Policy |
strict-origin-when-cross-origin |
Permissions-Policy |
camera, microphone, geolocation, motion sensors, payment and USB disabled (browsing-topics was dropped in 2.0.1: Brave and Firefox log it as an unknown feature, and the site runs no ad code) |
Cross-Origin-Opener-Policy |
same-origin |
Cache-Control |
HTML no-cache, no-transform; /assets/* public, max-age=31536000, immutable (hashed file names) |
- A new third-party script, frame or connection needs a CSP change here; check
the console in
npm run preview:cfafterwards. The desktop CSP is separate (tauri.conf.json) and stays free of third-party hosts. public/_redirects:/jsonPrismand/jsonPrism/*→ 301 to the same path without the old GitHub Pages prefix.- Also in
public/:robots.txt,sitemap.xml(updatelastmodwhen pages change),.well-known/security.txt(expires 2027-10-01 — renew it before then),og-image.png, andtheme-init.js(applies the theme before first paint without an inline script).
Rate limiting
Three Rate Limiting bindings
(ratelimits in wrangler.jsonc), applied in worker/rate-limit.ts:
| Binding | Counts | Limit | namespace_id (production / preview) |
|---|---|---|---|
SITE_LIMITER |
pages and public files: everything outside /api/ and /assets/ |
120 requests / 60 s | 4205 / 4206 |
API_LIMITER |
every /api/* request |
60 requests / 60 s | 4203 / 4204 |
VERIFY_LIMITER |
/api/turnstile/verify, on top of API_LIMITER |
30 requests / 60 s | 4201 / 4202 |
- The key is the client's IPv4 address, or the /64 network of an IPv6 address
(one subscriber usually holds a whole /64), from
CF-Connecting-IP. It is only the key; it is never logged. - A page load makes about three counted requests (
index.html,theme-init.js,favicon.svg); the hashed bundles under/assets/are not counted. 120 per minute is about 40 page loads a minute from one address. - Over the limit: pages get a plain-text 429 in the four UI languages, the API
gets a JSON 429
{"ok":false,"error":"rate_limited"}; both carryRetry-After: 60andCache-Control: no-store. The app treats a 429 from the verify endpoint as "check unavailable" and lets the user continue. - The limits are approximate. Counts are kept per Cloudflare data centre, and each edge machine checks a locally cached count that syncs in the background. Measured on production (2026-10-27): on one keep-alive connection they hold almost exactly (120 pages, then 429s), but 300 requests on fresh parallel connections in 13 s all passed, because they spread over many machines before the counts caught up. They throttle browsers, crawlers and simple scripts; a strict cap would need a Durable Object or a WAF rule (below).
- If the limiter itself fails the request goes through (
ratelimit.errorin the logs): a broken counter must not take the site down. - Every request that reaches the Worker is billed as a Worker request,
refused ones included. The limits keep floods off the API and slow scrapers;
volumetric attacks are Cloudflare's DDoS protection's job, in front of the
Worker. For a zone-level limit that also covers
/assets/*and runs before the Worker, add a WAF rate limiting rule for the hostname in the dashboard (Security → WAF → Rate limiting rules). - To change a limit, edit
simple.limit/simple.period(10 or 60 s) for production and its twin underpreviews, then deploy. Keep everynamespace_idunique within the Cloudflare account. - To see it work locally, run
npm run preview:cfand thenfor i in $(seq 70); do curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/api/health; done | sort | uniq -c— 60 × 200, then 429s for the rest of the minute. Against production, send the burst over one connection so it reaches one machine, e.g.curl -s -w '%{http_code}\n' $(printf -- '-o /dev/null https://jsonprism.poli0981.dev/api/health %.0s' $(seq 100)) | sort | uniq -c(this throttles your own address for a minute).
Workers Logs
observability.enabled: true,head_sampling_rate: 1(every request). Read them in the dashboard (the Worker's logs / observability view) or live withnpx wrangler tail.- The verify endpoint writes one structured line per request:
{"event":"turnstile.verify","outcome":…,"status":…,"colo":…,"ms":…}, pluscodesfor rejections anddetailwhen Cloudflare was unavailable. Outcomes:verified,rejected,bad-origin,bad-method,bad-content-type,too-large,rate-limited,bad-json,bad-token,misconfigured,unavailable. - Rate limiting writes
{"event":"ratelimit.exceeded","scope":"site"|"api","colo":…}for each refused request, andratelimit.errorwith adetailif the limiter binding fails. - Never log IPs, tokens or user content (
logEvent()inworker/http.ts). Source maps are not uploaded (upload_source_maps: false).
Local preview
cp .dev.vars.example .dev.vars # once
npm run preview:cf # wrangler dev (builds first) → http://localhost:8787
- Serves
dist/with_headers,_redirectsand the SPA fallback, plus the Worker — the closest thing to production. Turnstile uses the test sitekey and passes on its own; Web Analytics never loads (wrong hostname). npm run cf:checkis CI's deploy dry run;npm run cf:typesregenerates the Worker types after binding changes.
Production smoke
.github/workflows/production-smoke.yml runs on every push to main and on
demand:
- Waits up to 15 minutes for https://jsonprism.poli0981.dev/ to serve
<meta name="jsonprism-commit">with the pushed commit (skipped on manual runs). - Checks the CSP, HSTS,
nosniffandX-Frame-Optionsheaders;/about→ 200 (SPA fallback);/jsonPrism/about→ 301 to/about;/api/health; thesecurity.txtcontact; and that/api/turnstile/verifyanswers 403 to a foreignOrigin.
Failures reach Discord through notify-ci-failure.yml. When the wait step times
out, check the build in the Cloudflare dashboard first. Run the workflow by hand
after a rollback or a dashboard change.
Rollback
- Dashboard: the
jsonprismWorker → Deployments → the last good version → Rollback. - CLI:
npx wrangler deployments list, thennpx wrangler rollback [version-id] -m "reason"(without an ID it goes back to the previous version). Needsnpx wrangler loginwith access to the account. - A rollback doesn't touch
main: revert the bad commit too, or the next push deploys it again. Then run Production smoke by hand.
GitHub Pages redirect
- https://poli0981.github.io/jsonPrism/ serves only
.github/pages-redirect/index.htmland404.html(identical): a script that drops the/jsonPrismprefix and keeps the rest of the path, the query and the hash; a 3-second meta refresh to the home page when JavaScript is off;noindex. - Deploy it by hand — Actions → Pages redirect → Run workflow — and only
after changing
.github/pages-redirect/. Repository Settings → Pages → Source must stay GitHub Actions. - Keep it online: old links in YouTube descriptions, Discord and READMEs point there.
SonarQube Cloud
- Organization
poli0981, project keypoli0981_jsonPrism, settings insonar-project.properties. - CI-based analysis: job
sonarinci.ymlruns afterwebwith theSONAR_TOKENrepository secret and the coverage artifact (coverage/lcov.info). - Automatic Analysis must stay OFF (SonarQube Cloud → project → Administration → Analysis Method); with it on, the CI scan fails.
- Without
SONAR_TOKEN(Dependabot and fork PRs) the job skips instead of failing. The quality gate is reported, not enforced (sonar.qualitygate.wait=false). - CodeQL runs through GitHub's default setup (no workflow file).
Releases (desktop + Android)
The web app ships continuously from main; tags are for the desktop and
Android builds.
-
Bump the version on
main:npm version X.Y.Z --no-git-tag-version— updatespackage.jsonandpackage-lock.json;tauri.conf.jsonreads its version frompackage.json.versioninsrc-tauri/Cargo.toml, then refreshCargo.lock(e.g.cargo checkinsrc-tauri/) — CI runs clippy with--locked.bundle.android.versionCodeinsrc-tauri/tauri.conf.json:MAJOR*10000 + MINOR*100 + PATCH(2.0.0 → 20000).CHANGELOG.md.
-
Tag the merged commit (signed, like earlier tags) and push the tag:
git tag -s vX.Y.Z -m "JSONPrism vX.Y.Z" git push origin vX.Y.Z -
release.ymlchecks tag =package.json=Cargo.toml, runs the tests, creates one draft release, builds Windows (.msi, NSIS.exe), macOS universal (.dmg,.app.tar.gz), Linux (.deb,.rpm,.AppImage) and the signed Android APK (JSONPrism_<version>_android-universal.apk), then addsSHA256SUMS.txtand build-provenance attestations. Details in TAURI-NOTES.md. -
Review the draft (every asset present, notes taken from the changelog), then Publish. Publishing triggers
announce-release.yml(Discord) andannounce-discussion.yml(Discussions → Announcements). -
Rebuild a tag: Actions → Release Tauri bundles → Run workflow with the tag. It reuses the draft and refuses once the release is published.
The bundles are not code-signed yet, so Windows SmartScreen and macOS Gatekeeper warn on first launch.
Repository secrets
| Secret | Used by |
|---|---|
SONAR_TOKEN |
ci.yml (job sonar) |
ANDROID_KEYSTORE_BASE64, ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_PASSWORD, ANDROID_KEY_ALIAS |
release.yml (job android) — see TAURI-NOTES.md |
DISCORD_RELEASES_WEBHOOK, DISCORD_REPO_WEBHOOK, DISCORD_PING_ROLE_ID |
announce-release.yml |
DISCORD_CI_WEBHOOK |
notify-ci-failure.yml (CI and Production smoke failures) |
DISCORD_RELEASE_PIPELINE_WEBHOOK |
notify-release-pipeline.yml |
The Discord workflows call reusable workflows from poli0981/.github, pinned
to a commit, and receive only these secrets (no secrets: inherit).