28 Commits
Author SHA1 Message Date
poli0981andClaude Fable 5.2 24d7c1b117 test(a11y): wider coverage, status checks, and claims that match it
Every sitemap page is checked for sideways scrolling at 320px; the light-theme and phone scans cover a page of every template; a page that does not answer the expected status fails instead of being scanned as an error page; the search focus trap is exercised with results listed; the legal notice is checked at tablet and small-laptop sizes; the story reader is walked backwards with Shift+Tab; each half of a legal page must declare its language. ACCESSIBILITY.md says what the palette test and the suite actually cover, and that the live widgets are not in the test build. CI prints the preview log when the job fails.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 7511f0c45e fix(a11y): findings from an independent review of the branch
Regressions from this branch: overflow-wrap anywhere broke words inside the AI-usage table (break-word now, with minmax(0, 1fr) grid columns so the legal layout can still shrink); the legal notice kept covering footer controls between 768 and about 1100px (the body makes room for it at every width); the home link was a 32x12px mark once the wordmark was hidden (it keeps a 40px box); the sitemap filter dropped any path containing an admin segment (anchored to the host root); prefers-contrast did not reach the sepia reader theme.

Older bugs the new statement made claims about: Tab could leave the search dialog once results were listed, because the trap counted the tabindex=-1 options; and the half of a legal page that is not in the page's language had no lang (each half is wrapped at build time, src/lib/legal-lang.ts).

Found by the wider reflow sweep: the album photo grid used 1fr columns, which grew past a 320px screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 9f0a704280 docs: note the admin routes excluded from the sitemap
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 28400cc2bc fix(ui): keep the space around the breadcrumb slash
Turning the project, gallery and tag breadcrumbs into nav landmarks split them into elements, and the build strips the whitespace between elements: they rendered as one run-together string. They are flex rows with a gap now, like the post breadcrumb.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 b6a5282a41 fix(a11y): measure the legal notice from its own height, not its offset
The height published for the page's scroll padding came from offsetTop, which is not guaranteed to be viewport-relative for a fixed element once the page is scrolled. It is now the sheet's height plus its gap to the bottom edge, and the suite checks the published value against what the sheet covers after the page has scrolled, and that it is removed with the sheet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 a6aef58b46 docs: absolute link to ACCESSIBILITY.md in the pull request template
The template's text becomes a pull request body, where a relative link resolves against the pull request's URL, not the repository tree.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 21178aa35f docs: accessibility across README, changelog 2.2.0 and the design docs
README gains an Accessibility section and the test:a11y command. CHANGELOG 2.2.0. Design docs: decision D20, the a11y target in the PRD, the checklist in 03 section 8, the legal route list and legal notice in 05, the accessibility@ alias in 07, the CI gate in 08, the roadmap entry and the maintenance tasks in 17.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 0fb60fe867 test(a11y): axe-core, keyboard, reflow and forced-colours suite in the build check
npm run test:a11y drives the installed Chrome through Playwright against npm run preview: axe-core (WCAG 2.2 A and AA plus best practices) over every page in the build's sitemap, one page per template again in the light theme and at phone width, and the menu, search, photo viewer, report dialog, reading settings and legal notice while open; then the keyboard contract, no sideways scrolling at 320, 360 and 390px, and the forced-colours rules. It runs inside the required build job after the smoke test. New dev dependencies playwright 1.65.0 and @axe-core/playwright 4.14.0, both past the three-day cooldown and without install scripts. sonar.projectVersion catches up to 2.2.0.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 6ce2b7077f feat(a11y): forced colours, cues beyond colour, focus and reflow fixes
Forced colours (Windows High Contrast): the search field and its active result keep an outline, the scrollbar switch shows its knob and state, the chosen reading option is filled. prefers-contrast: more strengthens hairlines and drops the grain.

Not by colour alone: the current page is underlined in the header and the legal sidebar and gets a bar on its tab; the chosen reading option is bold and double-ruled; links inside the Q&A contact list are underlined.

Focus: scroll padding now clears the mobile tab bar, the story reader bar and the legal notice, which rests on top of the tab bar instead of covering it and publishes its height. Esc in the reading panel returns focus to the Aa button; pressing play keeps focus on the player; the report form ties its error to the field.

Reflow: the header needed 378px (vi) or 400px (en), so pages scrolled sideways at 360px and English pages did at 390px. The language switch shows its code below those widths and the wordmark goes below 352px; prose breaks long URLs.

