feat(worker): site-wide rate limit with the branded 429 page (D32) (#49)

* feat(worker): site-wide rate limit with the branded 429 page (D32)
* docs: record how the rate-limit binding really counts (measured on the preview)

Every page, feed and data request runs the Worker first and spends one
unit of SITE_LIMITER (60 per 10 s per IPv4 or IPv6 /64); over it, the
built /errors/429 page (status 429, Retry-After 10, no-store) or JSON
under /api/. What a page loads stays asset-first. Fails open. Measured on
the preview: holds a client on one connection; many-connection floods are
for the zone rule (docs/16 §9.1). Privacy #rate-limit, LEGAL_VERSION
2026-10-26, suite v3.0, v1.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 authored and GitHub committed 2026-10-27 06:16:14 +07:00
1 parent ffb470cebc
commit 0cdc730461
27 files changed
+944 -171

No files matched your search

+31
View File
@@ -4,6 +4,37 @@ All notable changes to SoftHarbor. The site is continuously deployed; a
version marks a release announced in the repository (docs/13). Dates are
UTC.
## [1.3.0] — 2026-10-26
Protection against floods: the site now limits how fast one network can
ask for it, and says so plainly when it does.
### Privacy — what changed
- To keep floods and runaway scripts off the site, requests for its pages,
feeds and data are now counted per network address for a few seconds,
then forgotten. No address is kept. The Privacy Policy has a new section,
"Rate limiting", so the consent dialog asks you to accept once more.
### Added
- **A rate limit for the whole site.** A browser or tool that asks for
far more than anyone reading would — over 60 requests in ten seconds —
gets a "Too many requests" page in English and Vietnamese for about ten
seconds instead of the page asked for. The public dataset at `/api/apps.json` and
the bot-check endpoint answer in JSON under the same limit, and the
dataset's answer is readable from other sites, so tools see the refusal
and when to retry. What a page loads — styles, scripts, fonts, icons — is
never limited, so a page that loads, loads whole.
### Changed
- The "Too many requests" page says how long to wait and points tools at
the dataset.
- The end-to-end tests also run the site's Worker locally and flood it on
purpose: the limit, the 429 page, and everyone let back in afterwards.
- The AI Disclosure names the model used for this release.
## [1.2.0] — 2026-10-23
Upkeep of everything behind the list — security checks that keep
+14 -10
View File
@@ -2,7 +2,7 @@
> Root instruction file for AI-assisted development (Claude Code).
> Read this first. Detailed specs live in `docs/00–16`.
> Suite version: 2.0 (2026-10-21, site v1.1) · Author: poli0981 / SkullMute
> Suite version: 3.0 (2026-10-26, site v1.3) · Author: poli0981 / SkullMute
## What this project is
@@ -17,8 +17,9 @@ googling every tool one by one.
- Hosting: **Cloudflare Workers Static Assets** on canonical
**`https://softharbor.net`** (Free zone; `www` 301s to apex; workers.dev
route disabled, PR previews only — see `docs/16`), deployed by Cloudflare
Workers Builds when `main` changes. One tiny Worker answers
`POST /api/verify` only (D25); no backend, no database.
Workers Builds when `main` changes. One tiny Worker runs the site-wide
rate limit (D32) and answers `POST /api/verify` (D25); no backend, no
database.
- Stack: Node 26 · pnpm 11 · Astro 7 (static output) · Svelte 5 islands ·
Tailwind CSS 4.3 · TypeScript strict (TS 7 `tsc` beside the TS 6 API that
`astro check` needs — D28) · Wrangler 4 — full table in `docs/01`
@@ -26,13 +27,16 @@ googling every tool one by one.
## Hard rules (never violate)
1. **Static-first.** No SSR, no database, no serverless functions; all
interactivity is client-side Svelte islands. The ONE exception (D25) is
`worker/`: a minimal Worker that answers only `POST /api/verify` (the
legal gate's Turnstile check) and runs only for the paths in
`assets.run_worker_first`. It never serves pages, never gates content, and
every failure on its side must fail OPEN. Anything else that seems to need
a server: redesign it or move it to a GitHub Actions workflow — a second
Worker route needs a decision-log entry.
interactivity is client-side Svelte islands. The ONE exception is
`worker/`, a minimal Worker that does exactly two things: the site-wide
rate limit (D32 — over it, a 429; otherwise the request goes to the asset
server untouched) and `POST /api/verify` (D25, the legal gate's Turnstile
check). It runs only for the paths in `assets.run_worker_first`, never
renders or rewrites a page, never withholds one from a person reading at
a normal pace, and every failure on its side must fail OPEN. Anything else
that seems to need a server: redesign it or move it to a GitHub Actions
workflow — a second Worker route, or a change to what runs it first,
needs a decision-log entry.
2. **Data is law.** Every listed app is exactly one JSON file in
`src/data/apps/<slug>.json`, validated by the Zod schema in
`src/content.config.ts`. Invalid data must fail the build. Never bypass the
+6 -4
View File
@@ -29,15 +29,17 @@ explaining it away. The scan is linked either way — judge it yourself.
## How it is built
Static. No database, no accounts, no cookies; fonts, icons and scripts are
self-hosted. The exceptions are deliberate and small: one tiny Worker endpoint
that checks the legal gate's Cloudflare Turnstile token (`worker/`, and the
gate lets you in even if the check cannot run), and cookieless Cloudflare Web
self-hosted. The exceptions are deliberate and small: one tiny Worker
(`worker/`) that rate-limits floods — over the limit you get a "Too many
requests" page for a few seconds — and checks the legal gate's Cloudflare
Turnstile token (the gate lets you in even if the check cannot run), and
cookieless Cloudflare Web
Analytics, which does not load at all when your browser sends Global Privacy
Control. The [Privacy Policy](https://softharbor.net/legal/privacy) has the
details.
Astro 7 (static) · Svelte 5 islands · Tailwind CSS 4 · TypeScript strict ·
Node 26 · pnpm 11 · Cloudflare Workers Static Assets (+ one Worker route).
Node 26 · pnpm 11 · Cloudflare Workers Static Assets (+ one small Worker).
Tested with Vitest (unit, islands, build scripts, the Worker) and Playwright +
axe on the built site; analysed by CodeQL and SonarQube Cloud.
+10 -7
View File
@@ -1,10 +1,10 @@
# 00 — Project Overview
> **Project:** SoftHarbor
> **Doc suite version:** 2.0 (2026-10-21, site v1.1)
> **Doc suite version:** 3.0 (2026-10-26, site v1.3)
> **Author:** poli0981 / SkullMute · **License:** code GPL-3.0-only · data CC BY-SA 4.0
> **Platform:** Web (static), Cloudflare Workers Static Assets, canonical `https://softharbor.net`
> — plus one Worker route, `POST /api/verify` (D25)
> — plus one Worker: the site-wide rate limit (D32) and `POST /api/verify` (D25)
## 1. Elevator pitch
@@ -104,10 +104,11 @@ consistent over time.
| D19 | Suite correctness | Spec claims about external systems are **verified against the real system** before they enter the docs | 2026-07-27 | The 2026-07-27 audit found two ops-repo workflows that never existed and four stale tool majors — all cheap to catch on paper, all expensive to catch in CI |
| D23 | Logo fallback | Third `logo` form `monogram` (initials) when no brand mark is available | 2026-07-29 | Simple Icons covers only part of the catalogue; docs/14 §3d sanctions no other source than the vendor's own assets (docs/15 §4) |
| D24 | Seed import | The seed batch was exempt from one-app-per-PR | 2026-07-29 | 286 machine-uniform files; the rule resumes for every later entry (docs/15 §4) |
| D25 | Server code | **One Worker, for `POST /api/verify` only** (amends hard rule 1): the legal gate's step 2 — Turnstile after acceptance, token checked server-side, rate-limited, everything fails **open**; `run_worker_first` keeps pages and assets on the unbilled asset path | 2026-10-21 | Consent-first human check on a public site without ever locking a person out (docs/09 §4a, docs/08 Part E) |
| D25 | Server code | **One Worker, for `POST /api/verify` only** (amends hard rule 1): the legal gate's step 2 — Turnstile after acceptance, token checked server-side, rate-limited, everything fails **open**; `run_worker_first` keeps pages and assets on the unbilled asset path — *amended 2026-10-26 by D32: the Worker now runs first for pages, feeds and data too, for the site-wide rate limit; content-hashed assets stay asset-first* | 2026-10-21 | Consent-first human check on a public site without ever locking a person out (docs/09 §4a, docs/08 Part E) |
| D26 | Analytics | **Cloudflare Web Analytics, honouring Global Privacy Control** (supersedes D14; amends hard rule 7): cookieless beacon, never under GPC, production host only | 2026-10-21 | Knowing whether the site works and is used, with the least data and a privacy signal honoured (docs/09 §8) |
| D27 | Contacts | **One address per purpose at `@poli0981.dev`** — `src/lib/contacts.ts`; `contact@softharbor.net` retired; mail hosted by Google | 2026-10-21 | A message reaches the right queue; `sponsor@` deliberately unused (docs/14 Part 2) |
| D28 | Toolchain | **Node 26 + TypeScript 6/7 side by side** (amends D7 and D21) — `.nvmrc` 26; `typescript` = the `@typescript/typescript6` API wrapper, `@typescript/native` = TS 7, whose `tsc --noEmit` now type-checks every `.ts` file in `pnpm check` | 2026-10-23 | Node 24 entered maintenance 2026-10-20; TS 7 ships no API yet, which astro check, typescript-eslint and svelte2tsx need (docs/01 §2) |
| D32 | Rate limiting | **Site-wide rate limit in the Worker** (amends hard rule 1 and D25): `run_worker_first` is `/*` minus the files a page loads (`/_astro/*`, icons, service worker); every request it routes spends one unit of `SITE_LIMITER` — 60 per 10 s per IPv4 or IPv6 /64, per location — and over it gets the branded `/errors/429` page (JSON under `/api/`), `Retry-After: 10`; fails **open** | 2026-10-26 | A flood or a runaway scraper gets refused cheaply with our own page instead of the Free zone's default; configured and tested in the repo (wrangler.jsonc, e2e/worker.spec.ts), not in a dashboard (docs/08 Part F) |
| D29 | Code analysis | **SonarQube Cloud CI-based analysis with coverage** (`ci.yml` `sonar` job, not a required check) replaces Automatic Analysis | 2026-10-23 | Automatic Analysis cannot import coverage; a CI scan measures the same lcov the ratchet gates (docs/12 §2, docs/11 §1) |
## 6. Identifiers (locked)
@@ -116,7 +117,7 @@ consistent over time.
|---|---|
| Repo slug | `poli0981/softharbor` |
| Canonical origin | `https://softharbor.net` (apex; `www` 301s to it) |
| Worker name | `softharbor` — code in `worker/`, one endpoint `POST /api/verify` (D25); workers.dev route disabled; versioned preview URLs only (docs/16 §3) |
| Worker name | `softharbor` — code in `worker/`: the site-wide rate limit (D32) and one endpoint, `POST /api/verify` (D25); workers.dev route disabled; versioned preview URLs only (docs/16 §3) |
| Contact email | One address per purpose at `@poli0981.dev` — `src/lib/contacts.ts`, page `/contact` (D27; `contact@softharbor.net` retired) |
| Component prefix | `Sh*` (islands: `ShLegalGate`, `ShSearch`, `ShFilterSheet`, `ShLangSwitch`, `ShPrefs`, `ShBugReport`) |
| CSS custom property prefix | `--sh-*` |
@@ -133,9 +134,10 @@ binary · automatic scraping of vendor metadata (all entries are hand-written)
· mobile-app listings · package-manager command snippets (winget/brew —
post-v1 backlog) · zone security add-ons kept deliberately OFF at launch:
rate limiting, Bot Fight Mode, paid Custom Errors (reasons & activation
recipes in docs/16 §9 — the Worker's own rate-limit binding on
`/api/verify` is not a zone feature) · server-rendered or gated pages of
any kind (D25 allows one verification endpoint, nothing more) · a third
recipes in docs/16 §9 — the Worker's own rate limits, site-wide since
D32, are not a zone feature) · server-rendered or gated pages of any kind
(D25 allows one verification endpoint and D32 one rate limit, nothing
more: a flood gets a 429, a person reading never does) · a third
locale (JP is a v1.2 candidate, docs/15).
## 8. Document map
@@ -159,3 +161,4 @@ See `CLAUDE.md` for the full table. Reading order for a new contributor:
| H10 | Enable *Settings → Actions → General → **Allow GitHub Actions to create and approve pull requests*** — without it the nightly quarantine sweep cannot open its PR and hard rule 5 stops being enforced mechanically (docs/12 §4) — ✅ enabled | P6 |
| H11 | Set the Worker's runtime secret **`TURNSTILE_SECRET`** (dashboard → Variables and Secrets, or `wrangler secret put`) — without it every check answers 503 and the gate silently fails open for everyone (docs/08 Part E) — ✅ set (verified 2026-10-21: a junk token gets `403 rejected`); redo whenever the Worker is re-created | v1.1 |
| H12 | Turn the zone's **Speed Brain** off — Cloudflare refuses speculative prefetch on Worker requests (503); production still sent a `Speculation-Rules` header on 2026-10-21 (docs/16 §9) | v1.1 |
| H13 | **Recommended:** deploy the zone **rate-limiting rule as layer 1** in front of the Worker's limit — one rule, URI Path starts with `/` and not a verified bot, 150 requests per 10 s per IP, Block 10 s (step-by-step and a verification command: docs/16 §9.1). It is the layer that stops a many-connection flood, which the Worker's per-machine counters mostly miss (docs/08 Part F), and it blocks before the Worker is billed; nothing in the repository depends on it | v1.3 |
+49 -32
View File
@@ -4,7 +4,8 @@
Static-first. The repository *is* the database; a deploy *is* a data
migration. Everything a visitor reads is a prebuilt static asset; since
v1.1 one small Worker answers exactly one endpoint (D25).
v1.1 one small Worker answers exactly one endpoint (D25), and since v1.3
it also stands in front of every page as the site-wide rate limit (D32).
```
maintainer PR ──▶ CI (ci.yml build + gates, codeql) ──▶ squash to main
@@ -14,8 +15,11 @@ v1.1 one small Worker answers exactly one endpoint (D25).
│ dist/ + worker/
▼
Cloudflare Workers Static Assets — softharbor.net
pages, assets, feeds ─▶ asset server (unbilled)
POST /api/verify ─────▶ worker/index.ts (D25)
/_astro/*, icons, SW ─▶ asset server (unbilled)
pages, feeds, /api/* ─▶ worker/index.ts: rate limit (D32)
├─ over it → 429
├─ POST /api/verify (D25)
└─ else → asset server
│
▼
Browser
@@ -29,21 +33,25 @@ v1.1 one small Worker answers exactly one endpoint (D25).
Consequences (accepted, documented):
- No SSR, no database, no page ever produced by server code. The only
server code is `worker/`, which answers `POST /api/verify` (the legal
gate's Turnstile check) and runs only for the paths in
`assets.run_worker_first`; every page, asset and feed is served by the
asset server without invoking it (§7, docs/08 Part E).
server code is `worker/`, which runs for the paths in
`assets.run_worker_first` — everything but the files a page loads — and
does two things: the site-wide rate limit (D32) and `POST /api/verify`
(the legal gate's Turnstile check, D25). Every page, asset and feed it
lets through is served by the asset server unchanged (§7, docs/08
Parts E and F).
- "Dynamic" behaviors are relocated: data mutation → Git + GitHub Actions;
personalization → localStorage; search → client-side index; shareable
view state → the URL (docs/05 §A3).
- Logs: Cloudflare's dashboard metrics for the site, plus Workers Logs for
the Worker's own one-line JSON events (outcome and duration — never an IP
or a token; invocation logs off).
- 403/429 can now come from us, but only as JSON answers from
`/api/verify` that the gate consumes and fails open on — never as a page.
Page-level 403/429 still cannot happen: the zone's security features
(rate limiting, Bot Fight Mode) are deliberately OFF (docs/16 §9), so the
templates stay dormant (docs/08 Part C).
the Worker's own one-line JSON events (a verification's outcome and
duration, a rate-limit refusal's kind — never an IP or a token;
invocation logs off).
- 429 comes from us since D32: our own `/errors/429` page for a page
request over the site-wide limit, JSON under `/api/` (docs/08 Part F).
403 still comes only as a JSON answer from `/api/verify`, which the gate
consumes and fails open on. Page-level 403 cannot happen — Bot Fight Mode
and the zone's WAF rules are off (docs/16 §9) — so `/errors/403` and
`/errors/500` stay dormant (docs/08 Part C).
## 2. Project tree
@@ -77,13 +85,15 @@ softharbor/
├── data/
│ └── quarantine/ # flagged apps parked here (docs/03 §5);
│ # created by `pnpm quarantine` on first use
├── worker/ # the ONE Worker (D25, docs/08 Part E)
│ ├── index.ts # /api/verify → verify.ts, else ASSETS.fetch()
├── worker/ # the ONE Worker (D25, D32 — docs/08 E, F)
│ ├── index.ts # rate limit → /api/verify → else ASSETS.fetch()
│ ├── limit.ts # site-wide rate limit, 429 page / JSON
│ ├── verify.ts # POST /api/verify → Turnstile Siteverify
│ ├── http.ts # JSON responses, body cap, rate-limit key
│ ├── env.ts # bindings, typed by hand
│ └── *.test.ts # Vitest `worker` project (docs/11)
├── e2e/ # Playwright + axe on the build (docs/11 §5)
├── e2e/ # Playwright + axe on the build, and the
│ # Worker under `wrangler dev` (docs/11 §5)
├── scripts/
│ ├── validate-data.mjs # L2 cross-file data rules (docs/03 §2)
│ ├── check-i18n-parity.mjs # EN/VI key parity (docs/07 §3)
@@ -156,7 +166,7 @@ softharbor/
├── legal/{disclaimer,privacy,terms,trademarks,third-party,
│ ai-disclosure}.astro
├── contact.astro # one address per purpose (D27)
├── errors/{403,429,500}.astro # dormant templates
├── errors/{403,429,500}.astro # 429 live (D32); 403, 500 dormant
├── 404.astro # → dist/404.html
├── offline.astro # SW fallback
├── api/apps.json.ts # static JSON export
@@ -178,11 +188,12 @@ softharbor/
| `/contact` | `/vi/contact` | `contact.astro` | One address per purpose (D27); gate-exempt |
| `/404` | — | `404.astro` | Served via `not_found_handling`; one bilingual page; gate-exempt |
| `/offline` | — | `offline.astro` | SW navigation fallback; one bilingual page; gate-exempt |
| `/errors/{403,429,500}` | — | templates | Dormant — Free zone, nothing issues them (docs/08 Part C) |
| `/errors/429` | — | template | **Live** (D32): the Worker serves it with status 429 to a client over the site-wide limit (docs/08 Part F) |
| `/errors/{403,500}` | — | templates | Dormant — Free zone, nothing issues them (docs/08 Part C) |
| `/api/apps.json` | — | endpoint | Full dataset export (docs/03 §6) |
| `/search-index.json` | — | endpoint | Serialized MiniSearch index, lazy-loaded |
| `/rss.xml` | — | endpoint | Latest additions feed |
| `POST /api/verify` | — | `worker/` | The only route that runs code (D25, docs/09 §4a) |
| `POST /api/verify` | — | `worker/` | The only endpoint answered by code (D25, docs/09 §4a); like every routed request it passes the site-wide limit first (D32) |
Every page route is prebuilt: 701 HTML files in `dist/` as of 2026-10-21
(326 apps × 2 locales plus the rest). Pages without a VI mirror (404,
@@ -343,9 +354,9 @@ document load with its own CSP and its own island tree.
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "softharbor",
"main": "./worker/index.ts", // D25 — POST /api/verify only
// ≥ 2025-04-01: a NAVIGATION that matches no asset gets dist/404.html from
// the asset server without invoking the Worker (docs/08 Part C).
"main": "./worker/index.ts", // D25 + D32 — rate limit, /api/verify
// ≥ 2025-04-01: on an asset-first path, a NAVIGATION that matches no asset
// gets dist/404.html from the asset server directly (docs/08 Part C).
"compatibility_date": "2026-10-01",
"assets": {
"directory": "./dist",
@@ -355,13 +366,17 @@ document load with its own CSP and its own island tree.
// Measured in S1 on a real deploy: "auto-trailing-slash" 307s /apps to
// /apps/, contradicting every canonical; this makes /apps the 200.
"html_handling": "drop-trailing-slash",
// The only path that runs the Worker before the asset server.
"run_worker_first": ["/api/verify"]
// D32: every request runs the Worker first EXCEPT what a page loads.
"run_worker_first": ["/*", "!/_astro/*", "!/icons/*", "!/favicon.ico",
"!/favicon.svg", "!/apple-touch-icon.png", "!/manifest.webmanifest",
"!/sw.js", "!/registerSW.js", "!/workbox-*.js"]
},
// Workers Rate Limiting for /api/verify: 20 per 60 s per IPv4 address or
// IPv6 /64, per Cloudflare location. namespace_id is account-wide.
// Workers Rate Limiting, per IPv4 address or IPv6 /64, per Cloudflare
// location; namespace_id is account-wide (docs/08 Part F).
"ratelimits": [
{ "name": "VERIFY_LIMITER", "namespace_id": "4101",
{ "name": "SITE_LIMITER", "namespace_id": "4102", // D32
"simple": { "limit": 60, "period": 10 } },
{ "name": "VERIFY_LIMITER", "namespace_id": "4101", // D25
"simple": { "limit": 20, "period": 60 } }
],
// Workers Logs keep the Worker's own JSON lines; invocation logs are off.
@@ -379,10 +394,12 @@ document load with its own CSP and its own island tree.
Rules:
- `main` exists since D25 and serves **only** `/api/verify`. Adding any
path to `run_worker_first` — or letting the Worker serve, gate or rewrite
a page — needs a decision-log entry: every match is a billed invocation,
and hard rule 1 allows one route.
- `main` exists since D25 and does exactly two things (hard rule 1): the
site-wide rate limit (D32) and `/api/verify`. Changing what
`run_worker_first` routes, the limits, or letting the Worker serve,
render or rewrite a page needs a decision-log entry: every routed request
is a billed invocation. Keep the negative patterns covering everything a
page loads, so a page that passed never half-loads.
- Never re-enable `workers_dev` (duplicate-content hazard — docs/16 §1/N3).
- Do not re-add `routes` without re-reading docs/16 §2.2: a deploy
reconciles the Worker's triggers, which is how `www` was lost once.
+140 -31
View File
@@ -2,7 +2,8 @@
> This is the operator's guide Kokone asked for. Part A is the click-by-click
> setup; Part C answers "can Cloudflare make our error pages?" definitively;
> Part E is the one Worker the site runs since v1.1 (D25).
> Part E is the one Worker the site runs since v1.1 (D25), and Part F the
> site-wide rate limit it has run since v1.3 (D32).
## Part A — Setup guide (account + zone + first deploy)
@@ -96,13 +97,15 @@ serves (`workers_dev: false`). Full domain checklist: docs/16 §10.
§A5–A6).
- **Workers Logs** (`observability.enabled`, invocation logs **off**) hold
only the Worker's own one-line JSON events: `{event: "verify", outcome,
ms}` per request, `verify.secret_refused` when Siteverify rejects our
secret, `verify.crash` on an unexpected exception — never an IP address
or a token (Part E). `wrangler tail` shows the same lines live.
ms}` per verification, `verify.secret_refused` when Siteverify rejects our
secret, `verify.crash` on an unexpected exception, `{event:
"rate_limited", kind}` per refused request — never an IP address or a
token (Parts E and F). A request that passes logs nothing. `wrangler tail` shows the same lines live.
- **Billing:** only requests that run the Worker are billed Worker
requests — `run_worker_first` paths (`/api/verify`) and the rare
non-navigation request that matches no asset (Part C). Pages, assets and
feeds are served by the asset server and are **not billed**.
requests. Since D32 that is every page, feed and data file —
`run_worker_first` is `/*` minus the files a page loads (Part F) — while
`/_astro/*`, icons and the service worker stay on the asset server and
are **not billed**.
- Asset limits to respect (check current values in CF docs at setup time;
documented limits as of writing): max ~20 000 files per deploy, 25 MiB
per file. SoftHarbor's footprint (local build, 2026-10-21): 763 files in
@@ -121,9 +124,11 @@ feature). HSTS **is** configured — zone-level, now at phase P3 (docs/16
§5). Do not "pre-enable" anything beyond that.
Two things that look similar but are not zone features: the Worker's
**Workers Rate Limiting binding** (`VERIFY_LIMITER`, Part E) guards only
`/api/verify`, and **Turnstile** (D25) is a widget our own page loads after
consent — neither touches how pages are served. Conversely, the zone's
**Workers Rate Limiting bindings** — `SITE_LIMITER` for every page, feed
and data request (Part F, D32) and `VERIFY_LIMITER` for `/api/verify`
(Part E) — and **Turnstile** (D25), a widget our own page loads after
consent. The zone's rate-limiting rule stays off; the Worker's limit is
configured in `wrangler.jsonc` and answers with our own 429 page. Conversely, the zone's
**Speed Brain** speculative prefetch should be **off**: Cloudflare refuses
prefetch on Worker requests with a 503, which is why `astro.config.ts` sets
`prefetch: false` (docs/16 §9 — ⚠ verify the zone setting; production still
@@ -135,22 +140,24 @@ Background (re-verified 2026-07-20): Cloudflare **Custom Errors** is a
**paid zone-plan** feature — our zone is Free (docs/16 §1/N4) — and even
where available it does not apply to 500/501/503/505 responses. Therefore
**every error page a user can see must come from our own build output**,
and anything Cloudflare itself emits shows Cloudflare's default page. The
v1.1 Worker (Part E) changes nothing for pages: its error statuses are JSON
answers to the gate's own `fetch`, never a document.
and anything Cloudflare itself emits shows Cloudflare's default page.
`/api/verify` (Part E) answers the gate's own `fetch` in JSON, never with a
document. Since D32 the Worker runs first for pages too (Part F), and its
one page-level answer is our own 429.
| Status | Who generates it | What the user sees | Our artifact |
|---|---|---|---|
| 404 (navigation) | Asset server, URL matches nothing. With `compatibility_date` ≥ 2025-04-01 a navigation miss gets `404.html` **without invoking the Worker** | Our branded, bilingual page, real HTTP 404, no legal gate | `dist/404.html` via `not_found_handling: "404-page"` |
| 404 (other) | A non-navigation miss (an image, a JSON file) reaches the Worker, which returns `env.ASSETS.fetch(request)` — the same `not_found_handling` | Same 404 | same |
| 500-class (pages) | Practically cannot originate from us — no code runs for a page. Cloudflare infra errors (52x) show Cloudflare's page — not customizable on a Free zone | CF default (rare) | `/errors/500` template kept **dormant** |
| 404 | The asset server, URL matches nothing. Since D32 the request reaches it through the Worker's `env.ASSETS.fetch(request)`, which applies the same `not_found_handling`; a miss under an asset-first pattern (`/_astro/*`, icons) gets it directly | Our branded, bilingual page, real HTTP 404, no legal gate | `dist/404.html` via `not_found_handling: "404-page"` |
| 500-class (pages) | Practically cannot originate from us: the Worker in front of pages only counts and hands over, and catches every limiter failure (Part F); an uncaught exception would show Cloudflare's 1101 page. Cloudflare infra errors (52x) show Cloudflare's page — not customizable on a Free zone | CF default (rare) | `/errors/500` template kept **dormant** |
| 403 (pages) | Nothing issues 403 for a page — WAF features deliberately OFF (docs/16 §9). If ever enabled on the Free zone, blocks render **Cloudflare's default page** (custom responses are paid features) | n/a | `/errors/403` dormant template |
| 429 (pages) | Nothing issues 429 for a page — zone rate limiting deliberately OFF (docs/16 §9); same Free-zone caveat as 403 | n/a | `/errors/429` dormant template |
| 4xx/5xx from `/api/verify` | The Worker: `400 invalid_json`/`invalid_token`, `403 bad_origin`/`rejected`, `405`, `413`, `415`, `429 rate_limited` (`Retry-After: 60`), `503 not_configured`/`unavailable`, `500 internal_error` | Nothing — the gate reads the status; 403 asks Turnstile for a fresh challenge, every other failure **fails open** (docs/05 §A9) | JSON body `{ "error": "<code>" }` |
| 429 (pages) | The Worker's site-wide rate limit (Part F, D32): over 60 requests per 10 s from one address. The zone rule stays OFF (docs/16 §9) | Our branded, bilingual page, real HTTP 429, `Retry-After: 10`, no legal gate | `/errors/429` — **live** since D32 |
| 429 (`/api/*`) | The same limit, for the data endpoints and `/api/verify` | JSON `{ "error": "rate_limited" }`, `Retry-After: 10`; CORS-readable on the dataset | — |
| 4xx/5xx from `/api/verify` | The Worker: `400 invalid_json`/`invalid_token`, `403 bad_origin`/`rejected`, `405`, `413`, `415`, `429 rate_limited` (`Retry-After: 60` from its own limit, 10 from the site-wide one), `503 not_configured`/`unavailable`, `500 internal_error` | Nothing — the gate reads the status; 403 asks Turnstile for a fresh challenge, every other failure **fails open** (docs/05 §A9) | JSON body `{ "error": "<code>" }` |
| No internet | Client-side | Our offline page | `offline.html` via service worker (Part D) |
The dormant templates cost three static pages and make a future Pro-zone
Custom Errors switch-on a config-only task (docs/16 §9 recipe). Like
The two dormant templates (403, 500) cost two static pages and make a
future Pro-zone Custom Errors switch-on a config-only task (docs/16 §9
recipe); the 429 one has been live since D32. Like
`/404` and `/offline` they are gate-exempt, `noindex` and bilingual on one
page (docs/06 §5).
@@ -245,23 +252,24 @@ the final pass runs on the real origin), fallback fires in airplane mode,
on the offline page (it is exempt — the page declares `gateExempt`, docs/14
Part 2).
## Part E — The `/api/verify` Worker (D25)
## Part E — The `/api/verify` endpoint (D25)
The one piece of server code (CLAUDE.md hard rule 1 as amended). Threat
model and the client half: docs/09 §4a, docs/05 §A9.
**Files.** `worker/index.ts` (entry: `/api/verify` → `handleVerify`,
anything else → `env.ASSETS.fetch(request)`), `worker/verify.ts` (the
endpoint), `worker/http.ts` (JSON responses, streamed body cap, rate-limit
**Files.** `worker/index.ts` (entry: the site-wide limit first — Part F —
then `/api/verify` → `handleVerify`, anything else →
`env.ASSETS.fetch(request)`), `worker/limit.ts` (Part F), `worker/verify.ts`
(the endpoint), `worker/http.ts` (JSON responses, streamed body cap, rate-limit
key), `worker/env.ts` (bindings, typed by hand — `@cloudflare/workers-types`
would collide with the DOM lib the site compiles against). Tested by the
Vitest `worker` project against a stubbed Siteverify (docs/11 §2); CI also
runs `wrangler deploy --dry-run` so a config error fails before production.
**Routing.** `assets.run_worker_first: ["/api/verify"]` is the only path
that runs the Worker before the asset server. Pages, assets and feeds never
invoke it; a navigation that matches nothing gets `404.html` from the asset
server (Part C).
**Routing.** Until D32 `/api/verify` was the only path that ran the
Worker before the asset server. Now every request except the files a page
loads does (Part F), and each one passes the site-wide limit before it
reaches this endpoint — whose own, stricter limit comes on top.
**Contract — `POST /api/verify`**, body `{"token": "<turnstile token>"}`:
@@ -312,6 +320,106 @@ sitekey itself is public by design and lives in `src/lib/turnstile.ts`.
`verify.crash`. Never an IP address, never a token; invocation logs are off
in `wrangler.jsonc`.
## Part F — The site-wide rate limit (D32)
**What runs it.** `assets.run_worker_first` is `/*` minus the files a page
loads once it has passed: `/_astro/*` (content-hashed JS, CSS and fonts),
`/icons/*`, the two favicons, `apple-touch-icon.png`,
`manifest.webmanifest`, `sw.js`, `registerSW.js` and `workbox-*.js`.
Negative patterns win over `/*` whatever the order. Every other request —
every page in both locales, `/rss.xml`, the sitemaps, `/search-index.json`,
`/api/apps.json`, `/api/verify`, `robots.txt`, `security.txt`, a miss that
ends on the 404 page — runs `worker/index.ts` first, which spends one unit
of `SITE_LIMITER` (`worker/limit.ts`) and, under the limit, hands the
request to `env.ASSETS.fetch()` unchanged.
**The limit.** 60 requests per 10 s per IPv4 address or IPv6 /64 (`rateKey`,
the same key as Part E), per Cloudflare location, namespace `4102`. That is
six a second, sustained: a person reading spends one per page, and what it
stops is a flood or a scraper running flat out. Generous on purpose,
because a school, an office or a mobile carrier's NAT puts many people
behind one address. `/api/verify` keeps its own 20 per 60 s on top
(Part E).
**What it really counts — measured on the PR preview, 2026-10-26.**
Cloudflare calls the binding "permissive, eventually consistent": each
machine counts locally and shares its counts in the background. In
practice that sharing barely shows:
| Burst (one client address) | Result |
|---|---|
| 120 requests over **one keep-alive connection**, ~11 s | 61 × `200`, then 59 × `429` — the limit, almost to the request |
| 1 500 requests, **a new connection each** (30 in parallel), ~20 a second for 79 s | 0 × `429` (1 487 × `200`, 12 local connection errors, one `500` whose cause version URLs cannot log) |
| Production `VERIFY_LIMITER`, 40 `POST /api/verify` in 33 s, a new connection each | 0 × `429` against 20 per 60 s |
So the Worker's limit holds a client that **reuses its connection** —
every browser (one HTTP/2 connection per origin) and most scrapers — and
answers it with our own page. A flood that opens a fresh connection per
request spreads over many machines and mostly slips past it; stopping that
is the job of the zone rule, which counts per IP at the edge before the
Worker runs: **layer 1, recommended** (docs/16 §9.1). Neither layer locks
out a person reading normally.
**Over the limit:**
| Request | Answer |
|---|---|
| `/api/*` | `429 {"error":"rate_limited"}`, `Retry-After: 10`, `no-store`, the Worker's own security headers — plus `Access-Control-Allow-Origin: *` and `Access-Control-Expose-Headers: Retry-After` on everything but `/api/verify`: the dataset is CORS-open, so its refusal must be readable cross-origin, or a consumer sees a network error instead |
| anything else | The built `/errors/429` page (bilingual, gate-exempt, `noindex`) with status **429**, `Retry-After: 10`, `Cache-Control: no-store` and no `ETag`; every other header is the asset server's (`_headers`). `HEAD` gets the headers only. If that page cannot be fetched, a plain-text 429 |
The 429 page's own CSS, JS and fonts are under `/_astro/` and never
limited, so it renders whole. The service worker's navigation route is
NetworkOnly and a 429 is a response, not a failure, so the visitor sees
our page rather than the offline fallback.
**Fails open.** No `SITE_LIMITER` binding, no `CF-Connecting-IP` (no client
to tell apart — one shared bucket would throttle strangers together), or a
limiter that throws: the request is served as if there were no limit.
**`_headers` still apply.** What `env.ASSETS.fetch()` returns carries
`public/_headers` exactly as a direct asset response does — measured under
`wrangler dev` and on the PR preview on 2026-10-26 (frame-ancestors,
`X-Frame-Options`, nosniff, the workers.dev `X-Robots-Tag`, the `/_astro/*`
and `/api/apps.json` `Cache-Control`; and on a refused page the same set
plus `Retry-After: 10` and `no-store`). Moving pages behind the Worker
changed no header.
**Billing.** Every routed request is now a billed Worker invocation. The
account is on Workers Paid: 10 million requests and 30 million
CPU-milliseconds a month included, then $0.30 per million requests and
$0.02 per million CPU-ms; Workers Logs include 20 million events a month
(Cloudflare's pricing page, read 2026-10-26 — Logs move to Observability
pricing on 2026-12-01). A page view costs one invocation and well under a
millisecond of CPU, and the files a page loads stay free ("requests to
static assets are free and unlimited"). A refused request
is billed too — the limit makes a flood cheap to answer, not free. A flood
large enough to matter is the job of Cloudflare's automatic DDoS
protection and of the zone rate-limiting rule (docs/16 §9.1), both of
which act before the Worker runs, so what they block is never billed —
the rule at the price of Cloudflare's default block page.
**Logs.** One line per refusal, `{event: "rate_limited", kind: "page" |
"api"}` — never the address; a request that passes logs nothing. Rate
limiting bindings have no dashboard of their own, so these lines (Workers
Logs, `wrangler tail`) are the only record of how often the limit fires —
read them before tuning it.
**Tests.** Unit: `worker/limit.test.ts` (stubbed limiter and asset server;
`wrangler.jsonc` is read with wrangler's `unstable_readConfig` to hold
`period` equal to `RETRY_AFTER_S` and keep the negative patterns). End to
end: the Playwright project `worker` (`e2e/worker.spec.ts`) starts `wrangler
dev` on `dist/` with the real config — Miniflare simulates the binding in
fixed windows aligned to the clock, without counting refusals — and floods
it: exactly the configured 60 × 200 and then 429s, the 429 page rendered
and styled in Chrome, `/api/*` answering JSON, a page's own files still
200, everyone back in when the window passes. On a deployed version: the
burst check in docs/13 §2.
**Tuning.** Change `limit` in `wrangler.jsonc` with a decision-log line;
`period` must stay equal to `RETRY_AFTER_S` (a test holds them together).
Keep namespace ids unique on the account — bindings that share one share
their counters, across Workers too.
## Appendix — Future custom-domain package (superseded in v1.1)
`softharbor.net` was purchased pre-launch (2026-07-20); the package was
@@ -323,8 +431,9 @@ sit in this appendix, for the record:
into `_headers`, and `preload` is a separate explicit decision (H9).
- `www` → apex uses **zone Redirect Rules** — the static `_redirects` file
cannot match hostnames and stays reserved for path-level slug renames.
- Rate limiting and Bot Fight Mode are **deliberately OFF**, not enabled by
default (reasons + recipes: docs/16 §9); on the Free zone their block
pages would be Cloudflare defaults anyway.
- Rate limiting and Bot Fight Mode are **deliberately OFF** at the zone,
not enabled by default (reasons + recipes: docs/16 §9); on the Free zone
their block pages would be Cloudflare defaults anyway. Since D32 rate
limiting lives in the Worker instead (Part F), with our own 429 page.
- The workers.dev route is **disabled** (`workers_dev: false`) rather than
served-with-noindex — cleaner than the old "decide then" note.
+6 -3
View File
@@ -22,7 +22,7 @@ honest-privacy story.
| T4 | Site integrity | XSS via data fields | All rendering through Astro's default escaping; `set:html` lint-banned (`astro/no-set-html-directive`) except five named files that inline build-time SVG, JSON-LD or one constant (docs/10 §3); JSON-LD escapes `<`; schema constrains URLs to https; CSP §4 as backstop |
| T5 | Visitors | Clickjacking / framing on a look-alike site | `frame-ancestors 'none'` + `X-Frame-Options: DENY` (and on Worker responses, §4a) |
| T6 | Repo | Malicious PR alters workflows/scripts/the Worker | Ruleset on `main`: PR required, **signed commits**, required checks (docs/12 §8); CODEOWNERS on `.github/**`, `scripts/**`, `src/data/**`, `worker/**`; every workflow declares least `permissions:` (the repo default token is read-write); `persist-credentials: false` on checkout; step outputs reach shell only via `env:` (no `${{ }}` in `run:`) |
| T7 | Availability | DDoS | Cloudflare edge absorbs; static assets, nothing to exhaust. The one endpoint is rate-limited per IP or /64 and fails open, so exhausting it locks nobody out (§4a) |
| T7 | Availability | DDoS, floods, runaway scrapers | Cloudflare's edge DDoS protection absorbs volumetric attacks before any code runs. Above that, the Worker's site-wide limit (D32, docs/08 Part F): 60 requests per 10 s per IPv4 or IPv6 /64 for every page, feed and data file, answered with our own 429 page or JSON — measured to hold a client on one connection (every browser, most scrapers) but not a flood opening a new connection per request, which is what the recommended zone rule in front of it is for (docs/16 §9.1). The files a page loads are never limited, so a page that passed loads whole; the limit and `/api/verify` both fail open, so an outage of either locks nobody out (§4a) |
| T8 | Users' privacy | Tracking/leakage | No cookies, no ads, no fingerprinting by us. Two Cloudflare services only, both started by our code: Web Analytics (cookieless; never under Global Privacy Control or off the production host) and Turnstile (only after the documents are accepted). The CSP allows exactly their origins (§4); storage inventory §8 |
| T9 | The domain itself | `softharbor.net` hijack (registrar/DNS) or email spoofing "from" the domain | Registrar transfer lock + auto-renew, DNSSEC enabled, zone changes only via the dashboard (custom domains are attached there, docs/16 §3); SPF + DMARC `p=quarantine` observed 2026-10-21 (→ `reject` planned) — docs/16 §2/§6 |
| T10 | The endpoint | `/api/verify` abused: cross-site POSTs, replayed or foreign tokens, oversized bodies, burning the Siteverify allowance | Same-origin check; `application/json` only; body ≤ 4 KB counted while streaming; token ≤ 2048 chars; Siteverify verdict re-checked for host, `action: legal_gate` and age ≤ 300 s; idempotency key; Workers Rate Limiting 20/60 s per IPv4 or IPv6 /64; `no-store` — all in §4a |
@@ -256,8 +256,10 @@ the gate's step 2 links to it.
(`src/lib/turnstile.test.ts`). The e2e suite stands in for Cloudflare:
`api.js` is served from its real URL (so the page CSP is exercised) and
`/api/verify` — which `astro preview` does not run — answers 200, 503 or is
blocked (docs/11 §5). What only production can show: the Worker, the
secret and `_headers` — verified after each deploy (docs/13 §3).
blocked (docs/11 §5). The Worker itself — routing, both limiters, `_headers` on
what it passes through — runs under `wrangler dev` in the e2e project
`worker` (docs/11 §5). What only production can show: the real edge, the
secret — verified after each deploy (docs/13 §3).
## 5. Vulnerability reporting
@@ -410,6 +412,7 @@ what — the list the Privacy Policy mirrors (`/legal/privacy`):
| Party | When | What |
|---|---|---|
| Cloudflare (hosting) | every request | connection data such as IP addresses, as infrastructure provider under its own policy; we see aggregate counts only |
| Our Worker's rate limit (D32) | every page, feed and data request | the IP address (IPv6: its /64) as the key of a counter Cloudflare's rate limiter keeps for 10 s; never logged — a refusal logs only its kind (docs/08 Part F) |
| Cloudflare Web Analytics (D26) | page loads on `softharbor.net` only, **never** when `navigator.globalPrivacyControl === true` | page URL, referrer, load timings, user-agent; cookieless; we see totals |
| Cloudflare Turnstile (D25) | once, after the documents are accepted | browser/device signals inside its iframe; the token plus IP go to Siteverify via our Worker (§4a) |
| GitHub | only if the visitor opens "Report a bug" | the prefilled URL carries page URL, user-agent and recent error lines — GitHub receives them **when the link is opened**; nothing is filed until the visitor submits (docs/05 §A6) |
+15 -8
View File
@@ -6,7 +6,8 @@
▲ manual: launch checklist (docs/13 §2) — screen readers, visual VI
│ diacritics, real-device offline, production-only checks
│ e2e (Playwright + axe): the BUILT site under `astro preview`,
│ desktop Chrome + Pixel 7 — docs/11 §5
│ desktop Chrome + Pixel 7, and the Worker under
│ `wrangler dev` — docs/11 §5
│ build-as-integration-test: `pnpm build` and its gates —
│ validate:data, i18n:check, check:csp, check:assets,
│ check:sw, check:feed (docs/12 §2)
@@ -65,7 +66,7 @@ excludes only the root `*.config.*` files.
| `licenses.ts` / `logo.ts` / `paths.ts` | generated package table (installed versions, legacy and missing licenses); logo forms incl. monogram, no `style` attribute, escaped initials; category-page order (`byAddedDesc`) |
| `contrast.test.ts` | WCAG ratios for every token pair, both themes; no-JS dark block identical to the dark theme (docs/06 §2) |
| `scripts/*` (scripts project) | `validate-data` (each rule → its error row), `check-csp`, `check-i18n-parity`, `check-service-worker`, `check-feed`, `quarantine` — real script, temp tree, exit code |
| `worker/*` (worker project) | method, origin, media type, size (declared and streamed), token shape, rate limit, Siteverify verdicts (host, action, age, test secrets), retry with the same idempotency key, 503 without a secret, security headers on every response |
| `worker/*` (worker project) | `/api/verify`: method, origin, media type, size (declared and streamed), token shape, rate limit, Siteverify verdicts (host, action, age, test secrets), retry with the same idempotency key, 503 without a secret, security headers on every response. The site-wide limit (`limit.test.ts`, D32): key per IPv4 or /64, the 429 page (status, `Retry-After`, `no-store`, no `ETag`, the asset server's headers kept, `HEAD`), JSON under `/api/` with CORS on the dataset only, plain-text fallback, fail-open (no binding, no address, a throwing limiter), one log line without the address; `wrangler.jsonc` read back to hold `period` = `RETRY_AFTER_S` and the negative patterns |
| islands | one test file per island (`Sh*.test.ts`): gate steps and Esc handling, search races and URL writes, filter sheet counts, language switch carrying the query, display menu storage, bug-report URL |
**Fuzzy vectors — resolved by S2 (2026-07-27), decision D22.** The old
@@ -284,9 +285,12 @@ references, and page-to-page links are covered by the e2e page set.
`playwright.config.ts`, specs in `e2e/`. Runs against the **built** site
served by `astro preview` on `127.0.0.1:4321` — the per-page meta CSP is
exactly as shipped (`ASTRO_PREVIEW_BACKGROUND=0` keeps the server in the
foreground; Astro ≥ 7.2 backgrounds it under CI). Two projects: `desktop`
(Desktop Chrome) and `mobile` (Pixel 7 — bottom sheets, the wrapped header,
touch targets). CI: one retry, traces kept on failure, report artifact.
foreground; Astro ≥ 7.2 backgrounds it under CI). Three projects:
`desktop` (Desktop Chrome) and `mobile` (Pixel 7 — bottom sheets, the
wrapped header, touch targets) against `astro preview`, and `worker`
(D32), which alone runs `e2e/worker.spec.ts` against a second server:
`wrangler dev` on `127.0.0.1:8799` serving the same `dist/` with the real
`wrangler.jsonc`. CI: one retry, traces kept on failure, report artifact.
**Shared fixture** (`e2e/fixtures.ts`, auto-applied): a test **fails** if
its page logged a console error, threw an uncaught exception, or fired a
@@ -305,8 +309,11 @@ animations before axe measures contrast.
|---|---|
| `smoke.spec.ts` | 15 pages in both locales (home, grid, detail, categories, legal, offline, contact): status < 400, an `h1`, a resolved `data-theme`, **no horizontal overflow**; an unknown URL → real 404 without the gate; **axe** (WCAG 2.0/2.1 A+AA, 2.2 AA tags) on five pages in **light and dark**, serious/critical findings fail |
| `gate.spec.ts` | blocks a first visit until accepted *and* checked; Esc twice cannot dismiss; **no Cloudflare request before acceptance**; check remembered ~48 h across a reload; blocked script or 503 → visitor let through with the "skipped" note and a 1 h retry; a lapsed check re-runs step 2 only; linked documents and error/offline pages are exempt |
| `worker.spec.ts` (project `worker`) | pages pass through the Worker with `_headers`, the 404 page and the trailing-slash redirect intact; a flood gets **exactly** the configured budget of 200s, then 429s — the branded page with `Retry-After` and `no-store`; while refused, `/api/apps.json` and `/api/verify` answer JSON (the dataset CORS-readable) and a page's CSS, the service worker and the favicon still load; the 429 page renders styled in Chrome with no CSP violation and no gate; everyone is back in when the window passes. Serial, and each test first waits for a fresh window (Miniflare counts in fixed windows aligned to the clock, refusals not counted) |
| `prefs-search.spec.ts` | display choices apply at once and are restored pre-paint on the next document; `/` from any page lands focused in `/apps#search`; Vietnamese search ignores diacritics, writes `?q=` and switches to "Best match"; a shared URL restores the view and "Clear all" really clears it |
**Not covered here, by design:** `_headers` and the Worker — `astro
preview` applies neither. They are verified on the Workers Builds preview
URL and in production after each merge (docs/13 §3).
**Not covered by `astro preview`:** `_headers` and the Worker — which is
why the `worker` project exists. What neither server can show — the real
edge, the production secret, Cloudflare's distributed counters — is
verified on the Workers Builds preview URL and in production after each
merge (docs/13 §3).
+3 -2
View File
@@ -142,8 +142,9 @@ cancels superseded runs except on `main`. Jobs:
check:csp → check:assets → check:sw → check:feed` → **`wrangler deploy
--dry-run`** (bundles `worker/` and validates `wrangler.jsonc` — bindings,
assets, `run_worker_first` — without credentials) → `pnpm knip` →
**Playwright e2e** on that build (docs/11 §5): the Chromium download is
cached per Playwright version (on a hit only the OS libraries are
**Playwright e2e** on that build (docs/11 §5) — `astro preview` for the
pages, `wrangler dev` for the Worker and its rate limits; the Chromium
download is cached per Playwright version (on a hit only the OS libraries are
installed), and the HTML report is uploaded as an artifact (7 days) when
the job fails.
- **`gates`** (15 min cap) — `validate:data`, `i18n:check`, `osv-scanner`
+9
View File
@@ -8,6 +8,7 @@ content. Git tags mark milestones only: **`v1.0.0`** at public launch
(tagged and released 2026-10-21; `package.json` `version` follows the tag),
**`v1.2.0`** for the upkeep release — re-check automation, Node 26 /
TypeScript 7, CI-based SonarQube Cloud, catalogue batch 2 (2026-10-23),
**`v1.3.0`** for the site-wide rate limit (D32, 2026-10-26),
minor tags when a feature phase ships. Publishing a GitHub Release fires `notify.yml` →
Discord (docs/12 §2). Data changes never tag. `CHANGELOG.md`
(Keep-a-Changelog, dates UTC) records feature work and anything a visitor
@@ -143,6 +144,14 @@ may be skipped (docs/12 §3).
→ `403 {"error":"rejected"}` (a `503 not_configured` means the runtime
secret is missing; a bare `405` from the asset server means the Worker
is not deployed);
- the site-wide rate limit (D32, docs/08 Part F) answers a burst over
**one connection** — one `curl` with many URLs reuses its connection;
parallel `curl`s would land on different machines and pass (Part F):
`curl -s $(for i in $(seq 70); do printf -- '-o /dev/null https://softharbor.net/robots.txt '; done) -w "%{http_code}\n" | sort | uniq -c`
→ about 60 × `200`, then `429`s; add `--next -s -D - -o /dev/null
https://softharbor.net/apps` to the same command to see a refused
page: `429`, `Retry-After: 10`, `Cache-Control: no-store` and the
`_headers` set. Ten seconds later everything is `200` again;
- `/rss.xml` serves the expected items (guid = slug, docs/05 §A4).
3. **Never run `wrangler deploy` by hand while builds are queued** — the
queued older build would land after it and roll production back
+12 -2
View File
@@ -103,7 +103,10 @@ dictionaries into the island would bundle every key (docs/07 §3).
Disclosure) · **2026-10-21** (v1.1: Privacy covers Web Analytics and the
Turnstile check and names the operator; Terms gained the operator and a
copyright-complaint procedure; nine EN/VI wording gaps and two false AI
Disclosure claims fixed).
Disclosure claims fixed) · **2026-10-26** (v1.3: Privacy gains
`#rate-limit` for the site-wide rate limit, D32 — our own code now
processes every visitor's address, if only for seconds, which the gate
asks everyone to accept once more).
### Contacts (D27)
@@ -225,6 +228,13 @@ analytics") stopped being true with D25/D26 and is not reproduced here
success and duration. A pass is remembered 48 h (`sh:human`); if the
check cannot run the visitor is let in and it is retried after an hour.
Basis: legitimate interest.
- **`#rate-limit`** *(2026-10-26, D32)* — the site's own code counts
requests for pages, feeds and data per IP (per /64 for IPv6) over a few
seconds; a network far above any reader's pace gets a "Too many
requests" page until the window passes; counts live only in
Cloudflare's rate limiter for that window; no address is recorded — a
refusal is logged without it. Basis: legitimate interest. Also one
sentence in the short version.
- **`#hosting`** — Cloudflare serves the site and the endpoint and
processes connection data under its own policy; we see aggregate counts.
- **`#email`** — `@poli0981.dev` mail is delivered to a Google-hosted
@@ -389,7 +399,7 @@ Terms, contacts, AI Disclosure) re-opens these items — sign-off on it:
legalese beyond necessity.
- [ ] Confirm comfort with C3 free-tier ruling as written in Disclaimer
context (pricing can change → covered by 3a(3)).
- [ ] `LEGAL_VERSION` follows the Part 2 policy (2026-10-21 as of v1.1); a
- [ ] `LEGAL_VERSION` follows the Part 2 policy (2026-10-26 as of v1.3); a
later material change to Disclaimer, Terms or Privacy bumps it, and
`legal.test.ts` fails if one is dated after it.
- [ ] Optional (recommended eventually): a qualified local review of Terms
+10 -4
View File
@@ -52,7 +52,9 @@ them (item 9 especially), so new work is appended, never renumbered.
1. **Zone upgrades on evidence, not by default** — revisit the
deliberately-OFF trio (rate limiting, Bot Fight Mode, Pro-zone Custom
Errors) only if abuse or 403/429 UX ever becomes real (docs/16 §9);
Errors) only if abuse or 403/429 UX ever becomes real (docs/16 §9) —
*rate limiting done another way on 2026-10-26: in the Worker, with our
own 429 page (D32); the zone rule is now an optional edge layer, §9.1*;
plus a `SearchAction` JSON-LD node (docs/16 §7) — its prerequisite, the
`/apps?q=` deep link, **shipped in v1.1** (`src/lib/urlstate.ts`).
2. ~~**VirusTotal automation — deadline 2027-01-26.**~~ **Done 2026-10-23
@@ -284,6 +286,9 @@ rule 8) · ads/affiliate links (conflicts with the trust proposition).
| 2026-10-23 | **D30 — VirusTotal re-check, assisted not decided** (docs/09 §6 step 5; docs/12 §4b). `scripts/vt-recheck.mjs` + `vt-recheck.yml`: daily on `main`, checks older than 90 days are re-scanned (download page, VT API v3, 4/min, ≤ 440 of 500 requests a day) and only the three `security` lines change; `checkedAt` now means "latest scan" (docs/04, docs/09 §6). The bot never flags and never promotes on its own: a detection turns `clean` into `unverified` plus a `[vt] <slug>` issue, and `unverified` → `clean` happens only for slugs the maintainer passes as `promote`. Dispatched on a data branch it previews a PR's new entries as an artifact. Terms fit: the Public API is offered to sites free to consumers; SoftHarbor is free and ad-free and submits only public URLs. The site's own copy moved with it — the "no known warnings" note and the AI Disclosure now describe the re-scan (`LEGAL_UPDATED.aiDisclosure` 2026-10-23; `LEGAL_VERSION` unchanged) | ✅ (owner, 2026-10-23) |
| 2026-10-23 | **D31 — Catalogue batch 2: 38 apps, two categories** (§2 item 10). Exempt from docs/03 §1's one-app-per-PR rule like D24 (38 researched entries, one PR). Categories `ai-local` and `cad-3d` (owner). **Not added:** Docker Desktop and Parsec — both free only under licence terms (Docker: not for larger companies; Parsec: personal, non-commercial use only), a C3 case the owner rules out; GPT4All and Ice — C5, unmaintained with open problems; QuickHash GUI — C4/C5, its only download site unreachable and no release since 2023. **C3 rulings:** LM Studio, Insomnia and RustDesk are `free` — the free tier serves the core purpose without a time limit and their subscriptions are optional add-ons (LM Studio's only for the separate Bionic agent's cloud models). **Store-only delivery meets C4** when the official download page on the developer's own domain hands off to the store (Lossless Scaling → Steam/Humble). **Licences as the sources grant them:** ShareX `GPL-2.0-or-later` (headers), KDE Connect `GPL-2.0-only OR GPL-3.0-only`, EarTrumpet `LicenseRef-EarTrumpet` (MIT plus an exclusion of three named companies), DuckStation `CC-BY-NC-ND-4.0` (source-available). Each entry was researched with AI assistance against docs/09 §6 steps 1–4 and scanned by the `vt-recheck` preview before merge (36 of 38 download pages with no detections); the owner reviewed the Vietnamese and promoted 30 to `clean`. Held `unverified`: Flameshot (unpatched advisory in its stable release), Bulk Crap Uninstaller (unsigned builds, antivirus history), OpenSCAD (2021 stable predates two CVE fixes), LM Studio (closed source, antivirus history), RustDesk (CVE backlog), AutoHotkey and LocalSend (one VirusTotal detection each), Lossless Scaling | ✅ (owner, 2026-10-23) |
| 2026-10-26 | **D32 — site-wide rate limit in the Worker** (amends hard rule 1 and D25; owner request, 2026-10-26). `run_worker_first` becomes `/*` minus the files a page loads — `/_astro/*`, `/icons/*`, the favicons, `apple-touch-icon.png`, the manifest, `sw.js`, `registerSW.js`, `workbox-*.js` — so every page, feed and data request runs `worker/limit.ts` first: `SITE_LIMITER` (namespace 4102), **60 per 10 s per IPv4 address or IPv6 /64**, per location. Over it: the built `/errors/429` page with status 429 (no longer dormant), `Retry-After: 10`, `no-store`; JSON under `/api/` (CORS-readable on the dataset). Fails **open** (no binding, no address, a throwing limiter); logs `{event: "rate_limited", kind}` without the address. `_headers` still apply to `env.ASSETS.fetch()` responses (measured). **Trade-offs accepted:** every routed request is a billed invocation (Workers Paid includes 10 M/month; refusals are billed too, so the limit makes floods cheap, not free); our code now processes every visitor's IP for seconds → Privacy `#rate-limit` and `LEGAL_VERSION` 2026-10-26. **Why not the zone rule alone:** on the Free zone it can only serve Cloudflare's default 429 page and cannot live in the repository; it is kept as an optional edge layer at 150 per 10 s (docs/16 §9.1). Tested end to end under `wrangler dev` by the new e2e project `worker` (docs/11 §5). **Measured on the PR preview:** over one keep-alive connection the limit holds almost exactly (61 × 200, then 429s), but a flood opening a new connection per request got no 429 at all (1 500 requests at ~20/s) — the binding counts per machine — and the production `VERIFY_LIMITER` likewise never refused 40 fresh-connection POSTs in 33 s. So the zone rule (docs/16 §9.1, H13) is the recommended first layer for floods, and the Worker's limit the polite one for browsers and keep-alive scrapers | ✅ (user, 2026-10-26) |
| 2026-10-26 | **Suite v3.0** (site v1.3) — a MAJOR bump by §6's rule, because D32 amends hard rule 1 | ✅ |
## 5. Open questions for Kokone
Everything below is blocked on a decision or a setting, not on code.
@@ -359,14 +364,15 @@ Status as of 2026-10-21: v1.0.0 shipped on 2026-07-30 and v1.1.0 on
## 6. Suite maintenance
This suite (**v2.0, 2026-10-21, describing site v1.1** — v1.2 was
This suite (**v3.0, 2026-10-26, describing site v1.3** — v2.0 was
2026-10-21, site v1.1; v1.2 was
2026-07-27; v1.1 was 2026-07-20 post-domain; v1.0 was 2026-07-15,
pre-domain) is the contract. Mind the two numbering schemes: *suite* v1.1
is the July domain revision, *site* v1.1 is the October release. Any
implementation that diverges updates the relevant doc **in the same PR**
(docs/10 §7-8). Version bumps: minor for clarifications, major when a hard
rule or locked decision changes — v2.0 is major because it amends hard
rules 1 and 7.
rule or locked decision changes — v2.0 was major because it amended hard
rules 1 and 7, v3.0 because D32 amends hard rule 1 again.
**v2.0 caught the docs up with site v1.1** — the code had moved for three
months while the suite stood still. D25–D27 and the 2026-10-21 rows of §4
+59 -5
View File
@@ -19,9 +19,9 @@
| N1 | Canonical origin | **`https://softharbor.net`** — apex, no `www` |
| N2 | `www.softharbor.net` | 301 → apex, path + query preserved (zone Redirect Rule) |
| N3 | `workers.dev` main route | **Disabled** (`workers_dev: false`); PR previews stay on versioned preview URLs (`preview_urls: true` — must be explicit, since it defaults to follow `workers_dev`) |
| N4 | Zone plan | **Free** (Workers Paid is account-level and unrelated). Consequence: Cloudflare **Custom Errors stays unavailable** (paid-zone feature) → our `/errors/*` templates remain dormant |
| N4 | Zone plan | **Free** (Workers Paid is account-level and unrelated). Consequence: Cloudflare **Custom Errors stays unavailable** (paid-zone feature) → `/errors/403` and `/errors/500` remain dormant; `/errors/429` is served by the Worker since D32, not by the zone |
| N5 | HSTS | Zone-level, phased rollout (§5) — **not** in `_headers` |
| N6 | Rate limiting & Bot Fight Mode | **OFF** at launch, with a ready-made activation recipe (§9) |
| N6 | Rate limiting & Bot Fight Mode | Bot Fight Mode **OFF** (§9). Rate limiting: the Worker's site-wide limit since D32 (docs/08 Part F), plus the zone rule as an optional edge layer — recipe §9.1 |
| N7 | Contact email | ~~`contact@softharbor.net` via Cloudflare Email Routing (§6) — resolves H5~~ — ⛔ **superseded 2026-10-21 by D27**: one address per purpose at `@poli0981.dev`, mail hosted by Google (§6) |
| N8 | Search plumbing | GSC **Domain property** + sitemap; Bing via GSC import; Crawler Hints (IndexNow) ON |
@@ -73,12 +73,12 @@ the `www` record (§2.2).* Today `wrangler.jsonc` (full reference: docs/02
```jsonc
{
"name": "softharbor",
"main": "./worker/index.ts", // D25 — /api/verify only
"main": "./worker/index.ts", // D25 + D32 — rate limit, /api/verify
"compatibility_date": "2026-10-01",
"assets": { "directory": "./dist", "binding": "ASSETS",
"not_found_handling": "404-page",
"html_handling": "drop-trailing-slash",
"run_worker_first": ["/api/verify"] },
"run_worker_first": ["/*", "!/_astro/*", …] }, // D32, docs/02 §7
// No "routes": softharbor.net and www.softharbor.net are Custom Domains
// attached in the dashboard; with no routes key a deploy leaves them be.
"workers_dev": false, // kills softharbor.<account>.workers.dev
@@ -271,12 +271,66 @@ hreflang errors) — added to docs/13 §6.
| Feature | Status & reason | Recipe if ever needed |
|---|---|---|
| **Rate limiting** (zone) | OFF. Static assets are unbilled and edge-served — there is nothing costly to protect; and on the Free zone the Block action serves **Cloudflare's default 429 page** (custom responses are Business+), undermining our error-page polish. *Not to be confused with the Worker's own Workers Rate Limiting binding, which guards only `/api/verify` (20/60 s per IP or /64, docs/08 Part E).* | Free zone includes **1 rule**: Security → WAF → Rate limiting rules → e.g. `(http.host eq "softharbor.net")`, 100 req / 10 s per IP, Block 1 min. Accept the default 429 page, or upgrade zone for custom response. |
| **Rate limiting** (zone) | **Recommended edge layer since D32 — owner step, ⚠ verify once deployed.** The site's rate limit lives in the Worker (docs/08 Part F: 60 page requests per 10 s, our own 429 page), but measured, it holds only a client that reuses its connection; a flood opening a new connection per request slips past it. The zone rule in front of it, layer 1, counts per IP at the edge and blocks before the Worker runs (so before it is billed) — on the Free zone only with **Cloudflare's default 429 page** (custom responses need Pro), which is why it must stay looser than the Worker's limit. | §9.1 — one rule, URI Path starts with `/` and not a verified bot, **150 per 10 s per IP**, Block 10 s. (The pre-D32 recipe here named `http.host` and a 1-minute block, neither of which the Free plan offers.) |
| **Bot Fight Mode** | OFF. It challenges automated clients — which would break exactly what we publish for automation: `/api/apps.json` consumers and the `notify.py` RSS cron. The legal gate's Turnstile check (D25) is no substitute and no conflict: it runs in visitors' browsers, after consent, and fails open. | Only with a scoped WAF exception for `/api/*` and `/rss.xml` — and only in response to actual abuse. |
| **Speed Brain** (speculative prefetch) | **Should be OFF.** Cloudflare refuses speculative requests on Worker requests — a `Sec-Purpose: prefetch` GET gets a bare **503** with `Cf-Speculation-Refused: prefetch refused: disabled for worker requests` — which is why `astro.config.ts` sets `prefetch: false` (docs/02 §4). **Observed 2026-10-21: production still sends `Speculation-Rules: "/cdn-cgi/speculation"`**, i.e. the zone feature appears to be on (H12, ⚠ verify and turn off). | Turn the zone's Speed Brain toggle off (Speed settings in the dashboard). Revisit only if Cloudflare ever allows speculation on Worker routes. |
| **Cloudflare Custom Errors** | Unavailable on Free zone (paid-plans feature; also never applies to 500/501/503/505). `/errors/{403,429,500}` templates stay **dormant** as designed. | Upgrade zone to Pro → Rules → Custom Error Rules → point 403/429 at the templates. Decision logged if taken. |
| **Cache tuning / Page Rules / Snippets** | Defaults. Workers Static Assets already serves from the edge; `_headers` (docs/09 §4) owns per-path `Cache-Control` — `/*` sets none and each specific rule detaches with `! Cache-Control`, because Cloudflare comma-joins a header set by several matching rules. | — |
### 9.1 Layer 1 at the edge — the zone rate-limiting rule (owner step)
Since D32 there are two layers. **Layer 1**, this zone rule, throws a
flood out at the edge before the Worker runs — not billed, but answered
with Cloudflare's default 429 page. **Layer 2**, the Worker's limit
(docs/08 Part F), answers over-use from a browser or a keep-alive client
with our own page. Layer 1 must be the looser of the two, or nobody would
ever see our page — and it is the only one that stops a flood that opens
a new connection per request, which the Worker's per-machine counters
mostly miss (measured, docs/08 Part F). Recommended, not optional.
Free-zone constraints (Cloudflare's docs, read 2026-10-26): **one** rule;
counted **per IP** only; the expression may use only **URI Path** and
**Verified Bot** (no Host); period **10 s**; block duration **10 s**; the
Block response is Cloudflare's default 429 (a custom response needs Pro).
Use Block, not a challenge: a challenge would break `/api/apps.json` and
RSS consumers, which cannot solve one.
Dashboard → the `softharbor.net` zone → **Security** → **Security rules** →
**Create rule** → **Rate limiting rules** (older dashboards: Security → WAF
→ Rate limiting rules):
1. **Rule name:** `Edge flood guard (layer 1, D32)`.
2. **If incoming requests match:** Field **URI Path**, Operator **starts
with**, Value `/` (every request) — **And** Field **Verified Bot**,
Value **Off**, so search engines' verified crawlers are left to the
Worker's limit and their own crawl-rate control. The expression preview
should read `(starts_with(http.request.uri.path, "/") and not
cf.client.bot)`.
3. **Cache status:** if **Also apply rate limiting to cached assets** is
offered, leave it **on** — every request counts.
4. **With the same characteristics:** **IP** (the only choice on Free).
5. **When rate exceeds:** **150** requests per **10 seconds**.
6. **Then take action:** **Block**; **Duration:** **10 seconds**.
7. **Deploy.**
**Why 150.** The rule counts everything — each page's CSS, JS and fonts
(about fifteen requests for a first page load, cached afterwards) and the
Worker's own 429s — while the Worker allows 60 page requests per 10 s. 150
is out of reach for any person, above the Worker's limit so over-use meets
our page first, and far below a flood. Never set it under ~100.
**Verify** once it is deployed, from one machine — hammer a file the
Worker never sees (an asset-first path), so only layer 1 can answer:
```bash
seq 1 200 | xargs -P 20 -I{} curl -s -o /dev/null -w "%{http_code}\n" https://softharbor.net/favicon.svg | sort | uniq -c
```
Expect roughly 150 × `200` and the rest `429` (Cloudflare's page, not
ours); ten seconds later the file answers `200` again. **Roll back** by
turning the rule off on the same page — nothing in the repository depends
on it.
## 10. Rollout sequence & verification
> **Status 2026-10-21.** The rollout below is complete and historical: www
+134
View File
@@ -0,0 +1,134 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// The Worker end to end (D32): `wrangler dev` serves dist/ with the real
// wrangler.jsonc — run_worker_first and its negative patterns, both rate
// limiters (simulated by Miniflare), public/_headers — so a flood can be
// thrown at it and the 429s inspected.
//
// Miniflare counts in fixed windows aligned to the wall clock, and a refused
// request does not count. So each test that needs a clean slate or a
// refusal first waits for the next window, which also makes a retried or
// re-used server start from zero.
import type { APIRequestContext } from '@playwright/test';
import { unstable_readConfig } from 'wrangler';
import { expect, test } from './fixtures';
test.describe.configure({ mode: 'serial' });
/** What this spec reads of wrangler.jsonc (wrangler's own Config type does not resolve here). */
interface WranglerConfig {
ratelimits: { name: string; simple: { limit: number; period: number } }[];
}
const site = (
unstable_readConfig({ config: 'wrangler.jsonc' }, { hideWarnings: true }) as WranglerConfig
).ratelimits.find((r) => r.name === 'SITE_LIMITER');
const LIMIT = site?.simple.limit ?? 0;
const PERIOD_MS = (site?.simple.period ?? 10) * 1000;
/** Resolves just after the next window starts: every count is back to zero. */
async function nextWindow(): Promise<void> {
const wait = PERIOD_MS - (Date.now() % PERIOD_MS) + 150;
await new Promise((resolve) => setTimeout(resolve, wait));
}
/** Spends this window's whole budget on `/`; returns every status, in order. */
async function flood(request: APIRequestContext, extra = 20): Promise<number[]> {
const statuses: number[] = [];
for (let i = 0; i < LIMIT + extra; i++) statuses.push((await request.get('/')).status());
return statuses;
}
test('pages pass through the Worker with the asset server’s own handling and headers', async ({
request,
}) => {
expect(LIMIT).toBeGreaterThan(0);
await nextWindow();
const res = await request.get('/apps');
expect(res.status()).toBe(200);
// public/_headers still applies to what ASSETS.fetch() returns.
expect(res.headers()['content-security-policy']).toBe("frame-ancestors 'none'");
expect(res.headers()['x-frame-options']).toBe('DENY');
// not_found_handling and html_handling, unchanged.
expect((await request.get('/apps/no-such-app')).status()).toBe(404);
const slashed = await request.get('/apps/', { maxRedirects: 0 });
expect(slashed.status()).toBe(307);
expect(slashed.headers()['location']).toMatch(/\/apps$/);
});
test('a flood gets exactly the configured budget, then the site’s own 429 page', async ({
request,
}) => {
await nextWindow();
const statuses = await flood(request);
expect(statuses.filter((s) => s === 200)).toHaveLength(LIMIT);
// Once refused, refused for the rest of the window.
expect(statuses.slice(LIMIT).every((s) => s === 429)).toBe(true);
const refused = await request.get('/apps/7-zip');
expect(refused.status()).toBe(429);
const h = refused.headers();
expect(h['retry-after']).toBe(String(PERIOD_MS / 1000));
expect(h['cache-control']).toBe('no-store');
expect(h['content-type']).toContain('text/html');
expect(h['x-frame-options']).toBe('DENY');
expect(await refused.text()).toContain('<title>Too many requests — SoftHarbor</title>');
});
test('while refused: /api/* answers JSON, and a page’s own files still load', async ({
request,
}) => {
await nextWindow();
const home = await (await request.get('/')).text();
await flood(request);
const data = await request.get('/api/apps.json');
expect(data.status()).toBe(429);
expect(await data.json()).toEqual({ error: 'rate_limited' });
expect(data.headers()['access-control-allow-origin']).toBe('*');
const verify = await request.post('/api/verify', { data: { token: 'x' } });
expect(verify.status()).toBe(429);
expect(await verify.json()).toEqual({ error: 'rate_limited' });
// Never limited: everything a page loads after it passed.
const css = /\/_astro\/[\w.-]+\.css/.exec(home)?.[0] ?? '/_astro/ (no stylesheet linked)';
for (const path of [css, '/sw.js', '/registerSW.js', '/favicon.svg', '/manifest.webmanifest']) {
expect((await request.get(path)).status(), path).toBe(200);
}
});
test.describe('the 429 page in a browser', () => {
// Chrome logs the document's own status; that line is expected here.
test.use({ allowConsole: [/status of 429/] });
test('renders whole — styled, no CSP violation, no gate', async ({ page, request }) => {
await nextWindow();
await flood(request);
const res = await page.goto('/apps');
expect(res?.status()).toBe(429);
await expect(page.locator('h1')).toHaveText('Too many requests');
await expect(page.locator('[lang="vi"] h2')).toHaveText('Quá nhiều yêu cầu');
const styled = await page.evaluate(() =>
[...document.styleSheets].every((s) => {
try {
return s.cssRules.length > 0;
} catch {
return false;
}
}),
);
expect(styled).toBe(true);
await expect(page.getByRole('dialog')).toHaveCount(0);
});
});
test('lets everyone back in when the window passes', async ({ request }) => {
await nextWindow();
await flood(request);
expect((await request.get('/apps')).status()).toBe(429);
await nextWindow();
expect((await request.get('/apps')).status()).toBe(200);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "softharbor",
"version": "1.2.0",
"version": "1.3.0",
"private": true,
"type": "module",
"description": "Bilingual (EN/VI) directory of free and buy-once desktop software",
+36 -13
View File
@@ -10,11 +10,18 @@
// fixture (e2e/fixtures.ts) fails any test whose page logged a console error
// or a CSP violation.
//
// Not covered here, by design: _headers and the Worker (`astro preview`
// applies neither) — those are verified on the Workers Builds preview URL.
// `astro preview` applies neither _headers nor the Worker, so a second server
// does: `wrangler dev` on the same dist/ with the real wrangler.jsonc, for the
// `worker` project alone (e2e/worker.spec.ts — routing, the rate limits, the
// 429 page). Cloudflare's own edge is still verified on the Workers Builds
// preview URL.
import { defineConfig, devices } from '@playwright/test';
const PORT = 4321;
// Not wrangler's default 8787/8788: another project's `wrangler dev` may hold
// those, and reuseExistingServer would then test the wrong site.
const WORKER_PORT = 8799;
const WORKER_SPEC = /worker\.spec\.ts$/;
export default defineConfig({
testDir: 'e2e',
@@ -27,17 +34,33 @@ export default defineConfig({
trace: 'retain-on-failure',
},
projects: [
{ name: 'desktop', use: { ...devices['Desktop Chrome'] } },
{ name: 'desktop', use: { ...devices['Desktop Chrome'] }, testIgnore: WORKER_SPEC },
// Bottom sheets, the wrapped header and touch targets live here.
{ name: 'mobile', use: { ...devices['Pixel 7'] } },
{ name: 'mobile', use: { ...devices['Pixel 7'] }, testIgnore: WORKER_SPEC },
{
name: 'worker',
testMatch: WORKER_SPEC,
use: { ...devices['Desktop Chrome'], baseURL: `http://127.0.0.1:${WORKER_PORT}` },
},
],
webServer: [
{
command: `pnpm exec astro preview --port ${PORT} --host 127.0.0.1`,
url: `http://127.0.0.1:${PORT}`,
reuseExistingServer: !process.env['CI'],
timeout: 60_000,
// Astro ≥ 7.2 backgrounds `astro preview` when it detects an AI agent or
// CI; Playwright needs it in the foreground to own its lifetime.
env: { ASTRO_PREVIEW_BACKGROUND: '0' },
},
{
command: `pnpm exec wrangler dev --port ${WORKER_PORT} --ip 127.0.0.1 --show-interactive-dev-session=false`,
// An asset-first path (a negative pattern), so the readiness probes
// spend nothing from the rate limit the tests measure.
url: `http://127.0.0.1:${WORKER_PORT}/favicon.svg`,
reuseExistingServer: !process.env['CI'],
timeout: 90_000,
env: { WRANGLER_SEND_METRICS: 'false' },
},
],
webServer: {
command: `pnpm exec astro preview --port ${PORT} --host 127.0.0.1`,
url: `http://127.0.0.1:${PORT}`,
reuseExistingServer: !process.env['CI'],
timeout: 60_000,
// Astro ≥ 7.2 backgrounds `astro preview` when it detects an AI agent or
// CI; Playwright needs it in the foreground to own its lifetime.
env: { ASTRO_PREVIEW_BACKGROUND: '0' },
},
});
+2 -2
View File
@@ -68,8 +68,8 @@ const rows = [
<p>
{en
? 'Claude models developed by Anthropic, used through Claude Code — Anthropic’s command-line coding tool: Claude Opus 5 (model identifier claude-opus-5) for the site and catalogue through v1.0, and Claude Opus 5.5 (claude-opus-5-5) for the v1.1 and v1.2 work of October 2026. Earlier work on the project used Claude models through the same tool. No other AI system contributed to this site.'
: 'Các mô hình Claude do Anthropic phát triển, sử dụng qua Claude Code — công cụ lập trình dòng lệnh của Anthropic: Claude Opus 5 (mã định danh mô hình claude-opus-5) cho trang web và danh mục đến hết v1.0, và Claude Opus 5.5 (claude-opus-5-5) cho phần việc v1.1 và v1.2 vào tháng 10/2026. Các giai đoạn trước của dự án cũng dùng mô hình Claude qua chính công cụ này. Không có hệ thống AI nào khác tham gia vào trang web này.'}
? 'Claude models developed by Anthropic, used through Claude Code — Anthropic’s command-line coding tool: Claude Opus 5 (model identifier claude-opus-5) for the site and catalogue through v1.0, and Claude Opus 5.5 (claude-opus-5-5) for the v1.1, v1.2 and v1.3 work of October 2026. Earlier work on the project used Claude models through the same tool. No other AI system contributed to this site.'
: 'Các mô hình Claude do Anthropic phát triển, sử dụng qua Claude Code — công cụ lập trình dòng lệnh của Anthropic: Claude Opus 5 (mã định danh mô hình claude-opus-5) cho trang web và danh mục đến hết v1.0, và Claude Opus 5.5 (claude-opus-5-5) cho phần việc v1.1, v1.2 và v1.3 vào tháng 10/2026. Các giai đoạn trước của dự án cũng dùng mô hình Claude qua chính công cụ này. Không có hệ thống AI nào khác tham gia vào trang web này.'}
</p>
<h2>{en ? 'Where it was used' : 'Đã dùng ở đâu'}</h2>
+30 -5
View File
@@ -2,9 +2,10 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/14 §3b. The storage inventory here must stay in step with docs/09 §8,
// and the two Cloudflare sections with src/scripts/analytics.js and
// src/lib/turnstile.ts + worker/verify.ts. Section ids are link targets:
// the gate's step 2 links to #turnstile.
// the two Cloudflare sections with src/scripts/analytics.js and
// src/lib/turnstile.ts + worker/verify.ts, and #rate-limit with
// worker/limit.ts. Section ids are link targets: the gate's step 2 links to
// #turnstile.
import { CONTACTS } from '../../lib/contacts';
import type { Locale } from '../../i18n';
interface Props {
@@ -20,7 +21,8 @@ const PRIVACY = CONTACTS.privacy;
<strong>Short version:</strong> no accounts, no ads, no cookies, and nothing sold or shared
for advertising. Two Cloudflare services see limited data — visitor statistics that skip you
if your browser sends Global Privacy Control, and a bot check that runs only after you accept
these documents. Your settings stay in your browser.
these documents. To keep floods off the site, requests are counted per network address for a
few seconds, then forgotten. Your settings stay in your browser.
</p>
<h2 id="who">Who runs this site</h2>
@@ -91,6 +93,17 @@ const PRIVACY = CONTACTS.privacy;
service.
</p>
<h2 id="rate-limit">Rate limiting</h2>
<p>
So that one runaway script cannot crowd everyone else out, this site's own code counts the
requests for its pages, feeds and data per IP address (per /64 network for IPv6) over a window
of a few seconds. A network that sends far more than anyone reading the site would gets a "Too
many requests" page until the window passes. The counts are held by Cloudflare's rate limiter
for that window only; we keep no record of addresses — when a request is refused, the log says
only that it happened. We do this out of a legitimate interest in keeping a public service
available to everyone.
</p>
<h2 id="hosting">Hosting</h2>
<p>
Cloudflare serves the site and the endpoint above. As a network provider it processes
@@ -139,7 +152,8 @@ const PRIVACY = CONTACTS.privacy;
<strong>Tóm tắt:</strong> không tài khoản, không quảng cáo, không cookie, và không bán hay
chia sẻ dữ liệu cho quảng cáo. Hai dịch vụ của Cloudflare thấy một ít dữ liệu — thống kê truy
cập sẽ bỏ qua bạn nếu trình duyệt gửi tín hiệu Global Privacy Control, và một bước kiểm tra
bot chỉ chạy sau khi bạn chấp nhận các văn bản này. Các tuỳ chọn của bạn nằm lại trong trình
bot chỉ chạy sau khi bạn chấp nhận các văn bản này. Để chặn lưu lượng dồn dập, số yêu cầu được
đếm theo địa chỉ mạng trong vài giây rồi bỏ đi. Các tuỳ chọn của bạn nằm lại trong trình
duyệt.
</p>
@@ -212,6 +226,17 @@ const PRIVACY = CONTACTS.privacy;
lợi ích chính đáng: giữ cho một dịch vụ công cộng không bị lạm dụng tự động.
</p>
<h2 id="rate-limit">Giới hạn tần suất truy cập</h2>
<p>
Để một đoạn mã chạy mất kiểm soát không chiếm hết chỗ của mọi người khác, mã của chính trang
này đếm số yêu cầu tới các trang, nguồn tin (feed) và dữ liệu theo từng địa chỉ IP (theo dải
/64 với IPv6) trong một khoảng vài giây. Mạng nào gửi nhiều hơn hẳn mức của một người đọc bình
thường sẽ thấy trang "Quá nhiều yêu cầu" cho tới khi hết khoảng đó. Số đếm chỉ được bộ giới
hạn của Cloudflare giữ trong đúng khoảng thời gian ấy; chúng tôi không lưu lại địa chỉ nào —
khi một yêu cầu bị từ chối, nhật ký chỉ ghi rằng việc đó đã xảy ra. Chúng tôi làm vậy vì lợi
ích chính đáng: giữ cho một dịch vụ công cộng luôn dùng được với mọi người.
</p>
<h2 id="hosting">Lưu trữ và phân phối</h2>
<p>
Cloudflare phục vụ trang web và điểm xác minh nói trên. Với vai trò nhà cung cấp mạng,
+1 -1
View File
@@ -51,7 +51,7 @@
"error.403.title": "Access denied",
"error.404.body": "The link may be old, or the entry may have been removed — flagged apps are quarantined rather than kept live.",
"error.404.title": "That page isn't here",
"error.429.body": "You have been rate limited. The public dataset at /api/apps.json exists precisely so tools do not have to scrape the pages.",
"error.429.body": "Too many requests came from your network in a short time. Wait about ten seconds, then reload the page. Writing a tool? The public dataset at /api/apps.json has every app in one request — no need to scrape the pages.",
"error.429.title": "Too many requests",
"error.500.body": "SoftHarbor is a static site, so this should be impossible. If you are seeing it, the report button in the footer helps.",
"error.500.title": "Something broke",
+1 -1
View File
@@ -51,7 +51,7 @@
"error.403.title": "Truy cập bị từ chối",
"error.404.body": "Liên kết có thể đã cũ, hoặc mục tương ứng đã được gỡ — ứng dụng bị gắn cờ sẽ được đưa vào khu cách ly thay vì giữ lại.",
"error.404.title": "Không tìm thấy trang",
"error.429.body": "Bạn đã bị giới hạn tần suất truy cập. Bộ dữ liệu công khai tại /api/apps.json tồn tại để công cụ không phải quét từng trang.",
"error.429.body": "Mạng của bạn vừa gửi quá nhiều yêu cầu trong thời gian ngắn. Hãy đợi khoảng mười giây rồi tải lại trang. Nếu bạn đang viết công cụ: bộ dữ liệu công khai tại /api/apps.json chứa mọi ứng dụng trong một lần tải — không cần quét từng trang.",
"error.429.title": "Quá nhiều yêu cầu",
"error.500.body": "SoftHarbor là trang tĩnh nên lỗi này gần như không thể xảy ra. Nếu bạn gặp, hãy dùng nút báo lỗi ở chân trang.",
"error.500.title": "Đã xảy ra lỗi",
+5 -4
View File
@@ -19,9 +19,10 @@
* this constant still dated every page, it moved with the new AI
* Disclosure); 2026-10-21 (v1.1: the Privacy Policy now covers Cloudflare
* Web Analytics and the Turnstile check, and Terms gained the operator and a
* copyright-complaint procedure).
* copyright-complaint procedure); 2026-10-26 (v1.3: the Privacy Policy
* covers the site-wide rate limit, D32).
*/
export const LEGAL_VERSION = '2026-10-21';
export const LEGAL_VERSION = '2026-10-26';
export type LegalDoc =
'aiDisclosure' | 'disclaimer' | 'privacy' | 'terms' | 'thirdParty' | 'trademarks';
@@ -38,9 +39,9 @@ export const ACCEPTED_DOCS = [
* One date for all six used to stamp documents that had not changed.
*/
export const LEGAL_UPDATED: Readonly<Record<LegalDoc, string>> = {
aiDisclosure: '2026-10-23',
aiDisclosure: '2026-10-26',
disclaimer: '2026-10-21',
privacy: '2026-10-21',
privacy: '2026-10-26',
terms: '2026-10-21',
thirdParty: '2026-10-21',
trademarks: '2026-10-21',
+3 -3
View File
@@ -1,9 +1,9 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// Dormant (docs/08 Part C): rate limiting is deliberately OFF in v1
// (docs/16 §9), and on a Free zone a block would show Cloudflare's own page
// anyway. Kept as a config-only switch-on.
// Live since D32 (docs/08 Part C): the Worker's site-wide rate limit answers
// an over-limit page request with this page, status 429 and Retry-After
// (worker/limit.ts). Requested directly it is an ordinary 200, like /404.
import ErrorPage from '../../components/pages/ErrorPage.astro';
---
+11 -5
View File
@@ -1,17 +1,23 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/** A Workers Rate Limiting binding (`ratelimits` in wrangler.jsonc). */
export interface RateLimiter {
limit(options: { key: string }): Promise<{ success: boolean }>;
}
/**
* What the Worker receives (wrangler.jsonc). Typed by hand rather than with
* @cloudflare/workers-types: these three members are all it uses, and the
* global runtime types would collide with the DOM lib the site compiles
* against.
* @cloudflare/workers-types: these members are all it uses, and the global
* runtime types would collide with the DOM lib the site compiles against.
*/
export interface Env {
/** The static site itself (`assets.binding`). */
ASSETS: { fetch(request: Request): Promise<Response> };
/** Workers Rate Limiting (`ratelimits`). Absent under a bare `wrangler dev`. */
VERIFY_LIMITER?: { limit(options: { key: string }): Promise<{ success: boolean }> };
/** The site-wide limit (D32): every request that runs the Worker. Absent → no limit. */
SITE_LIMITER?: RateLimiter;
/** The stricter /api/verify limit (D25). Absent under a bare `wrangler dev`. */
VERIFY_LIMITER?: RateLimiter;
/**
* Turnstile secret key. A RUNTIME secret (`wrangler secret put
* TURNSTILE_SECRET` or the dashboard's Variables and Secrets) — a Workers
+16 -9
View File
@@ -1,29 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// The ONE piece of server code (CLAUDE.md hard rule 1, D25). It runs first
// only for the paths in `assets.run_worker_first` (wrangler.jsonc) — today
// just /api/verify. Every page, asset and feed is served by the asset server
// without running this, exactly as before it existed.
// The ONE piece of server code (CLAUDE.md hard rule 1, D25, D32). It runs
// first for the paths in `assets.run_worker_first` (wrangler.jsonc): every
// page, feed and data file, but not the content-hashed assets, icons or the
// service worker. It does two things and serves nothing of its own:
// 1. the site-wide rate limit (worker/limit.ts) — over it, a 429;
// 2. POST /api/verify, the legal gate's Turnstile check (worker/verify.ts).
// Everything else is handed straight to the asset server.
import type { Env } from './env';
import { siteLimit } from './limit';
import { handleVerify } from './verify';
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const log = (entry: Record<string, unknown>) => console.log(JSON.stringify(entry));
const refused = await siteLimit(request, env, log);
if (refused) return refused;
if (new URL(request.url).pathname === '/api/verify') {
return handleVerify(request, env, {
// Wrapped: calling the global fetch detached from globalThis throws
// "Illegal invocation" in workerd.
fetch: (input, init) => fetch(input, init),
now: Date.now,
log: (entry) => console.log(JSON.stringify(entry)),
log,
});
}
// A request that matched no asset and is not a navigation (a missing
// image or JSON file) still lands here — navigations get 404.html from
// the asset server directly. ASSETS.fetch() applies the same
// not_found_handling, so the answer is the site's normal 404.
// Exactly what the asset server would have answered without the Worker:
// ASSETS.fetch() applies html_handling, not_found_handling (the site's
// 404 page) and public/_headers — checked under `wrangler dev` and on a
// preview version, 2026-10-26.
return env.ASSETS.fetch(request);
},
};
+208
View File
@@ -0,0 +1,208 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// The site-wide rate limit (D32) against a stubbed limiter and asset server.
// The real binding, routing and _headers are exercised end to end by
// e2e/worker.spec.ts under `wrangler dev`.
import { unstable_readConfig } from 'wrangler';
import { describe, expect, it, vi } from 'vitest';
import type { Env, RateLimiter } from './env';
import worker from './index';
import { ERROR_PAGE, RETRY_AFTER_S, siteLimit } from './limit';
const ORIGIN = 'https://softharbor.net';
const IP = '203.0.113.7';
function get(path: string, init: { method?: string; ip?: string | null } = {}): Request {
const headers: Record<string, string> = {};
if (init.ip !== null) headers['cf-connecting-ip'] = init.ip ?? IP;
return new Request(`${ORIGIN}${path}`, { method: init.method ?? 'GET', headers });
}
/** The built 429 page, as the asset server returns it (headers from public/_headers). */
const errorPage = (req: Request) =>
new Response(req.method === 'HEAD' ? null : '<title>Too many requests — SoftHarbor</title>', {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'public, max-age=0, must-revalidate',
ETag: '"abc"',
'X-Frame-Options': 'DENY',
},
});
function setup(
success: boolean | Error = false,
assets = vi.fn(async (r: Request) => errorPage(r)),
) {
const limit = vi.fn<RateLimiter['limit']>(async () => {
if (success instanceof Error) throw success;
return { success };
});
const log = vi.fn();
const env: Env = { ASSETS: { fetch: assets }, SITE_LIMITER: { limit } };
return { env, limit, log, assets };
}
describe('siteLimit', () => {
it('lets a client under the limit through, counted by IPv4 address or IPv6 /64', async () => {
const s = setup(true);
expect(await siteLimit(get('/apps'), s.env, s.log)).toBeUndefined();
expect(await siteLimit(get('/apps', { ip: '2001:db8:1:2:3:4:5:6' }), s.env, s.log)).toBe(
undefined,
);
expect(s.limit.mock.calls).toEqual([[{ key: IP }], [{ key: '2001:db8:1:2::/64' }]]);
expect(s.assets).not.toHaveBeenCalled();
expect(s.log).not.toHaveBeenCalled();
});
it('answers an over-limit page request with the branded 429 page', async () => {
const s = setup();
const res = await siteLimit(get('/apps/7-zip'), s.env, s.log);
expect(res?.status).toBe(429);
expect(res?.headers.get('retry-after')).toBe(String(RETRY_AFTER_S));
expect(res?.headers.get('cache-control')).toBe('no-store');
expect(res?.headers.get('etag')).toBeNull();
// The asset server's own security headers are kept.
expect(res?.headers.get('x-frame-options')).toBe('DENY');
expect(await res?.text()).toContain('Too many requests');
const fetched = s.assets.mock.calls[0]![0];
expect(fetched.url).toBe(`${ORIGIN}${ERROR_PAGE}`);
expect(fetched.method).toBe('GET');
});
it('asks for the page with HEAD when the client did, and sends no body', async () => {
const s = setup();
const res = await siteLimit(get('/rss.xml', { method: 'HEAD' }), s.env, s.log);
expect(res?.status).toBe(429);
expect(s.assets.mock.calls[0]![0].method).toBe('HEAD');
expect(res?.body).toBeNull();
});
it('answers /api/* with JSON, CORS-readable for the public dataset', async () => {
const s = setup();
const res = await siteLimit(get('/api/apps.json'), s.env, s.log);
expect(res?.status).toBe(429);
expect(await res?.json()).toEqual({ error: 'rate_limited' });
expect(res?.headers.get('retry-after')).toBe(String(RETRY_AFTER_S));
expect(res?.headers.get('access-control-allow-origin')).toBe('*');
expect(res?.headers.get('access-control-expose-headers')).toBe('Retry-After');
expect(res?.headers.get('cache-control')).toBe('no-store');
expect(s.assets).not.toHaveBeenCalled();
});
it('keeps /api/verify same-origin when it refuses it', async () => {
const s = setup();
const res = await siteLimit(get('/api/verify', { method: 'POST' }), s.env, s.log);
expect(res?.status).toBe(429);
expect(await res?.json()).toEqual({ error: 'rate_limited' });
expect(res?.headers.get('access-control-allow-origin')).toBeNull();
});
it.each([
['a missing page', async () => new Response('nope', { status: 404 })],
[
'an asset server that throws',
async (): Promise<Response> => {
throw new Error('down');
},
],
])('still refuses in plain text when the 429 page is %s', async (_name, fetchPage) => {
const s = setup(false, vi.fn(fetchPage));
const res = await siteLimit(get('/apps'), s.env, s.log);
expect(res?.status).toBe(429);
expect(res?.headers.get('content-type')).toBe('text/plain; charset=utf-8');
expect(res?.headers.get('retry-after')).toBe(String(RETRY_AFTER_S));
expect(res?.headers.get('content-security-policy')).toContain("default-src 'none'");
expect(await res?.text()).toContain('429 Too Many Requests');
});
it('fails open: no binding, no client address, or a limiter that throws', async () => {
const none = setup();
expect(await siteLimit(get('/apps'), { ASSETS: none.env.ASSETS }, none.log)).toBeUndefined();
const anonymous = setup();
expect(await siteLimit(get('/apps', { ip: null }), anonymous.env, anonymous.log)).toBe(
undefined,
);
expect(anonymous.limit).not.toHaveBeenCalled();
const broken = setup(new Error('limiter down'));
expect(await siteLimit(get('/apps'), broken.env, broken.log)).toBeUndefined();
});
it('logs one line per refusal — its kind, never the address', async () => {
const s = setup();
await siteLimit(get('/apps'), s.env, s.log);
await siteLimit(get('/api/apps.json'), s.env, s.log);
expect(s.log.mock.calls).toEqual([
[{ event: 'rate_limited', kind: 'page' }],
[{ event: 'rate_limited', kind: 'api' }],
]);
expect(JSON.stringify(s.log.mock.calls)).not.toContain(IP);
});
});
describe('the Worker entry', () => {
it('checks the limit before anything else, /api/verify included', async () => {
const s = setup();
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
try {
const page = await worker.fetch(get('/apps'), s.env);
expect(page.status).toBe(429);
const verify = await worker.fetch(get('/api/verify', { method: 'POST' }), s.env);
expect(verify.status).toBe(429);
// Only the 429 page was fetched, never the page that was asked for.
expect(s.assets.mock.calls.map(([r]) => new URL(r.url).pathname)).toEqual([ERROR_PAGE]);
expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toEqual({
event: 'rate_limited',
kind: 'page',
});
} finally {
log.mockRestore();
}
});
it('hands a request under the limit to the asset server untouched', async () => {
const assets = vi.fn(async () => new Response('page'));
const s = setup(true, assets);
const req = get('/apps');
const res = await worker.fetch(req, s.env);
expect(await res.text()).toBe('page');
expect(assets).toHaveBeenCalledWith(req);
});
});
/** What these tests read of wrangler.jsonc (wrangler's own Config type does not resolve here). */
interface WranglerConfig {
assets?: { run_worker_first?: boolean | string[] };
ratelimits: { name: string; namespace_id: string; simple: { limit: number; period: number } }[];
}
describe('wrangler.jsonc', () => {
const config = unstable_readConfig(
{ config: 'wrangler.jsonc' },
{ hideWarnings: true },
) as WranglerConfig;
it('routes every request through the Worker except the files a page loads', () => {
const list = config.assets?.run_worker_first;
if (!Array.isArray(list)) throw new Error('run_worker_first must be a list of patterns');
expect(list).toContain('/*');
// A page that passed the limit must load whole: its scripts, styles and
// fonts (/_astro/) and the service worker never meet the limiter.
for (const path of ['/_astro/*', '/sw.js', '/registerSW.js', '/workbox-*.js']) {
expect(list).toContain(`!${path}`);
}
});
it('declares both limiters, and Retry-After matches the site window', () => {
const byName = Object.fromEntries(config.ratelimits.map((r) => [r.name, r]));
expect(byName['SITE_LIMITER']?.simple.period).toBe(RETRY_AFTER_S);
expect(byName['SITE_LIMITER']?.simple.limit).toBeGreaterThan(0);
expect(byName['VERIFY_LIMITER']?.simple).toEqual({ limit: 20, period: 60 });
// Counters are shared by namespace across the account: never reuse one.
const ids = config.ratelimits.map((r) => r.namespace_id);
expect(new Set(ids).size).toBe(ids.length);
});
});
+87
View File
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// The site-wide rate limit (D32). Every request that runs the Worker — every
// page, feed, sitemap, the search index and /api/* — spends one unit of a
// per-client budget (SITE_LIMITER, wrangler.jsonc) before anything else
// happens. Content-hashed assets, icons and the service worker never get
// here (`run_worker_first`'s negative patterns): they are only ever fetched
// by a page that already passed, so a page never half-loads because its CSS
// was refused, and they stay on the unbilled asset path.
//
// Like the rest of the Worker it fails OPEN: no binding, no client address,
// or a limiter that throws all serve the request as if there were no limit.
import type { Env } from './env';
import { json, rateKey, SECURITY_HEADERS } from './http';
/** SITE_LIMITER's `period` (wrangler.jsonc): a refused client may retry one window later. */
export const RETRY_AFTER_S = 10;
/** The branded, bilingual refusal (src/pages/errors/429.astro), served from the build. */
export const ERROR_PAGE = '/errors/429';
/**
* `undefined` when the request may go on, otherwise the 429 to answer with.
* `log` gets one line per refusal, never an IP address.
*/
export async function siteLimit(
request: Request,
env: Env,
log: (entry: Record<string, unknown>) => void,
): Promise<Response | undefined> {
// Without an address there is no client to tell apart, and one shared
// "unknown" bucket would throttle everyone in it together.
if (!env.SITE_LIMITER || !request.headers.get('cf-connecting-ip')) return undefined;
try {
if ((await env.SITE_LIMITER.limit({ key: rateKey(request) })).success) return undefined;
} catch {
return undefined;
}
const { pathname } = new URL(request.url);
const api = pathname.startsWith('/api/');
log({ event: 'rate_limited', kind: api ? 'api' : 'page' });
return api ? apiRefusal(pathname) : pageRefusal(request, env);
}
function apiRefusal(pathname: string): Response {
const headers: Record<string, string> = { 'Retry-After': String(RETRY_AFTER_S) };
// The public dataset is CORS-open (public/_headers), so its refusal must be
// too — otherwise a cross-origin consumer sees a network error instead of
// the 429 and its Retry-After. /api/verify is same-origin only.
if (pathname !== '/api/verify') {
headers['Access-Control-Allow-Origin'] = '*';
headers['Access-Control-Expose-Headers'] = 'Retry-After';
}
return json({ error: 'rate_limited' }, 429, headers);
}
async function pageRefusal(request: Request, env: Env): Promise<Response> {
try {
const page = await env.ASSETS.fetch(
new Request(new URL(ERROR_PAGE, request.url), {
method: request.method === 'HEAD' ? 'HEAD' : 'GET',
}),
);
if (page.ok) {
// The asset server's headers (public/_headers: frame-ancestors,
// nosniff, …) stay; only caching changes, because a refusal is about
// this client at this moment.
const headers = new Headers(page.headers);
headers.set('Cache-Control', 'no-store');
headers.set('Retry-After', String(RETRY_AFTER_S));
headers.delete('ETag');
return new Response(page.body, { status: 429, headers });
}
} catch {
// The plain refusal below still says what happened.
}
return new Response(`429 Too Many Requests — Quá nhiều yêu cầu. Retry in ${RETRY_AFTER_S} s.\n`, {
status: 429,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'no-store',
'Retry-After': String(RETRY_AFTER_S),
...SECURITY_HEADERS,
},
});
}
+45 -19
View File
@@ -1,15 +1,15 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "softharbor",
// D25 (docs/15): ONE small Worker, for POST /api/verify (the legal gate's
// Turnstile check) and nothing else. Pages, assets and feeds are still
// served by the asset server without invoking it, so they stay unbilled;
// see `run_worker_first` below and worker/index.ts.
// D25 + D32 (docs/15): ONE small Worker. It runs the site-wide rate limit
// and answers POST /api/verify (the legal gate's Turnstile check); every
// page, feed and file it lets through is still served by the asset server
// (env.ASSETS). See `run_worker_first` below and worker/index.ts.
"main": "./worker/index.ts",
// ≥ 2025-04-01 matters: from that date a NAVIGATION request that matches no
// asset gets dist/404.html straight from the asset server instead of
// invoking the Worker. (Other misses — a missing image or JSON — do reach
// the Worker, which hands them to ASSETS.fetch() for the same 404.)
// ≥ 2025-04-01 still matters on the asset-first paths below: there a
// NAVIGATION that matches no asset gets dist/404.html from the asset server
// directly, and any other miss reaches the Worker, which counts it and
// hands it to ASSETS.fetch() for the same 404.
"compatibility_date": "2026-10-01",
"assets": {
"directory": "./dist",
@@ -21,21 +21,47 @@
// alternate we emit. "drop-trailing-slash" makes the no-slash URL the one
// that serves 200 and redirects the slashed variant to it.
"html_handling": "drop-trailing-slash",
// The only path that runs the Worker before the asset server. Add to it
// only with a decision-log entry: every match is a billed invocation.
"run_worker_first": ["/api/verify"],
// D32: the Worker runs FIRST for every request — so each one passes the
// site-wide rate limit — EXCEPT the files below, which stay asset-first:
// never limited, never billed. A page fetches them only after it passed
// itself, so limiting them could only leave a page half-loaded, and
// content-hashed files are cached for a year anyway. Negative patterns
// win over `/*` regardless of order. Change this list only with a
// decision-log entry: every request it routes is a billed invocation.
"run_worker_first": [
"/*",
"!/_astro/*", // content-hashed JS, CSS and the self-hosted fonts
"!/icons/*",
"!/favicon.ico",
"!/favicon.svg",
"!/apple-touch-icon.png",
"!/manifest.webmanifest",
"!/sw.js",
"!/registerSW.js",
"!/workbox-*.js",
],
},
// Workers Rate Limiting for /api/verify: 20 verifications per minute per
// IPv4 address or IPv6 /64, per Cloudflare location. Generous on purpose —
// a school or office behind one NAT address is many people. namespace_id is
// account-wide; 4101 is not used by any other Worker on this account.
// Workers Rate Limiting, counted per IPv4 address or IPv6 /64 and per
// Cloudflare location (worker/http.ts rateKey). Generous on purpose: a
// school, an office or a mobile carrier's NAT puts many people behind one
// address. namespace_id is account-wide; 4101 and 4102 are used by no
// other Worker on this account (checked 2026-10-26).
"ratelimits": [
// Every request that runs the Worker (D32): 60 per 10 s is six a second,
// sustained — far above anyone reading the site, low enough to stop a
// flood or a runaway scraper. Over it: the branded 429 page (or JSON
// under /api/), Retry-After 10. Keep `period` equal to RETRY_AFTER_S in
// worker/limit.ts (a test holds them together).
{ "name": "SITE_LIMITER", "namespace_id": "4102", "simple": { "limit": 60, "period": 10 } },
// /api/verify on top of that (D25): 20 verifications per minute.
{ "name": "VERIFY_LIMITER", "namespace_id": "4101", "simple": { "limit": 20, "period": 60 } },
],
// Workers Logs keep the Worker's own one-line JSON events (outcome and
// duration, never an IP or token — worker/verify.ts). Invocation logs are
// off: they would add per-request metadata the Privacy Policy does not
// need us to hold.
// Workers Logs keep the Worker's own one-line JSON events — a verification's
// outcome and duration (worker/verify.ts), a rate-limit refusal's kind
// (worker/limit.ts) — never an IP or token. A request that passes logs
// nothing. Invocation logs stay off: now that every page runs the Worker
// they would be a log line per page view, holding per-request metadata the
// Privacy Policy does not need us to hold.
"observability": {
"enabled": true,
"logs": { "enabled": true, "invocation_logs": false },