68 Commits
Author SHA1 Message Date
Gitea Actions b7fbf1399a chore(content): publish from admin (#4) 2026-11-24 02:25:39 +00:00
Gitea Actions 90ae9f4b80 chore(content): publish from admin (#2)
CI / build (push) Skipped
2026-11-24 02:01:03 +00:00
poli0981 fa48632276 Merge pull request 'fix(publish): record the build as the status main's protection requires (v2.4.1)' (#3) from fix/publish-status into main
CI / build (push) Successful in 5m9s
CI / publish (push) Skipped
Qodana / Qodana for JS (push) Successful in 2m51s
Reusable / Security / Secrets (gitleaks) (push) Successful in 11s
Reusable / Security / Rust (cargo-deny) (push) Skipped
Reusable / Security / .NET (NuGetAudit) (push) Skipped
Reusable / Security / SAST (Opengrep) (push) Failing after 28s
Reusable / Security / Dependencies (osv-scanner) (push) Successful in 17s
Security / security (push) Failing after 57s
CI / deploy (push) Successful in 2m46s
Reviewed-on: #3
2026-11-24 01:33:37 +00:00
poli0981andClaude Opus 5.5 9bb5350a34 docs: 2.4.1 — dispatched runs get no commit status on Gitea
CI / build (push) Skipped
CI / build (pull_request) Successful in 5m10s
CI / publish (pull_request) Skipped
CI / deploy (pull_request) Skipped
Lighthouse / lighthouse (pull_request) Successful in 6m8s
Qodana / Qodana for JS (pull_request) Successful in 3m35s
Reusable / Security / Secrets (gitleaks) (pull_request) Successful in 12s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 25s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 17s
Security / security (pull_request) Successful in 55s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:26:59 +07:00
poli0981andClaude Opus 5.5 66443e1153 fix(publish): record the build as the status main's protection requires
The first publish from the admin after the move stopped at its pull request: CI's
publish job tried to merge twice and Gitea answered 405 "Not all required status
checks successful". Gitea 28.4 writes commit statuses for push and pull_request runs
only, never for a dispatched run, so the content/bump commit never got the
`CI / build (*)` status branch protection requires.

The publish job (needs: build, now if: always()) records build's result as
`CI / build (workflow_dispatch)` on the commit it built, with a link to the run, and
only then merges and dispatches the deploy. A failed build is recorded as a failure and
merges nothing, so the admin shows "xuất bản lỗi" instead of building forever; a
cancelled one records nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 08:26:57 +07:00
poli0981 9bccbff69b Merge pull request 'chore: move the repository to Gitea (v2.4.0)' (#1) from chore/gitea-migration into main
CI / publish (push) Skipped
Qodana / Qodana for JS (push) Successful in 2m48s
Reusable / Security / Secrets (gitleaks) (push) Successful in 12s
Reusable / Security / Rust (cargo-deny) (push) Skipped
Reusable / Security / .NET (NuGetAudit) (push) Skipped
Reusable / Security / SAST (Opengrep) (push) Successful in 23s
Reusable / Security / Dependencies (osv-scanner) (push) Successful in 17s
Security / security (push) Successful in 54s
CI / deploy (push) Successful in 2m46s
CI / build (push) Skipped
Reviewed-on: #1
2026-11-23 18:50:00 +00:00
poli0981andClaude Opus 5.5 9a67566c6b ci: the preview listens on 127.0.0.1 in the runner's container
CI / build (push) Skipped
CI / build (pull_request) Successful in 5m25s
CI / publish (pull_request) Skipped
CI / deploy (pull_request) Skipped
Qodana / Qodana for JS (pull_request) Successful in 2m57s
Reusable / Security / Secrets (gitleaks) (pull_request) Successful in 36s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 23s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 17s
Security / security (pull_request) Successful in 1m18s
Lighthouse / lighthouse (pull_request) Successful in 5m56s
The second run kept the preview alive in the test step and still met ECONNREFUSED: in
the Gitea runner's container `localhost` made astro preview listen on ::1 only, while
Node's fetch in the a11y tests went to 127.0.0.1 (curl's check passed over IPv6).
CI and Lighthouse now start the preview with --host 127.0.0.1, the tests get
A11Y_BASE_URL=http://127.0.0.1:4321 and nginx proxies to 127.0.0.1. Checked locally:
160/160 a11y tests against a preview bound that way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:30:49 +07:00
poli0981andClaude Opus 5.5 0c90719dde ci(security): gitleaks ignores four public identifiers
CI / build (push) Skipped
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
CI / build (pull_request) Failing after 3m49s
CI / publish (pull_request) Skipped
CI / deploy (pull_request) Skipped
Qodana / Qodana for JS (pull_request) Canceled after 0s
Lighthouse / lighthouse (pull_request) Canceled after 4m31s
Reusable / Security / Secrets (gitleaks) (pull_request) Successful in 11s
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 23s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 17s
Security / security (pull_request) Successful in 52s
The ops repo's security.yml scans the whole history with gitleaks' default rules, and
its generic-api-key rule flagged four values that are not secrets: the forged Access
JWT the smoke test sends on purpose, the Access application's AUD tag, the Web
Analytics site tag every page carries, and the old SonarQube Cloud project key.
.gitleaksignore lists those four findings by commit:file:rule:line, with the reason
for each; anything else still fails the job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:17:39 +07:00
poli0981andClaude Opus 5.5 a409b03813 ci: keep servers and their tests in one step on the Gitea runner
PR #1's first run on Gitea: the a11y tests met ECONNREFUSED on port 4321 — the runner
(act) ends what a step started in the background when that step ends, so the preview
started in a step of its own was gone. Lighthouse never got that far: the runner
could not unpack treosh/lighthouse-ci-action (two files in its node_modules differ
only in case, on the runner's case-insensitive Windows disk).

- ci.yml: one step starts the preview, waits for it, runs the a11y tests and prints
  the server log when they fail.
- lighthouse.yml: Lighthouse CI 0.16.1 through npx (scripts off), in the same step as
  the preview and nginx; collect then assert, warn-only as before; reports still the
  lighthouse-reports artifact.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:15:23 +07:00
poli0981andClaude Opus 5.5 604c756813 docs(10): the report endpoint without the GitLab token
CI / build (push) Skipped
CI / build (pull_request) Failing after 3m37s
CI / publish (pull_request) Skipped
CI / deploy (pull_request) Skipped
Lighthouse / lighthouse (pull_request) Failing after 1m9s
Qodana / Qodana for JS (pull_request) Successful in 2m48s
Reusable / Security / Secrets (gitleaks) (pull_request) Failing after 11s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 24s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 17s
Security / security (pull_request) Failing after 52s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:04:09 +07:00
poli0981andClaude Opus 5.5 c13a37cfdc fix(report): reports still reach Discord without the GitLab token
CI / build (push) Skipped
CI / build (pull_request) Canceled after 0s
CI / publish (pull_request) Canceled after 0s
CI / deploy (pull_request) Canceled after 0s
Lighthouse / lighthouse (pull_request) Canceled after 0s
Qodana / Qodana for JS (pull_request) Canceled after 0s
Reusable / Security / Secrets (gitleaks) (pull_request) Failing after 11s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 22s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 15s
Security / security (pull_request) Failing after 48s
The endpoint answered 503 whenever the issue token was missing. Until the maintainer
provisions GITLAB_ISSUES_TOKEN (and whenever it is revoked) that would refuse every
report, where the dead GitHub token at least let the Discord notice through as a
degraded 202. It now needs Turnstile plus somewhere to put the report — the GitLab
issue or the Discord webhook — and skips the GitLab call when there is no token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:03:21 +07:00
poli0981andClaude Opus 5.5 f3d0546b0d docs: the design suite after the move to Gitea
CI / build (push) Skipped
CI / build (pull_request) Canceled after 0s
CI / publish (pull_request) Canceled after 0s
CI / deploy (pull_request) Canceled after 0s
Lighthouse / lighthouse (pull_request) Canceled after 0s
Qodana / Qodana for JS (pull_request) Canceled after 0s
Reusable / Security / Secrets (gitleaks) (pull_request) Failing after 11s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 22s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 15s
Security / security (pull_request) Failing after 49s
- 08 §0 "Forge & CI (Gitea)": where the repository and its mirror live, the runner
  and the 13:00–16:00 UTC window, the workflows, the deploy job, the required check
  `CI / build (*)`, Renovate, what was removed, and the ops runbook. The v2.x
  workflow details (§0b) are kept with dated notes.
- 00: decision D25 (the move, v2.4.0) and notes on D9, D17, D18, D21, D23, D24.
- 02, 06, 07, 10, 11, 17: the repo tree, secrets (GITEA_BOT_TOKEN,
  GITLAB_ISSUES_TOKEN, the Cloudflare Actions secrets), deploying from CI instead of
  Workers Builds, confidential GitLab issues for bug reports, the Gitea activity feed,
  Renovate and the security workflow in the maintenance routine.
- 01, 03, 04, 05, 13, 14, 15, 16 and the 12_LEGAL templates: GitHub mentions → Gitea
  or GitLab, Lighthouse on the runner image, costs, the roadmap line for v2.4.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:01:59 +07:00
poli0981andClaude Opus 5.5 4cdf68de7d fix(admin): "deploying" points at Gitea's Actions tab, not Workers Builds
CI / build (push) Skipped
CI / build (pull_request) Canceled after 0s
CI / publish (pull_request) Canceled after 0s
CI / deploy (pull_request) Canceled after 0s
Lighthouse / lighthouse (pull_request) Canceled after 0s
Qodana / Qodana for JS (pull_request) Canceled after 0s
Reusable / Security / Secrets (gitleaks) (pull_request) Failing after 11s
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 22s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 15s
Security / security (pull_request) Failing after 48s
The deploy is the CI job on the maintainer's runner now: it takes a few minutes, and
waits while the PC is off. The hint under the publish status says where to look, and
two comments stop naming Workers Builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 01:01:05 +07:00
poli0981andClaude Opus 5.5 7866666d26 docs(changelog): 2.4.0, the move to Gitea
Reusable / Security / Rust (cargo-deny) (pull_request) Skipped
Reusable / Security / .NET (NuGetAudit) (pull_request) Skipped
CI / build (pull_request) Canceled after 0s
CI / publish (pull_request) Canceled after 0s
CI / deploy (pull_request) Canceled after 0s
Lighthouse / lighthouse (pull_request) Canceled after 0s
Qodana / Qodana for JS (pull_request) Canceled after 0s
Reusable / Security / Secrets (gitleaks) (pull_request) Failing after 11s
Reusable / Security / SAST (Opengrep) (pull_request) Successful in 23s
Reusable / Security / Dependencies (osv-scanner) (pull_request) Successful in 16s
Security / security (pull_request) Failing after 50s
Triage / triage (pull_request_target) Successful in 3s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:55:04 +07:00
poli0981andClaude Opus 5.5 6892027626 docs(templates): GitLab issue and merge request templates
GitLab does not read GitHub/Gitea issue forms. .gitlab/issue_templates has Bug,
Accessibility and Language in Markdown, converted from .github/ISSUE_TEMPLATE (which
Gitea still reads), each applying its label; .gitlab/merge_request_templates/Default.md
is the PR template, noting that CI runs on Gitea, not on the mirror.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:51:21 +07:00
poli0981andClaude Opus 5.5 4e44f7a7f3 docs: README, CONTRIBUTING, ACCESSIBILITY and notices on Gitea
- README: badges from Gitea Actions (the SonarCloud one goes), a "Where things live"
  section, the clone URL, the deploy job in place of Workers Builds, GITEA_BOT_TOKEN for
  local admin saves, the quality tooling as it now is.
- CONTRIBUTING (EN + VI): the canonical repo on Gitea, issues and merge requests on the
  GitLab mirror, patches by e-mail to code@poli0981.dev; Renovate instead of
  Dependabot; out-of-scope requests are closed by hand (the triage bot is gone); ideas
  by e-mail now that Discussions are gone; the GitLab issue templates.
- ACCESSIBILITY: the Accessibility template on the mirror, the maintainer's Gitea
  profile, A11Y_CHANNEL=bundled for CI's Chromium.
- THIRD-PARTY-NOTICES: Gitea and GitLab instead of GitHub; the analysis tools as run now.
- The Gitea issue forms: the config's contact links (e-mail, SECURITY.md on Gitea) and
  the bug form's note on where site reports go; the PR template's links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:51:19 +07:00
poli0981andClaude Opus 5.5 3511fbe9ae docs(security): report by e-mail only
GitHub's private vulnerability reporting went with the old repository, Gitea has none,
and issues on the GitLab mirror are public. SECURITY.md now says e-mail
(security@poli0981.dev) is the only channel and that a report opened on the mirror by
mistake is made confidential; bug reports from the site are described as confidential
GitLab issues; the out-of-scope identities name Gitea and GitLab. security.txt's
Policy points at SECURITY.md on Gitea.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:51:18 +07:00
poli0981andClaude Opus 5.5 f21bce9674 chore(content): the submodule on Gitea, at the move's link edits
.gitmodules points src/content at git.poli0981.dev/poli0981/content; CI checks it out
from there, and so does content-bump.yml.

The bump to 114b8c9 carries the content repo's link edits for the move (licenses,
accessibility §5/§7, the project pages, third-party list) and privacy §4, effective
2026-11-24: bug reports are stored as confidential issues on GitLab instead of in a
private GitHub repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:48:45 +07:00
poli0981andClaude Opus 5.5 e90cc6fd65 chore: Renovate replaces Dependabot
Gitea has no Dependabot. renovate.json extends the shared preset
(local>poli0981/renovate-config): actions pinned to SHAs and kept current, minor and
patch updates grouped, OSV security PRs, the same 3-day wait for new npm releases
that Dependabot's cooldown gave, the labels dependencies/security. No schedule: the
central runner's daily cron is the schedule.

Dependabot's two holds carry over as package rules: no major update of `typescript`
(TS 7 has no JS API yet; the @typescript/native alias keeps its updates) and none of
prettier-plugin-astro (its 1.x reflow is a visual change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:48:35 +07:00
poli0981andClaude Opus 5.5 9aefec3bd9 fix(links): the code lives on Gitea now
The dev persona's GitHub profile link becomes the Gitea profile
(git.poli0981.dev/poli0981), with a generic code-brackets glyph instead of GitHub's
mark; the About page and the console banner point at the Gitea repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:48:08 +07:00
poli0981andClaude Opus 5.5 e32304443c fix(widgets): the activity widget reads Gitea's public feed
The home page's activity list came from GitHub's events API, gone with the account.
Decision PD3 of the migration: the widgets cron reads
git.poli0981.dev/api/v1/users/poli0981/activities/feeds (only the owner's own
actions), which answers without a token and lists public repositories only (checked
2026-11-24). Pushes (`commit_repo`, with Gitea's real commit count) and releases
(`publish_release`, the tag) are stored in the widget's existing shape, so a feed
kept in KV from before still renders; pushes listed a second time without content are
skipped. The optional GITHUB_TOKEN of the widgets worker goes.

The widget links to the repository on Gitea, its title says Gitea, and the component
is WidgetGitea.svelte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:48:06 +07:00
poli0981andClaude Opus 5.5 e528dcf6ac fix(admin): content saves and publishing through Gitea
The admin read and wrote poli0981/content through GitHub's REST, Git Data and GraphQL
APIs with two fine-grained tokens; both went with the account. src/lib/admin/gitea.ts
replaces src/lib/admin/github.ts (decision D12 of the migration):

- One Worker secret, GITEA_BOT_TOKEN: a write:repository token of the bot user
  poli0981-bot, a Write collaborator on the content and site repos only. Gitea scopes
  a token by its user's access, not by repository, so the old content/publish token
  split (and the admin's single-token warnings) goes; the bot still pushes nothing to
  the site repo, publishing goes through content-bump.yml.
- Listing: the branch head, the recursive tree, then the file contents in batches of
  50 (POST …/file-contents), instead of one GraphQL query.
- Saving: Gitea's change-files call commits every file in one commit and checks each
  file's sha itself, the lock that replaces the ref fast-forward and its retry; a stale
  sha becomes the same ConflictError as before.
- Publish status: the open content/bump PR, its `CI / build (…)` commit status, its
  body marker for "merges itself", and the last content-bump.yml run.
- Links to commits and runs point at git.poli0981.dev; a refused token reads as
  gitea_permission with what the bot needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:47:56 +07:00
poli0981andClaude Opus 5.5 ab544d8eba fix(report): site bug reports become confidential issues on the GitLab mirror
The reports went to a private GitHub repository, which went with the account.
Decision D14 of the migration: issues on the GitLab mirror (gitlab.com/poli0981/
poli0981-dev, wrangler var REPORT_PROJECT) through GitLab's API, with a new Worker
secret GITLAB_ISSUES_TOKEN (Reporter role, scope api) in place of GITHUB_ISSUES_TOKEN.

Every report is created confidential: it carries the reporter's description, route
and browser details, and the privacy policy promises only the owner sees it (the
content repo's privacy §4 now names GitLab). Reporter text cannot ping anyone or run
a GitLab quick action: a line that starts with "/" gets a zero-width space in front.
When GitLab fails, the Discord notice still carries the report (202), as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:47:41 +07:00
poli0981andClaude Opus 5.5 7215d59f31 ci(content): the admin's publish runs on Gitea's API
content-bump.yml used `gh` to open the content/bump PR, enable GitHub's auto-merge and
dispatch CI. On Gitea the same steps are calls to Gitea's API with the job token, in
scripts/content-publish.mjs (unit-tested):

- `open` (content-bump.yml): open or update the PR, write in its body whether it
  merges itself (<!-- publish: auto --> for Markdown/JSON, <!-- publish: review -->
  when MDX changed, with a comment), and dispatch ci.yml on content/bump: a PR the job
  token opens starts no workflow.
- `merge` (ci.yml's new publish job, after `build` passed on the dispatched run):
  squash-merge the PR at the commit CI built when its body says auto, then dispatch
  ci.yml on main, because the job token's merge commit starts no workflow either; that
  run deploys. A refused merge fails the job and says so on the PR; merging by hand
  deploys as usual.

Decision D5 named Gitea's merge_when_checks_succeed. The merge happens in CI instead:
the scheduled merge would also be the job token's push, so nothing would deploy it,
and the body marker gives the admin the "merges itself" flag Gitea's API lacks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:47:15 +07:00
poli0981andClaude Opus 5.5 b2c5062a05 ci(deploy): main deploys from Gitea CI with wrangler
Cloudflare Workers Builds pulled from GitHub and stopped with it (the maintainer has
disconnected it). Decision D3 of the migration: a deploy job in ci.yml, on a push to
main or a dispatch on main, after `build` passed on the same commit. It rebuilds with
the production settings Workers Builds' build variables used to give (the public
Turnstile site key, the Web Analytics beacon), runs `wrangler deploy` with the
user-level CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID secrets, and waits until
/api/health reports the commit.

PRs and other branches get no preview versions: that would put the Cloudflare token
within reach of a PR's code. The workflow's permissions move to the jobs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:35:56 +07:00
poli0981andClaude Opus 5.5 3948377cfe ci(qodana): the Qodana CLI instead of the action; findings stay an artifact
JetBrains/qodana-action relies on GitHub's APIs (annotations, PR comments, the SARIF
upload to code scanning), none of which Gitea has. The job now runs the Qodana CLI
2026.3.1 in native mode, downloaded at the version and SHA-256 the ops repo's
reusable-qodana.yml pins, after the same install and type generation as before.
Results still go to Qodana Cloud; the SARIF and HTML report become the qodana-report
artifact. Renovate's PRs skip the job, as Dependabot's did, and so does a run without
QODANA_TOKEN.

A local job rather than a caller of reusable-qodana.yml: the scan needs this repo's
generated binding types, and the ops tag callers pin predates the reusable workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:34:52 +07:00
poli0981andClaude Opus 5.5 bb03c4e9ca ci: the ops repo's security checks replace the OSV workflow
osv-scanner.yml called Google's reusable workflow and uploaded SARIF to GitHub code
scanning, which Gitea does not have. The ops repo's security.yml (pinned to the commit
of ops v2026.11.1) runs gitleaks over the whole history, Opengrep with the JS/TS rules
and osv-scanner over package-lock.json; reports are artifacts.

Weekly on Wednesday 14:13 UTC, this repo's slot in the ops cron registry (the old
Monday 03:17 UTC run falls outside the 13:00–16:00 UTC window the runner keeps), and
on every push to main and every PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:34:18 +07:00
poli0981andClaude Opus 5.5 407390c2f9 ci: Chrome and artifacts on the Gitea runner's image
GitHub's ubuntu image shipped Google Chrome, nginx and a sudo user; the Gitea runner's
image (docker.gitea.com/runner-images) has neither browser nor nginx, and its job
container runs as root.

- ci.yml: the accessibility tests take Playwright's Chromium at the lockfile's version
  (A11Y_CHANNEL=bundled), cached per Playwright version, when the image has no Chrome.
- lighthouse.yml: the same Chromium through CHROME_PATH, --no-sandbox for root
  (lighthouserc.json), nginx installed when missing, and the reports uploaded with
  christopherhx/gitea-upload-artifact: the action's own upload uses GitHub's artifact
  service, which refuses other servers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:34:03 +07:00
poli0981andClaude Opus 5.5 7c1bb3efea ci: drop SonarQube Cloud, as the migration's decision D1 says
The maintainer removed SonarQube Cloud from every repository (D1): the sonarcloud job,
sonar-project.properties, and the coverage upload that existed only to feed it. The
unit tests still enforce 80% line coverage in the build job. Qodana and the ops
repo's Opengrep cover the analysis. The docs follow in their own commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:32:47 +07:00
poli0981andClaude Opus 5.5 7db93e2b3b ci: remove the maintenance-mode triage, which needs GitHub
triage.yml ran on GitHub's issue and pull_request_target events with
actions/github-script. On Gitea outsiders cannot open issues or PRs (registration is
off), and the GitLab mirror's issues never reach Gitea Actions, so the bot has
nothing to watch. Decision D2 of the migration: the workflow and its script go;
the policy stays in CONTRIBUTING.md, and out-of-scope requests on the mirror are
closed by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:31:57 +07:00
poli0981andClaude Opus 5.5 9e14ad89f4 ci: move the workflows to .gitea/workflows
Gitea Actions reads .gitea/workflows first (runbook §3.2 item 1). The files move
unchanged here; the changes each one needs follow in their own commits. The issue
forms and the PR template stay under .github/, which Gitea also reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 00:31:44 +07:00
poli0981andClaude Opus 5.5 2ef30458a4 docs: the Workers Builds deploy command is fixed (2026-11-21) (#141)
From October to November 2026 the main branch's deploy command uploaded versions without
deploying them, so every release went live by a manual promote. The owner set it to
`npx wrangler deploy` on 2026-11-21; merging this is also the first check that a merge now
deploys by itself.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:11:07 +07:00
poli0981andClaude Opus 5.5 7bcbcf59dd docs: maintenance mode — policy, triage bot, issue forms, status badge, docs for 2.3.0 (#139)
* docs: maintenance mode — policy, triage bot, issue forms, status badge, docs for 2.3.0

From v2.3.0 the project takes no new features (CONTRIBUTING.md, in Vietnamese and
English). Accepted: scheduled dependency updates; security fixes (High/Critical
advisories, runtime vulnerabilities); major language/runtime/framework upgrades; bug
fixes including UI/UX and accessibility; language fixes.

- .github/workflows/triage.yml + scripts/triage.mjs (unit-tested): an issue or pull
  request whose title or label asks for a feature is labelled enhancement + out-of-scope,
  answered in both languages and closed (issues as "not planned"). The owner's items, bots,
  `maintenance-exception` and anything the owner does are left alone. It runs on
  pull_request_target but checks out only that one script from the default branch, never a
  pull request's code; workflow_dispatch is a dry run.
- Issue forms: blank issues off, questions and ideas to Discussions, security to the
  private policy; a new language-problem form; the bug form no longer claims the site's
  report button fills it (those reports go to a private repository). The pull request
  template asks which of the five kinds of change it is.
- README: a maintenance-mode badge and a Status section; the admin paragraph describes
  auto-publish. SECURITY.md: High/Critical fixes ship out of schedule; the age-check
  answer is local storage only.
- Docs: decisions D21–D24, maintenance policy and cadence (17 §0, QODANA_TOKEN rotation),
  roadmap frozen, CI (Qodana, whole-tree licences, triage, merge rules), architecture
  tree, the Workers Builds deploy command, licence notes without the stale
  license-checker/GSAP lines.
- CHANGELOG [2.3.0]; sonar.projectVersion 2.3.0.

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

* docs: link #138 in the 2.3.0 changelog

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

* docs: album labels come from both language entries

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

* fix(ci): triage without a checkout, and linear title patterns

SonarCloud and Qodana on #139:
- githubactions:S7631 flags any checkout in a pull_request_target workflow, even of the
  default branch. The workflow now reads scripts/triage.mjs from the default branch through
  the API and imports it from a data: URL — nothing is checked out at all.
- javascript:S8786: `\s+a?\s*` let two quantifiers compete for the same spaces. The title
  is trimmed once and the patterns are written so no two quantifiers overlap.
- Qodana RegExpRedundantEscape: the bot check is `endsWith("[bot]")`, no regex.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:48:09 +07:00
poli0981andClaude Opus 5.5 484907439a feat(content): content labels, an age check, blurred images and a warning banner (#138)
* feat(content): content labels, an age check, blurred images and a warning banner

Posts, chapters and albums can carry content labels and an age rating:
- Labels (src/lib/content-labels.ts, names in src/i18n `labels`): horror, blood,
  jumpscare, violence, self-harm, death — banner and blurred images; politics,
  religion, strong-language, flashing-lights, spoilers — banner only. `contentWarning`
  moves from stories to every long-form entry and albums, and single gallery photos can
  carry their own (R2 list or captions.json). Unknown labels fail the build.
- Banner (ContentNotice.astro, replaces ContentWarning.astro): names every label in the
  page's language, skipped by search. Images in a labelled region are blurred in plain
  CSS by default — nothing sharp flashes before a script — and a real "Hiện ảnh"
  checkbox un-blurs them through :has(), so it works with the keyboard and with
  JavaScript off. A region without pictures shows no such line.
- Age check (AgeGate.astro, src/lib/age-gate.ts) for `ageRating` 13+/16+/18+: the text
  sits in a closed <details> (search indexes the title, not the text); its summary asks
  in a native modal <dialog> — focus starts on "No", Esc cancels and never means yes,
  "No" explains and offers to choose again — and the answer is kept in localStorage
  only (age thresholds, never an age or birth date). It never pops up on its own, and
  without JavaScript the summary simply opens the text.
- Everywhere else: story/post/album cards name the labels (blurred covers), the lightbox
  shows labelled photos blurred behind "Hiện ảnh", RSS descriptions start with the
  warning in the item's language, OG cards carry it for blog posts too, JSON-LD
  contentRating. The post page now uses the cover's alt text when there is one.
- Admin: a `multiselect` field for labels (with Vietnamese names), an age-rating select,
  and per-photo labels in the gallery manager.
- Content (poli0981/content 98f7692): privacy policy §6 lists the age-check answer;
  "Đêm không tiếng" chapters 1–2 are rated 16+.
- Tests: label and age-check logic, admin validation, labels kept on album save, RSS
  prefix; the accessibility suite scans the gate folded and asked, checks focus, Esc,
  No/Yes/reset and the keyboard reveal.

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

* test(a11y): appendChild for the blur probe (astro check's DOM typing)

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

* fix(content): findings from an independent review of the labels branch

- Album pages: the lightbox now sits outside the labelled section, whose blur rule also
  blurred the viewer's photo — its "show" button removed the veil but not the blur.
- Age check: the browser opens a <details> by itself (find-in-page, a #:~:text= link
  from a search engine, an #id inside the text); without a "yes" on record the gate now
  folds it straight back. After "Chọn lại" → "Có", focus moves to the summary instead of
  being lost with the row that just hid.
- Search indexes nothing inside the gate, not even its status lines, which could have
  become the excerpt of a page the reader has not been let into.
- Albums take their labels and age rating from BOTH language entries (same photos, two
  pages; the stricter rating wins), on the album page and on its card.
- An age-rated post folds its cover away with the text (PostCover.astro), and post and
  album cards blur the cover of age-rated items too. The album card names the cover
  photo's own labels, not only the album's.
- Tests: the gate re-folds an unasked open and keeps focus after choosing again;
  albumWarning merges both languages.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:30:09 +07:00
poli0981andClaude Opus 5.5 15559ecc90 feat(admin): publish on every save, and say when the change is actually live (#137)
Saving or deleting in the admin now starts the publish workflow by itself, and the admin
follows the change all the way to production instead of stopping at "merged".

- Auto-publish: content saves/deletes and album saves/deletes dispatch content-bump.yml
  after their commit (lib/admin/autopublish). The workflow's concurrency group already
  coalesces bursts (one run going, one waiting, the waiting one reads the newest main). A
  failed dispatch keeps the save and is reported ("publish": "failed"); "Xuất bản" stays
  as the manual retry. Audit action publish.auto.
- Live status: the build records the content commit its src/content points at
  (__CONTENT_COMMIT__, from the gitlink in HEAD); /api/health and the admin report it as
  version.content. A pure publishPhase() turns content head, main's pointer, the running
  build, the bump PR and the last run into live / pending / building / review / deploying /
  failed, shown by the PublishBar and the dashboard (which now reads it live too).
- Fixes found while tracing the flow:
  - validation now matches the content schema, so a save can't queue a red build:
    chapter is a positive integer, cover and coverMedia can't both be set, album is a slug
    and must already have photos;
  - the tags inputs update on input, so Ctrl/⌘+S no longer saves the previous tags;
  - commits in the public content repo say "via admin" without the admin's email (the
    private audit log keeps who did what);
  - deleting an image also checks the content the live site was built from, not only
    main;
  - the cover gets an alt field in the editor, and the picker takes alt text for uploads;
  - one-shot stories (stories/<slug>.md) can be opened and created.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:05:33 +07:00
poli0981andClaude Opus 5.5 0c56acd806 ci: Qodana analysis and a licence check over the whole dependency tree (#135)
* ci: Qodana analysis and a licence check over the whole dependency tree

- Qodana (JetBrains, Qodana for JS) runs on every PR, on main and by hand
  (.github/workflows/qodana.yml, settings in qodana.yaml): native mode on the runner's
  Node 26 after `npm ci --ignore-scripts` and the generated types, profile
  qodana.recommended over the whole repository, build output, generated files, the
  content submodule and the design docs excluded, spelling/grammar checks off (they do
  not read Vietnamese). Results go to Qodana Cloud and, for main, to code scanning as
  SARIF. Dependabot and fork PRs skip it (no secrets), so it stays advisory.
- Licences: the allowlist moves to scripts/license-policy.mjs, shared by gen-notices
  (direct dependencies, THIRD-PARTY-NOTICES.md) and a new check-licenses step in the
  build job that reads every package in package-lock.json — transitive ones and every
  platform binary — with a small SPDX evaluator (OR, AND, WITH, parentheses). Packages
  with no licence fail; reviews are per package with a reason instead of per licence
  (an MPL note written for satori used to clear @axe-core/playwright too). Today:
  735 packages, 42 cleared (MPL-2.0 build/test tools, sharp's LGPL libvips).
- README badges and Quality row, THIRD-PARTY-NOTICES tool list.

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

* fix: Qodana's first findings, and a zero-problem quality gate

The first Qodana run reported 11 problems; all are handled:
- scripts/smoke-worker.mjs: the forged Access JWT is now built from its JSON parts at run
  time (same bytes) instead of sitting in the source as a token literal, which secret
  scanners rightly flag; the "did not come up" case reports through the same helper as
  any other failure instead of throwing into its own catch.
- scripts/check-csp-hashes.mjs: ("|') → ["'] in the JSON-LD matcher.
- src/lib/format.ts: drop the two escapes of `]` outside a character class (a lone `]`
  is a literal there); the classes keep theirs.
- src/lib/legal-lang.ts: the heading → language table is a Map, so "Tiếng Việt" is data,
  not a property name mixing scripts.
- qodana.yaml: ES6PreferShortImport off, with the reason — the build scripts and
  astro.config.mjs run under plain Node, where the `@/` alias doesn't resolve and a
  TypeScript import keeps its `.ts`.
- failThreshold: 0, so any new problem turns the check red.

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

* fix: sort the licence report with an explicit compare function

Sonar S2871: Array#sort() without a compare function sorts by UTF-16 code units, which
is not alphabetical for every name. Both lists now sort with localeCompare.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:55:31 +07:00
dependabot[bot] 1b7364a2aa chore(deps-dev): Bump typescript-eslint (#136)
Bumps the dev-tools group with 1 update in the / directory: [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint).


Updates `typescript-eslint` from 8.72.2 to 8.73.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.73.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: typescript-eslint
  dependency-version: 8.73.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-tools
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-21 07:36:51 +07:00
poli0981andClaude Opus 5.5 f384bc6e16 chore(deps): November 21 updates, Prettier Svelte 4.2 formatting, no more deepmerge ignore (#134)
- npm update --save --before=2026-11-18 (keeps the 3-day cooldown): astro 7.4.12,
  @astrojs/cloudflare 14.4.8, @astrojs/mdx 8.1.6, @astrojs/sitemap 3.7.5,
  @astrojs/svelte 9.1.6, jose 6.2.17, marked 18.2.1, eslint 10.15.0,
  eslint-plugin-svelte 3.24.1, knip 6.45.1, playwright 1.65.1, prettier 3.10.1,
  prettier-plugin-svelte 4.2.0, typescript-eslint 8.72.2, wrangler 4.164.0.
  Supersedes Dependabot #129-#133.
- prettier-plugin-svelte 4.2.0 breaks long tags at their edges instead of hugging the
  text, so 14 Svelte files are reformatted. Svelte 5 drops whitespace at the start and
  end of a tag, so the rendered markup is unchanged (compiled before/after samples
  produce identical output).
- osv-scanner.toml: deepmerge GHSA-gcqx-w48m-w2h4 (alias CVE-2026-93753) was withdrawn
  on 2026-11-16 and OSV no longer reports deepmerge 4.3.1, so both ignores go.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:26:03 +07:00
dependabot[bot] 76869fabec chore(deps): Bump google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml (#128)
Bumps [google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml](https://github.com/google/osv-scanner-action) from 2.7.0 to 2.7.1.
- [Release notes](https://github.com/google/osv-scanner-action/releases)
- [Commits](https://github.com/google/osv-scanner-action/compare/b1d267aea5211fa648d9d442fa64b90dbdcbdd36...32d3cd482bdadfb38b186c0ad1b031902d55d932)

---
updated-dependencies:
- dependency-name: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml
  dependency-version: 2.7.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-21 07:11:39 +07:00
dependabot[bot] 6824c92fa0 chore(deps): Bump SonarSource/sonarqube-scan-action from 8.4.1 to 8.5.0 (#127)
Bumps [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action) from 8.4.1 to 8.5.0.
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/e805d875275f728fac1885b413934be6d7c63f65...59202af334b4ba7b5db01b701b8e79f8b3bef0f4)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-21 07:11:29 +07:00
poli0981andClaude Fable 5.2 24d7c1b117 test(a11y): wider coverage, status checks, and claims that match it
Every sitemap page is checked for sideways scrolling at 320px; the light-theme and phone scans cover a page of every template; a page that does not answer the expected status fails instead of being scanned as an error page; the search focus trap is exercised with results listed; the legal notice is checked at tablet and small-laptop sizes; the story reader is walked backwards with Shift+Tab; each half of a legal page must declare its language. ACCESSIBILITY.md says what the palette test and the suite actually cover, and that the live widgets are not in the test build. CI prints the preview log when the job fails.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-09 20:53:14 +07:00
poli0981andClaude Opus 5.5 b4555d13d2 chore(deps): November updates, minimatch 11 override, OSV ignore for deepmerge (#123)
- npm update within Dependabot's three-day cooldown (--before 2026-11-06):
  Astro 7.4.7, @astrojs/cloudflare 14.4.6, mdx 8.1.3, svelte 9.1.2,
  Svelte 5.57.3, Tailwind 4.3.4, jose 6.2.15, marked 18.1.3, Pagefind 1.6.0,
  Wrangler 4.158, ESLint 10.14, typescript-eslint 8.72.1, knip 6.44.
- overrides.minimatch ^11.0.4 for GHSA-g3hv-75wg-m249 (ESLint and
  typescript-eslint still ask for ^10; they only use Minimatch#match).
- osv-scanner.toml: ignore deepmerge GHSA-gcqx-w48m-w2h4 until 2027-02-09
  (no fixed release; build-time config merge only).
- knip.json: drop the obsolete cloudflare ignoreDependencies hint.
- CHANGELOG: 2.1.2.

Supersedes Dependabot #117-#122.

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

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

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

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

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

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

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

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

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

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

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

CHANGELOG 2.1.1; Sonar project version 2.1.1.

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

No files matched your search

+298
View File
@@ -0,0 +1,298 @@
name: CI
# PRs always run: `build` is the required status check of main's branch protection, 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 — they deploy nothing either.
# NOTE: use `*.md` (root-level) — NOT `**/*.md` — because blog/story content lives at
# src/content/**/*.{md,mdx}.
#
# A push to main (and a dispatch on main) also deploys: the `deploy` job below.
on:
pull_request:
# 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"]
# Explicit, and granted per job: a grant made up here would reach every job, one added
# later included.
permissions: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# Cancel superseded PR runs; let main runs finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
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:
# 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@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 --ignore-scripts
# …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: |
npm run types
npm run types:widgets
- name: Format check
run: npm run format:check
- name: Lint
run: npm run lint
# .astro, .svelte and .ts through Volar — the TypeScript 6 API (TS 7.0 has none).
- name: Type check (astro check)
run: npm run check
# 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: |
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.
- 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: npm run check-exif -- --changed
- name: Build
run: npm run build
# 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 by Chrome.
# 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.
#
# GitHub's ubuntu image shipped Google Chrome; the Gitea runner's image
# (docker.gitea.com/runner-images) has none, so the job takes Playwright's own
# Chromium at the version the lockfile pins (A11Y_CHANNEL=bundled, tests/a11y/
# support.ts), cached per Playwright version. An image that has Chrome keeps using it.
# The job container runs as root; Playwright starts Chromium without its sandbox by
# default (chromiumSandbox: false), which is what a root user needs.
- name: Which Chrome
id: chrome
run: |
if [ -x /usr/bin/google-chrome ]; then
echo "system=true" >> "$GITHUB_OUTPUT"
else
echo "system=false" >> "$GITHUB_OUTPUT"
echo "playwright=$(node -p "require('playwright/package.json').version")" >> "$GITHUB_OUTPUT"
fi
- name: Cache Playwright's Chromium
id: pw-cache
if: steps.chrome.outputs.system != 'true'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/ms-playwright
key: playwright-chromium-${{ runner.os }}-${{ steps.chrome.outputs.playwright }}
# A cache hit restores the browser, not the system libraries it links.
- name: Playwright's Chromium
if: steps.chrome.outputs.system != 'true'
env:
CACHE_HIT: ${{ steps.pw-cache.outputs.cache-hit }}
run: |
if [ "$CACHE_HIT" = "true" ]; then
npx playwright install-deps chromium
else
npx playwright install --with-deps chromium
fi
echo "A11Y_CHANNEL=bundled" >> "$GITHUB_ENV"
# One step, server and tests together: the Gitea runner (act) ends what a step started
# in the background when that step ends. And on 127.0.0.1 explicitly: in the runner's
# container `localhost` made the preview listen on ::1 only, while Node's fetch in the
# tests went to 127.0.0.1 (PR #1's first runs: ECONNREFUSED on 4321).
- name: Accessibility tests (axe + keyboard)
env:
A11Y_BASE_URL: http://127.0.0.1:4321
run: |
npm run preview -- --host 127.0.0.1 > "$RUNNER_TEMP/preview.log" 2>&1 &
preview=$!
up=false
for i in $(seq 1 60); do
if curl -sf -o /dev/null http://127.0.0.1:4321/; then
echo "preview up after ${i}s"; up=true; break
fi
sleep 1
done
if [ "$up" != true ]; then
echo "preview server never came up"; cat "$RUNNER_TEMP/preview.log"; exit 1
fi
status=0
npm run test:a11y || status=$?
if [ "$status" -ne 0 ]; then
echo "--- preview server log (last 100 lines) ---"
tail -n 100 "$RUNNER_TEMP/preview.log" || true
fi
kill "$preview" 2>/dev/null || true
exit "$status"
# Content publish, second half (content-bump.yml is the first): when the admin's publish
# dispatched this run on content/bump, record `build`'s result as the commit status main's
# branch protection requires — Gitea writes none for a dispatched run, so without this the
# merge is refused (405) — and, when it passed, merge the content/bump PR (Markdown/JSON
# only — an MDX publish waits for a review) and dispatch this workflow on main, which
# deploys. The dispatch is needed because nothing the job token does starts a workflow, its
# merge commit included. If the merge is refused, the job fails and says so on the PR; a
# merge by hand deploys as usual. `always()`: a failed build is recorded too, so the admin
# shows "xuất bản lỗi" instead of building forever.
publish:
needs: build
if: always() && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/content/bump'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: write # the commit status, the merge
pull-requests: write # the merge, a comment when it fails
actions: write # dispatch ci.yml on main
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record the build, merge the publish PR, deploy main
env:
TOKEN: ${{ github.token }}
API: ${{ github.api_url }}
REPO: ${{ github.repository }}
SHA: ${{ github.sha }}
BUILD: ${{ needs.build.result }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: node scripts/content-publish.mjs merge
# Production. Cloudflare Workers Builds pulled from GitHub and stopped with it, so main
# deploys from here (migration decision D3): after `build` passed on the same commit,
# rebuild with the production settings and `wrangler deploy` at 100%. Nothing else
# deploys: PRs and other branches get no preview versions, which would put the Cloudflare
# token within reach of a PR's code (Gitea gives same-repo PRs the secrets, Renovate's
# included).
#
# The workflow's concurrency group keeps main runs in order and never cancels one, so two
# quick merges deploy one after the other, the newer last. The runner lives on the
# maintainer's PC: a merge made while it is off deploys when it comes back.
deploy:
needs: build
if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
submodules: recursive # the content, and HEAD:src/content for /api/health
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
cache: npm
- name: Install
run: npm ci --ignore-scripts
# What Workers Builds' build variables did: the Turnstile site key (public — every
# gated page carries it) is inlined into the client, and the Cloudflare Web Analytics
# beacon is switched on for production builds only (astro.config.mjs). GITHUB_SHA,
# which Gitea sets too, becomes the commit /api/health reports.
- name: Build (production)
env:
PUBLIC_TURNSTILE_SITE_KEY: "0x4AAAAAAD5Cup6ayN5o78wu"
PUBLIC_CF_BEACON: "true"
run: npm run build
# Token scope (docs 07): Account → Workers Scripts: Edit, plus what the bindings
# need to resolve (KV, R2, routes and custom domains on the zone). User-level
# Actions secrets on Gitea, shared by the web repos. Plain `wrangler` finds the
# generated config on its own: the build writes .wrangler/deploy/config.json
# pointing at dist/server/wrangler.json.
- name: Deploy to Cloudflare Workers
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
WRANGLER_SEND_METRICS: "false"
run: npx wrangler deploy --message "main ${GITHUB_SHA:0:7}"
# The deploy is live when the site says so: /api/health reports the commit of the
# build it runs (src/lib/version.ts).
- name: Live
run: |
for i in $(seq 1 30); do
live=$(curl -fsS https://poli0981.dev/api/health | node -e '
let s = ""; process.stdin.on("data", (d) => (s += d));
process.stdin.on("end", () => { try { console.log(JSON.parse(s).version.commit ?? ""); } catch { console.log(""); } });
' || true)
if [ "$live" = "$GITHUB_SHA" ]; then echo "live: $live"; exit 0; fi
sleep 4
done
echo "::error::/api/health still reports ${live:-nothing}, not $GITHUB_SHA"
exit 1
+87
View File
@@ -0,0 +1,87 @@
name: Content publish
# "Publish" in the admin (admin.poli0981.dev) dispatches this, and so does every admin save.
# It points the src/content submodule at poli0981/content's main, commits that on the
# content/bump branch, opens (or updates) a PR, and starts CI on the bump commit. When only
# Markdown/JSON changed, CI's `publish` job merges the PR once `build` passed there and
# starts the deploy of main (ci.yml).
#
# Why a workflow: the admin's token never pushes code to this repository; the most it can
# do here is start this workflow. MDX runs code at build time, so a publish that touches
# anything other than .md/.json waits for a human review instead of merging itself.
#
# Gitea, not GitHub (migration decision D5): `gh` is gone, the PR and the CI dispatch are
# plain calls to Gitea's API with the job token. A PR opened with the job token starts no
# workflow, so CI is dispatched on content/bump. Whether the PR merges by itself is in its
# body (`<!-- publish: auto -->` or `<!-- publish: review -->`), where the admin reads it:
# Gitea's API has no auto-merge field.
on:
workflow_dispatch:
permissions: {}
# One run at a time, never cancelled: a run waiting behind a running one reads the newest
# content main when it starts, so quick saves in a row end in one more publish, not many.
concurrency:
group: content-bump
cancel-in-progress: false
jobs:
bump:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write # push content/bump
pull-requests: write # open or update the PR, comment on it
actions: write # dispatch 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 and push content/bump
if: steps.bump.outputs.changed == 'true'
env:
NEW: ${{ steps.bump.outputs.new }}
FILES: ${{ steps.bump.outputs.files }}
run: |
git config user.name "Content publish"
git config user.email "actions@noreply.git.poli0981.dev"
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
- name: Open or update the PR, queue CI
if: steps.bump.outputs.changed == 'true'
env:
TOKEN: ${{ github.token }}
API: ${{ github.api_url }}
REPO: ${{ github.repository }}
NEW: ${{ steps.bump.outputs.new }}
AUTO: ${{ steps.bump.outputs.auto }}
run: node scripts/content-publish.mjs open
+148
View File
@@ -0,0 +1,148 @@
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 it is not a required check of main's branch protection (Gitea still shows a
# failed run red, continue-on-error or not). 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
env:
# Lighthouse CI itself, at a pinned version (released 2026-11-11). It was bundled in
# treosh/lighthouse-ci-action, which the Gitea runner cannot unpack (two files in its
# node_modules differ only in case, and the runner's action cache sits on a
# case-insensitive Windows disk). npx installs it in the job container instead; the
# job holds no secret. Bump by hand: Renovate does not read this line.
LHCI_VERSION: 0.16.1
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
submodules: recursive # src/content, or the build has no content to measure
persist-credentials: false
- 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
# GitHub's image shipped Google Chrome; the Gitea runner's image has none, so Lighthouse
# gets Playwright's Chromium at the version the lockfile pins (CHROME_PATH is what
# chrome-launcher reads). The job runs as root, where Chrome refuses to start with its
# sandbox on: lighthouserc.json passes --no-sandbox (the pages are this build, on
# localhost).
- name: Chrome for Lighthouse
run: |
if [ -x /usr/bin/google-chrome ]; then
echo "CHROME_PATH=/usr/bin/google-chrome" >> "$GITHUB_ENV"
else
npx playwright install --with-deps chromium
echo "CHROME_PATH=$(node -p "require('playwright').chromium.executablePath()")" >> "$GITHUB_ENV"
fi
# Cloudflare's edge compresses every text response in production; the preview does not.
# Lighthouse measures through nginx (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. GitHub's image had nginx and a
# user with sudo; the Gitea runner's job container runs as root and has no nginx.
- name: nginx for the compressing proxy
run: |
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO=sudo
if ! command -v nginx >/dev/null; then
$SUDO apt-get update -qq
$SUDO apt-get install -y -qq --no-install-recommends nginx
fi
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://127.0.0.1:4321;
proxy_http_version 1.1;
proxy_set_header Accept-Encoding "";
}
}
}
EOF
$SUDO nginx -t -c "$RUNNER_TEMP/nginx.conf"
# Everything that has to stay up runs in this one step: the Gitea runner (act) ends what
# a step started in the background when that step ends. `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.
#
# Four representative pages (docs 14 §3): home, a blog post, a story chapter, a gallery
# album — the heaviest template of each kind — collected and asserted against
# lighthouserc.json (warn-only). Nothing is uploaded to Google's public storage.
- name: Lighthouse
run: |
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO=sudo
# 127.0.0.1, not localhost: in the runner's container `localhost` binds ::1 only.
npm run preview -- --host 127.0.0.1 > "$RUNNER_TEMP/preview.log" 2>&1 &
$SUDO nginx -c "$RUNNER_TEMP/nginx.conf"
up=false
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"; up=true; break
fi
sleep 1
done
if [ "$up" != true ]; then
echo "preview server never came up"; cat "$RUNNER_TEMP/preview.log"; exit 1
fi
# --ignore-scripts: nothing in Lighthouse CI needs an install script, and the repo's
# .npmrc (strict-allow-scripts) would refuse any it does not know.
lhci() { npx --yes --ignore-scripts "@lhci/cli@${LHCI_VERSION}" "$@"; }
lhci collect --config=./lighthouserc.json \
--url=http://127.0.0.1:4322/ \
--url=http://127.0.0.1:4322/blog/lan-dau-viet-truyen/ \
--url=http://127.0.0.1:4322/truyen/dem-khong-tieng/chuong-01/ \
--url=http://127.0.0.1:4322/gallery/game/
lhci assert --config=./lighthouserc.json
# The reports, kept even when an assertion warns. An upload never decides the job.
- name: Keep the reports
if: ${{ !cancelled() }}
continue-on-error: true
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: lighthouse-reports
path: .lighthouseci/
if-no-files-found: ignore
retention-days: 14
+131
View File
@@ -0,0 +1,131 @@
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; its failThreshold makes any finding
# fail the scan. Results go to Qodana Cloud (the project token is the QODANA_TOKEN secret) and
# into the `qodana-report` artifact (SARIF + HTML report): Gitea has no code-scanning UI, so
# the SARIF upload of the GitHub days is gone.
#
# The Qodana CLI, not JetBrains/qodana-action (which relies on GitHub's APIs for annotations
# and comments), at a pinned version, SHA-256 verified — the version and checksum the ops
# repo's reusable-qodana.yml pins. Renovate does not update it (it is not an action): bump
# both together, by hand. A local job rather than a caller of that reusable workflow: the
# scan needs this repo's generated binding types first, and the ops tag callers pin
# (v2026.11.1) predates the reusable one.
#
# Advisory, not required: branch protection requires only CI's `build`. Renovate's PRs skip
# it — Gitea gives a same-repo PR the repository's secrets, and a Renovate run installs the
# very update under review, so no token goes near it — as does a run without the token.
on:
pull_request:
push:
branches: [main]
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
workflow_dispatch:
# Explicit, and granted on the job.
permissions: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# Cancel superseded PR runs; let main runs finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
qodana:
name: Qodana for JS
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
env:
QODANA_CLI_VERSION: 2026.3.1
QODANA_CLI_SHA256: dae6d31f481ed15c6c016fd746e907978f0c1437010326fa04a92f13c7c52338 # qodana_linux_x86_64.tar.gz
steps:
- name: Check for QODANA_TOKEN
id: token
env:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
ACTOR: ${{ github.actor }}
AUTHOR: ${{ github.event.pull_request.user.login }}
run: |
if [ "$ACTOR" = renovate-bot ] || [ "$AUTHOR" = renovate-bot ]; then
echo "present=false" >> "$GITHUB_OUTPUT"
echo "::notice::Qodana skipped — a Renovate pull request installs the update under review, so no token goes near it."
elif [ -n "$QODANA_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "::notice::Qodana skipped — QODANA_TOKEN is not available to this run."
fi
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
if: steps.token.outputs.present == 'true'
with:
fetch-depth: 0
submodules: recursive
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
if: steps.token.outputs.present == 'true'
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
if: steps.token.outputs.present == 'true'
run: npm ci --ignore-scripts
- name: Install scripts allow-listed
if: steps.token.outputs.present == 'true'
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
if: steps.token.outputs.present == 'true'
run: |
npm run types
npm run types:widgets
npm run astro -- sync
- name: Install the Qodana CLI ${{ env.QODANA_CLI_VERSION }}
if: steps.token.outputs.present == 'true'
run: |
set -euo pipefail
tmp="${RUNNER_TEMP:-/tmp}"
tgz="$tmp/qodana.tar.gz"
curl --proto '=https' -fsSL --retry 3 -o "$tgz" \
"https://github.com/JetBrains/qodana-cli/releases/download/v${QODANA_CLI_VERSION}/qodana_linux_x86_64.tar.gz"
echo "${QODANA_CLI_SHA256} $tgz" | sha256sum -c -
mkdir -p "$tmp/qodana-cli"
tar -xzf "$tgz" -C "$tmp/qodana-cli" qodana
echo "$tmp/qodana-cli" >> "$GITHUB_PATH"
# 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. Native mode
# (qodana.yaml: withinDocker: false): the job already is a container.
- name: Qodana scan
if: steps.token.outputs.present == 'true'
env:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
QODANA_ENDPOINT: https://qodana.cloud
run: |
qodana --version
qodana scan --within-docker false \
--results-dir "${RUNNER_TEMP:-/tmp}/qodana/results" \
--cache-dir "${RUNNER_TEMP:-/tmp}/qodana/cache"
# !cancelled(), not the implicit success(): a scan that finds something fails, and
# those are exactly the findings the report must keep. An upload never decides the job.
- name: Keep the report
if: ${{ !cancelled() && steps.token.outputs.present == 'true' }}
continue-on-error: true
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: qodana-report
path: ${{ runner.temp }}/qodana/results/
if-no-files-found: ignore
retention-days: 14
+37
View File
@@ -0,0 +1,37 @@
# Security checks from the ops repo (poli0981/.github, runbook §3.5 item 2 and §4.3).
#
# secrets → gitleaks over the whole git history; fails on a finding
# sast → Opengrep: the workflow, Dockerfile and shell rules always, plus the
# JavaScript / TypeScript rules (`node: true`); the SARIF report is an
# artifact, since Gitea has no code-scanning UI
# deps → osv-scanner over package-lock.json; fails on a known vulnerability
#
# It replaces osv-scanner.yml (Google's reusable workflow, which uploaded SARIF to GitHub
# code scanning): the dependency scan is the same database over the same lockfile, now
# next to the secrets and SAST checks. ci.yml keeps its per-PR `npm audit` gate.
#
# The reusable workflow is pinned to the commit of the ops repo's tag. Renovate does not
# bump this pin: the `# ops …` comment is no version it reads (runbook §3.2 item 3).
# Move it by hand when the ops repo is tagged. No secrets: nothing here needs a token.
name: Security
on:
push:
branches: [main]
pull_request:
schedule:
# Wednesdays 14:13 UTC = 21:13 Vietnam: inside the 13:00–16:00 UTC window when the
# runner's PC is on, on this repo's slot in the ops repo's cron registry.
- cron: "13 14 * * 3"
workflow_dispatch:
# Explicit, never inherited, and granted on the job.
permissions: {}
jobs:
security:
permissions:
contents: read
uses: poli0981/.github/.gitea/workflows/security.yml@2a255e0e9a60541da5c25fb4ad5cc24bd353d543 # ops v2026.11.1
with:
node: true
+50
View File
@@ -0,0 +1,50 @@
name: Rào cản trợ năng / Accessibility barrier
description: Điều gì đó trên poli0981.dev khó hoặc không dùng được / Something on poli0981.dev is hard or impossible to use
title: "[a11y] "
labels: ["accessibility"]
body:
- type: markdown
attributes:
value: |
Cảm ơn bạn đã báo. Bạn không cần tự tìm nguyên nhân, và không cần nói gì về tình trạng khuyết tật của mình.
Thanks for reporting. You do not have to diagnose anything, and you never need to tell me about a disability.
Không muốn đăng công khai? Gửi email tới accessibility@poli0981.dev hoặc dùng nút "Báo lỗi" ở cuối mọi trang (không cần tài khoản).
Prefer not to post in public? Email accessibility@poli0981.dev, or use "Report a bug" at the bottom of every page (no account needed).
- type: textarea
id: goal
attributes:
label: Bạn đang định làm gì? / What were you trying to do?
description: Ví dụ "mở menu bằng bàn phím" / For example "open the menu with the keyboard"
validations:
required: true
- type: textarea
id: barrier
attributes:
label: Điều gì đã xảy ra? / What happened instead?
description: Các bước tái hiện nếu có / Steps to reproduce, if you have them
validations:
required: true
- type: input
id: route
attributes:
label: Trang / Page
placeholder: "https://poli0981.dev/…"
- type: textarea
id: environment
attributes:
label: Môi trường / Environment
description: Hệ điều hành, trình duyệt, công nghệ hỗ trợ và phiên bản / Operating system, browser, assistive technology and versions
placeholder: "Windows 11 · Edge 142 · Narrator"
- type: dropdown
id: severity
attributes:
label: Mức độ / Severity
description: Để mình biết nên xử lý cái nào trước / So I know what to handle first
options:
- "Chặn hẳn — không làm được việc chính / Critical — blocks a core task"
- "Nghiêm trọng — rất khó, nhưng có cách khác / Serious — major difficulty, a workaround exists"
- "Vừa — gây khó chịu hoặc không nhất quán / Moderate — annoying or inconsistent"
- "Nhẹ — ảnh hưởng ít / Minor — little impact"
validations:
required: true
+7 -1
View File
@@ -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 đó
thành issue bảo mật, chỉ chủ repo xem được). / Quicker: the "Report a problem" button on the
page itself sends the page and environment along (those reports become confidential issues
only the maintainer can see).
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:
+12
View File
@@ -0,0 +1,12 @@
# Maintenance mode (CONTRIBUTING.md): issues are for bugs, accessibility and language problems.
# Gitea reads these forms; outsiders file issues on the GitLab mirror (.gitlab/issue_templates).
blank_issues_enabled: false
contact_links:
- name: Question or idea · Câu hỏi hoặc ý tưởng
url: mailto:code@poli0981.dev
about: >-
The project is in maintenance mode and takes no new features — ask or share ideas by e-mail.
· Dự án đang ở chế độ bảo trì, không nhận tính năng mới — hỏi hoặc gửi ý tưởng qua e-mail.
- name: Security vulnerability · Lỗ hổng bảo mật
url: https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/SECURITY.md
about: Report it by e-mail, never in a public issue. · Báo qua e-mail, không mở issue công khai.
+46
View File
@@ -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
-45
View File
@@ -1,45 +0,0 @@
version: 2
updates:
# 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
+33
View File
@@ -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://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/CONTRIBUTING.md)):
new features are not accepted, and a `feat:` pull request is closed.
- [ ] 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://git.poli0981.dev/poli0981/poli0981-dev/src/branch/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
-168
View File
@@ -1,168 +0,0 @@
name: CI
# 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:
# 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"]
# 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:
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:
# 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@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 --ignore-scripts
# …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: |
npm run types
npm run types:widgets
- name: Format check
run: npm run format:check
- name: Lint
run: npm run lint
# .astro, .svelte and .ts through Volar — the TypeScript 6 API (TS 7.0 has none).
- name: Type check (astro check)
run: npm run check
# 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: |
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
# 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: npm run check-exif -- --changed
- name: Build
run: npm run build
# 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
- 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@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
args: >-
${{ github.event_name == 'pull_request' && '-Dsonar.qualitygate.wait=true -Dsonar.qualitygate.timeout=300' || '' }}
-88
View File
@@ -1,88 +0,0 @@
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
-77
View File
@@ -1,77 +0,0 @@
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 &
- name: Wait for the server
run: |
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"; 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://localhost:4321/
http://localhost:4321/blog/lan-dau-viet-truyen/
http://localhost:4321/truyen/dem-khong-tieng/chuong-01/
http://localhost:4321/gallery/game/
uploadArtifacts: true
artifactName: lighthouse-reports
-42
View File
@@ -1,42 +0,0 @@
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@b1d267aea5211fa648d9d442fa64b90dbdcbdd36 # v2.7.0
permissions:
actions: read
contents: read
security-events: write
with:
upload-sarif: ${{ github.event_name != 'pull_request' }}
scan-args: |-
--lockfile=package-lock.json
+36
View File
@@ -0,0 +1,36 @@
<!-- Labels: accessibility. Converted from .github/ISSUE_TEMPLATE (Gitea reads those); keep both in step. -->
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).
Tiêu đề / Title: `[a11y] …`
### Bạn đang định làm gì? / What were you trying to do?
<!-- Ví dụ "mở menu bằng bàn phím" / For example "open the menu with the keyboard" -->
### Điều gì đã xảy ra? / What happened instead?
<!-- Các bước tái hiện nếu có / Steps to reproduce, if you have them -->
### Trang / Page
<!-- https://poli0981.dev/… -->
### Môi trường / Environment
<!-- 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 — e.g. Windows 11 · Edge 142 · Narrator -->
### Mức độ / Severity
- [ ] 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
/label ~accessibility
+34
View File
@@ -0,0 +1,34 @@
<!-- Labels: bug. Converted from .github/ISSUE_TEMPLATE (Gitea reads those); keep both in step. -->
Cảm ơn bạn đã báo lỗi. / Thanks for reporting.
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 đó thành
issue bảo mật, chỉ chủ repo xem được). / Quicker: the "Report a problem" button on the page itself
sends the page and environment along (those reports become confidential issues only the maintainer
can see).
Dự án đang ở chế độ bảo trì: mẫu 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 template is for bugs, not feature
requests — see CONTRIBUTING.md.
Tiêu đề / Title: `[web-report] …`
### Mô tả / Description
<!-- Chuyện gì đã xảy ra? / What happened? -->
### Trang / Route
<!-- /blog/… -->
### Môi trường / Environment
<!-- Trình duyệt, kích thước màn hình, theme, ngôn ngữ / Browser, viewport, theme, locale -->
### Console log (tùy chọn / optional)
```text
```
/label ~bug
+25
View File
@@ -0,0 +1,25 @@
<!-- Labels: language. Converted from .github/ISSUE_TEMPLATE (Gitea reads those); keep both in step. -->
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.
Tiêu đề / Title: `[language] …`
### Trang / Page
<!-- Đường dẫn trang, hoặc file nếu bạn biết. / The page's URL, or the file if you know it. -->
### Ngôn ngữ / Language
- [ ] Tiếng Việt / Vietnamese
- [ ] Tiếng Anh / English
### Câu hiện tại / Current text
<!-- Chép nguyên văn. / Copy it exactly. -->
### Đề xuất sửa và lý do / Suggested wording and why
<!-- 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? -->
/label ~language
@@ -0,0 +1,36 @@
<!-- Converted from .github/pull_request_template.md (Gitea reads that one); keep both in step. -->
## 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://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/CONTRIBUTING.md)):
new features are not accepted, and a `feat:` merge request is closed. GitLab CI does not run here:
the maintainer runs CI on Gitea before applying the change.
- [ ] 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://git.poli0981.dev/poli0981/poli0981-dev/src/branch/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
+19
View File
@@ -0,0 +1,19 @@
# gitleaks, run by the ops repo's security.yml, scans every commit with its default rules.
# Each line below is one finding that is NOT a secret, as commit:file:rule:line. Anything
# else is still reported, and so is a later commit that touches these lines. A real secret
# never goes here: it is rotated, and the history is dealt with.
# A deliberately forged Cloudflare Access JWT: the smoke test sends it to prove the admin
# API refuses a token that does not verify (it now lives in a variable, `forgedJwt`).
7ec559d216e593f53938bf1db8c85584f9115190:scripts/smoke-worker.mjs:generic-api-key:177
# The Cloudflare Access application's AUD tag. Public by design: it only says which app a
# token must be minted for (the comment above it in wrangler.jsonc says so).
7ec559d216e593f53938bf1db8c85584f9115190:wrangler.jsonc:generic-api-key:85
# The Cloudflare Web Analytics site tag: every production page sends it in its HTML.
48d4e7bbdccd00b34ac28819ce42309488bb63cd:src/components/CfBeacon.astro:generic-api-key:11
# SonarQube Cloud's project key, a public identifier, in the sonar-project.properties that
# left with Sonar (migration decision D1).
8a1316280f298a2814ba941ad33baad1d0596b3b:sonar-project.properties:generic-api-key:4
+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "src/content"]
path = src/content
url = https://github.com/poli0981/content.git
url = https://git.poli0981.dev/poli0981/content.git
+168
View File
@@ -0,0 +1,168 @@
# 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 have a GitLab account, you can open an issue with
the [Accessibility template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Accessibility)
on the mirror.
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, or
`A11Y_CHANNEL=bundled` for Playwright's own Chromium (what CI uses: the Gitea runner's image has no
Chrome). 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://git.poli0981.dev/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).
+269 -4
View File
@@ -2,8 +2,262 @@
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.
Content changes (posts, stories, albums) live in [`poli0981/content`](https://git.poli0981.dev/poli0981/content)
and are not listed here. Links to pull requests before 2.4.0 point at the GitHub repository, which
no longer exists; the commits themselves are all on Gitea.
## [Unreleased]
## [2.4.1] — 2026-11-24
### Fixed
- **Publishing from the admin merges again.** The first publish after the move stopped at its
pull request: Gitea 28.4 writes no commit status for a dispatched CI run, so the content PR
never had the `CI / build` check main's branch protection requires and every merge was refused
(405). CI's publish job now records the build's result as that status itself — and a failed
build as a failure, so the admin shows "xuất bản lỗi" instead of building forever — before it
merges and deploys.
## [2.4.0] — 2026-11-24
The move from GitHub to the owner's Gitea. The GitHub account is gone, and with it the
repository, Actions, Workers Builds' source, the admin's tokens and the bug-report tracker. This
release puts every one of them somewhere that works again; nothing new is added (maintenance
mode, [`CONTRIBUTING.md`](CONTRIBUTING.md)).
### Changed
- **Where the code lives.** The canonical repository is
[`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev), the
content submodule [`git.poli0981.dev/poli0981/content`](https://git.poli0981.dev/poli0981/content).
Issues and merge requests go to the mirror on
[GitLab](https://gitlab.com/poli0981/poli0981-dev) (Bug, Accessibility and Language templates);
patches and questions to `code@poli0981.dev`; security reports by e-mail only.
- **CI runs on Gitea Actions** (`.gitea/workflows`), on the owner's own runner: the build job is
unchanged in what it checks, and installs Playwright's Chromium where the runner image has no
Chrome. **`main` deploys from CI**: a `deploy` job runs `wrangler deploy` after `build` passes
and waits until `/api/health` reports the commit. Cloudflare Workers Builds is gone, and pull
requests get no preview versions.
- **The admin works through Gitea** (`src/lib/admin/gitea.ts`): one bot token
(`GITEA_BOT_TOKEN`) for saves and publishing, several files per commit with Gitea checking
each file's version, and the publish bar reading the content PR, its build status and the
publish workflow from Gitea. Publishing still merges itself for Markdown/JSON and waits for a
review when MDX changes: CI merges the content PR and starts the deploy.
- **Bug reports from the site** become **confidential issues on the GitLab mirror**
(`GITLAB_ISSUES_TOKEN`, var `REPORT_PROJECT`), seen only by the maintainer; reporter text cannot
ping anyone or run a GitLab quick action. Privacy §4 says so (content repo, effective
2026-11-24). The Discord fallback is unchanged.
- **The activity widget** reads Gitea's public activity feed (no token) and links to Gitea.
- The dev profile link, the About page, the console banner, the legal pages' source and issue
links, and the project pages point at Gitea.
- **Dependency updates** come from Renovate (the shared `poli0981/renovate-config` preset, 3-day
wait kept) instead of Dependabot. **Security checks** come from the ops repository's
`security.yml`: gitleaks over the whole history, Opengrep and osv-scanner, weekly and on every
change. **Qodana** runs through its CLI; reports are artifacts.
### Removed
- SonarQube Cloud (job, configuration and badge), GitHub code scanning uploads, the OSV workflow
(replaced by `security.yml`) and the maintenance-mode triage bot, which needed GitHub's events:
out-of-scope requests on the mirror are closed by hand.
## [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
@@ -79,7 +333,9 @@ A platform upgrade, a security pass, a new palette and a rebuilt admin
- Dozens of smaller issues found by SonarCloud and the new tests (error pages served with the
wrong status under `astro dev`, regex backtracking, scripts that passed without checking).
## [1.x] — 2026-07 → 2026-10 (untagged)
## [1.x] — 2026-07 → 2026-10
The public launch is tagged `v1-launch`; the 1.x changes after it were not tagged.
- **2026-07** — Bilingual Astro + Cloudflare Workers site: blog, stories with reading controls and
content warnings, projects, dev/uses, gaming, Q&A, links, legal pages; Pagefind search; RSS,
@@ -91,4 +347,13 @@ A platform upgrade, a security pass, a new palette and a rebuilt admin
- **2026-10** — Custom Worker entry in front of every page; Workers Rate Limiting; Web Analytics;
topic email aliases; R2 media; the Turnstile gate; the admin at `admin.poli0981.dev`.
[2.0.0]: https://github.com/poli0981/poli0981-dev/releases/tag/v2.0.0
[Unreleased]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.4.1...main
[2.4.1]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.4.0...v2.4.1
[2.4.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.3.0...v2.4.0
[2.3.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.2.0...v2.3.0
[2.2.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.1.2...v2.2.0
[2.1.2]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.1.1...v2.1.2
[2.1.1]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.1.0...v2.1.1
[2.1.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.0.0...v2.1.0
[2.0.0]: https://git.poli0981.dev/poli0981/poli0981-dev/releases/tag/v2.0.0
[1.x]: https://git.poli0981.dev/poli0981/poli0981-dev/releases/tag/v1-launch
+124
View File
@@ -0,0 +1,124 @@
# Contributing
> **Tiếng Việt ở bên dưới.** / Vietnamese below.
## Where things live
The canonical repository is on the owner's Gitea,
[`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev). It is
public to read, but registration is closed, so nobody else can open issues or pull requests there.
Since November 2026 (the GitHub repository is gone) outside contributions go through:
- **Issues and merge requests**: the mirror at
[`gitlab.com/poli0981/poli0981-dev`](https://gitlab.com/poli0981/poli0981-dev). Gitea pushes to
it after every change, so it always has the current code. GitLab CI does not run there: the
owner runs CI on Gitea before applying a merge request.
- **Patches by e-mail**: `git format-patch` / `git send-email` to `code@poli0981.dev`, also for
questions.
The owner applies accepted changes on Gitea; the mirror then shows the merge request as merged,
or the owner closes it with a link to the commit.
## 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 (Renovate, with a combined update about once a
month, always after a 3-day wait).
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 merge request asking for one is labelled
`enhancement` + `out-of-scope` and closed. 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 by e-mail to `code@poli0981.dev`, without any promise.
### How to report
- **A problem on the website**: the "Báo lỗi / Report a problem" button on the page itself (no
account needed), or the
[Bug template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Bug) on
the GitLab mirror.
- **An accessibility barrier**: the
[Accessibility template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Accessibility),
or `accessibility@poli0981.dev`.
- **A spelling or wording problem**: the
[Language template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Language).
- **A security vulnerability**: by e-mail only — see [SECURITY.md](SECURITY.md). Never in a public
issue on the mirror.
### Merge requests and patches
Welcome for the five kinds of change above. Keep one change per merge request (or patch series),
follow the checks in the merge request template, and run the commands listed in
[README.md](README.md#commands) before sending it. CI on Gitea must be green before the owner
merges — `build` is the required check, and the Qodana and security checks have to pass too.
Commits on `main` are signed.
---
## Mã nguồn ở đâu
Repo chính nằm trên Gitea của chủ repo,
[`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev). Ai cũng
đọc được, nhưng đăng ký tài khoản đã đóng nên người khác không mở được issue hay pull request ở đó.
Từ tháng 11/2026 (repo GitHub không còn), đóng góp từ bên ngoài đi qua:
- **Issue và merge request**: bản sao tại
[`gitlab.com/poli0981/poli0981-dev`](https://gitlab.com/poli0981/poli0981-dev). Gitea đẩy sang
sau mỗi thay đổi, nên luôn có mã mới nhất. GitLab CI không chạy ở đó: chủ repo chạy CI trên Gitea
trước khi áp dụng merge request.
- **Patch qua e-mail**: `git format-patch` / `git send-email` tới `code@poli0981.dev`, câu hỏi cũng
gửi về đây.
Chủ repo áp dụng thay đổi được chấp nhận trên Gitea; bản sao sau đó hiện merge request là đã merge,
hoặc chủ repo đóng nó kèm link tới commit.
## 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ỳ (Renovate, gộp một lần khoảng mỗi tháng, luôn sau 3 ngày chờ).
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 merge request đề xuất tính năng sẽ được gắn nhãn
`enhancement` + `out-of-scope` và đóng lại. 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ể gửi qua
e-mail `code@poli0981.dev`, 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 (không cần tài khoản), hoặc
[mẫu Bug](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Bug) trên bản
sao GitLab.
- **Rào cản accessibility**:
[mẫu Accessibility](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Accessibility),
hoặc `accessibility@poli0981.dev`.
- **Lỗi chính tả, câu chữ**:
[mẫu Language](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Language).
- **Lỗ hổng bảo mật**: chỉ qua e-mail — xem [SECURITY.md](SECURITY.md). Không mở issue công khai
trên bản sao.
### Merge request và patch
Hoan nghênh cho năm loại thay đổi ở trên. Mỗi merge request (hoặc chuỗi patch) một thay đổi, làm
theo các mục kiểm tra trong mẫu merge request, chạy các lệnh trong [README.md](README.md#commands)
trước khi gửi. CI trên Gitea phải xanh trước khi chủ repo merge — `build` là bắt buộc, Qodana và các
kiểm tra bảo mật cũng phải qua. Commit trên `main` có chữ ký.
+53 -16
View File
@@ -1,8 +1,10 @@
# poli0981.dev
[![CI](https://github.com/poli0981/poli0981-dev/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/poli0981-dev/actions/workflows/ci.yml)
[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=poli0981_poli0981-dev&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=poli0981_poli0981-dev)
[![CI](https://git.poli0981.dev/poli0981/poli0981-dev/actions/workflows/ci.yml/badge.svg?branch=main)](https://git.poli0981.dev/poli0981/poli0981-dev/actions?workflow=ci.yml)
[![Qodana](https://git.poli0981.dev/poli0981/poli0981-dev/actions/workflows/qodana.yml/badge.svg?branch=main)](https://git.poli0981.dev/poli0981/poli0981-dev/actions?workflow=qodana.yml)
[![Security](https://git.poli0981.dev/poli0981/poli0981-dev/actions/workflows/security.yml/badge.svg?branch=main)](https://git.poli0981.dev/poli0981/poli0981-dev/actions?workflow=security.yml)
[![License: GPL-3.0](https://img.shields.io/badge/code-GPL--3.0-blue)](LICENSE)
[![Status: maintenance mode](https://img.shields.io/badge/status-maintenance%20mode-orange)](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)**.
@@ -10,6 +12,24 @@ the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https
> 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; requests for one are closed. Details: [`CONTRIBUTING.md`](CONTRIBUTING.md).
## Where things live
Source: [`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev)
(canonical, on the owner's Gitea since November 2026; the GitHub repository is gone). Mirror for
issues and merge requests: [`gitlab.com/poli0981/poli0981-dev`](https://gitlab.com/poli0981/poli0981-dev).
Patches and questions: `code@poli0981.dev`. Security: `security@poli0981.dev` (see
[`SECURITY.md`](SECURITY.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 |
@@ -17,10 +37,11 @@ the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https
| 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`) |
| Content | Markdown/MDX in [`poli0981/content`](https://git.poli0981.dev/poli0981/content) (git submodule `src/content`) |
| Search | Pagefind (built after `astro build`) |
| Tooling | Node 26 · TypeScript 7 (`tsc`) next to TypeScript 6 (astro check, typescript-eslint) · `node:test` · ESLint · Prettier · knip |
| Quality | SonarCloud quality gate · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) |
| Quality | Qodana · gitleaks · Opengrep · OSV-Scanner · Renovate (3-day wait) · axe-core gate · licence check |
| CI | Gitea Actions (`.gitea/workflows`); `main` deploys with Wrangler from CI |
## How it fits together
@@ -30,7 +51,7 @@ visitor ─▶ Cloudflare edge ─▶ src/worker.ts (every request, pages includ
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)
workers/widgets (cron, every 45 min) ─▶ YouTube / Steam / Gitea ─▶ KV (data + mirrored images)
```
Almost every page is prerendered. The Worker entry runs first for every route so the bot gate,
@@ -42,7 +63,7 @@ the denylist and the security headers also cover static pages. Details:
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
git clone --recurse-submodules https://git.poli0981.dev/poli0981/poli0981-dev.git
cd poli0981-dev
npm ci --ignore-scripts && npm run check-install-scripts
npx lefthook install
@@ -51,7 +72,7 @@ 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`.
identity (`dev@localhost`); saving content needs a Gitea token as `GITEA_BOT_TOKEN` in `.dev.vars`.
## Commands
@@ -65,31 +86,47 @@ identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.d
| `npm run lint` · `npm run format:check` · `npm run knip` | ESLint · Prettier · unused files/exports |
| `npm test` · `npm run test:coverage` | `node:test` suites; coverage writes `coverage/lcov.info` (80% line floor) |
| `npm run smoke` | Runs the built Worker with `wrangler dev` and probes pages, headers, the gate and the denylist |
| `npm run test:a11y` | axe-core, keyboard, reflow and forced-colours checks against `npm run preview` (Chrome) |
| `npm run probe:ratelimit -- [url] [requests] [parallel]` | Spams a live URL and counts 429s from the Worker's site-wide limit vs. the WAF rule |
| `npm run new:post` | Scaffold a post or story from `docs/templates/` |
| `npm run check-exif` · `npm run strip-exif` | Refuse / remove GPS and camera metadata in images |
| `npm run gen-notices` | Regenerate `THIRD-PARTY-NOTICES.md` (CI checks it) |
## 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`.
CI deploys `main`: after `build` passes on a push to `main`, the `deploy` job in
[`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml) rebuilds with the production settings, runs
`npx wrangler deploy` and waits until `https://poli0981.dev/api/health` reports that commit. Pull
requests get no preview versions. The runner lives on the owner's PC, so a merge made while it is
off deploys when it comes back. (Cloudflare Workers Builds did this until it went with the GitHub
repository in November 2026.) 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,
publish (opens a submodule-bump PR that CI must pass), review an audit log and manage the IP
denylist. It sits behind Cloudflare Access, and the Worker independently verifies the Access
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.
Please report vulnerabilities privately, by e-mail — see [`SECURITY.md`](SECURITY.md). Bug
reports from the site's "Report a bug" button become confidential issues on the GitLab mirror,
visible only to the maintainer.
## 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
+15 -4
View File
@@ -3,7 +3,10 @@
## 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.
E-mail is the only channel: the repository lives on a self-hosted Gitea with no private
reporting (GitHub's went with the old repository), and issues on the GitLab mirror are public.
**Do not open a public issue on the mirror for a security problem.** One opened there by
mistake is made confidential and continued by e-mail.
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.
@@ -23,7 +26,7 @@ Machine-readable contact: <https://poli0981.dev/.well-known/security.txt> (RFC 9
**Out of scope**
- Findings that require an already-compromised Cloudflare, GitHub or Access identity
- Findings that require an already-compromised Cloudflare, Gitea, GitLab 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
@@ -36,15 +39,23 @@ Only the currently deployed site (`main` → Cloudflare Workers) is supported. R
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/`).
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
forwarded as a **confidential** issue on the GitLab mirror, visible only to the maintainer,
and to 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.
+15 -10
View File
@@ -14,7 +14,7 @@ CI fails if it drifts (docs 08 §6). Edit the script, not the block.
Generated by `scripts/gen-notices.mjs` from `package-lock.json`. CI fails if this
block drifts, so do not edit it by hand.
## Direct dependencies (34)
## Direct dependencies (36)
`runtime` are declared in `dependencies`; `build` in `devDependencies` and never served.
@@ -26,6 +26,7 @@ block drifts, so do not edit it by hand.
| `@astrojs/rss` | MIT | runtime |
| `@astrojs/sitemap` | MIT | runtime |
| `@astrojs/svelte` | MIT | runtime |
| `@axe-core/playwright` | MPL-2.0 | build |
| `@resvg/resvg-js` | MPL-2.0 | build |
| `@tailwindcss/vite` | MIT | runtime |
| `@types/node` | MIT | build |
@@ -40,6 +41,7 @@ block drifts, so do not edit it by hand.
| `lefthook` | MIT | build |
| `marked` | MIT | runtime |
| `pagefind` | MIT | build |
| `playwright` | Apache-2.0 | build |
| `prettier` | MIT | build |
| `prettier-plugin-astro` | MIT | build |
| `prettier-plugin-svelte` | MIT | build |
@@ -60,9 +62,9 @@ block drifts, so do not edit it by hand.
| License | Packages |
| ------- | -------- |
| MIT | 26 |
| Apache-2.0 | 3 |
| Apache-2.0 | 4 |
| MPL-2.0 | 3 |
| ISC | 2 |
| MPL-2.0 | 2 |
| MIT OR Apache-2.0 | 1 |
Transitive dependencies are deliberately not tallied here. Which packages get installed
@@ -72,9 +74,11 @@ inventory is `package-lock.json`; platform binaries are covered in prose below.
## Licenses outside the standard allowlist
**MPL-2.0** — 2 package(s): `@resvg/resvg-js`, `satori`
**MPL-2.0** — 3 package(s):
> Reviewed: File-level copyleft. satori and @resvg/resvg-js are used unmodified as build-time tools and never shipped to the browser, so no source-disclosure obligation is triggered.
- `@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 -->
@@ -101,13 +105,14 @@ Not packages — listed for transparency:
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.
- **Gitea** (self-hosted at git.poli0981.dev) — source code, the content repository and CI
(Gitea Actions, on the maintainer's own runner).
- **GitLab** — the public mirror of the repository, and confidential issues 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
- **YouTube, Steam and Gitea public APIs** — read by the widgets cron worker; visitors' browsers
never call them (images are mirrored and served from the site).
- **SonarCloud, CodeQL, OSV-Scanner, Snyk** — code and dependency analysis in CI; nothing they do
reaches the running site.
- **Qodana (JetBrains), gitleaks, Opengrep, OSV-Scanner, Renovate** — code and dependency
analysis and updates in CI; nothing they do reaches the running site.
## Fonts
+71 -21
View File
@@ -5,10 +5,16 @@ 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.
@@ -34,17 +40,56 @@ const themeBootstrap = {
},
};
// 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.
// 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 production builds, so CI, Lighthouse and local
// builds never report page views. The deploy job in .gitea/workflows/ci.yml sets
// PUBLIC_CF_BEACON=true; a Workers Builds build of main (WORKERS_CI / WORKERS_CI_BRANCH,
// before the move to Gitea) turns it on by itself.
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.
// The commit a build was made from (Gitea Actions sets GITHUB_SHA, as GitHub Actions did;
// Workers Builds set WORKERS_CI_COMMIT_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({
site: "https://poli0981.dev",
@@ -52,6 +97,11 @@ export default defineConfig({
// `export const prerender = false` (only api routes + middleware run on-demand).
output: "static",
// Every page's CSS goes inline (about 9 KB brotli): the two shared stylesheets were the
// only render-blocking requests, costing a round trip before first paint on a phone.
// Astro hashes the inlined <style> blocks into the CSP like any other.
build: { inlineStylesheets: "always" },
// Astro's prefetch is off by default, but <ClientRouter /> force-enables it with
// `prefetchAll: true` + a hover strategy. Cloudflare's zone-level Speculation Rules
// then answers every `Sec-Purpose: prefetch` request to a Worker origin with a 503
@@ -74,8 +124,9 @@ export default defineConfig({
},
// Bug-report pipeline env (docs 10). All optional so the site builds + degrades
// gracefully until the owner provisions them (Turnstile keys, a fine-grained GitHub
// Issues token, and a Discord webhook). The client site key is public + inlined.
// gracefully until the owner provisions them (Turnstile keys, a GitLab token that may
// open issues on the mirror, and a Discord webhook). The client site key is public +
// inlined.
env: {
schema: {
PUBLIC_TURNSTILE_SITE_KEY: envField.string({
@@ -84,17 +135,12 @@ export default defineConfig({
optional: true,
}),
TURNSTILE_SECRET: envField.string({ context: "server", access: "secret", optional: true }),
GITHUB_ISSUES_TOKEN: envField.string({ context: "server", access: "secret", optional: true }),
GITLAB_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({
// Admin (admin.poli0981.dev): the Gitea token of the bot user poli0981-bot, a Write
// collaborator on the content and site repos (src/lib/admin/gitea.ts); plus the email
// allowlist on top of Access (unset = the admin refuses everyone).
GITEA_BOT_TOKEN: envField.string({
context: "server",
access: "secret",
optional: true,
@@ -113,6 +159,7 @@ export default defineConfig({
integrations: [
themeBootstrap,
localizedNotFound,
svelte(),
mdx(),
sitemap({
@@ -134,7 +181,10 @@ export default defineConfig({
// Tailwind v4 is wired through the Vite plugin (NOT the legacy @astrojs/tailwind).
vite: {
plugins: [tailwindcss()],
define: { __BUILD_COMMIT__: JSON.stringify(BUILD_COMMIT) },
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`.
+4
View File
@@ -12,6 +12,10 @@ draft: true
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.
-->
+6 -1
View File
@@ -7,6 +7,7 @@ series: "{{SERIES}}"
chapter: 1
status: ongoing
contentWarning: []
# ageRating: "16+"
tags: []
draft: true
---
@@ -16,7 +17,11 @@ draft: true
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 e.g. [horror, violence] — renders a warning gate before the text
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
View File
@@ -1,6 +1,5 @@
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"ignoreDependencies": ["cloudflare"],
"entry": ["workers/widgets/src/index.ts", "scripts/*.mjs", "tests/support/**/*.{mjs,ts}"],
"ignore": ["public/sw.js", "public/skullhop.js", "public/gate.js"]
}
+2 -1
View File
@@ -3,7 +3,8 @@
"collect": {
"numberOfRuns": 3,
"settings": {
"throttlingMethod": "simulate"
"throttlingMethod": "simulate",
"chromeFlags": "--no-sandbox"
}
},
"assert": {
+14
View File
@@ -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.
+1623 -1576
View File
File diff suppressed because it is too large. Load diff
+25 -19
View File
@@ -18,10 +18,13 @@
"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",
@@ -41,47 +44,50 @@
},
"overrides": {
"fflate": "^0.7.5",
"minimatch": "^11.0.4",
"sharp": "$sharp",
"miniflare": {
"undici": "^7.30.1"
}
},
"dependencies": {
"@astrojs/cloudflare": "^14.4.2",
"@astrojs/mdx": "^8.1.1",
"@astrojs/cloudflare": "^14.4.8",
"@astrojs/mdx": "^8.1.6",
"@astrojs/rss": "^4.0.19",
"@astrojs/sitemap": "^3.7.4",
"@astrojs/svelte": "^9.1.1",
"@tailwindcss/vite": "^4.3.3",
"astro": "^7.4.2",
"jose": "^6.2.13",
"marked": "^18.1.1",
"@astrojs/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.2",
"tailwindcss": "^4.3.3",
"svelte": "^5.57.3",
"tailwindcss": "^4.3.5",
"yaml": "^2.9.1",
"zod": "^4.6.7"
},
"devDependencies": {
"@astrojs/check": "^0.9.12",
"@axe-core/playwright": "^4.14.0",
"@resvg/resvg-js": "^2.6.2",
"@types/node": "^26.6.5",
"@types/node": "^26.6.6",
"@typescript/native": "npm:typescript@^7.0.2",
"eslint": "^10.13.0",
"eslint": "^10.15.0",
"eslint-plugin-astro": "^3.2.1",
"eslint-plugin-svelte": "^3.23.1",
"eslint-plugin-svelte": "^3.24.1",
"exifr": "^7.1.3",
"knip": "^6.42.1",
"knip": "^6.45.1",
"lefthook": "^2.2.2",
"pagefind": "^1.5.2",
"prettier": "^3.9.10",
"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.63.2",
"satori-html": "^0.3.2",
"typescript": "~6.0.3",
"typescript-eslint": "~8.72.0",
"wrangler": "^4.152.0"
"typescript-eslint": "~8.73.0",
"wrangler": "^4.164.0"
}
}
+19 -13
View File
@@ -1,7 +1,7 @@
# poli0981.dev — Documentation Suite
- 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`
- Repo: `poli0981/poli0981-dev` (**public** từ 10/2026; từ 2026-11-24 trên Gitea tự host `https://git.poli0981.dev/poli0981/poli0981-dev`, mirror công khai nhận issue/MR `https://gitlab.com/poli0981/poli0981-dev` — `08` §0) · nội dung: `poli0981/content` (submodule `src/content`, cũng trên Gitea) · 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).
@@ -18,10 +18,10 @@
| 05 | 05_SITEMAP_UX.md | Route map, wireframe từng trang, legal gate, mobile nav |
| 06 | 06_SECURITY.md | Headers/CSP, form, rate limit, secrets, supply chain |
| 07 | 07_CLOUDFLARE_SETUP.md | **Hướng dẫn set Cloudflare từng bước** |
| 08 | 08_CI_CD.md | Workflows, permissions, deploy, Dependabot, hooks |
| 08 | 08_CI_CD.md | Forge & CI (Gitea), workflows, deploy, Renovate, hooks |
| 09 | 09_ERROR_PAGES_OFFLINE.md | 404/403/429/5xx/offline + cách test |
| 10 | 10_BUG_REPORT_PIPELINE.md | Console capture → GitHub Issue + Discord |
| 11 | 11_WIDGETS_INTEGRATIONS.md | YouTube/Steam/GitHub widgets, cron worker, KV |
| 10 | 10_BUG_REPORT_PIPELINE.md | Console capture → issue confidential trên GitLab + Discord |
| 11 | 11_WIDGETS_INTEGRATIONS.md | YouTube/Steam/Gitea widgets, cron worker, KV |
| 12 | 12_LEGAL/ | 5 văn bản song ngữ (xem dưới) |
| 13 | 13_SEO_RSS_OG.md | Meta, hreflang, sitemap, RSS, OG image, AI crawlers |
| 14 | 14_PERF_BUDGET.md | Ngân sách hiệu năng + kỷ luật islands |
@@ -29,31 +29,37 @@
| 16 | 16_COST.md | Chi phí chốt + ngưỡng cần theo dõi |
| 17 | 17_MAINTENANCE.md | Lịch bảo trì, update playbook, backup |
`12_LEGAL/`: `TERMS_OF_USE.md` · `PRIVACY_POLICY.md` · `DISCLAIMER.md` · `THIRD_PARTY_NOTICES.md` · `CONTENT_LICENSE.md` — **bản nháp gốc** (07/2026). Văn bản đang hiệu lực là `legal/*.md` trong repo `poli0981/content` (render ở `/legal/*`); sửa ở đó, không sửa ở đây.
`12_LEGAL/`: `TERMS_OF_USE.md` · `PRIVACY_POLICY.md` · `DISCLAIMER.md` · `THIRD_PARTY_NOTICES.md` · `CONTENT_LICENSE.md` — **bản nháp gốc** (07/2026). Văn bản đang hiệu lực là `legal/*.md` trong repo `poli0981/content` (render ở `/legal/*`); sửa ở đó, không sửa ở đây. Hai trang thêm sau (`ai-usage`, `accessibility`) chỉ có ở repo content, không có bản nháp tại đây.
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-10-24)
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-11-24)
| # | 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 (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 |
| 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; từ 2026-11-24 việc merge do job `publish` của CI làm, `08` §0b). 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) |
| D6 | Legal canonical | Trên site tại `/legal/*`; repo public mirror `poli0981/legal` = tuỳ chọn sau |
| 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 |
| D9 | API ngoài | Không weather/map; widget YouTube + Steam + GitHub qua cron worker (GitHub đến 2026-11-23; nay feed công khai của Gitea — D25) |
| D11 | Email | Google Workspace (MX Google), một hộp thư + alias theo chủ đề (`07` §11). Không Cloudflare Email Routing |
| D12 | Chống bot | **Cổng Turnstile** trước mọi trang, vé 48 giờ (`06` §3b); bot đã xác thực đi thẳng nhờ Transform Rule `x-verified-bot` |
| D13 | Rate limit | Workers Rate Limiting bindings theo nhóm `/api` (`06` §2) thay bộ đếm KV |
| D13 | Rate limit | WAF rule (edge) → Workers Rate Limiting: RL_SITE toàn site 100/10s → bindings theo nhóm `/api` (`06` §2, `07` §6) thay bộ đếm KV |
| D14 | Analytics | Cloudflare Web Analytics, **snippet thủ công** chỉ ở bản build production (`07` §12) |
| D15 | Admin | `admin.poli0981.dev` sau Cloudflare Access + Worker tự kiểm JWT (≤ 24 giờ, email phải có trong `ADMIN_EMAILS` — thiếu là từ chối); token GitHub chỉ ghi repo content; ảnh → Images binding → R2; mọi thao tác ghi audit log (`06` §9) |
| 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 (đến 2026-11-23; nay một token bot Gitea `GITEA_BOT_TOKEN`, `06` §9); ả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) |
| 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` §0b; bỏ 2026-11-24 — Qodana + Opengrep thay, D25) |
| D18 | Báo lỗi (10/2026) | Issue tạo ở repo **private** `poli0981/site-reports` (repo site đã public) — đến 2026-11-23; nay issue **confidential** trên mirror GitLab `poli0981/poli0981-dev` (D25) — `10` §4 |
| D19 | Phát hành | Tag `vX.Y.Z` có ký GPG + GitHub Release (từ v2.4.0: Gitea 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 — trên runner Gitea là Chromium của Playwright, `08` §0b) 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 (đến 2026-11-23; nay chủ repo đóng tay trên mirror GitLab — D25); 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) — đến 2026-11-23; nay job `deploy` của Gitea CI (D25) |
| D24 | Chất lượng (11/2026) | Thêm **Qodana** (Ultimate, Qodana for JS, ngưỡng 0) cạnh SonarCloud (SonarCloud bỏ 2026-11-24, D25). 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) |
| D25 | Chuyển sang Gitea (11/2026, chốt 2026-11-24, v2.4.0) | Tài khoản GitHub `poli0981` không còn ⇒ repo site + `content` sống trên Gitea tự host `git.poli0981.dev` (bản gốc); mirror công khai `gitlab.com/poli0981/poli0981-dev` nhận issue/MR (người ngoài không đăng ký được Gitea; patch/câu hỏi `code@`, bảo mật chỉ `security@`). CI = Gitea Actions (`.gitea/workflows/`, runner trên PC chủ repo, job lịch chỉ 13:00–16:00 UTC); deploy = job `deploy` của `ci.yml` (`wrangler deploy`) thay Workers Builds, không còn preview cho PR; check bắt buộc `CI / build (*)`. Bỏ SonarCloud, CodeQL/Snyk, `triage.yml`, Dependabot ⇒ Qodana + `security.yml` (gitleaks/Opengrep/osv-scanner) + Renovate tự host. Admin: một token bot `GITEA_BOT_TOKEN`; báo lỗi: issue confidential trên GitLab; widget hoạt động: feed Gitea không token. Runbook: repo `poli0981/.github`, `docs/GITEA-MIGRATION.md` (`08` §0) |
## Cách dùng suite
+7 -7
View File
@@ -6,7 +6,7 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
## 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).
1. Một địa chỉ duy nhất đại diện cả hai "mặt": developer (poli0981 — GitHub đến 11/2026, nay Gitea `git.poli0981.dev/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` 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.
@@ -25,7 +25,7 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
| Persona | Đến từ | Cần gì |
|---|---|---|
| Viewer của kênh | YouTube/Discord | Xem "người đứng sau kênh", video mới, đang chơi gì, FAQ, link social |
| Dev/recruiter/collab | GitHub, mail sponsor | Portfolio project, /uses, cách liên hệ đáng tin (`contact@poli0981.dev`) |
| Dev/recruiter/collab | Gitea/GitLab (trước 11/2026: GitHub), mail sponsor | Portfolio project, /uses, cách liên hệ đáng tin (`contact@poli0981.dev`) |
| Độc giả truyện | Social/share link | Trải nghiệm đọc dài thoải mái trên điện thoại, theo dõi qua RSS |
| Chính Kokone | — | Viết nhanh, đăng nhanh, không phải bảo trì nhiều |
@@ -37,24 +37,24 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
|---|---|---|
| Trang chủ | Hero + signature Waveline, bài blog/truyện mới nhất, widget video mới + đang chơi gì | P1 (widget P2) |
| /about | Song ngữ, 2 mặt dev/creator, ảnh đại diện, timeline ngắn | P1 |
| /projects | Card từ collection `projects`, filter theo tag, link GitHub/release | P1 |
| /projects | Card từ collection `projects`, filter theo tag, link repo (Gitea; trước 11/2026: GitHub)/release | P1 |
| /blog | Index + trang bài, tag, reading time, RSS riêng | P1 |
| /stories | Index theo series/status, **reader mode** riêng (font serif, chỉnh cỡ chữ, theme giấy, progress, prev/next chương, content-warning) | P1 |
| /gallery | Album theo năm/sự kiện, lightbox, EXIF đã strip | P2 |
| /gaming | Giới thiệu kênh, embed video (click-to-load, nocookie), thể loại yêu thích, widget Steam | P2 |
| /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 |
| /links | Toàn bộ social (YouTube, Discord ×2, Gitea (trước 11/2026: GitHub), Telegram, Bluesky, Mastodon, X, Facebook), icon + mô tả | 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 |
| Bug report | Nút footer → issue (GitHub đến 2026-11-23; nay issue confidential trên mirror GitLab) + Discord | P2 |
| Legal gate | Bottom-sheet lần đầu truy cập | P1 |
## 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.
+30 -27
View File
@@ -2,7 +2,7 @@
## 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 (`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.
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/Gitea vào KV.
```
Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Transform Rule x-verified-bot)
@@ -11,19 +11,20 @@ Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Trans
src/worker.ts — entry của Worker (assets.run_worker_first: mọi trang đều qua đây)
├── www → apex (301)
├── denylist IP (KV, một khoá "denylist", CIDR + hạn) → trang 403
├── rate limit toàn site RL_SITE 100/10s/IP (trừ admin.*) → trang 429
├── tách host: admin.poli0981.dev chỉ /admin*, /api/admin*, /media/*
├── /media/* → R2 poli0981-media (ảnh upload qua admin, cache 1 năm)
├── /ext-img/* → KV widgets:img:* (ảnh widget đã mirror; không gọi Google/Steam)
├── cổng Turnstile (vé 48 giờ) → trang xác minh thay <body>
├── trang tĩnh → ASSETS (dist/)
└── còn lại → app Astro (@astrojs/cloudflare/handler)
├── trang tĩnh → ASSETS (dist/) — trang không có ⇒ 404.html gần nhất (en/404.html dưới /en/)
└── /api/*, /admin* → app Astro (@astrojs/cloudflare/handler)
├── middleware: admin (Access JWT + CSRF), rate limit /api, trang lỗi
├── /api/report · /api/gate · /api/widgets · /api/health
└── /admin/* + /api/admin/* (GitHub API → repo content, R2, Images, KV)
└── /admin/* + /api/admin/* (Gitea 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)
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / feed Gitea (+ mirror ảnh)
```
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).
@@ -32,16 +33,16 @@ Mọi response đi ra đều qua `withSecurityHeaders` (`src/lib/security-header
| Thành phần | Bản | Ghi chú |
|---|---|---|
| Node.js | 26 (`.nvmrc` = `26`, Workers Builds `NODE_VERSION=26`) | engines: `>=26` |
| Node.js | 26 (`.nvmrc` = `26`, CI đọc `.nvmrc`; Workers Builds `NODE_VERSION=26` đến 2026-11) | 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 |
| Wrangler | ^4.152 | dev, types, smoke test, deploy tay |
| Wrangler | ^4.152 | dev, types, smoke test, deploy (job `deploy` của CI từ 2026-11-24; widgets 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 |
| Test | `node:test` của Node 26 | không thêm deps; `module.registerHooks` giả lập `astro:*`/`cloudflare:workers`; coverage ≥ 80% dòng (lcov từng gửi SonarCloud, bỏ 2026-11-24) |
| jose · marked · yaml · zod | ^6 · ^18 · ^2 · ^4 | Access JWT · preview admin · frontmatter · schema |
## 3. Cấu trúc repo
@@ -52,9 +53,9 @@ poli0981-dev/
├── 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
│ # check-install-scripts, smoke-worker, new-post, content-publish
├── src/
│ ├── worker.ts # entry: denylist, host, /media, /ext-img, cổng, assets
│ ├── worker.ts # entry: denylist, rate limit site, host, /media, /ext-img, cổng, assets
│ ├── middleware.ts # admin JWT + CSRF, rate limit /api, trang lỗi
│ ├── assets/ # ảnh qua pipeline Astro (gallery/, covers/)
│ ├── components/ # .astro + islands .svelte
@@ -66,11 +67,13 @@ poli0981-dev/
│ ├── lib/ # gate/, admin/, media/, denylist, ext-img, log, version, palette, theme…
│ ├── pages/ # routes + /en/* + api/* + admin/* + 403/404/429/500
│ └── styles/ # global.css (token), prose.css, admin.css
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/GitHub…)
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/Gitea…) · a11y/ (*.spec.ts: axe-core + bàn phím qua Playwright)
├── workers/widgets/ # worker cron riêng (wrangler.jsonc riêng)
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, dependabot.yml
├── astro.config.mjs · wrangler.jsonc · sonar-project.properties · lefthook.yml · knip.json
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · CHANGELOG.md
├── .gitea/workflows/ # ci.yml (build · deploy · publish), content-bump.yml, security.yml, qodana.yml, lighthouse.yml (08 §0)
├── .github/ # ISSUE_TEMPLATE/ (config, bug_report, accessibility, language — Gitea đọc) + pull_request_template.md
├── .gitlab/ # issue_templates/ (Bug, Accessibility, Language) + merge_request_templates/Default.md — cho mirror GitLab
├── astro.config.mjs · wrangler.jsonc · renovate.json · 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
@@ -80,7 +83,7 @@ poli0981-dev/
- **Một thân trang cho hai ngôn ngữ**: route vi và en chỉ là wrapper gọi component trong `src/components/pages/` với `locale` (và props từ builder `getStaticPaths` trong `src/lib/pages.ts`).
- Nút đổi ngôn ngữ: trang có bản dịch (`translationKey`) → đúng bản dịch; không có → mục tương ứng của ngôn ngữ kia (`sectionFallbackPath`), không bao giờ 404.
- Truyện: chương thuộc series → `/truyen/<series>/<slug>/`; truyện lẻ (không có thư mục series) → `/truyen/<slug>/`.
- 404: `src/pages/404.astro`; cấu hình assets `not_found_handling: "404-page"`.
- 404: `src/pages/404.astro` (vi) và `src/pages/en/404.astro`, cùng thân `components/pages/NotFoundPage.astro`. Assets `not_found_handling: "404-page"` trả `404.html` gần nhất theo đường dẫn, nên integration `localized-404` (astro.config.mjs) dời bản en từ `en/404/index.html` sang `en/404.html`; worker trả nguyên response 404 đó (app Astro chỉ nhận `/api/*`, `/admin*` — test canh mọi route `prerender = false` nằm trong `APP_PREFIXES`).
## 5. Worker "site" — wrangler.jsonc (rút gọn)
@@ -94,8 +97,8 @@ poli0981-dev/
"assets": { "binding": "ASSETS", "directory": "./dist", "not_found_handling": "404-page",
"html_handling": "auto-trailing-slash", "run_worker_first": ["/*", "!/_astro/*", "…"] },
"kv_namespaces": [{ "binding": "KV", "id": "…" }],
"ratelimits": [ RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ],
"vars": { "GATE_MODE": "on", "ACCESS_TEAM_DOMAIN": "…", "ACCESS_AUD": "…", "REPORT_REPO": "poli0981/site-reports" },
"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_PROJECT": "poli0981/poli0981-dev" }, // project GitLab (10 §4)
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "poli0981-media" }],
"images": { "binding": "IMAGES" },
"version_metadata": { "binding": "CF_VERSION_METADATA" },
@@ -104,7 +107,7 @@ poli0981-dev/
}
```
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`.
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng đầy đủ ở `06` §4): `TURNSTILE_SECRET`, `GATE_SECRET`, `GITLAB_ISSUES_TOKEN`, `DISCORD_WEBHOOK_BUG`, `GITEA_BOT_TOKEN`, `ADMIN_EMAILS` (từ 2026-11-24; trước đó `GITHUB_ISSUES_TOKEN`, `GITHUB_CONTENT_TOKEN`, `GITHUB_PUBLISH_TOKEN`).
`/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.
@@ -118,7 +121,7 @@ Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng
## 7. Setup máy dev (một lần)
```bash
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
git clone --recurse-submodules https://git.poli0981.dev/poli0981/poli0981-dev.git
cd poli0981-dev
nvm use # đọc .nvmrc = 26
npm ci --ignore-scripts && npm run check-install-scripts
@@ -127,14 +130,14 @@ 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; `THIRD-PARTY-NOTICES.md` sinh bằng `scripts/gen-notices.mjs` và CI kiểm lệch.
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` + Renovate 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 (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).
- Pin `^` trong cùng major; Renovate (tự host, chạy hằng ngày) gộp patch/minor vào một PR, chỉ đề xuất bản đã phát hành ≥ 3 ngày (`08` §6). Đến 2026-11-23: Dependabot hằng tuần, cooldown 3 ngày.
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + thử local (`17` §2; từ 2026-11-24 không còn version preview cho PR).
- **TypeScript 7**: `@typescript/native` là alias `npm:typescript@7` — thời Dependabot (bỏ qua alias `npm:`) phải nâng tay; Renovate theo dõi nó như một dependency riêng, luật giữ `typescript` major không chặn nó. `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: Renovate (cảnh báo OSV ⇒ PR nhãn `security`), `npm audit` (CI), `security.yml` (osv-scanner, Opengrep, gitleaks), Qodana (`06` §6). Đến 2026-11-23 còn Dependabot alerts, Snyk, CodeQL, SonarCloud.
## 9. ADR (Architecture Decision Records — rút gọn)
@@ -143,11 +146,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 | 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 |
| 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 (từ 2026-11-24 một token bot Gitea, `06` §9); ả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 issue + Discord (issue trên GitHub đến 2026-11-23; nay issue confidential trên GitLab, `10` §4); 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 |
| 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 (SonarCloud bỏ 2026-11-24 khi chuyển Gitea; ngưỡng 80% dòng vẫn nằm trong `test:coverage`) | 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 |
+13 -7
View File
@@ -112,24 +112,30 @@ Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai
| 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 + CW |
| 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 `--horror`, bấm để mở nội dung |
| 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) |
| WidgetLatestVideo / WidgetNowPlaying / WidgetGitea (trước 2026-11-24: WidgetGitHub) | .astro | đọc KV lúc request?—không: đọc lúc **build** + island refresh nhẹ (xem 11 §5) |
| Callout, TagPill, Pagination | .astro | |
## 8. A11y & mobile checklist (áp cho mọi PR UI)
- Focus ring rõ (2px accent, offset 2px), điều hướng bàn phím đủ; skip-link.
- Touch target ≥ 44×44; `safe-area-inset` cho TabBar; không hover-only cho thông tin.
- Ảnh có alt (bắt buộc trong schema gallery); icon-only button có `aria-label`.
- Kiểm tra 360px, 390px, 768px, 960px, 1280px; dark/light/theo hệ thống; vi/en (chuỗi EN thường dài hơn ~20%).
- Focus ring rõ (2px accent, offset 2px), điều hướng bàn phím đủ; skip-link. Thứ gì mở ra (menu, dialog, panel) thì đóng bằng Esc và **trả focus về nút đã mở nó**.
- Focus không được nằm dưới thanh cố định (WCAG 2.4.11): `scroll-padding` của `html` (global.css) đã trừ header, TabBar, thanh đọc truyện và bảng thông báo pháp lý — thanh mới ở mép trên/dưới phải cộng vào `--subheader-h` / `--bottom-bar-h`.
- Touch target: TabBar 56px, icon mạng xã hội ở footer 44px, nút header 40px; **không bao giờ dưới 24px** (WCAG 2.5.8). `safe-area-inset` cho TabBar; không hover-only cho thông tin.
- Trạng thái và "đang ở đâu" **không chỉ bằng màu** (WCAG 1.4.1): nav đang mở có gạch chân, tab đang mở có vạch trên, lựa chọn đang chọn in đậm + viền kép; link nằm giữa câu phải gạch chân.
- `forced-colors` (Windows High Contrast): thứ chỉ vẽ bằng `background`/`box-shadow` sẽ biến mất — thêm `outline` hoặc màu hệ thống (`Highlight`, `ButtonText`, `Canvas`…) trong `@media (forced-colors: active)`.
- Ảnh có alt (bắt buộc trong schema gallery; `alt=""` chỉ khi ảnh trang trí); icon-only button có `aria-label` **bắt đầu bằng chữ đang hiển thị** (WCAG 2.5.3 — axe so theo từng từ và bỏ phần trong ngoặc đơn).
- Heading không nhảy cấp: card (`PostCard`/`ProjectCard`/`GalleryCard`) nhận `headingLevel` — 2 khi nằm ngay dưới `h1`, 3 khi dưới một `h2`. Mỗi `<nav>` một tên riêng (footer đã dùng "Pháp lý" và "Mạng xã hội").
- Kiểm tra 320px, 360px, 390px, 768px, 960px, 1280px (không cuộn ngang ở bất kỳ mức nào); zoom 200%; dark/light/theo hệ thống; vi/en (chuỗi EN thường dài hơn ~20% — header cần 378px ở bản vi, 400px ở bản en, dưới đó nút ngôn ngữ rút thành `EN`/`VI`).
- `npm run test:a11y` xanh (axe-core mọi trang + các dialog khi mở, bàn phím, reflow, forced-colors — `tests/a11y/`), rồi nghe lại một lượt bằng trình đọc màn hình. Cam kết đầy đủ: `ACCESSIBILITY.md`.
- Màu mới phải vào `palette.ts` + `global.css` cùng lúc (test chặn nếu lệch hoặc dưới AA); không hard-code màu trong component — dùng token.
- `<dialog>` modal giữ `margin: auto` (preflight Tailwind xoá margin — global.css trả lại); danh sách trong `.prose` có marker (preflight xoá `list-style`).
- Nhãn landmark, aria-label và chuỗi giao diện lấy từ `src/i18n`, không viết cứng.
+24 -6
View File
@@ -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]
---
```
@@ -84,16 +102,16 @@ tags: [horror, short-story]
## 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 đè.
- **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 Gitea hay chỗ khác) ⇒ báo xung đột (409) thay vì ghi đè. Từ 2026-11-24 repo content nằm trên Gitea (`https://git.poli0981.dev/poli0981/content`), admin ghi qua token bot `GITEA_BOT_TOKEN` (`06` §9).
- **Ả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.
- **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, job `publish` merge PR và job `deploy` deploy `main` (đến 2026-11-23: Workers Builds deploy; ~5–8 phút). Runner chạy trên PC của chủ repo ⇒ PC tắt thì xuất bản chờ tới khi runner lên lại. 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 Gitea và mirror GitLab (đến 2026-11-23: 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`.
2. **Capture từ điện thoại**: github.com → repo → thư mục collection → Add file → viết vài dòng + frontmatter tối thiểu + `draft: true` → commit thẳng `main` (draft không build ra site nên an toàn).
2. **Capture từ điện thoại**: `git.poli0981.dev` → repo `content` → thư mục collection → Add File → New File (đến 2026-11-23: github.com) → viết vài dòng + frontmatter tối thiểu + `draft: true` → commit thẳng `main` (draft không build ra site nên an toàn).
3. **Xuất bản**: bỏ `draft`, điền đủ frontmatter, chạy checklist §7, push → CI deploy.
4. Template sẵn: `docs/templates/{blog,story-chapter,project,faq}.md` — copy là viết.
@@ -121,6 +139,6 @@ Tiện ích khuyến nghị: snippet VS Code cho từng frontmatter; `npm run ne
- [ ] 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 -7
View File
@@ -12,10 +12,10 @@
| `/gallery`, `/gallery/[album]` | `/en/...` | gallery |
| `/gaming` · `/dev` (kèm `/dev/uses`) | `/en/...` | md + widgets |
| `/qa` · `/links` | `/en/...` | faq + data links |
| `/legal/{terms,privacy,disclaimer,third-party,licenses,ai-usage}` | `/en/legal/...` | `legal/*.md` (repo content) |
| `/legal/{terms,privacy,disclaimer,third-party,licenses,ai-usage,accessibility}` | `/en/legal/...` | `legal/*.md` (repo content) |
| `/now` | `/en/now` | now |
| `/rss.xml`, `/blog/rss.xml`, `/truyen/rss.xml`, `/sitemap-index.xml`, `/robots.txt`, `/.well-known/security.txt` | | |
| `/404`, `/500`, `/403`, `/429`, `/offline` | song ngữ trong 1 trang | 09 |
| `/404` (+ bản en cho mọi đường dẫn `/en/…`), `/500`, `/403`, `/429`, `/offline` | tiêu đề chính + dòng ngôn ngữ kia; 404 có bản riêng mỗi ngôn ngữ | 09 |
| `admin.poli0981.dev`: `/admin/` (tổng quan), `/admin/content/`, `/admin/edit/`, `/admin/media/`, `/admin/gallery/`, `/admin/activity/`, `/admin/security/` | chỉ vi | on-demand, sau Access (`06` §9) |
## 2. Wireframe chính (mobile-first)
@@ -40,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]
```
@@ -50,11 +51,11 @@ ReadingControls: cỡ chữ S/M/L · nền Giấy/Sepia/Tối (độc lập them
**Gaming**: hero kênh (banner + subscribe button link) → 3 video mới (YouTube RSS, thumbnail click-to-load nocookie) → "Đang chơi" (Steam) → khối "Mình cover gì": VN · JRPG · indie/psychological horror (kèm dòng: không FPS/competitive) → link Discord gaming server. Được phép scanline nhẹ (03 §4).
**Dev**: intro → grid project featured → /uses (bảng: PC specs i7-14700KF · RTX 5080 16GB · 32GB DDR5 · 2K 240Hz · Win 11 Pro; software: OBS, Resolve Studio, VS Code…) → hoạt động GitHub (widget).
**Dev**: intro → grid project featured → /uses (bảng: PC specs i7-14700KF · RTX 5080 16GB · 32GB DDR5 · 2K 240Hz · Win 11 Pro; software: OBS, Resolve Studio, VS Code…) → hoạt động Gitea (widget; trước 2026-11-24 là GitHub).
**Q&A**: accordion theo group (Kênh/Dev/Cá nhân) → khối Liên hệ: "Nhanh nhất: Discord · Business: contact@poli0981.dev · Toàn bộ: /links".
**Links**: danh sách dọc lớn (icon + tên + mô tả 1 dòng + nút): YouTube, Discord gaming, Discord repo, GitHub, Telegram, Bluesky, Mastodon, X, Facebook page. `rel="me"` cho Mastodon verify.
**Links**: danh sách dọc lớn (icon + tên + mô tả 1 dòng + nút): YouTube, Discord gaming, Discord repo, Gitea (trước 2026-11-24: GitHub), Telegram, Bluesky, Mastodon, X, Facebook page. `rel="me"` cho Mastodon verify.
## 3. Điều hướng
@@ -71,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
+22 -16
View File
@@ -23,7 +23,11 @@ request → src/worker.ts (mọi route, cả trang tĩnh)
1. denylist: MỘT khoá KV "denylist" = [{cidr, reason?, until?, added?}]
đọc tối đa 1 lần/phút/isolate (+ cacheTtl 60 s ở colo); IP hoặc dải CIDR (IPv4/IPv6),
mục hết hạn bị bỏ qua → khớp ⇒ 403 (trang 09 §2, no-store) · KV lỗi ⇒ bỏ qua (fail-open, có log)
2. app Astro — middleware, nếu path bắt đầu /api/<group>:
2. rate limit toàn site: RL_SITE 100/10s, khoá "site:<ip>" (IPv6 gộp /64), cho MỌI request
tới Worker — trang, /media, /ext-img, /pagefind, /api — trừ host admin.* (đã có Access)
vượt ⇒ 429 + Retry-After: 10, đếm ngược 10 s · binding lỗi ⇒ bỏ qua (fail-open, có log,
không bỏ qua cổng Turnstile)
3. app Astro — middleware, nếu path bắt đầu /api/<group>:
Workers Rate Limiting binding theo nhóm (src/lib/ratelimit.ts), khoá "<group>:<ip>"
(IPv6 gộp theo /64):
report → RL_REPORT 5/60s · gate → RL_GATE 30/60s · admin → RL_ADMIN 120/60s
@@ -32,12 +36,13 @@ request → src/worker.ts (mọi route, cả trang tĩnh)
```
- Một khoá thay vì `denylist:<ip>`: tra cứu tốn như nhau dù IP nào hỏi (một lần đọc/phút/isolate) và chặn được cả dải. Quản lý ở **admin → Bảo mật** (`/admin/security/`): thêm kèm lý do + thời hạn (1 giờ … 30 ngày, hoặc đến khi gỡ), gỡ, có audit log. Không cho chặn dải chứa IP của chính admin — danh sách áp cho mọi host, kể cả admin. Thay đổi có hiệu lực trong khoảng một phút.
- Binding rate limit đếm **theo từng colo** và chỉ cho `period` 10 hoặc 60 s → lớp mềm; lớp cứng là zone rate-limit rule (07 §6). `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981004).
- Binding rate limit đếm **theo từng colo**, gần đúng (burst có thể lọt quá ngưỡng một chút) và chỉ cho `period` 10 hoặc 60 s → lớp mềm; lớp cứng là zone rate-limit rule (07 §6). `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981005). `Retry-After` phải bằng `period` (hằng số trong `src/lib/ratelimit.ts`, test đối chiếu với `wrangler.jsonc`).
- Ba lớp, ngoài vào trong: **WAF rule** (edge, chặn trước khi Worker chạy — không tốn request Worker, trang chặn 1015 của Cloudflare) → **RL_SITE** (ngưỡng thấp hơn WAF để khách thật gặp trang 429 "đẹp" trước) → **nhóm /api** (chặt nhất). Một lượt xem trang tốn 1–20 request tới Worker (file tĩnh `/_astro/*` không qua Worker), nên 100/10s chỉ chặn flood và giữ F5.
- Chặn quốc gia/ASN hay danh sách rất dài: dùng WAF custom rule / IP List (07 §7).
## 3. Form duy nhất: /api/report (bug)
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.
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 **confidential** trên mirror GitLab `poli0981/poli0981-dev` (đến 2026-11-23: repo private `poli0981/site-reports` trên GitHub) + Discord (`allowed_mentions` rỗng, `@mention` và quick action GitLab 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).
@@ -74,29 +79,30 @@ gate.js → Turnstile (action "gate") → POST /api/gate (RL_GATE, Sec-Fetch-Sit
|---|---|---|
| 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 |
| GITLAB_ISSUES_TOKEN | worker site | token GitLab, role **Reporter** trên project mirror `poli0981/poli0981-dev`, scope `api` — chỉ để tạo issue confidential (`10` §4) |
| DISCORD_WEBHOOK_BUG | worker site | webhook 1 kênh riêng |
| 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" |
| GITEA_BOT_TOKEN | worker site | token `write:repository` của user bot `poli0981-bot`, collaborator Write **chỉ** trên `poli0981/content` (admin lưu bài) và `poli0981/poli0981-dev` (nút Xuất bản dispatch `content-bump.yml`) — §9 |
| 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) |
| QODANA_TOKEN | secret Actions (Gitea) | token project trên Qodana Cloud (`08` §0b) |
| CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID | secret Actions cấp user (Gitea) | job `deploy` của `ci.yml` — quyền ở `07` §10 |
Bỏ ngày 2026-11-24 (chuyển sang Gitea): `GITHUB_ISSUES_TOKEN` (PAT chỉ repo private `poli0981/site-reports`, Issues R/W), `GITHUB_CONTENT_TOKEN` + `GITHUB_PUBLISH_TOKEN` (hai PAT của admin, thay bằng `GITEA_BOT_TOKEN`), `GITHUB_TOKEN` tuỳ chọn của worker widgets (feed Gitea không cần token), `SONAR_TOKEN` (secret GitHub Actions của SonarCloud).
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.
`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. (Từ 2026-11-24 CI không còn upload version preview cho PR, nhưng một `versions upload` chạy tay vẫn có thể là bản mới nhất.)
## 5. Nội dung nhúng bên thứ ba
- 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.
- 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 — job `deploy` của CI đặt `PUBLIC_CF_BEACON=true` (đến 2026-11-23: bản build `main` 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 public từ 10/2026)
- **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ế.
- **Quét** (từ 2026-11-24): Renovate tự host (chỉ đề xuất bản đã phát hành **≥ 3 ngày** — chặn kiểu Shai-Hulud; cảnh báo OSV mở PR nhãn `security` ngay, không chờ) · `npm audit --omit=dev --audit-level=high` trong CI (fail = chặn merge) · **`security.yml`** (reusable của repo ops: gitleaks trên toàn bộ lịch sử, Opengrep luật JS/TS, osv-scanner trên `package-lock.json`; PR, push `main`, thứ Tư hằng tuần; SARIF là artifact vì Gitea không có code scanning) · **Qodana** (ngưỡng 0, tư vấn). Đến 2026-11-23: Dependabot (alerts + security updates, cooldown 3 ngày), OSV-Scanner (SARIF), CodeQL, SonarCloud (quality gate trên PR), Snyk (GitHub app).
- Mỗi PR Renovate: đọ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`)
@@ -106,7 +112,7 @@ 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
Policy: https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/SECURITY.md
```
## 8. Checklist hardening
@@ -137,7 +143,7 @@ admin.poli0981.dev ─▶ Cloudflare Access (policy email) ─▶ Worker
- **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.
- **Một token Gitea** (`GITEA_BOT_TOKEN`, từ 2026-11-24; `src/lib/admin/gitea.ts`): token `write:repository` của user bot `poli0981-bot`, collaborator Write chỉ trên `poli0981/content` và `poli0981/poli0981-dev`. Scope của token Gitea áp cho mọi repo mà user đó với tới, nên giới hạn nằm ở danh sách collaborator của bot, không ở token. Bot không đẩy code vào repo site — ở đó nó chỉ dispatch `content-bump.yml`, và `main` chỉ chủ repo push được (branch protection, `08` §0). Lưu bài = API change-files của Gitea (`POST /repos/{o}/{r}/contents`, sha của từng file là khoá lạc quan ⇒ sửa song song thì admin báo xung đột 409); danh sách = head nhánh + cây đệ quy + `POST …/file-contents` theo lô 50 file. Trạng thái xuất bản = PR `content/bump` đang mở, commit status `CI / build (…)` của nó, marker `<!-- publish: auto -->` / `<!-- publish: review -->` trong thân PR, run `content-bump.yml` gần nhất. Xuất bản đi qua `content-bump.yml` (job token) + CI `build` bắt buộc; diff có file ngoài `.md/.json` (vd. `.mdx` — chạy code lúc build) ⇒ marker review, không tự merge. (Đến 2026-11-23: **hai token GitHub** fine-grained — quyền của một PAT áp cho *mọi* repo nó được chọn — `GITHUB_CONTENT_TOKEN` chỉ `poli0981/content` Contents R/W và `GITHUB_PUBLISH_TOKEN` chỉ `poli0981/poli0981-dev` Actions R/W; thiếu token thứ hai thì admin cảnh báo "một token". Cảnh báo đó đã bỏ.)
- **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.
@@ -146,7 +152,7 @@ admin.poli0981.dev ─▶ Cloudflare Access (policy email) ─▶ Worker
## 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.
- **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.gitlab_failed` (trước 2026-11-24: `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.
- **Timeout**: mọi `fetch` ra Gitea/GitLab/Discord/YouTube/Steam có `AbortSignal.timeout` (10–15 s) — một API treo không giữ request hay isolate.
+30 -20
View File
@@ -33,13 +33,22 @@ Zone → Security:
- **WAF → Managed rules**: bật Cloudflare Managed Ruleset (free ruleset).
- Settings → Security Level: Medium · Browser Integrity Check: ON.
## 6. Rate limiting rule (free có 1 rule) — lớp ngoài cho /api/*
## 6. Rate limiting rule (free có 1 rule) — lớp ngoài cho toàn site
Security → WAF → Rate limiting rules → Create:
- Name: `api-outer-limit`
- If: `URI Path starts with /api/`
- Rate: **20 requests / 10 seconds** per IP → Action: **Block**, duration 1 phút (mitigation timeout theo option gói free).
(Lớp trong Worker vẫn đếm 5/phút để trả trang 429 đẹp — rule này chỉ hứng flood thô.)
Gói Free: **1 rule**, biểu thức chỉ dùng được trường **URI Path** và **Verified Bot**, đếm theo **IP**, chu kỳ **10 s**, thời gian chặn **10 s**, không đổi được trang chặn (Cloudflare trả **429**, trang "Error 1015"). Rule chặn ở edge, trước Worker ⇒ flood không tốn request Worker.
Lớp trong Worker (06 §2) đếm thấp hơn — RL_SITE 100/10s cho mọi request tới Worker — để khách thật gặp trang 429 của site trước; rule này chỉ hứng flood thô, nên ngưỡng phải **cao hơn** 100.
Security → Security rules → Rate limiting rules (đang có rule mẫu "Leaked credential check" chiếm slot duy nhất — site không có form mật khẩu nào trên zone, admin đăng nhập qua Access ở `*.cloudflareaccess.com`, nên rule đó không bao giờ khớp: sửa nó thành rule dưới, hoặc xoá rồi tạo mới):
- Name: `site-outer-limit`
- Expression (Edit expression):
`(not starts_with(http.request.uri.path, "/_astro/") and not cf.client.bot)`
— bỏ file tĩnh đã hash (lần tải đầu một trang có thể kéo vài chục file) và bot đã xác thực (Googlebot…; bot AI đã bị chặn ở §5).
- Characteristics: IP · Rate: **150 requests / 10 seconds** · Action: **Block** · Duration: **10 seconds**.
- Gói Free không lọc được theo hostname, nên rule này đếm cả `admin.*` (RL_SITE thì miễn admin). Thư viện ảnh admin tải thumbnail lười (`loading="lazy"`), mỗi màn hình vài chục request — dưới 150.
- Khi bị tấn công: hạ xuống 60–80/10s hoặc đổi Action sang **Managed Challenge**; xong thì trả về.
Kiểm tra: `npm run probe:ratelimit -- https://poli0981.dev/legal/privacy/ 400` — dòng `worker 429` là RL_SITE (trang của site), `waf 429` là rule này (trang 1015). Rule chưa bật ⇒ chỉ thấy `worker 429`.
## 7. Custom rules (free có ~5 rule) — chặn IP/dải/quốc gia khi cần
@@ -66,7 +75,8 @@ Rule ghi đè header cho **mọi** request (client không giả được). Worke
## 9. Deploy Worker & custom domain
- **Workers Builds** (dashboard → worker `poli0981-dev` → Settings → Build), nối repo `poli0981/poli0981-dev`:
- **Deploy từ Gitea CI** (từ 2026-11-24): job `deploy` trong `.gitea/workflows/ci.yml` chạy sau `build` khi push `main` (hoặc `workflow_dispatch` trên `main`) — `npm ci --ignore-scripts` → `npm run build` với `PUBLIC_TURNSTILE_SITE_KEY=<site key>` + `PUBLIC_CF_BEACON=true` (thay biến build của Workers Builds) → `npx wrangler deploy --message "main <sha7>"` với secret Actions cấp user `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` (§10) → chờ tới khi `https://poli0981.dev/api/health` trả `version.commit` = commit vừa build (job đỏ nếu sau ~2 phút vẫn chưa). Push chỉ đổi docs (`poli0981.dev-docs/**`, `*.md`, `LICENSE`) không deploy. PR và nhánh khác **không** có version preview nữa (Gitea đưa secret cho PR cùng repo, nên token Cloudflare không được tới gần code của PR). Runner nằm trên PC của chủ repo: merge lúc PC tắt ⇒ deploy khi runner lên lại. Chi tiết workflow: `08` §0.
- **Workers Builds** (đến 2026-11-23 — dùng từ 10/2026, đã ngắt vì nó kéo code từ GitHub; giữ để tra lịch sử) (dashboard → worker `poli0981-dev` → Settings → Build), nối repo `poli0981/poli0981-dev`:
| Mục | Giá trị |
|---|---|
@@ -77,14 +87,14 @@ Rule ghi đè header cho **mọi** request (client không giả được). Worke
| 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`.
- Local (khẩn cấp): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
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. Từ 2026-11-24 Workers Builds đã ngắt khỏi repo, thay bằng job `deploy` ở trên.
- Local (khẩn cấp, vd. job `deploy` không chạy được): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login). Build local không đặt `PUBLIC_TURNSTILE_SITE_KEY`/`PUBLIC_CF_BEACON` thì cổng và beacon khác bản CI — đặt hai biến này như job `deploy` trước khi build.
- 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.
- Worker widgets (không nằm trong job `deploy`, trước đây cũng không nối Workers Builds): deploy tay `npx wrangler deploy --config workers/widgets/wrangler.jsonc` → kiểm tra Triggers có cron.
## 10. API token cho CI (least privilege)
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.
Từ 2026-11-24 job `deploy` của Gitea CI cần token Cloudflare: My Profile → API Tokens → Create Token → Custom → **Account → Workers Scripts → Edit**, cộng những gì binding cần để resolve (KV, R2, routes và custom domain trên zone), đúng account, TTL ≤ 1 năm. Lưu thành **secret Actions cấp user** trên Gitea (dùng chung cho các repo web): `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID`. (Đến 2026-11-23 Workers Builds tự có quyền deploy nên GitHub Actions không cần token Cloudflare.)
## 11. Email (Google Workspace)
@@ -95,6 +105,7 @@ Mail của domain chạy trên **Google Workspace** (MX → `aspmx.l.google.com`
| `contact@` | Liên hệ chung (fallback) | Footer, /links, /now, trang 403 |
| `security@` | Báo lỗ hổng | `/.well-known/security.txt`, `SECURITY.md` |
| `privacy@` | Yêu cầu về dữ liệu cá nhân | Privacy §7–8 |
| `accessibility@` | Báo rào cản trợ năng (trả lời ≤ 7 ngày) | `/legal/accessibility` §5, `ACCESSIBILITY.md`, issue template `accessibility.yml`, README |
| `legal@` | Vấn đề pháp lý | Terms |
| `copyright@` · `dmca@` · `takedown@` | Xin phép · khiếu nại bản quyền · yêu cầu gỡ khác | Licenses, `CONTENT-LICENSE.md` |
| `collab@` · `press@` · `sponsor@` | Hợp tác · báo chí · tài trợ | /links, Q&A, footer |
@@ -107,7 +118,7 @@ Mail của domain chạy trên **Google Workspace** (MX → `aspmx.l.google.com`
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`.
- Chỉ render trong bản build production: job `deploy` của Gitea CI đặt `PUBLIC_CF_BEACON=true` (đến 2026-11-23: build trên Workers Builds nhánh `main`, `WORKERS_CI=1` + `WORKERS_CI_BRANCH=main` → `PUBLIC_CF_BEACON` — `astro.config.mjs` vẫn nhận điều kiện này), nên job `build`/Lighthouse/local 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.
@@ -115,14 +126,13 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
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.
3. Token cho admin (từ 2026-11-24 — Gitea; `06` §9):
- *Bot Gitea*: user `poli0981-bot` trên `git.poli0981.dev`, thêm làm collaborator **Write** chỉ trên `poli0981/content` và `poli0981/poli0981-dev`; tạo token scope **`write:repository`** cho user đó → `npx wrangler secret put GITEA_BOT_TOKEN`. Scope token áp cho mọi repo bot với tới ⇒ đừng thêm bot vào repo khác.
- **`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).
- Báo lỗi: token GitLab role **Reporter** trên project mirror `poli0981/poli0981-dev` (gitlab.com), scope `api` → `npx wrangler secret put GITLAB_ISSUES_TOKEN`; var `REPORT_PROJECT` trong `wrangler.jsonc` (`10` §4).
- Đến 2026-11-23 (GitHub): hai fine-grained PAT — `GITHUB_CONTENT_TOKEN` (chỉ `poli0981/content`, Contents R/W) và `GITHUB_PUBLISH_TOKEN` (chỉ `poli0981/poli0981-dev`, Actions R/W) — và repo private `poli0981/site-reports` trong `GITHUB_ISSUES_TOKEN` (Issues R/W). Ba secret này không còn dùng — gỡ bằng `npx wrangler secret delete <tên>` để `wrangler secret list` khớp `06` §4.
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**.
4. Repo `poli0981-dev` (Gitea): `content-bump.yml` và job `publish` của `ci.yml` khai quyền của job token ngay trong workflow (`contents`/`pull-requests`/`actions: write`). (Đến 2026-11-23 trên GitHub: Settings → Actions → General → bật **Allow GitHub Actions to create and approve pull requests**, 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
@@ -134,7 +144,7 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
- [ ] `dig poli0981.dev` ra IP Cloudflare; DNSSEC = Success
- [ ] https:// bắt buộc, chứng chỉ hợp lệ, HSTS header có mặt
- [ ] Bot Fight ON · Managed WAF ON · (AI crawlers block ON nếu chọn)
- [ ] Rate limit rule active — test bằng script bắn 30 req/10s vào /api/ → bị block
- [ ] Rate limit rule active — `npm run probe:ratelimit` (§6) thấy `worker 429` rồi `waf 429`
- [ ] Turnstile hoạt động trên form report (site key đúng domain)
- [ ] Custom domain trỏ Worker, `www` redirect về apex
- [ ] Cron widgets chạy (Workers → widgets → Logs thấy execution)
@@ -144,5 +154,5 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
- [ ] 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
- [ ] Deploy (từ 2026-11-24): job `deploy` của Gitea CI xanh sau merge `main`, `/api/health` trả đúng commit; Workers Builds đã ngắt (không còn build nào kéo từ GitHub). (Đến 2026-11-23: Workers Builds — Deploy command `main` = `npx wrangler deploy`, nhánh khác = `npx wrangler versions upload`.)
- [ ] Auto-renew ON + transfer lock ON + 2FA ON
+49 -36
View File
@@ -1,14 +1,36 @@
# 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ử)
## 0. Forge & CI (Gitea, từ 2026-11-24)
- **Deploy**: Cloudflare **Workers Builds** nối repo (không có job deploy trong GitHub Actions): `main` → build + `npx wrangler deploy`; nhánh khác → `npx wrangler versions upload` (version preview, không nhận traffic). Cấu hình chi tiết + bẫy đã gặp: `07` §9.
- **`ci.yml`** (PR, push `main`, `workflow_dispatch`), job **`build`** (timeout 30 phút, checkout kèm submodule):
`npm ci --ignore-scripts` → `check-install-scripts` → `wrangler types` (site + widgets) → prettier → eslint → `astro check` (TS 6) → **`typecheck` bằng TypeScript 7** (in `tsc -v`, kiểm site + widgets) → knip → **`test:coverage`** (`node:test`, ngưỡng 80% dòng, xuất `coverage/lcov.info`) → `npm audit --omit=dev --audit-level=high` → `gen-notices --check` → `check-exif --changed` → build (+ OG, Pagefind, `check-csp-hashes`) → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/`/ext-img`/admin 403/`frame-ancestors`, pha ép bật cổng Turnstile kể cả cookie sai định dạng, pha denylist) → upload coverage làm artifact. Check `build` là **bắt buộc** (ruleset `main`).
- Job **`sonarcloud`** (sau `build`; chạy cho push `main` và PR cùng repo, bỏ qua Dependabot): tải coverage → `SonarSource/sonarqube-scan-action` (pin SHA) với `sonar-project.properties`; trên PR chờ **quality gate** ("Sonar way" cho new code: coverage ≥ 80%, trùng lặp ≤ 3%, rating A, hotspot đã review). Automatic analysis trên SonarCloud **tắt** (CI analysis thay thế); `SONAR_TOKEN` là secret của repo. `.svelte`/`.astro` không được Sonar phân tích — logic quan trọng nằm trong `.ts` để đo được.
- **CodeQL** (default setup, repo public) · **Snyk** (GitHub app) · **`osv-scanner.yml`** (reusable workflow v2.7.0, SARIF, hằng tuần + khi đổi lockfile) · **`lighthouse.yml`** (`treosh/lighthouse-ci-action` pin SHA, preset mobile, chỉ cảnh báo).
- **`content-bump.yml`** (nút **Xuất bản** của admin): trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR, auto-merge (squash) nếu diff chỉ `.md/.json`, rồi `gh workflow run ci.yml --ref content/bump` để có check `build` (PR mở bằng GITHUB_TOKEN không kích hoạt `pull_request`). Merge ⇒ Workers Builds deploy.
- **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.
- **Repo**: bản gốc ở `https://git.poli0981.dev/poli0981/poli0981-dev` (Gitea 28.4.0 tự host); submodule `src/content` = `https://git.poli0981.dev/poli0981/content` (`.gitmodules`). Bản sao công khai `https://gitlab.com/poli0981/poli0981-dev` (push mirror từ Gitea; GitLab CI không chạy ở đó) là nơi người ngoài mở issue và merge request — Gitea không cho người ngoài đăng ký. Patch/câu hỏi: `code@poli0981.dev`; bảo mật: chỉ qua `security@poli0981.dev`, không bao giờ mở issue công khai trên mirror. Tài khoản GitHub `poli0981` không còn. Runbook chuyển nhà: repo `poli0981/.github`, `docs/GITEA-MIGRATION.md` (+ `docs/migration/poli0981-dev.md`).
- **Runner**: một Gitea runner trên PC Windows của chủ repo; job `ubuntu-latest` chạy trong Docker (`docker.gitea.com/runner-images`, user root, **không có Chrome, không có nginx**: CI tự cài Chromium của Playwright cho test a11y và Lighthouse, Lighthouse tự cài nginx). Job chỉ chạy khi PC bật; job theo lịch chỉ đặt trong khung **13:00–16:00 UTC (20:00–23:00 giờ VN)**; run chờ quá 24 giờ không ai nhận thì bị huỷ.
- **Workflows** (`.gitea/workflows/`; mọi action pin theo SHA, Renovate giữ pin mới; artifact qua `christopherhx/gitea-upload-artifact` — Gitea không có giao diện code scanning nên SARIF/report là artifact):
| Workflow | Khi chạy | Việc |
|---|---|---|
| `ci.yml` | PR · push `main` (bỏ qua thay đổi chỉ ở `poli0981.dev-docs/**`, `*.md`, `LICENSE`) · `workflow_dispatch` | `build` (check bắt buộc duy nhất, các bước ở §0b) → `deploy` (push/dispatch trên `main`) · `publish` (dispatch trên `content/bump`, xuất bản nội dung) |
| `content-bump.yml` | `workflow_dispatch` (admin gọi bằng token bot) | bump submodule lên nhánh `content/bump`, mở/cập nhật PR qua API Gitea, dispatch `ci.yml` trên `content/bump` (§0b) |
| `security.yml` | PR · push `main` · thứ Tư 14:13 UTC (21:13 VN) · tay | gọi reusable `security.yml` của repo ops (pin commit `2a255e0e…` = ops v2026.11.1): gitleaks trên toàn bộ lịch sử, Opengrep (luật JS/TS), osv-scanner trên `package-lock.json` |
| `qodana.yml` | PR · push `main` (bỏ qua docs) · tay | Qodana CLI 2026.3.1, native mode; report = artifact `qodana-report` + Qodana Cloud; tư vấn, không bắt buộc |
| `lighthouse.yml` | PR (bỏ qua docs) · tay | ngân sách hiệu năng, chỉ cảnh báo; report = artifact `lighthouse-reports` |
- **Deploy**: Workers Builds (kéo code từ GitHub) đã ngắt. Job `deploy` của `ci.yml` chạy sau `build` khi push `main` (hoặc dispatch trên `main`): build lại với `PUBLIC_TURNSTILE_SITE_KEY` + `PUBLIC_CF_BEACON=true` → `npx wrangler deploy --message "main <sha7>"` (secret Actions cấp user trên Gitea: `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`) → chờ tới khi `https://poli0981.dev/api/health` báo đúng commit. Push chỉ đổi docs không deploy (paths-ignore). **Không còn bản preview cho PR** (token Cloudflare không bao giờ tới gần code của PR). Merge lúc PC tắt ⇒ deploy khi runner lên lại. Worker widgets vẫn deploy tay (`07` §9).
- **Check bắt buộc**: branch protection `main` trên Gitea — status check pattern `CI / build (*)` (Gitea đặt tên check là `<workflow> / <job> (<event>)`), cấm force push, cấm xoá nhánh, chỉ chủ repo được push, không yêu cầu approval.
- **Dependency**: Renovate tự host thay Dependabot (§6). Secret Actions: `QODANA_TOKEN` + hai secret Cloudflare ở trên; secret của Worker không đi qua Actions (`06` §4).
- **Bỏ khi chuyển (2026-11-24)**: SonarQube Cloud (job, `sonar-project.properties`, `SONAR_TOKEN` — Qodana + Opengrep thay), CodeQL/Snyk và upload SARIF vào code scanning, `osv-scanner.yml` (→ `security.yml`), `triage.yml` + `scripts/triage.mjs` (§8), Dependabot, Workers Builds.
## 0b. Chi tiết từng workflow (từ 10/2026, v2.0; cập nhật cho Gitea 2026-11-24) — §1–§5 bên dưới là kế hoạch ban đầu (lịch sử)
- **Deploy** (đến 2026-11-23; nay: job `deploy`, §0): 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` trừ thay đổi chỉ ở docs, `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 nếu image có; image của Gitea runner không có nên CI cài Chromium của Playwright đúng bản trong lockfile, cache theo phiên bản, `A11Y_CHANNEL=bundled` (trên runner GitHub đến 2026-11-23: dùng Chrome có sẵn, 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`). Bước upload coverage làm artifact (cho Sonar) bỏ ngày 2026-11-24. Check `build` là **bắt buộc** (branch protection `main`, §0), nên PR có vi phạm axe không merge được.
- Job **`sonarcloud`** (đến 2026-11-23; đã bỏ khi chuyển sang Gitea — Qodana + Opengrep thay) (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) — cả ba đến 2026-11-23; nay: `security.yml` (§0). **`lighthouse.yml`** (`treosh/lighthouse-ci-action` pin SHA, preset mobile, chỉ cảnh báo; trên Gitea: Chromium của Playwright qua `CHROME_PATH`, nginx tự cài, report là artifact `lighthouse-reports` vì upload của action chỉ chạy với GitHub).
- **`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, không huỷ run đang chạy): admin dispatch bằng `GITEA_BOT_TOKEN` → trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR qua API Gitea (job token), ghi vào thân PR marker `<!-- publish: auto -->` (diff chỉ `.md/.json`) hoặc `<!-- publish: review -->` (API Gitea không có trường auto-merge), rồi dispatch `ci.yml` trên `content/bump` (PR mở bằng job token không kích hoạt workflow nào). **Gitea 28.4 không ghi commit status cho run `workflow_dispatch`** (chỉ push/pull_request) ⇒ commit bump không có `CI / build (*)` mà branch protection đòi, merge bị từ chối 405 — lần xuất bản đầu tiên 2026-11-24 dính đúng lỗi này. Vì vậy job **`publish`** của `ci.yml` (`needs: build`, `if: always()`, chỉ khi dispatch trên `content/bump`) tự ghi status `CI / build (workflow_dispatch)` = kết quả của `build` (kèm link run), rồi nếu build xanh và PR mang marker auto thì squash-merge và dispatch `ci.yml` trên `main` ⇒ job `deploy`; build đỏ ⇒ status failure ⇒ admin hiện "xuất bản lỗi". MDX chờ review; merge tay cũng deploy. Script chung: `scripts/content-publish.mjs`. (Trên GitHub đến 2026-11-23: `gh pr merge --auto --squash`, `gh workflow run ci.yml --ref content/bump`, 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 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). Từ 2026-11-24 chạy bằng **Qodana CLI 2026.3.1** (pin phiên bản + SHA-256, nâng tay cùng repo ops) thay `JetBrains/qodana-action`; kết quả lên Qodana Cloud và vào artifact `qodana-report` (SARIF + HTML) — SARIF vào Code scanning chỉ có thời GitHub. Bỏ qua PR Renovate (Gitea đưa secret cho PR cùng repo, mà PR Renovate cài chính bản cập nhật đang xét) và run không có token, 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`** (đến 2026-11-23; đã bỏ cùng `scripts/triage.mjs` — xem §8) (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 — nay Renovate) đỏ vì bước audit ⇒ vá gộp trong một PR rồi đóng các PR dependency 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
@@ -71,33 +93,23 @@ Secrets runtime của Worker (`TURNSTILE_SECRET`, `GITHUB_ISSUES_TOKEN`, `DISCOR
| EXIF | `node scripts/check-exif.mjs --changed` | fail nếu ảnh có GPS |
| Notices | `node scripts/gen-notices.mjs --check` | THIRD-PARTY-NOTICES.md lệch ⇒ fail |
## 6. Dependabot (`.github/dependabot.yml`)
## 6. Renovate (`renovate.json`, từ 2026-11-24 — thay Dependabot)
```yaml
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule: { interval: weekly, day: monday }
cooldown: { default-days: 3 } # không đề xuất bản phát hành < 3 ngày tuổi
open-pull-requests-limit: 8
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 }
```jsonc
{
"extends": ["local>poli0981/renovate-config"], // preset chung của mọi repo (repo ops)
"packageRules": [
{ "matchDepNames": ["typescript"], "matchUpdateTypes": ["major"], "enabled": false }, // giữ TS 6 cho tooling (02 §8)
{ "matchPackageNames": ["prettier-plugin-astro"], "matchUpdateTypes": ["major"], "enabled": false } // 1.x đổi khoảng trắng hiển thị — cần PR riêng
]
}
```
- `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.
- Renovate **tự host**, chạy hằng ngày 13:31 UTC (20:31 VN) từ workflow `renovate.yml` của repo `poli0981/renovate-config` (bot `renovate-bot`, collaborator Write); PC tắt thì chạy khi runner lên lại. Preset: `config:recommended` + pin digest cho action + gộp mọi cập nhật non-major vào một PR, nhãn `dependencies`, Dependency Dashboard; bản phát hành npm phải đủ **3 ngày tuổi** (giữ đúng cooldown cũ); cảnh báo OSV mở PR riêng nhãn `security`, không chờ 3 ngày.
- `workers/widgets` không có `package.json` (không deps) nên không có mục riêng. Pin SHA của action trong `.gitea/workflows/` cũng do Renovate cập nhật; pin của reusable `security.yml` (comment `# ops …`) và phiên bản Qodana CLI thì nâng tay.
- `@typescript/native` (alias `npm:typescript@7`) là tên dependency khác nên luật giữ `typescript` major không chặn nó — Renovate đề xuất cập nhật như thường (thời Dependabot: không được theo dõi, nâng tay).
- Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. PR bảo mật (nhãn `security`): xử lý ≤ 48h (lịch ở `17`). PR bị một PR gộp thay thế ⇒ đóng kèm comment.
- Trước 2026-11-24: `.github/dependabot.yml` — npm hằng tuần (thứ Hai), `cooldown` 3 ngày, nhóm `astro`/`typescript`/`dev-tools`, hai mục `ignore` như trên; github-actions hằng tuần.
## 7. Git hooks (`lefthook.yml`)
@@ -116,8 +128,9 @@ Commit và tag đều ký GPG; không dùng `--no-verify`.
## 8. Branch & release
- `main` protected (ruleset): PR + check `build` xanh; merge kiểu **squash**. Conventional Commits.
- Mỗi PR: CI `build` + SonarCloud quality gate + CodeQL xanh trước khi merge; Workers Builds trên nhánh PR chỉ `versions upload`.
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + GitHub Release (notes lấy từ `CHANGELOG.md`). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026.
- 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`.
- `main` protected (branch protection Gitea, §0): check bắt buộc duy nhất là `build` (pattern `CI / build (*)`), cấm force push/xoá, chỉ chủ repo push, không cần approval; quy ước merge của repo là **squash**. Conventional Commits. (Đến 2026-11-23: ruleset GitHub, PR + check `build`, cho phép cả 3 kiểu merge.)
- Mỗi PR: ngoài `build` còn phải xanh (theo quy ước, branch protection không ép) Qodana (ngưỡng 0) và `security.yml` (gitleaks, Opengrep, osv-scanner); không còn version preview cho PR. (Thời GitHub: thêm SonarCloud quality gate và CodeQL; Workers Builds trên nhánh PR chỉ `versions upload`.)
- Chế độ bảo trì (D21): chính sách vẫn ở `CONTRIBUTING.md`; mẫu PR (`.github/pull_request_template.md`, Gitea đọc; `.gitlab/merge_request_templates/Default.md` cho mirror) có ô chọn 5 loại thay đổi được nhận. Bot `triage.yml` (đóng PR/issue tính năng mới) bỏ ngày 2026-11-24: người ngoài không mở issue/PR trên Gitea được, còn issue/MR trên GitLab không tới Gitea Actions ⇒ mục ngoài phạm vi được đóng tay trên GitLab.
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + Gitea Release (notes lấy từ `CHANGELOG.md`; đến v2.3.0 là GitHub Release). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026; `v2.4.0` = đợt chuyển sang Gitea. (Đến v2.3.0, mỗi tag còn sửa `sonar.projectVersion` trong `sonar-project.properties` — file đã bỏ.)
- Sau merge: job `deploy` tự chờ `https://poli0981.dev/api/health` trả đúng commit; job đỏ hoặc chưa chạy (PC tắt) ⇒ xem log, chạy lại job, hoặc deploy tay từ máy (`07` §9). Rollback: `wrangler versions deploy` (`17` §2). (Thời Workers Builds: nếu không deploy thì promote version của `main` bằng `wrangler versions deploy`.)
+7 -5
View File
@@ -14,13 +14,13 @@ Nhắc lại quyết định D8: Custom Errors của Cloudflare cần zone plan
| Trang | Trigger | Headline (VI / EN) | Ghi chú riêng |
|---|---|---|---|
| **404** `404.astro` | route không tồn tại | "Trang này không phát ra tín hiệu." / "This page makes no sound." | + ô search (mở Pagefind), gợi ý 3 bài mới. Assets config `not_found_handling: "404-page"` để request tĩnh lạc cũng nhận trang này (P0 Spike 3 verify) |
| **404** `404.astro` · `en/404.astro` | route không tồn tại | "Trang này không phát ra tín hiệu." / "This page makes no sound." | + ô search (mở Pagefind — đúng index của ngôn ngữ trang), gợi ý 3 bài mới cùng ngôn ngữ. Assets config `not_found_handling: "404-page"` trả `404.html` gần nhất theo đường dẫn: `/en/…` nhận bản tiếng Anh (`en/404.html`, xem 02 §4), mọi đường dẫn khác nhận bản tiếng Việt |
| **500** `500.astro` | exception khi render on-demand / api | "Có gì đó vỡ trong im lặng." / "Something broke, quietly." | Astro tự dùng 500.astro khi SSR lỗi; api route bọc try/catch trả JSON lỗi gọn. Mã tham chiếu = **Cloudflare Ray ID** của request, worker đóng dấu vào `#ref` (`src/lib/error-ref.ts`) — trùng field `ray` trong Workers Logs, ReportDialog tự đính vào báo lỗi |
| **403** worker entry | IP/dải nằm trong denylist (KV `denylist`, `06` §2) | "Cửa này đang khoá." / "This door is locked." | Kèm link `mailto:contact@` nếu nghĩ là nhầm. Không nêu lý do cụ thể |
| **429** middleware render | vượt rate-limit app (5 req/phút/IP trên /api) | "Chậm lại một nhịp." / "Take a breath." | Header `Retry-After: 60`; hiện đồng hồ đếm ngược 60s (vanilla JS inline) |
| **429** worker entry · middleware | vượt rate-limit toàn site (RL_SITE 100/10s/IP, worker entry) hoặc của một nhóm /api (middleware, `06` §2) | "Chậm lại một nhịp." / "Take a breath." | Header `Retry-After`: 10 (toàn site) / 60 (nhóm /api); đồng hồ đếm ngược đọc số giây trong `#cd` — mặc định 60, worker ghi đè thành 10. Vượt rule WAF (`07` §6) thì gặp trang 1015 của Cloudflare thay vì trang này |
| **/offline** | service worker fallback | "Không có mạng — nhưng vẫn có thứ để làm." / "You're offline." | Xem §3–4 |
403 (worker entry) và 429 (middleware) dùng template Astro đã **prerender sẵn thành static asset** (`/403/` `/429/` là trang thật): chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng + `no-store` — không nhân đôi markup (đường `astro dev` dùng `rewrite` cũng được bọc lại status).
403 (worker entry) và 429 (worker entry + middleware) dùng template Astro đã **prerender sẵn thành static asset** (`/403/` `/429/` là trang thật): chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng + `no-store` — không nhân đôi markup (đường `astro dev` dùng `rewrite` cũng được bọc lại status).
Trang xác minh của cổng Turnstile (06 §3b) **không** phải trang lỗi: nó là chính trang được yêu cầu (status 200, `<head>` thật) với `<body>` thay bằng thẻ xác minh. `/offline/` đứng ngoài cổng để service worker luôn precache được.
@@ -41,10 +41,12 @@ Canvas ≤ 6KB JS vanilla nằm ngay trong trang offline: đầu lâu pixel nh
| Case | Cách test | Kỳ vọng |
|---|---|---|
| 404 route | mở `/khong-ton-tai` | trang 404, status 404 |
| 404 route en | mở `/en/does-not-exist` | trang 404 tiếng Anh (`lang="en"`), status 404 |
| 404 asset | mở `/anh-khong-co.png` | trang 404 (not_found_handling) |
| 500 | tạm ném throw trong 1 api route ở preview | trang/JSON 500 + mã tham chiếu |
| 403 | thêm IP nhà vào denylist KV preview → mở site | trang 403 custom |
| 429 | bắn 6 POST /api/report trong 1 phút | request 6 nhận trang 429 + Retry-After |
| 429 lớp zone | bắn 30 req/10s | Cloudflare block (trang mặc định) — xác nhận rule sống |
| 429 | bắn 6 POST /api/report trong 1 phút | request 6 nhận trang 429 + Retry-After: 60 |
| 429 toàn site | `npm run probe:ratelimit` (> 100 req/10s) | trang 429, Retry-After: 10, đếm ngược 10 (dòng `worker 429`) |
| 429 lớp zone | `npm run probe:ratelimit -- <url> 400 40` (> 150 req/10s) | trang 1015 của Cloudflare (dòng `waf 429`) — xác nhận rule sống |
| Offline | DevTools → Network Offline → điều hướng | trang /offline + game chạy |
| Mobile | lặp các case trên ở viewport 390px | không vỡ layout |
+13 -8
View File
@@ -1,6 +1,6 @@
# 10 — Bug report pipeline (console error → GitHub Issue + Discord)
# 10 — Bug report pipeline (console error → issue confidential trên GitLab + Discord)
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).
Pipeline này là kênh báo lỗi chính cho visitor (không cần tài khoản nào), và cũng tiện cho chính mình. Repo site là public, nhưng báo cáo có thể chứa log/mô tả riêng tư nên mỗi báo cáo thành một issue **confidential** (chỉ chủ repo xem được) trên mirror GitLab `https://gitlab.com/poli0981/poli0981-dev` — đúng Privacy Policy §4 (repo content, hiệu lực 2026-11-24). Từ 10/2026 đến 2026-11-23 issue được tạo ở repo **private** `poli0981/site-reports` trên GitHub ("private GitHub issue" trong bản Privacy cũ); repo đó mất cùng tài khoản GitHub.
## 1. Client — thu console error
@@ -25,17 +25,22 @@ Dialog (`<dialog>` modal có nhãn, textarea có `<label>`) gồm: textarea mô
}
```
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.
Worker xử lý theo thứ tự: rate-limit (middleware, binding `RL_REPORT` 5/phút/client, fail 429) → thiếu secret (503: thiếu `TURNSTILE_SECRET`, hoặc thiếu cả `GITLAB_ISSUES_TOKEN` lẫn `DISCORD_WEBHOOK_BUG`) → 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 issue confidential trên GitLab** → **Discord webhook** → 201 `{ok: true}` (URL issue không trả về cho người báo vì issue là confidential). Nếu GitLab API lỗi (log `report.gitlab_failed`), hoặc chưa có `GITLAB_ISSUES_TOKEN` (bỏ qua bước GitLab): vẫn bắn Discord và trả 202 `{ok: true, degraded: true}` — 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
## 4. Issue confidential trên GitLab (từ 2026-11-24)
`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):
`POST https://gitlab.com/api/v4/projects/:id/issues` — `:id` là `REPORT_PROJECT` (var trong `wrangler.jsonc`, `poli0981/poli0981-dev` = mirror công khai của repo site), đã URL-encode — với `GITLAB_ISSUES_TOKEN` (token GitLab, role **Reporter** trên project đó, scope `api`):
- `confidential: true` — chỉ chủ project xem được, dù project public
- 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). `@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.
- labels: `bug,from-site`
- body: render đúng cấu trúc template §5 (description → meta → console trong code block). `@mention` trong title/body bị vô hiệu (chèn zero-width) để báo cáo không ping ai, và dòng bắt đầu bằng `/` cũng bị chèn zero-width để GitLab không chạy nó như quick action (`/close`…); nội dung khách đưa vào code span/fence an toàn.
Đến 2026-11-23: `POST /repos/<REPORT_REPO>/issues` của GitHub — `REPORT_REPO` = `poli0981/site-reports` (private) — với `GITHUB_ISSUES_TOKEN` (fine-grained, chỉ repo đó, Issues R/W). Repo và token đã mất cùng tài khoản GitHub.
## 5. Issue template dùng chung — `.github/ISSUE_TEMPLATE/bug_report.yml`
Gitea đọc form này, nhưng người ngoài không đăng ký được trên Gitea; họ mở issue trên mirror GitLab bằng `.gitlab/issue_templates/Bug.md` (bản Markdown của cùng form, giữ hai bản đồng bộ). Khung dưới đây là bản thiết kế ban đầu; form thật nằm trong repo.
```yaml
name: Bug report
description: Báo lỗi website (kèm console error)
@@ -78,4 +83,4 @@ Kênh riêng `#site-reports` trong server repo. Embed: màu `--horror`, title =
- [ ] Gửi hợp lệ → issue mở đúng template + Discord nhận embed trong < 5s
- [ ] 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"
- [ ] GitLab API lỗi (mô phỏng: token sai/hết hạn) → vẫn nhận Discord, 202 `degraded` + client báo "đã ghi nhận"; thiếu hẳn `GITLAB_ISSUES_TOKEN` → vẫn 202 `degraded` qua Discord; thiếu cả token lẫn webhook Discord → 503, dialog chuyển sang gửi qua Discord
+5 -5
View File
@@ -10,7 +10,7 @@ API thời tiết/map phục vụ *chủ site* chứ không phục vụ *khách*
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:yt|steam|gh|status
└─ GitHub API ──┘ └─► mirror thumbnail/icon ─► KV put widgets:img:* (≤ 2 MB, TTL 14 ngày)
└─ feed Gitea ──┘ └─► 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)
```
@@ -23,7 +23,7 @@ Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nha
|---|---|---|
| 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` | 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 |
| Hoạt động Gitea (từ 2026-11-24) | `https://git.poli0981.dev/api/v1/users/poli0981/activities/feeds?only-performed-by=true&limit=30` | Feed công khai, **không token** (chỉ liệt kê repo public; `only-performed-by` bỏ thao tác của bot). Lấy 3 mục mới nhất: `commit_repo` → push kèm số commit, `publish_release` → tag; push lặp lại không có nội dung bị bỏ qua. Lưu đúng dạng cũ (`PushEvent`/`ReleaseEvent`) nên snapshot KV từ thời GitHub vẫn hiển thị được. Đến 2026-11-23: `api.github.com/users/poli0981/events/public?per_page=10` với token tuỳ chọn `GITHUB_TOKEN` (60 req/h/IP khi không có token, IP egress của Workers dùng chung nên hay bị 403) |
## 4. KV schema
@@ -31,7 +31,7 @@ Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nha
|---|---|---|
| `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:gh` | `{updated, items:[{type,repo,ts,detail}]}` — giữ tên khoá `gh` dù nguồn nay là Gitea | — |
| `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 |
@@ -46,12 +46,12 @@ Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nha
- `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".
- `WidgetGitea` (`src/components/WidgetGitea.svelte`, trước 2026-11-24 là `WidgetGitHub`): 3 dòng "pushed to X · 2d ago", link tới repo trên Gitea.
- 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, `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).
`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 bỏ ngày 2026-11-24 — feed Gitea không cần token; gỡ bằng `wrangler secret delete GITHUB_TOKEN --config workers/widgets/wrangler.jsonc` nếu cò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 tay: `npx wrangler deploy --config workers/widgets/wrangler.jsonc` (không nằm trong job `deploy` của CI; trước đây cũng không nối Workers Builds).
## 8. Test
@@ -18,7 +18,7 @@ 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, 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.
**Code.** The source code of this website is free software, licensed under the GNU General Public License v3.0, and is public at https://git.poli0981.dev/poli0981/poli0981-dev, with a mirror for issues at https://gitlab.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.
@@ -26,7 +26,7 @@ Ghi chú pháp lý nhanh (để hiểu, không cần đưa lên site): GPL chỉ
## 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, 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.
**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://git.poli0981.dev/poli0981/poli0981-dev, kèm một bản sao để nhận issue tại https://gitlab.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.
+2 -2
View File
@@ -18,7 +18,7 @@ This is a personal website designed to collect as little data as possible.
**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.
**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 confidential issue on GitLab.com, in the project that mirrors this site's source code (confidential: only I can see it) and sent as 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.
@@ -48,7 +48,7 @@ This is a personal website designed to collect as little data as possible.
**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.
**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 issue bảo mật (confidential) trên GitLab.com, trong project bản sao mã nguồn của trang (chỉ mình xem được), kèm mộ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.
@@ -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 |
@@ -32,13 +31,14 @@ Trang web này được xây dựng bằng phần mềm mã nguồn mở. Mỗi
| Font: Literata | SIL OFL 1.1 | |
| Font: JetBrains Mono | SIL OFL 1.1 | |
**Dịch vụ hạ tầng** (không phải package, ghi nhận cho minh bạch): Cloudflare (hosting/CDN/analytics/Turnstile), GitHub (mã nguồn, issue), YouTube/Steam/GitHub API (widget dữ liệu công khai).
**Dịch vụ hạ tầng** (không phải package, ghi nhận cho minh bạch): Cloudflare (hosting/CDN/analytics/Turnstile), Gitea tự host `git.poli0981.dev` (mã nguồn, nội dung), GitLab (mirror công khai của mã nguồn, issue, báo lỗi dạng issue confidential), YouTube/Steam/feed công khai của Gitea (widget dữ liệu công khai). Đến 2026-11-23: GitHub (mã nguồn, issue) và GitHub API (widget).
## 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 đỏ.
+4 -3
View File
@@ -16,7 +16,7 @@ Bài không có bản dịch: không render hreflang (tránh trỏ trang không
## 3. Sitemap & robots
- `@astrojs/sitemap` với `i18n` config → `sitemap-index.xml`; loại trang lỗi, `/offline`, trang draft.
- `@astrojs/sitemap` với `i18n` config → `sitemap-index.xml`; loại trang lỗi, `/offline`, trang draft và mọi route `/admin/*` (chỉ tồn tại trên `admin.poli0981.dev`; trước v2.2.0 bị lọt 7 URL vào sitemap). Bộ test trợ năng (`tests/a11y/`) lấy danh sách trang từ chính sitemap này.
- `public/robots.txt`:
```
@@ -48,12 +48,13 @@ 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 glacier night (palette tối) + 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).
- 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)
- Toàn site: `Person` (Kokone, sameAs = các URL social ở /links — giúp knowledge panel liên kết YouTube/GitHub).
- Toàn site: `Person` (Kokone, sameAs = các URL social ở /links — giúp knowledge panel liên kết YouTube/Gitea; trước 2026-11-24 là GitHub).
- Bài blog: `BlogPosting`; truyện: `CreativeWork` (`genre`, `isPartOf` series); project: `SoftwareSourceCode` (codeRepository).
## 7. Việc SEO một lần sau launch
+4 -4
View File
@@ -18,15 +18,15 @@
## 2. Kỷ luật để giữ budget
- **Islands discipline**: mặc định `.astro` thuần; island chỉ khi có tương tác thật, ưu tiên `client:visible`/`client:idle`, cấm `client:load` trừ ThemeToggle. GSAP import động trong island, không vào bundle chung.
- **Islands discipline**: mặc định `.astro` thuần; island chỉ khi có tương tác thật, ưu tiên `client:visible`/`client:idle`, cấm `client:load` trên site public (kể cả ThemeToggle — CSS đã hiện đúng icon theo `data-theme-pref`, nên runtime Svelte không cần tranh băng thông với first paint). GSAP import động trong island, không vào bundle chung.
- **Font**: chỉ 4 family, subset latin+vietnamese, preload đúng 2 file, `size-adjust` fallback để CLS≈0. Literata chỉ nạp ở trang đọc.
- **Ảnh**: mọi ảnh qua Astro Image (AVIF ưu tiên), `loading=lazy` trừ LCP (`fetchpriority=high`), khai width/height luôn.
- **CSS**: Tailwind v4 tự purge; grain/scanline bằng 1 PNG nhỏ + CSS, không canvas chạy nền.
- **CSS**: Tailwind v4 tự purge; grain/scanline bằng 1 PNG nhỏ + CSS, không canvas chạy nền. CSS của mỗi trang nằm inline trong HTML (`build.inlineStylesheets: "always"`, ~9 KB brotli) — không còn request CSS chặn render, first paint không phải đợi thêm một vòng mạng.
- **Third-party = 0** ở first paint (YouTube facade, widget đọc KV nội bộ). Beacon Web Analytics là module script (tải defer, ~10 KB) nên không chặn render; nó chỉ có trong bản build production (không có trong Lighthouse CI).
## 3. Kiểm tra
- Local: `npm run build && npx astro preview` + Lighthouse trong DevTools cho 4 trang đại diện: `/`, 1 bài blog, 1 chương truyện, `/gallery/<album>`.
- CI: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý.
- Islands thêm từ 10/2026 đều nhỏ và `client:idle`/`client:load` có lý do: ThemeToggle (`client:load` — icon đúng ngay nhờ CSS theo `data-theme-pref`), SearchModal/MenuSheet (`client:idle`). Admin là trang on-demand riêng, không tính vào budget site.
- CI: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý. Đo qua nginx (gzip, cấu hình ngay trong bước "Start compressing proxy"; image của Gitea runner không có nginx lẫn Chrome nên bước đó tự cài nginx và Lighthouse dùng Chromium của Playwright — runner GitHub đến 2026-11-23 có sẵn cả hai; report là artifact `lighthouse-reports`, `08` §0): `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`).
+17 -7
View File
@@ -2,13 +2,13 @@
Ướ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.
Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chưa.
Trạng thái tại 2026-11-24 (v2.3.0 → v2.4.0 chuyển sang Gitea — **chế độ bảo trì**): ✅ xong · 🟡 đang làm · ⬜ chưa.
## P0 — Spikes ✅
| # | 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) |
| 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; từ 2026-11-24 job `deploy` của Gitea CI) |
| 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) |
@@ -24,7 +24,7 @@ Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chư
- 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`.
- Gaming + Dev/uses; widgets worker (YouTube/Steam/GitHub — GitHub thành Gitea từ 2026-11-24) + `/api/widgets`.
- Bug report pipeline đầy đủ (10) + issue template.
- Offline service worker + trang /offline.
- Lighthouse CI warn-mode.
@@ -38,6 +38,8 @@ Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chư
- Cổng Turnstile trước mọi trang (06 §3b) · admin `admin.poli0981.dev` (Access + JWT, R2 media, xuất bản qua workflow) · repo public.
- **v2.0.0**: Node 26 + TypeScript 7 · SonarCloud + test `node:test` (~99% dòng) · vá bypass cookie cổng · denylist CIDR · ảnh widget qua `/ext-img` · log JSON + version trên `/api/health` · báo lỗi vào repo private · palette Glacier Teal + theme theo hệ điều hành · sửa a11y/i18n · admin mới (tổng quan, hoạt động, bảo mật, audit log). Chi tiết: `CHANGELOG.md`.
- **v2.2.0** (11/2026): tuyên bố trợ năng (`/legal/accessibility` + `ACCESSIBILITY.md`, địa chỉ `accessibility@`) · cổng axe-core + bàn phím trong CI · hỗ trợ Windows High Contrast · "đang ở đâu" không chỉ bằng màu · sửa tràn ngang ở màn hình hẹp (reflow tới 320px) · focus không bị che dưới thanh cố định. Chi tiết: `CHANGELOG.md`, quyết định D20.
## P4 — Launch công khai 🟡
- [x] Checklist `06` §8 (security) phần tự động (headers, CSP, cổng)
@@ -45,18 +47,26 @@ Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chư
- [ ] 13 §7 (SEO một lần) xong
- [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
- [ ] Đă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/Gitea/Discord
## Hướng đi tiếp (sau v2.0)
- **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).
- **v2.4.0** (11/2026, không phải tính năng — tài khoản GitHub không còn): chuyển sang Gitea tự host + mirror GitLab, CI trên Gitea Actions và deploy bằng job `deploy`, Renovate thay Dependabot, bỏ SonarCloud/`triage.yml`, admin/báo lỗi/widget trên Gitea và GitLab (D25). Chi tiết: `CHANGELOG.md`.
## 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; đề xuất tính năng được đóng tay trên mirror GitLab (bot `.github/workflows/triage.yml` làm việc này đến 2026-11-23).
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 |
| Job deploy trong Gitea CI cho widgets worker (trước 2026-11-24: Workers Builds riêng) | 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) |
| Trang 404 riêng cho `/en/` | Hiện 404 song ngữ một trang | Cloudflare phục vụ `404.html` gần nhất theo thư mục |
| Locale `ja` | Seam i18n đã sẵn (`src/i18n/routing.ts`) | Có nội dung thật để dịch |
| Bình luận (Giscus) · trang /support (Ko-fi) | Tương tác/ủng hộ | Đổi D5; mở CSP cho host tương ứng |
+5 -3
View File
@@ -9,11 +9,13 @@ 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 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 |
| Gitea tự host (`git.poli0981.dev`) + Gitea Actions + Renovate tự host | — | $0 riêng cho site | Từ 2026-11-24. Hạ tầng chung cho mọi repo của chủ site (không tính vào bảng này); runner là PC của chủ repo nên không có phút CI tính tiền |
| Mirror GitLab.com (`poli0981/poli0981-dev`) | — | $0 | Project public; GitLab CI tắt; nhận issue/MR và báo lỗi từ site (issue confidential) |
| *Lịch sử:* GitHub public repo + Actions + Dependabot + CodeQL | — | $0 | Đến 2026-11-23. 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 | `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 |
| Zone Pro / Sentry / CMS bên thứ ba | — | $0 | **Cố ý không dùng** — admin tự làm (Access + Gitea API; đến 2026-11-23 là 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)**.
@@ -25,7 +27,7 @@ Tỷ giá tham khảo ~26.000 VND/USD, 2026-07.
| 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 | 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 |
| Phút CI | không tính tiền — runner Gitea trên PC của chủ repo (đến 2026-11-23: GitHub Actions, không giới hạn cho repo public) | ~200–400 | Không phải chi phí; giới hạn thật là PC phải bật (job lịch chỉ 13:00–16:00 UTC, `08` §0) |
| 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
+23 -9
View File
@@ -2,23 +2,35 @@
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ỳ (Renovate tự host chạy hằng ngày, gộp mọi patch/minor vào một PR — từ 2026-11-24; trước đó 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 (từ 2026-11-24): người ngoài không đăng ký được trên Gitea nên issue và merge request đến qua mirror GitLab (`https://gitlab.com/poli0981/poli0981-dev`) hoặc e-mail `code@poli0981.dev`; mục ngoài 5 loại trên được gắn `enhancement` + `out-of-scope` và **đóng tay** trên GitLab, dẫn `CONTRIBUTING.md` (ngoại lệ do chủ repo chấp nhận mang nhãn `maintenance-exception`). Lỗ hổng bảo mật chỉ qua `security@poli0981.dev` — nếu lỡ thành issue công khai trên GitLab thì chuyển nó sang confidential rồi tiếp tục qua e-mail. Form issue: lỗi, accessibility, ngôn ngữ (`.gitlab/issue_templates/` cho GitLab, `.github/ISSUE_TEMPLATE/` cho Gitea); blank issue tắt trên Gitea; câu hỏi/ý tưởng → `code@poli0981.dev`. Đến 2026-11-23 việc đóng do bot `.github/workflows/triage.yml` (logic `scripts/triage.mjs`) làm — gắn `enhancement` + `out-of-scope`, trả lời song ngữ và đóng; câu hỏi/ý tưởng đi Discussions. Bot đã bỏ: issue trên GitLab không tới được Gitea Actions.
## 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; **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 tuần** | Xem PR Renovate (bot chạy hằng ngày 20:31 VN khi PC bật) + Dependency Dashboard: PR gộp patch/minor xanh CI → merge; PR nhãn `security` → xử lý ≤ 48h. Xem run `security.yml` thứ Tư (21:13 VN). Liếc Discord `#site-reports` và issue mới trên mirror GitLab (báo lỗi từ site là issue confidential). (Đến 2026-11-23: thứ 2, triage PR Dependabot) |
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; xem PR Renovate cho `@typescript/native` (thời Dependabot phải nâng tay vì alias `npm:` bị bỏ qua) 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); Qodana Cloud không có vấn đề mới trên `main` (đến 2026-11-23: SonarCloud); nâng tay pin reusable `security.yml` khi repo ops có tag mới |
| **Hằng quý** | Nâng major có kế hoạch (Astro/Tailwind/Wrangler — đọc upgrade guide trước); chạy lại ma trận error test `09` §5; backup ngoài (§4) |
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 5 văn bản legal (đổi thì tăng `v` của legalAck) · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
| **Hằng năm** | **Xoay secrets**: GITLAB_ISSUES_TOKEN (báo lỗi, project mirror GitLab), GITEA_BOT_TOKEN (admin, user `poli0981-bot`), CLOUDFLARE_API_TOKEN (secret Actions cấp user trên Gitea, job `deploy`), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, QODANA_TOKEN (token project trên Qodana Cloud → secret Actions trên Gitea), token push mirror GitLab lưu trong Gitea (hạn ≤ 365 ngày; `setup-mirrors.ps1 -Rotate`, runbook `GITEA-MIGRATION.md` §9) — đến 2026-11-23 còn GITHUB_ISSUES_TOKEN, GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 7 trang legal (đổi thì tăng `v` của legalAck) · **rà trợ năng**: đọc lại `/legal/accessibility` + `ACCESSIBILITY.md`, đi một lượt bằng bàn phím và trình đọc màn hình, cập nhật ngày rà ở cả hai nơi · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
Đặt reminder: dùng chính hệ notify/cron GitHub Actions quen thuộc — workflow cron tháng/quý/năm bắn Discord nhắc việc (input sẵn trong repo `.github`).
Đặt reminder: dùng chính hệ notify/cron quen thuộc của repo `.github` — workflow cron tháng/quý/năm bắn Discord nhắc việc. Từ 2026-11-24 đó là Gitea Actions (trước: GitHub Actions), nên giờ cron phải nằm trong khung 13:00–16:00 UTC (`08` §0).
## 2. Update playbook (major upgrade an toàn)
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. 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 → kiểm `/api/health` trả đúng commit (Workers Builds không deploy ⇒ `wrangler versions deploy`) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
3. Mở PR → CI (`build` + smoke + a11y) + Qodana + Security xanh → bấm qua 6 trang đại diện + search + form report trên bản chạy local (`npm run build && npm run preview`) — từ 2026-11-24 PR không còn version preview. (Đến 2026-11-23: + SonarCloud; Workers Builds upload version preview của nhánh, xem ở dashboard → Versions → alias của nhánh.)
4. Squash-merge → job `deploy` của Gitea CI deploy `main` và tự chờ `/api/health` trả đúng commit (`07` §9; job đỏ hoặc PC tắt ⇒ chạy lại job / deploy tay) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429). (Đến 2026-11-23: Workers Builds deploy `main`; bản cũ còn chạy ⇒ sửa Deploy command, tạm thời `wrangler versions deploy <id>@100%`.)
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.
@@ -27,13 +39,13 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
- **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 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`; dashboard admin hiện cùng thông tin.
- **Đ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.
- **Nguồn sự thật = Git** (nội dung + code). Bản gốc trên Gitea `git.poli0981.dev` (Gitea tự backup hằng ngày 19:30–19:45 UTC); mirror GitLab (`gitlab.com/poli0981/<repo>`, Gitea đẩy sang sau mỗi thay đổi) là bản sao thứ nhất; máy local là bản thứ hai. (Đến 2026-11-23: GitHub là bản sao thứ nhất.)
- **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ử).
- **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`.
@@ -49,6 +61,8 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
| 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 |
| Version sai lên production (PR được deploy, regression) | Rollback ngay (§2), rồi kiểm Deploy command của Workers Builds (`07` §9) |
| Version sai lên production (regression) | Rollback ngay (§2), rồi xem run `deploy` của commit đó trên Gitea (`07` §9). (Thời Workers Builds: kiểm Deploy command — từng có PR được deploy) |
| 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) |
+1 -1
View File
@@ -3,4 +3,4 @@ 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
Policy: https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/SECURITY.md
+45
View File
@@ -0,0 +1,45 @@
# JetBrains Qodana — run by .gitea/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
+18
View File
@@ -0,0 +1,18 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["local>poli0981/renovate-config"],
"packageRules": [
{
"description": "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. TypeScript 7 itself is the @typescript/native alias (npm:typescript@7), a different dependency name, so it keeps its updates. Lift this once those tools support TypeScript 7.1's new API (docs 17).",
"matchDepNames": ["typescript"],
"matchUpdateTypes": ["major"],
"enabled": false
},
{
"description": "prettier-plugin-astro 1.x reflows <span>{expr}</span> onto separate lines in 50 .astro files, inserting whitespace text nodes inside inline elements: a visual change, not a formatting one. It needs its own PR with a rendered diff.",
"matchPackageNames": ["prettier-plugin-astro"],
"matchUpdateTypes": ["major"],
"enabled": false
}
]
}
+1 -1
View File
@@ -37,7 +37,7 @@ const CONTENT = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
// 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;
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'.
+73
View File
@@ -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(", ")})`,
);
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env node
// The Gitea half of a content publish (.gitea/workflows/content-bump.yml and ci.yml), with
// the job token. Two commands:
//
// node scripts/content-publish.mjs open content-bump.yml, after pushing content/bump:
// open or update the PR, say in its body whether it
// merges itself, and dispatch ci.yml on the branch
// node scripts/content-publish.mjs merge ci.yml's `publish` job, after `build` on
// content/bump: record build's result as the
// commit status branch protection requires; when it
// passed and the PR body says auto, merge the PR,
// then dispatch ci.yml on main to deploy
//
// Environment: API (github.api_url), REPO (owner/name), TOKEN (the job token); `open` also
// NEW (the content commit) and AUTO ("true" when only .md/.json changed); `merge` also SHA
// (the commit CI built), BUILD (needs.build.result) and RUN_URL (the run, for the status).
//
// Why the dispatches: Gitea, like GitHub, starts no workflow for what the job token does —
// neither for the PR it opens nor for the merge commit it pushes to main.
import { pathToFileURL } from "node:url";
export const BRANCH = "content/bump";
export const BASE = "main";
export const MARK_AUTO = "<!-- publish: auto -->";
export const MARK_REVIEW = "<!-- publish: review -->";
const REVIEW_NOTE =
"This publish touches files other than .md/.json (MDX runs code at build time), so it waits for a review instead of merging itself.";
/** The PR body; its last line is the marker the admin and the merge step read. */
export function prBody(contentCommit, auto) {
return [
`Bumps \`src/content\` to poli0981/content@${contentCommit}.`,
"Opened by the admin's **Publish** (`.gitea/workflows/content-bump.yml`).",
"",
auto
? "Only Markdown/JSON changed: CI merges this PR once `build` passes, then deploys main."
: REVIEW_NOTE,
"",
auto ? MARK_AUTO : MARK_REVIEW,
].join("\n");
}
export const isAuto = (body) => typeof body === "string" && body.includes(MARK_AUTO);
/** A small client for Gitea's REST API with the job token. */
export function gitea({ api, repo, token, fetch = globalThis.fetch }) {
return async function call(method, path, body) {
const res = await fetch(`${api}/repos/${repo}${path}`, {
method,
headers: {
authorization: `token ${token}`,
accept: "application/json",
...(body === undefined ? {} : { "content-type": "application/json" }),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await res.text();
if (!res.ok) {
const error = new Error(`${method} ${path} → ${res.status} ${text.slice(0, 300)}`);
error.status = res.status;
throw error;
}
return text ? JSON.parse(text) : null;
};
}
/** The open content/bump → main PR, or null. */
export async function findPull(call) {
const pulls = await call("GET", "/pulls?state=open&limit=50");
return pulls.find((p) => p.head?.ref === BRANCH && p.base?.ref === BASE) ?? null;
}
export async function open({ call, contentCommit, auto, log = console.log }) {
const body = prBody(contentCommit, auto);
let pull = await findPull(call);
const wasAuto = pull ? isAuto(pull.body) : true;
if (pull) {
await call("PATCH", `/pulls/${pull.number}`, { body });
log(`Updated PR #${pull.number}.`);
} else {
pull = await call("POST", "/pulls", {
base: BASE,
head: BRANCH,
title: "chore(content): publish from admin",
body,
});
log(`Opened PR #${pull.number}.`);
}
// Say it once, when the PR turns from "merges itself" to "waits for a review".
if (!auto && wasAuto) {
await call("POST", `/issues/${pull.number}/comments`, { body: REVIEW_NOTE });
}
await call("POST", "/actions/workflows/ci.yml/dispatches", { ref: BRANCH });
log(`Dispatched ci.yml on ${BRANCH}.`);
return pull.number;
}
/**
* The status main's branch protection requires (`CI / build (*)`). Gitea 28.4 writes commit
* statuses for push and pull_request runs only, never for a dispatched one, so the run CI
* makes on content/bump leaves the bump commit without it and every merge is refused (405,
* "Not all required status checks successful" — the first publish on 2026-11-24). The
* publish job runs after `build` in the same run and records its result here instead.
*/
export const BUILD_CONTEXT = "CI / build (workflow_dispatch)";
/**
* @param {{
* call: (method: string, path: string, body?: unknown) => Promise<any>,
* sha: string,
* build?: string,
* runUrl?: string,
* log?: (message: string) => void,
* }} options
*/
export async function merge({ call, sha, build = "success", runUrl, log = console.log }) {
if (build !== "success" && build !== "failure") {
log(`build ${build}: nothing to record or merge.`);
return "skipped";
}
await call("POST", `/statuses/${sha}`, {
state: build,
context: BUILD_CONTEXT,
description:
build === "success" ? "build passed in this dispatched run" : "build failed — see the run",
...(runUrl ? { target_url: runUrl } : {}),
});
log(`Recorded ${BUILD_CONTEXT}: ${build} on ${sha}.`);
if (build === "failure") return "failed";
const pull = await findPull(call);
if (!pull) {
log(`No open PR from ${BRANCH}: nothing to merge.`);
return "none";
}
if (pull.head?.sha !== sha) {
log(`PR #${pull.number} has moved on to ${pull.head?.sha}; its own CI run merges it.`);
return "moved";
}
if (!isAuto(pull.body)) {
log(`PR #${pull.number} touches more than .md/.json: it waits for a review.`);
return "review";
}
try {
await call("POST", `/pulls/${pull.number}/merge`, {
Do: "squash",
MergeTitleField: `${pull.title} (#${pull.number})`,
head_commit_id: sha,
delete_branch_after_merge: true,
});
} catch (error) {
// Leave a trail on the PR: the admin shows it as waiting, and a merge by hand still
// deploys (a user's push starts CI on main).
await call("POST", `/issues/${pull.number}/comments`, {
body: `CI could not merge this publish: ${error.message}\n\nMerge it by hand; the push to main deploys it.`,
}).catch(() => {});
throw error;
}
log(`Merged PR #${pull.number}.`);
await call("POST", "/actions/workflows/ci.yml/dispatches", { ref: BASE });
log(`Dispatched ci.yml on ${BASE} (deploy).`);
return "merged";
}
async function main(command) {
const { API, REPO, TOKEN } = process.env;
if (!API || !REPO || !TOKEN) throw new Error("API, REPO and TOKEN must be set");
const call = gitea({ api: API, repo: REPO, token: TOKEN });
if (command === "open") {
const { NEW, AUTO } = process.env;
if (!NEW) throw new Error("NEW must be set");
await open({ call, contentCommit: NEW, auto: AUTO === "true" });
} else if (command === "merge") {
const { SHA, BUILD, RUN_URL } = process.env;
if (!SHA) throw new Error("SHA must be set");
await merge({ call, sha: SHA, build: BUILD || "success", runUrl: RUN_URL || undefined });
} else {
throw new Error(`unknown command ${command ?? "(none)"}: use open or merge`);
}
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
main(process.argv[2]).catch((error) => {
console.error(`::error::${error.message}`);
process.exit(1);
});
}
+35 -39
View File
@@ -11,46 +11,41 @@
* `license-checker`. Same source of truth, one less dependency to vet — which is the
* point of the exercise.
*
* Any license outside ALLOWED 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 cases go in REVIEWED with a reason.
* 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 -->";
// docs 12: the licenses that need no discussion.
const ALLOWED = new Set([
"MIT",
"Apache-2.0",
"ISC",
"BSD-2-Clause",
"BSD-3-Clause",
"OFL-1.1",
"0BSD",
"Unlicense",
"CC0-1.0",
"MIT OR Apache-2.0",
"(MIT OR Apache-2.0)",
"Apache-2.0 WITH LLVM-exception",
"BlueOak-1.0.0",
"Python-2.0",
]);
/** Whether a license expression passes without review; an unparseable one never does. */
function allowedOutright(license) {
try {
return satisfies(license, ALLOWED);
} catch {
return false;
}
}
// Licenses cleared by hand. A reason is required — "we shipped it anyway" is not one.
const REVIEWED = new Map([
[
"MPL-2.0",
"File-level copyleft. satori and @resvg/resvg-js are used unmodified as build-time " +
"tools and never shipped to the browser, so no source-disclosure obligation is triggered.",
],
]);
/** 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`;
@@ -98,7 +93,7 @@ for (const { name } of direct) {
}
const flagged = [...byLicense.entries()]
.filter(([lic]) => !ALLOWED.has(lic))
.filter(([lic]) => !allowedOutright(lic))
.sort((a, b) => a[0].localeCompare(b[0]));
// ---------------------------------------------------------------- render
@@ -142,10 +137,11 @@ const lines = [
if (flagged.length > 0) {
lines.push("## Licenses outside the standard allowlist", "");
for (const [lic, list] of flagged) {
const note = REVIEWED.get(lic);
lines.push(`**${lic}** — ${list.length} package(s): ${list.map((n) => `\`${n}\``).join(", ")}`);
lines.push("");
lines.push(note ? `> Reviewed: ${note}` : `> ⚠️ NOT YET REVIEWED.`);
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("");
}
}
@@ -175,7 +171,9 @@ if (start === -1 || stop === -1) {
}
const next = current.slice(0, start) + generated + current.slice(stop + END.length);
const unreviewed = flagged.filter(([lic]) => !REVIEWED.has(lic));
const unreviewed = flagged.flatMap(([lic, list]) =>
list.filter((name) => !clearedByReview(name, lic)).map((name) => `${name} (${lic})`),
);
if (process.argv.includes("--check")) {
if (next !== current) {
@@ -187,8 +185,8 @@ if (process.argv.includes("--check")) {
}
if (unreviewed.length > 0) {
console.error(
`Unreviewed license(s) in the dependency tree: ${unreviewed.map(([l]) => l).join(", ")}\n` +
`Review them and add an entry to REVIEWED in scripts/gen-notices.mjs.`,
`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);
}
@@ -197,8 +195,6 @@ if (process.argv.includes("--check")) {
writeFileSync(NOTICES, next);
console.log(`wrote ${NOTICES} — ${direct.length} direct, ${resolvedCount} resolved packages`);
if (unreviewed.length > 0) {
console.log(
` note: ${unreviewed.length} license(s) need review: ${unreviewed.map(([l]) => l).join(", ")}`,
);
console.log(` note: ${unreviewed.length} package(s) need review: ${unreviewed.join(", ")}`);
}
}
+13 -4
View File
@@ -12,6 +12,9 @@ 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");
@@ -69,7 +72,7 @@ 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:${mix(C.horror, C.bg, 0.18)}; color:${C.horror}; 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(`
@@ -141,10 +144,16 @@ for (const { dir, section, titleKey } of SECTIONS) {
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++;
+122
View File
@@ -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;
}
+53
View File
@@ -0,0 +1,53 @@
// Spam a URL from this machine and report who answered 429: the Worker's site-wide limit
// (RL_SITE — the site's own 429 page, Retry-After: 10) or the zone WAF rate-limiting rule
// (Cloudflare's "Error 1015" page, before the Worker runs). Docs 06 §2 and 07 §6.
//
// npm run probe:ratelimit -- [url] [requests] [parallel]
// defaults: https://poli0981.dev/legal/privacy/ 300 20
//
// The default page skips the Turnstile gate, so a 200 is the real page. Every request spends
// this address's budget: expect 429s from the site for the next ~10 seconds.
const url = process.argv[2] ?? "https://poli0981.dev/legal/privacy/";
const total = Number(process.argv[3] ?? 300);
const parallel = Number(process.argv[4] ?? 20);
/** "worker 429" | "waf 429" | the status code as text. */
async function probe() {
const response = await fetch(url, {
redirect: "manual",
headers: { "user-agent": "poli0981-ratelimit-probe" },
signal: AbortSignal.timeout(15000),
});
const body = await response.text();
if (response.status !== 429) return String(response.status);
// The site's 429 page carries the countdown span; the WAF's block page never does.
return body.includes('id="cd"') ? "worker 429" : "waf 429";
}
const results = [];
const firstAt = {};
const started = Date.now();
let next = 0;
await Promise.all(
Array.from({ length: parallel }, async () => {
while (next < total) {
const index = next++;
const kind = await probe().catch((error) => `error (${error.name})`);
results.push(kind);
firstAt[kind] = Math.min(firstAt[kind] ?? Infinity, index + 1);
}
}),
);
const seconds = ((Date.now() - started) / 1000).toFixed(1);
console.log(`${total} requests to ${url} in ${seconds}s (${parallel} in parallel)`);
const counts = Object.groupBy(results, (kind) => kind);
for (const [kind, hits] of Object.entries(counts)) {
console.log(
` ${kind.padEnd(12)} ${String(hits.length).padStart(5)} first at #${firstAt[kind]}`,
);
}
if (!counts["worker 429"] && !counts["waf 429"]) {
console.log("no 429 at all — the limits were not reached (more requests or more parallel?)");
}
+49 -12
View File
@@ -8,7 +8,8 @@
// with Cloudflare's always-pass test secret, so the whole flow — gate page, exemptions,
// /api/gate → pass cookie → real page — is exercised end to end (siteverify is a real
// network call; the test secret accepts any token). Phase 3 lists the client's address in
// the KV denylist and expects 403s everywhere, pages included.
// the KV denylist and expects 403s everywhere, pages included. Phase 4 spams a page until the
// site-wide rate limit answers with the 429 page.
//
// Usage: npm run build && npm run smoke (works on Linux, macOS and Windows)
import { execFileSync, spawn } from "node:child_process";
@@ -107,6 +108,11 @@ async function withWorker(port, vars, run) {
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++) {
@@ -115,11 +121,10 @@ async function withWorker(port, vars, run) {
() => sleep(1000).then(() => false),
);
}
if (!up) throw new Error(`wrangler dev did not come up on ${base}`);
await run(get, port);
if (up) await run(get, port);
else fail(new Error(`wrangler dev did not come up on ${base}`));
} catch (error) {
failures.push(String(error));
console.error(error, `\n${log.slice(-4000)}`);
fail(error);
} finally {
stop(server);
}
@@ -178,18 +183,27 @@ await withWorker(8788, {}, async (get, port) => {
expect("/blog/ → 200", (await get("/blog/")).status === 200);
expect("/en/ → 200", (await get("/en/")).status === 200);
expect("unknown page → 404", (await get("/definitely-not-a-page/")).status === 404);
for (const [path, lang] of [
["/definitely-not-a-page/", "vi"],
["/en/definitely-not-a-page/", "en"],
]) {
const missing = await get(path);
const body = await missing.text();
expect(
`${path} → 404 page in ${lang}`,
missing.status === 404 && body.includes(`<html lang="${lang}"`),
`got ${missing.status}`,
);
}
const health = await get("/api/health");
const healthBody = health.status === 200 ? await health.json() : {};
expect("/api/health → 200 json", healthBody.ok === true);
expect("/api/health reports the version", "version" in healthBody);
expect("/sw.js → 200", (await get("/sw.js")).status === 200);
const asset = /\/_astro\/[^"']+\.css/.exec(html)?.[0];
expect(
"hashed CSS asset → 200",
asset ? (await get(asset)).status === 200 : false,
`asset=${asset}`,
);
// CSS is inline (astro.config.mjs `inlineStylesheets`); scripts and fonts stay hashed files.
const asset = /\/_astro\/[^"']+\.(?:js|woff2)/.exec(html)?.[0];
expect("hashed asset → 200", asset ? (await get(asset)).status === 200 : false, `asset=${asset}`);
expect("/rss.xml → 200", (await get("/rss.xml")).status === 200);
expect(
"/.well-known/security.txt → 200",
@@ -262,8 +276,12 @@ await withWorker(8788, {}, async (get, port) => {
"/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": "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6ImFAYi5jIn0.c2ln" },
headers: { "cf-access-jwt-assertion": forgedJwt },
});
expect("/api/admin with a forged JWT → 403", forged.status === 403);
});
@@ -375,6 +393,25 @@ try {
rmSync(tmp, { recursive: true, force: true });
}
console.log("— phase 4: spam until the site-wide rate limit answers");
// Last of all: the simulated counters outlive a `wrangler dev` restart, so a spent budget
// would turn the next phase into 429s. RL_SITE allows 100 per 10 s; keep going until a 429
// arrives — a burst can straddle two windows.
await withWorker(8791, {}, async (get) => {
let limited = null;
for (let i = 0; i < 400 && !limited; i++) {
const response = await get("/legal/privacy/");
if (response.status === 429) limited = response;
else await response.body?.cancel();
}
const html = limited ? await limited.text() : "";
expect("spam → 429 from the site-wide limit", limited !== null);
expect("429 sends Retry-After: 10", limited?.headers.get("retry-after") === "10");
expect("429 is no-store", limited?.headers.get("cache-control") === "no-store");
expect("429 has nosniff", limited?.headers.get("x-content-type-options") === "nosniff");
expect("429 countdown starts at 10", html.includes('<span id="cd">10</span>'));
});
if (failures.length) {
console.error(`\nsmoke test failed (${failures.length}): ${failures.join(", ")}`);
process.exit(1);
-35
View File
@@ -1,35 +0,0 @@
# 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.0.0
sonar.sourceEncoding=UTF-8
# .github is analyzed too: the workflow rules (pinned actions, no npx/install scripts) are
# part of the supply-chain posture, not noise to exclude.
sonar.sources=src,workers/widgets/src,scripts,public,.github
sonar.tests=tests
sonar.test.inclusions=tests/**/*.test.ts
# 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
+254
View File
@@ -0,0 +1,254 @@
---
import { useTranslations } from "../i18n";
import { homePath, type Locale } from "../i18n/routing";
import { withAge } from "../lib/age-gate";
import { minAge, type AgeRating } from "../lib/content-labels";
interface Props {
rating: AgeRating;
locale: Locale;
}
// Folds an age-rated text away until the reader confirms their age (src/lib/age-gate.ts).
// - In the HTML the text is a closed <details>: the safe state needs no script, and without
// JavaScript opening it is the confirmation (privacy policy §8: core content works with
// JavaScript off).
// - With JavaScript, the summary asks first, in a native modal <dialog> (focus stays inside,
// Esc cancels — it never means "yes"); the answer is kept in this browser's localStorage.
// - It never pops up on its own: the page around it (title, banner, navigation) stays usable.
// Search indexes the page's title, not anything inside the gate.
const { rating, locale } = Astro.props;
const t = useTranslations(locale);
const age = minAge(rating) ?? 18;
---
<!-- Search indexes none of it: not the text, and not the status lines either — they would
become the search excerpt of a page the reader has not been allowed into. -->
<div class="age-gate" data-min-age={age} data-pagefind-ignore>
<!-- The answer's state sits above the text, where the reader is, not after a long chapter. -->
<p class="age-status" data-state="allow" hidden>
<span>{withAge(t.cw.confirmed, age)}</span>
<button type="button" class="age-reset">{t.cw.reset}</button>
</p>
<p class="age-status" data-state="deny" hidden>
<span>{withAge(t.cw.denied, age)}</span>
<a href={homePath(locale)}>{t.cw.home}</a>
<button type="button" class="age-retry">{t.cw.retry}</button>
</p>
<details class="age-fold">
<summary class="age-summary">
<span class="age-badge">{rating}</span>
<span>{withAge(t.cw.gate, age)}</span>
<!-- "Select to confirm and read": true until the reader has answered yes. -->
<span class="age-hint">{t.cw.gateHint}</span>
</summary>
<div class="age-body" data-pagefind-ignore>
<slot />
</div>
</details>
<dialog class="age-dialog" aria-labelledby="age-question" aria-describedby="age-explain">
<form method="dialog">
<h2 id="age-question">{withAge(t.cw.question, age)}</h2>
<p id="age-explain">{withAge(t.cw.explain, age)}</p>
<div class="age-actions">
<button type="submit" value="yes" class="age-yes">{withAge(t.cw.yes, age)}</button>
<!-- Focus starts here: pressing Enter by habit must not mean "yes". -->
<button type="submit" value="no" class="age-no" autofocus>{t.cw.no}</button>
</div>
</form>
</dialog>
</div>
<script>
import { answer, decide, readAnswer, resetAnswer, saveAnswer } from "../lib/age-gate";
// localStorage can throw on access (blocked storage); the answer then lives for this page.
let store: Storage | null = null;
try {
store = window.localStorage;
} catch {
store = null;
}
let current = readAnswer(store);
for (const gate of document.querySelectorAll<HTMLElement>(".age-gate")) {
const age = Number(gate.dataset.minAge);
const fold = gate.querySelector<HTMLDetailsElement>(".age-fold");
const summary = fold?.querySelector("summary");
const dialog = gate.querySelector<HTMLDialogElement>(".age-dialog");
const allowRow = gate.querySelector<HTMLElement>('[data-state="allow"]');
const denyRow = gate.querySelector<HTMLElement>('[data-state="deny"]');
if (!fold || !summary || !dialog || !allowRow || !denyRow || !age) continue;
const render = () => {
const decision = decide(current, age);
gate.dataset.decision = decision;
fold.open = decision === "allow";
fold.hidden = decision === "deny";
allowRow.hidden = decision !== "allow";
denyRow.hidden = decision !== "deny";
};
summary.addEventListener("click", (event) => {
if (decide(current, age) === "allow") return; // an ordinary fold from here on
event.preventDefault();
dialog.returnValue = "";
dialog.showModal();
});
// The browser also opens a <details> by itself — find-in-page, a #:~:text= link from a
// search engine, an #id inside the text. Without a "yes" on record, fold it straight back.
fold.addEventListener("toggle", () => {
if (fold.open && decide(current, age) !== "allow") fold.open = false;
});
dialog.addEventListener("close", () => {
const choice = dialog.returnValue; // "yes", "no", or "" when cancelled with Esc
if (choice !== "yes" && choice !== "no") return;
current = answer(current, age, choice === "yes");
saveAnswer(store, current);
render();
// "Yes": the summary, right above the text — the dialog may have handed focus back to
// "Chọn lại", which render() just hid. "No": the summary is hidden now, so focus goes to
// the row that explains why and offers to choose again.
if (choice === "yes") summary.focus();
else denyRow.querySelector("button")?.focus();
});
denyRow.querySelector(".age-retry")?.addEventListener("click", () => {
dialog.returnValue = "";
dialog.showModal();
});
allowRow.querySelector(".age-reset")?.addEventListener("click", () => {
resetAnswer(store);
current = readAnswer(null);
render();
summary.focus();
});
render();
}
</script>
<style>
.age-gate {
display: grid;
gap: 0.75rem;
}
.age-fold {
border: 1px solid color-mix(in srgb, var(--horror) 55%, var(--line));
border-radius: var(--radius-card);
}
.age-fold[open] {
border-color: var(--line);
}
.age-summary {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 0.75rem;
min-block-size: 2.75rem;
padding: 0.9rem 1.1rem;
cursor: pointer;
list-style: none;
color: var(--text);
}
.age-summary::-webkit-details-marker {
display: none;
}
.age-fold[open] > .age-summary {
border-block-end: 1px solid var(--line);
}
.age-hint {
color: var(--muted);
}
.age-gate[data-decision="allow"] .age-hint {
display: none;
}
.age-badge {
padding: 0.1em 0.55em;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--horror) 45%, transparent);
background: color-mix(in srgb, var(--horror) 18%, transparent);
font-family: var(--ff-mono);
font-size: var(--text-meta);
font-weight: 600;
}
.age-body {
padding: 1.1rem;
}
.age-status[hidden],
.age-fold[hidden] {
display: none;
}
.age-status {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
margin: 0;
color: var(--muted);
font-size: var(--text-meta);
}
.age-status a {
color: var(--accent);
}
.age-dialog {
max-inline-size: min(30rem, calc(100vw - 2rem));
padding: 1.4rem 1.5rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-modal);
background: var(--surface);
color: var(--text);
box-shadow: var(--shadow-elevated);
}
.age-dialog::backdrop {
background: var(--overlay, rgb(2 6 23 / 0.66));
}
.age-dialog h2 {
margin: 0 0 0.6rem;
font-size: var(--text-lead);
}
.age-dialog p {
margin: 0 0 1.2rem;
color: var(--muted);
}
.age-actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
}
.age-actions button {
min-block-size: 2.75rem;
padding: 0.5rem 1rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-control);
background: var(--elevated);
color: var(--text);
cursor: pointer;
}
.age-actions .age-yes {
border-color: var(--accent);
background: var(--accent);
color: var(--accent-contrast);
}
.age-status button {
min-block-size: 2.75rem;
padding: 0.25rem 0.75rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-control);
background: transparent;
color: var(--text);
cursor: pointer;
}
@media (forced-colors: active) {
.age-fold,
.age-badge,
.age-dialog {
border-color: CanvasText;
}
}
</style>
+3 -2
View File
@@ -4,8 +4,9 @@
// connect-src. `type="module"` works: the CDN answers CORS with `*`, and the beacon falls
// back to `querySelector("script[data-cf-beacon]")` when `document.currentScript` is null.
//
// Rendered only for production builds made by Workers Builds on main (see PUBLIC_CF_BEACON
// in astro.config.mjs) so CI, Lighthouse and branch previews never add page views.
// Rendered only for production builds — the deploy job in .gitea/workflows/ci.yml sets
// PUBLIC_CF_BEACON=true (astro.config.mjs) — so CI, Lighthouse and local builds never add
// page views.
import { PUBLIC_CF_BEACON } from "astro:env/client";
const CF_BEACON_TOKEN = "349c7ecb1c304ff8985c878004df42b3"; // public site tag, not a secret
+119
View File
@@ -0,0 +1,119 @@
---
import { useTranslations } from "../i18n";
import type { Locale } from "../i18n/routing";
import { labelNames, needsBlur, type AgeRating } from "../lib/content-labels";
interface Props {
/** The item's content labels (src/lib/content-labels.ts). */
labels: readonly string[];
ageRating?: AgeRating | undefined;
locale: Locale;
}
// The banner at the top of a labelled post, chapter or album. When a label blurs images, the
// region this sits in must carry `data-cw-blur` (global.css): every image in it stays blurred
// until "Hiện ảnh" is ticked. That is a real checkbox read by CSS `:has()`, so it works with
// JavaScript off and nothing sharp shows before a script runs. Search skips the banner.
const { labels, ageRating, locale } = Astro.props;
const t = useTranslations(locale);
const names = labelNames(labels, t.labels);
const blur = needsBlur(labels);
---
{
(names.length > 0 || ageRating) && (
<div class="cw-notice" role="note" aria-labelledby="cw-title" data-pagefind-ignore>
<p class="cw-head">
<span class="cw-icon" aria-hidden="true">
⚠
</span>
<strong id="cw-title">{t.cw.title}</strong>
</p>
<ul class="cw-tags" role="list">
{names.map((name) => (
<li class="cw-tag">{name}</li>
))}
{ageRating && <li class="cw-tag cw-age">{ageRating}</li>}
</ul>
{blur && (
<p class="cw-blur-row">
<span>{t.cw.blurNote}</span>
<label class="cw-reveal">
<input type="checkbox" class="cw-reveal-input" />
{t.cw.reveal}
</label>
</p>
)}
</div>
)
}
<style>
.cw-notice {
display: grid;
gap: 0.6rem;
margin-block: 0 1.75rem;
padding: 0.9rem 1.1rem;
border: 1px solid color-mix(in srgb, var(--horror) 55%, var(--line));
border-radius: var(--radius-card);
background: color-mix(in srgb, var(--horror) 10%, var(--surface));
color: var(--text);
}
.cw-head {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0;
}
.cw-icon {
color: var(--horror);
font-size: 1.1em;
}
.cw-tags {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin: 0;
padding: 0;
list-style: none;
}
.cw-tag {
padding: 0.1em 0.55em;
border-radius: 999px;
border: 1px solid color-mix(in srgb, var(--horror) 45%, transparent);
background: color-mix(in srgb, var(--horror) 18%, transparent);
font-family: var(--ff-mono);
font-size: var(--text-meta);
}
.cw-age {
font-weight: 600;
}
.cw-blur-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 1rem;
margin: 0;
color: var(--muted);
font-size: var(--text-meta);
}
.cw-reveal {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-block-size: 2.75rem; /* WCAG 2.5.8: a comfortable target, not just the box */
color: var(--text);
cursor: pointer;
}
.cw-reveal-input {
inline-size: 1.1rem;
block-size: 1.1rem;
accent-color: var(--accent);
}
@media (forced-colors: active) {
.cw-notice,
.cw-tag {
border-color: CanvasText;
}
}
</style>
-81
View File
@@ -1,81 +0,0 @@
---
interface Props {
warnings: string[];
title?: string;
hint?: string;
}
// JS-free reveal via native <details> — keyboard-accessible and CSP-clean.
const { warnings, title = "Cảnh báo nội dung", hint = "Bấm để đọc" } = Astro.props;
---
<details class="cw">
<summary class="cw-summary">
<span class="cw-icon" aria-hidden="true">⚠</span>
<span class="cw-title">{title}</span>
{
warnings.length > 0 && (
<span class="cw-tags">
{warnings.map((w) => (
<span class="cw-tag">{w}</span>
))}
</span>
)
}
<span class="cw-hint">{hint}</span>
</summary>
<div class="cw-body">
<slot />
</div>
</details>
<style>
.cw {
border: 1px solid color-mix(in srgb, var(--horror) 55%, var(--line));
border-radius: var(--radius-card);
background: color-mix(in srgb, var(--horror) 10%, var(--surface));
}
.cw-summary {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem 0.75rem;
padding: 0.9rem 1.1rem;
cursor: pointer;
list-style: none;
color: var(--text);
}
.cw-summary::-webkit-details-marker {
display: none;
}
.cw-icon {
color: var(--horror);
font-size: 1.1em;
}
.cw-title {
font-weight: 600;
}
.cw-tags {
display: inline-flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.cw-tag {
padding: 0.1em 0.5em;
border-radius: 999px;
background: color-mix(in srgb, var(--horror) 30%, transparent);
color: color-mix(in srgb, var(--horror) 30%, var(--text));
font-family: var(--ff-mono);
font-size: var(--text-meta);
}
.cw-hint {
margin-inline-start: auto;
color: var(--muted);
font-size: var(--text-meta);
}
.cw[open] .cw-hint {
display: none;
}
.cw-body {
padding: 0 1.1rem 1.1rem;
}
</style>
+9 -2
View File
@@ -117,15 +117,22 @@ function relFor(href: string, me?: boolean): string | undefined {
.footer-legal a:hover {
color: var(--accent);
}
/* Each icon is 18px but its link is a 44px square (docs 03 §8; WCAG 2.5.8 asks for 24).
The negative margins take back the padding that adds, so the first icon still lines up
with the text above and the row keeps its height. */
.footer-social {
display: flex;
flex-wrap: wrap;
gap: 0.85rem;
align-items: center;
margin-block: 0.25rem;
margin-block: -0.5rem;
margin-inline-start: -0.8125rem;
}
.footer-social a {
display: inline-flex;
align-items: center;
justify-content: center;
min-inline-size: 2.75rem;
min-block-size: 2.75rem;
color: var(--muted);
transition: color var(--duration-fast) var(--ease-site);
}
+38 -5
View File
@@ -1,23 +1,36 @@
---
import { Image } from "astro:assets";
import MediaImage from "./MediaImage.astro";
import { type GalleryEntry } from "../lib/collections";
import { albumWarning, type GalleryEntry } from "../lib/collections";
import type { GalleryPhoto } from "../lib/gallery";
import { sectionPath, type Locale } from "../i18n/routing";
import { useTranslations } from "../i18n";
import { labelNames, needsBlur } from "../lib/content-labels";
interface Props {
entry: GalleryEntry;
cover: GalleryPhoto;
locale: Locale;
/** Heading level of the card title: 3 under a section heading, 2 right under the
page's h1 (an index page) — heading levels must not skip. */
headingLevel?: 2 | 3;
}
const { entry, cover, locale } = Astro.props;
const { entry, cover, locale, headingLevel = 3 } = Astro.props;
const Title = `h${headingLevel}` as const;
const href = sectionPath("gallery", locale, entry.data.album);
const year = entry.data.date.getFullYear();
// The cover stays blurred when the album (in either language) or that photo carries a label
// that blurs images, or when the album is age-rated; the card says why.
const t = useTranslations(locale);
const { labels: albumLabels, ageRating } = await albumWarning(entry.data.album);
const labels = [...new Set([...albumLabels, ...cover.labels])];
const blurCover = needsBlur(labels) || Boolean(ageRating);
const warning = [...labelNames(labels, t.labels), ...(ageRating ? [ageRating] : [])].join(" · ");
---
<article class="card">
<a class="card-link" href={href}>
<div class="cover">
<div class="cover" data-cw-blur={blurCover ? "" : undefined}>
{
cover.kind === "local" ? (
<Image
@@ -34,8 +47,17 @@ const year = entry.data.date.getFullYear();
}
</div>
<div class="body">
<h3 class="title">{entry.data.title}</h3>
<Title class="title">{entry.data.title}</Title>
<span class="year">{year}</span>
{
warning && (
<span class="cw">
<span aria-hidden="true">⚠</span>
<span class="sr-only">{t.cw.title}:</span>
{warning}
</span>
)
}
</div>
</a>
</article>
@@ -66,11 +88,22 @@ const year = entry.data.date.getFullYear();
}
.body {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.75rem;
gap: 0.25rem 0.75rem;
padding: 0.9rem 1.1rem 1rem;
}
/* Its own line under the title; the gap stands in for the whitespace the build strips. */
.cw {
display: inline-flex;
flex-wrap: wrap;
gap: 0.35em;
flex-basis: 100%;
color: color-mix(in srgb, var(--horror) 35%, var(--text));
font-family: var(--ff-mono);
font-size: var(--text-meta);
}
.title {
font-size: var(--text-lead);
font-weight: 700;
+99
View File
@@ -0,0 +1,99 @@
---
import { Image } from "astro:assets";
import MediaImage from "./MediaImage.astro";
import type { GalleryPhoto } from "../lib/gallery";
import type { Locale } from "../i18n/routing";
interface Props {
photos: GalleryPhoto[];
/** The lightbox slide (full-size image) each thumbnail links to. */
hrefs: string[];
/** Per photo: blurred on its own (a label of its own, in an album that isn't blurred). */
blurred: boolean[];
/** Per photo: the accessible name — "open", the caption, and any warning. */
labels: string[];
locale: Locale;
}
// The album's thumbnails. Each links to its full-size image, so the album works without JS;
// the lightbox island takes over plain clicks once it hydrates.
const { photos, hrefs, blurred, labels } = Astro.props;
---
<div class="photo-grid">
{
photos.map((p, i) => (
<a
class:list={["thumb", { "cw-photo": blurred[i] }]}
href={hrefs[i]}
data-lightbox-index={i}
aria-label={labels[i]}
>
{p.kind === "local" ? (
<Image
src={p.image}
alt=""
widths={[400, 800]}
sizes="(max-width: 640px) 50vw, 320px"
loading={i === 0 ? "eager" : "lazy"}
decoding="async"
{...(i === 0 ? { fetchpriority: "high" as const } : {})}
/>
) : (
<MediaImage
media={p.media}
alt=""
sizes="(max-width: 640px) 50vw, 320px"
loading={i === 0 ? "eager" : "lazy"}
{...(i === 0 ? { fetchpriority: "high" as const } : {})}
/>
)}
</a>
))
}
</div>
<style>
.photo-grid {
margin-block-start: 1.5rem;
display: grid;
gap: 0.75rem;
/* minmax(0, 1fr), not 1fr: a `1fr` column is at least as wide as its photos' minimum
content size, which made the first column 235px wide and the page wider than a
320px screen. With a zero minimum the columns stay equal. */
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 640px) {
.photo-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (min-width: 960px) {
.photo-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
.thumb {
display: block;
padding: 0;
border: 1px solid var(--line);
border-radius: var(--radius-card);
background: var(--surface);
overflow: clip;
cursor: pointer;
aspect-ratio: 1 / 1;
transition:
transform var(--duration-fast) var(--ease-site),
border-color var(--duration-fast) var(--ease-site);
}
.thumb:hover {
transform: translateY(-2px);
border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
}
.thumb :global(img) {
display: block;
inline-size: 100%;
block-size: 100%;
object-fit: cover;
}
</style>
+26 -3
View File
@@ -62,7 +62,11 @@ const pathname = Astro.url.pathname;
></path>
</svg>
</button>
<ThemeToggle client:load labels={t.theme} />
{
/* idle, not load: CSS already shows the right icon from <html data-theme-pref>, so
the Svelte runtime need not compete with first paint for bandwidth. */
}
<ThemeToggle client:idle labels={t.theme} />
<LangSwitch href={langHref} />
<button
type="button"
@@ -89,8 +93,10 @@ const pathname = Astro.url.pathname;
position: sticky;
inset-block-start: 0;
z-index: 40;
background: color-mix(in srgb, var(--bg) 85%, transparent);
backdrop-filter: blur(8px);
/* Opaque and without backdrop-filter: Safari 26 extends a sticky header's background
up under the iPhone status bar, but gives up when the header has a backdrop-filter —
the page then scrolled into view above the header. */
background: var(--bg);
border-block-end: 1px solid var(--line);
}
.header-inner {
@@ -102,6 +108,10 @@ const pathname = Astro.url.pathname;
.brand {
display: inline-flex;
align-items: center;
/* As tall as the buttons beside it, and never narrower: once the wordmark is hidden
(below) the link would otherwise be the 32×12px mark alone. */
min-block-size: 2.5rem;
min-inline-size: 2.5rem;
gap: 0.5rem;
color: var(--text);
font-family: var(--ff-display);
@@ -113,6 +123,14 @@ const pathname = Astro.url.pathname;
block-size: 0.75rem;
color: var(--accent);
}
/* Down to a 320px viewport (WCAG 1.4.10 Reflow; also a desktop window at 400% zoom) the
header has no room for the wordmark: the mark alone stays, and the link keeps its
name through aria-label. */
@media (max-width: 21.99rem) {
.brand-text {
display: none;
}
}
.primary-nav {
display: none;
gap: 0.35rem;
@@ -132,8 +150,13 @@ const pathname = Astro.url.pathname;
color: var(--text);
background: var(--surface);
}
/* Colour is not the only cue for "you are here" (WCAG 1.4.1): the underline also
survives forced-colors mode, where the accent is replaced by the link colour. */
.primary-nav a[aria-current="page"] {
color: var(--accent);
text-decoration: underline;
text-decoration-thickness: 2px;
text-underline-offset: 0.45em;
}
.actions {
display: flex;
+34 -3
View File
@@ -13,6 +13,7 @@ const target: Locale = current === "vi" ? "en" : "vi";
const t = useTranslations(current);
const { href = alternatePath(Astro.url.pathname, target), label = t.lang.switchTo } = Astro.props;
const code = target.toUpperCase();
---
{
@@ -20,14 +21,24 @@ const { href = alternatePath(Astro.url.pathname, target), label = t.lang.switchT
voice control can act on what the user sees — WCAG 2.5.3 Label in Name (A).
`aria-label="Ngôn ngữ"` alone dropped it entirely. */
}
{
/* On a narrow phone the full name does not fit next to the brand and the three buttons
(the header needs 378px with "English", 400px with "Tiếng Việt"), and the page then
scrolled sideways. Below those widths the link shows the language code instead. The
accessible name carries both the name and the code as words of their own
("Tiếng Việt, VI — Language"), so it contains whichever of the two is on screen. axe
matches whole words and drops anything in parentheses: "VI" inside "Việt" does not
count, and neither would "(VI)". */
}
<a
class="lang-switch"
class:list={["lang-switch", `to-${target}`]}
{href}
hreflang={target}
lang={target}
aria-label={`${label} — ${t.lang.label}`}
aria-label={`${label}, ${code} — ${t.lang.label}`}
>
{label}
<span class="full">{label}</span>
<span class="short" aria-hidden="true">{code}</span>
</a>
<style>
@@ -52,4 +63,24 @@ const { href = alternatePath(Astro.url.pathname, target), label = t.lang.switchT
background: var(--surface);
border-color: var(--line);
}
.short {
display: none;
}
/* rem, so the switch-over moves with the reader's font size like the text it measures. */
@media (max-width: 23.99rem) {
.to-en .full {
display: none;
}
.to-en .short {
display: inline;
}
}
@media (max-width: 25.24rem) {
.to-vi .full {
display: none;
}
.to-vi .short {
display: inline;
}
}
</style>
+34 -3
View File
@@ -50,10 +50,38 @@
document.removeEventListener("keydown", onKey);
};
});
// The sheet does not take focus and sits at the end of the tab order, so someone tabbing
// through the page reaches controls that lie underneath it. Publish how much of the
// viewport's bottom it covers; the page's scroll padding (global.css) then keeps whatever
// receives focus above it (WCAG 2.4.11). The figure is the sheet's own height plus its
// gap to the bottom edge — laid-out sizes, so neither the slide-in transform nor how far
// the page is scrolled skews it. Set through CSSOM, never a style attribute (CSP).
$effect(() => {
if (!visible || !sheetEl) return;
const el = sheetEl;
const root = document.documentElement;
const sync = () => {
const gap = Number.parseFloat(getComputedStyle(el).bottom) || 0;
root.style.setProperty("--sheet-h", `${Math.round(el.offsetHeight + gap)}px`);
};
sync();
const observer = new ResizeObserver(sync);
observer.observe(el);
window.addEventListener("resize", sync);
return () => {
observer.disconnect();
window.removeEventListener("resize", sync);
root.style.removeProperty("--sheet-h");
};
});
</script>
{#if visible}
<aside bind:this={sheetEl} class="gate" role="note" aria-label={strings.label}>
<!-- A named complementary landmark (the <aside> itself): a screen-reader user can jump
to the notice from the landmark list instead of meeting it at the very end of the
page. role="note" is not a landmark and left the sheet outside every region. -->
<aside bind:this={sheetEl} class="gate" aria-label={strings.label}>
<div class="gate-body">
<p>{strings.line1}</p>
<p>{strings.line2}</p>
@@ -73,11 +101,14 @@
position: fixed;
z-index: 55;
inset-inline: 0;
inset-block-end: 0;
/* On a phone the sheet rests on top of the tab bar instead of covering it: the bar's
four controls stay visible and reachable while the notice is up (WCAG 2.4.11), and
the bar already pads for the home indicator. --bottom-bar-h is 0 from 768px up. */
inset-block-end: var(--bottom-bar-h, 0px);
/* Does NOT block scroll — no backdrop; only the card is interactive. */
max-block-size: 40vh;
overflow-y: auto;
padding: 1rem 1.15rem calc(1rem + env(safe-area-inset-bottom, 0));
padding: 1rem 1.15rem;
background: var(--elevated);
border-block-start: 1px solid var(--line);
box-shadow: var(--shadow-elevated);
+80 -6
View File
@@ -3,9 +3,12 @@
import { prefersReducedMotion } from "../lib/motion";
/**
* `blur`: the photo has a content label that blurs images (src/lib/content-labels.ts);
* `warning` names it. Such a slide opens blurred, behind a "show" button, unless the page's
* own "Hiện ảnh" box (ContentNotice) is ticked.
* @type {{
* slides: { src: string, srcset: string, width: number, height: number, alt: string }[],
* labels: { viewer: string, close: string, prev: string, next: string, counter: string }
* slides: { src: string, srcset: string, width: number, height: number, alt: string, blur?: boolean, warning?: string }[],
* labels: { viewer: string, close: string, prev: string, next: string, counter: string, reveal?: string }
* }}
*/
let { slides = [], labels } = $props();
@@ -15,8 +18,12 @@
let dialogEl = $state(null);
let trackEl = $state(null);
let opener = null; // element to restore focus to on close
/** @type {Record<number, boolean>} slides shown unblurred in this viewing */
let revealed = $state({});
let pageRevealed = $state(false);
const current = $derived(slides[index]);
const veiled = $derived(Boolean(current?.blur) && !pageRevealed && !revealed[index]);
const counter = $derived(
labels.counter.replace("{i}", String(index + 1)).replace("{n}", String(slides.length)),
);
@@ -25,6 +32,7 @@
if (i < 0 || i >= slides.length) return;
opener = document.activeElement;
index = i;
pageRevealed = document.querySelector(".cw-reveal-input:checked") !== null;
open = true;
await tick();
dialogEl?.querySelector(".close")?.focus();
@@ -149,7 +157,13 @@
aria-describedby="lb-caption"
>
<div class="bar">
<span class="count" aria-live="polite">{counter}</span>
<!-- Arrowing to another photo announces its position and its caption: focus stays on
the button, so nothing else would say which photo is now showing. -->
<span class="count" aria-live="polite">
{counter}<span class="sr-only">
— {current.alt}{veiled && current.warning ? ` — ${current.warning}` : ""}
</span>
</span>
<button type="button" class="close" onclick={close} aria-label={labels.close}>✕</button>
</div>
@@ -158,8 +172,10 @@
class="nav prev"
onclick={prev}
disabled={index === 0}
aria-label={labels.prev}>‹</button
aria-label={labels.prev}
>
‹
</button>
<div
class="track"
@@ -170,6 +186,7 @@
onpointercancel={onPointerUp}
>
<img
class:veiled
src={current.src}
srcset={current.srcset}
sizes="92vw"
@@ -178,6 +195,21 @@
alt={current.alt}
decoding="async"
/>
{#if veiled}
<div class="veil">
{#if current.warning}<p>{current.warning}</p>{/if}
<!-- The button goes away once used, so focus moves on to the close button. -->
<button
type="button"
onclick={() => {
revealed[index] = true;
keepFocus();
}}
>
{labels.reveal ?? "Show"}
</button>
</div>
{/if}
</div>
<button
@@ -185,10 +217,15 @@
class="nav next"
onclick={next}
disabled={index === slides.length - 1}
aria-label={labels.next}>›</button
aria-label={labels.next}
>
›
</button>
<p class="caption" id="lb-caption">{current.alt}</p>
<!-- The same words are the image's alt and the dialog's description (aria-describedby
still resolves a hidden node), so the visible copy is hidden from the reading order
rather than read a third time. -->
<p class="caption" id="lb-caption" aria-hidden="true">{current.alt}</p>
</div>
{/if}
@@ -268,6 +305,43 @@
block-size: auto;
object-fit: contain;
}
.track {
position: relative;
}
.track img.veiled {
filter: blur(1.5rem) saturate(0.6);
clip-path: inset(0);
}
.veil {
position: absolute;
inset: 0;
display: grid;
place-content: center;
justify-items: center;
gap: 0.75rem;
padding: 1rem;
text-align: center;
color: var(--text);
}
.veil p {
margin: 0;
padding: 0.35rem 0.75rem;
border-radius: var(--radius-control);
background: color-mix(in srgb, var(--bg) 80%, transparent);
font-size: var(--text-meta);
}
.veil button {
min-block-size: 2.75rem;
padding: 0.5rem 1.1rem;
border: 1px solid var(--line-strong);
border-radius: var(--radius-control);
background: var(--bg);
color: var(--text);
cursor: pointer;
}
.veil button:hover {
border-color: var(--accent);
}
.caption {
grid-column: 1 / -1;
grid-row: 3;
+4 -2
View File
@@ -112,8 +112,10 @@
</nav>
{#if legal.length}
<nav aria-labelledby="menu-sheet-legal">
<p id="menu-sheet-legal" class="group-title">{legalTitle}</p>
<!-- Named "Menu — Legal", not just "Legal": the footer's nav already has that name, and
two landmarks that sound the same cannot be told apart in a landmark list. -->
<nav aria-label={`${title} — ${legalTitle}`}>
<p class="group-title">{legalTitle}</p>
<ul class="links legal">
{#each legal as item (item.href)}
<li><a href={item.href} onclick={closeMenu}>{item.label}</a></li>
+24 -2
View File
@@ -89,8 +89,9 @@ const tabs = [
z-index: 40;
display: flex;
align-items: stretch;
background: color-mix(in srgb, var(--surface) 92%, transparent);
backdrop-filter: blur(10px);
/* Opaque, no backdrop-filter — same reason as the site header: Safari 26 only extends
a fixed bar's colour under its own toolbar when the bar has no backdrop-filter. */
background: var(--surface);
border-block-start: 1px solid var(--line);
padding-block-end: env(safe-area-inset-bottom, 0);
}
@@ -110,9 +111,30 @@ const tabs = [
font-weight: 500;
cursor: pointer;
}
/* The current tab gets a bar along its top edge as well as the accent colour, so colour
is not the only cue (WCAG 1.4.1). It is a pseudo-element, not a border or a filter:
the bar itself must stay a plain opaque strip for Safari 26 (see .tabbar above). */
.tab {
position: relative;
}
.tab[aria-current="page"] {
color: var(--accent);
}
.tab[aria-current="page"]::before {
content: "";
position: absolute;
inset-block-start: 0;
inset-inline: 22%;
block-size: 2px;
border-radius: 0 0 2px 2px;
background: currentColor;
}
/* Forced colours repaint backgrounds; a system colour written here is kept. */
@media (forced-colors: active) {
.tab[aria-current="page"]::before {
background: LinkText;
}
}
.tab-icon {
display: block;
}
+34 -3
View File
@@ -5,22 +5,34 @@ import { type BlogEntry, readingTime } from "../lib/collections";
import { sectionPath, type Locale } from "../i18n/routing";
import { useTranslations } from "../i18n";
import { formatDate, isoDate } from "../lib/format";
import { labelNames, needsBlur } from "../lib/content-labels";
interface Props {
entry: BlogEntry;
locale: Locale;
/** Heading level of the card title: 3 under a section heading, 2 right under the
page's h1 (an index page) — heading levels must not skip. */
headingLevel?: 2 | 3;
}
const { entry, locale } = Astro.props;
const { entry, locale, headingLevel = 3 } = Astro.props;
const Title = `h${headingLevel}` as const;
const t = useTranslations(locale);
const href = sectionPath("blog", locale, entry.id);
const mins = readingTime(entry.body);
// A labelled or age-rated post: its cover stays blurred here (no "show" box on a card — open
// the post), and the card names the labels and any age rating.
const blurCover = needsBlur(entry.data.contentWarning) || Boolean(entry.data.ageRating);
const warning = [
...labelNames(entry.data.contentWarning, t.labels),
...(entry.data.ageRating ? [entry.data.ageRating] : []),
].join(" · ");
---
<article class="card">
<a class="card-link" href={href}>
{
(entry.data.cover || entry.data.coverMedia) && (
<div class="card-cover">
<div class="card-cover" data-cw-blur={blurCover ? "" : undefined}>
{entry.data.cover ? (
<Image
src={entry.data.cover}
@@ -42,13 +54,22 @@ const mins = readingTime(entry.body);
)
}
<div class="card-body">
<h3 class="card-title">{entry.data.title}</h3>
<Title class="card-title">{entry.data.title}</Title>
<p class="card-desc">{entry.data.description}</p>
<div class="card-meta">
<time datetime={isoDate(entry.data.date)}>{formatDate(entry.data.date, locale)}</time>
<span class="dot" aria-hidden="true">·</span>
<span>{mins} {t.post.minRead}</span>
</div>
{
warning && (
<p class="card-cw">
<span aria-hidden="true">⚠</span>
<span class="sr-only">{t.cw.title}:</span>
{warning}
</p>
)
}
</div>
</a>
</article>
@@ -105,4 +126,14 @@ const mins = readingTime(entry.body);
font-family: var(--ff-mono);
font-size: var(--text-meta);
}
/* The build strips whitespace between the icon and the words: the gap spaces them. */
.card-cw {
display: flex;
flex-wrap: wrap;
gap: 0.35em;
margin-block-start: 0.5rem;
color: color-mix(in srgb, var(--horror) 35%, var(--text));
font-family: var(--ff-mono);
font-size: var(--text-meta);
}
</style>
+55
View File
@@ -0,0 +1,55 @@
---
import { Image } from "astro:assets";
import type { ImageMetadata } from "astro";
import MediaImage from "./MediaImage.astro";
import type { MediaRef } from "../lib/media";
interface Props {
/** A local cover (src/assets), or */
cover?: ImageMetadata | undefined;
/** an R2 upload; its alt text, when set in the admin, describes it (else decorative). */
coverMedia?: (MediaRef & { alt?: string }) | undefined;
}
// A post's cover image. Its own component so the post page can put it inside the age check
// when the post is age-rated, and outside it otherwise.
const { cover, coverMedia } = Astro.props;
---
{
(cover || coverMedia) && (
<div class="post-cover">
{cover ? (
<Image
src={cover}
alt=""
widths={[720, 1080, 1440]}
sizes="(max-width: 768px) 100vw, 720px"
fetchpriority="high"
/>
) : (
coverMedia && (
<MediaImage
media={coverMedia}
alt={coverMedia.alt ?? ""}
sizes="(max-width: 768px) 100vw, 720px"
loading="eager"
fetchpriority="high"
/>
)
)}
</div>
)
}
<style>
.post-cover {
margin-block-end: 2rem;
}
.post-cover :global(img) {
inline-size: 100%;
block-size: auto;
border-radius: var(--radius-card);
border: 1px solid var(--line);
}
</style>
+4 -2
View File
@@ -9,15 +9,17 @@ interface Props {
emptyText?: string;
emptyHref?: string;
emptyLabel?: string;
/** Passed to every PostCard; see there. */
headingLevel?: 2 | 3;
}
const { posts, locale, emptyText, emptyHref, emptyLabel } = Astro.props;
const { posts, locale, emptyText, emptyHref, emptyLabel, headingLevel } = Astro.props;
---
{
posts.length > 0 ? (
<div class="post-grid">
{posts.map((entry) => (
<PostCard {entry} {locale} />
<PostCard {entry} {locale} {headingLevel} />
))}
</div>
) : (
+6 -2
View File
@@ -6,8 +6,12 @@ import { useTranslations } from "../i18n";
interface Props {
entry: ProjectEntry;
locale: Locale;
/** Heading level of the card title: 3 under a section heading, 2 right under the
page's h1 (an index page) — heading levels must not skip. */
headingLevel?: 2 | 3;
}
const { entry, locale } = Astro.props;
const { entry, locale, headingLevel = 3 } = Astro.props;
const Title = `h${headingLevel}` as const;
const t = useTranslations(locale);
const href = sectionPath("projects", locale, entry.id);
const { name, tagline, stack, repo, url, featured, year } = entry.data;
@@ -16,7 +20,7 @@ const { name, tagline, stack, repo, url, featured, year } = entry.data;
<article class:list={["card project", { featured }]}>
<a class="card-link" href={href}>
<div class="head">
<h3 class="card-title">{name}</h3>
<Title class="card-title">{name}</Title>
<span class="year">{year}</span>
</div>
<p class="tagline">{tagline}</p>
+17
View File
@@ -12,3 +12,20 @@ const { class: className = "", reader = false } = Astro.props;
<div class:list={["prose", { "prose--reader": reader }, className]}>
<slot />
</div>
<script>
// A wide code block scrolls sideways. Chromium and Firefox let the keyboard reach any
// scroller, Safari does not — so a <pre> that overflows joins the tab order (and leaves
// it again once it fits, e.g. after a resize), where arrow keys scroll it (WCAG 2.1.1).
const blocks = document.querySelectorAll<HTMLElement>(".prose pre");
if (blocks.length > 0 && "ResizeObserver" in window) {
const observer = new ResizeObserver((entries) => {
for (const { target } of entries) {
if (!(target instanceof HTMLElement)) continue;
if (target.scrollWidth > target.clientWidth) target.tabIndex = 0;
else target.removeAttribute("tabindex");
}
});
blocks.forEach((pre) => observer.observe(pre));
}
</script>
+29 -3
View File
@@ -19,6 +19,7 @@
let barEl = $state(null);
let panelEl = $state(null);
let aaEl = $state(null);
function target() {
return document.getElementById("reader-root");
@@ -72,7 +73,12 @@
onScroll();
const onKey = (e) => {
if (e.key === "Escape" && open) open = false;
if (e.key !== "Escape" || !open) return;
// The panel is unmounted on close: if focus was inside it, hand it back to the "Aa"
// button rather than letting it fall to <body> (the next Tab would start at the top).
const hadFocus = panelEl?.contains(document.activeElement);
open = false;
if (hadFocus) aaEl?.focus();
};
const onDown = (e) => {
if (open && panelEl && !panelEl.contains(e.target)) open = false;
@@ -95,6 +101,7 @@
<div class="rc" bind:this={panelEl}>
<!-- The name starts with the visible "Aa" so voice control can target it (WCAG 2.5.3). -->
<button
bind:this={aaEl}
type="button"
class="aa"
onclick={() => (open = !open)}
@@ -115,8 +122,10 @@
type="button"
class:active={size === key}
aria-pressed={size === key}
onclick={() => setSize(key)}>{text}</button
onclick={() => setSize(key)}
>
{text}
</button>
{/each}
</div>
</div>
@@ -128,8 +137,10 @@
type="button"
class:active={theme === key}
aria-pressed={theme === key}
onclick={() => setTheme(key)}>{text}</button
onclick={() => setTheme(key)}
>
{text}
</button>
{/each}
</div>
</div>
@@ -206,8 +217,23 @@
cursor: pointer;
font-size: var(--text-meta);
}
/* The chosen option is heavier and double-ruled as well as accent-coloured, so colour is
not the only cue (WCAG 1.4.1). The inset shadow thickens the border without moving
the label. */
.opts button.active {
border-color: var(--accent);
color: var(--accent);
font-weight: 700;
box-shadow: inset 0 0 0 1px var(--accent);
}
/* Forced colours drop the shadow and give every button the same border and text colour. */
@media (forced-colors: active) {
.opts button.active {
forced-color-adjust: none;
background: Highlight;
border-color: Highlight;
color: HighlightText;
box-shadow: none;
}
}
</style>
+12
View File
@@ -147,6 +147,7 @@ const strings = {
preview.hidden = true;
}
statusEl.textContent = "";
clearInvalid();
if (REPORT_ENABLED) {
fallback.hidden = true;
submitBtn.hidden = false;
@@ -173,10 +174,21 @@ const strings = {
}
});
const clearInvalid = () => {
desc.removeAttribute("aria-invalid");
desc.removeAttribute("aria-describedby");
};
desc.addEventListener("input", clearInvalid);
submitBtn.addEventListener("click", async () => {
const description = desc.value.trim();
if (description.length < 10) {
// Tie the message to the field and send focus back to it, so a screen reader
// announces what is wrong where it can be fixed (WCAG 3.3.1).
statusEl.textContent = strings.tooShort;
desc.setAttribute("aria-invalid", "true");
desc.setAttribute("aria-describedby", "report-status");
desc.focus();
return;
}
if (!token) {
+18
View File
@@ -77,4 +77,22 @@
background: var(--accent);
translate: 0.775rem -50%;
}
/* Forced colours repaint backgrounds, and the knob is nothing but a background: without
this the switch is an empty outline whose state cannot be seen. System colours written
here are kept. */
@media (forced-colors: active) {
.track {
border-color: ButtonText;
}
.knob {
background: ButtonText;
}
.sb-switch[aria-checked="true"] .track {
background: Highlight;
border-color: Highlight;
}
.sb-switch[aria-checked="true"] .knob {
background: HighlightText;
}
}
</style>
+26 -2
View File
@@ -176,7 +176,12 @@
location.href = flat[selectedIndex].url;
}
} else if (e.key === "Tab") {
const f = dialogEl?.querySelectorAll("input, a[href], button:not(:disabled)");
// Only what Tab can actually reach: the results are options with tabindex="-1"
// (arrow keys move through them). Counting them made the last result the "last"
// stop, which Tab never lands on — so Tab from the Esc button left the dialog.
const f = dialogEl?.querySelectorAll(
'input, a[href]:not([tabindex="-1"]), button:not(:disabled)',
);
if (!f || !f.length) return;
const first = f[0];
const last = f[f.length - 1];
@@ -243,7 +248,10 @@
autocapitalize="off"
spellcheck="false"
/>
<button type="button" class="close" onclick={close} aria-label={labels.close}>Esc</button>
<!-- The name starts with the visible "Esc" so voice control can target it (WCAG 2.5.3). -->
<button type="button" class="close" onclick={close} aria-label={`Esc — ${labels.close}`}>
Esc
</button>
</div>
<div class="results">
@@ -412,6 +420,22 @@
background: var(--surface);
border-inline-start-color: var(--accent);
}
/* Forced colours (Windows High Contrast) drop box-shadows and repaint backgrounds, which
is all the focus indicator and the active option were made of; outlines are kept. The
resting option's transparent edge would turn solid there, so it takes the page colour. */
@media (forced-colors: active) {
.search-row:focus-within {
outline: 2px solid Highlight;
outline-offset: -2px;
}
.result {
border-inline-start-color: Canvas;
}
.result.active {
outline: 2px solid Highlight;
outline-offset: -2px;
}
}
.r-title {
display: block;
font-weight: 600;
+3 -2
View File
@@ -15,8 +15,9 @@ const { platform, size = 20, class: className } = Astro.props;
const PATHS: Record<string, string> = {
youtube:
"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z",
github:
"M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12",
// Generic code brackets (not a brand mark) — the self-hosted forge (Gitea) holding the code.
gitea:
"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z",
discord:
"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z",
x: "M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z",
+14 -4
View File
@@ -3,6 +3,7 @@ import { type StoryEntry } from "../lib/collections";
import { sectionPath, type Locale } from "../i18n/routing";
import { useTranslations } from "../i18n";
import { formatDate, isoDate } from "../lib/format";
import { labelNames } from "../lib/content-labels";
interface Props {
entry: StoryEntry;
@@ -18,7 +19,11 @@ const statusLabel = {
dropped: t.story.statusDropped,
}[entry.data.status];
const hasCW = entry.data.contentWarning.length > 0;
// Every label, translated, plus the age rating — the reader decides before opening it.
const warning = [
...labelNames(entry.data.contentWarning, t.labels),
...(entry.data.ageRating ? [entry.data.ageRating] : []),
].join(" · ");
---
<article class="card story">
@@ -27,9 +32,11 @@ const hasCW = entry.data.contentWarning.length > 0;
<div class="badges">
<span class:list={["status", entry.data.status]}>{statusLabel}</span>
{
hasCW && (
<span class="cw-badge" title={entry.data.contentWarning.join(", ")}>
⚠ {entry.data.contentWarning[0]}
warning && (
<span class="cw-badge">
<span aria-hidden="true">⚠</span>
<span class="sr-only">{t.cw.title}:</span>
{warning}
</span>
)
}
@@ -87,6 +94,9 @@ const hasCW = entry.data.contentWarning.length > 0;
border-color: color-mix(in srgb, var(--ok) 45%, var(--line));
}
.cw-badge {
/* The build strips whitespace between the icon and the words: the gap spaces them. */
display: inline-flex;
gap: 0.35em;
padding: 0.1em 0.55em;
border-radius: 999px;
font-family: var(--ff-mono);
+4 -1
View File
@@ -94,7 +94,10 @@
aria-hidden="true"
>
<defs>
<linearGradient id={uid} x1="0" y1="0" x2="1" y2="0">
<!-- userSpaceOnUse, not the default objectBoundingBox: the idle flatline's bounding box
is 0 tall, and WebKit (every iOS browser) then drops the gradient, and with it the
whole stroke — the footer showed an empty band on iPhone. -->
<linearGradient id={uid} gradientUnits="userSpaceOnUse" x1="0" y1="0" x2={coordWidth} y2="0">
<stop class="s-line" offset="0%" />
<stop class="s-line" offset="36%" />
<stop class="s-accent" offset="50%" />
@@ -54,10 +54,12 @@
<span class="gh-verb">{verb(item)}</span>
<a
class="gh-repo"
href={`https://github.com/${item.repo}`}
href={`https://git.poli0981.dev/${item.repo}`}
target="_blank"
rel="noopener noreferrer">{item.repo}</a
rel="noopener noreferrer"
>
{item.repo}
</a>
{#if item.detail}
<span class="gh-detail">· {item.detail}</span>
{/if}
+17 -3
View File
@@ -1,5 +1,5 @@
<script>
import { onMount } from "svelte";
import { onMount, tick } from "svelte";
import { externalImagePath } from "../lib/ext-img";
/**
@@ -18,6 +18,17 @@
/** @type {Record<string, boolean>} */
let playing = $state({}); // YouTube facade, per video id: false = thumbnail, true = nocookie iframe
/**
* Swap the thumbnail for the player. The play button is unmounted by that swap, so focus
* moves to the iframe that replaces it instead of falling back to <body>.
* @param {string} id
*/
async function play(id) {
playing[id] = true;
await tick();
document.getElementById(`w-player-${id}`)?.focus();
}
// A source counts as present only when its status is not "na" (and it has items).
const videos = $derived(
data.status?.yt !== "na" ? (data.yt?.items ?? []).slice(0, maxVideos) : [],
@@ -55,6 +66,7 @@
<div class="w-media">
{#if playing[video.id]}
<iframe
id={`w-player-${video.id}`}
title={video.title}
src={`https://www.youtube-nocookie.com/embed/${video.id}?autoplay=1`}
allow="autoplay; encrypted-media; picture-in-picture"
@@ -64,11 +76,13 @@
{#if picture(video.thumb)}
<img src={picture(video.thumb)} alt="" loading="lazy" width="480" height="270" />
{/if}
<!-- The name carries the video's title: the gaming page shows up to three of
these, and three buttons all called "Play video" cannot be told apart. -->
<button
type="button"
class="w-play"
aria-label={labels.playLabel}
onclick={() => (playing[video.id] = true)}
aria-label={`${labels.playLabel}: ${video.title}`}
onclick={() => play(video.id)}
>
▶
</button>
+7 -6
View File
@@ -4,7 +4,7 @@
import { ago, dateTime, shortSha } from "./format";
/** @typedef {import("@/lib/admin/audit").AuditEntry} AuditEntry */
/** @typedef {import("@/lib/admin/github").ContentCommit} ContentCommit */
/** @typedef {import("@/lib/admin/gitea").ContentCommit} ContentCommit */
/** @type {{ audit: AuditEntry[]; commits: ContentCommit[] } | null} */
let data = $state(null);
@@ -21,6 +21,7 @@
"gallery.save": "Lưu album",
"gallery.delete": "Xoá album",
publish: "Xuất bản",
"publish.auto": "Tự xuất bản",
"denylist.add": "Chặn IP",
"denylist.remove": "Bỏ chặn IP",
};
@@ -58,8 +59,8 @@
<section class="card">
<div class="section-head">
<h2>Nhật ký admin</h2>
<label class="muted small"
>Lọc
<label class="muted small">
Lọc
<select bind:value={filter}>
<option value="">Tất cả</option>
<option value="content">Nội dung</option>
@@ -96,9 +97,9 @@
<ol class="log">
{#each data.commits as commit (commit.sha)}
<li>
<a href={commit.url} target="_blank" rel="noopener noreferrer"
><code>{shortSha(commit.sha)}</code></a
>
<a href={commit.url} target="_blank" rel="noopener noreferrer">
<code>{shortSha(commit.sha)}</code>
</a>
<span class="what">{commit.message}</span>
<span class="muted small when" title={dateTime(commit.date)}>
{ago(commit.date)} · {commit.author}
+6 -4
View File
@@ -59,9 +59,9 @@
{#if sessionLost}
<div class="session" role="alert">
<span
>Phiên đăng nhập Cloudflare Access đã hết hạn. Bản nháp đang viết vẫn được giữ trên máy.</span
>
<span>
Phiên đăng nhập Cloudflare Access đã hết hạn. Bản nháp đang viết vẫn được giữ trên máy.
</span>
<button type="button" onclick={() => location.reload()}>Đăng nhập lại</button>
</div>
{/if}
@@ -99,8 +99,10 @@
<button
type="button"
class={pending.danger ? "danger" : "primary"}
onclick={() => answer(true)}>{pending.confirmLabel}</button
onclick={() => answer(true)}
>
{pending.confirmLabel}
</button>
</div>
{/if}
</dialog>
+19 -15
View File
@@ -71,7 +71,8 @@
function create() {
if (!newPath || taken) return;
const params = new URLSearchParams({ new: collection, slug: slug.trim(), lang: newLang });
if (collection === "stories") params.set("series", series.trim());
// No series = a one-shot story (stories/<slug>.md).
if (collection === "stories" && series.trim()) params.set("series", series.trim());
location.href = `/admin/edit/?${params}`;
}
@@ -86,7 +87,7 @@
<div class="page-head">
<div>
<h1>Nội dung</h1>
<p>Lưu là commit vào repo nội dung; bấm “Xuất bản” để đưa lên site.</p>
<p>Lưu hoặc xoá là commit vào repo nội dung rồi tự xuất bản lên site (thường 10–15 phút).</p>
</div>
</div>
@@ -99,8 +100,8 @@
create();
}}
>
<label
>Loại
<label>
Loại
<select bind:value={collection}>
{#each Object.values(COLLECTIONS).filter((spec) => spec.creatable) as spec (spec.id)}
<option value={spec.id}>{spec.label}</option>
@@ -108,10 +109,13 @@
</select>
</label>
{#if collection === "stories"}
<label>Bộ truyện (slug) <input bind:value={series} placeholder="dem-khong-tieng" /></label>
<label>
Bộ truyện (slug, để trống nếu truyện một chương)
<input bind:value={series} placeholder="dem-khong-tieng" />
</label>
{/if}
<label
>Slug
<label>
Slug
<input
bind:value={slug}
placeholder="ten-bai-viet"
@@ -121,11 +125,11 @@
spellcheck="false"
/>
</label>
<label
>Ngôn ngữ
<select bind:value={newLang}
><option value="vi">vi</option><option value="en">en</option></select
>
<label>
Ngôn ngữ
<select bind:value={newLang}>
<option value="vi">vi</option><option value="en">en</option>
</select>
</label>
<button type="submit" class="primary" disabled={!newPath || taken}>Tạo</button>
</form>
@@ -179,9 +183,9 @@
{:else if groups.length === 0}
<p class="muted">
{#if filtered}
Không có mục nào khớp bộ lọc. <button type="button" class="ghost" onclick={clearFilters}
>Xoá bộ lọc</button
>
Không có mục nào khớp bộ lọc. <button type="button" class="ghost" onclick={clearFilters}>
Xoá bộ lọc
</button>
{:else}
Repo nội dung chưa có bài nào.
{/if}
+43 -42
View File
@@ -2,6 +2,7 @@
import { onMount } from "svelte";
import { api, describeError } from "./api";
import { ago, dateTime, shortSha } from "./format";
import { PHASE_TEXT } from "@/lib/admin/publish-phase";
/**
* @typedef {{ id: string; label: string; total: number; drafts: number; vi: number; en: number }} CollectionCount
@@ -11,7 +12,7 @@
* widgets: { yt: string; steam: string; gh: string; lastRun: string } | null;
* config: import("@/lib/admin/status").ConfigStatus;
* }} Overview
* @typedef {{ contentHead: string; published: string; pr: { number: number; url: string; checks: string | null } | null; run: { status: string; conclusion: string | null; url: string } | null }} Publish
* @typedef {{ contentHead: string; published: string; live: string | null; phase: import("@/lib/admin/publish-phase").PublishPhase; pr: { number: number; url: string; checks: string | null } | null; run: { status: string; conclusion: string | null; url: string } | null }} Publish
*/
/** @type {Overview | null} */
@@ -58,10 +59,12 @@
{#if overview.config.version.commit}
· commit
<a
href={`https://github.com/poli0981/poli0981-dev/commit/${overview.config.version.commit}`}
href={`https://git.poli0981.dev/poli0981/poli0981-dev/commit/${overview.config.version.commit}`}
target="_blank"
rel="noopener noreferrer"><code>{shortSha(overview.config.version.commit)}</code></a
rel="noopener noreferrer"
>
<code>{shortSha(overview.config.version.commit)}</code>
</a>
{/if}
· triển khai {ago(overview.config.version.timestamp)}
</p>
@@ -89,11 +92,13 @@
{#if overview.content}
<table>
<thead>
<tr
><th scope="col">Loại</th><th scope="col">Tổng</th><th scope="col">vi</th><th
scope="col">en</th
><th scope="col">Nháp</th></tr
>
<tr>
<th scope="col">Loại</th><th scope="col">Tổng</th><th scope="col">vi</th><th
scope="col"
>
en
</th><th scope="col">Nháp</th>
</tr>
</thead>
<tbody>
{#each overview.content.collections as c (c.id)}
@@ -102,10 +107,9 @@
<td>{c.total}</td>
<td>{c.vi}</td>
<td>{c.en}</td>
<td
>{#if c.drafts}<span class="pill" data-tone="warn">{c.drafts}</span
>{:else}0{/if}</td
>
<td>
{#if c.drafts}<span class="pill" data-tone="warn">{c.drafts}</span>{:else}0{/if}
</td>
</tr>
{/each}
</tbody>
@@ -115,29 +119,34 @@
{#if drafts}· {drafts} bản nháp chưa hiện trên site{/if}
</p>
{:else}
<p class="muted">Chưa đặt GITHUB_CONTENT_TOKEN — admin không đọc được repo nội dung.</p>
<p class="muted">Chưa đặt GITEA_BOT_TOKEN — admin không đọc được repo nội dung.</p>
{/if}
</section>
<section class="card">
<h2>Xuất bản</h2>
{#if publish}
{#if publish.contentHead === publish.published}
<p><span class="pill" data-tone="ok">Đã đồng bộ</span></p>
<p>
<span class="pill" data-tone={PHASE_TEXT[publish.phase].tone}>
{PHASE_TEXT[publish.phase].label}
</span>
</p>
<p class="muted small">
Repo nội dung <code>{shortSha(publish.contentHead)}</code> · đã merge
<code>{shortSha(publish.published)}</code>
{#if publish.live}· đang chạy <code>{shortSha(publish.live)}</code>{/if}
</p>
{#if publish.phase === "deploying"}
<p class="muted small">
Site đang dùng nội dung <code>{shortSha(publish.published)}</code>.
</p>
{:else}
<p><span class="pill" data-tone="warn">Có thay đổi chưa xuất bản</span></p>
<p class="muted small">
Repo <code>{shortSha(publish.contentHead)}</code> · site
<code>{shortSha(publish.published)}</code>
Thường mất vài phút sau khi merge (job deploy trong CI, runner trên máy). Lâu hơn: xem
tab Actions trên Gitea — máy tắt thì job đợi đến khi bật lại.
</p>
{/if}
{#if publish.run?.conclusion === "failure"}
{#if publish.phase === "failed" && publish.run}
<p class="small">
<span class="pill" data-tone="err">Lần chạy gần nhất lỗi</span>
<a href={publish.run.url} target="_blank" rel="noopener noreferrer">Xem log ↗</a>
<a href={publish.pr?.url ?? publish.run.url} target="_blank" rel="noopener noreferrer">
Xem lỗi ↗
</a>
</p>
{/if}
{:else}
@@ -150,15 +159,15 @@
<p><a href="/admin/media/">{overview.media.count} ảnh</a> trong thư viện R2.</p>
{#if overview.widgets}
<p class="pills">
<span class="pill" data-tone={tone(overview.widgets.yt)}
>YouTube {overview.widgets.yt}</span
>
<span class="pill" data-tone={tone(overview.widgets.steam)}
>Steam {overview.widgets.steam}</span
>
<span class="pill" data-tone={tone(overview.widgets.gh)}
>GitHub {overview.widgets.gh}</span
>
<span class="pill" data-tone={tone(overview.widgets.yt)}>
YouTube {overview.widgets.yt}
</span>
<span class="pill" data-tone={tone(overview.widgets.steam)}>
Steam {overview.widgets.steam}
</span>
<span class="pill" data-tone={tone(overview.widgets.gh)}>
Gitea {overview.widgets.gh}
</span>
</p>
<p class="muted small" title={dateTime(overview.widgets.lastRun)}>
Cron widgets chạy {ago(overview.widgets.lastRun)}
@@ -183,11 +192,6 @@
: ""}{/each}
</p>
{/if}
{#if overview.config.singleToken}
<p class="small warn">
Xuất bản đang dùng chung token nội dung — nên tạo GITHUB_PUBLISH_TOKEN riêng.
</p>
{/if}
<p class="small"><a href="/admin/security/">Danh sách chặn IP →</a></p>
</section>
</div>
@@ -240,9 +244,6 @@
.small {
font-size: var(--text-meta);
}
.warn {
color: var(--warn);
}
p {
margin: 0.4rem 0;
}
+105 -18
View File
@@ -6,6 +6,7 @@
import { confirmAction, toast } from "./ui";
import { dateTime } from "./format";
import { collectionOf, newEntryPath, validateFrontmatter } from "@/lib/admin/collections";
import { afterSaveMessage } from "@/lib/admin/publish-phase";
import { mediaFallbackSrc, mediaPictureHtml } from "@/lib/media";
/** @type {{ path?: string | null; create?: { collection: string; slug: string; lang: string; series?: string } | null }} */
@@ -48,10 +49,13 @@
const field = spec?.fields.find((f) => f.key === e.field);
const message = {
required: "Bắt buộc.",
type: "Sai kiểu dữ liệu.",
type: field?.integer ? "Cần một số nguyên." : "Sai kiểu dữ liệu.",
option: "Chọn một giá trị trong danh sách.",
max: `Tối đa ${field?.max ?? ""} ký tự.`,
format: field?.type === "url" ? "Cần một URL http(s)." : "Sai định dạng.",
min: `Nhỏ nhất là ${field?.min ?? ""}.`,
conflict: "Bài đã có ảnh bìa local (cover trong file) — chỉ được dùng một trong hai.",
missing: "Album này chưa có ảnh — tạo album ở trang Gallery trước.",
}[e.code];
return [e.field, message];
}),
@@ -200,7 +204,9 @@
sha = result.sha;
dirty = false;
clearDraft();
toast("Đã lưu vào repo nội dung — bấm “Xuất bản” để đưa lên site.");
const message = afterSaveMessage(result.publish, "Đã lưu");
toast(message.text, message.kind);
if (message.queued) dispatchEvent(new Event("admin:published"));
if (isNew) {
isNew = false;
history.replaceState(
@@ -212,7 +218,7 @@
} catch (error) {
toast(
error instanceof ApiError && error.data.error === "conflict"
? "File đã bị sửa ở nơi khác (vd. GitHub). Bản đang viết vẫn còn trên máy — tải lại trang rồi chọn “Khôi phục”."
? "File đã bị sửa ở nơi khác (vd. trên Gitea). Bản đang viết vẫn còn trên máy — tải lại trang rồi chọn “Khôi phục”."
: describeError(error),
"error",
);
@@ -265,6 +271,19 @@
touch();
}
/**
* Tick or untick one option of a multiselect; the list keeps the options' own order, and an
* empty list is dropped from the frontmatter on save.
* @param {{ key: string; options?: readonly string[] }} field @param {string} option @param {boolean} on
*/
function toggleOption(field, option, on) {
/** @type {string[]} */
const before = data[field.key] ?? [];
const chosen = on ? [...before, option] : before.filter((item) => item !== option);
data[field.key] = (field.options ?? []).filter((item) => chosen.includes(item));
touch();
}
/** @param {string} key */
const invalid = (key) => triedSave && key in fieldError;
</script>
@@ -291,8 +310,10 @@
onclick={save}
disabled={saving || loading || Boolean(loadError)}
aria-keyshortcuts="Control+S Meta+S"
title="Lưu (Ctrl/⌘+S)">Lưu</button
title="Lưu (Ctrl/⌘+S)"
>
Lưu
</button>
</div>
</div>
@@ -321,22 +342,69 @@
{@const errorId = `err-${field.key}`}
<div class="field">
{#if field.type === "checkbox"}
<label class="check"
><input type="checkbox" bind:checked={data[field.key]} /> {field.label}</label
>
<label class="check">
<input type="checkbox" bind:checked={data[field.key]} />
{field.label}
</label>
{:else if field.type === "media"}
<span class="label">{field.label}</span>
{#if data[field.key]?.id}
<img class="cover" src={mediaFallbackSrc(data[field.key])} alt="" />
<div class="row">
<button type="button" onclick={() => (picking = "cover")}>Đổi ảnh</button>
<button type="button" onclick={() => ((data[field.key] = undefined), touch())}
>Bỏ</button
>
<button type="button" onclick={() => ((data[field.key] = undefined), touch())}>
Bỏ
</button>
</div>
<!-- The alt travels with this post: picking copies the library's text once,
and editing it here changes only this cover, not the library. -->
<label>
<span class="label">Mô tả ảnh bìa (alt)</span>
<input
maxlength="300"
value={data[field.key].alt ?? ""}
oninput={(event) => {
const alt = event.currentTarget.value.trim();
const next = { ...data[field.key] };
if (alt) next.alt = alt;
else delete next.alt;
data[field.key] = next;
}}
placeholder="Ảnh cho thấy gì — để trống nếu chỉ trang trí"
/>
</label>
{:else}
<button type="button" onclick={() => (picking = "cover")}>Chọn ảnh bìa</button>
{/if}
{#if invalid(field.key)}
<span class="field-error" id={errorId}>{fieldError[field.key]}</span>
{/if}
{:else if field.type === "multiselect"}
<fieldset
class="multi"
aria-describedby={invalid(field.key)
? errorId
: field.hint
? `hint-${field.key}`
: undefined}
>
<legend class="label">{field.label}</legend>
{#each field.options ?? [] as option (option)}
<label class="check">
<input
type="checkbox"
checked={(data[field.key] ?? []).includes(option)}
onchange={(event) => toggleOption(field, option, event.currentTarget.checked)}
/>
{field.optionLabels?.[option] ?? option}
</label>
{/each}
</fieldset>
{#if invalid(field.key)}
<span class="field-error" id={errorId}>{fieldError[field.key]}</span>
{:else if field.hint}
<span class="hint" id={`hint-${field.key}`}>{field.hint}</span>
{/if}
{:else}
<label>
<span class="label">{field.label}{field.required ? " *" : ""}</span>
@@ -354,14 +422,16 @@
aria-describedby={invalid(field.key) ? errorId : undefined}
>
<option value={undefined}>—</option>
{#each field.options ?? [] as option (option)}<option value={option}
>{option}</option
>{/each}
{#each field.options ?? [] as option (option)}<option value={option}>
{option}
</option>{/each}
</select>
{:else if field.type === "tags"}
<!-- On every keystroke, not on change: Ctrl/⌘+S while the cursor is still
here must save what is typed, and `change` only fires on blur. -->
<input
value={(data[field.key] ?? []).join(", ")}
onchange={(event) => setTags(field.key, event.currentTarget.value)}
oninput={(event) => setTags(field.key, event.currentTarget.value)}
placeholder="cách nhau bởi dấu phẩy"
/>
{:else if field.type === "number"}
@@ -412,8 +482,10 @@
aria-controls="panel-edit"
aria-selected={tab === "edit"}
tabindex={tab === "edit" ? 0 : -1}
onclick={() => (tab = "edit")}>Soạn</button
onclick={() => (tab = "edit")}
>
Soạn
</button>
<button
type="button"
role="tab"
@@ -421,11 +493,14 @@
aria-controls="panel-preview"
aria-selected={tab === "preview"}
tabindex={tab === "preview" ? 0 : -1}
onclick={() => (tab = "preview")}>Xem trước</button
onclick={() => (tab = "preview")}
>
Xem trước
</button>
</div>
<button type="button" class="insert" onclick={() => (picking = "insert")}>Chèn ảnh</button
>
<button type="button" class="insert" onclick={() => (picking = "insert")}>
Chèn ảnh
</button>
</div>
{#if tab === "edit"}
<div role="tabpanel" id="panel-edit" aria-labelledby="tab-edit">
@@ -537,6 +612,18 @@
align-items: center;
gap: 0.5rem;
}
.multi {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr));
gap: 0.35rem 0.75rem;
margin: 0;
padding: 0.6rem 0.75rem 0.75rem;
border: 1px solid var(--line);
border-radius: var(--radius-control);
}
.multi legend {
padding-inline: 0.25rem;
}
.cover {
display: block;
inline-size: 100%;
+88 -23
View File
@@ -4,9 +4,12 @@
import MediaPicker from "./MediaPicker.svelte";
import { confirmAction, toast } from "./ui";
import { SLUG_PATTERN } from "@/lib/admin/collections";
import { afterSaveMessage } from "@/lib/admin/publish-phase";
import { LABEL_IDS } from "@/lib/content-labels";
import { mediaFallbackSrc } from "@/lib/media";
import vi from "@/i18n/vi";
/** @typedef {{ id: string; w: number; h: number; caption: { vi: string; en: string } }} Photo */
/** @typedef {{ id: string; w: number; h: number; caption: { vi: string; en: string }; contentWarning?: string[] }} Photo */
/** @typedef {{ album: string; titles: Record<string, string>; photos: Photo[]; sha: string | null; coverIndex: number; local: number }} Album */
/** @typedef {{ album: string; titles: Record<string, string>; photos: Photo[]; sha: string | null; local: number; coverId: string | null }} Editing */
@@ -119,6 +122,19 @@
picking = false;
}
/**
* Tick or untick one of a photo's labels; the list keeps the label order, and a photo with
* none has no `contentWarning` key at all in the saved JSON.
* @param {Photo} photo @param {string} id @param {boolean} on
*/
function togglePhotoLabel(photo, id, on) {
const before = photo.contentWarning ?? [];
const chosen = on ? [...before, id] : before.filter((label) => label !== id);
const labels = LABEL_IDS.filter((label) => chosen.includes(label));
if (labels.length > 0) photo.contentWarning = labels;
else delete photo.contentWarning;
}
/** @param {Photo} photo */
function removePhoto(photo) {
if (!current) return;
@@ -143,7 +159,7 @@
const cover = current.photos.findIndex((p) => p.id === current?.coverId);
saving = true;
try {
await api("/api/admin/gallery", "PUT", {
const result = await api("/api/admin/gallery", "PUT", {
album,
photos: current.photos,
sha: current.sha,
@@ -158,7 +174,9 @@
}
: {}),
});
toast("Đã lưu album vào repo nội dung — bấm “Xuất bản” để đưa lên site.");
const message = afterSaveMessage(result.publish, "Đã lưu album");
toast(message.text, message.kind);
if (message.queued) dispatchEvent(new Event("admin:published"));
creating = false;
await load();
const saved = albums.find((a) => a.album === album);
@@ -179,8 +197,10 @@
);
if (!ok) return;
try {
await api("/api/admin/gallery", "DELETE", { album: current.album });
toast("Đã xoá album.");
const result = await api("/api/admin/gallery", "DELETE", { album: current.album });
const message = afterSaveMessage(result.publish, "Đã xoá album");
toast(message.text, message.kind);
if (message.queued) dispatchEvent(new Event("admin:published"));
current = null;
baseline = "";
await load();
@@ -216,9 +236,9 @@
onclick={() => open(album)}
>
<span>{album.titles.vi ?? album.album}</span>
<span class="meta"
>{album.photos.length} ảnh R2{album.local ? ` · ${album.local} ảnh repo` : ""}</span
>
<span class="meta">
{album.photos.length} ảnh R2{album.local ? ` · ${album.local} ảnh repo` : ""}
</span>
</button>
</li>
{/each}
@@ -274,14 +294,34 @@
>
<img src={mediaFallbackSrc(photo)} alt="" />
<div class="captions">
<label
><span class="sr-only">Chú thích tiếng Việt, ảnh {index + 1}</span>
<input bind:value={photo.caption.vi} placeholder="Chú thích (vi)" /></label
>
<label
><span class="sr-only">English caption, photo {index + 1}</span>
<input bind:value={photo.caption.en} placeholder="Caption (en)" /></label
>
<label>
<span class="sr-only">Chú thích tiếng Việt, ảnh {index + 1}</span>
<input bind:value={photo.caption.vi} placeholder="Chú thích (vi)" />
</label>
<label>
<span class="sr-only">English caption, photo {index + 1}</span>
<input bind:value={photo.caption.en} placeholder="Caption (en)" />
</label>
<!-- This photo's own content labels: blurred on the site when one asks for it. -->
<details class="photo-labels">
<summary>
Nhãn{photo.contentWarning?.length ? ` (${photo.contentWarning.length})` : ""}
<span class="sr-only">của ảnh {index + 1}</span>
</summary>
<div class="label-list">
{#each LABEL_IDS as id (id)}
<label class="check">
<input
type="checkbox"
checked={photo.contentWarning?.includes(id) ?? false}
onchange={(event) =>
togglePhotoLabel(photo, id, event.currentTarget.checked)}
/>
{vi.labels[id]}
</label>
{/each}
</div>
</details>
</div>
<div class="order">
<button
@@ -289,25 +329,33 @@
class="cover-pick"
aria-pressed={current.coverId === photo.id}
aria-label={`Đặt ảnh ${index + 1} làm ảnh bìa`}
onclick={() => current && (current.coverId = photo.id)}>★</button
onclick={() => current && (current.coverId = photo.id)}
>
★
</button>
<button
type="button"
aria-label={`Đưa ảnh ${index + 1} lên`}
disabled={index === 0}
onclick={() => move(index, index - 1)}>↑</button
onclick={() => move(index, index - 1)}
>
↑
</button>
<button
type="button"
aria-label={`Đưa ảnh ${index + 1} xuống`}
disabled={index === current.photos.length - 1}
onclick={() => move(index, index + 1)}>↓</button
onclick={() => move(index, index + 1)}
>
↓
</button>
<button
type="button"
aria-label={`Bỏ ảnh ${index + 1} khỏi album`}
onclick={() => removePhoto(photo)}>✕</button
onclick={() => removePhoto(photo)}
>
✕
</button>
</div>
</li>
{/each}
@@ -321,9 +369,9 @@
{#if !creating}
<button type="button" class="danger" onclick={removeAlbum}>Xoá album</button>
{/if}
<button type="button" class="primary push" onclick={save} disabled={saving || !dirty}
>{saving ? "Đang lưu…" : "Lưu album"}</button
>
<button type="button" class="primary push" onclick={save} disabled={saving || !dirty}>
{saving ? "Đang lưu…" : "Lưu album"}
</button>
</div>
</section>
{/if}
@@ -425,6 +473,23 @@
display: grid;
gap: 0.35rem;
}
.photo-labels summary {
cursor: pointer;
color: var(--muted);
font-size: var(--text-meta);
}
.label-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr));
gap: 0.25rem 0.75rem;
padding-block: 0.35rem;
font-size: var(--text-meta);
}
.label-list .check {
display: flex;
align-items: center;
gap: 0.4rem;
}
.order {
display: flex;
gap: 0.25rem;
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff. Show more