15 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 b4555d13d2 chore(deps): November updates, minimatch 11 override, OSV ignore for deepmerge (#123)
- npm update within Dependabot's three-day cooldown (--before 2026-11-06):
  Astro 7.4.7, @astrojs/cloudflare 14.4.6, mdx 8.1.3, svelte 9.1.2,
  Svelte 5.57.3, Tailwind 4.3.4, jose 6.2.15, marked 18.1.3, Pagefind 1.6.0,
  Wrangler 4.158, ESLint 10.14, typescript-eslint 8.72.1, knip 6.44.
- overrides.minimatch ^11.0.4 for GHSA-g3hv-75wg-m249 (ESLint and
  typescript-eslint still ask for ^10; they only use Minimatch#match).
- osv-scanner.toml: ignore deepmerge GHSA-gcqx-w48m-w2h4 until 2027-02-09
  (no fixed release; build-time config merge only).
- knip.json: drop the obsolete cloudflare ignoreDependencies hint.
- CHANGELOG: 2.1.2.

Supersedes Dependabot #117-#122.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 07:23:08 +07:00
dependabot[bot] 886db0eae7 chore(deps): Bump SonarSource/sonarqube-scan-action from 8.3.0 to 8.4.0 (#116)
Bumps [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action) from 8.3.0 to 8.4.0.
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/d209202bc7d53ff1cc128f7f907dac145c9d6ae9...4d1dc0c91ee400dcf8a6dddf2f705ac36542e304)

---
updated-dependencies:
- dependency-name: SonarSource/sonarqube-scan-action
  dependency-version: 8.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-09 07:09:48 +07:00
github-actions[bot] 87749f009c chore(content): publish f81d476 (#115)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 22:22:02 +07:00
github-actions[bot] 0d9aa619db chore(content): publish dca7a8e (#114)
projects/omnideck.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 15:06:01 +00:00
github-actions[bot] 0c07890c57 chore(content): publish ce7d7fe (#113)
projects/omnideck.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 14:49:26 +00:00
github-actions[bot] c9ab55703b chore(content): publish fea9d71 (#112)
projects/omnideck.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 13:24:09 +00:00
github-actions[bot] 0940aafed2 chore(content): publish 04450d8 (#111)
projects/omnideck.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 19:52:23 +07:00
github-actions[bot] 64d69b5fe5 chore(content): publish efc0e60 (#110)
now/now-en.md
now/now.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 12:31:19 +00:00
github-actions[bot] 12cd8129d5 chore(content): publish 76e032d (#109)
gallery-photos/game.json

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 12:18:52 +00:00
github-actions[bot] cff21e1070 chore(content): publish b9beab8 (#108)
projects/omnideck.md

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-10-30 11:57:34 +00:00
poli0981andClaude Opus 5.5 444e0e43e9 Fix iPhone-only bugs: invisible Waveline, page showing above the header (#107)
Two bugs seen only on iPhone (Safari, iOS 26):

- The resting Waveline drew nothing in WebKit. Its gradient used the
  default objectBoundingBox units, and a flat line's bounding box is 0 px
  tall, so WebKit drops the gradient and the stroke with it (Chrome draws
  it anyway). The footer, section headings and error pages showed an
  empty band. Both gradients now use userSpaceOnUse across the viewBox.
- Safari 26 shows the page under the status bar and extends a sticky
  header's colour up to the edge, but its fixed-container sampling
  (LocalFrameView::fixedContainerEdges) bails out to "multiple colours"
  when the container has a backdrop-filter, so the page scrolled into view
  above the header. The site header, mobile tab bar and admin bar drop
  the blur and use opaque backgrounds.

CHANGELOG 2.1.1; Sonar project version 2.1.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:13:46 +07:00
poli0981andClaude Opus 5.5 846e5ec17d Site-wide rate limit: 429 for every request the Worker sees (#106)
* feat(security): site-wide rate limit for every request the Worker sees

Only the /api groups were rate-limited; pages, /media, /ext-img and the
search index had no limit at all (a 200-request burst against production
answered 200 every time). A new RL_SITE binding (100 requests per 10 s per
client, IPv6 per /64) is checked by the Worker entry right after the IP
denylist. Over it: the 429 page, no-store, Retry-After: 10, its countdown
rewritten to 10 s. The admin host is exempt (behind Access, RL_ADMIN per
account). A throwing limiter fails open without skipping the Turnstile gate.

- tests: worker spam/keys/exemptions/fail-open; Retry-After constants are
  checked against the periods in wrangler.jsonc
- smoke: a fourth phase spams the built Worker until the limit answers
- scripts/probe-ratelimit.mjs: tell the Worker's 429 from the WAF's 1015
- docs 06/07/02/09/00: three layers (WAF → RL_SITE → /api groups) and the
  Free plan's real WAF limits; CHANGELOG 2.1.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(sonar): project version 2.1.0 for the release

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(worker): stay a 429 if the rate-limit page can't be built

Review follow-ups on the site-wide limit:
- If fetching or rewriting the 429 page threw, the error reached the edge
  fail-open path, which hands the request to the Astro app and skips the
  Turnstile gate. It now answers a plain-text 429 (no-store, Retry-After).
- Drop Last-Modified and Content-Length with the ETag, as the gate does:
  the countdown rewrite only kept the length by luck ("60" vs "10").
- Docs: the WAF rule can't filter by host on Free, so it counts admin.*
  too; 09 lists the worker entry as a 429 source and the probe checks;
  CHANGELOG says what was unlimited before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:34:15 +07:00
poli0981andClaude Opus 5.5 bf66593c7d Faster first paint on phones: inline CSS, idle hydration (#105)
* perf: inline page CSS, hydrate the theme toggle and hero wave when idle

Lighthouse puts every page's LCP (a text block) about 2.4 s after the
first byte on a throttled phone, almost all of it render delay: two
render-blocking stylesheets (34 KB raw, 9 KB brotli) cost a round trip
before first paint, and the theme toggle's client:load pulled the Svelte
runtime into the same window on every page.

Inline every page's CSS (build.inlineStylesheets "always"; the CSP check
still finds every style block hashed) and hydrate ThemeToggle and the
home hero's Waveline on idle: CSS already shows the toggle's icon from
data-theme-pref, and the wave renders as a flatline until it hydrates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(lighthouse): measure through a compressing proxy, like production

astro preview serves HTML, CSS and JS uncompressed; Cloudflare's edge
compresses every text response with brotli. Measured straight off the
preview, the simulated phone downloaded three to four times the bytes a
real one does (home HTML 108 KB vs 25 KB), so LCP overshot on transfer
time alone. scripts/compress-proxy.mjs sits in front of the preview in
the Lighthouse job and compresses text responses with br or gzip; fonts,
images, redirects and HEAD pass through untouched.

Docs 14 and the changelog describe the inline CSS, the idle islands and
how CI now measures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(lighthouse): compress through nginx instead of a Node proxy

Sonar's taint rules flagged the hand-written proxy (the request URL and
upstream headers flowing into an outgoing request and into response
headers: S5144, S5146, S6109) and failed the gate, though it only ever
joined two ports on the CI runner. nginx is preinstalled on the Ubuntu
runner: the step writes a short config that gzips text responses from
the preview and listens on 127.0.0.1 only. gzip is a little larger than
the edge's brotli, so the numbers stay slightly pessimistic.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 13:58:43 +07:00
poli0981andClaude Opus 5.5 8aa760a5af fix(i18n): serve an English 404 page under /en/ (#104)
Any missing /en/ path got the Vietnamese 404 page. Both 404s now share
components/pages/NotFoundPage.astro (links, recent posts and a search
over the page language's Pagefind index, the heading echoed in the other
language), and ErrorLayout takes a locale.

The asset layer answers a miss with the nearest 404.html up the path, so
an integration moves Astro's en/404/index.html to en/404.html. The Worker
now returns that asset 404 for every missing page instead of handing it
to the app, whose localized error page lookup (/en/404/index) is answered
with a redirect. A test keeps every on-demand route under APP_PREFIXES,
which is what makes skipping the app safe.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 13:27:21 +07:00
poli0981andClaude Opus 5.5 edd1ad7ca8 docs(changelog): the public launch is tagged v1-launch (#103)
The 1.x heading said "untagged", but the launch has a tag and a GitHub
Release. Say that only the later 1.x changes were not tagged, and point
the [1.x] reference (dangling until now) at that release.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 12:29:37 +07:00
42 changed files with 2259 additions and 1529 deletions

No files matched your search

+1 -1
View File
@@ -160,7 +160,7 @@ jobs:
# quality gate and fails with it, so a red gate is visible on the PR; on main it only
# reports (the gate there is a trend, not a merge decision).
- name: SonarCloud scan
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
uses: SonarSource/sonarqube-scan-action@4d1dc0c91ee400dcf8a6dddf2f705ac36542e304 # v8.4.0
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
+34 -5
View File
@@ -50,10 +50,39 @@ jobs:
- name: Start preview server
run: npm run preview &
# Cloudflare's edge compresses every text response in production; the preview does not.
# Lighthouse measures through nginx (preinstalled on the runner, gzip — a little larger
# than the edge's brotli) so its simulated phone downloads about the bytes a real one
# would (home HTML 108 KB raw, 25–30 KB compressed), not three to four times as many.
- name: Start compressing proxy
run: |
cat > "$RUNNER_TEMP/nginx.conf" <<'EOF'
events {}
http {
access_log off;
gzip on;
gzip_proxied any;
gzip_comp_level 6;
gzip_vary on;
gzip_types text/css text/javascript application/javascript application/json
application/manifest+json application/xml image/svg+xml;
server {
listen 127.0.0.1:4322;
location / {
proxy_pass http://localhost:4321;
proxy_http_version 1.1;
proxy_set_header Accept-Encoding "";
}
}
}
EOF
sudo nginx -t -c "$RUNNER_TEMP/nginx.conf"
sudo nginx -c "$RUNNER_TEMP/nginx.conf"
- name: Wait for the server
run: |
for i in $(seq 1 60); do
if curl -sf -o /dev/null http://localhost:4321/; then
if curl -sf -o /dev/null http://127.0.0.1:4322/; then
echo "preview up after ${i}s"; exit 0
fi
sleep 1
@@ -69,9 +98,9 @@ jobs:
with:
configPath: ./lighthouserc.json
urls: |
http://localhost:4321/
http://localhost:4321/blog/lan-dau-viet-truyen/
http://localhost:4321/truyen/dem-khong-tieng/chuong-01/
http://localhost:4321/gallery/game/
http://127.0.0.1:4322/
http://127.0.0.1:4322/blog/lan-dau-viet-truyen/
http://127.0.0.1:4322/truyen/dem-khong-tieng/chuong-01/
http://127.0.0.1:4322/gallery/game/
uploadArtifacts: true
artifactName: lighthouse-reports
+79 -1
View File
@@ -5,6 +5,77 @@ milestones. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.
Content changes (posts, stories, albums) live in [`poli0981/content`](https://github.com/poli0981/content)
and are not listed here.
## [Unreleased]
## [2.1.2] — 2026-11-09
### Security
- Lint tooling runs on minimatch 11.0.5 instead of 10.2.5, which carried a denial of service
through crafted glob patterns (GHSA-g3hv-75wg-m249). ESLint and typescript-eslint still ask for
minimatch 10, so an `overrides` entry in `package.json` holds 11 until they move; they only call
`new Minimatch(…).match()` and `minimatch()`, which 11 keeps.
- The OSV scan ignores deepmerge's prototype-poisoning advisory (GHSA-gcqx-w48m-w2h4) until
2027-02-09, in the new `osv-scanner.toml`. No fixed release exists, and the only copy merges this
repo's own Svelte config at build time; nothing from a visitor reaches it. These two advisories
had kept the weekly scan, and every Dependabot PR, red since 2026-11-02.
### Changed
- Dependencies: Astro 7.4.7, @astrojs/cloudflare 14.4.6, @astrojs/mdx 8.1.3, @astrojs/svelte
9.1.2, Svelte 5.57.3, Tailwind CSS 4.3.4, jose 6.2.15, marked 18.1.3 and Pagefind 1.6.0; Wrangler
4.158, ESLint 10.14, typescript-eslint 8.72.1, knip 6.44 and the SonarCloud scan action 8.4.0.
Releases younger than three days were held back, as Dependabot's cooldown does.
- knip no longer needs `cloudflare` in `ignoreDependencies`; it now reads `cloudflare:workers`
imports as a runtime module.
## [2.1.1] — 2026-10-28
### Fixed
- iPhone: the Waveline is visible again while it rests. Its gradient was sized to the line's
bounding box, which is 0 px tall for a flat line, and WebKit then draws nothing — the footer,
the section headings and the error pages showed an empty band where the line belongs. Chrome
drew it anyway, so only iOS browsers were affected.
- iPhone (Safari 26): the page no longer scrolls into view above the sticky header, under the
status bar. Safari extends a sticky header's colour up to the screen edge only when the header
has no `backdrop-filter`; the header, the mobile tab bar and the admin bar dropped the blur
and are now opaque.
## [2.1.0] — 2026-10-27
### Security
- **Site-wide rate limit.** Every request that reaches the Worker — pages, `/media`, `/ext-img`,
the search index and the API — now spends one budget per client: 100 requests per 10 seconds
(IPv6 counted per /64), a new `RL_SITE` binding in `wrangler.jsonc`. Over it, visitors get the
site's 429 page with `Retry-After: 10` and a 10-second countdown; the stricter per-endpoint
API limits still apply underneath. Before, only the API groups were limited — pages, images,
the search index and the widgets endpoint were not. The admin host is exempt (Cloudflare Access
stands in front of it), and a failing limiter lets requests through without skipping the
Turnstile gate.
- Setup docs describe the zone WAF rate-limiting rule as the outer layer above it, with the Free
plan's real limits (path and verified-bot fields, 10-second periods and blocks).
### Added
- `npm run probe:ratelimit` spams a live URL and tells the Worker's 429s apart from the WAF's.
The CI smoke test now spams the built Worker until the site-wide limit answers.
### Changed
- Faster first paint on phones: every page carries its CSS inline (about 9 KB brotli) instead of
two render-blocking stylesheets, and the theme toggle and the home page's hero wave hydrate
when the browser is idle rather than during first paint.
- Lighthouse CI measures through nginx, which gzips responses as Cloudflare's edge compresses them
in production; the local preview server sends everything uncompressed.
### Fixed
- A missing page under `/en/` gets an English 404 page — English links, recent posts and a
search over the English index — instead of the Vietnamese one. The Worker now returns the
asset layer's 404 for every missing page rather than rendering it again through the app.
## [2.0.0] — 2026-10-24
A platform upgrade, a security pass, a new palette and a rebuilt admin
@@ -79,7 +150,9 @@ A platform upgrade, a security pass, a new palette and a rebuilt admin
- Dozens of smaller issues found by SonarCloud and the new tests (error pages served with the
wrong status under `astro dev`, regex backtracking, scripts that passed without checking).
## [1.x] — 2026-07 → 2026-10 (untagged)
## [1.x] — 2026-07 → 2026-10
The public launch is tagged `v1-launch`; the 1.x changes after it were not tagged.
- **2026-07** — Bilingual Astro + Cloudflare Workers site: blog, stories with reading controls and
content warnings, projects, dev/uses, gaming, Q&A, links, legal pages; Pagefind search; RSS,
@@ -91,4 +164,9 @@ A platform upgrade, a security pass, a new palette and a rebuilt admin
- **2026-10** — Custom Worker entry in front of every page; Workers Rate Limiting; Web Analytics;
topic email aliases; R2 media; the Turnstile gate; the admin at `admin.poli0981.dev`.
[Unreleased]: https://github.com/poli0981/poli0981-dev/compare/v2.1.2...HEAD
[2.1.2]: https://github.com/poli0981/poli0981-dev/compare/v2.1.1...v2.1.2
[2.1.1]: https://github.com/poli0981/poli0981-dev/compare/v2.1.0...v2.1.1
[2.1.0]: https://github.com/poli0981/poli0981-dev/compare/v2.0.0...v2.1.0
[2.0.0]: https://github.com/poli0981/poli0981-dev/releases/tag/v2.0.0
[1.x]: https://github.com/poli0981/poli0981-dev/releases/tag/v1-launch
+1
View File
@@ -65,6 +65,7 @@ identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.d
| `npm run lint` · `npm run format:check` · `npm run knip` | ESLint · Prettier · unused files/exports |
| `npm test` · `npm run test:coverage` | `node:test` suites; coverage writes `coverage/lcov.info` (80% line floor) |
| `npm run smoke` | Runs the built Worker with `wrangler dev` and probes pages, headers, the gate and the denylist |
| `npm run probe:ratelimit -- [url] [requests] [parallel]` | Spams a live URL and counts 429s from the Worker's site-wide limit vs. the WAF rule |
| `npm run new:post` | Scaffold a post or story from `docs/templates/` |
| `npm run check-exif` · `npm run strip-exif` | Refuse / remove GPS and camera metadata in images |
| `npm run gen-notices` | Regenerate `THIRD-PARTY-NOTICES.md` (CI checks it) |
+30
View File
@@ -5,6 +5,9 @@ import svelte from "@astrojs/svelte";
import mdx from "@astrojs/mdx";
import sitemap from "@astrojs/sitemap";
import tailwindcss from "@tailwindcss/vite";
import { existsSync } from "node:fs";
import { rename, rmdir } from "node:fs/promises";
import { DEFAULT_LOCALE, LOCALES } from "./src/i18n/routing.ts";
import { THEME_BOOTSTRAP } from "./src/lib/theme.ts";
// Error/system pages that must never appear in the sitemap.
@@ -34,6 +37,27 @@ const themeBootstrap = {
},
};
// A miss is answered by the asset layer with the nearest 404.html up the path (wrangler.jsonc
// `not_found_handling: "404-page"`), so a locale's own 404 page has to be a file named
// 404.html in that locale's folder. Astro writes only the root error pages that way —
// src/pages/en/404.astro lands at en/404/index.html — so move the localized ones into place.
// A locale without a 404 page of its own keeps getting the root one.
/** @type {import('astro').AstroIntegration} */
const localizedNotFound = {
name: "localized-404",
hooks: {
"astro:build:done": async ({ dir }) => {
for (const locale of LOCALES.filter((l) => l !== DEFAULT_LOCALE)) {
const built = new URL(`${locale}/404/index.html`, dir);
if (!existsSync(built)) continue;
await rename(built, new URL(`${locale}/404.html`, dir));
await rmdir(new URL(`${locale}/404/`, dir));
}
},
},
};
// Cloudflare Web Analytics beacon: only in builds made by Workers Builds for main
// (WORKERS_CI / WORKERS_CI_BRANCH are injected there), so CI, Lighthouse and branch
// previews never report page views. Overridable with PUBLIC_CF_BEACON=true|false.
@@ -52,6 +76,11 @@ export default defineConfig({
// `export const prerender = false` (only api routes + middleware run on-demand).
output: "static",
// Every page's CSS goes inline (about 9 KB brotli): the two shared stylesheets were the
// only render-blocking requests, costing a round trip before first paint on a phone.
// Astro hashes the inlined <style> blocks into the CSP like any other.
build: { inlineStylesheets: "always" },
// Astro's prefetch is off by default, but <ClientRouter /> force-enables it with
// `prefetchAll: true` + a hover strategy. Cloudflare's zone-level Speculation Rules
// then answers every `Sec-Purpose: prefetch` request to a Worker origin with a 503
@@ -113,6 +142,7 @@ export default defineConfig({
integrations: [
themeBootstrap,
localizedNotFound,
svelte(),
mdx(),
sitemap({
-1
View File
@@ -1,6 +1,5 @@
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"ignoreDependencies": ["cloudflare"],
"entry": ["workers/widgets/src/index.ts", "scripts/*.mjs", "tests/support/**/*.{mjs,ts}"],
"ignore": ["public/sw.js", "public/skullhop.js", "public/gate.js"]
}
+21
View File
@@ -0,0 +1,21 @@
# OSV-Scanner reads this file from the directory of the scanned lockfile
# (.github/workflows/osv-scanner.yml scans package-lock.json at the repo root).
#
# Every entry needs a reason and an ignoreUntil date, so an ignore expires on
# its own and the weekly scan turns red again for another look.
# deepmerge <= 4.3.1: mergeObject() can return objects with a poisoned prototype.
# No patched release exists (4.3.1 is the latest, from 2023). The only path to it
# is @astrojs/svelte → @sveltejs/vite-plugin-svelte, which merges this repo's own
# Svelte/Vite config at build time. Nothing from a visitor or the network reaches
# it, and it is not part of the Worker bundle. Recheck when vite-plugin-svelte
# drops deepmerge or a fixed version ships.
[[IgnoredVulns]]
id = "GHSA-gcqx-w48m-w2h4"
ignoreUntil = 2027-02-09
reason = "Build-time only (vite-plugin-svelte merges our own config); no patched deepmerge release exists."
[[IgnoredVulns]]
id = "CVE-2026-93753"
ignoreUntil = 2027-02-09
reason = "Alias of GHSA-gcqx-w48m-w2h4 (deepmerge); same reasoning."
+1426 -1273
View File
File diff suppressed because it is too large. Load diff
+18 -16
View File
@@ -18,6 +18,7 @@
"build": "astro build && node scripts/gen-og.mjs && pagefind --site dist/client && node scripts/check-csp-hashes.mjs",
"check-csp": "node scripts/check-csp-hashes.mjs",
"smoke": "node scripts/smoke-worker.mjs",
"probe:ratelimit": "node scripts/probe-ratelimit.mjs",
"test": "node --import ./tests/support/register.mjs --test \"tests/**/*.test.ts\"",
"pretest:coverage": "node -e \"require('node:fs').mkdirSync('coverage', { recursive: true })\"",
"test:coverage": "node --import ./tests/support/register.mjs --test --experimental-test-coverage --test-coverage-include=\"src/**/*.ts\" --test-coverage-include=\"workers/widgets/src/**/*.ts\" --test-coverage-exclude=\"**/*.d.ts\" --test-coverage-exclude=\"src/lib/easter.ts\" --test-coverage-exclude=\"src/content.config.ts\" --test-coverage-lines=80 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info \"tests/**/*.test.ts\"",
@@ -41,39 +42,40 @@
},
"overrides": {
"fflate": "^0.7.5",
"minimatch": "^11.0.4",
"sharp": "$sharp",
"miniflare": {
"undici": "^7.30.1"
}
},
"dependencies": {
"@astrojs/cloudflare": "^14.4.2",
"@astrojs/mdx": "^8.1.1",
"@astrojs/cloudflare": "^14.4.6",
"@astrojs/mdx": "^8.1.3",
"@astrojs/rss": "^4.0.19",
"@astrojs/sitemap": "^3.7.4",
"@astrojs/svelte": "^9.1.1",
"@tailwindcss/vite": "^4.3.3",
"astro": "^7.4.2",
"jose": "^6.2.13",
"marked": "^18.1.1",
"@astrojs/svelte": "^9.1.2",
"@tailwindcss/vite": "^4.3.4",
"astro": "^7.4.7",
"jose": "^6.2.15",
"marked": "^18.1.3",
"sharp": "^0.35.5",
"svelte": "^5.57.2",
"tailwindcss": "^4.3.3",
"svelte": "^5.57.3",
"tailwindcss": "^4.3.4",
"yaml": "^2.9.1",
"zod": "^4.6.7"
},
"devDependencies": {
"@astrojs/check": "^0.9.12",
"@resvg/resvg-js": "^2.6.2",
"@types/node": "^26.6.5",
"@types/node": "^26.6.6",
"@typescript/native": "npm:typescript@^7.0.2",
"eslint": "^10.13.0",
"eslint": "^10.14.0",
"eslint-plugin-astro": "^3.2.1",
"eslint-plugin-svelte": "^3.23.1",
"eslint-plugin-svelte": "^3.24.0",
"exifr": "^7.1.3",
"knip": "^6.42.1",
"knip": "^6.44.1",
"lefthook": "^2.2.2",
"pagefind": "^1.5.2",
"pagefind": "^1.6.0",
"prettier": "^3.9.10",
"prettier-plugin-astro": "^0.14.1",
"prettier-plugin-svelte": "^4.1.1",
@@ -81,7 +83,7 @@
"satori": "^0.63.2",
"satori-html": "^0.3.2",
"typescript": "~6.0.3",
"typescript-eslint": "~8.72.0",
"wrangler": "^4.152.0"
"typescript-eslint": "~8.72.1",
"wrangler": "^4.158.0"
}
}
+1 -1
View File
@@ -46,7 +46,7 @@
| D9 | API ngoài | Không weather/map; widget YouTube + Steam + GitHub qua cron worker |
| D11 | Email | Google Workspace (MX Google), một hộp thư + alias theo chủ đề (`07` §11). Không Cloudflare Email Routing |
| D12 | Chống bot | **Cổng Turnstile** trước mọi trang, vé 48 giờ (`06` §3b); bot đã xác thực đi thẳng nhờ Transform Rule `x-verified-bot` |
| D13 | Rate limit | Workers Rate Limiting bindings theo nhóm `/api` (`06` §2) thay bộ đếm KV |
| D13 | Rate limit | WAF rule (edge) → Workers Rate Limiting: RL_SITE toàn site 100/10s → bindings theo nhóm `/api` (`06` §2, `07` §6) thay bộ đếm KV |
| D14 | Analytics | Cloudflare Web Analytics, **snippet thủ công** chỉ ở bản build production (`07` §12) |
| D15 | Admin | `admin.poli0981.dev` sau Cloudflare Access + Worker tự kiểm JWT (≤ 24 giờ, email phải có trong `ADMIN_EMAILS` — thiếu là từ chối); token GitHub chỉ ghi repo content; ảnh → Images binding → R2; mọi thao tác ghi audit log (`06` §9) |
| D10 | Data services | **KV** (cache widget + ảnh widget mirror cho `/ext-img`, denylist một khoá, audit log admin) + **R2** `poli0981-media` cho ảnh upload qua admin (từ 10/2026; AVIF/WebP sinh một lần lúc upload, phục vụ qua `/media`, cache 1 năm). Không D1. Ảnh build-time cũ vẫn ở `src/assets/` |
+6 -5
View File
@@ -11,12 +11,13 @@ Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Trans
src/worker.ts — entry của Worker (assets.run_worker_first: mọi trang đều qua đây)
├── www → apex (301)
├── denylist IP (KV, một khoá "denylist", CIDR + hạn) → trang 403
├── rate limit toàn site RL_SITE 100/10s/IP (trừ admin.*) → trang 429
├── tách host: admin.poli0981.dev chỉ /admin*, /api/admin*, /media/*
├── /media/* → R2 poli0981-media (ảnh upload qua admin, cache 1 năm)
├── /ext-img/* → KV widgets:img:* (ảnh widget đã mirror; không gọi Google/Steam)
├── cổng Turnstile (vé 48 giờ) → trang xác minh thay <body>
├── trang tĩnh → ASSETS (dist/)
└── còn lại → app Astro (@astrojs/cloudflare/handler)
├── trang tĩnh → ASSETS (dist/) — trang không có ⇒ 404.html gần nhất (en/404.html dưới /en/)
└── /api/*, /admin* → app Astro (@astrojs/cloudflare/handler)
├── middleware: admin (Access JWT + CSRF), rate limit /api, trang lỗi
├── /api/report · /api/gate · /api/widgets · /api/health
└── /admin/* + /api/admin/* (GitHub API → repo content, R2, Images, KV)
@@ -54,7 +55,7 @@ poli0981-dev/
├── scripts/ # gen-og, gen-notices, check-exif/strip-exif, check-csp-hashes,
│ # check-install-scripts, smoke-worker, new-post
├── src/
│ ├── worker.ts # entry: denylist, host, /media, /ext-img, cổng, assets
│ ├── worker.ts # entry: denylist, rate limit site, host, /media, /ext-img, cổng, assets
│ ├── middleware.ts # admin JWT + CSRF, rate limit /api, trang lỗi
│ ├── assets/ # ảnh qua pipeline Astro (gallery/, covers/)
│ ├── components/ # .astro + islands .svelte
@@ -80,7 +81,7 @@ poli0981-dev/
- **Một thân trang cho hai ngôn ngữ**: route vi và en chỉ là wrapper gọi component trong `src/components/pages/` với `locale` (và props từ builder `getStaticPaths` trong `src/lib/pages.ts`).
- Nút đổi ngôn ngữ: trang có bản dịch (`translationKey`) → đúng bản dịch; không có → mục tương ứng của ngôn ngữ kia (`sectionFallbackPath`), không bao giờ 404.
- Truyện: chương thuộc series → `/truyen/<series>/<slug>/`; truyện lẻ (không có thư mục series) → `/truyen/<slug>/`.
- 404: `src/pages/404.astro`; cấu hình assets `not_found_handling: "404-page"`.
- 404: `src/pages/404.astro` (vi) và `src/pages/en/404.astro`, cùng thân `components/pages/NotFoundPage.astro`. Assets `not_found_handling: "404-page"` trả `404.html` gần nhất theo đường dẫn, nên integration `localized-404` (astro.config.mjs) dời bản en từ `en/404/index.html` sang `en/404.html`; worker trả nguyên response 404 đó (app Astro chỉ nhận `/api/*`, `/admin*` — test canh mọi route `prerender = false` nằm trong `APP_PREFIXES`).
## 5. Worker "site" — wrangler.jsonc (rút gọn)
@@ -94,7 +95,7 @@ poli0981-dev/
"assets": { "binding": "ASSETS", "directory": "./dist", "not_found_handling": "404-page",
"html_handling": "auto-trailing-slash", "run_worker_first": ["/*", "!/_astro/*", "…"] },
"kv_namespaces": [{ "binding": "KV", "id": "…" }],
"ratelimits": [ RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ],
"ratelimits": [ RL_SITE 100/10s · RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ],
"vars": { "GATE_MODE": "on", "ACCESS_TEAM_DOMAIN": "…", "ACCESS_AUD": "…", "REPORT_REPO": "poli0981/site-reports" },
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "poli0981-media" }],
"images": { "binding": "IMAGES" },
+1 -1
View File
@@ -15,7 +15,7 @@
| `/legal/{terms,privacy,disclaimer,third-party,licenses,ai-usage}` | `/en/legal/...` | `legal/*.md` (repo content) |
| `/now` | `/en/now` | now |
| `/rss.xml`, `/blog/rss.xml`, `/truyen/rss.xml`, `/sitemap-index.xml`, `/robots.txt`, `/.well-known/security.txt` | | |
| `/404`, `/500`, `/403`, `/429`, `/offline` | song ngữ trong 1 trang | 09 |
| `/404` (+ bản en cho mọi đường dẫn `/en/…`), `/500`, `/403`, `/429`, `/offline` | tiêu đề chính + dòng ngôn ngữ kia; 404 có bản riêng mỗi ngôn ngữ | 09 |
| `admin.poli0981.dev`: `/admin/` (tổng quan), `/admin/content/`, `/admin/edit/`, `/admin/media/`, `/admin/gallery/`, `/admin/activity/`, `/admin/security/` | chỉ vi | on-demand, sau Access (`06` §9) |
## 2. Wireframe chính (mobile-first)
+7 -2
View File
@@ -23,7 +23,11 @@ request → src/worker.ts (mọi route, cả trang tĩnh)
1. denylist: MỘT khoá KV "denylist" = [{cidr, reason?, until?, added?}]
đọc tối đa 1 lần/phút/isolate (+ cacheTtl 60 s ở colo); IP hoặc dải CIDR (IPv4/IPv6),
mục hết hạn bị bỏ qua → khớp ⇒ 403 (trang 09 §2, no-store) · KV lỗi ⇒ bỏ qua (fail-open, có log)
2. app Astro — middleware, nếu path bắt đầu /api/<group>:
2. rate limit toàn site: RL_SITE 100/10s, khoá "site:<ip>" (IPv6 gộp /64), cho MỌI request
tới Worker — trang, /media, /ext-img, /pagefind, /api — trừ host admin.* (đã có Access)
vượt ⇒ 429 + Retry-After: 10, đếm ngược 10 s · binding lỗi ⇒ bỏ qua (fail-open, có log,
không bỏ qua cổng Turnstile)
3. app Astro — middleware, nếu path bắt đầu /api/<group>:
Workers Rate Limiting binding theo nhóm (src/lib/ratelimit.ts), khoá "<group>:<ip>"
(IPv6 gộp theo /64):
report → RL_REPORT 5/60s · gate → RL_GATE 30/60s · admin → RL_ADMIN 120/60s
@@ -32,7 +36,8 @@ request → src/worker.ts (mọi route, cả trang tĩnh)
```
- Một khoá thay vì `denylist:<ip>`: tra cứu tốn như nhau dù IP nào hỏi (một lần đọc/phút/isolate) và chặn được cả dải. Quản lý ở **admin → Bảo mật** (`/admin/security/`): thêm kèm lý do + thời hạn (1 giờ … 30 ngày, hoặc đến khi gỡ), gỡ, có audit log. Không cho chặn dải chứa IP của chính admin — danh sách áp cho mọi host, kể cả admin. Thay đổi có hiệu lực trong khoảng một phút.
- Binding rate limit đếm **theo từng colo** và chỉ cho `period` 10 hoặc 60 s → lớp mềm; lớp cứng là zone rate-limit rule (07 §6). `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981004).
- Binding rate limit đếm **theo từng colo**, gần đúng (burst có thể lọt quá ngưỡng một chút) và chỉ cho `period` 10 hoặc 60 s → lớp mềm; lớp cứng là zone rate-limit rule (07 §6). `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981005). `Retry-After` phải bằng `period` (hằng số trong `src/lib/ratelimit.ts`, test đối chiếu với `wrangler.jsonc`).
- Ba lớp, ngoài vào trong: **WAF rule** (edge, chặn trước khi Worker chạy — không tốn request Worker, trang chặn 1015 của Cloudflare) → **RL_SITE** (ngưỡng thấp hơn WAF để khách thật gặp trang 429 "đẹp" trước) → **nhóm /api** (chặt nhất). Một lượt xem trang tốn 1–20 request tới Worker (file tĩnh `/_astro/*` không qua Worker), nên 100/10s chỉ chặn flood và giữ F5.
- Chặn quốc gia/ASN hay danh sách rất dài: dùng WAF custom rule / IP List (07 §7).
## 3. Form duy nhất: /api/report (bug)
+16 -7
View File
@@ -33,13 +33,22 @@ Zone → Security:
- **WAF → Managed rules**: bật Cloudflare Managed Ruleset (free ruleset).
- Settings → Security Level: Medium · Browser Integrity Check: ON.
## 6. Rate limiting rule (free có 1 rule) — lớp ngoài cho /api/*
## 6. Rate limiting rule (free có 1 rule) — lớp ngoài cho toàn site
Security → WAF → Rate limiting rules → Create:
- Name: `api-outer-limit`
- If: `URI Path starts with /api/`
- Rate: **20 requests / 10 seconds** per IP → Action: **Block**, duration 1 phút (mitigation timeout theo option gói free).
(Lớp trong Worker vẫn đếm 5/phút để trả trang 429 đẹp — rule này chỉ hứng flood thô.)
Gói Free: **1 rule**, biểu thức chỉ dùng được trường **URI Path** và **Verified Bot**, đếm theo **IP**, chu kỳ **10 s**, thời gian chặn **10 s**, không đổi được trang chặn (Cloudflare trả **429**, trang "Error 1015"). Rule chặn ở edge, trước Worker ⇒ flood không tốn request Worker.
Lớp trong Worker (06 §2) đếm thấp hơn — RL_SITE 100/10s cho mọi request tới Worker — để khách thật gặp trang 429 của site trước; rule này chỉ hứng flood thô, nên ngưỡng phải **cao hơn** 100.
Security → Security rules → Rate limiting rules (đang có rule mẫu "Leaked credential check" chiếm slot duy nhất — site không có form mật khẩu nào trên zone, admin đăng nhập qua Access ở `*.cloudflareaccess.com`, nên rule đó không bao giờ khớp: sửa nó thành rule dưới, hoặc xoá rồi tạo mới):
- Name: `site-outer-limit`
- Expression (Edit expression):
`(not starts_with(http.request.uri.path, "/_astro/") and not cf.client.bot)`
— bỏ file tĩnh đã hash (lần tải đầu một trang có thể kéo vài chục file) và bot đã xác thực (Googlebot…; bot AI đã bị chặn ở §5).
- Characteristics: IP · Rate: **150 requests / 10 seconds** · Action: **Block** · Duration: **10 seconds**.
- Gói Free không lọc được theo hostname, nên rule này đếm cả `admin.*` (RL_SITE thì miễn admin). Thư viện ảnh admin tải thumbnail lười (`loading="lazy"`), mỗi màn hình vài chục request — dưới 150.
- Khi bị tấn công: hạ xuống 60–80/10s hoặc đổi Action sang **Managed Challenge**; xong thì trả về.
Kiểm tra: `npm run probe:ratelimit -- https://poli0981.dev/legal/privacy/ 400` — dòng `worker 429` là RL_SITE (trang của site), `waf 429` là rule này (trang 1015). Rule chưa bật ⇒ chỉ thấy `worker 429`.
## 7. Custom rules (free có ~5 rule) — chặn IP/dải/quốc gia khi cần
@@ -134,7 +143,7 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
- [ ] `dig poli0981.dev` ra IP Cloudflare; DNSSEC = Success
- [ ] https:// bắt buộc, chứng chỉ hợp lệ, HSTS header có mặt
- [ ] Bot Fight ON · Managed WAF ON · (AI crawlers block ON nếu chọn)
- [ ] Rate limit rule active — test bằng script bắn 30 req/10s vào /api/ → bị block
- [ ] Rate limit rule active — `npm run probe:ratelimit` (§6) thấy `worker 429` rồi `waf 429`
- [ ] Turnstile hoạt động trên form report (site key đúng domain)
- [ ] Custom domain trỏ Worker, `www` redirect về apex
- [ ] Cron widgets chạy (Workers → widgets → Logs thấy execution)
+7 -5
View File
@@ -14,13 +14,13 @@ Nhắc lại quyết định D8: Custom Errors của Cloudflare cần zone plan
| Trang | Trigger | Headline (VI / EN) | Ghi chú riêng |
|---|---|---|---|
| **404** `404.astro` | route không tồn tại | "Trang này không phát ra tín hiệu." / "This page makes no sound." | + ô search (mở Pagefind), gợi ý 3 bài mới. Assets config `not_found_handling: "404-page"` để request tĩnh lạc cũng nhận trang này (P0 Spike 3 verify) |
| **404** `404.astro` · `en/404.astro` | route không tồn tại | "Trang này không phát ra tín hiệu." / "This page makes no sound." | + ô search (mở Pagefind — đúng index của ngôn ngữ trang), gợi ý 3 bài mới cùng ngôn ngữ. Assets config `not_found_handling: "404-page"` trả `404.html` gần nhất theo đường dẫn: `/en/…` nhận bản tiếng Anh (`en/404.html`, xem 02 §4), mọi đường dẫn khác nhận bản tiếng Việt |
| **500** `500.astro` | exception khi render on-demand / api | "Có gì đó vỡ trong im lặng." / "Something broke, quietly." | Astro tự dùng 500.astro khi SSR lỗi; api route bọc try/catch trả JSON lỗi gọn. Mã tham chiếu = **Cloudflare Ray ID** của request, worker đóng dấu vào `#ref` (`src/lib/error-ref.ts`) — trùng field `ray` trong Workers Logs, ReportDialog tự đính vào báo lỗi |
| **403** worker entry | IP/dải nằm trong denylist (KV `denylist`, `06` §2) | "Cửa này đang khoá." / "This door is locked." | Kèm link `mailto:contact@` nếu nghĩ là nhầm. Không nêu lý do cụ thể |
| **429** middleware render | vượt rate-limit app (5 req/phút/IP trên /api) | "Chậm lại một nhịp." / "Take a breath." | Header `Retry-After: 60`; hiện đồng hồ đếm ngược 60s (vanilla JS inline) |
| **429** worker entry · middleware | vượt rate-limit toàn site (RL_SITE 100/10s/IP, worker entry) hoặc của một nhóm /api (middleware, `06` §2) | "Chậm lại một nhịp." / "Take a breath." | Header `Retry-After`: 10 (toàn site) / 60 (nhóm /api); đồng hồ đếm ngược đọc số giây trong `#cd` — mặc định 60, worker ghi đè thành 10. Vượt rule WAF (`07` §6) thì gặp trang 1015 của Cloudflare thay vì trang này |
| **/offline** | service worker fallback | "Không có mạng — nhưng vẫn có thứ để làm." / "You're offline." | Xem §3–4 |
403 (worker entry) và 429 (middleware) dùng template Astro đã **prerender sẵn thành static asset** (`/403/` `/429/` là trang thật): chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng + `no-store` — không nhân đôi markup (đường `astro dev` dùng `rewrite` cũng được bọc lại status).
403 (worker entry) và 429 (worker entry + middleware) dùng template Astro đã **prerender sẵn thành static asset** (`/403/` `/429/` là trang thật): chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng + `no-store` — không nhân đôi markup (đường `astro dev` dùng `rewrite` cũng được bọc lại status).
Trang xác minh của cổng Turnstile (06 §3b) **không** phải trang lỗi: nó là chính trang được yêu cầu (status 200, `<head>` thật) với `<body>` thay bằng thẻ xác minh. `/offline/` đứng ngoài cổng để service worker luôn precache được.
@@ -41,10 +41,12 @@ Canvas ≤ 6KB JS vanilla nằm ngay trong trang offline: đầu lâu pixel nh
| Case | Cách test | Kỳ vọng |
|---|---|---|
| 404 route | mở `/khong-ton-tai` | trang 404, status 404 |
| 404 route en | mở `/en/does-not-exist` | trang 404 tiếng Anh (`lang="en"`), status 404 |
| 404 asset | mở `/anh-khong-co.png` | trang 404 (not_found_handling) |
| 500 | tạm ném throw trong 1 api route ở preview | trang/JSON 500 + mã tham chiếu |
| 403 | thêm IP nhà vào denylist KV preview → mở site | trang 403 custom |
| 429 | bắn 6 POST /api/report trong 1 phút | request 6 nhận trang 429 + Retry-After |
| 429 lớp zone | bắn 30 req/10s | Cloudflare block (trang mặc định) — xác nhận rule sống |
| 429 | bắn 6 POST /api/report trong 1 phút | request 6 nhận trang 429 + Retry-After: 60 |
| 429 toàn site | `npm run probe:ratelimit` (> 100 req/10s) | trang 429, Retry-After: 10, đếm ngược 10 (dòng `worker 429`) |
| 429 lớp zone | `npm run probe:ratelimit -- <url> 400 40` (> 150 req/10s) | trang 1015 của Cloudflare (dòng `waf 429`) — xác nhận rule sống |
| Offline | DevTools → Network Offline → điều hướng | trang /offline + game chạy |
| Mobile | lặp các case trên ở viewport 390px | không vỡ layout |
+4 -4
View File
@@ -18,15 +18,15 @@
## 2. Kỷ luật để giữ budget
- **Islands discipline**: mặc định `.astro` thuần; island chỉ khi có tương tác thật, ưu tiên `client:visible`/`client:idle`, cấm `client:load` trừ ThemeToggle. GSAP import động trong island, không vào bundle chung.
- **Islands discipline**: mặc định `.astro` thuần; island chỉ khi có tương tác thật, ưu tiên `client:visible`/`client:idle`, cấm `client:load` trên site public (kể cả ThemeToggle — CSS đã hiện đúng icon theo `data-theme-pref`, nên runtime Svelte không cần tranh băng thông với first paint). GSAP import động trong island, không vào bundle chung.
- **Font**: chỉ 4 family, subset latin+vietnamese, preload đúng 2 file, `size-adjust` fallback để CLS≈0. Literata chỉ nạp ở trang đọc.
- **Ảnh**: mọi ảnh qua Astro Image (AVIF ưu tiên), `loading=lazy` trừ LCP (`fetchpriority=high`), khai width/height luôn.
- **CSS**: Tailwind v4 tự purge; grain/scanline bằng 1 PNG nhỏ + CSS, không canvas chạy nền.
- **CSS**: Tailwind v4 tự purge; grain/scanline bằng 1 PNG nhỏ + CSS, không canvas chạy nền. CSS của mỗi trang nằm inline trong HTML (`build.inlineStylesheets: "always"`, ~9 KB brotli) — không còn request CSS chặn render, first paint không phải đợi thêm một vòng mạng.
- **Third-party = 0** ở first paint (YouTube facade, widget đọc KV nội bộ). Beacon Web Analytics là module script (tải defer, ~10 KB) nên không chặn render; nó chỉ có trong bản build production (không có trong Lighthouse CI).
## 3. Kiểm tra
- Local: `npm run build && npx astro preview` + Lighthouse trong DevTools cho 4 trang đại diện: `/`, 1 bài blog, 1 chương truyện, `/gallery/<album>`.
- CI: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý.
- Islands thêm từ 10/2026 đều nhỏ và `client:idle`/`client:load` có lý do: ThemeToggle (`client:load` — icon đúng ngay nhờ CSS theo `data-theme-pref`), SearchModal/MenuSheet (`client:idle`). Admin là trang on-demand riêng, không tính vào budget site.
- CI: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý. Đo qua nginx có sẵn trên runner (gzip, cấu hình ngay trong bước "Start compressing proxy"): `astro preview` không nén gì, còn edge Cloudflare nén brotli mọi response dạng chữ ở production — đo thẳng preview thì điện thoại giả lập phải tải gấp 3–4 lần số byte thật (HTML trang chủ 108 KB thay vì ~25 KB). gzip to hơn brotli chút ít nên số đo vẫn hơi bi quan so với production.
- Islands thêm từ 10/2026 đều nhỏ và `client:idle`: ThemeToggle, Waveline ở hero trang chủ, SearchModal/MenuSheet; Waveline dưới màn hình đầu là `client:visible`. Admin là trang on-demand riêng, không tính vào budget site.
- Thực địa: Cloudflare Web Analytics có Core Web Vitals thật của khách — xem hằng tháng (lịch `17`).
-1
View File
@@ -57,6 +57,5 @@ Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chư
| Analytics Engine cho số liệu cổng/báo lỗi | Biết cổng chặn bao nhiêu, báo lỗi đến từ đâu | Không thêm cookie; giữ khớp Privacy Policy |
| Đếm lượt xem bằng Durable Object | Số đọc cho blog/truyện không cần dịch vụ ngoài | Cập nhật Privacy Policy trước |
| RSS full-content cho blog | Người đọc qua RSS | Truyện vẫn chỉ mô tả + link (ARR) |
| Trang 404 riêng cho `/en/` | Hiện 404 song ngữ một trang | Cloudflare phục vụ `404.html` gần nhất theo thư mục |
| Locale `ja` | Seam i18n đã sẵn (`src/i18n/routing.ts`) | Có nội dung thật để dịch |
| Bình luận (Giscus) · trang /support (Ko-fi) | Tương tác/ủng hộ | Đổi D5; mở CSP cho host tương ứng |
+53
View File
@@ -0,0 +1,53 @@
// Spam a URL from this machine and report who answered 429: the Worker's site-wide limit
// (RL_SITE — the site's own 429 page, Retry-After: 10) or the zone WAF rate-limiting rule
// (Cloudflare's "Error 1015" page, before the Worker runs). Docs 06 §2 and 07 §6.
//
// npm run probe:ratelimit -- [url] [requests] [parallel]
// defaults: https://poli0981.dev/legal/privacy/ 300 20
//
// The default page skips the Turnstile gate, so a 200 is the real page. Every request spends
// this address's budget: expect 429s from the site for the next ~10 seconds.
const url = process.argv[2] ?? "https://poli0981.dev/legal/privacy/";
const total = Number(process.argv[3] ?? 300);
const parallel = Number(process.argv[4] ?? 20);
/** "worker 429" | "waf 429" | the status code as text. */
async function probe() {
const response = await fetch(url, {
redirect: "manual",
headers: { "user-agent": "poli0981-ratelimit-probe" },
signal: AbortSignal.timeout(15000),
});
const body = await response.text();
if (response.status !== 429) return String(response.status);
// The site's 429 page carries the countdown span; the WAF's block page never does.
return body.includes('id="cd"') ? "worker 429" : "waf 429";
}
const results = [];
const firstAt = {};
const started = Date.now();
let next = 0;
await Promise.all(
Array.from({ length: parallel }, async () => {
while (next < total) {
const index = next++;
const kind = await probe().catch((error) => `error (${error.name})`);
results.push(kind);
firstAt[kind] = Math.min(firstAt[kind] ?? Infinity, index + 1);
}
}),
);
const seconds = ((Date.now() - started) / 1000).toFixed(1);
console.log(`${total} requests to ${url} in ${seconds}s (${parallel} in parallel)`);
const counts = Object.groupBy(results, (kind) => kind);
for (const [kind, hits] of Object.entries(counts)) {
console.log(
` ${kind.padEnd(12)} ${String(hits.length).padStart(5)} first at #${firstAt[kind]}`,
);
}
if (!counts["worker 429"] && !counts["waf 429"]) {
console.log("no 429 at all — the limits were not reached (more requests or more parallel?)");
}
+36 -7
View File
@@ -8,7 +8,8 @@
// with Cloudflare's always-pass test secret, so the whole flow — gate page, exemptions,
// /api/gate → pass cookie → real page — is exercised end to end (siteverify is a real
// network call; the test secret accepts any token). Phase 3 lists the client's address in
// the KV denylist and expects 403s everywhere, pages included.
// the KV denylist and expects 403s everywhere, pages included. Phase 4 spams a page until the
// site-wide rate limit answers with the 429 page.
//
// Usage: npm run build && npm run smoke (works on Linux, macOS and Windows)
import { execFileSync, spawn } from "node:child_process";
@@ -178,18 +179,27 @@ await withWorker(8788, {}, async (get, port) => {
expect("/blog/ → 200", (await get("/blog/")).status === 200);
expect("/en/ → 200", (await get("/en/")).status === 200);
expect("unknown page → 404", (await get("/definitely-not-a-page/")).status === 404);
for (const [path, lang] of [
["/definitely-not-a-page/", "vi"],
["/en/definitely-not-a-page/", "en"],
]) {
const missing = await get(path);
const body = await missing.text();
expect(
`${path} → 404 page in ${lang}`,
missing.status === 404 && body.includes(`<html lang="${lang}"`),
`got ${missing.status}`,
);
}
const health = await get("/api/health");
const healthBody = health.status === 200 ? await health.json() : {};
expect("/api/health → 200 json", healthBody.ok === true);
expect("/api/health reports the version", "version" in healthBody);
expect("/sw.js → 200", (await get("/sw.js")).status === 200);
const asset = /\/_astro\/[^"']+\.css/.exec(html)?.[0];
expect(
"hashed CSS asset → 200",
asset ? (await get(asset)).status === 200 : false,
`asset=${asset}`,
);
// CSS is inline (astro.config.mjs `inlineStylesheets`); scripts and fonts stay hashed files.
const asset = /\/_astro\/[^"']+\.(?:js|woff2)/.exec(html)?.[0];
expect("hashed asset → 200", asset ? (await get(asset)).status === 200 : false, `asset=${asset}`);
expect("/rss.xml → 200", (await get("/rss.xml")).status === 200);
expect(
"/.well-known/security.txt → 200",
@@ -375,6 +385,25 @@ try {
rmSync(tmp, { recursive: true, force: true });
}
console.log("— phase 4: spam until the site-wide rate limit answers");
// Last of all: the simulated counters outlive a `wrangler dev` restart, so a spent budget
// would turn the next phase into 429s. RL_SITE allows 100 per 10 s; keep going until a 429
// arrives — a burst can straddle two windows.
await withWorker(8791, {}, async (get) => {
let limited = null;
for (let i = 0; i < 400 && !limited; i++) {
const response = await get("/legal/privacy/");
if (response.status === 429) limited = response;
else await response.body?.cancel();
}
const html = limited ? await limited.text() : "";
expect("spam → 429 from the site-wide limit", limited !== null);
expect("429 sends Retry-After: 10", limited?.headers.get("retry-after") === "10");
expect("429 is no-store", limited?.headers.get("cache-control") === "no-store");
expect("429 has nosniff", limited?.headers.get("x-content-type-options") === "nosniff");
expect("429 countdown starts at 10", html.includes('<span id="cd">10</span>'));
});
if (failures.length) {
console.error(`\nsmoke test failed (${failures.length}): ${failures.join(", ")}`);
process.exit(1);
+1 -1
View File
@@ -4,7 +4,7 @@ sonar.organization=poli0981
sonar.projectKey=poli0981_poli0981-dev
sonar.projectName=poli0981-dev
# Bumped with each release tag; "previous version" new-code periods start from it.
sonar.projectVersion=2.0.0
sonar.projectVersion=2.1.1
sonar.sourceEncoding=UTF-8
# .github is analyzed too: the workflow rules (pinned actions, no npx/install scripts) are
+9 -3
View File
@@ -62,7 +62,11 @@ const pathname = Astro.url.pathname;
></path>
</svg>
</button>
<ThemeToggle client:load labels={t.theme} />
{
/* idle, not load: CSS already shows the right icon from <html data-theme-pref>, so
the Svelte runtime need not compete with first paint for bandwidth. */
}
<ThemeToggle client:idle labels={t.theme} />
<LangSwitch href={langHref} />
<button
type="button"
@@ -89,8 +93,10 @@ const pathname = Astro.url.pathname;
position: sticky;
inset-block-start: 0;
z-index: 40;
background: color-mix(in srgb, var(--bg) 85%, transparent);
backdrop-filter: blur(8px);
/* Opaque and without backdrop-filter: Safari 26 extends a sticky header's background
up under the iPhone status bar, but gives up when the header has a backdrop-filter —
the page then scrolled into view above the header. */
background: var(--bg);
border-block-end: 1px solid var(--line);
}
.header-inner {
+3 -2
View File
@@ -89,8 +89,9 @@ const tabs = [
z-index: 40;
display: flex;
align-items: stretch;
background: color-mix(in srgb, var(--surface) 92%, transparent);
backdrop-filter: blur(10px);
/* Opaque, no backdrop-filter — same reason as the site header: Safari 26 only extends
a fixed bar's colour under its own toolbar when the bar has no backdrop-filter. */
background: var(--surface);
border-block-start: 1px solid var(--line);
padding-block-end: env(safe-area-inset-bottom, 0);
}
+4 -1
View File
@@ -94,7 +94,10 @@
aria-hidden="true"
>
<defs>
<linearGradient id={uid} x1="0" y1="0" x2="1" y2="0">
<!-- userSpaceOnUse, not the default objectBoundingBox: the idle flatline's bounding box
is 0 tall, and WebKit (every iOS browser) then drops the gradient, and with it the
whole stroke — the footer showed an empty band on iPhone. -->
<linearGradient id={uid} gradientUnits="userSpaceOnUse" x1="0" y1="0" x2={coordWidth} y2="0">
<stop class="s-line" offset="0%" />
<stop class="s-line" offset="36%" />
<stop class="s-accent" offset="50%" />
+2 -1
View File
@@ -30,7 +30,8 @@ const shortcuts = [
<p class="eyebrow">poli0981.dev</p>
<h1 class="hero-title">Kokone <span class="accent">/ SkullMute</span></h1>
<p class="hero-tag">~ {t.site.tagline} ~</p>
<div class="hero-wave"><Waveline client:visible height={48} /></div>
{/* idle: in view at load anyway, and its flatline renders without JS until then. */}
<div class="hero-wave"><Waveline client:idle height={48} /></div>
</section>
<WidgetsRefresh client:idle labels={t.widgets} initial={widgets} />
+156
View File
@@ -0,0 +1,156 @@
---
// The 404 page for one locale: 404.astro (vi) and en/404.astro. The asset layer serves the
// nearest 404.html up a missing path, so /en/... misses get the English one (astro.config.mjs
// moves it to en/404.html; src/worker.ts returns that response as is).
import ErrorLayout from "@/layouts/ErrorLayout.astro";
import { getLatestMixed } from "@/lib/collections";
import { useTranslations } from "@/i18n";
import { DEFAULT_LOCALE, sectionPath, type Locale } from "@/i18n/routing";
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const t = useTranslations(locale);
// The heading again in a second language — English, or the default one on the English page.
const echo: Locale = locale === "en" ? DEFAULT_LOCALE : "en";
const latest = await getLatestMixed(locale, 3);
const linkFor = (item: (typeof latest)[number]) =>
item.kind === "blog"
? sectionPath("blog", locale, item.entry.id)
: sectionPath("stories", locale, ...item.entry.id.split("/"));
---
<ErrorLayout title="404 — poli0981.dev" {locale} showReport>
<p class="code">404</p>
<h1>{t.notFound.heading}</h1>
<p class="echo" lang={echo}>{useTranslations(echo).notFound.heading}</p>
<form id="s404-form" class="s404" role="search">
<input
id="s404-input"
type="search"
placeholder={t.notFound.search}
aria-label={t.search.aria}
autocomplete="off"
spellcheck="false"
/>
</form>
<ul id="s404-results" class="s404-results" aria-live="polite"></ul>
{
latest.length > 0 && (
<ul class="recent">
{latest.map((item) => (
<li>
<a href={linkFor(item)}>{item.entry.data.title}</a>
</li>
))}
</ul>
)
}
</ErrorLayout>
<script>
// Lightweight inline search — lazy-loads the Pagefind runtime on first input.
// Degrades silently where the index is absent (e.g. `astro dev`).
const form = document.getElementById("s404-form");
const input = document.getElementById("s404-input");
const list = document.getElementById("s404-results");
if (form && input instanceof HTMLInputElement && list) {
form.addEventListener("submit", (e) => e.preventDefault());
type PagefindApi = {
search: (q: string) => Promise<{ results: { data: () => Promise<unknown> }[] }>;
};
let pf: PagefindApi | null = null;
let timer: ReturnType<typeof setTimeout>;
const load = async (): Promise<PagefindApi> => {
if (pf) return pf;
const mod = (await import(
new URL("/pagefind/pagefind.js", location.origin).href
)) as PagefindApi;
pf = mod;
return mod;
};
input.addEventListener("input", () => {
clearTimeout(timer);
const q = input.value.trim();
if (!q) {
list.replaceChildren();
return;
}
timer = setTimeout(async () => {
try {
const api = await load();
const search = await api.search(q);
const items = await Promise.all(search.results.slice(0, 5).map((r) => r.data()));
list.replaceChildren(
...items.map((d) => {
const data = d as { url: string; meta?: { title?: string } };
const li = document.createElement("li");
const a = document.createElement("a");
a.href = data.url;
a.textContent = data.meta?.title ?? data.url;
li.appendChild(a);
return li;
}),
);
} catch {
/* index unavailable — leave results empty */
}
}, 200);
});
}
</script>
<style>
.s404 {
margin-block-start: 0.5rem;
inline-size: min(28rem, 90vw);
}
.s404 input {
inline-size: 100%;
padding: 0.7rem 1rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--text);
font: inherit;
}
.s404 input:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.s404-results {
list-style: none;
padding: 0;
margin: 0.75rem 0 0;
inline-size: min(28rem, 90vw);
display: flex;
flex-direction: column;
gap: 0.4rem;
text-align: start;
}
.s404-results a {
color: var(--accent);
font-size: var(--text-meta);
}
.s404-results a:hover {
color: var(--accent-strong);
}
.recent {
list-style: none;
padding: 0;
margin: 1.25rem 0 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.recent a {
color: var(--text);
}
.recent a:hover {
color: var(--accent);
}
</style>
+5
View File
@@ -28,6 +28,7 @@ const en: UIStrings = {
breadcrumb: "Breadcrumb",
postNav: "Older and newer posts",
chapterNav: "Previous and next chapter",
errorNav: "Error page navigation",
},
project: {
repo: "repo",
@@ -170,6 +171,10 @@ const en: UIStrings = {
groupPage: "Pages",
countLabel: "{n} results",
},
notFound: {
heading: "This page makes no sound.",
search: "Search posts and stories…",
},
qaGroups: {
channel: "Channel",
dev: "Dev",
+5
View File
@@ -26,6 +26,7 @@ const vi = {
breadcrumb: "Đường dẫn",
postNav: "Bài cũ hơn và mới hơn",
chapterNav: "Chương trước và sau",
errorNav: "Điều hướng lỗi",
},
project: {
repo: "repo",
@@ -166,6 +167,10 @@ const vi = {
groupPage: "Trang",
countLabel: "{n} kết quả",
},
notFound: {
heading: "Trang này không phát ra tín hiệu.",
search: "Tìm bài viết, truyện…",
},
qaGroups: {
channel: "Kênh",
dev: "Lập trình",
+2 -2
View File
@@ -124,8 +124,8 @@ const nav = [
inset-block-start: 0;
z-index: 20;
border-block-end: 1px solid var(--line);
background: color-mix(in srgb, var(--surface) 92%, transparent);
backdrop-filter: blur(8px);
/* Opaque, no backdrop-filter: see .site-header (Safari 26 status-bar tint). */
background: var(--surface);
}
.admin-top {
display: flex;
+27 -10
View File
@@ -3,9 +3,13 @@ import "../styles/global.css";
import { Font } from "astro:assets";
import ReportDialog from "../components/ReportDialog.astro";
import CfBeacon from "../components/CfBeacon.astro";
import { useTranslations } from "../i18n";
import { DEFAULT_LOCALE, homePath, sectionPath, type Locale } from "../i18n/routing";
interface Props {
title: string;
/** Page language — `lang`, the links and the report dialog (only 404 has an English twin). */
locale?: Locale;
/** Show the Home / Blog / Truyện links (hidden for 429 + offline). */
showLinks?: boolean;
/** Show the "Báo lỗi" affordance (404 / 500 only). */
@@ -13,11 +17,12 @@ interface Props {
/** Reference code (500) forwarded to the report dialog. */
ref?: string;
}
const { title, showLinks = true, showReport = false, ref } = Astro.props;
const { title, locale = DEFAULT_LOCALE, showLinks = true, showReport = false, ref } = Astro.props;
const t = useTranslations(locale);
---
<!doctype html>
<html lang="vi" data-theme="dark">
<html lang={locale} data-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
@@ -34,7 +39,18 @@ const { title, showLinks = true, showReport = false, ref } = Astro.props;
<main class="err">
<svg class="flatline" viewBox="0 0 320 24" preserveAspectRatio="none" aria-hidden="true">
<defs>
<linearGradient id="err-flat" x1="0" y1="0" x2="1" y2="0">
{
/* userSpaceOnUse: a flat line has a 0-tall bounding box, and WebKit drops an
objectBoundingBox gradient on it — the line vanished on iPhone (see Waveline). */
}
<linearGradient
id="err-flat"
gradientUnits="userSpaceOnUse"
x1="0"
y1="0"
x2="320"
y2="0"
>
<stop offset="0%" class="l"></stop>
<stop offset="42%" class="l"></stop>
<stop offset="50%" class="a"></stop>
@@ -56,10 +72,10 @@ const { title, showLinks = true, showReport = false, ref } = Astro.props;
{
showLinks && (
<nav class="err-nav" aria-label="Điều hướng lỗi">
<a href="/">Trang chủ</a>
<a href="/blog/">Blog</a>
<a href="/truyen/">Truyện</a>
<nav class="err-nav" aria-label={t.landmarks.errorNav}>
<a href={homePath(locale)}>{t.nav.home}</a>
<a href={sectionPath("blog", locale)}>{t.nav.blog}</a>
<a href={sectionPath("stories", locale)}>{t.nav.stories}</a>
</nav>
)
}
@@ -67,13 +83,13 @@ const { title, showLinks = true, showReport = false, ref } = Astro.props;
{
showReport && (
<button type="button" class="err-report" data-report-trigger>
Báo lỗi
{t.actions.reportBug}
</button>
)
}
</main>
{showReport && <ReportDialog locale="vi" ref={ref} />}
{showReport && <ReportDialog {locale} ref={ref} />}
</body>
</html>
@@ -135,7 +151,8 @@ const { title, showLinks = true, showReport = false, ref } = Astro.props;
font-size: var(--text-h2);
line-height: 1.15;
}
:global(.err .en) {
/* The heading again in the other language, under the main one. */
:global(.err .echo) {
color: var(--muted);
font-size: var(--text-lead);
}
+4
View File
@@ -5,8 +5,12 @@ import { env } from "cloudflare:workers";
// RL_API. /api/widgets is never limited: its response is identical for every visitor
// and edge-cached (api/widgets.ts), and the home page fetches it on every view.
/** The /api groups' window (wrangler.jsonc `ratelimits`), sent as Retry-After. */
export const RATE_LIMIT_WINDOW_SECONDS = 60;
/** RL_SITE's window: the site-wide limit src/worker.ts applies before any route. */
export const SITE_RATE_LIMIT_SECONDS = 10;
type RateLimiter = { limit(options: { key: string }): Promise<{ success: boolean }> };
const BINDING_FOR_GROUP: Record<string, string> = {
+1 -1
View File
@@ -8,7 +8,7 @@ const contact = emailForScope("general");
<ErrorLayout title="403 — poli0981.dev">
<p class="code">403</p>
<h1>Cửa này đang khoá.</h1>
<p class="en">This door is locked.</p>
<p class="echo" lang="en">This door is locked.</p>
<p class="code">
Nếu bạn nghĩ đây là nhầm lẫn / If this looks wrong —
<a href={contact.href}>{contact.address}</a>
+2 -141
View File
@@ -1,144 +1,5 @@
---
import ErrorLayout from "@/layouts/ErrorLayout.astro";
import { getLatestMixed } from "@/lib/collections";
import { sectionPath } from "@/i18n/routing";
const latest = await getLatestMixed("vi", 3);
const linkFor = (item: (typeof latest)[number]) =>
item.kind === "blog"
? sectionPath("blog", "vi", item.entry.id)
: sectionPath("stories", "vi", ...item.entry.id.split("/"));
import NotFoundPage from "@/components/pages/NotFoundPage.astro";
---
<ErrorLayout title="404 — poli0981.dev" showReport>
<p class="code">404</p>
<h1>Trang này không phát ra tín hiệu.</h1>
<p class="en">This page makes no sound.</p>
<form id="s404-form" class="s404" role="search">
<input
id="s404-input"
type="search"
placeholder="Tìm bài viết, truyện…"
aria-label="Tìm kiếm trên trang"
autocomplete="off"
spellcheck="false"
/>
</form>
<ul id="s404-results" class="s404-results" aria-live="polite"></ul>
{
latest.length > 0 && (
<ul class="recent">
{latest.map((item) => (
<li>
<a href={linkFor(item)}>{item.entry.data.title}</a>
</li>
))}
</ul>
)
}
</ErrorLayout>
<script>
// Lightweight inline search — lazy-loads the Pagefind runtime on first input.
// Degrades silently where the index is absent (e.g. `astro dev`).
const form = document.getElementById("s404-form");
const input = document.getElementById("s404-input");
const list = document.getElementById("s404-results");
if (form && input instanceof HTMLInputElement && list) {
form.addEventListener("submit", (e) => e.preventDefault());
type PagefindApi = {
search: (q: string) => Promise<{ results: { data: () => Promise<unknown> }[] }>;
};
let pf: PagefindApi | null = null;
let timer: ReturnType<typeof setTimeout>;
const load = async (): Promise<PagefindApi> => {
if (pf) return pf;
const mod = (await import(
new URL("/pagefind/pagefind.js", location.origin).href
)) as PagefindApi;
pf = mod;
return mod;
};
input.addEventListener("input", () => {
clearTimeout(timer);
const q = input.value.trim();
if (!q) {
list.replaceChildren();
return;
}
timer = setTimeout(async () => {
try {
const api = await load();
const search = await api.search(q);
const items = await Promise.all(search.results.slice(0, 5).map((r) => r.data()));
list.replaceChildren(
...items.map((d) => {
const data = d as { url: string; meta?: { title?: string } };
const li = document.createElement("li");
const a = document.createElement("a");
a.href = data.url;
a.textContent = data.meta?.title ?? data.url;
li.appendChild(a);
return li;
}),
);
} catch {
/* index unavailable — leave results empty */
}
}, 200);
});
}
</script>
<style>
.s404 {
margin-block-start: 0.5rem;
inline-size: min(28rem, 90vw);
}
.s404 input {
inline-size: 100%;
padding: 0.7rem 1rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--text);
font: inherit;
}
.s404 input:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.s404-results {
list-style: none;
padding: 0;
margin: 0.75rem 0 0;
inline-size: min(28rem, 90vw);
display: flex;
flex-direction: column;
gap: 0.4rem;
text-align: start;
}
.s404-results a {
color: var(--accent);
font-size: var(--text-meta);
}
.s404-results a:hover {
color: var(--accent-strong);
}
.recent {
list-style: none;
padding: 0;
margin: 1.25rem 0 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.recent a {
color: var(--text);
}
.recent a:hover {
color: var(--accent);
}
</style>
<NotFoundPage locale="vi" />
+3 -2
View File
@@ -5,15 +5,16 @@ import ErrorLayout from "@/layouts/ErrorLayout.astro";
<ErrorLayout title="429 — poli0981.dev" showLinks={false}>
<p class="code">429</p>
<h1>Chậm lại một nhịp.</h1>
<p class="en">Take a breath.</p>
<p class="echo" lang="en">Take a breath.</p>
{/* 60 s = the /api groups' window; the Worker rewrites it for the site-wide limit (10 s). */}
<p class="code">Thử lại sau / Retry in <span id="cd">60</span>s</p>
{
/* Processed (not `is:inline`): body-level, so the <meta> CSP governs it and only a
bundled script gets a hash. Deferring costs nothing for a 1s-tick countdown. */
}
<script>
let n = 60;
const el = document.getElementById("cd");
let n = Number(el?.textContent) || 60;
const t = setInterval(() => {
n -= 1;
if (el) el.textContent = String(n);
+1 -1
View File
@@ -5,7 +5,7 @@ import ErrorLayout from "@/layouts/ErrorLayout.astro";
<ErrorLayout title="500 — poli0981.dev" showReport>
<p class="code">500</p>
<h1>Có gì đó vỡ trong im lặng.</h1>
<p class="en">Something broke, quietly.</p>
<p class="echo" lang="en">Something broke, quietly.</p>
{/* The Worker stamps the Cloudflare Ray ID into #ref (src/lib/error-ref.ts). */}
<p class="code">
Mã tham chiếu / Reference: <span class="ref" id="ref">—</span>
+5
View File
@@ -0,0 +1,5 @@
---
import NotFoundPage from "@/components/pages/NotFoundPage.astro";
---
<NotFoundPage locale="en" />
+1 -1
View File
@@ -5,7 +5,7 @@ import ErrorLayout from "@/layouts/ErrorLayout.astro";
<ErrorLayout title="Offline — poli0981.dev" showLinks={false}>
<p class="code">offline</p>
<h1>Không có mạng — nhưng vẫn có thứ để làm.</h1>
<p class="en">You're offline.</p>
<p class="echo" lang="en">You're offline.</p>
<p class="code">Kết nối lại rồi thử tải trang một lần nữa nhé.</p>
<div class="game">
+67 -5
View File
@@ -8,6 +8,7 @@ import { renderGate } from "./lib/gate/render";
import { routeHosts } from "./lib/hosts";
import { log, requestFields } from "./lib/log";
import { serveMedia } from "./lib/media/serve";
import { clientSubject, SITE_RATE_LIMIT_SECONDS } from "./lib/ratelimit";
import { withSecurityHeaders } from "./lib/security-headers";
import { versionInfo } from "./lib/version";
@@ -19,8 +20,11 @@ import { versionInfo } from "./lib/version";
// The build-time prerender worker always uses the adapter's own entry, so nothing here
// runs during `astro build`.
/** On-demand Astro routes: always rendered by the app, never looked up in ASSETS. */
const APP_PREFIXES = ["/api/", "/admin", "/media/", "/ext-img/"];
/**
* On-demand Astro routes: always rendered by the app, never looked up in ASSETS. Every
* `prerender = false` page must live under one of these (tests/worker.test.ts checks).
*/
export const APP_PREFIXES = ["/api/", "/admin", "/media/", "/ext-img/"];
/** Secrets aren't in the generated Env type (wrangler only sees `vars`). */
type GateEnv = { GATE_MODE?: string; GATE_SECRET?: string; TURNSTILE_SECRET?: string };
@@ -51,6 +55,61 @@ async function denied(request: Request, env: Env): Promise<Response | null> {
return withSecurityHeaders(response);
}
/**
* The site-wide rate limit (RL_SITE, docs 06 §2): one budget per client for every request
* the Worker sees — pages, /media, /ext-img, /pagefind and the API, whose groups then apply
* their own stricter limits in the middleware. Over it → the 429 page with Retry-After and
* its countdown set to the window. The admin host is exempt: Cloudflare Access stands in
* front of it, its API is limited per account (RL_ADMIN) and the media library loads many
* thumbnails at once. Fails OPEN like the denylist, and never throws: the edge fail-open
* below would skip the gate too. The zone WAF rule (docs 07 §6) is the hard limit.
*/
async function rateLimited(request: Request, url: URL, env: Env): Promise<Response | null> {
const ip = request.headers.get("cf-connecting-ip");
// Typed as always bound, but unit tests (and any env without the binding) have none.
const limiter = env.RL_SITE as RateLimit | undefined;
if (!ip || !limiter || url.hostname.startsWith("admin.")) return null;
try {
if ((await limiter.limit({ key: `site:${clientSubject(ip)}` })).success) return null;
} catch (error) {
log.error("ratelimit.unavailable", { ...requestFields(request), error });
return null;
}
log.warn("ratelimit.exceeded", { ...requestFields(request), group: "site" });
const seconds = String(SITE_RATE_LIMIT_SECONDS);
try {
const page = await env.ASSETS.fetch(new URL("/429/", request.url));
const response = new Response(page.body, { status: 429, headers: page.headers });
response.headers.set("Cache-Control", "no-store");
response.headers.set("Retry-After", seconds);
// The body is rewritten below.
for (const header of ["ETag", "Last-Modified", "Content-Length"]) {
response.headers.delete(header);
}
const stamped = new HTMLRewriter()
.on("#cd", {
element(el) {
el.setInnerContent(seconds);
},
})
.transform(response);
return withSecurityHeaders(stamped);
} catch (error) {
// Still a 429 — falling through to the edge fail-open would serve the page ungated.
log.error("ratelimit.page_failed", { ...requestFields(request), error });
return withSecurityHeaders(
new Response("Too many requests", {
status: 429,
headers: {
"content-type": "text/plain; charset=utf-8",
"cache-control": "no-store",
"retry-after": seconds,
},
}),
);
}
}
/**
* The Turnstile gate (docs 06 §3b): unless the request carries a valid 48-hour pass, a
* page answers with the gate instead of its content. Returns the response to send, or
@@ -100,7 +159,7 @@ export default {
return Response.redirect(url.toString(), 301);
}
const blocked = await denied(request, env);
const blocked = (await denied(request, env)) ?? (await rateLimited(request, url, env));
if (blocked) return blocked;
const hostRoute = routeHosts(url);
@@ -137,6 +196,10 @@ export default {
// Serve pages straight from ASSETS with the *original* request. The adapter's own
// asset lookup fetches by URL string, which drops the method and conditional
// headers — every revalidation would turn into a full 200 and HEAD into GET.
// A miss is answered here as well: the asset layer sends the nearest 404.html up the
// path with status 404 (`not_found_handling: "404-page"`), so /en/... gets the English
// page. The app has nothing else for a path outside APP_PREFIXES, and its own lookup of
// a localized error page (/en/404/index) is answered with a redirect.
// In `astro dev` nothing is built yet, so let the app handle everything.
const isRead = request.method === "GET" || request.method === "HEAD";
if (
@@ -144,8 +207,7 @@ export default {
isRead &&
!APP_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))
) {
const asset = await env.ASSETS.fetch(request);
if (asset.status !== 404) return withSecurityHeaders(asset);
return withSecurityHeaders(await env.ASSETS.fetch(request));
}
} catch (error) {
// Fail open: a bug in edge logic must never take the static site down with it.
+18 -1
View File
@@ -1,10 +1,17 @@
// The small libraries: rate limiting, Turnstile, headers, bodies, logs, version, denylist,
// formatting, links, SEO, RSS, OG, i18n and nav.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { afterEach, describe, it } from "node:test";
import { setWorkerEnv } from "./support/stubs/cloudflare-workers.ts";
import { captureLogs, FakeKV, FakeRateLimiter, jsonResponse, mockFetch } from "./support/fakes.ts";
import { allowRequest, apiGroup, clientSubject } from "../src/lib/ratelimit.ts";
import {
allowRequest,
apiGroup,
clientSubject,
RATE_LIMIT_WINDOW_SECONDS,
SITE_RATE_LIMIT_SECONDS,
} from "../src/lib/ratelimit.ts";
import { verifyTurnstile } from "../src/lib/turnstile-server.ts";
import { applySecurityHeaders, withSecurityHeaders } from "../src/lib/security-headers.ts";
import {
@@ -84,6 +91,16 @@ describe("rate limiting", () => {
setWorkerEnv({});
assert.equal(await allowRequest("gate", "a"), true);
});
it("sends a Retry-After equal to each binding's period in wrangler.jsonc", async () => {
const config = await readFile(new URL("../wrangler.jsonc", import.meta.url), "utf8");
const period = (name: string) =>
Number(new RegExp(`"name": "${name}"[^}]*"period": (\\d+)`).exec(config)?.[1]);
assert.equal(period("RL_SITE"), SITE_RATE_LIMIT_SECONDS);
for (const name of ["RL_REPORT", "RL_GATE", "RL_ADMIN", "RL_API"]) {
assert.equal(period(name), RATE_LIMIT_WINDOW_SECONDS, name);
}
});
});
describe("Turnstile siteverify", () => {
+39 -22
View File
@@ -272,14 +272,27 @@ export interface AssetPage {
/** The static-asset binding: pathname → page; anything else is a 404. */
export function fakeAssets(pages: Record<string, AssetPage>) {
const requests: Request[] = [];
// `not_found_handling: "404-page"`: a miss gets the nearest 404.html up the path.
const notFoundPage = (pathname: string): AssetPage | undefined => {
for (let dir = pathname; dir;) {
dir = dir.slice(0, dir.lastIndexOf("/"));
const page = pages[`${dir}/404.html`];
if (page) return page;
}
return undefined;
};
return {
requests,
async fetch(input: Request | URL | string): Promise<Response> {
const request = input instanceof Request ? input : new Request(String(input));
requests.push(request);
const page = pages[new URL(request.url).pathname];
if (!page)
return new Response("not found", { status: 404, headers: { "content-type": "text/html" } });
const { pathname } = new URL(request.url);
const page = pages[pathname];
if (!page) {
const body =
request.method === "HEAD" ? null : (notFoundPage(pathname)?.body ?? "not found");
return new Response(body, { status: 404, headers: { "content-type": "text/html" } });
}
return new Response(request.method === "HEAD" ? null : (page.body ?? ""), {
status: page.status ?? 200,
headers: page.headers ?? { "content-type": "text/html; charset=utf-8" },
@@ -293,12 +306,15 @@ export function fakeAssets(pages: Record<string, AssetPage>) {
export class FakeRateLimiter {
readonly counts = new Map<string, number>();
readonly limitPerKey: number;
/** When set, every call throws it (the binding failing). */
failWith: Error | null = null;
constructor(limitPerKey: number) {
this.limitPerKey = limitPerKey;
}
async limit({ key }: { key: string }): Promise<{ success: boolean }> {
if (this.failWith) throw this.failWith;
const count = (this.counts.get(key) ?? 0) + 1;
this.counts.set(key, count);
return { success: count <= this.limitPerKey };
@@ -374,10 +390,10 @@ interface FakeElement {
}
/**
* Just enough of workerd's HTMLRewriter for src/lib/gate/render.ts and src/lib/error-ref.ts:
* the selectors they use (`html`, `head script[src]`, `link[rel="modulepreload"]`,
* `script[type="application/ld+json"]`, `body`, `#ref`) applied to the whole document with
* string surgery.
* Just enough of workerd's HTMLRewriter for src/lib/gate/render.ts, src/lib/error-ref.ts and
* the 429 countdown in src/worker.ts: the selectors they use (`html`, `head script[src]`,
* `link[rel="modulepreload"]`, `script[type="application/ld+json"]`, `body`, `#<id>`)
* applied to the whole document with string surgery.
*/
export class FakeHTMLRewriter {
private readonly handlers: [string, ElementHandlers][] = [];
@@ -446,6 +462,22 @@ function applySelector(
return out + html.slice(copied);
};
if (selector.startsWith("#")) {
const id = html.indexOf(` id="${selector.slice(1)}"`);
if (id === -1) return html;
const open = html.indexOf(">", id) + 1;
const close = html.indexOf("</", open);
let inner = html.slice(open, close);
handler({
getAttribute: () => null,
remove() {},
setInnerContent: (content) => {
inner = content.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
},
});
return html.slice(0, open) + inner + html.slice(close);
}
switch (selector) {
case "html": {
const tag = /<html[^>]*>/.exec(html)?.[0] ?? "";
@@ -461,21 +493,6 @@ function applySelector(
return replaceTags(/<link\b[^>]*rel="modulepreload"[^>]*>/g);
case 'script[type="application/ld+json"]':
return replaceScripts((tag) => attribute(tag, "type") === "application/ld+json");
case "#ref": {
const id = html.indexOf(' id="ref"');
if (id === -1) return html;
const open = html.indexOf(">", id) + 1;
const close = html.indexOf("</", open);
let inner = html.slice(open, close);
handler({
getAttribute: () => null,
remove() {},
setInnerContent: (content) => {
inner = content.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
},
});
return html.slice(0, open) + inner + html.slice(close);
}
case "body":
return html.replace(
/(<body[^>]*>)[\s\S]*(<\/body>)/,
+155 -3
View File
@@ -1,6 +1,9 @@
// The Worker entry (src/worker.ts): everything every page passes through.
import assert from "node:assert/strict";
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { beforeEach, describe, it } from "node:test";
import { fileURLToPath } from "node:url";
import { setHandler } from "./support/stubs/cloudflare-handler.ts";
import {
captureLogs,
@@ -8,11 +11,12 @@ import {
fakeContext,
FakeKV,
FakeR2,
FakeRateLimiter,
installCaches,
installHTMLRewriter,
type AssetPage,
} from "./support/fakes.ts";
import worker from "../src/worker.ts";
import worker, { APP_PREFIXES } from "../src/worker.ts";
import { issuePass } from "../src/lib/gate/cookie.ts";
import { resetDenylistMemo } from "../src/lib/denylist.ts";
@@ -22,6 +26,17 @@ const PAGES: Record<string, AssetPage> = {
"/": { body: HOME },
"/en/": { body: HOME.replace('lang="vi"', 'lang="en"') },
"/403/": { status: 200, body: "<html><body>403 page</body></html>" },
"/429/": {
body: `<html><body><p>429 page, retry in <span id="cd">60</span>s</p></body></html>`,
headers: {
"content-type": "text/html; charset=utf-8",
etag: '"asset-etag"',
"last-modified": "Mon, 26 Oct 2026 00:00:00 GMT",
"content-length": "72",
},
},
"/404.html": { body: `<html lang="vi"><body>404 page</body></html>` },
"/en/404.html": { body: `<html lang="en"><body>404 page</body></html>` },
"/data.json": { body: "{}", headers: { "content-type": "application/json" } },
"/pagefind/pagefind.js": { body: "pagefind", headers: { "content-type": "text/javascript" } },
};
@@ -99,14 +114,48 @@ describe("worker: routing", () => {
assert.equal(assets.requests.at(-1)?.method, "HEAD");
});
it("falls through to the Astro app on an asset 404 and for app routes", async () => {
for (const path of ["/no-such-page/", "/api/health", "/admin/"]) {
it("answers a missing page with the nearest 404 page, in that path's language", async () => {
for (const [path, lang] of [
["/no-such-page/", "vi"],
["/blog/no-such-post/", "vi"],
["/en/no-such-page/", "en"],
["/en/stories/no-such-story/", "en"],
]) {
const { response } = await run(`https://poli0981.dev${path}`);
assert.equal(response.status, 404, path);
assert.match(await response.text(), new RegExp(`lang="${lang}"`), path);
assert.equal(response.headers.get("x-frame-options"), "DENY", path);
}
});
it("hands app routes to the Astro app", async () => {
for (const path of ["/api/health", "/admin/"]) {
const host = path === "/admin/" ? "admin.poli0981.dev" : "poli0981.dev";
const { response } = await run(`https://${host}${path}`);
assert.match(await response.text(), /from the Astro handler/, path);
}
});
it("keeps every on-demand page under APP_PREFIXES", async () => {
// A `prerender = false` page elsewhere would never reach the app: the Worker answers
// every other path from ASSETS, misses included.
const root = fileURLToPath(new URL("../src/pages/", import.meta.url));
const files = (await readdir(root, { recursive: true })).filter((f) => /\.(astro|ts)$/.test(f));
const onDemand: string[] = [];
for (const file of files) {
if (/export const prerender = false/.test(await readFile(join(root, file), "utf8"))) {
onDemand.push(`/${file.replaceAll("\\", "/").replace(/(index)?\.(astro|ts)$/, "")}`);
}
}
assert.ok(onDemand.length > 10, "found the admin pages and API routes");
for (const route of onDemand) {
assert.ok(
APP_PREFIXES.some((prefix) => route.startsWith(prefix)),
route,
);
}
});
it("lets the app handle everything under astro dev", async () => {
globalThis.$env.DEV = true;
const { response, assets } = await run("https://poli0981.dev/");
@@ -220,6 +269,109 @@ describe("worker: IP denylist", () => {
});
});
describe("worker: site-wide rate limit", () => {
it("answers spam with the 429 page, Retry-After and its countdown set to the window", async () => {
const limiter = new FakeRateLimiter(3);
const statuses: number[] = [];
for (let i = 0; i < 5; i++) {
statuses.push((await run("https://poli0981.dev/", {}, { RL_SITE: limiter })).response.status);
}
assert.deepEqual(statuses, [200, 200, 200, 429, 429]);
const { env } = makeEnv({ RL_SITE: limiter });
const { result, logs } = await captureLogs(() =>
fetchWorker(
request("https://poli0981.dev/"),
env,
fakeContext() as unknown as ExecutionContext,
),
);
assert.equal(result.status, 429);
assert.equal(result.headers.get("retry-after"), "10");
assert.equal(result.headers.get("cache-control"), "no-store");
for (const header of ["etag", "last-modified", "content-length"]) {
assert.equal(result.headers.get(header), null, header);
}
assert.equal(result.headers.get("x-content-type-options"), "nosniff");
assert.match(await result.text(), /429 page, retry in <span id="cd">10<\/span>s/);
assert.equal(logs[0]?.event, "ratelimit.exceeded");
assert.equal(logs[0]?.group, "site");
});
it("spends one budget per client on every route, IPv6 by its /64", async () => {
const limiter = new FakeRateLimiter(100);
const from = (ip: string) => ({ headers: { "cf-connecting-ip": ip } });
await run("https://poli0981.dev/", from("2001:db8:0:1::1"), { RL_SITE: limiter });
await run("https://poli0981.dev/blog/", from("2001:db8:0:1::2"), { RL_SITE: limiter });
await run("https://poli0981.dev/api/health", {}, { RL_SITE: limiter });
await run("https://poli0981.dev/media/v1/x/webp-800", {}, { RL_SITE: limiter });
await run("https://poli0981.dev/pagefind/pagefind.js", {}, { RL_SITE: limiter });
assert.deepEqual(Object.fromEntries(limiter.counts), {
"site:2001:db8:0:1::/64": 2,
"site:198.51.100.7": 3,
});
});
it("is checked before the gate, and a limited client never sees the page", async () => {
const limiter = new FakeRateLimiter(0);
const { response } = await run("https://poli0981.dev/", {}, { ...gateOn, RL_SITE: limiter });
assert.equal(response.status, 429);
assert.doesNotMatch(await response.text(), /real page|data-human-check/);
});
it("leaves the admin host and requests without a client address alone", async () => {
const limiter = new FakeRateLimiter(0);
const admin = await run("https://admin.poli0981.dev/admin/", {}, { RL_SITE: limiter });
assert.match(await admin.response.text(), /from the Astro handler/);
const { env } = makeEnv({ RL_SITE: limiter });
const anonymous = await fetchWorker(
new Request("https://poli0981.dev/"),
env,
fakeContext() as unknown as ExecutionContext,
);
assert.equal(anonymous.status, 200);
assert.equal(limiter.counts.size, 0);
});
it("fails open when the limiter breaks — without skipping the gate", async () => {
const limiter = new FakeRateLimiter(100);
limiter.failWith = new Error("rate limiter down");
const { env } = makeEnv({ ...gateOn, RL_SITE: limiter });
const { result, logs } = await captureLogs(() =>
fetchWorker(
request("https://poli0981.dev/"),
env,
fakeContext() as unknown as ExecutionContext,
),
);
assert.equal(result.status, 200);
assert.match(await result.text(), /data-human-check/);
assert.equal(logs[0]?.event, "ratelimit.unavailable");
});
it("stays a 429 when the page can't be fetched — never the ungated page", async () => {
const { env } = makeEnv({ ...gateOn, RL_SITE: new FakeRateLimiter(0) });
(env as unknown as { ASSETS: { fetch: () => never } }).ASSETS.fetch = () => {
throw new Error("assets down");
};
const { result, logs } = await captureLogs(() =>
fetchWorker(
request("https://poli0981.dev/"),
env,
fakeContext() as unknown as ExecutionContext,
),
);
assert.equal(result.status, 429);
assert.equal(result.headers.get("retry-after"), "10");
assert.equal(result.headers.get("cache-control"), "no-store");
assert.equal(await result.text(), "Too many requests");
assert.deepEqual(
logs.map((line) => line.event),
["ratelimit.exceeded", "ratelimit.page_failed"],
);
});
});
describe("worker: Turnstile gate", () => {
it("answers a page view without a pass with the gate", async () => {
const { response } = await run("https://poli0981.dev/", {}, gateOn);
+7 -1
View File
@@ -64,8 +64,14 @@
// Workers Rate Limiting (docs 06 §2) — replaces the KV read-then-write counter. The
// period must be 10 or 60 s; counters are per Cloudflare location, so these are
// per-colo soft limits (the zone WAF rule in docs 07 §6 stays the hard outer limit).
// namespace_id only has to be unique within the account.
// namespace_id only has to be unique within the account. A period here must match its
// Retry-After in src/lib/ratelimit.ts (tests/lib.test.ts checks).
"ratelimits": [
// Site-wide, per client, for every request the Worker sees (src/worker.ts): pages,
// /media, /ext-img, /pagefind and the API. A page view costs 1–20 of these (static
// assets never reach the Worker), so 100 per 10 s only stops floods and F5-spam; the
// /api groups below are the strict ones. The WAF rule sits above it (docs 07 §6).
{ "name": "RL_SITE", "namespace_id": "981005", "simple": { "limit": 100, "period": 10 } },
{ "name": "RL_REPORT", "namespace_id": "981001", "simple": { "limit": 5, "period": 60 } },
// Generous: one carrier-grade-NAT address can front many phones on VN mobile networks.
{ "name": "RL_GATE", "namespace_id": "981002", "simple": { "limit": 30, "period": 60 } },