From 846e5ec17d0b23759404dd5b49a39f36132d31bc Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:34:15 +0700 Subject: [PATCH] Site-wide rate limit: 429 for every request the Worker sees (#106) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(security): site-wide rate limit for every request the Worker sees Only the /api groups were rate-limited; pages, /media, /ext-img and the search index had no limit at all (a 200-request burst against production answered 200 every time). A new RL_SITE binding (100 requests per 10 s per client, IPv6 per /64) is checked by the Worker entry right after the IP denylist. Over it: the 429 page, no-store, Retry-After: 10, its countdown rewritten to 10 s. The admin host is exempt (behind Access, RL_ADMIN per account). A throwing limiter fails open without skipping the Turnstile gate. - tests: worker spam/keys/exemptions/fail-open; Retry-After constants are checked against the periods in wrangler.jsonc - smoke: a fourth phase spams the built Worker until the limit answers - scripts/probe-ratelimit.mjs: tell the Worker's 429 from the WAF's 1015 - docs 06/07/02/09/00: three layers (WAF → RL_SITE → /api groups) and the Free plan's real WAF limits; CHANGELOG 2.1.0 Co-Authored-By: Claude Opus 5.5 * chore(sonar): project version 2.1.0 for the release Co-Authored-By: Claude Opus 5.5 * fix(worker): stay a 429 if the rate-limit page can't be built Review follow-ups on the site-wide limit: - If fetching or rewriting the 429 page threw, the error reached the edge fail-open path, which hands the request to the Astro app and skips the Turnstile gate. It now answers a plain-text 429 (no-store, Retry-After). - Drop Last-Modified and Content-Length with the ETag, as the gate does: the countdown rewrite only kept the length by luck ("60" vs "10"). - Docs: the WAF rule can't filter by host on Free, so it counts admin.* too; 09 lists the worker entry as a 429 source and the probe checks; CHANGELOG says what was unlimited before. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 23 +++- README.md | 1 + package.json | 1 + poli0981.dev-docs/00_INDEX.md | 2 +- poli0981.dev-docs/02_ARCHITECTURE.md | 5 +- poli0981.dev-docs/06_SECURITY.md | 9 +- poli0981.dev-docs/07_CLOUDFLARE_SETUP.md | 23 ++-- poli0981.dev-docs/09_ERROR_PAGES_OFFLINE.md | 9 +- scripts/probe-ratelimit.mjs | 53 +++++++++ scripts/smoke-worker.mjs | 22 +++- sonar-project.properties | 2 +- src/lib/ratelimit.ts | 4 + src/pages/429.astro | 3 +- src/worker.ts | 58 +++++++++- tests/lib.test.ts | 19 +++- tests/support/fakes.ts | 42 ++++---- tests/worker.test.ts | 113 ++++++++++++++++++++ wrangler.jsonc | 8 +- 18 files changed, 355 insertions(+), 42 deletions(-) create mode 100644 scripts/probe-ratelimit.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 641bbfe..0d10282 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ and are not listed here. ## [Unreleased] +## [2.1.0] — 2026-10-27 + +### Security + +- **Site-wide rate limit.** Every request that reaches the Worker — pages, `/media`, `/ext-img`, + the search index and the API — now spends one budget per client: 100 requests per 10 seconds + (IPv6 counted per /64), a new `RL_SITE` binding in `wrangler.jsonc`. Over it, visitors get the + site's 429 page with `Retry-After: 10` and a 10-second countdown; the stricter per-endpoint + API limits still apply underneath. Before, only the API groups were limited — pages, images, + the search index and the widgets endpoint were not. The admin host is exempt (Cloudflare Access + stands in front of it), and a failing limiter lets requests through without skipping the + Turnstile gate. +- Setup docs describe the zone WAF rate-limiting rule as the outer layer above it, with the Free + plan's real limits (path and verified-bot fields, 10-second periods and blocks). + +### Added + +- `npm run probe:ratelimit` spams a live URL and tells the Worker's 429s apart from the WAF's. + The CI smoke test now spams the built Worker until the site-wide limit answers. + ### Changed - Faster first paint on phones: every page carries its CSS inline (about 9 KB brotli) instead of @@ -109,6 +129,7 @@ The public launch is tagged `v1-launch`; the 1.x changes after it were not tagge - **2026-10** — Custom Worker entry in front of every page; Workers Rate Limiting; Web Analytics; topic email aliases; R2 media; the Turnstile gate; the admin at `admin.poli0981.dev`. -[Unreleased]: https://github.com/poli0981/poli0981-dev/compare/v2.0.0...HEAD +[Unreleased]: https://github.com/poli0981/poli0981-dev/compare/v2.1.0...HEAD +[2.1.0]: https://github.com/poli0981/poli0981-dev/compare/v2.0.0...v2.1.0 [2.0.0]: https://github.com/poli0981/poli0981-dev/releases/tag/v2.0.0 [1.x]: https://github.com/poli0981/poli0981-dev/releases/tag/v1-launch diff --git a/README.md b/README.md index c46676b..7465cd8 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.d | `npm run lint` · `npm run format:check` · `npm run knip` | ESLint · Prettier · unused files/exports | | `npm test` · `npm run test:coverage` | `node:test` suites; coverage writes `coverage/lcov.info` (80% line floor) | | `npm run smoke` | Runs the built Worker with `wrangler dev` and probes pages, headers, the gate and the denylist | +| `npm run probe:ratelimit -- [url] [requests] [parallel]` | Spams a live URL and counts 429s from the Worker's site-wide limit vs. the WAF rule | | `npm run new:post` | Scaffold a post or story from `docs/templates/` | | `npm run check-exif` · `npm run strip-exif` | Refuse / remove GPS and camera metadata in images | | `npm run gen-notices` | Regenerate `THIRD-PARTY-NOTICES.md` (CI checks it) | diff --git a/package.json b/package.json index 68982ae..4f86994 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "build": "astro build && node scripts/gen-og.mjs && pagefind --site dist/client && node scripts/check-csp-hashes.mjs", "check-csp": "node scripts/check-csp-hashes.mjs", "smoke": "node scripts/smoke-worker.mjs", + "probe:ratelimit": "node scripts/probe-ratelimit.mjs", "test": "node --import ./tests/support/register.mjs --test \"tests/**/*.test.ts\"", "pretest:coverage": "node -e \"require('node:fs').mkdirSync('coverage', { recursive: true })\"", "test:coverage": "node --import ./tests/support/register.mjs --test --experimental-test-coverage --test-coverage-include=\"src/**/*.ts\" --test-coverage-include=\"workers/widgets/src/**/*.ts\" --test-coverage-exclude=\"**/*.d.ts\" --test-coverage-exclude=\"src/lib/easter.ts\" --test-coverage-exclude=\"src/content.config.ts\" --test-coverage-lines=80 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info \"tests/**/*.test.ts\"", diff --git a/poli0981.dev-docs/00_INDEX.md b/poli0981.dev-docs/00_INDEX.md index 1dc4bd8..9a48738 100644 --- a/poli0981.dev-docs/00_INDEX.md +++ b/poli0981.dev-docs/00_INDEX.md @@ -46,7 +46,7 @@ | D9 | API ngoài | Không weather/map; widget YouTube + Steam + GitHub qua cron worker | | D11 | Email | Google Workspace (MX Google), một hộp thư + alias theo chủ đề (`07` §11). Không Cloudflare Email Routing | | D12 | Chống bot | **Cổng Turnstile** trước mọi trang, vé 48 giờ (`06` §3b); bot đã xác thực đi thẳng nhờ Transform Rule `x-verified-bot` | -| D13 | Rate limit | Workers Rate Limiting bindings theo nhóm `/api` (`06` §2) thay bộ đếm KV | +| D13 | Rate limit | WAF rule (edge) → Workers Rate Limiting: RL_SITE toàn site 100/10s → bindings theo nhóm `/api` (`06` §2, `07` §6) thay bộ đếm KV | | D14 | Analytics | Cloudflare Web Analytics, **snippet thủ công** chỉ ở bản build production (`07` §12) | | D15 | Admin | `admin.poli0981.dev` sau Cloudflare Access + Worker tự kiểm JWT (≤ 24 giờ, email phải có trong `ADMIN_EMAILS` — thiếu là từ chối); token GitHub chỉ ghi repo content; ảnh → Images binding → R2; mọi thao tác ghi audit log (`06` §9) | | D10 | Data services | **KV** (cache widget + ảnh widget mirror cho `/ext-img`, denylist một khoá, audit log admin) + **R2** `poli0981-media` cho ảnh upload qua admin (từ 10/2026; AVIF/WebP sinh một lần lúc upload, phục vụ qua `/media`, cache 1 năm). Không D1. Ảnh build-time cũ vẫn ở `src/assets/` | diff --git a/poli0981.dev-docs/02_ARCHITECTURE.md b/poli0981.dev-docs/02_ARCHITECTURE.md index 708ad68..2de9c89 100644 --- a/poli0981.dev-docs/02_ARCHITECTURE.md +++ b/poli0981.dev-docs/02_ARCHITECTURE.md @@ -11,6 +11,7 @@ Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Trans src/worker.ts — entry của Worker (assets.run_worker_first: mọi trang đều qua đây) ├── www → apex (301) ├── denylist IP (KV, một khoá "denylist", CIDR + hạn) → trang 403 + ├── rate limit toàn site RL_SITE 100/10s/IP (trừ admin.*) → trang 429 ├── tách host: admin.poli0981.dev chỉ /admin*, /api/admin*, /media/* ├── /media/* → R2 poli0981-media (ảnh upload qua admin, cache 1 năm) ├── /ext-img/* → KV widgets:img:* (ảnh widget đã mirror; không gọi Google/Steam) @@ -54,7 +55,7 @@ poli0981-dev/ ├── scripts/ # gen-og, gen-notices, check-exif/strip-exif, check-csp-hashes, │ # check-install-scripts, smoke-worker, new-post ├── src/ -│ ├── worker.ts # entry: denylist, host, /media, /ext-img, cổng, assets +│ ├── worker.ts # entry: denylist, rate limit site, host, /media, /ext-img, cổng, assets │ ├── middleware.ts # admin JWT + CSRF, rate limit /api, trang lỗi │ ├── assets/ # ảnh qua pipeline Astro (gallery/, covers/) │ ├── components/ # .astro + islands .svelte @@ -94,7 +95,7 @@ poli0981-dev/ "assets": { "binding": "ASSETS", "directory": "./dist", "not_found_handling": "404-page", "html_handling": "auto-trailing-slash", "run_worker_first": ["/*", "!/_astro/*", "…"] }, "kv_namespaces": [{ "binding": "KV", "id": "…" }], - "ratelimits": [ RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ], + "ratelimits": [ RL_SITE 100/10s · RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ], "vars": { "GATE_MODE": "on", "ACCESS_TEAM_DOMAIN": "…", "ACCESS_AUD": "…", "REPORT_REPO": "poli0981/site-reports" }, "r2_buckets": [{ "binding": "MEDIA", "bucket_name": "poli0981-media" }], "images": { "binding": "IMAGES" }, diff --git a/poli0981.dev-docs/06_SECURITY.md b/poli0981.dev-docs/06_SECURITY.md index 34a08a9..f14dec5 100644 --- a/poli0981.dev-docs/06_SECURITY.md +++ b/poli0981.dev-docs/06_SECURITY.md @@ -23,7 +23,11 @@ request → src/worker.ts (mọi route, cả trang tĩnh) 1. denylist: MỘT khoá KV "denylist" = [{cidr, reason?, until?, added?}] đọc tối đa 1 lần/phút/isolate (+ cacheTtl 60 s ở colo); IP hoặc dải CIDR (IPv4/IPv6), mục hết hạn bị bỏ qua → khớp ⇒ 403 (trang 09 §2, no-store) · KV lỗi ⇒ bỏ qua (fail-open, có log) - 2. app Astro — middleware, nếu path bắt đầu /api/: + 2. rate limit toàn site: RL_SITE 100/10s, khoá "site:" (IPv6 gộp /64), cho MỌI request + tới Worker — trang, /media, /ext-img, /pagefind, /api — trừ host admin.* (đã có Access) + vượt ⇒ 429 + Retry-After: 10, đếm ngược 10 s · binding lỗi ⇒ bỏ qua (fail-open, có log, + không bỏ qua cổng Turnstile) + 3. app Astro — middleware, nếu path bắt đầu /api/: Workers Rate Limiting binding theo nhóm (src/lib/ratelimit.ts), khoá ":" (IPv6 gộp theo /64): report → RL_REPORT 5/60s · gate → RL_GATE 30/60s · admin → RL_ADMIN 120/60s @@ -32,7 +36,8 @@ request → src/worker.ts (mọi route, cả trang tĩnh) ``` - Một khoá thay vì `denylist:`: tra cứu tốn như nhau dù IP nào hỏi (một lần đọc/phút/isolate) và chặn được cả dải. Quản lý ở **admin → Bảo mật** (`/admin/security/`): thêm kèm lý do + thời hạn (1 giờ … 30 ngày, hoặc đến khi gỡ), gỡ, có audit log. Không cho chặn dải chứa IP của chính admin — danh sách áp cho mọi host, kể cả admin. Thay đổi có hiệu lực trong khoảng một phút. -- Binding rate limit đếm **theo từng colo** và chỉ cho `period` 10 hoặc 60 s → lớp mềm; lớp cứng là zone rate-limit rule (07 §6). `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981004). +- Binding rate limit đếm **theo từng colo**, gần đúng (burst có thể lọt quá ngưỡng một chút) và chỉ cho `period` 10 hoặc 60 s → lớp mềm; lớp cứng là zone rate-limit rule (07 §6). `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981005). `Retry-After` phải bằng `period` (hằng số trong `src/lib/ratelimit.ts`, test đối chiếu với `wrangler.jsonc`). +- Ba lớp, ngoài vào trong: **WAF rule** (edge, chặn trước khi Worker chạy — không tốn request Worker, trang chặn 1015 của Cloudflare) → **RL_SITE** (ngưỡng thấp hơn WAF để khách thật gặp trang 429 "đẹp" trước) → **nhóm /api** (chặt nhất). Một lượt xem trang tốn 1–20 request tới Worker (file tĩnh `/_astro/*` không qua Worker), nên 100/10s chỉ chặn flood và giữ F5. - Chặn quốc gia/ASN hay danh sách rất dài: dùng WAF custom rule / IP List (07 §7). ## 3. Form duy nhất: /api/report (bug) diff --git a/poli0981.dev-docs/07_CLOUDFLARE_SETUP.md b/poli0981.dev-docs/07_CLOUDFLARE_SETUP.md index ce59f02..a63629f 100644 --- a/poli0981.dev-docs/07_CLOUDFLARE_SETUP.md +++ b/poli0981.dev-docs/07_CLOUDFLARE_SETUP.md @@ -33,13 +33,22 @@ Zone → Security: - **WAF → Managed rules**: bật Cloudflare Managed Ruleset (free ruleset). - Settings → Security Level: Medium · Browser Integrity Check: ON. -## 6. Rate limiting rule (free có 1 rule) — lớp ngoài cho /api/* +## 6. Rate limiting rule (free có 1 rule) — lớp ngoài cho toàn site -Security → WAF → Rate limiting rules → Create: -- Name: `api-outer-limit` -- If: `URI Path starts with /api/` -- Rate: **20 requests / 10 seconds** per IP → Action: **Block**, duration 1 phút (mitigation timeout theo option gói free). -(Lớp trong Worker vẫn đếm 5/phút để trả trang 429 đẹp — rule này chỉ hứng flood thô.) +Gói Free: **1 rule**, biểu thức chỉ dùng được trường **URI Path** và **Verified Bot**, đếm theo **IP**, chu kỳ **10 s**, thời gian chặn **10 s**, không đổi được trang chặn (Cloudflare trả **429**, trang "Error 1015"). Rule chặn ở edge, trước Worker ⇒ flood không tốn request Worker. + +Lớp trong Worker (06 §2) đếm thấp hơn — RL_SITE 100/10s cho mọi request tới Worker — để khách thật gặp trang 429 của site trước; rule này chỉ hứng flood thô, nên ngưỡng phải **cao hơn** 100. + +Security → Security rules → Rate limiting rules (đang có rule mẫu "Leaked credential check" chiếm slot duy nhất — site không có form mật khẩu nào trên zone, admin đăng nhập qua Access ở `*.cloudflareaccess.com`, nên rule đó không bao giờ khớp: sửa nó thành rule dưới, hoặc xoá rồi tạo mới): +- Name: `site-outer-limit` +- Expression (Edit expression): + `(not starts_with(http.request.uri.path, "/_astro/") and not cf.client.bot)` + — bỏ file tĩnh đã hash (lần tải đầu một trang có thể kéo vài chục file) và bot đã xác thực (Googlebot…; bot AI đã bị chặn ở §5). +- Characteristics: IP · Rate: **150 requests / 10 seconds** · Action: **Block** · Duration: **10 seconds**. +- Gói Free không lọc được theo hostname, nên rule này đếm cả `admin.*` (RL_SITE thì miễn admin). Thư viện ảnh admin tải thumbnail lười (`loading="lazy"`), mỗi màn hình vài chục request — dưới 150. +- Khi bị tấn công: hạ xuống 60–80/10s hoặc đổi Action sang **Managed Challenge**; xong thì trả về. + +Kiểm tra: `npm run probe:ratelimit -- https://poli0981.dev/legal/privacy/ 400` — dòng `worker 429` là RL_SITE (trang của site), `waf 429` là rule này (trang 1015). Rule chưa bật ⇒ chỉ thấy `worker 429`. ## 7. Custom rules (free có ~5 rule) — chặn IP/dải/quốc gia khi cần @@ -134,7 +143,7 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c - [ ] `dig poli0981.dev` ra IP Cloudflare; DNSSEC = Success - [ ] https:// bắt buộc, chứng chỉ hợp lệ, HSTS header có mặt - [ ] Bot Fight ON · Managed WAF ON · (AI crawlers block ON nếu chọn) -- [ ] Rate limit rule active — test bằng script bắn 30 req/10s vào /api/ → bị block +- [ ] Rate limit rule active — `npm run probe:ratelimit` (§6) thấy `worker 429` rồi `waf 429` - [ ] Turnstile hoạt động trên form report (site key đúng domain) - [ ] Custom domain trỏ Worker, `www` redirect về apex - [ ] Cron widgets chạy (Workers → widgets → Logs thấy execution) diff --git a/poli0981.dev-docs/09_ERROR_PAGES_OFFLINE.md b/poli0981.dev-docs/09_ERROR_PAGES_OFFLINE.md index 34e1db0..c3569be 100644 --- a/poli0981.dev-docs/09_ERROR_PAGES_OFFLINE.md +++ b/poli0981.dev-docs/09_ERROR_PAGES_OFFLINE.md @@ -17,10 +17,10 @@ Nhắc lại quyết định D8: Custom Errors của Cloudflare cần zone plan | **404** `404.astro` · `en/404.astro` | route không tồn tại | "Trang này không phát ra tín hiệu." / "This page makes no sound." | + ô search (mở Pagefind — đúng index của ngôn ngữ trang), gợi ý 3 bài mới cùng ngôn ngữ. Assets config `not_found_handling: "404-page"` trả `404.html` gần nhất theo đường dẫn: `/en/…` nhận bản tiếng Anh (`en/404.html`, xem 02 §4), mọi đường dẫn khác nhận bản tiếng Việt | | **500** `500.astro` | exception khi render on-demand / api | "Có gì đó vỡ trong im lặng." / "Something broke, quietly." | Astro tự dùng 500.astro khi SSR lỗi; api route bọc try/catch trả JSON lỗi gọn. Mã tham chiếu = **Cloudflare Ray ID** của request, worker đóng dấu vào `#ref` (`src/lib/error-ref.ts`) — trùng field `ray` trong Workers Logs, ReportDialog tự đính vào báo lỗi | | **403** worker entry | IP/dải nằm trong denylist (KV `denylist`, `06` §2) | "Cửa này đang khoá." / "This door is locked." | Kèm link `mailto:contact@` nếu nghĩ là nhầm. Không nêu lý do cụ thể | -| **429** middleware render | vượt rate-limit app (5 req/phút/IP trên /api) | "Chậm lại một nhịp." / "Take a breath." | Header `Retry-After: 60`; hiện đồng hồ đếm ngược 60s (vanilla JS inline) | +| **429** worker entry · middleware | vượt rate-limit toàn site (RL_SITE 100/10s/IP, worker entry) hoặc của một nhóm /api (middleware, `06` §2) | "Chậm lại một nhịp." / "Take a breath." | Header `Retry-After`: 10 (toàn site) / 60 (nhóm /api); đồng hồ đếm ngược đọc số giây trong `#cd` — mặc định 60, worker ghi đè thành 10. Vượt rule WAF (`07` §6) thì gặp trang 1015 của Cloudflare thay vì trang này | | **/offline** | service worker fallback | "Không có mạng — nhưng vẫn có thứ để làm." / "You're offline." | Xem §3–4 | -403 (worker entry) và 429 (middleware) dùng template Astro đã **prerender sẵn thành static asset** (`/403/` `/429/` là trang thật): chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng + `no-store` — không nhân đôi markup (đường `astro dev` dùng `rewrite` cũng được bọc lại status). +403 (worker entry) và 429 (worker entry + middleware) dùng template Astro đã **prerender sẵn thành static asset** (`/403/` `/429/` là trang thật): chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng + `no-store` — không nhân đôi markup (đường `astro dev` dùng `rewrite` cũng được bọc lại status). Trang xác minh của cổng Turnstile (06 §3b) **không** phải trang lỗi: nó là chính trang được yêu cầu (status 200, `` thật) với `` thay bằng thẻ xác minh. `/offline/` đứng ngoài cổng để service worker luôn precache được. @@ -45,7 +45,8 @@ Canvas ≤ 6KB JS vanilla nằm ngay trong trang offline: đầu lâu pixel nh | 404 asset | mở `/anh-khong-co.png` | trang 404 (not_found_handling) | | 500 | tạm ném throw trong 1 api route ở preview | trang/JSON 500 + mã tham chiếu | | 403 | thêm IP nhà vào denylist KV preview → mở site | trang 403 custom | -| 429 | bắn 6 POST /api/report trong 1 phút | request 6 nhận trang 429 + Retry-After | -| 429 lớp zone | bắn 30 req/10s | Cloudflare block (trang mặc định) — xác nhận rule sống | +| 429 | bắn 6 POST /api/report trong 1 phút | request 6 nhận trang 429 + Retry-After: 60 | +| 429 toàn site | `npm run probe:ratelimit` (> 100 req/10s) | trang 429, Retry-After: 10, đếm ngược 10 (dòng `worker 429`) | +| 429 lớp zone | `npm run probe:ratelimit -- 400 40` (> 150 req/10s) | trang 1015 của Cloudflare (dòng `waf 429`) — xác nhận rule sống | | Offline | DevTools → Network Offline → điều hướng | trang /offline + game chạy | | Mobile | lặp các case trên ở viewport 390px | không vỡ layout | diff --git a/scripts/probe-ratelimit.mjs b/scripts/probe-ratelimit.mjs new file mode 100644 index 0000000..91b37cd --- /dev/null +++ b/scripts/probe-ratelimit.mjs @@ -0,0 +1,53 @@ +// Spam a URL from this machine and report who answered 429: the Worker's site-wide limit +// (RL_SITE — the site's own 429 page, Retry-After: 10) or the zone WAF rate-limiting rule +// (Cloudflare's "Error 1015" page, before the Worker runs). Docs 06 §2 and 07 §6. +// +// npm run probe:ratelimit -- [url] [requests] [parallel] +// defaults: https://poli0981.dev/legal/privacy/ 300 20 +// +// The default page skips the Turnstile gate, so a 200 is the real page. Every request spends +// this address's budget: expect 429s from the site for the next ~10 seconds. + +const url = process.argv[2] ?? "https://poli0981.dev/legal/privacy/"; +const total = Number(process.argv[3] ?? 300); +const parallel = Number(process.argv[4] ?? 20); + +/** "worker 429" | "waf 429" | the status code as text. */ +async function probe() { + const response = await fetch(url, { + redirect: "manual", + headers: { "user-agent": "poli0981-ratelimit-probe" }, + signal: AbortSignal.timeout(15000), + }); + const body = await response.text(); + if (response.status !== 429) return String(response.status); + // The site's 429 page carries the countdown span; the WAF's block page never does. + return body.includes('id="cd"') ? "worker 429" : "waf 429"; +} + +const results = []; +const firstAt = {}; +const started = Date.now(); +let next = 0; +await Promise.all( + Array.from({ length: parallel }, async () => { + while (next < total) { + const index = next++; + const kind = await probe().catch((error) => `error (${error.name})`); + results.push(kind); + firstAt[kind] = Math.min(firstAt[kind] ?? Infinity, index + 1); + } + }), +); + +const seconds = ((Date.now() - started) / 1000).toFixed(1); +console.log(`${total} requests to ${url} in ${seconds}s (${parallel} in parallel)`); +const counts = Object.groupBy(results, (kind) => kind); +for (const [kind, hits] of Object.entries(counts)) { + console.log( + ` ${kind.padEnd(12)} ${String(hits.length).padStart(5)} first at #${firstAt[kind]}`, + ); +} +if (!counts["worker 429"] && !counts["waf 429"]) { + console.log("no 429 at all — the limits were not reached (more requests or more parallel?)"); +} diff --git a/scripts/smoke-worker.mjs b/scripts/smoke-worker.mjs index 0daa740..d008757 100644 --- a/scripts/smoke-worker.mjs +++ b/scripts/smoke-worker.mjs @@ -8,7 +8,8 @@ // with Cloudflare's always-pass test secret, so the whole flow — gate page, exemptions, // /api/gate → pass cookie → real page — is exercised end to end (siteverify is a real // network call; the test secret accepts any token). Phase 3 lists the client's address in -// the KV denylist and expects 403s everywhere, pages included. +// the KV denylist and expects 403s everywhere, pages included. Phase 4 spams a page until the +// site-wide rate limit answers with the 429 page. // // Usage: npm run build && npm run smoke (works on Linux, macOS and Windows) import { execFileSync, spawn } from "node:child_process"; @@ -384,6 +385,25 @@ try { rmSync(tmp, { recursive: true, force: true }); } +console.log("— phase 4: spam until the site-wide rate limit answers"); +// Last of all: the simulated counters outlive a `wrangler dev` restart, so a spent budget +// would turn the next phase into 429s. RL_SITE allows 100 per 10 s; keep going until a 429 +// arrives — a burst can straddle two windows. +await withWorker(8791, {}, async (get) => { + let limited = null; + for (let i = 0; i < 400 && !limited; i++) { + const response = await get("/legal/privacy/"); + if (response.status === 429) limited = response; + else await response.body?.cancel(); + } + const html = limited ? await limited.text() : ""; + expect("spam → 429 from the site-wide limit", limited !== null); + expect("429 sends Retry-After: 10", limited?.headers.get("retry-after") === "10"); + expect("429 is no-store", limited?.headers.get("cache-control") === "no-store"); + expect("429 has nosniff", limited?.headers.get("x-content-type-options") === "nosniff"); + expect("429 countdown starts at 10", html.includes('10')); +}); + if (failures.length) { console.error(`\nsmoke test failed (${failures.length}): ${failures.join(", ")}`); process.exit(1); diff --git a/sonar-project.properties b/sonar-project.properties index 3cc8953..688f1f1 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -4,7 +4,7 @@ sonar.organization=poli0981 sonar.projectKey=poli0981_poli0981-dev sonar.projectName=poli0981-dev # Bumped with each release tag; "previous version" new-code periods start from it. -sonar.projectVersion=2.0.0 +sonar.projectVersion=2.1.0 sonar.sourceEncoding=UTF-8 # .github is analyzed too: the workflow rules (pinned actions, no npx/install scripts) are diff --git a/src/lib/ratelimit.ts b/src/lib/ratelimit.ts index 3367e26..410a412 100644 --- a/src/lib/ratelimit.ts +++ b/src/lib/ratelimit.ts @@ -5,8 +5,12 @@ import { env } from "cloudflare:workers"; // RL_API. /api/widgets is never limited: its response is identical for every visitor // and edge-cached (api/widgets.ts), and the home page fetches it on every view. +/** The /api groups' window (wrangler.jsonc `ratelimits`), sent as Retry-After. */ export const RATE_LIMIT_WINDOW_SECONDS = 60; +/** RL_SITE's window: the site-wide limit src/worker.ts applies before any route. */ +export const SITE_RATE_LIMIT_SECONDS = 10; + type RateLimiter = { limit(options: { key: string }): Promise<{ success: boolean }> }; const BINDING_FOR_GROUP: Record = { diff --git a/src/pages/429.astro b/src/pages/429.astro index 50cace0..15418bc 100644 --- a/src/pages/429.astro +++ b/src/pages/429.astro @@ -6,14 +6,15 @@ import ErrorLayout from "@/layouts/ErrorLayout.astro";

429

Chậm lại một nhịp.

Take a breath.

+ {/* 60 s = the /api groups' window; the Worker rewrites it for the site-wide limit (10 s). */}

Thử lại sau / Retry in 60s

{ /* Processed (not `is:inline`): body-level, so the CSP governs it and only a bundled script gets a hash. Deferring costs nothing for a 1s-tick countdown. */ }