Names and structure: unique names for the navs that shared one with the footer, play buttons carry their video title, the search close button is named Esc - Close, card headings take a level so lists no longer skip h2, breadcrumbs and the legal notice are landmarks, the photo viewer announces the caption on change. Footer social icons are 44px targets.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 84ce2b8876 fix(seo): keep the admin routes out of the sitemap
The sitemap listed seven /admin/ URLs. They are prerendered shells that only exist on admin.poli0981.dev; on this host they answer 301 or 403. Found while driving the accessibility suite from the sitemap.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 004cf466ce feat(a11y): accessibility statement, issue and PR templates
A seventh legal page, /legal/accessibility (content repo c9e9827), linked from the footer, the menu, the legal sidebar and the legal notice. ACCESSIBILITY.md at the root is the repository's copy with the notes for contributors, which also ticks the Accessibility entry of GitHub's community standards. New issue template (label accessibility) and a pull request template carrying the checklist. The content bump also brings alt text for the four FrameLedger screenshots.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 08:27:12 +07:00
poli0981andClaude Fable 5.2 46cede84e3 chore(deps): Tailwind CSS 4.3.5 (#125)
tailwindcss and @tailwindcss/vite 4.3.4 -> 4.3.5, with their transitive patches (npm update --save --before=2026-11-06T23:43Z, the same three-day cooldown Dependabot applies). Astro 7.4.8, jose 6.2.17, marked 18.2.0, typescript-eslint 8.72.2, wrangler 4.159.0, eslint-plugin-svelte 3.24.1 and knip 6.44.2 are younger than three days and wait for the next Dependabot run.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 07:12:43 +07:00
dependabot[bot] 5eb87b45d5 chore(deps): Bump SonarSource/sonarqube-scan-action from 8.4.0 to 8.4.1 (#124)
Bumps [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action) from 8.4.0 to 8.4.1.
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/4d1dc0c91ee400dcf8a6dddf2f705ac36542e304...e805d875275f728fac1885b413934be6d7c63f65)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-09 20:53:14 +07:00
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
85 changed files with 3879 additions and 1640 deletions

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
name: Rào cản trợ năng / Accessibility barrier
description: Điều gì đó trên poli0981.dev khó hoặc không dùng được / Something on poli0981.dev is hard or impossible to use
title: "[a11y] "
labels: ["accessibility"]
body:
- type: markdown
attributes:
value: |
Cảm ơn bạn đã báo. Bạn không cần tự tìm nguyên nhân, và không cần nói gì về tình trạng khuyết tật của mình.
Thanks for reporting. You do not have to diagnose anything, and you never need to tell me about a disability.
Không muốn đăng công khai? Gửi email tới accessibility@poli0981.dev hoặc dùng nút "Báo lỗi" ở cuối mọi trang (không cần tài khoản).
Prefer not to post in public? Email accessibility@poli0981.dev, or use "Report a bug" at the bottom of every page (no account needed).
- type: textarea
id: goal
attributes:
label: Bạn đang định làm gì? / What were you trying to do?
description: Ví dụ "mở menu bằng bàn phím" / For example "open the menu with the keyboard"
validations:
required: true
- type: textarea
id: barrier
attributes:
label: Điều gì đã xảy ra? / What happened instead?
description: Các bước tái hiện nếu có / Steps to reproduce, if you have them
validations:
required: true
- type: input
id: route
attributes:
label: Trang / Page
placeholder: "https://poli0981.dev/…"
- type: textarea
id: environment
attributes:
label: Môi trường / Environment
description: Hệ điều hành, trình duyệt, công nghệ hỗ trợ và phiên bản / Operating system, browser, assistive technology and versions
placeholder: "Windows 11 · Edge 142 · Narrator"
- type: dropdown
id: severity
attributes:
label: Mức độ / Severity
description: Để mình biết nên xử lý cái nào trước / So I know what to handle first
options:
- "Chặn hẳn — không làm được việc chính / Critical — blocks a core task"
- "Nghiêm trọng — rất khó, nhưng có cách khác / Serious — major difficulty, a workaround exists"
- "Vừa — gây khó chịu hoặc không nhất quán / Moderate — annoying or inconsistent"
- "Nhẹ — ảnh hưởng ít / Minor — little impact"
validations:
required: true
+22
View File
@@ -0,0 +1,22 @@
## What and why
<!-- One or two sentences. Link the issue if there is one. -->
## Checks
- [ ] `npm run format:check`, `npm run lint`, `npm run check`, `npm run typecheck`, `npm test`
- [ ] `CHANGELOG.md` updated under `[Unreleased]` when visitors or operators would notice the change
## Accessibility (only if the interface changed)
See [`ACCESSIBILITY.md`](https://github.com/poli0981/poli0981-dev/blob/main/ACCESSIBILITY.md).
`npm run test:a11y` covers what a machine can check; the rest is by hand.
- [ ] Works with the keyboard alone, start to finish; focus is visible and never lands under a fixed bar
- [ ] Anything that opens (menu, dialog, panel) closes with Esc and hands focus back to what opened it
- [ ] Icon-only controls have a name that starts with their visible text, taken from `src/i18n`
- [ ] State and "you are here" are not shown by colour alone; new colours go through `tests/palette.test.ts`
- [ ] Headings do not skip a level; images have an `alt` (empty only when decorative)
- [ ] New animation has a still branch under `prefers-reduced-motion`
- [ ] Looked at 320 px wide, at 200% zoom, in dark and light, in Vietnamese and English
- [ ] Listened to once with a screen reader
+24 -1
View File
@@ -117,6 +117,29 @@ jobs:
- name: Smoke test built worker
run: npm run smoke
# Accessibility gate (ACCESSIBILITY.md). The same build is served by `astro preview`
# (workerd, real bindings, no bot gate without its secrets) and driven with the
# runner's own Chrome — Playwright downloads no browser. axe-core scans every page in
# the sitemap and the dialogs while open; the keyboard, reflow and forced-colours
# checks follow. Runs inside this job because `build` is the required status check.
- name: Start preview server
run: |
npm run preview > "$RUNNER_TEMP/preview.log" 2>&1 &
for i in $(seq 1 60); do
if curl -sf -o /dev/null http://localhost:4321/; then
echo "preview up after ${i}s"; exit 0
fi
sleep 1
done
echo "preview server never came up"; cat "$RUNNER_TEMP/preview.log"; exit 1
- name: Accessibility tests (axe + keyboard)
run: npm run test:a11y
- name: Preview server log (on failure)
if: failure()
run: tail -n 100 "$RUNNER_TEMP/preview.log" || true
- name: Upload coverage
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
@@ -160,7 +183,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@e805d875275f728fac1885b413934be6d7c63f65 # v8.4.1
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
+154
View File
@@ -0,0 +1,154 @@
# Accessibility
How accessibility is handled on [poli0981.dev](https://poli0981.dev): what the site aims for, what is
in place, how it is tested, what is known not to work, and how to report a barrier.
The statement written for visitors, in English and Vietnamese, is on the site at
[`/legal/accessibility`](https://poli0981.dev/legal/accessibility/) (and
[`/en/legal/accessibility`](https://poli0981.dev/en/legal/accessibility/)). This file is the
repository's copy, with the notes for people who work on the code — if the two ever disagree about
what a visitor can expect, the site wins.
> Tiếng Việt: tuyên bố trợ năng dành cho khách truy cập nằm ở
> [`/legal/accessibility`](https://poli0981.dev/legal/accessibility/). Gặp rào cản? Gửi email tới
> **accessibility@poli0981.dev** hoặc dùng nút "Báo lỗi" ở cuối mọi trang.
## Reporting a barrier
Email **accessibility@poli0981.dev**, or use **Report a bug** at the bottom of every page — it needs
no account and lands in a private tracker. If you use GitHub, you can open an issue with the
[Accessibility template](https://github.com/poli0981/poli0981-dev/issues/new?template=accessibility.yml).
It helps to say which page, what you were trying to do, what happened instead, and which browser and
assistive technology you use. You do not have to diagnose anything, and you never need to tell me
about a disability.
Expect a reply within 7 days. Reports are handled in this order:
- **Critical** — blocks a core task (reading a page, moving around the site, reporting a problem)
- **Serious** — major difficulty, but there is another way to do it
- **Moderate** — annoying or inconsistent
- **Minor** — little impact
This is a personal site maintained by one person, in their spare time, so there is no fixed date for
every fix. You will be told what is planned, and a workaround if there is one.
## Target
[WCAG 2.2](https://www.w3.org/TR/WCAG22/) Level AA, used as the guide for design and review. The site
has not been audited by a third party, and this is not a claim of conformance.
## What is in place
- **Keyboard.** Every page works with the keyboard alone. There is a skip link
(`src/components/SkipLink.astro`) and one focus ring for everything (`src/styles/global.css`). The
menu sheet, the search and the photo viewer trap focus while open, close with Esc and hand focus
back to what opened them; the report form is a native `<dialog>`. `/` opens the search. The
page's scroll padding keeps whatever takes focus clear of the sticky header, the mobile tab bar
and the legal notice.
- **Screen readers.** Each page declares its language, and text in the other language carries its
own: the language switch, and each half of a legal page, which holds both languages
(`src/lib/legal-lang.ts`). There is one `<h1>` per page and heading levels do not skip. Every `<nav>` has its own name, taken
from `src/i18n`. Icon-only controls are named, and a name starts with the text that is visible
(WCAG 2.5.3). The search is an ARIA combobox. Live regions announce search results, the photo
viewer's position and caption, and the report form's status.
- **Colour and contrast.** In both palettes, text is at least 4.5:1 on every surface it sits on,
and the line colour used where a boundary has to be seen is at least 3:1;
`tests/palette.test.ts` fails the build if one drops below. Decorative hairlines are fainter.
The current page and a chosen option are never shown by colour alone. Windows High Contrast (`forced-colors`) and
`prefers-contrast: more` are handled.
- **Motion.** One global rule collapses every animation under `prefers-reduced-motion`, and
scripted motion follows it (`src/lib/motion.ts`). Nothing loops or plays by itself; a YouTube
video loads only after its play button is pressed.
- **Zoom and reflow.** Type is fluid and in `rem`, zooming is never locked, and pages reflow down
to a 320 px viewport.
- **Touch.** The tab bar's targets are 56 px tall, the header's controls 40 px and the footer's
icons 44 px. Text links in the footer and the sidebars are about 24 px tall or less and meet
WCAG 2.5.8 through the space around them.
- **Reading.** Stories have their own settings: three text sizes and a paper, sepia or dark
background.
## Tested with
| How | What |
| ---------------- | ------------------------------------------------------------------ |
| Keyboard only | Chrome, Edge and Brave on Windows 11 |
| Windows Narrator | Edge, Chrome and Brave on Windows 11 |
| VoiceOver | Safari on iPhone |
| Automated | axe-core in Chrome, on every pull request (see "For contributors") |
Not yet tested by the maintainer: NVDA, JAWS, TalkBack, VoiceOver on macOS, and voice control. They
are expected to work; a report saying otherwise is welcome.
The site supports the current versions of Chrome, Edge, Firefox and Safari, on desktop and mobile.
## Known limitations
- **Bot check.** A first visit passes through a Cloudflare Turnstile check. It usually needs no
action, but it is a third-party component this repository cannot change. Anyone it stops can
write to the address above.
- **Videos.** Videos are YouTube embeds. Captions are whatever YouTube provides for each video;
there are no transcripts.
- **Older images.** Gallery photos must have a caption in both languages (the build fails
otherwise). A few images inside older posts may still lack a text alternative.
- **Offline mini-game.** The game on the offline page is drawn on a canvas. It can be played with
the Space key, but a screen reader cannot follow it. It is an extra, not content.
- **Search** needs JavaScript. Without it, every page is still reachable from the menu and the
footer links.
- **The admin** (`admin.poli0981.dev`) is a single-owner tool and is not covered by this document.
- **Automated checks run in Chrome only**, and no tool can judge everything: a passing run is
necessary, not sufficient. The live widgets (latest video, now playing) have no data in the
test build, so their markup is checked by hand.
## For contributors
A change to the interface is expected to keep all of this true:
- It works with the keyboard alone, start to finish; focus is visible and never lands under a fixed bar.
- Anything that opens closes with Esc and hands focus back to what opened it.
- Icon-only controls have a name that starts with their visible text, taken from `src/i18n`.
- State and "you are here" are not shown by colour alone. A new colour goes into
`src/lib/palette.ts` and `src/styles/global.css` together, where the palette test checks it.
- Headings do not skip a level; images have an `alt`, empty only when they are decorative.
- New animation has a still branch under `prefers-reduced-motion`.
- It has been looked at 320 px wide, at 200% zoom, in dark and light, in Vietnamese and English,
and listened to once with a screen reader.
What the pipeline checks:
- **`npm run test:a11y`** runs in the required `build` check, so a pull request with a violation
cannot be merged. It scans every page listed in the build's sitemap with axe-core (WCAG 2.2 A and
AA rules plus axe's best practices), a page of each template again in the light theme and at
phone width, and the menu, search, photo viewer, report dialog, reading settings and legal notice
while they are open. It then walks the keyboard contract — the skip link, focus traps, Esc and
focus return, focus not hidden under a bar in either direction — checks that no page scrolls
sideways at 320 px (and a sample at 360 and 390 px), and checks the forced-colours rules. The
tests are in `tests/a11y/`.
- **`tests/palette.test.ts`** checks the text and line colours of both palettes against AA.
- **Lighthouse** reports an accessibility score on pull requests; it is advisory.
To run the suite locally, build and serve the site, then run it from a second terminal:
```bash
npm run build
```
```bash
npm run preview
```
```bash
npm run test:a11y
```
It drives the Chrome that is already installed; set `A11Y_CHANNEL=msedge` to use Edge instead. If a
rule cannot be met, say why in the pull request rather than switching the rule off.
## Ownership and review
Maintained by Kokone ([poli0981](https://github.com/poli0981)), the site's only maintainer, who
triages reports and keeps this file and the site's statement in step. Both are reviewed with every
release that changes the interface and at least once a year
([`17_MAINTENANCE.md`](poli0981.dev-docs/17_MAINTENANCE.md)).
Last reviewed: 2026-11-10 (v2.2.0).
+134 -1
View File
@@ -5,6 +5,131 @@ 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.2.0] — 2026-11-10
### Added
- **Accessibility statement.** A new page, `/legal/accessibility` (Vietnamese and English), says
what the site aims for (WCAG 2.2 AA, as a guide — it has not been audited), what is in place, how
it is tested, what is known not to work and how to report a barrier: a new address,
accessibility@poli0981.dev, or the "Report a bug" button. [`ACCESSIBILITY.md`](ACCESSIBILITY.md)
is the repository's copy, with the notes for contributors; there is an accessibility issue
template and a pull request template with the checklist.
- **Accessibility gate in CI.** `npm run test:a11y` runs in the required `build` check: axe-core
over every page in the sitemap and over the menu, search, photo viewer, report dialog, reading
settings and legal notice while open, then keyboard, reflow and forced-colours tests
(`tests/a11y/`, Playwright driving the runner's Chrome). Lighthouse stays advisory.
- Windows High Contrast (`forced-colors`): the search field and its active result keep a visible
indicator, the scrollbar switch shows its knob and state, and the chosen reading option is
filled. `prefers-contrast: more` strengthens hairlines and drops the film grain.
### Changed
- The current page is marked by more than colour: an underline in the header and in the legal
sidebar, a bar along the top of the current tab on phones. The chosen reading option is bold and
double-ruled.
- Footer social icons are 44 px targets (the icons keep their size); the row is a little wider.
- On a phone the legal notice rests on top of the tab bar instead of covering it.
- Below 384 px (Vietnamese pages) or 404 px (English pages) the language switch shows `EN` / `VI`
instead of the full name, and below 352 px the header drops the "SkullMute" wordmark.
- Dependencies: Tailwind CSS 4.3.5. New dev dependencies: `playwright` 1.65 and
`@axe-core/playwright` 4.14, both older than the three-day cooldown and without install scripts.
### Fixed
- The header was wider than the screen on narrow phones — it needs 378 px in Vietnamese and 400 px
in English — so pages scrolled sideways at 360 px, and English pages did on a 390 px iPhone. Pages
now reflow down to 320 px; a long URL in a legal page no longer widens it either.
- Focus could land underneath the mobile tab bar, the legal notice or the story reader's bar. The
page's scroll padding now accounts for all three.
- Esc in the story reader's "Aa" panel dropped focus to the top of the page; it returns to the
button. Pressing play on a video keeps focus on the player.
- Tab could walk out of the search dialog once results were listed; the trap now counts only what
Tab can reach.
- A legal page holds both languages, and the half that is not in the page's language had no
`lang`, so a screen reader read it with the wrong voice. Each half now declares its own.
- Names: the three "Play video" buttons on the gaming page each carry their video's title; the
search's "Esc" button is named "Esc — Close"; the "Social" and "Legal" navs that shared a name
with the footer's (dev and gaming pages, menu sheet, legal sidebar) have their own.
- Headings no longer skip from h1 to h3 on the blog, tag, project and gallery lists. Project,
gallery and tag breadcrumbs are navigation landmarks, and the legal notice is a landmark.
- Links inside the Q&A contact list are underlined, not told apart by colour alone.
- The report form ties its "too short" message to the text box and returns focus there. The photo
viewer announces the caption when you move to another photo, and no longer reads it three times.
- The sitemap listed seven `/admin/` URLs that only exist on the admin host.
- The four FrameLedger screenshots have text alternatives (content repository).
## [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 +204,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 +218,10 @@ 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.2.0...HEAD
[2.2.0]: https://github.com/poli0981/poli0981-dev/compare/v2.1.2...v2.2.0
[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
+11 -1
View File
@@ -20,7 +20,7 @@ the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https
| Content | Markdown/MDX in [`poli0981/content`](https://github.com/poli0981/content) (git submodule `src/content`) |
| Search | Pagefind (built after `astro build`) |
| Tooling | Node 26 · TypeScript 7 (`tsc`) next to TypeScript 6 (astro check, typescript-eslint) · `node:test` · ESLint · Prettier · knip |
| Quality | SonarCloud quality gate · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) |
| Quality | SonarCloud quality gate · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) · axe-core accessibility gate |
## How it fits together
@@ -65,6 +65,8 @@ 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 test:a11y` | axe-core, keyboard, reflow and forced-colours checks against `npm run preview` (Chrome) |
| `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) |
@@ -91,6 +93,14 @@ JWT (≤ 24 hours old) and an email allowlist on every request.
Please report vulnerabilities privately — see [`SECURITY.md`](SECURITY.md). Bug reports from the
site's "Report a bug" button land in a private repository, not in this one's issues.
## Accessibility
The site aims for WCAG 2.2 AA and checks it on every pull request (axe-core over every page, plus
keyboard, reflow and forced-colours tests). What is in place, what is known not to work and how to
report a barrier: [`ACCESSIBILITY.md`](ACCESSIBILITY.md); the statement for visitors is at
[`/legal/accessibility`](https://poli0981.dev/legal/accessibility/). Barriers can be reported to
**accessibility@poli0981.dev**.
## License
- **Code**: [GPL-3.0-only](LICENSE).
+6 -4
View File
@@ -14,7 +14,7 @@ CI fails if it drifts (docs 08 §6). Edit the script, not the block.
Generated by `scripts/gen-notices.mjs` from `package-lock.json`. CI fails if this
block drifts, so do not edit it by hand.
## Direct dependencies (34)
## Direct dependencies (36)
`runtime` are declared in `dependencies`; `build` in `devDependencies` and never served.
@@ -26,6 +26,7 @@ block drifts, so do not edit it by hand.
| `@astrojs/rss` | MIT | runtime |
| `@astrojs/sitemap` | MIT | runtime |
| `@astrojs/svelte` | MIT | runtime |
| `@axe-core/playwright` | MPL-2.0 | build |
| `@resvg/resvg-js` | MPL-2.0 | build |
| `@tailwindcss/vite` | MIT | runtime |
| `@types/node` | MIT | build |
@@ -40,6 +41,7 @@ block drifts, so do not edit it by hand.
| `lefthook` | MIT | build |
| `marked` | MIT | runtime |
| `pagefind` | MIT | build |
| `playwright` | Apache-2.0 | build |
| `prettier` | MIT | build |
| `prettier-plugin-astro` | MIT | build |
| `prettier-plugin-svelte` | MIT | build |
@@ -60,9 +62,9 @@ block drifts, so do not edit it by hand.
| License | Packages |
| ------- | -------- |
| MIT | 26 |
| Apache-2.0 | 3 |
| Apache-2.0 | 4 |
| MPL-2.0 | 3 |
| ISC | 2 |
| MPL-2.0 | 2 |
| MIT OR Apache-2.0 | 1 |
Transitive dependencies are deliberately not tallied here. Which packages get installed
@@ -72,7 +74,7 @@ inventory is `package-lock.json`; platform binaries are covered in prose below.
## Licenses outside the standard allowlist
**MPL-2.0** — 2 package(s): `@resvg/resvg-js`, `satori`
**MPL-2.0** — 3 package(s): `@axe-core/playwright`, `@resvg/resvg-js`, `satori`
> Reviewed: File-level copyleft. satori and @resvg/resvg-js are used unmodified as build-time tools and never shipped to the browser, so no source-disclosure obligation is triggered.
+34 -2
View File
@@ -5,10 +5,15 @@ 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.
const NON_INDEXED = /\/(404|500|403|429|offline)\/?$/;
// Error/system pages that must never appear in the sitemap — and the admin's routes, which
// only exist on admin.poli0981.dev (on this host they answer 301/403) but were listed
// because they are prerendered shells like any other page.
const NON_INDEXED = /\/(404|500|403|429|offline)\/?$|^https?:\/\/[^/]+\/admin(\/|$)/;
// Sitemap <lastmod>. Every deploy is a full rebuild, so build time is the truthful
// "as of" for the whole site.
@@ -34,6 +39,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 +78,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 +144,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."
+1516 -1306
View File
File diff suppressed because it is too large. Load diff
+21 -16
View File
@@ -18,9 +18,11 @@
"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\"",
"test:a11y": "node --test --test-concurrency=1 \"tests/a11y/*.spec.ts\"",
"gen-notices": "node scripts/gen-notices.mjs",
"new:post": "node scripts/new-post.mjs",
"gen-og": "node scripts/gen-og.mjs",
@@ -41,39 +43,42 @@
},
"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.5",
"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.5",
"yaml": "^2.9.1",
"zod": "^4.6.7"
},
"devDependencies": {
"@astrojs/check": "^0.9.12",
"@axe-core/playwright": "^4.14.0",
"@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",
"playwright": "^1.65.0",
"prettier": "^3.9.10",
"prettier-plugin-astro": "^0.14.1",
"prettier-plugin-svelte": "^4.1.1",
@@ -81,7 +86,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"
}
}
+4 -3
View File
@@ -29,9 +29,9 @@
| 16 | 16_COST.md | Chi phí chốt + ngưỡng cần theo dõi |
| 17 | 17_MAINTENANCE.md | Lịch bảo trì, update playbook, backup |
`12_LEGAL/`: `TERMS_OF_USE.md` · `PRIVACY_POLICY.md` · `DISCLAIMER.md` · `THIRD_PARTY_NOTICES.md` · `CONTENT_LICENSE.md` — **bản nháp gốc** (07/2026). Văn bản đang hiệu lực là `legal/*.md` trong repo `poli0981/content` (render ở `/legal/*`); sửa ở đó, không sửa ở đây.
`12_LEGAL/`: `TERMS_OF_USE.md` · `PRIVACY_POLICY.md` · `DISCLAIMER.md` · `THIRD_PARTY_NOTICES.md` · `CONTENT_LICENSE.md` — **bản nháp gốc** (07/2026). Văn bản đang hiệu lực là `legal/*.md` trong repo `poli0981/content` (render ở `/legal/*`); sửa ở đó, không sửa ở đây. Hai trang thêm sau (`ai-usage`, `accessibility`) chỉ có ở repo content, không có bản nháp tại đây.
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-10-24)
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-11-10)
| # | Quyết định | Chọn |
|---|---|---|
@@ -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/` |
@@ -54,6 +54,7 @@
| D17 | Toolchain (10/2026) | Node 26 · TypeScript 7 (`tsc` kiểm kiểu) chạy song song TypeScript 6 (astro check, typescript-eslint, svelte2tsx cần JS API) · test bằng `node:test` (không thêm deps) · SonarCloud phân tích qua CI (`08` §0) |
| D18 | Báo lỗi (10/2026) | Issue tạo ở repo **private** `poli0981/site-reports` (repo site đã public) — `10` §4 |
| D19 | Phát hành | Tag `vX.Y.Z` có ký GPG + GitHub Release + `CHANGELOG.md`; deploy vẫn là "merge `main`" (`08` §8) |
| D20 | Trợ năng (11/2026, v2.2.0) | Mục tiêu **WCAG 2.2 AA** — kim chỉ nam, không tự nhận đã được kiểm định. Tuyên bố cho khách ở `/legal/accessibility` (song ngữ, repo content); `ACCESSIBILITY.md` ở root là bản của repo kèm ghi chú cho người sửa code (trang site thắng nếu lệch). Rào cản báo về `accessibility@` hoặc nút "Báo lỗi". Cổng tự động: `npm run test:a11y` (axe-core + bàn phím + reflow + forced-colors, Playwright lái Chrome có sẵn) chạy trong check bắt buộc `build` (`08` §0, checklist ở `03` §8) — ngoại lệ có chủ đích của D17 "không thêm deps cho test" |
## Cách dùng suite
+2 -2
View File
@@ -45,7 +45,7 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
| /dev (/uses) | PC specs, tool stack, setup OBS/Resolve | P2 |
| /qa | FAQ tĩnh từ collection `faq` + khối "Liên hệ" trỏ /links và `contact@` | P1 |
| /links | Toàn bộ social (YouTube, Discord ×2, GitHub, Telegram, Bluesky, Mastodon, X, Facebook), icon + mô tả | P1 |
| /legal/* | 5 trang từ `12_LEGAL/`, song ngữ | P1 |
| /legal/* | 7 trang song ngữ: 5 trang gốc từ `12_LEGAL/` + `ai-usage` + `accessibility` (tuyên bố trợ năng, 11/2026) | P1 |
| Search | Pagefind, modal, lọc theo locale | P2 |
| Error/offline | 404/403/429/500/offline custom | P1 (mini-game P3) |
| Bug report | Nút footer → GitHub Issue + Discord | P2 |
@@ -54,7 +54,7 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
## 6. Yêu cầu phi chức năng
- **Hiệu năng**: xem `14_PERF_BUDGET.md` (LCP < 2.0s mobile 4G, Lighthouse ≥ 95).
- **A11y**: WCAG 2.1 AA cho contrast/focus/keyboard; `prefers-reduced-motion` được tôn trọng ở mọi animation.
- **A11y**: mục tiêu WCAG 2.2 AA (`ACCESSIBILITY.md`, `/legal/accessibility`): contrast/focus/keyboard, không dựa riêng vào màu, reflow tới 320px, `forced-colors`; `prefers-reduced-motion` được tôn trọng ở mọi animation. `npm run test:a11y` (axe-core + bàn phím) chặn PR.
- **i18n**: UI 100% song ngữ; nội dung theo bài; URL ổn định khi thêm locale mới.
- **SEO**: hreflang, sitemap, JSON-LD, OG image tự sinh (xem `13_SEO_RSS_OG.md`).
- **Bảo mật**: xem `06_SECURITY.md`; mọi phiên bản dependency không có CVE chưa vá ở thời điểm chốt.
+9 -8
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
@@ -66,11 +67,11 @@ poli0981-dev/
│ ├── lib/ # gate/, admin/, media/, denylist, ext-img, log, version, palette, theme…
│ ├── pages/ # routes + /en/* + api/* + admin/* + 403/404/429/500
│ └── styles/ # global.css (token), prose.css, admin.css
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/GitHub…)
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/GitHub…) · a11y/ (*.spec.ts: axe-core + bàn phím qua Playwright)
├── workers/widgets/ # worker cron riêng (wrangler.jsonc riêng)
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, dependabot.yml
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, dependabot.yml, ISSUE_TEMPLATE/ (bug_report, accessibility), pull_request_template.md
├── astro.config.mjs · wrangler.jsonc · sonar-project.properties · lefthook.yml · knip.json
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · CHANGELOG.md
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · ACCESSIBILITY.md · CHANGELOG.md
```
## 4. Rendering & routing
@@ -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" },
+9 -4
View File
@@ -126,10 +126,15 @@ Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai
## 8. A11y & mobile checklist (áp cho mọi PR UI)
- Focus ring rõ (2px accent, offset 2px), điều hướng bàn phím đủ; skip-link.
- Touch target ≥ 44×44; `safe-area-inset` cho TabBar; không hover-only cho thông tin.
- Ảnh có alt (bắt buộc trong schema gallery); icon-only button có `aria-label`.
- Kiểm tra 360px, 390px, 768px, 960px, 1280px; dark/light/theo hệ thống; vi/en (chuỗi EN thường dài hơn ~20%).
- Focus ring rõ (2px accent, offset 2px), điều hướng bàn phím đủ; skip-link. Thứ gì mở ra (menu, dialog, panel) thì đóng bằng Esc và **trả focus về nút đã mở nó**.
- Focus không được nằm dưới thanh cố định (WCAG 2.4.11): `scroll-padding` của `html` (global.css) đã trừ header, TabBar, thanh đọc truyện và bảng thông báo pháp lý — thanh mới ở mép trên/dưới phải cộng vào `--subheader-h` / `--bottom-bar-h`.
- Touch target: TabBar 56px, icon mạng xã hội ở footer 44px, nút header 40px; **không bao giờ dưới 24px** (WCAG 2.5.8). `safe-area-inset` cho TabBar; không hover-only cho thông tin.
- Trạng thái và "đang ở đâu" **không chỉ bằng màu** (WCAG 1.4.1): nav đang mở có gạch chân, tab đang mở có vạch trên, lựa chọn đang chọn in đậm + viền kép; link nằm giữa câu phải gạch chân.
- `forced-colors` (Windows High Contrast): thứ chỉ vẽ bằng `background`/`box-shadow` sẽ biến mất — thêm `outline` hoặc màu hệ thống (`Highlight`, `ButtonText`, `Canvas`…) trong `@media (forced-colors: active)`.
- Ảnh có alt (bắt buộc trong schema gallery; `alt=""` chỉ khi ảnh trang trí); icon-only button có `aria-label` **bắt đầu bằng chữ đang hiển thị** (WCAG 2.5.3 — axe so theo từng từ và bỏ phần trong ngoặc đơn).
- Heading không nhảy cấp: card (`PostCard`/`ProjectCard`/`GalleryCard`) nhận `headingLevel` — 2 khi nằm ngay dưới `h1`, 3 khi dưới một `h2`. Mỗi `<nav>` một tên riêng (footer đã dùng "Pháp lý" và "Mạng xã hội").
- Kiểm tra 320px, 360px, 390px, 768px, 960px, 1280px (không cuộn ngang ở bất kỳ mức nào); zoom 200%; dark/light/theo hệ thống; vi/en (chuỗi EN thường dài hơn ~20% — header cần 378px ở bản vi, 400px ở bản en, dưới đó nút ngôn ngữ rút thành `EN`/`VI`).
- `npm run test:a11y` xanh (axe-core mọi trang + các dialog khi mở, bàn phím, reflow, forced-colors — `tests/a11y/`), rồi nghe lại một lượt bằng trình đọc màn hình. Cam kết đầy đủ: `ACCESSIBILITY.md`.
- Màu mới phải vào `palette.ts` + `global.css` cùng lúc (test chặn nếu lệch hoặc dưới AA); không hard-code màu trong component — dùng token.
- `<dialog>` modal giữ `margin: auto` (preflight Tailwind xoá margin — global.css trả lại); danh sách trong `.prose` có marker (preflight xoá `list-style`).
- Nhãn landmark, aria-label và chuỗi giao diện lấy từ `src/i18n`, không viết cứng.
+4 -4
View File
@@ -12,10 +12,10 @@
| `/gallery`, `/gallery/[album]` | `/en/...` | gallery |
| `/gaming` · `/dev` (kèm `/dev/uses`) | `/en/...` | md + widgets |
| `/qa` · `/links` | `/en/...` | faq + data links |
| `/legal/{terms,privacy,disclaimer,third-party,licenses,ai-usage}` | `/en/legal/...` | `legal/*.md` (repo content) |
| `/legal/{terms,privacy,disclaimer,third-party,licenses,ai-usage,accessibility}` | `/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)
@@ -71,8 +71,8 @@ ReadingControls: cỡ chữ S/M/L · nền Giấy/Sepia/Tối (độc lập them
## 5. Legal gate — LegalGateSheet
- **Kích hoạt**: lần truy cập đầu (thiếu `localStorage.legalAck`), delay 800ms sau khi trang tương tác được; không hiện trên `/legal/*` và trang lỗi.
- **Hình thức**: bottom-sheet (mobile) / card góc phải dưới (desktop), chiếm ≤ 40% chiều cao, **không chặn scroll** — nội dung phía sau vẫn đọc được (SEO/crawler không ảnh hưởng vì chỉ là overlay client-side).
- **Nội dung** (song ngữ theo locale): 3 dòng — nội dung © Kokone; phần mềm/thương hiệu được nhắc tới thuộc chủ sở hữu tương ứng, site không liên kết; site dùng analytics không cookie. Link: Terms · Privacy · Disclaimer · Third-party · Licenses. Nút: **"Đã hiểu / Got it"** → `legalAck = {v:1, ts}`.
- **Hình thức**: bottom-sheet (mobile — nằm **trên** TabBar chứ không đè lên, để 4 nút của TabBar vẫn thấy và bấm được) / card góc phải dưới (desktop), chiếm ≤ 40% chiều cao, **không chặn scroll** — nội dung phía sau vẫn đọc được (SEO/crawler không ảnh hưởng vì chỉ là overlay client-side).
- **Nội dung** (song ngữ theo locale): 3 dòng — nội dung © Kokone; phần mềm/thương hiệu được nhắc tới thuộc chủ sở hữu tương ứng, site không liên kết; site dùng analytics không cookie. Link: cả 7 trang của `legalNav` (Terms · Privacy · Disclaimer · Third-party · Licenses · AI · Trợ năng). Nút: **"Đã hiểu / Got it"** → `legalAck = {v:1, ts}`. Sheet là landmark `complementary` có tên, công bố chiều cao của mình qua `--sheet-h` để focus phía sau không bị che (`03` §8).
- Đổi phiên bản văn bản legal lớn → tăng `v` để sheet hiện lại. Footer luôn có link legal (gate chỉ là lớp nhắc).
## 6. Copy & tone
+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)
+17 -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
@@ -95,6 +104,7 @@ Mail của domain chạy trên **Google Workspace** (MX → `aspmx.l.google.com`
| `contact@` | Liên hệ chung (fallback) | Footer, /links, /now, trang 403 |
| `security@` | Báo lỗ hổng | `/.well-known/security.txt`, `SECURITY.md` |
| `privacy@` | Yêu cầu về dữ liệu cá nhân | Privacy §7–8 |
| `accessibility@` | Báo rào cản trợ năng (trả lời ≤ 7 ngày) | `/legal/accessibility` §5, `ACCESSIBILITY.md`, issue template `accessibility.yml`, README |
| `legal@` | Vấn đề pháp lý | Terms |
| `copyright@` · `dmca@` · `takedown@` | Xin phép · khiếu nại bản quyền · yêu cầu gỡ khác | Licenses, `CONTENT-LICENSE.md` |
| `collab@` · `press@` · `sponsor@` | Hợp tác · báo chí · tài trợ | /links, Q&A, footer |
@@ -134,7 +144,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)
+2 -2
View File
@@ -4,7 +4,7 @@
- **Deploy**: Cloudflare **Workers Builds** nối repo (không có job deploy trong GitHub Actions): `main` → build + `npx wrangler deploy`; nhánh khác → `npx wrangler versions upload` (version preview, không nhận traffic). Cấu hình chi tiết + bẫy đã gặp: `07` §9.
- **`ci.yml`** (PR, push `main`, `workflow_dispatch`), job **`build`** (timeout 30 phút, checkout kèm submodule):
`npm ci --ignore-scripts` → `check-install-scripts` → `wrangler types` (site + widgets) → prettier → eslint → `astro check` (TS 6) → **`typecheck` bằng TypeScript 7** (in `tsc -v`, kiểm site + widgets) → knip → **`test:coverage`** (`node:test`, ngưỡng 80% dòng, xuất `coverage/lcov.info`) → `npm audit --omit=dev --audit-level=high` → `gen-notices --check` → `check-exif --changed` → build (+ OG, Pagefind, `check-csp-hashes`) → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/`/ext-img`/admin 403/`frame-ancestors`, pha ép bật cổng Turnstile kể cả cookie sai định dạng, pha denylist) → upload coverage làm artifact. Check `build` là **bắt buộc** (ruleset `main`).
`npm ci --ignore-scripts` → `check-install-scripts` → `wrangler types` (site + widgets) → prettier → eslint → `astro check` (TS 6) → **`typecheck` bằng TypeScript 7** (in `tsc -v`, kiểm site + widgets) → knip → **`test:coverage`** (`node:test`, ngưỡng 80% dòng, xuất `coverage/lcov.info`) → `npm audit --omit=dev --audit-level=high` → `gen-notices --check` → `check-exif --changed` → build (+ OG, Pagefind, `check-csp-hashes`) → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/`/ext-img`/admin 403/`frame-ancestors`, pha ép bật cổng Turnstile kể cả cookie sai định dạng, pha denylist) → **cổng trợ năng** (từ v2.2.0: `npm run preview` chạy nền rồi `npm run test:a11y` — Playwright lái Chrome có sẵn trên runner, không tải trình duyệt; axe-core quét mọi trang trong sitemap của bản build, một trang mỗi template ở theme sáng và bề rộng điện thoại, và menu/tìm kiếm/lightbox/hộp báo lỗi/bảng Aa/bảng pháp lý khi đang mở; sau đó là test bàn phím, reflow 320/360/390px và `forced-colors`) → upload coverage làm artifact. Check `build` là **bắt buộc** (ruleset `main`), nên PR có vi phạm axe không merge được.
- Job **`sonarcloud`** (sau `build`; chạy cho push `main` và PR cùng repo, bỏ qua Dependabot): tải coverage → `SonarSource/sonarqube-scan-action` (pin SHA) với `sonar-project.properties`; trên PR chờ **quality gate** ("Sonar way" cho new code: coverage ≥ 80%, trùng lặp ≤ 3%, rating A, hotspot đã review). Automatic analysis trên SonarCloud **tắt** (CI analysis thay thế); `SONAR_TOKEN` là secret của repo. `.svelte`/`.astro` không được Sonar phân tích — logic quan trọng nằm trong `.ts` để đo được.
- **CodeQL** (default setup, repo public) · **Snyk** (GitHub app) · **`osv-scanner.yml`** (reusable workflow v2.7.0, SARIF, hằng tuần + khi đổi lockfile) · **`lighthouse.yml`** (`treosh/lighthouse-ci-action` pin SHA, preset mobile, chỉ cảnh báo).
- **`content-bump.yml`** (nút **Xuất bản** của admin): trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR, auto-merge (squash) nếu diff chỉ `.md/.json`, rồi `gh workflow run ci.yml --ref content/bump` để có check `build` (PR mở bằng GITHUB_TOKEN không kích hoạt `pull_request`). Merge ⇒ Workers Builds deploy.
@@ -118,6 +118,6 @@ Commit và tag đều ký GPG; không dùng `--no-verify`.
- `main` protected (ruleset): PR + check `build` xanh; merge kiểu **squash**. Conventional Commits.
- Mỗi PR: CI `build` + SonarCloud quality gate + CodeQL xanh trước khi merge; Workers Builds trên nhánh PR chỉ `versions upload`.
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + GitHub Release (notes lấy từ `CHANGELOG.md`). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026.
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + GitHub Release (notes lấy từ `CHANGELOG.md`). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026. Mỗi tag: sửa `sonar.projectVersion` trong `sonar-project.properties` cho khớp.
- Sau merge: kiểm `https://poli0981.dev/api/health` trả đúng commit (`07` §9); nếu Workers Builds không deploy thì promote version của `main` bằng `wrangler versions deploy`.
+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 |
+1 -1
View File
@@ -16,7 +16,7 @@ Bài không có bản dịch: không render hreflang (tránh trỏ trang không
## 3. Sitemap & robots
- `@astrojs/sitemap` với `i18n` config → `sitemap-index.xml`; loại trang lỗi, `/offline`, trang draft.
- `@astrojs/sitemap` với `i18n` config → `sitemap-index.xml`; loại trang lỗi, `/offline`, trang draft và mọi route `/admin/*` (chỉ tồn tại trên `admin.poli0981.dev`; trước v2.2.0 bị lọt 7 URL vào sitemap). Bộ test trợ năng (`tests/a11y/`) lấy danh sách trang từ chính sitemap này.
- `public/robots.txt`:
```
+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`).
+2 -1
View File
@@ -38,6 +38,8 @@ Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chư
- Cổng Turnstile trước mọi trang (06 §3b) · admin `admin.poli0981.dev` (Access + JWT, R2 media, xuất bản qua workflow) · repo public.
- **v2.0.0**: Node 26 + TypeScript 7 · SonarCloud + test `node:test` (~99% dòng) · vá bypass cookie cổng · denylist CIDR · ảnh widget qua `/ext-img` · log JSON + version trên `/api/health` · báo lỗi vào repo private · palette Glacier Teal + theme theo hệ điều hành · sửa a11y/i18n · admin mới (tổng quan, hoạt động, bảo mật, audit log). Chi tiết: `CHANGELOG.md`.
- **v2.2.0** (11/2026): tuyên bố trợ năng (`/legal/accessibility` + `ACCESSIBILITY.md`, địa chỉ `accessibility@`) · cổng axe-core + bàn phím trong CI · hỗ trợ Windows High Contrast · "đang ở đâu" không chỉ bằng màu · sửa tràn ngang ở màn hình hẹp (reflow tới 320px) · focus không bị che dưới thanh cố định. Chi tiết: `CHANGELOG.md`, quyết định D20.
## P4 — Launch công khai 🟡
- [x] Checklist `06` §8 (security) phần tự động (headers, CSP, cổng)
@@ -57,6 +59,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 |
+3 -1
View File
@@ -9,7 +9,7 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
| **Hằng tuần** (thứ 2, sau khi Dependabot chạy) | Triage PR Dependabot: patch/minor xanh CI → merge; security alert → xử lý ≤ 48h. Liếc Discord `#site-reports` |
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; **nâng tay `@typescript/native`** (Dependabot bỏ qua alias `npm:`) và xem TS 7.1 đã có JS API chưa (`02` §8); xem Web Analytics + Core Web Vitals; liếc Workers Logs (lọc `level: error`) + dashboard admin (trạng thái cron widgets, secret thiếu); SonarCloud không có issue mới trên `main` |
| **Hằng quý** | Nâng major có kế hoạch (Astro/Tailwind/Wrangler — đọc upgrade guide trước); chạy lại ma trận error test `09` §5; backup ngoài (§4) |
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 5 văn bản legal (đổi thì tăng `v` của legalAck) · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 7 trang legal (đổi thì tăng `v` của legalAck) · **rà trợ năng**: đọc lại `/legal/accessibility` + `ACCESSIBILITY.md`, đi một lượt bằng bàn phím và trình đọc màn hình, cập nhật ngày rà ở cả hai nơi · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
Đặt reminder: dùng chính hệ notify/cron GitHub Actions quen thuộc — workflow cron tháng/quý/năm bắn Discord nhắc việc (input sẵn trong repo `.github`).
@@ -51,4 +51,6 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
| Spam form vượt rate-limit thường xuyên | Nâng Turnstile lên chế độ khó hơn + thêm custom rule quốc gia cho /api |
| Version sai lên production (PR được deploy, regression) | Rollback ngay (§2), rồi kiểm Deploy command của Workers Builds (`07` §9) |
| Bị khoá ngoài admin (Access/`ADMIN_EMAILS`) | `wrangler secret put ADMIN_EMAILS` với email đúng; kiểm policy Access; denylist có chặn nhầm IP mình không (`wrangler kv key get … denylist`) |
| Có báo cáo rào cản trợ năng (`accessibility@`, nút Báo lỗi, issue nhãn `accessibility`) | Trả lời ≤ 7 ngày; lỗi chặn hẳn việc đọc/dùng trang làm trước; nói rõ định làm gì + cách tạm thời; sửa xong thì thêm test vào `tests/a11y/` và, nếu chưa sửa được, ghi vào "Known limitations" của `ACCESSIBILITY.md` + trang `/legal/accessibility` |
| Release có đổi giao diện | `npm run test:a11y` xanh + nghe lại các chỗ đã đổi bằng Narrator/VoiceOver; cập nhật "Last reviewed" trong `ACCESSIBILITY.md` |
| Đổi email/mất hộp thư đích | Cập nhật alias Google Workspace + `src/lib/links.ts` + security.txt + legal contact ngay (`07` §11) |
+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);
+3 -2
View File
@@ -4,14 +4,15 @@ 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.2.0
sonar.sourceEncoding=UTF-8
# .github is analyzed too: the workflow rules (pinned actions, no npx/install scripts) are
# part of the supply-chain posture, not noise to exclude.
sonar.sources=src,workers/widgets/src,scripts,public,.github
sonar.tests=tests
sonar.test.inclusions=tests/**/*.test.ts
# *.spec.ts is the browser-driven accessibility suite (tests/a11y, `npm run test:a11y`).
sonar.test.inclusions=tests/**/*.test.ts,tests/**/*.spec.ts
# Not ours or not code: the content submodule (Markdown), photos, generated declaration
# files and the prebuilt search bundle.
+9 -2
View File
@@ -117,15 +117,22 @@ function relFor(href: string, me?: boolean): string | undefined {
.footer-legal a:hover {
color: var(--accent);
}
/* Each icon is 18px but its link is a 44px square (docs 03 §8; WCAG 2.5.8 asks for 24).
The negative margins take back the padding that adds, so the first icon still lines up
with the text above and the row keeps its height. */
.footer-social {
display: flex;
flex-wrap: wrap;
gap: 0.85rem;
align-items: center;
margin-block: 0.25rem;
margin-block: -0.5rem;
margin-inline-start: -0.8125rem;
}
.footer-social a {
display: inline-flex;
align-items: center;
justify-content: center;
min-inline-size: 2.75rem;
min-block-size: 2.75rem;
color: var(--muted);
transition: color var(--duration-fast) var(--ease-site);
}
+6 -2
View File
@@ -9,8 +9,12 @@ interface Props {
entry: GalleryEntry;
cover: GalleryPhoto;
locale: Locale;
/** Heading level of the card title: 3 under a section heading, 2 right under the
page's h1 (an index page) — heading levels must not skip. */
headingLevel?: 2 | 3;
}
const { entry, cover, locale } = Astro.props;
const { entry, cover, locale, headingLevel = 3 } = Astro.props;
const Title = `h${headingLevel}` as const;
const href = sectionPath("gallery", locale, entry.data.album);
const year = entry.data.date.getFullYear();
---
@@ -34,7 +38,7 @@ const year = entry.data.date.getFullYear();
}
</div>
<div class="body">
<h3 class="title">{entry.data.title}</h3>
<Title class="title">{entry.data.title}</Title>
<span class="year">{year}</span>
</div>
</a>
+26 -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 {
@@ -102,6 +108,10 @@ const pathname = Astro.url.pathname;
.brand {
display: inline-flex;
align-items: center;
/* As tall as the buttons beside it, and never narrower: once the wordmark is hidden
(below) the link would otherwise be the 32×12px mark alone. */
min-block-size: 2.5rem;
min-inline-size: 2.5rem;
gap: 0.5rem;
color: var(--text);
font-family: var(--ff-display);
@@ -113,6 +123,14 @@ const pathname = Astro.url.pathname;
block-size: 0.75rem;
color: var(--accent);
}
/* Down to a 320px viewport (WCAG 1.4.10 Reflow; also a desktop window at 400% zoom) the
header has no room for the wordmark: the mark alone stays, and the link keeps its
name through aria-label. */
@media (max-width: 21.99rem) {
.brand-text {
display: none;
}
}
.primary-nav {
display: none;
gap: 0.35rem;
@@ -132,8 +150,13 @@ const pathname = Astro.url.pathname;
color: var(--text);
background: var(--surface);
}
/* Colour is not the only cue for "you are here" (WCAG 1.4.1): the underline also
survives forced-colors mode, where the accent is replaced by the link colour. */
.primary-nav a[aria-current="page"] {
color: var(--accent);
text-decoration: underline;
text-decoration-thickness: 2px;
text-underline-offset: 0.45em;
}
.actions {
display: flex;
+34 -3
View File
@@ -13,6 +13,7 @@ const target: Locale = current === "vi" ? "en" : "vi";
const t = useTranslations(current);
const { href = alternatePath(Astro.url.pathname, target), label = t.lang.switchTo } = Astro.props;
const code = target.toUpperCase();
---
{
@@ -20,14 +21,24 @@ const { href = alternatePath(Astro.url.pathname, target), label = t.lang.switchT
voice control can act on what the user sees — WCAG 2.5.3 Label in Name (A).
`aria-label="Ngôn ngữ"` alone dropped it entirely. */
}
{
/* On a narrow phone the full name does not fit next to the brand and the three buttons
(the header needs 378px with "English", 400px with "Tiếng Việt"), and the page then
scrolled sideways. Below those widths the link shows the language code instead. The
accessible name carries both the name and the code as words of their own
("Tiếng Việt, VI — Language"), so it contains whichever of the two is on screen. axe
matches whole words and drops anything in parentheses: "VI" inside "Việt" does not
count, and neither would "(VI)". */
}
<a
class="lang-switch"
class:list={["lang-switch", `to-${target}`]}
{href}
hreflang={target}
lang={target}
aria-label={`${label} — ${t.lang.label}`}
aria-label={`${label}, ${code} — ${t.lang.label}`}
>
{label}
<span class="full">{label}</span>
<span class="short" aria-hidden="true">{code}</span>
</a>
<style>
@@ -52,4 +63,24 @@ const { href = alternatePath(Astro.url.pathname, target), label = t.lang.switchT
background: var(--surface);
border-color: var(--line);
}
.short {
display: none;
}
/* rem, so the switch-over moves with the reader's font size like the text it measures. */
@media (max-width: 23.99rem) {
.to-en .full {
display: none;
}
.to-en .short {
display: inline;
}
}
@media (max-width: 25.24rem) {
.to-vi .full {
display: none;
}
.to-vi .short {
display: inline;
}
}
</style>
+34 -3
View File
@@ -50,10 +50,38 @@
document.removeEventListener("keydown", onKey);
};
});
// The sheet does not take focus and sits at the end of the tab order, so someone tabbing
// through the page reaches controls that lie underneath it. Publish how much of the
// viewport's bottom it covers; the page's scroll padding (global.css) then keeps whatever
// receives focus above it (WCAG 2.4.11). The figure is the sheet's own height plus its
// gap to the bottom edge — laid-out sizes, so neither the slide-in transform nor how far
// the page is scrolled skews it. Set through CSSOM, never a style attribute (CSP).
$effect(() => {
if (!visible || !sheetEl) return;
const el = sheetEl;
const root = document.documentElement;
const sync = () => {
const gap = Number.parseFloat(getComputedStyle(el).bottom) || 0;
root.style.setProperty("--sheet-h", `${Math.round(el.offsetHeight + gap)}px`);
};
sync();
const observer = new ResizeObserver(sync);
observer.observe(el);
window.addEventListener("resize", sync);
return () => {
observer.disconnect();
window.removeEventListener("resize", sync);
root.style.removeProperty("--sheet-h");
};
});
</script>
{#if visible}
<aside bind:this={sheetEl} class="gate" role="note" aria-label={strings.label}>
<!-- A named complementary landmark (the <aside> itself): a screen-reader user can jump
to the notice from the landmark list instead of meeting it at the very end of the
page. role="note" is not a landmark and left the sheet outside every region. -->
<aside bind:this={sheetEl} class="gate" aria-label={strings.label}>
<div class="gate-body">
<p>{strings.line1}</p>
<p>{strings.line2}</p>
@@ -73,11 +101,14 @@
position: fixed;
z-index: 55;
inset-inline: 0;
inset-block-end: 0;
/* On a phone the sheet rests on top of the tab bar instead of covering it: the bar's
four controls stay visible and reachable while the notice is up (WCAG 2.4.11), and
the bar already pads for the home indicator. --bottom-bar-h is 0 from 768px up. */
inset-block-end: var(--bottom-bar-h, 0px);
/* Does NOT block scroll — no backdrop; only the card is interactive. */
max-block-size: 40vh;
overflow-y: auto;
padding: 1rem 1.15rem calc(1rem + env(safe-area-inset-bottom, 0));
padding: 1rem 1.15rem;
background: var(--elevated);
border-block-start: 1px solid var(--line);
box-shadow: var(--shadow-elevated);
+9 -2
View File
@@ -149,7 +149,11 @@
aria-describedby="lb-caption"
>
<div class="bar">
<span class="count" aria-live="polite">{counter}</span>
<!-- Arrowing to another photo announces its position and its caption: focus stays on
the button, so nothing else would say which photo is now showing. -->
<span class="count" aria-live="polite"
>{counter}<span class="sr-only"> — {current.alt}</span></span
>
<button type="button" class="close" onclick={close} aria-label={labels.close}>✕</button>
</div>
@@ -188,7 +192,10 @@
aria-label={labels.next}>›</button
>
<p class="caption" id="lb-caption">{current.alt}</p>
<!-- The same words are the image's alt and the dialog's description (aria-describedby
still resolves a hidden node), so the visible copy is hidden from the reading order
rather than read a third time. -->
<p class="caption" id="lb-caption" aria-hidden="true">{current.alt}</p>
</div>
{/if}
+4 -2
View File
@@ -112,8 +112,10 @@
</nav>
{#if legal.length}
<nav aria-labelledby="menu-sheet-legal">
<p id="menu-sheet-legal" class="group-title">{legalTitle}</p>
<!-- Named "Menu — Legal", not just "Legal": the footer's nav already has that name, and
two landmarks that sound the same cannot be told apart in a landmark list. -->
<nav aria-label={`${title} — ${legalTitle}`}>
<p class="group-title">{legalTitle}</p>
<ul class="links legal">
{#each legal as item (item.href)}
<li><a href={item.href} onclick={closeMenu}>{item.label}</a></li>
+24 -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);
}
@@ -110,9 +111,30 @@ const tabs = [
font-weight: 500;
cursor: pointer;
}
/* The current tab gets a bar along its top edge as well as the accent colour, so colour
is not the only cue (WCAG 1.4.1). It is a pseudo-element, not a border or a filter:
the bar itself must stay a plain opaque strip for Safari 26 (see .tabbar above). */
.tab {
position: relative;
}
.tab[aria-current="page"] {
color: var(--accent);
}
.tab[aria-current="page"]::before {
content: "";
position: absolute;
inset-block-start: 0;
inset-inline: 22%;
block-size: 2px;
border-radius: 0 0 2px 2px;
background: currentColor;
}
/* Forced colours repaint backgrounds; a system colour written here is kept. */
@media (forced-colors: active) {
.tab[aria-current="page"]::before {
background: LinkText;
}
}
.tab-icon {
display: block;
}
+6 -2
View File
@@ -9,8 +9,12 @@ import { formatDate, isoDate } from "../lib/format";
interface Props {
entry: BlogEntry;
locale: Locale;
/** Heading level of the card title: 3 under a section heading, 2 right under the
page's h1 (an index page) — heading levels must not skip. */
headingLevel?: 2 | 3;
}
const { entry, locale } = Astro.props;
const { entry, locale, headingLevel = 3 } = Astro.props;
const Title = `h${headingLevel}` as const;
const t = useTranslations(locale);
const href = sectionPath("blog", locale, entry.id);
const mins = readingTime(entry.body);
@@ -42,7 +46,7 @@ const mins = readingTime(entry.body);
)
}
<div class="card-body">
<h3 class="card-title">{entry.data.title}</h3>
<Title class="card-title">{entry.data.title}</Title>
<p class="card-desc">{entry.data.description}</p>
<div class="card-meta">
<time datetime={isoDate(entry.data.date)}>{formatDate(entry.data.date, locale)}</time>
+4 -2
View File
@@ -9,15 +9,17 @@ interface Props {
emptyText?: string;
emptyHref?: string;
emptyLabel?: string;
/** Passed to every PostCard; see there. */
headingLevel?: 2 | 3;
}
const { posts, locale, emptyText, emptyHref, emptyLabel } = Astro.props;
const { posts, locale, emptyText, emptyHref, emptyLabel, headingLevel } = Astro.props;
---
{
posts.length > 0 ? (
<div class="post-grid">
{posts.map((entry) => (
<PostCard {entry} {locale} />
<PostCard {entry} {locale} {headingLevel} />
))}
</div>
) : (
+6 -2
View File
@@ -6,8 +6,12 @@ import { useTranslations } from "../i18n";
interface Props {
entry: ProjectEntry;
locale: Locale;
/** Heading level of the card title: 3 under a section heading, 2 right under the
page's h1 (an index page) — heading levels must not skip. */
headingLevel?: 2 | 3;
}
const { entry, locale } = Astro.props;
const { entry, locale, headingLevel = 3 } = Astro.props;
const Title = `h${headingLevel}` as const;
const t = useTranslations(locale);
const href = sectionPath("projects", locale, entry.id);
const { name, tagline, stack, repo, url, featured, year } = entry.data;
@@ -16,7 +20,7 @@ const { name, tagline, stack, repo, url, featured, year } = entry.data;
<article class:list={["card project", { featured }]}>
<a class="card-link" href={href}>
<div class="head">
<h3 class="card-title">{name}</h3>
<Title class="card-title">{name}</Title>
<span class="year">{year}</span>
</div>
<p class="tagline">{tagline}</p>
+17
View File
@@ -12,3 +12,20 @@ const { class: className = "", reader = false } = Astro.props;
<div class:list={["prose", { "prose--reader": reader }, className]}>
<slot />
</div>
<script>
// A wide code block scrolls sideways. Chromium and Firefox let the keyboard reach any
// scroller, Safari does not — so a <pre> that overflows joins the tab order (and leaves
// it again once it fits, e.g. after a resize), where arrow keys scroll it (WCAG 2.1.1).
const blocks = document.querySelectorAll<HTMLElement>(".prose pre");
if (blocks.length > 0 && "ResizeObserver" in window) {
const observer = new ResizeObserver((entries) => {
for (const { target } of entries) {
if (!(target instanceof HTMLElement)) continue;
if (target.scrollWidth > target.clientWidth) target.tabIndex = 0;
else target.removeAttribute("tabindex");
}
});
blocks.forEach((pre) => observer.observe(pre));
}
</script>
+23 -1
View File
@@ -19,6 +19,7 @@
let barEl = $state(null);
let panelEl = $state(null);
let aaEl = $state(null);
function target() {
return document.getElementById("reader-root");
@@ -72,7 +73,12 @@
onScroll();
const onKey = (e) => {
if (e.key === "Escape" && open) open = false;
if (e.key !== "Escape" || !open) return;
// The panel is unmounted on close: if focus was inside it, hand it back to the "Aa"
// button rather than letting it fall to <body> (the next Tab would start at the top).
const hadFocus = panelEl?.contains(document.activeElement);
open = false;
if (hadFocus) aaEl?.focus();
};
const onDown = (e) => {
if (open && panelEl && !panelEl.contains(e.target)) open = false;
@@ -95,6 +101,7 @@
<div class="rc" bind:this={panelEl}>
<!-- The name starts with the visible "Aa" so voice control can target it (WCAG 2.5.3). -->
<button
bind:this={aaEl}
type="button"
class="aa"
onclick={() => (open = !open)}
@@ -206,8 +213,23 @@
cursor: pointer;
font-size: var(--text-meta);
}
/* The chosen option is heavier and double-ruled as well as accent-coloured, so colour is
not the only cue (WCAG 1.4.1). The inset shadow thickens the border without moving
the label. */
.opts button.active {
border-color: var(--accent);
color: var(--accent);
font-weight: 700;
box-shadow: inset 0 0 0 1px var(--accent);
}
/* Forced colours drop the shadow and give every button the same border and text colour. */
@media (forced-colors: active) {
.opts button.active {
forced-color-adjust: none;
background: Highlight;
border-color: Highlight;
color: HighlightText;
box-shadow: none;
}
}
</style>
+12
View File
@@ -147,6 +147,7 @@ const strings = {
preview.hidden = true;
}
statusEl.textContent = "";
clearInvalid();
if (REPORT_ENABLED) {
fallback.hidden = true;
submitBtn.hidden = false;
@@ -173,10 +174,21 @@ const strings = {
}
});
const clearInvalid = () => {
desc.removeAttribute("aria-invalid");
desc.removeAttribute("aria-describedby");
};
desc.addEventListener("input", clearInvalid);
submitBtn.addEventListener("click", async () => {
const description = desc.value.trim();
if (description.length < 10) {
// Tie the message to the field and send focus back to it, so a screen reader
// announces what is wrong where it can be fixed (WCAG 3.3.1).
statusEl.textContent = strings.tooShort;
desc.setAttribute("aria-invalid", "true");
desc.setAttribute("aria-describedby", "report-status");
desc.focus();
return;
}
if (!token) {
+18
View File
@@ -77,4 +77,22 @@
background: var(--accent);
translate: 0.775rem -50%;
}
/* Forced colours repaint backgrounds, and the knob is nothing but a background: without
this the switch is an empty outline whose state cannot be seen. System colours written
here are kept. */
@media (forced-colors: active) {
.track {
border-color: ButtonText;
}
.knob {
background: ButtonText;
}
.sb-switch[aria-checked="true"] .track {
background: Highlight;
border-color: Highlight;
}
.sb-switch[aria-checked="true"] .knob {
background: HighlightText;
}
}
</style>
+26 -2
View File
@@ -176,7 +176,12 @@
location.href = flat[selectedIndex].url;
}
} else if (e.key === "Tab") {
const f = dialogEl?.querySelectorAll("input, a[href], button:not(:disabled)");
// Only what Tab can actually reach: the results are options with tabindex="-1"
// (arrow keys move through them). Counting them made the last result the "last"
// stop, which Tab never lands on — so Tab from the Esc button left the dialog.
const f = dialogEl?.querySelectorAll(
'input, a[href]:not([tabindex="-1"]), button:not(:disabled)',
);
if (!f || !f.length) return;
const first = f[0];
const last = f[f.length - 1];
@@ -243,7 +248,10 @@
autocapitalize="off"
spellcheck="false"
/>
<button type="button" class="close" onclick={close} aria-label={labels.close}>Esc</button>
<!-- The name starts with the visible "Esc" so voice control can target it (WCAG 2.5.3). -->
<button type="button" class="close" onclick={close} aria-label={`Esc — ${labels.close}`}
>Esc</button
>
</div>
<div class="results">
@@ -412,6 +420,22 @@
background: var(--surface);
border-inline-start-color: var(--accent);
}
/* Forced colours (Windows High Contrast) drop box-shadows and repaint backgrounds, which
is all the focus indicator and the active option were made of; outlines are kept. The
resting option's transparent edge would turn solid there, so it takes the page colour. */
@media (forced-colors: active) {
.search-row:focus-within {
outline: 2px solid Highlight;
outline-offset: -2px;
}
.result {
border-inline-start-color: Canvas;
}
.result.active {
outline: 2px solid Highlight;
outline-offset: -2px;
}
}
.r-title {
display: block;
font-weight: 600;
+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%" />
+17 -3
View File
@@ -1,5 +1,5 @@
<script>
import { onMount } from "svelte";
import { onMount, tick } from "svelte";
import { externalImagePath } from "../lib/ext-img";
/**
@@ -18,6 +18,17 @@
/** @type {Record<string, boolean>} */
let playing = $state({}); // YouTube facade, per video id: false = thumbnail, true = nocookie iframe
/**
* Swap the thumbnail for the player. The play button is unmounted by that swap, so focus
* moves to the iframe that replaces it instead of falling back to <body>.
* @param {string} id
*/
async function play(id) {
playing[id] = true;
await tick();
document.getElementById(`w-player-${id}`)?.focus();
}
// A source counts as present only when its status is not "na" (and it has items).
const videos = $derived(
data.status?.yt !== "na" ? (data.yt?.items ?? []).slice(0, maxVideos) : [],
@@ -55,6 +66,7 @@
<div class="w-media">
{#if playing[video.id]}
<iframe
id={`w-player-${video.id}`}
title={video.title}
src={`https://www.youtube-nocookie.com/embed/${video.id}?autoplay=1`}
allow="autoplay; encrypted-media; picture-in-picture"
@@ -64,11 +76,13 @@
{#if picture(video.thumb)}
<img src={picture(video.thumb)} alt="" loading="lazy" width="480" height="270" />
{/if}
<!-- The name carries the video's title: the gaming page shows up to three of
these, and three buttons all called "Play video" cannot be told apart. -->
<button
type="button"
class="w-play"
aria-label={labels.playLabel}
onclick={() => (playing[video.id] = true)}
aria-label={`${labels.playLabel}: ${video.title}`}
onclick={() => play(video.id)}
>
▶
</button>
+2 -1
View File
@@ -31,11 +31,12 @@ const tags = collectTags(posts);
}
{
locale === "vi" ? (
<PostGrid {posts} {locale} emptyText="Chưa có bài viết nào." />
<PostGrid {posts} {locale} headingLevel={2} emptyText="Chưa có bài viết nào." />
) : (
<PostGrid
{posts}
{locale}
headingLevel={2}
emptyText={t.post.onlyVi}
emptyHref={sectionPath("blog", "vi")}
emptyLabel="Blog (tiếng Việt)"
+11 -2
View File
@@ -17,14 +17,23 @@ const t = useTranslations(locale);
{/* Tags are per-locale (a vi tag has no guaranteed en page) → no hreflang. */}
<BaseLayout title={`#${tag}`} {locale} alternates={null}>
<section class="page py-section">
<p class="crumb"><a href={sectionPath("blog", locale)}>{t.nav.blog}</a> / #{tag}</p>
<nav class="crumb" aria-label={t.landmarks.breadcrumb}>
<a href={sectionPath("blog", locale)}>{t.nav.blog}</a>
<span aria-hidden="true">/</span>
<span aria-current="page">#{tag}</span>
</nav>
<h1 class="text-h1">#{tag}</h1>
<div class="grid-wrap"><PostGrid {posts} {locale} /></div>
<div class="grid-wrap"><PostGrid {posts} {locale} headingLevel={2} /></div>
</section>
</BaseLayout>
<style>
/* A flex row with a gap: the build strips the whitespace between the link, the slash
and the current page, so the spacing cannot come from the markup. */
.crumb {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
color: var(--muted);
font-family: var(--ff-mono);
font-size: var(--text-meta);
+2 -1
View File
@@ -67,7 +67,8 @@ function relFor(href: string, me?: boolean): string | undefined {
<section class="page block">
<h2 class="block-title">{t.dev.connect}</h2>
<nav class="socials" aria-label={t.footer.social}>
{/* Named after its heading: the footer already has a nav called "Social". */}
<nav class="socials" aria-label={t.dev.connect}>
{
devSocials.map((link) => (
<a
+16 -6
View File
@@ -51,9 +51,11 @@ const slides = await Promise.all(
<BaseLayout title={entry.data.title} description={entry.data.description} {locale}>
<section class="page py-section">
<p class="crumb">
<a href={sectionPath("gallery", locale)}>{t.nav.gallery}</a> / {entry.data.title}
</p>
<nav class="crumb" aria-label={t.landmarks.breadcrumb}>
<a href={sectionPath("gallery", locale)}>{t.nav.gallery}</a>
<span aria-hidden="true">/</span>
<span aria-current="page">{entry.data.title}</span>
</nav>
<h1 class="text-h1">{entry.data.title}</h1>
{entry.data.description && <p class="lead">{entry.data.description}</p>}
<p class="date">{formatDate(entry.data.date, locale)}</p>
@@ -100,7 +102,12 @@ const slides = await Promise.all(
</BaseLayout>
<style>
/* A flex row with a gap: the build strips the whitespace between the link, the slash
and the current page, so the spacing cannot come from the markup. */
.crumb {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
color: var(--muted);
font-family: var(--ff-mono);
font-size: var(--text-meta);
@@ -123,16 +130,19 @@ const slides = await Promise.all(
margin-block-start: 1.5rem;
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(2, 1fr);
/* minmax(0, 1fr), not 1fr: a `1fr` column is at least as wide as its photos' minimum
content size, which made the first column 235px wide and the page wider than a
320px screen. With a zero minimum the columns stay equal. */
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 640px) {
.photo-grid {
grid-template-columns: repeat(3, 1fr);
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (min-width: 960px) {
.photo-grid {
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
.thumb {
+1 -1
View File
@@ -29,7 +29,7 @@ const cards = await Promise.all(
cards.length > 0 ? (
<div class="gallery-grid">
{cards.map(({ entry, cover }) => (
<GalleryCard {entry} {cover} {locale} />
<GalleryCard {entry} {cover} {locale} headingLevel={2} />
))}
</div>
) : (
+2 -1
View File
@@ -50,7 +50,8 @@ function relFor(href: string, me?: boolean): string | undefined {
<section class="page block">
<h2 class="block-title">{t.gaming.community}</h2>
<nav class="socials" aria-label={t.footer.social}>
{/* Named after its heading: the footer already has a nav called "Social". */}
<nav class="socials" aria-label={t.gaming.community}>
{
gameSocials.map((link) => (
<a
+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} />
+1
View File
@@ -20,6 +20,7 @@ const titleMap: Record<string, string> = {
"third-party": t.legal.thirdParty,
licenses: t.legal.licenses,
"ai-usage": t.legal.aiUsage,
accessibility: t.legal.accessibility,
};
const title = titleMap[entry.id] ?? entry.data.title;
// Without this every legal page inherited the site-wide default description, so all
+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>
+1 -1
View File
@@ -28,7 +28,7 @@ const projects = await getProjects(locale);
projects.length > 0 ? (
<div class="project-grid">
{projects.map((entry) => (
<ProjectCard {entry} {locale} />
<ProjectCard {entry} {locale} headingLevel={2} />
))}
</div>
) : locale === "vi" ? (
+6 -1
View File
@@ -112,6 +112,8 @@ const groups = [
.only-vi a {
color: var(--accent);
font-family: var(--ff-mono);
text-decoration: underline;
text-underline-offset: 0.2em;
}
.qa-group {
margin-block-end: 2rem;
@@ -158,12 +160,15 @@ const groups = [
color: var(--muted);
margin-block: 0.5rem 1rem;
}
/* These links sit inside a sentence, where the accent alone is only 1.6:1 against the
text around it — so they are underlined at rest, not just on hover (WCAG 1.4.1). */
.contact-list a {
color: var(--accent);
text-decoration: underline;
text-underline-offset: 0.2em;
}
.contact-list a:hover {
color: var(--accent-strong);
text-decoration: underline;
}
.contact-list {
list-style: none;
+6
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",
@@ -214,6 +219,7 @@ const en: UIStrings = {
thirdParty: "Third-party",
licenses: "Licenses",
aiUsage: "AI disclosure",
accessibility: "Accessibility",
},
now: {
title: "Now",
+6
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",
@@ -211,6 +216,7 @@ const vi = {
thirdParty: "Bên thứ ba",
licenses: "Giấy phép",
aiUsage: "Sử dụng AI",
accessibility: "Trợ năng",
},
now: {
title: "Bây giờ",
+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);
}
+21 -5
View File
@@ -3,6 +3,7 @@ import BaseLayout from "./BaseLayout.astro";
import Prose from "../components/Prose.astro";
import { useTranslations } from "../i18n";
import { legalNav, isActivePath } from "../lib/nav";
import { markLanguageHalves } from "../lib/legal-lang";
import type { Locale } from "../i18n/routing";
interface Props {
@@ -16,12 +17,18 @@ const t = useTranslations(locale);
const links = legalNav(locale);
const pathname = Astro.url.pathname;
const effectiveLabel = locale === "vi" ? "Hiệu lực" : "Effective";
// The document holds both languages; each half gets its `lang` at build time.
const body = markLanguageHalves(await Astro.slots.render("default"));
---
<BaseLayout {title} {description} {locale}>
<div class="legal-wrap page">
<aside class="legal-side">
<p class="side-title">{t.footer.legal}</p>
{
/* A navigation landmark, named apart from the footer's "Legal" nav so the two can be
told apart in a landmark list. */
}
<nav class="legal-side" aria-label={t.gate.linksLabel}>
<p class="side-title" aria-hidden="true">{t.footer.legal}</p>
<ul>
{
links.map((l) => (
@@ -33,7 +40,7 @@ const effectiveLabel = locale === "vi" ? "Hiệu lực" : "Effective";
))
}
</ul>
</aside>
</nav>
<article class="legal-doc">
<h1>{title}</h1>
@@ -45,15 +52,18 @@ const effectiveLabel = locale === "vi" ? "Hiệu lực" : "Effective";
)
}
<Prose class="legal-body">
<slot />
<Fragment set:html={body} />
</Prose>
</article>
</div>
</BaseLayout>
<style>
/* minmax(0, …): a plain `1fr` column never gets narrower than its longest unbreakable
word, so a bare URL in the text made the whole page 4px wider than a 320px screen. */
.legal-wrap {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 2rem;
padding-block: clamp(2rem, 6vw, 3.5rem);
}
@@ -83,6 +93,12 @@ const effectiveLabel = locale === "vi" ? "Hiệu lực" : "Effective";
.legal-side a[aria-current="page"] {
color: var(--accent);
}
/* Not by colour alone (WCAG 1.4.1). */
.legal-side a[aria-current="page"] {
text-decoration: underline;
text-decoration-thickness: 2px;
text-underline-offset: 0.35em;
}
.legal-doc h1 {
font-size: var(--text-h1);
}
@@ -98,7 +114,7 @@ const effectiveLabel = locale === "vi" ? "Hiệu lực" : "Effective";
@media (min-width: 900px) {
.legal-wrap {
grid-template-columns: 14rem 1fr;
grid-template-columns: 14rem minmax(0, 1fr);
gap: 3rem;
}
.legal-side {
+10 -3
View File
@@ -60,9 +60,11 @@ const crumbs = breadcrumbSchema([
image={ogUrl("project", entry.id)}
>
<article class="proj" data-pagefind-body>
<p class="crumb" data-pagefind-ignore>
<a href={sectionPath("projects", locale)}>{t.nav.projects}</a> / {name}
</p>
<nav class="crumb" aria-label={t.landmarks.breadcrumb} data-pagefind-ignore>
<a href={sectionPath("projects", locale)}>{t.nav.projects}</a>
<span aria-hidden="true">/</span>
<span aria-current="page">{name}</span>
</nav>
<h1>{name}</h1>
<p class="tagline">{tagline}</p>
<div class="facts">
@@ -118,7 +120,12 @@ const crumbs = breadcrumbSchema([
padding-inline: clamp(1rem, 4vw, 2rem);
padding-block: clamp(2rem, 6vw, 3.5rem);
}
/* A flex row with a gap: the build strips the whitespace between the link, the slash
and the current page, so the spacing cannot come from the markup. */
.crumb {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
color: var(--muted);
font-family: var(--ff-mono);
font-size: var(--text-meta);
+19
View File
@@ -130,6 +130,18 @@ const storySchema = {
border-block-end: 1px solid var(--line);
font-size: var(--text-meta);
}
/* The bar is a second sticky strip under the header: tell the page's scroll padding
(global.css) so a control focused by Shift+Tab is not left underneath it. Its height
is the 2.5rem "Aa" button plus the block padding and the border. */
:global(html:has(.reader-bar)) {
--subheader-h: 3.75rem;
}
@media (prefers-reduced-transparency: reduce) {
.reader-bar {
background: var(--bg);
backdrop-filter: none;
}
}
.reader-bar .back {
display: inline-flex;
align-items: center;
@@ -193,6 +205,13 @@ const storySchema = {
--accent-strong: #6f4808;
--accent-contrast: #ffffff;
}
/* global.css strengthens --line under "increase contrast", but the sepia block above is
more specific and would put the faint hairline back. */
@media (prefers-contrast: more) {
.reader[data-reader-theme="sepia"] {
--line: var(--line-strong);
}
}
.reader-head {
margin-block-end: 1.75rem;
text-align: center;
+21
View File
@@ -0,0 +1,21 @@
/**
* Legal documents are bilingual within one file — `## English`, then `## Tiếng Việt` — and
* both locale routes render the whole document. Without a `lang` on the half that is not
* in the page's language, a screen reader reads it with the wrong voice (WCAG 3.1.2).
*
* This wraps each half of the rendered HTML in a container carrying its language. A
* section under any other `<h2>` (the "Models" and "Components" tables) is left alone and
* keeps the page's language. The container is styled `display: contents` (prose.css).
*/
const HALVES: Record<string, string> = { English: "en", "Tiếng Việt": "vi" };
export function markLanguageHalves(html: string): string {
return html
.split(/(?=<h2[\s>])/)
.map((section) => {
const heading = /^<h2[^>]*>([^<]*)<\/h2>/.exec(section)?.[1].trim();
const lang = heading === undefined ? undefined : HALVES[heading];
return lang ? `<div lang="${lang}">${section}</div>` : section;
})
.join("");
}
+1
View File
@@ -44,6 +44,7 @@ export function legalNav(locale: Locale): NavItem[] {
{ href: sectionPath("legal", locale, "third-party"), label: t.legal.thirdParty },
{ href: sectionPath("legal", locale, "licenses"), label: t.legal.licenses },
{ href: sectionPath("legal", locale, "ai-usage"), label: t.legal.aiUsage },
{ href: sectionPath("legal", locale, "accessibility"), label: t.legal.accessibility },
];
}
+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">
+32 -3
View File
@@ -130,7 +130,13 @@ html {
/* Height of the sticky site header: the story reader bar docks under it and in-page
anchors stop below it. */
--header-h: 3.75rem;
scroll-padding-block-start: calc(var(--header-h) + 1rem);
/* What covers the bottom edge of the viewport: the fixed mobile tab bar (set below) and,
while it is showing, the legal notice sheet (LegalGateSheet sets --sheet-h). */
--bottom-bar-h: 0px;
scroll-padding-block-start: calc(var(--header-h) + var(--subheader-h, 0px) + 1rem);
/* Focus and in-page anchors scroll clear of those bars instead of landing underneath
them (WCAG 2.4.11 Focus Not Obscured). */
scroll-padding-block-end: calc(max(var(--bottom-bar-h), var(--sheet-h, 0px)) + 1rem);
-webkit-text-size-adjust: 100%;
scrollbar-gutter: stable;
/* Native checkboxes, radios and range inputs take the palette accent. */
@@ -194,10 +200,18 @@ body {
/* Leave room for the fixed mobile tab bar so the footer isn't hidden behind it. */
@media (max-width: 767px) {
body {
padding-block-end: calc(3.5rem + env(safe-area-inset-bottom, 0px));
html {
/* MobileTabBar: 3.5rem of tabs, its 1px top border, and the home-indicator inset. */
--bottom-bar-h: calc(3.5rem + 1px + env(safe-area-inset-bottom, 0px));
}
}
/* …and, at every width, room for the legal notice while it is up. Scroll padding cannot
help at the very end of the document: without this the last links of the footer could
not scroll out from under the sheet (full-width on a phone, a card over the footer's
right half on a tablet). */
body {
padding-block-end: max(var(--bottom-bar-h), var(--sheet-h, 0px));
}
h1,
h2,
@@ -313,6 +327,21 @@ body::after {
}
}
/* ------------------------------------------------------------------ *
* More contrast (the OS "increase contrast" setting): hairlines take the 3:1 line
* colour and the film grain goes away, since it only lowers contrast.
* ------------------------------------------------------------------ */
@media (prefers-contrast: more) {
:root,
[data-theme],
[data-reader-theme] {
--line: var(--line-strong);
}
body::after {
display: none;
}
}
/* Konami easter egg (src/lib/easter.ts): flips the accent to the horror tone for a
beat. Self-reverting after 4s; no layout shift, so reduced-motion needs nothing. */
:root[data-konami="on"] {
+16
View File
@@ -7,6 +7,11 @@
font-size: var(--text-body);
line-height: 1.7;
color: var(--text);
/* A bare URL or an e-mail address is one unbreakable word: on a 320px screen it pushed
the page wider than the viewport. Break inside such words only when nothing else fits.
`break-word`, not `anywhere`: the latter also lets a table shrink its columns below
their longest word, which broke "Anthropic" across two lines in the AI-usage table. */
overflow-wrap: break-word;
}
.prose--reader {
--measure: 68ch;
@@ -17,6 +22,17 @@
.prose > * + * {
margin-block-start: 1em;
}
/* The legal pages wrap each language half in a container that carries `lang`
(src/lib/legal-lang.ts). It takes no box of its own, so the rhythm rule above has to
reach through it; :where() keeps the specificity of that rule, so the heading margins
below still win. */
.prose > [lang] {
display: contents;
}
.prose > :where([lang]) > * + *,
.prose > :where(* + [lang]) > :where(:first-child) {
margin-block-start: 1em;
}
.prose h2,
.prose h3,
.prose h4 {
+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.
+476
View File
@@ -0,0 +1,476 @@
// What a static scan cannot see: the things that open (menu, search, photo viewer, report
// dialog, reading settings, legal notice) scanned while open, and the keyboard contract
// around them — Esc closes, focus comes back to what opened it, and focus never lands
// underneath a fixed bar.
import assert from "node:assert/strict";
import { after, before, describe, it } from "node:test";
import type { Browser, BrowserContext, Page } from "playwright";
import {
DESKTOP,
expectNoViolations,
firstMatch,
focused,
launch,
newContext,
open,
PHONE,
settle,
sitemapPaths,
} from "./support.ts";
const paths = await sitemapPaths();
const albumPath = firstMatch(paths, /^\/gallery\/[^/]+\/$/);
const chapterPath = firstMatch(paths, /^\/truyen\/[^/]+\/[^/]+\/$/);
let browser: Browser;
before(async () => {
browser = await launch();
});
after(async () => {
await browser?.close();
});
/** Run `body` in a fresh profile and always close it. */
async function withPage(
options: Parameters<typeof newContext>[1],
path: string,
body: (page: Page, context: BrowserContext) => Promise<void>,
): Promise<void> {
const context = await newContext(browser, options);
try {
await body(await open(context, path), context);
} finally {
await context.close();
}
}
const isInside = (page: Page, selector: string) =>
page.evaluate((sel) => Boolean(document.activeElement?.closest(sel)), selector);
describe("menu sheet (phone)", () => {
it("opens from the tab bar, traps focus, and Esc hands focus back", async () => {
await withPage({ viewport: PHONE }, "/", async (page) => {
const trigger = page.locator(".tabbar [data-menu-trigger]");
await trigger.focus();
await page.keyboard.press("Enter");
await page.waitForSelector("#menu-sheet.open");
assert.equal(await trigger.getAttribute("aria-expanded"), "true");
assert.ok(await isInside(page, "#menu-sheet"), "focus moved into the sheet");
await expectNoViolations(page, "menu sheet open");
for (let i = 0; i < 30; i++) {
await page.keyboard.press("Tab");
assert.ok(await isInside(page, "#menu-sheet"), `Tab #${i + 1} stays in the sheet`);
}
await page.keyboard.press("Escape");
await page.waitForSelector("#menu-sheet:not(.open)");
assert.equal(await trigger.getAttribute("aria-expanded"), "false");
assert.ok(await isInside(page, ".tabbar [data-menu-trigger]"), "focus is back on the button");
});
});
});
describe("search", () => {
it("opens from its button, lists results as options, and Esc hands focus back", async () => {
await withPage({}, "/", async (page) => {
const trigger = page.locator("[data-search-trigger]");
await trigger.focus();
await page.keyboard.press("Enter");
const field = page.locator("#search-modal [role=combobox]");
await field.waitFor();
assert.ok(await isInside(page, "#search-modal [role=combobox]"), "the field has focus");
await field.fill("SkullMute");
await page.waitForSelector("#search-modal [role=option]");
await page.keyboard.press("ArrowDown");
const active = await field.getAttribute("aria-activedescendant");
assert.ok(active, "an option is active");
assert.equal(await page.locator(`#${active}`).getAttribute("aria-selected"), "true");
await expectNoViolations(page, "search open with results");
// The trap has to hold with results listed: they are tabindex="-1" options, and
// counting them once let Tab walk out of the dialog from the Esc button.
for (let i = 0; i < 6; i++) {
await page.keyboard.press("Tab");
assert.ok(await isInside(page, "#search-modal"), `Tab #${i + 1} stays in the search`);
}
for (let i = 0; i < 3; i++) {
await page.keyboard.press("Shift+Tab");
assert.ok(await isInside(page, "#search-modal"), `Shift+Tab #${i + 1} stays in the search`);
}
// WCAG 2.5.3: the close button shows "Esc", so its name has to start with it.
const closeName = await page.locator("#search-modal .close").getAttribute("aria-label");
assert.match(closeName ?? "", /^Esc\b/);
await page.keyboard.press("Escape");
await page.waitForSelector("#search-modal", { state: "detached" });
assert.ok(await isInside(page, "[data-search-trigger]"), "focus is back on the button");
});
});
it('opens with "/" from anywhere on the page', async () => {
await withPage({}, "/", async (page) => {
await page.keyboard.press("/");
await page.waitForSelector("#search-modal [role=combobox]");
assert.ok(await isInside(page, "#search-modal"));
});
});
});
describe("photo viewer", () => {
it("opens from a thumbnail, is scanned open, and Esc returns to the thumbnail", async () => {
await withPage({}, albumPath, async (page) => {
const thumb = page.locator("a.thumb[data-lightbox-index]").first();
await thumb.focus();
await page.keyboard.press("Enter");
await page.waitForSelector(".lb[role=dialog]");
assert.ok(await isInside(page, ".lb"), "focus moved into the viewer");
await expectNoViolations(page, "photo viewer open");
await page.keyboard.press("Escape");
await page.waitForSelector(".lb", { state: "detached" });
assert.ok(
await isInside(page, "a.thumb[data-lightbox-index]"),
"focus is back on a thumbnail",
);
});
});
});
describe("report dialog", () => {
it("is labelled, scanned open, and ties a too-short message to the field", async () => {
await withPage({}, "/", async (page) => {
await page.locator("[data-report-trigger]").first().click();
await page.waitForSelector("dialog#report-dialog[open]");
assert.ok(await isInside(page, "#report-desc"), "the text box has focus");
await expectNoViolations(page, "report dialog open");
// Sending is switched off in builds without a Turnstile site key (CI); the button is
// hidden there and the check has nothing to press.
const submit = page.locator("#report-submit");
if (await submit.isVisible()) {
await submit.click();
const desc = page.locator("#report-desc");
assert.equal(await desc.getAttribute("aria-invalid"), "true");
assert.equal(await desc.getAttribute("aria-describedby"), "report-status");
assert.ok(await isInside(page, "#report-desc"), "focus returns to the field");
await desc.pressSequentially("x");
assert.equal(await desc.getAttribute("aria-invalid"), null);
}
});
});
});
describe("reading settings", () => {
it("is scanned open, and Esc from inside the panel hands focus back to Aa", async () => {
await withPage({}, chapterPath, async (page) => {
const aa = page.locator(".rc .aa");
await aa.focus();
await page.keyboard.press("Enter");
await page.waitForSelector("#reading-controls");
await expectNoViolations(page, "reading settings open");
await page.keyboard.press("Tab");
assert.ok(await isInside(page, "#reading-controls"), "Tab enters the panel");
await page.keyboard.press("Escape");
await page.waitForSelector("#reading-controls", { state: "detached" });
assert.equal(await focused(page), "button.aa");
});
});
});
/**
* Tab (or Shift+Tab) through the page and collect every control that receives focus while
* covered by one of the fixed bars. Stops when focus reaches `until` or after `limit`
* presses. Forward tabbing exercises the bars at the bottom edge, backward the top ones.
*/
async function obscuredWhileTabbing(
page: Page,
bars: string[],
until: string | null,
key: "Tab" | "Shift+Tab" = "Tab",
limit = 250,
) {
const offenders: string[] = [];
for (let i = 0; i < limit; i++) {
await page.keyboard.press(key);
const hit = await page.evaluate(
({ bars, until }) => {
const el = document.activeElement;
if (!el || el === document.body) return { stop: false, offender: null };
if (until && el.closest(until)) return { stop: true, offender: null };
const r = el.getBoundingClientRect();
for (const selector of bars) {
const bar = document.querySelector(selector);
if (!bar || bar.contains(el)) continue;
const b = bar.getBoundingClientRect();
if (b.width === 0 || b.height === 0) continue;
const overlapX = Math.min(r.right, b.right) - Math.max(r.left, b.left);
const overlapY = Math.min(r.bottom, b.bottom) - Math.max(r.top, b.top);
if (overlapX <= 0.5 || overlapY <= 0.5) continue;
// Overlapping is not yet hidden: the skip link is drawn over the header. What
// counts is which of the two is on top where the control's centre is.
const x = Math.min(Math.max(r.left + r.width / 2, 0), window.innerWidth - 1);
const y = Math.min(Math.max(r.top + r.height / 2, 0), window.innerHeight - 1);
const top = document.elementFromPoint(x, y);
if (top && bar.contains(top)) {
const text = (el.textContent ?? "").trim().slice(0, 40);
return {
stop: false,
offender: `${el.tagName.toLowerCase()} "${text}" under ${selector}`,
};
}
}
return { stop: false, offender: null };
},
{ bars, until },
);
if (hit.offender) offenders.push(hit.offender);
if (hit.stop) break;
}
return offenders;
}
describe("focus is not hidden under fixed bars (WCAG 2.4.11)", () => {
it("phone: nothing takes focus underneath the tab bar or the header", async () => {
await withPage({ viewport: PHONE }, "/", async (page) => {
const offenders = await obscuredWhileTabbing(page, [".tabbar", ".site-header"], ".tabbar");
assert.deepEqual(offenders, []);
});
});
it("story reader: nothing takes focus underneath the header or the reader bar going back up", async () => {
await withPage({ viewport: PHONE }, chapterPath, async (page) => {
// Start from the last control of the chapter and walk backwards: only then does the
// browser scroll controls in at the top edge, where the two sticky bars are.
await page.evaluate(() => {
const controls = document.querySelectorAll<HTMLElement>("main a[href], main button");
controls[controls.length - 1]?.focus();
});
assert.ok(await isInside(page, "main"), "the walk starts inside the chapter");
const offenders = await obscuredWhileTabbing(
page,
[".site-header", ".reader-bar"],
".site-header",
"Shift+Tab",
120,
);
assert.deepEqual(offenders, []);
});
});
// The notice is a full-width sheet on a phone and a card in the bottom-right corner from
// 768px up, where on a tablet it lies over the right half of the footer.
for (const [name, viewport] of [
["phone", PHONE],
["tablet", { width: 820, height: 1180 }],
["small laptop", { width: 1024, height: 768 }],
["desktop", DESKTOP],
] as const) {
it(`${name}: the legal notice is scanned, covers nothing that takes focus, and Esc dismisses it`, async () => {
await withPage({ viewport, acknowledged: false }, "/", async (page) => {
await page.waitForSelector("aside.gate", { timeout: 15_000 });
await settle(page);
await expectNoViolations(page, `legal notice showing (${name})`);
if (name === "phone") {
// The notice sits above the tab bar rather than on top of it.
const sheetBottom = await page
.locator("aside.gate")
.evaluate((el) => el.getBoundingClientRect().bottom);
const barTop = await page
.locator(".tabbar")
.evaluate((el) => el.getBoundingClientRect().top);
assert.ok(
sheetBottom <= barTop + 0.5,
`sheet ends at ${sheetBottom}, tab bar starts at ${barTop}`,
);
}
const offenders = await obscuredWhileTabbing(page, ["aside.gate", ".tabbar"], "aside.gate");
assert.deepEqual(offenders, []);
assert.ok(await isInside(page, "aside.gate"), "Tab reaches the notice");
// The height the sheet publishes for the scroll padding has to be right with the
// page scrolled too (Tab has scrolled it by now); a resize makes it measure again.
const [published, covered] = await page.evaluate(() => {
window.dispatchEvent(new Event("resize"));
const gate = document.querySelector("aside.gate");
const top = gate ? gate.getBoundingClientRect().top : window.innerHeight;
const value = getComputedStyle(document.documentElement).getPropertyValue("--sheet-h");
return [Number.parseFloat(value), window.innerHeight - top];
});
assert.ok(
Math.abs(published - covered) <= 1,
`--sheet-h is ${published}px, the sheet covers ${covered}px`,
);
await page.keyboard.press("Escape");
await page.waitForSelector("aside.gate", { state: "detached" });
const cleared = await page.evaluate(() =>
getComputedStyle(document.documentElement).getPropertyValue("--sheet-h"),
);
assert.equal(cleared, "", "--sheet-h is removed with the sheet");
});
});
}
});
describe("page chrome", () => {
it("the first Tab stop is the skip link, and it leads into <main>", async () => {
await withPage({}, "/", async (page) => {
await page.keyboard.press("Tab");
const skip = await page.evaluate(() => {
const el = document.activeElement as HTMLAnchorElement;
const r = el.getBoundingClientRect();
return {
href: el.getAttribute("href"),
visible: r.width > 0 && r.bottom > 0 && r.top >= 0,
};
});
assert.deepEqual(skip, { href: "#main", visible: true });
await page.keyboard.press("Enter");
await page.keyboard.press("Tab");
assert.ok(await isInside(page, "main#main"), "the next Tab stop is inside <main>");
});
});
it("the current page is marked by more than colour (WCAG 1.4.1)", async () => {
await withPage({}, "/blog/", async (page) => {
const decoration = await page
.locator('.primary-nav a[aria-current="page"]')
.evaluate((el) => getComputedStyle(el).textDecorationLine);
assert.match(decoration, /underline/);
});
await withPage({ viewport: PHONE }, "/blog/", async (page) => {
const bar = await page.locator('.tabbar .tab[aria-current="page"]').evaluate((el) => {
const style = getComputedStyle(el, "::before");
return { content: style.content, height: style.height };
});
assert.notEqual(bar.content, "none");
assert.equal(bar.height, "2px");
});
});
it("each half of a legal page declares its own language (WCAG 3.1.2)", async () => {
for (const path of ["/legal/accessibility/", "/en/legal/accessibility/"]) {
await withPage({}, path, async (page) => {
const halves = await page.evaluate(() => {
const en = document.querySelector('[id="english"] + *');
const vi = document.querySelector('[id="tiếng-việt"] + *');
return {
en: en?.matches(":lang(en)") ?? false,
vi: vi?.matches(":lang(vi)") ?? false,
// The wrappers take no box: the paragraph rhythm must survive them.
rhythm: vi ? Number.parseFloat(getComputedStyle(vi).marginBlockStart) : 0,
};
});
assert.deepEqual({ en: halves.en, vi: halves.vi }, { en: true, vi: true }, path);
assert.ok(halves.rhythm > 0, `${path}: paragraphs inside a half keep their spacing`);
});
}
});
it("the home link stays a real target when the wordmark is hidden (WCAG 2.5.8)", async () => {
await withPage({ viewport: { width: 320, height: 640 } }, "/", async (page) => {
const box = await page.locator(".site-header .brand").boundingBox();
assert.ok(box && box.width >= 24 && box.height >= 24, JSON.stringify(box));
});
});
/** Pages wider than the viewport, three loads at a time. */
async function overflowing(width: number, routes: string[]): Promise<string[]> {
const context = await newContext(browser, { viewport: { width, height: 700 } });
const wide: string[] = [];
try {
for (let i = 0; i < routes.length; i += 3) {
await Promise.all(
routes.slice(i, i + 3).map(async (path) => {
const page = await open(context, path);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
await page.close();
if (overflow > 0) wide.push(`${path} (+${overflow}px)`);
}),
);
}
} finally {
await context.close();
}
return wide;
}
// 320px is the WCAG 1.4.10 floor, and every page in the sitemap is held to it.
it("no page scrolls sideways at 320px — every page (WCAG 1.4.10)", async () => {
assert.deepEqual(await overflowing(320, paths), []);
});
// 360 and 390 are the common phone widths, where the header used to be wider than the
// screen (it needs 378px in Vietnamese, 400px in English).
for (const width of [360, 390]) {
it(`no page scrolls sideways at ${width}px (WCAG 1.4.10)`, async () => {
const routes = ["/", "/en/", "/blog/", chapterPath, albumPath, "/en/legal/ai-usage/"];
assert.deepEqual(await overflowing(width, routes), []);
});
}
});
describe("forced colours (Windows High Contrast)", () => {
const forced = { forcedColors: "active" } as const;
const style = (page: Page, selector: string, property: string) =>
page
.locator(selector)
.first()
.evaluate((el, prop) => getComputedStyle(el).getPropertyValue(prop), property);
it("the search field and the active result keep a visible indicator", async () => {
await withPage(forced, "/", async (page) => {
await page.keyboard.press("/");
const field = page.locator("#search-modal [role=combobox]");
await field.waitFor();
assert.equal(await style(page, "#search-modal .search-row", "outline-style"), "solid");
await field.fill("SkullMute");
await page.waitForSelector("#search-modal [role=option]");
await page.keyboard.press("ArrowDown");
assert.equal(await style(page, "#search-modal .result.active", "outline-style"), "solid");
});
});
it("the scrollbar switch shows its knob and its state", async () => {
await withPage(forced, "/", async (page) => {
const button = page.locator(".sb-switch");
await button.scrollIntoViewIfNeeded();
const colours = async () => ({
knob: await style(page, ".sb-switch .knob", "background-color"),
track: await style(page, ".sb-switch .track", "background-color"),
});
const off = await colours();
assert.notEqual(off.knob, off.track, "the knob stands out from the track when off");
await button.click();
assert.equal(await button.getAttribute("aria-checked"), "true");
const on = await colours();
assert.notEqual(on.knob, on.track, "the knob stands out from the track when on");
assert.notEqual(on.track, off.track, "on and off look different");
});
});
it("the chosen reading option is filled, not just recoloured", async () => {
await withPage(forced, chapterPath, async (page) => {
await page.locator(".rc .aa").click();
await page.waitForSelector("#reading-controls");
const chosen = await style(page, "#reading-controls button.active", "background-color");
const other = await style(page, "#reading-controls button:not(.active)", "background-color");
assert.notEqual(chosen, other);
});
});
});
+97
View File
@@ -0,0 +1,97 @@
// axe-core over every page of the build. The list comes from the build's own sitemap, so a
// new page or post is covered the day it exists and a deleted one cannot break the suite.
import { after, before, describe, it } from "node:test";
import type { Browser, BrowserContext } from "playwright";
import {
expectNoViolations,
firstMatch,
launch,
newContext,
open,
PHONE,
sitemapPaths,
} from "./support.ts";
const paths = await sitemapPaths();
// Pages the sitemap leaves out on purpose, which visitors still land on. The two missing
// pages answer 404 with the site's own error page, one per language.
const NOT_FOUND = ["/khong-co-trang-nay/", "/en/no-such-page/"];
const unlisted = [...NOT_FOUND, "/offline/"];
// One page of every template for the second theme and the phone layout: the light palette
// and the narrow layout change colours and chrome, not the structure of every single post.
// A template added later belongs in this list.
const templates = [
"/",
"/en/",
firstMatch(paths, /^\/about\/$/),
firstMatch(paths, /^\/blog\/$/),
firstMatch(paths, /^\/blog\/tag\/[^/]+\/$/),
firstMatch(paths, /^\/blog\/(?!tag\/)[^/]+\/$/),
firstMatch(paths, /^\/truyen\/$/),
firstMatch(paths, /^\/truyen\/[^/]+\/[^/]+\/$/),
firstMatch(paths, /^\/projects\/$/),
firstMatch(paths, /^\/projects\/[^/]+\/$/),
firstMatch(paths, /^\/gallery\/$/),
firstMatch(paths, /^\/gallery\/[^/]+\/$/),
firstMatch(paths, /^\/gaming\/$/),
firstMatch(paths, /^\/dev\/$/),
firstMatch(paths, /^\/dev\/uses\/$/),
firstMatch(paths, /^\/qa\/$/),
firstMatch(paths, /^\/links\/$/),
firstMatch(paths, /^\/now\/$/),
firstMatch(paths, /^\/legal\/accessibility\/$/),
firstMatch(paths, /^\/en\/legal\/accessibility\/$/),
...NOT_FOUND,
];
let browser: Browser;
before(async () => {
browser = await launch();
});
after(async () => {
await browser?.close();
});
function scan(title: string, routes: string[], options: Parameters<typeof newContext>[1]) {
describe(title, { concurrency: 4 }, () => {
let context: BrowserContext;
before(async () => {
context = await newContext(browser, options);
});
after(async () => {
await context?.close();
});
for (const route of routes) {
it(route, async () => {
const page = await open(context, route, NOT_FOUND.includes(route) ? 404 : 200);
try {
await expectNoViolations(page, `${route} (${title})`);
} finally {
await page.close();
}
});
}
});
}
scan("dark theme, desktop — every page", [...paths, ...unlisted], { colorScheme: "dark" });
scan("light theme, desktop — one page per template", templates, { colorScheme: "light" });
scan("dark theme, phone — one page per template", templates, {
colorScheme: "dark",
viewport: PHONE,
});
scan("light theme, phone — one page per template", templates, {
colorScheme: "light",
viewport: PHONE,
});
// Below 384px the header swaps the language name for its code and, below 352px, drops the
// wordmark: scan those two layouts as well.
scan("dark theme, 360px — both home pages", ["/", "/en/"], {
viewport: { width: 360, height: 780 },
});
scan("dark theme, 320px — both home pages", ["/", "/en/"], {
viewport: { width: 320, height: 640 },
});
+144
View File
@@ -0,0 +1,144 @@
// Shared plumbing for the accessibility suite (`npm run test:a11y`).
//
// The suite drives a real browser against a running build — `npm run build`, then
// `npm run preview` on port 4321 (override with A11Y_BASE_URL). It uses the Chrome that is
// already installed (the CI runner ships one), so nothing is downloaded; set A11Y_CHANNEL
// to another Playwright channel ("msedge"), or to "bundled" for Playwright's own Chromium.
import assert from "node:assert/strict";
import { AxeBuilder } from "@axe-core/playwright";
import { chromium, type Browser, type BrowserContext, type Page } from "playwright";
const BASE = (process.env.A11Y_BASE_URL ?? "http://localhost:4321").replace(/\/+$/, "");
/** WCAG 2.2 A + AA (the target in ACCESSIBILITY.md) plus axe's best-practice rules, which
is where heading order and landmark checks live. */
const AXE_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa", "best-practice"];
export const DESKTOP = { width: 1280, height: 800 };
export const PHONE = { width: 390, height: 844 };
export async function launch(): Promise<Browser> {
const channel = process.env.A11Y_CHANNEL ?? "chrome";
return chromium.launch(channel === "bundled" ? {} : { channel });
}
interface ContextOptions {
colorScheme?: "dark" | "light";
viewport?: { width: number; height: number };
forcedColors?: "active" | "none";
/** false = a first-time visitor, who gets the legal notice sheet. */
acknowledged?: boolean;
}
/**
* A fresh browser profile. Reduced motion is on so nothing is caught mid-transition (the
* site collapses every animation under it); the service worker is blocked so each run
* reads the build, not a cache. The site follows the OS colour scheme by default.
*/
export async function newContext(
browser: Browser,
{
colorScheme = "dark",
viewport = DESKTOP,
forcedColors = "none",
acknowledged = true,
}: ContextOptions = {},
): Promise<BrowserContext> {
const context = await browser.newContext({
baseURL: BASE,
colorScheme,
viewport,
forcedColors,
reducedMotion: "reduce",
serviceWorkers: "block",
});
if (acknowledged) {
await context.addInitScript(() => {
try {
localStorage.setItem("legalAck", JSON.stringify({ v: 99, ts: 0 }));
} catch {
/* storage unavailable: the sheet shows, which only makes the scan stricter */
}
});
}
return context;
}
/**
* Load a page and wait until its `client:idle` islands have hydrated. The status is checked
* so that an error page — a 429 from the site-wide rate limit, a route that stopped
* building — is never scanned in the route's place and passed.
*/
export async function open(context: BrowserContext, path: string, status = 200): Promise<Page> {
const page = await context.newPage();
const response = await page.goto(path, { waitUntil: "load" });
assert.equal(response?.status(), status, `${path} answers ${status}`);
await settle(page);
return page;
}
export async function settle(page: Page): Promise<void> {
await page.waitForLoadState("networkidle");
await page.evaluate(
() =>
new Promise<void>((resolve) => {
const done = () => requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
if ("requestIdleCallback" in window) requestIdleCallback(done, { timeout: 2000 });
else setTimeout(done, 200);
}),
);
}
/** Fail with a readable list when axe finds anything on the page as it stands. */
export async function expectNoViolations(page: Page, label: string): Promise<void> {
// The Turnstile widget in the report dialog is Cloudflare's iframe, not this site's
// markup (ACCESSIBILITY.md lists it under known limitations).
const { violations } = await new AxeBuilder({ page })
.withTags(AXE_TAGS)
.exclude("#report-turnstile")
.analyze();
const report = violations
.map((violation) => {
const nodes = violation.nodes
.slice(0, 5)
.map(
(node) =>
` ${node.target.join(" ")}\n ${node.failureSummary?.split("\n").join(" ")}`,
)
.join("\n");
return ` ${violation.id} (${violation.impact}) — ${violation.help}\n${nodes}`;
})
.join("\n");
assert.equal(violations.length, 0, `axe violations on ${label}:\n${report}`);
}
/** Every page of the build, as site-relative paths, read from its own sitemap. */
export async function sitemapPaths(): Promise<string[]> {
const response = await fetch(`${BASE}/sitemap-0.xml`);
assert.equal(response.status, 200, `${BASE}/sitemap-0.xml — is the preview server running?`);
const xml = await response.text();
const paths = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map(
(match) => new URL(match[1]).pathname,
);
assert.ok(paths.length > 10, "the sitemap lists the site's pages");
return [...new Set(paths)].sort();
}
/** The first sitemap path matching a pattern — a stand-in for "one page of this template". */
export function firstMatch(paths: string[], pattern: RegExp): string {
const found = paths.find((path) => pattern.test(path));
assert.ok(found, `a page matching ${pattern} exists in the sitemap`);
return found;
}
/** What has focus, in a form that reads well in an assertion message. */
export async function focused(page: Page): Promise<string> {
return page.evaluate(() => {
const el = document.activeElement;
if (!el || el === document.body) return "body";
const id = el.id ? `#${el.id}` : "";
const cls =
typeof el.className === "string" && el.className ? `.${el.className.split(" ")[0]}` : "";
return `${el.tagName.toLowerCase()}${id}${cls}`;
});
}
+46 -2
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 {
@@ -55,6 +62,7 @@ import { toLocale, useTranslations } from "../src/i18n/index.ts";
import vi from "../src/i18n/vi.ts";
import en from "../src/i18n/en.ts";
import { isActivePath, legalNav, menuNav, primaryNav } from "../src/lib/nav.ts";
import { markLanguageHalves } from "../src/lib/legal-lang.ts";
import { DURATION, prefersReducedMotion } from "../src/lib/motion.ts";
import { USES, USES_STACK } from "../src/lib/uses.ts";
@@ -84,6 +92,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", () => {
@@ -381,6 +399,31 @@ describe("SEO, RSS and OG", () => {
});
});
describe("legal documents", () => {
it("wraps each language half in its lang and leaves other sections alone", () => {
const html =
'<h2 id="english">English</h2><p>One.</p>' +
'<h2 id="tiếng-việt">Tiếng Việt</h2><p>Một.</p><ul><li>Hai</li></ul>' +
'<h2 id="models">Models</h2><table></table>';
assert.equal(
markLanguageHalves(html),
'<div lang="en"><h2 id="english">English</h2><p>One.</p></div>' +
'<div lang="vi"><h2 id="tiếng-việt">Tiếng Việt</h2><p>Một.</p><ul><li>Hai</li></ul></div>' +
'<h2 id="models">Models</h2><table></table>',
);
});
it("keeps whatever precedes the first heading, and a document without halves, as they are", () => {
assert.equal(
markLanguageHalves("<p>Intro.</p><h2>Other</h2><p>x</p>"),
"<p>Intro.</p><h2>Other</h2><p>x</p>",
);
assert.equal(markLanguageHalves(""), "");
// A heading that only mentions a language is not a half.
assert.equal(markLanguageHalves("<h2>English notes</h2>"), "<h2>English notes</h2>");
});
});
describe("i18n and nav", () => {
it("builds localized paths and swaps locales", () => {
assert.equal(homePath("vi"), "/");
@@ -419,7 +462,8 @@ describe("i18n and nav", () => {
it("lists nav items and matches active sections exactly", () => {
assert.equal(primaryNav("en")[0].href, "/en/blog/");
assert.ok(menuNav("vi").some((item) => item.href === "/now/"));
assert.equal(legalNav("en").length, 6);
assert.equal(legalNav("en").length, 7);
assert.equal(legalNav("vi").at(-1)?.href, "/legal/accessibility/");
assert.equal(isActivePath("/blog/post/", "/blog/"), true);
assert.equal(isActivePath("/blogging/", "/blog/"), false);
assert.equal(isActivePath("/en/blog/", "/en/"), false);
+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 } },