Docs for v2.0, plus widget and CSP fixes (#100)

* docs: README, CHANGELOG and the docs suite brought up to v2.0

- README.md (new): what the site is, stack, how the Worker fits together,
  getting started on Node 26, commands, deploying with Workers Builds, the
  admin, security and licensing.
- CHANGELOG.md (new): v2.0.0 in Keep a Changelog form, plus a summary of the
  untagged 1.x months.
- SECURITY.md: admin.poli0981.dev, the bot gate and the widgets worker are in
  scope; tagged releases; reports go to a private repository; what the admin
  stores.
- THIRD-PARTY-NOTICES.md: every infrastructure service, with what each one is
  used for. CONTENT-LICENSE.md: the content submodule and /media images.
- poli0981.dev-docs v2.0: decision log D16–D19; architecture (worker entry,
  stack, repo layout, dev setup, ADR 09–11); design system (Glacier Teal
  tokens, theme modes, a11y rules); security (headers, single-key CIDR
  denylist, body limits, secrets table, supply chain on a public repo,
  admin hardening and Access recommendations, structured logs); Cloudflare
  setup (correct Workers Builds commands and the deploy incident, ADMIN_EMAILS,
  Access settings, observability); CI/CD as it runs today; bug reports,
  widgets, error pages, routes, roadmap with status and next steps,
  maintenance (TypeScript 7 bumps, rollback, R2/KV backup).

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

* docs(changelog): link the documentation PR

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

* fix(widgets): Steam icons via Steam's Cloudflare CDN; optional GitHub token

Found by watching the first cron run of the new worker in production: no
image had been mirrored and two sources were stale.

- media.steampowered.com answers requests from Workers with 403, so every
  Steam icon mirror failed. cdn.cloudflare.steamstatic.com serves the same
  files to Workers (probed from Cloudflare's network).
- The GitHub events API allows 60 unauthenticated requests an hour per IP and
  Workers share egress IPs, so the feed was 403 for hours at a time. The
  worker now sends GITHUB_TOKEN when that optional secret exists (a
  fine-grained token with no permissions is enough for public data).
- YouTube's feeds/videos.xml currently answers 404 for both the channel and
  the uploads-playlist URL, from Cloudflare and from elsewhere; the worker
  already keeps the last good feed, so nothing changes there.

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

* fix(csp): callout styles were blocked; the CSP check now covers styles

Lighthouse flagged a CSP violation on the one MDX post. Astro hashes the
styles of the components a page renders, but not of a component that only
appears inside MDX content: Callout's inline <style> shipped without its hash
and the browser refused it, so callouts were unstyled in production.

- Callout's rules move to src/styles/prose.css (the stylesheet Prose loads on
  every long-form page); the component has no <style> block any more.
- scripts/check-csp-hashes.mjs now hashes every inline <style> block against
  the page's policy and fails on any style attribute (a policy without
  'unsafe-inline' never allows one), with self-tests for both matchers. The
  build reports 339 style blocks across 64 pages, all hashed.

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

