Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ef30458a4 | ||
|
|
7bcbcf59dd | ||
|
|
484907439a | ||
|
|
15559ecc90 | ||
|
|
0c56acd806 | ||
|
|
1b7364a2aa | ||
|
|
f384bc6e16 | ||
|
|
76869fabec | ||
|
|
6824c92fa0 | ||
|
|
24d7c1b117 | ||
|
|
7511f0c45e | ||
|
|
9f0a704280 | ||
|
|
28400cc2bc | ||
|
|
b6a5282a41 | ||
|
|
a6aef58b46 | ||
|
|
21178aa35f | ||
|
|
0fb60fe867 | ||
|
|
6ce2b7077f | ||
|
|
84ce2b8876 | ||
|
|
004cf466ce | ||
|
|
46cede84e3 | ||
|
|
5eb87b45d5 | ||
|
|
b4555d13d2 | ||
|
|
886db0eae7 | ||
|
|
87749f009c | ||
|
|
0d9aa619db | ||
|
|
0c07890c57 | ||
|
|
c9ab55703b | ||
|
|
0940aafed2 | ||
|
|
64d69b5fe5 | ||
|
|
12cd8129d5 | ||
|
|
cff21e1070 | ||
|
|
444e0e43e9 | ||
|
|
846e5ec17d | ||
|
|
bf66593c7d | ||
|
|
8aa760a5af | ||
|
|
edd1ad7ca8 | ||
|
|
f18264a859 | ||
|
|
c32b0b0586 | ||
|
|
1b1e922fe2 | ||
|
|
71e6c11de3 | ||
|
|
8a1316280f | ||
|
|
2d53af534f | ||
|
|
1ad81f9b82 | ||
|
|
408af42756 | ||
|
|
d20a511c33 | ||
|
|
a779da4ba9 | ||
|
|
4f7c037215 | ||
|
|
2c15630a80 | ||
|
|
a66c5fa976 | ||
|
|
0bd5279dd1 | ||
|
|
7ec559d216 | ||
|
|
49a7537e6c | ||
|
|
b160b6b3b3 | ||
|
|
af4cf073df | ||
|
|
b1020e6357 | ||
|
|
9f8000981d | ||
|
|
48d4e7bbdc | ||
|
|
e2344fb39b | ||
|
|
e433935de2 | ||
|
|
637dac67ff | ||
|
|
5f151ff259 | ||
|
|
fb798af1d8 | ||
|
|
08b0522d7a | ||
|
|
6f4cf4718f | ||
|
|
746e26dd6c | ||
|
|
d1fc366a0f | ||
|
|
432d92104b | ||
|
|
dc8d79b230 | ||
|
|
8448d9d0d5 | ||
|
|
5468359bde | ||
|
|
c324a4231a | ||
|
|
3ec11f2c89 | ||
|
|
14a7c326b1 | ||
|
|
39b33744b5 | ||
|
|
0b4edf3e5e | ||
|
|
fd440118f6 | ||
|
|
432deaf369 | ||
|
|
46c62cc21a | ||
|
|
7eb47f7248 | ||
|
|
4395717d22 | ||
|
|
4d5496e533 | ||
|
|
3a7bf3312a | ||
|
|
2113b7d550 | ||
|
|
209e5fa80e | ||
|
|
696fce9090 | ||
|
|
b6ce2c5d5b | ||
|
|
27f3cefb69 | ||
|
|
b1fab46ac0 | ||
|
|
eda1592855 | ||
|
|
c7085e3875 | ||
|
|
2e672270b7 | ||
|
|
0de00b7580 | ||
|
|
ab257d98db | ||
|
|
397ae4d13b | ||
|
|
d32321c015 | ||
|
|
32f1272377 | ||
|
|
206998a20f | ||
|
|
d415294be0 | ||
|
|
f4d92a3d4f | ||
|
|
901763b72f | ||
|
|
c07c409f8a | ||
|
|
3cc8fd6452 | ||
|
|
3c0f18f05d | ||
|
|
96eff66b1d | ||
|
|
8e6c83482d | ||
|
|
4f2efd843e | ||
|
|
018ac3150b | ||
|
|
ab7965cb57 | ||
|
|
814120bdae | ||
|
|
013e3f3203 |
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# LF everywhere — in the repository and in every working tree, whatever the OS. Without this,
|
||||
# core.autocrlf=true (the Windows default) checks text out as CRLF, and `prettier --check` and
|
||||
# `npm run gen-notices -- --check` then fail locally while CI on Linux passes.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Binary assets: never touched.
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.webp binary
|
||||
*.avif binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.ttf binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
@@ -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
|
||||
@@ -7,7 +7,13 @@ body:
|
||||
attributes:
|
||||
value: |
|
||||
Cảm ơn bạn đã báo lỗi. / Thanks for reporting.
|
||||
Báo lỗi gửi từ nút "Báo lỗi" trên trang sẽ tự điền các mục dưới đây.
|
||||
Nhanh hơn: nút "Báo lỗi" ngay trên trang gửi kèm trang và môi trường đang dùng (báo cáo đó đi
|
||||
vào một repo riêng, không hiện ở đây). / Quicker: the "Report a problem" button on the page
|
||||
itself sends the page and environment along (those reports go to a private repository and
|
||||
do not show up here).
|
||||
Dự án đang ở chế độ bảo trì: form này dành cho lỗi, không dành cho đề xuất tính năng — xem
|
||||
CONTRIBUTING.md. / The project is in maintenance mode: this form is for bugs, not feature
|
||||
requests — see CONTRIBUTING.md.
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Maintenance mode (CONTRIBUTING.md): issues are for bugs, accessibility and language problems.
|
||||
# Questions and ideas go to Discussions; security problems are reported privately.
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Question or idea · Câu hỏi hoặc ý tưởng
|
||||
url: https://github.com/poli0981/poli0981-dev/discussions
|
||||
about: >-
|
||||
The project is in maintenance mode and takes no new features — ask or talk ideas over in
|
||||
Discussions. · Dự án đang ở chế độ bảo trì, không nhận tính năng mới — hỏi hoặc trao đổi
|
||||
ý tưởng trong Discussions.
|
||||
- name: Security vulnerability · Lỗ hổng bảo mật
|
||||
url: https://github.com/poli0981/poli0981-dev/security/policy
|
||||
about: Report it privately, never in a public issue. · Báo riêng, không mở issue công khai.
|
||||
@@ -0,0 +1,46 @@
|
||||
name: Lỗi ngôn ngữ / Language problem
|
||||
description: >-
|
||||
Lỗi chính tả gây hiểu nhầm, câu chữ không hợp văn hoá hay giọng địa phương (tiếng Việt hoặc tiếng
|
||||
Anh). / A misleading typo, or wording that does not fit the culture or local voice (Vietnamese or
|
||||
English).
|
||||
title: "[language] "
|
||||
labels: ["language"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Cảm ơn bạn! Mỗi báo cáo một chỗ (hoặc một nhóm chỗ cùng một lỗi). / Thanks! One report per
|
||||
place, or per group of places with the same problem.
|
||||
- type: input
|
||||
id: page
|
||||
attributes:
|
||||
label: Trang / Page
|
||||
description: Đường dẫn trang, hoặc file nếu bạn biết. / The page's URL, or the file if you know it.
|
||||
placeholder: "https://poli0981.dev/blog/…"
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: language
|
||||
attributes:
|
||||
label: Ngôn ngữ / Language
|
||||
options:
|
||||
- Tiếng Việt / Vietnamese
|
||||
- Tiếng Anh / English
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: current
|
||||
attributes:
|
||||
label: Câu hiện tại / Current text
|
||||
description: Chép nguyên văn. / Copy it exactly.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: suggestion
|
||||
attributes:
|
||||
label: Đề xuất sửa và lý do / Suggested wording and why
|
||||
description: >-
|
||||
Vì sao câu hiện tại gây hiểu nhầm hoặc không hợp? / Why is the current text misleading or a
|
||||
poor fit?
|
||||
validations:
|
||||
required: true
|
||||
@@ -1,20 +1,45 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Root npm project. `/workers/widgets` is intentionally omitted until that worker exists.
|
||||
# Root npm project. `/workers/widgets` is omitted on purpose: that worker is
|
||||
# dependency-free (no package.json, the YouTube RSS is hand-parsed), so there is no
|
||||
# manifest for Dependabot to read. Add an entry the day that worker gains a package.json.
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
# Supply-chain hardening (docs 06 §6): never propose a release younger than three days.
|
||||
# Malicious publishes — the Shai-Hulud shape — are usually caught and pulled within hours.
|
||||
cooldown:
|
||||
default-days: 3
|
||||
open-pull-requests-limit: 8
|
||||
groups:
|
||||
astro:
|
||||
patterns: ["astro", "@astrojs/*"]
|
||||
# The type-checking toolchain moves together: typescript-eslint pins the TypeScript
|
||||
# versions it accepts.
|
||||
typescript:
|
||||
patterns: ["typescript", "typescript-eslint"]
|
||||
dev-tools:
|
||||
dependency-type: development
|
||||
ignore:
|
||||
# `typescript` stays on 6.x on purpose. TypeScript 7.0 ships no JS API, and astro
|
||||
# check (Volar), typescript-eslint and svelte2tsx all need one. TS 7 itself is the
|
||||
# `@typescript/native` alias (npm:typescript@7) — and Dependabot skips every `npm:`
|
||||
# alias, so that one is bumped by hand (docs 17). Lift this ignore once those tools
|
||||
# support TypeScript 7.1's new API.
|
||||
- dependency-name: typescript
|
||||
update-types: ["version-update:semver-major"]
|
||||
# prettier-plugin-astro 1.x reflows `<span>{expr}</span>` onto separate lines in 50
|
||||
# .astro files, which inserts whitespace text nodes inside inline elements. That is a
|
||||
# visual change, not a formatting one — it needs its own PR with a rendered diff.
|
||||
- dependency-name: prettier-plugin-astro
|
||||
update-types: ["version-update:semver-major"]
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
cooldown:
|
||||
default-days: 3
|
||||
@@ -0,0 +1,33 @@
|
||||
## What and why
|
||||
|
||||
<!-- One or two sentences. Link the issue if there is one. -->
|
||||
|
||||
## Kind of change
|
||||
|
||||
The project is in maintenance mode ([CONTRIBUTING.md](https://github.com/poli0981/poli0981-dev/blob/main/CONTRIBUTING.md)):
|
||||
new features are not accepted, and a `feat:` pull request is closed automatically.
|
||||
|
||||
- [ ] Dependency update
|
||||
- [ ] Security fix (High/Critical advisory, or a runtime vulnerability)
|
||||
- [ ] Major language, runtime or framework upgrade
|
||||
- [ ] Bug fix — including UI/UX and accessibility
|
||||
- [ ] Language fix — a misleading typo, or wording that does not fit
|
||||
|
||||
## 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
|
||||
@@ -1,10 +1,14 @@
|
||||
name: CI
|
||||
|
||||
# Docs-only changes skip CI/deploy. NOTE: use `*.md` (root-level) — NOT `**/*.md` —
|
||||
# because blog/story content lives at src/content/**/*.{md,mdx} and must still deploy.
|
||||
# PRs always run: `build` is a required status check in the main ruleset, so a
|
||||
# paths-ignore here would leave docs-only PRs waiting forever for a check that never
|
||||
# starts. Pushes to main may still skip docs-only changes. NOTE: use `*.md` (root-level)
|
||||
# — NOT `**/*.md` — because blog/story content lives at src/content/**/*.{md,mdx}.
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
# Dispatched on content/bump by content-bump.yml (PRs opened with GITHUB_TOKEN don't
|
||||
# trigger pull_request workflows), so the required `build` check exists for them.
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
@@ -21,58 +25,172 @@ concurrency:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
# A hung `wrangler dev` in the smoke test must not hold a runner for six hours.
|
||||
timeout-minutes: 30
|
||||
# Job-level too, so a second job added later can't silently inherit something wider.
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# Actions are pinned to commit SHAs, not tags: a tag is mutable, so `@v7` would
|
||||
# execute whatever that tag points at on the day CI runs. Dependabot's
|
||||
# github-actions ecosystem updates the pins and keeps the version comment in sync.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # check-exif diffs changed images against the base ref
|
||||
# src/content is a submodule (poli0981/content). Without this the content
|
||||
# collections resolve to an empty directory and the build fails on the
|
||||
# first getCollection() call.
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# No dependency lifecycle script runs in CI at all (docs 06 §6, anti-worm). None is
|
||||
# needed: esbuild, workerd and sharp take their platform binaries from
|
||||
# optionalDependencies — their install scripts only re-verify them — and lefthook's
|
||||
# only installs git hooks. Local installs stay guarded by package.json#allowScripts
|
||||
# plus .npmrc strict-allow-scripts.
|
||||
- name: Install
|
||||
run: npm ci
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
# KV/ASSETS/SESSION types live in the gitignored worker-configuration.d.ts,
|
||||
# generated from wrangler.jsonc. `astro check` fails without them — and there
|
||||
# is no @cloudflare/workers-types dependency to fall back on. No auth needed.
|
||||
# …which also means npm's own strict-allow-scripts check never runs here. This keeps
|
||||
# the alarm: any lockfile package with an install script must be on allowScripts.
|
||||
- name: Install scripts allow-listed
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Binding types live in the gitignored worker-configuration.d.ts files, generated from
|
||||
# the wrangler configs; both type checks fail without them. No auth needed.
|
||||
# --strict-vars=false (in the script): `vars` are typed as string, not their literal
|
||||
# value, so code comparing e.g. GATE_MODE against "on" typechecks whatever it is set to.
|
||||
- name: Generate Cloudflare binding types
|
||||
run: npx wrangler types
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
|
||||
- name: Format check
|
||||
run: npx prettier --check .
|
||||
run: npm run format:check
|
||||
|
||||
- name: Lint
|
||||
run: npx eslint .
|
||||
run: npm run lint
|
||||
|
||||
- name: Type check
|
||||
# .astro, .svelte and .ts through Volar — the TypeScript 6 API (TS 7.0 has none).
|
||||
- name: Type check (astro check)
|
||||
run: npm run check
|
||||
|
||||
# The cron worker is a separate TS project (own tsconfig + Env types) and is
|
||||
# excluded from the root check. Deploy is manual, so typecheck it here as a guard.
|
||||
- name: Typecheck widgets worker
|
||||
working-directory: workers/widgets
|
||||
# Every .ts file again with the native TypeScript 7 compiler, plus the widgets worker
|
||||
# (a separate TS project). The version line makes a bin mix-up impossible to miss.
|
||||
- name: Type check (TypeScript 7)
|
||||
run: |
|
||||
npx wrangler types
|
||||
npx tsc -p tsconfig.json --noEmit
|
||||
node node_modules/@typescript/native/bin/tsc --version
|
||||
npm run typecheck
|
||||
|
||||
- name: Dead code
|
||||
run: npm run knip
|
||||
|
||||
# node:test + V8 coverage. Fails under 80% lines; writes coverage/lcov.info for the
|
||||
# SonarCloud job below.
|
||||
- name: Unit tests (coverage)
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: Audit (prod deps, high+)
|
||||
run: npm audit --omit=dev --audit-level=high
|
||||
|
||||
# THIRD-PARTY-NOTICES.md must match the direct dependencies, and every license must be
|
||||
# either on the allowlist or explicitly reviewed (docs 08 §6).
|
||||
- name: Third-party notices
|
||||
run: npm run gen-notices -- --check
|
||||
|
||||
# The same policy over every package in package-lock.json, transitive dependencies and
|
||||
# each platform's binaries included; anything outside it needs a per-package review.
|
||||
- name: Licences (whole dependency tree)
|
||||
run: npm run check-licenses
|
||||
|
||||
# Fail if any changed image under src/assets/ still carries GPS or a camera serial.
|
||||
- name: Check EXIF (changed images)
|
||||
env:
|
||||
DIFF_BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
run: node scripts/check-exif.mjs --changed
|
||||
run: npm run check-exif -- --changed
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# Deployment is handled by Cloudflare Workers Builds (connected to this repo),
|
||||
# not GitHub Actions — this workflow is CI gates only (lint/types/knip/audit/build).
|
||||
# Workers Builds must deploy with: wrangler deploy --config ./dist/server/wrangler.json
|
||||
# (the root wrangler.jsonc has no `main`; the adapter writes the real config there).
|
||||
# src/worker.ts fronts every page, so a crash there would take the static site down
|
||||
# too. Boot the built worker locally (wrangler dev, simulated bindings, no auth) and
|
||||
# probe pages, revalidation, HEAD, redirects, 404s, assets, the gate and the API.
|
||||
- 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:
|
||||
name: coverage
|
||||
path: coverage/lcov.info
|
||||
retention-days: 7
|
||||
if-no-files-found: error
|
||||
|
||||
# Deployment is Cloudflare Workers Builds (connected to this repo), not GitHub
|
||||
# Actions — this workflow is CI gates only. Workers Builds settings (docs 07): deploy
|
||||
# command `npx wrangler deploy` on main, version command `npx wrangler versions upload`
|
||||
# on every other branch. Plain `wrangler` finds the generated config on its own: the
|
||||
# build writes .wrangler/deploy/config.json pointing at dist/server/wrangler.json.
|
||||
|
||||
# The SonarCloud analysis (automatic analysis is switched off; this is the only one).
|
||||
# Needs SONAR_TOKEN, which Dependabot runs and forks never get, so those skip it, as do
|
||||
# the content/bump dispatches (content only, no code to analyze).
|
||||
sonarcloud:
|
||||
needs: build
|
||||
if: >-
|
||||
github.event_name == 'push' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
github.actor != 'dependabot[bot]')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # blame data and new-code detection need the whole history
|
||||
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: coverage
|
||||
path: coverage
|
||||
|
||||
# Settings live in sonar-project.properties. On pull requests the job waits for the
|
||||
# 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@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
with:
|
||||
args: >-
|
||||
${{ github.event_name == 'pull_request' && '-Dsonar.qualitygate.wait=true -Dsonar.qualitygate.timeout=300' || '' }}
|
||||
@@ -0,0 +1,88 @@
|
||||
name: Content publish
|
||||
|
||||
# "Publish" in the admin (admin.poli0981.dev) dispatches this. It points the src/content
|
||||
# submodule at poli0981/content's main, commits that on the content/bump branch, opens
|
||||
# (or updates) a PR and, when only Markdown/JSON changed, enables auto-merge. CI then runs
|
||||
# on the bump commit; when the required `build` check passes the PR merges itself and
|
||||
# Workers Builds deploys main.
|
||||
#
|
||||
# Why a workflow: the admin's token can write ONLY the content repo (+ dispatch this). If
|
||||
# it leaked, the worst case is content edits — never code pushed to this repo. MDX runs
|
||||
# code at build time, so anything other than .md/.json waits for a human review.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: content-bump
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
bump:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # push content/bump
|
||||
pull-requests: write # open the PR, enable auto-merge
|
||||
actions: write # run ci.yml on the bump commit
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Point src/content at content main
|
||||
id: bump
|
||||
run: |
|
||||
git -C src/content fetch --quiet origin main
|
||||
old=$(git rev-parse HEAD:src/content)
|
||||
new=$(git -C src/content rev-parse FETCH_HEAD)
|
||||
echo "new=$new" >> "$GITHUB_OUTPUT"
|
||||
if [ "$old" = "$new" ]; then
|
||||
echo "Already published ($new)."
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
files=$(git -C src/content diff --name-only "$old" "$new")
|
||||
echo "$files"
|
||||
if echo "$files" | grep -qvE '\.(md|json)$'; then auto=false; else auto=true; fi
|
||||
git -C src/content checkout --quiet "$new"
|
||||
{
|
||||
echo "changed=true"
|
||||
echo "auto=$auto"
|
||||
echo "files<<EOF"
|
||||
echo "$files"
|
||||
echo "EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Commit, open/update the PR, queue CI
|
||||
if: steps.bump.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
NEW: ${{ steps.bump.outputs.new }}
|
||||
AUTO: ${{ steps.bump.outputs.auto }}
|
||||
FILES: ${{ steps.bump.outputs.files }}
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git switch --create content/bump
|
||||
git add src/content
|
||||
git commit --quiet -m "chore(content): publish ${NEW:0:7}" -m "$FILES"
|
||||
git push --force --quiet origin content/bump
|
||||
|
||||
if [ "$(gh pr view content/bump --json state --jq .state 2>/dev/null)" != "OPEN" ]; then
|
||||
gh pr create --base main --head content/bump \
|
||||
--title "chore(content): publish from admin" \
|
||||
--body "Bumps \`src/content\` to poli0981/content@${NEW}. Opened by the admin's **Publish** button (.github/workflows/content-bump.yml)."
|
||||
fi
|
||||
|
||||
if [ "$AUTO" = "true" ]; then
|
||||
gh pr merge content/bump --auto --squash
|
||||
else
|
||||
gh pr merge content/bump --disable-auto 2>/dev/null || true
|
||||
gh pr comment content/bump --body "This publish touches files other than .md/.json (MDX runs code at build time), so it waits for a review instead of auto-merging."
|
||||
fi
|
||||
|
||||
# PRs opened with GITHUB_TOKEN don't trigger pull_request workflows; a dispatch is
|
||||
# the exception, and its `build` check lands on the bump commit for the ruleset.
|
||||
gh workflow run ci.yml --ref content/bump
|
||||
@@ -0,0 +1,106 @@
|
||||
name: Lighthouse
|
||||
|
||||
# docs 14 §3: assert the perf budget on a preview build — WARN ONLY, never blocking.
|
||||
# Lighthouse numbers move with runner load, so a hard gate here would block deploys on
|
||||
# noise rather than on regressions. The job is advisory by construction: assertions are
|
||||
# `warn`, and continue-on-error means a red run never fails the check suite.
|
||||
# Per the doc, act when it goes red twice in a row rather than on a single bad run.
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lighthouse:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
# The whole point: informative, never a blocker.
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: recursive # src/content, or the build has no content to measure
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same as ci.yml: no dependency lifecycle scripts in CI.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Generate Cloudflare binding types
|
||||
run: npm run types
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# `astro preview` boots the built worker in workerd with the real bindings and
|
||||
# _headers, so the numbers reflect production rather than a bare static server.
|
||||
- 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://127.0.0.1:4322/; then
|
||||
echo "preview up after ${i}s"; exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "preview server never came up"; exit 1
|
||||
|
||||
# Four representative pages (docs 14 §3): home, a blog post, a story chapter, a
|
||||
# gallery album — the heaviest template of each kind. The action bundles @lhci/cli,
|
||||
# so nothing is downloaded with npx at run time; it collects, asserts against
|
||||
# lighthouserc.json (warn-only) and uploads the reports even when an assertion warns.
|
||||
- name: Lighthouse
|
||||
uses: treosh/lighthouse-ci-action@3e7e23fb74242897f95c0ba9cabad3d0227b9b18 # 12.6.2
|
||||
with:
|
||||
configPath: ./lighthouserc.json
|
||||
urls: |
|
||||
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
|
||||
@@ -0,0 +1,42 @@
|
||||
name: OSV scan
|
||||
|
||||
# docs 06 §6 and 08 §2 both call for a weekly dependency scan; this is it.
|
||||
# It complements the per-PR `npm audit --omit=dev --audit-level=high` gate in ci.yml:
|
||||
# audit only sees the production tree and only fails on high+, while OSV covers the
|
||||
# whole lockfile (devDependencies included) against the full OSV database.
|
||||
on:
|
||||
schedule:
|
||||
# Mondays 03:17 UTC — off the hour, where scheduled-runner contention is lowest.
|
||||
- cron: "17 3 * * 1"
|
||||
workflow_dispatch:
|
||||
# Re-run when the dependency graph itself changes, so a bad bump is caught on the PR
|
||||
# rather than up to a week later…
|
||||
pull_request:
|
||||
paths: ["package-lock.json"]
|
||||
# …and once it lands, so the Security tab reflects main straight away.
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["package-lock.json"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
scan:
|
||||
# The repo is public, so code scanning is free: findings are uploaded as SARIF and
|
||||
# show up under Security → Code scanning, and a finding still fails the run.
|
||||
# PR runs skip the upload — Dependabot PRs get a read-only token, so the upload
|
||||
# step would fail there for a reason unrelated to the scan itself.
|
||||
uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@32d3cd482bdadfb38b186c0ad1b031902d55d932 # v2.7.1
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
with:
|
||||
upload-sarif: ${{ github.event_name != 'pull_request' }}
|
||||
scan-args: |-
|
||||
--lockfile=package-lock.json
|
||||
@@ -0,0 +1,87 @@
|
||||
name: Qodana
|
||||
|
||||
# JetBrains Qodana (Qodana for JS, WebStorm's inspections) over the whole repository: on every
|
||||
# PR, on main and by hand. Settings live in qodana.yaml. Results go to Qodana Cloud (the
|
||||
# project token is the QODANA_TOKEN secret) and, for main, to GitHub code scanning as SARIF.
|
||||
#
|
||||
# Advisory, not required: the main ruleset requires only `build`, and Dependabot and fork PRs
|
||||
# get no secrets, so they skip this job like the SonarCloud one in ci.yml.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
# Explicit — a missing block makes GitHub default every scope to `none`.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
# Cancel superseded PR runs; let main runs finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
qodana:
|
||||
if: >-
|
||||
github.event_name != 'pull_request' ||
|
||||
(github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
github.actor != 'dependabot[bot]')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write # problem annotations on the commit
|
||||
pull-requests: write # the summary comment on PRs
|
||||
security-events: write # SARIF upload (main and manual runs)
|
||||
steps:
|
||||
# Pinned to commit SHAs like every other workflow here; Dependabot keeps them current.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
# The PR's own head commit, not the merge preview, so Qodana Cloud links to it.
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same rules as ci.yml: no dependency lifecycle script runs in CI, and any lockfile
|
||||
# package with an install script must be on package.json#allowScripts.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Install scripts allow-listed
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Gitignored, generated types the TypeScript service needs to resolve imports of
|
||||
# cloudflare:workers, astro:content and friends.
|
||||
- name: Generate types
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
npm run astro -- sync
|
||||
|
||||
- name: Qodana scan
|
||||
uses: JetBrains/qodana-action@13e3acbbaeb2cbfc37893b98e74594985edf42eb # v2026.2.4
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
QODANA_ENDPOINT: https://qodana.cloud
|
||||
with:
|
||||
# Whole repository every time (it is small), so the quality gate in qodana.yaml
|
||||
# always judges the full picture rather than the files a PR happens to touch.
|
||||
pr-mode: false
|
||||
upload-result: true
|
||||
|
||||
# Like the OSV scan: main and manual runs only, so PR runs don't open code-scanning
|
||||
# alerts for code that may never merge.
|
||||
- name: Upload SARIF to code scanning
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' }}
|
||||
uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
sarif_file: ${{ runner.temp }}/qodana/results/qodana.sarif.json
|
||||
category: qodana
|
||||
@@ -0,0 +1,83 @@
|
||||
name: Triage
|
||||
|
||||
# Maintenance mode (CONTRIBUTING.md): an issue or pull request asking for a new feature is
|
||||
# labelled `enhancement` + `out-of-scope`, answered in both languages and closed. The rules
|
||||
# live in scripts/triage.mjs (unit-tested); this only wires them to GitHub. The owner's own
|
||||
# items, bots, and anything labelled `maintenance-exception` are left alone.
|
||||
#
|
||||
# pull_request_target runs with this repository's token, so it must never run a pull
|
||||
# request's code. Nothing is checked out at all: the script reads scripts/triage.mjs from the
|
||||
# default branch through the API and imports it from memory.
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened, edited, labeled]
|
||||
pull_request_target:
|
||||
types: [opened, reopened, edited, labeled]
|
||||
# Dry run on main: classify a title and print the decision, writing nothing.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
title:
|
||||
description: "Title to classify"
|
||||
required: true
|
||||
kind:
|
||||
description: "issue or pull_request"
|
||||
default: issue
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: triage-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Label and close feature requests
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { data: file } = await github.rest.repos.getContent({
|
||||
...context.repo,
|
||||
path: "scripts/triage.mjs",
|
||||
ref: context.payload.repository.default_branch,
|
||||
});
|
||||
const source = file.content.replaceAll("\n", "");
|
||||
const { decide, closingComment, LABELS } = await import(
|
||||
`data:text/javascript;base64,${source}`
|
||||
);
|
||||
|
||||
if (context.eventName === "workflow_dispatch") {
|
||||
const { title, kind } = context.payload.inputs;
|
||||
const verdict = decide({ title, labels: [], author: "someone", association: "NONE" });
|
||||
core.notice(`${kind} "${title}": ${verdict.action} (${verdict.reason})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const item = context.payload.issue ?? context.payload.pull_request;
|
||||
const kind = context.payload.pull_request ? "pull_request" : "issue";
|
||||
const verdict = decide({
|
||||
title: item.title,
|
||||
labels: (item.labels ?? []).map((label) => label.name),
|
||||
author: item.user.login,
|
||||
association: item.author_association,
|
||||
sender: context.payload.sender?.login,
|
||||
owner: context.repo.owner,
|
||||
state: item.state,
|
||||
});
|
||||
core.info(`#${item.number}: ${verdict.action} (${verdict.reason})`);
|
||||
if (verdict.action !== "close") return;
|
||||
|
||||
const target = { ...context.repo, issue_number: item.number };
|
||||
await github.rest.issues.addLabels({ ...target, labels: [LABELS.feature, LABELS.closed] });
|
||||
await github.rest.issues.createComment({ ...target, body: closingComment(kind) });
|
||||
if (kind === "pull_request") {
|
||||
await github.rest.pulls.update({ ...context.repo, pull_number: item.number, state: "closed" });
|
||||
} else {
|
||||
await github.rest.issues.update({ ...target, state: "closed", state_reason: "not_planned" });
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
# build output
|
||||
dist/
|
||||
coverage/
|
||||
.astro/
|
||||
|
||||
# dependencies
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "src/content"]
|
||||
path = src/content
|
||||
url = https://github.com/poli0981/content.git
|
||||
@@ -1,4 +1,11 @@
|
||||
# Supply-chain hardening (ignore-scripts) is applied in CI only — see docs 06 §1.6.
|
||||
# Locally we leave install scripts enabled so `sharp` can set up its binaries
|
||||
# for build-time image processing (astro imageService: 'compile').
|
||||
# Supply-chain hardening (docs 06 §6). npm >= 11 resolves lifecycle scripts against
|
||||
# package.json#allowScripts; `strict-allow-scripts` turns "package X has an install
|
||||
# script you haven't reviewed" from a warning into a failed install. A dependency that
|
||||
# suddenly grows a postinstall — the Shai-Hulud worm shape — stops the build instead of
|
||||
# executing. Review it, then `npm approve-scripts <pkg>` to add it to the allowlist.
|
||||
#
|
||||
# The previous note here claimed CI applied `ignore-scripts` and that `sharp` needed
|
||||
# scripts. Both were wrong: CI never set it, and sharp@0.35 ships prebuilt @img/sharp-*
|
||||
# binaries with no install script at all.
|
||||
fund=false
|
||||
strict-allow-scripts=true
|
||||
@@ -1,4 +1,5 @@
|
||||
# Generated / build output
|
||||
coverage/
|
||||
dist/
|
||||
.astro/
|
||||
.wrangler/
|
||||
@@ -9,3 +10,21 @@ package-lock.json
|
||||
|
||||
# Spec documentation suite — authored content, not ours to reformat
|
||||
poli0981.dev-docs/
|
||||
|
||||
# src/content is a git submodule (poli0981/content). Formatting it from here would
|
||||
# leave the submodule permanently dirty and the reformat could never be committed
|
||||
# from this repo — content is formatted in its own repo.
|
||||
src/content/
|
||||
|
||||
# Generated by scripts/gen-notices.mjs, which owns its formatting. Letting prettier
|
||||
# re-align the tables would put the two tools in permanent disagreement: prettier
|
||||
# rewrites the block, then `gen-notices --check` reports drift, on every single run.
|
||||
THIRD-PARTY-NOTICES.md
|
||||
|
||||
# Frontmatter templates for `npm run new:post`. Their {{PLACEHOLDER}} tokens are not
|
||||
# YAML — prettier reads `{{LANG}}` as a nested flow mapping and rewrites it to
|
||||
# `{ { LANG } }`, which new-post.mjs then never substitutes.
|
||||
docs/templates/
|
||||
|
||||
# Local Claude Code worktrees (excluded from git via .git/info/exclude).
|
||||
.claude/
|
||||
@@ -0,0 +1,165 @@
|
||||
# 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.
|
||||
- **Content warnings.** A labelled post, chapter or album opens with a banner that names its
|
||||
labels (horror, violence, politics…) in words, not by colour or icon alone. For the visual
|
||||
labels, images in the page are blurred until "Show images" is ticked. That control is a real
|
||||
checkbox, and the blur is plain CSS, so it works from the keyboard and without JavaScript.
|
||||
Blurring is a courtesy layer, not access control: the images are still downloaded.
|
||||
- **Age check.** An age-rated text is folded inside a `<details>` element. With JavaScript, its
|
||||
summary asks for the reader's age in a native modal `<dialog>`: focus starts on "No", Esc
|
||||
cancels and never counts as "yes", and focus returns to the summary. If the reader says no,
|
||||
focus moves to a line that explains why and offers to choose again. Nothing pops up on its own.
|
||||
Without JavaScript the summary opens the text. The answer stays in the browser
|
||||
(`localStorage`); see the privacy policy.
|
||||
|
||||
## 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).
|
||||
@@ -0,0 +1,302 @@
|
||||
# Changelog
|
||||
|
||||
Notable changes to poli0981.dev. The site deploys continuously from `main`; tags mark
|
||||
milestones. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
Content changes (posts, stories, albums) live in [`poli0981/content`](https://github.com/poli0981/content)
|
||||
and are not listed here.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.3.0] — 2026-11-21
|
||||
|
||||
The last feature release: from here on the project is in **maintenance mode**
|
||||
([`CONTRIBUTING.md`](CONTRIBUTING.md)).
|
||||
|
||||
### Added
|
||||
|
||||
- **Content labels, an age check and blurred images.** Posts, chapters and albums — and single
|
||||
gallery photos — can carry labels from a fixed list (horror, blood, jump scares, violence,
|
||||
self-harm, death, politics, religion, strong language, flashing lights, spoilers) and an age
|
||||
rating (13+, 16+, 18+).
|
||||
- A banner names the labels in the page's language.
|
||||
- For the visual labels, images are blurred until "Show images" is ticked. That is a real
|
||||
checkbox, and the blur is plain CSS, so it works from the keyboard and without JavaScript.
|
||||
- An age-rated text stays folded until the reader confirms their age in a native dialog. It
|
||||
never pops up on its own, and Esc never means "yes". The answer stays in the browser
|
||||
(`localStorage`: an age threshold, never a birth date).
|
||||
- Cards, the photo viewer, RSS descriptions and OG cards carry the warning too. The privacy
|
||||
policy (§6) lists the new local-storage item
|
||||
([#138](https://github.com/poli0981/poli0981-dev/pull/138)).
|
||||
- **The admin publishes on its own.** Every save or delete starts the publish workflow; bursts
|
||||
coalesce. The admin now follows a change until it is actually live: the build records the
|
||||
content commit it was made from (`version.content` in `/api/health`), and the publish bar
|
||||
shows building / waiting for review / merged and deploying / live / failed. The editor and
|
||||
gallery manager set labels, age ratings and per-photo labels
|
||||
([#137](https://github.com/poli0981/poli0981-dev/pull/137)).
|
||||
- **Qodana** (JetBrains, Qodana for JS) on every pull request and on `main`, with a zero-problem
|
||||
quality gate. Results go to Qodana Cloud and, for `main`, to code scanning
|
||||
([#135](https://github.com/poli0981/poli0981-dev/pull/135)).
|
||||
- **Licence check over the whole dependency tree**: every package in `package-lock.json`, with
|
||||
reviews per package instead of per licence. A package with no licence fails CI (#135).
|
||||
- Maintenance-mode governance:
|
||||
- `CONTRIBUTING.md`, in Vietnamese and English;
|
||||
- a language-problem issue form, with blank issues off and questions sent to Discussions;
|
||||
- a "kind of change" checklist in the pull request template;
|
||||
- a triage workflow that labels and closes new-feature requests.
|
||||
|
||||
### Changed
|
||||
|
||||
- Admin commits in the public content repository no longer carry the admin's email address; the
|
||||
private audit log keeps who did what (#137).
|
||||
- The admin's checks now match the content schema, so a save cannot queue a failing build:
|
||||
chapters are positive whole numbers, `cover` and `coverMedia` exclude each other, and an album
|
||||
must be a slug that already has photos (#137).
|
||||
- Deleting an image is refused while the **live** site's content still uses it, not only while
|
||||
`main` does (#137).
|
||||
- The post page uses the cover's alt text when one is set (#138); the editor has a field for it,
|
||||
and the media picker takes alt text for uploads (#137).
|
||||
- One-shot stories (`stories/<slug>.md`) can be created and edited in the admin (#137).
|
||||
- Dependencies, keeping the three-day cooldown: astro 7.4.12, @astrojs/cloudflare 14.4.8,
|
||||
@astrojs/svelte 9.1.6, jose 6.2.17, marked 18.2.1, wrangler 4.164.0, eslint 10.15.0,
|
||||
typescript-eslint 8.73.0, prettier 3.10.1, prettier-plugin-svelte 4.2.0 (14 Svelte files
|
||||
reformatted; the rendered markup is unchanged), playwright 1.65.1, knip 6.45.1
|
||||
([#134](https://github.com/poli0981/poli0981-dev/pull/134),
|
||||
[#136](https://github.com/poli0981/poli0981-dev/pull/136)). The SonarQube scan action is at 8.5.0
|
||||
and the OSV-Scanner workflow at 2.7.1 ([#127](https://github.com/poli0981/poli0981-dev/pull/127),
|
||||
[#128](https://github.com/poli0981/poli0981-dev/pull/128)).
|
||||
|
||||
### Fixed
|
||||
|
||||
- In the editor, Ctrl/⌘+S while typing in a tags field saved the previous tags (#137).
|
||||
- Qodana's first findings (#135):
|
||||
- the smoke test's forged Access token is built at run time instead of sitting in the source
|
||||
as a token literal;
|
||||
- redundant escapes in a Markdown-to-text regex;
|
||||
- a single-character alternation in the CSP check;
|
||||
- a heading table keyed by a mixed-script property name.
|
||||
|
||||
### Security
|
||||
|
||||
- deepmerge GHSA-gcqx-w48m-w2h4 (alias CVE-2026-93753) was withdrawn on 2026-11-16, and its
|
||||
Dependabot alert is closed. The OSV-Scanner ignore entries for it are gone (#134).
|
||||
- Node.js 26.13.1 (security release of 2026-11-10) is what CI and the build use (`.nvmrc` = 26).
|
||||
|
||||
## [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
|
||||
([#98](https://github.com/poli0981/poli0981-dev/pull/98),
|
||||
[#99](https://github.com/poli0981/poli0981-dev/pull/99),
|
||||
[#100](https://github.com/poli0981/poli0981-dev/pull/100)).
|
||||
|
||||
### Security
|
||||
|
||||
- **Turnstile gate bypass fixed** ([#97](https://github.com/poli0981/poli0981-dev/pull/97)): a pass
|
||||
cookie with a malformed signature made the check throw and the Worker failed open, serving the
|
||||
real page. Decoding is now total, signatures must be exactly 43 characters, and if deciding or
|
||||
rendering the gate throws the visitor gets a 503 — never the page behind it.
|
||||
- Admin: Access tokens older than 24 hours are refused, and `ADMIN_EMAILS` is required (fail
|
||||
closed). Every admin action is recorded in a KV audit log (90 days).
|
||||
- The IP denylist is enforced by the Worker entry for every route, pages included (it only
|
||||
covered on-demand routes), supports CIDR ranges and expiry, and is managed from the admin.
|
||||
- Request bodies are capped (report 32 KB, gate 8 KB, admin JSON 512 KB, uploads 20 MB) and
|
||||
every outgoing fetch has a timeout.
|
||||
- Bug reports go to the private `poli0981/site-reports` repository (the site repo is public);
|
||||
`@mentions` in reports are neutralised and Discord pings are disabled.
|
||||
- Widget thumbnails and game icons are mirrored by the cron worker and served from `/ext-img`, so
|
||||
browsers no longer contact Google or Steam before a visitor clicks; `img-src` is `'self'` only.
|
||||
- `frame-ancestors 'none'` is now sent as a header (it has no effect in a meta CSP).
|
||||
- CI installs with `--ignore-scripts` and fails on new install scripts; Dependabot waits three days
|
||||
before proposing a release; SonarCloud, CodeQL, OSV-Scanner and Snyk run on every PR.
|
||||
|
||||
### Added
|
||||
|
||||
- Light/dark theme that **follows the OS** by default, with a system → light → dark toggle.
|
||||
- "Glacier Teal" palette (navy and teal) across the site and admin, checked against WCAG AA by
|
||||
`tests/palette.test.ts`.
|
||||
- Admin: an overview dashboard, an activity page (audit log + content commits), a security page
|
||||
(IP denylist, configuration), editor draft autosave with restore, Ctrl/⌘+S, client-side field
|
||||
validation, a sandboxed preview, media search and usage, parallel uploads, gallery cover picker,
|
||||
drag-and-drop ordering and album deletion, a "session expired" banner.
|
||||
- Reader routes for one-shot stories (`/truyen/<slug>/`).
|
||||
- `/api/health` reports the running Worker version and the commit it was built from; the 500 page
|
||||
shows the Cloudflare Ray ID, which matches the structured JSON logs in Workers Logs.
|
||||
- Test suite on `node:test` (about 200 tests, ~99% line coverage of the TypeScript sources) and a
|
||||
SonarCloud quality gate.
|
||||
|
||||
### Changed
|
||||
|
||||
- Node 26; TypeScript 7 (`tsc`) for type checking, alongside TypeScript 6 for tools that need its
|
||||
API; ES2025 target. Astro 7.4, @astrojs/cloudflare 14.4, Wrangler 4.152 and current
|
||||
dependencies.
|
||||
- Vietnamese and English pages share one component each (eleven duplicated pages removed).
|
||||
- The header shows the full navigation from 960 px (it overflowed between 768 and 900 px).
|
||||
- Workers Builds deploys only `main`; other branches upload preview versions.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The language switch no longer leads to a 404 on posts whose slugs differ between languages.
|
||||
- The story reader bar no longer hides behind the sticky header.
|
||||
- Modal dialogs (the bug-report dialog) were stuck in the top-left corner; lists in posts had no
|
||||
bullets — both caused by Tailwind's preflight.
|
||||
- Callouts in MDX posts rendered unstyled: Astro left their inline styles out of the page's CSP, so
|
||||
the browser refused them. The rules moved to the shared prose stylesheet, and the build's CSP
|
||||
check now verifies every inline `<style>` (and forbids style attributes) as well as scripts.
|
||||
- Accessibility: the search is an ARIA combobox, the mobile menu is a modal dialog with a focus
|
||||
trap, lightbox focus handling, labelled report dialog, a correct "copied" message, Esc no longer
|
||||
dismisses the legal notice from elsewhere, landmark and link labels translated.
|
||||
- Gallery albums work without JavaScript; contact lines on /qa and the 403 page are real links.
|
||||
- Widgets: Steam game icons never appeared. The CDN hosts the worker used answer Workers with 403
|
||||
for any icon their edge has not cached; the worker now fetches icons from Steam's
|
||||
community-assets hosts, which serve Workers, falls back to another CDN, and keeps the copy an
|
||||
earlier run stored (games without an icon show their name only)
|
||||
([#101](https://github.com/poli0981/poli0981-dev/pull/101),
|
||||
[#102](https://github.com/poli0981/poli0981-dev/pull/102)). An optional read-only `GITHUB_TOKEN`
|
||||
keeps the GitHub feed from going stale under the per-IP rate limit Workers share.
|
||||
- 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
|
||||
|
||||
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,
|
||||
sitemap, JSON-LD and generated OG images; offline page with the Skull Hop mini-game; bug-report
|
||||
pipeline (Turnstile → GitHub issue + Discord); widgets cron worker.
|
||||
- **2026-08** — Content moved to the `poli0981/content` submodule; gallery with real photos; /now
|
||||
page; `new:post`; Lighthouse CI; generated third-party notices; CSP hash guard; security.txt; AI
|
||||
usage disclosure.
|
||||
- **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.3.0...HEAD
|
||||
[2.3.0]: https://github.com/poli0981/poli0981-dev/compare/v2.2.0...v2.3.0
|
||||
[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
|
||||
@@ -0,0 +1,52 @@
|
||||
# Content License
|
||||
|
||||
**This file covers content, not code.** The two are licensed differently on purpose.
|
||||
|
||||
| Scope | License | File |
|
||||
| ----------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------ |
|
||||
| Source code — every code, config, style and script file | **GPL-3.0-only** | `LICENSE` |
|
||||
| Content — posts, stories, photographs, original media (`src/content/**`, `src/assets/**`, images served from `/media/`) | **All Rights Reserved** | this file |
|
||||
| Third-party packages and fonts | their own licenses | `THIRD-PARTY-NOTICES.md` |
|
||||
|
||||
`package.json` declares `"license": "SEE LICENSE IN LICENSE"` precisely so nobody reads the
|
||||
GPL as covering the stories and photographs. It does not.
|
||||
|
||||
## English
|
||||
|
||||
All written content, stories, photographs, and other original media in this repository and on
|
||||
`poli0981.dev` are **© Kokone (SkullMute), all rights reserved**.
|
||||
|
||||
You may not reproduce, republish, or redistribute them, and **you may not use them to train
|
||||
machine-learning systems**, without prior written permission. Short quotations with attribution
|
||||
and a link are permitted (see Terms of Use §4). An individual page may state a different license
|
||||
for that page's content, in which case the page's own license prevails.
|
||||
|
||||
Cloning this repository does not grant a content license. `src/content` is a git submodule of
|
||||
the separate `poli0981/content` repository, under the same terms. If you fork, remove
|
||||
`src/content/**` and `src/assets/**` or replace them with your own.
|
||||
|
||||
**Permissions:** copyright@poli0981.dev · **Copyright infringement (DMCA):** dmca@poli0981.dev ·
|
||||
**Other removal requests:** takedown@poli0981.dev
|
||||
|
||||
## Tiếng Việt
|
||||
|
||||
Toàn bộ bài viết, truyện, ảnh và media gốc trong repo này và trên `poli0981.dev` thuộc **bản quyền
|
||||
© Kokone (SkullMute), bảo lưu mọi quyền**.
|
||||
|
||||
Không sao chép, đăng lại, phân phối lại, và **không dùng để huấn luyện hệ thống máy học** khi chưa
|
||||
có sự cho phép bằng văn bản. Được phép trích ngắn có ghi nguồn kèm link (xem Điều khoản §4). Một
|
||||
trang cụ thể có thể ghi giấy phép khác cho nội dung của trang đó — khi ấy giấy phép ghi tại trang
|
||||
được ưu tiên.
|
||||
|
||||
Việc clone repo này không đồng nghĩa với việc được cấp phép nội dung. `src/content` là submodule
|
||||
của repo riêng `poli0981/content`, cùng điều khoản này. Nếu bạn fork, hãy xoá `src/content/**` và
|
||||
`src/assets/**` hoặc thay bằng nội dung của chính bạn.
|
||||
|
||||
**Xin phép:** copyright@poli0981.dev · **Vi phạm bản quyền (DMCA):** dmca@poli0981.dev ·
|
||||
**Yêu cầu gỡ khác:** takedown@poli0981.dev
|
||||
|
||||
---
|
||||
|
||||
Rendered on the site at [`/legal/licenses`](https://poli0981.dev/legal/licenses/).
|
||||
See also [`/legal/ai-usage`](https://poli0981.dev/legal/ai-usage/) for how AI is used to build
|
||||
this site — a separate question from training on its content.
|
||||
@@ -0,0 +1,84 @@
|
||||
# Contributing
|
||||
|
||||
> **Tiếng Việt ở bên dưới.** / Vietnamese below.
|
||||
|
||||
## Maintenance mode
|
||||
|
||||
Since **v2.3.0 (November 2026)** this project is in **maintenance mode**. The site is complete; it
|
||||
is kept healthy, but **no new features are being added**. Only these changes are accepted:
|
||||
|
||||
1. **Dependency updates** on the regular schedule (Dependabot weekly, a combined update about
|
||||
once a month, always after a 3-day cooldown).
|
||||
2. **Security**: a dependency advisory of **High or Critical** severity, or a serious
|
||||
vulnerability in the runtime itself (Node.js, the Workers runtime), fixed as soon as
|
||||
possible — together with a feature only when the owner judges it truly necessary.
|
||||
3. **Major language, runtime or framework upgrades**: Node.js 26 → 28, TypeScript 7.1 replacing
|
||||
the TypeScript 6 API alias, the next Astro or Svelte major, and the like.
|
||||
4. **Bugs**: anything that does not work as intended, including **UI/UX** glitches and
|
||||
**accessibility** barriers ([ACCESSIBILITY.md](ACCESSIBILITY.md)).
|
||||
5. **Language**: spelling mistakes that could mislead, and wording that does not fit the culture
|
||||
or the local voice, in Vietnamese or English.
|
||||
|
||||
**Not accepted: new features.** An issue or pull request asking for one is labelled
|
||||
`enhancement` + `out-of-scope` and closed automatically
|
||||
([`.github/workflows/triage.yml`](.github/workflows/triage.yml)). If it was closed by mistake,
|
||||
reply on it and the owner will take another look; an exception the owner accepts carries the
|
||||
`maintenance-exception` label. Ideas are still welcome in
|
||||
[Discussions](https://github.com/poli0981/poli0981-dev/discussions), without any promise.
|
||||
|
||||
### How to report
|
||||
|
||||
- **A problem on the website**: the "Báo lỗi / Report a problem" button on the page itself, or the
|
||||
bug report form under [Issues](https://github.com/poli0981/poli0981-dev/issues/new/choose).
|
||||
- **An accessibility barrier**: the accessibility form under Issues.
|
||||
- **A spelling or wording problem**: the language form under Issues.
|
||||
- **A security vulnerability**: privately — see [SECURITY.md](SECURITY.md). Never in a public
|
||||
issue.
|
||||
|
||||
### Pull requests
|
||||
|
||||
Welcome for the five kinds of change above. Keep one change per pull request, follow the checks
|
||||
in the [pull request template](.github/pull_request_template.md), and run the commands listed in
|
||||
[README.md](README.md#commands) before opening it. CI must be green — `build` is required, and
|
||||
the SonarCloud and Qodana gates have to pass too. Commits on `main` are signed.
|
||||
|
||||
---
|
||||
|
||||
## Chế độ bảo trì
|
||||
|
||||
Từ **v2.3.0 (tháng 11/2026)**, dự án ở **chế độ bảo trì**. Trang web đã hoàn chỉnh; repo vẫn được giữ
|
||||
cho khoẻ mạnh nhưng **không thêm tính năng mới**. Chỉ nhận những thay đổi sau:
|
||||
|
||||
1. **Cập nhật dependency** định kỳ (Dependabot hằng tuần, gộp một lần khoảng mỗi tháng, luôn sau
|
||||
3 ngày "nguội").
|
||||
2. **Bảo mật**: lỗ hổng trong dependency ở mức **High hoặc Critical**, hoặc lỗ hổng nghiêm trọng của
|
||||
chính runtime (Node.js, Workers runtime) — sửa sớm nhất có thể; kèm tính năng chỉ khi chủ repo
|
||||
đánh giá là thật sự cần thiết.
|
||||
3. **Nâng cấp lớn ngôn ngữ, runtime, framework**: Node.js 26 → 28, TypeScript 7.1 thay alias API
|
||||
TypeScript 6, bản major tiếp theo của Astro hay Svelte…
|
||||
4. **Lỗi**: mọi thứ không chạy đúng ý định, gồm cả lỗi **UI/UX** và rào cản **accessibility**
|
||||
([ACCESSIBILITY.md](ACCESSIBILITY.md)).
|
||||
5. **Ngôn ngữ**: lỗi chính tả có thể gây hiểu nhầm, câu chữ không hợp văn hoá hay giọng địa phương,
|
||||
ở cả tiếng Việt lẫn tiếng Anh.
|
||||
|
||||
**Không nhận: tính năng mới.** Issue hoặc pull request đề xuất tính năng sẽ được gắn nhãn
|
||||
`enhancement` + `out-of-scope` và tự động đóng
|
||||
([`.github/workflows/triage.yml`](.github/workflows/triage.yml)). Nếu bị đóng nhầm, hãy trả lời ngay
|
||||
trong đó — chủ repo sẽ xem lại; ngoại lệ được chấp nhận mang nhãn `maintenance-exception`. Ý tưởng
|
||||
vẫn có thể trao đổi trong [Discussions](https://github.com/poli0981/poli0981-dev/discussions), không
|
||||
cam kết sẽ làm.
|
||||
|
||||
### Báo lỗi ở đâu
|
||||
|
||||
- **Lỗi trên trang web**: nút "Báo lỗi" ngay trên trang, hoặc form báo lỗi trong
|
||||
[Issues](https://github.com/poli0981/poli0981-dev/issues/new/choose).
|
||||
- **Rào cản accessibility**: form accessibility trong Issues.
|
||||
- **Lỗi chính tả, câu chữ**: form ngôn ngữ trong Issues.
|
||||
- **Lỗ hổng bảo mật**: báo riêng — xem [SECURITY.md](SECURITY.md). Không mở issue công khai.
|
||||
|
||||
### Pull request
|
||||
|
||||
Hoan nghênh cho năm loại thay đổi ở trên. Mỗi pull request một thay đổi, làm theo các mục kiểm tra
|
||||
trong [mẫu pull request](.github/pull_request_template.md), chạy các lệnh trong
|
||||
[README.md](README.md#commands) trước khi mở. CI phải xanh — `build` là bắt buộc, cổng SonarCloud
|
||||
và Qodana cũng phải qua. Commit trên `main` có chữ ký.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Disclaimer
|
||||
|
||||
The canonical, always-current version is rendered on the site at
|
||||
[`/legal/disclaimer`](https://poli0981.dev/legal/disclaimer/) (and
|
||||
[`/en/legal/disclaimer`](https://poli0981.dev/en/legal/disclaimer/)). This file exists so the
|
||||
notice travels with the repository — if the two ever disagree, the site wins.
|
||||
|
||||
## English
|
||||
|
||||
**1. No affiliation.** This is an independent personal website. It is not affiliated with,
|
||||
endorsed by, or sponsored by any company, brand, game publisher, or software developer mentioned
|
||||
anywhere on the Site.
|
||||
|
||||
**2. Third-party software and projects.** Any software, tools, games, or projects listed or
|
||||
referenced here belong to their respective developers and owners. Listings exist solely to gather
|
||||
information in one place for convenience. Names and logos are used only for identification
|
||||
(nominative use). All trademarks are the property of their respective holders.
|
||||
|
||||
**3. Gaming content.** Game titles, screenshots, and video thumbnails shown on the Site or on the
|
||||
SkullMute channel belong to their respective publishers and are used to identify and discuss the
|
||||
works.
|
||||
|
||||
**4. Opinions.** Everything on this Site reflects my personal views only, not those of any
|
||||
employer, partner, or community I take part in.
|
||||
|
||||
**5. No professional advice.** Technical write-ups and guides are shared as-is from personal
|
||||
experience. Use them at your own risk; nothing here is professional, legal, or financial advice.
|
||||
|
||||
**6. Fiction.** Stories published on this Site are works of fiction. Names, characters, and events
|
||||
are products of imagination; any resemblance to real persons or events is coincidental. Some
|
||||
stories carry content warnings — please heed them.
|
||||
|
||||
**7. External links.** Linked sites and services are outside my control; I am not responsible for
|
||||
their content, availability, or policies.
|
||||
|
||||
## Tiếng Việt
|
||||
|
||||
**1. Không liên kết.** Đây là trang cá nhân độc lập. Trang không liên kết, không được bảo trợ hay
|
||||
tài trợ bởi bất kỳ công ty, thương hiệu, nhà phát hành game hay nhà phát triển phần mềm nào được
|
||||
nhắc tới trên Trang.
|
||||
|
||||
**2. Phần mềm và dự án bên thứ ba.** Mọi phần mềm, công cụ, game hay dự án được liệt kê hoặc nhắc
|
||||
tới ở đây đều thuộc về nhà phát triển và chủ sở hữu tương ứng. Việc liệt kê chỉ nhằm gom thông tin
|
||||
về một chỗ cho tiện. Tên và logo chỉ dùng để nhận diện. Mọi nhãn hiệu thuộc về chủ sở hữu của
|
||||
chúng.
|
||||
|
||||
**3. Nội dung game.** Tên game, ảnh chụp màn hình và thumbnail video xuất hiện trên Trang hoặc trên
|
||||
kênh SkullMute thuộc về nhà phát hành tương ứng, được dùng để nhận diện và bàn luận về tác phẩm.
|
||||
|
||||
**4. Quan điểm.** Mọi thứ trên Trang chỉ phản ánh quan điểm cá nhân của mình, không đại diện cho
|
||||
bất kỳ nơi làm việc, đối tác hay cộng đồng nào mình tham gia.
|
||||
|
||||
**5. Không phải tư vấn chuyên môn.** Các bài kỹ thuật và hướng dẫn được chia sẻ nguyên trạng từ
|
||||
kinh nghiệm cá nhân. Dùng theo rủi ro của bạn; không có gì ở đây là tư vấn chuyên môn, pháp lý hay
|
||||
tài chính.
|
||||
|
||||
**6. Hư cấu.** Truyện đăng trên Trang là tác phẩm hư cấu. Tên, nhân vật và sự kiện là sản phẩm của
|
||||
trí tưởng tượng; mọi sự trùng hợp với người thật, việc thật đều là ngẫu nhiên. Một số truyện có
|
||||
cảnh báo nội dung — mong bạn lưu ý.
|
||||
|
||||
**7. Liên kết ngoài.** Các trang và dịch vụ được liên kết nằm ngoài tầm kiểm soát của mình; mình
|
||||
không chịu trách nhiệm về nội dung, tình trạng hoạt động hay chính sách của họ.
|
||||
@@ -0,0 +1,232 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
“This License” refers to version 3 of the GNU General Public License.
|
||||
|
||||
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
|
||||
|
||||
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
|
||||
|
||||
A “covered work” means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
|
||||
|
||||
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
|
||||
|
||||
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,125 @@
|
||||
# poli0981.dev
|
||||
|
||||
[](https://github.com/poli0981/poli0981-dev/actions/workflows/ci.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_poli0981-dev)
|
||||
[](https://github.com/poli0981/poli0981-dev/actions/workflows/qodana.yml)
|
||||
[](LICENSE)
|
||||
[](CONTRIBUTING.md#maintenance-mode)
|
||||
|
||||
The personal site of Kokone (SkullMute) — dev portfolio, blog, short fiction and a hub for
|
||||
the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https://poli0981.dev)**.
|
||||
|
||||
> Trang cá nhân của Kokone (SkullMute): dự án, blog, truyện ngắn và kênh SkullMute — song ngữ
|
||||
> Việt/Anh. Tài liệu thiết kế đầy đủ (tiếng Việt) nằm trong [`poli0981.dev-docs/`](poli0981.dev-docs/00_INDEX.md).
|
||||
|
||||
## Status
|
||||
|
||||
**Maintenance mode since v2.3.0 (November 2026).** The site is complete. It still gets
|
||||
dependency updates, security fixes (High/Critical advisories, runtime vulnerabilities), major
|
||||
runtime and framework upgrades, bug fixes (UI/UX and accessibility included) and language fixes,
|
||||
but no new features. Issues and pull requests asking for one are closed automatically. Details:
|
||||
[`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
> **Trạng thái:** chế độ bảo trì từ v2.3.0 — chỉ cập nhật dependency, vá bảo mật, nâng cấp
|
||||
> runtime/framework, sửa lỗi (cả UI/UX, accessibility) và sửa lỗi ngôn ngữ; không thêm tính năng mới.
|
||||
|
||||
## Stack
|
||||
|
||||
| Layer | Choice |
|
||||
| --------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Framework | [Astro 7](https://astro.build) (static-first) with Svelte 5 islands |
|
||||
| Styling | Tailwind CSS 4, design tokens in `src/styles/global.css` ("Glacier Teal" palette) |
|
||||
| Hosting | Cloudflare Workers + Static Assets; KV, R2, Images, Rate Limiting, Access, Turnstile |
|
||||
| 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 · Qodana · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) · axe-core gate · licence check |
|
||||
|
||||
## How it fits together
|
||||
|
||||
```
|
||||
visitor ─▶ Cloudflare edge ─▶ src/worker.ts (every request, pages included)
|
||||
www → apex · IP denylist (KV) · admin host split · /media (R2) · /ext-img (KV)
|
||||
Turnstile gate (48-hour pass) · static pages from ASSETS · the rest → Astro app
|
||||
├─ /api/report, /api/gate, /api/widgets, /api/health
|
||||
└─ admin.poli0981.dev (Cloudflare Access + JWT check)
|
||||
workers/widgets (cron, every 45 min) ─▶ YouTube / Steam / GitHub ─▶ KV (data + mirrored images)
|
||||
```
|
||||
|
||||
Almost every page is prerendered. The Worker entry runs first for every route so the bot gate,
|
||||
the denylist and the security headers also cover static pages. Details:
|
||||
[`02_ARCHITECTURE.md`](poli0981.dev-docs/02_ARCHITECTURE.md) and [`06_SECURITY.md`](poli0981.dev-docs/06_SECURITY.md).
|
||||
|
||||
## Getting started
|
||||
|
||||
Requirements: Node 26 (`.nvmrc`) and npm 11. The content submodule is public, so a plain clone works.
|
||||
|
||||
```bash
|
||||
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
|
||||
cd poli0981-dev
|
||||
npm ci --ignore-scripts && npm run check-install-scripts
|
||||
npx lefthook install
|
||||
npm run types && npm run types:widgets
|
||||
npm run dev
|
||||
```
|
||||
|
||||
`npm run dev` runs Astro on workerd with local bindings. The admin works locally with a stand-in
|
||||
identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.dev.vars`.
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | What it does |
|
||||
| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
|
||||
| `npm run dev` | Dev server (workerd, local KV/R2) |
|
||||
| `npm run build` | `astro build` → OG images → Pagefind index → CSP hash check |
|
||||
| `npm run preview` | Serve the build |
|
||||
| `npm run check` | `astro check` (TypeScript 6 language service) |
|
||||
| `npm run typecheck` | `tsc` from TypeScript 7 for the site and the widgets worker |
|
||||
| `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) |
|
||||
|
||||
## Deploying
|
||||
|
||||
Cloudflare **Workers Builds** builds every push: `main` runs `npx wrangler deploy`, any other
|
||||
branch only `npx wrangler versions upload` (a preview version that takes no traffic). After a
|
||||
merge, `https://poli0981.dev/api/health` reports the running version and commit. The widgets
|
||||
worker deploys by hand: `npx wrangler deploy --config workers/widgets/wrangler.jsonc`.
|
||||
Setup from scratch: [`07_CLOUDFLARE_SETUP.md`](poli0981.dev-docs/07_CLOUDFLARE_SETUP.md);
|
||||
pipeline: [`08_CI_CD.md`](poli0981.dev-docs/08_CI_CD.md); changes per release: [`CHANGELOG.md`](CHANGELOG.md).
|
||||
|
||||
## Admin
|
||||
|
||||
`admin.poli0981.dev` is the owner's editor: write and edit posts (commits to the content repo),
|
||||
upload images (transformed once into AVIF/WebP and stored in R2), manage gallery albums, set
|
||||
content labels and age ratings, review an audit log and manage the IP denylist. Every save or
|
||||
delete publishes itself: it starts a submodule-bump PR that CI must pass, which then merges and
|
||||
deploys, and the admin follows it until the change is live (`/api/health` reports the content
|
||||
commit too). It sits behind Cloudflare Access, and the Worker independently verifies the Access
|
||||
JWT (≤ 24 hours old) and an email allowlist on every request.
|
||||
|
||||
## Security
|
||||
|
||||
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).
|
||||
- **Content** (posts, stories, photographs — the `poli0981/content` submodule, `src/assets/`,
|
||||
uploaded media): **all rights reserved**, see [`CONTENT-LICENSE.md`](CONTENT-LICENSE.md).
|
||||
- Third-party packages and fonts: [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md).
|
||||
- How AI was used to build the site: [`/legal/ai-usage`](https://poli0981.dev/legal/ai-usage/).
|
||||
@@ -0,0 +1,64 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Email **security@poli0981.dev**. Please include steps to reproduce and the affected URL.
|
||||
Do not open a public issue for a security problem.
|
||||
|
||||
Expect an acknowledgement within 7 days. This is a personal site maintained by one
|
||||
person, in their spare time — there is no bug bounty and no payout.
|
||||
|
||||
Machine-readable contact: <https://poli0981.dev/.well-known/security.txt> (RFC 9116).
|
||||
|
||||
## Scope
|
||||
|
||||
**In scope**
|
||||
|
||||
- `poli0981.dev`, including its `/api/*` endpoints, `/media/*` and `/ext-img/*`
|
||||
- `admin.poli0981.dev` — anything that reaches the admin or its API without passing
|
||||
Cloudflare Access, the Worker's own Access JWT check or the email allowlist, or that lets
|
||||
an admin page run attacker-controlled script
|
||||
- The Turnstile bot gate in front of the pages (a way to see page content without a pass)
|
||||
- The widgets cron worker and this repository's build, CI and deploy pipeline
|
||||
|
||||
**Out of scope**
|
||||
|
||||
- Findings that require an already-compromised Cloudflare, GitHub or Access identity
|
||||
- Attacks on Cloudflare Access's own login flow (report those to Cloudflare)
|
||||
- Volumetric denial of service
|
||||
- Missing hardening headers with no demonstrated impact
|
||||
- Reports that are only raw automated-scanner output, with no working proof of concept
|
||||
- Anything about the third-party services the site links out to (YouTube, Steam, Discord…)
|
||||
|
||||
## Supported versions
|
||||
|
||||
Only the currently deployed site (`main` → Cloudflare Workers) is supported. Releases are
|
||||
tagged (`v2.0.0` onwards, see [`CHANGELOG.md`](CHANGELOG.md)) for reference only — there are
|
||||
no backports. `https://poli0981.dev/api/health` reports the version and commit that is live.
|
||||
|
||||
The project is in maintenance mode ([`CONTRIBUTING.md`](CONTRIBUTING.md)), and security work
|
||||
is the first thing it keeps doing: a dependency advisory of High or Critical severity, or a
|
||||
serious vulnerability in Node.js or the Workers runtime, is fixed and deployed as soon as
|
||||
possible, outside the regular update schedule.
|
||||
|
||||
## What the site actually handles
|
||||
|
||||
Useful context when judging impact — the site is static and stores almost nothing:
|
||||
|
||||
- No visitor accounts or logins, no ad or analytics trackers. The only cookie is
|
||||
`__Host-gate`, a signed 48-hour pass set after the Turnstile bot check (expiry, random
|
||||
value and HMAC — no identifier; see `src/lib/gate/`). Preferences, and the answer to the age
|
||||
check on age-rated pages (an age threshold, never a birth date), stay in the browser's
|
||||
`localStorage` and are never sent to the site.
|
||||
- User-submitted input: the bug-report form (Turnstile-gated, schema-validated, size-capped,
|
||||
forwarded to an issue in a **private** repository and a Discord webhook) and the bot-check
|
||||
token exchange at `/api/gate`. Both are rate-limited per client.
|
||||
- IP addresses are used transiently for rate limiting and the IP denylist; they are not
|
||||
stored with reports. Workers Logs keep request logs for 7 days.
|
||||
- The admin is single-owner: Cloudflare Access in front, plus the Worker verifying the Access
|
||||
JWT, a 24-hour token age and an email allowlist on every request; every action is written to
|
||||
an audit log.
|
||||
|
||||
The hardening in place is described in
|
||||
[`poli0981.dev-docs/06_SECURITY.md`](poli0981.dev-docs/06_SECURITY.md), and the privacy
|
||||
statement at [`/legal/privacy`](https://poli0981.dev/legal/privacy/).
|
||||
@@ -0,0 +1,125 @@
|
||||
# Third-Party Notices
|
||||
|
||||
This site is built with open-source software. Each component below remains under its own
|
||||
license; the full license texts ship inside each package under `node_modules/`.
|
||||
|
||||
A shorter, human-facing version is rendered on the site at
|
||||
[`/legal/third-party`](https://poli0981.dev/legal/third-party/).
|
||||
|
||||
**The table below is generated** from `package-lock.json` by `scripts/gen-notices.mjs`, and
|
||||
CI fails if it drifts (docs 08 §6). Edit the script, not the block.
|
||||
|
||||
<!-- BEGIN GENERATED — edit scripts/gen-notices.mjs, not this 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 (36)
|
||||
|
||||
`runtime` are declared in `dependencies`; `build` in `devDependencies` and never served.
|
||||
|
||||
| Package | License | Kind |
|
||||
| ------- | ------- | ---- |
|
||||
| `@astrojs/check` | MIT | build |
|
||||
| `@astrojs/cloudflare` | MIT | runtime |
|
||||
| `@astrojs/mdx` | MIT | runtime |
|
||||
| `@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 |
|
||||
| `@typescript/native` | Apache-2.0 | build |
|
||||
| `astro` | MIT | runtime |
|
||||
| `eslint` | MIT | build |
|
||||
| `eslint-plugin-astro` | MIT | build |
|
||||
| `eslint-plugin-svelte` | MIT | build |
|
||||
| `exifr` | MIT | build |
|
||||
| `jose` | MIT | runtime |
|
||||
| `knip` | ISC | build |
|
||||
| `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 |
|
||||
| `prettier-plugin-tailwindcss` | MIT | build |
|
||||
| `satori` | MPL-2.0 | build |
|
||||
| `satori-html` | MIT | build |
|
||||
| `sharp` | Apache-2.0 | runtime |
|
||||
| `svelte` | MIT | runtime |
|
||||
| `tailwindcss` | MIT | runtime |
|
||||
| `typescript` | Apache-2.0 | build |
|
||||
| `typescript-eslint` | MIT | build |
|
||||
| `wrangler` | MIT OR Apache-2.0 | build |
|
||||
| `yaml` | ISC | runtime |
|
||||
| `zod` | MIT | runtime |
|
||||
|
||||
## License spread across direct dependencies
|
||||
|
||||
| License | Packages |
|
||||
| ------- | -------- |
|
||||
| MIT | 26 |
|
||||
| Apache-2.0 | 4 |
|
||||
| MPL-2.0 | 3 |
|
||||
| ISC | 2 |
|
||||
| MIT OR Apache-2.0 | 1 |
|
||||
|
||||
Transitive dependencies are deliberately not tallied here. Which packages get installed
|
||||
depends on the platform (npm resolves only the matching `@img/sharp-*` / `*-msvc`
|
||||
binaries), and even a bare count would change with every lockfile bump. The complete
|
||||
inventory is `package-lock.json`; platform binaries are covered in prose below.
|
||||
|
||||
## Licenses outside the standard allowlist
|
||||
|
||||
**MPL-2.0** — 3 package(s):
|
||||
|
||||
- `@axe-core/playwright` — reviewed: File-level copyleft. Runs only in the accessibility tests (tests/a11y); never shipped.
|
||||
- `@resvg/resvg-js` — reviewed: File-level copyleft. Used unmodified at build time to draw the OG cards (scripts/gen-og.mjs); never shipped to the browser or the Worker.
|
||||
- `satori` — reviewed: File-level copyleft. Used unmodified at build time to draw the OG cards (scripts/gen-og.mjs); never shipped to the browser or the Worker.
|
||||
|
||||
<!-- END GENERATED -->
|
||||
|
||||
## Platform binaries (not in the table above)
|
||||
|
||||
npm installs only the prebuilt binary matching the build machine, so these vary by platform
|
||||
and are surveyed in prose rather than generated.
|
||||
|
||||
**`@img/sharp-*` — Apache-2.0 AND LGPL-3.0-or-later.** sharp's prebuilt binaries bundle
|
||||
libvips, part of which is LGPL. This is fine here and worth writing down rather than
|
||||
rediscovering: sharp is a **build-time** dependency (`imageService: "compile"`), the binary
|
||||
runs on the build machine and is never served to a visitor, and LGPL obligations attach to
|
||||
_distributing_ the library. The built site contains only the resulting AVIF/WebP files.
|
||||
|
||||
**`@resvg/resvg-js-*`, `lightningcss-*` — MPL-2.0.** File-level copyleft, used unmodified as
|
||||
build tools, likewise never shipped.
|
||||
|
||||
## Infrastructure services
|
||||
|
||||
Not packages — listed for transparency:
|
||||
|
||||
- **Cloudflare** — Workers and static assets (hosting, CDN), Workers KV (widget data, mirrored
|
||||
widget images, the IP denylist, the admin audit log), R2 (images uploaded through the admin),
|
||||
Images (one-time AVIF/WebP transforms), Rate Limiting, Turnstile (bot gate and bug-report
|
||||
form), Access (the admin), Web Analytics (cookieless page views, production builds only) and
|
||||
Workers Logs.
|
||||
- **GitHub** — source code, the content repository, Actions CI, and issues in a private
|
||||
repository for site bug reports.
|
||||
- **Discord** — a webhook receiving bug-report notifications.
|
||||
- **YouTube, Steam and GitHub public APIs** — read by the widgets cron worker; visitors' browsers
|
||||
never call them (images are mirrored and served from the site).
|
||||
- **SonarCloud, Qodana (JetBrains), CodeQL, OSV-Scanner, Snyk** — code and dependency analysis in
|
||||
CI; nothing they do reaches the running site.
|
||||
|
||||
## Fonts
|
||||
|
||||
Bricolage Grotesque, Be Vietnam Pro, Literata and JetBrains Mono are served self-hosted via
|
||||
Astro's Fonts API under the **SIL Open Font License 1.1**. They are fetched at build time, so
|
||||
they do not appear in the dependency table above.
|
||||
|
||||
## AI tooling
|
||||
|
||||
The models used to write this site's code are disclosed separately at
|
||||
[`/legal/ai-usage`](https://poli0981.dev/legal/ai-usage/).
|
||||
@@ -5,9 +5,89 @@ import svelte from "@astrojs/svelte";
|
||||
import mdx from "@astrojs/mdx";
|
||||
import sitemap from "@astrojs/sitemap";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import { execFileSync } from "node:child_process";
|
||||
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.
|
||||
const BUILD_TIME = new Date().toISOString();
|
||||
|
||||
// The theme must be applied before first paint or the default flashes, so this has to
|
||||
// be inline and synchronous — which rules out a processed <script> (Astro turns those
|
||||
// into deferred external modules). `is:inline` would work but Astro never hashes it
|
||||
// (see core/csp/common.js: trackScriptHashes only covers bundled scripts, client
|
||||
// directives, island prebuilts, and settings.scripts), leaving it to survive only
|
||||
// because a <meta> CSP does not govern markup that precedes it — fragile by accident.
|
||||
// `injectScript("head-inline")` is the one path that is BOTH rendered verbatim inline
|
||||
// AND hashed from that same string, so the CSP can never drift from the source.
|
||||
// It also restores the "hide scrollbar" preference for the same reason (no flash of a
|
||||
// scrollbar that then disappears). The script itself lives in src/lib/theme.ts, next to
|
||||
// the rules it shares with ThemeToggle.svelte.
|
||||
|
||||
/** @type {import('astro').AstroIntegration} */
|
||||
const themeBootstrap = {
|
||||
name: "theme-bootstrap",
|
||||
hooks: {
|
||||
"astro:config:setup": ({ injectScript }) => injectScript("head-inline", THEME_BOOTSTRAP),
|
||||
},
|
||||
};
|
||||
|
||||
// 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.
|
||||
const CF_BEACON_DEFAULT =
|
||||
process.env.WORKERS_CI === "1" && process.env.WORKERS_CI_BRANCH === "main";
|
||||
|
||||
// The commit a build was made from (Workers Builds sets WORKERS_CI_COMMIT_SHA, GitHub Actions
|
||||
// GITHUB_SHA). /api/health reports it next to the Worker version id (src/lib/version.ts), so
|
||||
// "what is live?" maps straight to a commit.
|
||||
const BUILD_COMMIT = process.env.WORKERS_CI_COMMIT_SHA ?? process.env.GITHUB_SHA ?? null;
|
||||
|
||||
// The poli0981/content commit this build's src/content points at: the gitlink recorded in
|
||||
// HEAD, so it is right even when the submodule checkout itself is missing or dirty. The admin
|
||||
// compares it with the content repo's head to tell "merged" from "live"; /api/health reports
|
||||
// it next to the site commit. null when git or the gitlink isn't there.
|
||||
function contentCommit() {
|
||||
try {
|
||||
const sha = execFileSync("git", ["rev-parse", "HEAD:src/content"], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).trim();
|
||||
return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const CONTENT_COMMIT = contentCommit();
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
@@ -16,6 +96,18 @@ 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
|
||||
// (`Cf-Speculation-Refused`), so hovering any link logged a failed request. Pin this
|
||||
// off so re-adding the router can never silently switch hover-prefetch back on.
|
||||
prefetch: false,
|
||||
|
||||
// The @cloudflare/vite-plugin (used by this adapter) runs `astro dev` on workerd and
|
||||
// auto-exposes the wrangler.jsonc bindings (KV/ASSETS) + .dev.vars — no platformProxy needed.
|
||||
adapter: cloudflare({
|
||||
@@ -43,15 +135,43 @@ export default defineConfig({
|
||||
TURNSTILE_SECRET: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
GITHUB_ISSUES_TOKEN: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
DISCORD_WEBHOOK_BUG: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
// Admin (admin.poli0981.dev), two fine-grained tokens (src/lib/admin/github.ts):
|
||||
// content repo Contents RW, and site repo Actions RW for the publish workflow;
|
||||
// plus the email allowlist on top of Access (unset = the admin refuses everyone).
|
||||
GITHUB_CONTENT_TOKEN: envField.string({
|
||||
context: "server",
|
||||
access: "secret",
|
||||
optional: true,
|
||||
}),
|
||||
GITHUB_PUBLISH_TOKEN: envField.string({
|
||||
context: "server",
|
||||
access: "secret",
|
||||
optional: true,
|
||||
}),
|
||||
ADMIN_EMAILS: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
PUBLIC_CF_BEACON: envField.boolean({
|
||||
context: "client",
|
||||
access: "public",
|
||||
default: CF_BEACON_DEFAULT,
|
||||
}),
|
||||
// Signs the 48-hour Turnstile-gate pass cookie (src/lib/gate). The gate itself is
|
||||
// switched by the GATE_MODE var in wrangler.jsonc and stays off without this secret.
|
||||
GATE_SECRET: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
},
|
||||
},
|
||||
|
||||
integrations: [
|
||||
themeBootstrap,
|
||||
localizedNotFound,
|
||||
svelte(),
|
||||
mdx(),
|
||||
sitemap({
|
||||
i18n: { defaultLocale: "vi", locales: { vi: "vi", en: "en" } },
|
||||
filter: (page) => !NON_INDEXED.test(page),
|
||||
// The sitemap shipped with no <lastmod> at all. Per-page dates would mean
|
||||
// threading content dates through the integration; the build timestamp is the
|
||||
// honest site-wide answer and is what crawlers use to schedule a recrawl.
|
||||
serialize: (item) => ({ ...item, lastmod: BUILD_TIME }),
|
||||
}),
|
||||
],
|
||||
|
||||
@@ -62,7 +182,13 @@ export default defineConfig({
|
||||
},
|
||||
|
||||
// Tailwind v4 is wired through the Vite plugin (NOT the legacy @astrojs/tailwind).
|
||||
vite: { plugins: [tailwindcss()] },
|
||||
vite: {
|
||||
plugins: [tailwindcss()],
|
||||
define: {
|
||||
__BUILD_COMMIT__: JSON.stringify(BUILD_COMMIT),
|
||||
__CONTENT_COMMIT__: JSON.stringify(CONTENT_COMMIT),
|
||||
},
|
||||
},
|
||||
|
||||
// Self-hosted fonts via the built-in Fonts API. Subsets include `vietnamese`.
|
||||
// Preload is chosen per-<Font> in BaseLayout — exactly the 2 first-paint files.
|
||||
@@ -111,11 +237,15 @@ export default defineConfig({
|
||||
algorithm: "SHA-256",
|
||||
directives: [
|
||||
"default-src 'self'",
|
||||
"img-src 'self' data: https://i.ytimg.com https://media.steampowered.com https://*.steamstatic.com",
|
||||
// Widget thumbnails/icons are mirrored into KV and served from /ext-img (lib/ext-img),
|
||||
// so no third-party image host is allowed — a page never contacts YouTube or Steam
|
||||
// before the visitor presses play.
|
||||
"img-src 'self' data:",
|
||||
// youtube-nocookie: video facade; challenges.cloudflare.com: Turnstile widget iframe.
|
||||
"frame-src https://www.youtube-nocookie.com https://challenges.cloudflare.com",
|
||||
// challenges.cloudflare.com: Turnstile client XHRs (siteverify is server-side).
|
||||
"connect-src 'self' https://challenges.cloudflare.com",
|
||||
// cloudflareinsights.com: Web Analytics beacon reports (manual snippet mode).
|
||||
"connect-src 'self' https://challenges.cloudflare.com https://cloudflareinsights.com",
|
||||
"font-src 'self'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'self'",
|
||||
@@ -123,9 +253,15 @@ export default defineConfig({
|
||||
],
|
||||
// 'self' keeps dynamically-imported island chunks loadable; 'wasm-unsafe-eval'
|
||||
// is pre-baked for Pagefind's WebAssembly; challenges.cloudflare.com loads the
|
||||
// Turnstile api.js (bug-report captcha, docs 10).
|
||||
// Turnstile api.js (bug-report captcha, docs 10); static.cloudflareinsights.com
|
||||
// serves the Web Analytics beacon (src/components/CfBeacon.astro).
|
||||
scriptDirective: {
|
||||
resources: ["'self'", "'wasm-unsafe-eval'", "https://challenges.cloudflare.com"],
|
||||
resources: [
|
||||
"'self'",
|
||||
"'wasm-unsafe-eval'",
|
||||
"https://challenges.cloudflare.com",
|
||||
"https://static.cloudflareinsights.com",
|
||||
],
|
||||
},
|
||||
styleDirective: { resources: ["'self'"] },
|
||||
},
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
---
|
||||
title: "{{TITLE}}"
|
||||
description: ""
|
||||
lang: {{LANG}}
|
||||
date: {{DATE}}
|
||||
tags: []
|
||||
draft: true
|
||||
---
|
||||
|
||||
<!--
|
||||
description max 200 chars, shown in listings, RSS and the OG card
|
||||
translationKey add the SAME value to the vi and en file to pair them for hreflang
|
||||
updated optional, YYYY-MM-DD — adds dateModified to the BlogPosting schema
|
||||
cover optional, path relative to this file; Astro validates it exists
|
||||
contentWarning optional labels from src/lib/content-labels.ts, e.g. [politics] — a banner;
|
||||
the visual ones (horror, blood, violence…) also blur the post's images
|
||||
ageRating optional "13+" | "16+" | "18+" — the text stays folded until the reader
|
||||
confirms their age
|
||||
draft: true hidden in production, visible in `npm run dev`. Flip when ready.
|
||||
-->
|
||||
|
||||
Mở bài ở đây.
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
q: "{{TITLE}}"
|
||||
lang: {{LANG}}
|
||||
group: dev
|
||||
order: 1
|
||||
---
|
||||
|
||||
<!--
|
||||
group channel | dev | personal — decides which section of /qa it lands in
|
||||
order ascending within the group
|
||||
The body becomes acceptedAnswer.text in the FAQPage schema, so keep it plain prose.
|
||||
-->
|
||||
|
||||
Trả lời ở đây.
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: "{{TITLE}}"
|
||||
tagline: ""
|
||||
lang: {{LANG}}
|
||||
stack: []
|
||||
status: active
|
||||
featured: false
|
||||
year: {{YEAR}}
|
||||
draft: true
|
||||
---
|
||||
|
||||
<!--
|
||||
status active | maintained | archived
|
||||
repo/url optional, must be full URLs (validated by z.url())
|
||||
stack e.g. ["Astro", "TypeScript"] — becomes programmingLanguage in JSON-LD
|
||||
featured true floats it to the top of /projects
|
||||
-->
|
||||
|
||||
Mô tả dự án.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: "{{TITLE}}"
|
||||
description: ""
|
||||
lang: {{LANG}}
|
||||
date: {{DATE}}
|
||||
series: "{{SERIES}}"
|
||||
chapter: 1
|
||||
status: ongoing
|
||||
contentWarning: []
|
||||
# ageRating: "16+"
|
||||
tags: []
|
||||
draft: true
|
||||
---
|
||||
|
||||
<!--
|
||||
The FOLDER name under stories/ is the series route segment — keep chapters of one
|
||||
series in one folder, e.g. stories/dem-khong-tieng/chuong-01.md
|
||||
chapter integer, consecutive; drives prev/next links and ordering
|
||||
status ongoing | complete | dropped
|
||||
contentWarning labels from src/lib/content-labels.ts, e.g. [horror, violence]: a warning
|
||||
banner; horror, blood, jumpscare, violence, self-harm and death also
|
||||
blur the images
|
||||
ageRating "13+" | "16+" | "18+" (optional): the text stays folded until the
|
||||
reader confirms their age (remembered in their browser only)
|
||||
-->
|
||||
|
||||
Chương bắt đầu ở đây.
|
||||
@@ -1,23 +1,26 @@
|
||||
import { defineConfig } from "eslint/config";
|
||||
import tseslint from "typescript-eslint";
|
||||
import astro from "eslint-plugin-astro";
|
||||
import svelte from "eslint-plugin-svelte";
|
||||
|
||||
export default tseslint.config(
|
||||
export default defineConfig(
|
||||
{
|
||||
ignores: [
|
||||
"dist/",
|
||||
".astro/",
|
||||
"**/.wrangler/",
|
||||
"node_modules/",
|
||||
"coverage/",
|
||||
".claude/",
|
||||
"public/pagefind/",
|
||||
"poli0981.dev-docs/",
|
||||
"**/worker-configuration.d.ts",
|
||||
],
|
||||
},
|
||||
...tseslint.configs.recommended,
|
||||
...tseslint.configs.strict,
|
||||
...astro.configs.recommended,
|
||||
...svelte.configs.recommended,
|
||||
tseslint.configs.recommended,
|
||||
tseslint.configs.strict,
|
||||
astro.configs.recommended,
|
||||
svelte.configs.recommended,
|
||||
{
|
||||
rules: {
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/knip@6/schema.json",
|
||||
"ignoreDependencies": ["cloudflare", "lefthook"],
|
||||
"entry": ["workers/widgets/src/index.ts", "scripts/*.mjs"],
|
||||
"ignore": ["public/sw.js"]
|
||||
"entry": ["workers/widgets/src/index.ts", "scripts/*.mjs", "tests/support/**/*.{mjs,ts}"],
|
||||
"ignore": ["public/sw.js", "public/skullhop.js", "public/gate.js"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"ci": {
|
||||
"collect": {
|
||||
"numberOfRuns": 3,
|
||||
"settings": {
|
||||
"throttlingMethod": "simulate"
|
||||
}
|
||||
},
|
||||
"assert": {
|
||||
"assertions": {
|
||||
"categories:performance": ["warn", { "minScore": 0.95 }],
|
||||
"categories:accessibility": ["warn", { "minScore": 0.95 }],
|
||||
"categories:best-practices": ["warn", { "minScore": 0.95 }],
|
||||
"categories:seo": ["warn", { "minScore": 0.95 }],
|
||||
|
||||
"largest-contentful-paint": ["warn", { "maxNumericValue": 2000 }],
|
||||
"cumulative-layout-shift": ["warn", { "maxNumericValue": 0.05 }],
|
||||
"total-blocking-time": ["warn", { "maxNumericValue": 200 }],
|
||||
"total-byte-weight": ["warn", { "maxNumericValue": 614400 }]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
# 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:
|
||||
#
|
||||
# [[IgnoredVulns]]
|
||||
# id = "GHSA-xxxx-xxxx-xxxx"
|
||||
# ignoreUntil = 2027-01-31
|
||||
# reason = "Why it cannot reach a visitor, and what would make it go away."
|
||||
#
|
||||
# No entries today. The last one, deepmerge GHSA-gcqx-w48m-w2h4 (alias
|
||||
# CVE-2026-93753), was removed on 2026-11-21: the advisory was withdrawn on
|
||||
# 2026-11-16 and OSV no longer reports deepmerge 4.3.1.
|
||||
@@ -5,57 +5,89 @@
|
||||
"private": true,
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
"node": ">=26"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild": true,
|
||||
"workerd": true,
|
||||
"lefthook": true,
|
||||
"fsevents": true
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro build && node scripts/gen-og.mjs && pagefind --site dist/client",
|
||||
"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",
|
||||
"check-licenses": "node scripts/check-licenses.mjs",
|
||||
"new:post": "node scripts/new-post.mjs",
|
||||
"gen-og": "node scripts/gen-og.mjs",
|
||||
"preview": "astro preview",
|
||||
"astro": "astro",
|
||||
"check": "astro check",
|
||||
"typecheck": "node node_modules/@typescript/native/bin/tsc -p tsconfig.json && node node_modules/@typescript/native/bin/tsc -p workers/widgets/tsconfig.json",
|
||||
"types": "wrangler types --strict-vars=false",
|
||||
"types:widgets": "wrangler types --config workers/widgets/wrangler.jsonc workers/widgets/worker-configuration.d.ts",
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"knip": "knip",
|
||||
"deploy": "wrangler deploy --config ./dist/server/wrangler.json",
|
||||
"gen-demo-gallery": "node scripts/gen-demo-gallery.mjs",
|
||||
"deploy": "wrangler deploy",
|
||||
"strip-exif": "node scripts/strip-exif.mjs",
|
||||
"check-exif": "node scripts/check-exif.mjs"
|
||||
"check-exif": "node scripts/check-exif.mjs",
|
||||
"check-install-scripts": "node scripts/check-install-scripts.mjs"
|
||||
},
|
||||
"overrides": {
|
||||
"fflate": "^0.7.5",
|
||||
"minimatch": "^11.0.4",
|
||||
"sharp": "$sharp",
|
||||
"miniflare": {
|
||||
"undici": "^7.30.1"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "^14.1.3",
|
||||
"@astrojs/mdx": "^7.0.3",
|
||||
"@astrojs/cloudflare": "^14.4.8",
|
||||
"@astrojs/mdx": "^8.1.6",
|
||||
"@astrojs/rss": "^4.0.19",
|
||||
"@astrojs/sitemap": "^3.7.3",
|
||||
"@astrojs/svelte": "^9.0.1",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"astro": "^7.1.1",
|
||||
"sharp": "^0.35.3",
|
||||
"svelte": "^5.56.6",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"zod": "^4.4.3"
|
||||
"@astrojs/sitemap": "^3.7.5",
|
||||
"@astrojs/svelte": "^9.1.6",
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"astro": "^7.4.12",
|
||||
"jose": "^6.2.17",
|
||||
"marked": "^18.2.1",
|
||||
"sharp": "^0.35.5",
|
||||
"svelte": "^5.57.3",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"yaml": "^2.9.1",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.9",
|
||||
"@astrojs/check": "^0.9.12",
|
||||
"@axe-core/playwright": "^4.14.0",
|
||||
"@resvg/resvg-js": "^2.6.2",
|
||||
"@types/node": "^26.1.1",
|
||||
"eslint": "^10.7.0",
|
||||
"eslint-plugin-astro": "^3.0.1",
|
||||
"eslint-plugin-svelte": "^3.21.0",
|
||||
"@types/node": "^26.6.6",
|
||||
"@typescript/native": "npm:typescript@^7.0.2",
|
||||
"eslint": "^10.15.0",
|
||||
"eslint-plugin-astro": "^3.2.1",
|
||||
"eslint-plugin-svelte": "^3.24.1",
|
||||
"exifr": "^7.1.3",
|
||||
"gray-matter": "^4.0.3",
|
||||
"knip": "^6.27.0",
|
||||
"lefthook": "^2.1.10",
|
||||
"pagefind": "^1.5.2",
|
||||
"prettier": "^3.9.5",
|
||||
"knip": "^6.45.1",
|
||||
"lefthook": "^2.2.2",
|
||||
"pagefind": "^1.6.0",
|
||||
"playwright": "^1.65.1",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-astro": "^0.14.1",
|
||||
"prettier-plugin-svelte": "^4.1.1",
|
||||
"prettier-plugin-svelte": "^4.2.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
"satori": "^0.28.0",
|
||||
"satori": "^0.63.2",
|
||||
"satori-html": "^0.3.2",
|
||||
"typescript": "~6.0.3",
|
||||
"typescript-eslint": "^8.64.0",
|
||||
"wrangler": "^4.112.0"
|
||||
"typescript-eslint": "~8.73.0",
|
||||
"wrangler": "^4.164.0"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
# poli0981.dev — Documentation Suite
|
||||
|
||||
- Phiên bản suite: **v1.0** · Ngày: 2026-07-17
|
||||
- Repo: `poli0981/poli0981.dev` (private) · Domain: `poli0981.dev`
|
||||
- Phiên bản suite: **v2.0** · Ngày: 2026-10-24 (v1.0: 2026-07-17)
|
||||
- Repo: `poli0981/poli0981-dev` (**public** từ 10/2026) · nội dung: `poli0981/content` (submodule `src/content`) · Domain: `poli0981.dev`
|
||||
- Lịch sử thay đổi theo phiên bản: `CHANGELOG.md` ở gốc repo.
|
||||
- Ngôn ngữ tài liệu: tiếng Việt (thuật ngữ kỹ thuật giữ tiếng Anh). Riêng `12_LEGAL/` soạn song ngữ EN/VI vì là văn bản sẽ render trên site.
|
||||
- Tài liệu gốc: `poli0981.dev_proposal.md` (bản đề xuất v0.1, đã được duyệt).
|
||||
|
||||
@@ -28,14 +29,14 @@
|
||||
| 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`
|
||||
`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)
|
||||
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-11-10)
|
||||
|
||||
| # | Quyết định | Chọn |
|
||||
|---|---|---|
|
||||
| D1 | Framework/hosting | Astro 7 + Svelte 5 islands, Cloudflare Workers + Static Assets |
|
||||
| D2 | Quy trình viết | **Markdown + Git thuần** (không Keystatic). Capture mobile: GitHub web editor + `draft: true` |
|
||||
| D2 | Quy trình viết | Markdown + Git (repo `poli0981/content`). Từ 10/2026 thêm **admin tự viết** ở `admin.poli0981.dev` (soạn/sửa → commit repo content; **Xuất bản** → workflow `content-bump.yml` mở PR bump submodule + auto-merge). Không Keystatic/CMS bên thứ ba |
|
||||
| D3 | Q&A | FAQ tĩnh + liên hệ qua social/`contact@` — **không form, không D1** |
|
||||
| D4 | Ngôn ngữ | VI (mặc định, không prefix) + EN (`/en/`) |
|
||||
| D5 | Bình luận blog | Tắt (không Giscus) |
|
||||
@@ -43,11 +44,25 @@
|
||||
| D7 | Giấy phép | Code GPL-3.0 · Nội dung All Rights Reserved |
|
||||
| D8 | Error pages | Tự phục vụ từ app (không mua zone Pro) |
|
||||
| D9 | API ngoài | Không weather/map; widget YouTube + Steam + GitHub qua cron worker |
|
||||
| D10 | Data services | Chỉ **KV** (v1). Không D1, không R2 cho tới khi gallery > ~1 GB |
|
||||
| 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 | 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/` |
|
||||
| D16 | Palette & theme (10/2026) | **Glacier Teal** (xanh đêm + teal) thay palette ấm; theme mặc định **theo hệ điều hành**, nút 3 trạng thái hệ thống/sáng/tối (`03` §2, §6) |
|
||||
| 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" |
|
||||
| D21 | Chế độ bảo trì (11/2026, v2.3.0) | Không thêm tính năng mới. Chỉ nhận: deps định kỳ · vá bảo mật (High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (UI/UX, a11y) · sửa lỗi ngôn ngữ. Bot `triage.yml` gắn `enhancement` + `out-of-scope` và đóng đề xuất tính năng; ngoại lệ = nhãn `maintenance-exception` (`CONTRIBUTING.md`, `17` §0) |
|
||||
| D22 | Nhãn nội dung & tuổi (11/2026) | `contentWarning` từ danh sách cố định 11 nhãn (`src/lib/content-labels.ts`) cho blog/truyện/album/từng ảnh + `ageRating` 13+/16+/18+. Banner; ảnh mờ bằng CSS (`:has()`, chạy khi tắt JS); hỏi tuổi bằng `<dialog>` gốc, không tự bật, câu trả lời chỉ ở localStorage `ageGate` (mốc tuổi, không ngày sinh) — Privacy §6 (`04` §2) |
|
||||
| D23 | Xuất bản tự động (11/2026) | Mỗi lần lưu/xoá trong admin tự dispatch `content-bump.yml`; build ghi `__CONTENT_COMMIT__` ⇒ `/api/health` có `version.content`, admin phân biệt "đã merge" với "đã lên web". Điều kiện: Workers Builds deploy `main` (`07` §9) |
|
||||
| D24 | Chất lượng (11/2026) | Thêm **Qodana** (Ultimate, Qodana for JS, ngưỡng 0) cạnh SonarCloud. License: kiểm toàn bộ `package-lock.json`, ngoại lệ theo **gói** có lý do (`scripts/license-policy.mjs`) — license audit của Qodana cần Ultimate Plus nên không dùng (`08` §0) |
|
||||
|
||||
## Cách dùng suite
|
||||
|
||||
1. Đọc `15_ROADMAP.md` trước — bắt đầu bằng 4 P0 spikes.
|
||||
1. `15_ROADMAP.md` có trạng thái từng phase (P0–P3 đã xong, P4 launch đang chạy) và hướng đi tiếp.
|
||||
2. `07_CLOUDFLARE_SETUP.md` làm một lần khi mua domain, tick checklist cuối file.
|
||||
3. Mỗi file có mục **Trạng thái/Checklist** riêng khi áp dụng — suite này là nguồn sự thật, cập nhật khi quyết định thay đổi.
|
||||
4. Lưu ý chung: mọi phiên bản package trong suite đã verify tới 2026-07-17; khi scaffold thực tế, lấy bản patch mới nhất trong cùng major.
|
||||
4. Lưu ý chung: phiên bản package ghi trong suite là bản đang dùng tại 2026-10-24 (`02` §2); `package.json` + lockfile mới là nguồn sự thật.
|
||||
@@ -2,19 +2,19 @@
|
||||
|
||||
## 1. Sản phẩm
|
||||
|
||||
Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật ký + nơi viết truyện ngẫu hứng + hub cho kênh SkullMute**. Repo private, chi phí gần bằng 0, chạy trên hạ tầng Cloudflare đã có.
|
||||
Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật ký + nơi viết truyện ngẫu hứng + hub cho kênh SkullMute**. Repo public (từ 10/2026; nội dung ở repo riêng `poli0981/content`, All Rights Reserved), chi phí gần bằng 0, chạy trên hạ tầng Cloudflare đã có.
|
||||
|
||||
## 2. Mục tiêu
|
||||
|
||||
1. Một địa chỉ duy nhất đại diện cả hai "mặt": developer (GitHub poli0981) và creator (SkullMute).
|
||||
2. Viết được **thoải mái và bền**: blog/nhật ký/truyện bằng Markdown, xuất bản bằng `git push`, không phụ thuộc CMS bên thứ ba.
|
||||
2. Viết được **thoải mái và bền**: blog/nhật ký/truyện bằng Markdown, xuất bản bằng `git push` hoặc nút **Xuất bản** của admin tự viết — không phụ thuộc CMS bên thứ ba.
|
||||
3. Đẹp có chủ đích ("Phòng đọc lúc nửa đêm"), không giống template, mobile hoàn chỉnh.
|
||||
4. Vận hành ~US$12–13/năm phát sinh mới; không thêm dịch vụ trả phí nào khác.
|
||||
5. Bảo mật "vừa đủ": headers chuẩn, chống abuse form, chặn IP, không mở bề mặt admin nào ra internet.
|
||||
5. Bảo mật "vừa đủ": headers chuẩn, chống abuse form, chặn IP, cổng chống bot; bề mặt admin duy nhất là `admin.poli0981.dev` sau Cloudflare Access (Worker kiểm JWT lần nữa).
|
||||
|
||||
## 3. Non-goals (v1 KHÔNG làm)
|
||||
|
||||
- Không CMS/admin UI (Keystatic để ngỏ cho tương lai — xem ADR-04).
|
||||
- Không CMS bên thứ ba. Admin tự viết (10/2026) chỉ phục vụ chủ site — xem ADR-04 và `06` §9.
|
||||
- Không comment, không form Q&A, không tài khoản người dùng, không newsletter.
|
||||
- Không D1/database; không e-commerce/donate (có thể thêm link Ko-fi tĩnh sau).
|
||||
- Không tiếng Nhật ở v1 (kiến trúc i18n phải cho phép thêm `ja` sau mà không refactor).
|
||||
@@ -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.
|
||||
|
||||
@@ -2,109 +2,140 @@
|
||||
|
||||
## 1. Tổng quan
|
||||
|
||||
Site **prerender tĩnh gần như toàn bộ** bằng Astro, deploy lên **Cloudflare Workers + Static Assets**. Một Worker chính phục vụ site + vài API route; một Worker phụ (`widgets`) chạy cron lấy dữ liệu YouTube/Steam/GitHub vào KV.
|
||||
Site **prerender tĩnh gần như toàn bộ** bằng Astro, deploy lên **Cloudflare Workers + Static Assets**. Một Worker chính (`poli0981-dev`) phục vụ site, admin và vài API route; một Worker phụ (`poli0981-widgets`) chạy cron lấy dữ liệu YouTube/Steam/GitHub vào KV.
|
||||
|
||||
```
|
||||
Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto)
|
||||
Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Transform Rule x-verified-bot)
|
||||
│
|
||||
▼
|
||||
Worker "site" (Astro adapter)
|
||||
├── Static Assets (dist/) ── phần lớn request, FREE
|
||||
├── /api/report ── Turnstile + rate-limit(KV) → GitHub Issue + Discord
|
||||
└── middleware ── headers, denylist(KV) → 403, rate-limit → 429
|
||||
▲ đọc
|
||||
KV (widgets:*, denylist:*, rl:*)
|
||||
▼ ghi
|
||||
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / GitHub API
|
||||
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/) — 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)
|
||||
▲ đọc │ ghi
|
||||
KV (widgets:*, denylist, audit:*) ◄───┘
|
||||
▲ ghi
|
||||
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / GitHub API (+ mirror ảnh)
|
||||
```
|
||||
|
||||
## 2. Stack chốt (verify 2026-07-17)
|
||||
Mọi response đi ra đều qua `withSecurityHeaders` (`src/lib/security-headers.ts`) và mang log JSON có cấu trúc (`src/lib/log.ts`: `event`, `ray`, `path`… — xem `06` §10).
|
||||
|
||||
## 2. Stack (đang dùng tại 2026-10-24)
|
||||
|
||||
| Thành phần | Bản | Ghi chú |
|
||||
|---|---|---|
|
||||
| Node.js | 24 LTS (`.nvmrc` = `24`) | engines: `>=24` |
|
||||
| Astro | ^7.0.9 | CSP API + Fonts API built-in (stable từ v6) |
|
||||
| @astrojs/cloudflare | ^14 | target Workers |
|
||||
| @astrojs/mdx, sitemap, rss | mới nhất | |
|
||||
| Svelte + @astrojs/svelte | ^5 | islands |
|
||||
| Tailwind CSS | ^4.3 | CSS-first, `@theme` |
|
||||
| GSAP | ^3.13 | free toàn bộ plugin |
|
||||
| Node.js | 26 (`.nvmrc` = `26`, Workers Builds `NODE_VERSION=26`) | engines: `>=26` |
|
||||
| Astro | ^7.4 | CSP API + Fonts API built-in |
|
||||
| @astrojs/cloudflare | ^14.4 | target Workers; entry riêng `src/worker.ts` |
|
||||
| @astrojs/mdx, sitemap, rss | ^8 · ^3 · ^4 | item RSS dựng ở `src/lib/rss.ts` (truyện chỉ mô tả + link) |
|
||||
| Svelte + @astrojs/svelte | 5 + ^9.1 | islands |
|
||||
| Tailwind CSS | ^4 | CSS-first, `@theme` |
|
||||
| Pagefind | ^1 | chạy post-build |
|
||||
| @vite-pwa/astro | mới nhất | chỉ offline fallback |
|
||||
| Wrangler | ^4 | dev + deploy |
|
||||
| TypeScript | mới nhất, strict | |
|
||||
| Wrangler | ^4.152 | dev, types, smoke test, deploy tay |
|
||||
| TypeScript | **7.0** (`@typescript/native` → `tsc`) + **6.0** (`typescript`) | TS7 kiểm kiểu nhanh (`npm run typecheck`), TS6 cho astro check / typescript-eslint / svelte2tsx (TS 7.0 chưa có JS API). `target`/`lib` = ES2025, `erasableSyntaxOnly` |
|
||||
| Test | `node:test` của Node 26 | không thêm deps; `module.registerHooks` giả lập `astro:*`/`cloudflare:workers`; coverage lcov cho SonarCloud |
|
||||
| jose · marked · yaml · zod | ^6 · ^18 · ^2 · ^4 | Access JWT · preview admin · frontmatter · schema |
|
||||
|
||||
## 3. Cấu trúc repo
|
||||
|
||||
```
|
||||
poli0981.dev/
|
||||
├── docs/ # suite này
|
||||
├── public/ # favicon, robots.txt, security.txt, offline assets
|
||||
├── scripts/ # strip-exif.mjs, check-exif.mjs, gen-notices.mjs
|
||||
poli0981-dev/
|
||||
├── poli0981.dev-docs/ # suite này
|
||||
├── docs/templates/ # khung bài mới (npm run new:post)
|
||||
├── public/ # favicon, robots.txt, security.txt, sw.js, gate.js, skullhop.js
|
||||
├── scripts/ # gen-og, gen-notices, check-exif/strip-exif, check-csp-hashes,
|
||||
│ # check-install-scripts, smoke-worker, new-post
|
||||
├── src/
|
||||
│ ├── 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
|
||||
│ ├── content/ # collections (xem 04)
|
||||
│ ├── i18n/ # vi.ts, en.ts + helper t()
|
||||
│ ├── layouts/ # Base, Post, StoryReader, Legal
|
||||
│ ├── middleware.ts # headers, denylist, rate-limit
|
||||
│ ├── pages/ # routes + /en/* + api/report.ts + 404/500
|
||||
│ └── styles/ # global.css (@theme tokens)
|
||||
│ │ ├── pages/ # thân trang dùng chung vi/en (route chỉ là wrapper)
|
||||
│ │ └── admin/ # islands của admin
|
||||
│ ├── content/ # submodule poli0981/content (xem 04)
|
||||
│ ├── i18n/ # vi.ts, en.ts, routing.ts
|
||||
│ ├── layouts/ # Base, Post, StoryReader, Project, Error, Admin
|
||||
│ ├── 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…) · a11y/ (*.spec.ts: axe-core + bàn phím qua Playwright)
|
||||
├── workers/widgets/ # worker cron riêng (wrangler.jsonc riêng)
|
||||
├── .github/ # workflows caller, ISSUE_TEMPLATE, dependabot.yml
|
||||
├── astro.config.mjs · wrangler.jsonc · lefthook.yml · knip.json
|
||||
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md
|
||||
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, qodana.yml, triage.yml, dependabot.yml, ISSUE_TEMPLATE/ (config, bug_report, accessibility, language), pull_request_template.md
|
||||
├── astro.config.mjs · wrangler.jsonc · sonar-project.properties · qodana.yaml · lefthook.yml · knip.json
|
||||
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · ACCESSIBILITY.md · CONTRIBUTING.md · CHANGELOG.md
|
||||
```
|
||||
|
||||
## 4. Rendering & routing
|
||||
|
||||
- Mặc định **prerender: true** toàn site. Chỉ `src/pages/api/*` và middleware chạy on-demand trên Worker.
|
||||
- Mặc định **prerender** toàn site. Chạy on-demand trên Worker: `src/pages/api/*`, `src/pages/admin/*` và middleware.
|
||||
- **i18n** (Astro built-in): `defaultLocale: 'vi'`, `locales: ['vi','en']`, không prefix cho vi → `/blog/...` và `/en/blog/...`. UI string trong `src/i18n/`, nội dung theo `lang` frontmatter (xem 04 §4).
|
||||
- View Transitions bật toàn site; fallback bình thường cho trình duyệt cũ.
|
||||
- 404: `src/pages/404.astro` (+ bản `/en/404`); cấu hình assets `not_found_handling: "404-page"`.
|
||||
- **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` (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 (khung)
|
||||
## 5. Worker "site" — wrangler.jsonc (rút gọn)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"name": "poli0981-dev",
|
||||
"compatibility_date": "2026-07-01",
|
||||
"compatibility_date": "2026-10-15",
|
||||
"compatibility_flags": ["nodejs_compat"],
|
||||
// "main" + "assets" do `astro add cloudflare` sinh — giữ nguyên giá trị adapter tạo
|
||||
"assets": { "binding": "ASSETS", "directory": "./dist" },
|
||||
"kv_namespaces": [{ "binding": "KV", "id": "<id>" }],
|
||||
"observability": { "enabled": true },
|
||||
"routes": [{ "pattern": "poli0981.dev", "custom_domain": true }]
|
||||
"main": "./src/worker.ts",
|
||||
"workers_dev": false, "preview_urls": false,
|
||||
"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_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" },
|
||||
"version_metadata": { "binding": "CF_VERSION_METADATA" },
|
||||
"observability": { "enabled": true, "redact_query_string": true,
|
||||
"logs": { "enabled": true, "invocation_logs": true }, "traces": { "enabled": true, "head_sampling_rate": 0.1 } }
|
||||
}
|
||||
```
|
||||
|
||||
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit): `TURNSTILE_SECRET`, `GITHUB_ISSUES_TOKEN` (fine-grained PAT, chỉ Issues R/W repo này), `DISCORD_WEBHOOK_BUG`.
|
||||
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng đầy đủ ở `06` §4): `TURNSTILE_SECRET`, `GATE_SECRET`, `GITHUB_ISSUES_TOKEN`, `DISCORD_WEBHOOK_BUG`, `GITHUB_CONTENT_TOKEN`, `GITHUB_PUBLISH_TOKEN`, `ADMIN_EMAILS`.
|
||||
|
||||
`/api/health` trả `version` (id bản Worker đang chạy + commit đã build, từ `version_metadata` và `__BUILD_COMMIT__`) — dùng để xác minh deploy từ bên ngoài.
|
||||
|
||||
## 6. Worker "widgets" (workers/widgets/)
|
||||
|
||||
- Riêng biệt để không đụng entry Astro sinh ra; cron `"*/45 * * * *"`.
|
||||
- Bind cùng KV namespace (quyền ghi); secrets: `STEAM_API_KEY`, `STEAM_ID64`.
|
||||
- Chi tiết nguồn dữ liệu + schema KV: `11_WIDGETS_INTEGRATIONS.md`.
|
||||
- Riêng biệt để không đụng entry của site; cron `"*/45 * * * *"`; không có `package.json` (không deps).
|
||||
- Bind cùng KV namespace (quyền ghi); secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`.
|
||||
- Ngoài dữ liệu, worker **mirror ảnh thumbnail/icon vào KV** (`widgets:img:*`, ≤ 2 MB, 14 ngày) để site phục vụ qua `/ext-img/*` — khách không gọi Google/Steam trước khi bấm.
|
||||
- Deploy tay: `npx wrangler deploy --config workers/widgets/wrangler.jsonc`. Chi tiết: `11_WIDGETS_INTEGRATIONS.md`.
|
||||
|
||||
## 7. Setup dự án (một lần)
|
||||
## 7. Setup máy dev (một lần)
|
||||
|
||||
```bash
|
||||
nvm use 24
|
||||
npm create cloudflare@latest -- poli0981.dev --framework=astro
|
||||
cd poli0981.dev
|
||||
npx astro add svelte tailwind mdx sitemap cloudflare
|
||||
npm i -D pagefind knip lefthook eslint prettier prettier-plugin-astro \
|
||||
prettier-plugin-tailwindcss typescript-eslint eslint-plugin-astro eslint-plugin-svelte
|
||||
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
|
||||
cd poli0981-dev
|
||||
nvm use # đọc .nvmrc = 26
|
||||
npm ci --ignore-scripts && npm run check-install-scripts
|
||||
npx lefthook install
|
||||
npm run types && npm run types:widgets
|
||||
npm run dev # astro dev trên workerd (bindings local); admin dùng danh tính giả dev@localhost
|
||||
```
|
||||
|
||||
Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR description; mỗi gói mới phải qua `npm audit` + Dependabot theo dõi; cập nhật `THIRD-PARTY-NOTICES.md` bằng `scripts/gen-notices.mjs` trong CI.
|
||||
Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR description; mỗi gói mới phải qua `npm audit` + Dependabot theo dõi; `THIRD-PARTY-NOTICES.md` sinh bằng `scripts/gen-notices.mjs` và CI kiểm lệch.
|
||||
|
||||
## 8. Chính sách phiên bản & CVE
|
||||
|
||||
- Pin `^` trong cùng major; Dependabot mở PR patch/minor hằng tuần.
|
||||
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + preview.
|
||||
- Nền tảng CVE đã kiểm tra khi chốt stack: chuỗi CVE Astro 2026 (XSS `define:vars`, server-islands, slot-name, SSRF image) đều đã vá trước 7.0.9; các CVE thuộc adapter node/vercel không áp dụng (dùng adapter cloudflare). Quy trình theo dõi tiếp: `06_SECURITY.md` §6.
|
||||
- Pin `^` trong cùng major; Dependabot mở PR patch/minor hằng tuần (cooldown 3 ngày — `08` §6).
|
||||
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + preview (`17` §2).
|
||||
- **TypeScript 7**: `@typescript/native` là alias `npm:typescript@7` — Dependabot bỏ qua alias `npm:`, nên nâng tay; `typescript` (bản 6) giữ đến khi TS 7.1 có JS API cho astro check / typescript-eslint / svelte2tsx, lúc đó gộp về một bản.
|
||||
- Theo dõi CVE liên tục: Dependabot alerts, `npm audit` (CI), OSV-Scanner, Snyk, CodeQL, SonarCloud (`06` §6).
|
||||
|
||||
## 9. ADR (Architecture Decision Records — rút gọn)
|
||||
|
||||
@@ -113,7 +144,11 @@ Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR descriptio
|
||||
| 01 | Astro thay vì SvelteKit/Next | Content-first, ~0 JS mặc định, Content Collections type-safe, RSS/sitemap first-class | Site biến thành web-app nhiều tương tác |
|
||||
| 02 | Workers thay vì Pages | Hướng Cloudflare khuyến nghị cho dự án mới; assets request free; 1 nền tảng cho cả site + cron | — |
|
||||
| 03 | Svelte islands thay vì React | Nhẹ hơn, đã quen từ WXT/BookmarkMagic; tránh kéo React runtime vào site tĩnh | Cần lib chỉ có React |
|
||||
| 04 | Không Keystatic (v1) | Ít bề mặt tấn công + ít deps; capture mobile đã có đường khác | Sau 1–2 tháng thấy thật sự cần viết trọn bài từ điện thoại |
|
||||
| 05 | Không D1/Sentry | Q&A form bị bỏ; bug report đi thẳng GitHub+Discord | Xuất hiện nhu cầu dữ liệu động thật |
|
||||
| 06 | GPL-3.0 code / ARR content | Nhất quán hệ sinh thái repo; truyện & ảnh cần bảo hộ chặt | Mở public repo → cân nhắc thêm |
|
||||
| 04 | Admin tự viết thay vì Keystatic (10/2026) | Host riêng sau Access + kiểm JWT; token chỉ ghi repo content, xuất bản qua workflow có CI; ảnh qua Images binding → R2; ít deps (`jose`, `yaml`, `marked`) | Cần nhiều người biên tập / phân quyền |
|
||||
| 05 | Không D1/Sentry | Q&A form bị bỏ; bug report đi thẳng GitHub+Discord; lỗi runtime xem ở Workers Logs (log JSON) | Xuất hiện nhu cầu dữ liệu động thật |
|
||||
| 06 | GPL-3.0 code / ARR content | Nhất quán hệ sinh thái repo; truyện & ảnh cần bảo hộ chặt | — |
|
||||
| 07 | Error pages tự phục vụ | Custom Errors của Cloudflare cần zone plan trả phí; site chạy trên Worker nên tự làm được | Nếu một ngày mua Pro vì lý do khác |
|
||||
| 08 | Logic edge ở worker entry (`src/worker.ts`) | Trang tĩnh được adapter phục vụ trước middleware ⇒ cổng Turnstile, denylist, `/media`, chuyển host, security headers phải nằm ở entry + `assets.run_worker_first` | Adapter có hook chính thức cho trang tĩnh |
|
||||
| 09 | TypeScript 7 song song TypeScript 6 (10/2026) | `tsc` 7 nhanh hơn nhiều cho kiểm kiểu; công cụ hệ sinh thái chưa chạy được trên TS 7.0 (không có JS API) | TS 7.1 có API mới |
|
||||
| 10 | `node:test` + SonarCloud thay Vitest (10/2026) | Không thêm deps; Node 26 chạy thẳng TypeScript, `registerHooks` giả lập module ảo; lcov cho quality gate | Cần test component trong DOM thật |
|
||||
| 11 | Palette Glacier Teal + theme theo hệ điều hành (10/2026) | Tông lạnh theo yêu cầu chủ site; mọi cặp màu kiểm WCAG AA bằng test; một nguồn màu `src/lib/palette.ts` | Đổi nhận diện |
|
||||
@@ -1,36 +1,48 @@
|
||||
# 03 — Design System: "Phòng đọc lúc nửa đêm"
|
||||
# 03 — Design System: "Phòng đọc lúc nửa đêm" — Glacier Teal
|
||||
|
||||
## 1. Concept
|
||||
|
||||
SkullMute = âm thanh bị tắt có chủ đích. Site mang cảm giác **phòng đọc tối, ấm, chỉ có ngọn đèn bàn** — tĩnh lặng, không neon cyberpunk, không portfolio template. Boldness dồn vào **một** signature (Waveline §5); mọi thứ còn lại kỷ luật và yên tĩnh.
|
||||
SkullMute = âm thanh bị tắt có chủ đích. Site mang cảm giác **phòng đọc lúc nửa đêm** — tĩnh lặng, không neon cyberpunk, không portfolio template. Boldness dồn vào **một** signature (Waveline §5); mọi thứ còn lại kỷ luật và yên tĩnh.
|
||||
|
||||
## 2. Màu (token trong `@theme` của Tailwind v4)
|
||||
Từ 10/2026 (v2.0) palette chuyển từ "ngọn đèn bàn" ấm sang **Glacier Teal**: nền xanh đêm, chữ trắng lạnh, accent teal như ánh màn hình. Bản sáng là "băng ban ngày" — trắng xanh nhạt, accent teal đậm. Tinh thần giữ nguyên: một màu nhấn, phần còn lại im lặng.
|
||||
|
||||
### Dark — mặc định ("mực đêm")
|
||||
## 2. Màu — nguồn và quy tắc
|
||||
|
||||
Token runtime khai báo trong `src/styles/global.css` (khối `:root, [data-theme="dark"]` và `[data-theme="light"]`), sinh utility Tailwind qua `@theme inline`. **`src/lib/palette.ts` giữ cùng giá trị** cho code ngoài CSS (meta `theme-color`, ảnh OG, easter egg). `tests/palette.test.ts` fail khi hai nơi lệch nhau hoặc khi một cặp chữ/control dưới chuẩn: chữ (text, muted, accent, accent-strong, horror, ok, warn, err) ≥ 4.5:1 trên `bg`/`surface`/`elevated`; `line-strong` ≥ 3:1 (WCAG 1.4.11); `accent-contrast` trên `accent` ≥ 4.5:1.
|
||||
|
||||
### Dark — "glacier night" (mặc định khi không có JS)
|
||||
|
||||
| Token | Hex | Dùng cho |
|
||||
|---|---|---|
|
||||
| `--color-bg` | `#0D1117` | nền trang |
|
||||
| `--color-surface` | `#12161F` | card, header |
|
||||
| `--color-elevated` | `#1A2030` | modal, hover card |
|
||||
| `--color-line` | `#242B38` | border, divider |
|
||||
| `--color-text` | `#E9E4D8` | chữ chính (ngà ấm) |
|
||||
| `--color-muted` | `#98A0AE` | meta, caption |
|
||||
| `--color-accent` | `#E8A33D` | link, CTA, "ánh đèn bàn" |
|
||||
| `--color-accent-strong` | `#F4B860` | hover/focus của accent |
|
||||
| `--color-horror` | `#8C2F39` | tag horror, content-warning |
|
||||
| `--bg` | `#0B1220` | nền trang, `theme-color` |
|
||||
| `--surface` | `#0F192A` | card, header |
|
||||
| `--elevated` | `#16233A` | modal, menu, toast |
|
||||
| `--line` | `#223047` | border trang trí, divider |
|
||||
| `--line-strong` | `#5B6F8F` | viền control (input, nút) — ≥ 3:1 |
|
||||
| `--text` | `#E6EDF5` | chữ chính |
|
||||
| `--muted` | `#94A3B8` | meta, caption |
|
||||
| `--accent` | `#2DD4BF` | link, CTA, focus ring |
|
||||
| `--accent-strong` | `#5EEAD4` | hover/focus của accent |
|
||||
| `--accent-contrast` | `#042F2E` | chữ trên nền accent (selection, nút primary) |
|
||||
| `--horror` | `#FB7185` | tag horror, content-warning |
|
||||
| `--ok` / `--warn` / `--err` | `#34D399` / `#FBBF24` / `#F87171` | trạng thái |
|
||||
| `--overlay` · `--shadow-color` | `rgb(2 6 23 / .66)` · `rgb(0 0 0 / .45)` | backdrop modal · bóng elevated |
|
||||
|
||||
### Light — "trang giấy cũ" (ưu tiên cho reading mode)
|
||||
### Light — "glacier day"
|
||||
|
||||
| Token | Hex | Ghi chú |
|
||||
|---|---|---|
|
||||
| bg `#F5EFE2` · surface `#FFFDF7` · line `#E2D9C5` | | |
|
||||
| text `#26221A` · muted `#6E6757` | | |
|
||||
| accent `#9A6414` | accent phải **đậm hơn** bản dark để đạt AA trên nền sáng |
|
||||
| Token | Hex |
|
||||
|---|---|
|
||||
| bg `#F4F8FB` · surface `#FFFFFF` · elevated `#FFFFFF` · line `#D6E0EA` · line-strong `#7C8CA3` | |
|
||||
| text `#0F1B2D` · muted `#4A5A70` | |
|
||||
| accent `#0F766E` · accent-strong `#115E59` · accent-contrast `#FFFFFF` | accent đậm hơn bản dark để đạt AA trên nền sáng |
|
||||
| horror `#BE123C` · ok `#047857` · warn `#B45309` · err `#B91C1C` | |
|
||||
| overlay `rgb(15 27 45 / .42)` · shadow-color `rgb(15 27 45 / .14)` | |
|
||||
|
||||
Quy tắc contrast: text/bg ≥ 7:1, muted ≥ 4.5:1, accent-làm-chữ ≥ 4.5:1 — kiểm tra bằng tooling khi chốt hex cuối (giá trị trên là điểm xuất phát, được phép tinh chỉnh ±10% lightness, không đổi hue).
|
||||
### Palette riêng theo vùng
|
||||
|
||||
Semantic phụ: `--color-ok #4C9A6A`, `--color-warn #C9822B`, `--color-err #C24A4A` (dùng ít).
|
||||
- **Lớp đọc truyện** (`ReadingControls`): "Giấy" = palette sáng, "Tối" = palette tối (global.css áp cùng khối token cho `[data-reader-theme="paper|dark"]`), "Sepia" là palette ấm riêng trong `StoryReaderLayout.astro` (cũng được test AA).
|
||||
- **Lightbox** luôn dùng palette tối (`data-theme="dark"` trên chính nó) — ảnh xem tốt nhất trên nền tối.
|
||||
- **Ảnh OG** (`scripts/gen-og.mjs`) và favicon dùng palette tối.
|
||||
|
||||
## 3. Typography (đều có subset `vietnamese` — P0 Spike 2 phải test dấu trên máy thật)
|
||||
|
||||
@@ -60,13 +72,13 @@ Type scale (fluid, mobile 360px → desktop 1280px):
|
||||
## 4. Spacing / hình khối
|
||||
|
||||
- Space scale 4px: 1,2,3,4,6,8,12,16,24,32 (×4px). Section padding: `clamp(3rem, 8vw, 6rem)`.
|
||||
- Radius: 6 (control) / 10 (card) / 16 (modal). Border 1px `--color-line`; shadow chỉ ở elevated, tối và mềm (`0 8px 30px rgb(0 0 0 / .35)`).
|
||||
- Radius: 6 (control) / 10 (card) / 16 (modal). Border 1px `--line` (trang trí) hoặc `--line-strong` (control); shadow chỉ ở elevated: `--shadow-elevated` = `0 8px 30px var(--shadow-color)`.
|
||||
- Grain: overlay noise PNG 2–3% opacity toàn trang (một element `body::after`, `pointer-events:none`). Khu `/gaming` được phép thêm scanline 2% — nơi duy nhất.
|
||||
- Layout: container 72rem; trang chủ dùng lưới 12 cột với 1–2 phần tử cố ý lệch/đè (hero title đè lên Waveline) — bất đối xứng có kiểm soát, không "mọi thứ đều nghiêng".
|
||||
|
||||
## 5. Signature — Waveline (motif "sóng âm bị tắt")
|
||||
|
||||
- Một đường SVG ngang 1.5px màu `--color-line`, giữa có đoạn `--color-accent`.
|
||||
- Một đường SVG ngang 1.5px màu `--line`, giữa có đoạn `--accent`.
|
||||
- **Idle**: flatline. **Hover/scroll-into-view**: 1.2s "sống dậy" thành waveform 5–7 nhịp (path morph hoặc `stroke-dashoffset` + `d` keyframes bằng GSAP) rồi tắt về flatline — đúng một nhịp, không loop.
|
||||
- Xuất hiện tại: hero (dưới tagline), divider giữa section, footer. **Không** dùng trong card/list.
|
||||
- `prefers-reduced-motion`: luôn flatline tĩnh.
|
||||
@@ -83,18 +95,31 @@ Type scale (fluid, mobile 360px → desktop 1280px):
|
||||
|
||||
Nguyên tắc: **một** khoảnh khắc dàn dựng khi load trang chủ; còn lại là micro-interaction. GSAP chỉ nạp ở island nào cần (Waveline, hero) — không nạp global. Mọi animation phải có nhánh reduced-motion.
|
||||
|
||||
### Theme (sáng/tối/theo hệ thống)
|
||||
|
||||
- Lựa chọn lưu ở `localStorage.theme` (`light`/`dark`; không có = **theo hệ thống**). Bootstrap inline trong `<head>` (`src/lib/theme.ts`, được hash vào CSP) đặt `data-theme-pref` (lựa chọn) và `data-theme` (palette đang hiện) trước first paint, và nghe `prefers-color-scheme` để đổi theo hệ điều hành khi đang ở chế độ hệ thống.
|
||||
- `ThemeToggle` xoay vòng hệ thống → sáng → tối; icon chọn bằng CSS theo `data-theme-pref` nên đúng ngay trước khi island hydrate. Khi ghim sáng/tối, hai thẻ `meta[name=theme-color]` cùng trỏ màu nền đã chọn để thanh trình duyệt khớp trang.
|
||||
- Không có JS: trang hiện bản tối.
|
||||
|
||||
### Thanh cuộn
|
||||
|
||||
Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai báo trong từng palette (`global.css`), pha từ `--muted`/`--accent` với `--bg` bằng `color-mix(in oklab, …)`: thumb ≥ 3:1 so với nền (dark: muted 65%, light: muted 75%). `scrollbar-color` (kế thừa) cho mọi vùng cuộn; `scrollbar-width: thin` khi trình duyệt hỗ trợ `scrollbar-color`, còn Safari dùng nhánh `::-webkit-scrollbar`. Tuỳ chọn "Ẩn thanh cuộn" chỉ ẩn thanh của trang (vẫn cuộn bằng chuột/phím); vùng cuộn con giữ thanh mảnh.
|
||||
|
||||
## 7. Component inventory
|
||||
|
||||
| Component | Loại | Ghi chú |
|
||||
|---|---|---|
|
||||
| Header / MobileTabBar / Footer | .astro | TabBar: Home·Blog·Truyện·Menu, ẩn ≥768px |
|
||||
| ThemeToggle, LangSwitch | island nhỏ | localStorage `theme`, link hreflang cho lang |
|
||||
| PostCard / StoryCard / ProjectCard | .astro | StoryCard có badge status + CW |
|
||||
| Prose | style | typography cho nội dung md |
|
||||
| Header / MobileTabBar / Footer | .astro | TabBar: Home·Blog·Truyện·Menu, ẩn ≥768px; nav chính của header hiện từ 960px (dưới đó dùng nút menu — bản EN cần ~900px) |
|
||||
| ThemeToggle, LangSwitch | island nhỏ / .astro | ThemeToggle 3 trạng thái (§6); LangSwitch nhận href đã giải bản dịch từ BaseLayout |
|
||||
| ScrollbarToggle | island nhỏ (footer, chỉ hiện khi `pointer: fine`) | switch `role="switch"`; localStorage `scrollbar=hidden` → `html[data-scrollbar="hidden"]`, áp trước first paint cùng bootstrap theme |
|
||||
| PostCard / StoryCard / ProjectCard | .astro | StoryCard có badge status + nhãn đã dịch + mốc tuổi; PostCard/GalleryCard: bìa mờ khi có nhãn làm mờ |
|
||||
| Prose | .astro + `src/styles/prose.css` | typography cho nội dung md; cùng stylesheet dùng cho preview trong admin |
|
||||
| ReadingControls | island | cỡ chữ (3 mức, localStorage `reader`), theme giấy/sepia/tối, progress bar 2px |
|
||||
| ContentWarning | .astro | banner `--color-horror`, bấm để mở nội dung |
|
||||
| Lightbox | island | vuốt được, lazy |
|
||||
| SearchModal | island | Pagefind UI, mở bằng `/` hoặc nút |
|
||||
| ContentNotice | .astro | banner `--horror` nêu mọi nhãn (`src/lib/content-labels.ts`); nhãn làm mờ ⇒ ô "Hiện ảnh" (checkbox + CSS `:has()`, chạy khi tắt JS); vùng bài mang `data-cw-blur` |
|
||||
| AgeGate | .astro | nội dung có `ageRating` nằm trong `<details>`; có JS ⇒ `<dialog>` hỏi tuổi (Esc = huỷ), trả lời lưu localStorage `ageGate` (`src/lib/age-gate.ts`) |
|
||||
| Lightbox | island | vuốt được, lazy; thumbnail là link tới ảnh lớn (chạy được khi tắt JS) |
|
||||
| SearchModal | island | Pagefind, mở bằng `/` hoặc nút; ARIA combobox (`aria-activedescendant`), báo lỗi khi không tải được index |
|
||||
| MenuSheet | island | dialog modal, bẫy focus, trả focus về nút mở |
|
||||
| LegalGateSheet | island | spec ở `05` §6 |
|
||||
| Waveline | island | §5 |
|
||||
| WidgetLatestVideo / WidgetNowPlaying / WidgetGitHub | .astro | đọc KV lúc request?—không: đọc lúc **build** + island refresh nhẹ (xem 11 §5) |
|
||||
@@ -102,7 +127,15 @@ Nguyên tắc: **một** khoảnh khắc dàn dựng khi load trang chủ; còn
|
||||
|
||||
## 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, 1280px; dark/light; 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.
|
||||
@@ -25,6 +25,8 @@ const base = z.object({
|
||||
tags: z.array(z.string()).default([]),
|
||||
cover: image().optional(),
|
||||
draft: z.boolean().default(false),
|
||||
contentWarning: z.array(z.enum(LABEL_IDS)).default([]), // nhãn: src/lib/content-labels.ts
|
||||
ageRating: z.enum(["13+","16+","18+"]).optional(), // có ⇒ hỏi tuổi trước khi hiện
|
||||
});
|
||||
|
||||
blog: base // tags gợi ý: dev-log, diary, share, gaming
|
||||
@@ -32,7 +34,6 @@ stories: base.extend({
|
||||
series: z.string().optional(),
|
||||
chapter: z.number().int().positive().optional(),
|
||||
status: z.enum(['ongoing','complete','dropped']).default('ongoing'),
|
||||
contentWarning: z.array(z.string()).default([]), // vd: ['horror','blood']
|
||||
})
|
||||
projects: z.object({ name, tagline, lang, stack: z.array(z.string()),
|
||||
repo: z.string().url().optional(), url: z.string().url().optional(),
|
||||
@@ -46,6 +47,22 @@ gallery: z.object({ title, lang, date, description: z.string().optional(),
|
||||
|
||||
Alt text ảnh gallery: file `src/assets/gallery/<album>/captions.json` (`{"IMG_001.avif": {"vi":"...","en":"..."}}`) — build fail nếu thiếu key.
|
||||
|
||||
### Nhãn nội dung & giới hạn tuổi (v2.3.0)
|
||||
|
||||
- **Nhãn** (`contentWarning`, blog · truyện · album; danh sách cố định ở `src/lib/content-labels.ts`,
|
||||
tên vi/en ở `src/i18n` nhóm `labels`): `horror`, `blood`, `jumpscare`, `violence`, `self-harm`,
|
||||
`death` — **làm mờ ảnh** + banner; `politics`, `religion`, `strong-language`, `flashing-lights`,
|
||||
`spoilers` — chỉ banner. Nhãn lạ ⇒ build fail.
|
||||
- **Album**: nhãn và `ageRating` lấy từ **cả hai** file ngôn ngữ (cùng ảnh, hai trang) — gắn ở một
|
||||
bản là đủ; mốc tuổi chặt hơn được dùng (`albumWarning()` trong `src/lib/collections.ts`).
|
||||
- **Từng ảnh** có thể có nhãn riêng: `contentWarning` cạnh caption trong `gallery-photos/<album>.json`
|
||||
(admin → Gallery → "Nhãn") hoặc `captions.json` (`{"IMG_001.avif": {"vi":"…","en":"…","contentWarning":["blood"]}}`).
|
||||
- **Giới hạn tuổi** (`ageRating`: `13+` | `16+` | `18+`): phần nội dung thu gọn tới khi người đọc xác
|
||||
nhận tuổi; câu trả lời chỉ lưu localStorage `ageGate` (mốc tuổi, không ngày sinh) — xem chính sách
|
||||
quyền riêng tư §6. Tắt JS: bấm mở là tự xác nhận.
|
||||
- Làm mờ là lớp hiển thị, **không** phải kiểm soát truy cập (ảnh vẫn được tải). Thẻ danh sách, RSS và
|
||||
ảnh OG đều nêu nhãn; trích đoạn tìm kiếm không lấy banner và phần nội dung có giới hạn tuổi.
|
||||
|
||||
## 3. Frontmatter mẫu
|
||||
|
||||
```yaml
|
||||
@@ -71,6 +88,7 @@ series: "Đêm không tiếng"
|
||||
chapter: 1
|
||||
status: ongoing
|
||||
contentWarning: [horror]
|
||||
ageRating: "16+"
|
||||
tags: [horror, short-story]
|
||||
---
|
||||
```
|
||||
@@ -82,6 +100,14 @@ tags: [horror, short-story]
|
||||
- Không có bản dịch → trang index locale kia có mục "Chỉ có bằng tiếng Việt" (hiện tối đa 5 bài gần nhất, tuỳ chọn tắt).
|
||||
- Slug: kebab-case không dấu (`dem-khong-tieng`), ổn định vĩnh viễn — đổi title không đổi slug; nếu buộc đổi, thêm redirect trong middleware.
|
||||
|
||||
## 5a. Viết qua admin (`admin.poli0981.dev`)
|
||||
|
||||
- **Nội dung**: danh sách theo collection → *Tạo mới* (loại, slug, ngôn ngữ; truyện cần slug bộ) hoặc sửa bài có sẵn. Form theo đúng schema (`src/lib/admin/collections.ts`), thân bài Markdown + *Xem trước*, *Chèn ảnh* (chèn `<picture>` từ thư viện), *Ảnh bìa* (`coverMedia`). **Lưu** = commit thẳng vào `poli0981/content` (`main`), giữ nguyên định dạng frontmatter phần không sửa; sửa song song trên GitHub ⇒ báo xung đột (409) thay vì ghi đè.
|
||||
- **Ảnh**: kéo-thả nhiều ảnh → nén một lần (AVIF/WebP, bỏ EXIF) → R2; sửa alt, copy snippet, xoá khi không còn bài nào dùng.
|
||||
- **Gallery**: tạo album (vi/en + `gallery-photos/<album>.json` trong một commit), thêm/bớt/sắp xếp ảnh R2, chú thích vi/en bắt buộc.
|
||||
- **Xuất bản**: nút trên thanh admin ⇒ workflow `content-bump.yml` (xem `08` §0); site cập nhật sau khi CI xanh và Workers Builds deploy (~5–8 phút). Bài mới tạo mặc định `draft: true` — bỏ tick để hiện trên site.
|
||||
- Lưu ý: repo content **public** ⇒ bản nháp vẫn đọc được trên GitHub.
|
||||
|
||||
## 5. Quy trình viết (quyết định D2 — Markdown + Git thuần)
|
||||
|
||||
1. **Ở PC**: tạo file trong VS Code/Obsidian (vault trỏ thẳng `src/content/`), viết với `draft: true`, xem bằng `npm run dev`.
|
||||
@@ -95,14 +121,24 @@ Tiện ích khuyến nghị: snippet VS Code cho từng frontmatter; `npm run ne
|
||||
|
||||
- Ảnh nội dung đặt trong `src/assets/` để Astro Image tự sinh AVIF/WebP + srcset; **không** bỏ ảnh content vào `public/`.
|
||||
- **Chính sách EXIF**: mọi ảnh chụp (đặc biệt gallery kỷ niệm) phải qua `node scripts/strip-exif.mjs <folder>` (sharp: re-encode, bỏ toàn bộ metadata) **trước khi commit**.
|
||||
- Chốt chặn CI: `scripts/check-exif.mjs` quét ảnh thay đổi trong PR, thấy GPS/serial → **fail build**. (Repo đang private nhưng ảnh build ra là public — strip từ gốc.)
|
||||
- Chốt chặn CI: `scripts/check-exif.mjs` quét ảnh thay đổi trong PR, thấy GPS/serial → **fail build**. (Repo public và ảnh build ra cũng public — strip từ gốc; `check-exif` đọc bytes thật, file không đọc được cũng tính là lỗi.)
|
||||
- Kích thước: ảnh gốc ≤ 2560px cạnh dài, ≤ 1.5MB sau strip. Khi tổng `src/assets/gallery/` > ~1GB → kích hoạt phương án R2 (`17` §5).
|
||||
|
||||
### 6b. Ảnh R2 (upload qua admin)
|
||||
|
||||
Ảnh upload qua admin được biến đổi **một lần** (Images binding) rồi lưu R2 `poli0981-media`; site chỉ ghi URL:
|
||||
|
||||
- `id` = 16 hex đầu của SHA-256 ảnh gốc (upload trùng ⇒ cùng id, không xử lý lại). Biến thể cố định: AVIF 480/800/1200, WebP 800/1600, không phóng to quá chiều rộng gốc → `/media/v1/<id>/<avif|webp>-<w>`, `Cache-Control: public, max-age=31536000, immutable`. Đổi pipeline ⇒ tiền tố mới (`v2/`), không ghi đè.
|
||||
- Ảnh bìa: frontmatter `coverMedia: { id, w, h, alt? }` (blog/stories/projects) — thay cho `cover` (không dùng cả hai). Render bằng `src/components/MediaImage.astro` (`<picture>` AVIF + WebP, có width/height).
|
||||
- Ảnh trong bài: admin chèn sẵn snippet `<picture>` (HTML hợp lệ trong .md/.mdx).
|
||||
- Gallery: `gallery-photos/<album>.json` trong repo content = `{ "photos": [{ "id", "w", "h", "caption": { "vi", "en" } }] }`, gộp sau ảnh local của album (`src/lib/gallery.ts`); album chỉ có ảnh R2 cũng hợp lệ. Sai schema/thiếu chú thích ⇒ fail build.
|
||||
- EXIF: biến thể và master đều bỏ metadata khi biến đổi; R2 không giữ file gốc.
|
||||
|
||||
## 7. Checklist trước khi publish một bài
|
||||
|
||||
- [ ] frontmatter đủ + đúng schema (`astro check` pass)
|
||||
- [ ] slug không dấu, chưa từng dùng
|
||||
- [ ] ảnh đã strip EXIF, có alt/caption
|
||||
- [ ] truyện: contentWarning đặt đúng; chương đánh số liên tục
|
||||
- [ ] nhãn nội dung (`contentWarning`) và mốc tuổi (`ageRating`) đặt đúng; truyện: chương đánh số liên tục
|
||||
- [ ] đọc lại trên preview mobile (dev server, viewport 390px)
|
||||
- [ ] bài EN/VI có `translationKey` nếu là bản dịch
|
||||
@@ -8,13 +8,15 @@
|
||||
| `/about` | `/en/about` | md đơn |
|
||||
| `/projects`, `/projects/[slug]` | `/en/...` | collection projects |
|
||||
| `/blog`, `/blog/[slug]`, `/blog/tag/[tag]` | `/en/...` | blog |
|
||||
| `/truyen`, `/truyen/[series]/[slug]` | `/en/stories/...` | stories |
|
||||
| `/truyen`, `/truyen/[series]/[slug]`, `/truyen/[slug]` (truyện lẻ) | `/en/stories/...` | stories |
|
||||
| `/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}` | `/en/legal/...` | 12_LEGAL |
|
||||
| `/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)
|
||||
|
||||
@@ -38,7 +40,8 @@
|
||||
```
|
||||
[thanh mảnh: ← series | tiêu đề chương | Aa] ← Aa mở ReadingControls
|
||||
[progress bar 2px sticky top]
|
||||
[ContentWarning nếu có → bấm mới hiện nội dung]
|
||||
[ContentNotice nếu có nhãn → banner; nhãn làm mờ ⇒ ảnh mờ tới khi tick "Hiện ảnh"]
|
||||
[AgeGate nếu có ageRating → bấm summary ⇒ hỏi tuổi ⇒ mới hiện nội dung]
|
||||
Literata 68ch, 1.125–1.25rem
|
||||
[Chương trước ─ Mục lục series ─ Chương sau]
|
||||
```
|
||||
@@ -69,8 +72,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
|
||||
|
||||
@@ -2,74 +2,156 @@
|
||||
|
||||
Mức đe doạ thực tế của site cá nhân: bot spam form, scraper, script-kiddie quét lỗ hổng, thi thoảng một đợt flood. Thiết kế dưới đây "vừa đủ" cho mức đó — không zero-trust enterprise.
|
||||
|
||||
## 1. HTTP headers (middleware `src/middleware.ts`, áp cho mọi response HTML)
|
||||
## 1. HTTP headers (`src/lib/security-headers.ts`, gắn ở worker entry cho mọi response)
|
||||
|
||||
| Header | Giá trị |
|
||||
|---|---|
|
||||
| Content-Security-Policy | Dùng **CSP API built-in của Astro** (stable từ v6, bật trong `astro.config`) — tự hash script/style của build. Bổ sung directive thủ công: `img-src 'self' data: https://i.ytimg.com; frame-src https://www.youtube-nocookie.com; connect-src 'self'; script-src` thêm **`'wasm-unsafe-eval'`** (Pagefind chạy WebAssembly — thiếu là search chết, xem P0 Spike 4); `frame-ancestors 'none'`; `base-uri 'none'`; `form-action 'self'` |
|
||||
| Strict-Transport-Security | `max-age=31536000; includeSubDomains; preload` (TLD .dev vốn nằm trong HSTS preload — header để nhất quán) |
|
||||
| X-Content-Type-Options | `nosniff` |
|
||||
| Content-Security-Policy (meta) | **CSP API built-in của Astro** — tự hash mọi script/style của build (cả bootstrap theme inline, `src/lib/theme.ts`). Directive thêm: `img-src 'self' data:` (ảnh widget đi qua `/ext-img`, không còn host ngoài); `frame-src` YouTube nocookie + Turnstile; `connect-src 'self'` + Turnstile + Web Analytics; `script-src` thêm **`'wasm-unsafe-eval'`** (Pagefind); `base-uri 'none'`; `form-action 'self'`; `object-src 'none'`. `scripts/check-csp-hashes.mjs` (sau build) fail nếu một script inline thiếu hash hoặc không trang nào được kiểm |
|
||||
| Content-Security-Policy (header) | `frame-ancestors 'none'` — directive này không có hiệu lực trong meta nên đi bằng header; hai CSP cộng dồn, không ghi đè hash |
|
||||
| Strict-Transport-Security | `max-age=31536000; includeSubDomains; preload` |
|
||||
| X-Content-Type-Options · X-Frame-Options | `nosniff` · `DENY` |
|
||||
| Referrer-Policy | `strict-origin-when-cross-origin` |
|
||||
| Permissions-Policy | `camera=(), microphone=(), geolocation=(), payment=(), usb=()` |
|
||||
| Cross-Origin-Opener-Policy | `same-origin` |
|
||||
| Cross-Origin-Opener-Policy | `same-origin` (admin thêm `Cross-Origin-Resource-Policy: same-origin`) |
|
||||
|
||||
Không đặt COEP (không cần SharedArrayBuffer; đặt sẽ vỡ embed YouTube).
|
||||
|
||||
## 2. Middleware — denylist & rate limit (trả trang lỗi custom của mình)
|
||||
## 2. Denylist IP & rate limit
|
||||
|
||||
```
|
||||
request → IP = cf-connecting-ip
|
||||
1. KV get denylist:<ip-or-cidr-match> → có ⇒ 403 (trang 09 §2)
|
||||
2. nếu path bắt đầu /api/:
|
||||
KV rl:<ip> counter (cửa sổ 60s, giới hạn 5)
|
||||
vượt ⇒ 429 + Retry-After (trang 09 §2)
|
||||
3. tiếp tục; gắn headers §1 vào response
|
||||
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. 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
|
||||
còn lại → RL_API 120/60s · widgets → không giới hạn (cache edge 5 phút)
|
||||
vượt ⇒ 429 + Retry-After: 60 (trang 09 §2)
|
||||
```
|
||||
|
||||
- KV eventual-consistency → giới hạn có thể "mềm" vài request ở nhiều colo — chấp nhận được cho chống abuse; lớp cứng hơn là zone rate-limit rule (07 §6).
|
||||
- Quản lý denylist: `wrangler kv key put --binding=KV "denylist:1.2.3.0/24" "spam 2026-08"` — kèm ghi chú lý do. Chặn theo quốc gia/ASN thì dùng zone custom rule (07 §7) vì middleware chỉ nên giữ list ngắn.
|
||||
- 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**, 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)
|
||||
|
||||
Turnstile bắt buộc → verify `siteverify` với `TURNSTILE_SECRET` → validate payload bằng Zod (đúng schema `10` §3, size ≤ 32KB) → rate limit §2 → xử lý. Sai bất kỳ bước nào: 400/403/429, message chung chung, không lộ chi tiết.
|
||||
Rate limit §2 → body đọc có trần **32 KB** (khai `Content-Length` lớn hơn hoặc stream vượt ⇒ 413, không đọc hết) → validate Zod (`10` §3) → Turnstile `siteverify` (`success` + `action: "report"` + `hostname`) → issue ở repo **private** `poli0981/site-reports` + Discord (`allowed_mentions` rỗng, `@mention` trong nội dung bị vô hiệu) — mỗi lời gọi ra ngoài có timeout 10 s. Sai bất kỳ bước nào: 400/413/429, message chung chung, không lộ chi tiết.
|
||||
|
||||
Các API khác cũng có trần body: `/api/gate` 8 KB; JSON của admin 512 KB và bắt buộc `Content-Type: application/json`; upload ảnh 20 MB (từ chối theo `Content-Length` trước khi parse form).
|
||||
|
||||
## 3b. Cổng Turnstile trước mọi trang (`src/lib/gate/`, `src/worker.ts`)
|
||||
|
||||
Khách chưa có "vé" thì mọi trang HTML trả về **trang xác minh** thay cho nội dung; qua Turnstile → vé 48 giờ.
|
||||
|
||||
```
|
||||
GET trang → worker entry (assets.run_worker_first)
|
||||
cổng tắt (GATE_MODE ≠ on/force, hoặc thiếu GATE_SECRET / TURNSTILE_SECRET) → phục vụ bình thường
|
||||
không phải GET · host admin.* · /api/ · /admin · /media/ · /legal/ · /en/legal/ → bỏ qua cổng
|
||||
header x-verified-bot = "true" (Transform Rule, 07 §8b) → bỏ qua cổng
|
||||
thiếu header x-verified-bot (rule chưa có) → MỞ cổng + log lỗi (trừ GATE_MODE=force)
|
||||
cookie __Host-gate hợp lệ (HMAC, chưa hết hạn) → phục vụ bình thường
|
||||
/pagefind/* → 403 (index chứa toàn văn)
|
||||
trang thật 200 text/html → giữ nguyên <head>, thay <body> bằng giao diện xác minh,
|
||||
bỏ script src/modulepreload/JSON-LD; 200 + no-store + noindex
|
||||
còn lại (3xx/304/404/không phải HTML) → trả nguyên
|
||||
gate.js → Turnstile (action "gate") → POST /api/gate (RL_GATE, Sec-Fetch-Site same-origin)
|
||||
→ siteverify (success + action + hostname) → Set-Cookie __Host-gate=v1.<exp>.<nonce>.<sig>
|
||||
(Max-Age 172800, Secure, HttpOnly, SameSite=Lax, Path=/) → reload
|
||||
```
|
||||
|
||||
- Đứng ngoài cổng ngay ở tầng asset (không gọi Worker): `/_astro/*`, `/og/*`, favicon, `sw.js`, `skullhop.js`, `gate.js`, `/offline*`, robots, sitemap, RSS, `/.well-known/*` — xem `run_worker_first` trong `wrangler.jsonc`.
|
||||
- Giữ `<head>` thật ⇒ preview link (kể cả bot không "verified" như Zalo) vẫn đúng title/ảnh; trả **200** vì nhiều bot preview bỏ qua mã khác 2xx.
|
||||
- Vé chỉ chứa hạn + nonce + chữ ký (43 ký tự base64url), không định danh; đổi `GATE_SECRET` ⇒ mọi vé cũ mất hiệu lực ngay.
|
||||
- **Fail-closed**: cookie sai định dạng (vd. chữ ký base64 lệch độ dài) bị coi như không có vé; nếu chính bước quyết định/vẽ cổng ném lỗi ⇒ 503 + `Retry-After`, **không bao giờ** trả trang thật (lỗi bypass 10/2026 — có test hồi quy và bước smoke riêng).
|
||||
- **Kill switch**: đặt `GATE_MODE` về `"off"` trong `wrangler.jsonc` (deploy) — hoặc sửa biến trên dashboard để tắt tức thì (lần deploy sau sẽ ghi đè).
|
||||
- Test: `npm test` (cookie/chính sách) + `npm run smoke` (pha 2 ép cổng bằng secret test của Turnstile, chạy trọn luồng).
|
||||
|
||||
## 4. Secrets & quyền tối thiểu
|
||||
|
||||
| Secret | Nơi | Phạm vi |
|
||||
|---|---|---|
|
||||
| TURNSTILE_SECRET | worker site | — |
|
||||
| GITHUB_ISSUES_TOKEN | worker site | Fine-grained PAT: **chỉ repo này, chỉ Issues R/W**, hạn 1 năm, đặt lịch xoay ở `17` |
|
||||
| TURNSTILE_SECRET | worker site | form báo lỗi + cổng |
|
||||
| GATE_SECRET | worker site | ký vé cổng (≥ 32 byte ngẫu nhiên) |
|
||||
| GITHUB_ISSUES_TOKEN | worker site | Fine-grained PAT: **chỉ repo `poli0981/site-reports`, chỉ Issues R/W**, hạn ≤ 1 năm |
|
||||
| DISCORD_WEBHOOK_BUG | worker site | webhook 1 kênh riêng |
|
||||
| STEAM_API_KEY, STEAM_ID64 | worker widgets | key Steam mặc định |
|
||||
| CLOUDFLARE_API_TOKEN | GitHub Actions secret | scope Workers Scripts:Edit + account đúng (07 §10) |
|
||||
| GITHUB_CONTENT_TOKEN | worker site | Fine-grained PAT: **chỉ `poli0981/content`, Contents R/W** (admin lưu bài) |
|
||||
| GITHUB_PUBLISH_TOKEN | worker site | Fine-grained PAT: **chỉ `poli0981/poli0981-dev`, Actions R/W** (nút Xuất bản). Thiếu ⇒ admin dùng tạm token nội dung và cảnh báo "một token" |
|
||||
| ADMIN_EMAILS | worker site | email được vào admin, phân cách dấu phẩy — **bắt buộc**, thiếu là không ai vào được |
|
||||
| STEAM_API_KEY, STEAM_ID64, DISCORD_WEBHOOK_CI | worker widgets | key Steam mặc định; webhook cảnh báo cron |
|
||||
| GITHUB_TOKEN (tuỳ chọn) | worker widgets | fine-grained PAT **không quyền nào** (chỉ đọc dữ liệu public) — nâng hạn mức API events từ 60/giờ/IP (IP egress của Workers dùng chung, hay bị 403) |
|
||||
| SONAR_TOKEN | GitHub Actions secret | phân tích SonarCloud (`08` §0) |
|
||||
|
||||
Không secret nào trong repo/`wrangler.jsonc`; `.dev.vars` nằm trong `.gitignore`.
|
||||
Không secret nào trong repo/`wrangler.jsonc`; `.dev.vars` nằm trong `.gitignore`. Admin chỉ hiện **tên** secret đã/chưa đặt (`/admin/security/`), không bao giờ hiện giá trị.
|
||||
|
||||
`wrangler secret put` tạo một version mới dựa trên version **mới nhất** đã upload và deploy nó ngay: chỉ đặt secret khi version mới nhất là bản của `main` (không phải bản preview của một PR) — kiểm bằng `wrangler versions list` trước.
|
||||
|
||||
## 5. Nội dung nhúng bên thứ ba
|
||||
|
||||
- YouTube: **click-to-load facade** (thumb tĩnh từ i.ytimg.com) → bấm mới tạo iframe `youtube-nocookie.com`. Vừa nhanh vừa gọn Privacy Policy.
|
||||
- Không font/CDN/script bên ngoài nào khác — mọi asset self-host.
|
||||
- YouTube: **click-to-load facade** — thumbnail do worker widgets mirror vào KV và site phục vụ qua `/ext-img/yt/<id>` (icon Steam qua `/ext-img/steam/…`), nên trình duyệt khách **không gọi** `i.ytimg.com`/Steam trước khi bấm; bấm mới tạo iframe `youtube-nocookie.com`. `/ext-img` chỉ nhận đúng 2 mẫu đường dẫn, chỉ đọc KV (không bao giờ fetch theo yêu cầu của khách), trả kèm `CSP: sandbox`.
|
||||
- Ngoại lệ duy nhất cho script bên ngoài: beacon Cloudflare Web Analytics (`static.cloudflareinsights.com`, báo về `cloudflareinsights.com`) — `type=module`, không cookie, chỉ có trong bản build production của Workers Builds (`src/components/CfBeacon.astro`). Turnstile chỉ tải khi trang xác minh/form báo lỗi cần. Còn lại: không font/CDN/script ngoài — mọi asset self-host.
|
||||
|
||||
## 6. Supply chain (repo private — lưu ý riêng)
|
||||
## 6. Supply chain (repo public từ 10/2026)
|
||||
|
||||
- **CodeQL không free cho repo private** → thay bằng: Dependabot (alerts + security updates, free cả private) + bước CI `npm audit --omit=dev --audit-level=high` + `osv-scanner` (action chính thức) chạy weekly.
|
||||
- `npm ci` từ lockfile; script `preinstall` bị chặn bằng `.npmrc: ignore-scripts=true` cho CI, chỉ bật lại cho gói cần build (sharp) qua allowlist — cân bằng chống supply-chain-worm kiểu Shai-Hulud.
|
||||
- Mỗi PR của Dependabot: đọc changelog trước khi merge major; patch/minor auto-merge khi CI xanh (08 §6).
|
||||
- **Cài đặt**: `npm ci --ignore-scripts` từ lockfile ở CI; `scripts/check-install-scripts.mjs` liệt kê gói có install script và fail khi xuất hiện gói mới ngoài allowlist (esbuild/workerd/sharp chạy được nhờ optionalDependencies, không cần script).
|
||||
- **Quét**: Dependabot (alerts + security updates, **cooldown 3 ngày** — không đề xuất bản vừa phát hành, chặn kiểu Shai-Hulud) · `npm audit --omit=dev --audit-level=high` trong CI (fail = chặn merge) · OSV-Scanner (SARIF, hằng tuần + khi đổi lockfile) · **CodeQL** (free vì repo public) · **SonarCloud** (quality gate trên PR) · Snyk (GitHub app).
|
||||
- Mỗi PR Dependabot: đọc changelog trước khi merge major; patch/minor merge khi CI xanh (08 §6). Khi `main` dính advisory mới, mọi PR đỏ ở bước audit ⇒ vá gộp một PR rồi đóng các PR bị thay thế.
|
||||
|
||||
## 7. security.txt (`public/.well-known/security.txt`)
|
||||
|
||||
```
|
||||
Contact: mailto:security@poli0981.dev
|
||||
Contact: mailto:contact@poli0981.dev
|
||||
Expires: 2027-07-01T00:00:00Z
|
||||
Preferred-Languages: vi, en
|
||||
Canonical: https://poli0981.dev/.well-known/security.txt
|
||||
Policy: https://github.com/poli0981/poli0981-dev/blob/main/SECURITY.md
|
||||
```
|
||||
|
||||
## 8. Checklist hardening trước launch
|
||||
## 8. Checklist hardening
|
||||
|
||||
- [ ] securityheaders.com đạt A (chấp nhận trừ điểm COEP)
|
||||
- [ ] CSP không chặn: View Transitions, GSAP, Pagefind (wasm), ảnh ytimg, iframe nocookie
|
||||
- [ ] Gửi form report với Turnstile sai → 403; spam 6 req/phút → 429 trang custom
|
||||
- [ ] IP test trong denylist → 403 trang custom
|
||||
- [x] securityheaders.com đạt A (chấp nhận trừ điểm COEP)
|
||||
- [x] CSP không chặn: Pagefind (wasm), Turnstile, iframe nocookie, beacon; `check-csp-hashes` xanh trên mọi trang
|
||||
- [x] Cookie cổng sai định dạng ⇒ vẫn gặp cổng (test + smoke); cổng lỗi ⇒ 503, không lộ trang
|
||||
- [ ] Gửi form report với Turnstile sai → 400; spam 6 req/phút → 429 trang custom
|
||||
- [ ] IP test trong denylist (thêm từ `/admin/security/`, hạn 1 giờ) → 403 trang custom
|
||||
- [ ] `wrangler secret list` khớp đúng bảng §4, không thừa
|
||||
- [ ] Zone settings khớp `07` checklist
|
||||
|
||||
## 9. Admin (`admin.poli0981.dev`)
|
||||
|
||||
```
|
||||
admin.poli0981.dev ─▶ Cloudflare Access (policy email) ─▶ Worker
|
||||
src/lib/hosts.ts : host admin chỉ phục vụ /admin*, /api/admin*, /media/*; còn lại 301 về site;
|
||||
poli0981.dev/admin* ⇒ 301 sang host admin, /api/admin* ⇒ 404
|
||||
src/middleware.ts : mọi route /admin* & /api/admin* (so theo routePattern) phải có
|
||||
Cf-Access-Jwt-Assertion hợp lệ — jose + JWKS của team, aud = ACCESS_AUD,
|
||||
iss = ACCESS_TEAM_DOMAIN, RS256, chưa hết hạn, phát hành ≤ 24 giờ
|
||||
(maxTokenAge); email ∈ ADMIN_EMAILS (BẮT BUỘC — trống ⇒ từ chối tất cả)
|
||||
request ghi: Sec-Fetch-Site same-origin + Origin đúng (chống CSRF same-site),
|
||||
JSON phải có Content-Type application/json
|
||||
RL_ADMIN; Cache-Control no-store; X-Robots-Tag noindex; CORP same-origin
|
||||
```
|
||||
|
||||
- **Vì sao host riêng**: cùng origin thì một lỗi XSS ở trang công khai có thể gọi API admin bằng cookie Access. Khác origin + kiểm `Sec-Fetch-Site` ⇒ không.
|
||||
- **Ba lớp**: Access chặn ở edge; Worker tự kiểm JWT (preview URL/workers.dev đều tắt, header giả ⇒ 403 — smoke test kiểm cả JWT giả); `ADMIN_EMAILS` quyết định ai được thao tác — policy Access lỡ mở rộng cũng không mở admin.
|
||||
- **Khuyến nghị cấu hình Access** (dashboard, `07` §13b): bắt buộc MFA ở IdP/Access, session duration ≤ 24 giờ (khớp `maxTokenAge`), bật *binding cookie*, cookie `SameSite=Lax` trở lên.
|
||||
- **Hai token GitHub** (fine-grained — quyền của một token áp cho *mọi* repo nó được chọn, nên không thể "ghi repo này, chỉ dispatch repo kia" bằng một token): `GITHUB_CONTENT_TOKEN` (chỉ `poli0981/content`, Contents R/W) và `GITHUB_PUBLISH_TOKEN` (chỉ `poli0981/poli0981-dev`, Actions R/W — không có Contents ⇒ lộ cũng không đẩy được code). Đọc trạng thái (PR, check, gitlink) không cần quyền vì hai repo đều public. Thiếu quyền ⇒ admin báo rõ token nào cần quyền gì (header `X-Accepted-GitHub-Permissions`). Xuất bản đi qua `content-bump.yml` (GITHUB_TOKEN) + CI `build` bắt buộc; diff có file ngoài `.md/.json` (vd. `.mdx` — chạy code lúc build) ⇒ không auto-merge.
|
||||
- **Audit log**: mỗi thao tác (lưu/xoá nội dung, upload/sửa alt/xoá ảnh, lưu/xoá album, xuất bản, chặn/bỏ chặn IP) ghi một khoá KV `audit:*` (90 ngày) kèm email, đích và commit — xem ở `/admin/activity/` cạnh lịch sử commit của repo content.
|
||||
- **Upload ảnh**: kiểm magic bytes (không SVG), ≤ 20 MB, id = SHA-256 ⇒ trùng thì không biến đổi lại; biến thể + master tái mã hoá (mất EXIF/GPS), không giữ file gốc; `/media` chỉ phục vụ key biến thể, `CSP: sandbox`. Không xoá được ảnh còn được nội dung dùng.
|
||||
- **Preview Markdown** render trong `<iframe sandbox="allow-same-origin" srcdoc>`: không `allow-scripts` nên không gì trong Markdown chạy được (kể cả `onerror`), không điều hướng được trang admin; frame kế thừa CSP của trang. Không cần thư viện sanitize.
|
||||
- **Phiên hết hạn**: client gọi API với `redirect: "manual"` — Access trả redirect về trang đăng nhập hoặc middleware trả 403 ⇒ hiện banner "Đăng nhập lại"; bản nháp đang viết được tự lưu cục bộ (`localStorage`) và hỏi khôi phục.
|
||||
- Dev (`astro dev`) dùng danh tính giả `dev@localhost` — chỉ khi `import.meta.env.DEV` (luôn false trong bản build).
|
||||
|
||||
## 10. Log & giới hạn vận hành
|
||||
|
||||
- **Log có cấu trúc** (`src/lib/log.ts`): một dòng JSON mỗi sự kiện — `level`, `event` (vd. `gate.failed`, `denylist.blocked`, `admin.access_denied`, `admin.content_saved`, `ratelimit.exceeded`, `report.github_failed`, `widgets.source_failed`), `ray`, `method`, `path`, lỗi đã serialize. Workers Logs (`observability.logs`, giữ 7 ngày, query string bị che) tự index các field; traces lấy mẫu 10%. Không log IP vào issue/Discord.
|
||||
- **Phiên bản đang chạy**: binding `version_metadata` + commit build (`__BUILD_COMMIT__`) ⇒ `/api/health`, dashboard admin và log lỗi edge đều nói đúng bản nào đang phục vụ.
|
||||
- **Trang 500** hiện Cloudflare Ray ID (worker đóng dấu vào `#ref`) — trùng field `ray` trong log, người dùng đọc/gửi kèm báo lỗi là tra được ngay.
|
||||
- **Timeout**: mọi `fetch` ra GitHub/Discord/YouTube/Steam có `AbortSignal.timeout` (10–15 s) — một API treo không giữ request hay isolate.
|
||||
@@ -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
|
||||
|
||||
@@ -54,39 +63,96 @@ Ghi chú: các rule này khi khớp sẽ hiện trang chặn mặc định của
|
||||
|
||||
Account Home → **Turnstile → Add widget**: domain `poli0981.dev`, mode **Managed**, loại Invisible/Non-interactive tuỳ test. Lưu **Site Key** vào code (public), **Secret Key** → `wrangler secret put TURNSTILE_SECRET`.
|
||||
|
||||
Cổng xác minh (06 §3b) **dùng lại widget này** với `action: "gate"` (form báo lỗi dùng `action: "report"`; server kiểm tra action + hostname nên token không dùng chéo được). Secret ký vé: `GATE_SECRET` (chuỗi ngẫu nhiên ≥ 32 byte, không ai cần biết) — `openssl rand -base64 48 | npx wrangler secret put GATE_SECRET`.
|
||||
|
||||
## 8b. Transform Rule — đánh dấu bot hợp lệ cho cổng
|
||||
|
||||
Rules → **Transform Rules → Modify Request Header** → Create:
|
||||
- Tên: `verified-bot-flag` · When: *Custom filter* `(http.host eq "poli0981.dev")`
|
||||
- Then: **Set dynamic** · Header `x-verified-bot` · Value `to_string(cf.client.bot)`
|
||||
|
||||
Rule ghi đè header cho **mọi** request (client không giả được). Worker thấy `"true"` ⇒ bot đã được Cloudflare xác thực (Googlebot, Bingbot, bot preview Facebook/Discord/X…) ⇒ đi thẳng. Không thấy header ⇒ coi như rule chưa có ⇒ cổng tự mở (fail-open) và log lỗi — tránh khoá công cụ tìm kiếm. Giữ **Block AI bots** bật (§5): bot AI "verified" cũng có `cf.client.bot`, nên chúng phải bị chặn từ WAF chứ không trông vào cổng.
|
||||
|
||||
## 9. Deploy Worker & custom domain
|
||||
|
||||
- Local: `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
|
||||
- Gắn domain: Workers & Pages → worker `poli0981-dev` → Settings → **Domains & Routes → Add → Custom domain** → `poli0981.dev` (tự tạo DNS + cert). Thêm route redirect `www` nếu muốn: tạo thêm custom domain `www.poli0981.dev` và redirect 301 trong middleware về apex.
|
||||
- Worker widgets: `cd workers/widgets && npx wrangler deploy` → kiểm tra Triggers có cron.
|
||||
- **Workers Builds** (dashboard → worker `poli0981-dev` → Settings → Build), nối repo `poli0981/poli0981-dev`:
|
||||
|
||||
| Mục | Giá trị |
|
||||
|---|---|
|
||||
| Production branch | `main` |
|
||||
| Build command | `npm run build` |
|
||||
| **Deploy command** (production) | `npx wrangler deploy` |
|
||||
| **Non-production branch deploy command** | `npx wrangler versions upload` — chỉ upload version + alias preview, **không** nhận traffic |
|
||||
| Build variables | `NODE_VERSION=26`, `PUBLIC_TURNSTILE_SITE_KEY=<site key>` |
|
||||
| Build cache | bật |
|
||||
|
||||
Bẫy đã gặp (19/10/2026): Deploy command của nhánh PR từng là `wrangler deploy` ⇒ mỗi PR (cả Dependabot) được đưa lên production 100%. Ngược lại, nếu Deploy command của `main` là `versions upload` thì merge **không** deploy — khi đó promote tay: `npx wrangler versions list` → `npx wrangler versions deploy <id>@100% --yes --message "main <sha>"`. Xác minh sau mỗi merge: `curl https://poli0981.dev/api/health` phải trả đúng `version.commit` (và `version.content` = commit repo nội dung đã publish). Từ v2.3.0 admin tự xuất bản sau mỗi lần lưu ⇒ Deploy command của `main` **phải** là `npx wrangler deploy`, nếu không mọi lần lưu dừng ở pha "đã merge — đang deploy" (đã xảy ra từ 10/2026 tới 11/2026: mọi deploy trong thời gian đó là promote tay). **Đã sửa ngày 21/11/2026** (Deploy command = `npx wrangler deploy`, Version command = `npx wrangler versions upload`); deployment do Workers Builds tạo hiện trong `npx wrangler deployments list` ngay sau khi build `main` xong, không cần promote.
|
||||
- Local (khẩn cấp): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
|
||||
- Gắn domain: Workers & Pages → worker `poli0981-dev` → Settings → **Domains & Routes → Add → Custom domain** → `poli0981.dev` (tự tạo DNS + cert). `www.poli0981.dev` là custom domain thứ hai; worker entry redirect 301 về apex.
|
||||
- Worker widgets (không nối Workers Builds): `npx wrangler deploy --config workers/widgets/wrangler.jsonc` → kiểm tra Triggers có cron.
|
||||
|
||||
## 10. API token cho CI (least privilege)
|
||||
|
||||
My Profile → API Tokens → Create Token → Custom:
|
||||
- Permissions: **Account → Workers Scripts → Edit** (+ Account → Workers KV Storage → Edit nếu CI cần seed KV).
|
||||
- Account Resources: đúng account của bạn. TTL: 1 năm.
|
||||
→ Lưu vào GitHub repo secret `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` (bootstrap bằng script ở `08` §4).
|
||||
Workers Builds tự có quyền deploy nên GitHub Actions **không** cần token Cloudflare. Chỉ tạo khi muốn deploy từ máy khác/CI riêng: My Profile → API Tokens → Create Token → Custom → **Account → Workers Scripts → Edit** (+ Workers KV Storage → Edit nếu cần seed KV), đúng account, TTL ≤ 1 năm.
|
||||
|
||||
## 11. Email Routing
|
||||
## 11. Email (Google Workspace)
|
||||
|
||||
Zone → Email → Email Routing → Enable:
|
||||
- Custom address: `contact@poli0981.dev` → forward tới hộp thư thật (xác minh mail đích).
|
||||
- Thêm `business@` nếu muốn tách mail sponsor. Catch-all: **Drop**.
|
||||
- DNS MX/SPF do wizard tự thêm — đồng ý. (Chỉ nhận; khi nào cần *gửi* từ domain sẽ tính sau — chưa nằm trong scope.)
|
||||
Mail của domain chạy trên **Google Workspace** (MX → `aspmx.l.google.com`, SPF `include:_spf.google.com`, DKIM `google._domainkey`, DMARC `p=none`) — **không** dùng Cloudflare Email Routing (hai bên không thể cùng giữ MX). Một hộp thư, các địa chỉ dưới đây là *alias* (Admin console → Users → Alternate email addresses):
|
||||
|
||||
| Địa chỉ | Dùng cho | Xuất hiện ở |
|
||||
|---|---|---|
|
||||
| `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 |
|
||||
| `code@` · `games@` | Mã nguồn · key game/playtest | /dev, /gaming, /links |
|
||||
|
||||
Địa chỉ công khai trên site lấy từ `src/lib/links.ts` (`CONTACT_EMAILS`); địa chỉ pháp lý nằm trực tiếp trong `content/legal/*.md`. Đổi/bỏ alias → sửa cả hai chỗ + `security.txt` (xem 17 §runbook).
|
||||
|
||||
## 12. Web Analytics
|
||||
|
||||
Account → Analytics & Logs → **Web Analytics → Add site** → chọn zone (tự động qua proxy, không cần gắn script — chọn chế độ automatic). Không cookie, khớp Privacy Policy.
|
||||
Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở chế độ **JS snippet (manual)** — *tắt* tự động chèn, nếu không mỗi trang sẽ có 2 beacon (và beacon tự chèn là script inline mà CSP chặn).
|
||||
|
||||
- Snippet nằm ở `src/components/CfBeacon.astro` (token là site tag công khai, không phải secret), chèn vào `<head>` của `BaseLayout` + `ErrorLayout`.
|
||||
- Chỉ render khi build trên Workers Builds nhánh `main` (`WORKERS_CI=1` + `WORKERS_CI_BRANCH=main` → `PUBLIC_CF_BEACON`), nên CI/Lighthouse/preview không làm bẩn số liệu. Ép bật/tắt: biến build `PUBLIC_CF_BEACON=true|false`.
|
||||
- CSP: `script-src https://static.cloudflareinsights.com`, `connect-src https://cloudflareinsights.com`.
|
||||
- Không cookie, khớp Privacy Policy §2.
|
||||
|
||||
## 13b. Admin — `admin.poli0981.dev`
|
||||
|
||||
1. Workers → `poli0981-dev` → Domains & Routes → **Custom domain** `admin.poli0981.dev` (cùng Worker).
|
||||
2. Zero Trust → Access → Applications → **Self-hosted**, domain `admin.poli0981.dev` (cả host), policy Allow theo email chủ site (IdP Google hoặc One-time PIN). Lấy **team domain** + **AUD tag** → `vars.ACCESS_TEAM_DOMAIN` / `vars.ACCESS_AUD` trong `wrangler.jsonc` (không phải secret).
|
||||
3. Hai GitHub **fine-grained** PAT (hạn ≤ 1 năm; Settings → Developer settings → Fine-grained tokens):
|
||||
- *Content*: Repository access = **Only select repositories → `poli0981/content`**; Repository permissions → **Contents: Read and write** → `npx wrangler secret put GITHUB_CONTENT_TOKEN`.
|
||||
- *Publish*: Repository access = **Only select repositories → `poli0981/poli0981-dev`**; Repository permissions → **Actions: Read and write** → `npx wrangler secret put GITHUB_PUBLISH_TOKEN`.
|
||||
- Sửa quyền của token có sẵn không đổi giá trị token ⇒ không cần đặt lại secret.
|
||||
- **`ADMIN_EMAILS` (bắt buộc)** = email được vào admin, phân cách dấu phẩy: `printf '%s' "you@example.com" | npx wrangler secret put ADMIN_EMAILS`. Thiếu secret này admin từ chối mọi người (fail-closed). Đặt khi version mới nhất là bản `main` (`06` §4).
|
||||
- Báo lỗi: thêm repo private `poli0981/site-reports` vào `GITHUB_ISSUES_TOKEN` (Issues: Read and write).
|
||||
3b. Siết Access (application `admin.poli0981.dev` → Settings): **Session duration ≤ 24h** (Worker cũng từ chối token > 24 giờ), policy yêu cầu **MFA** (IdP có 2FA hoặc rule Access), bật **Binding cookie**, cookie `SameSite=Lax` hoặc `Strict`, `HttpOnly`.
|
||||
4. Repo `poli0981-dev` → Settings → Actions → General → bật **Allow GitHub Actions to create and approve pull requests** (cho `content-bump.yml`); quyền mặc định của GITHUB_TOKEN giữ **read**.
|
||||
5. R2 `poli0981-media` (`wrangler r2 bucket create poli0981-media --location apac`), không bật public URL. Images binding không cần bật gì thêm (gói Free: 5.000 biến đổi/tháng).
|
||||
|
||||
## 14. Observability
|
||||
|
||||
`wrangler.jsonc` → `observability`: logs bật (invocation logs, lấy mẫu 100%, query string bị che), traces lấy mẫu 10%. Xem ở Workers → `poli0981-dev` → **Logs** (giữ 7 ngày): lọc theo field `event` (log JSON của `src/lib/log.ts`, `06` §10) hoặc `ray` (mã trên trang 500). Binding `version_metadata` cho biết version đang chạy; `/api/health` trả cả commit.
|
||||
|
||||
## 13. Checklist nghiệm thu
|
||||
|
||||
- [ ] `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)
|
||||
- [ ] `contact@poli0981.dev` nhận mail test
|
||||
- [ ] `contact@` và `security@poli0981.dev` nhận mail test
|
||||
- [ ] Web Analytics bắt đầu có số liệu sau ~24h
|
||||
- [ ] Trình duyệt ẩn danh vào `/` → thấy bước xác minh rồi vào trang; `curl -s https://poli0981.dev/ | grep data-human-check` có kết quả; RSS/sitemap/trang pháp lý không bị chặn
|
||||
- [ ] Search Console (URL Inspection → Test live URL) thấy trang thật; Facebook Sharing Debugger đúng title/ảnh
|
||||
- [ ] `https://admin.poli0981.dev/` → đăng nhập Access → thấy admin; `curl -H 'cf-access-jwt-assertion: x' …/api/admin/content` (qua host chính) → 404/403
|
||||
- [ ] `ADMIN_EMAILS` đã đặt; Access session ≤ 24h + MFA + binding cookie
|
||||
- [ ] Workers Builds: Deploy command `main` = `npx wrangler deploy`, nhánh khác = `npx wrangler versions upload`; sau merge `/api/health` trả đúng commit
|
||||
- [ ] Auto-renew ON + transfer lock ON + 2FA ON
|
||||
@@ -1,5 +1,18 @@
|
||||
# 08 — CI/CD
|
||||
|
||||
## 0. Thực tế đang chạy (10/2026, v2.0) — §1–§5 bên dưới là kế hoạch ban đầu (lịch sử)
|
||||
|
||||
- **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) → **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`** (từ v2.3.0 admin tự gọi sau **mỗi lần lưu/xoá**; nút **Xuất bản** còn lại để chạy lại; `concurrency` gộp các lần gọi dồn dập): 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.
|
||||
- **`qodana.yml`** (từ v2.3.0, PR + push `main` + tay): Qodana for JS (gói Ultimate, token `QODANA_TOKEN`), native mode trên Node 26 của runner sau `npm ci` + sinh types, profile `qodana.recommended` quét cả repo, `failThreshold: 0` (`qodana.yaml` ghi các inspection tắt kèm lý do); kết quả lên Qodana Cloud và — với `main` — SARIF vào Code scanning. Bỏ qua PR Dependabot/fork (không có secret) nên chỉ là check tư vấn. Không phân tích `.astro`/`.svelte`.
|
||||
- **Kiểm license**: `gen-notices --check` (dependency trực tiếp, bảng trong `THIRD-PARTY-NOTICES.md`) + `check-licenses` (toàn bộ lockfile, ngoại lệ theo gói) trong job `build` — chính sách ở `scripts/license-policy.mjs` (`12_LEGAL/THIRD_PARTY_NOTICES.md`). Qodana license audit cần Ultimate Plus nên không dùng.
|
||||
- **`triage.yml`** (issues + `pull_request_target`; **không checkout gì** — đọc `scripts/triage.mjs` của nhánh mặc định qua API rồi import từ bộ nhớ, nên không bao giờ chạy code của PR; Sonar S7631 bắt mọi checkout trong `pull_request_target`): đề xuất tính năng ⇒ nhãn `enhancement` + `out-of-scope`, bình luận song ngữ, đóng. Chạy khô bằng `workflow_dispatch`.
|
||||
- **Bẫy đã gặp**: khi `main` dính advisory, *mọi* PR (cả Dependabot) đỏ vì bước audit ⇒ vá gộp trong một PR rồi đóng các PR Dependabot bị thay thế. `gen-notices --check` từng đếm số gói transitive ⇒ PR bump nào cũng đỏ; nay chỉ kiểm chính sách license.
|
||||
|
||||
## 1. Nguyên tắc
|
||||
|
||||
- Tái dùng hạ tầng `poli0981/.github`: thêm reusable workflow **`web-astro-ci.yml`** + **`web-astro-deploy.yml`**, repo này chỉ chứa caller stub — đúng mô hình 15 repo hiện tại.
|
||||
@@ -69,19 +82,25 @@ updates:
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule: { interval: weekly, day: monday }
|
||||
groups:
|
||||
astro: { patterns: ["astro", "@astrojs/*"] }
|
||||
dev-tools:{ dependency-type: development }
|
||||
cooldown: { default-days: 3 } # không đề xuất bản phát hành < 3 ngày tuổi
|
||||
open-pull-requests-limit: 8
|
||||
- package-ecosystem: npm
|
||||
directory: "/workers/widgets"
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
astro: { patterns: ["astro", "@astrojs/*"] }
|
||||
typescript: { patterns: ["typescript", "typescript-eslint"] }
|
||||
dev-tools: { dependency-type: development }
|
||||
ignore:
|
||||
- dependency-name: typescript # giữ TS 6 cho tooling (02 §8)
|
||||
update-types: ["version-update:semver-major"]
|
||||
- dependency-name: prettier-plugin-astro # 1.x đổi khoảng trắng hiển thị — cần PR riêng
|
||||
update-types: ["version-update:semver-major"]
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule: { interval: weekly }
|
||||
```
|
||||
|
||||
Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. Security alerts: xử lý ≤ 48h (lịch ở `17`).
|
||||
- `workers/widgets` không có `package.json` (không deps) nên không có mục riêng.
|
||||
- `@typescript/native` (alias `npm:typescript@7`) **không** được Dependabot theo dõi — nâng tay (`17` §1).
|
||||
- Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. Security alerts: xử lý ≤ 48h (lịch ở `17`). PR bị một PR gộp thay thế ⇒ đóng kèm comment.
|
||||
|
||||
## 7. Git hooks (`lefthook.yml`)
|
||||
|
||||
@@ -89,15 +108,20 @@ Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc
|
||||
pre-commit:
|
||||
parallel: true
|
||||
commands:
|
||||
format: { glob: "*.{astro,svelte,ts,md,css,json}", run: npx prettier --write {staged_files}, stage_fixed: true }
|
||||
lint: { glob: "*.{astro,svelte,ts}", run: npx eslint {staged_files} }
|
||||
format: { glob: "*.{astro,svelte,ts,js,mjs,md,css,json,jsonc,yml,yaml}", run: npx prettier --write {staged_files}, stage_fixed: true }
|
||||
lint: { glob: "*.{astro,svelte,ts,js,mjs}", run: npx eslint {staged_files} }
|
||||
pre-push:
|
||||
commands:
|
||||
typecheck: { run: npm run check } # astro check && tsc --noEmit
|
||||
typecheck: { run: npm run check } # astro check
|
||||
```
|
||||
|
||||
Commit và tag đều ký GPG; không dùng `--no-verify`.
|
||||
|
||||
## 8. Branch & release
|
||||
|
||||
- `main` protected: PR + CI xanh (solo nên cho phép self-merge, vẫn bắt CI).
|
||||
- Conventional Commits như các repo khác; site không cần semver release — "release" = deploy `main`. Tag mốc lớn (`v1-launch`) để tra cứu.
|
||||
- Preview: `wrangler versions upload` cho preview URL trước khi merge thay đổi lớn về UI (thủ công, không bắt buộc trong CI).
|
||||
- `main` protected (ruleset): PR + check bắt buộc duy nhất là `build` (ruleset cho phép cả 3 kiểu merge; quy ước của repo là **squash**). Conventional Commits.
|
||||
- Mỗi PR: ngoài `build` còn phải xanh (theo quy ước, ruleset không ép) SonarCloud quality gate, Qodana (ngưỡng 0) và CodeQL; Workers Builds trên nhánh PR chỉ `versions upload`.
|
||||
- Chế độ bảo trì (D21): PR tính năng mới bị bot `triage.yml` đóng; mẫu PR có ô chọn 5 loại thay đổi được nhận (`CONTRIBUTING.md`).
|
||||
- **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`.
|
||||
|
||||
@@ -14,13 +14,15 @@ 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) |
|
||||
| **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. In mã tham chiếu = `crypto.randomUUID().slice(0,8)` để người dùng đính vào bug report |
|
||||
| **403** middleware render | IP nằm trong `denylist:*` (KV) | "Cửa này đang khoá." / "This door is locked." | Kèm dòng: nếu nghĩ là nhầm → contact@. 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) |
|
||||
| **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** 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/429 do middleware sinh: render template Astro đã **prerender sẵn thành static asset** (`/403` `/429` là trang thật), middleware chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng — không nhân đôi markup.
|
||||
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.
|
||||
|
||||
## 3. Offline ("No Internet") — service worker
|
||||
|
||||
@@ -39,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,6 +1,6 @@
|
||||
# 10 — Bug report pipeline (console error → GitHub Issue + Discord)
|
||||
|
||||
Repo private ⇒ khách không mở issue trực tiếp được. Pipeline này là kênh báo lỗi duy nhất cho visitor, và cũng tiện cho chính mình.
|
||||
Pipeline này là kênh báo lỗi chính cho visitor (không cần tài khoản GitHub), và cũng tiện cho chính mình. Từ 10/2026 repo site là public, nhưng báo cáo có thể chứa log/mô tả riêng tư nên issue được tạo ở repo **private** `poli0981/site-reports` (đúng lời hứa "private GitHub issue" của Privacy Policy).
|
||||
|
||||
## 1. Client — thu console error
|
||||
|
||||
@@ -12,7 +12,7 @@ Repo private ⇒ khách không mở issue trực tiếp được. Pipeline này
|
||||
|
||||
## 2. UX — nút "Báo lỗi" (footer mọi trang, và trang 404/500)
|
||||
|
||||
Dialog gồm: textarea mô tả (bắt buộc, ≥ 10 ký tự) → checkbox **"Đính kèm log lỗi console (n mục)"** mặc định bật, kèm nút *Xem trước* mở đúng nội dung sẽ gửi → dòng tự đính: route, UA, viewport, theme, locale, mã tham chiếu (nếu đến từ trang 500) → Turnstile → Gửi. Thành công: "Đã gửi — cảm ơn bạn!". Thất bại: hiện thông báo + nút copy nội dung để gửi qua Discord.
|
||||
Dialog (`<dialog>` modal có nhãn, textarea có `<label>`) gồm: textarea mô tả (bắt buộc, ≥ 10 ký tự) → checkbox **"Đính kèm log lỗi console (n mục)"** mặc định bật, kèm nút *Xem trước* mở đúng nội dung sẽ gửi → dòng tự đính: route, UA, viewport, theme, locale, mã tham chiếu (từ trang 500: **Cloudflare Ray ID** do worker đóng dấu, trùng field `ray` trong Workers Logs) → Turnstile → Gửi. Thành công: "Đã gửi — cảm ơn bạn!". Thất bại: hiện thông báo + nút copy nội dung để gửi qua Discord (báo "đã sao chép" hoặc lý do clipboard bị chặn).
|
||||
|
||||
## 3. API contract — `POST /api/report`
|
||||
|
||||
@@ -25,14 +25,14 @@ Dialog gồm: textarea mô tả (bắt buộc, ≥ 10 ký tự) → checkbox **"
|
||||
}
|
||||
```
|
||||
|
||||
Worker xử lý theo thứ tự: Turnstile verify → Zod validate (fail 400) → rate-limit KV (5/phút/IP, fail 429) → **tạo GitHub Issue** → **Discord webhook** → 201. Nếu GitHub API lỗi: vẫn bắn Discord (kèm full payload) và trả 202 — không mất báo cáo.
|
||||
Worker xử lý theo thứ tự: rate-limit (middleware, binding `RL_REPORT` 5/phút/client, fail 429) → thiếu secret (503) → body > 32 KB (413 — đọc stream có trần, không đọc hết) → Zod validate (fail 400) → Turnstile siteverify (`src/lib/turnstile-server.ts`: kiểm `success` **+ `action: "report"` + `hostname: poli0981.dev`**, fail 400 `turnstile_failed`) → **tạo GitHub Issue** → **Discord webhook** → 201 `{ok: true}`. Nếu GitHub API lỗi: vẫn bắn Discord (kèm full payload) và trả 202 — không mất báo cáo. Mỗi lời gọi ra ngoài có timeout 10 s; response `no-store`. Token Turnstile dùng một lần: dialog gọi `turnstile.reset()` sau mỗi lần gửi.
|
||||
|
||||
## 4. GitHub Issue
|
||||
|
||||
`POST /repos/poli0981/poli0981.dev/issues` với `GITHUB_ISSUES_TOKEN` (fine-grained, chỉ Issues R/W):
|
||||
`POST /repos/<REPORT_REPO>/issues` — `REPORT_REPO` là var trong `wrangler.jsonc` (mặc định `poli0981/site-reports`, private) — với `GITHUB_ISSUES_TOKEN` (fine-grained, **chỉ repo đó**, Issues R/W):
|
||||
- title: `[web-report] <60 ký tự đầu của description>`
|
||||
- labels: `bug`, `from-site`
|
||||
- body: render đúng cấu trúc template §5 (description → meta table → console trong code block).
|
||||
- body: render đúng cấu trúc template §5 (description → meta table → console trong code block). `@mention` trong title/body bị vô hiệu (chèn zero-width) để báo cáo không ping ai; nội dung khách đưa vào code span/fence an toàn.
|
||||
|
||||
## 5. Issue template dùng chung — `.github/ISSUE_TEMPLATE/bug_report.yml`
|
||||
|
||||
@@ -65,7 +65,7 @@ body:
|
||||
|
||||
## 6. Discord webhook
|
||||
|
||||
Kênh riêng `#site-reports` trong server repo. Embed: màu `--color-horror`, title = issue title, field route/UA, link issue. (Tái dùng format của `notify.py` cho đồng bộ.)
|
||||
Kênh riêng `#site-reports` trong server repo. Embed: màu `--horror`, title = issue title, field route/UA, link issue; `allowed_mentions: { parse: [] }` để nội dung khách không ping được ai. (Tái dùng format của `notify.py` cho đồng bộ.)
|
||||
|
||||
## 7. Privacy & giới hạn
|
||||
|
||||
@@ -76,5 +76,6 @@ Kênh riêng `#site-reports` trong server repo. Embed: màu `--color-horror`, ti
|
||||
|
||||
- [ ] Lỗi giả (`throw` trong console) xuất hiện trong preview đính kèm
|
||||
- [ ] Gửi hợp lệ → issue mở đúng template + Discord nhận embed trong < 5s
|
||||
- [ ] Turnstile token sai → 403; 6 lần/phút → 429; payload 40KB → 400
|
||||
- [ ] Turnstile token sai → 400 `turnstile_failed`; 6 lần/phút → 429 + `Retry-After`; payload 40KB → 413
|
||||
- [ ] Gửi 2 lần trong cùng một lần mở dialog → cả hai qua được (widget được reset)
|
||||
- [ ] Tắt GITHUB token (mô phỏng lỗi) → vẫn nhận Discord + client báo "đã ghi nhận"
|
||||
@@ -7,14 +7,15 @@ API thời tiết/map phục vụ *chủ site* chứ không phục vụ *khách*
|
||||
## 2. Kiến trúc: cron → KV → build/island
|
||||
|
||||
```
|
||||
workers/widgets (cron */45 phút)
|
||||
workers/widgets (cron */45 phút, 3 nguồn chạy song song, timeout 10 s/nguồn)
|
||||
├─ YouTube RSS ─┐
|
||||
├─ Steam API ──┼─► chuẩn hoá JSON ─► KV put widgets:*
|
||||
└─ GitHub API ──┘
|
||||
Site đọc: lúc BUILD (fetch KV qua wrangler/API cho trang tĩnh) + island refresh nhẹ gọi /api/widgets (GET, cache 5')
|
||||
├─ Steam API ──┼─► chuẩn hoá JSON ─► KV put widgets:yt|steam|gh|status
|
||||
└─ GitHub API ──┘ └─► mirror thumbnail/icon ─► KV put widgets:img:* (≤ 2 MB, TTL 14 ngày)
|
||||
Site đọc: lúc BUILD (snapshot KV cho trang tĩnh) + island refresh nhẹ gọi /api/widgets (GET, cache 5')
|
||||
Ảnh: /ext-img/yt/<id> · /ext-img/steam/<appid>/<hash> → chỉ ĐỌC KV widgets:img:* (src/lib/ext-img.ts)
|
||||
```
|
||||
|
||||
Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key, không dính rate limit của họ.
|
||||
Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nhanh, không lộ key, không dính rate limit của họ, và trình duyệt không chạm Google/Steam trước khi khách bấm (khớp Privacy Policy §5). Kiểu dữ liệu chung của site và worker nằm ở `src/lib/widgets-types.ts`.
|
||||
|
||||
## 3. Nguồn dữ liệu
|
||||
|
||||
@@ -22,7 +23,7 @@ Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key,
|
||||
|---|---|---|
|
||||
| Video mới (≤3) | `https://www.youtube.com/feeds/videos.xml?channel_id=<UCxxx>` | RSS công khai, **không cần API key**; parse XML lấy id/title/thumb/published |
|
||||
| Đang chơi gì | `ISteamUser…/GetRecentlyPlayedGames/v1/?key=…&steamid=…&count=3` | Cần Steam profile → Privacy → **Game details: Public**; key free tại steamcommunity.com/dev |
|
||||
| Hoạt động GitHub | `api.github.com/users/poli0981/events/public?per_page=10` | Không cần token (60 req/h/IP đủ cho cron 45'); lọc PushEvent/ReleaseEvent |
|
||||
| Hoạt động GitHub | `api.github.com/users/poli0981/events/public?per_page=10` | Token tuỳ chọn `GITHUB_TOKEN` (không quyền nào): không có token thì hạn mức 60 req/h tính theo IP — IP egress của Workers dùng chung nên hay bị 403 ⇒ feed `stale`. Lọc PushEvent/ReleaseEvent |
|
||||
|
||||
## 4. KV schema
|
||||
|
||||
@@ -31,7 +32,8 @@ Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key,
|
||||
| `widgets:yt` | `{updated, items:[{id,title,thumb,published}]}` | không TTL — ghi đè |
|
||||
| `widgets:steam` | `{updated, items:[{appid,name,playtime2w,icon}]}` | — |
|
||||
| `widgets:gh` | `{updated, items:[{type,repo,ts,detail}]}` | — |
|
||||
| `widgets:status` | `{yt:"ok"|"stale"|"na", steam:…, gh:…, lastRun}` | — |
|
||||
| `widgets:status` | `{yt:"ok"|"stale"|"na", steam:…, gh:…, lastRun}` | — (dashboard admin hiển thị) |
|
||||
| `widgets:img:yt:<id>` · `widgets:img:steam:<appid>:<hash>` | bytes ảnh, metadata `{type}` (jpeg/png/webp) | 14 ngày; ảnh > 2 MB hoặc sai kiểu bị bỏ qua; lượt tải mới lỗi thì giữ bản cũ. Icon Steam: worker hỏi lần lượt `shared.fastly.steamstatic.com` → `shared.akamai.steamstatic.com` (đường dẫn `/community_assets/images/apps/<appid>/<hash>.jpg`, luôn trả ảnh cho Workers) → `cdn.fastly.steamstatic.com` (`/steamcommunity/public/images/apps/…`). Không dùng `cdn.cloudflare`/`cdn.akamai.steamstatic.com` hay `media.steampowered.com`: chúng trả 403 cho Workers với mọi ảnh chưa nằm trong cache của chúng (đo từ mạng Cloudflare ngày 24/10/2026). Game chưa có icon thì widget chỉ hiện tên |
|
||||
|
||||
## 5. Quy tắc bền vững (kế thừa convention tracker của bạn)
|
||||
|
||||
@@ -42,14 +44,14 @@ Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key,
|
||||
|
||||
## 6. Hiển thị
|
||||
|
||||
- `WidgetLatestVideo`: thumbnail tĩnh `i.ytimg.com` + nút play → bấm mới tạo iframe `youtube-nocookie.com` (facade — khớp CSP `06` §1 và Privacy).
|
||||
- `WidgetLatestVideo`: thumbnail qua `/ext-img/yt/<id>` (bản mirror trong KV, CSP `img-src 'self'`) + nút play → bấm mới tạo iframe `youtube-nocookie.com` (facade — `06` §5 và Privacy). Thiếu ảnh mirror ⇒ khung không ảnh, không gọi ra ngoài.
|
||||
- `WidgetNowPlaying`: icon game + tên + "x giờ / 2 tuần"; 0 game gần đây ⇒ ẩn.
|
||||
- `WidgetGitHub`: 3 dòng "pushed to X · 2d ago".
|
||||
- Trang tĩnh build kèm snapshot KV tại thời điểm build; island gọi `/api/widgets` (GET, `Cache-Control: max-age=300`, đọc KV) để tươi hơn giữa các lần deploy. Không có JS ⇒ vẫn thấy snapshot build — progressive enhancement.
|
||||
|
||||
## 7. Secrets & cấu hình worker widgets
|
||||
|
||||
`wrangler.jsonc`: `triggers: { crons: ["*/45 * * * *"] }`, bind KV chung. Secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`. Biến thường: `YT_CHANNEL_ID` (vars, không nhạy cảm).
|
||||
`wrangler.jsonc`: `triggers: { crons: ["*/45 * * * *"] }`, bind KV chung, `observability.logs` bật. Secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`, `GITHUB_TOKEN` (tuỳ chọn). Biến thường: `YT_CHANNEL_ID` (vars, không nhạy cảm). Mỗi lần chạy ghi log JSON `widgets.run` (+ `widgets.source_failed` cho nguồn lỗi). Deploy: `npx wrangler deploy --config workers/widgets/wrangler.jsonc` (không nối Workers Builds).
|
||||
|
||||
## 8. Test
|
||||
|
||||
|
||||
@@ -18,16 +18,16 @@ Ghi chú pháp lý nhanh (để hiểu, không cần đưa lên site): GPL chỉ
|
||||
|
||||
## English (render trên site)
|
||||
|
||||
**Code.** The source code of this website is free software, licensed under the GNU General Public License v3.0. When the repository is public you can obtain it there; until then, code snippets published in blog posts are shared under the license stated in each post.
|
||||
**Code.** The source code of this website is free software, licensed under the GNU General Public License v3.0, and is public at https://github.com/poli0981/poli0981-dev. Code snippets published in blog posts are shared under the license stated in each post.
|
||||
|
||||
**Content.** All written content, stories, photographs, and other original media on this Site are **© Kokone (SkullMute), all rights reserved**. You may not reproduce, republish, or redistribute them, and you may not use them to train machine-learning systems, without prior written permission. Short quotations with attribution and a link are permitted (see Terms §4). Individual pages may state a different license for that page's content, which then prevails.
|
||||
|
||||
**Permissions & takedown.** Requests: contact@poli0981.dev.
|
||||
**Permissions & takedown.** Permission to reuse content: copyright@poli0981.dev. Copyright infringement notices (DMCA): dmca@poli0981.dev. Other removal requests (e.g. personal data about you): takedown@poli0981.dev.
|
||||
|
||||
## Tiếng Việt (render trên site)
|
||||
|
||||
**Mã nguồn.** Mã nguồn của website là phần mềm tự do, cấp phép theo GNU General Public License v3.0. Khi repo được mở public, bạn có thể lấy mã tại đó; trước lúc đó, các đoạn code đăng trong bài blog được chia sẻ theo giấy phép ghi trong từng bài.
|
||||
**Mã nguồn.** Mã nguồn của website là phần mềm tự do, cấp phép theo GNU General Public License v3.0, công khai tại https://github.com/poli0981/poli0981-dev. Các đoạn code đăng trong bài blog được chia sẻ theo giấy phép ghi trong từng bài.
|
||||
|
||||
**Nội dung.** Toàn bộ bài viết, truyện, ảnh và media gốc trên Trang web thuộc **bản quyền © Kokone (SkullMute), bảo lưu mọi quyền**. Không sao chép, đăng lại, phân phối lại, và không dùng để huấn luyện hệ thống máy học khi chưa có sự cho phép bằng văn bản. Được phép trích ngắn có ghi nguồn kèm link (xem Điều khoản §4). Trang cụ thể có thể ghi giấy phép khác cho nội dung của trang đó — khi ấy giấy phép ghi tại trang được ưu tiên.
|
||||
|
||||
**Xin phép & yêu cầu gỡ:** contact@poli0981.dev.
|
||||
**Xin phép & yêu cầu gỡ:** xin phép dùng nội dung: copyright@poli0981.dev. Thông báo vi phạm bản quyền (DMCA): dmca@poli0981.dev. Yêu cầu gỡ khác (vd. dữ liệu cá nhân về bạn): takedown@poli0981.dev.
|
||||
@@ -10,21 +10,23 @@
|
||||
|
||||
This is a personal website designed to collect as little data as possible.
|
||||
|
||||
**1. What I do NOT do.** No advertising, no ad trackers, no cross-site tracking, no sale of data, no user accounts, no analytics cookies.
|
||||
**1. What I do NOT do.** No advertising, no ad trackers, no cross-site tracking, no sale of data, no user accounts, no analytics cookies. The only cookie is the bot-check pass described in §3.
|
||||
|
||||
**2. Analytics.** The Site uses Cloudflare Web Analytics, a cookie-free, privacy-focused service that reports aggregate statistics (page views, country, browser type). It does not build visitor profiles.
|
||||
**2. Analytics.** The Site uses Cloudflare Web Analytics, a cookie-free, privacy-focused service that reports aggregate statistics (page views, country, browser type, page-load performance). Pages load its small script from static.cloudflareinsights.com, which reports to Cloudflare. It sets no cookies and does not build visitor profiles.
|
||||
|
||||
**3. Hosting & security logs.** The Site runs on Cloudflare. Like virtually all websites, requests pass through infrastructure that processes IP addresses and request metadata for security (DDoS mitigation, abuse prevention, rate limiting). I use IP addresses only transiently for rate limiting and blocking abuse; they are not stored in my own records.
|
||||
|
||||
**Bot check.** Before your first page view the Site runs Cloudflare Turnstile, a challenge that checks the browser is not an automated scraper; Cloudflare processes technical signals for it (such as IP address and browser characteristics) under its own privacy policy. Passing it sets one strictly necessary cookie, `__Host-gate`, valid for 48 hours. It holds only an expiry time, a random value and a signature — nothing that identifies you — and is never used for tracking. Search engines and link-preview services verified by Cloudflare skip the check; feeds, the sitemap and the legal pages are always open.
|
||||
|
||||
**4. Bug reports (the only form on the Site).** If you choose to send a bug report, the following is transmitted and stored as a private GitHub issue and a Discord notification: your description, the page route, browser user-agent, viewport size, theme/language setting, and — only if you leave the checkbox enabled — the last console error messages shown to you in a preview before sending. No IP address is stored with the report. Contact me to request deletion of a report you sent.
|
||||
|
||||
**5. Embedded videos.** YouTube videos load only after you click them, via YouTube's privacy-enhanced domain (youtube-nocookie.com). Before you click, only a static thumbnail is loaded. Once you click, YouTube's own privacy policy applies.
|
||||
|
||||
**6. Local storage.** The Site stores small preferences in your browser only: theme, reading settings, language hint, legal-notice acknowledgement, and (if you play the offline mini-game) a best score. These never leave your device.
|
||||
**6. Local storage.** The Site stores small preferences in your browser only: theme, scrollbar visibility, reading settings, legal-notice acknowledgement, and (if you play the offline mini-game) a best score. These never leave your device.
|
||||
|
||||
**7. Email.** If you email contact@poli0981.dev, your message is forwarded via Cloudflare Email Routing to my mailbox and kept as normal correspondence.
|
||||
**7. Email.** Mail sent to any @poli0981.dev address (contact@, privacy@, security@, and the other topic addresses listed on the Site) is delivered to my mailbox on Google Workspace (Google LLC processes it under its own terms) and kept as normal correspondence.
|
||||
|
||||
**8. Your choices & rights.** You can browse with JavaScript disabled (core content still works), clear local storage at any time, and request deletion of bug reports or emails you sent. Requests: contact@poli0981.dev.
|
||||
**8. Your choices & rights.** JavaScript is needed once, to pass the bot check; after that, core content works with it disabled. You can clear local storage and the bot-check cookie at any time, and request deletion of bug reports or emails you sent. Requests: privacy@poli0981.dev.
|
||||
|
||||
**9. Children.** The Site is not directed at children under 13 and collects no data targeting them.
|
||||
|
||||
@@ -38,21 +40,23 @@ This is a personal website designed to collect as little data as possible.
|
||||
|
||||
Đây là website cá nhân, được thiết kế để thu thập càng ít dữ liệu càng tốt.
|
||||
|
||||
**1. Những thứ mình KHÔNG làm.** Không quảng cáo, không tracker quảng cáo, không theo dõi chéo trang, không bán dữ liệu, không tài khoản người dùng, không cookie analytics.
|
||||
**1. Những thứ mình KHÔNG làm.** Không quảng cáo, không tracker quảng cáo, không theo dõi chéo trang, không bán dữ liệu, không tài khoản người dùng, không cookie analytics. Cookie duy nhất là "vé" xác minh chống bot ở mục 3.
|
||||
|
||||
**2. Thống kê truy cập.** Trang web dùng Cloudflare Web Analytics — dịch vụ không cookie, tôn trọng quyền riêng tư, chỉ báo số liệu tổng hợp (lượt xem, quốc gia, loại trình duyệt), không dựng hồ sơ người xem.
|
||||
**2. Thống kê truy cập.** Trang web dùng Cloudflare Web Analytics — dịch vụ không cookie, tôn trọng quyền riêng tư, chỉ báo số liệu tổng hợp (lượt xem, quốc gia, loại trình duyệt, tốc độ tải trang). Các trang tải một script nhỏ từ static.cloudflareinsights.com và gửi số liệu về Cloudflare. Script không đặt cookie và không dựng hồ sơ người xem.
|
||||
|
||||
**3. Hạ tầng & log bảo mật.** Trang web chạy trên Cloudflare. Như hầu hết website, request đi qua hạ tầng có xử lý địa chỉ IP và metadata cho mục đích bảo mật (chống DDoS, chống lạm dụng, rate limiting). Mình chỉ dùng IP thoáng qua để giới hạn tần suất và chặn phá hoại; IP không được lưu trong hồ sơ riêng của mình.
|
||||
|
||||
**Xác minh chống bot.** Trước lượt xem đầu tiên, trang chạy Cloudflare Turnstile — bước kiểm tra trình duyệt không phải bot thu thập nội dung; Cloudflare xử lý các tín hiệu kỹ thuật (như địa chỉ IP, đặc điểm trình duyệt) theo chính sách riêng của họ. Qua bước này, trình duyệt nhận một cookie thiết yếu duy nhất, `__Host-gate`, hiệu lực 48 giờ. Cookie chỉ chứa thời điểm hết hạn, một giá trị ngẫu nhiên và chữ ký — không có gì định danh bạn — và không bao giờ dùng để theo dõi. Công cụ tìm kiếm và dịch vụ xem trước liên kết đã được Cloudflare xác thực thì bỏ qua bước này; RSS, sitemap và các trang pháp lý luôn mở.
|
||||
|
||||
**4. Báo lỗi (biểu mẫu duy nhất trên trang).** Nếu bạn chủ động gửi báo lỗi, những thứ sau được truyền và lưu dưới dạng GitHub issue riêng tư + thông báo Discord: mô tả của bạn, đường dẫn trang, user-agent trình duyệt, kích thước màn hình, cài đặt theme/ngôn ngữ, và — chỉ khi bạn để nguyên ô tick — các lỗi console gần nhất (có bản xem trước trước khi gửi). Địa chỉ IP không được lưu kèm báo cáo. Muốn xoá báo cáo đã gửi: liên hệ mình.
|
||||
|
||||
**5. Video nhúng.** Video YouTube chỉ tải sau khi bạn bấm, qua tên miền tăng cường riêng tư (youtube-nocookie.com). Trước khi bấm, chỉ có ảnh thumbnail tĩnh. Sau khi bấm, chính sách của YouTube áp dụng.
|
||||
|
||||
**6. Lưu trữ cục bộ.** Trang web lưu vài tuỳ chọn nhỏ ngay trong trình duyệt của bạn: theme, cài đặt đọc, gợi ý ngôn ngữ, ghi nhận đã xem thông báo pháp lý, và (nếu bạn chơi mini-game offline) điểm cao nhất. Chúng không bao giờ rời thiết bị của bạn.
|
||||
**6. Lưu trữ cục bộ.** Trang web lưu vài tuỳ chọn nhỏ ngay trong trình duyệt của bạn: theme, ẩn/hiện thanh cuộn, cài đặt đọc, ghi nhận đã xem thông báo pháp lý, và (nếu bạn chơi mini-game offline) điểm cao nhất. Chúng không bao giờ rời thiết bị của bạn.
|
||||
|
||||
**7. Email.** Mail gửi tới contact@poli0981.dev được chuyển tiếp qua Cloudflare Email Routing về hộp thư của mình và lưu như thư từ thông thường.
|
||||
**7. Email.** Mail gửi tới bất kỳ địa chỉ @poli0981.dev nào (contact@, privacy@, security@ và các địa chỉ theo chủ đề ghi trên trang) được chuyển vào hộp thư Google Workspace của mình (Google LLC xử lý theo điều khoản của họ) và lưu như thư từ thông thường.
|
||||
|
||||
**8. Lựa chọn & quyền của bạn.** Bạn có thể duyệt web khi tắt JavaScript (nội dung chính vẫn hoạt động), xoá local storage bất cứ lúc nào, và yêu cầu xoá báo lỗi/email đã gửi. Liên hệ: contact@poli0981.dev.
|
||||
**8. Lựa chọn & quyền của bạn.** Cần JavaScript một lần để qua bước xác minh; sau đó nội dung chính vẫn hoạt động khi tắt JavaScript. Bạn có thể xoá local storage và cookie xác minh bất cứ lúc nào, và yêu cầu xoá báo lỗi/email đã gửi. Liên hệ: privacy@poli0981.dev.
|
||||
|
||||
**9. Trẻ em.** Trang web không hướng tới trẻ dưới 13 tuổi và không thu thập dữ liệu nhắm vào trẻ em.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ Welcome to `poli0981.dev` (the "Site"), operated by Kokone ("I", "me"). By acces
|
||||
|
||||
**9. Governing law.** These Terms are governed by the laws of Vietnam.
|
||||
|
||||
**Contact:** contact@poli0981.dev
|
||||
**Contact:** legal@poli0981.dev (legal matters) · contact@poli0981.dev (anything else)
|
||||
|
||||
---
|
||||
|
||||
@@ -56,4 +56,4 @@ Chào mừng đến `poli0981.dev` ("Trang web"), do Kokone ("mình") vận hàn
|
||||
|
||||
**9. Luật áp dụng.** Điều khoản này chịu sự điều chỉnh của pháp luật Việt Nam.
|
||||
|
||||
**Liên hệ:** contact@poli0981.dev
|
||||
**Liên hệ:** legal@poli0981.dev (vấn đề pháp lý) · contact@poli0981.dev (việc khác)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Third-Party Notices / Ghi nhận bên thứ ba
|
||||
|
||||
> **Ghi chú nội bộ:** file này gồm 2 phần — (A) phần khung render lên `/legal/third-party`, (B) bảng package **tự sinh** bằng `scripts/gen-notices.mjs` trong CI (dựa trên `license-checker`), CI fail nếu bảng lệch với lockfile. Đừng sửa tay phần B.
|
||||
> **Ghi chú nội bộ:** file này gồm 2 phần — (A) phần khung render lên `/legal/third-party`, (B) bảng package **tự sinh** bằng `scripts/gen-notices.mjs` trong CI (đọc `package.json` của từng gói đã cài — không dùng `license-checker`), CI fail nếu bảng lệch với lockfile. Đừng sửa tay phần B.
|
||||
|
||||
---
|
||||
|
||||
@@ -21,7 +21,6 @@ Trang web này được xây dựng bằng phần mềm mã nguồn mở. Mỗi
|
||||
| Astro + @astrojs/* | MIT | framework |
|
||||
| Svelte | MIT | islands |
|
||||
| Tailwind CSS | MIT | styling |
|
||||
| GSAP | GSAP Standard License (miễn phí, Webflow) | kiểm tra đúng tên license trong bản phát hành khi cài |
|
||||
| Pagefind | MIT | search |
|
||||
| @vite-pwa/astro / Workbox | MIT | offline |
|
||||
| Zod | MIT | validation |
|
||||
@@ -37,8 +36,9 @@ Trang web này được xây dựng bằng phần mềm mã nguồn mở. Mỗi
|
||||
## Quy trình sinh tự động
|
||||
|
||||
```bash
|
||||
node scripts/gen-notices.mjs # ghi đè phần (B) từ npm ls --json + license-checker
|
||||
node scripts/gen-notices.mjs # ghi đè phần (B): dependency trực tiếp, license đọc từ node_modules/<pkg>/package.json
|
||||
node scripts/gen-notices.mjs --check # CI: so khớp, lệch ⇒ exit 1
|
||||
node scripts/check-licenses.mjs # CI: toàn bộ package-lock.json (transitive + binary mọi nền tảng)
|
||||
```
|
||||
|
||||
Quy tắc: package mới có license ngoài allowlist (MIT, Apache-2.0, ISC, BSD-2/3, OFL, GSAP Standard) ⇒ script cảnh báo đỏ, phải review tay trước khi merge.
|
||||
Quy tắc (`scripts/license-policy.mjs`, dùng chung cho hai script): license ngoài allowlist (MIT, Apache-2.0, ISC, BSD-2/3, OFL-1.1, 0BSD, Unlicense, CC0-1.0, BlueOak-1.0.0, Python-2.0; biểu thức SPDX `OR`/`AND`/`WITH` được hiểu) ⇒ CI đỏ, phải review tay và ghi ngoại lệ **theo gói** kèm lý do (hiện có: MPL-2.0 của satori/resvg/lightningcss/axe-core, LGPL-3.0-or-later của libvips trong sharp — đều chỉ chạy lúc build/test). Gói không khai license cũng làm CI đỏ.
|
||||
@@ -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`:
|
||||
|
||||
```
|
||||
@@ -47,8 +47,9 @@ Item: title, link, pubDate, description, `<language>` theo bài, category = tags
|
||||
|
||||
## 5. OG image tự sinh
|
||||
|
||||
- Build-time bằng Satori + resvg (hoặc `astro-og-canvas` nếu gọn hơn lúc triển khai): template 1200×630, nền mực đêm + Waveline + title (Bricolage) + badge khu (Blog/Truyện/Project) + `poli0981.dev`.
|
||||
- Truyện có contentWarning: OG thêm dải màu horror + nhãn CW (không spoil chi tiết).
|
||||
- Build-time bằng Satori + resvg (hoặc `astro-og-canvas` nếu gọn hơn lúc triển khai): template 1200×630, nền glacier night (palette tối) + Waveline + title (Bricolage) + badge khu (Blog/Truyện/Project) + `poli0981.dev`.
|
||||
- Bài/truyện có nhãn (`contentWarning`) hoặc mốc tuổi (`ageRating`): OG thêm dải màu horror "Cảnh báo · Kinh dị · 16+" bằng ngôn ngữ của bài (không spoil chi tiết). Thẻ OG chỉ có chữ nên không bao giờ lộ ảnh bìa.
|
||||
- RSS: description của mục có nhãn được thêm tiền tố "[Cảnh báo: Kinh dị · 16+] " (theo ngôn ngữ của mục) — feed reader không có banner.
|
||||
- Cache theo hash(title+khu) để build nhanh.
|
||||
|
||||
## 6. Dữ liệu có cấu trúc (JSON-LD)
|
||||
|
||||
@@ -18,14 +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.
|
||||
- **Third-party = 0** ở first paint (YouTube facade, widget đọc KV nội bộ).
|
||||
- **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 (P2): job Lighthouse CI chạy trên preview build, assert budget bảng §1 — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý.
|
||||
- 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,44 +2,70 @@
|
||||
|
||||
Ước lượng theo "buổi tối" (~2–3h). Nguyên tắc quen thuộc: **xong P0 spikes mới viết feature** — spike nào fail thì sửa kế hoạch khi chưa tốn công.
|
||||
|
||||
## P0 — Spikes (làm trước tiên, ~3–4 buổi)
|
||||
Trạng thái tại 2026-11-21 (v2.3.0 — **chế độ bảo trì**): ✅ xong · 🟡 đang làm · ⬜ chưa.
|
||||
|
||||
| # | Spike | Cách làm | Tiêu chí đạt |
|
||||
|---|---|---|---|
|
||||
| S1 | **Pipeline sống end-to-end** | Mua domain (07 §1) → scaffold `create-cloudflare` Astro → `wrangler deploy` → gắn custom domain → caller CI/deploy stub chạy | Push 1 commit ⇒ site đổi trên `poli0981.dev` trong <3 phút |
|
||||
| S2 | **Font tiếng Việt** | Cấu hình Fonts API 4 font, subset `latin+vietnamese`; trang test chứa chuỗi đủ dấu ("ắ ằ ẳ ẵ ặ ế ệ ễ ỡ ợ ự ữ Đ…") ở mọi weight | Render đúng trên Android + iPhone thật, không fallback lệch baseline, tổng 2 file first-paint <90KB |
|
||||
| S3 | **Error handling sau edge** | Set `not_found_handling: "404-page"`; middleware trả 403/429 từ asset prerender; test qua domain thật (không phải localhost) | Ma trận `09` §5 pass các dòng 404/403/429 |
|
||||
| S4 | **CSP không vỡ tính năng** | Bật CSP built-in + directive `06` §1; chạy thử View Transitions, 1 animation GSAP, Pagefind search, YouTube facade | Console 0 lỗi CSP; search hoạt động (nhớ `wasm-unsafe-eval`) |
|
||||
## P0 — Spikes ✅
|
||||
|
||||
## P1 — Nền móng + nội dung lõi (~6–8 buổi)
|
||||
| # | Spike | Cách làm | Tiêu chí đạt | |
|
||||
|---|---|---|---|---|
|
||||
| S1 | **Pipeline sống end-to-end** | Mua domain (07 §1) → scaffold Astro → deploy → gắn custom domain → CI | Push 1 commit ⇒ site đổi trên `poli0981.dev` trong <3 phút | ✅ (Workers Builds) |
|
||||
| S2 | **Font tiếng Việt** | Fonts API 4 font, subset `latin+vietnamese`; trang test đủ dấu ở mọi weight | Render đúng trên Android + iPhone thật, 2 file first-paint <90KB | ✅ |
|
||||
| S3 | **Error handling sau edge** | `not_found_handling: "404-page"`; 403/429 từ asset prerender; test qua domain thật | Ma trận `09` §5 pass các dòng 404/403/429 | ✅ |
|
||||
| S4 | **CSP không vỡ tính năng** | CSP built-in + directive `06` §1; Pagefind, YouTube facade, Turnstile | Console 0 lỗi CSP; search hoạt động (`wasm-unsafe-eval`) | ✅ (`check-csp-hashes` trong build) |
|
||||
|
||||
## P1 — Nền móng + nội dung lõi ✅
|
||||
|
||||
- Design tokens + Base layout + Header/Footer/TabBar + theme/lang toggle + Waveline.
|
||||
- Content Collections + schemas + templates; trang: Home (chưa widget), About, Blog (index/bài/tag), Stories (index/reader/ReadingControls/CW), Q&A, Links, Legal ×5 + LegalGateSheet.
|
||||
- Trang lỗi 404/500/403/429 + middleware headers/denylist/rate-limit.
|
||||
- Migrate: viết 2–3 bài blog đầu + 1 truyện ngắn để có nội dung thật khi launch.
|
||||
- **Launch nội bộ cuối P1** (site đã dùng được).
|
||||
- Content Collections + schemas + templates; trang: Home, About, Blog (index/bài/tag), Stories (index/reader/ReadingControls/CW), Q&A, Links, Legal ×5 + LegalGateSheet.
|
||||
- Trang lỗi 404/500/403/429 + headers/denylist/rate-limit.
|
||||
- Nội dung thật đầu tiên: bài blog + truyện "Đêm không tiếng".
|
||||
|
||||
## P2 — Hoàn thiện trải nghiệm (~5–6 buổi)
|
||||
## P2 — Hoàn thiện trải nghiệm ✅
|
||||
|
||||
- Pagefind search modal · RSS ×3 · sitemap/hreflang/JSON-LD · OG image tự sinh.
|
||||
- Gallery + lightbox + strip-exif/check-exif scripts.
|
||||
- Gaming + Dev/uses; widgets worker (YouTube/Steam/GitHub) + `/api/widgets`.
|
||||
- Bug report pipeline đầy đủ (10) + issue template.
|
||||
- Offline service worker + trang /offline (chưa game).
|
||||
- Offline service worker + trang /offline.
|
||||
- Lighthouse CI warn-mode.
|
||||
|
||||
## P3 — Gia vị (rảnh thì làm)
|
||||
## P3 — Gia vị ✅
|
||||
|
||||
- Mini-game Skull Hop (09 §4) · `npm run new:post` · trang /now cadence tháng · easter egg konami/ASCII skull trong console (`console.log` banner) · dòng thời tiết footer nếu vẫn thích.
|
||||
- Mini-game Skull Hop (09 §4) · `npm run new:post` · trang /now · easter egg konami/ASCII skull trong console.
|
||||
|
||||
## P4 — Launch công khai
|
||||
## P3.5 — Nền tảng & admin (10/2026) ✅
|
||||
|
||||
- [ ] Checklist `06` §8 (security) + `07` §13 (Cloudflare) + `09` §5 (errors) pass
|
||||
- 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)
|
||||
- [ ] Phần còn lại của `06` §8 + `07` §13 (Cloudflare) + `09` §5 (errors) chạy tay trên production
|
||||
- [ ] 13 §7 (SEO một lần) xong
|
||||
- [ ] Đọc lại 5 văn bản legal, điền {{EFFECTIVE_DATE}}, xoá ghi chú nội bộ
|
||||
- [x] Văn bản legal có ngày hiệu lực (2026-10-24), không còn ghi chú nội bộ
|
||||
- [ ] Test 2 thiết bị thật + 1 máy lạ (bạn bè) — thu 1 vòng feedback
|
||||
- [ ] Tag `v1-launch`, đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/GitHub/Discord
|
||||
- [ ] Đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/GitHub/Discord
|
||||
|
||||
## Sau v1 — backlog để ngỏ
|
||||
- **v2.3.0** (11/2026, bản tính năng cuối): nhãn nội dung + hỏi tuổi + ảnh mờ + banner cảnh báo (D22) · admin tự xuất bản và biết khi nào "đã lên web" (D23) · Qodana + kiểm license toàn cây (D24) · **chuyển sang chế độ bảo trì** (D21).
|
||||
|
||||
Keystatic (ADR-04, xét lại sau 1–2 tháng dùng thật) · bot Telegram capture · locale `ja` · R2 cho gallery (>1GB) · repo public `poli0981/legal` · trang /support (Ko-fi) · Giscus nếu đổi ý về comment.
|
||||
## Chế độ bảo trì (từ v2.3.0, 11/2026)
|
||||
|
||||
Không thêm tính năng mới. Chỉ: cập nhật dependency định kỳ · vá bảo mật (advisory High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (cả UI/UX, accessibility) · sửa lỗi ngôn ngữ. Chính sách: `CONTRIBUTING.md`; lịch: `17` §0–§1; bot đóng đề xuất tính năng: `.github/workflows/triage.yml`.
|
||||
|
||||
P4 còn mở vẫn làm được vì không phải tính năng. Bảng dưới đây **đóng băng** — giữ để biết đã cân nhắc gì; mục nào chỉ quay lại khi rơi vào một trong năm loại thay đổi được nhận (VD gộp TypeScript 7.1 = nâng cấp lớn).
|
||||
|
||||
## Hướng đi đã cân nhắc (đóng băng)
|
||||
|
||||
| Hướng | Vì sao | Điều kiện |
|
||||
|---|---|---|
|
||||
| Gộp TypeScript về một bản 7.x | Bỏ alias `@typescript/native` + TS 6 | TS 7.1 có JS API; astro check / typescript-eslint / svelte2tsx hỗ trợ |
|
||||
| Workers Builds riêng cho widgets worker | Hết deploy tay | Khi worker có thay đổi thường xuyên hơn |
|
||||
| Backup định kỳ R2 + KV (denylist, audit) | Ảnh upload chỉ nằm ở R2 | Workflow cron dùng `wrangler r2 object get` / `kv key list` (17 §4) |
|
||||
| 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) |
|
||||
| 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 |
|
||||
@@ -9,10 +9,11 @@ Tỷ giá tham khảo ~26.000 VND/USD, 2026-07.
|
||||
| Domain `poli0981.dev` (Cloudflare Registrar, at-cost, WHOIS redaction free) | năm | **~$12–13** (~320–340k VND) — số chính xác hiện khi search trong dashboard | **Phát sinh mới duy nhất** |
|
||||
| Cloudflare Workers Paid | tháng | $5 | Đã có sẵn — site nằm trong hạn mức |
|
||||
| KV · Turnstile · Web Analytics · Email Routing · WAF free · Bot Fight | — | $0 | Free / trong gói |
|
||||
| GitHub private repo + Actions + Dependabot | — | $0 | Free plan (2.000 phút Actions/tháng — CI dùng ~5–10%) |
|
||||
| GitHub public repo + Actions + Dependabot + CodeQL | — | $0 | Repo public: phút Actions không giới hạn cho runner chuẩn; SonarCloud free cho dự án public |
|
||||
| Astro/Svelte/Tailwind/GSAP/font/Pagefind | — | $0 | OSS |
|
||||
| R2 | — | $0 | Chưa dùng (kích hoạt khi gallery >1GB, free tới 10GB) |
|
||||
| Zone Pro / Sentry / CMS / CDN ảnh | — | $0 | **Cố ý không dùng** — có phương án thay thế trong suite |
|
||||
| R2 | `poli0981-media` | $0 | Ảnh upload qua admin (biến thể AVIF/WebP + master). Free 10 GB lưu trữ, 1M thao tác ghi, 10M đọc/tháng — đọc hầu hết trúng Cache API ở edge |
|
||||
| Images (binding) | biến đổi lúc upload | $0 | Free 5.000 biến đổi duy nhất/tháng (mỗi ảnh ≈ 6), vượt thì $0.50/1.000. Ảnh trùng (cùng hash) không biến đổi lại |
|
||||
| Zone Pro / Sentry / CMS bên thứ ba | — | $0 | **Cố ý không dùng** — admin tự làm (Access + GitHub API), ảnh dùng R2 + Images của chính Cloudflare |
|
||||
|
||||
**Tổng phát sinh mới: ~$12–13/năm.** Tổng vận hành thực (gồm Workers đã trả): **~$72–73/năm (~1,9 triệu VND)**.
|
||||
|
||||
@@ -20,9 +21,11 @@ Tỷ giá tham khảo ~26.000 VND/USD, 2026-07.
|
||||
|
||||
| Hạn mức | Gói hiện tại | Site này dự kiến | Khi nào lo |
|
||||
|---|---|---|---|
|
||||
| Worker requests | 10 triệu/tháng trong gói Paid | vài nghìn–chục nghìn (static assets **không tính**) | Viral rất lớn + nhiều hit /api — gần như không xảy ra |
|
||||
| Worker requests | 10 triệu/tháng trong gói Paid | mỗi lượt xem trang + mỗi ảnh `/media` = 1 request (cổng Turnstile chạy trước mọi trang); hashed asset/feeds/OG **không tính** | Viral rất lớn — vẫn còn xa ngưỡng ở quy mô site cá nhân |
|
||||
| Cloudflare Access | 50 người dùng miễn phí | 1 (chủ site) | Không áp dụng |
|
||||
| Images (binding) | 5.000 biến đổi duy nhất/tháng | ≈ 6 / ảnh upload; ảnh trùng = 0 | Upload > ~800 ảnh mới/tháng |
|
||||
| KV reads/writes | hạn mức Paid rộng | cron 45' + vài GET | Không |
|
||||
| GitHub Actions phút | 2.000/tháng (private) | ~100–200 | Nếu sau này thêm job nặng — theo dõi ở Settings → Billing |
|
||||
| GitHub Actions phút | không giới hạn (public) | ~200–400 | Repo `content`/`site-reports` vẫn private nếu sau này có workflow riêng — theo dõi ở Settings → Billing |
|
||||
| Domain renew | — | $12–13/năm | Thẻ hết hạn ⇒ mất domain — auto-renew ON + lịch nhắc (17) |
|
||||
|
||||
## 3. Quy tắc chi tiêu
|
||||
|
||||
@@ -2,14 +2,26 @@
|
||||
|
||||
Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì định kỳ ~15–30 phút/tuần.
|
||||
|
||||
## 0. Chế độ bảo trì (từ v2.3.0, 11/2026 — quyết định D21)
|
||||
|
||||
Không thêm tính năng mới. Repo chỉ nhận (`CONTRIBUTING.md`):
|
||||
|
||||
1. Cập nhật dependency định kỳ (Dependabot hằng tuần + gộp `npm update --save --before=<hôm nay − 3 ngày>` khoảng mỗi tháng, như PR #123/#134).
|
||||
2. Bảo mật: advisory **High/Critical** trong dependency hoặc lỗ hổng nghiêm trọng của Node.js/Workers runtime ⇒ sửa và deploy ngay, ngoài lịch; tính năng chỉ khi thật sự cần.
|
||||
3. Nâng cấp lớn ngôn ngữ/runtime/framework (Node 26 → 28, TS 7.1 thay alias TS 6, Astro/Svelte major…).
|
||||
4. Sửa lỗi, gồm UI/UX và accessibility.
|
||||
5. Sửa lỗi ngôn ngữ (chính tả gây hiểu nhầm, câu chữ không hợp văn hoá/giọng địa phương).
|
||||
|
||||
Issue/PR đề xuất tính năng: `.github/workflows/triage.yml` (logic `scripts/triage.mjs`) gắn `enhancement` + `out-of-scope`, trả lời song ngữ và đóng. Bỏ qua: chủ repo, bot, mục có nhãn `maintenance-exception` (ngoại lệ do chủ repo quyết), và mọi thao tác do chính chủ repo làm (mở lại, gắn nhãn). Thử khô: Actions → Triage → Run workflow (nhập tiêu đề). Form issue: lỗi, accessibility, ngôn ngữ; blank issue tắt; câu hỏi/ý tưởng → Discussions.
|
||||
|
||||
## 1. Lịch định kỳ
|
||||
|
||||
| Nhịp | Việc |
|
||||
|---|---|
|
||||
| **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; xem Web Analytics + Core Web Vitals; liếc Workers metrics (request, error rate); kiểm tra cron widgets còn chạy |
|
||||
| **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, CLOUDFLARE_API_TOKEN, STEAM_API_KEY · 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, QODANA_TOKEN (token project trên Qodana Cloud → secret repo) · 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`).
|
||||
|
||||
@@ -17,29 +29,40 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
|
||||
|
||||
1. Branch `chore/upgrade-<pkg>-vX` → đọc CHANGELOG/upgrade guide chính thức.
|
||||
2. `npm i <pkg>@latest` → chạy full CI local (`format/lint/check/knip/build`).
|
||||
3. `wrangler versions upload` → preview URL → bấm qua 6 trang đại diện + search + form report.
|
||||
4. Merge → deploy → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
|
||||
5. Ghi 1 dòng vào `docs/00_INDEX.md` nếu có breaking change ảnh hưởng quyết định cũ.
|
||||
3. Mở PR → CI (`build` + smoke) + SonarCloud xanh; Workers Builds upload version preview của nhánh → bấm qua 6 trang đại diện + search + form report (dashboard → Versions → alias của nhánh).
|
||||
4. Squash-merge → Workers Builds deploy `main` (Deploy command `npx wrangler deploy`, `07` §9) → kiểm `/api/health` trả đúng commit (nếu vẫn bản cũ: Deploy command lại thành `versions upload` ⇒ sửa trong dashboard, tạm thời `wrangler versions deploy <id>@100%`) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
|
||||
5. Ghi vào `CHANGELOG.md`; ghi 1 dòng vào `poli0981.dev-docs/00_INDEX.md` nếu có breaking change ảnh hưởng quyết định cũ.
|
||||
|
||||
**Rollback**: `npx wrangler versions list` → `npx wrangler versions deploy <id-cũ>@100% --yes` (hoặc `wrangler rollback`). Secret mới đặt sau version đó sẽ không có trong version cũ — đặt lại nếu cần.
|
||||
|
||||
## 3. Giám sát
|
||||
|
||||
- **Uptime** (tuỳ chọn, free): UptimeRobot/StatusCake ping `https://poli0981.dev/` 5 phút/lần → alert email/Discord. Đủ dùng, không cần status page.
|
||||
- **Lỗi runtime**: Workers observability (đã bật trong wrangler.jsonc) → xem Logs khi có report; không cần Sentry ở quy mô này (ADR-05).
|
||||
- **Lỗi runtime**: Workers Logs (log JSON có `event`/`ray`, `06` §10) → tra theo Ray ID mà người dùng gửi kèm báo lỗi; không cần Sentry ở quy mô này (ADR-05).
|
||||
- **Đang chạy bản nào**: `curl https://poli0981.dev/api/health` → `version.id` + `version.commit` + `version.content` (commit repo nội dung mà bản build dùng); dashboard admin hiện cùng thông tin, thanh Xuất bản báo pha "đang build / đã merge — đang deploy / đã lên web".
|
||||
- **Admin**: `/admin/activity/` (audit log 90 ngày + commit repo content) — liếc khi nghi có thao tác lạ.
|
||||
- **Cron widgets**: tự cảnh báo qua Discord khi fail 3 lần (11 §5).
|
||||
|
||||
## 4. Backup & khôi phục
|
||||
|
||||
- **Nguồn sự thật = Git** (nội dung + code). GitHub đã là bản sao thứ nhất; máy local là bản thứ hai.
|
||||
- **Quý**: `git bundle create backup-YYYYQ.bundle --all` → cất vào ổ ngoài/cloud cá nhân (một lệnh, chứa toàn bộ lịch sử).
|
||||
- KV widgets = dữ liệu tái sinh được, không cần backup. Secrets: lưu trong password manager (không chỉ trong Cloudflare).
|
||||
- **R2 `poli0981-media`** (ảnh upload qua admin — *không* có trong Git): quý một lần sao ra ngoài, vd. `npx wrangler r2 object get poli0981-media/<key> --file …` theo danh sách `private/meta/*.json`, hoặc rclone với S3 API token chỉ-đọc.
|
||||
- **KV**: widgets tái sinh được; `denylist` và `audit:*` nên xuất định kỳ: `npx wrangler kv key get --binding KV denylist --preview false > denylist.json` và `npx wrangler kv key list --binding KV --prefix audit: --preview false > audit.json`.
|
||||
- Secrets: lưu trong password manager (không chỉ trong Cloudflare).
|
||||
- **Khôi phục thảm hoạ** (mất account/worker): repo + `07_CLOUDFLARE_SETUP.md` + `wrangler deploy` ⇒ site sống lại trong < 1 giờ. Domain là thứ duy nhất không thay được — vì thế 2FA + transfer lock + auto-renew là 3 khoá quan trọng nhất của cả hệ thống.
|
||||
|
||||
## 5. Trigger cần hành động (đặt sẵn ngưỡng)
|
||||
|
||||
| Sự kiện | Hành động |
|
||||
|---|---|
|
||||
| `src/assets/gallery/` > ~1GB hoặc build > 10 phút | Chuyển ảnh gốc sang R2 + biến gallery thành load từ R2 (kế hoạch ngủ trong ADR/backlog) |
|
||||
| Muốn viết trọn bài từ điện thoại thường xuyên | Xét lại Keystatic (ADR-04) |
|
||||
| `src/assets/gallery/` > ~1GB hoặc build > 10 phút | Album mới đã dùng ảnh R2 qua admin; chuyển dần album cũ sang `gallery-photos/<album>.json` |
|
||||
| Cổng Turnstile gây phiền / nghi chặn nhầm bot tốt | Kill switch: `GATE_MODE: "off"` (deploy). Kiểm Transform Rule `x-verified-bot` còn tồn tại (`wrangler tail`) |
|
||||
| Gần hết 5.000 biến đổi Images/tháng | Upload trùng không tốn thêm; nếu vẫn thiếu thì bật Images Paid ($0.50/1.000) — ghi vào `16` trước |
|
||||
| Muốn viết trọn bài từ điện thoại thường xuyên | Dùng admin `admin.poli0981.dev` (đã có) |
|
||||
| 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 |
|
||||
| Repo chuyển public | Bật CodeQL (free cho public) vào caller CI; kiểm tra lại EXIF toàn bộ ảnh lịch sử; xoá secret khỏi lịch sử nếu từng lỡ (không nên có) |
|
||||
| Đổi email/mất hộp thư đích | Cập nhật Email Routing + security.txt + legal contact ngay |
|
||||
| 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) |
|
||||
@@ -0,0 +1,6 @@
|
||||
Contact: mailto:security@poli0981.dev
|
||||
Contact: mailto:contact@poli0981.dev
|
||||
Expires: 2027-07-01T00:00:00Z
|
||||
Preferred-Languages: vi, en
|
||||
Canonical: https://poli0981.dev/.well-known/security.txt
|
||||
Policy: https://github.com/poli0981/poli0981-dev/blob/main/SECURITY.md
|
||||
@@ -5,7 +5,24 @@
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
X-Frame-Options: DENY
|
||||
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
|
||||
Content-Security-Policy: frame-ancestors 'none'
|
||||
|
||||
# The service worker must always revalidate so updates (bumped SHELL) propagate.
|
||||
/sw.js
|
||||
Cache-Control: no-cache
|
||||
|
||||
# Stable (unhashed) url so the SW can precache it by name — so it needs revalidation
|
||||
# for updates to land, same reasoning as sw.js.
|
||||
/skullhop.js
|
||||
Cache-Control: no-cache
|
||||
|
||||
# Turnstile gate client — unhashed url referenced from Worker-rendered markup, so it must
|
||||
# revalidate for fixes to reach visitors.
|
||||
/gate.js
|
||||
Cache-Control: no-cache
|
||||
|
||||
# RFC 9116 requires text/plain. Wrangler already infers it from the .txt extension at
|
||||
# upload time; this is belt-and-braces so a future asset-handling change can't break it.
|
||||
/.well-known/security.txt
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
Cache-Control: public, max-age=86400
|
||||
@@ -1,9 +1,9 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect width="32" height="32" rx="7" fill="#0d1117" />
|
||||
<rect width="32" height="32" rx="7" fill="#0b1220" />
|
||||
<path
|
||||
d="M3 16 H9 L11 9 L14 23 L17 11 L20 20 L23 16 H29"
|
||||
fill="none"
|
||||
stroke="#e8a33d"
|
||||
stroke="#2dd4bf"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
|
||||
|
Before Width: | Height: | Size: 305 B After Width: | Height: | Size: 305 B |
@@ -0,0 +1,77 @@
|
||||
// Turnstile gate client (served as a static file so the page's existing CSP — 'self' plus
|
||||
// challenges.cloudflare.com — allows it without a hash). Renders the widget, trades the
|
||||
// token for the 48-hour pass cookie at /api/gate, then reloads into the real page.
|
||||
// See src/lib/gate/render.ts for the markup this drives.
|
||||
(() => {
|
||||
const root = document.querySelector("[data-human-check]");
|
||||
if (!root) return;
|
||||
const status = root.querySelector(".human-check-status");
|
||||
const retry = root.querySelector(".human-check-retry");
|
||||
const say = (key) => {
|
||||
status.textContent = root.dataset[key] || "";
|
||||
};
|
||||
const offerRetry = () => {
|
||||
retry.hidden = false;
|
||||
};
|
||||
retry.addEventListener("click", () => location.reload());
|
||||
|
||||
// The theme actually on screen: an explicit choice on <html>, else the OS preference.
|
||||
const theme = () => {
|
||||
const chosen = document.documentElement.dataset.theme;
|
||||
if (chosen === "light" || chosen === "dark") return chosen;
|
||||
return matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
|
||||
};
|
||||
|
||||
const loadTurnstile = () =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (window.turnstile) return resolve(window.turnstile);
|
||||
const script = document.createElement("script");
|
||||
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
||||
script.async = true;
|
||||
script.onload = () =>
|
||||
window.turnstile ? resolve(window.turnstile) : reject(new Error("turnstile-missing"));
|
||||
script.onerror = () => reject(new Error("turnstile-load-failed"));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
|
||||
const verify = async (token) => {
|
||||
say("msgVerifying");
|
||||
try {
|
||||
const res = await fetch("/api/gate", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ token }),
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (res.status === 204) {
|
||||
say("msgOk");
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
say(res.status === 429 ? "msgSlowDown" : "msgError");
|
||||
} catch {
|
||||
say("msgError");
|
||||
}
|
||||
offerRetry();
|
||||
};
|
||||
|
||||
loadTurnstile()
|
||||
.then((turnstile) => {
|
||||
const id = turnstile.render("#human-check-widget", {
|
||||
sitekey: root.dataset.sitekey,
|
||||
action: "gate",
|
||||
language: root.dataset.lang,
|
||||
theme: theme(),
|
||||
callback: verify,
|
||||
"error-callback": () => {
|
||||
say("msgError");
|
||||
offerRetry();
|
||||
},
|
||||
"expired-callback": () => turnstile.reset(id),
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
say("msgLoadFailed");
|
||||
offerRetry();
|
||||
});
|
||||
})();
|
||||
@@ -1,14 +1,35 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
Disallow: /api/
|
||||
Disallow: /admin/
|
||||
|
||||
# AI-training crawlers — blocked (content is All Rights Reserved; mirrors the
|
||||
# Cloudflare "Block AI Scrapers" toggle, docs 06/07/13).
|
||||
User-agent: GPTBot
|
||||
User-agent: OAI-SearchBot
|
||||
User-agent: ChatGPT-User
|
||||
User-agent: CCBot
|
||||
User-agent: Google-Extended
|
||||
User-agent: anthropic-ai
|
||||
User-agent: ClaudeBot
|
||||
User-agent: Claude-Web
|
||||
User-agent: Claude-SearchBot
|
||||
User-agent: PerplexityBot
|
||||
User-agent: Perplexity-User
|
||||
User-agent: Applebot-Extended
|
||||
User-agent: Bytespider
|
||||
User-agent: Amazonbot
|
||||
User-agent: Meta-ExternalAgent
|
||||
User-agent: Meta-ExternalFetcher
|
||||
User-agent: FacebookBot
|
||||
User-agent: cohere-ai
|
||||
User-agent: Diffbot
|
||||
User-agent: ImagesiftBot
|
||||
User-agent: Omgilibot
|
||||
User-agent: Timpibot
|
||||
User-agent: AI2Bot
|
||||
User-agent: DuckAssistBot
|
||||
User-agent: MistralAI-User
|
||||
Disallow: /
|
||||
|
||||
Sitemap: https://poli0981.dev/sitemap-index.xml
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Skull Hop — the offline mini-game (docs 09 §4).
|
||||
*
|
||||
* Lives in public/ at a STABLE url rather than being bundled by Astro, because the
|
||||
* service worker precaches it by name. A hashed /_astro/ chunk could not be precached
|
||||
* (the filename changes every build) and the SW only warms those on first fetch — which
|
||||
* for a page nobody visits while online means the game would 404 exactly when needed.
|
||||
*
|
||||
* No sprite file for the same reason: one more thing to precache and to 404. The skull is
|
||||
* drawn from a pixel grid below, which also keeps it crisp at any DPR.
|
||||
*
|
||||
* Vanilla, no imports, no build step. Loaded with <script src defer> so CSP 'self' covers
|
||||
* it without a hash.
|
||||
*/
|
||||
(() => {
|
||||
const canvas = document.getElementById("skullhop");
|
||||
if (!(canvas instanceof HTMLCanvasElement)) return;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
|
||||
const startBtn = document.getElementById("skullhop-start");
|
||||
const scoreEl = document.getElementById("skullhop-score");
|
||||
const bestEl = document.getElementById("skullhop-best");
|
||||
|
||||
// A [0, 1) number from the platform CSPRNG. Overkill for spacing obstacles, but it costs
|
||||
// nothing and keeps the one predictable generator out of the codebase.
|
||||
const random = () => crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
|
||||
|
||||
const W = 320;
|
||||
const H = 120;
|
||||
const GROUND = H - 18;
|
||||
const KEY = "skullhop";
|
||||
|
||||
// 8x8 pixel skull. 1 = bone, 2 = eye socket / mouth gap.
|
||||
const SKULL = [
|
||||
[0, 1, 1, 1, 1, 1, 1, 0],
|
||||
[1, 1, 1, 1, 1, 1, 1, 1],
|
||||
[1, 2, 2, 1, 1, 2, 2, 1],
|
||||
[1, 2, 2, 1, 1, 2, 2, 1],
|
||||
[1, 1, 1, 2, 2, 1, 1, 1],
|
||||
[1, 1, 1, 1, 1, 1, 1, 1],
|
||||
[0, 1, 2, 1, 2, 1, 2, 1],
|
||||
[0, 1, 1, 1, 1, 1, 1, 0],
|
||||
];
|
||||
|
||||
const css = (name, fallback) =>
|
||||
getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
|
||||
|
||||
// Palette colours (src/lib/palette.ts, dark values as the fallback). Read again on every
|
||||
// start, so a theme that followed the OS while the page was open is picked up.
|
||||
let bone, accent, line, muted;
|
||||
function readPalette() {
|
||||
bone = css("--text", "#e6edf5");
|
||||
accent = css("--accent", "#2dd4bf");
|
||||
line = css("--line", "#223047");
|
||||
muted = css("--muted", "#94a3b8");
|
||||
}
|
||||
readPalette();
|
||||
|
||||
let best = 0;
|
||||
try {
|
||||
best = Number(localStorage.getItem(KEY)) || 0;
|
||||
} catch {
|
||||
/* private mode — best score just won't persist */
|
||||
}
|
||||
if (bestEl) bestEl.textContent = String(best);
|
||||
|
||||
let running = false;
|
||||
let raf = 0;
|
||||
let y = 0; // height above ground
|
||||
let vy = 0;
|
||||
let score = 0;
|
||||
let speed = 1.6;
|
||||
let bars = [];
|
||||
let t = 0;
|
||||
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
canvas.width = W * dpr;
|
||||
canvas.height = H * dpr;
|
||||
ctx.scale(dpr, dpr);
|
||||
ctx.imageSmoothingEnabled = false;
|
||||
|
||||
function drawSkull(px, py, size) {
|
||||
for (let r = 0; r < 8; r++) {
|
||||
for (let c = 0; c < 8; c++) {
|
||||
const v = SKULL[r][c];
|
||||
if (!v) continue;
|
||||
ctx.fillStyle = v === 1 ? bone : line;
|
||||
ctx.fillRect(px + c * size, py + r * size, size, size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function reset() {
|
||||
readPalette();
|
||||
y = 0;
|
||||
vy = 0;
|
||||
score = 0;
|
||||
speed = 1.6;
|
||||
t = 0;
|
||||
bars = [];
|
||||
if (scoreEl) scoreEl.textContent = "0";
|
||||
}
|
||||
|
||||
function jump() {
|
||||
if (!running) {
|
||||
start();
|
||||
return;
|
||||
}
|
||||
if (y === 0) vy = 4.6;
|
||||
}
|
||||
|
||||
function gameOver() {
|
||||
running = false;
|
||||
cancelAnimationFrame(raf);
|
||||
if (score > best) {
|
||||
best = score;
|
||||
try {
|
||||
localStorage.setItem(KEY, String(best));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
if (bestEl) bestEl.textContent = String(best);
|
||||
}
|
||||
if (startBtn) {
|
||||
startBtn.hidden = false;
|
||||
startBtn.textContent = startBtn.dataset.again || "Again";
|
||||
startBtn.focus();
|
||||
}
|
||||
ctx.fillStyle = muted;
|
||||
ctx.font = "10px ui-monospace, monospace";
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillText(canvas.dataset.over || "Game over", W / 2, 28);
|
||||
}
|
||||
|
||||
function frame() {
|
||||
t += 1;
|
||||
speed += 0.0016; // ramps up, docs 09 §4
|
||||
|
||||
// physics
|
||||
vy -= 0.26;
|
||||
y += vy;
|
||||
if (y <= 0) {
|
||||
y = 0;
|
||||
vy = 0;
|
||||
}
|
||||
|
||||
// spawn waveform bars with a gap that stays clearable
|
||||
const last = bars[bars.length - 1];
|
||||
if (!last || last.x < W - (90 + random() * 70)) {
|
||||
bars.push({ x: W + 8, h: 10 + random() * 16 });
|
||||
}
|
||||
for (const b of bars) b.x -= speed;
|
||||
if (bars.length && bars[0].x < -12) {
|
||||
bars.shift();
|
||||
score += 1;
|
||||
if (scoreEl) scoreEl.textContent = String(score);
|
||||
}
|
||||
|
||||
// draw
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
|
||||
// ground
|
||||
ctx.fillStyle = line;
|
||||
ctx.fillRect(0, GROUND + 10, W, 1);
|
||||
|
||||
// background waveline, the site motif
|
||||
ctx.strokeStyle = line;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
for (let x = 0; x <= W; x += 4) {
|
||||
const yy = 30 + Math.sin((x + t * 1.5) / 22) * 6;
|
||||
if (x === 0) ctx.moveTo(x, yy);
|
||||
else ctx.lineTo(x, yy);
|
||||
}
|
||||
ctx.stroke();
|
||||
|
||||
// obstacles
|
||||
ctx.fillStyle = accent;
|
||||
for (const b of bars) ctx.fillRect(b.x, GROUND + 10 - b.h, 5, b.h);
|
||||
|
||||
// skull
|
||||
const sx = 34;
|
||||
const sy = GROUND + 10 - 16 - y;
|
||||
drawSkull(sx, sy, 2);
|
||||
|
||||
// collision — skull box is 16x16 at (sx, sy)
|
||||
for (const b of bars) {
|
||||
if (b.x < sx + 15 && b.x + 5 > sx && GROUND + 10 - b.h < sy + 16) {
|
||||
gameOver();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
raf = requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
function start() {
|
||||
reset();
|
||||
running = true;
|
||||
if (startBtn) startBtn.hidden = true;
|
||||
raf = requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
// Idle frame so the canvas is never blank before the first play.
|
||||
function idle() {
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
ctx.fillStyle = line;
|
||||
ctx.fillRect(0, GROUND + 10, W, 1);
|
||||
drawSkull(34, GROUND - 6, 2);
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.code === "Space" || e.code === "ArrowUp") {
|
||||
const el = e.target;
|
||||
if (el instanceof HTMLElement && (el.tagName === "INPUT" || el.isContentEditable)) return;
|
||||
e.preventDefault();
|
||||
jump();
|
||||
}
|
||||
});
|
||||
canvas.addEventListener("pointerdown", (e) => {
|
||||
e.preventDefault();
|
||||
jump();
|
||||
});
|
||||
startBtn?.addEventListener("click", start);
|
||||
|
||||
idle();
|
||||
|
||||
// docs 09 §4: reduced motion means it must not start on its own. It never does —
|
||||
// the button is always the entry point — but this keeps the canvas static and makes
|
||||
// the intent explicit rather than incidental.
|
||||
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches && startBtn) {
|
||||
startBtn.hidden = false;
|
||||
}
|
||||
})();
|
||||
@@ -5,9 +5,15 @@
|
||||
*
|
||||
* Bump SHELL when the offline page or this file changes so clients update.
|
||||
*/
|
||||
const SHELL = "shell-v1";
|
||||
const SHELL = "shell-v4";
|
||||
const OFFLINE = "/offline/";
|
||||
const PRECACHE = [OFFLINE, "/favicon.svg"];
|
||||
// skullhop.js is precached by name rather than warmed like /_astro/*: it only loads on
|
||||
// the offline page, which nobody visits while online, so warm-on-fetch would never fire
|
||||
// and the game would 404 in the one situation it exists for.
|
||||
const PRECACHE = [OFFLINE, "/favicon.svg", "/skullhop.js"];
|
||||
// Hashed assets from older deploys are never requested again; cap the warm cache so it
|
||||
// can't grow by a deploy's worth of files forever. Oldest entries go first.
|
||||
const MAX_WARM_ASSETS = 80;
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
event.waitUntil(
|
||||
@@ -27,6 +33,16 @@ self.addEventListener("activate", (event) => {
|
||||
);
|
||||
});
|
||||
|
||||
/** Drop the oldest warmed /_astro/* entries beyond MAX_WARM_ASSETS (keys keep insert order). */
|
||||
async function trimWarmAssets(cache) {
|
||||
const assets = (await cache.keys()).filter((request) =>
|
||||
new URL(request.url).pathname.startsWith("/_astro/"),
|
||||
);
|
||||
const excess = assets.length - MAX_WARM_ASSETS;
|
||||
if (excess > 0)
|
||||
await Promise.all(assets.slice(0, excess).map((request) => cache.delete(request)));
|
||||
}
|
||||
|
||||
self.addEventListener("fetch", (event) => {
|
||||
const { request } = event;
|
||||
if (request.method !== "GET") return;
|
||||
@@ -44,16 +60,16 @@ self.addEventListener("fetch", (event) => {
|
||||
// never need to know the hashed filenames at build time).
|
||||
if (url.pathname.startsWith("/_astro/")) {
|
||||
event.respondWith(
|
||||
caches.open(SHELL).then((cache) =>
|
||||
cache.match(request).then(
|
||||
(hit) =>
|
||||
hit ||
|
||||
fetch(request).then((res) => {
|
||||
if (res.ok) cache.put(request, res.clone());
|
||||
return res;
|
||||
}),
|
||||
),
|
||||
),
|
||||
caches.open(SHELL).then(async (cache) => {
|
||||
const hit = await cache.match(request);
|
||||
if (hit) return hit;
|
||||
const res = await fetch(request);
|
||||
if (res.ok) {
|
||||
// Keep the worker alive until the copy is stored (and the cache trimmed).
|
||||
event.waitUntil(cache.put(request, res.clone()).then(() => trimWarmAssets(cache)));
|
||||
}
|
||||
return res;
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
# JetBrains Qodana — run by .github/workflows/qodana.yml on every PR and on main
|
||||
# (docs 08 §0). Reference: https://www.jetbrains.com/help/qodana/configuration-reference.html
|
||||
#
|
||||
# Qodana for JS is WebStorm's inspection engine. It reads .ts/.js/.mjs, CSS, JSON, YAML and
|
||||
# Markdown — not .astro or .svelte, which stay with astro check, eslint-plugin-astro/-svelte
|
||||
# and Prettier in ci.yml.
|
||||
version: "1.0"
|
||||
linter: qodana-js
|
||||
|
||||
# Native mode: the workflow sets up Node from .nvmrc and runs `npm ci` itself, so the analysis
|
||||
# resolves the same Node 26 and node_modules as the build (the Docker image ships its own Node).
|
||||
withinDocker: false
|
||||
|
||||
# Quality gate: the first run's 11 findings were fixed or, for one inspection, switched off
|
||||
# below with the reason, so any problem now is a new one and turns the check red.
|
||||
failThreshold: 0
|
||||
|
||||
profile:
|
||||
name: qodana.recommended
|
||||
inspections:
|
||||
# Not source code: build output, coverage, generated types, the content submodule (prose,
|
||||
# in its own repo), the design docs and the frontmatter templates.
|
||||
- group: ALL
|
||||
ignore:
|
||||
- "dist/**"
|
||||
- "coverage/**"
|
||||
- ".astro/**"
|
||||
- ".wrangler/**"
|
||||
- "src/content/**"
|
||||
- "poli0981.dev-docs/**"
|
||||
- "docs/templates/**"
|
||||
- "public/pagefind/**"
|
||||
- "worker-configuration.d.ts"
|
||||
- "workers/widgets/worker-configuration.d.ts"
|
||||
# Prose checkers don't read Vietnamese: every other word of the bilingual UI strings,
|
||||
# comments and docs would be a "typo".
|
||||
- inspection: SpellCheckingInspection
|
||||
enabled: false
|
||||
- inspection: GrazieInspection
|
||||
enabled: false
|
||||
# "Import can be shortened" wants tsconfig's `@/` alias or extensionless paths. The build
|
||||
# scripts and astro.config.mjs run under plain Node, where `@/` doesn't resolve and a
|
||||
# TypeScript import needs its `.ts`; in src/ relative vs alias imports are a style choice.
|
||||
- inspection: ES6PreferShortImport
|
||||
enabled: false
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* CSP guard: every inline <script> in the built HTML must be covered by a hash in that
|
||||
* page's own Content-Security-Policy meta tag.
|
||||
*
|
||||
* Astro hashes the scripts it controls, but NOT `is:inline` ones — see
|
||||
* core/csp/common.js `trackScriptHashes()`, which only walks bundled scripts, client
|
||||
* directives, island prebuilts, and `settings.scripts` (the `injectScript()` hook).
|
||||
* An `is:inline` script therefore ships unhashed and is blocked wherever it appears
|
||||
* after the meta tag in document order. That is exactly how /500 and /429 shipped with
|
||||
* dead scripts, and how the theme bootstrap survived only by sitting *before* the meta.
|
||||
*
|
||||
* Run after `astro build`. Exits non-zero and names the offender. Every built page must carry
|
||||
* a CSP meta tag, and at least one page must have been checked: a guard whose selector stops
|
||||
* matching would otherwise report "ok — 0 pages" and pass.
|
||||
*
|
||||
* JSON-LD blocks are skipped on purpose: `script-src` does not apply to non-executable
|
||||
* data blocks, and Astro deliberately leaves them unhashed.
|
||||
*/
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const ROOT = "dist/client";
|
||||
// Attribute order and quoting are the HTML author's choice, so the CSP meta is found tag by
|
||||
// tag: any <meta> whose http-equiv is content-security-policy, content in either quote style.
|
||||
const META_TAG = /<meta\b[^>]*>/gi;
|
||||
const IS_CSP = /\bhttp-equiv\s*=\s*["']?content-security-policy["'\s>]/i;
|
||||
const CONTENT = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
|
||||
// Matches what a *browser* executes, not what Astro happens to emit. This guard exists to
|
||||
// notice scripts nobody expected, so a matcher that only recognises the tidy form reports
|
||||
// "all clear" on exactly the surprise it was built to catch. Following HTML's tag grammar:
|
||||
// /i `<SCRIPT>` runs just fine
|
||||
// (\s[^>]*)? after the tag name, either `>` or whitespace-then-anything. Requiring
|
||||
// the whitespace is what stops `<scripting>` matching.
|
||||
// <\/script(\s[^>]*)?> end tags take the same shape — `</script >` and even
|
||||
// `</script foo>` are valid end tags whose attributes the parser discards.
|
||||
// CodeQL js/bad-tag-filter found three separate holes here, one patch at a time, so the
|
||||
// cases below are now asserted on every run instead of being re-reasoned from scratch.
|
||||
const SCRIPT = /<script(\s[^>]*)?>([\s\S]*?)<\/script(\s[^>]*)?>/gi;
|
||||
const JSON_LD = /type=["']?application\/ld\+json/i;
|
||||
// Inline <style> blocks need their hash in the policy just the same, and Astro misses some:
|
||||
// the styles of a component rendered only from MDX content (Callout) shipped unhashed, so the
|
||||
// browser dropped them. A style *attribute* can never pass a policy without 'unsafe-inline'.
|
||||
const STYLE = /<style(\s[^>]*)?>([\s\S]*?)<\/style(\s[^>]*)?>/gi;
|
||||
const STYLE_ATTR = /<[a-z][\w-]*\s(?:[^>]*?\s)?style\s*=/gi;
|
||||
|
||||
/** Tag forms a browser executes (or doesn't). Asserted before every real run. */
|
||||
const SELFTEST = [
|
||||
["<script>X</script>", true, "plain"],
|
||||
["<SCRIPT>X</SCRIPT>", true, "uppercase"],
|
||||
["<ScRiPt>X</ScRiPt>", true, "mixed case"],
|
||||
["<script defer>X</script>", true, "with attributes"],
|
||||
['<script type="module">X</script>', true, "typed"],
|
||||
["<script\n defer\n>X</script>", true, "newlines in the start tag"],
|
||||
["<script>X</script >", true, "space before the end-tag close"],
|
||||
["<script>X</script\t\n bar>", true, "end tag with junk (HTML discards it)"],
|
||||
["<scripting>X</scripting>", false, "different element, must not match"],
|
||||
["<noscript>X</noscript>", false, "different element, must not match"],
|
||||
];
|
||||
|
||||
/** CSP meta forms the guard must read, and the policy it must find in each. */
|
||||
const META_SELFTEST = [
|
||||
['<meta http-equiv="content-security-policy" content="a">', "a"],
|
||||
["<META CONTENT='b' HTTP-EQUIV='Content-Security-Policy'>", "b"],
|
||||
['<meta content="c" http-equiv=content-security-policy>', "c"],
|
||||
['<meta name="description" content="d">', null],
|
||||
];
|
||||
|
||||
function selftest() {
|
||||
const failures = SELFTEST.filter(([html, shouldMatch]) => {
|
||||
SCRIPT.lastIndex = 0;
|
||||
return SCRIPT.test(html) !== shouldMatch;
|
||||
}).map(
|
||||
([html, shouldMatch, label]) =>
|
||||
`${label}: expected ${shouldMatch ? "match" : "no match"} for ${html}`,
|
||||
);
|
||||
for (const [html, expected] of META_SELFTEST) {
|
||||
if (cspOf(html) !== expected) failures.push(`CSP meta: expected ${expected} for ${html}`);
|
||||
}
|
||||
for (const [html, shouldMatch] of [
|
||||
["<style>X</style>", true],
|
||||
["<STYLE media=screen>X</style >", true],
|
||||
["<stylesheet>X</stylesheet>", false],
|
||||
]) {
|
||||
STYLE.lastIndex = 0;
|
||||
if (STYLE.test(html) !== shouldMatch) failures.push(`style block: wrong result for ${html}`);
|
||||
}
|
||||
for (const [html, shouldMatch] of [
|
||||
['<p style="color:red">', true],
|
||||
["<svg viewBox='0 0 1 1' style=x>", true],
|
||||
['<meta content="style-src x">', false],
|
||||
['<p data-style="x">', false],
|
||||
]) {
|
||||
STYLE_ATTR.lastIndex = 0;
|
||||
if (STYLE_ATTR.test(html) !== shouldMatch)
|
||||
failures.push(`style attribute: wrong result for ${html}`);
|
||||
}
|
||||
if (failures.length > 0) {
|
||||
console.error("CSP guard SELFTEST FAILED — a matcher is wrong:\n");
|
||||
for (const failure of failures) console.error(` ${failure}`);
|
||||
console.error("\nA guard that mis-parses script tags silently passes the very thing it");
|
||||
console.error("is meant to catch. Fix the pattern before trusting any 'ok' below.");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/** The page's CSP meta content, or null when it has none. */
|
||||
function cspOf(html) {
|
||||
for (const [tag] of html.matchAll(META_TAG)) {
|
||||
if (!IS_CSP.test(tag)) continue;
|
||||
const content = CONTENT.exec(tag);
|
||||
if (content) return content[1] ?? content[2];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function htmlFiles(dir) {
|
||||
const out = [];
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) out.push(...htmlFiles(full));
|
||||
else if (entry.name.endsWith(".html")) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
selftest();
|
||||
|
||||
const offenders = [];
|
||||
const withoutCsp = [];
|
||||
let pages = 0;
|
||||
let scripts = 0;
|
||||
let styles = 0;
|
||||
|
||||
for (const file of htmlFiles(ROOT)) {
|
||||
const html = readFileSync(file, "utf8");
|
||||
const csp = cspOf(html);
|
||||
if (csp === null) {
|
||||
withoutCsp.push(file);
|
||||
continue;
|
||||
}
|
||||
pages += 1;
|
||||
|
||||
const declared = new Set([...csp.matchAll(/sha256-[A-Za-z0-9+/=]+/g)].map((m) => m[0]));
|
||||
|
||||
for (const match of html.matchAll(SCRIPT)) {
|
||||
const [, attrs, body] = match;
|
||||
if (!body.trim() || JSON_LD.test(attrs)) continue;
|
||||
scripts += 1;
|
||||
const hash = `sha256-${createHash("sha256").update(body, "utf8").digest("base64")}`;
|
||||
if (!declared.has(hash)) {
|
||||
offenders.push({ file, hash, preview: body.trim().slice(0, 80) });
|
||||
}
|
||||
}
|
||||
|
||||
for (const [, , body] of html.matchAll(STYLE)) {
|
||||
styles += 1;
|
||||
const hash = `sha256-${createHash("sha256").update(body, "utf8").digest("base64")}`;
|
||||
if (!declared.has(hash)) {
|
||||
offenders.push({ file, hash, preview: `<style> ${body.trim().slice(0, 72)}` });
|
||||
}
|
||||
}
|
||||
for (const [tag] of html.matchAll(STYLE_ATTR)) {
|
||||
offenders.push({ file, hash: "style attribute", preview: tag.slice(0, 80) });
|
||||
}
|
||||
}
|
||||
|
||||
if (pages === 0) {
|
||||
console.error(`CSP check FAILED — no page under ${ROOT} has a CSP meta tag (built at all?).`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (withoutCsp.length > 0) {
|
||||
console.error(`CSP check FAILED — ${withoutCsp.length} page(s) ship without a CSP meta tag:\n`);
|
||||
for (const file of withoutCsp) console.error(` ${file}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (offenders.length > 0) {
|
||||
console.error(`CSP check FAILED — ${offenders.length} inline script(s)/style(s) not allowed:\n`);
|
||||
for (const o of offenders) {
|
||||
console.error(` ${o.file}\n ${o.hash}\n ${o.preview}...\n`);
|
||||
}
|
||||
console.error(
|
||||
"Fix: prefer a processed <script> (Astro bundles + hashes it), or for code that must\n" +
|
||||
"run inline before paint, add it via injectScript('head-inline', ...) in astro.config.mjs.\n" +
|
||||
"For styles: move the rules into a stylesheet the page always loads (src/styles/*.css)\n" +
|
||||
"and replace style attributes with classes.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(
|
||||
`CSP check ok — ${scripts} inline scripts and ${styles} style blocks across ${pages} pages, all hashed.`,
|
||||
);
|
||||
@@ -1,26 +1,34 @@
|
||||
// CI gate: fail the build if any CHANGED image under src/assets/ carries GPS or a
|
||||
// camera serial number. Backs up the manual strip-exif discipline (docs 04 §6 / 08 §5).
|
||||
// Usage: node scripts/check-exif.mjs --changed (DIFF_BASE env set by CI; falls back to HEAD~1)
|
||||
// CI gate: fail the build if an image under src/assets/ carries GPS or a camera serial
|
||||
// number. Backs up the manual strip-exif discipline (docs 04 §6 / 08 §5).
|
||||
//
|
||||
// node scripts/check-exif.mjs every image under src/assets/
|
||||
// node scripts/check-exif.mjs --changed only images changed since DIFF_BASE (set by CI;
|
||||
// falls back to HEAD~1, then to every image)
|
||||
import { execSync } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import exifr from "exifr";
|
||||
|
||||
const sh = (cmd) => execSync(cmd, { encoding: "utf8" }).trim();
|
||||
// core.quotePath=false: git otherwise prints non-ASCII paths (Vietnamese file names) quoted
|
||||
// and octal-escaped, which then never match the src/assets/ filter and were silently skipped.
|
||||
const sh = (cmd) => execSync(`git -c core.quotePath=false ${cmd}`, { encoding: "utf8" }).trim();
|
||||
const IMG = /\.(jpe?g|png|webp|avif)$/i;
|
||||
|
||||
function changedImages() {
|
||||
function changedRange() {
|
||||
const base = process.env.DIFF_BASE;
|
||||
let range = null;
|
||||
if (base && !/^0+$/.test(base)) {
|
||||
range = `${base} HEAD`;
|
||||
} else {
|
||||
try {
|
||||
sh("git rev-parse HEAD~1");
|
||||
range = "HEAD~1 HEAD";
|
||||
} catch {
|
||||
range = null;
|
||||
}
|
||||
if (base && !/^0+$/.test(base)) return `${base} HEAD`;
|
||||
try {
|
||||
sh("rev-parse --verify --quiet HEAD~1");
|
||||
return "HEAD~1 HEAD";
|
||||
} catch {
|
||||
return null; // a single-commit history: check everything
|
||||
}
|
||||
const out = range ? sh(`git diff --name-only ${range}`) : sh("git ls-files src/assets");
|
||||
}
|
||||
|
||||
function images() {
|
||||
const range = process.argv.includes("--changed") ? changedRange() : null;
|
||||
const out = range
|
||||
? sh(`diff --name-only --diff-filter=d ${range} -- src/assets`)
|
||||
: sh("ls-files src/assets");
|
||||
return out
|
||||
.split("\n")
|
||||
.map((f) => f.trim())
|
||||
@@ -29,14 +37,24 @@ function changedImages() {
|
||||
|
||||
const SERIAL = ["SerialNumber", "BodySerialNumber", "LensSerialNumber"];
|
||||
const offenders = [];
|
||||
const files = images();
|
||||
|
||||
for (const file of changedImages()) {
|
||||
const gps = await exifr.gps(file).catch(() => null);
|
||||
const meta = await exifr.parse(file, { pick: ["Make", "Model", ...SERIAL] }).catch(() => null);
|
||||
const hasGps = gps && (gps.latitude != null || gps.longitude != null);
|
||||
const hasSerial = meta && SERIAL.some((k) => meta[k]);
|
||||
if (hasGps || hasSerial) {
|
||||
offenders.push(`${file}${hasGps ? " [GPS]" : ""}${hasSerial ? " [serial]" : ""}`);
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Hand exifr the bytes, not the path: its own file reader throws on current Node ("The
|
||||
// options argument must be of type object"), and the old .catch(() => null) turned that
|
||||
// into "no EXIF" — the check passed every image without reading one.
|
||||
const bytes = await readFile(file);
|
||||
const gps = await exifr.gps(bytes);
|
||||
const meta = await exifr.parse(bytes, { pick: ["Make", "Model", ...SERIAL] });
|
||||
const hasGps = gps && (gps.latitude != null || gps.longitude != null);
|
||||
const hasSerial = meta && SERIAL.some((k) => meta[k]);
|
||||
if (hasGps || hasSerial) {
|
||||
offenders.push(`${file}${hasGps ? " [GPS]" : ""}${hasSerial ? " [serial]" : ""}`);
|
||||
}
|
||||
} catch (error) {
|
||||
// An image exifr can't read is an image nobody verified — fail rather than wave it on.
|
||||
offenders.push(`${file} [unreadable: ${error instanceof Error ? error.message : error}]`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,4 +63,4 @@ if (offenders.length) {
|
||||
for (const o of offenders) console.error(" " + o);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("EXIF check passed.");
|
||||
console.log(`EXIF check passed (${files.length} image${files.length === 1 ? "" : "s"}).`);
|
||||
@@ -0,0 +1,29 @@
|
||||
// Supply-chain alarm (docs 06 §6): every package in the lockfile that ships an install script
|
||||
// must be on package.json#allowScripts.
|
||||
//
|
||||
// Locally, npm enforces this itself (.npmrc strict-allow-scripts): an unreviewed postinstall
|
||||
// fails the install. CI installs with --ignore-scripts, where that check never runs — so a
|
||||
// dependency that suddenly grows a postinstall (the Shai-Hulud worm shape) would slip through
|
||||
// unnoticed. This keeps the alarm on in CI, without ever running the script.
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const pkg = JSON.parse(readFileSync("package.json", "utf8"));
|
||||
const lock = JSON.parse(readFileSync("package-lock.json", "utf8"));
|
||||
const allowed = new Set(Object.keys(pkg.allowScripts ?? {}));
|
||||
|
||||
const unreviewed = [];
|
||||
for (const [path, entry] of Object.entries(lock.packages ?? {})) {
|
||||
if (!entry.hasInstallScript || !path) continue;
|
||||
const name = path.slice(path.lastIndexOf("node_modules/") + "node_modules/".length);
|
||||
if (!allowed.has(name)) unreviewed.push(`${name}@${entry.version}`);
|
||||
}
|
||||
|
||||
if (unreviewed.length > 0) {
|
||||
console.error("Packages with an install script that is not on package.json#allowScripts:");
|
||||
for (const item of unreviewed) console.error(` ${item}`);
|
||||
console.error(
|
||||
"\nReview the script, then allow it locally with `npm approve-scripts <pkg>` (or remove the dependency).",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`install scripts ok — all allow-listed (${[...allowed].join(", ")}).`);
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Licence check over the whole dependency tree. CI runs it in the `build` job (docs 08 §6).
|
||||
*
|
||||
* node scripts/check-licenses.mjs
|
||||
*
|
||||
* gen-notices.mjs writes THIRD-PARTY-NOTICES.md from the direct dependencies only (what is
|
||||
* installed differs per platform, and that file must not). This check reads package-lock.json
|
||||
* instead, which records the declared licence of EVERY package — transitive ones and each
|
||||
* platform's binaries included — so it gives the same answer on Windows and on Linux CI, with
|
||||
* nothing installed.
|
||||
*
|
||||
* A package passes when its licence expression is satisfied by ALLOWED, or by the one licence
|
||||
* its REVIEWED entry clears (scripts/license-policy.mjs). A package with no licence, or one
|
||||
* that is not an SPDX expression, fails. So does a REVIEWED entry that no longer matches any
|
||||
* package: the list should say what is actually in the tree.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { ALLOWED, REVIEWED, reviewFor, satisfies } from "./license-policy.mjs";
|
||||
|
||||
const PREFIX = "node_modules/";
|
||||
const lock = JSON.parse(readFileSync("package-lock.json", "utf8"));
|
||||
|
||||
/** null when the package is fine, "reviewed" when its REVIEWED entry clears it, else why not. */
|
||||
function verdict(name, license) {
|
||||
if (!license) return "declares no licence";
|
||||
try {
|
||||
if (satisfies(license, ALLOWED)) return null;
|
||||
const review = reviewFor(name);
|
||||
if (review && satisfies(license, new Set([...ALLOWED, review.license]))) return "reviewed";
|
||||
return `${license} is outside the policy`;
|
||||
} catch (error) {
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
const problems = new Set();
|
||||
const byName = (a, b) => a.localeCompare(b);
|
||||
const reviewed = new Set();
|
||||
const usedReviews = new Set();
|
||||
let total = 0;
|
||||
|
||||
for (const [path, entry] of Object.entries(lock.packages ?? {})) {
|
||||
// "" is this project; anything without node_modules/ would be a workspace or a link.
|
||||
if (!path.includes(PREFIX) || entry.link) continue;
|
||||
const name = path.slice(path.lastIndexOf(PREFIX) + PREFIX.length);
|
||||
total++;
|
||||
const result = verdict(name, entry.license);
|
||||
if (result === "reviewed") {
|
||||
reviewed.add(name);
|
||||
usedReviews.add(reviewFor(name));
|
||||
} else if (result) {
|
||||
problems.add(`${name}@${entry.version}: ${result}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of REVIEWED) {
|
||||
if (!usedReviews.has(entry)) {
|
||||
problems.add(`REVIEWED entry for ${entry.packages.join(", ")} matches no package — remove it`);
|
||||
}
|
||||
}
|
||||
|
||||
if (problems.size > 0) {
|
||||
console.error(`Licence check failed (${problems.size}):`);
|
||||
for (const problem of [...problems].sort(byName)) console.error(` ${problem}`);
|
||||
console.error(
|
||||
"Clear a package in REVIEWED (scripts/license-policy.mjs) with a reason, or drop it.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(
|
||||
`licences ok — ${total} packages in package-lock.json; cleared by review: ` +
|
||||
`${reviewed.size} (${[...reviewed].sort(byName).join(", ")})`,
|
||||
);
|
||||
@@ -1,51 +0,0 @@
|
||||
// Generate EXIF-clean placeholder images for the demo gallery album.
|
||||
// One-off helper: run `npm run gen-demo-gallery`, commit the output JPGs.
|
||||
// Replace src/assets/gallery/demo/ with real photos later (run strip-exif on them).
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import sharp from "sharp";
|
||||
|
||||
const OUT = "src/assets/gallery/demo";
|
||||
await mkdir(OUT, { recursive: true });
|
||||
|
||||
const W = 1600;
|
||||
const H = 1067; // 3:2
|
||||
// Base colours (ink-night → accent hues), matching the site palette mood.
|
||||
const HUES = [
|
||||
[31, 111, 235],
|
||||
[46, 160, 67],
|
||||
[219, 109, 40],
|
||||
[139, 92, 246],
|
||||
[217, 70, 90],
|
||||
];
|
||||
|
||||
for (let i = 0; i < HUES.length; i++) {
|
||||
const [r, g, b] = HUES[i];
|
||||
const buf = Buffer.alloc(W * H * 3);
|
||||
for (let y = 0; y < H; y++) {
|
||||
const t = y / H; // vertical fade toward near-black
|
||||
const rr = Math.round(r * (1 - t * 0.78) + 13 * t);
|
||||
const gg = Math.round(g * (1 - t * 0.78) + 17 * t);
|
||||
const bb = Math.round(b * (1 - t * 0.78) + 23 * t);
|
||||
for (let x = 0; x < W; x++) {
|
||||
const o = (y * W + x) * 3;
|
||||
buf[o] = rr;
|
||||
buf[o + 1] = gg;
|
||||
buf[o + 2] = bb;
|
||||
}
|
||||
}
|
||||
const label = String(i + 1).padStart(2, "0");
|
||||
const svg = Buffer.from(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}">` +
|
||||
`<text x="50%" y="53%" font-family="sans-serif" font-size="240" font-weight="700" ` +
|
||||
`fill="#ffffff" fill-opacity="0.88" text-anchor="middle">${label}</text></svg>`,
|
||||
);
|
||||
const file = join(OUT, `demo-${label}.jpg`);
|
||||
// sharp writes no metadata unless asked → EXIF-clean by construction.
|
||||
await sharp(buf, { raw: { width: W, height: H, channels: 3 } })
|
||||
.composite([{ input: svg }])
|
||||
.jpeg({ quality: 82 })
|
||||
.toFile(file);
|
||||
console.log(`wrote ${file}`);
|
||||
}
|
||||
console.log(`done: ${HUES.length} placeholder image(s)`);
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* Generate the package table in THIRD-PARTY-NOTICES.md from the lockfile (docs 08 §6).
|
||||
*
|
||||
* node scripts/gen-notices.mjs rewrite the generated block
|
||||
* node scripts/gen-notices.mjs --check fail if the file is out of date (CI)
|
||||
*
|
||||
* The file is split the way docs 12 describes: hand-written framing outside the
|
||||
* BEGIN/END markers, machine-generated table inside. Only the inside is touched.
|
||||
*
|
||||
* Licenses are read from each installed package's own package.json rather than via
|
||||
* `license-checker`. Same source of truth, one less dependency to vet — which is the
|
||||
* point of the exercise.
|
||||
*
|
||||
* Any license outside the shared policy's ALLOWED list is reported. That is deliberately
|
||||
* noisy: an unexpected license is exactly the thing a human should look at, so it fails rather
|
||||
* than being quietly folded into the table. Cleared packages go in REVIEWED with a reason
|
||||
* (scripts/license-policy.mjs, shared with check-licenses.mjs, which covers the whole tree).
|
||||
*
|
||||
* The block holds nothing that changes on a routine version bump (no versions, no package
|
||||
* count): it used to print the size of the resolved tree, so every Dependabot PR that added
|
||||
* or dropped one transitive package failed CI here.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
||||
import { ALLOWED, reviewFor, satisfies } from "./license-policy.mjs";
|
||||
|
||||
const NOTICES = "THIRD-PARTY-NOTICES.md";
|
||||
const BEGIN = "<!-- BEGIN GENERATED — edit scripts/gen-notices.mjs, not this block -->";
|
||||
const END = "<!-- END GENERATED -->";
|
||||
|
||||
/** Whether a license expression passes without review; an unparseable one never does. */
|
||||
function allowedOutright(license) {
|
||||
try {
|
||||
return satisfies(license, ALLOWED);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the package's REVIEWED entry clears its license. */
|
||||
function clearedByReview(name, license) {
|
||||
const review = reviewFor(name);
|
||||
if (!review) return false;
|
||||
try {
|
||||
return satisfies(license, new Set([...ALLOWED, review.license]));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function licenseOf(name) {
|
||||
const p = `node_modules/${name}/package.json`;
|
||||
if (!existsSync(p)) return null;
|
||||
const pkg = JSON.parse(readFileSync(p, "utf8"));
|
||||
if (typeof pkg.license === "string") return pkg.license;
|
||||
if (pkg.license?.type) return pkg.license.type;
|
||||
if (Array.isArray(pkg.licenses)) return pkg.licenses.map((l) => l.type ?? l).join(" OR ");
|
||||
return null;
|
||||
}
|
||||
|
||||
const pkg = JSON.parse(readFileSync("package.json", "utf8"));
|
||||
const lock = JSON.parse(readFileSync("package-lock.json", "utf8"));
|
||||
|
||||
const direct = [
|
||||
...Object.keys(pkg.dependencies ?? {}).map((n) => ({ name: n, kind: "runtime" })),
|
||||
...Object.keys(pkg.devDependencies ?? {}).map((n) => ({ name: n, kind: "build" })),
|
||||
].sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
// Deterministic by construction. Licenses are read from disk, but which packages are ON
|
||||
// disk varies by platform: the lockfile carries every `@img/sharp-*` / `*-msvc` variant
|
||||
// and npm installs only the matching one. Surveying installed packages would therefore
|
||||
// generate a different file on Windows and on Linux CI, and `--check` would fail forever.
|
||||
// So the survey is restricted to direct dependencies, which are installed everywhere. The
|
||||
// lockfile's resolved count is printed to the console only — see the header comment.
|
||||
// Platform binaries are covered in prose in THIRD-PARTY-NOTICES.md instead — notably
|
||||
// sharp's prebuilt libvips, which is Apache-2.0 AND LGPL-3.0-or-later.
|
||||
const resolvedCount = new Set(
|
||||
Object.keys(lock.packages ?? {})
|
||||
.filter((p) => p.startsWith("node_modules/"))
|
||||
.map((p) => p.slice(p.lastIndexOf("node_modules/") + "node_modules/".length)),
|
||||
).size;
|
||||
|
||||
const byLicense = new Map();
|
||||
const unknown = [];
|
||||
for (const { name } of direct) {
|
||||
const lic = licenseOf(name);
|
||||
if (!lic) {
|
||||
unknown.push(name);
|
||||
continue;
|
||||
}
|
||||
const list = byLicense.get(lic) ?? [];
|
||||
list.push(name);
|
||||
byLicense.set(lic, list);
|
||||
}
|
||||
|
||||
const flagged = [...byLicense.entries()]
|
||||
.filter(([lic]) => !allowedOutright(lic))
|
||||
.sort((a, b) => a[0].localeCompare(b[0]));
|
||||
|
||||
// ---------------------------------------------------------------- render
|
||||
|
||||
const rows = direct.map(({ name, kind }) => {
|
||||
const lic = licenseOf(name) ?? "(not installed — run npm ci)";
|
||||
return `| \`${name}\` | ${lic} | ${kind} |`;
|
||||
});
|
||||
|
||||
const licenseSummary = [...byLicense.entries()]
|
||||
.sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
|
||||
.map(([lic, list]) => `| ${lic} | ${list.length} |`);
|
||||
|
||||
const lines = [
|
||||
BEGIN,
|
||||
"",
|
||||
`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 (${direct.length})`,
|
||||
"",
|
||||
"`runtime` are declared in `dependencies`; `build` in `devDependencies` and never served.",
|
||||
"",
|
||||
"| Package | License | Kind |",
|
||||
"| ------- | ------- | ---- |",
|
||||
...rows,
|
||||
"",
|
||||
"## License spread across direct dependencies",
|
||||
"",
|
||||
"| License | Packages |",
|
||||
"| ------- | -------- |",
|
||||
...licenseSummary,
|
||||
"",
|
||||
"Transitive dependencies are deliberately not tallied here. Which packages get installed",
|
||||
"depends on the platform (npm resolves only the matching `@img/sharp-*` / `*-msvc`",
|
||||
"binaries), and even a bare count would change with every lockfile bump. The complete",
|
||||
"inventory is `package-lock.json`; platform binaries are covered in prose below.",
|
||||
"",
|
||||
];
|
||||
|
||||
if (flagged.length > 0) {
|
||||
lines.push("## Licenses outside the standard allowlist", "");
|
||||
for (const [lic, list] of flagged) {
|
||||
lines.push(`**${lic}** — ${list.length} package(s):`, "");
|
||||
for (const name of list) {
|
||||
const note = clearedByReview(name, lic) ? `reviewed: ${reviewFor(name).reason}` : null;
|
||||
lines.push(`- \`${name}\` — ${note ?? "⚠️ NOT YET REVIEWED."}`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
}
|
||||
|
||||
if (unknown.length > 0) {
|
||||
lines.push(
|
||||
`## Unknown license (${unknown.length})`,
|
||||
"",
|
||||
`Packages whose \`package.json\` declares no license: ${unknown.map((n) => `\`${n}\``).join(", ")}`,
|
||||
"",
|
||||
);
|
||||
}
|
||||
|
||||
lines.push(END);
|
||||
const generated = lines.join("\n");
|
||||
|
||||
// ---------------------------------------------------------------- write / check
|
||||
|
||||
const current = readFileSync(NOTICES, "utf8");
|
||||
const start = current.indexOf(BEGIN);
|
||||
const stop = current.indexOf(END);
|
||||
if (start === -1 || stop === -1) {
|
||||
console.error(
|
||||
`${NOTICES} is missing the generated-block markers. Expected:\n ${BEGIN}\n ${END}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
const next = current.slice(0, start) + generated + current.slice(stop + END.length);
|
||||
|
||||
const unreviewed = flagged.flatMap(([lic, list]) =>
|
||||
list.filter((name) => !clearedByReview(name, lic)).map((name) => `${name} (${lic})`),
|
||||
);
|
||||
|
||||
if (process.argv.includes("--check")) {
|
||||
if (next !== current) {
|
||||
console.error(
|
||||
`${NOTICES} is out of date with package-lock.json.\n` +
|
||||
`Run \`npm run gen-notices\` and commit the result.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
if (unreviewed.length > 0) {
|
||||
console.error(
|
||||
`Unreviewed license(s) among the direct dependencies: ${unreviewed.join(", ")}\n` +
|
||||
`Review them and add an entry to REVIEWED in scripts/license-policy.mjs.`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`${NOTICES} is up to date (${direct.length} direct, ${resolvedCount} resolved).`);
|
||||
} else {
|
||||
writeFileSync(NOTICES, next);
|
||||
console.log(`wrote ${NOTICES} — ${direct.length} direct, ${resolvedCount} resolved packages`);
|
||||
if (unreviewed.length > 0) {
|
||||
console.log(` note: ${unreviewed.length} package(s) need review: ${unreviewed.join(", ")}`);
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,20 @@
|
||||
// Build-time Open Graph image generation. Runs in Node (see src/lib/og.ts for why a
|
||||
// prerendered endpoint can't do this). Reads content frontmatter, renders a 1200x630 card
|
||||
// per entry with Satori + resvg, and writes to dist/client/og/<key>.png.
|
||||
//
|
||||
// The `ogKey` logic here MUST stay in sync with src/lib/og.ts.
|
||||
// per entry with Satori + resvg, and writes to dist/client/og/<key>.png. File names come
|
||||
// from ogKey() in src/lib/og.ts — the same function the pages use to link to them (Node
|
||||
// runs the .ts file directly).
|
||||
import satori from "satori";
|
||||
import { html } from "satori-html";
|
||||
import { Resvg } from "@resvg/resvg-js";
|
||||
import matter from "gray-matter";
|
||||
import { parse as parseYaml } from "yaml";
|
||||
import { readFileSync, writeFileSync, mkdirSync, readdirSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import path from "node:path";
|
||||
import { ogKey } from "../src/lib/og.ts";
|
||||
import { PALETTE } from "../src/lib/palette.ts";
|
||||
import { labelNames } from "../src/lib/content-labels.ts";
|
||||
import vi from "../src/i18n/vi.ts";
|
||||
import en from "../src/i18n/en.ts";
|
||||
|
||||
const root = fileURLToPath(new URL("..", import.meta.url));
|
||||
const fontsDir = path.join(root, "src/assets/fonts");
|
||||
@@ -28,6 +33,23 @@ const fonts = [
|
||||
},
|
||||
];
|
||||
|
||||
// Cards are always dark: they show up in feeds of either theme, and dark carries the
|
||||
// brand. Colours come from the site palette (src/lib/palette.ts).
|
||||
const C = PALETTE.dark;
|
||||
|
||||
/** `a` blended into `b` at `weight` (0–1), as #rrggbb — Satori has no color-mix(). */
|
||||
function mix(a, b, weight) {
|
||||
const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
|
||||
const [x, y] = [rgb(a), rgb(b)];
|
||||
return `#${x
|
||||
.map((v, i) =>
|
||||
Math.round(v * weight + y[i] * (1 - weight))
|
||||
.toString(16)
|
||||
.padStart(2, "0"),
|
||||
)
|
||||
.join("")}`;
|
||||
}
|
||||
|
||||
const BADGES = {
|
||||
blog: { vi: "Blog", en: "Blog" },
|
||||
story: { vi: "Truyện", en: "Story" },
|
||||
@@ -35,18 +57,14 @@ const BADGES = {
|
||||
};
|
||||
|
||||
// The signature Waveline motif, as an inline SVG (Satori renders paths; resvg rasterizes).
|
||||
const WAVE = `<svg width="240" height="26" viewBox="0 0 120 20" fill="none"><path d="M2 10 H30 L38 3 L50 17 L62 4 L74 15 L84 10 H118" stroke="#e8a33d" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
|
||||
const WAVE = `<svg width="240" height="26" viewBox="0 0 120 20" fill="none"><path d="M2 10 H30 L38 3 L50 17 L62 4 L74 15 L84 10 H118" stroke="${C.accent}" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
|
||||
|
||||
function esc(s) {
|
||||
return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
}
|
||||
|
||||
function ogKey(section, id) {
|
||||
return `${section}-${id.replace(/\//g, "__")}`;
|
||||
}
|
||||
|
||||
const SHELL = (inner) =>
|
||||
`<div style="display:flex; flex-direction:column; justify-content:space-between; width:1200px; height:630px; background:#0d1117; padding:72px; font-family:Bricolage;">${inner}</div>`;
|
||||
`<div style="display:flex; flex-direction:column; justify-content:space-between; width:1200px; height:630px; background:${C.bg}; padding:72px; font-family:Bricolage;">${inner}</div>`;
|
||||
|
||||
// NOTE: satori-html's `html` must be called as a function on a plain string —
|
||||
// its tagged-template form escapes interpolated HTML fragments (the wave/strip).
|
||||
@@ -54,21 +72,21 @@ function entryCard({ title, badge, cw }) {
|
||||
const t = esc(title);
|
||||
const size = t.length > 70 ? 50 : t.length > 45 ? 60 : 74;
|
||||
const strip = cw
|
||||
? `<div style="display:flex; align-items:center; align-self:flex-start; padding:6px 18px; border-radius:999px; background:#3a1720; color:#e79aa4; font-size:22px; font-weight:500;">CW · ${esc(cw)}</div>`
|
||||
? `<div style="display:flex; align-items:center; align-self:flex-start; padding:6px 18px; border-radius:999px; background:${mix(C.horror, C.bg, 0.18)}; color:${C.horror}; font-size:22px; font-weight:500;">${esc(cw)}</div>`
|
||||
: "";
|
||||
return html(
|
||||
SHELL(`
|
||||
<div style="display:flex; align-items:center; justify-content:space-between;">
|
||||
<div style="display:flex; padding:10px 22px; border:2px solid #2a3242; border-radius:999px; color:#98a0ae; font-size:26px; font-weight:500;">${esc(badge)}</div>
|
||||
<div style="display:flex; padding:10px 22px; border:2px solid ${C.line}; border-radius:999px; color:${C.muted}; font-size:26px; font-weight:500;">${esc(badge)}</div>
|
||||
${WAVE}
|
||||
</div>
|
||||
<div style="display:flex; flex-direction:column; gap:20px;">
|
||||
${strip}
|
||||
<span style="color:#e9e4d8; font-size:${size}px; font-weight:700; line-height:1.08;">${t}</span>
|
||||
<span style="color:${C.text}; font-size:${size}px; font-weight:700; line-height:1.08;">${t}</span>
|
||||
</div>
|
||||
<div style="display:flex; justify-content:space-between; align-items:center;">
|
||||
<span style="color:#e8a33d; font-size:30px; font-weight:700;">poli0981.dev</span>
|
||||
<span style="color:#98a0ae; font-size:24px; font-weight:500;">Kokone · SkullMute</span>
|
||||
<span style="color:${C.accent}; font-size:30px; font-weight:700;">poli0981.dev</span>
|
||||
<span style="color:${C.muted}; font-size:24px; font-weight:500;">Kokone · SkullMute</span>
|
||||
</div>
|
||||
`),
|
||||
);
|
||||
@@ -78,13 +96,21 @@ const defaultCard = html(
|
||||
SHELL(`
|
||||
<div style="display:flex; justify-content:flex-end;">${WAVE}</div>
|
||||
<div style="display:flex; flex-direction:column; gap:14px;">
|
||||
<span style="color:#e9e4d8; font-size:88px; font-weight:700;">Kokone · SkullMute</span>
|
||||
<span style="color:#98a0ae; font-size:34px; font-weight:500;">~ dev & storyteller ~</span>
|
||||
<span style="color:${C.text}; font-size:88px; font-weight:700;">Kokone · SkullMute</span>
|
||||
<span style="color:${C.muted}; font-size:34px; font-weight:500;">~ dev & storyteller ~</span>
|
||||
</div>
|
||||
<div style="display:flex;"><span style="color:#e8a33d; font-size:30px; font-weight:700;">poli0981.dev</span></div>
|
||||
<div style="display:flex;"><span style="color:${C.accent}; font-size:30px; font-weight:700;">poli0981.dev</span></div>
|
||||
`),
|
||||
);
|
||||
|
||||
// Frontmatter only (the body is never needed here). gray-matter was dropped: its js-yaml@3 →
|
||||
// argparse@1 → sprintf-js chain carries an advisory with no fixed version. YAML 1.2 core
|
||||
// schema is fine — no date fields are read below.
|
||||
function frontmatter(src) {
|
||||
const m = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(src);
|
||||
return (m && parseYaml(m[1])) || {};
|
||||
}
|
||||
|
||||
async function render(node) {
|
||||
const svg = await satori(node, { width: 1200, height: 630, fonts });
|
||||
return new Resvg(svg, { fitTo: { mode: "width", value: 1200 } }).render().asPng();
|
||||
@@ -113,15 +139,21 @@ for (const { dir, section, titleKey } of SECTIONS) {
|
||||
const relPosix = String(rel).replace(/\\/g, "/");
|
||||
if (!/\.(md|mdx)$/.test(relPosix)) continue;
|
||||
if (path.basename(relPosix).startsWith("_")) continue;
|
||||
const { data } = matter(readFileSync(path.join(base, relPosix), "utf8"));
|
||||
const data = frontmatter(readFileSync(path.join(base, relPosix), "utf8"));
|
||||
if (data.draft === true) continue;
|
||||
const id = relPosix.replace(/\.(md|mdx)$/, "");
|
||||
const lang = data.lang === "en" ? "en" : "vi";
|
||||
const title = data[titleKey] ?? id;
|
||||
// A labelled post or chapter says so on its card, in its own language: a link preview
|
||||
// shows no banner. Cards are text only, so no image of the item ever appears on them.
|
||||
const strings = lang === "en" ? en : vi;
|
||||
const labels = Array.isArray(data.contentWarning) ? data.contentWarning.map(String) : [];
|
||||
const parts = [
|
||||
...labelNames(labels, strings.labels),
|
||||
...(data.ageRating ? [String(data.ageRating)] : []),
|
||||
];
|
||||
const cw =
|
||||
section === "story" && Array.isArray(data.contentWarning) && data.contentWarning.length
|
||||
? data.contentWarning.join(" · ")
|
||||
: null;
|
||||
section !== "project" && parts.length ? [strings.cw.title, ...parts].join(" · ") : null;
|
||||
const png = await render(entryCard({ title, badge: BADGES[section][lang], cw }));
|
||||
writeFileSync(path.join(outDir, `${ogKey(section, id)}.png`), png);
|
||||
count++;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Licence policy shared by scripts/gen-notices.mjs (direct dependencies → the table in
|
||||
* THIRD-PARTY-NOTICES.md) and scripts/check-licenses.mjs (every package in package-lock.json).
|
||||
* See docs 08 §6 and docs 12.
|
||||
*
|
||||
* The code is GPL-3.0-only. ALLOWED holds the licences that need no discussion. Anything else
|
||||
* has to be cleared PER PACKAGE in REVIEWED, with a reason: clearing a licence for everyone
|
||||
* would let the next package under it in without anyone looking (that is how
|
||||
* @axe-core/playwright once passed under a note written for satori).
|
||||
*/
|
||||
|
||||
/** SPDX licence identifiers that need no review. */
|
||||
export const ALLOWED = new Set([
|
||||
"MIT",
|
||||
"Apache-2.0",
|
||||
"ISC",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"OFL-1.1",
|
||||
"0BSD",
|
||||
"Unlicense",
|
||||
"CC0-1.0",
|
||||
"BlueOak-1.0.0",
|
||||
"Python-2.0",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Packages cleared by hand: `packages` are exact names or a prefix ending in `*`, `license`
|
||||
* is the one extra licence the entry allows for them. "We shipped it anyway" is not a reason.
|
||||
*/
|
||||
export const REVIEWED = [
|
||||
{
|
||||
packages: ["satori", "@resvg/resvg-js", "@resvg/resvg-js-*"],
|
||||
license: "MPL-2.0",
|
||||
reason:
|
||||
"File-level copyleft. Used unmodified at build time to draw the OG cards " +
|
||||
"(scripts/gen-og.mjs); never shipped to the browser or the Worker.",
|
||||
},
|
||||
{
|
||||
packages: ["axe-core", "@axe-core/playwright"],
|
||||
license: "MPL-2.0",
|
||||
reason:
|
||||
"File-level copyleft. Runs only in the accessibility tests (tests/a11y); never shipped.",
|
||||
},
|
||||
{
|
||||
packages: ["lightningcss", "lightningcss-*"],
|
||||
license: "MPL-2.0",
|
||||
reason:
|
||||
"File-level copyleft. Vite and Tailwind run it unmodified at build time to transform " +
|
||||
"this site's own CSS; the tool itself is not shipped.",
|
||||
},
|
||||
{
|
||||
packages: ["@img/sharp-libvips-*", "@img/sharp-win32-*", "@img/sharp-wasm32"],
|
||||
license: "LGPL-3.0-or-later",
|
||||
reason:
|
||||
"sharp's prebuilt libvips, loaded unmodified by Astro's image service at build time; " +
|
||||
"none of it is shipped. LGPL-3.0 is compatible with GPL-3.0.",
|
||||
},
|
||||
];
|
||||
|
||||
/** The REVIEWED entry that covers a package, if any. */
|
||||
export function reviewFor(name) {
|
||||
return REVIEWED.find((entry) =>
|
||||
entry.packages.some((pattern) =>
|
||||
pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an SPDX licence expression is satisfied by a set of allowed identifiers:
|
||||
* `A OR B` needs one side, `A AND B` needs both, parentheses group, and `X WITH exception`
|
||||
* counts as X (an exception only adds permissions). Throws a SyntaxError for anything that
|
||||
* is not an expression, such as "SEE LICENSE IN LICENSE".
|
||||
*/
|
||||
export function satisfies(expression, allowed) {
|
||||
const tokens = expression.replaceAll("(", " ( ").replaceAll(")", " ) ").trim().split(/\s+/);
|
||||
let at = 0;
|
||||
const isOperator = (token, op) => token?.toUpperCase() === op;
|
||||
const fail = () => {
|
||||
throw new SyntaxError(`Not an SPDX expression: "${expression}"`);
|
||||
};
|
||||
|
||||
function primary() {
|
||||
const token = tokens[at++];
|
||||
if (token === "(") {
|
||||
const value = anyOf();
|
||||
if (tokens[at++] !== ")") fail();
|
||||
return value;
|
||||
}
|
||||
if (!token || token === ")" || ["AND", "OR", "WITH"].some((op) => isOperator(token, op))) {
|
||||
fail();
|
||||
}
|
||||
if (isOperator(tokens[at], "WITH")) {
|
||||
if (!tokens[at + 1]) fail();
|
||||
at += 2;
|
||||
}
|
||||
return allowed.has(token);
|
||||
}
|
||||
function allOf() {
|
||||
let value = primary();
|
||||
while (isOperator(tokens[at], "AND")) {
|
||||
at++;
|
||||
const next = primary();
|
||||
value = value && next;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function anyOf() {
|
||||
let value = allOf();
|
||||
while (isOperator(tokens[at], "OR")) {
|
||||
at++;
|
||||
const next = allOf();
|
||||
value = value || next;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
const result = anyOf();
|
||||
if (at !== tokens.length) fail();
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Scaffold a content entry with correct frontmatter (docs 04 §5).
|
||||
*
|
||||
* npm run new:post -- blog "Đêm render đầu tiên"
|
||||
* npm run new:post -- story "Chương 3" --series dem-khong-tieng
|
||||
* npm run new:post -- project "RepoLens" --lang en
|
||||
* npm run new:post -- faq "Bạn dùng công cụ gì?"
|
||||
*
|
||||
* The templates in docs/templates/ are the single source of truth — this script only
|
||||
* substitutes placeholders. Adding a field to a schema means editing the template, and
|
||||
* the scaffolder follows automatically instead of drifting from it.
|
||||
*
|
||||
* NOTE: src/content is a git submodule (poli0981/content). Files land there, so the
|
||||
* commit belongs in that repo — the script says so after writing.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
|
||||
const TYPES = {
|
||||
blog: { template: "blog.md", dir: "src/content/blog" },
|
||||
story: { template: "story-chapter.md", dir: "src/content/stories" },
|
||||
project: { template: "project.md", dir: "src/content/projects" },
|
||||
faq: { template: "faq.md", dir: "src/content/faq" },
|
||||
};
|
||||
|
||||
function usage(msg) {
|
||||
if (msg) console.error(`error: ${msg}\n`);
|
||||
console.error(`usage: npm run new:post -- <${Object.keys(TYPES).join("|")}> "Title" [options]
|
||||
|
||||
options:
|
||||
--lang <vi|en> default vi
|
||||
--series <slug> story only; the folder name under stories/, e.g. dem-khong-tieng
|
||||
--slug <slug> override the slug derived from the title
|
||||
|
||||
examples:
|
||||
npm run new:post -- blog "Đêm render đầu tiên"
|
||||
npm run new:post -- story "Chương 3" --series dem-khong-tieng
|
||||
npm run new:post -- faq "Bạn dùng công cụ gì?"`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vietnamese title → ASCII slug. docs 04 §7 requires slugs without diacritics.
|
||||
* NFD splits a base letter from its combining marks so the marks can be dropped, but
|
||||
* đ/Đ is its own codepoint rather than d + a mark, so it needs handling by hand.
|
||||
*/
|
||||
function slugify(input) {
|
||||
return input
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "") // strip combining marks exposed by NFD
|
||||
.replace(/[đĐ]/g, (c) => (c === "đ" ? "d" : "D")) // đ/Đ: own codepoints, not marks
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.split("-")
|
||||
.filter(Boolean)
|
||||
.join("-"); // no leading/trailing "-" (and no backtracking /^-+|-+$/)
|
||||
}
|
||||
|
||||
// `--name value` pairs anywhere on the line; everything else is positional. (Filtering out
|
||||
// only the "--x" tokens left their values behind as positionals, so a flag placed before
|
||||
// the title became the title.)
|
||||
const flags = new Map();
|
||||
const positional = [];
|
||||
const argv = process.argv.slice(2);
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
if (argv[i].startsWith("--")) flags.set(argv[i].slice(2), argv[++i]);
|
||||
else positional.push(argv[i]);
|
||||
}
|
||||
const flag = (name) => flags.get(name);
|
||||
|
||||
const [type, title] = positional;
|
||||
if (!type) usage("missing type");
|
||||
if (!TYPES[type]) usage(`unknown type "${type}"`);
|
||||
if (!title) usage("missing title");
|
||||
|
||||
const lang = flag("lang") ?? "vi";
|
||||
if (lang !== "vi" && lang !== "en") usage(`--lang must be vi or en, got "${lang}"`);
|
||||
|
||||
const series = flag("series");
|
||||
if (type === "story" && !series) usage("story needs --series <slug> (the folder under stories/)");
|
||||
|
||||
const slug = flag("slug") ?? slugify(title);
|
||||
if (!slug) usage(`could not derive a slug from "${title}" — pass --slug`);
|
||||
|
||||
const { template, dir } = TYPES[type];
|
||||
const now = new Date();
|
||||
const date = now.toISOString().slice(0, 10);
|
||||
|
||||
// en entries live beside vi ones with an -en suffix, matching the existing files.
|
||||
const base = lang === "en" && type !== "story" ? `${slug}-en` : slug;
|
||||
const target = type === "story" ? join(dir, series, `${base}.md`) : join(dir, `${base}.md`);
|
||||
|
||||
if (existsSync(target)) {
|
||||
console.error(`error: ${target} already exists — refusing to overwrite.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const tpl = readFileSync(join("docs/templates", template), "utf8");
|
||||
const body = tpl
|
||||
// The template has `title: "{{TITLE}}"`, a YAML double-quoted scalar: escape \ and ".
|
||||
.replaceAll("{{TITLE}}", title.replaceAll("\\", "\\\\").replaceAll('"', '\\"'))
|
||||
.replaceAll("{{LANG}}", lang)
|
||||
.replaceAll("{{DATE}}", date)
|
||||
.replaceAll("{{YEAR}}", String(now.getUTCFullYear()))
|
||||
.replaceAll("{{SERIES}}", series ?? "");
|
||||
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, body);
|
||||
|
||||
console.log(`created ${target}`);
|
||||
console.log(`
|
||||
next:
|
||||
1. fill in the frontmatter (the comment block lists what each field does)
|
||||
2. \`npm run dev\` — drafts are visible there, hidden in production
|
||||
3. flip \`draft: true\` to false when ready
|
||||
4. commit in the CONTENT repo (src/content is a submodule -> poli0981/content),
|
||||
then bump the pointer here:
|
||||
git -C src/content add -A && git -C src/content commit -m "..." && git -C src/content push
|
||||
git add src/content && git commit -m "content: ..."`);
|
||||
@@ -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?)");
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
// Boots the BUILT worker (dist/server/wrangler.json) with `wrangler dev` — local mode, all
|
||||
// bindings simulated, no Cloudflare credentials — and probes the routes that matter. The
|
||||
// custom entry (src/worker.ts) fronts every page, so a crash there would take the whole
|
||||
// static site down; this runs in CI before anything can merge.
|
||||
//
|
||||
// Phase 1 runs as configured (gate off), including /media and /ext-img against objects
|
||||
// seeded into the local R2 bucket and KV namespace. Phase 2 forces the Turnstile gate on
|
||||
// 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. 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";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { request as httpRequest } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
|
||||
// wrangler runs through this Node binary and its own CLI file — never looked up on PATH.
|
||||
// (`spawn("npx")` needed a shell on Windows, and a PATH lookup is a command the environment
|
||||
// can swap.)
|
||||
const require = createRequire(import.meta.url);
|
||||
const wranglerPkgPath = require.resolve("wrangler/package.json");
|
||||
const WRANGLER = join(dirname(wranglerPkgPath), require(wranglerPkgPath).bin.wrangler);
|
||||
const CONFIG = ["--config", "dist/server/wrangler.json"];
|
||||
|
||||
const TEST_TURNSTILE_SECRET = "1x0000000000000000000000000000000AA";
|
||||
// The whole run; CI's job timeout is only the outer bound.
|
||||
const DEADLINE_MS = 10 * 60 * 1000;
|
||||
const failures = [];
|
||||
|
||||
setTimeout(() => {
|
||||
console.error(`smoke test timed out after ${DEADLINE_MS / 60000} minutes`);
|
||||
process.exit(1);
|
||||
}, DEADLINE_MS).unref();
|
||||
|
||||
function expect(name, ok, detail = "") {
|
||||
console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : ` — ${detail}`}`);
|
||||
if (!ok) failures.push(name);
|
||||
}
|
||||
|
||||
/** Run a wrangler subcommand to completion, showing its output only when it fails. */
|
||||
function wrangler(args) {
|
||||
try {
|
||||
execFileSync(process.execPath, [WRANGLER, ...args], { stdio: "pipe", encoding: "utf8" });
|
||||
} catch (error) {
|
||||
console.error(`wrangler ${args.join(" ")} failed:\n${error.stdout ?? ""}${error.stderr ?? ""}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A `wrangler kv key …` command against the local KV binding. The binding has both an `id`
|
||||
* and a `preview_id`, and wrangler makes you pick one; run it against both so the seed is
|
||||
* there whichever namespace local dev reads.
|
||||
*/
|
||||
function kv(args) {
|
||||
for (const preview of ["--preview", "--preview=false"]) {
|
||||
wrangler(["kv", "key", ...args, "--binding", "KV", "--local", preview, ...CONFIG]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop `wrangler dev` and the workerd it started. */
|
||||
function stop(server) {
|
||||
if (server.exitCode !== null) return;
|
||||
try {
|
||||
if (process.platform === "win32") {
|
||||
// /T ends the whole tree (wrangler → workerd). Absolute path: no PATH lookup.
|
||||
const taskkill = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "taskkill.exe");
|
||||
execFileSync(taskkill, ["/pid", String(server.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
} else {
|
||||
process.kill(-server.pid, "SIGTERM"); // the whole process group
|
||||
}
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
}
|
||||
|
||||
/** A GET whose path is sent byte for byte — fetch() would normalize `%2e%2e` away first. */
|
||||
function rawStatus(port, path) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = httpRequest({ host: "127.0.0.1", port, path }, (res) => {
|
||||
res.resume();
|
||||
resolve(res.statusCode);
|
||||
});
|
||||
req.setTimeout(15000, () => req.destroy(new Error(`timeout: ${path}`)));
|
||||
req.on("error", reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
async function withWorker(port, vars, run) {
|
||||
const args = [WRANGLER, "dev", ...CONFIG, "--port", String(port), "--ip", "127.0.0.1"];
|
||||
for (const [key, value] of Object.entries(vars)) args.push("--var", `${key}:${value}`);
|
||||
const server = spawn(process.execPath, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, NO_COLOR: "1" },
|
||||
detached: process.platform !== "win32",
|
||||
windowsHide: true,
|
||||
});
|
||||
let log = "";
|
||||
server.stdout.on("data", (d) => (log += d));
|
||||
server.stderr.on("data", (d) => (log += d));
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
const get = (path, init) =>
|
||||
fetch(`${base}${path}`, { redirect: "manual", signal: AbortSignal.timeout(15000), ...init });
|
||||
// A phase that can't run is a failure, reported with the tail of wrangler's own output.
|
||||
const fail = (error) => {
|
||||
failures.push(String(error));
|
||||
console.error(error, `\n${log.slice(-4000)}`);
|
||||
};
|
||||
try {
|
||||
let up = false;
|
||||
for (let i = 0; i < 60 && !up; i++) {
|
||||
up = await get("/api/health").then(
|
||||
() => true,
|
||||
() => sleep(1000).then(() => false),
|
||||
);
|
||||
}
|
||||
if (up) await run(get, port);
|
||||
else fail(new Error(`wrangler dev did not come up on ${base}`));
|
||||
} catch (error) {
|
||||
fail(error);
|
||||
} finally {
|
||||
stop(server);
|
||||
}
|
||||
}
|
||||
|
||||
// Seed one image variant into the local (simulated) R2 bucket for the /media checks, and
|
||||
// one mirrored widget picture into local KV for /ext-img.
|
||||
const MEDIA_KEY = "v1/0123456789abcdef/webp-800";
|
||||
const YT_ID = "smokeTest_1";
|
||||
const tmp = mkdtempSync(join(tmpdir(), "smoke-"));
|
||||
const seedFile = join(tmp, "variant.webp");
|
||||
writeFileSync(seedFile, Buffer.from("RIFF\0\0\0\0WEBPVP8 smoke-test-bytes"));
|
||||
wrangler([
|
||||
"r2",
|
||||
"object",
|
||||
"put",
|
||||
`poli0981-media/${MEDIA_KEY}`,
|
||||
"--file",
|
||||
seedFile,
|
||||
"--content-type",
|
||||
"image/webp",
|
||||
"--local",
|
||||
...CONFIG,
|
||||
]);
|
||||
kv(["put", `widgets:img:yt:${YT_ID}`, "--path", seedFile, "--metadata", '{"type":"image/jpeg"}']);
|
||||
|
||||
// "Real page" = the site footer is there (the gate page swaps the whole <body>).
|
||||
const isGate = (html) => html.includes("data-human-check");
|
||||
const isRealPage = (html) => html.includes("data-site-footer");
|
||||
let homeTitle = "";
|
||||
|
||||
console.log("— phase 1: as configured (gate off)");
|
||||
await withWorker(8788, {}, async (get, port) => {
|
||||
const home = await get("/");
|
||||
const html = await home.text();
|
||||
homeTitle = /<title>([^<]*)<\/title>/.exec(html)?.[1] ?? "";
|
||||
expect("/ → 200 real page", home.status === 200 && isRealPage(html), `got ${home.status}`);
|
||||
expect("/ has nosniff", home.headers.get("x-content-type-options") === "nosniff");
|
||||
expect("/ has HSTS", (home.headers.get("strict-transport-security") ?? "").includes("max-age"));
|
||||
expect("/ has XFO DENY", home.headers.get("x-frame-options") === "DENY");
|
||||
expect(
|
||||
"/ forbids framing via CSP header",
|
||||
(home.headers.get("content-security-policy") ?? "").includes("frame-ancestors 'none'"),
|
||||
);
|
||||
|
||||
const etag = home.headers.get("etag");
|
||||
const revalidated = etag ? await get("/", { headers: { "if-none-match": etag } }) : null;
|
||||
expect(
|
||||
"/ revalidates to 304",
|
||||
revalidated?.status === 304,
|
||||
`etag=${etag} got ${revalidated?.status}`,
|
||||
);
|
||||
expect("HEAD / → 200", (await get("/", { method: "HEAD" })).status === 200);
|
||||
|
||||
expect("/blog → 307 to /blog/", (await get("/blog")).status === 307);
|
||||
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);
|
||||
// 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",
|
||||
(await get("/.well-known/security.txt")).status === 200,
|
||||
);
|
||||
expect("/pagefind/ open while gate off", (await get("/pagefind/pagefind.js")).status === 200);
|
||||
|
||||
const media = await get(`/media/${MEDIA_KEY}`);
|
||||
const mediaEtag = media.headers.get("etag");
|
||||
const mediaCsp = media.headers.get("content-security-policy") ?? "";
|
||||
expect(
|
||||
"/media variant → 200 image/webp",
|
||||
media.status === 200 && media.headers.get("content-type") === "image/webp",
|
||||
`got ${media.status} ${media.headers.get("content-type")}`,
|
||||
);
|
||||
expect(
|
||||
"/media is immutable for a year",
|
||||
(media.headers.get("cache-control") ?? "").includes("max-age=31536000, immutable"),
|
||||
);
|
||||
expect("/media is sandboxed", mediaCsp.includes("sandbox"), mediaCsp);
|
||||
expect("/media keeps frame-ancestors too", mediaCsp.includes("frame-ancestors"), mediaCsp);
|
||||
expect("/media is nosniff", media.headers.get("x-content-type-options") === "nosniff");
|
||||
const mediaAgain = mediaEtag
|
||||
? await get(`/media/${MEDIA_KEY}`, { headers: { "if-none-match": mediaEtag } })
|
||||
: null;
|
||||
expect("/media revalidates to 304", mediaAgain?.status === 304, `got ${mediaAgain?.status}`);
|
||||
expect(
|
||||
"HEAD /media → 200",
|
||||
(await get(`/media/${MEDIA_KEY}`, { method: "HEAD" })).status === 200,
|
||||
);
|
||||
expect(
|
||||
"missing variant → 404",
|
||||
(await get("/media/v1/0123456789abcdef/webp-801")).status === 404,
|
||||
);
|
||||
for (const path of [
|
||||
"/media/private/master/0123456789abcdef",
|
||||
"/media/v1/%2e%2e/private/master/0123456789abcdef",
|
||||
"/media/v2/0123456789abcdef/webp-800",
|
||||
]) {
|
||||
expect(`${path} → 404`, (await rawStatus(port, path)) === 404);
|
||||
}
|
||||
expect(
|
||||
"POST /media → 405",
|
||||
(await get(`/media/${MEDIA_KEY}`, { method: "POST" })).status === 405,
|
||||
);
|
||||
|
||||
const picture = await get(`/ext-img/yt/${YT_ID}`);
|
||||
expect(
|
||||
"/ext-img mirrored picture → 200 image/jpeg",
|
||||
picture.status === 200 && picture.headers.get("content-type") === "image/jpeg",
|
||||
`got ${picture.status} ${picture.headers.get("content-type")}`,
|
||||
);
|
||||
expect(
|
||||
"/ext-img is sandboxed",
|
||||
(picture.headers.get("content-security-policy") ?? "").includes("sandbox"),
|
||||
);
|
||||
expect("/ext-img unknown picture → 404", (await get("/ext-img/yt/notMirrored")).status === 404);
|
||||
expect(
|
||||
"/ext-img never proxies arbitrary URLs",
|
||||
(await rawStatus(port, "/ext-img/https://example.com/x.png")) === 404,
|
||||
);
|
||||
expect(
|
||||
"POST /ext-img → 405",
|
||||
(await get(`/ext-img/yt/${YT_ID}`, { method: "POST" })).status === 405,
|
||||
);
|
||||
|
||||
// The admin needs a Cloudflare Access JWT on every request; a build never bypasses it.
|
||||
expect("/admin/ without Access → 403", (await get("/admin/")).status === 403);
|
||||
expect(
|
||||
"/api/admin/content without Access → 403",
|
||||
(await get("/api/admin/content")).status === 403,
|
||||
);
|
||||
// Well-formed but signed by nobody: real JSON header and claims, a junk signature. Built
|
||||
// here rather than pasted as a token literal, which secret scanners rightly flag.
|
||||
const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
||||
const forgedJwt = `${part({ alg: "RS256" })}.${part({ email: "a@b.c" })}.c2ln`;
|
||||
const forged = await get("/api/admin/content", {
|
||||
headers: { "cf-access-jwt-assertion": forgedJwt },
|
||||
});
|
||||
expect("/api/admin with a forged JWT → 403", forged.status === 403);
|
||||
});
|
||||
|
||||
console.log("— phase 2: Turnstile gate forced on (test secret)");
|
||||
await withWorker(
|
||||
8789,
|
||||
{ GATE_MODE: "force", GATE_SECRET: "smoke-test-secret", TURNSTILE_SECRET: TEST_TURNSTILE_SECRET },
|
||||
async (get) => {
|
||||
const gated = await get("/");
|
||||
const html = await gated.text();
|
||||
expect("/ without pass → 200 gate", gated.status === 200 && isGate(html) && !isRealPage(html));
|
||||
expect(
|
||||
"gate keeps the page <title>",
|
||||
homeTitle !== "" && html.includes(`<title>${homeTitle}</title>`),
|
||||
);
|
||||
expect("gate drops JSON-LD", !html.includes("application/ld+json"));
|
||||
expect("gate is no-store", (gated.headers.get("cache-control") ?? "").includes("no-store"));
|
||||
expect("gate is noindex", gated.headers.get("x-robots-tag") === "noindex");
|
||||
expect("gate has no ETag", !gated.headers.has("etag"));
|
||||
|
||||
const bot = await get("/", { headers: { "x-verified-bot": "true" } });
|
||||
expect("verified bot → real page", isRealPage(await bot.text()));
|
||||
expect("legal page is exempt", isRealPage(await (await get("/legal/privacy/")).text()));
|
||||
expect("/rss.xml still 200", (await get("/rss.xml")).status === 200);
|
||||
expect("unknown page still 404", (await get("/definitely-not-a-page/")).status === 404);
|
||||
expect("HEAD / not gated", (await get("/", { method: "HEAD" })).status === 200);
|
||||
expect("/pagefind/ without pass → 403", (await get("/pagefind/pagefind.js")).status === 403);
|
||||
expect("/media not gated", (await get(`/media/${MEDIA_KEY}`)).status === 200);
|
||||
|
||||
// A pass whose signature `atob` can't decode used to throw past the gate into the
|
||||
// worker's fail-open path and serve the real page.
|
||||
const expiry = Math.floor(Date.now() / 1000) + 3600;
|
||||
for (const value of [
|
||||
`v1.${expiry}.x.A`,
|
||||
`v1.${expiry}.x.AAAAA`,
|
||||
`v1.${expiry}.x.${"A".repeat(43)}`,
|
||||
]) {
|
||||
const forgedPass = await get("/", { headers: { cookie: `__Host-gate=${value}` } });
|
||||
const forgedHtml = await forgedPass.text();
|
||||
expect(
|
||||
`malformed pass ${value.slice(-6)} → still the gate`,
|
||||
isGate(forgedHtml) && !isRealPage(forgedHtml),
|
||||
);
|
||||
}
|
||||
|
||||
const crossSite = await get("/api/gate", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "sec-fetch-site": "cross-site" },
|
||||
body: JSON.stringify({ token: "XXXX.DUMMY.TOKEN.XXXX" }),
|
||||
});
|
||||
expect("cross-site /api/gate → 403", crossSite.status === 403, `got ${crossSite.status}`);
|
||||
|
||||
const oversized = await get("/api/gate", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "sec-fetch-site": "same-origin" },
|
||||
body: JSON.stringify({ token: "x".repeat(20000) }),
|
||||
});
|
||||
expect("oversized /api/gate body → 413", oversized.status === 413, `got ${oversized.status}`);
|
||||
|
||||
const verified = await get("/api/gate", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "sec-fetch-site": "same-origin" },
|
||||
body: JSON.stringify({ token: "XXXX.DUMMY.TOKEN.XXXX" }),
|
||||
});
|
||||
const setCookie = verified.headers.get("set-cookie") ?? "";
|
||||
expect(
|
||||
"/api/gate → 204 + pass cookie",
|
||||
verified.status === 204 && setCookie.startsWith("__Host-gate="),
|
||||
`got ${verified.status}`,
|
||||
);
|
||||
|
||||
const pass = setCookie.split(";")[0];
|
||||
const withPass = await get("/", { headers: { cookie: pass } });
|
||||
expect("with pass → real page", isRealPage(await withPass.text()));
|
||||
expect(
|
||||
"with pass → pagefind 200",
|
||||
(await get("/pagefind/pagefind.js", { headers: { cookie: pass } })).status === 200,
|
||||
);
|
||||
|
||||
const tampered = `${pass.slice(0, -2)}xx`;
|
||||
expect(
|
||||
"tampered pass → gate",
|
||||
isGate(await (await get("/", { headers: { cookie: tampered } })).text()),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
console.log("— phase 3: client address on the KV denylist");
|
||||
// workerd sees the smoke test as 127.0.0.1; list it (and its IPv6 twin) for this phase only.
|
||||
const LISTED = JSON.stringify([
|
||||
{ cidr: "127.0.0.1", reason: "smoke test" },
|
||||
{ cidr: "::1/128", reason: "smoke test" },
|
||||
]);
|
||||
kv(["put", "denylist", LISTED]);
|
||||
try {
|
||||
await withWorker(8790, {}, async (get) => {
|
||||
const page = await get("/");
|
||||
expect("denylisted → 403 on a page", page.status === 403, `got ${page.status}`);
|
||||
expect("denylisted 403 is no-store", page.headers.get("cache-control") === "no-store");
|
||||
expect(
|
||||
"denylisted → 403 on the API",
|
||||
(await get("/api/report", { method: "POST" })).status === 403,
|
||||
);
|
||||
expect("denylisted → 403 on /media", (await get(`/media/${MEDIA_KEY}`)).status === 403);
|
||||
});
|
||||
} finally {
|
||||
kv(["delete", "denylist"]);
|
||||
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);
|
||||
}
|
||||
console.log("\nsmoke test ok");
|
||||
process.exit(0);
|
||||
@@ -1,24 +1,92 @@
|
||||
// Strip ALL metadata (EXIF/GPS/serial/XMP) from images by re-encoding with sharp.
|
||||
// Prepare photos for committing: strip ALL metadata AND enforce the size budget.
|
||||
// Run manually BEFORE committing any photo: `npm run strip-exif src/assets/gallery/<album>`
|
||||
// sharp writes no metadata unless asked; `.rotate()` bakes EXIF orientation into pixels first.
|
||||
import { readdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join, extname } from "node:path";
|
||||
//
|
||||
// Two jobs, because docs 04 §5 states two rules for a committed photo and having them in
|
||||
// separate tools meant the second one was never actually applied:
|
||||
// 1. No metadata. sharp writes none unless asked; `.rotate()` bakes EXIF orientation
|
||||
// into the pixels first so the image still looks right after the metadata is gone.
|
||||
// (`scripts/check-exif.mjs` is the CI gate that fails if this was skipped.)
|
||||
// 2. Max 2560px on the long edge, max ~1.5MB. Phone photos arrive at 6048x8064 / 2.5MB,
|
||||
// which is a pointless amount of bytes for a 400-800px gallery thumbnail and blows
|
||||
// out both the repo and the Astro build.
|
||||
import { readdir, readFile, writeFile, stat } from "node:fs/promises";
|
||||
import { join, extname, relative, resolve, sep } from "node:path";
|
||||
import sharp from "sharp";
|
||||
|
||||
const dir = process.argv[2];
|
||||
if (!dir) {
|
||||
console.error("usage: node scripts/strip-exif.mjs <folder>");
|
||||
const ASSETS = resolve("src/assets");
|
||||
const arg = process.argv[2];
|
||||
if (!arg) {
|
||||
console.error("usage: node scripts/strip-exif.mjs <folder under src/assets/>");
|
||||
process.exit(1);
|
||||
}
|
||||
// The tool rewrites every image it finds in place, so it only ever walks src/assets.
|
||||
const dir = resolve(arg);
|
||||
if (dir !== ASSETS && !dir.startsWith(ASSETS + sep)) {
|
||||
console.error(`refusing to touch ${arg}: only folders under src/assets/ are processed`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const EXT = new Set([".jpg", ".jpeg", ".png", ".webp", ".avif"]);
|
||||
const files = (await readdir(dir)).filter((f) => EXT.has(extname(f).toLowerCase()));
|
||||
const MAX_EDGE = 2560;
|
||||
const MAX_BYTES = 1.5 * 1024 * 1024;
|
||||
// mozjpeg at 85 rather than plain 82: stripping metadata always costs one re-encode
|
||||
// generation, and mozjpeg buys back enough bytes that already-compressed phone photos
|
||||
// don't come out *larger* than they went in. Over budget, step down to at most 70.
|
||||
const QUALITIES = [85, 80, 75, 70];
|
||||
|
||||
for (const f of files) {
|
||||
const p = join(dir, f);
|
||||
/** Every image under `root`, subfolders included. */
|
||||
async function imagesUnder(root) {
|
||||
const out = [];
|
||||
for (const entry of await readdir(root, { withFileTypes: true })) {
|
||||
const full = join(root, entry.name);
|
||||
if (entry.isDirectory()) out.push(...(await imagesUnder(full)));
|
||||
else if (EXT.has(extname(entry.name).toLowerCase())) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function encode(input, ext, resized, quality) {
|
||||
let pipeline = sharp(input).rotate();
|
||||
if (resized) {
|
||||
pipeline = pipeline.resize({
|
||||
width: MAX_EDGE,
|
||||
height: MAX_EDGE,
|
||||
fit: "inside",
|
||||
withoutEnlargement: true,
|
||||
});
|
||||
}
|
||||
if (ext === ".jpg" || ext === ".jpeg") pipeline = pipeline.jpeg({ quality, mozjpeg: true });
|
||||
return pipeline.toBuffer();
|
||||
}
|
||||
|
||||
const files = await imagesUnder(dir);
|
||||
let saved = 0;
|
||||
const overBudget = [];
|
||||
|
||||
for (const p of files) {
|
||||
const before = (await stat(p)).size;
|
||||
const input = await readFile(p); // read fully first, then overwrite the same path
|
||||
const out = await sharp(input).rotate().toBuffer();
|
||||
const { width, height } = await sharp(input).metadata();
|
||||
const resized = Math.max(width ?? 0, height ?? 0) > MAX_EDGE;
|
||||
const ext = extname(p).toLowerCase();
|
||||
|
||||
let out = await encode(input, ext, resized, QUALITIES[0]);
|
||||
for (const quality of QUALITIES.slice(1)) {
|
||||
if (out.length <= MAX_BYTES || (ext !== ".jpg" && ext !== ".jpeg")) break;
|
||||
out = await encode(input, ext, resized, quality);
|
||||
}
|
||||
await writeFile(p, out);
|
||||
console.log(`stripped ${p}`);
|
||||
if (out.length > MAX_BYTES) overBudget.push(relative(".", p));
|
||||
|
||||
saved += before - out.length;
|
||||
const note = resized ? `${width}x${height} -> max ${MAX_EDGE}px` : "metadata only";
|
||||
console.log(
|
||||
` ${relative(dir, p).padEnd(28)} ${(before / 1024).toFixed(0)}KB -> ${(out.length / 1024).toFixed(0)}KB (${note})`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log(`done: ${files.length} image(s), ${(saved / 1024 / 1024).toFixed(2)}MB saved`);
|
||||
if (overBudget.length) {
|
||||
console.warn(`still over ${MAX_BYTES / 1024 / 1024}MB (resize or recompress by hand):`);
|
||||
for (const file of overBudget) console.warn(` ${file}`);
|
||||
}
|
||||
console.log(`done: ${files.length} image(s)`);
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Maintenance-mode triage (CONTRIBUTING.md): an issue or pull request that asks for a new
|
||||
* feature is labelled and closed with an explanation; everything else is left for the owner.
|
||||
* .github/workflows/triage.yml reads this file from the default branch through the API and runs
|
||||
* it in actions/github-script: nothing is checked out, so no pull request's code ever runs.
|
||||
*
|
||||
* Deliberately narrow: only clear signals count (the title, or a label the reporter could not
|
||||
* set by accident). A bug report that happens to say "add" is not a feature request.
|
||||
*/
|
||||
|
||||
export const LABELS = {
|
||||
/** Marks a feature request (GitHub's default label, reused). */
|
||||
feature: "enhancement",
|
||||
/** Closed because new features are out of scope while the project is in maintenance mode. */
|
||||
closed: "out-of-scope",
|
||||
/** The owner's exception: the bot leaves the item alone. */
|
||||
exception: "maintenance-exception",
|
||||
};
|
||||
|
||||
// Tested against the trimmed title. Each pattern is linear: no two quantifiers compete for the
|
||||
// same characters.
|
||||
const FEATURE_TITLES = [
|
||||
/^feat(\([^)]*\))?!?:/i, // conventional commits: "feat: …", "feat(ui)!: …"
|
||||
/^\[(feat|feature|features|enhancement|request|idea|tính năng|đề xuất)\b/iu,
|
||||
/\bfeature[\s-]+request\b/i,
|
||||
/\b(new|add|adding)(\s+a)?\s+feature\b/i,
|
||||
/(đề xuất|yêu cầu|thêm|bổ sung)\s+tính năng|tính năng mới/iu,
|
||||
];
|
||||
|
||||
/** People whose items are never closed: the owner and collaborators, and bots. */
|
||||
const TRUSTED = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
|
||||
|
||||
/**
|
||||
* What to do with one issue or pull request.
|
||||
*
|
||||
* @param {{ title: string, labels: string[], author: string, association?: string,
|
||||
* sender?: string, owner?: string, state?: string }} item
|
||||
* `association` is the author's (GitHub's author_association); `sender` is whoever
|
||||
* triggered the event, so the owner reopening or relabelling an item is never undone.
|
||||
* @returns {{ action: "close" | "none", reason: string }}
|
||||
*/
|
||||
export function decide(item) {
|
||||
const labels = item.labels.map((label) => label.toLowerCase());
|
||||
if (item.state && item.state !== "open") return { action: "none", reason: "not open" };
|
||||
if (labels.includes(LABELS.exception)) return { action: "none", reason: "owner's exception" };
|
||||
if (TRUSTED.has(item.association ?? "")) return { action: "none", reason: "trusted author" };
|
||||
if (item.author.endsWith("[bot]")) return { action: "none", reason: "bot" };
|
||||
if (item.sender && item.owner && item.sender === item.owner) {
|
||||
return { action: "none", reason: "the owner acted on it" };
|
||||
}
|
||||
if (labels.includes(LABELS.feature)) return { action: "close", reason: "labelled as a feature" };
|
||||
const title = item.title.trim();
|
||||
if (FEATURE_TITLES.some((pattern) => pattern.test(title))) {
|
||||
return { action: "close", reason: "the title asks for a feature" };
|
||||
}
|
||||
return { action: "none", reason: "not a feature request" };
|
||||
}
|
||||
|
||||
/** The comment left on a closed item, in both of the project's languages. */
|
||||
export function closingComment(kind) {
|
||||
const what = kind === "pull_request" ? "pull request" : "issue";
|
||||
return [
|
||||
"**Vietnamese / Tiếng Việt** — Cảm ơn bạn! Dự án đang ở **chế độ bảo trì**: không nhận tính năng",
|
||||
"mới. Repo chỉ nhận cập nhật dependency, vá bảo mật, nâng cấp runtime/framework, sửa lỗi (kể",
|
||||
"cả UI/UX và accessibility) và sửa lỗi ngôn ngữ. Vì vậy mục này được đóng tự động. Nếu bạn",
|
||||
"nghĩ đây là lỗi chứ không phải tính năng mới, hãy trả lời bên dưới — chủ repo sẽ xem lại.",
|
||||
"",
|
||||
`**English** — Thank you! This project is in **maintenance mode** and does not take new`,
|
||||
`features. It accepts dependency updates, security fixes, runtime/framework upgrades, bug fixes`,
|
||||
`(including UI/UX and accessibility) and language fixes, so this ${what} was closed`,
|
||||
`automatically. If you think it is a bug rather than a new feature, reply below and the owner`,
|
||||
`will take another look.`,
|
||||
"",
|
||||
"→ [CONTRIBUTING.md](https://github.com/poli0981/poli0981-dev/blob/main/CONTRIBUTING.md)",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# SonarCloud analysis, run by the `sonarcloud` job in .github/workflows/ci.yml
|
||||
# (automatic analysis is switched off — this file is the whole configuration).
|
||||
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.3.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
|
||||
# *.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.
|
||||
sonar.exclusions=src/content/**,src/assets/**,**/*.d.ts,public/pagefind/**
|
||||
|
||||
# Coverage comes from `npm run test:coverage` (node:test + V8 → lcov), uploaded by the
|
||||
# build job. What it does not measure, and why:
|
||||
# - scripts/** build tooling: it runs in CI as part of the build itself (gen-og,
|
||||
# check-csp-hashes, gen-notices) and in the smoke test;
|
||||
# - public/** browser-only scripts (service worker, gate client, offline mini-game);
|
||||
# - src/lib/easter.ts the DOM-only console easter egg;
|
||||
# - src/content.config.ts schema declarations, exercised by every build;
|
||||
# - config files.
|
||||
# .astro and .svelte files are not analyzed by SonarCloud at all. Keep this list in step
|
||||
# with the --test-coverage-exclude flags of `npm run test:coverage`.
|
||||
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
||||
sonar.coverage.exclusions=scripts/**,public/**,.github/**,src/lib/easter.ts,src/content.config.ts,**/*.config.js,**/*.config.mjs
|
||||
|
||||
# The vi/en dictionaries and the link table are parallel DATA by design (the same keys in
|
||||
# each locale), not duplicated logic.
|
||||
sonar.cpd.exclusions=src/i18n/vi.ts,src/i18n/en.ts,src/lib/links.ts
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"demo-01.jpg": {
|
||||
"vi": "Ảnh mẫu 01 — gradient xanh dương sang mực đêm",
|
||||
"en": "Demo image 01 — blue to ink-night gradient"
|
||||
},
|
||||
"demo-02.jpg": {
|
||||
"vi": "Ảnh mẫu 02 — gradient xanh lá sang mực đêm",
|
||||
"en": "Demo image 02 — green to ink-night gradient"
|
||||
},
|
||||
"demo-03.jpg": {
|
||||
"vi": "Ảnh mẫu 03 — gradient cam sang mực đêm",
|
||||
"en": "Demo image 03 — orange to ink-night gradient"
|
||||
},
|
||||
"demo-04.jpg": {
|
||||
"vi": "Ảnh mẫu 04 — gradient tím sang mực đêm",
|
||||
"en": "Demo image 04 — purple to ink-night gradient"
|
||||
},
|
||||
"demo-05.jpg": {
|
||||
"vi": "Ảnh mẫu 05 — gradient đỏ sang mực đêm",
|
||||
"en": "Demo image 05 — red to ink-night gradient"
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"dev-01.jpg": {
|
||||
"vi": "Màn hình làm việc ngẫu nhiên — IDE trong hình là RustRover",
|
||||
"en": "A random working screen — the IDE here is RustRover"
|
||||
},
|
||||
"dev-02.jpg": {
|
||||
"vi": "Màn hình làm việc với Claude",
|
||||
"en": "A working screen with Claude"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 192 KiB |
|
After Width: | Height: | Size: 27 KiB |
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"game-01.jpg": {
|
||||
"vi": "Kugayama Shiori's Death Diary — một trong các ending",
|
||||
"en": "Kugayama Shiori's Death Diary — one of the endings"
|
||||
},
|
||||
"game-02.jpg": {
|
||||
"vi": "AI Limit — đang đánh boss",
|
||||
"en": "AI Limit — mid boss fight"
|
||||
},
|
||||
"game-03.jpg": {
|
||||
"vi": "Ảnh chụp màn hình từ một game khác",
|
||||
"en": "A screenshot from another game"
|
||||
},
|
||||
"game-04.jpg": {
|
||||
"vi": "Ảnh chụp màn hình từ một game khác",
|
||||
"en": "A screenshot from another game"
|
||||
},
|
||||
"game-05.jpg": {
|
||||
"vi": "Ảnh chụp màn hình từ một game khác",
|
||||
"en": "A screenshot from another game"
|
||||
},
|
||||
"game-06.jpg": {
|
||||
"vi": "Kugayama Shiori's Death Diary — một ảnh chụp ngẫu nhiên",
|
||||
"en": "Kugayama Shiori's Death Diary — a random capture"
|
||||
},
|
||||
"game-07.jpg": {
|
||||
"vi": "AI Limit — cutscene của boss",
|
||||
"en": "AI Limit — a boss cutscene"
|
||||
},
|
||||
"game-08.jpg": {
|
||||
"vi": "AI Limit — cutscene của boss",
|
||||
"en": "AI Limit — a boss cutscene"
|
||||
},
|
||||
"game-09.jpg": {
|
||||
"vi": "Ảnh chụp màn hình từ một game khác",
|
||||
"en": "A screenshot from another game"
|
||||
},
|
||||
"game-10.jpg": {
|
||||
"vi": "Ninja Gaiden 4 — nhân vật đang điều khiển",
|
||||
"en": "Ninja Gaiden 4 — the player character"
|
||||
},
|
||||
"game-11.jpg": {
|
||||
"vi": "Ninja Gaiden 4 — cutscene của boss",
|
||||
"en": "Ninja Gaiden 4 — a boss cutscene"
|
||||
},
|
||||
"game-12.jpg": {
|
||||
"vi": "Ninja Gaiden 4 — một NPC nữ",
|
||||
"en": "Ninja Gaiden 4 — a female NPC"
|
||||
},
|
||||
"game-13.jpg": {
|
||||
"vi": "AI Limit — cutscene của boss",
|
||||
"en": "AI Limit — a boss cutscene"
|
||||
},
|
||||
"game-14.jpg": {
|
||||
"vi": "AI Limit — nhân vật đang điều khiển",
|
||||
"en": "AI Limit — the player character"
|
||||
},
|
||||
"game-15.jpg": {
|
||||
"vi": "AI Limit — nhân vật đang điều khiển",
|
||||
"en": "AI Limit — the player character"
|
||||
},
|
||||
"game-16.jpg": {
|
||||
"vi": "AI Limit — cutscene của boss",
|
||||
"en": "AI Limit — a boss cutscene"
|
||||
},
|
||||
"game-17.jpg": {
|
||||
"vi": "Type-NOISE: Shonen Shojo — cutscene chụp ngẫu nhiên",
|
||||
"en": "Type-NOISE: Shonen Shojo — a cutscene, captured at random"
|
||||
},
|
||||
"game-18.jpg": {
|
||||
"vi": "Type-NOISE: Shonen Shojo — cutscene chụp ngẫu nhiên",
|
||||
"en": "Type-NOISE: Shonen Shojo — a cutscene, captured at random"
|
||||
},
|
||||
"game-19.jpg": {
|
||||
"vi": "Type-NOISE: Shonen Shojo — cutscene chụp ngẫu nhiên",
|
||||
"en": "Type-NOISE: Shonen Shojo — a cutscene, captured at random"
|
||||
},
|
||||
"game-20.jpg": {
|
||||
"vi": "Ảnh chụp màn hình từ một game khác",
|
||||
"en": "A screenshot from another game"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 250 KiB |
|
After Width: | Height: | Size: 369 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 245 KiB |
|
After Width: | Height: | Size: 289 KiB |
|
After Width: | Height: | Size: 177 KiB |
|
After Width: | Height: | Size: 183 KiB |
|
After Width: | Height: | Size: 172 KiB |