5 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 72cb9a033d feat: 2.0.2 — rate limiting for the whole site (#157)
The Worker now runs first for every request except the content-hashed
bundles under /assets/ (run_worker_first: ["/*", "!/assets/*"]) and counts
it against a per-client limit before serving it:

- SITE_LIMITER: pages and public files, 120 requests / 60 s
- API_LIMITER: every /api/* request, 60 / 60 s
- VERIFY_LIMITER: /api/turnstile/verify on top, 30 / 60 s (unchanged)

Over the limit, pages get a plain-text 429 in the four UI languages and the
API a JSON 429 (rate_limited); both carry Retry-After: 60. Clients are keyed
on their IPv4 address or the /64 of their IPv6 address, never logged. Pages
still go through env.ASSETS.fetch(), so _headers, _redirects and the SPA
fallback apply as before. A failing limiter lets requests through. Previews
get their own counters (namespace_id 4204/4206).

Docs: DEPLOYMENT, PRIVACY (wording only, nothing new collected, no
re-consent), SECURITY, CONTRIBUTING, READMEs, CLAUDE.md, ROADMAP, CHANGELOG.
Version 2.0.2 (versionCode 20002).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 05:36:02 +07:00
dependabot[bot] 6229199137 build(deps): Bump the i18n group with 2 updates
Bumps the i18n group with 2 updates: [i18next](https://github.com/i18next/i18next) and [react-i18next](https://github.com/i18next/react-i18next).


Updates `i18next` from 26.5.5 to 26.5.6
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.5.5...v26.5.6)

Updates `react-i18next` from 17.1.1 to 17.1.3
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.1.1...v17.1.3)

---
updated-dependencies:
- dependency-name: i18next
  dependency-version: 26.5.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: i18n
- dependency-name: react-i18next
  dependency-version: 17.1.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: i18n
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 13:50:09 +07:00
dependabot[bot] 9309fae1f6 build(deps-dev): Bump wrangler
Bumps the cloudflare group with 1 update: [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler).


Updates `wrangler` from 4.151.3 to 4.152.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/HEAD/packages/wrangler)

---
updated-dependencies:
- dependency-name: wrangler
  dependency-version: 4.152.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: cloudflare
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 13:41:20 +07:00
poli0981andClaude Opus 5.5 46d1e53656 fix: 2.0.1 — editors scroll again and fewer console errors (#153)
- The wrapper div @uiw/react-codemirror renders now fills its panel, so the input editor and the read-only output scroll with the wheel, touch and keyboard; the read-only output's scroll container is focusable (arrow/page keys) without becoming contenteditable.
- CSP (web and Tauri) allows 'wasm-unsafe-eval' for bson's WebAssembly helper; Permissions-Policy drops browsing-topics.
- Version 2.0.1 (Android versionCode 20001); CHANGELOG and docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 23:43:42 +07:00
poli0981andClaude Opus 5.5 db94730fa5 ci(smoke): wait for the deploy to settle and retry the production checks (#152)
Require the pushed commit three times in a row before checking production, and retry the header/route/API checks up to four times, 20 s apart. A deploy needs a short while to reach every Cloudflare edge location.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 23:22:15 +07:00
29 changed files with 518 additions and 118 deletions

No files matched your search

+40 -17
View File
@@ -28,37 +28,60 @@ jobs:
timeout-minutes: 20
permissions: {}
steps:
# A new deploy reaches Cloudflare's edge locations over a minute or so;
# until then some requests still hit the previous version. Wait until the
# commit has been served several times in a row.
- name: Wait for this commit to go live
if: github.event_name == 'push'
env:
SHA: ${{ github.sha }}
run: |
want="${SHA:0:7}"
for attempt in $(seq 1 60); do
streak=0
for attempt in $(seq 1 90); do
live=$(curl -fsS -A "$UA" --max-time 10 "$SITE/" | sed -n 's/.*<meta name="jsonprism-commit" content="\([0-9a-f]*\)".*/\1/p' | head -n 1 || true)
if [ "$live" = "$want" ]; then
echo "Production serves $live"
exit 0
streak=$((streak + 1))
if [ "$streak" -ge 3 ]; then
echo "Production serves $live"
exit 0
fi
sleep 10
continue
fi
streak=0
echo "Attempt $attempt: live=${live:-unknown}, waiting for $want"
sleep 15
sleep 10
done
echo "::error::Production did not serve $want within 15 minutes. Check Workers Builds in the Cloudflare dashboard."
exit 1
- name: Check headers, routes and API
run: |
set -euo pipefail
fail() { echo "::error::$1"; exit 1; }
headers=$(curl -fsSI -A "$UA" "$SITE/")
for expected in "content-security-policy: default-src 'self'" "strict-transport-security: max-age=" "x-content-type-options: nosniff" "x-frame-options: deny"; do
grep -qi "^$expected" <<<"$headers" || fail "Missing header: $expected"
set -uo pipefail
checks() {
local headers expected old code
headers=$(curl -fsSI -A "$UA" "$SITE/") || { echo "home page unreachable"; return 1; }
for expected in "content-security-policy: default-src 'self'" "strict-transport-security: max-age=" "x-content-type-options: nosniff" "x-frame-options: deny"; do
grep -qi "^$expected" <<<"$headers" || { echo "missing header: $expected"; return 1; }
done
[ "$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' "$SITE/about")" = 200 ] || { echo "/about is not served by the SPA fallback"; return 1; }
old=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code} %{redirect_url}' "$SITE/jsonPrism/about")
[ "$old" = "301 $SITE/about" ] || { echo "/jsonPrism/about gave '$old', expected a 301 to /about"; return 1; }
[ "$(curl -fsS -A "$UA" "$SITE/api/health")" = '{"ok":true,"service":"jsonprism"}' ] || { echo "/api/health is not healthy"; return 1; }
curl -fsS -A "$UA" "$SITE/.well-known/security.txt" | grep -q '^Contact: mailto:security@poli0981.dev' || { echo "security.txt is missing or stale"; return 1; }
code=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' -X POST -H 'Origin: https://example.com' -H 'Content-Type: application/json' --data '{"token":"x"}' "$SITE/api/turnstile/verify")
[ "$code" = 403 ] || { echo "/api/turnstile/verify answered $code to a foreign origin, expected 403"; return 1; }
}
# Retry briefly in case a request still lands on an edge location
# that hasn't picked up the deploy yet.
for attempt in 1 2 3 4; do
if problem=$(checks); then
echo "Production checks passed."
exit 0
fi
echo "Attempt $attempt: $problem"
sleep 20
done
[ "$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' "$SITE/about")" = 200 ] || fail "/about is not served by the SPA fallback"
old=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code} %{redirect_url}' "$SITE/jsonPrism/about")
[ "$old" = "301 $SITE/about" ] || fail "/jsonPrism/about gave '$old', expected a 301 to /about"
[ "$(curl -fsS -A "$UA" "$SITE/api/health")" = '{"ok":true,"service":"jsonprism"}' ] || fail "/api/health is not healthy"
curl -fsS -A "$UA" "$SITE/.well-known/security.txt" | grep -q '^Contact: mailto:security@poli0981.dev' || fail "security.txt is missing or stale"
code=$(curl -sS -A "$UA" -o /dev/null -w '%{http_code}' -X POST -H 'Origin: https://example.com' -H 'Content-Type: application/json' --data '{"token":"x"}' "$SITE/api/turnstile/verify")
[ "$code" = 403 ] || fail "/api/turnstile/verify answered $code to a foreign origin, expected 403"
echo "Production checks passed."
echo "::error::$problem"
exit 1
+18
View File
@@ -8,6 +8,24 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond".
## [2.0.2] — 2026-10-27
### Added
- **Rate limiting for the whole website, not just the human check.** The Worker now runs first for every request except the content-hashed bundles under `/assets/` (`run_worker_first: ["/*", "!/assets/*"]`) and counts it against a per-client limit before serving it: pages and public files 120 requests a minute (`SITE_LIMITER`, about 40 page loads), every `/api/*` request 60 a minute (`API_LIMITER`), and `/api/turnstile/verify` keeps its own 30 a minute on top. Over the limit, pages get a plain-text `429 Too Many Requests` in English, Vietnamese, Japanese and Chinese, and the API gets `{"ok":false,"error":"rate_limited"}`; both carry `Retry-After: 60`. Clients are keyed on their IPv4 address or the /64 network of their IPv6 address, which is never logged. Pages are still served through the assets binding, so the security headers, the old-path redirects and the SPA fallback are unchanged. If the limiter itself fails, requests go through rather than taking the site down. Preview deployments get their own counters.
### Changed
- The Privacy Policy describes the rate limit for page requests too. Nothing new is collected, so you are not asked to accept it again.
## [2.0.1] — 2026-10-22
### Fixed
- **The editor and the output panel scroll again.** The wrapper `@uiw/react-codemirror` renders around the editor had no height, so both editors grew to fit their content inside a clipped panel: long input or output could not be scrolled with the mouse, touch or keyboard. The wrapper now fills its panel. The read-only output's scroll container also takes keyboard focus, so the arrow and page keys scroll it, without making the output editable (which would open the on-screen keyboard on phones).
- **Fewer console errors.** The content security policy now allows WebAssembly (`'wasm-unsafe-eval'`, which still forbids JavaScript `eval`) on the website and in the apps, so the bson library's small 64-bit math helper no longer logs a violation (it fell back to JavaScript before). `browsing-topics` was removed from the `Permissions-Policy` header, which Brave and Firefox reported as an unknown feature. The remaining messages come from inside Cloudflare's Turnstile frame, which has its own policy.
- **Production smoke check.** After a deploy it now waits until the new version answers several times in a row and retries before failing, because a deploy takes a moment to reach every Cloudflare edge location.
## [2.0.0] — 2026-10-22
A new home, a hardened toolchain and a full audit. The web app moves to **<https://jsonprism.poli0981.dev>** on Cloudflare Workers; the old GitHub Pages address redirects there, keeping the path. Because the website now uses Cloudflare services, the Privacy Policy and Terms are at version 2.0 and **everyone is asked to accept them again** (`CONSENT_VERSION` 2).
+3 -3
View File
@@ -6,14 +6,14 @@ Guidance for Claude (and other AI assistants) working on this repository.
**JSONPrism** converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back. Conversion always runs on the user's device. It ships as:
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets + a tiny `/api/*` Worker), deployed by Cloudflare Workers Builds on every push to `main`;
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets behind a tiny Worker that rate limits requests and answers `/api/*`), deployed by Cloudflare Workers Builds on every push to `main`;
- native apps built with Tauri 2: Windows, macOS, Linux and Android (sideload APK).
GitHub Pages (`poli0981.github.io/jsonPrism`) now only redirects to the new domain.
The maintainer is **Kokone** ([@poli0981](https://github.com/poli0981)). Audience: the developer community on the open-source Discord server plus YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
**Current release**: 2.0.0. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
**Current release**: 2.0.2. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
## Stack — exact versions matter
@@ -33,7 +33,7 @@ Do not propose downgrading or "modernizing" to deprecated patterns.
## Web platform (Cloudflare)
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback; only `/api/*` runs the Worker (`run_worker_first`). Bindings: `ASSETS`, `VERIFY_LIMITER` (rate limit), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback. Every request except the hashed `/assets/*` bundles runs the Worker first (`run_worker_first`): it rate limits per client (`worker/rate-limit.ts`), then passes pages to `env.ASSETS.fetch()` (which still applies `_headers`, `_redirects` and the SPA fallback) or answers `/api/*`. Bindings: `ASSETS`, `SITE_LIMITER` / `API_LIMITER` / `VERIFY_LIMITER` (rate limits; each needs a preview twin with its own `namespace_id` under `previews`), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
- `worker/index.ts` may only have a **default export** — workerd treats every named export of the entry module as an entrypoint and refuses to start. Put shared code in other modules (`worker/verify.ts`, `worker/turnstile.ts`, `worker/http.ts`).
- Worker logs are structured (`logEvent`) and must never contain IPs, tokens or user content.
- `public/_headers` holds the CSP and security headers; `public/_redirects` maps the old `/jsonPrism/*` paths. Adding any third-party script, style, font or connection means updating the CSP there (and the Tauri CSP in `tauri.conf.json` if it applies to the apps).
+8 -4
View File
@@ -117,16 +117,20 @@ Cloudflare's runtime and is not bound by this rule.
## Cloudflare Worker (web build)
The website is served by a Cloudflare Worker configured in
[`wrangler.jsonc`](wrangler.jsonc). Only `/api/*` runs Worker code;
everything else is static files from `dist/`. The code lives in
[`wrangler.jsonc`](wrangler.jsonc). Every request except the hashed bundles
under `/assets/` runs the Worker first: it applies a per-client rate limit,
then serves pages from `dist/` through the `ASSETS` binding or answers
`/api/*`. The code lives in
[`worker/`](worker/):
| File | Role |
|---|---|
| `worker/index.ts` | Router. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
| `worker/index.ts` | Router: rate limit, then the `ASSETS` binding for pages or the API handlers. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
| `worker/rate-limit.ts` | Per-client limits (`SITE_LIMITER`, `API_LIMITER`), IPv4 / IPv6-/64 keys, 429 responses |
| `worker/env.ts` | The bindings and variables the Worker reads |
| `worker/verify.ts` | `POST /api/turnstile/verify`: same-origin check, JSON only, body size cap, rate limit |
| `worker/turnstile.ts` | Cloudflare siteverify call: timeout, one retry, hostname / action / age checks |
| `worker/http.ts` | JSON responses with strict headers, structured logs |
| `worker/http.ts` | JSON and plain-text responses with strict headers, structured logs |
Worker logs must never contain IP addresses, tokens or user content.
+8 -7
View File
@@ -35,13 +35,14 @@ Privacy questions and requests: **privacy@poli0981.dev**.
Cloudflare, Inc. serves the website and processes the data every web
request carries (IP address, user agent, requested URL, time, TLS details)
to deliver pages and protect the service against abuse. JSONPrism's own
server code handles only the human-check API (`/api/turnstile/verify`)
and a health check. For that API it records structured events — outcome,
HTTP status, the Cloudflare data centre code, duration and Turnstile error
codes — in Cloudflare Workers Logs, kept for 7 days. These events never
contain IP addresses, Turnstile tokens or anything you convert. The API is
rate limited per client by Cloudflare; the client key is not stored by
JSONPrism.
server code answers only the human-check API (`/api/turnstile/verify`) and
a health check, and counts page and API requests against a per-client rate
limit before serving them. It records structured events — outcome, HTTP
status, the Cloudflare data centre code, duration, Turnstile error codes
and refused over-limit requests — in Cloudflare Workers Logs, kept for 7
days. These events never contain IP addresses, Turnstile tokens or anything
you convert. The rate-limit counters are kept by Cloudflare, keyed on your
IP address (for IPv6, its /64 network); JSONPrism does not store the key.
### Human check (website)
+1 -1
View File
@@ -70,7 +70,7 @@ Details: [`PRIVACY.md`](PRIVACY.md).
- **i18next** for translations, **Zustand** for state, **React Router 8** for routing, **Sonner** for toasts
- **Vitest** + Testing Library for tests
- **Node.js 26** for the toolchain
- **Cloudflare Workers** hosts the web app (static assets plus a small Worker for `/api/*`)
- **Cloudflare Workers** hosts the web app (static assets behind a small Worker that rate limits requests and serves `/api/*`)
- **Tauri 2.12** for the desktop (Windows, macOS, Linux) and Android apps
## Quick start
+1 -1
View File
@@ -70,7 +70,7 @@ Chi tiết: [`PRIVACY.md`](PRIVACY.md).
- **i18next** cho dịch thuật, **Zustand** cho state, **React Router 8** cho routing, **Sonner** cho toast
- **Vitest** + Testing Library cho test
- **Node.js 26** cho toolchain
- **Cloudflare Workers** host bản web (static assets kèm một Worker nhỏ cho `/api/*`)
- **Cloudflare Workers** host bản web (static assets phía sau một Worker nhỏ giới hạn tần suất request và phục vụ `/api/*`)
- **Tauri 2.12** cho app desktop (Windows, macOS, Linux) và Android
## Bắt đầu nhanh
+3 -2
View File
@@ -50,8 +50,9 @@ website's edge configuration.
In scope:
- `src/` — the React app, converters and batch processor.
- `worker/` — the Cloudflare Worker (`/api/turnstile/verify`,
`/api/health`): origin checks, rate limiting, request validation.
- `worker/` — the Cloudflare Worker (per-client rate limits for the whole
site, `/api/turnstile/verify`, `/api/health`): rate limiting, origin
checks, request validation.
- Website edge configuration: `public/_headers` (CSP and security
headers), `public/_redirects`, `wrangler.jsonc`.
- `src-tauri/` — the Rust shell, capabilities, file-system scope and CSP.
+56 -17
View File
@@ -19,16 +19,23 @@ in [dev_env.md](dev_env.md), Tauri details in [TAURI-NOTES.md](TAURI-NOTES.md).
```
browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
├─ /api/* → worker/index.ts ──► Turnstile siteverify
└─ everything → static assets from dist/
else (_headers, _redirects, SPA fallback to index.html)
├─ /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 in
`wrangler.jsonc`.
- **Static assets**: the Vite build in `dist/`, served by Workers Static Assets
with `not_found_handling: "single-page-application"`.
- **Worker code** runs only for `/api/*` (`run_worker_first: ["/api/*"]`).
- **Worker code** runs first for every request except `/assets/*`
(`run_worker_first: ["/*", "!/assets/*"]`). It counts the request against a
per-client [rate limit](#rate-limiting), hands pages and public files to the
`ASSETS` binding — which still applies `_headers`, `_redirects` and 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 |
@@ -39,8 +46,9 @@ browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
- `worker/index.ts` may only have a default export: workerd treats every named
export of the entry module as an entrypoint. Put helpers in other modules.
- API responses set their own headers (`worker/http.ts`: `no-store`,
`nosniff`, `default-src 'none'`); assets get theirs from `public/_headers`.
- 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 from `public/_headers`.
- The Worker has its own `tsconfig.worker.json`; its runtime and binding types
come from `npm run cf:types` (`wrangler types` → gitignored
`worker-configuration.d.ts`).
@@ -78,8 +86,8 @@ 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` → `previews`
declares them again: a separate rate-limit counter (`namespace_id` 4202) and
an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
declares them again: separate rate-limit counters (`namespace_id` 4202, 4204,
4206) and an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
preview-safe twin there, or `wrangler preview` fails with "missing a
`previews` block".
- Previews get no `TURNSTILE_SECRET` (set one with
@@ -117,7 +125,7 @@ is enabled) and reports it on the pull request.
| --- | --- | --- |
| `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. |
| `VERIFY_LIMITER` | Binding | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
| `SITE_LIMITER`, `API_LIMITER`, `VERIFY_LIMITER` | Bindings | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
- Plain variables added in the dashboard are replaced by `wrangler.jsonc` `vars`
on every deploy (`keep_vars` is off); secrets are kept. The sitekey needs no
@@ -196,11 +204,11 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
| Header | Value |
| --- | --- |
| `Content-Security-Policy` | `default-src 'self'`; scripts from self, `static.cloudflareinsights.com` and `challenges.cloudflare.com`; `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). |
| `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, USB and Topics all disabled |
| `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) |
@@ -216,13 +224,41 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
## Rate limiting
- Binding `VERIFY_LIMITER` (`ratelimits` in `wrangler.jsonc`, `namespace_id`
`4201`): 30 requests per 60 s per client, keyed on `CF-Connecting-IP`. The IP
is only the key; it is never logged.
- Over the limit → 429 `rate_limited` with `Retry-After: 60`. The app treats
that as "check unavailable" and lets the user continue.
- To change it, edit `simple.limit` / `simple.period` and deploy. Keep
Three [Rate Limiting bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
(`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 carry
`Retry-After: 60` and `Cache-Control: no-store`. The app treats a 429 from
the verify endpoint as "check unavailable" and lets the user continue.
- Counters live per Cloudflare data centre and update asynchronously, so a
burst can overshoot slightly before the 429s start. If the limiter itself
fails the request goes through (`ratelimit.error` in 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 under `previews`, then deploy. Keep every
`namespace_id` unique within the Cloudflare account.
- To see it work locally, run `npm run preview:cf` and then
`for 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.
## Workers Logs
@@ -235,6 +271,9 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
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, and `ratelimit.error` with a `detail` if the
limiter binding fails.
- Never log IPs, tokens or user content (`logEvent()` in `worker/http.ts`).
Source maps are not uploaded (`upload_source_maps: false`).
+2 -1
View File
@@ -4,7 +4,7 @@ This document is the **single source of truth** for what's done, what's next, an
Update it as work lands — keep the project status honest.
**Current release: v2.0.0 (2026-10-22).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
**Current release: v2.0.2 (2026-10-27).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
---
@@ -302,6 +302,7 @@ A platform release: a new home for the web app, a human check and analytics conf
- [x] Web app served by the Cloudflare Worker `jsonprism` (Workers Static Assets, SPA fallback) at **https://jsonprism.poli0981.dev**; config in `wrangler.jsonc`, operations in [`docs/DEPLOYMENT.md`](DEPLOYMENT.md)
- [x] Cloudflare Workers Builds deploys every push to `main`; the GitHub Pages deploy workflow and `public/404.html` are gone
- [x] `/api/*` Worker in `worker/`: `POST /api/turnstile/verify` (same-origin only, 4 KB body cap, 30 requests / 60 s rate limit) and `GET /api/health`; structured Workers Logs without IPs, tokens or user content
- [x] 2.0.2: per-client rate limits for the whole site — the Worker runs first for everything except the hashed `/assets/*` bundles; pages 120 / 60 s, API 60 / 60 s, verify 30 / 60 s; IPv6 keyed on its /64; 429 with `Retry-After`
- [x] Static headers in `public/_headers` (CSP, HSTS, COOP, Permissions-Policy, immutable `/assets/*`), `/jsonPrism/*` → 301 in `public/_redirects`, `robots.txt`, `sitemap.xml`, `.well-known/security.txt`, Open Graph image
- [x] GitHub Pages keeps only a path-preserving redirect to the new domain (`pages-redirect.yml`, run by hand)
- [x] `production-smoke.yml` waits for each pushed commit to go live, then checks headers, routes, redirects and the API
+2 -1
View File
@@ -87,10 +87,11 @@ Widening the scope requires both a capability edit and a CSP review in
`app.security.csp` in `tauri.conf.json`:
```
default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
```
- 2.0.0 added `object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'`.
- 2.0.1 added `'wasm-unsafe-eval'` to `script-src`: bson compiles a tiny WebAssembly helper for 64-bit math (it falls back to JavaScript when blocked, but every WebView logged a CSP violation).
- No third-party origins. Cloudflare Turnstile and Web Analytics are web-only
and compiled out of Tauri builds (`__IS_TAURI_BUILD__`), so this CSP never
needs their hosts. The web CSP lives in `public/_headers` — see
+1 -1
View File
@@ -56,7 +56,7 @@ npm run preview:cf # wrangler dev on http://localhost:8787 (builds
- `.dev.vars` holds the Worker secret `TURNSTILE_SECRET` for local runs. It is
gitignored; never put the production secret in it.
- `npm run preview:cf` serves `dist/` the way production does (`_headers`,
`_redirects`, SPA fallback) together with the `/api/*` Worker. On localhost
`_redirects`, SPA fallback) behind the Worker (rate limits, `/api/*`). On localhost
the app uses Cloudflare's test sitekey, so the Consent Gate's Turnstile check
passes on its own.
- `npm run cf:types` — regenerates `worker-configuration.d.ts` (gitignored)
+18 -18
View File
@@ -1,12 +1,12 @@
{
"name": "jsonprism",
"version": "2.0.0",
"version": "2.0.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jsonprism",
"version": "2.0.0",
"version": "2.0.2",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/lang-json": "^6.0.2",
@@ -39,7 +39,7 @@
"clsx": "^2.1.1",
"fast-xml-parser": "^5.11.2",
"fflate": "^0.8.3",
"i18next": "^26.5.5",
"i18next": "^26.5.6",
"i18next-browser-languagedetector": "^8.2.1",
"js-yaml": "^5.5.0",
"lucide-react": "^1.61.0",
@@ -47,7 +47,7 @@
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-i18next": "^17.1.1",
"react-i18next": "^17.1.3",
"react-router": "^8.5.0",
"smol-toml": "^1.9.1",
"sonner": "^2.0.8",
@@ -83,7 +83,7 @@
"typescript-eslint": "^8.72.0",
"vite": "^8.3.5",
"vitest": "^5.0.5",
"wrangler": "^4.151.3"
"wrangler": "^4.152.0"
},
"engines": {
"node": ">=26.0.0"
@@ -6721,9 +6721,9 @@
}
},
"node_modules/i18next": {
"version": "26.5.5",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.5.5.tgz",
"integrity": "sha512-txdaNOlnZCdiTMSlEzl5hUJU8TC9R4J/RCR1G7XrDPbWT2t3mR142QPz84ZuZeXDt3yq+9zmsdPiakxYtmp3fw==",
"version": "26.5.6",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-26.5.6.tgz",
"integrity": "sha512-GFWrDwGmYhOQS3bKvjA2Ir2ob9ScEdyY1UbeQJ10jyVACGQ6XxmDYqC/lxEj/IPEJlPQYNRnYffDET6TM8mnFg==",
"funding": [
{
"type": "individual",
@@ -7401,9 +7401,9 @@
}
},
"node_modules/miniflare": {
"version": "5.20261019.1-beta",
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.1-beta.tgz",
"integrity": "sha512-1n7MN2UqZnPniyYAqNuV1YEAaja66ozKGVCc5ZTmYQhTubnoAwGLccwb+ZWYLOajuw3pOaJ70u//bZMuURlRew==",
"version": "5.20261019.2-beta",
"resolved": "https://registry.npmjs.org/miniflare/-/miniflare-5.20261019.2-beta.tgz",
"integrity": "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -7952,9 +7952,9 @@
}
},
"node_modules/react-i18next": {
"version": "17.1.1",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.1.1.tgz",
"integrity": "sha512-Q76xpzxrZNcqhB7M31Ns7isulGOlmhURqRsJOGlYgJJCyoy1pMq6tRl8KQycGNNY1vPaxbIdrogrqY9nkb+SEA==",
"version": "17.1.3",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-17.1.3.tgz",
"integrity": "sha512-XfaTqU09NPuBDuADQ8TEPbE0Goc2Gh6FHu0qvdFWfOWCdGQWRxRY2Uo5tDPtGBdzu4COXp0LQCkQIYa0IhJXlA==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.29.7",
@@ -9285,9 +9285,9 @@
}
},
"node_modules/wrangler": {
"version": "4.151.3",
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.151.3.tgz",
"integrity": "sha512-mzPQLmkAhZUV7CdiAhE+hiIAJlS9xPL6vZe1B8oQFuWxFu7nmQnvHAVjcAcabwSGkXFXH9uspzXwHOFrfbQmqQ==",
"version": "4.152.0",
"resolved": "https://registry.npmjs.org/wrangler/-/wrangler-4.152.0.tgz",
"integrity": "sha512-lmXTF1sCDEqBaEMpreGczvg/x3AIh1d/qxc4BN7utQ4jEDwdA4YG0L6kr3ev0TtVLHRb6QLySNAOAunwn+dHeA==",
"dev": true,
"license": "MIT OR Apache-2.0",
"dependencies": {
@@ -9295,7 +9295,7 @@
"@cloudflare/unenv-preset": "2.16.2",
"blake3-wasm": "2.1.5",
"esbuild": "0.28.2",
"miniflare": "5.20261019.1-beta",
"miniflare": "5.20261019.2-beta",
"path-to-regexp": "6.3.0",
"unenv": "2.0.0-rc.24",
"workerd": "1.20261019.1"
+4 -4
View File
@@ -1,7 +1,7 @@
{
"name": "jsonprism",
"private": true,
"version": "2.0.0",
"version": "2.0.2",
"type": "module",
"description": "Disperse JSON into 12 formats (six convert back) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
"author": "poli0981 <code@poli0981.dev> (https://github.com/poli0981)",
@@ -73,7 +73,7 @@
"clsx": "^2.1.1",
"fast-xml-parser": "^5.11.2",
"fflate": "^0.8.3",
"i18next": "^26.5.5",
"i18next": "^26.5.6",
"i18next-browser-languagedetector": "^8.2.1",
"js-yaml": "^5.5.0",
"lucide-react": "^1.61.0",
@@ -81,7 +81,7 @@
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-i18next": "^17.1.1",
"react-i18next": "^17.1.3",
"react-router": "^8.5.0",
"smol-toml": "^1.9.1",
"sonner": "^2.0.8",
@@ -117,6 +117,6 @@
"typescript-eslint": "^8.72.0",
"vite": "^8.3.5",
"vitest": "^5.0.5",
"wrangler": "^4.151.3"
"wrangler": "^4.152.0"
}
}
+5 -3
View File
@@ -2,18 +2,20 @@
# API responses from worker/ set their own headers.
#
# CSP notes:
# - script-src: the Cloudflare Web Analytics beacon and the Turnstile widget.
# - script-src: the Cloudflare Web Analytics beacon and the Turnstile widget;
# 'wasm-unsafe-eval' lets bson compile its small WebAssembly helper for
# 64-bit math (it allows WebAssembly only, not JavaScript eval).
# - style-src 'unsafe-inline': CodeMirror, Radix and Sonner inject styles at runtime.
# - connect-src: the analytics beacon reports to cloudflareinsights.com (or /cdn-cgi/rum).
# - frame-src: the Turnstile challenge iframe.
# - worker-src 'self': the conversion Web Worker.
/*
Content-Security-Policy: default-src 'self'; script-src 'self' https://static.cloudflareinsights.com https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://cloudflareinsights.com; frame-src https://challenges.cloudflare.com; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests
Content-Security-Policy: default-src 'self'; script-src 'self' 'wasm-unsafe-eval' https://static.cloudflareinsights.com https://challenges.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://cloudflareinsights.com; frame-src https://challenges.cloudflare.com; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=(), browsing-topics=()
Permissions-Policy: accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()
Cross-Origin-Opener-Policy: same-origin
# HTML must revalidate so a deploy is picked up; no-transform keeps zone
# features (Rocket Loader, Email Obfuscation) from rewriting pages and
+2 -2
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "adler2"
@@ -1876,7 +1876,7 @@ dependencies = [
[[package]]
name = "jsonprism"
version = "2.0.0"
version = "2.0.2"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "jsonprism"
version = "2.0.0"
version = "2.0.2"
description = "Disperse JSON into many formats."
authors = ["poli0981 <code@poli0981.dev>"]
license = "Apache-2.0"
+4 -4
View File
@@ -6,12 +6,12 @@
By installing and using JSONPrism, you agree to the terms below.\par
\par
JSONPrism is free, open-source software licensed under the Apache License 2.0:\par
https://github.com/poli0981/jsonPrism/blob/v2.0.0/LICENSE\par
https://github.com/poli0981/jsonPrism/blob/v2.0.2/LICENSE\par
\par
Your use is also governed by the following documents (version 2.0, effective 2026-10-22):\par
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.0.0/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.0.0/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.0.0/DISCLAIMER.md\par
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.0.2/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.0.2/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.0.2/DISCLAIMER.md\par
\par
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. The desktop app converts everything on your device and makes no network requests of its own.\par
\par
+2 -2
View File
@@ -26,7 +26,7 @@
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self' ipc: http://ipc.localhost; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"
}
},
"bundle": {
@@ -78,7 +78,7 @@
},
"android": {
"minSdkVersion": 31,
"versionCode": 20000
"versionCode": 20002
}
},
"plugins": {
+26 -1
View File
@@ -1,6 +1,11 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import CodeMirror, { EditorState, EditorView, type BasicSetupOptions } from '@uiw/react-codemirror';
import CodeMirror, {
EditorState,
EditorView,
ViewPlugin,
type BasicSetupOptions,
} from '@uiw/react-codemirror';
import { json } from '@codemirror/lang-json';
import { yaml } from '@codemirror/lang-yaml';
import { xml } from '@codemirror/lang-xml';
@@ -108,6 +113,21 @@ const jsonlLint = linter((view) => {
return diagnostics;
});
/**
* Read-only output isn't contenteditable (that would raise the on-screen
* keyboard on phones), so CodeMirror never moves a cursor through it and
* swallows the arrow keys. Make the scroll container itself focusable instead:
* the browser then scrolls it with the arrow and page keys.
*/
function focusableScroller(label: string | undefined) {
return ViewPlugin.define((view) => {
view.scrollDOM.tabIndex = 0;
view.scrollDOM.setAttribute('role', 'region');
if (label) view.scrollDOM.setAttribute('aria-label', label);
return {};
});
}
function languageExtensions(language: EditorLanguage, readOnly: boolean) {
switch (language) {
case 'json':
@@ -237,6 +257,7 @@ export function CodeEditor({
...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
...(readOnly ? { 'aria-readonly': 'true' } : {}),
}),
...(readOnly ? [focusableScroller(ariaLabel)] : []),
theme,
];
}, [ariaLabel, language, phrases, readOnly, resolvedTheme, wrap]);
@@ -244,6 +265,10 @@ export function CodeEditor({
return (
<div className={cn('h-full overflow-hidden', className)}>
<CodeMirror
// The wrapper div this component renders must fill the panel too, or
// `height="100%"` has nothing to resolve against: the editor grows to
// its content, gets clipped, and never scrolls.
className="h-full"
value={value}
readOnly={readOnly}
editable={!readOnly}
@@ -113,6 +113,17 @@ describe('CodeEditor — editable', () => {
});
});
describe('CodeEditor — sizing', () => {
// Regression: the wrapper @uiw/react-codemirror renders had no height, so the
// editor grew to its content inside an overflow-hidden panel and could not scroll.
it.each([false, true])('fills its panel so long documents scroll (readOnly=%s)', (readOnly) => {
const { root } = renderEditor({ value: 'x\n'.repeat(500), readOnly });
const wrapper = root.parentElement!;
expect(wrapper).toHaveClass('cm-theme-none', 'h-full');
expect(wrapper.parentElement).toHaveClass('h-full', 'overflow-hidden');
});
});
describe('CodeEditor — read-only', () => {
it('marks the content read-only and drops the editing chrome', () => {
const { content, container } = renderEditor({
@@ -123,6 +134,12 @@ describe('CodeEditor — read-only', () => {
});
expect(content).toHaveAttribute('contenteditable', 'false');
expect(content).toHaveAttribute('aria-readonly', 'true');
// Regression: not contenteditable, so the scroll container takes focus and
// the browser scrolls it with the arrow and page keys.
const scroller = container.querySelector('.cm-scroller')!;
expect(scroller).toHaveAttribute('tabindex', '0');
expect(scroller).toHaveAttribute('role', 'region');
expect(scroller).toHaveAttribute('aria-label', 'YAML output (read-only)');
expect(content).toHaveAttribute('aria-label', 'YAML output (read-only)');
expect(container.querySelector('.cm-lineNumbers')).not.toBeNull();
expect(container.querySelector('.cm-activeLine')).toBeNull();
+92 -3
View File
@@ -1,14 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { WorkerEnv } from '../env';
import worker from '../index';
import { handleVerify, VERIFIED_TTL_MS, type WorkerEnv } from '../verify';
import { handleVerify, VERIFIED_TTL_MS } from '../verify';
import { TEST_SECRET } from '../turnstile';
/** What the runtime hands the Worker: a Request carrying Cloudflare's `cf` properties. */
type IncomingRequest = Parameters<typeof worker.fetch>[0];
const ORIGIN = 'https://jsonprism.poli0981.dev';
const URL_VERIFY = `${ORIGIN}/api/turnstile/verify`;
const assetsFetch = vi.fn(async () => new Response('<!doctype html>'));
function env(overrides: Partial<WorkerEnv> = {}): WorkerEnv {
return {
ASSETS: {} as Fetcher,
ASSETS: { fetch: assetsFetch } as unknown as Fetcher,
ALLOWED_HOSTNAMES: 'jsonprism.poli0981.dev',
TURNSTILE_SECRET: 'real-secret',
...overrides,
@@ -17,7 +23,7 @@ function env(overrides: Partial<WorkerEnv> = {}): WorkerEnv {
function verifyRequest(
init: { body?: string; headers?: Record<string, string>; method?: string } = {},
) {
): IncomingRequest {
return new Request(URL_VERIFY, {
method: init.method ?? 'POST',
headers: { Origin: ORIGIN, 'Content-Type': 'application/json', ...init.headers },
@@ -27,6 +33,13 @@ function verifyRequest(
const call = (request: Request, e: WorkerEnv = env()) => handleVerify(request, e);
/** A limiter that allows the first `allowed` calls, like Cloudflare's binding once a client is over. */
function limiter(allowed = Infinity) {
let calls = 0;
const limit = vi.fn(async (_options: RateLimitOptions) => ({ success: ++calls <= allowed }));
return { limit } as RateLimit & { limit: typeof limit };
}
let siteverify: ReturnType<typeof vi.fn<typeof fetch>>;
beforeEach(() => {
@@ -151,4 +164,80 @@ describe('router', () => {
const missing = await worker.fetch(new Request(`${ORIGIN}/api/nope`), env());
expect(missing.status).toBe(404);
});
it('hands pages and public files to the ASSETS binding', async () => {
const page: IncomingRequest = new Request(`${ORIGIN}/about`);
const res = await worker.fetch(page, env());
expect(await res.text()).toBe('<!doctype html>');
expect(assetsFetch).toHaveBeenCalledWith(page);
});
});
describe('rate limiting', () => {
const fromClient = (path: string): IncomingRequest =>
new Request(`${ORIGIN}${path}`, { headers: { 'CF-Connecting-IP': '203.0.113.9' } });
it('counts pages against SITE_LIMITER and answers 429 in plain text once over', async () => {
const site = limiter(2);
const api = limiter();
const e = env({ SITE_LIMITER: site, API_LIMITER: api });
expect((await worker.fetch(fromClient('/'), e)).status).toBe(200);
expect((await worker.fetch(fromClient('/theme-init.js'), e)).status).toBe(200);
const res = await worker.fetch(fromClient('/'), e);
expect(res.status).toBe(429);
expect(res.headers.get('Retry-After')).toBe('60');
expect(res.headers.get('Cache-Control')).toBe('no-store');
expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8');
expect(await res.text()).toContain('Too many requests');
expect(assetsFetch).toHaveBeenCalledTimes(2);
expect(site.limit).toHaveBeenCalledWith({ key: '203.0.113.9' });
expect(api.limit).not.toHaveBeenCalled();
});
it('counts every /api/* request against API_LIMITER and answers JSON 429', async () => {
const site = limiter();
const api = limiter(1);
const e = env({ SITE_LIMITER: site, API_LIMITER: api });
expect((await worker.fetch(fromClient('/api/health'), e)).status).toBe(200);
for (const path of ['/api/health', '/api/nope', '/api/turnstile/verify']) {
const res = await worker.fetch(fromClient(path), e);
expect(res.status).toBe(429);
expect(res.headers.get('Retry-After')).toBe('60');
expect(await res.json()).toEqual({ ok: false, error: 'rate_limited' });
}
expect(siteverify).not.toHaveBeenCalled();
expect(site.limit).not.toHaveBeenCalled();
});
it('applies VERIFY_LIMITER on top of API_LIMITER', async () => {
const api = limiter();
const verify = limiter(0);
const res = await worker.fetch(
verifyRequest({ headers: { 'CF-Connecting-IP': '203.0.113.9' } }),
env({ API_LIMITER: api, VERIFY_LIMITER: verify }),
);
expect(res.status).toBe(429);
expect(api.limit).toHaveBeenCalledOnce();
expect(verify.limit).toHaveBeenCalledWith({ key: '203.0.113.9' });
});
it('lets requests through when the limiter itself fails', async () => {
const broken = {
limit: vi.fn().mockRejectedValue(new Error('backend down')),
} as unknown as RateLimit;
const res = await worker.fetch(fromClient('/'), env({ SITE_LIMITER: broken }));
expect(res.status).toBe(200);
});
it('never logs the client address', async () => {
const log = vi.mocked(console.log);
await worker.fetch(fromClient('/'), env({ SITE_LIMITER: limiter(0) }));
await worker.fetch(fromClient('/api/health'), env({ API_LIMITER: limiter(0) }));
const lines = log.mock.calls.map((args) => String(args[0]));
expect(lines).toHaveLength(2);
for (const line of lines) {
expect(JSON.parse(line)).toMatchObject({ event: 'ratelimit.exceeded' });
expect(line).not.toContain('203.0.113.9');
}
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { clientKey } from '../rate-limit';
const from = (ip?: string) =>
new Request('https://jsonprism.poli0981.dev/', {
headers: ip === undefined ? {} : { 'CF-Connecting-IP': ip },
});
describe('clientKey', () => {
it('keys IPv4 clients on the full address', () => {
expect(clientKey(from('203.0.113.9'))).toBe('203.0.113.9');
});
it('keys IPv6 clients on their /64 network', () => {
const a = clientKey(from('2001:db8:85a3:42:1:2:3:4'));
expect(a).toBe('2001:db8:85a3:42::/64');
expect(clientKey(from('2001:db8:85a3:42:ffff::1'))).toBe(a);
expect(clientKey(from('2001:DB8:85A3:0042::9'))).toBe(a);
expect(clientKey(from('2001:db8:85a3:43::1'))).not.toBe(a);
});
it('expands :: wherever it appears', () => {
expect(clientKey(from('2001:db8::1'))).toBe('2001:db8:0:0::/64');
expect(clientKey(from('::1'))).toBe('0:0:0:0::/64');
expect(clientKey(from('2001:db8:1:2::'))).toBe('2001:db8:1:2::/64');
});
it('keeps IPv4-mapped IPv6 addresses whole', () => {
expect(clientKey(from('::ffff:192.0.2.1'))).toBe('::ffff:192.0.2.1');
});
it('falls back to a shared key without the header', () => {
expect(clientKey(from())).toBe('unknown');
expect(clientKey(from(''))).toBe('unknown');
});
});
+14
View File
@@ -0,0 +1,14 @@
/** Bindings and vars the Worker reads (declared in wrangler.jsonc). */
export interface WorkerEnv {
ASSETS: Fetcher;
/** Comma-separated hostnames a token may have been issued on. */
ALLOWED_HOSTNAMES: string;
/** Secret set in the Cloudflare dashboard (.dev.vars locally). */
TURNSTILE_SECRET?: string | undefined;
/** Pages and public files: everything outside /api/ and the hashed /assets/ bundles. */
SITE_LIMITER?: RateLimit;
/** Every /api/* request. */
API_LIMITER?: RateLimit;
/** /api/turnstile/verify on top of API_LIMITER. */
VERIFY_LIMITER?: RateLimit;
}
+18 -4
View File
@@ -1,7 +1,6 @@
/** JSON responses for the API routes, with defensive headers (assets get theirs from public/_headers). */
/** Responses the Worker builds itself, with defensive headers (assets get theirs from public/_headers). */
const API_HEADERS: Record<string, string> = {
'Content-Type': 'application/json; charset=utf-8',
const BASE_HEADERS: Record<string, string> = {
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
@@ -16,7 +15,22 @@ export function json(
): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...API_HEADERS, ...extraHeaders },
headers: {
...BASE_HEADERS,
'Content-Type': 'application/json; charset=utf-8',
...extraHeaders,
},
});
}
export function text(
body: string,
status: number,
extraHeaders: Record<string, string> = {},
): Response {
return new Response(body, {
status,
headers: { ...BASE_HEADERS, 'Content-Type': 'text/plain; charset=utf-8', ...extraHeaders },
});
}
+14 -4
View File
@@ -1,18 +1,28 @@
/**
* JSONPrism edge Worker. Static assets (the SPA) are served by Workers Static
* Assets before this code runs; `run_worker_first: ["/api/*"]` routes only the
* API here. Conversion never happens server-side.
* JSONPrism edge Worker. `run_worker_first` sends every request here except the
* hashed bundles under /assets/, which Workers Static Assets serves directly.
* Each request is counted against a per-client rate limit first; pages and
* public files are then handed to the ASSETS binding (which still applies
* public/_headers, public/_redirects and the SPA fallback), and /api/* is
* answered here. Conversion never happens server-side.
*
* Only the default export may live in this module: workerd treats every named
* export of the entry module as an entrypoint and refuses to start otherwise.
*/
import type { WorkerEnv } from './env';
import { json } from './http';
import { handleVerify, type WorkerEnv } from './verify';
import { throttle } from './rate-limit';
import { handleVerify } from './verify';
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);
if (!url.pathname.startsWith('/api/')) {
return (await throttle(request, env.SITE_LIMITER, 'site')) ?? env.ASSETS.fetch(request);
}
const limited = await throttle(request, env.API_LIMITER, 'api');
if (limited) return limited;
switch (url.pathname) {
case '/api/turnstile/verify':
return handleVerify(request, env);
+82
View File
@@ -0,0 +1,82 @@
/**
* Per-client throttles. Every request except the hashed bundles under /assets/
* reaches the Worker (`run_worker_first` in wrangler.jsonc): pages and public
* files count against SITE_LIMITER, /api/* against API_LIMITER, and the
* human-check endpoint also against its own VERIFY_LIMITER.
*
* Cloudflare counts per data centre and updates the counters asynchronously,
* so a burst can overshoot slightly before the 429s start. The limits stop
* floods and scrapers; people never get near them.
*/
import { json, logEvent, text } from './http';
/** Every limiter uses a 60-second period, so a minute is always enough. */
const RETRY_AFTER = '60';
/** The SPA isn't loaded yet when a page is refused, so the edge answers in all four UI languages. */
const SITE_MESSAGE = [
'Too many requests. Wait a minute, then try again.',
'Quá nhiều yêu cầu. Vui lòng đợi một phút rồi thử lại.',
'リクエストが多すぎます。1 分ほど待ってから、もう一度お試しください。',
'请求过多。请等待一分钟后再试。',
].join('\n');
type LimitScope = 'site' | 'api';
/**
* The limiter key: the client's IPv4 address, or the /64 network of an IPv6
* address — one subscriber usually holds a whole /64 and could otherwise
* rotate through it. Only ever a key; never logged.
*/
export function clientKey(request: Request): string {
const ip = request.headers.get('CF-Connecting-IP')?.trim().toLowerCase();
if (!ip) return 'unknown';
// IPv4, or IPv6 with an embedded IPv4 tail (::ffff:192.0.2.1): keep it whole.
if (!ip.includes(':') || ip.includes('.')) return ip;
const [head = '', tail] = ip.split('::');
const left = head ? head.split(':') : [];
const right = tail ? tail.split(':') : [];
const groups =
tail === undefined
? left
: [
...left,
...Array<string>(Math.max(0, 8 - left.length - right.length)).fill('0'),
...right,
];
const prefix = groups.slice(0, 4).map((group) => Number.parseInt(group, 16).toString(16));
return `${prefix.join(':')}::/64`;
}
/**
* Counts the request. Returns the 429 response when the client is over the
* limit, otherwise null. Without the binding (unit tests) or when the limiter
* itself fails, the request goes through: a broken counter must not take the
* site down.
*/
export async function throttle(
request: Request,
limiter: RateLimit | undefined,
scope: LimitScope,
): Promise<Response | null> {
if (!limiter) return null;
const colo = (request.cf as { colo?: string } | undefined)?.colo;
let success: boolean;
try {
({ success } = await limiter.limit({ key: clientKey(request) }));
} catch (error) {
logEvent('ratelimit.error', {
scope,
colo,
detail: error instanceof Error ? error.message : String(error),
});
return null;
}
if (success) return null;
logEvent('ratelimit.exceeded', { scope, colo });
const headers = { 'Retry-After': RETRY_AFTER };
return scope === 'api'
? json({ ok: false, error: 'rate_limited' }, 429, headers)
: text(SITE_MESSAGE, 429, headers);
}
+4 -12
View File
@@ -7,18 +7,11 @@
* public static files, so there is no server resource it unlocks.
*/
import type { WorkerEnv } from './env';
import { json, logEvent } from './http';
import { clientKey } from './rate-limit';
import { MAX_TOKEN_LENGTH, TEST_SECRET, verifyTurnstileToken } from './turnstile';
export interface WorkerEnv {
ASSETS: Fetcher;
/** Comma-separated hostnames a token may have been issued on. */
ALLOWED_HOSTNAMES: string;
/** Secret set in the Cloudflare dashboard (.dev.vars locally). */
TURNSTILE_SECRET?: string | undefined;
VERIFY_LIMITER?: RateLimit;
}
/** Keep in sync with src/lib/turnstile.ts (TURNSTILE_ACTION). */
const TURNSTILE_ACTION = 'gate';
/** How long the browser may trust a passed check. Keep in sync with src/lib/human-check-storage.ts. */
@@ -109,9 +102,8 @@ export async function handleVerify(request: Request, env: WorkerEnv): Promise<Re
}
if (env.VERIFY_LIMITER) {
// Generous per-client throttle; shared IPs (NAT, mobile carriers) still fit.
const key = request.headers.get('CF-Connecting-IP') ?? 'unknown';
const { success } = await env.VERIFY_LIMITER.limit({ key });
// Stricter than API_LIMITER, still generous: shared IPs (NAT, mobile carriers) fit.
const { success } = await env.VERIFY_LIMITER.limit({ key: clientKey(request) });
if (!success) return finish(429, { ok: false, error: 'rate_limited' }, 'rate-limited');
}
+36 -5
View File
@@ -3,8 +3,10 @@
// Workers Builds (configured in the Cloudflare dashboard) runs
// `npx wrangler deploy` on every push to `main`; the "build" section below runs
// `npm run build` first. The Worker serves the Vite build from ./dist as static
// assets (SPA fallback to index.html) and only runs code for /api/* — today
// the Turnstile verification endpoint and a health check.
// assets (SPA fallback to index.html). Every request except the hashed bundles
// under /assets/ runs the Worker first, which rate limits it per client, then
// hands pages to the ASSETS binding or answers /api/* itself (the Turnstile
// verification endpoint and a health check).
//
// Secrets (set in the dashboard, never committed):
// TURNSTILE_SECRET — Turnstile widget secret for jsonprism.poli0981.dev
@@ -24,15 +26,34 @@
"directory": "./dist",
"binding": "ASSETS",
"not_found_handling": "single-page-application",
"run_worker_first": ["/api/*"]
// Everything except /assets/* (content-hashed, immutable, the bulk of each
// page load) goes through the Worker so it can be rate limited. Requests
// that reach the Worker are billed as Worker requests; /assets/* stays free.
"run_worker_first": ["/*", "!/assets/*"]
},
"vars": {
// Comma-separated hostnames a Turnstile token may have been issued on.
"ALLOWED_HOSTNAMES": "jsonprism.poli0981.dev"
},
// Per-client throttles (IPv4 address or IPv6 /64), counted per Cloudflare
// data centre. Over the limit → 429 with Retry-After: 60. namespace_id must
// be unique within the account; previews use the even twins below.
"ratelimits": [
{
// Per-IP throttle for /api/turnstile/verify.
// Pages and public files (index.html, theme-init.js, favicon…): about
// three per page load, so 40 page loads a minute per client.
"name": "SITE_LIMITER",
"namespace_id": "4205",
"simple": { "limit": 120, "period": 60 }
},
{
// Every /api/* request.
"name": "API_LIMITER",
"namespace_id": "4203",
"simple": { "limit": 60, "period": 60 }
},
{
// /api/turnstile/verify, on top of API_LIMITER.
"name": "VERIFY_LIMITER",
"namespace_id": "4201",
"simple": { "limit": 30, "period": 60 }
@@ -40,7 +61,7 @@
],
// Workers Builds runs `npx wrangler preview` for non-production branches.
// Previews inherit no vars or bindings, so they are declared again here:
// a separate rate-limit counter, and no hostnames for the human check —
// separate rate-limit counters, and no hostnames for the human check —
// previews get no TURNSTILE_SECRET either, so the check reports
// "unavailable" and lets testers continue. Web Analytics only loads on the
// production hostname.
@@ -49,6 +70,16 @@
"ALLOWED_HOSTNAMES": ""
},
"ratelimits": [
{
"name": "SITE_LIMITER",
"namespace_id": "4206",
"simple": { "limit": 120, "period": 60 }
},
{
"name": "API_LIMITER",
"namespace_id": "4204",
"simple": { "limit": 60, "period": 60 }
},
{
"name": "VERIFY_LIMITER",
"namespace_id": "4202",