* chore(og): Number.parseInt in the colour mixer (Sonar S7773)

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 authored and GitHub committed 2026-10-24 11:48:47 +07:00
1 parent 71e6c11de3
commit 1b1e922fe2
29 files changed
+722 -306

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
# Changelog
Notable changes to poli0981.dev. The site deploys continuously from `main`; tags mark
milestones. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
Content changes (posts, stories, albums) live in [`poli0981/content`](https://github.com/poli0981/content)
and are not listed here.
## [2.0.0] — 2026-10-24
A platform upgrade, a security pass, a new palette and a rebuilt admin
([#98](https://github.com/poli0981/poli0981-dev/pull/98),
[#99](https://github.com/poli0981/poli0981-dev/pull/99),
[#100](https://github.com/poli0981/poli0981-dev/pull/100)).
### Security
- **Turnstile gate bypass fixed** ([#97](https://github.com/poli0981/poli0981-dev/pull/97)): a pass
cookie with a malformed signature made the check throw and the Worker failed open, serving the
real page. Decoding is now total, signatures must be exactly 43 characters, and if deciding or
rendering the gate throws the visitor gets a 503 — never the page behind it.
- Admin: Access tokens older than 24 hours are refused, and `ADMIN_EMAILS` is required (fail
closed). Every admin action is recorded in a KV audit log (90 days).
- The IP denylist is enforced by the Worker entry for every route, pages included (it only
covered on-demand routes), supports CIDR ranges and expiry, and is managed from the admin.
- Request bodies are capped (report 32 KB, gate 8 KB, admin JSON 512 KB, uploads 20 MB) and
every outgoing fetch has a timeout.
- Bug reports go to the private `poli0981/site-reports` repository (the site repo is public);
`@mentions` in reports are neutralised and Discord pings are disabled.
- Widget thumbnails and game icons are mirrored by the cron worker and served from `/ext-img`, so
browsers no longer contact Google or Steam before a visitor clicks; `img-src` is `'self'` only.
- `frame-ancestors 'none'` is now sent as a header (it has no effect in a meta CSP).
- CI installs with `--ignore-scripts` and fails on new install scripts; Dependabot waits three days
before proposing a release; SonarCloud, CodeQL, OSV-Scanner and Snyk run on every PR.
### Added
- Light/dark theme that **follows the OS** by default, with a system → light → dark toggle.
- "Glacier Teal" palette (navy and teal) across the site and admin, checked against WCAG AA by
`tests/palette.test.ts`.
- Admin: an overview dashboard, an activity page (audit log + content commits), a security page
(IP denylist, configuration), editor draft autosave with restore, Ctrl/⌘+S, client-side field
validation, a sandboxed preview, media search and usage, parallel uploads, gallery cover picker,
drag-and-drop ordering and album deletion, a "session expired" banner.
- Reader routes for one-shot stories (`/truyen/<slug>/`).
- `/api/health` reports the running Worker version and the commit it was built from; the 500 page
shows the Cloudflare Ray ID, which matches the structured JSON logs in Workers Logs.
- Test suite on `node:test` (about 200 tests, ~99% line coverage of the TypeScript sources) and a
SonarCloud quality gate.
### Changed
- Node 26; TypeScript 7 (`tsc`) for type checking, alongside TypeScript 6 for tools that need its
API; ES2025 target. Astro 7.4, @astrojs/cloudflare 14.4, Wrangler 4.152 and current
dependencies.
- Vietnamese and English pages share one component each (eleven duplicated pages removed).
- The header shows the full navigation from 960 px (it overflowed between 768 and 900 px).
- Workers Builds deploys only `main`; other branches upload preview versions.
### Fixed
- The language switch no longer leads to a 404 on posts whose slugs differ between languages.
- The story reader bar no longer hides behind the sticky header.
- Modal dialogs (the bug-report dialog) were stuck in the top-left corner; lists in posts had no
bullets — both caused by Tailwind's preflight.
- Callouts in MDX posts rendered unstyled: Astro left their inline styles out of the page's CSP, so
the browser refused them. The rules moved to the shared prose stylesheet, and the build's CSP
check now verifies every inline `<style>` (and forbids style attributes) as well as scripts.
- Accessibility: the search is an ARIA combobox, the mobile menu is a modal dialog with a focus
trap, lightbox focus handling, labelled report dialog, a correct "copied" message, Esc no longer
dismisses the legal notice from elsewhere, landmark and link labels translated.
- Gallery albums work without JavaScript; contact lines on /qa and the 403 page are real links.
- Widgets: Steam game icons are fetched from Steam's Cloudflare CDN (`media.steampowered.com` refuses
Workers with 403), and an optional read-only `GITHUB_TOKEN` keeps the GitHub feed from going stale
under the per-IP rate limit Workers share.
- Dozens of smaller issues found by SonarCloud and the new tests (error pages served with the
wrong status under `astro dev`, regex backtracking, scripts that passed without checking).
## [1.x] — 2026-07 → 2026-10 (untagged)
- **2026-07** — Bilingual Astro + Cloudflare Workers site: blog, stories with reading controls and
content warnings, projects, dev/uses, gaming, Q&A, links, legal pages; Pagefind search; RSS,
sitemap, JSON-LD and generated OG images; offline page with the Skull Hop mini-game; bug-report
pipeline (Turnstile → GitHub issue + Discord); widgets cron worker.
- **2026-08** — Content moved to the `poli0981/content` submodule; gallery with real photos; /now
page; `new:post`; Lighthouse CI; generated third-party notices; CSP hash guard; security.txt; AI
usage disclosure.
- **2026-10** — Custom Worker entry in front of every page; Workers Rate Limiting; Web Analytics;
topic email aliases; R2 media; the Turnstile gate; the admin at `admin.poli0981.dev`.
[2.0.0]: https://github.com/poli0981/poli0981-dev/releases/tag/v2.0.0
+10 -8
View File
@@ -2,11 +2,11 @@
**This file covers content, not code.** The two are licensed differently on purpose.
| Scope | License | File |
| ----------------------------------------------------------------------------------------- | ----------------------- | ------------------------ |
| Source code — every code, config, style and script file | **GPL-3.0-only** | `LICENSE` |
| Content — posts, stories, photographs, original media (`src/content/**`, `src/assets/**`) | **All Rights Reserved** | this file |
| Third-party packages and fonts | their own licenses | `THIRD-PARTY-NOTICES.md` |
| Scope | License | File |
| ----------------------------------------------------------------------------------------------------------------------- | ----------------------- | ------------------------ |
| Source code — every code, config, style and script file | **GPL-3.0-only** | `LICENSE` |
| Content — posts, stories, photographs, original media (`src/content/**`, `src/assets/**`, images served from `/media/`) | **All Rights Reserved** | this file |
| Third-party packages and fonts | their own licenses | `THIRD-PARTY-NOTICES.md` |
`package.json` declares `"license": "SEE LICENSE IN LICENSE"` precisely so nobody reads the
GPL as covering the stories and photographs. It does not.
@@ -21,7 +21,8 @@ machine-learning systems**, without prior written permission. Short quotations w
and a link are permitted (see Terms of Use §4). An individual page may state a different license
for that page's content, in which case the page's own license prevails.
Cloning this repository does not grant a content license. If you fork it, remove
Cloning this repository does not grant a content license. `src/content` is a git submodule of
the separate `poli0981/content` repository, under the same terms. If you fork, remove
`src/content/**` and `src/assets/**` or replace them with your own.
**Permissions:** copyright@poli0981.dev · **Copyright infringement (DMCA):** dmca@poli0981.dev ·
@@ -37,8 +38,9 @@ có sự cho phép bằng văn bản. Được phép trích ngắn có ghi ngu
trang cụ thể có thể ghi giấy phép khác cho nội dung của trang đó — khi ấy giấy phép ghi tại trang
được ưu tiên.
Việc clone repo này không đồng nghĩa với việc được cấp phép nội dung. Nếu bạn fork, hãy xoá
`src/content/**` và `src/assets/**` hoặc thay bằng nội dung của chính bạn.
Việc clone repo này không đồng nghĩa với việc được cấp phép nội dung. `src/content` là submodule
của repo riêng `poli0981/content`, cùng điều khoản này. Nếu bạn fork, hãy xoá `src/content/**` và
`src/assets/**` hoặc thay bằng nội dung của chính bạn.
**Xin phép:** copyright@poli0981.dev · **Vi phạm bản quyền (DMCA):** dmca@poli0981.dev ·
**Yêu cầu gỡ khác:** takedown@poli0981.dev
+100
View File
@@ -0,0 +1,100 @@
# 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)
[![License: GPL-3.0](https://img.shields.io/badge/code-GPL--3.0-blue)](LICENSE)
The personal site of Kokone (SkullMute) — dev portfolio, blog, short fiction and a hub for
the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https://poli0981.dev)**.
> Trang cá nhân của Kokone (SkullMute): dự án, blog, truyện ngắn và kênh SkullMute — song ngữ
> Việt/Anh. Tài liệu thiết kế đầy đủ (tiếng Việt) nằm trong [`poli0981.dev-docs/`](poli0981.dev-docs/00_INDEX.md).
## Stack
| Layer | Choice |
| --------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Framework | [Astro 7](https://astro.build) (static-first) with Svelte 5 islands |
| Styling | Tailwind CSS 4, design tokens in `src/styles/global.css` ("Glacier Teal" palette) |
| Hosting | Cloudflare Workers + Static Assets; KV, R2, Images, Rate Limiting, Access, Turnstile |
| Content | Markdown/MDX in [`poli0981/content`](https://github.com/poli0981/content) (git submodule `src/content`) |
| Search | Pagefind (built after `astro build`) |
| Tooling | Node 26 · TypeScript 7 (`tsc`) next to TypeScript 6 (astro check, typescript-eslint) · `node:test` · ESLint · Prettier · knip |
| Quality | SonarCloud quality gate · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) |
## How it fits together
```
visitor ─▶ Cloudflare edge ─▶ src/worker.ts (every request, pages included)
www → apex · IP denylist (KV) · admin host split · /media (R2) · /ext-img (KV)
Turnstile gate (48-hour pass) · static pages from ASSETS · the rest → Astro app
├─ /api/report, /api/gate, /api/widgets, /api/health
└─ admin.poli0981.dev (Cloudflare Access + JWT check)
workers/widgets (cron, every 45 min) ─▶ YouTube / Steam / GitHub ─▶ KV (data + mirrored images)
```
Almost every page is prerendered. The Worker entry runs first for every route so the bot gate,
the denylist and the security headers also cover static pages. Details:
[`02_ARCHITECTURE.md`](poli0981.dev-docs/02_ARCHITECTURE.md) and [`06_SECURITY.md`](poli0981.dev-docs/06_SECURITY.md).
## Getting started
Requirements: Node 26 (`.nvmrc`) and npm 11. The content submodule is public, so a plain clone works.
```bash
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
cd poli0981-dev
npm ci --ignore-scripts && npm run check-install-scripts
npx lefthook install
npm run types && npm run types:widgets
npm run dev
```
`npm run dev` runs Astro on workerd with local bindings. The admin works locally with a stand-in
identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.dev.vars`.
## Commands
| Command | What it does |
| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `npm run dev` | Dev server (workerd, local KV/R2) |
| `npm run build` | `astro build` → OG images → Pagefind index → CSP hash check |
| `npm run preview` | Serve the build |
| `npm run check` | `astro check` (TypeScript 6 language service) |
| `npm run typecheck` | `tsc` from TypeScript 7 for the site and the widgets worker |
| `npm run lint` · `npm run format:check` · `npm run knip` | ESLint · Prettier · unused files/exports |
| `npm test` · `npm run test:coverage` | `node:test` suites; coverage writes `coverage/lcov.info` (80% line floor) |
| `npm run smoke` | Runs the built Worker with `wrangler dev` and probes pages, headers, the gate and the denylist |
| `npm run new:post` | Scaffold a post or story from `docs/templates/` |
| `npm run check-exif` · `npm run strip-exif` | Refuse / remove GPS and camera metadata in images |
| `npm run gen-notices` | Regenerate `THIRD-PARTY-NOTICES.md` (CI checks it) |
## Deploying
Cloudflare **Workers Builds** builds every push: `main` runs `npx wrangler deploy`, any other
branch only `npx wrangler versions upload` (a preview version that takes no traffic). After a
merge, `https://poli0981.dev/api/health` reports the running version and commit. The widgets
worker deploys by hand: `npx wrangler deploy --config workers/widgets/wrangler.jsonc`.
Setup from scratch: [`07_CLOUDFLARE_SETUP.md`](poli0981.dev-docs/07_CLOUDFLARE_SETUP.md);
pipeline: [`08_CI_CD.md`](poli0981.dev-docs/08_CI_CD.md); changes per release: [`CHANGELOG.md`](CHANGELOG.md).
## Admin
`admin.poli0981.dev` is the owner's editor: write and edit posts (commits to the content repo),
upload images (transformed once into AVIF/WebP and stored in R2), manage gallery albums,
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
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.
## License
- **Code**: [GPL-3.0-only](LICENSE).
- **Content** (posts, stories, photographs — the `poli0981/content` submodule, `src/assets/`,
uploaded media): **all rights reserved**, see [`CONTENT-LICENSE.md`](CONTENT-LICENSE.md).
- Third-party packages and fonts: [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md).
- How AI was used to build the site: [`/legal/ai-usage`](https://poli0981.dev/legal/ai-usage/).
+22 -10
View File
@@ -14,12 +14,17 @@ Machine-readable contact: <https://poli0981.dev/.well-known/security.txt> (RFC 9
**In scope**
- `poli0981.dev` and its `/api/*` endpoints
- This repository's build and deploy pipeline
- `poli0981.dev`, including its `/api/*` endpoints, `/media/*` and `/ext-img/*`
- `admin.poli0981.dev` — anything that reaches the admin or its API without passing
Cloudflare Access, the Worker's own Access JWT check or the email allowlist, or that lets
an admin page run attacker-controlled script
- The Turnstile bot gate in front of the pages (a way to see page content without a pass)
- The widgets cron worker and this repository's build, CI and deploy pipeline
**Out of scope**
- Findings that require an already-compromised Cloudflare or GitHub account
- Findings that require an already-compromised Cloudflare, GitHub or Access identity
- Attacks on Cloudflare Access's own login flow (report those to Cloudflare)
- Volumetric denial of service
- Missing hardening headers with no demonstrated impact
- Reports that are only raw automated-scanner output, with no working proof of concept
@@ -27,8 +32,9 @@ Machine-readable contact: <https://poli0981.dev/.well-known/security.txt> (RFC 9
## Supported versions
Only the currently deployed site (`main` → Cloudflare Workers) is supported. There are
no tagged releases and no backports.
Only the currently deployed site (`main` → Cloudflare Workers) is supported. Releases are
tagged (`v2.0.0` onwards, see [`CHANGELOG.md`](CHANGELOG.md)) for reference only — there are
no backports. `https://poli0981.dev/api/health` reports the version and commit that is live.
## What the site actually handles
@@ -37,9 +43,15 @@ Useful context when judging impact — the site is static and stores almost noth
- 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/`).
- User-submitted input: the bug-report form (Turnstile-gated, schema-validated, forwarded
to a private GitHub issue and a Discord webhook) and the bot-check token exchange at
`/api/gate`. Both are rate-limited per client.
- IP addresses are used transiently for rate limiting and are not stored with reports.
- User-submitted input: the bug-report form (Turnstile-gated, schema-validated, size-capped,
forwarded to an issue in a **private** repository and a Discord webhook) and the bot-check
token exchange at `/api/gate`. Both are rate-limited per client.
- IP addresses are used transiently for rate limiting and the IP denylist; they are not
stored with reports. Workers Logs keep request logs for 7 days.
- The admin is single-owner: Cloudflare Access in front, plus the Worker verifying the Access
JWT, a 24-hour token age and an email allowlist on every request; every action is written to
an audit log.
See [`/legal/privacy`](https://poli0981.dev/legal/privacy/) for the full statement.
The hardening in place is described in
[`poli0981.dev-docs/06_SECURITY.md`](poli0981.dev-docs/06_SECURITY.md), and the privacy
statement at [`/legal/privacy`](https://poli0981.dev/legal/privacy/).
+14 -2
View File
@@ -94,8 +94,20 @@ build tools, likewise never shipped.
## Infrastructure services
Not packages — listed for transparency: Cloudflare (hosting, CDN, Turnstile), GitHub (source,
issues), and the public YouTube / Steam / GitHub data APIs used by the widgets worker.
Not packages — listed for transparency:
- **Cloudflare** — Workers and static assets (hosting, CDN), Workers KV (widget data, mirrored
widget images, the IP denylist, the admin audit log), R2 (images uploaded through the admin),
Images (one-time AVIF/WebP transforms), Rate Limiting, Turnstile (bot gate and bug-report
form), Access (the admin), Web Analytics (cookieless page views, production builds only) and
Workers Logs.
- **GitHub** — source code, the content repository, Actions CI, and issues in a private
repository for site bug reports.
- **Discord** — a webhook receiving bug-report notifications.
- **YouTube, Steam and GitHub public APIs** — read by the widgets cron worker; visitors' browsers
never call them (images are mirrored and served from the site).
- **SonarCloud, CodeQL, OSV-Scanner, Snyk** — code and dependency analysis in CI; nothing they do
reaches the running site.
## Fonts
+13 -8
View File
@@ -1,7 +1,8 @@
# poli0981.dev — Documentation Suite
- Phiên bản suite: **v1.0** · Ngày: 2026-07-17
- Repo: `poli0981/poli0981.dev` (private) · Domain: `poli0981.dev`
- Phiên bản suite: **v2.0** · Ngày: 2026-10-24 (v1.0: 2026-07-17)
- Repo: `poli0981/poli0981-dev` (**public** từ 10/2026) · nội dung: `poli0981/content` (submodule `src/content`) · Domain: `poli0981.dev`
- Lịch sử thay đổi theo phiên bản: `CHANGELOG.md` ở gốc repo.
- Ngôn ngữ tài liệu: tiếng Việt (thuật ngữ kỹ thuật giữ tiếng Anh). Riêng `12_LEGAL/` soạn song ngữ EN/VI vì là văn bản sẽ render trên site.
- Tài liệu gốc: `poli0981.dev_proposal.md` (bản đề xuất v0.1, đã được duyệt).
@@ -28,9 +29,9 @@
| 16 | 16_COST.md | Chi phí chốt + ngưỡng cần theo dõi |
| 17 | 17_MAINTENANCE.md | Lịch bảo trì, update playbook, backup |
`12_LEGAL/`: `TERMS_OF_USE.md` · `PRIVACY_POLICY.md` · `DISCLAIMER.md` · `THIRD_PARTY_NOTICES.md` · `CONTENT_LICENSE.md`
`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.
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-10-07)
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-10-24)
| # | Quyết định | Chọn |
|---|---|---|
@@ -47,12 +48,16 @@
| 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 |
| 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; token GitHub chỉ ghi repo content; ảnh → Images binding → R2 (`06` §9) |
| D10 | Data services | **KV** (cache widget, denylist) + **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/` |
| D15 | Admin | `admin.poli0981.dev` sau Cloudflare Access + Worker tự kiểm JWT (≤ 24 giờ, email phải có trong `ADMIN_EMAILS` — thiếu là từ chối); token GitHub chỉ ghi repo content; ảnh → Images binding → R2; mọi thao tác ghi audit log (`06` §9) |
| D10 | Data services | **KV** (cache widget + ảnh widget mirror cho `/ext-img`, denylist một khoá, audit log admin) + **R2** `poli0981-media` cho ảnh upload qua admin (từ 10/2026; AVIF/WebP sinh một lần lúc upload, phục vụ qua `/media`, cache 1 năm). Không D1. Ảnh build-time cũ vẫn ở `src/assets/` |
| D16 | Palette & theme (10/2026) | **Glacier Teal** (xanh đêm + teal) thay palette ấm; theme mặc định **theo hệ điều hành**, nút 3 trạng thái hệ thống/sáng/tối (`03` §2, §6) |
| D17 | Toolchain (10/2026) | Node 26 · TypeScript 7 (`tsc` kiểm kiểu) chạy song song TypeScript 6 (astro check, typescript-eslint, svelte2tsx cần JS API) · test bằng `node:test` (không thêm deps) · SonarCloud phân tích qua CI (`08` §0) |
| D18 | Báo lỗi (10/2026) | Issue tạo ở repo **private** `poli0981/site-reports` (repo site đã public) — `10` §4 |
| D19 | Phát hành | Tag `vX.Y.Z` có ký GPG + GitHub Release + `CHANGELOG.md`; deploy vẫn là "merge `main`" (`08` §8) |
## Cách dùng suite
1. Đọc `15_ROADMAP.md` trước — bắt đầu bằng 4 P0 spikes.
1. `15_ROADMAP.md` có trạng thái từng phase (P0–P3 đã xong, P4 launch đang chạy) và hướng đi tiếp.
2. `07_CLOUDFLARE_SETUP.md` làm một lần khi mua domain, tick checklist cuối file.
3. Mỗi file có mục **Trạng thái/Checklist** riêng khi áp dụng — suite này là nguồn sự thật, cập nhật khi quyết định thay đổi.
4. Lưu ý chung: mọi phiên bản package trong suite đã verify tới 2026-07-17; khi scaffold thực tế, lấy bản patch mới nhất trong cùng major.
4. Lưu ý chung: phiên bản package ghi trong suite là bản đang dùng tại 2026-10-24 (`02` §2); `package.json` + lockfile mới là nguồn sự thật.
+1 -1
View File
@@ -2,7 +2,7 @@
## 1. Sản phẩm
Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật ký + nơi viết truyện ngẫu hứng + hub cho kênh SkullMute**. Repo private, chi phí gần bằng 0, chạy trên hạ tầng Cloudflare đã có.
Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật ký + nơi viết truyện ngẫu hứng + hub cho kênh SkullMute**. Repo public (từ 10/2026; nội dung ở repo riêng `poli0981/content`, All Rights Reserved), chi phí gần bằng 0, chạy trên hạ tầng Cloudflare đã có.
## 2. Mục tiêu
+95 -62
View File
@@ -2,109 +2,139 @@
## 1. Tổng quan
Site **prerender tĩnh gần như toàn bộ** bằng Astro, deploy lên **Cloudflare Workers + Static Assets**. Một Worker chính phục vụ site + vài API route; một Worker phụ (`widgets`) chạy cron lấy dữ liệu YouTube/Steam/GitHub vào KV.
Site **prerender tĩnh gần như toàn bộ** bằng Astro, deploy lên **Cloudflare Workers + Static Assets**. Một Worker chính (`poli0981-dev`) phục vụ site, admin và vài API route; một Worker phụ (`poli0981-widgets`) chạy cron lấy dữ liệu YouTube/Steam/GitHub vào KV.
```
Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto)
Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Transform Rule x-verified-bot)
│
▼
Worker "site" (Astro adapter)
├── Static Assets (dist/) ── phần lớn request, FREE
├── /api/report ── Turnstile + rate-limit(KV) → GitHub Issue + Discord
└── middleware ── headers, denylist(KV) → 403, rate-limit → 429
▲ đọc
KV (widgets:*, denylist:*, rl:*)
▼ ghi
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / GitHub API
src/worker.ts — entry của Worker (assets.run_worker_first: mọi trang đều qua đây)
├── www → apex (301)
├── denylist IP (KV, một khoá "denylist", CIDR + hạn) → trang 403
├── 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)
├── middleware: admin (Access JWT + CSRF), rate limit /api, trang lỗi
├── /api/report · /api/gate · /api/widgets · /api/health
└── /admin/* + /api/admin/* (GitHub API → repo content, R2, Images, KV)
▲ đọc │ ghi
KV (widgets:*, denylist, audit:*) ◄───┘
▲ ghi
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / GitHub API (+ mirror ảnh)
```
## 2. Stack chốt (verify 2026-07-17)
Mọi response đi ra đều qua `withSecurityHeaders` (`src/lib/security-headers.ts`) và mang log JSON có cấu trúc (`src/lib/log.ts`: `event`, `ray`, `path`… — xem `06` §10).
## 2. Stack (đang dùng tại 2026-10-24)
| Thành phần | Bản | Ghi chú |
|---|---|---|
| Node.js | 24 LTS (`.nvmrc` = `24`) | engines: `>=24` |
| Astro | ^7.0.9 | CSP API + Fonts API built-in (stable từ v6) |
| @astrojs/cloudflare | ^14 | target Workers |
| @astrojs/mdx, sitemap, rss | mới nhất | |
| Svelte + @astrojs/svelte | ^5 | islands |
| Tailwind CSS | ^4.3 | CSS-first, `@theme` |
| GSAP | ^3.13 | free toàn bộ plugin |
| Node.js | 26 (`.nvmrc` = `26`, Workers Builds `NODE_VERSION=26`) | engines: `>=26` |
| Astro | ^7.4 | CSP API + Fonts API built-in |
| @astrojs/cloudflare | ^14.4 | target Workers; entry riêng `src/worker.ts` |
| @astrojs/mdx, sitemap, rss | ^8 · ^3 · ^4 | item RSS dựng ở `src/lib/rss.ts` (truyện chỉ mô tả + link) |
| Svelte + @astrojs/svelte | 5 + ^9.1 | islands |
| Tailwind CSS | ^4 | CSS-first, `@theme` |
| Pagefind | ^1 | chạy post-build |
| @vite-pwa/astro | mới nhất | chỉ offline fallback |
| Wrangler | ^4 | dev + deploy |
| TypeScript | mới nhất, strict | |
| Wrangler | ^4.152 | dev, types, smoke test, deploy tay |
| TypeScript | **7.0** (`@typescript/native` → `tsc`) + **6.0** (`typescript`) | TS7 kiểm kiểu nhanh (`npm run typecheck`), TS6 cho astro check / typescript-eslint / svelte2tsx (TS 7.0 chưa có JS API). `target`/`lib` = ES2025, `erasableSyntaxOnly` |
| Test | `node:test` của Node 26 | không thêm deps; `module.registerHooks` giả lập `astro:*`/`cloudflare:workers`; coverage lcov cho SonarCloud |
| jose · marked · yaml · zod | ^6 · ^18 · ^2 · ^4 | Access JWT · preview admin · frontmatter · schema |
## 3. Cấu trúc repo
```
poli0981.dev/
├── docs/ # suite này
├── public/ # favicon, robots.txt, security.txt, offline assets
├── scripts/ # strip-exif.mjs, check-exif.mjs, gen-notices.mjs
poli0981-dev/
├── poli0981.dev-docs/ # suite này
├── docs/templates/ # khung bài mới (npm run new:post)
├── public/ # favicon, robots.txt, security.txt, sw.js, gate.js, skullhop.js
├── scripts/ # gen-og, gen-notices, check-exif/strip-exif, check-csp-hashes,
│ # check-install-scripts, smoke-worker, new-post
├── src/
│ ├── worker.ts # entry: denylist, host, /media, /ext-img, cổng, assets
│ ├── middleware.ts # admin JWT + CSRF, rate limit /api, trang lỗi
│ ├── assets/ # ảnh qua pipeline Astro (gallery/, covers/)
│ ├── components/ # .astro + islands .svelte
│ ├── content/ # collections (xem 04)
│ ├── i18n/ # vi.ts, en.ts + helper t()
│ ├── layouts/ # Base, Post, StoryReader, Legal
│ ├── middleware.ts # headers, denylist, rate-limit
│ ├── pages/ # routes + /en/* + api/report.ts + 404/500
│ └── styles/ # global.css (@theme tokens)
│ │ ├── pages/ # thân trang dùng chung vi/en (route chỉ là wrapper)
│ │ └── admin/ # islands của admin
│ ├── content/ # submodule poli0981/content (xem 04)
│ ├── i18n/ # vi.ts, en.ts, routing.ts
│ ├── layouts/ # Base, Post, StoryReader, Project, Error, Admin
│ ├── lib/ # gate/, admin/, media/, denylist, ext-img, log, version, palette, theme…
│ ├── pages/ # routes + /en/* + api/* + admin/* + 403/404/429/500
│ └── styles/ # global.css (token), prose.css, admin.css
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/GitHub…)
├── workers/widgets/ # worker cron riêng (wrangler.jsonc riêng)
├── .github/ # workflows caller, ISSUE_TEMPLATE, dependabot.yml
├── astro.config.mjs · wrangler.jsonc · lefthook.yml · knip.json
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, 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
```
## 4. Rendering & routing
- Mặc định **prerender: true** toàn site. Chỉ `src/pages/api/*` và middleware chạy on-demand trên Worker.
- Mặc định **prerender** toàn site. Chạy on-demand trên Worker: `src/pages/api/*`, `src/pages/admin/*` và middleware.
- **i18n** (Astro built-in): `defaultLocale: 'vi'`, `locales: ['vi','en']`, không prefix cho vi → `/blog/...` và `/en/blog/...`. UI string trong `src/i18n/`, nội dung theo `lang` frontmatter (xem 04 §4).
- View Transitions bật toàn site; fallback bình thường cho trình duyệt cũ.
- 404: `src/pages/404.astro` (+ bản `/en/404`); cấu hình assets `not_found_handling: "404-page"`.
- **Một thân trang cho hai ngôn ngữ**: route vi và en chỉ là wrapper gọi component trong `src/components/pages/` với `locale` (và props từ builder `getStaticPaths` trong `src/lib/pages.ts`).
- Nút đổi ngôn ngữ: trang có bản dịch (`translationKey`) → đúng bản dịch; không có → mục tương ứng của ngôn ngữ kia (`sectionFallbackPath`), không bao giờ 404.
- Truyện: chương thuộc series → `/truyen/<series>/<slug>/`; truyện lẻ (không có thư mục series) → `/truyen/<slug>/`.
- 404: `src/pages/404.astro`; cấu hình assets `not_found_handling: "404-page"`.
## 5. Worker "site" — wrangler.jsonc (khung)
## 5. Worker "site" — wrangler.jsonc (rút gọn)
```jsonc
{
"name": "poli0981-dev",
"compatibility_date": "2026-07-01",
"compatibility_date": "2026-10-15",
"compatibility_flags": ["nodejs_compat"],
// "main" + "assets" do `astro add cloudflare` sinh — giữ nguyên giá trị adapter tạo
"assets": { "binding": "ASSETS", "directory": "./dist" },
"kv_namespaces": [{ "binding": "KV", "id": "<id>" }],
"observability": { "enabled": true },
"routes": [{ "pattern": "poli0981.dev", "custom_domain": true }]
"main": "./src/worker.ts",
"workers_dev": false, "preview_urls": false,
"assets": { "binding": "ASSETS", "directory": "./dist", "not_found_handling": "404-page",
"html_handling": "auto-trailing-slash", "run_worker_first": ["/*", "!/_astro/*", "…"] },
"kv_namespaces": [{ "binding": "KV", "id": "…" }],
"ratelimits": [ RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ],
"vars": { "GATE_MODE": "on", "ACCESS_TEAM_DOMAIN": "…", "ACCESS_AUD": "…", "REPORT_REPO": "poli0981/site-reports" },
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "poli0981-media" }],
"images": { "binding": "IMAGES" },
"version_metadata": { "binding": "CF_VERSION_METADATA" },
"observability": { "enabled": true, "redact_query_string": true,
"logs": { "enabled": true, "invocation_logs": true }, "traces": { "enabled": true, "head_sampling_rate": 0.1 } }
}
```
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit): `TURNSTILE_SECRET`, `GITHUB_ISSUES_TOKEN` (fine-grained PAT, chỉ Issues R/W repo này), `DISCORD_WEBHOOK_BUG`.
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng đầy đủ ở `06` §4): `TURNSTILE_SECRET`, `GATE_SECRET`, `GITHUB_ISSUES_TOKEN`, `DISCORD_WEBHOOK_BUG`, `GITHUB_CONTENT_TOKEN`, `GITHUB_PUBLISH_TOKEN`, `ADMIN_EMAILS`.
`/api/health` trả `version` (id bản Worker đang chạy + commit đã build, từ `version_metadata` và `__BUILD_COMMIT__`) — dùng để xác minh deploy từ bên ngoài.
## 6. Worker "widgets" (workers/widgets/)
- Riêng biệt để không đụng entry Astro sinh ra; cron `"*/45 * * * *"`.
- Bind cùng KV namespace (quyền ghi); secrets: `STEAM_API_KEY`, `STEAM_ID64`.
- Chi tiết nguồn dữ liệu + schema KV: `11_WIDGETS_INTEGRATIONS.md`.
- Riêng biệt để không đụng entry của site; cron `"*/45 * * * *"`; không có `package.json` (không deps).
- Bind cùng KV namespace (quyền ghi); secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`.
- Ngoài dữ liệu, worker **mirror ảnh thumbnail/icon vào KV** (`widgets:img:*`, ≤ 2 MB, 14 ngày) để site phục vụ qua `/ext-img/*` — khách không gọi Google/Steam trước khi bấm.
- Deploy tay: `npx wrangler deploy --config workers/widgets/wrangler.jsonc`. Chi tiết: `11_WIDGETS_INTEGRATIONS.md`.
## 7. Setup dự án (một lần)
## 7. Setup máy dev (một lần)
```bash
nvm use 24
npm create cloudflare@latest -- poli0981.dev --framework=astro
cd poli0981.dev
npx astro add svelte tailwind mdx sitemap cloudflare
npm i -D pagefind knip lefthook eslint prettier prettier-plugin-astro \
prettier-plugin-tailwindcss typescript-eslint eslint-plugin-astro eslint-plugin-svelte
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
cd poli0981-dev
nvm use # đọc .nvmrc = 26
npm ci --ignore-scripts && npm run check-install-scripts
npx lefthook install
npm run types && npm run types:widgets
npm run dev # astro dev trên workerd (bindings local); admin dùng danh tính giả dev@localhost
```
Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR description; mỗi gói mới phải qua `npm audit` + Dependabot theo dõi; cập nhật `THIRD-PARTY-NOTICES.md` bằng `scripts/gen-notices.mjs` trong CI.
Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR description; mỗi gói mới phải qua `npm audit` + Dependabot theo dõi; `THIRD-PARTY-NOTICES.md` sinh bằng `scripts/gen-notices.mjs` và CI kiểm lệch.
## 8. Chính sách phiên bản & CVE
- Pin `^` trong cùng major; Dependabot mở PR patch/minor hằng tuần.
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + preview.
- Nền tảng CVE đã kiểm tra khi chốt stack: chuỗi CVE Astro 2026 (XSS `define:vars`, server-islands, slot-name, SSRF image) đều đã vá trước 7.0.9; các CVE thuộc adapter node/vercel không áp dụng (dùng adapter cloudflare). Quy trình theo dõi tiếp: `06_SECURITY.md` §6.
- Pin `^` trong cùng major; Dependabot mở PR patch/minor hằng tuần (cooldown 3 ngày — `08` §6).
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + preview (`17` §2).
- **TypeScript 7**: `@typescript/native` là alias `npm:typescript@7` — Dependabot bỏ qua alias `npm:`, nên nâng tay; `typescript` (bản 6) giữ đến khi TS 7.1 có JS API cho astro check / typescript-eslint / svelte2tsx, lúc đó gộp về một bản.
- Theo dõi CVE liên tục: Dependabot alerts, `npm audit` (CI), OSV-Scanner, Snyk, CodeQL, SonarCloud (`06` §6).
## 9. ADR (Architecture Decision Records — rút gọn)
@@ -114,7 +144,10 @@ Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR descriptio
| 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 | Xuất hiện nhu cầu dữ liệu động thật |
| 06 | GPL-3.0 code / ARR content | Nhất quán hệ sinh thái repo; truyện & ảnh cần bảo hộ chặt | Mở public repo → cân nhắc thêm |
| 08 | Logic edge ở worker entry (`src/worker.ts`) | Trang tĩnh được adapter phục vụ trước middleware ⇒ cổng Turnstile, `/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 |
| 05 | Không D1/Sentry | Q&A form bị bỏ; bug report đi thẳng GitHub+Discord; lỗi runtime xem ở Workers Logs (log JSON) | Xuất hiện nhu cầu dữ liệu động thật |
| 06 | GPL-3.0 code / ARR content | Nhất quán hệ sinh thái repo; truyện & ảnh cần bảo hộ chặt | — |
| 07 | Error pages tự phục vụ | Custom Errors của Cloudflare cần zone plan trả phí; site chạy trên Worker nên tự làm được | Nếu một ngày mua Pro vì lý do khác |
| 08 | Logic edge ở worker entry (`src/worker.ts`) | Trang tĩnh được adapter phục vụ trước middleware ⇒ cổng Turnstile, denylist, `/media`, chuyển host, security headers phải nằm ở entry + `assets.run_worker_first` | Adapter có hook chính thức cho trang tĩnh |
| 09 | TypeScript 7 song song TypeScript 6 (10/2026) | `tsc` 7 nhanh hơn nhiều cho kiểm kiểu; công cụ hệ sinh thái chưa chạy được trên TS 7.0 (không có JS API) | TS 7.1 có API mới |
| 10 | `node:test` + SonarCloud thay Vitest (10/2026) | Không thêm deps; Node 26 chạy thẳng TypeScript, `registerHooks` giả lập module ảo; lcov cho quality gate | Cần test component trong DOM thật |
| 11 | Palette Glacier Teal + theme theo hệ điều hành (10/2026) | Tông lạnh theo yêu cầu chủ site; mọi cặp màu kiểm WCAG AA bằng test; một nguồn màu `src/lib/palette.ts` | Đổi nhận diện |
+52 -30
View File
@@ -1,36 +1,48 @@
# 03 — Design System: "Phòng đọc lúc nửa đêm"
# 03 — Design System: "Phòng đọc lúc nửa đêm" — Glacier Teal
## 1. Concept
SkullMute = âm thanh bị tắt có chủ đích. Site mang cảm giác **phòng đọc tối, ấm, chỉ có ngọn đèn bàn** — tĩnh lặng, không neon cyberpunk, không portfolio template. Boldness dồn vào **một** signature (Waveline §5); mọi thứ còn lại kỷ luật và yên tĩnh.
SkullMute = âm thanh bị tắt có chủ đích. Site mang cảm giác **phòng đọc lúc nửa đêm** — tĩnh lặng, không neon cyberpunk, không portfolio template. Boldness dồn vào **một** signature (Waveline §5); mọi thứ còn lại kỷ luật và yên tĩnh.
## 2. Màu (token trong `@theme` của Tailwind v4)
Từ 10/2026 (v2.0) palette chuyển từ "ngọn đèn bàn" ấm sang **Glacier Teal**: nền xanh đêm, chữ trắng lạnh, accent teal như ánh màn hình. Bản sáng là "băng ban ngày" — trắng xanh nhạt, accent teal đậm. Tinh thần giữ nguyên: một màu nhấn, phần còn lại im lặng.
### Dark — mặc định ("mực đêm")
## 2. Màu — nguồn và quy tắc
Token runtime khai báo trong `src/styles/global.css` (khối `:root, [data-theme="dark"]` và `[data-theme="light"]`), sinh utility Tailwind qua `@theme inline`. **`src/lib/palette.ts` giữ cùng giá trị** cho code ngoài CSS (meta `theme-color`, ảnh OG, easter egg). `tests/palette.test.ts` fail khi hai nơi lệch nhau hoặc khi một cặp chữ/control dưới chuẩn: chữ (text, muted, accent, accent-strong, horror, ok, warn, err) ≥ 4.5:1 trên `bg`/`surface`/`elevated`; `line-strong` ≥ 3:1 (WCAG 1.4.11); `accent-contrast` trên `accent` ≥ 4.5:1.
### Dark — "glacier night" (mặc định khi không có JS)
| Token | Hex | Dùng cho |
|---|---|---|
| `--color-bg` | `#0D1117` | nền trang |
| `--color-surface` | `#12161F` | card, header |
| `--color-elevated` | `#1A2030` | modal, hover card |
| `--color-line` | `#242B38` | border, divider |
| `--color-text` | `#E9E4D8` | chữ chính (ngà ấm) |
| `--color-muted` | `#98A0AE` | meta, caption |
| `--color-accent` | `#E8A33D` | link, CTA, "ánh đèn bàn" |
| `--color-accent-strong` | `#F4B860` | hover/focus của accent |
| `--color-horror` | `#8C2F39` | tag horror, content-warning |
| `--bg` | `#0B1220` | nền trang, `theme-color` |
| `--surface` | `#0F192A` | card, header |
| `--elevated` | `#16233A` | modal, menu, toast |
| `--line` | `#223047` | border trang trí, divider |
| `--line-strong` | `#5B6F8F` | viền control (input, nút) — ≥ 3:1 |
| `--text` | `#E6EDF5` | chữ chính |
| `--muted` | `#94A3B8` | meta, caption |
| `--accent` | `#2DD4BF` | link, CTA, focus ring |
| `--accent-strong` | `#5EEAD4` | hover/focus của accent |
| `--accent-contrast` | `#042F2E` | chữ trên nền accent (selection, nút primary) |
| `--horror` | `#FB7185` | tag horror, content-warning |
| `--ok` / `--warn` / `--err` | `#34D399` / `#FBBF24` / `#F87171` | trạng thái |
| `--overlay` · `--shadow-color` | `rgb(2 6 23 / .66)` · `rgb(0 0 0 / .45)` | backdrop modal · bóng elevated |
### Light — "trang giấy cũ" (ưu tiên cho reading mode)
### Light — "glacier day"
| Token | Hex | Ghi chú |
|---|---|---|
| bg `#F5EFE2` · surface `#FFFDF7` · line `#E2D9C5` | | |
| text `#26221A` · muted `#6E6757` | | |
| accent `#9A6414` | accent phải **đậm hơn** bản dark để đạt AA trên nền sáng |
| Token | Hex |
|---|---|
| bg `#F4F8FB` · surface `#FFFFFF` · elevated `#FFFFFF` · line `#D6E0EA` · line-strong `#7C8CA3` | |
| text `#0F1B2D` · muted `#4A5A70` | |
| accent `#0F766E` · accent-strong `#115E59` · accent-contrast `#FFFFFF` | accent đậm hơn bản dark để đạt AA trên nền sáng |
| horror `#BE123C` · ok `#047857` · warn `#B45309` · err `#B91C1C` | |
| overlay `rgb(15 27 45 / .42)` · shadow-color `rgb(15 27 45 / .14)` | |
Quy tắc contrast: text/bg ≥ 7:1, muted ≥ 4.5:1, accent-làm-chữ ≥ 4.5:1 — kiểm tra bằng tooling khi chốt hex cuối (giá trị trên là điểm xuất phát, được phép tinh chỉnh ±10% lightness, không đổi hue).
### Palette riêng theo vùng
Semantic phụ: `--color-ok #4C9A6A`, `--color-warn #C9822B`, `--color-err #C24A4A` (dùng ít).
- **Lớp đọc truyện** (`ReadingControls`): "Giấy" = palette sáng, "Tối" = palette tối (global.css áp cùng khối token cho `[data-reader-theme="paper|dark"]`), "Sepia" là palette ấm riêng trong `StoryReaderLayout.astro` (cũng được test AA).
- **Lightbox** luôn dùng palette tối (`data-theme="dark"` trên chính nó) — ảnh xem tốt nhất trên nền tối.
- **Ảnh OG** (`scripts/gen-og.mjs`) và favicon dùng palette tối.
## 3. Typography (đều có subset `vietnamese` — P0 Spike 2 phải test dấu trên máy thật)
@@ -60,13 +72,13 @@ Type scale (fluid, mobile 360px → desktop 1280px):
## 4. Spacing / hình khối
- Space scale 4px: 1,2,3,4,6,8,12,16,24,32 (×4px). Section padding: `clamp(3rem, 8vw, 6rem)`.
- Radius: 6 (control) / 10 (card) / 16 (modal). Border 1px `--color-line`; shadow chỉ ở elevated, tối và mềm (`0 8px 30px rgb(0 0 0 / .35)`).
- Radius: 6 (control) / 10 (card) / 16 (modal). Border 1px `--line` (trang trí) hoặc `--line-strong` (control); shadow chỉ ở elevated: `--shadow-elevated` = `0 8px 30px var(--shadow-color)`.
- Grain: overlay noise PNG 2–3% opacity toàn trang (một element `body::after`, `pointer-events:none`). Khu `/gaming` được phép thêm scanline 2% — nơi duy nhất.
- Layout: container 72rem; trang chủ dùng lưới 12 cột với 1–2 phần tử cố ý lệch/đè (hero title đè lên Waveline) — bất đối xứng có kiểm soát, không "mọi thứ đều nghiêng".
## 5. Signature — Waveline (motif "sóng âm bị tắt")
- Một đường SVG ngang 1.5px màu `--color-line`, giữa có đoạn `--color-accent`.
- Một đường SVG ngang 1.5px màu `--line`, giữa có đoạn `--accent`.
- **Idle**: flatline. **Hover/scroll-into-view**: 1.2s "sống dậy" thành waveform 5–7 nhịp (path morph hoặc `stroke-dashoffset` + `d` keyframes bằng GSAP) rồi tắt về flatline — đúng một nhịp, không loop.
- Xuất hiện tại: hero (dưới tagline), divider giữa section, footer. **Không** dùng trong card/list.
- `prefers-reduced-motion`: luôn flatline tĩnh.
@@ -83,6 +95,12 @@ Type scale (fluid, mobile 360px → desktop 1280px):
Nguyên tắc: **một** khoảnh khắc dàn dựng khi load trang chủ; còn lại là micro-interaction. GSAP chỉ nạp ở island nào cần (Waveline, hero) — không nạp global. Mọi animation phải có nhánh reduced-motion.
### Theme (sáng/tối/theo hệ thống)
- Lựa chọn lưu ở `localStorage.theme` (`light`/`dark`; không có = **theo hệ thống**). Bootstrap inline trong `<head>` (`src/lib/theme.ts`, được hash vào CSP) đặt `data-theme-pref` (lựa chọn) và `data-theme` (palette đang hiện) trước first paint, và nghe `prefers-color-scheme` để đổi theo hệ điều hành khi đang ở chế độ hệ thống.
- `ThemeToggle` xoay vòng hệ thống → sáng → tối; icon chọn bằng CSS theo `data-theme-pref` nên đúng ngay trước khi island hydrate. Khi ghim sáng/tối, hai thẻ `meta[name=theme-color]` cùng trỏ màu nền đã chọn để thanh trình duyệt khớp trang.
- Không có JS: trang hiện bản tối.
### Thanh cuộn
Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai báo trong từng palette (`global.css`), pha từ `--muted`/`--accent` với `--bg` bằng `color-mix(in oklab, …)`: thumb ≥ 3:1 so với nền (dark: muted 65%, light: muted 75%). `scrollbar-color` (kế thừa) cho mọi vùng cuộn; `scrollbar-width: thin` khi trình duyệt hỗ trợ `scrollbar-color`, còn Safari dùng nhánh `::-webkit-scrollbar`. Tuỳ chọn "Ẩn thanh cuộn" chỉ ẩn thanh của trang (vẫn cuộn bằng chuột/phím); vùng cuộn con giữ thanh mảnh.
@@ -91,15 +109,16 @@ Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai
| Component | Loại | Ghi chú |
|---|---|---|
| Header / MobileTabBar / Footer | .astro | TabBar: Home·Blog·Truyện·Menu, ẩn ≥768px |
| ThemeToggle, LangSwitch | island nhỏ | localStorage `theme`, link hreflang cho lang |
| 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 |
| Prose | style | typography cho nội dung md |
| Prose | .astro + `src/styles/prose.css` | typography cho nội dung md; cùng stylesheet dùng cho preview trong admin |
| ReadingControls | island | cỡ chữ (3 mức, localStorage `reader`), theme giấy/sepia/tối, progress bar 2px |
| ContentWarning | .astro | banner `--color-horror`, bấm để mở nội dung |
| Lightbox | island | vuốt được, lazy |
| SearchModal | island | Pagefind UI, mở bằng `/` hoặc nút |
| ContentWarning | .astro | banner `--horror`, bấm để mở nội dung |
| 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) |
@@ -110,4 +129,7 @@ Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai
- Focus ring rõ (2px accent, offset 2px), điều hướng bàn phím đủ; skip-link.
- Touch target ≥ 44×44; `safe-area-inset` cho TabBar; không hover-only cho thông tin.
- Ảnh có alt (bắt buộc trong schema gallery); icon-only button có `aria-label`.
- Kiểm tra 360px, 390px, 768px, 1280px; dark/light; vi/en (chuỗi EN thường dài hơn ~20%).
- 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%).
- 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.
+1 -1
View File
@@ -103,7 +103,7 @@ Tiện ích khuyến nghị: snippet VS Code cho từng frontmatter; `npm run ne
- Ảnh nội dung đặt trong `src/assets/` để Astro Image tự sinh AVIF/WebP + srcset; **không** bỏ ảnh content vào `public/`.
- **Chính sách EXIF**: mọi ảnh chụp (đặc biệt gallery kỷ niệm) phải qua `node scripts/strip-exif.mjs <folder>` (sharp: re-encode, bỏ toàn bộ metadata) **trước khi commit**.
- Chốt chặn CI: `scripts/check-exif.mjs` quét ảnh thay đổi trong PR, thấy GPS/serial → **fail build**. (Repo đang private nhưng ảnh build ra là public — strip từ gốc.)
- Chốt chặn CI: `scripts/check-exif.mjs` quét ảnh thay đổi trong PR, thấy GPS/serial → **fail build**. (Repo public và ảnh build ra cũng public — strip từ gốc; `check-exif` đọc bytes thật, file không đọc được cũng tính là lỗi.)
- Kích thước: ảnh gốc ≤ 2560px cạnh dài, ≤ 1.5MB sau strip. Khi tổng `src/assets/gallery/` > ~1GB → kích hoạt phương án R2 (`17` §5).
### 6b. Ảnh R2 (upload qua admin)
+4 -2
View File
@@ -8,13 +8,15 @@
| `/about` | `/en/about` | md đơn |
| `/projects`, `/projects/[slug]` | `/en/...` | collection projects |
| `/blog`, `/blog/[slug]`, `/blog/tag/[tag]` | `/en/...` | blog |
| `/truyen`, `/truyen/[series]/[slug]` | `/en/stories/...` | stories |
| `/truyen`, `/truyen/[series]/[slug]`, `/truyen/[slug]` (truyện lẻ) | `/en/stories/...` | stories |
| `/gallery`, `/gallery/[album]` | `/en/...` | gallery |
| `/gaming` · `/dev` (kèm `/dev/uses`) | `/en/...` | md + widgets |
| `/qa` · `/links` | `/en/...` | faq + data links |
| `/legal/{terms,privacy,disclaimer,third-party,licenses}` | `/en/legal/...` | 12_LEGAL |
| `/legal/{terms,privacy,disclaimer,third-party,licenses,ai-usage}` | `/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 |
| `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)
+62 -41
View File
@@ -2,40 +2,44 @@
Mức đe doạ thực tế của site cá nhân: bot spam form, scraper, script-kiddie quét lỗ hổng, thi thoảng một đợt flood. Thiết kế dưới đây "vừa đủ" cho mức đó — không zero-trust enterprise.
## 1. HTTP headers (middleware `src/middleware.ts`, áp cho mọi response HTML)
## 1. HTTP headers (`src/lib/security-headers.ts`, gắn ở worker entry cho mọi response)
| Header | Giá trị |
|---|---|
| Content-Security-Policy | Dùng **CSP API built-in của Astro** (stable từ v6, bật trong `astro.config`) — tự hash script/style của build. Bổ sung directive thủ công: `img-src 'self' data: https://i.ytimg.com; frame-src https://www.youtube-nocookie.com; connect-src 'self'; script-src` thêm **`'wasm-unsafe-eval'`** (Pagefind chạy WebAssembly — thiếu là search chết, xem P0 Spike 4); `frame-ancestors 'none'`; `base-uri 'none'`; `form-action 'self'` |
| Strict-Transport-Security | `max-age=31536000; includeSubDomains; preload` (TLD .dev vốn nằm trong HSTS preload — header để nhất quán) |
| X-Content-Type-Options | `nosniff` |
| Content-Security-Policy (meta) | **CSP API built-in của Astro** — tự hash mọi script/style của build (cả bootstrap theme inline, `src/lib/theme.ts`). Directive thêm: `img-src 'self' data:` (ảnh widget đi qua `/ext-img`, không còn host ngoài); `frame-src` YouTube nocookie + Turnstile; `connect-src 'self'` + Turnstile + Web Analytics; `script-src` thêm **`'wasm-unsafe-eval'`** (Pagefind); `base-uri 'none'`; `form-action 'self'`; `object-src 'none'`. `scripts/check-csp-hashes.mjs` (sau build) fail nếu một script inline thiếu hash hoặc không trang nào được kiểm |
| Content-Security-Policy (header) | `frame-ancestors 'none'` — directive này không có hiệu lực trong meta nên đi bằng header; hai CSP cộng dồn, không ghi đè hash |
| Strict-Transport-Security | `max-age=31536000; includeSubDomains; preload` |
| X-Content-Type-Options · X-Frame-Options | `nosniff` · `DENY` |
| Referrer-Policy | `strict-origin-when-cross-origin` |
| Permissions-Policy | `camera=(), microphone=(), geolocation=(), payment=(), usb=()` |
| Cross-Origin-Opener-Policy | `same-origin` |
| Cross-Origin-Opener-Policy | `same-origin` (admin thêm `Cross-Origin-Resource-Policy: same-origin`) |
Không đặt COEP (không cần SharedArrayBuffer; đặt sẽ vỡ embed YouTube).
## 2. Middleware — denylist & rate limit (trả trang lỗi custom của mình)
## 2. Denylist IP & rate limit
```
request → IP = cf-connecting-ip
1. KV get denylist:<ip> → có ⇒ 403 (trang 09 §2)
2. nếu path bắt đầu /api/<group>:
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>:
Workers Rate Limiting binding theo nhóm (src/lib/ratelimit.ts), khoá "<group>:<ip>"
(IPv6 gộp theo /64):
report → RL_REPORT 5/60s · gate → RL_GATE 30/60s · admin → RL_ADMIN 120/60s
còn lại → RL_API 120/60s · widgets → không giới hạn (cache edge 5 phút)
vượt ⇒ 429 + Retry-After: 60 (trang 09 §2)
3. tiếp tục; gắn headers §1 vào response
```
- Binding đếm **theo từng colo** (không toàn cục) và chỉ cho `period` 10 hoặc 60 s → đây là lớp mềm chống lạm dụng; lớp cứng là zone rate-limit rule (07 §6). Không còn ghi KV cho mỗi request API (bộ đếm KV cũ đọc-rồi-ghi, không nguyên tử, và có thể ném lỗi khi burst vì KV chỉ cho ~1 ghi/giây/khoá).
- `namespace_id` của mỗi binding chỉ cần duy nhất trong account (981001–981004).
- Quản lý denylist: `wrangler kv key put --binding=KV "denylist:1.2.3.4" "spam 2026-08"` — kèm ghi chú lý do. Khoá chỉ khớp **đúng IP**; chặn dải (CIDR), quốc gia hay ASN thì dùng WAF IP List / zone custom rule (07 §7) vì middleware chỉ nên giữ list ngắn.
- Một khoá thay vì `denylist:<ip>`: tra cứu tốn như nhau dù IP nào hỏi (một lần đọc/phút/isolate) và chặn được cả dải. Quản lý ở **admin → Bảo mật** (`/admin/security/`): thêm kèm lý do + thời hạn (1 giờ … 30 ngày, hoặc đến khi gỡ), gỡ, có audit log. Không cho chặn dải chứa IP của chính admin — danh sách áp cho mọi host, kể cả admin. Thay đổi có hiệu lực trong khoảng một phút.
- Binding rate limit đếm **theo từng colo** 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).
- Chặn quốc gia/ASN hay danh sách rất dài: dùng WAF custom rule / IP List (07 §7).
## 3. Form duy nhất: /api/report (bug)
Turnstile bắt buộc → verify `siteverify` với `TURNSTILE_SECRET` → validate payload bằng Zod (đúng schema `10` §3, size ≤ 32KB) → rate limit §2 → xử lý. Sai bất kỳ bước nào: 400/403/429, message chung chung, không lộ chi tiết.
Rate limit §2 → body đọc có trần **32 KB** (khai `Content-Length` lớn hơn hoặc stream vượt ⇒ 413, không đọc hết) → validate Zod (`10` §3) → Turnstile `siteverify` (`success` + `action: "report"` + `hostname`) → issue ở repo **private** `poli0981/site-reports` + Discord (`allowed_mentions` rỗng, `@mention` trong nội dung bị vô hiệu) — mỗi lời gọi ra ngoài có timeout 10 s. Sai bất kỳ bước nào: 400/413/429, message chung chung, không lộ chi tiết.
Các API khác cũng có trần body: `/api/gate` 8 KB; JSON của admin 512 KB và bắt buộc `Content-Type: application/json`; upload ảnh 20 MB (từ chối theo `Content-Length` trước khi parse form).
## 3b. Cổng Turnstile trước mọi trang (`src/lib/gate/`, `src/worker.ts`)
@@ -59,7 +63,8 @@ gate.js → Turnstile (action "gate") → POST /api/gate (RL_GATE, Sec-Fetch-Sit
- Đứng ngoài cổng ngay ở tầng asset (không gọi Worker): `/_astro/*`, `/og/*`, favicon, `sw.js`, `skullhop.js`, `gate.js`, `/offline*`, robots, sitemap, RSS, `/.well-known/*` — xem `run_worker_first` trong `wrangler.jsonc`.
- Giữ `<head>` thật ⇒ preview link (kể cả bot không "verified" như Zalo) vẫn đúng title/ảnh; trả **200** vì nhiều bot preview bỏ qua mã khác 2xx.
- Vé chỉ chứa hạn + nonce + chữ ký, không định danh; đổi `GATE_SECRET` ⇒ mọi vé cũ mất hiệu lực ngay.
- Vé chỉ chứa hạn + nonce + chữ ký (43 ký tự base64url), không định danh; đổi `GATE_SECRET` ⇒ mọi vé cũ mất hiệu lực ngay.
- **Fail-closed**: cookie sai định dạng (vd. chữ ký base64 lệch độ dài) bị coi như không có vé; nếu chính bước quyết định/vẽ cổng ném lỗi ⇒ 503 + `Retry-After`, **không bao giờ** trả trang thật (lỗi bypass 10/2026 — có test hồi quy và bước smoke riêng).
- **Kill switch**: đặt `GATE_MODE` về `"off"` trong `wrangler.jsonc` (deploy) — hoặc sửa biến trên dashboard để tắt tức thì (lần deploy sau sẽ ghi đè).
- Test: `npm test` (cookie/chính sách) + `npm run smoke` (pha 2 ép cổng bằng secret test của Turnstile, chạy trọn luồng).
@@ -67,24 +72,31 @@ gate.js → Turnstile (action "gate") → POST /api/gate (RL_GATE, Sec-Fetch-Sit
| Secret | Nơi | Phạm vi |
|---|---|---|
| TURNSTILE_SECRET | worker site | — |
| GITHUB_ISSUES_TOKEN | worker site | Fine-grained PAT: **chỉ repo này, chỉ Issues R/W**, hạn 1 năm, đặt lịch xoay ở `17` |
| TURNSTILE_SECRET | worker site | form báo lỗi + cổng |
| GATE_SECRET | worker site | ký vé cổng (≥ 32 byte ngẫu nhiên) |
| GITHUB_ISSUES_TOKEN | worker site | Fine-grained PAT: **chỉ repo `poli0981/site-reports`, chỉ Issues R/W**, hạn ≤ 1 năm |
| DISCORD_WEBHOOK_BUG | worker site | webhook 1 kênh riêng |
| STEAM_API_KEY, STEAM_ID64 | worker widgets | key Steam mặc định |
| CLOUDFLARE_API_TOKEN | GitHub Actions secret | scope Workers Scripts:Edit + account đúng (07 §10) |
| GITHUB_CONTENT_TOKEN | worker site | Fine-grained PAT: **chỉ `poli0981/content`, Contents R/W** (admin lưu bài) |
| GITHUB_PUBLISH_TOKEN | worker site | Fine-grained PAT: **chỉ `poli0981/poli0981-dev`, Actions R/W** (nút Xuất bản). Thiếu ⇒ admin dùng tạm token nội dung và cảnh báo "một token" |
| ADMIN_EMAILS | worker site | email được vào admin, phân cách dấu phẩy — **bắt buộc**, thiếu là không ai vào được |
| STEAM_API_KEY, STEAM_ID64, DISCORD_WEBHOOK_CI | worker widgets | key Steam mặc định; webhook cảnh báo cron |
| GITHUB_TOKEN (tuỳ chọn) | worker widgets | fine-grained PAT **không quyền nào** (chỉ đọc dữ liệu public) — nâng hạn mức API events từ 60/giờ/IP (IP egress của Workers dùng chung, hay bị 403) |
| SONAR_TOKEN | GitHub Actions secret | phân tích SonarCloud (`08` §0) |
Không secret nào trong repo/`wrangler.jsonc`; `.dev.vars` nằm trong `.gitignore`.
Không secret nào trong repo/`wrangler.jsonc`; `.dev.vars` nằm trong `.gitignore`. Admin chỉ hiện **tên** secret đã/chưa đặt (`/admin/security/`), không bao giờ hiện giá trị.
`wrangler secret put` tạo một version mới dựa trên version **mới nhất** đã upload và deploy nó ngay: chỉ đặt secret khi version mới nhất là bản của `main` (không phải bản preview của một PR) — kiểm bằng `wrangler versions list` trước.
## 5. Nội dung nhúng bên thứ ba
- YouTube: **click-to-load facade** (thumb tĩnh từ i.ytimg.com) → bấm mới tạo iframe `youtube-nocookie.com`. Vừa nhanh vừa gọn Privacy Policy.
- 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` nên tải trễ, không cookie, chỉ có trong bản build production của Workers Builds (`src/components/CfBeacon.astro`). CSP mở đúng 2 host đó (`script-src` + `connect-src`). Còn lại: không font/CDN/script ngoài — mọi asset self-host.
- YouTube: **click-to-load facade** — thumbnail do worker widgets mirror vào KV và site phục vụ qua `/ext-img/yt/<id>` (icon Steam qua `/ext-img/steam/…`), nên trình duyệt khách **không gọi** `i.ytimg.com`/Steam trước khi bấm; bấm mới tạo iframe `youtube-nocookie.com`. `/ext-img` chỉ nhận đúng 2 mẫu đường dẫn, chỉ đọc KV (không bao giờ fetch theo yêu cầu của khách), trả kèm `CSP: sandbox`.
- Ngoại lệ duy nhất cho script bên ngoài: beacon Cloudflare Web Analytics (`static.cloudflareinsights.com`, báo về `cloudflareinsights.com`) — `type=module`, không cookie, chỉ có trong bản build production của Workers Builds (`src/components/CfBeacon.astro`). Turnstile chỉ tải khi trang xác minh/form báo lỗi cần. Còn lại: không font/CDN/script ngoài — mọi asset self-host.
## 6. Supply chain (repo private — lưu ý riêng)
## 6. Supply chain (repo public từ 10/2026)
- **CodeQL không free cho repo private** → thay bằng: Dependabot (alerts + security updates, free cả private) + bước CI `npm audit --omit=dev --audit-level=high` + `osv-scanner` (action chính thức) chạy weekly.
- `npm ci` từ lockfile; script `preinstall` bị chặn bằng `.npmrc: ignore-scripts=true` cho CI, chỉ bật lại cho gói cần build (sharp) qua allowlist — cân bằng chống supply-chain-worm kiểu Shai-Hulud.
- Mỗi PR của Dependabot: đọc changelog trước khi merge major; patch/minor auto-merge khi CI xanh (08 §6).
- **Cài đặt**: `npm ci --ignore-scripts` từ lockfile ở CI; `scripts/check-install-scripts.mjs` liệt kê gói có install script và fail khi xuất hiện gói mới ngoài allowlist (esbuild/workerd/sharp chạy được nhờ optionalDependencies, không cần script).
- **Quét**: Dependabot (alerts + security updates, **cooldown 3 ngày** — không đề xuất bản vừa phát hành, chặn kiểu Shai-Hulud) · `npm audit --omit=dev --audit-level=high` trong CI (fail = chặn merge) · OSV-Scanner (SARIF, hằng tuần + khi đổi lockfile) · **CodeQL** (free vì repo public) · **SonarCloud** (quality gate trên PR) · Snyk (GitHub app).
- Mỗi PR Dependabot: đọc changelog trước khi merge major; patch/minor merge khi CI xanh (08 §6). Khi `main` dính advisory mới, mọi PR đỏ ở bước audit ⇒ vá gộp một PR rồi đóng các PR bị thay thế.
## 7. security.txt (`public/.well-known/security.txt`)
@@ -97,12 +109,13 @@ Canonical: https://poli0981.dev/.well-known/security.txt
Policy: https://github.com/poli0981/poli0981-dev/blob/main/SECURITY.md
```
## 8. Checklist hardening trước launch
## 8. Checklist hardening
- [ ] securityheaders.com đạt A (chấp nhận trừ điểm COEP)
- [ ] CSP không chặn: View Transitions, GSAP, Pagefind (wasm), ảnh ytimg, iframe nocookie
- [ ] Gửi form report với Turnstile sai → 403; spam 6 req/phút → 429 trang custom
- [ ] IP test trong denylist → 403 trang custom
- [x] securityheaders.com đạt A (chấp nhận trừ điểm COEP)
- [x] CSP không chặn: Pagefind (wasm), Turnstile, iframe nocookie, beacon; `check-csp-hashes` xanh trên mọi trang
- [x] Cookie cổng sai định dạng ⇒ vẫn gặp cổng (test + smoke); cổng lỗi ⇒ 503, không lộ trang
- [ ] Gửi form report với Turnstile sai → 400; spam 6 req/phút → 429 trang custom
- [ ] IP test trong denylist (thêm từ `/admin/security/`, hạn 1 giờ) → 403 trang custom
- [ ] `wrangler secret list` khớp đúng bảng §4, không thừa
- [ ] Zone settings khớp `07` checklist
@@ -114,18 +127,26 @@ admin.poli0981.dev ─▶ Cloudflare Access (policy email) ─▶ Worker
poli0981.dev/admin* ⇒ 301 sang host admin, /api/admin* ⇒ 404
src/middleware.ts : mọi route /admin* & /api/admin* (so theo routePattern) phải có
Cf-Access-Jwt-Assertion hợp lệ — jose + JWKS của team, aud = ACCESS_AUD,
iss = ACCESS_TEAM_DOMAIN, RS256, chưa hết hạn; (tuỳ chọn) ADMIN_EMAILS
request ghi: Sec-Fetch-Site same-origin + Origin đúng (chống CSRF same-site)
RL_ADMIN theo email; Cache-Control no-store; X-Robots-Tag noindex
iss = ACCESS_TEAM_DOMAIN, RS256, chưa hết hạn, phát hành ≤ 24 giờ
(maxTokenAge); email ∈ ADMIN_EMAILS (BẮT BUỘC — trống ⇒ từ chối tất cả)
request ghi: Sec-Fetch-Site same-origin + Origin đúng (chống CSRF same-site),
JSON phải có Content-Type application/json
RL_ADMIN; Cache-Control no-store; X-Robots-Tag noindex; CORP same-origin
```
- **Vì sao host riêng**: cùng origin thì một lỗi XSS ở trang công khai có thể gọi API admin bằng cookie Access. Khác origin + kiểm `Sec-Fetch-Site` ⇒ không.
- **Hai lớp**: Access chặn ở edge; Worker vẫn tự kiểm JWT ⇒ preview URL/workers.dev (đều tắt) hay header giả đều 403 (smoke test kiểm cả JWT giả).
- **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ỉ repo `poli0981/content`, **Contents: Read and write** (lưu bài/album).
- `GITHUB_PUBLISH_TOKEN`: chỉ repo `poli0981/poli0981-dev`, **Actions: Read and write** (dispatch `content-bump.yml`) — 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ì (lấy từ 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.
- **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`.
- **Preview Markdown** dùng `{@html}` trên chính nội dung của chủ site; CSP của trang admin (không `unsafe-inline`) chặn script/handler.
- **Ba lớp**: Access chặn ở edge; Worker tự kiểm JWT (preview URL/workers.dev đều tắt, header giả ⇒ 403 — smoke test kiểm cả JWT giả); `ADMIN_EMAILS` quyết định ai được thao tác — policy Access lỡ mở rộng cũng không mở admin.
- **Khuyến nghị cấu hình Access** (dashboard, `07` §13b): bắt buộc MFA ở IdP/Access, session duration ≤ 24 giờ (khớp `maxTokenAge`), bật *binding cookie*, cookie `SameSite=Lax` trở lên.
- **Hai token GitHub** (fine-grained — quyền của một token áp cho *mọi* repo nó được chọn, nên không thể "ghi repo này, chỉ dispatch repo kia" bằng một token): `GITHUB_CONTENT_TOKEN` (chỉ `poli0981/content`, Contents R/W) và `GITHUB_PUBLISH_TOKEN` (chỉ `poli0981/poli0981-dev`, Actions R/W — không có Contents ⇒ lộ cũng không đẩy được code). Đọc trạng thái (PR, check, gitlink) không cần quyền vì hai repo đều public. Thiếu quyền ⇒ admin báo rõ token nào cần quyền gì (header `X-Accepted-GitHub-Permissions`). Xuất bản đi qua `content-bump.yml` (GITHUB_TOKEN) + CI `build` bắt buộc; diff có file ngoài `.md/.json` (vd. `.mdx` — chạy code lúc build) ⇒ không auto-merge.
- **Audit log**: mỗi thao tác (lưu/xoá nội dung, upload/sửa alt/xoá ảnh, lưu/xoá album, xuất bản, chặn/bỏ chặn IP) ghi một khoá KV `audit:*` (90 ngày) kèm email, đích và commit — xem ở `/admin/activity/` cạnh lịch sử commit của repo content.
- **Upload ảnh**: kiểm magic bytes (không SVG), ≤ 20 MB, id = SHA-256 ⇒ trùng thì không biến đổi lại; biến thể + master tái mã hoá (mất EXIF/GPS), không giữ file gốc; `/media` chỉ phục vụ key biến thể, `CSP: sandbox`. Không xoá được ảnh còn được nội dung dùng.
- **Preview Markdown** render trong `<iframe sandbox="allow-same-origin" srcdoc>`: không `allow-scripts` nên không gì trong Markdown chạy được (kể cả `onerror`), không điều hướng được trang admin; frame kế thừa CSP của trang. Không cần thư viện sanitize.
- **Phiên hết hạn**: client gọi API với `redirect: "manual"` — Access trả redirect về trang đăng nhập hoặc middleware trả 403 ⇒ hiện banner "Đăng nhập lại"; bản nháp đang viết được tự lưu cục bộ (`localStorage`) và hỏi khôi phục.
- Dev (`astro dev`) dùng danh tính giả `dev@localhost` — chỉ khi `import.meta.env.DEV` (luôn false trong bản build).
## 10. Log & giới hạn vận hành
- **Log có cấu trúc** (`src/lib/log.ts`): một dòng JSON mỗi sự kiện — `level`, `event` (vd. `gate.failed`, `denylist.blocked`, `admin.access_denied`, `admin.content_saved`, `ratelimit.exceeded`, `report.github_failed`, `widgets.source_failed`), `ray`, `method`, `path`, lỗi đã serialize. Workers Logs (`observability.logs`, giữ 7 ngày, query string bị che) tự index các field; traces lấy mẫu 10%. Không log IP vào issue/Discord.
- **Phiên bản đang chạy**: binding `version_metadata` + commit build (`__BUILD_COMMIT__`) ⇒ `/api/health`, dashboard admin và log lỗi edge đều nói đúng bản nào đang phục vụ.
- **Trang 500** hiện Cloudflare Ray ID (worker đóng dấu vào `#ref`) — trùng field `ray` trong log, người dùng đọc/gửi kèm báo lỗi là tra được ngay.
- **Timeout**: mọi `fetch` ra GitHub/Discord/YouTube/Steam có `AbortSignal.timeout` (10–15 s) — một API treo không giữ request hay isolate.
+26 -8
View File
@@ -66,16 +66,25 @@ Rule ghi đè header cho **mọi** request (client không giả được). Worke
## 9. Deploy Worker & custom domain
- Local: `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
- Gắn domain: Workers & Pages → worker `poli0981-dev` → Settings → **Domains & Routes → Add → Custom domain** → `poli0981.dev` (tự tạo DNS + cert). Thêm route redirect `www` nếu muốn: tạo thêm custom domain `www.poli0981.dev` và redirect 301 trong middleware về apex.
- Worker widgets: `cd workers/widgets && npx wrangler deploy` → kiểm tra Triggers có cron.
- **Workers Builds** (dashboard → worker `poli0981-dev` → Settings → Build), nối repo `poli0981/poli0981-dev`:
| Mục | Giá trị |
|---|---|
| Production branch | `main` |
| Build command | `npm run build` |
| **Deploy command** (production) | `npx wrangler deploy` |
| **Non-production branch deploy command** | `npx wrangler versions upload` — chỉ upload version + alias preview, **không** nhận traffic |
| Build variables | `NODE_VERSION=26`, `PUBLIC_TURNSTILE_SITE_KEY=<site key>` |
| Build cache | bật |
Bẫy đã gặp (19/10/2026): Deploy command của nhánh PR từng là `wrangler deploy` ⇒ mỗi PR (cả Dependabot) được đưa lên production 100%. Ngược lại, nếu Deploy command của `main` là `versions upload` thì merge **không** deploy — khi đó promote tay: `npx wrangler versions list` → `npx wrangler versions deploy <id>@100% --yes --message "main <sha>"`. Xác minh sau mỗi merge: `curl https://poli0981.dev/api/health` phải trả đúng `version.commit`.
- Local (khẩn cấp): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
- Gắn domain: Workers & Pages → worker `poli0981-dev` → Settings → **Domains & Routes → Add → Custom domain** → `poli0981.dev` (tự tạo DNS + cert). `www.poli0981.dev` là custom domain thứ hai; worker entry redirect 301 về apex.
- Worker widgets (không nối Workers Builds): `npx wrangler deploy --config workers/widgets/wrangler.jsonc` → kiểm tra Triggers có cron.
## 10. API token cho CI (least privilege)
My Profile → API Tokens → Create Token → Custom:
- Permissions: **Account → Workers Scripts → Edit** (+ Account → Workers KV Storage → Edit nếu CI cần seed KV).
- Account Resources: đúng account của bạn. TTL: 1 năm.
→ Lưu vào GitHub repo secret `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` (bootstrap bằng script ở `08` §4).
Workers Builds tự có quyền deploy nên GitHub Actions **không** cần token Cloudflare. Chỉ tạo khi muốn deploy từ máy khác/CI riêng: My Profile → API Tokens → Create Token → Custom → **Account → Workers Scripts → Edit** (+ Workers KV Storage → Edit nếu cần seed KV), đúng account, TTL ≤ 1 năm.
## 11. Email (Google Workspace)
@@ -109,10 +118,17 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
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. (Tuỳ chọn) `ADMIN_EMAILS` = danh sách email, phân cách dấu phẩy.
- Sửa quyền của token có sẵn không đổi giá trị token ⇒ không cần đặt lại secret.
- **`ADMIN_EMAILS` (bắt buộc)** = email được vào admin, phân cách dấu phẩy: `printf '%s' "you@example.com" | npx wrangler secret put ADMIN_EMAILS`. Thiếu secret này admin từ chối mọi người (fail-closed). Đặt khi version mới nhất là bản `main` (`06` §4).
- Báo lỗi: thêm repo private `poli0981/site-reports` vào `GITHUB_ISSUES_TOKEN` (Issues: Read and write).
3b. Siết Access (application `admin.poli0981.dev` → Settings): **Session duration ≤ 24h** (Worker cũng từ chối token > 24 giờ), policy yêu cầu **MFA** (IdP có 2FA hoặc rule Access), bật **Binding cookie**, cookie `SameSite=Lax` hoặc `Strict`, `HttpOnly`.
4. Repo `poli0981-dev` → Settings → Actions → General → bật **Allow GitHub Actions to create and approve pull requests** (cho `content-bump.yml`); quyền mặc định của GITHUB_TOKEN giữ **read**.
5. R2 `poli0981-media` (`wrangler r2 bucket create poli0981-media --location apac`), không bật public URL. Images binding không cần bật gì thêm (gói Free: 5.000 biến đổi/tháng).
## 14. Observability
`wrangler.jsonc` → `observability`: logs bật (invocation logs, lấy mẫu 100%, query string bị che), traces lấy mẫu 10%. Xem ở Workers → `poli0981-dev` → **Logs** (giữ 7 ngày): lọc theo field `event` (log JSON của `src/lib/log.ts`, `06` §10) hoặc `ray` (mã trên trang 500). Binding `version_metadata` cho biết version đang chạy; `/api/health` trả cả commit.
## 13. Checklist nghiệm thu
- [ ] `dig poli0981.dev` ra IP Cloudflare; DNSSEC = Success
@@ -127,4 +143,6 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
- [ ] Trình duyệt ẩn danh vào `/` → thấy bước xác minh rồi vào trang; `curl -s https://poli0981.dev/ | grep data-human-check` có kết quả; RSS/sitemap/trang pháp lý không bị chặn
- [ ] Search Console (URL Inspection → Test live URL) thấy trang thật; Facebook Sharing Debugger đúng title/ảnh
- [ ] `https://admin.poli0981.dev/` → đăng nhập Access → thấy admin; `curl -H 'cf-access-jwt-assertion: x' …/api/admin/content` (qua host chính) → 404/403
- [ ] `ADMIN_EMAILS` đã đặt; Access session ≤ 24h + MFA + binding cookie
- [ ] Workers Builds: Deploy command `main` = `npx wrangler deploy`, nhánh khác = `npx wrangler versions upload`; sau merge `/api/health` trả đúng commit
- [ ] Auto-renew ON + transfer lock ON + 2FA ON
+30 -19
View File
@@ -1,13 +1,14 @@
# 08 — CI/CD
## 0. Thực tế đang chạy (10/2026) — các mục sau là kế hoạch ban đầu
## 0. Thực tế đang chạy (10/2026, v2.0) — §1–§5 bên dưới là kế hoạch ban đầu (lịch sử)
- **Deploy**: Cloudflare **Workers Builds** nối repo, build + `wrangler deploy --config ./dist/server/wrangler.json` mỗi lần push `main` (không có job deploy trong GitHub Actions; secrets `CLOUDFLARE_*` trên GitHub không dùng). Nhánh khác có preview build.
- **`ci.yml`** (PR, push `main`, `workflow_dispatch`): install → `wrangler types --strict-vars=false` → prettier → eslint → `astro check` → typecheck widgets → knip → **unit test** (`npm test`) → `npm audit --omit=dev --audit-level=high` → notices → EXIF → build → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/admin 403 và pha ép bật cổng Turnstile). Check `build` là **bắt buộc** (ruleset `main`), nên PR chỉ sửa docs vẫn phải chạy.
- **`osv-scanner.yml`**: reusable workflow SARIF (tab Security), hằng tuần + khi đổi lockfile.
- **`lighthouse.yml`**: chỉ cảnh báo.
- **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ế.
- **Bẫy đã gặp**: khi `main` dính advisory, *mọi* PR (cả Dependabot) đỏ vì bước audit ⇒ vá gộp trong một PR rồi đóng các PR Dependabot bị thay thế. `gen-notices --check` từng đếm số gói transitive ⇒ PR bump nào cũng đỏ; nay chỉ kiểm chính sách license.
## 1. Nguyên tắc
@@ -78,19 +79,25 @@ updates:
- package-ecosystem: npm
directory: "/"
schedule: { interval: weekly, day: monday }
groups:
astro: { patterns: ["astro", "@astrojs/*"] }
dev-tools:{ dependency-type: development }
cooldown: { default-days: 3 } # không đề xuất bản phát hành < 3 ngày tuổi
open-pull-requests-limit: 8
- package-ecosystem: npm
directory: "/workers/widgets"
schedule: { interval: weekly }
groups:
astro: { patterns: ["astro", "@astrojs/*"] }
typescript: { patterns: ["typescript", "typescript-eslint"] }
dev-tools: { dependency-type: development }
ignore:
- dependency-name: typescript # giữ TS 6 cho tooling (02 §8)
update-types: ["version-update:semver-major"]
- dependency-name: prettier-plugin-astro # 1.x đổi khoảng trắng hiển thị — cần PR riêng
update-types: ["version-update:semver-major"]
- package-ecosystem: github-actions
directory: "/"
schedule: { interval: weekly }
```
Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. Security alerts: xử lý ≤ 48h (lịch ở `17`).
- `workers/widgets` không có `package.json` (không deps) nên không có mục riêng.
- `@typescript/native` (alias `npm:typescript@7`) **không** được Dependabot theo dõi — nâng tay (`17` §1).
- Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. Security alerts: xử lý ≤ 48h (lịch ở `17`). PR bị một PR gộp thay thế ⇒ đóng kèm comment.
## 7. Git hooks (`lefthook.yml`)
@@ -98,15 +105,19 @@ Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc
pre-commit:
parallel: true
commands:
format: { glob: "*.{astro,svelte,ts,md,css,json}", run: npx prettier --write {staged_files}, stage_fixed: true }
lint: { glob: "*.{astro,svelte,ts}", run: npx eslint {staged_files} }
format: { glob: "*.{astro,svelte,ts,js,mjs,md,css,json,jsonc,yml,yaml}", run: npx prettier --write {staged_files}, stage_fixed: true }
lint: { glob: "*.{astro,svelte,ts,js,mjs}", run: npx eslint {staged_files} }
pre-push:
commands:
typecheck: { run: npm run check } # astro check && tsc --noEmit
typecheck: { run: npm run check } # astro check
```
Commit và tag đều ký GPG; không dùng `--no-verify`.
## 8. Branch & release
- `main` protected: PR + CI xanh (solo nên cho phép self-merge, vẫn bắt CI).
- Conventional Commits như các repo khác; site không cần semver release — "release" = deploy `main`. Tag mốc lớn (`v1-launch`) để tra cứu.
- Preview: `wrangler versions upload` cho preview URL trước khi merge thay đổi lớn về UI (thủ công, không bắt buộc trong CI).
- `main` protected (ruleset): PR + check `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`.
+3 -3
View File
@@ -15,12 +15,12 @@ Nhắc lại quyết định D8: Custom Errors của Cloudflare cần zone plan
| Trang | Trigger | Headline (VI / EN) | Ghi chú riêng |
|---|---|---|---|
| **404** `404.astro` | route không tồn tại | "Trang này không phát ra tín hiệu." / "This page makes no sound." | + ô search (mở Pagefind), gợi ý 3 bài mới. Assets config `not_found_handling: "404-page"` để request tĩnh lạc cũng nhận trang này (P0 Spike 3 verify) |
| **500** `500.astro` | exception khi render on-demand / api | "Có gì đó vỡ trong im lặng." / "Something broke, quietly." | Astro tự dùng 500.astro khi SSR lỗi; api route bọc try/catch trả JSON lỗi gọn. In mã tham chiếu = `crypto.randomUUID().slice(0,8)` để người dùng đính vào bug report |
| **403** middleware render | IP nằm trong `denylist:*` (KV) | "Cửa này đang khoá." / "This door is locked." | Kèm dòng: nếu nghĩ là nhầm → contact@. Không nêu lý do cụ thể |
| **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) |
| **/offline** | service worker fallback | "Không có mạng — nhưng vẫn có thứ để làm." / "You're offline." | Xem §3–4 |
403/429 do middleware sinh: render template Astro đã **prerender sẵn thành static asset** (`/403` `/429` là trang thật), middleware chỉ `fetch` asset đó qua binding ASSETS rồi trả với status tương ứng — không nhân đôi markup.
403 (worker entry) và 429 (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.
+6 -6
View File
@@ -1,6 +1,6 @@
# 10 — Bug report pipeline (console error → GitHub Issue + Discord)
Repo private ⇒ khách không mở issue trực tiếp được. Pipeline này là kênh báo lỗi duy nhất cho visitor, và cũng tiện cho chính mình.
Pipeline này là kênh báo lỗi chính cho visitor (không cần tài khoản GitHub), và cũng tiện cho chính mình. Từ 10/2026 repo site là public, nhưng báo cáo có thể chứa log/mô tả riêng tư nên issue được tạo ở repo **private** `poli0981/site-reports` (đúng lời hứa "private GitHub issue" của Privacy Policy).
## 1. Client — thu console error
@@ -12,7 +12,7 @@ Repo private ⇒ khách không mở issue trực tiếp được. Pipeline này
## 2. UX — nút "Báo lỗi" (footer mọi trang, và trang 404/500)
Dialog gồm: textarea mô tả (bắt buộc, ≥ 10 ký tự) → checkbox **"Đính kèm log lỗi console (n mục)"** mặc định bật, kèm nút *Xem trước* mở đúng nội dung sẽ gửi → dòng tự đính: route, UA, viewport, theme, locale, mã tham chiếu (nếu đến từ trang 500) → Turnstile → Gửi. Thành công: "Đã gửi — cảm ơn bạn!". Thất bại: hiện thông báo + nút copy nội dung để gửi qua Discord.
Dialog (`<dialog>` modal có nhãn, textarea có `<label>`) gồm: textarea mô tả (bắt buộc, ≥ 10 ký tự) → checkbox **"Đính kèm log lỗi console (n mục)"** mặc định bật, kèm nút *Xem trước* mở đúng nội dung sẽ gửi → dòng tự đính: route, UA, viewport, theme, locale, mã tham chiếu (từ trang 500: **Cloudflare Ray ID** do worker đóng dấu, trùng field `ray` trong Workers Logs) → Turnstile → Gửi. Thành công: "Đã gửi — cảm ơn bạn!". Thất bại: hiện thông báo + nút copy nội dung để gửi qua Discord (báo "đã sao chép" hoặc lý do clipboard bị chặn).
## 3. API contract — `POST /api/report`
@@ -25,14 +25,14 @@ Dialog gồm: textarea mô tả (bắt buộc, ≥ 10 ký tự) → checkbox **"
}
```
Worker xử lý theo thứ tự: rate-limit (middleware, binding `RL_REPORT` 5/phút/client, fail 429) → thiếu secret (503) → body > 32 KB (413) → 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. 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. 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) → body > 32 KB (413 — đọc stream có trần, không đọc hết) → Zod validate (fail 400) → Turnstile siteverify (`src/lib/turnstile-server.ts`: kiểm `success` **+ `action: "report"` + `hostname: poli0981.dev`**, fail 400 `turnstile_failed`) → **tạo GitHub Issue** → **Discord webhook** → 201 `{ok: true}`. Nếu GitHub API lỗi: vẫn bắn Discord (kèm full payload) và trả 202 — không mất báo cáo. Mỗi lời gọi ra ngoài có timeout 10 s; response `no-store`. Token Turnstile dùng một lần: dialog gọi `turnstile.reset()` sau mỗi lần gửi.
## 4. GitHub Issue
`POST /repos/poli0981/poli0981.dev/issues` với `GITHUB_ISSUES_TOKEN` (fine-grained, chỉ Issues R/W):
`POST /repos/<REPORT_REPO>/issues` — `REPORT_REPO` là var trong `wrangler.jsonc` (mặc định `poli0981/site-reports`, private) — với `GITHUB_ISSUES_TOKEN` (fine-grained, **chỉ repo đó**, Issues R/W):
- title: `[web-report] <60 ký tự đầu của description>`
- labels: `bug`, `from-site`
- body: render đúng cấu trúc template §5 (description → meta table → console trong code block).
- body: render đúng cấu trúc template §5 (description → meta table → console trong code block). `@mention` trong title/body bị vô hiệu (chèn zero-width) để báo cáo không ping ai; nội dung khách đưa vào code span/fence an toàn.
## 5. Issue template dùng chung — `.github/ISSUE_TEMPLATE/bug_report.yml`
@@ -65,7 +65,7 @@ body:
## 6. Discord webhook
Kênh riêng `#site-reports` trong server repo. Embed: màu `--color-horror`, title = issue title, field route/UA, link issue. (Tái dùng format của `notify.py` cho đồng bộ.)
Kênh riêng `#site-reports` trong server repo. Embed: màu `--horror`, title = issue title, field route/UA, link issue; `allowed_mentions: { parse: [] }` để nội dung khách không ping được ai. (Tái dùng format của `notify.py` cho đồng bộ.)
## 7. Privacy & giới hạn
+11 -9
View File
@@ -7,14 +7,15 @@ API thời tiết/map phục vụ *chủ site* chứ không phục vụ *khách*
## 2. Kiến trúc: cron → KV → build/island
```
workers/widgets (cron */45 phút)
workers/widgets (cron */45 phút, 3 nguồn chạy song song, timeout 10 s/nguồn)
├─ YouTube RSS ─┐
├─ Steam API ──┼─► chuẩn hoá JSON ─► KV put widgets:*
└─ GitHub API ──┘
Site đọc: lúc BUILD (fetch KV qua wrangler/API cho trang tĩnh) + island refresh nhẹ gọi /api/widgets (GET, cache 5')
├─ Steam API ──┼─► chuẩn hoá JSON ─► KV put widgets:yt|steam|gh|status
└─ GitHub API ──┘ └─► mirror thumbnail/icon ─► KV put widgets:img:* (≤ 2 MB, TTL 14 ngày)
Site đọc: lúc BUILD (snapshot KV cho trang tĩnh) + island refresh nhẹ gọi /api/widgets (GET, cache 5')
Ảnh: /ext-img/yt/<id> · /ext-img/steam/<appid>/<hash> → chỉ ĐỌC KV widgets:img:* (src/lib/ext-img.ts)
```
Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key, không dính rate limit của họ.
Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nhanh, không lộ key, không dính rate limit của họ, và trình duyệt không chạm Google/Steam trước khi khách bấm (khớp Privacy Policy §5). Kiểu dữ liệu chung của site và worker nằm ở `src/lib/widgets-types.ts`.
## 3. Nguồn dữ liệu
@@ -22,7 +23,7 @@ Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key,
|---|---|---|
| Video mới (≤3) | `https://www.youtube.com/feeds/videos.xml?channel_id=<UCxxx>` | RSS công khai, **không cần API key**; parse XML lấy id/title/thumb/published |
| Đang chơi gì | `ISteamUser…/GetRecentlyPlayedGames/v1/?key=…&steamid=…&count=3` | Cần Steam profile → Privacy → **Game details: Public**; key free tại steamcommunity.com/dev |
| Hoạt động GitHub | `api.github.com/users/poli0981/events/public?per_page=10` | Không cần token (60 req/h/IP đủ cho cron 45'); lọc PushEvent/ReleaseEvent |
| Hoạt động GitHub | `api.github.com/users/poli0981/events/public?per_page=10` | Token tuỳ chọn `GITHUB_TOKEN` (không quyền nào): không có token thì hạn mức 60 req/h tính theo IP — IP egress của Workers dùng chung nên hay bị 403 ⇒ feed `stale`. Lọc PushEvent/ReleaseEvent |
## 4. KV schema
@@ -31,7 +32,8 @@ Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key,
| `widgets:yt` | `{updated, items:[{id,title,thumb,published}]}` | không TTL — ghi đè |
| `widgets:steam` | `{updated, items:[{appid,name,playtime2w,icon}]}` | — |
| `widgets:gh` | `{updated, items:[{type,repo,ts,detail}]}` | — |
| `widgets:status` | `{yt:"ok"|"stale"|"na", steam:…, gh:…, lastRun}` | — |
| `widgets:status` | `{yt:"ok"|"stale"|"na", steam:…, gh:…, lastRun}` | — (dashboard admin hiển thị) |
| `widgets:img:yt:<id>` · `widgets:img:steam:<appid>:<hash>` | bytes ảnh, metadata `{type}` (jpeg/png/webp) | 14 ngày; ảnh > 2 MB hoặc sai kiểu bị bỏ qua. Icon Steam lấy từ `cdn.cloudflare.steamstatic.com` — `media.steampowered.com` trả 403 cho Workers |
## 5. Quy tắc bền vững (kế thừa convention tracker của bạn)
@@ -42,14 +44,14 @@ Khách **không bao giờ** gọi thẳng bên thứ ba: nhanh, không lộ key,
## 6. Hiển thị
- `WidgetLatestVideo`: thumbnail tĩnh `i.ytimg.com` + nút play → bấm mới tạo iframe `youtube-nocookie.com` (facade — khớp CSP `06` §1 và Privacy).
- `WidgetLatestVideo`: thumbnail qua `/ext-img/yt/<id>` (bản mirror trong KV, CSP `img-src 'self'`) + nút play → bấm mới tạo iframe `youtube-nocookie.com` (facade — `06` §5 và Privacy). Thiếu ảnh mirror ⇒ khung không ảnh, không gọi ra ngoài.
- `WidgetNowPlaying`: icon game + tên + "x giờ / 2 tuần"; 0 game gần đây ⇒ ẩn.
- `WidgetGitHub`: 3 dòng "pushed to X · 2d ago".
- Trang tĩnh build kèm snapshot KV tại thời điểm build; island gọi `/api/widgets` (GET, `Cache-Control: max-age=300`, đọc KV) để tươi hơn giữa các lần deploy. Không có JS ⇒ vẫn thấy snapshot build — progressive enhancement.
## 7. Secrets & cấu hình worker widgets
`wrangler.jsonc`: `triggers: { crons: ["*/45 * * * *"] }`, bind KV chung. Secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`. Biến thường: `YT_CHANNEL_ID` (vars, không nhạy cảm).
`wrangler.jsonc`: `triggers: { crons: ["*/45 * * * *"] }`, bind KV chung, `observability.logs` bật. Secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`, `GITHUB_TOKEN` (tuỳ chọn). Biến thường: `YT_CHANNEL_ID` (vars, không nhạy cảm). Mỗi lần chạy ghi log JSON `widgets.run` (+ `widgets.source_failed` cho nguồn lỗi). Deploy: `npx wrangler deploy --config workers/widgets/wrangler.jsonc` (không nối Workers Builds).
## 8. Test
+1 -1
View File
@@ -47,7 +47,7 @@ Item: title, link, pubDate, description, `<language>` theo bài, category = tags
## 5. OG image tự sinh
- Build-time bằng Satori + resvg (hoặc `astro-og-canvas` nếu gọn hơn lúc triển khai): template 1200×630, nền mực đêm + Waveline + title (Bricolage) + badge khu (Blog/Truyện/Project) + `poli0981.dev`.
- 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).
- Cache theo hash(title+khu) để build nhanh.
+2 -1
View File
@@ -27,5 +27,6 @@
## 3. Kiểm tra
- Local: `npm run build && npx astro preview` + Lighthouse trong DevTools cho 4 trang đại diện: `/`, 1 bài blog, 1 chương truyện, `/gallery/<album>`.
- CI (P2): job Lighthouse CI chạy trên preview build, assert budget bảng §1 — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý.
- CI: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý.
- 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.
- Thực địa: Cloudflare Web Analytics có Core Web Vitals thật của khách — xem hằng tháng (lịch `17`).
+39 -22
View File
@@ -2,44 +2,61 @@
Ước lượng theo "buổi tối" (~2–3h). Nguyên tắc quen thuộc: **xong P0 spikes mới viết feature** — spike nào fail thì sửa kế hoạch khi chưa tốn công.
## P0 — Spikes (làm trước tiên, ~3–4 buổi)
Trạng thái tại 2026-10-24 (v2.0.0): ✅ xong · 🟡 đang làm · ⬜ chưa.
| # | Spike | Cách làm | Tiêu chí đạt |
|---|---|---|---|
| S1 | **Pipeline sống end-to-end** | Mua domain (07 §1) → scaffold `create-cloudflare` Astro → `wrangler deploy` → gắn custom domain → caller CI/deploy stub chạy | Push 1 commit ⇒ site đổi trên `poli0981.dev` trong <3 phút |
| S2 | **Font tiếng Việt** | Cấu hình Fonts API 4 font, subset `latin+vietnamese`; trang test chứa chuỗi đủ dấu ("ắ ằ ẳ ẵ ặ ế ệ ễ ỡ ợ ự ữ Đ…") ở mọi weight | Render đúng trên Android + iPhone thật, không fallback lệch baseline, tổng 2 file first-paint <90KB |
| S3 | **Error handling sau edge** | Set `not_found_handling: "404-page"`; middleware trả 403/429 từ asset prerender; test qua domain thật (không phải localhost) | Ma trận `09` §5 pass các dòng 404/403/429 |
| S4 | **CSP không vỡ tính năng** | Bật CSP built-in + directive `06` §1; chạy thử View Transitions, 1 animation GSAP, Pagefind search, YouTube facade | Console 0 lỗi CSP; search hoạt động (nhớ `wasm-unsafe-eval`) |
## P0 — Spikes ✅
## P1 — Nền móng + nội dung lõi (~6–8 buổi)
| # | Spike | Cách làm | Tiêu chí đạt | |
|---|---|---|---|---|
| S1 | **Pipeline sống end-to-end** | Mua domain (07 §1) → scaffold Astro → deploy → gắn custom domain → CI | Push 1 commit ⇒ site đổi trên `poli0981.dev` trong <3 phút | ✅ (Workers Builds) |
| S2 | **Font tiếng Việt** | Fonts API 4 font, subset `latin+vietnamese`; trang test đủ dấu ở mọi weight | Render đúng trên Android + iPhone thật, 2 file first-paint <90KB | ✅ |
| S3 | **Error handling sau edge** | `not_found_handling: "404-page"`; 403/429 từ asset prerender; test qua domain thật | Ma trận `09` §5 pass các dòng 404/403/429 | ✅ |
| S4 | **CSP không vỡ tính năng** | CSP built-in + directive `06` §1; Pagefind, YouTube facade, Turnstile | Console 0 lỗi CSP; search hoạt động (`wasm-unsafe-eval`) | ✅ (`check-csp-hashes` trong build) |
## P1 — Nền móng + nội dung lõi ✅
- Design tokens + Base layout + Header/Footer/TabBar + theme/lang toggle + Waveline.
- Content Collections + schemas + templates; trang: Home (chưa widget), About, Blog (index/bài/tag), Stories (index/reader/ReadingControls/CW), Q&A, Links, Legal ×5 + LegalGateSheet.
- Trang lỗi 404/500/403/429 + middleware headers/denylist/rate-limit.
- Migrate: viết 2–3 bài blog đầu + 1 truyện ngắn để có nội dung thật khi launch.
- **Launch nội bộ cuối P1** (site đã dùng được).
- Content Collections + schemas + templates; trang: Home, About, Blog (index/bài/tag), Stories (index/reader/ReadingControls/CW), Q&A, Links, Legal ×5 + LegalGateSheet.
- Trang lỗi 404/500/403/429 + headers/denylist/rate-limit.
- Nội dung thật đầu tiên: bài blog + truyện "Đêm không tiếng".
## P2 — Hoàn thiện trải nghiệm (~5–6 buổi)
## P2 — Hoàn thiện trải nghiệm ✅
- Pagefind search modal · RSS ×3 · sitemap/hreflang/JSON-LD · OG image tự sinh.
- Gallery + lightbox + strip-exif/check-exif scripts.
- Gaming + Dev/uses; widgets worker (YouTube/Steam/GitHub) + `/api/widgets`.
- Bug report pipeline đầy đủ (10) + issue template.
- Offline service worker + trang /offline (chưa game).
- Offline service worker + trang /offline.
- Lighthouse CI warn-mode.
## P3 — Gia vị (rảnh thì làm)
## P3 — Gia vị ✅
- Mini-game Skull Hop (09 §4) · `npm run new:post` · trang /now cadence tháng · easter egg konami/ASCII skull trong console (`console.log` banner) · dòng thời tiết footer nếu vẫn thích.
- Mini-game Skull Hop (09 §4) · `npm run new:post` · trang /now · easter egg konami/ASCII skull trong console.
## P4 — Launch công khai
## P3.5 — Nền tảng & admin (10/2026) ✅
- [ ] Checklist `06` §8 (security) + `07` §13 (Cloudflare) + `09` §5 (errors) pass
- Cổng Turnstile trước mọi trang (06 §3b) · admin `admin.poli0981.dev` (Access + JWT, R2 media, xuất bản qua workflow) · repo public.
- **v2.0.0**: Node 26 + TypeScript 7 · SonarCloud + test `node:test` (~99% dòng) · vá bypass cookie cổng · denylist CIDR · ảnh widget qua `/ext-img` · log JSON + version trên `/api/health` · báo lỗi vào repo private · palette Glacier Teal + theme theo hệ điều hành · sửa a11y/i18n · admin mới (tổng quan, hoạt động, bảo mật, audit log). Chi tiết: `CHANGELOG.md`.
## P4 — Launch công khai 🟡
- [x] Checklist `06` §8 (security) phần tự động (headers, CSP, cổng)
- [ ] Phần còn lại của `06` §8 + `07` §13 (Cloudflare) + `09` §5 (errors) chạy tay trên production
- [ ] 13 §7 (SEO một lần) xong
- [ ] Đọc lại 5 văn bản legal, điền {{EFFECTIVE_DATE}}, xoá ghi chú nội bộ
- [x] Văn bản legal có ngày hiệu lực (2026-10-24), không còn ghi chú nội bộ
- [ ] Test 2 thiết bị thật + 1 máy lạ (bạn bè) — thu 1 vòng feedback
- [ ] Tag `v1-launch`, đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/GitHub/Discord
- [ ] Đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/GitHub/Discord
## Sau v1 — backlog để ngỏ
## Hướng đi tiếp (sau v2.0)
Keystatic (ADR-04, xét lại sau 1–2 tháng dùng thật) · bot Telegram capture · locale `ja` · R2 cho gallery (>1GB) · repo public `poli0981/legal` · trang /support (Ko-fi) · Giscus nếu đổi ý về comment.
| Hướng | Vì sao | Điều kiện |
|---|---|---|
| Gộp TypeScript về một bản 7.x | Bỏ alias `@typescript/native` + TS 6 | TS 7.1 có JS API; astro check / typescript-eslint / svelte2tsx hỗ trợ |
| Workers Builds riêng cho widgets worker | Hết deploy tay | Khi worker có thay đổi thường xuyên hơn |
| Backup định kỳ R2 + KV (denylist, audit) | Ảnh upload chỉ nằm ở R2 | Workflow cron dùng `wrangler r2 object get` / `kv key list` (17 §4) |
| Analytics Engine cho số liệu cổng/báo lỗi | Biết cổng chặn bao nhiêu, báo lỗi đến từ đâu | Không thêm cookie; giữ khớp Privacy Policy |
| Đếm lượt xem bằng Durable Object | Số đọc cho blog/truyện không cần dịch vụ ngoài | Cập nhật Privacy Policy trước |
| RSS full-content cho blog | Người đọc qua RSS | Truyện vẫn chỉ mô tả + link (ARR) |
| 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 |
+2 -2
View File
@@ -9,7 +9,7 @@ Tỷ giá tham khảo ~26.000 VND/USD, 2026-07.
| Domain `poli0981.dev` (Cloudflare Registrar, at-cost, WHOIS redaction free) | năm | **~$12–13** (~320–340k VND) — số chính xác hiện khi search trong dashboard | **Phát sinh mới duy nhất** |
| Cloudflare Workers Paid | tháng | $5 | Đã có sẵn — site nằm trong hạn mức |
| KV · Turnstile · Web Analytics · Email Routing · WAF free · Bot Fight | — | $0 | Free / trong gói |
| GitHub private repo + Actions + Dependabot | — | $0 | Free plan (2.000 phút Actions/tháng — CI dùng ~5–10%) |
| GitHub public repo + Actions + Dependabot + CodeQL | — | $0 | Repo public: phút Actions không giới hạn cho runner chuẩn; SonarCloud free cho dự án public |
| Astro/Svelte/Tailwind/GSAP/font/Pagefind | — | $0 | OSS |
| R2 | `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 |
@@ -25,7 +25,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 | 2.000/tháng (private) | ~100–200 | Nếu sau này thêm job nặng — theo dõi ở Settings → Billing |
| GitHub Actions phút | không giới hạn (public) | ~200–400 | Repo `content`/`site-reports` vẫn private nếu sau này có workflow riêng — theo dõi ở Settings → Billing |
| Domain renew | — | $12–13/năm | Thẻ hết hạn ⇒ mất domain — auto-renew ON + lịch nhắc (17) |
## 3. Quy tắc chi tiêu
+15 -8
View File
@@ -7,9 +7,9 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
| Nhịp | Việc |
|---|---|
| **Hằng tuần** (thứ 2, sau khi Dependabot chạy) | Triage PR Dependabot: patch/minor xanh CI → merge; security alert → xử lý ≤ 48h. Liếc Discord `#site-reports` |
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; xem Web Analytics + Core Web Vitals; liếc Workers metrics (request, error rate); kiểm tra cron widgets còn chạy |
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; **nâng tay `@typescript/native`** (Dependabot bỏ qua alias `npm:`) và xem TS 7.1 đã có JS API chưa (`02` §8); xem Web Analytics + Core Web Vitals; liếc Workers Logs (lọc `level: error`) + dashboard admin (trạng thái cron widgets, secret thiếu); SonarCloud không có issue mới trên `main` |
| **Hằng quý** | Nâng major có kế hoạch (Astro/Tailwind/Wrangler — đọc upgrade guide trước); chạy lại ma trận error test `09` §5; backup ngoài (§4) |
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN, 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 · cập nhật `Expires` trong security.txt · đọc lại 5 văn bản legal (đổi thì tăng `v` của legalAck) · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 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 |
Đặt reminder: dùng chính hệ notify/cron GitHub Actions quen thuộc — workflow cron tháng/quý/năm bắn Discord nhắc việc (input sẵn trong repo `.github`).
@@ -17,21 +17,27 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
1. Branch `chore/upgrade-<pkg>-vX` → đọc CHANGELOG/upgrade guide chính thức.
2. `npm i <pkg>@latest` → chạy full CI local (`format/lint/check/knip/build`).
3. `wrangler versions upload` → preview URL → bấm qua 6 trang đại diện + search + form report.
4. Merge → deploy → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
5. Ghi 1 dòng vào `docs/00_INDEX.md` nếu có breaking change ảnh hưởng quyết định cũ.
3. Mở PR → CI (`build` + smoke) + SonarCloud xanh; Workers Builds upload version preview của nhánh → bấm qua 6 trang đại diện + search + form report (dashboard → Versions → alias của nhánh).
4. Squash-merge → 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).
5. Ghi vào `CHANGELOG.md`; ghi 1 dòng vào `poli0981.dev-docs/00_INDEX.md` nếu có breaking change ảnh hưởng quyết định cũ.
**Rollback**: `npx wrangler versions list` → `npx wrangler versions deploy <id-cũ>@100% --yes` (hoặc `wrangler rollback`). Secret mới đặt sau version đó sẽ không có trong version cũ — đặt lại nếu cần.
## 3. Giám sát
- **Uptime** (tuỳ chọn, free): UptimeRobot/StatusCake ping `https://poli0981.dev/` 5 phút/lần → alert email/Discord. Đủ dùng, không cần status page.
- **Lỗi runtime**: Workers observability (đã bật trong wrangler.jsonc) → xem Logs khi có report; không cần Sentry ở quy mô này (ADR-05).
- **Lỗi runtime**: Workers Logs (log JSON có `event`/`ray`, `06` §10) → tra theo Ray ID mà người dùng gửi kèm báo lỗi; không cần Sentry ở quy mô này (ADR-05).
- **Đang chạy bản nào**: `curl https://poli0981.dev/api/health` → `version.id` + `version.commit`; dashboard admin hiện cùng thông tin.
- **Admin**: `/admin/activity/` (audit log 90 ngày + commit repo content) — liếc khi nghi có thao tác lạ.
- **Cron widgets**: tự cảnh báo qua Discord khi fail 3 lần (11 §5).
## 4. Backup & khôi phục
- **Nguồn sự thật = Git** (nội dung + code). GitHub đã là bản sao thứ nhất; máy local là bản thứ hai.
- **Quý**: `git bundle create backup-YYYYQ.bundle --all` → cất vào ổ ngoài/cloud cá nhân (một lệnh, chứa toàn bộ lịch sử).
- KV widgets = dữ liệu tái sinh được, không cần backup. Secrets: lưu trong password manager (không chỉ trong Cloudflare).
- **R2 `poli0981-media`** (ảnh upload qua admin — *không* có trong Git): quý một lần sao ra ngoài, vd. `npx wrangler r2 object get poli0981-media/<key> --file …` theo danh sách `private/meta/*.json`, hoặc rclone với S3 API token chỉ-đọc.
- **KV**: widgets tái sinh được; `denylist` và `audit:*` nên xuất định kỳ: `npx wrangler kv key get --binding KV denylist --preview false > denylist.json` và `npx wrangler kv key list --binding KV --prefix audit: --preview false > audit.json`.
- Secrets: lưu trong password manager (không chỉ trong Cloudflare).
- **Khôi phục thảm hoạ** (mất account/worker): repo + `07_CLOUDFLARE_SETUP.md` + `wrangler deploy` ⇒ site sống lại trong < 1 giờ. Domain là thứ duy nhất không thay được — vì thế 2FA + transfer lock + auto-renew là 3 khoá quan trọng nhất của cả hệ thống.
## 5. Trigger cần hành động (đặt sẵn ngưỡng)
@@ -43,5 +49,6 @@ 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 |
| Repo chuyển public | Bật CodeQL (free cho public) vào caller CI; kiểm tra lại EXIF toàn bộ ảnh lịch sử; xoá secret khỏi lịch sử nếu từng lỡ (không nên có) |
| Version sai lên production (PR được deploy, regression) | Rollback ngay (§2), rồi kiểm Deploy command của Workers Builds (`07` §9) |
| Bị khoá ngoài admin (Access/`ADMIN_EMAILS`) | `wrangler secret put ADMIN_EMAILS` với email đúng; kiểm policy Access; denylist có chặn nhầm IP mình không (`wrangler kv key get … denylist`) |
| Đổ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) |
+42 -3
View File
@@ -38,6 +38,11 @@ const CONTENT = /\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i;
// cases below are now asserted on every run instead of being re-reasoned from scratch.
const SCRIPT = /<script(\s[^>]*)?>([\s\S]*?)<\/script(\s[^>]*)?>/gi;
const JSON_LD = /type=("|')?application\/ld\+json/i;
// Inline <style> blocks need their hash in the policy just the same, and Astro misses some:
// the styles of a component rendered only from MDX content (Callout) shipped unhashed, so the
// browser dropped them. A style *attribute* can never pass a policy without 'unsafe-inline'.
const STYLE = /<style(\s[^>]*)?>([\s\S]*?)<\/style(\s[^>]*)?>/gi;
const STYLE_ATTR = /<[a-z][\w-]*\s(?:[^>]*?\s)?style\s*=/gi;
/** Tag forms a browser executes (or doesn't). Asserted before every real run. */
const SELFTEST = [
@@ -72,6 +77,24 @@ function selftest() {
for (const [html, expected] of META_SELFTEST) {
if (cspOf(html) !== expected) failures.push(`CSP meta: expected ${expected} for ${html}`);
}
for (const [html, shouldMatch] of [
["<style>X</style>", true],
["<STYLE media=screen>X</style >", true],
["<stylesheet>X</stylesheet>", false],
]) {
STYLE.lastIndex = 0;
if (STYLE.test(html) !== shouldMatch) failures.push(`style block: wrong result for ${html}`);
}
for (const [html, shouldMatch] of [
['<p style="color:red">', true],
["<svg viewBox='0 0 1 1' style=x>", true],
['<meta content="style-src x">', false],
['<p data-style="x">', false],
]) {
STYLE_ATTR.lastIndex = 0;
if (STYLE_ATTR.test(html) !== shouldMatch)
failures.push(`style attribute: wrong result for ${html}`);
}
if (failures.length > 0) {
console.error("CSP guard SELFTEST FAILED — a matcher is wrong:\n");
for (const failure of failures) console.error(` ${failure}`);
@@ -107,6 +130,7 @@ const offenders = [];
const withoutCsp = [];
let pages = 0;
let scripts = 0;
let styles = 0;
for (const file of htmlFiles(ROOT)) {
const html = readFileSync(file, "utf8");
@@ -128,6 +152,17 @@ for (const file of htmlFiles(ROOT)) {
offenders.push({ file, hash, preview: body.trim().slice(0, 80) });
}
}
for (const [, , body] of html.matchAll(STYLE)) {
styles += 1;
const hash = `sha256-${createHash("sha256").update(body, "utf8").digest("base64")}`;
if (!declared.has(hash)) {
offenders.push({ file, hash, preview: `<style> ${body.trim().slice(0, 72)}` });
}
}
for (const [tag] of html.matchAll(STYLE_ATTR)) {
offenders.push({ file, hash: "style attribute", preview: tag.slice(0, 80) });
}
}
if (pages === 0) {
@@ -141,15 +176,19 @@ if (withoutCsp.length > 0) {
}
if (offenders.length > 0) {
console.error(`CSP check FAILED — ${offenders.length} inline script(s) missing a hash:\n`);
console.error(`CSP check FAILED — ${offenders.length} inline script(s)/style(s) not allowed:\n`);
for (const o of offenders) {
console.error(` ${o.file}\n ${o.hash}\n ${o.preview}...\n`);
}
console.error(
"Fix: prefer a processed <script> (Astro bundles + hashes it), or for code that must\n" +
"run inline before paint, add it via injectScript('head-inline', ...) in astro.config.mjs.",
"run inline before paint, add it via injectScript('head-inline', ...) in astro.config.mjs.\n" +
"For styles: move the rules into a stylesheet the page always loads (src/styles/*.css)\n" +
"and replace style attributes with classes.",
);
process.exit(1);
}
console.log(`CSP check ok — ${scripts} inline scripts across ${pages} pages, all hashed.`);
console.log(
`CSP check ok — ${scripts} inline scripts and ${styles} style blocks across ${pages} pages, all hashed.`,
);
+1 -1
View File
@@ -36,7 +36,7 @@ const C = PALETTE.dark;
/** `a` blended into `b` at `weight` (0–1), as #rrggbb — Satori has no color-mix(). */
function mix(a, b, weight) {
const rgb = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
const [x, y] = [rgb(a), rgb(b)];
return `#${x
.map((v, i) =>
+3 -50
View File
@@ -1,4 +1,7 @@
---
// Styles live in src/styles/prose.css, not in a <style> block here: Callout is only ever
// rendered from MDX content, and Astro does not hash the styles of such components into the
// page's CSP — the browser dropped them (scripts/check-csp-hashes.mjs now checks styles too).
interface Props {
type?: "info" | "tip" | "warn";
title?: string;
@@ -14,53 +17,3 @@ const icon = { info: "i", tip: "★", warn: "!" }[type];
<slot />
</div>
</aside>
<style>
.callout {
display: flex;
gap: 0.75rem;
padding: 0.9rem 1rem;
border-radius: var(--radius-card);
border: 1px solid var(--line);
background: var(--surface);
font-family: var(--ff-body);
font-size: var(--text-body);
}
.callout-icon {
flex: none;
inline-size: 1.5rem;
block-size: 1.5rem;
display: grid;
place-items: center;
border-radius: 999px;
font-family: var(--ff-mono);
font-weight: 700;
font-size: 0.85rem;
color: var(--bg);
}
.callout-title {
font-weight: 600;
margin-block-end: 0.25rem;
}
.callout-body > :global(* + *) {
margin-block-start: 0.5em;
}
.callout.info {
border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
}
.callout.info .callout-icon {
background: var(--accent);
}
.callout.tip {
border-color: color-mix(in srgb, var(--ok) 40%, var(--line));
}
.callout.tip .callout-icon {
background: var(--ok);
}
.callout.warn {
border-color: color-mix(in srgb, var(--warn) 45%, var(--line));
}
.callout.warn .callout-icon {
background: var(--warn);
}
</style>
+49
View File
@@ -144,3 +144,52 @@
.prose .token.url {
color: var(--muted);
}
/* Callout (src/components/Callout.astro) — used from MDX content, so its rules live here. */
.callout {
display: flex;
gap: 0.75rem;
padding: 0.9rem 1rem;
border-radius: var(--radius-card);
border: 1px solid var(--line);
background: var(--surface);
font-family: var(--ff-body);
font-size: var(--text-body);
}
.callout-icon {
flex: none;
inline-size: 1.5rem;
block-size: 1.5rem;
display: grid;
place-items: center;
border-radius: 999px;
font-family: var(--ff-mono);
font-weight: 700;
font-size: 0.85rem;
color: var(--bg);
}
.callout-title {
font-weight: 600;
margin-block-end: 0.25rem;
}
.callout-body > * + * {
margin-block-start: 0.5em;
}
.callout.info {
border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
}
.callout.info .callout-icon {
background: var(--accent);
}
.callout.tip {
border-color: color-mix(in srgb, var(--ok) 40%, var(--line));
}
.callout.tip .callout-icon {
background: var(--ok);
}
.callout.warn {
border-color: color-mix(in srgb, var(--warn) 45%, var(--line));
}
.callout.warn .callout-icon {
background: var(--warn);
}
+10 -3
View File
@@ -72,7 +72,10 @@ function upstream(
{ type: "PushEvent" },
])
);
if (url.startsWith("https://i.ytimg.com/") || url.startsWith("https://media.steampowered.com/"))
if (
url.startsWith("https://i.ytimg.com/") ||
url.startsWith("https://cdn.cloudflare.steamstatic.com/")
)
return overrides.img?.(call) ?? image();
if (url.startsWith("https://discord.example/"))
return overrides.discord?.(call) ?? new Response(null, { status: 204 });
@@ -172,9 +175,13 @@ describe("widget sources", () => {
assert.ok(calls.some((c) => c.url.includes("key=key%26x")));
// Push, release, release-without-a-tag — WatchEvent skipped, capped at three.
assert.deepEqual(
(await fetchGitHub()).map((e) => e.detail),
(await fetchGitHub({})).map((e) => e.detail),
["2 commits", "v1", "release"],
);
const gh = calls.find((c) => c.url.startsWith("https://api.github.com/"));
assert.equal(gh?.headers.get("authorization"), null);
await fetchGitHub({ GITHUB_TOKEN: "ro-token" });
assert.equal(calls.at(-1)?.headers.get("authorization"), "Bearer ro-token");
assert.ok(kv.store.has(`widgets:img:steam:570:${HASH}`));
});
@@ -197,7 +204,7 @@ describe("widget sources", () => {
});
await assert.rejects(fetchYouTube(env(kv)), /youtube 500/);
await assert.rejects(fetchSteam(env(kv)), /steam 403/);
await assert.rejects(fetchGitHub(), /github 503/);
await assert.rejects(fetchGitHub({}), /github 503/);
});
});
+17 -4
View File
@@ -25,6 +25,12 @@ export interface WidgetsEnv {
STEAM_API_KEY: string;
STEAM_ID64: string;
DISCORD_WEBHOOK_CI?: string;
/**
* Optional, any fine-grained token with no permissions (public data only). Unauthenticated
* the events API allows 60 requests an hour per IP, and Workers share their egress IPs,
* so the GitHub feed goes stale for hours at a time without one.
*/
GITHUB_TOKEN?: string;
}
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -36,9 +42,13 @@ const IMAGE_TTL_SECONDS = 14 * 24 * 60 * 60;
const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
const IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);
const get = (url: string, accept?: string) =>
const get = (url: string, accept?: string, token?: string) =>
fetch(url, {
headers: { "user-agent": UA, ...(accept ? { accept } : {}) },
headers: {
"user-agent": UA,
...(accept ? { accept } : {}),
...(token ? { authorization: `Bearer ${token}` } : {}),
},
signal: AbortSignal.timeout(TIMEOUT_MS),
});
@@ -155,17 +165,20 @@ export async function fetchSteam(env: WidgetsEnv): Promise<GameItem[]> {
return Promise.all(
games.map(async ({ iconHash, ...game }) => {
if (!iconHash) return game;
const source = `https://media.steampowered.com/steamcommunity/public/images/apps/${game.appid}/${iconHash}.jpg`;
// media.steampowered.com answers Workers with 403; Steam's own Cloudflare CDN serves
// the same file.
const source = `https://cdn.cloudflare.steamstatic.com/steamcommunity/public/images/apps/${game.appid}/${iconHash}.jpg`;
const ok = await mirrorImage(env.KV, `steam:${game.appid}:${iconHash}`, source);
return { ...game, icon: ok ? `/ext-img/steam/${game.appid}/${iconHash}` : "" };
}),
);
}
export async function fetchGitHub(): Promise<GhItem[]> {
export async function fetchGitHub(env: Pick<WidgetsEnv, "GITHUB_TOKEN">): Promise<GhItem[]> {
const res = await get(
"https://api.github.com/users/poli0981/events/public?per_page=10",
"application/vnd.github+json",
env.GITHUB_TOKEN,
);
if (!res.ok) throw new Error(`github ${res.status}`);
return normalizeGitHub((await res.json()) as GhEvent[]);
+1 -1
View File
@@ -43,7 +43,7 @@ export default {
const sources: [Source, string, () => Promise<unknown[]>][] = [
["yt", "widgets:yt", () => fetchYouTube(env)],
["steam", "widgets:steam", () => fetchSteam(env)],
["gh", "widgets:gh", fetchGitHub],
["gh", "widgets:gh", () => fetchGitHub(env)],
];
const results = await Promise.all(
sources.map(([src, key, fetcher]) => refresh(env.KV, key, src, status, now, fetcher)),