Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7fbf1399a | ||
|
|
90ae9f4b80 | ||
|
|
fa48632276 | ||
|
|
9bb5350a34
|
||
|
|
66443e1153
|
||
|
|
9bccbff69b | ||
|
|
9a67566c6b
|
||
|
|
0c90719dde
|
||
|
|
a409b03813
|
||
|
|
604c756813
|
||
|
|
c13a37cfdc
|
||
|
|
f3d0546b0d
|
||
|
|
4cdf68de7d
|
||
|
|
7866666d26
|
||
|
|
6892027626
|
||
|
|
4e44f7a7f3
|
||
|
|
3511fbe9ae
|
||
|
|
f21bce9674
|
||
|
|
e90cc6fd65
|
||
|
|
9aefec3bd9
|
||
|
|
e32304443c
|
||
|
|
e528dcf6ac
|
||
|
|
ab544d8eba
|
||
|
|
7215d59f31
|
||
|
|
b2c5062a05
|
||
|
|
3948377cfe
|
||
|
|
bb03c4e9ca
|
||
|
|
407390c2f9
|
||
|
|
7c1bb3efea
|
||
|
|
7db93e2b3b
|
||
|
|
9e14ad89f4
|
||
|
|
2ef30458a4 |
No files matched your search
@@ -0,0 +1,298 @@
|
||||
name: CI
|
||||
|
||||
# PRs always run: `build` is the required status check of main's branch protection, so
|
||||
# a paths-ignore here would leave docs-only PRs waiting forever for a check that never
|
||||
# starts. Pushes to main may still skip docs-only changes — they deploy nothing either.
|
||||
# NOTE: use `*.md` (root-level) — NOT `**/*.md` — because blog/story content lives at
|
||||
# src/content/**/*.{md,mdx}.
|
||||
#
|
||||
# A push to main (and a dispatch on main) also deploys: the `deploy` job below.
|
||||
on:
|
||||
pull_request:
|
||||
# Dispatched on content/bump by content-bump.yml (PRs opened with GITHUB_TOKEN don't
|
||||
# trigger pull_request workflows), so the required `build` check exists for them.
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
|
||||
# Explicit, and granted per job: a grant made up here would reach every job, one added
|
||||
# later included.
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
# Cancel superseded PR runs; let main runs finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
# A hung `wrangler dev` in the smoke test must not hold a runner for six hours.
|
||||
timeout-minutes: 30
|
||||
# Job-level too, so a second job added later can't silently inherit something wider.
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
# Actions are pinned to commit SHAs, not tags: a tag is mutable, so `@v7` would
|
||||
# execute whatever that tag points at on the day CI runs. Dependabot's
|
||||
# github-actions ecosystem updates the pins and keeps the version comment in sync.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # check-exif diffs changed images against the base ref
|
||||
# src/content is a submodule (poli0981/content). Without this the content
|
||||
# collections resolve to an empty directory and the build fails on the
|
||||
# first getCollection() call.
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# No dependency lifecycle script runs in CI at all (docs 06 §6, anti-worm). None is
|
||||
# needed: esbuild, workerd and sharp take their platform binaries from
|
||||
# optionalDependencies — their install scripts only re-verify them — and lefthook's
|
||||
# only installs git hooks. Local installs stay guarded by package.json#allowScripts
|
||||
# plus .npmrc strict-allow-scripts.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
# …which also means npm's own strict-allow-scripts check never runs here. This keeps
|
||||
# the alarm: any lockfile package with an install script must be on allowScripts.
|
||||
- name: Install scripts allow-listed
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Binding types live in the gitignored worker-configuration.d.ts files, generated from
|
||||
# the wrangler configs; both type checks fail without them. No auth needed.
|
||||
# --strict-vars=false (in the script): `vars` are typed as string, not their literal
|
||||
# value, so code comparing e.g. GATE_MODE against "on" typechecks whatever it is set to.
|
||||
- name: Generate Cloudflare binding types
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
|
||||
- name: Format check
|
||||
run: npm run format:check
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
# .astro, .svelte and .ts through Volar — the TypeScript 6 API (TS 7.0 has none).
|
||||
- name: Type check (astro check)
|
||||
run: npm run check
|
||||
|
||||
# Every .ts file again with the native TypeScript 7 compiler, plus the widgets worker
|
||||
# (a separate TS project). The version line makes a bin mix-up impossible to miss.
|
||||
- name: Type check (TypeScript 7)
|
||||
run: |
|
||||
node node_modules/@typescript/native/bin/tsc --version
|
||||
npm run typecheck
|
||||
|
||||
- name: Dead code
|
||||
run: npm run knip
|
||||
|
||||
# node:test + V8 coverage. Fails under 80% lines.
|
||||
- name: Unit tests (coverage)
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: Audit (prod deps, high+)
|
||||
run: npm audit --omit=dev --audit-level=high
|
||||
|
||||
# THIRD-PARTY-NOTICES.md must match the direct dependencies, and every license must be
|
||||
# either on the allowlist or explicitly reviewed (docs 08 §6).
|
||||
- name: Third-party notices
|
||||
run: npm run gen-notices -- --check
|
||||
|
||||
# The same policy over every package in package-lock.json, transitive dependencies and
|
||||
# each platform's binaries included; anything outside it needs a per-package review.
|
||||
- name: Licences (whole dependency tree)
|
||||
run: npm run check-licenses
|
||||
|
||||
# Fail if any changed image under src/assets/ still carries GPS or a camera serial.
|
||||
- name: Check EXIF (changed images)
|
||||
env:
|
||||
DIFF_BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
run: npm run check-exif -- --changed
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# src/worker.ts fronts every page, so a crash there would take the static site down
|
||||
# too. Boot the built worker locally (wrangler dev, simulated bindings, no auth) and
|
||||
# probe pages, revalidation, HEAD, redirects, 404s, assets, the gate and the API.
|
||||
- name: Smoke test built worker
|
||||
run: npm run smoke
|
||||
|
||||
# Accessibility gate (ACCESSIBILITY.md). The same build is served by `astro preview`
|
||||
# (workerd, real bindings, no bot gate without its secrets) and driven by Chrome.
|
||||
# axe-core scans every page in the sitemap and the dialogs while open; the keyboard,
|
||||
# reflow and forced-colours checks follow. Runs inside this job because `build` is
|
||||
# the required status check.
|
||||
#
|
||||
# GitHub's ubuntu image shipped Google Chrome; the Gitea runner's image
|
||||
# (docker.gitea.com/runner-images) has none, so the job takes Playwright's own
|
||||
# Chromium at the version the lockfile pins (A11Y_CHANNEL=bundled, tests/a11y/
|
||||
# support.ts), cached per Playwright version. An image that has Chrome keeps using it.
|
||||
# The job container runs as root; Playwright starts Chromium without its sandbox by
|
||||
# default (chromiumSandbox: false), which is what a root user needs.
|
||||
- name: Which Chrome
|
||||
id: chrome
|
||||
run: |
|
||||
if [ -x /usr/bin/google-chrome ]; then
|
||||
echo "system=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "system=false" >> "$GITHUB_OUTPUT"
|
||||
echo "playwright=$(node -p "require('playwright/package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Cache Playwright's Chromium
|
||||
id: pw-cache
|
||||
if: steps.chrome.outputs.system != 'true'
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-chromium-${{ runner.os }}-${{ steps.chrome.outputs.playwright }}
|
||||
|
||||
# A cache hit restores the browser, not the system libraries it links.
|
||||
- name: Playwright's Chromium
|
||||
if: steps.chrome.outputs.system != 'true'
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.pw-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
if [ "$CACHE_HIT" = "true" ]; then
|
||||
npx playwright install-deps chromium
|
||||
else
|
||||
npx playwright install --with-deps chromium
|
||||
fi
|
||||
echo "A11Y_CHANNEL=bundled" >> "$GITHUB_ENV"
|
||||
|
||||
# One step, server and tests together: the Gitea runner (act) ends what a step started
|
||||
# in the background when that step ends. And on 127.0.0.1 explicitly: in the runner's
|
||||
# container `localhost` made the preview listen on ::1 only, while Node's fetch in the
|
||||
# tests went to 127.0.0.1 (PR #1's first runs: ECONNREFUSED on 4321).
|
||||
- name: Accessibility tests (axe + keyboard)
|
||||
env:
|
||||
A11Y_BASE_URL: http://127.0.0.1:4321
|
||||
run: |
|
||||
npm run preview -- --host 127.0.0.1 > "$RUNNER_TEMP/preview.log" 2>&1 &
|
||||
preview=$!
|
||||
up=false
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf -o /dev/null http://127.0.0.1:4321/; then
|
||||
echo "preview up after ${i}s"; up=true; break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "$up" != true ]; then
|
||||
echo "preview server never came up"; cat "$RUNNER_TEMP/preview.log"; exit 1
|
||||
fi
|
||||
status=0
|
||||
npm run test:a11y || status=$?
|
||||
if [ "$status" -ne 0 ]; then
|
||||
echo "--- preview server log (last 100 lines) ---"
|
||||
tail -n 100 "$RUNNER_TEMP/preview.log" || true
|
||||
fi
|
||||
kill "$preview" 2>/dev/null || true
|
||||
exit "$status"
|
||||
|
||||
# Content publish, second half (content-bump.yml is the first): when the admin's publish
|
||||
# dispatched this run on content/bump, record `build`'s result as the commit status main's
|
||||
# branch protection requires — Gitea writes none for a dispatched run, so without this the
|
||||
# merge is refused (405) — and, when it passed, merge the content/bump PR (Markdown/JSON
|
||||
# only — an MDX publish waits for a review) and dispatch this workflow on main, which
|
||||
# deploys. The dispatch is needed because nothing the job token does starts a workflow, its
|
||||
# merge commit included. If the merge is refused, the job fails and says so on the PR; a
|
||||
# merge by hand deploys as usual. `always()`: a failed build is recorded too, so the admin
|
||||
# shows "xuất bản lỗi" instead of building forever.
|
||||
publish:
|
||||
needs: build
|
||||
if: always() && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/content/bump'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: write # the commit status, the merge
|
||||
pull-requests: write # the merge, a comment when it fails
|
||||
actions: write # dispatch ci.yml on main
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Record the build, merge the publish PR, deploy main
|
||||
env:
|
||||
TOKEN: ${{ github.token }}
|
||||
API: ${{ github.api_url }}
|
||||
REPO: ${{ github.repository }}
|
||||
SHA: ${{ github.sha }}
|
||||
BUILD: ${{ needs.build.result }}
|
||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
run: node scripts/content-publish.mjs merge
|
||||
|
||||
# Production. Cloudflare Workers Builds pulled from GitHub and stopped with it, so main
|
||||
# deploys from here (migration decision D3): after `build` passed on the same commit,
|
||||
# rebuild with the production settings and `wrangler deploy` at 100%. Nothing else
|
||||
# deploys: PRs and other branches get no preview versions, which would put the Cloudflare
|
||||
# token within reach of a PR's code (Gitea gives same-repo PRs the secrets, Renovate's
|
||||
# included).
|
||||
#
|
||||
# The workflow's concurrency group keeps main runs in order and never cancels one, so two
|
||||
# quick merges deploy one after the other, the newer last. The runner lives on the
|
||||
# maintainer's PC: a merge made while it is off deploys when it comes back.
|
||||
deploy:
|
||||
needs: build
|
||||
if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: recursive # the content, and HEAD:src/content for /api/health
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
# What Workers Builds' build variables did: the Turnstile site key (public — every
|
||||
# gated page carries it) is inlined into the client, and the Cloudflare Web Analytics
|
||||
# beacon is switched on for production builds only (astro.config.mjs). GITHUB_SHA,
|
||||
# which Gitea sets too, becomes the commit /api/health reports.
|
||||
- name: Build (production)
|
||||
env:
|
||||
PUBLIC_TURNSTILE_SITE_KEY: "0x4AAAAAAD5Cup6ayN5o78wu"
|
||||
PUBLIC_CF_BEACON: "true"
|
||||
run: npm run build
|
||||
|
||||
# Token scope (docs 07): Account → Workers Scripts: Edit, plus what the bindings
|
||||
# need to resolve (KV, R2, routes and custom domains on the zone). User-level
|
||||
# Actions secrets on Gitea, shared by the web repos. Plain `wrangler` finds the
|
||||
# generated config on its own: the build writes .wrangler/deploy/config.json
|
||||
# pointing at dist/server/wrangler.json.
|
||||
- name: Deploy to Cloudflare Workers
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
WRANGLER_SEND_METRICS: "false"
|
||||
run: npx wrangler deploy --message "main ${GITHUB_SHA:0:7}"
|
||||
|
||||
# The deploy is live when the site says so: /api/health reports the commit of the
|
||||
# build it runs (src/lib/version.ts).
|
||||
- name: Live
|
||||
run: |
|
||||
for i in $(seq 1 30); do
|
||||
live=$(curl -fsS https://poli0981.dev/api/health | node -e '
|
||||
let s = ""; process.stdin.on("data", (d) => (s += d));
|
||||
process.stdin.on("end", () => { try { console.log(JSON.parse(s).version.commit ?? ""); } catch { console.log(""); } });
|
||||
' || true)
|
||||
if [ "$live" = "$GITHUB_SHA" ]; then echo "live: $live"; exit 0; fi
|
||||
sleep 4
|
||||
done
|
||||
echo "::error::/api/health still reports ${live:-nothing}, not $GITHUB_SHA"
|
||||
exit 1
|
||||
@@ -0,0 +1,87 @@
|
||||
name: Content publish
|
||||
|
||||
# "Publish" in the admin (admin.poli0981.dev) dispatches this, and so does every admin save.
|
||||
# It points the src/content submodule at poli0981/content's main, commits that on the
|
||||
# content/bump branch, opens (or updates) a PR, and starts CI on the bump commit. When only
|
||||
# Markdown/JSON changed, CI's `publish` job merges the PR once `build` passed there and
|
||||
# starts the deploy of main (ci.yml).
|
||||
#
|
||||
# Why a workflow: the admin's token never pushes code to this repository; the most it can
|
||||
# do here is start this workflow. MDX runs code at build time, so a publish that touches
|
||||
# anything other than .md/.json waits for a human review instead of merging itself.
|
||||
#
|
||||
# Gitea, not GitHub (migration decision D5): `gh` is gone, the PR and the CI dispatch are
|
||||
# plain calls to Gitea's API with the job token. A PR opened with the job token starts no
|
||||
# workflow, so CI is dispatched on content/bump. Whether the PR merges by itself is in its
|
||||
# body (`<!-- publish: auto -->` or `<!-- publish: review -->`), where the admin reads it:
|
||||
# Gitea's API has no auto-merge field.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
# One run at a time, never cancelled: a run waiting behind a running one reads the newest
|
||||
# content main when it starts, so quick saves in a row end in one more publish, not many.
|
||||
concurrency:
|
||||
group: content-bump
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
bump:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write # push content/bump
|
||||
pull-requests: write # open or update the PR, comment on it
|
||||
actions: write # dispatch ci.yml on the bump commit
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Point src/content at content main
|
||||
id: bump
|
||||
run: |
|
||||
git -C src/content fetch --quiet origin main
|
||||
old=$(git rev-parse HEAD:src/content)
|
||||
new=$(git -C src/content rev-parse FETCH_HEAD)
|
||||
echo "new=$new" >> "$GITHUB_OUTPUT"
|
||||
if [ "$old" = "$new" ]; then
|
||||
echo "Already published ($new)."
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
files=$(git -C src/content diff --name-only "$old" "$new")
|
||||
echo "$files"
|
||||
if echo "$files" | grep -qvE '\.(md|json)$'; then auto=false; else auto=true; fi
|
||||
git -C src/content checkout --quiet "$new"
|
||||
{
|
||||
echo "changed=true"
|
||||
echo "auto=$auto"
|
||||
echo "files<<EOF"
|
||||
echo "$files"
|
||||
echo "EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Commit and push content/bump
|
||||
if: steps.bump.outputs.changed == 'true'
|
||||
env:
|
||||
NEW: ${{ steps.bump.outputs.new }}
|
||||
FILES: ${{ steps.bump.outputs.files }}
|
||||
run: |
|
||||
git config user.name "Content publish"
|
||||
git config user.email "actions@noreply.git.poli0981.dev"
|
||||
git switch --create content/bump
|
||||
git add src/content
|
||||
git commit --quiet -m "chore(content): publish ${NEW:0:7}" -m "$FILES"
|
||||
git push --force --quiet origin content/bump
|
||||
|
||||
- name: Open or update the PR, queue CI
|
||||
if: steps.bump.outputs.changed == 'true'
|
||||
env:
|
||||
TOKEN: ${{ github.token }}
|
||||
API: ${{ github.api_url }}
|
||||
REPO: ${{ github.repository }}
|
||||
NEW: ${{ steps.bump.outputs.new }}
|
||||
AUTO: ${{ steps.bump.outputs.auto }}
|
||||
run: node scripts/content-publish.mjs open
|
||||
@@ -0,0 +1,148 @@
|
||||
name: Lighthouse
|
||||
|
||||
# docs 14 §3: assert the perf budget on a preview build — WARN ONLY, never blocking.
|
||||
# Lighthouse numbers move with runner load, so a hard gate here would block deploys on
|
||||
# noise rather than on regressions. The job is advisory by construction: assertions are
|
||||
# `warn`, and it is not a required check of main's branch protection (Gitea still shows a
|
||||
# failed run red, continue-on-error or not). Per the doc, act when it goes red twice in a
|
||||
# row rather than on a single bad run.
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lighthouse:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
# The whole point: informative, never a blocker.
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
# Lighthouse CI itself, at a pinned version (released 2026-11-11). It was bundled in
|
||||
# treosh/lighthouse-ci-action, which the Gitea runner cannot unpack (two files in its
|
||||
# node_modules differ only in case, and the runner's action cache sits on a
|
||||
# case-insensitive Windows disk). npx installs it in the job container instead; the
|
||||
# job holds no secret. Bump by hand: Renovate does not read this line.
|
||||
LHCI_VERSION: 0.16.1
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: recursive # src/content, or the build has no content to measure
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same as ci.yml: no dependency lifecycle scripts in CI.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Generate Cloudflare binding types
|
||||
run: npm run types
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# GitHub's image shipped Google Chrome; the Gitea runner's image has none, so Lighthouse
|
||||
# gets Playwright's Chromium at the version the lockfile pins (CHROME_PATH is what
|
||||
# chrome-launcher reads). The job runs as root, where Chrome refuses to start with its
|
||||
# sandbox on: lighthouserc.json passes --no-sandbox (the pages are this build, on
|
||||
# localhost).
|
||||
- name: Chrome for Lighthouse
|
||||
run: |
|
||||
if [ -x /usr/bin/google-chrome ]; then
|
||||
echo "CHROME_PATH=/usr/bin/google-chrome" >> "$GITHUB_ENV"
|
||||
else
|
||||
npx playwright install --with-deps chromium
|
||||
echo "CHROME_PATH=$(node -p "require('playwright').chromium.executablePath()")" >> "$GITHUB_ENV"
|
||||
fi
|
||||
|
||||
# Cloudflare's edge compresses every text response in production; the preview does not.
|
||||
# Lighthouse measures through nginx (gzip — a little larger than the edge's brotli) so
|
||||
# its simulated phone downloads about the bytes a real one would (home HTML 108 KB raw,
|
||||
# 25–30 KB compressed), not three to four times as many. GitHub's image had nginx and a
|
||||
# user with sudo; the Gitea runner's job container runs as root and has no nginx.
|
||||
- name: nginx for the compressing proxy
|
||||
run: |
|
||||
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO=sudo
|
||||
if ! command -v nginx >/dev/null; then
|
||||
$SUDO apt-get update -qq
|
||||
$SUDO apt-get install -y -qq --no-install-recommends nginx
|
||||
fi
|
||||
cat > "$RUNNER_TEMP/nginx.conf" <<'EOF'
|
||||
events {}
|
||||
http {
|
||||
access_log off;
|
||||
gzip on;
|
||||
gzip_proxied any;
|
||||
gzip_comp_level 6;
|
||||
gzip_vary on;
|
||||
gzip_types text/css text/javascript application/javascript application/json
|
||||
application/manifest+json application/xml image/svg+xml;
|
||||
server {
|
||||
listen 127.0.0.1:4322;
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:4321;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Accept-Encoding "";
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
$SUDO nginx -t -c "$RUNNER_TEMP/nginx.conf"
|
||||
|
||||
# Everything that has to stay up runs in this one step: the Gitea runner (act) ends what
|
||||
# a step started in the background when that step ends. `astro preview` boots the built
|
||||
# worker in workerd with the real bindings and _headers, so the numbers reflect
|
||||
# production rather than a bare static server.
|
||||
#
|
||||
# Four representative pages (docs 14 §3): home, a blog post, a story chapter, a gallery
|
||||
# album — the heaviest template of each kind — collected and asserted against
|
||||
# lighthouserc.json (warn-only). Nothing is uploaded to Google's public storage.
|
||||
- name: Lighthouse
|
||||
run: |
|
||||
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO=sudo
|
||||
# 127.0.0.1, not localhost: in the runner's container `localhost` binds ::1 only.
|
||||
npm run preview -- --host 127.0.0.1 > "$RUNNER_TEMP/preview.log" 2>&1 &
|
||||
$SUDO nginx -c "$RUNNER_TEMP/nginx.conf"
|
||||
up=false
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf -o /dev/null http://127.0.0.1:4322/; then
|
||||
echo "preview up after ${i}s"; up=true; break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "$up" != true ]; then
|
||||
echo "preview server never came up"; cat "$RUNNER_TEMP/preview.log"; exit 1
|
||||
fi
|
||||
# --ignore-scripts: nothing in Lighthouse CI needs an install script, and the repo's
|
||||
# .npmrc (strict-allow-scripts) would refuse any it does not know.
|
||||
lhci() { npx --yes --ignore-scripts "@lhci/cli@${LHCI_VERSION}" "$@"; }
|
||||
lhci collect --config=./lighthouserc.json \
|
||||
--url=http://127.0.0.1:4322/ \
|
||||
--url=http://127.0.0.1:4322/blog/lan-dau-viet-truyen/ \
|
||||
--url=http://127.0.0.1:4322/truyen/dem-khong-tieng/chuong-01/ \
|
||||
--url=http://127.0.0.1:4322/gallery/game/
|
||||
lhci assert --config=./lighthouserc.json
|
||||
|
||||
# The reports, kept even when an assertion warns. An upload never decides the job.
|
||||
- name: Keep the reports
|
||||
if: ${{ !cancelled() }}
|
||||
continue-on-error: true
|
||||
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: lighthouse-reports
|
||||
path: .lighthouseci/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,131 @@
|
||||
name: Qodana
|
||||
|
||||
# JetBrains Qodana (Qodana for JS, WebStorm's inspections) over the whole repository: on every
|
||||
# PR, on main and by hand. Settings live in qodana.yaml; its failThreshold makes any finding
|
||||
# fail the scan. Results go to Qodana Cloud (the project token is the QODANA_TOKEN secret) and
|
||||
# into the `qodana-report` artifact (SARIF + HTML report): Gitea has no code-scanning UI, so
|
||||
# the SARIF upload of the GitHub days is gone.
|
||||
#
|
||||
# The Qodana CLI, not JetBrains/qodana-action (which relies on GitHub's APIs for annotations
|
||||
# and comments), at a pinned version, SHA-256 verified — the version and checksum the ops
|
||||
# repo's reusable-qodana.yml pins. Renovate does not update it (it is not an action): bump
|
||||
# both together, by hand. A local job rather than a caller of that reusable workflow: the
|
||||
# scan needs this repo's generated binding types first, and the ops tag callers pin
|
||||
# (v2026.11.1) predates the reusable one.
|
||||
#
|
||||
# Advisory, not required: branch protection requires only CI's `build`. Renovate's PRs skip
|
||||
# it — Gitea gives a same-repo PR the repository's secrets, and a Renovate run installs the
|
||||
# very update under review, so no token goes near it — as does a run without the token.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
# Explicit, and granted on the job.
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
# Cancel superseded PR runs; let main runs finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
qodana:
|
||||
name: Qodana for JS
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
QODANA_CLI_VERSION: 2026.3.1
|
||||
QODANA_CLI_SHA256: dae6d31f481ed15c6c016fd746e907978f0c1437010326fa04a92f13c7c52338 # qodana_linux_x86_64.tar.gz
|
||||
steps:
|
||||
- name: Check for QODANA_TOKEN
|
||||
id: token
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
run: |
|
||||
if [ "$ACTOR" = renovate-bot ] || [ "$AUTHOR" = renovate-bot ]; then
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Qodana skipped — a Renovate pull request installs the update under review, so no token goes near it."
|
||||
elif [ -n "$QODANA_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::Qodana skipped — QODANA_TOKEN is not available to this run."
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
if: steps.token.outputs.present == 'true'
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
if: steps.token.outputs.present == 'true'
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same rules as ci.yml: no dependency lifecycle script runs in CI, and any lockfile
|
||||
# package with an install script must be on package.json#allowScripts.
|
||||
- name: Install
|
||||
if: steps.token.outputs.present == 'true'
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Install scripts allow-listed
|
||||
if: steps.token.outputs.present == 'true'
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Gitignored, generated types the TypeScript service needs to resolve imports of
|
||||
# cloudflare:workers, astro:content and friends.
|
||||
- name: Generate types
|
||||
if: steps.token.outputs.present == 'true'
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
npm run astro -- sync
|
||||
|
||||
- name: Install the Qodana CLI ${{ env.QODANA_CLI_VERSION }}
|
||||
if: steps.token.outputs.present == 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tmp="${RUNNER_TEMP:-/tmp}"
|
||||
tgz="$tmp/qodana.tar.gz"
|
||||
curl --proto '=https' -fsSL --retry 3 -o "$tgz" \
|
||||
"https://github.com/JetBrains/qodana-cli/releases/download/v${QODANA_CLI_VERSION}/qodana_linux_x86_64.tar.gz"
|
||||
echo "${QODANA_CLI_SHA256} $tgz" | sha256sum -c -
|
||||
mkdir -p "$tmp/qodana-cli"
|
||||
tar -xzf "$tgz" -C "$tmp/qodana-cli" qodana
|
||||
echo "$tmp/qodana-cli" >> "$GITHUB_PATH"
|
||||
|
||||
# Whole repository every time (it is small), so the quality gate in qodana.yaml always
|
||||
# judges the full picture rather than the files a PR happens to touch. Native mode
|
||||
# (qodana.yaml: withinDocker: false): the job already is a container.
|
||||
- name: Qodana scan
|
||||
if: steps.token.outputs.present == 'true'
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
QODANA_ENDPOINT: https://qodana.cloud
|
||||
run: |
|
||||
qodana --version
|
||||
qodana scan --within-docker false \
|
||||
--results-dir "${RUNNER_TEMP:-/tmp}/qodana/results" \
|
||||
--cache-dir "${RUNNER_TEMP:-/tmp}/qodana/cache"
|
||||
|
||||
# !cancelled(), not the implicit success(): a scan that finds something fails, and
|
||||
# those are exactly the findings the report must keep. An upload never decides the job.
|
||||
- name: Keep the report
|
||||
if: ${{ !cancelled() && steps.token.outputs.present == 'true' }}
|
||||
continue-on-error: true
|
||||
uses: christopherhx/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
|
||||
with:
|
||||
name: qodana-report
|
||||
path: ${{ runner.temp }}/qodana/results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,37 @@
|
||||
# Security checks from the ops repo (poli0981/.github, runbook §3.5 item 2 and §4.3).
|
||||
#
|
||||
# secrets → gitleaks over the whole git history; fails on a finding
|
||||
# sast → Opengrep: the workflow, Dockerfile and shell rules always, plus the
|
||||
# JavaScript / TypeScript rules (`node: true`); the SARIF report is an
|
||||
# artifact, since Gitea has no code-scanning UI
|
||||
# deps → osv-scanner over package-lock.json; fails on a known vulnerability
|
||||
#
|
||||
# It replaces osv-scanner.yml (Google's reusable workflow, which uploaded SARIF to GitHub
|
||||
# code scanning): the dependency scan is the same database over the same lockfile, now
|
||||
# next to the secrets and SAST checks. ci.yml keeps its per-PR `npm audit` gate.
|
||||
#
|
||||
# The reusable workflow is pinned to the commit of the ops repo's tag. Renovate does not
|
||||
# bump this pin: the `# ops …` comment is no version it reads (runbook §3.2 item 3).
|
||||
# Move it by hand when the ops repo is tagged. No secrets: nothing here needs a token.
|
||||
name: Security
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
schedule:
|
||||
# Wednesdays 14:13 UTC = 21:13 Vietnam: inside the 13:00–16:00 UTC window when the
|
||||
# runner's PC is on, on this repo's slot in the ops repo's cron registry.
|
||||
- cron: "13 14 * * 3"
|
||||
workflow_dispatch:
|
||||
|
||||
# Explicit, never inherited, and granted on the job.
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
security:
|
||||
permissions:
|
||||
contents: read
|
||||
uses: poli0981/.github/.gitea/workflows/security.yml@2a255e0e9a60541da5c25fb4ad5cc24bd353d543 # ops v2026.11.1
|
||||
with:
|
||||
node: true
|
||||
@@ -7,10 +7,10 @@ body:
|
||||
attributes:
|
||||
value: |
|
||||
Cảm ơn bạn đã báo lỗi. / Thanks for reporting.
|
||||
Nhanh hơn: nút "Báo lỗi" ngay trên trang gửi kèm trang và môi trường đang dùng (báo cáo đó đi
|
||||
vào một repo riêng, không hiện ở đây). / Quicker: the "Report a problem" button on the page
|
||||
itself sends the page and environment along (those reports go to a private repository and
|
||||
do not show up here).
|
||||
Nhanh hơn: nút "Báo lỗi" ngay trên trang gửi kèm trang và môi trường đang dùng (báo cáo đó
|
||||
thành issue bảo mật, chỉ chủ repo xem được). / Quicker: the "Report a problem" button on the
|
||||
page itself sends the page and environment along (those reports become confidential issues
|
||||
only the maintainer can see).
|
||||
Dự án đang ở chế độ bảo trì: form này dành cho lỗi, không dành cho đề xuất tính năng — xem
|
||||
CONTRIBUTING.md. / The project is in maintenance mode: this form is for bugs, not feature
|
||||
requests — see CONTRIBUTING.md.
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
# Maintenance mode (CONTRIBUTING.md): issues are for bugs, accessibility and language problems.
|
||||
# Questions and ideas go to Discussions; security problems are reported privately.
|
||||
# Gitea reads these forms; outsiders file issues on the GitLab mirror (.gitlab/issue_templates).
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Question or idea · Câu hỏi hoặc ý tưởng
|
||||
url: https://github.com/poli0981/poli0981-dev/discussions
|
||||
url: mailto:code@poli0981.dev
|
||||
about: >-
|
||||
The project is in maintenance mode and takes no new features — ask or talk ideas over in
|
||||
Discussions. · Dự án đang ở chế độ bảo trì, không nhận tính năng mới — hỏi hoặc trao đổi
|
||||
ý tưởng trong Discussions.
|
||||
The project is in maintenance mode and takes no new features — ask or share ideas by e-mail.
|
||||
· Dự án đang ở chế độ bảo trì, không nhận tính năng mới — hỏi hoặc gửi ý tưởng qua e-mail.
|
||||
- name: Security vulnerability · Lỗ hổng bảo mật
|
||||
url: https://github.com/poli0981/poli0981-dev/security/policy
|
||||
about: Report it privately, never in a public issue. · Báo riêng, không mở issue công khai.
|
||||
url: https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/SECURITY.md
|
||||
about: Report it by e-mail, never in a public issue. · Báo qua e-mail, không mở issue công khai.
|
||||
@@ -1,45 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
# Root npm project. `/workers/widgets` is omitted on purpose: that worker is
|
||||
# dependency-free (no package.json, the YouTube RSS is hand-parsed), so there is no
|
||||
# manifest for Dependabot to read. Add an entry the day that worker gains a package.json.
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
# Supply-chain hardening (docs 06 §6): never propose a release younger than three days.
|
||||
# Malicious publishes — the Shai-Hulud shape — are usually caught and pulled within hours.
|
||||
cooldown:
|
||||
default-days: 3
|
||||
open-pull-requests-limit: 8
|
||||
groups:
|
||||
astro:
|
||||
patterns: ["astro", "@astrojs/*"]
|
||||
# The type-checking toolchain moves together: typescript-eslint pins the TypeScript
|
||||
# versions it accepts.
|
||||
typescript:
|
||||
patterns: ["typescript", "typescript-eslint"]
|
||||
dev-tools:
|
||||
dependency-type: development
|
||||
ignore:
|
||||
# `typescript` stays on 6.x on purpose. TypeScript 7.0 ships no JS API, and astro
|
||||
# check (Volar), typescript-eslint and svelte2tsx all need one. TS 7 itself is the
|
||||
# `@typescript/native` alias (npm:typescript@7) — and Dependabot skips every `npm:`
|
||||
# alias, so that one is bumped by hand (docs 17). Lift this ignore once those tools
|
||||
# support TypeScript 7.1's new API.
|
||||
- dependency-name: typescript
|
||||
update-types: ["version-update:semver-major"]
|
||||
# prettier-plugin-astro 1.x reflows `<span>{expr}</span>` onto separate lines in 50
|
||||
# .astro files, which inserts whitespace text nodes inside inline elements. That is a
|
||||
# visual change, not a formatting one — it needs its own PR with a rendered diff.
|
||||
- dependency-name: prettier-plugin-astro
|
||||
update-types: ["version-update:semver-major"]
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
cooldown:
|
||||
default-days: 3
|
||||
@@ -4,8 +4,8 @@
|
||||
|
||||
## Kind of change
|
||||
|
||||
The project is in maintenance mode ([CONTRIBUTING.md](https://github.com/poli0981/poli0981-dev/blob/main/CONTRIBUTING.md)):
|
||||
new features are not accepted, and a `feat:` pull request is closed automatically.
|
||||
The project is in maintenance mode ([CONTRIBUTING.md](https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/CONTRIBUTING.md)):
|
||||
new features are not accepted, and a `feat:` pull request is closed.
|
||||
|
||||
- [ ] Dependency update
|
||||
- [ ] Security fix (High/Critical advisory, or a runtime vulnerability)
|
||||
@@ -20,7 +20,7 @@ new features are not accepted, and a `feat:` pull request is closed automaticall
|
||||
|
||||
## Accessibility (only if the interface changed)
|
||||
|
||||
See [`ACCESSIBILITY.md`](https://github.com/poli0981/poli0981-dev/blob/main/ACCESSIBILITY.md).
|
||||
See [`ACCESSIBILITY.md`](https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/ACCESSIBILITY.md).
|
||||
`npm run test:a11y` covers what a machine can check; the rest is by hand.
|
||||
|
||||
- [ ] Works with the keyboard alone, start to finish; focus is visible and never lands under a fixed bar
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
name: CI
|
||||
|
||||
# PRs always run: `build` is a required status check in the main ruleset, so a
|
||||
# paths-ignore here would leave docs-only PRs waiting forever for a check that never
|
||||
# starts. Pushes to main may still skip docs-only changes. NOTE: use `*.md` (root-level)
|
||||
# — NOT `**/*.md` — because blog/story content lives at src/content/**/*.{md,mdx}.
|
||||
on:
|
||||
pull_request:
|
||||
# Dispatched on content/bump by content-bump.yml (PRs opened with GITHUB_TOKEN don't
|
||||
# trigger pull_request workflows), so the required `build` check exists for them.
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
|
||||
# Explicit — a missing block makes GitHub default every scope to `none`.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
# Cancel superseded PR runs; let main runs finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
# A hung `wrangler dev` in the smoke test must not hold a runner for six hours.
|
||||
timeout-minutes: 30
|
||||
# Job-level too, so a second job added later can't silently inherit something wider.
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
# Actions are pinned to commit SHAs, not tags: a tag is mutable, so `@v7` would
|
||||
# execute whatever that tag points at on the day CI runs. Dependabot's
|
||||
# github-actions ecosystem updates the pins and keeps the version comment in sync.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # check-exif diffs changed images against the base ref
|
||||
# src/content is a submodule (poli0981/content). Without this the content
|
||||
# collections resolve to an empty directory and the build fails on the
|
||||
# first getCollection() call.
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# No dependency lifecycle script runs in CI at all (docs 06 §6, anti-worm). None is
|
||||
# needed: esbuild, workerd and sharp take their platform binaries from
|
||||
# optionalDependencies — their install scripts only re-verify them — and lefthook's
|
||||
# only installs git hooks. Local installs stay guarded by package.json#allowScripts
|
||||
# plus .npmrc strict-allow-scripts.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
# …which also means npm's own strict-allow-scripts check never runs here. This keeps
|
||||
# the alarm: any lockfile package with an install script must be on allowScripts.
|
||||
- name: Install scripts allow-listed
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Binding types live in the gitignored worker-configuration.d.ts files, generated from
|
||||
# the wrangler configs; both type checks fail without them. No auth needed.
|
||||
# --strict-vars=false (in the script): `vars` are typed as string, not their literal
|
||||
# value, so code comparing e.g. GATE_MODE against "on" typechecks whatever it is set to.
|
||||
- name: Generate Cloudflare binding types
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
|
||||
- name: Format check
|
||||
run: npm run format:check
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
# .astro, .svelte and .ts through Volar — the TypeScript 6 API (TS 7.0 has none).
|
||||
- name: Type check (astro check)
|
||||
run: npm run check
|
||||
|
||||
# Every .ts file again with the native TypeScript 7 compiler, plus the widgets worker
|
||||
# (a separate TS project). The version line makes a bin mix-up impossible to miss.
|
||||
- name: Type check (TypeScript 7)
|
||||
run: |
|
||||
node node_modules/@typescript/native/bin/tsc --version
|
||||
npm run typecheck
|
||||
|
||||
- name: Dead code
|
||||
run: npm run knip
|
||||
|
||||
# node:test + V8 coverage. Fails under 80% lines; writes coverage/lcov.info for the
|
||||
# SonarCloud job below.
|
||||
- name: Unit tests (coverage)
|
||||
run: npm run test:coverage
|
||||
|
||||
- name: Audit (prod deps, high+)
|
||||
run: npm audit --omit=dev --audit-level=high
|
||||
|
||||
# THIRD-PARTY-NOTICES.md must match the direct dependencies, and every license must be
|
||||
# either on the allowlist or explicitly reviewed (docs 08 §6).
|
||||
- name: Third-party notices
|
||||
run: npm run gen-notices -- --check
|
||||
|
||||
# The same policy over every package in package-lock.json, transitive dependencies and
|
||||
# each platform's binaries included; anything outside it needs a per-package review.
|
||||
- name: Licences (whole dependency tree)
|
||||
run: npm run check-licenses
|
||||
|
||||
# Fail if any changed image under src/assets/ still carries GPS or a camera serial.
|
||||
- name: Check EXIF (changed images)
|
||||
env:
|
||||
DIFF_BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
|
||||
run: npm run check-exif -- --changed
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# src/worker.ts fronts every page, so a crash there would take the static site down
|
||||
# too. Boot the built worker locally (wrangler dev, simulated bindings, no auth) and
|
||||
# probe pages, revalidation, HEAD, redirects, 404s, assets, the gate and the API.
|
||||
- name: Smoke test built worker
|
||||
run: npm run smoke
|
||||
|
||||
# Accessibility gate (ACCESSIBILITY.md). The same build is served by `astro preview`
|
||||
# (workerd, real bindings, no bot gate without its secrets) and driven with the
|
||||
# runner's own Chrome — Playwright downloads no browser. axe-core scans every page in
|
||||
# the sitemap and the dialogs while open; the keyboard, reflow and forced-colours
|
||||
# checks follow. Runs inside this job because `build` is the required status check.
|
||||
- name: Start preview server
|
||||
run: |
|
||||
npm run preview > "$RUNNER_TEMP/preview.log" 2>&1 &
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf -o /dev/null http://localhost:4321/; then
|
||||
echo "preview up after ${i}s"; exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "preview server never came up"; cat "$RUNNER_TEMP/preview.log"; exit 1
|
||||
|
||||
- name: Accessibility tests (axe + keyboard)
|
||||
run: npm run test:a11y
|
||||
|
||||
- name: Preview server log (on failure)
|
||||
if: failure()
|
||||
run: tail -n 100 "$RUNNER_TEMP/preview.log" || true
|
||||
|
||||
- name: Upload coverage
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: coverage
|
||||
path: coverage/lcov.info
|
||||
retention-days: 7
|
||||
if-no-files-found: error
|
||||
|
||||
# Deployment is Cloudflare Workers Builds (connected to this repo), not GitHub
|
||||
# Actions — this workflow is CI gates only. Workers Builds settings (docs 07): deploy
|
||||
# command `npx wrangler deploy` on main, version command `npx wrangler versions upload`
|
||||
# on every other branch. Plain `wrangler` finds the generated config on its own: the
|
||||
# build writes .wrangler/deploy/config.json pointing at dist/server/wrangler.json.
|
||||
|
||||
# The SonarCloud analysis (automatic analysis is switched off; this is the only one).
|
||||
# Needs SONAR_TOKEN, which Dependabot runs and forks never get, so those skip it, as do
|
||||
# the content/bump dispatches (content only, no code to analyze).
|
||||
sonarcloud:
|
||||
needs: build
|
||||
if: >-
|
||||
github.event_name == 'push' ||
|
||||
(github.event_name == 'pull_request' &&
|
||||
github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
github.actor != 'dependabot[bot]')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0 # blame data and new-code detection need the whole history
|
||||
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: coverage
|
||||
path: coverage
|
||||
|
||||
# Settings live in sonar-project.properties. On pull requests the job waits for the
|
||||
# quality gate and fails with it, so a red gate is visible on the PR; on main it only
|
||||
# reports (the gate there is a trend, not a merge decision).
|
||||
- name: SonarCloud scan
|
||||
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
with:
|
||||
args: >-
|
||||
${{ github.event_name == 'pull_request' && '-Dsonar.qualitygate.wait=true -Dsonar.qualitygate.timeout=300' || '' }}
|
||||
@@ -1,88 +0,0 @@
|
||||
name: Content publish
|
||||
|
||||
# "Publish" in the admin (admin.poli0981.dev) dispatches this. It points the src/content
|
||||
# submodule at poli0981/content's main, commits that on the content/bump branch, opens
|
||||
# (or updates) a PR and, when only Markdown/JSON changed, enables auto-merge. CI then runs
|
||||
# on the bump commit; when the required `build` check passes the PR merges itself and
|
||||
# Workers Builds deploys main.
|
||||
#
|
||||
# Why a workflow: the admin's token can write ONLY the content repo (+ dispatch this). If
|
||||
# it leaked, the worst case is content edits — never code pushed to this repo. MDX runs
|
||||
# code at build time, so anything other than .md/.json waits for a human review.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: content-bump
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
bump:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # push content/bump
|
||||
pull-requests: write # open the PR, enable auto-merge
|
||||
actions: write # run ci.yml on the bump commit
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: true
|
||||
|
||||
- name: Point src/content at content main
|
||||
id: bump
|
||||
run: |
|
||||
git -C src/content fetch --quiet origin main
|
||||
old=$(git rev-parse HEAD:src/content)
|
||||
new=$(git -C src/content rev-parse FETCH_HEAD)
|
||||
echo "new=$new" >> "$GITHUB_OUTPUT"
|
||||
if [ "$old" = "$new" ]; then
|
||||
echo "Already published ($new)."
|
||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
files=$(git -C src/content diff --name-only "$old" "$new")
|
||||
echo "$files"
|
||||
if echo "$files" | grep -qvE '\.(md|json)$'; then auto=false; else auto=true; fi
|
||||
git -C src/content checkout --quiet "$new"
|
||||
{
|
||||
echo "changed=true"
|
||||
echo "auto=$auto"
|
||||
echo "files<<EOF"
|
||||
echo "$files"
|
||||
echo "EOF"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Commit, open/update the PR, queue CI
|
||||
if: steps.bump.outputs.changed == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
NEW: ${{ steps.bump.outputs.new }}
|
||||
AUTO: ${{ steps.bump.outputs.auto }}
|
||||
FILES: ${{ steps.bump.outputs.files }}
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git switch --create content/bump
|
||||
git add src/content
|
||||
git commit --quiet -m "chore(content): publish ${NEW:0:7}" -m "$FILES"
|
||||
git push --force --quiet origin content/bump
|
||||
|
||||
if [ "$(gh pr view content/bump --json state --jq .state 2>/dev/null)" != "OPEN" ]; then
|
||||
gh pr create --base main --head content/bump \
|
||||
--title "chore(content): publish from admin" \
|
||||
--body "Bumps \`src/content\` to poli0981/content@${NEW}. Opened by the admin's **Publish** button (.github/workflows/content-bump.yml)."
|
||||
fi
|
||||
|
||||
if [ "$AUTO" = "true" ]; then
|
||||
gh pr merge content/bump --auto --squash
|
||||
else
|
||||
gh pr merge content/bump --disable-auto 2>/dev/null || true
|
||||
gh pr comment content/bump --body "This publish touches files other than .md/.json (MDX runs code at build time), so it waits for a review instead of auto-merging."
|
||||
fi
|
||||
|
||||
# PRs opened with GITHUB_TOKEN don't trigger pull_request workflows; a dispatch is
|
||||
# the exception, and its `build` check lands on the bump commit for the ruleset.
|
||||
gh workflow run ci.yml --ref content/bump
|
||||
@@ -1,106 +0,0 @@
|
||||
name: Lighthouse
|
||||
|
||||
# docs 14 §3: assert the perf budget on a preview build — WARN ONLY, never blocking.
|
||||
# Lighthouse numbers move with runner load, so a hard gate here would block deploys on
|
||||
# noise rather than on regressions. The job is advisory by construction: assertions are
|
||||
# `warn`, and continue-on-error means a red run never fails the check suite.
|
||||
# Per the doc, act when it goes red twice in a row rather than on a single bad run.
|
||||
on:
|
||||
pull_request:
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lighthouse:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
# The whole point: informative, never a blocker.
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: recursive # src/content, or the build has no content to measure
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same as ci.yml: no dependency lifecycle scripts in CI.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Generate Cloudflare binding types
|
||||
run: npm run types
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
# `astro preview` boots the built worker in workerd with the real bindings and
|
||||
# _headers, so the numbers reflect production rather than a bare static server.
|
||||
- name: Start preview server
|
||||
run: npm run preview &
|
||||
|
||||
# Cloudflare's edge compresses every text response in production; the preview does not.
|
||||
# Lighthouse measures through nginx (preinstalled on the runner, gzip — a little larger
|
||||
# than the edge's brotli) so its simulated phone downloads about the bytes a real one
|
||||
# would (home HTML 108 KB raw, 25–30 KB compressed), not three to four times as many.
|
||||
- name: Start compressing proxy
|
||||
run: |
|
||||
cat > "$RUNNER_TEMP/nginx.conf" <<'EOF'
|
||||
events {}
|
||||
http {
|
||||
access_log off;
|
||||
gzip on;
|
||||
gzip_proxied any;
|
||||
gzip_comp_level 6;
|
||||
gzip_vary on;
|
||||
gzip_types text/css text/javascript application/javascript application/json
|
||||
application/manifest+json application/xml image/svg+xml;
|
||||
server {
|
||||
listen 127.0.0.1:4322;
|
||||
location / {
|
||||
proxy_pass http://localhost:4321;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Accept-Encoding "";
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
sudo nginx -t -c "$RUNNER_TEMP/nginx.conf"
|
||||
sudo nginx -c "$RUNNER_TEMP/nginx.conf"
|
||||
|
||||
- name: Wait for the server
|
||||
run: |
|
||||
for i in $(seq 1 60); do
|
||||
if curl -sf -o /dev/null http://127.0.0.1:4322/; then
|
||||
echo "preview up after ${i}s"; exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "preview server never came up"; exit 1
|
||||
|
||||
# Four representative pages (docs 14 §3): home, a blog post, a story chapter, a
|
||||
# gallery album — the heaviest template of each kind. The action bundles @lhci/cli,
|
||||
# so nothing is downloaded with npx at run time; it collects, asserts against
|
||||
# lighthouserc.json (warn-only) and uploads the reports even when an assertion warns.
|
||||
- name: Lighthouse
|
||||
uses: treosh/lighthouse-ci-action@3e7e23fb74242897f95c0ba9cabad3d0227b9b18 # 12.6.2
|
||||
with:
|
||||
configPath: ./lighthouserc.json
|
||||
urls: |
|
||||
http://127.0.0.1:4322/
|
||||
http://127.0.0.1:4322/blog/lan-dau-viet-truyen/
|
||||
http://127.0.0.1:4322/truyen/dem-khong-tieng/chuong-01/
|
||||
http://127.0.0.1:4322/gallery/game/
|
||||
uploadArtifacts: true
|
||||
artifactName: lighthouse-reports
|
||||
@@ -1,42 +0,0 @@
|
||||
name: OSV scan
|
||||
|
||||
# docs 06 §6 and 08 §2 both call for a weekly dependency scan; this is it.
|
||||
# It complements the per-PR `npm audit --omit=dev --audit-level=high` gate in ci.yml:
|
||||
# audit only sees the production tree and only fails on high+, while OSV covers the
|
||||
# whole lockfile (devDependencies included) against the full OSV database.
|
||||
on:
|
||||
schedule:
|
||||
# Mondays 03:17 UTC — off the hour, where scheduled-runner contention is lowest.
|
||||
- cron: "17 3 * * 1"
|
||||
workflow_dispatch:
|
||||
# Re-run when the dependency graph itself changes, so a bad bump is caught on the PR
|
||||
# rather than up to a week later…
|
||||
pull_request:
|
||||
paths: ["package-lock.json"]
|
||||
# …and once it lands, so the Security tab reflects main straight away.
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ["package-lock.json"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
scan:
|
||||
# The repo is public, so code scanning is free: findings are uploaded as SARIF and
|
||||
# show up under Security → Code scanning, and a finding still fails the run.
|
||||
# PR runs skip the upload — Dependabot PRs get a read-only token, so the upload
|
||||
# step would fail there for a reason unrelated to the scan itself.
|
||||
uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@32d3cd482bdadfb38b186c0ad1b031902d55d932 # v2.7.1
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
security-events: write
|
||||
with:
|
||||
upload-sarif: ${{ github.event_name != 'pull_request' }}
|
||||
scan-args: |-
|
||||
--lockfile=package-lock.json
|
||||
@@ -1,87 +0,0 @@
|
||||
name: Qodana
|
||||
|
||||
# JetBrains Qodana (Qodana for JS, WebStorm's inspections) over the whole repository: on every
|
||||
# PR, on main and by hand. Settings live in qodana.yaml. Results go to Qodana Cloud (the
|
||||
# project token is the QODANA_TOKEN secret) and, for main, to GitHub code scanning as SARIF.
|
||||
#
|
||||
# Advisory, not required: the main ruleset requires only `build`, and Dependabot and fork PRs
|
||||
# get no secrets, so they skip this job like the SonarCloud one in ci.yml.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
paths-ignore: ["poli0981.dev-docs/**", "*.md", "LICENSE"]
|
||||
workflow_dispatch:
|
||||
|
||||
# Explicit — a missing block makes GitHub default every scope to `none`.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
# Cancel superseded PR runs; let main runs finish.
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
|
||||
jobs:
|
||||
qodana:
|
||||
if: >-
|
||||
github.event_name != 'pull_request' ||
|
||||
(github.event.pull_request.head.repo.full_name == github.repository &&
|
||||
github.actor != 'dependabot[bot]')
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write # problem annotations on the commit
|
||||
pull-requests: write # the summary comment on PRs
|
||||
security-events: write # SARIF upload (main and manual runs)
|
||||
steps:
|
||||
# Pinned to commit SHAs like every other workflow here; Dependabot keeps them current.
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
# The PR's own head commit, not the merge preview, so Qodana Cloud links to it.
|
||||
ref: ${{ github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# Same rules as ci.yml: no dependency lifecycle script runs in CI, and any lockfile
|
||||
# package with an install script must be on package.json#allowScripts.
|
||||
- name: Install
|
||||
run: npm ci --ignore-scripts
|
||||
|
||||
- name: Install scripts allow-listed
|
||||
run: npm run check-install-scripts
|
||||
|
||||
# Gitignored, generated types the TypeScript service needs to resolve imports of
|
||||
# cloudflare:workers, astro:content and friends.
|
||||
- name: Generate types
|
||||
run: |
|
||||
npm run types
|
||||
npm run types:widgets
|
||||
npm run astro -- sync
|
||||
|
||||
- name: Qodana scan
|
||||
uses: JetBrains/qodana-action@13e3acbbaeb2cbfc37893b98e74594985edf42eb # v2026.2.4
|
||||
env:
|
||||
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
|
||||
QODANA_ENDPOINT: https://qodana.cloud
|
||||
with:
|
||||
# Whole repository every time (it is small), so the quality gate in qodana.yaml
|
||||
# always judges the full picture rather than the files a PR happens to touch.
|
||||
pr-mode: false
|
||||
upload-result: true
|
||||
|
||||
# Like the OSV scan: main and manual runs only, so PR runs don't open code-scanning
|
||||
# alerts for code that may never merge.
|
||||
- name: Upload SARIF to code scanning
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' }}
|
||||
uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
sarif_file: ${{ runner.temp }}/qodana/results/qodana.sarif.json
|
||||
category: qodana
|
||||
@@ -1,83 +0,0 @@
|
||||
name: Triage
|
||||
|
||||
# Maintenance mode (CONTRIBUTING.md): an issue or pull request asking for a new feature is
|
||||
# labelled `enhancement` + `out-of-scope`, answered in both languages and closed. The rules
|
||||
# live in scripts/triage.mjs (unit-tested); this only wires them to GitHub. The owner's own
|
||||
# items, bots, and anything labelled `maintenance-exception` are left alone.
|
||||
#
|
||||
# pull_request_target runs with this repository's token, so it must never run a pull
|
||||
# request's code. Nothing is checked out at all: the script reads scripts/triage.mjs from the
|
||||
# default branch through the API and imports it from memory.
|
||||
on:
|
||||
issues:
|
||||
types: [opened, reopened, edited, labeled]
|
||||
pull_request_target:
|
||||
types: [opened, reopened, edited, labeled]
|
||||
# Dry run on main: classify a title and print the decision, writing nothing.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
title:
|
||||
description: "Title to classify"
|
||||
required: true
|
||||
kind:
|
||||
description: "issue or pull_request"
|
||||
default: issue
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: triage-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- name: Label and close feature requests
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
with:
|
||||
script: |
|
||||
const { data: file } = await github.rest.repos.getContent({
|
||||
...context.repo,
|
||||
path: "scripts/triage.mjs",
|
||||
ref: context.payload.repository.default_branch,
|
||||
});
|
||||
const source = file.content.replaceAll("\n", "");
|
||||
const { decide, closingComment, LABELS } = await import(
|
||||
`data:text/javascript;base64,${source}`
|
||||
);
|
||||
|
||||
if (context.eventName === "workflow_dispatch") {
|
||||
const { title, kind } = context.payload.inputs;
|
||||
const verdict = decide({ title, labels: [], author: "someone", association: "NONE" });
|
||||
core.notice(`${kind} "${title}": ${verdict.action} (${verdict.reason})`);
|
||||
return;
|
||||
}
|
||||
|
||||
const item = context.payload.issue ?? context.payload.pull_request;
|
||||
const kind = context.payload.pull_request ? "pull_request" : "issue";
|
||||
const verdict = decide({
|
||||
title: item.title,
|
||||
labels: (item.labels ?? []).map((label) => label.name),
|
||||
author: item.user.login,
|
||||
association: item.author_association,
|
||||
sender: context.payload.sender?.login,
|
||||
owner: context.repo.owner,
|
||||
state: item.state,
|
||||
});
|
||||
core.info(`#${item.number}: ${verdict.action} (${verdict.reason})`);
|
||||
if (verdict.action !== "close") return;
|
||||
|
||||
const target = { ...context.repo, issue_number: item.number };
|
||||
await github.rest.issues.addLabels({ ...target, labels: [LABELS.feature, LABELS.closed] });
|
||||
await github.rest.issues.createComment({ ...target, body: closingComment(kind) });
|
||||
if (kind === "pull_request") {
|
||||
await github.rest.pulls.update({ ...context.repo, pull_number: item.number, state: "closed" });
|
||||
} else {
|
||||
await github.rest.issues.update({ ...target, state: "closed", state_reason: "not_planned" });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<!-- Labels: accessibility. Converted from .github/ISSUE_TEMPLATE (Gitea reads those); keep both in step. -->
|
||||
|
||||
Cảm ơn bạn đã báo. Bạn không cần tự tìm nguyên nhân, và không cần nói gì về tình trạng khuyết tật
|
||||
của mình. / Thanks for reporting. You do not have to diagnose anything, and you never need to tell
|
||||
me about a disability.
|
||||
|
||||
Không muốn đăng công khai? Gửi email tới accessibility@poli0981.dev hoặc dùng nút "Báo lỗi" ở cuối
|
||||
mọi trang (không cần tài khoản). / Prefer not to post in public? Email accessibility@poli0981.dev,
|
||||
or use "Report a bug" at the bottom of every page (no account needed).
|
||||
|
||||
Tiêu đề / Title: `[a11y] …`
|
||||
|
||||
### Bạn đang định làm gì? / What were you trying to do?
|
||||
|
||||
<!-- Ví dụ "mở menu bằng bàn phím" / For example "open the menu with the keyboard" -->
|
||||
|
||||
### Điều gì đã xảy ra? / What happened instead?
|
||||
|
||||
<!-- Các bước tái hiện nếu có / Steps to reproduce, if you have them -->
|
||||
|
||||
### Trang / Page
|
||||
|
||||
<!-- https://poli0981.dev/… -->
|
||||
|
||||
### Môi trường / Environment
|
||||
|
||||
<!-- Hệ điều hành, trình duyệt, công nghệ hỗ trợ và phiên bản / Operating system, browser, assistive technology and versions — e.g. Windows 11 · Edge 142 · Narrator -->
|
||||
|
||||
### Mức độ / Severity
|
||||
|
||||
- [ ] Chặn hẳn — không làm được việc chính / Critical — blocks a core task
|
||||
- [ ] Nghiêm trọng — rất khó, nhưng có cách khác / Serious — major difficulty, a workaround exists
|
||||
- [ ] Vừa — gây khó chịu hoặc không nhất quán / Moderate — annoying or inconsistent
|
||||
- [ ] Nhẹ — ảnh hưởng ít / Minor — little impact
|
||||
|
||||
/label ~accessibility
|
||||
@@ -0,0 +1,34 @@
|
||||
<!-- Labels: bug. Converted from .github/ISSUE_TEMPLATE (Gitea reads those); keep both in step. -->
|
||||
|
||||
Cảm ơn bạn đã báo lỗi. / Thanks for reporting.
|
||||
|
||||
Nhanh hơn: nút "Báo lỗi" ngay trên trang gửi kèm trang và môi trường đang dùng (báo cáo đó thành
|
||||
issue bảo mật, chỉ chủ repo xem được). / Quicker: the "Report a problem" button on the page itself
|
||||
sends the page and environment along (those reports become confidential issues only the maintainer
|
||||
can see).
|
||||
|
||||
Dự án đang ở chế độ bảo trì: mẫu này dành cho lỗi, không dành cho đề xuất tính năng — xem
|
||||
CONTRIBUTING.md. / The project is in maintenance mode: this template is for bugs, not feature
|
||||
requests — see CONTRIBUTING.md.
|
||||
|
||||
Tiêu đề / Title: `[web-report] …`
|
||||
|
||||
### Mô tả / Description
|
||||
|
||||
<!-- Chuyện gì đã xảy ra? / What happened? -->
|
||||
|
||||
### Trang / Route
|
||||
|
||||
<!-- /blog/… -->
|
||||
|
||||
### Môi trường / Environment
|
||||
|
||||
<!-- Trình duyệt, kích thước màn hình, theme, ngôn ngữ / Browser, viewport, theme, locale -->
|
||||
|
||||
### Console log (tùy chọn / optional)
|
||||
|
||||
```text
|
||||
|
||||
```
|
||||
|
||||
/label ~bug
|
||||
@@ -0,0 +1,25 @@
|
||||
<!-- Labels: language. Converted from .github/ISSUE_TEMPLATE (Gitea reads those); keep both in step. -->
|
||||
|
||||
Cảm ơn bạn! Mỗi báo cáo một chỗ (hoặc một nhóm chỗ cùng một lỗi). / Thanks! One report per place,
|
||||
or per group of places with the same problem.
|
||||
|
||||
Tiêu đề / Title: `[language] …`
|
||||
|
||||
### Trang / Page
|
||||
|
||||
<!-- Đường dẫn trang, hoặc file nếu bạn biết. / The page's URL, or the file if you know it. -->
|
||||
|
||||
### Ngôn ngữ / Language
|
||||
|
||||
- [ ] Tiếng Việt / Vietnamese
|
||||
- [ ] Tiếng Anh / English
|
||||
|
||||
### Câu hiện tại / Current text
|
||||
|
||||
<!-- Chép nguyên văn. / Copy it exactly. -->
|
||||
|
||||
### Đề xuất sửa và lý do / Suggested wording and why
|
||||
|
||||
<!-- Vì sao câu hiện tại gây hiểu nhầm hoặc không hợp? / Why is the current text misleading or a poor fit? -->
|
||||
|
||||
/label ~language
|
||||
@@ -0,0 +1,36 @@
|
||||
<!-- Converted from .github/pull_request_template.md (Gitea reads that one); keep both in step. -->
|
||||
|
||||
## What and why
|
||||
|
||||
<!-- One or two sentences. Link the issue if there is one. -->
|
||||
|
||||
## Kind of change
|
||||
|
||||
The project is in maintenance mode ([CONTRIBUTING.md](https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/CONTRIBUTING.md)):
|
||||
new features are not accepted, and a `feat:` merge request is closed. GitLab CI does not run here:
|
||||
the maintainer runs CI on Gitea before applying the change.
|
||||
|
||||
- [ ] Dependency update
|
||||
- [ ] Security fix (High/Critical advisory, or a runtime vulnerability)
|
||||
- [ ] Major language, runtime or framework upgrade
|
||||
- [ ] Bug fix — including UI/UX and accessibility
|
||||
- [ ] Language fix — a misleading typo, or wording that does not fit
|
||||
|
||||
## Checks
|
||||
|
||||
- [ ] `npm run format:check`, `npm run lint`, `npm run check`, `npm run typecheck`, `npm test`
|
||||
- [ ] `CHANGELOG.md` updated under `[Unreleased]` when visitors or operators would notice the change
|
||||
|
||||
## Accessibility (only if the interface changed)
|
||||
|
||||
See [`ACCESSIBILITY.md`](https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/ACCESSIBILITY.md).
|
||||
`npm run test:a11y` covers what a machine can check; the rest is by hand.
|
||||
|
||||
- [ ] Works with the keyboard alone, start to finish; focus is visible and never lands under a fixed bar
|
||||
- [ ] Anything that opens (menu, dialog, panel) closes with Esc and hands focus back to what opened it
|
||||
- [ ] Icon-only controls have a name that starts with their visible text, taken from `src/i18n`
|
||||
- [ ] State and "you are here" are not shown by colour alone; new colours go through `tests/palette.test.ts`
|
||||
- [ ] Headings do not skip a level; images have an `alt` (empty only when decorative)
|
||||
- [ ] New animation has a still branch under `prefers-reduced-motion`
|
||||
- [ ] Looked at 320 px wide, at 200% zoom, in dark and light, in Vietnamese and English
|
||||
- [ ] Listened to once with a screen reader
|
||||
@@ -0,0 +1,19 @@
|
||||
# gitleaks, run by the ops repo's security.yml, scans every commit with its default rules.
|
||||
# Each line below is one finding that is NOT a secret, as commit:file:rule:line. Anything
|
||||
# else is still reported, and so is a later commit that touches these lines. A real secret
|
||||
# never goes here: it is rotated, and the history is dealt with.
|
||||
|
||||
# A deliberately forged Cloudflare Access JWT: the smoke test sends it to prove the admin
|
||||
# API refuses a token that does not verify (it now lives in a variable, `forgedJwt`).
|
||||
7ec559d216e593f53938bf1db8c85584f9115190:scripts/smoke-worker.mjs:generic-api-key:177
|
||||
|
||||
# The Cloudflare Access application's AUD tag. Public by design: it only says which app a
|
||||
# token must be minted for (the comment above it in wrangler.jsonc says so).
|
||||
7ec559d216e593f53938bf1db8c85584f9115190:wrangler.jsonc:generic-api-key:85
|
||||
|
||||
# The Cloudflare Web Analytics site tag: every production page sends it in its HTML.
|
||||
48d4e7bbdccd00b34ac28819ce42309488bb63cd:src/components/CfBeacon.astro:generic-api-key:11
|
||||
|
||||
# SonarQube Cloud's project key, a public identifier, in the sonar-project.properties that
|
||||
# left with Sonar (migration decision D1).
|
||||
8a1316280f298a2814ba941ad33baad1d0596b3b:sonar-project.properties:generic-api-key:4
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "src/content"]
|
||||
path = src/content
|
||||
url = https://github.com/poli0981/content.git
|
||||
url = https://git.poli0981.dev/poli0981/content.git
|
||||
+7
-4
@@ -16,8 +16,9 @@ what a visitor can expect, the site wins.
|
||||
## Reporting a barrier
|
||||
|
||||
Email **accessibility@poli0981.dev**, or use **Report a bug** at the bottom of every page — it needs
|
||||
no account and lands in a private tracker. If you use GitHub, you can open an issue with the
|
||||
[Accessibility template](https://github.com/poli0981/poli0981-dev/issues/new?template=accessibility.yml).
|
||||
no account and lands in a private tracker. If you have a GitLab account, you can open an issue with
|
||||
the [Accessibility template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Accessibility)
|
||||
on the mirror.
|
||||
|
||||
It helps to say which page, what you were trying to do, what happened instead, and which browser and
|
||||
assistive technology you use. You do not have to diagnose anything, and you never need to tell me
|
||||
@@ -152,12 +153,14 @@ npm run preview
|
||||
npm run test:a11y
|
||||
```
|
||||
|
||||
It drives the Chrome that is already installed; set `A11Y_CHANNEL=msedge` to use Edge instead. If a
|
||||
It drives the Chrome that is already installed; set `A11Y_CHANNEL=msedge` to use Edge instead, or
|
||||
`A11Y_CHANNEL=bundled` for Playwright's own Chromium (what CI uses: the Gitea runner's image has no
|
||||
Chrome). If a
|
||||
rule cannot be met, say why in the pull request rather than switching the rule off.
|
||||
|
||||
## Ownership and review
|
||||
|
||||
Maintained by Kokone ([poli0981](https://github.com/poli0981)), the site's only maintainer, who
|
||||
Maintained by Kokone ([poli0981](https://git.poli0981.dev/poli0981)), the site's only maintainer, who
|
||||
triages reports and keeps this file and the site's statement in step. Both are reviewed with every
|
||||
release that changes the interface and at least once a year
|
||||
([`17_MAINTENANCE.md`](poli0981.dev-docs/17_MAINTENANCE.md)).
|
||||
|
||||
+67
-10
@@ -2,11 +2,66 @@
|
||||
|
||||
Notable changes to poli0981.dev. The site deploys continuously from `main`; tags mark
|
||||
milestones. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
Content changes (posts, stories, albums) live in [`poli0981/content`](https://github.com/poli0981/content)
|
||||
and are not listed here.
|
||||
Content changes (posts, stories, albums) live in [`poli0981/content`](https://git.poli0981.dev/poli0981/content)
|
||||
and are not listed here. Links to pull requests before 2.4.0 point at the GitHub repository, which
|
||||
no longer exists; the commits themselves are all on Gitea.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.4.1] — 2026-11-24
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Publishing from the admin merges again.** The first publish after the move stopped at its
|
||||
pull request: Gitea 28.4 writes no commit status for a dispatched CI run, so the content PR
|
||||
never had the `CI / build` check main's branch protection requires and every merge was refused
|
||||
(405). CI's publish job now records the build's result as that status itself — and a failed
|
||||
build as a failure, so the admin shows "xuất bản lỗi" instead of building forever — before it
|
||||
merges and deploys.
|
||||
|
||||
## [2.4.0] — 2026-11-24
|
||||
|
||||
The move from GitHub to the owner's Gitea. The GitHub account is gone, and with it the
|
||||
repository, Actions, Workers Builds' source, the admin's tokens and the bug-report tracker. This
|
||||
release puts every one of them somewhere that works again; nothing new is added (maintenance
|
||||
mode, [`CONTRIBUTING.md`](CONTRIBUTING.md)).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Where the code lives.** The canonical repository is
|
||||
[`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev), the
|
||||
content submodule [`git.poli0981.dev/poli0981/content`](https://git.poli0981.dev/poli0981/content).
|
||||
Issues and merge requests go to the mirror on
|
||||
[GitLab](https://gitlab.com/poli0981/poli0981-dev) (Bug, Accessibility and Language templates);
|
||||
patches and questions to `code@poli0981.dev`; security reports by e-mail only.
|
||||
- **CI runs on Gitea Actions** (`.gitea/workflows`), on the owner's own runner: the build job is
|
||||
unchanged in what it checks, and installs Playwright's Chromium where the runner image has no
|
||||
Chrome. **`main` deploys from CI**: a `deploy` job runs `wrangler deploy` after `build` passes
|
||||
and waits until `/api/health` reports the commit. Cloudflare Workers Builds is gone, and pull
|
||||
requests get no preview versions.
|
||||
- **The admin works through Gitea** (`src/lib/admin/gitea.ts`): one bot token
|
||||
(`GITEA_BOT_TOKEN`) for saves and publishing, several files per commit with Gitea checking
|
||||
each file's version, and the publish bar reading the content PR, its build status and the
|
||||
publish workflow from Gitea. Publishing still merges itself for Markdown/JSON and waits for a
|
||||
review when MDX changes: CI merges the content PR and starts the deploy.
|
||||
- **Bug reports from the site** become **confidential issues on the GitLab mirror**
|
||||
(`GITLAB_ISSUES_TOKEN`, var `REPORT_PROJECT`), seen only by the maintainer; reporter text cannot
|
||||
ping anyone or run a GitLab quick action. Privacy §4 says so (content repo, effective
|
||||
2026-11-24). The Discord fallback is unchanged.
|
||||
- **The activity widget** reads Gitea's public activity feed (no token) and links to Gitea.
|
||||
- The dev profile link, the About page, the console banner, the legal pages' source and issue
|
||||
links, and the project pages point at Gitea.
|
||||
- **Dependency updates** come from Renovate (the shared `poli0981/renovate-config` preset, 3-day
|
||||
wait kept) instead of Dependabot. **Security checks** come from the ops repository's
|
||||
`security.yml`: gitleaks over the whole history, Opengrep and osv-scanner, weekly and on every
|
||||
change. **Qodana** runs through its CLI; reports are artifacts.
|
||||
|
||||
### Removed
|
||||
|
||||
- SonarQube Cloud (job, configuration and badge), GitHub code scanning uploads, the OSV workflow
|
||||
(replaced by `security.yml`) and the maintenance-mode triage bot, which needed GitHub's events:
|
||||
out-of-scope requests on the mirror are closed by hand.
|
||||
|
||||
## [2.3.0] — 2026-11-21
|
||||
|
||||
The last feature release: from here on the project is in **maintenance mode**
|
||||
@@ -292,11 +347,13 @@ The public launch is tagged `v1-launch`; the 1.x changes after it were not tagge
|
||||
- **2026-10** — Custom Worker entry in front of every page; Workers Rate Limiting; Web Analytics;
|
||||
topic email aliases; R2 media; the Turnstile gate; the admin at `admin.poli0981.dev`.
|
||||
|
||||
[Unreleased]: https://github.com/poli0981/poli0981-dev/compare/v2.3.0...HEAD
|
||||
[2.3.0]: https://github.com/poli0981/poli0981-dev/compare/v2.2.0...v2.3.0
|
||||
[2.2.0]: https://github.com/poli0981/poli0981-dev/compare/v2.1.2...v2.2.0
|
||||
[2.1.2]: https://github.com/poli0981/poli0981-dev/compare/v2.1.1...v2.1.2
|
||||
[2.1.1]: https://github.com/poli0981/poli0981-dev/compare/v2.1.0...v2.1.1
|
||||
[2.1.0]: https://github.com/poli0981/poli0981-dev/compare/v2.0.0...v2.1.0
|
||||
[2.0.0]: https://github.com/poli0981/poli0981-dev/releases/tag/v2.0.0
|
||||
[1.x]: https://github.com/poli0981/poli0981-dev/releases/tag/v1-launch
|
||||
[Unreleased]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.4.1...main
|
||||
[2.4.1]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.4.0...v2.4.1
|
||||
[2.4.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.3.0...v2.4.0
|
||||
[2.3.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.2.0...v2.3.0
|
||||
[2.2.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.1.2...v2.2.0
|
||||
[2.1.2]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.1.1...v2.1.2
|
||||
[2.1.1]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.1.0...v2.1.1
|
||||
[2.1.0]: https://git.poli0981.dev/poli0981/poli0981-dev/compare/v2.0.0...v2.1.0
|
||||
[2.0.0]: https://git.poli0981.dev/poli0981/poli0981-dev/releases/tag/v2.0.0
|
||||
[1.x]: https://git.poli0981.dev/poli0981/poli0981-dev/releases/tag/v1-launch
|
||||
+77
-37
@@ -2,13 +2,30 @@
|
||||
|
||||
> **Tiếng Việt ở bên dưới.** / Vietnamese below.
|
||||
|
||||
## Where things live
|
||||
|
||||
The canonical repository is on the owner's Gitea,
|
||||
[`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev). It is
|
||||
public to read, but registration is closed, so nobody else can open issues or pull requests there.
|
||||
Since November 2026 (the GitHub repository is gone) outside contributions go through:
|
||||
|
||||
- **Issues and merge requests**: the mirror at
|
||||
[`gitlab.com/poli0981/poli0981-dev`](https://gitlab.com/poli0981/poli0981-dev). Gitea pushes to
|
||||
it after every change, so it always has the current code. GitLab CI does not run there: the
|
||||
owner runs CI on Gitea before applying a merge request.
|
||||
- **Patches by e-mail**: `git format-patch` / `git send-email` to `code@poli0981.dev`, also for
|
||||
questions.
|
||||
|
||||
The owner applies accepted changes on Gitea; the mirror then shows the merge request as merged,
|
||||
or the owner closes it with a link to the commit.
|
||||
|
||||
## Maintenance mode
|
||||
|
||||
Since **v2.3.0 (November 2026)** this project is in **maintenance mode**. The site is complete; it
|
||||
is kept healthy, but **no new features are being added**. Only these changes are accepted:
|
||||
|
||||
1. **Dependency updates** on the regular schedule (Dependabot weekly, a combined update about
|
||||
once a month, always after a 3-day cooldown).
|
||||
1. **Dependency updates** on the regular schedule (Renovate, with a combined update about once a
|
||||
month, always after a 3-day wait).
|
||||
2. **Security**: a dependency advisory of **High or Critical** severity, or a serious
|
||||
vulnerability in the runtime itself (Node.js, the Workers runtime), fixed as soon as
|
||||
possible — together with a feature only when the owner judges it truly necessary.
|
||||
@@ -19,38 +36,58 @@ is kept healthy, but **no new features are being added**. Only these changes are
|
||||
5. **Language**: spelling mistakes that could mislead, and wording that does not fit the culture
|
||||
or the local voice, in Vietnamese or English.
|
||||
|
||||
**Not accepted: new features.** An issue or pull request asking for one is labelled
|
||||
`enhancement` + `out-of-scope` and closed automatically
|
||||
([`.github/workflows/triage.yml`](.github/workflows/triage.yml)). If it was closed by mistake,
|
||||
reply on it and the owner will take another look; an exception the owner accepts carries the
|
||||
`maintenance-exception` label. Ideas are still welcome in
|
||||
[Discussions](https://github.com/poli0981/poli0981-dev/discussions), without any promise.
|
||||
**Not accepted: new features.** An issue or merge request asking for one is labelled
|
||||
`enhancement` + `out-of-scope` and closed. If it was closed by mistake, reply on it and the owner
|
||||
will take another look; an exception the owner accepts carries the `maintenance-exception` label.
|
||||
Ideas are still welcome by e-mail to `code@poli0981.dev`, without any promise.
|
||||
|
||||
### How to report
|
||||
|
||||
- **A problem on the website**: the "Báo lỗi / Report a problem" button on the page itself, or the
|
||||
bug report form under [Issues](https://github.com/poli0981/poli0981-dev/issues/new/choose).
|
||||
- **An accessibility barrier**: the accessibility form under Issues.
|
||||
- **A spelling or wording problem**: the language form under Issues.
|
||||
- **A security vulnerability**: privately — see [SECURITY.md](SECURITY.md). Never in a public
|
||||
issue.
|
||||
- **A problem on the website**: the "Báo lỗi / Report a problem" button on the page itself (no
|
||||
account needed), or the
|
||||
[Bug template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Bug) on
|
||||
the GitLab mirror.
|
||||
- **An accessibility barrier**: the
|
||||
[Accessibility template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Accessibility),
|
||||
or `accessibility@poli0981.dev`.
|
||||
- **A spelling or wording problem**: the
|
||||
[Language template](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Language).
|
||||
- **A security vulnerability**: by e-mail only — see [SECURITY.md](SECURITY.md). Never in a public
|
||||
issue on the mirror.
|
||||
|
||||
### Pull requests
|
||||
### Merge requests and patches
|
||||
|
||||
Welcome for the five kinds of change above. Keep one change per pull request, follow the checks
|
||||
in the [pull request template](.github/pull_request_template.md), and run the commands listed in
|
||||
[README.md](README.md#commands) before opening it. CI must be green — `build` is required, and
|
||||
the SonarCloud and Qodana gates have to pass too. Commits on `main` are signed.
|
||||
Welcome for the five kinds of change above. Keep one change per merge request (or patch series),
|
||||
follow the checks in the merge request template, and run the commands listed in
|
||||
[README.md](README.md#commands) before sending it. CI on Gitea must be green before the owner
|
||||
merges — `build` is the required check, and the Qodana and security checks have to pass too.
|
||||
Commits on `main` are signed.
|
||||
|
||||
---
|
||||
|
||||
## Mã nguồn ở đâu
|
||||
|
||||
Repo chính nằm trên Gitea của chủ repo,
|
||||
[`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev). Ai cũng
|
||||
đọc được, nhưng đăng ký tài khoản đã đóng nên người khác không mở được issue hay pull request ở đó.
|
||||
Từ tháng 11/2026 (repo GitHub không còn), đóng góp từ bên ngoài đi qua:
|
||||
|
||||
- **Issue và merge request**: bản sao tại
|
||||
[`gitlab.com/poli0981/poli0981-dev`](https://gitlab.com/poli0981/poli0981-dev). Gitea đẩy sang
|
||||
sau mỗi thay đổi, nên luôn có mã mới nhất. GitLab CI không chạy ở đó: chủ repo chạy CI trên Gitea
|
||||
trước khi áp dụng merge request.
|
||||
- **Patch qua e-mail**: `git format-patch` / `git send-email` tới `code@poli0981.dev`, câu hỏi cũng
|
||||
gửi về đây.
|
||||
|
||||
Chủ repo áp dụng thay đổi được chấp nhận trên Gitea; bản sao sau đó hiện merge request là đã merge,
|
||||
hoặc chủ repo đóng nó kèm link tới commit.
|
||||
|
||||
## Chế độ bảo trì
|
||||
|
||||
Từ **v2.3.0 (tháng 11/2026)**, dự án ở **chế độ bảo trì**. Trang web đã hoàn chỉnh; repo vẫn được giữ
|
||||
cho khoẻ mạnh nhưng **không thêm tính năng mới**. Chỉ nhận những thay đổi sau:
|
||||
|
||||
1. **Cập nhật dependency** định kỳ (Dependabot hằng tuần, gộp một lần khoảng mỗi tháng, luôn sau
|
||||
3 ngày "nguội").
|
||||
1. **Cập nhật dependency** định kỳ (Renovate, gộp một lần khoảng mỗi tháng, luôn sau 3 ngày chờ).
|
||||
2. **Bảo mật**: lỗ hổng trong dependency ở mức **High hoặc Critical**, hoặc lỗ hổng nghiêm trọng của
|
||||
chính runtime (Node.js, Workers runtime) — sửa sớm nhất có thể; kèm tính năng chỉ khi chủ repo
|
||||
đánh giá là thật sự cần thiết.
|
||||
@@ -61,24 +98,27 @@ cho khoẻ mạnh nhưng **không thêm tính năng mới**. Chỉ nhận nhữn
|
||||
5. **Ngôn ngữ**: lỗi chính tả có thể gây hiểu nhầm, câu chữ không hợp văn hoá hay giọng địa phương,
|
||||
ở cả tiếng Việt lẫn tiếng Anh.
|
||||
|
||||
**Không nhận: tính năng mới.** Issue hoặc pull request đề xuất tính năng sẽ được gắn nhãn
|
||||
`enhancement` + `out-of-scope` và tự động đóng
|
||||
([`.github/workflows/triage.yml`](.github/workflows/triage.yml)). Nếu bị đóng nhầm, hãy trả lời ngay
|
||||
trong đó — chủ repo sẽ xem lại; ngoại lệ được chấp nhận mang nhãn `maintenance-exception`. Ý tưởng
|
||||
vẫn có thể trao đổi trong [Discussions](https://github.com/poli0981/poli0981-dev/discussions), không
|
||||
cam kết sẽ làm.
|
||||
**Không nhận: tính năng mới.** Issue hoặc merge request đề xuất tính năng sẽ được gắn nhãn
|
||||
`enhancement` + `out-of-scope` và đóng lại. Nếu bị đóng nhầm, hãy trả lời ngay trong đó — chủ repo
|
||||
sẽ xem lại; ngoại lệ được chấp nhận mang nhãn `maintenance-exception`. Ý tưởng vẫn có thể gửi qua
|
||||
e-mail `code@poli0981.dev`, không cam kết sẽ làm.
|
||||
|
||||
### Báo lỗi ở đâu
|
||||
|
||||
- **Lỗi trên trang web**: nút "Báo lỗi" ngay trên trang, hoặc form báo lỗi trong
|
||||
[Issues](https://github.com/poli0981/poli0981-dev/issues/new/choose).
|
||||
- **Rào cản accessibility**: form accessibility trong Issues.
|
||||
- **Lỗi chính tả, câu chữ**: form ngôn ngữ trong Issues.
|
||||
- **Lỗ hổng bảo mật**: báo riêng — xem [SECURITY.md](SECURITY.md). Không mở issue công khai.
|
||||
- **Lỗi trên trang web**: nút "Báo lỗi" ngay trên trang (không cần tài khoản), hoặc
|
||||
[mẫu Bug](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Bug) trên bản
|
||||
sao GitLab.
|
||||
- **Rào cản accessibility**:
|
||||
[mẫu Accessibility](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Accessibility),
|
||||
hoặc `accessibility@poli0981.dev`.
|
||||
- **Lỗi chính tả, câu chữ**:
|
||||
[mẫu Language](https://gitlab.com/poli0981/poli0981-dev/-/issues/new?issuable_template=Language).
|
||||
- **Lỗ hổng bảo mật**: chỉ qua e-mail — xem [SECURITY.md](SECURITY.md). Không mở issue công khai
|
||||
trên bản sao.
|
||||
|
||||
### Pull request
|
||||
### Merge request và patch
|
||||
|
||||
Hoan nghênh cho năm loại thay đổi ở trên. Mỗi pull request một thay đổi, làm theo các mục kiểm tra
|
||||
trong [mẫu pull request](.github/pull_request_template.md), chạy các lệnh trong
|
||||
[README.md](README.md#commands) trước khi mở. CI phải xanh — `build` là bắt buộc, cổng SonarCloud
|
||||
và Qodana cũng phải qua. Commit trên `main` có chữ ký.
|
||||
Hoan nghênh cho năm loại thay đổi ở trên. Mỗi merge request (hoặc chuỗi patch) một thay đổi, làm
|
||||
theo các mục kiểm tra trong mẫu merge request, chạy các lệnh trong [README.md](README.md#commands)
|
||||
trước khi gửi. CI trên Gitea phải xanh trước khi chủ repo merge — `build` là bắt buộc, Qodana và các
|
||||
kiểm tra bảo mật cũng phải qua. Commit trên `main` có chữ ký.
|
||||
@@ -1,8 +1,8 @@
|
||||
# poli0981.dev
|
||||
|
||||
[](https://github.com/poli0981/poli0981-dev/actions/workflows/ci.yml)
|
||||
[](https://sonarcloud.io/summary/new_code?id=poli0981_poli0981-dev)
|
||||
[](https://github.com/poli0981/poli0981-dev/actions/workflows/qodana.yml)
|
||||
[](https://git.poli0981.dev/poli0981/poli0981-dev/actions?workflow=ci.yml)
|
||||
[](https://git.poli0981.dev/poli0981/poli0981-dev/actions?workflow=qodana.yml)
|
||||
[](https://git.poli0981.dev/poli0981/poli0981-dev/actions?workflow=security.yml)
|
||||
[](LICENSE)
|
||||
[](CONTRIBUTING.md#maintenance-mode)
|
||||
|
||||
@@ -17,8 +17,15 @@ the SkullMute channel, in Vietnamese and English. Live at **[poli0981.dev](https
|
||||
**Maintenance mode since v2.3.0 (November 2026).** The site is complete. It still gets
|
||||
dependency updates, security fixes (High/Critical advisories, runtime vulnerabilities), major
|
||||
runtime and framework upgrades, bug fixes (UI/UX and accessibility included) and language fixes,
|
||||
but no new features. Issues and pull requests asking for one are closed automatically. Details:
|
||||
[`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
but no new features; requests for one are closed. Details: [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
## Where things live
|
||||
|
||||
Source: [`git.poli0981.dev/poli0981/poli0981-dev`](https://git.poli0981.dev/poli0981/poli0981-dev)
|
||||
(canonical, on the owner's Gitea since November 2026; the GitHub repository is gone). Mirror for
|
||||
issues and merge requests: [`gitlab.com/poli0981/poli0981-dev`](https://gitlab.com/poli0981/poli0981-dev).
|
||||
Patches and questions: `code@poli0981.dev`. Security: `security@poli0981.dev` (see
|
||||
[`SECURITY.md`](SECURITY.md)).
|
||||
|
||||
> **Trạng thái:** chế độ bảo trì từ v2.3.0 — chỉ cập nhật dependency, vá bảo mật, nâng cấp
|
||||
> runtime/framework, sửa lỗi (cả UI/UX, accessibility) và sửa lỗi ngôn ngữ; không thêm tính năng mới.
|
||||
@@ -30,10 +37,11 @@ but no new features. Issues and pull requests asking for one are closed automati
|
||||
| Framework | [Astro 7](https://astro.build) (static-first) with Svelte 5 islands |
|
||||
| Styling | Tailwind CSS 4, design tokens in `src/styles/global.css` ("Glacier Teal" palette) |
|
||||
| Hosting | Cloudflare Workers + Static Assets; KV, R2, Images, Rate Limiting, Access, Turnstile |
|
||||
| Content | Markdown/MDX in [`poli0981/content`](https://github.com/poli0981/content) (git submodule `src/content`) |
|
||||
| Content | Markdown/MDX in [`poli0981/content`](https://git.poli0981.dev/poli0981/content) (git submodule `src/content`) |
|
||||
| Search | Pagefind (built after `astro build`) |
|
||||
| Tooling | Node 26 · TypeScript 7 (`tsc`) next to TypeScript 6 (astro check, typescript-eslint) · `node:test` · ESLint · Prettier · knip |
|
||||
| Quality | SonarCloud quality gate · Qodana · CodeQL · OSV-Scanner · Snyk · Dependabot (3-day cooldown) · axe-core gate · licence check |
|
||||
| Quality | Qodana · gitleaks · Opengrep · OSV-Scanner · Renovate (3-day wait) · axe-core gate · licence check |
|
||||
| CI | Gitea Actions (`.gitea/workflows`); `main` deploys with Wrangler from CI |
|
||||
|
||||
## How it fits together
|
||||
|
||||
@@ -43,7 +51,7 @@ visitor ─▶ Cloudflare edge ─▶ src/worker.ts (every request, pages includ
|
||||
Turnstile gate (48-hour pass) · static pages from ASSETS · the rest → Astro app
|
||||
├─ /api/report, /api/gate, /api/widgets, /api/health
|
||||
└─ admin.poli0981.dev (Cloudflare Access + JWT check)
|
||||
workers/widgets (cron, every 45 min) ─▶ YouTube / Steam / GitHub ─▶ KV (data + mirrored images)
|
||||
workers/widgets (cron, every 45 min) ─▶ YouTube / Steam / Gitea ─▶ KV (data + mirrored images)
|
||||
```
|
||||
|
||||
Almost every page is prerendered. The Worker entry runs first for every route so the bot gate,
|
||||
@@ -55,7 +63,7 @@ the denylist and the security headers also cover static pages. Details:
|
||||
Requirements: Node 26 (`.nvmrc`) and npm 11. The content submodule is public, so a plain clone works.
|
||||
|
||||
```bash
|
||||
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
|
||||
git clone --recurse-submodules https://git.poli0981.dev/poli0981/poli0981-dev.git
|
||||
cd poli0981-dev
|
||||
npm ci --ignore-scripts && npm run check-install-scripts
|
||||
npx lefthook install
|
||||
@@ -64,7 +72,7 @@ npm run dev
|
||||
```
|
||||
|
||||
`npm run dev` runs Astro on workerd with local bindings. The admin works locally with a stand-in
|
||||
identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.dev.vars`.
|
||||
identity (`dev@localhost`); saving content needs a Gitea token as `GITEA_BOT_TOKEN` in `.dev.vars`.
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -86,10 +94,13 @@ identity (`dev@localhost`); saving content needs a `GITHUB_CONTENT_TOKEN` in `.d
|
||||
|
||||
## Deploying
|
||||
|
||||
Cloudflare **Workers Builds** builds every push: `main` runs `npx wrangler deploy`, any other
|
||||
branch only `npx wrangler versions upload` (a preview version that takes no traffic). After a
|
||||
merge, `https://poli0981.dev/api/health` reports the running version and commit. The widgets
|
||||
worker deploys by hand: `npx wrangler deploy --config workers/widgets/wrangler.jsonc`.
|
||||
CI deploys `main`: after `build` passes on a push to `main`, the `deploy` job in
|
||||
[`.gitea/workflows/ci.yml`](.gitea/workflows/ci.yml) rebuilds with the production settings, runs
|
||||
`npx wrangler deploy` and waits until `https://poli0981.dev/api/health` reports that commit. Pull
|
||||
requests get no preview versions. The runner lives on the owner's PC, so a merge made while it is
|
||||
off deploys when it comes back. (Cloudflare Workers Builds did this until it went with the GitHub
|
||||
repository in November 2026.) The widgets worker deploys by hand:
|
||||
`npx wrangler deploy --config workers/widgets/wrangler.jsonc`.
|
||||
Setup from scratch: [`07_CLOUDFLARE_SETUP.md`](poli0981.dev-docs/07_CLOUDFLARE_SETUP.md);
|
||||
pipeline: [`08_CI_CD.md`](poli0981.dev-docs/08_CI_CD.md); changes per release: [`CHANGELOG.md`](CHANGELOG.md).
|
||||
|
||||
@@ -105,8 +116,9 @@ JWT (≤ 24 hours old) and an email allowlist on every request.
|
||||
|
||||
## Security
|
||||
|
||||
Please report vulnerabilities privately — see [`SECURITY.md`](SECURITY.md). Bug reports from the
|
||||
site's "Report a bug" button land in a private repository, not in this one's issues.
|
||||
Please report vulnerabilities privately, by e-mail — see [`SECURITY.md`](SECURITY.md). Bug
|
||||
reports from the site's "Report a bug" button become confidential issues on the GitLab mirror,
|
||||
visible only to the maintainer.
|
||||
|
||||
## Accessibility
|
||||
|
||||
|
||||
+7
-3
@@ -3,7 +3,10 @@
|
||||
## Reporting a vulnerability
|
||||
|
||||
Email **security@poli0981.dev**. Please include steps to reproduce and the affected URL.
|
||||
Do not open a public issue for a security problem.
|
||||
E-mail is the only channel: the repository lives on a self-hosted Gitea with no private
|
||||
reporting (GitHub's went with the old repository), and issues on the GitLab mirror are public.
|
||||
**Do not open a public issue on the mirror for a security problem.** One opened there by
|
||||
mistake is made confidential and continued by e-mail.
|
||||
|
||||
Expect an acknowledgement within 7 days. This is a personal site maintained by one
|
||||
person, in their spare time — there is no bug bounty and no payout.
|
||||
@@ -23,7 +26,7 @@ Machine-readable contact: <https://poli0981.dev/.well-known/security.txt> (RFC 9
|
||||
|
||||
**Out of scope**
|
||||
|
||||
- Findings that require an already-compromised Cloudflare, GitHub or Access identity
|
||||
- Findings that require an already-compromised Cloudflare, Gitea, GitLab or Access identity
|
||||
- Attacks on Cloudflare Access's own login flow (report those to Cloudflare)
|
||||
- Volumetric denial of service
|
||||
- Missing hardening headers with no demonstrated impact
|
||||
@@ -51,7 +54,8 @@ Useful context when judging impact — the site is static and stores almost noth
|
||||
check on age-rated pages (an age threshold, never a birth date), stay in the browser's
|
||||
`localStorage` and are never sent to the site.
|
||||
- User-submitted input: the bug-report form (Turnstile-gated, schema-validated, size-capped,
|
||||
forwarded to an issue in a **private** repository and a Discord webhook) and the bot-check
|
||||
forwarded as a **confidential** issue on the GitLab mirror, visible only to the maintainer,
|
||||
and to a Discord webhook) and the bot-check
|
||||
token exchange at `/api/gate`. Both are rate-limited per client.
|
||||
- IP addresses are used transiently for rate limiting and the IP denylist; they are not
|
||||
stored with reports. Workers Logs keep request logs for 7 days.
|
||||
|
||||
@@ -105,13 +105,14 @@ Not packages — listed for transparency:
|
||||
Images (one-time AVIF/WebP transforms), Rate Limiting, Turnstile (bot gate and bug-report
|
||||
form), Access (the admin), Web Analytics (cookieless page views, production builds only) and
|
||||
Workers Logs.
|
||||
- **GitHub** — source code, the content repository, Actions CI, and issues in a private
|
||||
repository for site bug reports.
|
||||
- **Gitea** (self-hosted at git.poli0981.dev) — source code, the content repository and CI
|
||||
(Gitea Actions, on the maintainer's own runner).
|
||||
- **GitLab** — the public mirror of the repository, and confidential issues for site bug reports.
|
||||
- **Discord** — a webhook receiving bug-report notifications.
|
||||
- **YouTube, Steam and GitHub public APIs** — read by the widgets cron worker; visitors' browsers
|
||||
- **YouTube, Steam and Gitea public APIs** — read by the widgets cron worker; visitors' browsers
|
||||
never call them (images are mirrored and served from the site).
|
||||
- **SonarCloud, Qodana (JetBrains), CodeQL, OSV-Scanner, Snyk** — code and dependency analysis in
|
||||
CI; nothing they do reaches the running site.
|
||||
- **Qodana (JetBrains), gitleaks, Opengrep, OSV-Scanner, Renovate** — code and dependency
|
||||
analysis and updates in CI; nothing they do reaches the running site.
|
||||
|
||||
## Fonts
|
||||
|
||||
|
||||
+15
-18
@@ -61,15 +61,16 @@ const localizedNotFound = {
|
||||
},
|
||||
};
|
||||
|
||||
// Cloudflare Web Analytics beacon: only in builds made by Workers Builds for main
|
||||
// (WORKERS_CI / WORKERS_CI_BRANCH are injected there), so CI, Lighthouse and branch
|
||||
// previews never report page views. Overridable with PUBLIC_CF_BEACON=true|false.
|
||||
// Cloudflare Web Analytics beacon: only in production builds, so CI, Lighthouse and local
|
||||
// builds never report page views. The deploy job in .gitea/workflows/ci.yml sets
|
||||
// PUBLIC_CF_BEACON=true; a Workers Builds build of main (WORKERS_CI / WORKERS_CI_BRANCH,
|
||||
// before the move to Gitea) turns it on by itself.
|
||||
const CF_BEACON_DEFAULT =
|
||||
process.env.WORKERS_CI === "1" && process.env.WORKERS_CI_BRANCH === "main";
|
||||
|
||||
// The commit a build was made from (Workers Builds sets WORKERS_CI_COMMIT_SHA, GitHub Actions
|
||||
// GITHUB_SHA). /api/health reports it next to the Worker version id (src/lib/version.ts), so
|
||||
// "what is live?" maps straight to a commit.
|
||||
// The commit a build was made from (Gitea Actions sets GITHUB_SHA, as GitHub Actions did;
|
||||
// Workers Builds set WORKERS_CI_COMMIT_SHA). /api/health reports it next to the Worker version
|
||||
// id (src/lib/version.ts), so "what is live?" maps straight to a commit.
|
||||
const BUILD_COMMIT = process.env.WORKERS_CI_COMMIT_SHA ?? process.env.GITHUB_SHA ?? null;
|
||||
|
||||
// The poli0981/content commit this build's src/content points at: the gitlink recorded in
|
||||
@@ -123,8 +124,9 @@ export default defineConfig({
|
||||
},
|
||||
|
||||
// Bug-report pipeline env (docs 10). All optional so the site builds + degrades
|
||||
// gracefully until the owner provisions them (Turnstile keys, a fine-grained GitHub
|
||||
// Issues token, and a Discord webhook). The client site key is public + inlined.
|
||||
// gracefully until the owner provisions them (Turnstile keys, a GitLab token that may
|
||||
// open issues on the mirror, and a Discord webhook). The client site key is public +
|
||||
// inlined.
|
||||
env: {
|
||||
schema: {
|
||||
PUBLIC_TURNSTILE_SITE_KEY: envField.string({
|
||||
@@ -133,17 +135,12 @@ export default defineConfig({
|
||||
optional: true,
|
||||
}),
|
||||
TURNSTILE_SECRET: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
GITHUB_ISSUES_TOKEN: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
GITLAB_ISSUES_TOKEN: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
DISCORD_WEBHOOK_BUG: envField.string({ context: "server", access: "secret", optional: true }),
|
||||
// Admin (admin.poli0981.dev), two fine-grained tokens (src/lib/admin/github.ts):
|
||||
// content repo Contents RW, and site repo Actions RW for the publish workflow;
|
||||
// plus the email allowlist on top of Access (unset = the admin refuses everyone).
|
||||
GITHUB_CONTENT_TOKEN: envField.string({
|
||||
context: "server",
|
||||
access: "secret",
|
||||
optional: true,
|
||||
}),
|
||||
GITHUB_PUBLISH_TOKEN: envField.string({
|
||||
// Admin (admin.poli0981.dev): the Gitea token of the bot user poli0981-bot, a Write
|
||||
// collaborator on the content and site repos (src/lib/admin/gitea.ts); plus the email
|
||||
// allowlist on top of Access (unset = the admin refuses everyone).
|
||||
GITEA_BOT_TOKEN: envField.string({
|
||||
context: "server",
|
||||
access: "secret",
|
||||
optional: true,
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
"collect": {
|
||||
"numberOfRuns": 3,
|
||||
"settings": {
|
||||
"throttlingMethod": "simulate"
|
||||
"throttlingMethod": "simulate",
|
||||
"chromeFlags": "--no-sandbox"
|
||||
}
|
||||
},
|
||||
"assert": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# poli0981.dev — Documentation Suite
|
||||
|
||||
- Phiên bản suite: **v2.0** · Ngày: 2026-10-24 (v1.0: 2026-07-17)
|
||||
- Repo: `poli0981/poli0981-dev` (**public** từ 10/2026) · nội dung: `poli0981/content` (submodule `src/content`) · Domain: `poli0981.dev`
|
||||
- Repo: `poli0981/poli0981-dev` (**public** từ 10/2026; từ 2026-11-24 trên Gitea tự host `https://git.poli0981.dev/poli0981/poli0981-dev`, mirror công khai nhận issue/MR `https://gitlab.com/poli0981/poli0981-dev` — `08` §0) · nội dung: `poli0981/content` (submodule `src/content`, cũng trên Gitea) · Domain: `poli0981.dev`
|
||||
- Lịch sử thay đổi theo phiên bản: `CHANGELOG.md` ở gốc repo.
|
||||
- Ngôn ngữ tài liệu: tiếng Việt (thuật ngữ kỹ thuật giữ tiếng Anh). Riêng `12_LEGAL/` soạn song ngữ EN/VI vì là văn bản sẽ render trên site.
|
||||
- Tài liệu gốc: `poli0981.dev_proposal.md` (bản đề xuất v0.1, đã được duyệt).
|
||||
@@ -18,10 +18,10 @@
|
||||
| 05 | 05_SITEMAP_UX.md | Route map, wireframe từng trang, legal gate, mobile nav |
|
||||
| 06 | 06_SECURITY.md | Headers/CSP, form, rate limit, secrets, supply chain |
|
||||
| 07 | 07_CLOUDFLARE_SETUP.md | **Hướng dẫn set Cloudflare từng bước** |
|
||||
| 08 | 08_CI_CD.md | Workflows, permissions, deploy, Dependabot, hooks |
|
||||
| 08 | 08_CI_CD.md | Forge & CI (Gitea), workflows, deploy, Renovate, hooks |
|
||||
| 09 | 09_ERROR_PAGES_OFFLINE.md | 404/403/429/5xx/offline + cách test |
|
||||
| 10 | 10_BUG_REPORT_PIPELINE.md | Console capture → GitHub Issue + Discord |
|
||||
| 11 | 11_WIDGETS_INTEGRATIONS.md | YouTube/Steam/GitHub widgets, cron worker, KV |
|
||||
| 10 | 10_BUG_REPORT_PIPELINE.md | Console capture → issue confidential trên GitLab + Discord |
|
||||
| 11 | 11_WIDGETS_INTEGRATIONS.md | YouTube/Steam/Gitea widgets, cron worker, KV |
|
||||
| 12 | 12_LEGAL/ | 5 văn bản song ngữ (xem dưới) |
|
||||
| 13 | 13_SEO_RSS_OG.md | Meta, hreflang, sitemap, RSS, OG image, AI crawlers |
|
||||
| 14 | 14_PERF_BUDGET.md | Ngân sách hiệu năng + kỷ luật islands |
|
||||
@@ -31,34 +31,35 @@
|
||||
|
||||
`12_LEGAL/`: `TERMS_OF_USE.md` · `PRIVACY_POLICY.md` · `DISCLAIMER.md` · `THIRD_PARTY_NOTICES.md` · `CONTENT_LICENSE.md` — **bản nháp gốc** (07/2026). Văn bản đang hiệu lực là `legal/*.md` trong repo `poli0981/content` (render ở `/legal/*`); sửa ở đó, không sửa ở đây. Hai trang thêm sau (`ai-usage`, `accessibility`) chỉ có ở repo content, không có bản nháp tại đây.
|
||||
|
||||
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-11-10)
|
||||
## Nhật ký quyết định (chốt 2026-07-17, cập nhật 2026-11-24)
|
||||
|
||||
| # | Quyết định | Chọn |
|
||||
|---|---|---|
|
||||
| D1 | Framework/hosting | Astro 7 + Svelte 5 islands, Cloudflare Workers + Static Assets |
|
||||
| D2 | Quy trình viết | Markdown + Git (repo `poli0981/content`). Từ 10/2026 thêm **admin tự viết** ở `admin.poli0981.dev` (soạn/sửa → commit repo content; **Xuất bản** → workflow `content-bump.yml` mở PR bump submodule + auto-merge). Không Keystatic/CMS bên thứ ba |
|
||||
| D2 | Quy trình viết | Markdown + Git (repo `poli0981/content`). Từ 10/2026 thêm **admin tự viết** ở `admin.poli0981.dev` (soạn/sửa → commit repo content; **Xuất bản** → workflow `content-bump.yml` mở PR bump submodule + auto-merge; từ 2026-11-24 việc merge do job `publish` của CI làm, `08` §0b). Không Keystatic/CMS bên thứ ba |
|
||||
| D3 | Q&A | FAQ tĩnh + liên hệ qua social/`contact@` — **không form, không D1** |
|
||||
| D4 | Ngôn ngữ | VI (mặc định, không prefix) + EN (`/en/`) |
|
||||
| D5 | Bình luận blog | Tắt (không Giscus) |
|
||||
| D6 | Legal canonical | Trên site tại `/legal/*`; repo public mirror `poli0981/legal` = tuỳ chọn sau |
|
||||
| D7 | Giấy phép | Code GPL-3.0 · Nội dung All Rights Reserved |
|
||||
| D8 | Error pages | Tự phục vụ từ app (không mua zone Pro) |
|
||||
| D9 | API ngoài | Không weather/map; widget YouTube + Steam + GitHub qua cron worker |
|
||||
| D9 | API ngoài | Không weather/map; widget YouTube + Steam + GitHub qua cron worker (GitHub đến 2026-11-23; nay feed công khai của Gitea — D25) |
|
||||
| D11 | Email | Google Workspace (MX Google), một hộp thư + alias theo chủ đề (`07` §11). Không Cloudflare Email Routing |
|
||||
| D12 | Chống bot | **Cổng Turnstile** trước mọi trang, vé 48 giờ (`06` §3b); bot đã xác thực đi thẳng nhờ Transform Rule `x-verified-bot` |
|
||||
| D13 | Rate limit | WAF rule (edge) → Workers Rate Limiting: RL_SITE toàn site 100/10s → bindings theo nhóm `/api` (`06` §2, `07` §6) thay bộ đếm KV |
|
||||
| D14 | Analytics | Cloudflare Web Analytics, **snippet thủ công** chỉ ở bản build production (`07` §12) |
|
||||
| D15 | Admin | `admin.poli0981.dev` sau Cloudflare Access + Worker tự kiểm JWT (≤ 24 giờ, email phải có trong `ADMIN_EMAILS` — thiếu là từ chối); token GitHub chỉ ghi repo content; ảnh → Images binding → R2; mọi thao tác ghi audit log (`06` §9) |
|
||||
| D15 | Admin | `admin.poli0981.dev` sau Cloudflare Access + Worker tự kiểm JWT (≤ 24 giờ, email phải có trong `ADMIN_EMAILS` — thiếu là từ chối); token GitHub chỉ ghi repo content (đến 2026-11-23; nay một token bot Gitea `GITEA_BOT_TOKEN`, `06` §9); ảnh → Images binding → R2; mọi thao tác ghi audit log (`06` §9) |
|
||||
| D10 | Data services | **KV** (cache widget + ảnh widget mirror cho `/ext-img`, denylist một khoá, audit log admin) + **R2** `poli0981-media` cho ảnh upload qua admin (từ 10/2026; AVIF/WebP sinh một lần lúc upload, phục vụ qua `/media`, cache 1 năm). Không D1. Ảnh build-time cũ vẫn ở `src/assets/` |
|
||||
| D16 | Palette & theme (10/2026) | **Glacier Teal** (xanh đêm + teal) thay palette ấm; theme mặc định **theo hệ điều hành**, nút 3 trạng thái hệ thống/sáng/tối (`03` §2, §6) |
|
||||
| D17 | Toolchain (10/2026) | Node 26 · TypeScript 7 (`tsc` kiểm kiểu) chạy song song TypeScript 6 (astro check, typescript-eslint, svelte2tsx cần JS API) · test bằng `node:test` (không thêm deps) · SonarCloud phân tích qua CI (`08` §0) |
|
||||
| D18 | Báo lỗi (10/2026) | Issue tạo ở repo **private** `poli0981/site-reports` (repo site đã public) — `10` §4 |
|
||||
| D19 | Phát hành | Tag `vX.Y.Z` có ký GPG + GitHub Release + `CHANGELOG.md`; deploy vẫn là "merge `main`" (`08` §8) |
|
||||
| D20 | Trợ năng (11/2026, v2.2.0) | Mục tiêu **WCAG 2.2 AA** — kim chỉ nam, không tự nhận đã được kiểm định. Tuyên bố cho khách ở `/legal/accessibility` (song ngữ, repo content); `ACCESSIBILITY.md` ở root là bản của repo kèm ghi chú cho người sửa code (trang site thắng nếu lệch). Rào cản báo về `accessibility@` hoặc nút "Báo lỗi". Cổng tự động: `npm run test:a11y` (axe-core + bàn phím + reflow + forced-colors, Playwright lái Chrome có sẵn) chạy trong check bắt buộc `build` (`08` §0, checklist ở `03` §8) — ngoại lệ có chủ đích của D17 "không thêm deps cho test" |
|
||||
| D21 | Chế độ bảo trì (11/2026, v2.3.0) | Không thêm tính năng mới. Chỉ nhận: deps định kỳ · vá bảo mật (High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (UI/UX, a11y) · sửa lỗi ngôn ngữ. Bot `triage.yml` gắn `enhancement` + `out-of-scope` và đóng đề xuất tính năng; ngoại lệ = nhãn `maintenance-exception` (`CONTRIBUTING.md`, `17` §0) |
|
||||
| D17 | Toolchain (10/2026) | Node 26 · TypeScript 7 (`tsc` kiểm kiểu) chạy song song TypeScript 6 (astro check, typescript-eslint, svelte2tsx cần JS API) · test bằng `node:test` (không thêm deps) · SonarCloud phân tích qua CI (`08` §0b; bỏ 2026-11-24 — Qodana + Opengrep thay, D25) |
|
||||
| D18 | Báo lỗi (10/2026) | Issue tạo ở repo **private** `poli0981/site-reports` (repo site đã public) — đến 2026-11-23; nay issue **confidential** trên mirror GitLab `poli0981/poli0981-dev` (D25) — `10` §4 |
|
||||
| D19 | Phát hành | Tag `vX.Y.Z` có ký GPG + GitHub Release (từ v2.4.0: Gitea Release) + `CHANGELOG.md`; deploy vẫn là "merge `main`" (`08` §8) |
|
||||
| D20 | Trợ năng (11/2026, v2.2.0) | Mục tiêu **WCAG 2.2 AA** — kim chỉ nam, không tự nhận đã được kiểm định. Tuyên bố cho khách ở `/legal/accessibility` (song ngữ, repo content); `ACCESSIBILITY.md` ở root là bản của repo kèm ghi chú cho người sửa code (trang site thắng nếu lệch). Rào cản báo về `accessibility@` hoặc nút "Báo lỗi". Cổng tự động: `npm run test:a11y` (axe-core + bàn phím + reflow + forced-colors, Playwright lái Chrome có sẵn — trên runner Gitea là Chromium của Playwright, `08` §0b) chạy trong check bắt buộc `build` (`08` §0, checklist ở `03` §8) — ngoại lệ có chủ đích của D17 "không thêm deps cho test" |
|
||||
| D21 | Chế độ bảo trì (11/2026, v2.3.0) | Không thêm tính năng mới. Chỉ nhận: deps định kỳ · vá bảo mật (High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (UI/UX, a11y) · sửa lỗi ngôn ngữ. Bot `triage.yml` gắn `enhancement` + `out-of-scope` và đóng đề xuất tính năng (đến 2026-11-23; nay chủ repo đóng tay trên mirror GitLab — D25); ngoại lệ = nhãn `maintenance-exception` (`CONTRIBUTING.md`, `17` §0) |
|
||||
| D22 | Nhãn nội dung & tuổi (11/2026) | `contentWarning` từ danh sách cố định 11 nhãn (`src/lib/content-labels.ts`) cho blog/truyện/album/từng ảnh + `ageRating` 13+/16+/18+. Banner; ảnh mờ bằng CSS (`:has()`, chạy khi tắt JS); hỏi tuổi bằng `<dialog>` gốc, không tự bật, câu trả lời chỉ ở localStorage `ageGate` (mốc tuổi, không ngày sinh) — Privacy §6 (`04` §2) |
|
||||
| D23 | Xuất bản tự động (11/2026) | Mỗi lần lưu/xoá trong admin tự dispatch `content-bump.yml`; build ghi `__CONTENT_COMMIT__` ⇒ `/api/health` có `version.content`, admin phân biệt "đã merge" với "đã lên web". Điều kiện: Workers Builds deploy `main` (`07` §9) |
|
||||
| D24 | Chất lượng (11/2026) | Thêm **Qodana** (Ultimate, Qodana for JS, ngưỡng 0) cạnh SonarCloud. License: kiểm toàn bộ `package-lock.json`, ngoại lệ theo **gói** có lý do (`scripts/license-policy.mjs`) — license audit của Qodana cần Ultimate Plus nên không dùng (`08` §0) |
|
||||
| D23 | Xuất bản tự động (11/2026) | Mỗi lần lưu/xoá trong admin tự dispatch `content-bump.yml`; build ghi `__CONTENT_COMMIT__` ⇒ `/api/health` có `version.content`, admin phân biệt "đã merge" với "đã lên web". Điều kiện: Workers Builds deploy `main` (`07` §9) — đến 2026-11-23; nay job `deploy` của Gitea CI (D25) |
|
||||
| D24 | Chất lượng (11/2026) | Thêm **Qodana** (Ultimate, Qodana for JS, ngưỡng 0) cạnh SonarCloud (SonarCloud bỏ 2026-11-24, D25). License: kiểm toàn bộ `package-lock.json`, ngoại lệ theo **gói** có lý do (`scripts/license-policy.mjs`) — license audit của Qodana cần Ultimate Plus nên không dùng (`08` §0) |
|
||||
| D25 | Chuyển sang Gitea (11/2026, chốt 2026-11-24, v2.4.0) | Tài khoản GitHub `poli0981` không còn ⇒ repo site + `content` sống trên Gitea tự host `git.poli0981.dev` (bản gốc); mirror công khai `gitlab.com/poli0981/poli0981-dev` nhận issue/MR (người ngoài không đăng ký được Gitea; patch/câu hỏi `code@`, bảo mật chỉ `security@`). CI = Gitea Actions (`.gitea/workflows/`, runner trên PC chủ repo, job lịch chỉ 13:00–16:00 UTC); deploy = job `deploy` của `ci.yml` (`wrangler deploy`) thay Workers Builds, không còn preview cho PR; check bắt buộc `CI / build (*)`. Bỏ SonarCloud, CodeQL/Snyk, `triage.yml`, Dependabot ⇒ Qodana + `security.yml` (gitleaks/Opengrep/osv-scanner) + Renovate tự host. Admin: một token bot `GITEA_BOT_TOKEN`; báo lỗi: issue confidential trên GitLab; widget hoạt động: feed Gitea không token. Runbook: repo `poli0981/.github`, `docs/GITEA-MIGRATION.md` (`08` §0) |
|
||||
|
||||
## Cách dùng suite
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
|
||||
|
||||
## 2. Mục tiêu
|
||||
|
||||
1. Một địa chỉ duy nhất đại diện cả hai "mặt": developer (GitHub poli0981) và creator (SkullMute).
|
||||
1. Một địa chỉ duy nhất đại diện cả hai "mặt": developer (poli0981 — GitHub đến 11/2026, nay Gitea `git.poli0981.dev/poli0981`) và creator (SkullMute).
|
||||
2. Viết được **thoải mái và bền**: blog/nhật ký/truyện bằng Markdown, xuất bản bằng `git push` hoặc nút **Xuất bản** của admin tự viết — không phụ thuộc CMS bên thứ ba.
|
||||
3. Đẹp có chủ đích ("Phòng đọc lúc nửa đêm"), không giống template, mobile hoàn chỉnh.
|
||||
4. Vận hành ~US$12–13/năm phát sinh mới; không thêm dịch vụ trả phí nào khác.
|
||||
@@ -25,7 +25,7 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
|
||||
| Persona | Đến từ | Cần gì |
|
||||
|---|---|---|
|
||||
| Viewer của kênh | YouTube/Discord | Xem "người đứng sau kênh", video mới, đang chơi gì, FAQ, link social |
|
||||
| Dev/recruiter/collab | GitHub, mail sponsor | Portfolio project, /uses, cách liên hệ đáng tin (`contact@poli0981.dev`) |
|
||||
| Dev/recruiter/collab | Gitea/GitLab (trước 11/2026: GitHub), mail sponsor | Portfolio project, /uses, cách liên hệ đáng tin (`contact@poli0981.dev`) |
|
||||
| Độc giả truyện | Social/share link | Trải nghiệm đọc dài thoải mái trên điện thoại, theo dõi qua RSS |
|
||||
| Chính Kokone | — | Viết nhanh, đăng nhanh, không phải bảo trì nhiều |
|
||||
|
||||
@@ -37,18 +37,18 @@ Website cá nhân `poli0981.dev` cho Kokone: **portfolio dev + blog kiêm nhật
|
||||
|---|---|---|
|
||||
| Trang chủ | Hero + signature Waveline, bài blog/truyện mới nhất, widget video mới + đang chơi gì | P1 (widget P2) |
|
||||
| /about | Song ngữ, 2 mặt dev/creator, ảnh đại diện, timeline ngắn | P1 |
|
||||
| /projects | Card từ collection `projects`, filter theo tag, link GitHub/release | P1 |
|
||||
| /projects | Card từ collection `projects`, filter theo tag, link repo (Gitea; trước 11/2026: GitHub)/release | P1 |
|
||||
| /blog | Index + trang bài, tag, reading time, RSS riêng | P1 |
|
||||
| /stories | Index theo series/status, **reader mode** riêng (font serif, chỉnh cỡ chữ, theme giấy, progress, prev/next chương, content-warning) | P1 |
|
||||
| /gallery | Album theo năm/sự kiện, lightbox, EXIF đã strip | P2 |
|
||||
| /gaming | Giới thiệu kênh, embed video (click-to-load, nocookie), thể loại yêu thích, widget Steam | P2 |
|
||||
| /dev (/uses) | PC specs, tool stack, setup OBS/Resolve | P2 |
|
||||
| /qa | FAQ tĩnh từ collection `faq` + khối "Liên hệ" trỏ /links và `contact@` | P1 |
|
||||
| /links | Toàn bộ social (YouTube, Discord ×2, GitHub, Telegram, Bluesky, Mastodon, X, Facebook), icon + mô tả | P1 |
|
||||
| /links | Toàn bộ social (YouTube, Discord ×2, Gitea (trước 11/2026: GitHub), Telegram, Bluesky, Mastodon, X, Facebook), icon + mô tả | P1 |
|
||||
| /legal/* | 7 trang song ngữ: 5 trang gốc từ `12_LEGAL/` + `ai-usage` + `accessibility` (tuyên bố trợ năng, 11/2026) | P1 |
|
||||
| Search | Pagefind, modal, lọc theo locale | P2 |
|
||||
| Error/offline | 404/403/429/500/offline custom | P1 (mini-game P3) |
|
||||
| Bug report | Nút footer → GitHub Issue + Discord | P2 |
|
||||
| Bug report | Nút footer → issue (GitHub đến 2026-11-23; nay issue confidential trên mirror GitLab) + Discord | P2 |
|
||||
| Legal gate | Bottom-sheet lần đầu truy cập | P1 |
|
||||
|
||||
## 6. Yêu cầu phi chức năng
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 1. Tổng quan
|
||||
|
||||
Site **prerender tĩnh gần như toàn bộ** bằng Astro, deploy lên **Cloudflare Workers + Static Assets**. Một Worker chính (`poli0981-dev`) phục vụ site, admin và vài API route; một Worker phụ (`poli0981-widgets`) chạy cron lấy dữ liệu YouTube/Steam/GitHub vào KV.
|
||||
Site **prerender tĩnh gần như toàn bộ** bằng Astro, deploy lên **Cloudflare Workers + Static Assets**. Một Worker chính (`poli0981-dev`) phục vụ site, admin và vài API route; một Worker phụ (`poli0981-widgets`) chạy cron lấy dữ liệu YouTube/Steam/Gitea vào KV.
|
||||
|
||||
```
|
||||
Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Transform Rule x-verified-bot)
|
||||
@@ -20,11 +20,11 @@ Khách ──HTTPS──> Cloudflare edge (WAF free, Bot Fight, DDoS auto, Trans
|
||||
└── /api/*, /admin* → app Astro (@astrojs/cloudflare/handler)
|
||||
├── middleware: admin (Access JWT + CSRF), rate limit /api, trang lỗi
|
||||
├── /api/report · /api/gate · /api/widgets · /api/health
|
||||
└── /admin/* + /api/admin/* (GitHub API → repo content, R2, Images, KV)
|
||||
└── /admin/* + /api/admin/* (Gitea API → repo content, R2, Images, KV)
|
||||
▲ đọc │ ghi
|
||||
KV (widgets:*, denylist, audit:*) ◄───┘
|
||||
▲ ghi
|
||||
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / GitHub API (+ mirror ảnh)
|
||||
Worker "widgets" (cron 45') ──> YouTube RSS / Steam API / feed Gitea (+ mirror ảnh)
|
||||
```
|
||||
|
||||
Mọi response đi ra đều qua `withSecurityHeaders` (`src/lib/security-headers.ts`) và mang log JSON có cấu trúc (`src/lib/log.ts`: `event`, `ray`, `path`… — xem `06` §10).
|
||||
@@ -33,16 +33,16 @@ Mọi response đi ra đều qua `withSecurityHeaders` (`src/lib/security-header
|
||||
|
||||
| Thành phần | Bản | Ghi chú |
|
||||
|---|---|---|
|
||||
| Node.js | 26 (`.nvmrc` = `26`, Workers Builds `NODE_VERSION=26`) | engines: `>=26` |
|
||||
| Node.js | 26 (`.nvmrc` = `26`, CI đọc `.nvmrc`; Workers Builds `NODE_VERSION=26` đến 2026-11) | engines: `>=26` |
|
||||
| Astro | ^7.4 | CSP API + Fonts API built-in |
|
||||
| @astrojs/cloudflare | ^14.4 | target Workers; entry riêng `src/worker.ts` |
|
||||
| @astrojs/mdx, sitemap, rss | ^8 · ^3 · ^4 | item RSS dựng ở `src/lib/rss.ts` (truyện chỉ mô tả + link) |
|
||||
| Svelte + @astrojs/svelte | 5 + ^9.1 | islands |
|
||||
| Tailwind CSS | ^4 | CSS-first, `@theme` |
|
||||
| Pagefind | ^1 | chạy post-build |
|
||||
| Wrangler | ^4.152 | dev, types, smoke test, deploy tay |
|
||||
| Wrangler | ^4.152 | dev, types, smoke test, deploy (job `deploy` của CI từ 2026-11-24; widgets deploy tay) |
|
||||
| TypeScript | **7.0** (`@typescript/native` → `tsc`) + **6.0** (`typescript`) | TS7 kiểm kiểu nhanh (`npm run typecheck`), TS6 cho astro check / typescript-eslint / svelte2tsx (TS 7.0 chưa có JS API). `target`/`lib` = ES2025, `erasableSyntaxOnly` |
|
||||
| Test | `node:test` của Node 26 | không thêm deps; `module.registerHooks` giả lập `astro:*`/`cloudflare:workers`; coverage lcov cho SonarCloud |
|
||||
| Test | `node:test` của Node 26 | không thêm deps; `module.registerHooks` giả lập `astro:*`/`cloudflare:workers`; coverage ≥ 80% dòng (lcov từng gửi SonarCloud, bỏ 2026-11-24) |
|
||||
| jose · marked · yaml · zod | ^6 · ^18 · ^2 · ^4 | Access JWT · preview admin · frontmatter · schema |
|
||||
|
||||
## 3. Cấu trúc repo
|
||||
@@ -53,7 +53,7 @@ poli0981-dev/
|
||||
├── docs/templates/ # khung bài mới (npm run new:post)
|
||||
├── public/ # favicon, robots.txt, security.txt, sw.js, gate.js, skullhop.js
|
||||
├── scripts/ # gen-og, gen-notices, check-exif/strip-exif, check-csp-hashes,
|
||||
│ # check-install-scripts, smoke-worker, new-post
|
||||
│ # check-install-scripts, smoke-worker, new-post, content-publish
|
||||
├── src/
|
||||
│ ├── worker.ts # entry: denylist, rate limit site, host, /media, /ext-img, cổng, assets
|
||||
│ ├── middleware.ts # admin JWT + CSRF, rate limit /api, trang lỗi
|
||||
@@ -67,10 +67,12 @@ poli0981-dev/
|
||||
│ ├── lib/ # gate/, admin/, media/, denylist, ext-img, log, version, palette, theme…
|
||||
│ ├── pages/ # routes + /en/* + api/* + admin/* + 403/404/429/500
|
||||
│ └── styles/ # global.css (token), prose.css, admin.css
|
||||
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/GitHub…) · a11y/ (*.spec.ts: axe-core + bàn phím qua Playwright)
|
||||
├── tests/ # node:test + support/ (stub astro:*, fake KV/R2/Gitea…) · a11y/ (*.spec.ts: axe-core + bàn phím qua Playwright)
|
||||
├── workers/widgets/ # worker cron riêng (wrangler.jsonc riêng)
|
||||
├── .github/ # ci.yml, content-bump.yml, lighthouse.yml, osv-scanner.yml, qodana.yml, triage.yml, dependabot.yml, ISSUE_TEMPLATE/ (config, bug_report, accessibility, language), pull_request_template.md
|
||||
├── astro.config.mjs · wrangler.jsonc · sonar-project.properties · qodana.yaml · lefthook.yml · knip.json
|
||||
├── .gitea/workflows/ # ci.yml (build · deploy · publish), content-bump.yml, security.yml, qodana.yml, lighthouse.yml (08 §0)
|
||||
├── .github/ # ISSUE_TEMPLATE/ (config, bug_report, accessibility, language — Gitea đọc) + pull_request_template.md
|
||||
├── .gitlab/ # issue_templates/ (Bug, Accessibility, Language) + merge_request_templates/Default.md — cho mirror GitLab
|
||||
├── astro.config.mjs · wrangler.jsonc · renovate.json · qodana.yaml · lefthook.yml · knip.json
|
||||
└── LICENSE (GPL-3.0) · CONTENT-LICENSE.md · DISCLAIMER.md · THIRD-PARTY-NOTICES.md · SECURITY.md · ACCESSIBILITY.md · CONTRIBUTING.md · CHANGELOG.md
|
||||
```
|
||||
|
||||
@@ -96,7 +98,7 @@ poli0981-dev/
|
||||
"html_handling": "auto-trailing-slash", "run_worker_first": ["/*", "!/_astro/*", "…"] },
|
||||
"kv_namespaces": [{ "binding": "KV", "id": "…" }],
|
||||
"ratelimits": [ RL_SITE 100/10s · RL_REPORT 5/60s · RL_GATE 30/60s · RL_ADMIN 120/60s · RL_API 120/60s ],
|
||||
"vars": { "GATE_MODE": "on", "ACCESS_TEAM_DOMAIN": "…", "ACCESS_AUD": "…", "REPORT_REPO": "poli0981/site-reports" },
|
||||
"vars": { "GATE_MODE": "on", "ACCESS_TEAM_DOMAIN": "…", "ACCESS_AUD": "…", "REPORT_PROJECT": "poli0981/poli0981-dev" }, // project GitLab (10 §4)
|
||||
"r2_buckets": [{ "binding": "MEDIA", "bucket_name": "poli0981-media" }],
|
||||
"images": { "binding": "IMAGES" },
|
||||
"version_metadata": { "binding": "CF_VERSION_METADATA" },
|
||||
@@ -105,7 +107,7 @@ poli0981-dev/
|
||||
}
|
||||
```
|
||||
|
||||
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng đầy đủ ở `06` §4): `TURNSTILE_SECRET`, `GATE_SECRET`, `GITHUB_ISSUES_TOKEN`, `DISCORD_WEBHOOK_BUG`, `GITHUB_CONTENT_TOKEN`, `GITHUB_PUBLISH_TOKEN`, `ADMIN_EMAILS`.
|
||||
Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng đầy đủ ở `06` §4): `TURNSTILE_SECRET`, `GATE_SECRET`, `GITLAB_ISSUES_TOKEN`, `DISCORD_WEBHOOK_BUG`, `GITEA_BOT_TOKEN`, `ADMIN_EMAILS` (từ 2026-11-24; trước đó `GITHUB_ISSUES_TOKEN`, `GITHUB_CONTENT_TOKEN`, `GITHUB_PUBLISH_TOKEN`).
|
||||
|
||||
`/api/health` trả `version` (id bản Worker đang chạy + commit đã build, từ `version_metadata` và `__BUILD_COMMIT__`) — dùng để xác minh deploy từ bên ngoài.
|
||||
|
||||
@@ -119,7 +121,7 @@ Secrets (đặt bằng `wrangler secret put`, không bao giờ commit — bảng
|
||||
## 7. Setup máy dev (một lần)
|
||||
|
||||
```bash
|
||||
git clone --recurse-submodules https://github.com/poli0981/poli0981-dev.git
|
||||
git clone --recurse-submodules https://git.poli0981.dev/poli0981/poli0981-dev.git
|
||||
cd poli0981-dev
|
||||
nvm use # đọc .nvmrc = 26
|
||||
npm ci --ignore-scripts && npm run check-install-scripts
|
||||
@@ -128,14 +130,14 @@ npm run types && npm run types:widgets
|
||||
npm run dev # astro dev trên workerd (bindings local); admin dùng danh tính giả dev@localhost
|
||||
```
|
||||
|
||||
Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR description; mỗi gói mới phải qua `npm audit` + Dependabot theo dõi; `THIRD-PARTY-NOTICES.md` sinh bằng `scripts/gen-notices.mjs` và CI kiểm lệch.
|
||||
Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR description; mỗi gói mới phải qua `npm audit` + Renovate theo dõi; `THIRD-PARTY-NOTICES.md` sinh bằng `scripts/gen-notices.mjs` và CI kiểm lệch.
|
||||
|
||||
## 8. Chính sách phiên bản & CVE
|
||||
|
||||
- Pin `^` trong cùng major; Dependabot mở PR patch/minor hằng tuần (cooldown 3 ngày — `08` §6).
|
||||
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + preview (`17` §2).
|
||||
- **TypeScript 7**: `@typescript/native` là alias `npm:typescript@7` — Dependabot bỏ qua alias `npm:`, nên nâng tay; `typescript` (bản 6) giữ đến khi TS 7.1 có JS API cho astro check / typescript-eslint / svelte2tsx, lúc đó gộp về một bản.
|
||||
- Theo dõi CVE liên tục: Dependabot alerts, `npm audit` (CI), OSV-Scanner, Snyk, CodeQL, SonarCloud (`06` §6).
|
||||
- Pin `^` trong cùng major; Renovate (tự host, chạy hằng ngày) gộp patch/minor vào một PR, chỉ đề xuất bản đã phát hành ≥ 3 ngày (`08` §6). Đến 2026-11-23: Dependabot hằng tuần, cooldown 3 ngày.
|
||||
- Trước mỗi lần nâng **major**: đọc upgrade guide chính thức + chạy toàn bộ CI + thử local (`17` §2; từ 2026-11-24 không còn version preview cho PR).
|
||||
- **TypeScript 7**: `@typescript/native` là alias `npm:typescript@7` — thời Dependabot (bỏ qua alias `npm:`) phải nâng tay; Renovate theo dõi nó như một dependency riêng, luật giữ `typescript` major không chặn nó. `typescript` (bản 6) giữ đến khi TS 7.1 có JS API cho astro check / typescript-eslint / svelte2tsx, lúc đó gộp về một bản.
|
||||
- Theo dõi CVE liên tục: Renovate (cảnh báo OSV ⇒ PR nhãn `security`), `npm audit` (CI), `security.yml` (osv-scanner, Opengrep, gitleaks), Qodana (`06` §6). Đến 2026-11-23 còn Dependabot alerts, Snyk, CodeQL, SonarCloud.
|
||||
|
||||
## 9. ADR (Architecture Decision Records — rút gọn)
|
||||
|
||||
@@ -144,11 +146,11 @@ Quy tắc gói bên thứ ba: chỉ thêm khi có lý do trong ADR/PR descriptio
|
||||
| 01 | Astro thay vì SvelteKit/Next | Content-first, ~0 JS mặc định, Content Collections type-safe, RSS/sitemap first-class | Site biến thành web-app nhiều tương tác |
|
||||
| 02 | Workers thay vì Pages | Hướng Cloudflare khuyến nghị cho dự án mới; assets request free; 1 nền tảng cho cả site + cron | — |
|
||||
| 03 | Svelte islands thay vì React | Nhẹ hơn, đã quen từ WXT/BookmarkMagic; tránh kéo React runtime vào site tĩnh | Cần lib chỉ có React |
|
||||
| 04 | Admin tự viết thay vì Keystatic (10/2026) | Host riêng sau Access + kiểm JWT; token chỉ ghi repo content, xuất bản qua workflow có CI; ảnh qua Images binding → R2; ít deps (`jose`, `yaml`, `marked`) | Cần nhiều người biên tập / phân quyền |
|
||||
| 05 | Không D1/Sentry | Q&A form bị bỏ; bug report đi thẳng GitHub+Discord; lỗi runtime xem ở Workers Logs (log JSON) | Xuất hiện nhu cầu dữ liệu động thật |
|
||||
| 04 | Admin tự viết thay vì Keystatic (10/2026) | Host riêng sau Access + kiểm JWT; token chỉ ghi repo content, xuất bản qua workflow có CI (từ 2026-11-24 một token bot Gitea, `06` §9); ảnh qua Images binding → R2; ít deps (`jose`, `yaml`, `marked`) | Cần nhiều người biên tập / phân quyền |
|
||||
| 05 | Không D1/Sentry | Q&A form bị bỏ; bug report đi thẳng issue + Discord (issue trên GitHub đến 2026-11-23; nay issue confidential trên GitLab, `10` §4); lỗi runtime xem ở Workers Logs (log JSON) | Xuất hiện nhu cầu dữ liệu động thật |
|
||||
| 06 | GPL-3.0 code / ARR content | Nhất quán hệ sinh thái repo; truyện & ảnh cần bảo hộ chặt | — |
|
||||
| 07 | Error pages tự phục vụ | Custom Errors của Cloudflare cần zone plan trả phí; site chạy trên Worker nên tự làm được | Nếu một ngày mua Pro vì lý do khác |
|
||||
| 08 | Logic edge ở worker entry (`src/worker.ts`) | Trang tĩnh được adapter phục vụ trước middleware ⇒ cổng Turnstile, denylist, `/media`, chuyển host, security headers phải nằm ở entry + `assets.run_worker_first` | Adapter có hook chính thức cho trang tĩnh |
|
||||
| 09 | TypeScript 7 song song TypeScript 6 (10/2026) | `tsc` 7 nhanh hơn nhiều cho kiểm kiểu; công cụ hệ sinh thái chưa chạy được trên TS 7.0 (không có JS API) | TS 7.1 có API mới |
|
||||
| 10 | `node:test` + SonarCloud thay Vitest (10/2026) | Không thêm deps; Node 26 chạy thẳng TypeScript, `registerHooks` giả lập module ảo; lcov cho quality gate | Cần test component trong DOM thật |
|
||||
| 10 | `node:test` + SonarCloud thay Vitest (10/2026) | Không thêm deps; Node 26 chạy thẳng TypeScript, `registerHooks` giả lập module ảo; lcov cho quality gate (SonarCloud bỏ 2026-11-24 khi chuyển Gitea; ngưỡng 80% dòng vẫn nằm trong `test:coverage`) | Cần test component trong DOM thật |
|
||||
| 11 | Palette Glacier Teal + theme theo hệ điều hành (10/2026) | Tông lạnh theo yêu cầu chủ site; mọi cặp màu kiểm WCAG AA bằng test; một nguồn màu `src/lib/palette.ts` | Đổi nhận diện |
|
||||
@@ -122,7 +122,7 @@ Token `--scrollbar-thumb` / `--scrollbar-thumb-hover` / `--scrollbar-track` khai
|
||||
| MenuSheet | island | dialog modal, bẫy focus, trả focus về nút mở |
|
||||
| LegalGateSheet | island | spec ở `05` §6 |
|
||||
| Waveline | island | §5 |
|
||||
| WidgetLatestVideo / WidgetNowPlaying / WidgetGitHub | .astro | đọc KV lúc request?—không: đọc lúc **build** + island refresh nhẹ (xem 11 §5) |
|
||||
| WidgetLatestVideo / WidgetNowPlaying / WidgetGitea (trước 2026-11-24: WidgetGitHub) | .astro | đọc KV lúc request?—không: đọc lúc **build** + island refresh nhẹ (xem 11 §5) |
|
||||
| Callout, TagPill, Pagination | .astro | |
|
||||
|
||||
## 8. A11y & mobile checklist (áp cho mọi PR UI)
|
||||
|
||||
@@ -102,16 +102,16 @@ tags: [horror, short-story]
|
||||
|
||||
## 5a. Viết qua admin (`admin.poli0981.dev`)
|
||||
|
||||
- **Nội dung**: danh sách theo collection → *Tạo mới* (loại, slug, ngôn ngữ; truyện cần slug bộ) hoặc sửa bài có sẵn. Form theo đúng schema (`src/lib/admin/collections.ts`), thân bài Markdown + *Xem trước*, *Chèn ảnh* (chèn `<picture>` từ thư viện), *Ảnh bìa* (`coverMedia`). **Lưu** = commit thẳng vào `poli0981/content` (`main`), giữ nguyên định dạng frontmatter phần không sửa; sửa song song trên GitHub ⇒ báo xung đột (409) thay vì ghi đè.
|
||||
- **Nội dung**: danh sách theo collection → *Tạo mới* (loại, slug, ngôn ngữ; truyện cần slug bộ) hoặc sửa bài có sẵn. Form theo đúng schema (`src/lib/admin/collections.ts`), thân bài Markdown + *Xem trước*, *Chèn ảnh* (chèn `<picture>` từ thư viện), *Ảnh bìa* (`coverMedia`). **Lưu** = commit thẳng vào `poli0981/content` (`main`), giữ nguyên định dạng frontmatter phần không sửa; sửa song song (trên Gitea hay chỗ khác) ⇒ báo xung đột (409) thay vì ghi đè. Từ 2026-11-24 repo content nằm trên Gitea (`https://git.poli0981.dev/poli0981/content`), admin ghi qua token bot `GITEA_BOT_TOKEN` (`06` §9).
|
||||
- **Ảnh**: kéo-thả nhiều ảnh → nén một lần (AVIF/WebP, bỏ EXIF) → R2; sửa alt, copy snippet, xoá khi không còn bài nào dùng.
|
||||
- **Gallery**: tạo album (vi/en + `gallery-photos/<album>.json` trong một commit), thêm/bớt/sắp xếp ảnh R2, chú thích vi/en bắt buộc.
|
||||
- **Xuất bản**: nút trên thanh admin ⇒ workflow `content-bump.yml` (xem `08` §0); site cập nhật sau khi CI xanh và Workers Builds deploy (~5–8 phút). Bài mới tạo mặc định `draft: true` — bỏ tick để hiện trên site.
|
||||
- Lưu ý: repo content **public** ⇒ bản nháp vẫn đọc được trên GitHub.
|
||||
- **Xuất bản**: nút trên thanh admin ⇒ workflow `content-bump.yml` (xem `08` §0); site cập nhật sau khi CI xanh, job `publish` merge PR và job `deploy` deploy `main` (đến 2026-11-23: Workers Builds deploy; ~5–8 phút). Runner chạy trên PC của chủ repo ⇒ PC tắt thì xuất bản chờ tới khi runner lên lại. Bài mới tạo mặc định `draft: true` — bỏ tick để hiện trên site.
|
||||
- Lưu ý: repo content **public** ⇒ bản nháp vẫn đọc được trên Gitea và mirror GitLab (đến 2026-11-23: GitHub).
|
||||
|
||||
## 5. Quy trình viết (quyết định D2 — Markdown + Git thuần)
|
||||
|
||||
1. **Ở PC**: tạo file trong VS Code/Obsidian (vault trỏ thẳng `src/content/`), viết với `draft: true`, xem bằng `npm run dev`.
|
||||
2. **Capture từ điện thoại**: github.com → repo → thư mục collection → Add file → viết vài dòng + frontmatter tối thiểu + `draft: true` → commit thẳng `main` (draft không build ra site nên an toàn).
|
||||
2. **Capture từ điện thoại**: `git.poli0981.dev` → repo `content` → thư mục collection → Add File → New File (đến 2026-11-23: github.com) → viết vài dòng + frontmatter tối thiểu + `draft: true` → commit thẳng `main` (draft không build ra site nên an toàn).
|
||||
3. **Xuất bản**: bỏ `draft`, điền đủ frontmatter, chạy checklist §7, push → CI deploy.
|
||||
4. Template sẵn: `docs/templates/{blog,story-chapter,project,faq}.md` — copy là viết.
|
||||
|
||||
|
||||
@@ -51,11 +51,11 @@ ReadingControls: cỡ chữ S/M/L · nền Giấy/Sepia/Tối (độc lập them
|
||||
|
||||
**Gaming**: hero kênh (banner + subscribe button link) → 3 video mới (YouTube RSS, thumbnail click-to-load nocookie) → "Đang chơi" (Steam) → khối "Mình cover gì": VN · JRPG · indie/psychological horror (kèm dòng: không FPS/competitive) → link Discord gaming server. Được phép scanline nhẹ (03 §4).
|
||||
|
||||
**Dev**: intro → grid project featured → /uses (bảng: PC specs i7-14700KF · RTX 5080 16GB · 32GB DDR5 · 2K 240Hz · Win 11 Pro; software: OBS, Resolve Studio, VS Code…) → hoạt động GitHub (widget).
|
||||
**Dev**: intro → grid project featured → /uses (bảng: PC specs i7-14700KF · RTX 5080 16GB · 32GB DDR5 · 2K 240Hz · Win 11 Pro; software: OBS, Resolve Studio, VS Code…) → hoạt động Gitea (widget; trước 2026-11-24 là GitHub).
|
||||
|
||||
**Q&A**: accordion theo group (Kênh/Dev/Cá nhân) → khối Liên hệ: "Nhanh nhất: Discord · Business: contact@poli0981.dev · Toàn bộ: /links".
|
||||
|
||||
**Links**: danh sách dọc lớn (icon + tên + mô tả 1 dòng + nút): YouTube, Discord gaming, Discord repo, GitHub, Telegram, Bluesky, Mastodon, X, Facebook page. `rel="me"` cho Mastodon verify.
|
||||
**Links**: danh sách dọc lớn (icon + tên + mô tả 1 dòng + nút): YouTube, Discord gaming, Discord repo, Gitea (trước 2026-11-24: GitHub), Telegram, Bluesky, Mastodon, X, Facebook page. `rel="me"` cho Mastodon verify.
|
||||
|
||||
## 3. Điều hướng
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ request → src/worker.ts (mọi route, cả trang tĩnh)
|
||||
|
||||
## 3. Form duy nhất: /api/report (bug)
|
||||
|
||||
Rate limit §2 → body đọc có trần **32 KB** (khai `Content-Length` lớn hơn hoặc stream vượt ⇒ 413, không đọc hết) → validate Zod (`10` §3) → Turnstile `siteverify` (`success` + `action: "report"` + `hostname`) → issue ở repo **private** `poli0981/site-reports` + Discord (`allowed_mentions` rỗng, `@mention` trong nội dung bị vô hiệu) — mỗi lời gọi ra ngoài có timeout 10 s. Sai bất kỳ bước nào: 400/413/429, message chung chung, không lộ chi tiết.
|
||||
Rate limit §2 → body đọc có trần **32 KB** (khai `Content-Length` lớn hơn hoặc stream vượt ⇒ 413, không đọc hết) → validate Zod (`10` §3) → Turnstile `siteverify` (`success` + `action: "report"` + `hostname`) → issue **confidential** trên mirror GitLab `poli0981/poli0981-dev` (đến 2026-11-23: repo private `poli0981/site-reports` trên GitHub) + Discord (`allowed_mentions` rỗng, `@mention` và quick action GitLab trong nội dung bị vô hiệu) — mỗi lời gọi ra ngoài có timeout 10 s. Sai bất kỳ bước nào: 400/413/429, message chung chung, không lộ chi tiết.
|
||||
|
||||
Các API khác cũng có trần body: `/api/gate` 8 KB; JSON của admin 512 KB và bắt buộc `Content-Type: application/json`; upload ảnh 20 MB (từ chối theo `Content-Length` trước khi parse form).
|
||||
|
||||
@@ -79,29 +79,30 @@ gate.js → Turnstile (action "gate") → POST /api/gate (RL_GATE, Sec-Fetch-Sit
|
||||
|---|---|---|
|
||||
| TURNSTILE_SECRET | worker site | form báo lỗi + cổng |
|
||||
| GATE_SECRET | worker site | ký vé cổng (≥ 32 byte ngẫu nhiên) |
|
||||
| GITHUB_ISSUES_TOKEN | worker site | Fine-grained PAT: **chỉ repo `poli0981/site-reports`, chỉ Issues R/W**, hạn ≤ 1 năm |
|
||||
| GITLAB_ISSUES_TOKEN | worker site | token GitLab, role **Reporter** trên project mirror `poli0981/poli0981-dev`, scope `api` — chỉ để tạo issue confidential (`10` §4) |
|
||||
| DISCORD_WEBHOOK_BUG | worker site | webhook 1 kênh riêng |
|
||||
| GITHUB_CONTENT_TOKEN | worker site | Fine-grained PAT: **chỉ `poli0981/content`, Contents R/W** (admin lưu bài) |
|
||||
| GITHUB_PUBLISH_TOKEN | worker site | Fine-grained PAT: **chỉ `poli0981/poli0981-dev`, Actions R/W** (nút Xuất bản). Thiếu ⇒ admin dùng tạm token nội dung và cảnh báo "một token" |
|
||||
| GITEA_BOT_TOKEN | worker site | token `write:repository` của user bot `poli0981-bot`, collaborator Write **chỉ** trên `poli0981/content` (admin lưu bài) và `poli0981/poli0981-dev` (nút Xuất bản dispatch `content-bump.yml`) — §9 |
|
||||
| ADMIN_EMAILS | worker site | email được vào admin, phân cách dấu phẩy — **bắt buộc**, thiếu là không ai vào được |
|
||||
| STEAM_API_KEY, STEAM_ID64, DISCORD_WEBHOOK_CI | worker widgets | key Steam mặc định; webhook cảnh báo cron |
|
||||
| GITHUB_TOKEN (tuỳ chọn) | worker widgets | fine-grained PAT **không quyền nào** (chỉ đọc dữ liệu public) — nâng hạn mức API events từ 60/giờ/IP (IP egress của Workers dùng chung, hay bị 403) |
|
||||
| SONAR_TOKEN | GitHub Actions secret | phân tích SonarCloud (`08` §0) |
|
||||
| QODANA_TOKEN | secret Actions (Gitea) | token project trên Qodana Cloud (`08` §0b) |
|
||||
| CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID | secret Actions cấp user (Gitea) | job `deploy` của `ci.yml` — quyền ở `07` §10 |
|
||||
|
||||
Bỏ ngày 2026-11-24 (chuyển sang Gitea): `GITHUB_ISSUES_TOKEN` (PAT chỉ repo private `poli0981/site-reports`, Issues R/W), `GITHUB_CONTENT_TOKEN` + `GITHUB_PUBLISH_TOKEN` (hai PAT của admin, thay bằng `GITEA_BOT_TOKEN`), `GITHUB_TOKEN` tuỳ chọn của worker widgets (feed Gitea không cần token), `SONAR_TOKEN` (secret GitHub Actions của SonarCloud).
|
||||
|
||||
Không secret nào trong repo/`wrangler.jsonc`; `.dev.vars` nằm trong `.gitignore`. Admin chỉ hiện **tên** secret đã/chưa đặt (`/admin/security/`), không bao giờ hiện giá trị.
|
||||
|
||||
`wrangler secret put` tạo một version mới dựa trên version **mới nhất** đã upload và deploy nó ngay: chỉ đặt secret khi version mới nhất là bản của `main` (không phải bản preview của một PR) — kiểm bằng `wrangler versions list` trước.
|
||||
`wrangler secret put` tạo một version mới dựa trên version **mới nhất** đã upload và deploy nó ngay: chỉ đặt secret khi version mới nhất là bản của `main` (không phải bản preview của một PR) — kiểm bằng `wrangler versions list` trước. (Từ 2026-11-24 CI không còn upload version preview cho PR, nhưng một `versions upload` chạy tay vẫn có thể là bản mới nhất.)
|
||||
|
||||
## 5. Nội dung nhúng bên thứ ba
|
||||
|
||||
- YouTube: **click-to-load facade** — thumbnail do worker widgets mirror vào KV và site phục vụ qua `/ext-img/yt/<id>` (icon Steam qua `/ext-img/steam/…`), nên trình duyệt khách **không gọi** `i.ytimg.com`/Steam trước khi bấm; bấm mới tạo iframe `youtube-nocookie.com`. `/ext-img` chỉ nhận đúng 2 mẫu đường dẫn, chỉ đọc KV (không bao giờ fetch theo yêu cầu của khách), trả kèm `CSP: sandbox`.
|
||||
- Ngoại lệ duy nhất cho script bên ngoài: beacon Cloudflare Web Analytics (`static.cloudflareinsights.com`, báo về `cloudflareinsights.com`) — `type=module`, không cookie, chỉ có trong bản build production của Workers Builds (`src/components/CfBeacon.astro`). Turnstile chỉ tải khi trang xác minh/form báo lỗi cần. Còn lại: không font/CDN/script ngoài — mọi asset self-host.
|
||||
- Ngoại lệ duy nhất cho script bên ngoài: beacon Cloudflare Web Analytics (`static.cloudflareinsights.com`, báo về `cloudflareinsights.com`) — `type=module`, không cookie, chỉ có trong bản build production — job `deploy` của CI đặt `PUBLIC_CF_BEACON=true` (đến 2026-11-23: bản build `main` của Workers Builds) (`src/components/CfBeacon.astro`). Turnstile chỉ tải khi trang xác minh/form báo lỗi cần. Còn lại: không font/CDN/script ngoài — mọi asset self-host.
|
||||
|
||||
## 6. Supply chain (repo public từ 10/2026)
|
||||
|
||||
- **Cài đặt**: `npm ci --ignore-scripts` từ lockfile ở CI; `scripts/check-install-scripts.mjs` liệt kê gói có install script và fail khi xuất hiện gói mới ngoài allowlist (esbuild/workerd/sharp chạy được nhờ optionalDependencies, không cần script).
|
||||
- **Quét**: Dependabot (alerts + security updates, **cooldown 3 ngày** — không đề xuất bản vừa phát hành, chặn kiểu Shai-Hulud) · `npm audit --omit=dev --audit-level=high` trong CI (fail = chặn merge) · OSV-Scanner (SARIF, hằng tuần + khi đổi lockfile) · **CodeQL** (free vì repo public) · **SonarCloud** (quality gate trên PR) · Snyk (GitHub app).
|
||||
- Mỗi PR Dependabot: đọc changelog trước khi merge major; patch/minor merge khi CI xanh (08 §6). Khi `main` dính advisory mới, mọi PR đỏ ở bước audit ⇒ vá gộp một PR rồi đóng các PR bị thay thế.
|
||||
- **Quét** (từ 2026-11-24): Renovate tự host (chỉ đề xuất bản đã phát hành **≥ 3 ngày** — chặn kiểu Shai-Hulud; cảnh báo OSV mở PR nhãn `security` ngay, không chờ) · `npm audit --omit=dev --audit-level=high` trong CI (fail = chặn merge) · **`security.yml`** (reusable của repo ops: gitleaks trên toàn bộ lịch sử, Opengrep luật JS/TS, osv-scanner trên `package-lock.json`; PR, push `main`, thứ Tư hằng tuần; SARIF là artifact vì Gitea không có code scanning) · **Qodana** (ngưỡng 0, tư vấn). Đến 2026-11-23: Dependabot (alerts + security updates, cooldown 3 ngày), OSV-Scanner (SARIF), CodeQL, SonarCloud (quality gate trên PR), Snyk (GitHub app).
|
||||
- Mỗi PR Renovate: đọc changelog trước khi merge major; patch/minor merge khi CI xanh (08 §6). Khi `main` dính advisory mới, mọi PR đỏ ở bước audit ⇒ vá gộp một PR rồi đóng các PR bị thay thế.
|
||||
|
||||
## 7. security.txt (`public/.well-known/security.txt`)
|
||||
|
||||
@@ -111,7 +112,7 @@ Contact: mailto:contact@poli0981.dev
|
||||
Expires: 2027-07-01T00:00:00Z
|
||||
Preferred-Languages: vi, en
|
||||
Canonical: https://poli0981.dev/.well-known/security.txt
|
||||
Policy: https://github.com/poli0981/poli0981-dev/blob/main/SECURITY.md
|
||||
Policy: https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/SECURITY.md
|
||||
```
|
||||
|
||||
## 8. Checklist hardening
|
||||
@@ -142,7 +143,7 @@ admin.poli0981.dev ─▶ Cloudflare Access (policy email) ─▶ Worker
|
||||
- **Vì sao host riêng**: cùng origin thì một lỗi XSS ở trang công khai có thể gọi API admin bằng cookie Access. Khác origin + kiểm `Sec-Fetch-Site` ⇒ không.
|
||||
- **Ba lớp**: Access chặn ở edge; Worker tự kiểm JWT (preview URL/workers.dev đều tắt, header giả ⇒ 403 — smoke test kiểm cả JWT giả); `ADMIN_EMAILS` quyết định ai được thao tác — policy Access lỡ mở rộng cũng không mở admin.
|
||||
- **Khuyến nghị cấu hình Access** (dashboard, `07` §13b): bắt buộc MFA ở IdP/Access, session duration ≤ 24 giờ (khớp `maxTokenAge`), bật *binding cookie*, cookie `SameSite=Lax` trở lên.
|
||||
- **Hai token GitHub** (fine-grained — quyền của một token áp cho *mọi* repo nó được chọn, nên không thể "ghi repo này, chỉ dispatch repo kia" bằng một token): `GITHUB_CONTENT_TOKEN` (chỉ `poli0981/content`, Contents R/W) và `GITHUB_PUBLISH_TOKEN` (chỉ `poli0981/poli0981-dev`, Actions R/W — không có Contents ⇒ lộ cũng không đẩy được code). Đọc trạng thái (PR, check, gitlink) không cần quyền vì hai repo đều public. Thiếu quyền ⇒ admin báo rõ token nào cần quyền gì (header `X-Accepted-GitHub-Permissions`). Xuất bản đi qua `content-bump.yml` (GITHUB_TOKEN) + CI `build` bắt buộc; diff có file ngoài `.md/.json` (vd. `.mdx` — chạy code lúc build) ⇒ không auto-merge.
|
||||
- **Một token Gitea** (`GITEA_BOT_TOKEN`, từ 2026-11-24; `src/lib/admin/gitea.ts`): token `write:repository` của user bot `poli0981-bot`, collaborator Write chỉ trên `poli0981/content` và `poli0981/poli0981-dev`. Scope của token Gitea áp cho mọi repo mà user đó với tới, nên giới hạn nằm ở danh sách collaborator của bot, không ở token. Bot không đẩy code vào repo site — ở đó nó chỉ dispatch `content-bump.yml`, và `main` chỉ chủ repo push được (branch protection, `08` §0). Lưu bài = API change-files của Gitea (`POST /repos/{o}/{r}/contents`, sha của từng file là khoá lạc quan ⇒ sửa song song thì admin báo xung đột 409); danh sách = head nhánh + cây đệ quy + `POST …/file-contents` theo lô 50 file. Trạng thái xuất bản = PR `content/bump` đang mở, commit status `CI / build (…)` của nó, marker `<!-- publish: auto -->` / `<!-- publish: review -->` trong thân PR, run `content-bump.yml` gần nhất. Xuất bản đi qua `content-bump.yml` (job token) + CI `build` bắt buộc; diff có file ngoài `.md/.json` (vd. `.mdx` — chạy code lúc build) ⇒ marker review, không tự merge. (Đến 2026-11-23: **hai token GitHub** fine-grained — quyền của một PAT áp cho *mọi* repo nó được chọn — `GITHUB_CONTENT_TOKEN` chỉ `poli0981/content` Contents R/W và `GITHUB_PUBLISH_TOKEN` chỉ `poli0981/poli0981-dev` Actions R/W; thiếu token thứ hai thì admin cảnh báo "một token". Cảnh báo đó đã bỏ.)
|
||||
- **Audit log**: mỗi thao tác (lưu/xoá nội dung, upload/sửa alt/xoá ảnh, lưu/xoá album, xuất bản, chặn/bỏ chặn IP) ghi một khoá KV `audit:*` (90 ngày) kèm email, đích và commit — xem ở `/admin/activity/` cạnh lịch sử commit của repo content.
|
||||
- **Upload ảnh**: kiểm magic bytes (không SVG), ≤ 20 MB, id = SHA-256 ⇒ trùng thì không biến đổi lại; biến thể + master tái mã hoá (mất EXIF/GPS), không giữ file gốc; `/media` chỉ phục vụ key biến thể, `CSP: sandbox`. Không xoá được ảnh còn được nội dung dùng.
|
||||
- **Preview Markdown** render trong `<iframe sandbox="allow-same-origin" srcdoc>`: không `allow-scripts` nên không gì trong Markdown chạy được (kể cả `onerror`), không điều hướng được trang admin; frame kế thừa CSP của trang. Không cần thư viện sanitize.
|
||||
@@ -151,7 +152,7 @@ admin.poli0981.dev ─▶ Cloudflare Access (policy email) ─▶ Worker
|
||||
|
||||
## 10. Log & giới hạn vận hành
|
||||
|
||||
- **Log có cấu trúc** (`src/lib/log.ts`): một dòng JSON mỗi sự kiện — `level`, `event` (vd. `gate.failed`, `denylist.blocked`, `admin.access_denied`, `admin.content_saved`, `ratelimit.exceeded`, `report.github_failed`, `widgets.source_failed`), `ray`, `method`, `path`, lỗi đã serialize. Workers Logs (`observability.logs`, giữ 7 ngày, query string bị che) tự index các field; traces lấy mẫu 10%. Không log IP vào issue/Discord.
|
||||
- **Log có cấu trúc** (`src/lib/log.ts`): một dòng JSON mỗi sự kiện — `level`, `event` (vd. `gate.failed`, `denylist.blocked`, `admin.access_denied`, `admin.content_saved`, `ratelimit.exceeded`, `report.gitlab_failed` (trước 2026-11-24: `report.github_failed`), `widgets.source_failed`), `ray`, `method`, `path`, lỗi đã serialize. Workers Logs (`observability.logs`, giữ 7 ngày, query string bị che) tự index các field; traces lấy mẫu 10%. Không log IP vào issue/Discord.
|
||||
- **Phiên bản đang chạy**: binding `version_metadata` + commit build (`__BUILD_COMMIT__`) ⇒ `/api/health`, dashboard admin và log lỗi edge đều nói đúng bản nào đang phục vụ.
|
||||
- **Trang 500** hiện Cloudflare Ray ID (worker đóng dấu vào `#ref`) — trùng field `ray` trong log, người dùng đọc/gửi kèm báo lỗi là tra được ngay.
|
||||
- **Timeout**: mọi `fetch` ra GitHub/Discord/YouTube/Steam có `AbortSignal.timeout` (10–15 s) — một API treo không giữ request hay isolate.
|
||||
- **Timeout**: mọi `fetch` ra Gitea/GitLab/Discord/YouTube/Steam có `AbortSignal.timeout` (10–15 s) — một API treo không giữ request hay isolate.
|
||||
@@ -75,7 +75,8 @@ Rule ghi đè header cho **mọi** request (client không giả được). Worke
|
||||
|
||||
## 9. Deploy Worker & custom domain
|
||||
|
||||
- **Workers Builds** (dashboard → worker `poli0981-dev` → Settings → Build), nối repo `poli0981/poli0981-dev`:
|
||||
- **Deploy từ Gitea CI** (từ 2026-11-24): job `deploy` trong `.gitea/workflows/ci.yml` chạy sau `build` khi push `main` (hoặc `workflow_dispatch` trên `main`) — `npm ci --ignore-scripts` → `npm run build` với `PUBLIC_TURNSTILE_SITE_KEY=<site key>` + `PUBLIC_CF_BEACON=true` (thay biến build của Workers Builds) → `npx wrangler deploy --message "main <sha7>"` với secret Actions cấp user `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` (§10) → chờ tới khi `https://poli0981.dev/api/health` trả `version.commit` = commit vừa build (job đỏ nếu sau ~2 phút vẫn chưa). Push chỉ đổi docs (`poli0981.dev-docs/**`, `*.md`, `LICENSE`) không deploy. PR và nhánh khác **không** có version preview nữa (Gitea đưa secret cho PR cùng repo, nên token Cloudflare không được tới gần code của PR). Runner nằm trên PC của chủ repo: merge lúc PC tắt ⇒ deploy khi runner lên lại. Chi tiết workflow: `08` §0.
|
||||
- **Workers Builds** (đến 2026-11-23 — dùng từ 10/2026, đã ngắt vì nó kéo code từ GitHub; giữ để tra lịch sử) (dashboard → worker `poli0981-dev` → Settings → Build), nối repo `poli0981/poli0981-dev`:
|
||||
|
||||
| Mục | Giá trị |
|
||||
|---|---|
|
||||
@@ -86,14 +87,14 @@ Rule ghi đè header cho **mọi** request (client không giả được). Worke
|
||||
| Build variables | `NODE_VERSION=26`, `PUBLIC_TURNSTILE_SITE_KEY=<site key>` |
|
||||
| Build cache | bật |
|
||||
|
||||
Bẫy đã gặp (19/10/2026): Deploy command của nhánh PR từng là `wrangler deploy` ⇒ mỗi PR (cả Dependabot) được đưa lên production 100%. Ngược lại, nếu Deploy command của `main` là `versions upload` thì merge **không** deploy — khi đó promote tay: `npx wrangler versions list` → `npx wrangler versions deploy <id>@100% --yes --message "main <sha>"`. Xác minh sau mỗi merge: `curl https://poli0981.dev/api/health` phải trả đúng `version.commit` (và `version.content` = commit repo nội dung đã publish). Từ v2.3.0 admin tự xuất bản sau mỗi lần lưu ⇒ Deploy command của `main` **phải** là `npx wrangler deploy`, nếu không mọi lần lưu dừng ở pha "đã merge — đang deploy" (đã xảy ra từ 10/2026 tới 11/2026: mọi deploy trong thời gian đó là promote tay).
|
||||
- Local (khẩn cấp): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login).
|
||||
Bẫy đã gặp (19/10/2026): Deploy command của nhánh PR từng là `wrangler deploy` ⇒ mỗi PR (cả Dependabot) được đưa lên production 100%. Ngược lại, nếu Deploy command của `main` là `versions upload` thì merge **không** deploy — khi đó promote tay: `npx wrangler versions list` → `npx wrangler versions deploy <id>@100% --yes --message "main <sha>"`. Xác minh sau mỗi merge: `curl https://poli0981.dev/api/health` phải trả đúng `version.commit` (và `version.content` = commit repo nội dung đã publish). Từ v2.3.0 admin tự xuất bản sau mỗi lần lưu ⇒ Deploy command của `main` **phải** là `npx wrangler deploy`, nếu không mọi lần lưu dừng ở pha "đã merge — đang deploy" (đã xảy ra từ 10/2026 tới 11/2026: mọi deploy trong thời gian đó là promote tay). **Đã sửa ngày 21/11/2026** (Deploy command = `npx wrangler deploy`, Version command = `npx wrangler versions upload`); deployment do Workers Builds tạo hiện trong `npx wrangler deployments list` ngay sau khi build `main` xong, không cần promote. Từ 2026-11-24 Workers Builds đã ngắt khỏi repo, thay bằng job `deploy` ở trên.
|
||||
- Local (khẩn cấp, vd. job `deploy` không chạy được): `npm run build && npx wrangler deploy` (lần đầu wrangler mở OAuth login). Build local không đặt `PUBLIC_TURNSTILE_SITE_KEY`/`PUBLIC_CF_BEACON` thì cổng và beacon khác bản CI — đặt hai biến này như job `deploy` trước khi build.
|
||||
- Gắn domain: Workers & Pages → worker `poli0981-dev` → Settings → **Domains & Routes → Add → Custom domain** → `poli0981.dev` (tự tạo DNS + cert). `www.poli0981.dev` là custom domain thứ hai; worker entry redirect 301 về apex.
|
||||
- Worker widgets (không nối Workers Builds): `npx wrangler deploy --config workers/widgets/wrangler.jsonc` → kiểm tra Triggers có cron.
|
||||
- Worker widgets (không nằm trong job `deploy`, trước đây cũng không nối Workers Builds): deploy tay `npx wrangler deploy --config workers/widgets/wrangler.jsonc` → kiểm tra Triggers có cron.
|
||||
|
||||
## 10. API token cho CI (least privilege)
|
||||
|
||||
Workers Builds tự có quyền deploy nên GitHub Actions **không** cần token Cloudflare. Chỉ tạo khi muốn deploy từ máy khác/CI riêng: My Profile → API Tokens → Create Token → Custom → **Account → Workers Scripts → Edit** (+ Workers KV Storage → Edit nếu cần seed KV), đúng account, TTL ≤ 1 năm.
|
||||
Từ 2026-11-24 job `deploy` của Gitea CI cần token Cloudflare: My Profile → API Tokens → Create Token → Custom → **Account → Workers Scripts → Edit**, cộng những gì binding cần để resolve (KV, R2, routes và custom domain trên zone), đúng account, TTL ≤ 1 năm. Lưu thành **secret Actions cấp user** trên Gitea (dùng chung cho các repo web): `CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID`. (Đến 2026-11-23 Workers Builds tự có quyền deploy nên GitHub Actions không cần token Cloudflare.)
|
||||
|
||||
## 11. Email (Google Workspace)
|
||||
|
||||
@@ -117,7 +118,7 @@ Mail của domain chạy trên **Google Workspace** (MX → `aspmx.l.google.com`
|
||||
Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở chế độ **JS snippet (manual)** — *tắt* tự động chèn, nếu không mỗi trang sẽ có 2 beacon (và beacon tự chèn là script inline mà CSP chặn).
|
||||
|
||||
- Snippet nằm ở `src/components/CfBeacon.astro` (token là site tag công khai, không phải secret), chèn vào `<head>` của `BaseLayout` + `ErrorLayout`.
|
||||
- Chỉ render khi build trên Workers Builds nhánh `main` (`WORKERS_CI=1` + `WORKERS_CI_BRANCH=main` → `PUBLIC_CF_BEACON`), nên CI/Lighthouse/preview không làm bẩn số liệu. Ép bật/tắt: biến build `PUBLIC_CF_BEACON=true|false`.
|
||||
- Chỉ render trong bản build production: job `deploy` của Gitea CI đặt `PUBLIC_CF_BEACON=true` (đến 2026-11-23: build trên Workers Builds nhánh `main`, `WORKERS_CI=1` + `WORKERS_CI_BRANCH=main` → `PUBLIC_CF_BEACON` — `astro.config.mjs` vẫn nhận điều kiện này), nên job `build`/Lighthouse/local không làm bẩn số liệu. Ép bật/tắt: biến build `PUBLIC_CF_BEACON=true|false`.
|
||||
- CSP: `script-src https://static.cloudflareinsights.com`, `connect-src https://cloudflareinsights.com`.
|
||||
- Không cookie, khớp Privacy Policy §2.
|
||||
|
||||
@@ -125,14 +126,13 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
|
||||
|
||||
1. Workers → `poli0981-dev` → Domains & Routes → **Custom domain** `admin.poli0981.dev` (cùng Worker).
|
||||
2. Zero Trust → Access → Applications → **Self-hosted**, domain `admin.poli0981.dev` (cả host), policy Allow theo email chủ site (IdP Google hoặc One-time PIN). Lấy **team domain** + **AUD tag** → `vars.ACCESS_TEAM_DOMAIN` / `vars.ACCESS_AUD` trong `wrangler.jsonc` (không phải secret).
|
||||
3. Hai GitHub **fine-grained** PAT (hạn ≤ 1 năm; Settings → Developer settings → Fine-grained tokens):
|
||||
- *Content*: Repository access = **Only select repositories → `poli0981/content`**; Repository permissions → **Contents: Read and write** → `npx wrangler secret put GITHUB_CONTENT_TOKEN`.
|
||||
- *Publish*: Repository access = **Only select repositories → `poli0981/poli0981-dev`**; Repository permissions → **Actions: Read and write** → `npx wrangler secret put GITHUB_PUBLISH_TOKEN`.
|
||||
- Sửa quyền của token có sẵn không đổi giá trị token ⇒ không cần đặt lại secret.
|
||||
3. Token cho admin (từ 2026-11-24 — Gitea; `06` §9):
|
||||
- *Bot Gitea*: user `poli0981-bot` trên `git.poli0981.dev`, thêm làm collaborator **Write** chỉ trên `poli0981/content` và `poli0981/poli0981-dev`; tạo token scope **`write:repository`** cho user đó → `npx wrangler secret put GITEA_BOT_TOKEN`. Scope token áp cho mọi repo bot với tới ⇒ đừng thêm bot vào repo khác.
|
||||
- **`ADMIN_EMAILS` (bắt buộc)** = email được vào admin, phân cách dấu phẩy: `printf '%s' "you@example.com" | npx wrangler secret put ADMIN_EMAILS`. Thiếu secret này admin từ chối mọi người (fail-closed). Đặt khi version mới nhất là bản `main` (`06` §4).
|
||||
- Báo lỗi: thêm repo private `poli0981/site-reports` vào `GITHUB_ISSUES_TOKEN` (Issues: Read and write).
|
||||
- Báo lỗi: token GitLab role **Reporter** trên project mirror `poli0981/poli0981-dev` (gitlab.com), scope `api` → `npx wrangler secret put GITLAB_ISSUES_TOKEN`; var `REPORT_PROJECT` trong `wrangler.jsonc` (`10` §4).
|
||||
- Đến 2026-11-23 (GitHub): hai fine-grained PAT — `GITHUB_CONTENT_TOKEN` (chỉ `poli0981/content`, Contents R/W) và `GITHUB_PUBLISH_TOKEN` (chỉ `poli0981/poli0981-dev`, Actions R/W) — và repo private `poli0981/site-reports` trong `GITHUB_ISSUES_TOKEN` (Issues R/W). Ba secret này không còn dùng — gỡ bằng `npx wrangler secret delete <tên>` để `wrangler secret list` khớp `06` §4.
|
||||
3b. Siết Access (application `admin.poli0981.dev` → Settings): **Session duration ≤ 24h** (Worker cũng từ chối token > 24 giờ), policy yêu cầu **MFA** (IdP có 2FA hoặc rule Access), bật **Binding cookie**, cookie `SameSite=Lax` hoặc `Strict`, `HttpOnly`.
|
||||
4. Repo `poli0981-dev` → Settings → Actions → General → bật **Allow GitHub Actions to create and approve pull requests** (cho `content-bump.yml`); quyền mặc định của GITHUB_TOKEN giữ **read**.
|
||||
4. Repo `poli0981-dev` (Gitea): `content-bump.yml` và job `publish` của `ci.yml` khai quyền của job token ngay trong workflow (`contents`/`pull-requests`/`actions: write`). (Đến 2026-11-23 trên GitHub: Settings → Actions → General → bật **Allow GitHub Actions to create and approve pull requests**, quyền mặc định của GITHUB_TOKEN giữ **read**.)
|
||||
5. R2 `poli0981-media` (`wrangler r2 bucket create poli0981-media --location apac`), không bật public URL. Images binding không cần bật gì thêm (gói Free: 5.000 biến đổi/tháng).
|
||||
|
||||
## 14. Observability
|
||||
@@ -154,5 +154,5 @@ Account → Analytics & Logs → **Web Analytics** → site `poli0981.dev` ở c
|
||||
- [ ] Search Console (URL Inspection → Test live URL) thấy trang thật; Facebook Sharing Debugger đúng title/ảnh
|
||||
- [ ] `https://admin.poli0981.dev/` → đăng nhập Access → thấy admin; `curl -H 'cf-access-jwt-assertion: x' …/api/admin/content` (qua host chính) → 404/403
|
||||
- [ ] `ADMIN_EMAILS` đã đặt; Access session ≤ 24h + MFA + binding cookie
|
||||
- [ ] Workers Builds: Deploy command `main` = `npx wrangler deploy`, nhánh khác = `npx wrangler versions upload`; sau merge `/api/health` trả đúng commit
|
||||
- [ ] Deploy (từ 2026-11-24): job `deploy` của Gitea CI xanh sau merge `main`, `/api/health` trả đúng commit; Workers Builds đã ngắt (không còn build nào kéo từ GitHub). (Đến 2026-11-23: Workers Builds — Deploy command `main` = `npx wrangler deploy`, nhánh khác = `npx wrangler versions upload`.)
|
||||
- [ ] Auto-renew ON + transfer lock ON + 2FA ON
|
||||
@@ -1,17 +1,36 @@
|
||||
# 08 — CI/CD
|
||||
|
||||
## 0. Thực tế đang chạy (10/2026, v2.0) — §1–§5 bên dưới là kế hoạch ban đầu (lịch sử)
|
||||
## 0. Forge & CI (Gitea, từ 2026-11-24)
|
||||
|
||||
- **Deploy**: Cloudflare **Workers Builds** nối repo (không có job deploy trong GitHub Actions): `main` → build + `npx wrangler deploy`; nhánh khác → `npx wrangler versions upload` (version preview, không nhận traffic). Cấu hình chi tiết + bẫy đã gặp: `07` §9.
|
||||
- **`ci.yml`** (PR, push `main`, `workflow_dispatch`), job **`build`** (timeout 30 phút, checkout kèm submodule):
|
||||
`npm ci --ignore-scripts` → `check-install-scripts` → `wrangler types` (site + widgets) → prettier → eslint → `astro check` (TS 6) → **`typecheck` bằng TypeScript 7** (in `tsc -v`, kiểm site + widgets) → knip → **`test:coverage`** (`node:test`, ngưỡng 80% dòng, xuất `coverage/lcov.info`) → `npm audit --omit=dev --audit-level=high` → `gen-notices --check` → `check-exif --changed` → build (+ OG, Pagefind, `check-csp-hashes`) → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/`/ext-img`/admin 403/`frame-ancestors`, pha ép bật cổng Turnstile kể cả cookie sai định dạng, pha denylist) → **cổng trợ năng** (từ v2.2.0: `npm run preview` chạy nền rồi `npm run test:a11y` — Playwright lái Chrome có sẵn trên runner, không tải trình duyệt; axe-core quét mọi trang trong sitemap của bản build, một trang mỗi template ở theme sáng và bề rộng điện thoại, và menu/tìm kiếm/lightbox/hộp báo lỗi/bảng Aa/bảng pháp lý khi đang mở; sau đó là test bàn phím, reflow 320/360/390px và `forced-colors`) → upload coverage làm artifact. Check `build` là **bắt buộc** (ruleset `main`), nên PR có vi phạm axe không merge được.
|
||||
- Job **`sonarcloud`** (sau `build`; chạy cho push `main` và PR cùng repo, bỏ qua Dependabot): tải coverage → `SonarSource/sonarqube-scan-action` (pin SHA) với `sonar-project.properties`; trên PR chờ **quality gate** ("Sonar way" cho new code: coverage ≥ 80%, trùng lặp ≤ 3%, rating A, hotspot đã review). Automatic analysis trên SonarCloud **tắt** (CI analysis thay thế); `SONAR_TOKEN` là secret của repo. `.svelte`/`.astro` không được Sonar phân tích — logic quan trọng nằm trong `.ts` để đo được.
|
||||
- **CodeQL** (default setup, repo public) · **Snyk** (GitHub app) · **`osv-scanner.yml`** (reusable workflow v2.7.0, SARIF, hằng tuần + khi đổi lockfile) · **`lighthouse.yml`** (`treosh/lighthouse-ci-action` pin SHA, preset mobile, chỉ cảnh báo).
|
||||
- **`content-bump.yml`** (từ v2.3.0 admin tự gọi sau **mỗi lần lưu/xoá**; nút **Xuất bản** còn lại để chạy lại; `concurrency` gộp các lần gọi dồn dập): trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR, auto-merge (squash) nếu diff chỉ `.md/.json`, rồi `gh workflow run ci.yml --ref content/bump` để có check `build` (PR mở bằng GITHUB_TOKEN không kích hoạt `pull_request`). Merge ⇒ Workers Builds deploy.
|
||||
- **`qodana.yml`** (từ v2.3.0, PR + push `main` + tay): Qodana for JS (gói Ultimate, token `QODANA_TOKEN`), native mode trên Node 26 của runner sau `npm ci` + sinh types, profile `qodana.recommended` quét cả repo, `failThreshold: 0` (`qodana.yaml` ghi các inspection tắt kèm lý do); kết quả lên Qodana Cloud và — với `main` — SARIF vào Code scanning. Bỏ qua PR Dependabot/fork (không có secret) nên chỉ là check tư vấn. Không phân tích `.astro`/`.svelte`.
|
||||
- **Repo**: bản gốc ở `https://git.poli0981.dev/poli0981/poli0981-dev` (Gitea 28.4.0 tự host); submodule `src/content` = `https://git.poli0981.dev/poli0981/content` (`.gitmodules`). Bản sao công khai `https://gitlab.com/poli0981/poli0981-dev` (push mirror từ Gitea; GitLab CI không chạy ở đó) là nơi người ngoài mở issue và merge request — Gitea không cho người ngoài đăng ký. Patch/câu hỏi: `code@poli0981.dev`; bảo mật: chỉ qua `security@poli0981.dev`, không bao giờ mở issue công khai trên mirror. Tài khoản GitHub `poli0981` không còn. Runbook chuyển nhà: repo `poli0981/.github`, `docs/GITEA-MIGRATION.md` (+ `docs/migration/poli0981-dev.md`).
|
||||
- **Runner**: một Gitea runner trên PC Windows của chủ repo; job `ubuntu-latest` chạy trong Docker (`docker.gitea.com/runner-images`, user root, **không có Chrome, không có nginx**: CI tự cài Chromium của Playwright cho test a11y và Lighthouse, Lighthouse tự cài nginx). Job chỉ chạy khi PC bật; job theo lịch chỉ đặt trong khung **13:00–16:00 UTC (20:00–23:00 giờ VN)**; run chờ quá 24 giờ không ai nhận thì bị huỷ.
|
||||
- **Workflows** (`.gitea/workflows/`; mọi action pin theo SHA, Renovate giữ pin mới; artifact qua `christopherhx/gitea-upload-artifact` — Gitea không có giao diện code scanning nên SARIF/report là artifact):
|
||||
|
||||
| Workflow | Khi chạy | Việc |
|
||||
|---|---|---|
|
||||
| `ci.yml` | PR · push `main` (bỏ qua thay đổi chỉ ở `poli0981.dev-docs/**`, `*.md`, `LICENSE`) · `workflow_dispatch` | `build` (check bắt buộc duy nhất, các bước ở §0b) → `deploy` (push/dispatch trên `main`) · `publish` (dispatch trên `content/bump`, xuất bản nội dung) |
|
||||
| `content-bump.yml` | `workflow_dispatch` (admin gọi bằng token bot) | bump submodule lên nhánh `content/bump`, mở/cập nhật PR qua API Gitea, dispatch `ci.yml` trên `content/bump` (§0b) |
|
||||
| `security.yml` | PR · push `main` · thứ Tư 14:13 UTC (21:13 VN) · tay | gọi reusable `security.yml` của repo ops (pin commit `2a255e0e…` = ops v2026.11.1): gitleaks trên toàn bộ lịch sử, Opengrep (luật JS/TS), osv-scanner trên `package-lock.json` |
|
||||
| `qodana.yml` | PR · push `main` (bỏ qua docs) · tay | Qodana CLI 2026.3.1, native mode; report = artifact `qodana-report` + Qodana Cloud; tư vấn, không bắt buộc |
|
||||
| `lighthouse.yml` | PR (bỏ qua docs) · tay | ngân sách hiệu năng, chỉ cảnh báo; report = artifact `lighthouse-reports` |
|
||||
|
||||
- **Deploy**: Workers Builds (kéo code từ GitHub) đã ngắt. Job `deploy` của `ci.yml` chạy sau `build` khi push `main` (hoặc dispatch trên `main`): build lại với `PUBLIC_TURNSTILE_SITE_KEY` + `PUBLIC_CF_BEACON=true` → `npx wrangler deploy --message "main <sha7>"` (secret Actions cấp user trên Gitea: `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`) → chờ tới khi `https://poli0981.dev/api/health` báo đúng commit. Push chỉ đổi docs không deploy (paths-ignore). **Không còn bản preview cho PR** (token Cloudflare không bao giờ tới gần code của PR). Merge lúc PC tắt ⇒ deploy khi runner lên lại. Worker widgets vẫn deploy tay (`07` §9).
|
||||
- **Check bắt buộc**: branch protection `main` trên Gitea — status check pattern `CI / build (*)` (Gitea đặt tên check là `<workflow> / <job> (<event>)`), cấm force push, cấm xoá nhánh, chỉ chủ repo được push, không yêu cầu approval.
|
||||
- **Dependency**: Renovate tự host thay Dependabot (§6). Secret Actions: `QODANA_TOKEN` + hai secret Cloudflare ở trên; secret của Worker không đi qua Actions (`06` §4).
|
||||
- **Bỏ khi chuyển (2026-11-24)**: SonarQube Cloud (job, `sonar-project.properties`, `SONAR_TOKEN` — Qodana + Opengrep thay), CodeQL/Snyk và upload SARIF vào code scanning, `osv-scanner.yml` (→ `security.yml`), `triage.yml` + `scripts/triage.mjs` (§8), Dependabot, Workers Builds.
|
||||
|
||||
## 0b. Chi tiết từng workflow (từ 10/2026, v2.0; cập nhật cho Gitea 2026-11-24) — §1–§5 bên dưới là kế hoạch ban đầu (lịch sử)
|
||||
|
||||
- **Deploy** (đến 2026-11-23; nay: job `deploy`, §0): Cloudflare **Workers Builds** nối repo (không có job deploy trong GitHub Actions): `main` → build + `npx wrangler deploy`; nhánh khác → `npx wrangler versions upload` (version preview, không nhận traffic). Cấu hình chi tiết + bẫy đã gặp: `07` §9.
|
||||
- **`ci.yml`** (PR, push `main` trừ thay đổi chỉ ở docs, `workflow_dispatch`), job **`build`** (timeout 30 phút, checkout kèm submodule):
|
||||
`npm ci --ignore-scripts` → `check-install-scripts` → `wrangler types` (site + widgets) → prettier → eslint → `astro check` (TS 6) → **`typecheck` bằng TypeScript 7** (in `tsc -v`, kiểm site + widgets) → knip → **`test:coverage`** (`node:test`, ngưỡng 80% dòng, xuất `coverage/lcov.info`) → `npm audit --omit=dev --audit-level=high` → `gen-notices --check` → `check-exif --changed` → build (+ OG, Pagefind, `check-csp-hashes`) → **smoke test** (`npm run smoke`: chạy worker đã build bằng `wrangler dev`, kiểm trang/304/HEAD/`/media`/`/ext-img`/admin 403/`frame-ancestors`, pha ép bật cổng Turnstile kể cả cookie sai định dạng, pha denylist) → **cổng trợ năng** (từ v2.2.0: `npm run preview` chạy nền rồi `npm run test:a11y` — Playwright lái Chrome có sẵn nếu image có; image của Gitea runner không có nên CI cài Chromium của Playwright đúng bản trong lockfile, cache theo phiên bản, `A11Y_CHANNEL=bundled` (trên runner GitHub đến 2026-11-23: dùng Chrome có sẵn, không tải trình duyệt); axe-core quét mọi trang trong sitemap của bản build, một trang mỗi template ở theme sáng và bề rộng điện thoại, và menu/tìm kiếm/lightbox/hộp báo lỗi/bảng Aa/bảng pháp lý khi đang mở; sau đó là test bàn phím, reflow 320/360/390px và `forced-colors`). Bước upload coverage làm artifact (cho Sonar) bỏ ngày 2026-11-24. Check `build` là **bắt buộc** (branch protection `main`, §0), nên PR có vi phạm axe không merge được.
|
||||
- Job **`sonarcloud`** (đến 2026-11-23; đã bỏ khi chuyển sang Gitea — Qodana + Opengrep thay) (sau `build`; chạy cho push `main` và PR cùng repo, bỏ qua Dependabot): tải coverage → `SonarSource/sonarqube-scan-action` (pin SHA) với `sonar-project.properties`; trên PR chờ **quality gate** ("Sonar way" cho new code: coverage ≥ 80%, trùng lặp ≤ 3%, rating A, hotspot đã review). Automatic analysis trên SonarCloud **tắt** (CI analysis thay thế); `SONAR_TOKEN` là secret của repo. `.svelte`/`.astro` không được Sonar phân tích — logic quan trọng nằm trong `.ts` để đo được.
|
||||
- **CodeQL** (default setup, repo public) · **Snyk** (GitHub app) · **`osv-scanner.yml`** (reusable workflow v2.7.0, SARIF, hằng tuần + khi đổi lockfile) — cả ba đến 2026-11-23; nay: `security.yml` (§0). **`lighthouse.yml`** (`treosh/lighthouse-ci-action` pin SHA, preset mobile, chỉ cảnh báo; trên Gitea: Chromium của Playwright qua `CHROME_PATH`, nginx tự cài, report là artifact `lighthouse-reports` vì upload của action chỉ chạy với GitHub).
|
||||
- **`content-bump.yml`** (từ v2.3.0 admin tự gọi sau **mỗi lần lưu/xoá**; nút **Xuất bản** còn lại để chạy lại; `concurrency` gộp các lần gọi dồn dập, không huỷ run đang chạy): admin dispatch bằng `GITEA_BOT_TOKEN` → trỏ submodule `src/content` về `content/main`, commit lên nhánh `content/bump`, mở/cập nhật PR qua API Gitea (job token), ghi vào thân PR marker `<!-- publish: auto -->` (diff chỉ `.md/.json`) hoặc `<!-- publish: review -->` (API Gitea không có trường auto-merge), rồi dispatch `ci.yml` trên `content/bump` (PR mở bằng job token không kích hoạt workflow nào). **Gitea 28.4 không ghi commit status cho run `workflow_dispatch`** (chỉ push/pull_request) ⇒ commit bump không có `CI / build (*)` mà branch protection đòi, merge bị từ chối 405 — lần xuất bản đầu tiên 2026-11-24 dính đúng lỗi này. Vì vậy job **`publish`** của `ci.yml` (`needs: build`, `if: always()`, chỉ khi dispatch trên `content/bump`) tự ghi status `CI / build (workflow_dispatch)` = kết quả của `build` (kèm link run), rồi nếu build xanh và PR mang marker auto thì squash-merge và dispatch `ci.yml` trên `main` ⇒ job `deploy`; build đỏ ⇒ status failure ⇒ admin hiện "xuất bản lỗi". MDX chờ review; merge tay cũng deploy. Script chung: `scripts/content-publish.mjs`. (Trên GitHub đến 2026-11-23: `gh pr merge --auto --squash`, `gh workflow run ci.yml --ref content/bump`, merge ⇒ Workers Builds deploy.)
|
||||
- **`qodana.yml`** (từ v2.3.0, PR + push `main` + tay): Qodana for JS (gói Ultimate, token `QODANA_TOKEN`), native mode sau `npm ci` + sinh types, profile `qodana.recommended` quét cả repo, `failThreshold: 0` (`qodana.yaml` ghi các inspection tắt kèm lý do). Từ 2026-11-24 chạy bằng **Qodana CLI 2026.3.1** (pin phiên bản + SHA-256, nâng tay cùng repo ops) thay `JetBrains/qodana-action`; kết quả lên Qodana Cloud và vào artifact `qodana-report` (SARIF + HTML) — SARIF vào Code scanning chỉ có thời GitHub. Bỏ qua PR Renovate (Gitea đưa secret cho PR cùng repo, mà PR Renovate cài chính bản cập nhật đang xét) và run không có token, nên chỉ là check tư vấn. Không phân tích `.astro`/`.svelte`.
|
||||
- **Kiểm license**: `gen-notices --check` (dependency trực tiếp, bảng trong `THIRD-PARTY-NOTICES.md`) + `check-licenses` (toàn bộ lockfile, ngoại lệ theo gói) trong job `build` — chính sách ở `scripts/license-policy.mjs` (`12_LEGAL/THIRD_PARTY_NOTICES.md`). Qodana license audit cần Ultimate Plus nên không dùng.
|
||||
- **`triage.yml`** (issues + `pull_request_target`; **không checkout gì** — đọc `scripts/triage.mjs` của nhánh mặc định qua API rồi import từ bộ nhớ, nên không bao giờ chạy code của PR; Sonar S7631 bắt mọi checkout trong `pull_request_target`): đề xuất tính năng ⇒ nhãn `enhancement` + `out-of-scope`, bình luận song ngữ, đóng. Chạy khô bằng `workflow_dispatch`.
|
||||
- **Bẫy đã gặp**: khi `main` dính advisory, *mọi* PR (cả Dependabot) đỏ vì bước audit ⇒ vá gộp trong một PR rồi đóng các PR Dependabot bị thay thế. `gen-notices --check` từng đếm số gói transitive ⇒ PR bump nào cũng đỏ; nay chỉ kiểm chính sách license.
|
||||
- **`triage.yml`** (đến 2026-11-23; đã bỏ cùng `scripts/triage.mjs` — xem §8) (issues + `pull_request_target`; **không checkout gì** — đọc `scripts/triage.mjs` của nhánh mặc định qua API rồi import từ bộ nhớ, nên không bao giờ chạy code của PR; Sonar S7631 bắt mọi checkout trong `pull_request_target`): đề xuất tính năng ⇒ nhãn `enhancement` + `out-of-scope`, bình luận song ngữ, đóng. Chạy khô bằng `workflow_dispatch`.
|
||||
- **Bẫy đã gặp**: khi `main` dính advisory, *mọi* PR (cả Dependabot — nay Renovate) đỏ vì bước audit ⇒ vá gộp trong một PR rồi đóng các PR dependency bị thay thế. `gen-notices --check` từng đếm số gói transitive ⇒ PR bump nào cũng đỏ; nay chỉ kiểm chính sách license.
|
||||
|
||||
## 1. Nguyên tắc
|
||||
|
||||
@@ -74,33 +93,23 @@ Secrets runtime của Worker (`TURNSTILE_SECRET`, `GITHUB_ISSUES_TOKEN`, `DISCOR
|
||||
| EXIF | `node scripts/check-exif.mjs --changed` | fail nếu ảnh có GPS |
|
||||
| Notices | `node scripts/gen-notices.mjs --check` | THIRD-PARTY-NOTICES.md lệch ⇒ fail |
|
||||
|
||||
## 6. Dependabot (`.github/dependabot.yml`)
|
||||
## 6. Renovate (`renovate.json`, từ 2026-11-24 — thay Dependabot)
|
||||
|
||||
```yaml
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: npm
|
||||
directory: "/"
|
||||
schedule: { interval: weekly, day: monday }
|
||||
cooldown: { default-days: 3 } # không đề xuất bản phát hành < 3 ngày tuổi
|
||||
open-pull-requests-limit: 8
|
||||
groups:
|
||||
astro: { patterns: ["astro", "@astrojs/*"] }
|
||||
typescript: { patterns: ["typescript", "typescript-eslint"] }
|
||||
dev-tools: { dependency-type: development }
|
||||
ignore:
|
||||
- dependency-name: typescript # giữ TS 6 cho tooling (02 §8)
|
||||
update-types: ["version-update:semver-major"]
|
||||
- dependency-name: prettier-plugin-astro # 1.x đổi khoảng trắng hiển thị — cần PR riêng
|
||||
update-types: ["version-update:semver-major"]
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule: { interval: weekly }
|
||||
```jsonc
|
||||
{
|
||||
"extends": ["local>poli0981/renovate-config"], // preset chung của mọi repo (repo ops)
|
||||
"packageRules": [
|
||||
{ "matchDepNames": ["typescript"], "matchUpdateTypes": ["major"], "enabled": false }, // giữ TS 6 cho tooling (02 §8)
|
||||
{ "matchPackageNames": ["prettier-plugin-astro"], "matchUpdateTypes": ["major"], "enabled": false } // 1.x đổi khoảng trắng hiển thị — cần PR riêng
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `workers/widgets` không có `package.json` (không deps) nên không có mục riêng.
|
||||
- `@typescript/native` (alias `npm:typescript@7`) **không** được Dependabot theo dõi — nâng tay (`17` §1).
|
||||
- Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. Security alerts: xử lý ≤ 48h (lịch ở `17`). PR bị một PR gộp thay thế ⇒ đóng kèm comment.
|
||||
- Renovate **tự host**, chạy hằng ngày 13:31 UTC (20:31 VN) từ workflow `renovate.yml` của repo `poli0981/renovate-config` (bot `renovate-bot`, collaborator Write); PC tắt thì chạy khi runner lên lại. Preset: `config:recommended` + pin digest cho action + gộp mọi cập nhật non-major vào một PR, nhãn `dependencies`, Dependency Dashboard; bản phát hành npm phải đủ **3 ngày tuổi** (giữ đúng cooldown cũ); cảnh báo OSV mở PR riêng nhãn `security`, không chờ 3 ngày.
|
||||
- `workers/widgets` không có `package.json` (không deps) nên không có mục riêng. Pin SHA của action trong `.gitea/workflows/` cũng do Renovate cập nhật; pin của reusable `security.yml` (comment `# ops …`) và phiên bản Qodana CLI thì nâng tay.
|
||||
- `@typescript/native` (alias `npm:typescript@7`) là tên dependency khác nên luật giữ `typescript` major không chặn nó — Renovate đề xuất cập nhật như thường (thời Dependabot: không được theo dõi, nâng tay).
|
||||
- Chính sách merge: patch/minor xanh CI → merge trong tuần; major → đọc upgrade guide, làm branch thử. PR bảo mật (nhãn `security`): xử lý ≤ 48h (lịch ở `17`). PR bị một PR gộp thay thế ⇒ đóng kèm comment.
|
||||
- Trước 2026-11-24: `.github/dependabot.yml` — npm hằng tuần (thứ Hai), `cooldown` 3 ngày, nhóm `astro`/`typescript`/`dev-tools`, hai mục `ignore` như trên; github-actions hằng tuần.
|
||||
|
||||
## 7. Git hooks (`lefthook.yml`)
|
||||
|
||||
@@ -119,9 +128,9 @@ Commit và tag đều ký GPG; không dùng `--no-verify`.
|
||||
|
||||
## 8. Branch & release
|
||||
|
||||
- `main` protected (ruleset): PR + check bắt buộc duy nhất là `build` (ruleset cho phép cả 3 kiểu merge; quy ước của repo là **squash**). Conventional Commits.
|
||||
- Mỗi PR: ngoài `build` còn phải xanh (theo quy ước, ruleset không ép) SonarCloud quality gate, Qodana (ngưỡng 0) và CodeQL; Workers Builds trên nhánh PR chỉ `versions upload`.
|
||||
- Chế độ bảo trì (D21): PR tính năng mới bị bot `triage.yml` đóng; mẫu PR có ô chọn 5 loại thay đổi được nhận (`CONTRIBUTING.md`).
|
||||
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + GitHub Release (notes lấy từ `CHANGELOG.md`). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026. Mỗi tag: sửa `sonar.projectVersion` trong `sonar-project.properties` cho khớp.
|
||||
- Sau merge: kiểm `https://poli0981.dev/api/health` trả đúng commit (`07` §9); nếu Workers Builds không deploy thì promote version của `main` bằng `wrangler versions deploy`.
|
||||
- `main` protected (branch protection Gitea, §0): check bắt buộc duy nhất là `build` (pattern `CI / build (*)`), cấm force push/xoá, chỉ chủ repo push, không cần approval; quy ước merge của repo là **squash**. Conventional Commits. (Đến 2026-11-23: ruleset GitHub, PR + check `build`, cho phép cả 3 kiểu merge.)
|
||||
- Mỗi PR: ngoài `build` còn phải xanh (theo quy ước, branch protection không ép) Qodana (ngưỡng 0) và `security.yml` (gitleaks, Opengrep, osv-scanner); không còn version preview cho PR. (Thời GitHub: thêm SonarCloud quality gate và CodeQL; Workers Builds trên nhánh PR chỉ `versions upload`.)
|
||||
- Chế độ bảo trì (D21): chính sách vẫn ở `CONTRIBUTING.md`; mẫu PR (`.github/pull_request_template.md`, Gitea đọc; `.gitlab/merge_request_templates/Default.md` cho mirror) có ô chọn 5 loại thay đổi được nhận. Bot `triage.yml` (đóng PR/issue tính năng mới) bỏ ngày 2026-11-24: người ngoài không mở issue/PR trên Gitea được, còn issue/MR trên GitLab không tới Gitea Actions ⇒ mục ngoài phạm vi được đóng tay trên GitLab.
|
||||
- **Release**: tag `vX.Y.Z` có ký GPG trên commit `main` đã deploy + Gitea Release (notes lấy từ `CHANGELOG.md`; đến v2.3.0 là GitHub Release). Deploy vẫn là "merge `main`" — tag chỉ đánh dấu mốc. `v2.0.0` = đợt nâng cấp 10/2026; `v2.4.0` = đợt chuyển sang Gitea. (Đến v2.3.0, mỗi tag còn sửa `sonar.projectVersion` trong `sonar-project.properties` — file đã bỏ.)
|
||||
- Sau merge: job `deploy` tự chờ `https://poli0981.dev/api/health` trả đúng commit; job đỏ hoặc chưa chạy (PC tắt) ⇒ xem log, chạy lại job, hoặc deploy tay từ máy (`07` §9). Rollback: `wrangler versions deploy` (`17` §2). (Thời Workers Builds: nếu không deploy thì promote version của `main` bằng `wrangler versions deploy`.)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 10 — Bug report pipeline (console error → GitHub Issue + Discord)
|
||||
# 10 — Bug report pipeline (console error → issue confidential trên GitLab + Discord)
|
||||
|
||||
Pipeline này là kênh báo lỗi chính cho visitor (không cần tài khoản GitHub), và cũng tiện cho chính mình. Từ 10/2026 repo site là public, nhưng báo cáo có thể chứa log/mô tả riêng tư nên issue được tạo ở repo **private** `poli0981/site-reports` (đúng lời hứa "private GitHub issue" của Privacy Policy).
|
||||
Pipeline này là kênh báo lỗi chính cho visitor (không cần tài khoản nào), và cũng tiện cho chính mình. Repo site là public, nhưng báo cáo có thể chứa log/mô tả riêng tư nên mỗi báo cáo thành một issue **confidential** (chỉ chủ repo xem được) trên mirror GitLab `https://gitlab.com/poli0981/poli0981-dev` — đúng Privacy Policy §4 (repo content, hiệu lực 2026-11-24). Từ 10/2026 đến 2026-11-23 issue được tạo ở repo **private** `poli0981/site-reports` trên GitHub ("private GitHub issue" trong bản Privacy cũ); repo đó mất cùng tài khoản GitHub.
|
||||
|
||||
## 1. Client — thu console error
|
||||
|
||||
@@ -25,17 +25,22 @@ Dialog (`<dialog>` modal có nhãn, textarea có `<label>`) gồm: textarea mô
|
||||
}
|
||||
```
|
||||
|
||||
Worker xử lý theo thứ tự: rate-limit (middleware, binding `RL_REPORT` 5/phút/client, fail 429) → thiếu secret (503) → body > 32 KB (413 — đọc stream có trần, không đọc hết) → Zod validate (fail 400) → Turnstile siteverify (`src/lib/turnstile-server.ts`: kiểm `success` **+ `action: "report"` + `hostname: poli0981.dev`**, fail 400 `turnstile_failed`) → **tạo GitHub Issue** → **Discord webhook** → 201 `{ok: true}`. Nếu GitHub API lỗi: vẫn bắn Discord (kèm full payload) và trả 202 — không mất báo cáo. Mỗi lời gọi ra ngoài có timeout 10 s; response `no-store`. Token Turnstile dùng một lần: dialog gọi `turnstile.reset()` sau mỗi lần gửi.
|
||||
Worker xử lý theo thứ tự: rate-limit (middleware, binding `RL_REPORT` 5/phút/client, fail 429) → thiếu secret (503: thiếu `TURNSTILE_SECRET`, hoặc thiếu cả `GITLAB_ISSUES_TOKEN` lẫn `DISCORD_WEBHOOK_BUG`) → body > 32 KB (413 — đọc stream có trần, không đọc hết) → Zod validate (fail 400) → Turnstile siteverify (`src/lib/turnstile-server.ts`: kiểm `success` **+ `action: "report"` + `hostname: poli0981.dev`**, fail 400 `turnstile_failed`) → **tạo issue confidential trên GitLab** → **Discord webhook** → 201 `{ok: true}` (URL issue không trả về cho người báo vì issue là confidential). Nếu GitLab API lỗi (log `report.gitlab_failed`), hoặc chưa có `GITLAB_ISSUES_TOKEN` (bỏ qua bước GitLab): vẫn bắn Discord và trả 202 `{ok: true, degraded: true}` — không mất báo cáo. Mỗi lời gọi ra ngoài có timeout 10 s; response `no-store`. Token Turnstile dùng một lần: dialog gọi `turnstile.reset()` sau mỗi lần gửi.
|
||||
|
||||
## 4. GitHub Issue
|
||||
## 4. Issue confidential trên GitLab (từ 2026-11-24)
|
||||
|
||||
`POST /repos/<REPORT_REPO>/issues` — `REPORT_REPO` là var trong `wrangler.jsonc` (mặc định `poli0981/site-reports`, private) — với `GITHUB_ISSUES_TOKEN` (fine-grained, **chỉ repo đó**, Issues R/W):
|
||||
`POST https://gitlab.com/api/v4/projects/:id/issues` — `:id` là `REPORT_PROJECT` (var trong `wrangler.jsonc`, `poli0981/poli0981-dev` = mirror công khai của repo site), đã URL-encode — với `GITLAB_ISSUES_TOKEN` (token GitLab, role **Reporter** trên project đó, scope `api`):
|
||||
- `confidential: true` — chỉ chủ project xem được, dù project public
|
||||
- title: `[web-report] <60 ký tự đầu của description>`
|
||||
- labels: `bug`, `from-site`
|
||||
- body: render đúng cấu trúc template §5 (description → meta table → console trong code block). `@mention` trong title/body bị vô hiệu (chèn zero-width) để báo cáo không ping ai; nội dung khách đưa vào code span/fence an toàn.
|
||||
- labels: `bug,from-site`
|
||||
- body: render đúng cấu trúc template §5 (description → meta → console trong code block). `@mention` trong title/body bị vô hiệu (chèn zero-width) để báo cáo không ping ai, và dòng bắt đầu bằng `/` cũng bị chèn zero-width để GitLab không chạy nó như quick action (`/close`…); nội dung khách đưa vào code span/fence an toàn.
|
||||
|
||||
Đến 2026-11-23: `POST /repos/<REPORT_REPO>/issues` của GitHub — `REPORT_REPO` = `poli0981/site-reports` (private) — với `GITHUB_ISSUES_TOKEN` (fine-grained, chỉ repo đó, Issues R/W). Repo và token đã mất cùng tài khoản GitHub.
|
||||
|
||||
## 5. Issue template dùng chung — `.github/ISSUE_TEMPLATE/bug_report.yml`
|
||||
|
||||
Gitea đọc form này, nhưng người ngoài không đăng ký được trên Gitea; họ mở issue trên mirror GitLab bằng `.gitlab/issue_templates/Bug.md` (bản Markdown của cùng form, giữ hai bản đồng bộ). Khung dưới đây là bản thiết kế ban đầu; form thật nằm trong repo.
|
||||
|
||||
```yaml
|
||||
name: Bug report
|
||||
description: Báo lỗi website (kèm console error)
|
||||
@@ -78,4 +83,4 @@ Kênh riêng `#site-reports` trong server repo. Embed: màu `--horror`, title =
|
||||
- [ ] Gửi hợp lệ → issue mở đúng template + Discord nhận embed trong < 5s
|
||||
- [ ] Turnstile token sai → 400 `turnstile_failed`; 6 lần/phút → 429 + `Retry-After`; payload 40KB → 413
|
||||
- [ ] Gửi 2 lần trong cùng một lần mở dialog → cả hai qua được (widget được reset)
|
||||
- [ ] Tắt GITHUB token (mô phỏng lỗi) → vẫn nhận Discord + client báo "đã ghi nhận"
|
||||
- [ ] GitLab API lỗi (mô phỏng: token sai/hết hạn) → vẫn nhận Discord, 202 `degraded` + client báo "đã ghi nhận"; thiếu hẳn `GITLAB_ISSUES_TOKEN` → vẫn 202 `degraded` qua Discord; thiếu cả token lẫn webhook Discord → 503, dialog chuyển sang gửi qua Discord
|
||||
@@ -10,7 +10,7 @@ API thời tiết/map phục vụ *chủ site* chứ không phục vụ *khách*
|
||||
workers/widgets (cron */45 phút, 3 nguồn chạy song song, timeout 10 s/nguồn)
|
||||
├─ YouTube RSS ─┐
|
||||
├─ Steam API ──┼─► chuẩn hoá JSON ─► KV put widgets:yt|steam|gh|status
|
||||
└─ GitHub API ──┘ └─► mirror thumbnail/icon ─► KV put widgets:img:* (≤ 2 MB, TTL 14 ngày)
|
||||
└─ feed Gitea ──┘ └─► mirror thumbnail/icon ─► KV put widgets:img:* (≤ 2 MB, TTL 14 ngày)
|
||||
Site đọc: lúc BUILD (snapshot KV cho trang tĩnh) + island refresh nhẹ gọi /api/widgets (GET, cache 5')
|
||||
Ảnh: /ext-img/yt/<id> · /ext-img/steam/<appid>/<hash> → chỉ ĐỌC KV widgets:img:* (src/lib/ext-img.ts)
|
||||
```
|
||||
@@ -23,7 +23,7 @@ Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nha
|
||||
|---|---|---|
|
||||
| Video mới (≤3) | `https://www.youtube.com/feeds/videos.xml?channel_id=<UCxxx>` | RSS công khai, **không cần API key**; parse XML lấy id/title/thumb/published |
|
||||
| Đang chơi gì | `ISteamUser…/GetRecentlyPlayedGames/v1/?key=…&steamid=…&count=3` | Cần Steam profile → Privacy → **Game details: Public**; key free tại steamcommunity.com/dev |
|
||||
| Hoạt động GitHub | `api.github.com/users/poli0981/events/public?per_page=10` | Token tuỳ chọn `GITHUB_TOKEN` (không quyền nào): không có token thì hạn mức 60 req/h tính theo IP — IP egress của Workers dùng chung nên hay bị 403 ⇒ feed `stale`. Lọc PushEvent/ReleaseEvent |
|
||||
| Hoạt động Gitea (từ 2026-11-24) | `https://git.poli0981.dev/api/v1/users/poli0981/activities/feeds?only-performed-by=true&limit=30` | Feed công khai, **không token** (chỉ liệt kê repo public; `only-performed-by` bỏ thao tác của bot). Lấy 3 mục mới nhất: `commit_repo` → push kèm số commit, `publish_release` → tag; push lặp lại không có nội dung bị bỏ qua. Lưu đúng dạng cũ (`PushEvent`/`ReleaseEvent`) nên snapshot KV từ thời GitHub vẫn hiển thị được. Đến 2026-11-23: `api.github.com/users/poli0981/events/public?per_page=10` với token tuỳ chọn `GITHUB_TOKEN` (60 req/h/IP khi không có token, IP egress của Workers dùng chung nên hay bị 403) |
|
||||
|
||||
## 4. KV schema
|
||||
|
||||
@@ -31,7 +31,7 @@ Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nha
|
||||
|---|---|---|
|
||||
| `widgets:yt` | `{updated, items:[{id,title,thumb,published}]}` | không TTL — ghi đè |
|
||||
| `widgets:steam` | `{updated, items:[{appid,name,playtime2w,icon}]}` | — |
|
||||
| `widgets:gh` | `{updated, items:[{type,repo,ts,detail}]}` | — |
|
||||
| `widgets:gh` | `{updated, items:[{type,repo,ts,detail}]}` — giữ tên khoá `gh` dù nguồn nay là Gitea | — |
|
||||
| `widgets:status` | `{yt:"ok"|"stale"|"na", steam:…, gh:…, lastRun}` | — (dashboard admin hiển thị) |
|
||||
| `widgets:img:yt:<id>` · `widgets:img:steam:<appid>:<hash>` | bytes ảnh, metadata `{type}` (jpeg/png/webp) | 14 ngày; ảnh > 2 MB hoặc sai kiểu bị bỏ qua; lượt tải mới lỗi thì giữ bản cũ. Icon Steam: worker hỏi lần lượt `shared.fastly.steamstatic.com` → `shared.akamai.steamstatic.com` (đường dẫn `/community_assets/images/apps/<appid>/<hash>.jpg`, luôn trả ảnh cho Workers) → `cdn.fastly.steamstatic.com` (`/steamcommunity/public/images/apps/…`). Không dùng `cdn.cloudflare`/`cdn.akamai.steamstatic.com` hay `media.steampowered.com`: chúng trả 403 cho Workers với mọi ảnh chưa nằm trong cache của chúng (đo từ mạng Cloudflare ngày 24/10/2026). Game chưa có icon thì widget chỉ hiện tên |
|
||||
|
||||
@@ -46,12 +46,12 @@ Khách **không bao giờ** gọi thẳng bên thứ ba — kể cả ảnh: nha
|
||||
|
||||
- `WidgetLatestVideo`: thumbnail qua `/ext-img/yt/<id>` (bản mirror trong KV, CSP `img-src 'self'`) + nút play → bấm mới tạo iframe `youtube-nocookie.com` (facade — `06` §5 và Privacy). Thiếu ảnh mirror ⇒ khung không ảnh, không gọi ra ngoài.
|
||||
- `WidgetNowPlaying`: icon game + tên + "x giờ / 2 tuần"; 0 game gần đây ⇒ ẩn.
|
||||
- `WidgetGitHub`: 3 dòng "pushed to X · 2d ago".
|
||||
- `WidgetGitea` (`src/components/WidgetGitea.svelte`, trước 2026-11-24 là `WidgetGitHub`): 3 dòng "pushed to X · 2d ago", link tới repo trên Gitea.
|
||||
- Trang tĩnh build kèm snapshot KV tại thời điểm build; island gọi `/api/widgets` (GET, `Cache-Control: max-age=300`, đọc KV) để tươi hơn giữa các lần deploy. Không có JS ⇒ vẫn thấy snapshot build — progressive enhancement.
|
||||
|
||||
## 7. Secrets & cấu hình worker widgets
|
||||
|
||||
`wrangler.jsonc`: `triggers: { crons: ["*/45 * * * *"] }`, bind KV chung, `observability.logs` bật. Secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI`, `GITHUB_TOKEN` (tuỳ chọn). Biến thường: `YT_CHANNEL_ID` (vars, không nhạy cảm). Mỗi lần chạy ghi log JSON `widgets.run` (+ `widgets.source_failed` cho nguồn lỗi). Deploy: `npx wrangler deploy --config workers/widgets/wrangler.jsonc` (không nối Workers Builds).
|
||||
`wrangler.jsonc`: `triggers: { crons: ["*/45 * * * *"] }`, bind KV chung, `observability.logs` bật. Secrets: `STEAM_API_KEY`, `STEAM_ID64`, `DISCORD_WEBHOOK_CI` (`GITHUB_TOKEN` tuỳ chọn bỏ ngày 2026-11-24 — feed Gitea không cần token; gỡ bằng `wrangler secret delete GITHUB_TOKEN --config workers/widgets/wrangler.jsonc` nếu còn). Biến thường: `YT_CHANNEL_ID` (vars, không nhạy cảm). Mỗi lần chạy ghi log JSON `widgets.run` (+ `widgets.source_failed` cho nguồn lỗi). Deploy tay: `npx wrangler deploy --config workers/widgets/wrangler.jsonc` (không nằm trong job `deploy` của CI; trước đây cũng không nối Workers Builds).
|
||||
|
||||
## 8. Test
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Ghi chú pháp lý nhanh (để hiểu, không cần đưa lên site): GPL chỉ
|
||||
|
||||
## English (render trên site)
|
||||
|
||||
**Code.** The source code of this website is free software, licensed under the GNU General Public License v3.0, and is public at https://github.com/poli0981/poli0981-dev. Code snippets published in blog posts are shared under the license stated in each post.
|
||||
**Code.** The source code of this website is free software, licensed under the GNU General Public License v3.0, and is public at https://git.poli0981.dev/poli0981/poli0981-dev, with a mirror for issues at https://gitlab.com/poli0981/poli0981-dev. Code snippets published in blog posts are shared under the license stated in each post.
|
||||
|
||||
**Content.** All written content, stories, photographs, and other original media on this Site are **© Kokone (SkullMute), all rights reserved**. You may not reproduce, republish, or redistribute them, and you may not use them to train machine-learning systems, without prior written permission. Short quotations with attribution and a link are permitted (see Terms §4). Individual pages may state a different license for that page's content, which then prevails.
|
||||
|
||||
@@ -26,7 +26,7 @@ Ghi chú pháp lý nhanh (để hiểu, không cần đưa lên site): GPL chỉ
|
||||
|
||||
## Tiếng Việt (render trên site)
|
||||
|
||||
**Mã nguồn.** Mã nguồn của website là phần mềm tự do, cấp phép theo GNU General Public License v3.0, công khai tại https://github.com/poli0981/poli0981-dev. Các đoạn code đăng trong bài blog được chia sẻ theo giấy phép ghi trong từng bài.
|
||||
**Mã nguồn.** Mã nguồn của website là phần mềm tự do, cấp phép theo GNU General Public License v3.0, công khai tại https://git.poli0981.dev/poli0981/poli0981-dev, kèm một bản sao để nhận issue tại https://gitlab.com/poli0981/poli0981-dev. Các đoạn code đăng trong bài blog được chia sẻ theo giấy phép ghi trong từng bài.
|
||||
|
||||
**Nội dung.** Toàn bộ bài viết, truyện, ảnh và media gốc trên Trang web thuộc **bản quyền © Kokone (SkullMute), bảo lưu mọi quyền**. Không sao chép, đăng lại, phân phối lại, và không dùng để huấn luyện hệ thống máy học khi chưa có sự cho phép bằng văn bản. Được phép trích ngắn có ghi nguồn kèm link (xem Điều khoản §4). Trang cụ thể có thể ghi giấy phép khác cho nội dung của trang đó — khi ấy giấy phép ghi tại trang được ưu tiên.
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ This is a personal website designed to collect as little data as possible.
|
||||
|
||||
**Bot check.** Before your first page view the Site runs Cloudflare Turnstile, a challenge that checks the browser is not an automated scraper; Cloudflare processes technical signals for it (such as IP address and browser characteristics) under its own privacy policy. Passing it sets one strictly necessary cookie, `__Host-gate`, valid for 48 hours. It holds only an expiry time, a random value and a signature — nothing that identifies you — and is never used for tracking. Search engines and link-preview services verified by Cloudflare skip the check; feeds, the sitemap and the legal pages are always open.
|
||||
|
||||
**4. Bug reports (the only form on the Site).** If you choose to send a bug report, the following is transmitted and stored as a private GitHub issue and a Discord notification: your description, the page route, browser user-agent, viewport size, theme/language setting, and — only if you leave the checkbox enabled — the last console error messages shown to you in a preview before sending. No IP address is stored with the report. Contact me to request deletion of a report you sent.
|
||||
**4. Bug reports (the only form on the Site).** If you choose to send a bug report, the following is transmitted and stored as a confidential issue on GitLab.com, in the project that mirrors this site's source code (confidential: only I can see it) and sent as a Discord notification: your description, the page route, browser user-agent, viewport size, theme/language setting, and — only if you leave the checkbox enabled — the last console error messages shown to you in a preview before sending. No IP address is stored with the report. Contact me to request deletion of a report you sent.
|
||||
|
||||
**5. Embedded videos.** YouTube videos load only after you click them, via YouTube's privacy-enhanced domain (youtube-nocookie.com). Before you click, only a static thumbnail is loaded. Once you click, YouTube's own privacy policy applies.
|
||||
|
||||
@@ -48,7 +48,7 @@ This is a personal website designed to collect as little data as possible.
|
||||
|
||||
**Xác minh chống bot.** Trước lượt xem đầu tiên, trang chạy Cloudflare Turnstile — bước kiểm tra trình duyệt không phải bot thu thập nội dung; Cloudflare xử lý các tín hiệu kỹ thuật (như địa chỉ IP, đặc điểm trình duyệt) theo chính sách riêng của họ. Qua bước này, trình duyệt nhận một cookie thiết yếu duy nhất, `__Host-gate`, hiệu lực 48 giờ. Cookie chỉ chứa thời điểm hết hạn, một giá trị ngẫu nhiên và chữ ký — không có gì định danh bạn — và không bao giờ dùng để theo dõi. Công cụ tìm kiếm và dịch vụ xem trước liên kết đã được Cloudflare xác thực thì bỏ qua bước này; RSS, sitemap và các trang pháp lý luôn mở.
|
||||
|
||||
**4. Báo lỗi (biểu mẫu duy nhất trên trang).** Nếu bạn chủ động gửi báo lỗi, những thứ sau được truyền và lưu dưới dạng GitHub issue riêng tư + thông báo Discord: mô tả của bạn, đường dẫn trang, user-agent trình duyệt, kích thước màn hình, cài đặt theme/ngôn ngữ, và — chỉ khi bạn để nguyên ô tick — các lỗi console gần nhất (có bản xem trước trước khi gửi). Địa chỉ IP không được lưu kèm báo cáo. Muốn xoá báo cáo đã gửi: liên hệ mình.
|
||||
**4. Báo lỗi (biểu mẫu duy nhất trên trang).** Nếu bạn chủ động gửi báo lỗi, những thứ sau được truyền và lưu dưới dạng issue bảo mật (confidential) trên GitLab.com, trong project bản sao mã nguồn của trang (chỉ mình xem được), kèm một thông báo Discord: mô tả của bạn, đường dẫn trang, user-agent trình duyệt, kích thước màn hình, cài đặt theme/ngôn ngữ, và — chỉ khi bạn để nguyên ô tick — các lỗi console gần nhất (có bản xem trước trước khi gửi). Địa chỉ IP không được lưu kèm báo cáo. Muốn xoá báo cáo đã gửi: liên hệ mình.
|
||||
|
||||
**5. Video nhúng.** Video YouTube chỉ tải sau khi bạn bấm, qua tên miền tăng cường riêng tư (youtube-nocookie.com). Trước khi bấm, chỉ có ảnh thumbnail tĩnh. Sau khi bấm, chính sách của YouTube áp dụng.
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ Trang web này được xây dựng bằng phần mềm mã nguồn mở. Mỗi
|
||||
| Font: Literata | SIL OFL 1.1 | |
|
||||
| Font: JetBrains Mono | SIL OFL 1.1 | |
|
||||
|
||||
**Dịch vụ hạ tầng** (không phải package, ghi nhận cho minh bạch): Cloudflare (hosting/CDN/analytics/Turnstile), GitHub (mã nguồn, issue), YouTube/Steam/GitHub API (widget dữ liệu công khai).
|
||||
**Dịch vụ hạ tầng** (không phải package, ghi nhận cho minh bạch): Cloudflare (hosting/CDN/analytics/Turnstile), Gitea tự host `git.poli0981.dev` (mã nguồn, nội dung), GitLab (mirror công khai của mã nguồn, issue, báo lỗi dạng issue confidential), YouTube/Steam/feed công khai của Gitea (widget dữ liệu công khai). Đến 2026-11-23: GitHub (mã nguồn, issue) và GitHub API (widget).
|
||||
|
||||
## Quy trình sinh tự động
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ Item: title, link, pubDate, description, `<language>` theo bài, category = tags
|
||||
|
||||
## 6. Dữ liệu có cấu trúc (JSON-LD)
|
||||
|
||||
- Toàn site: `Person` (Kokone, sameAs = các URL social ở /links — giúp knowledge panel liên kết YouTube/GitHub).
|
||||
- Toàn site: `Person` (Kokone, sameAs = các URL social ở /links — giúp knowledge panel liên kết YouTube/Gitea; trước 2026-11-24 là GitHub).
|
||||
- Bài blog: `BlogPosting`; truyện: `CreativeWork` (`genre`, `isPartOf` series); project: `SoftwareSourceCode` (codeRepository).
|
||||
|
||||
## 7. Việc SEO một lần sau launch
|
||||
|
||||
@@ -27,6 +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: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý. Đo qua nginx có sẵn trên runner (gzip, cấu hình ngay trong bước "Start compressing proxy"): `astro preview` không nén gì, còn edge Cloudflare nén brotli mọi response dạng chữ ở production — đo thẳng preview thì điện thoại giả lập phải tải gấp 3–4 lần số byte thật (HTML trang chủ 108 KB thay vì ~25 KB). gzip to hơn brotli chút ít nên số đo vẫn hơi bi quan so với production.
|
||||
- CI: `lighthouse.yml` (`treosh/lighthouse-ci-action`, preset **mobile** như bảng §1) chạy trên bản build, assert budget — chỉ warn, không block, để tránh flaky chặn deploy; đỏ 2 lần liên tiếp thì xử lý. Đo qua nginx (gzip, cấu hình ngay trong bước "Start compressing proxy"; image của Gitea runner không có nginx lẫn Chrome nên bước đó tự cài nginx và Lighthouse dùng Chromium của Playwright — runner GitHub đến 2026-11-23 có sẵn cả hai; report là artifact `lighthouse-reports`, `08` §0): `astro preview` không nén gì, còn edge Cloudflare nén brotli mọi response dạng chữ ở production — đo thẳng preview thì điện thoại giả lập phải tải gấp 3–4 lần số byte thật (HTML trang chủ 108 KB thay vì ~25 KB). gzip to hơn brotli chút ít nên số đo vẫn hơi bi quan so với production.
|
||||
- Islands thêm từ 10/2026 đều nhỏ và `client:idle`: ThemeToggle, Waveline ở hero trang chủ, SearchModal/MenuSheet; Waveline dưới màn hình đầu là `client:visible`. Admin là trang on-demand riêng, không tính vào budget site.
|
||||
- Thực địa: Cloudflare Web Analytics có Core Web Vitals thật của khách — xem hằng tháng (lịch `17`).
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
Ước lượng theo "buổi tối" (~2–3h). Nguyên tắc quen thuộc: **xong P0 spikes mới viết feature** — spike nào fail thì sửa kế hoạch khi chưa tốn công.
|
||||
|
||||
Trạng thái tại 2026-11-21 (v2.3.0 — **chế độ bảo trì**): ✅ xong · 🟡 đang làm · ⬜ chưa.
|
||||
Trạng thái tại 2026-11-24 (v2.3.0 → v2.4.0 chuyển sang Gitea — **chế độ bảo trì**): ✅ xong · 🟡 đang làm · ⬜ chưa.
|
||||
|
||||
## P0 — Spikes ✅
|
||||
|
||||
| # | Spike | Cách làm | Tiêu chí đạt | |
|
||||
|---|---|---|---|---|
|
||||
| S1 | **Pipeline sống end-to-end** | Mua domain (07 §1) → scaffold Astro → deploy → gắn custom domain → CI | Push 1 commit ⇒ site đổi trên `poli0981.dev` trong <3 phút | ✅ (Workers Builds) |
|
||||
| S1 | **Pipeline sống end-to-end** | Mua domain (07 §1) → scaffold Astro → deploy → gắn custom domain → CI | Push 1 commit ⇒ site đổi trên `poli0981.dev` trong <3 phút | ✅ (Workers Builds; từ 2026-11-24 job `deploy` của Gitea CI) |
|
||||
| S2 | **Font tiếng Việt** | Fonts API 4 font, subset `latin+vietnamese`; trang test đủ dấu ở mọi weight | Render đúng trên Android + iPhone thật, 2 file first-paint <90KB | ✅ |
|
||||
| S3 | **Error handling sau edge** | `not_found_handling: "404-page"`; 403/429 từ asset prerender; test qua domain thật | Ma trận `09` §5 pass các dòng 404/403/429 | ✅ |
|
||||
| S4 | **CSP không vỡ tính năng** | CSP built-in + directive `06` §1; Pagefind, YouTube facade, Turnstile | Console 0 lỗi CSP; search hoạt động (`wasm-unsafe-eval`) | ✅ (`check-csp-hashes` trong build) |
|
||||
@@ -24,7 +24,7 @@ Trạng thái tại 2026-11-21 (v2.3.0 — **chế độ bảo trì**): ✅ xong
|
||||
|
||||
- Pagefind search modal · RSS ×3 · sitemap/hreflang/JSON-LD · OG image tự sinh.
|
||||
- Gallery + lightbox + strip-exif/check-exif scripts.
|
||||
- Gaming + Dev/uses; widgets worker (YouTube/Steam/GitHub) + `/api/widgets`.
|
||||
- Gaming + Dev/uses; widgets worker (YouTube/Steam/GitHub — GitHub thành Gitea từ 2026-11-24) + `/api/widgets`.
|
||||
- Bug report pipeline đầy đủ (10) + issue template.
|
||||
- Offline service worker + trang /offline.
|
||||
- Lighthouse CI warn-mode.
|
||||
@@ -47,13 +47,14 @@ Trạng thái tại 2026-11-21 (v2.3.0 — **chế độ bảo trì**): ✅ xong
|
||||
- [ ] 13 §7 (SEO một lần) xong
|
||||
- [x] Văn bản legal có ngày hiệu lực (2026-10-24), không còn ghi chú nội bộ
|
||||
- [ ] Test 2 thiết bị thật + 1 máy lạ (bạn bè) — thu 1 vòng feedback
|
||||
- [ ] Đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/GitHub/Discord
|
||||
- [ ] Đăng giới thiệu lên các kênh (dùng notify.py 😄), thêm link site vào bio YouTube/Gitea/Discord
|
||||
|
||||
- **v2.3.0** (11/2026, bản tính năng cuối): nhãn nội dung + hỏi tuổi + ảnh mờ + banner cảnh báo (D22) · admin tự xuất bản và biết khi nào "đã lên web" (D23) · Qodana + kiểm license toàn cây (D24) · **chuyển sang chế độ bảo trì** (D21).
|
||||
- **v2.4.0** (11/2026, không phải tính năng — tài khoản GitHub không còn): chuyển sang Gitea tự host + mirror GitLab, CI trên Gitea Actions và deploy bằng job `deploy`, Renovate thay Dependabot, bỏ SonarCloud/`triage.yml`, admin/báo lỗi/widget trên Gitea và GitLab (D25). Chi tiết: `CHANGELOG.md`.
|
||||
|
||||
## Chế độ bảo trì (từ v2.3.0, 11/2026)
|
||||
|
||||
Không thêm tính năng mới. Chỉ: cập nhật dependency định kỳ · vá bảo mật (advisory High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (cả UI/UX, accessibility) · sửa lỗi ngôn ngữ. Chính sách: `CONTRIBUTING.md`; lịch: `17` §0–§1; bot đóng đề xuất tính năng: `.github/workflows/triage.yml`.
|
||||
Không thêm tính năng mới. Chỉ: cập nhật dependency định kỳ · vá bảo mật (advisory High/Critical, lỗ hổng runtime) · nâng cấp lớn ngôn ngữ/runtime/framework · sửa lỗi (cả UI/UX, accessibility) · sửa lỗi ngôn ngữ. Chính sách: `CONTRIBUTING.md`; lịch: `17` §0–§1; đề xuất tính năng được đóng tay trên mirror GitLab (bot `.github/workflows/triage.yml` làm việc này đến 2026-11-23).
|
||||
|
||||
P4 còn mở vẫn làm được vì không phải tính năng. Bảng dưới đây **đóng băng** — giữ để biết đã cân nhắc gì; mục nào chỉ quay lại khi rơi vào một trong năm loại thay đổi được nhận (VD gộp TypeScript 7.1 = nâng cấp lớn).
|
||||
|
||||
@@ -62,7 +63,7 @@ P4 còn mở vẫn làm được vì không phải tính năng. Bảng dưới
|
||||
| Hướng | Vì sao | Điều kiện |
|
||||
|---|---|---|
|
||||
| Gộp TypeScript về một bản 7.x | Bỏ alias `@typescript/native` + TS 6 | TS 7.1 có JS API; astro check / typescript-eslint / svelte2tsx hỗ trợ |
|
||||
| Workers Builds riêng cho widgets worker | Hết deploy tay | Khi worker có thay đổi thường xuyên hơn |
|
||||
| Job deploy trong Gitea CI cho widgets worker (trước 2026-11-24: Workers Builds riêng) | Hết deploy tay | Khi worker có thay đổi thường xuyên hơn |
|
||||
| Backup định kỳ R2 + KV (denylist, audit) | Ảnh upload chỉ nằm ở R2 | Workflow cron dùng `wrangler r2 object get` / `kv key list` (17 §4) |
|
||||
| Analytics Engine cho số liệu cổng/báo lỗi | Biết cổng chặn bao nhiêu, báo lỗi đến từ đâu | Không thêm cookie; giữ khớp Privacy Policy |
|
||||
| Đếm lượt xem bằng Durable Object | Số đọc cho blog/truyện không cần dịch vụ ngoài | Cập nhật Privacy Policy trước |
|
||||
|
||||
@@ -9,11 +9,13 @@ Tỷ giá tham khảo ~26.000 VND/USD, 2026-07.
|
||||
| Domain `poli0981.dev` (Cloudflare Registrar, at-cost, WHOIS redaction free) | năm | **~$12–13** (~320–340k VND) — số chính xác hiện khi search trong dashboard | **Phát sinh mới duy nhất** |
|
||||
| Cloudflare Workers Paid | tháng | $5 | Đã có sẵn — site nằm trong hạn mức |
|
||||
| KV · Turnstile · Web Analytics · Email Routing · WAF free · Bot Fight | — | $0 | Free / trong gói |
|
||||
| GitHub public repo + Actions + Dependabot + CodeQL | — | $0 | Repo public: phút Actions không giới hạn cho runner chuẩn; SonarCloud free cho dự án public |
|
||||
| Gitea tự host (`git.poli0981.dev`) + Gitea Actions + Renovate tự host | — | $0 riêng cho site | Từ 2026-11-24. Hạ tầng chung cho mọi repo của chủ site (không tính vào bảng này); runner là PC của chủ repo nên không có phút CI tính tiền |
|
||||
| Mirror GitLab.com (`poli0981/poli0981-dev`) | — | $0 | Project public; GitLab CI tắt; nhận issue/MR và báo lỗi từ site (issue confidential) |
|
||||
| *Lịch sử:* GitHub public repo + Actions + Dependabot + CodeQL | — | $0 | Đến 2026-11-23. Repo public: phút Actions không giới hạn cho runner chuẩn; SonarCloud free cho dự án public |
|
||||
| Astro/Svelte/Tailwind/GSAP/font/Pagefind | — | $0 | OSS |
|
||||
| R2 | `poli0981-media` | $0 | Ảnh upload qua admin (biến thể AVIF/WebP + master). Free 10 GB lưu trữ, 1M thao tác ghi, 10M đọc/tháng — đọc hầu hết trúng Cache API ở edge |
|
||||
| Images (binding) | biến đổi lúc upload | $0 | Free 5.000 biến đổi duy nhất/tháng (mỗi ảnh ≈ 6), vượt thì $0.50/1.000. Ảnh trùng (cùng hash) không biến đổi lại |
|
||||
| Zone Pro / Sentry / CMS bên thứ ba | — | $0 | **Cố ý không dùng** — admin tự làm (Access + GitHub API), ảnh dùng R2 + Images của chính Cloudflare |
|
||||
| Zone Pro / Sentry / CMS bên thứ ba | — | $0 | **Cố ý không dùng** — admin tự làm (Access + Gitea API; đến 2026-11-23 là GitHub API), ảnh dùng R2 + Images của chính Cloudflare |
|
||||
|
||||
**Tổng phát sinh mới: ~$12–13/năm.** Tổng vận hành thực (gồm Workers đã trả): **~$72–73/năm (~1,9 triệu VND)**.
|
||||
|
||||
@@ -25,7 +27,7 @@ Tỷ giá tham khảo ~26.000 VND/USD, 2026-07.
|
||||
| Cloudflare Access | 50 người dùng miễn phí | 1 (chủ site) | Không áp dụng |
|
||||
| Images (binding) | 5.000 biến đổi duy nhất/tháng | ≈ 6 / ảnh upload; ảnh trùng = 0 | Upload > ~800 ảnh mới/tháng |
|
||||
| KV reads/writes | hạn mức Paid rộng | cron 45' + vài GET | Không |
|
||||
| GitHub Actions phút | không giới hạn (public) | ~200–400 | Repo `content`/`site-reports` vẫn private nếu sau này có workflow riêng — theo dõi ở Settings → Billing |
|
||||
| Phút CI | không tính tiền — runner Gitea trên PC của chủ repo (đến 2026-11-23: GitHub Actions, không giới hạn cho repo public) | ~200–400 | Không phải chi phí; giới hạn thật là PC phải bật (job lịch chỉ 13:00–16:00 UTC, `08` §0) |
|
||||
| Domain renew | — | $12–13/năm | Thẻ hết hạn ⇒ mất domain — auto-renew ON + lịch nhắc (17) |
|
||||
|
||||
## 3. Quy tắc chi tiêu
|
||||
|
||||
@@ -6,31 +6,31 @@ Mục tiêu: site "để yên vẫn sống". Tổng thời gian bảo trì đị
|
||||
|
||||
Không thêm tính năng mới. Repo chỉ nhận (`CONTRIBUTING.md`):
|
||||
|
||||
1. Cập nhật dependency định kỳ (Dependabot hằng tuần + gộp `npm update --save --before=<hôm nay − 3 ngày>` khoảng mỗi tháng, như PR #123/#134).
|
||||
1. Cập nhật dependency định kỳ (Renovate tự host chạy hằng ngày, gộp mọi patch/minor vào một PR — từ 2026-11-24; trước đó Dependabot hằng tuần + gộp `npm update --save --before=<hôm nay − 3 ngày>` khoảng mỗi tháng, như PR #123/#134).
|
||||
2. Bảo mật: advisory **High/Critical** trong dependency hoặc lỗ hổng nghiêm trọng của Node.js/Workers runtime ⇒ sửa và deploy ngay, ngoài lịch; tính năng chỉ khi thật sự cần.
|
||||
3. Nâng cấp lớn ngôn ngữ/runtime/framework (Node 26 → 28, TS 7.1 thay alias TS 6, Astro/Svelte major…).
|
||||
4. Sửa lỗi, gồm UI/UX và accessibility.
|
||||
5. Sửa lỗi ngôn ngữ (chính tả gây hiểu nhầm, câu chữ không hợp văn hoá/giọng địa phương).
|
||||
|
||||
Issue/PR đề xuất tính năng: `.github/workflows/triage.yml` (logic `scripts/triage.mjs`) gắn `enhancement` + `out-of-scope`, trả lời song ngữ và đóng. Bỏ qua: chủ repo, bot, mục có nhãn `maintenance-exception` (ngoại lệ do chủ repo quyết), và mọi thao tác do chính chủ repo làm (mở lại, gắn nhãn). Thử khô: Actions → Triage → Run workflow (nhập tiêu đề). Form issue: lỗi, accessibility, ngôn ngữ; blank issue tắt; câu hỏi/ý tưởng → Discussions.
|
||||
Issue/PR đề xuất tính năng (từ 2026-11-24): người ngoài không đăng ký được trên Gitea nên issue và merge request đến qua mirror GitLab (`https://gitlab.com/poli0981/poli0981-dev`) hoặc e-mail `code@poli0981.dev`; mục ngoài 5 loại trên được gắn `enhancement` + `out-of-scope` và **đóng tay** trên GitLab, dẫn `CONTRIBUTING.md` (ngoại lệ do chủ repo chấp nhận mang nhãn `maintenance-exception`). Lỗ hổng bảo mật chỉ qua `security@poli0981.dev` — nếu lỡ thành issue công khai trên GitLab thì chuyển nó sang confidential rồi tiếp tục qua e-mail. Form issue: lỗi, accessibility, ngôn ngữ (`.gitlab/issue_templates/` cho GitLab, `.github/ISSUE_TEMPLATE/` cho Gitea); blank issue tắt trên Gitea; câu hỏi/ý tưởng → `code@poli0981.dev`. Đến 2026-11-23 việc đóng do bot `.github/workflows/triage.yml` (logic `scripts/triage.mjs`) làm — gắn `enhancement` + `out-of-scope`, trả lời song ngữ và đóng; câu hỏi/ý tưởng đi Discussions. Bot đã bỏ: issue trên GitLab không tới được Gitea Actions.
|
||||
|
||||
## 1. Lịch định kỳ
|
||||
|
||||
| Nhịp | Việc |
|
||||
|---|---|
|
||||
| **Hằng tuần** (thứ 2, sau khi Dependabot chạy) | Triage PR Dependabot: patch/minor xanh CI → merge; security alert → xử lý ≤ 48h. Liếc Discord `#site-reports` |
|
||||
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; **nâng tay `@typescript/native`** (Dependabot bỏ qua alias `npm:`) và xem TS 7.1 đã có JS API chưa (`02` §8); xem Web Analytics + Core Web Vitals; liếc Workers Logs (lọc `level: error`) + dashboard admin (trạng thái cron widgets, secret thiếu); SonarCloud không có issue mới trên `main` |
|
||||
| **Hằng tuần** | Xem PR Renovate (bot chạy hằng ngày 20:31 VN khi PC bật) + Dependency Dashboard: PR gộp patch/minor xanh CI → merge; PR nhãn `security` → xử lý ≤ 48h. Xem run `security.yml` thứ Tư (21:13 VN). Liếc Discord `#site-reports` và issue mới trên mirror GitLab (báo lỗi từ site là issue confidential). (Đến 2026-11-23: thứ 2, triage PR Dependabot) |
|
||||
| **Hằng tháng** | `npm outdated` đọc report weekly; nâng minor còn sót; xem PR Renovate cho `@typescript/native` (thời Dependabot phải nâng tay vì alias `npm:` bị bỏ qua) và xem TS 7.1 đã có JS API chưa (`02` §8); xem Web Analytics + Core Web Vitals; liếc Workers Logs (lọc `level: error`) + dashboard admin (trạng thái cron widgets, secret thiếu); Qodana Cloud không có vấn đề mới trên `main` (đến 2026-11-23: SonarCloud); nâng tay pin reusable `security.yml` khi repo ops có tag mới |
|
||||
| **Hằng quý** | Nâng major có kế hoạch (Astro/Tailwind/Wrangler — đọc upgrade guide trước); chạy lại ma trận error test `09` §5; backup ngoài (§4) |
|
||||
| **Hằng năm** | **Xoay secrets**: GITHUB_ISSUES_TOKEN (repo `site-reports`), GITHUB_CONTENT_TOKEN + GITHUB_PUBLISH_TOKEN (admin), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, SONAR_TOKEN, QODANA_TOKEN (token project trên Qodana Cloud → secret repo) · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 7 trang legal (đổi thì tăng `v` của legalAck) · **rà trợ năng**: đọc lại `/legal/accessibility` + `ACCESSIBILITY.md`, đi một lượt bằng bàn phím và trình đọc màn hình, cập nhật ngày rà ở cả hai nơi · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
|
||||
| **Hằng năm** | **Xoay secrets**: GITLAB_ISSUES_TOKEN (báo lỗi, project mirror GitLab), GITEA_BOT_TOKEN (admin, user `poli0981-bot`), CLOUDFLARE_API_TOKEN (secret Actions cấp user trên Gitea, job `deploy`), GATE_SECRET (vô hiệu mọi vé cổng — làm lúc ít khách), STEAM_API_KEY, QODANA_TOKEN (token project trên Qodana Cloud → secret Actions trên Gitea), token push mirror GitLab lưu trong Gitea (hạn ≤ 365 ngày; `setup-mirrors.ps1 -Rotate`, runbook `GITEA-MIGRATION.md` §9) — đến 2026-11-23 còn GITHUB_ISSUES_TOKEN, GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN, SONAR_TOKEN · rà `ADMIN_EMAILS` + policy Access · cập nhật `Expires` trong security.txt · đọc lại 7 trang legal (đổi thì tăng `v` của legalAck) · **rà trợ năng**: đọc lại `/legal/accessibility` + `ACCESSIBILITY.md`, đi một lượt bằng bàn phím và trình đọc màn hình, cập nhật ngày rà ở cả hai nơi · kiểm tra thẻ thanh toán còn hạn cho auto-renew domain |
|
||||
|
||||
Đặt reminder: dùng chính hệ notify/cron GitHub Actions quen thuộc — workflow cron tháng/quý/năm bắn Discord nhắc việc (input sẵn trong repo `.github`).
|
||||
Đặt reminder: dùng chính hệ notify/cron quen thuộc của repo `.github` — workflow cron tháng/quý/năm bắn Discord nhắc việc. Từ 2026-11-24 đó là Gitea Actions (trước: GitHub Actions), nên giờ cron phải nằm trong khung 13:00–16:00 UTC (`08` §0).
|
||||
|
||||
## 2. Update playbook (major upgrade an toàn)
|
||||
|
||||
1. Branch `chore/upgrade-<pkg>-vX` → đọc CHANGELOG/upgrade guide chính thức.
|
||||
2. `npm i <pkg>@latest` → chạy full CI local (`format/lint/check/knip/build`).
|
||||
3. Mở PR → CI (`build` + smoke) + SonarCloud xanh; Workers Builds upload version preview của nhánh → bấm qua 6 trang đại diện + search + form report (dashboard → Versions → alias của nhánh).
|
||||
4. Squash-merge → Workers Builds deploy `main` (Deploy command `npx wrangler deploy`, `07` §9) → kiểm `/api/health` trả đúng commit (nếu vẫn bản cũ: Deploy command lại thành `versions upload` ⇒ sửa trong dashboard, tạm thời `wrangler versions deploy <id>@100%`) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429).
|
||||
3. Mở PR → CI (`build` + smoke + a11y) + Qodana + Security xanh → bấm qua 6 trang đại diện + search + form report trên bản chạy local (`npm run build && npm run preview`) — từ 2026-11-24 PR không còn version preview. (Đến 2026-11-23: + SonarCloud; Workers Builds upload version preview của nhánh, xem ở dashboard → Versions → alias của nhánh.)
|
||||
4. Squash-merge → job `deploy` của Gitea CI deploy `main` và tự chờ `/api/health` trả đúng commit (`07` §9; job đỏ hoặc PC tắt ⇒ chạy lại job / deploy tay) → chạy nhanh ma trận lỗi 3 dòng đầu (404/403/429). (Đến 2026-11-23: Workers Builds deploy `main`; bản cũ còn chạy ⇒ sửa Deploy command, tạm thời `wrangler versions deploy <id>@100%`.)
|
||||
5. Ghi vào `CHANGELOG.md`; ghi 1 dòng vào `poli0981.dev-docs/00_INDEX.md` nếu có breaking change ảnh hưởng quyết định cũ.
|
||||
|
||||
**Rollback**: `npx wrangler versions list` → `npx wrangler versions deploy <id-cũ>@100% --yes` (hoặc `wrangler rollback`). Secret mới đặt sau version đó sẽ không có trong version cũ — đặt lại nếu cần.
|
||||
@@ -45,7 +45,7 @@ Issue/PR đề xuất tính năng: `.github/workflows/triage.yml` (logic `script
|
||||
|
||||
## 4. Backup & khôi phục
|
||||
|
||||
- **Nguồn sự thật = Git** (nội dung + code). GitHub đã là bản sao thứ nhất; máy local là bản thứ hai.
|
||||
- **Nguồn sự thật = Git** (nội dung + code). Bản gốc trên Gitea `git.poli0981.dev` (Gitea tự backup hằng ngày 19:30–19:45 UTC); mirror GitLab (`gitlab.com/poli0981/<repo>`, Gitea đẩy sang sau mỗi thay đổi) là bản sao thứ nhất; máy local là bản thứ hai. (Đến 2026-11-23: GitHub là bản sao thứ nhất.)
|
||||
- **Quý**: `git bundle create backup-YYYYQ.bundle --all` → cất vào ổ ngoài/cloud cá nhân (một lệnh, chứa toàn bộ lịch sử).
|
||||
- **R2 `poli0981-media`** (ảnh upload qua admin — *không* có trong Git): quý một lần sao ra ngoài, vd. `npx wrangler r2 object get poli0981-media/<key> --file …` theo danh sách `private/meta/*.json`, hoặc rclone với S3 API token chỉ-đọc.
|
||||
- **KV**: widgets tái sinh được; `denylist` và `audit:*` nên xuất định kỳ: `npx wrangler kv key get --binding KV denylist --preview false > denylist.json` và `npx wrangler kv key list --binding KV --prefix audit: --preview false > audit.json`.
|
||||
@@ -61,7 +61,7 @@ Issue/PR đề xuất tính năng: `.github/workflows/triage.yml` (logic `script
|
||||
| Gần hết 5.000 biến đổi Images/tháng | Upload trùng không tốn thêm; nếu vẫn thiếu thì bật Images Paid ($0.50/1.000) — ghi vào `16` trước |
|
||||
| Muốn viết trọn bài từ điện thoại thường xuyên | Dùng admin `admin.poli0981.dev` (đã có) |
|
||||
| Spam form vượt rate-limit thường xuyên | Nâng Turnstile lên chế độ khó hơn + thêm custom rule quốc gia cho /api |
|
||||
| Version sai lên production (PR được deploy, regression) | Rollback ngay (§2), rồi kiểm Deploy command của Workers Builds (`07` §9) |
|
||||
| Version sai lên production (regression) | Rollback ngay (§2), rồi xem run `deploy` của commit đó trên Gitea (`07` §9). (Thời Workers Builds: kiểm Deploy command — từng có PR được deploy) |
|
||||
| Bị khoá ngoài admin (Access/`ADMIN_EMAILS`) | `wrangler secret put ADMIN_EMAILS` với email đúng; kiểm policy Access; denylist có chặn nhầm IP mình không (`wrangler kv key get … denylist`) |
|
||||
| Có báo cáo rào cản trợ năng (`accessibility@`, nút Báo lỗi, issue nhãn `accessibility`) | Trả lời ≤ 7 ngày; lỗi chặn hẳn việc đọc/dùng trang làm trước; nói rõ định làm gì + cách tạm thời; sửa xong thì thêm test vào `tests/a11y/` và, nếu chưa sửa được, ghi vào "Known limitations" của `ACCESSIBILITY.md` + trang `/legal/accessibility` |
|
||||
| Release có đổi giao diện | `npm run test:a11y` xanh + nghe lại các chỗ đã đổi bằng Narrator/VoiceOver; cập nhật "Last reviewed" trong `ACCESSIBILITY.md` |
|
||||
|
||||
@@ -3,4 +3,4 @@ Contact: mailto:contact@poli0981.dev
|
||||
Expires: 2027-07-01T00:00:00Z
|
||||
Preferred-Languages: vi, en
|
||||
Canonical: https://poli0981.dev/.well-known/security.txt
|
||||
Policy: https://github.com/poli0981/poli0981-dev/blob/main/SECURITY.md
|
||||
Policy: https://git.poli0981.dev/poli0981/poli0981-dev/src/branch/main/SECURITY.md
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
# JetBrains Qodana — run by .github/workflows/qodana.yml on every PR and on main
|
||||
# JetBrains Qodana — run by .gitea/workflows/qodana.yml on every PR and on main
|
||||
# (docs 08 §0). Reference: https://www.jetbrains.com/help/qodana/configuration-reference.html
|
||||
#
|
||||
# Qodana for JS is WebStorm's inspection engine. It reads .ts/.js/.mjs, CSS, JSON, YAML and
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["local>poli0981/renovate-config"],
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "typescript stays on 6.x on purpose: TypeScript 7.0 ships no JS API, and astro check (Volar), typescript-eslint and svelte2tsx all need one. TypeScript 7 itself is the @typescript/native alias (npm:typescript@7), a different dependency name, so it keeps its updates. Lift this once those tools support TypeScript 7.1's new API (docs 17).",
|
||||
"matchDepNames": ["typescript"],
|
||||
"matchUpdateTypes": ["major"],
|
||||
"enabled": false
|
||||
},
|
||||
{
|
||||
"description": "prettier-plugin-astro 1.x reflows <span>{expr}</span> onto separate lines in 50 .astro files, inserting whitespace text nodes inside inline elements: a visual change, not a formatting one. It needs its own PR with a rendered diff.",
|
||||
"matchPackageNames": ["prettier-plugin-astro"],
|
||||
"matchUpdateTypes": ["major"],
|
||||
"enabled": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env node
|
||||
// The Gitea half of a content publish (.gitea/workflows/content-bump.yml and ci.yml), with
|
||||
// the job token. Two commands:
|
||||
//
|
||||
// node scripts/content-publish.mjs open content-bump.yml, after pushing content/bump:
|
||||
// open or update the PR, say in its body whether it
|
||||
// merges itself, and dispatch ci.yml on the branch
|
||||
// node scripts/content-publish.mjs merge ci.yml's `publish` job, after `build` on
|
||||
// content/bump: record build's result as the
|
||||
// commit status branch protection requires; when it
|
||||
// passed and the PR body says auto, merge the PR,
|
||||
// then dispatch ci.yml on main to deploy
|
||||
//
|
||||
// Environment: API (github.api_url), REPO (owner/name), TOKEN (the job token); `open` also
|
||||
// NEW (the content commit) and AUTO ("true" when only .md/.json changed); `merge` also SHA
|
||||
// (the commit CI built), BUILD (needs.build.result) and RUN_URL (the run, for the status).
|
||||
//
|
||||
// Why the dispatches: Gitea, like GitHub, starts no workflow for what the job token does —
|
||||
// neither for the PR it opens nor for the merge commit it pushes to main.
|
||||
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
export const BRANCH = "content/bump";
|
||||
export const BASE = "main";
|
||||
export const MARK_AUTO = "<!-- publish: auto -->";
|
||||
export const MARK_REVIEW = "<!-- publish: review -->";
|
||||
|
||||
const REVIEW_NOTE =
|
||||
"This publish touches files other than .md/.json (MDX runs code at build time), so it waits for a review instead of merging itself.";
|
||||
|
||||
/** The PR body; its last line is the marker the admin and the merge step read. */
|
||||
export function prBody(contentCommit, auto) {
|
||||
return [
|
||||
`Bumps \`src/content\` to poli0981/content@${contentCommit}.`,
|
||||
"Opened by the admin's **Publish** (`.gitea/workflows/content-bump.yml`).",
|
||||
"",
|
||||
auto
|
||||
? "Only Markdown/JSON changed: CI merges this PR once `build` passes, then deploys main."
|
||||
: REVIEW_NOTE,
|
||||
"",
|
||||
auto ? MARK_AUTO : MARK_REVIEW,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export const isAuto = (body) => typeof body === "string" && body.includes(MARK_AUTO);
|
||||
|
||||
/** A small client for Gitea's REST API with the job token. */
|
||||
export function gitea({ api, repo, token, fetch = globalThis.fetch }) {
|
||||
return async function call(method, path, body) {
|
||||
const res = await fetch(`${api}/repos/${repo}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
authorization: `token ${token}`,
|
||||
accept: "application/json",
|
||||
...(body === undefined ? {} : { "content-type": "application/json" }),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) {
|
||||
const error = new Error(`${method} ${path} → ${res.status} ${text.slice(0, 300)}`);
|
||||
error.status = res.status;
|
||||
throw error;
|
||||
}
|
||||
return text ? JSON.parse(text) : null;
|
||||
};
|
||||
}
|
||||
|
||||
/** The open content/bump → main PR, or null. */
|
||||
export async function findPull(call) {
|
||||
const pulls = await call("GET", "/pulls?state=open&limit=50");
|
||||
return pulls.find((p) => p.head?.ref === BRANCH && p.base?.ref === BASE) ?? null;
|
||||
}
|
||||
|
||||
export async function open({ call, contentCommit, auto, log = console.log }) {
|
||||
const body = prBody(contentCommit, auto);
|
||||
let pull = await findPull(call);
|
||||
const wasAuto = pull ? isAuto(pull.body) : true;
|
||||
if (pull) {
|
||||
await call("PATCH", `/pulls/${pull.number}`, { body });
|
||||
log(`Updated PR #${pull.number}.`);
|
||||
} else {
|
||||
pull = await call("POST", "/pulls", {
|
||||
base: BASE,
|
||||
head: BRANCH,
|
||||
title: "chore(content): publish from admin",
|
||||
body,
|
||||
});
|
||||
log(`Opened PR #${pull.number}.`);
|
||||
}
|
||||
// Say it once, when the PR turns from "merges itself" to "waits for a review".
|
||||
if (!auto && wasAuto) {
|
||||
await call("POST", `/issues/${pull.number}/comments`, { body: REVIEW_NOTE });
|
||||
}
|
||||
await call("POST", "/actions/workflows/ci.yml/dispatches", { ref: BRANCH });
|
||||
log(`Dispatched ci.yml on ${BRANCH}.`);
|
||||
return pull.number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The status main's branch protection requires (`CI / build (*)`). Gitea 28.4 writes commit
|
||||
* statuses for push and pull_request runs only, never for a dispatched one, so the run CI
|
||||
* makes on content/bump leaves the bump commit without it and every merge is refused (405,
|
||||
* "Not all required status checks successful" — the first publish on 2026-11-24). The
|
||||
* publish job runs after `build` in the same run and records its result here instead.
|
||||
*/
|
||||
export const BUILD_CONTEXT = "CI / build (workflow_dispatch)";
|
||||
|
||||
/**
|
||||
* @param {{
|
||||
* call: (method: string, path: string, body?: unknown) => Promise<any>,
|
||||
* sha: string,
|
||||
* build?: string,
|
||||
* runUrl?: string,
|
||||
* log?: (message: string) => void,
|
||||
* }} options
|
||||
*/
|
||||
export async function merge({ call, sha, build = "success", runUrl, log = console.log }) {
|
||||
if (build !== "success" && build !== "failure") {
|
||||
log(`build ${build}: nothing to record or merge.`);
|
||||
return "skipped";
|
||||
}
|
||||
await call("POST", `/statuses/${sha}`, {
|
||||
state: build,
|
||||
context: BUILD_CONTEXT,
|
||||
description:
|
||||
build === "success" ? "build passed in this dispatched run" : "build failed — see the run",
|
||||
...(runUrl ? { target_url: runUrl } : {}),
|
||||
});
|
||||
log(`Recorded ${BUILD_CONTEXT}: ${build} on ${sha}.`);
|
||||
if (build === "failure") return "failed";
|
||||
|
||||
const pull = await findPull(call);
|
||||
if (!pull) {
|
||||
log(`No open PR from ${BRANCH}: nothing to merge.`);
|
||||
return "none";
|
||||
}
|
||||
if (pull.head?.sha !== sha) {
|
||||
log(`PR #${pull.number} has moved on to ${pull.head?.sha}; its own CI run merges it.`);
|
||||
return "moved";
|
||||
}
|
||||
if (!isAuto(pull.body)) {
|
||||
log(`PR #${pull.number} touches more than .md/.json: it waits for a review.`);
|
||||
return "review";
|
||||
}
|
||||
try {
|
||||
await call("POST", `/pulls/${pull.number}/merge`, {
|
||||
Do: "squash",
|
||||
MergeTitleField: `${pull.title} (#${pull.number})`,
|
||||
head_commit_id: sha,
|
||||
delete_branch_after_merge: true,
|
||||
});
|
||||
} catch (error) {
|
||||
// Leave a trail on the PR: the admin shows it as waiting, and a merge by hand still
|
||||
// deploys (a user's push starts CI on main).
|
||||
await call("POST", `/issues/${pull.number}/comments`, {
|
||||
body: `CI could not merge this publish: ${error.message}\n\nMerge it by hand; the push to main deploys it.`,
|
||||
}).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
log(`Merged PR #${pull.number}.`);
|
||||
await call("POST", "/actions/workflows/ci.yml/dispatches", { ref: BASE });
|
||||
log(`Dispatched ci.yml on ${BASE} (deploy).`);
|
||||
return "merged";
|
||||
}
|
||||
|
||||
async function main(command) {
|
||||
const { API, REPO, TOKEN } = process.env;
|
||||
if (!API || !REPO || !TOKEN) throw new Error("API, REPO and TOKEN must be set");
|
||||
const call = gitea({ api: API, repo: REPO, token: TOKEN });
|
||||
if (command === "open") {
|
||||
const { NEW, AUTO } = process.env;
|
||||
if (!NEW) throw new Error("NEW must be set");
|
||||
await open({ call, contentCommit: NEW, auto: AUTO === "true" });
|
||||
} else if (command === "merge") {
|
||||
const { SHA, BUILD, RUN_URL } = process.env;
|
||||
if (!SHA) throw new Error("SHA must be set");
|
||||
await merge({ call, sha: SHA, build: BUILD || "success", runUrl: RUN_URL || undefined });
|
||||
} else {
|
||||
throw new Error(`unknown command ${command ?? "(none)"}: use open or merge`);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main(process.argv[2]).catch((error) => {
|
||||
console.error(`::error::${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* Maintenance-mode triage (CONTRIBUTING.md): an issue or pull request that asks for a new
|
||||
* feature is labelled and closed with an explanation; everything else is left for the owner.
|
||||
* .github/workflows/triage.yml reads this file from the default branch through the API and runs
|
||||
* it in actions/github-script: nothing is checked out, so no pull request's code ever runs.
|
||||
*
|
||||
* Deliberately narrow: only clear signals count (the title, or a label the reporter could not
|
||||
* set by accident). A bug report that happens to say "add" is not a feature request.
|
||||
*/
|
||||
|
||||
export const LABELS = {
|
||||
/** Marks a feature request (GitHub's default label, reused). */
|
||||
feature: "enhancement",
|
||||
/** Closed because new features are out of scope while the project is in maintenance mode. */
|
||||
closed: "out-of-scope",
|
||||
/** The owner's exception: the bot leaves the item alone. */
|
||||
exception: "maintenance-exception",
|
||||
};
|
||||
|
||||
// Tested against the trimmed title. Each pattern is linear: no two quantifiers compete for the
|
||||
// same characters.
|
||||
const FEATURE_TITLES = [
|
||||
/^feat(\([^)]*\))?!?:/i, // conventional commits: "feat: …", "feat(ui)!: …"
|
||||
/^\[(feat|feature|features|enhancement|request|idea|tính năng|đề xuất)\b/iu,
|
||||
/\bfeature[\s-]+request\b/i,
|
||||
/\b(new|add|adding)(\s+a)?\s+feature\b/i,
|
||||
/(đề xuất|yêu cầu|thêm|bổ sung)\s+tính năng|tính năng mới/iu,
|
||||
];
|
||||
|
||||
/** People whose items are never closed: the owner and collaborators, and bots. */
|
||||
const TRUSTED = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
|
||||
|
||||
/**
|
||||
* What to do with one issue or pull request.
|
||||
*
|
||||
* @param {{ title: string, labels: string[], author: string, association?: string,
|
||||
* sender?: string, owner?: string, state?: string }} item
|
||||
* `association` is the author's (GitHub's author_association); `sender` is whoever
|
||||
* triggered the event, so the owner reopening or relabelling an item is never undone.
|
||||
* @returns {{ action: "close" | "none", reason: string }}
|
||||
*/
|
||||
export function decide(item) {
|
||||
const labels = item.labels.map((label) => label.toLowerCase());
|
||||
if (item.state && item.state !== "open") return { action: "none", reason: "not open" };
|
||||
if (labels.includes(LABELS.exception)) return { action: "none", reason: "owner's exception" };
|
||||
if (TRUSTED.has(item.association ?? "")) return { action: "none", reason: "trusted author" };
|
||||
if (item.author.endsWith("[bot]")) return { action: "none", reason: "bot" };
|
||||
if (item.sender && item.owner && item.sender === item.owner) {
|
||||
return { action: "none", reason: "the owner acted on it" };
|
||||
}
|
||||
if (labels.includes(LABELS.feature)) return { action: "close", reason: "labelled as a feature" };
|
||||
const title = item.title.trim();
|
||||
if (FEATURE_TITLES.some((pattern) => pattern.test(title))) {
|
||||
return { action: "close", reason: "the title asks for a feature" };
|
||||
}
|
||||
return { action: "none", reason: "not a feature request" };
|
||||
}
|
||||
|
||||
/** The comment left on a closed item, in both of the project's languages. */
|
||||
export function closingComment(kind) {
|
||||
const what = kind === "pull_request" ? "pull request" : "issue";
|
||||
return [
|
||||
"**Vietnamese / Tiếng Việt** — Cảm ơn bạn! Dự án đang ở **chế độ bảo trì**: không nhận tính năng",
|
||||
"mới. Repo chỉ nhận cập nhật dependency, vá bảo mật, nâng cấp runtime/framework, sửa lỗi (kể",
|
||||
"cả UI/UX và accessibility) và sửa lỗi ngôn ngữ. Vì vậy mục này được đóng tự động. Nếu bạn",
|
||||
"nghĩ đây là lỗi chứ không phải tính năng mới, hãy trả lời bên dưới — chủ repo sẽ xem lại.",
|
||||
"",
|
||||
`**English** — Thank you! This project is in **maintenance mode** and does not take new`,
|
||||
`features. It accepts dependency updates, security fixes, runtime/framework upgrades, bug fixes`,
|
||||
`(including UI/UX and accessibility) and language fixes, so this ${what} was closed`,
|
||||
`automatically. If you think it is a bug rather than a new feature, reply below and the owner`,
|
||||
`will take another look.`,
|
||||
"",
|
||||
"→ [CONTRIBUTING.md](https://github.com/poli0981/poli0981-dev/blob/main/CONTRIBUTING.md)",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
# SonarCloud analysis, run by the `sonarcloud` job in .github/workflows/ci.yml
|
||||
# (automatic analysis is switched off — this file is the whole configuration).
|
||||
sonar.organization=poli0981
|
||||
sonar.projectKey=poli0981_poli0981-dev
|
||||
sonar.projectName=poli0981-dev
|
||||
# Bumped with each release tag; "previous version" new-code periods start from it.
|
||||
sonar.projectVersion=2.3.0
|
||||
sonar.sourceEncoding=UTF-8
|
||||
|
||||
# .github is analyzed too: the workflow rules (pinned actions, no npx/install scripts) are
|
||||
# part of the supply-chain posture, not noise to exclude.
|
||||
sonar.sources=src,workers/widgets/src,scripts,public,.github
|
||||
sonar.tests=tests
|
||||
# *.spec.ts is the browser-driven accessibility suite (tests/a11y, `npm run test:a11y`).
|
||||
sonar.test.inclusions=tests/**/*.test.ts,tests/**/*.spec.ts
|
||||
|
||||
# Not ours or not code: the content submodule (Markdown), photos, generated declaration
|
||||
# files and the prebuilt search bundle.
|
||||
sonar.exclusions=src/content/**,src/assets/**,**/*.d.ts,public/pagefind/**
|
||||
|
||||
# Coverage comes from `npm run test:coverage` (node:test + V8 → lcov), uploaded by the
|
||||
# build job. What it does not measure, and why:
|
||||
# - scripts/** build tooling: it runs in CI as part of the build itself (gen-og,
|
||||
# check-csp-hashes, gen-notices) and in the smoke test;
|
||||
# - public/** browser-only scripts (service worker, gate client, offline mini-game);
|
||||
# - src/lib/easter.ts the DOM-only console easter egg;
|
||||
# - src/content.config.ts schema declarations, exercised by every build;
|
||||
# - config files.
|
||||
# .astro and .svelte files are not analyzed by SonarCloud at all. Keep this list in step
|
||||
# with the --test-coverage-exclude flags of `npm run test:coverage`.
|
||||
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
||||
sonar.coverage.exclusions=scripts/**,public/**,.github/**,src/lib/easter.ts,src/content.config.ts,**/*.config.js,**/*.config.mjs
|
||||
|
||||
# The vi/en dictionaries and the link table are parallel DATA by design (the same keys in
|
||||
# each locale), not duplicated logic.
|
||||
sonar.cpd.exclusions=src/i18n/vi.ts,src/i18n/en.ts,src/lib/links.ts
|
||||
@@ -4,8 +4,9 @@
|
||||
// connect-src. `type="module"` works: the CDN answers CORS with `*`, and the beacon falls
|
||||
// back to `querySelector("script[data-cf-beacon]")` when `document.currentScript` is null.
|
||||
//
|
||||
// Rendered only for production builds made by Workers Builds on main (see PUBLIC_CF_BEACON
|
||||
// in astro.config.mjs) so CI, Lighthouse and branch previews never add page views.
|
||||
// Rendered only for production builds — the deploy job in .gitea/workflows/ci.yml sets
|
||||
// PUBLIC_CF_BEACON=true (astro.config.mjs) — so CI, Lighthouse and local builds never add
|
||||
// page views.
|
||||
import { PUBLIC_CF_BEACON } from "astro:env/client";
|
||||
|
||||
const CF_BEACON_TOKEN = "349c7ecb1c304ff8985c878004df42b3"; // public site tag, not a secret
|
||||
|
||||
@@ -15,8 +15,9 @@ const { platform, size = 20, class: className } = Astro.props;
|
||||
const PATHS: Record<string, string> = {
|
||||
youtube:
|
||||
"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z",
|
||||
github:
|
||||
"M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12",
|
||||
// Generic code brackets (not a brand mark) — the self-hosted forge (Gitea) holding the code.
|
||||
gitea:
|
||||
"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z",
|
||||
discord:
|
||||
"M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z",
|
||||
x: "M14.234 10.162 22.977 0h-2.072l-7.591 8.824L7.251 0H.258l9.168 13.343L.258 24H2.33l8.016-9.318L16.749 24h6.993zm-2.837 3.299-.929-1.329L3.076 1.56h3.182l5.965 8.532.929 1.329 7.754 11.09h-3.182z",
|
||||
|
||||
@@ -54,7 +54,7 @@
|
||||
<span class="gh-verb">{verb(item)}</span>
|
||||
<a
|
||||
class="gh-repo"
|
||||
href={`https://github.com/${item.repo}`}
|
||||
href={`https://git.poli0981.dev/${item.repo}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
@@ -4,7 +4,7 @@
|
||||
import { ago, dateTime, shortSha } from "./format";
|
||||
|
||||
/** @typedef {import("@/lib/admin/audit").AuditEntry} AuditEntry */
|
||||
/** @typedef {import("@/lib/admin/github").ContentCommit} ContentCommit */
|
||||
/** @typedef {import("@/lib/admin/gitea").ContentCommit} ContentCommit */
|
||||
|
||||
/** @type {{ audit: AuditEntry[]; commits: ContentCommit[] } | null} */
|
||||
let data = $state(null);
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
{#if overview.config.version.commit}
|
||||
· commit
|
||||
<a
|
||||
href={`https://github.com/poli0981/poli0981-dev/commit/${overview.config.version.commit}`}
|
||||
href={`https://git.poli0981.dev/poli0981/poli0981-dev/commit/${overview.config.version.commit}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
@@ -119,7 +119,7 @@
|
||||
{#if drafts}· {drafts} bản nháp chưa hiện trên site{/if}
|
||||
</p>
|
||||
{:else}
|
||||
<p class="muted">Chưa đặt GITHUB_CONTENT_TOKEN — admin không đọc được repo nội dung.</p>
|
||||
<p class="muted">Chưa đặt GITEA_BOT_TOKEN — admin không đọc được repo nội dung.</p>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
@@ -138,7 +138,8 @@
|
||||
</p>
|
||||
{#if publish.phase === "deploying"}
|
||||
<p class="muted small">
|
||||
Thường mất 1–3 phút sau khi merge. Lâu hơn: kiểm tra Workers Builds trên Cloudflare.
|
||||
Thường mất vài phút sau khi merge (job deploy trong CI, runner trên máy). Lâu hơn: xem
|
||||
tab Actions trên Gitea — máy tắt thì job đợi đến khi bật lại.
|
||||
</p>
|
||||
{/if}
|
||||
{#if publish.phase === "failed" && publish.run}
|
||||
@@ -165,7 +166,7 @@
|
||||
Steam {overview.widgets.steam}
|
||||
</span>
|
||||
<span class="pill" data-tone={tone(overview.widgets.gh)}>
|
||||
GitHub {overview.widgets.gh}
|
||||
Gitea {overview.widgets.gh}
|
||||
</span>
|
||||
</p>
|
||||
<p class="muted small" title={dateTime(overview.widgets.lastRun)}>
|
||||
@@ -191,11 +192,6 @@
|
||||
: ""}{/each}
|
||||
</p>
|
||||
{/if}
|
||||
{#if overview.config.singleToken}
|
||||
<p class="small warn">
|
||||
Xuất bản đang dùng chung token nội dung — nên tạo GITHUB_PUBLISH_TOKEN riêng.
|
||||
</p>
|
||||
{/if}
|
||||
<p class="small"><a href="/admin/security/">Danh sách chặn IP →</a></p>
|
||||
</section>
|
||||
</div>
|
||||
@@ -248,9 +244,6 @@
|
||||
.small {
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.warn {
|
||||
color: var(--warn);
|
||||
}
|
||||
p {
|
||||
margin: 0.4rem 0;
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@
|
||||
} catch (error) {
|
||||
toast(
|
||||
error instanceof ApiError && error.data.error === "conflict"
|
||||
? "File đã bị sửa ở nơi khác (vd. GitHub). Bản đang viết vẫn còn trên máy — tải lại trang rồi chọn “Khôi phục”."
|
||||
? "File đã bị sửa ở nơi khác (vd. trên Gitea). Bản đang viết vẫn còn trên máy — tải lại trang rồi chọn “Khôi phục”."
|
||||
: describeError(error),
|
||||
"error",
|
||||
);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
/** @typedef {{ number: number; url: string; autoMerge: boolean; checks: string | null }} PullRequest */
|
||||
/** @typedef {import("@/lib/admin/publish-phase").PublishPhase} Phase */
|
||||
/** @typedef {{ contentHead: string; published: string; live: string | null; phase: Phase; pr: PullRequest | null; run: { status: string; conclusion: string | null; url: string } | null; singleToken?: boolean }} Status */
|
||||
/** @typedef {{ contentHead: string; published: string; live: string | null; phase: Phase; pr: PullRequest | null; run: { status: string; conclusion: string | null; url: string } | null }} Status */
|
||||
|
||||
/** @type {Status | null} */
|
||||
let status = $state(null);
|
||||
@@ -81,15 +81,6 @@
|
||||
{PHASE_TEXT[status.phase].label}
|
||||
{#if status.phase === "live" && status.live}({short(status.live)}){/if}
|
||||
</span>
|
||||
{#if status.singleToken}
|
||||
<a
|
||||
class="warn"
|
||||
href="/admin/security/"
|
||||
title="Xuất bản đang dùng chung token nội dung — xem trang Bảo mật"
|
||||
>
|
||||
⚠<span class="sr-only">Xuất bản đang dùng chung token nội dung</span>
|
||||
</a>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="primary"
|
||||
@@ -123,9 +114,6 @@
|
||||
.state[data-tone="err"] {
|
||||
color: var(--err);
|
||||
}
|
||||
.warn {
|
||||
color: var(--warn);
|
||||
}
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
@@ -22,9 +22,8 @@
|
||||
/** What each secret is for, so a missing one says what stops working. */
|
||||
/** @type {Record<string, string>} */
|
||||
const SECRET_ROLES = {
|
||||
GITHUB_CONTENT_TOKEN: "lưu nội dung từ admin",
|
||||
GITHUB_PUBLISH_TOKEN: "xuất bản (token riêng, chỉ quyền Actions)",
|
||||
GITHUB_ISSUES_TOKEN: "báo lỗi → issue GitHub riêng tư",
|
||||
GITEA_BOT_TOKEN: "lưu nội dung và xuất bản (bot poli0981-bot trên Gitea)",
|
||||
GITLAB_ISSUES_TOKEN: "báo lỗi → issue bảo mật trên GitLab",
|
||||
DISCORD_WEBHOOK_BUG: "báo lỗi → Discord",
|
||||
TURNSTILE_SECRET: "Turnstile (cổng + báo lỗi)",
|
||||
GATE_SECRET: "ký cookie của cổng Turnstile",
|
||||
@@ -176,13 +175,6 @@
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if config.singleToken}
|
||||
<p class="small warn">
|
||||
Xuất bản đang dùng GITHUB_CONTENT_TOKEN, nghĩa là token đó có quyền trên repo site. Tạo
|
||||
GITHUB_PUBLISH_TOKEN (chỉ Actions: Read and write trên poli0981-dev) rồi thu hẹp token
|
||||
nội dung về repo content.
|
||||
</p>
|
||||
{/if}
|
||||
<p class="muted small">
|
||||
Giới hạn tốc độ mỗi IP / phút: báo lỗi 5, cổng 30, admin 120, API khác 120
|
||||
(wrangler.jsonc).
|
||||
@@ -247,7 +239,4 @@
|
||||
.small {
|
||||
font-size: var(--text-meta);
|
||||
}
|
||||
.warn {
|
||||
color: var(--warn);
|
||||
}
|
||||
</style>
|
||||
@@ -81,9 +81,8 @@ export function describeError(error: unknown): string {
|
||||
const fields = (error.data.fields as { field: string }[] | undefined) ?? [];
|
||||
return `Trường chưa hợp lệ: ${fields.map((f) => f.field).join(", ")}`;
|
||||
}
|
||||
if (code === "github_permission") {
|
||||
const needs = error.data.needs ? ` (GitHub cần: ${String(error.data.needs)})` : "";
|
||||
return `Token GitHub thiếu quyền${needs}. Lưu bài cần GITHUB_CONTENT_TOKEN có Contents: Read and write trên poli0981/content; Xuất bản cần GITHUB_PUBLISH_TOKEN có Actions: Read and write trên poli0981/poli0981-dev.`;
|
||||
if (code === "gitea_permission") {
|
||||
return "Token Gitea bị từ chối. GITEA_BOT_TOKEN cần quyền write:repository, và bot poli0981-bot phải là cộng tác viên (Write) trên poli0981/content và poli0981/poli0981-dev.";
|
||||
}
|
||||
if (error.status === 409)
|
||||
return "Xung đột: nội dung đã thay đổi ở nơi khác (hoặc ảnh đang được dùng).";
|
||||
|
||||
@@ -53,14 +53,15 @@ const timeline: Record<Locale, [string, string][]> = {
|
||||
{
|
||||
vi ? (
|
||||
<>
|
||||
Mình viết code, thích công cụ tối giản và bền. Dự án mở nằm trên GitHub (
|
||||
<code>poli0981</code>). Ưu tiên: ít phụ thuộc, dễ bảo trì, chi phí gần bằng không.
|
||||
Mình viết code, thích công cụ tối giản và bền. Dự án mở nằm trên Gitea của mình (
|
||||
<code>git.poli0981.dev</code>). Ưu tiên: ít phụ thuộc, dễ bảo trì, chi phí gần bằng
|
||||
không.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
I write code and like tools that are minimal and durable. Open projects live on
|
||||
GitHub (<code>poli0981</code>). Priorities: few dependencies, easy to maintain,
|
||||
near-zero cost.
|
||||
I write code and like tools that are minimal and durable. Open projects live on my
|
||||
own Gitea (<code>git.poli0981.dev</code>). Priorities: few dependencies, easy to
|
||||
maintain, near-zero cost.
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import BaseLayout from "@/layouts/BaseLayout.astro";
|
||||
import Waveline from "@/components/Waveline.svelte";
|
||||
import ProjectCard from "@/components/ProjectCard.astro";
|
||||
import WidgetGitHub from "@/components/WidgetGitHub.svelte";
|
||||
import WidgetGitea from "@/components/WidgetGitea.svelte";
|
||||
import SocialIcon from "@/components/SocialIcon.astro";
|
||||
import { getProjects } from "@/lib/collections";
|
||||
import { getWidgetSnapshot } from "@/lib/widgets";
|
||||
@@ -63,7 +63,7 @@ function relFor(href: string, me?: boolean): string | undefined {
|
||||
<a class="more" href={sectionPath("dev", locale, "uses")}>{t.dev.gearCta} →</a>
|
||||
</section>
|
||||
|
||||
<WidgetGitHub client:idle labels={t.gh} {locale} initial={widgets} />
|
||||
<WidgetGitea client:idle labels={t.gh} {locale} initial={widgets} />
|
||||
|
||||
<section class="page block">
|
||||
<h2 class="block-title">{t.dev.connect}</h2>
|
||||
|
||||
+1
-1
Submodule src/content updated: 98f7692ff8...1a846923a9.
+1
-1
@@ -155,7 +155,7 @@ const en: UIStrings = {
|
||||
languages: "Languages & frameworks",
|
||||
},
|
||||
gh: {
|
||||
title: "GitHub activity",
|
||||
title: "Gitea activity",
|
||||
push: "Pushed to",
|
||||
release: "Released in",
|
||||
},
|
||||
|
||||
+1
-1
@@ -153,7 +153,7 @@ const vi = {
|
||||
languages: "Ngôn ngữ & framework",
|
||||
},
|
||||
gh: {
|
||||
title: "Hoạt động GitHub",
|
||||
title: "Hoạt động trên Gitea",
|
||||
push: "Đẩy lên",
|
||||
release: "Phát hành",
|
||||
},
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN } from "astro:env/server";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { log } from "../log";
|
||||
import { recordAudit } from "./audit";
|
||||
import { dispatchPublish } from "./github";
|
||||
import { dispatchPublish } from "./gitea";
|
||||
|
||||
// Every admin save or delete publishes by itself: it starts .github/workflows/content-bump.yml,
|
||||
// which points src/content at the content repo's main, and CI + auto-merge + Workers Builds
|
||||
// take it live. Saves in quick succession don't pile up — the workflow's concurrency group
|
||||
// Every admin save or delete publishes by itself: it starts .gitea/workflows/content-bump.yml,
|
||||
// which points src/content at the content repo's main, and CI merges and deploys it. Saves in quick succession don't pile up — the workflow's concurrency group
|
||||
// keeps one run going and one waiting, and the waiting one always reads the newest main.
|
||||
|
||||
/** The token that may start the publish workflow (falls back to the content token). */
|
||||
export const publishToken = (): string | undefined => GITHUB_PUBLISH_TOKEN ?? GITHUB_CONTENT_TOKEN;
|
||||
|
||||
/** "queued" when the workflow was started, "failed" when it could not be (the save stands). */
|
||||
export type AutoPublish = "queued" | "failed";
|
||||
|
||||
@@ -21,7 +17,7 @@ export type AutoPublish = "queued" | "failed";
|
||||
* of turning a good save into an error.
|
||||
*/
|
||||
export async function autoPublish(admin: string, commit: string): Promise<AutoPublish> {
|
||||
const token = publishToken();
|
||||
const token = GITEA_BOT_TOKEN;
|
||||
if (!token) return "failed";
|
||||
try {
|
||||
await dispatchPublish(token);
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// Gitea access for the admin (git.poli0981.dev, where both repositories live since the move
|
||||
// from GitHub). One token, GITEA_BOT_TOKEN: a `write:repository` token of the bot user
|
||||
// `poli0981-bot`, a Write collaborator on exactly poli0981/content (saves) and
|
||||
// poli0981/poli0981-dev (to start the publish workflow) — the migration's decision D12. A
|
||||
// Gitea token's scopes apply to every repository its user can reach, so the limit is the
|
||||
// bot's collaborator list, not the token. It never pushes to the site repo: publishing goes
|
||||
// through .gitea/workflows/content-bump.yml. Both repositories are public, so the reads
|
||||
// would work without it; the admin sends it anyway, as one identity for everything.
|
||||
|
||||
const API = "https://git.poli0981.dev/api/v1";
|
||||
const CONTENT_REPO = "/repos/poli0981/content";
|
||||
const SITE_REPO = "/repos/poli0981/poli0981-dev";
|
||||
const BRANCH = "main";
|
||||
/** The status Gitea Actions gives ci.yml's build job: `<workflow> / <job> (<event>)`. */
|
||||
const BUILD_CHECK = /^CI \/ build \(/;
|
||||
/** The publish PR's body says whether CI merges it (scripts/content-publish.mjs). */
|
||||
const AUTO_MARK = "<!-- publish: auto -->";
|
||||
|
||||
export class GiteaError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** The content changed under us since the editor loaded it. */
|
||||
export class ConflictError extends Error {}
|
||||
|
||||
/** A Gitea call that hangs must not hold the admin request (or the isolate) open. */
|
||||
const TIMEOUT_MS = 15_000;
|
||||
|
||||
async function request<T>(token: string, path: string, init: RequestInit = {}): Promise<T> {
|
||||
const res = await fetch(`${API}${path}`, {
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
...init,
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
authorization: `token ${token}`,
|
||||
"user-agent": "poli0981-admin",
|
||||
...(init.body ? { "content-type": "application/json" } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.text().catch(() => "");
|
||||
throw new GiteaError(
|
||||
`Gitea ${init.method ?? "GET"} ${path} → ${res.status} ${detail.slice(0, 300)}`,
|
||||
res.status,
|
||||
);
|
||||
}
|
||||
const text = await res.text();
|
||||
return (text ? JSON.parse(text) : null) as T;
|
||||
}
|
||||
|
||||
const decodeBase64 = (data: string): Uint8Array =>
|
||||
Uint8Array.from(atob(data.replace(/\n/g, "")), (c) => c.charCodeAt(0));
|
||||
|
||||
function encodeBase64(text: string): string {
|
||||
let binary = "";
|
||||
for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
/** UTF-8 text, or null for a file that isn't (an image someone committed by hand). */
|
||||
function decodeText(data: string): string | null {
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true }).decode(decodeBase64(data));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RepoFile {
|
||||
path: string;
|
||||
/** Git blob sha — the optimistic-concurrency token for edits. */
|
||||
sha: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface ContentsEntry {
|
||||
path: string;
|
||||
sha: string;
|
||||
type: string;
|
||||
content?: string | null;
|
||||
encoding?: string | null;
|
||||
}
|
||||
|
||||
/** Larger files are not content the admin edits; skipping them keeps the read small. */
|
||||
const MAX_TEXT_BYTES = 1024 * 1024;
|
||||
/** Paths per batch read: Gitea caps list answers at MAX_RESPONSE_ITEMS (50 by default). */
|
||||
const BATCH = 50;
|
||||
|
||||
/**
|
||||
* Every text file of the content repo's main branch — or of one commit, `at` — plus the
|
||||
* commit it was read at: the tree in one request, then the files' contents in batches.
|
||||
*/
|
||||
export async function listContentFiles(
|
||||
token: string,
|
||||
at?: string,
|
||||
): Promise<{ head: string; files: RepoFile[] }> {
|
||||
const head =
|
||||
at ??
|
||||
(await request<{ commit: { id: string } }>(token, `${CONTENT_REPO}/branches/${BRANCH}`)).commit
|
||||
.id;
|
||||
|
||||
const tree: { path: string; type: string; size?: number }[] = [];
|
||||
try {
|
||||
// 1000 entries a page, Gitea's most; `truncated` says another page follows.
|
||||
for (let page = 1; page <= 20; page++) {
|
||||
const answer = await request<{
|
||||
tree: { path: string; type: string; size?: number }[] | null;
|
||||
truncated: boolean;
|
||||
}>(token, `${CONTENT_REPO}/git/trees/${head}?recursive=true&per_page=1000&page=${page}`);
|
||||
tree.push(...(answer.tree ?? []));
|
||||
if (!answer.truncated) break;
|
||||
}
|
||||
} catch (error) {
|
||||
// A commit the repo doesn't have (yet) has no tree: report it as empty, not as a crash.
|
||||
if (at && error instanceof GiteaError && (error.status === 404 || error.status === 422)) {
|
||||
return { head, files: [] };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const paths = tree
|
||||
.filter((entry) => entry.type === "blob" && (entry.size ?? 0) <= MAX_TEXT_BYTES)
|
||||
.map((entry) => entry.path);
|
||||
const files: RepoFile[] = [];
|
||||
for (let i = 0; i < paths.length; i += BATCH) {
|
||||
const entries = await request<(ContentsEntry | null)[]>(
|
||||
token,
|
||||
`${CONTENT_REPO}/file-contents?ref=${head}`,
|
||||
{ method: "POST", body: JSON.stringify({ files: paths.slice(i, i + BATCH) }) },
|
||||
);
|
||||
for (const entry of entries) {
|
||||
if (!entry || entry.type !== "file" || typeof entry.content !== "string") continue;
|
||||
const text = decodeText(entry.content);
|
||||
if (text !== null) files.push({ path: entry.path, sha: entry.sha, text });
|
||||
}
|
||||
}
|
||||
return { head, files };
|
||||
}
|
||||
|
||||
/** One file of the content repo at main, or null if it doesn't exist. */
|
||||
export async function readContentFile(token: string, path: string): Promise<RepoFile | null> {
|
||||
try {
|
||||
const file = await request<ContentsEntry>(
|
||||
token,
|
||||
`${CONTENT_REPO}/contents/${encodeURI(path)}?ref=${BRANCH}`,
|
||||
);
|
||||
if (file.type !== "file" || typeof file.content !== "string") return null;
|
||||
const text = decodeText(file.content);
|
||||
return text === null ? null : { path, sha: file.sha, text };
|
||||
} catch (error) {
|
||||
if (error instanceof GiteaError && error.status === 404) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export interface FileChange {
|
||||
path: string;
|
||||
/** New text, or null to delete the file. */
|
||||
text: string | null;
|
||||
/** Blob sha the editor started from; null = the file must not exist yet. */
|
||||
expectSha: string | null;
|
||||
}
|
||||
|
||||
/** What Gitea answers when a file isn't where the commit expects it (422, or 404 to delete). */
|
||||
const STALE = /sha does not match|already exists|does not exist|not exist/i;
|
||||
|
||||
/**
|
||||
* Commit several files to the content repo's main branch in one commit (Gitea's
|
||||
* "change files" call). Refuses with ConflictError when any file isn't at the sha the
|
||||
* caller expects: checked here first for a clear message, and again by Gitea itself, which
|
||||
* compares each file's sha as it commits — the lock against a save racing another.
|
||||
*/
|
||||
export async function commitContent(
|
||||
token: string,
|
||||
message: string,
|
||||
changes: FileChange[],
|
||||
): Promise<string> {
|
||||
for (const change of changes) {
|
||||
const current = await readContentFile(token, change.path);
|
||||
if ((current?.sha ?? null) !== change.expectSha) {
|
||||
throw new ConflictError(`${change.path} changed since it was opened`);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const result = await request<{ commit: { sha: string } }>(token, `${CONTENT_REPO}/contents`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
branch: BRANCH,
|
||||
message,
|
||||
files: changes.map((change) =>
|
||||
change.text === null
|
||||
? { operation: "delete", path: change.path, sha: change.expectSha }
|
||||
: change.expectSha === null
|
||||
? { operation: "create", path: change.path, content: encodeBase64(change.text) }
|
||||
: {
|
||||
operation: "update",
|
||||
path: change.path,
|
||||
sha: change.expectSha,
|
||||
content: encodeBase64(change.text),
|
||||
},
|
||||
),
|
||||
}),
|
||||
});
|
||||
return result.commit.sha;
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof GiteaError &&
|
||||
(error.status === 409 || error.status === 422 || error.status === 404) &&
|
||||
STALE.test(error.message)
|
||||
) {
|
||||
throw new ConflictError("the content changed while saving");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export interface PublishStatus {
|
||||
contentHead: string;
|
||||
/**
|
||||
* The content commit the site repo's main points at (the src/content gitlink): merged, but
|
||||
* live only once the deploy job has deployed that main — compare with versionInfo().content.
|
||||
*/
|
||||
published: string;
|
||||
pr: {
|
||||
number: number;
|
||||
url: string;
|
||||
/** CI merges it by itself (Markdown/JSON only), or it waits for a review. */
|
||||
autoMerge: boolean;
|
||||
checks: "pending" | "success" | "failure" | null;
|
||||
} | null;
|
||||
run: { status: string; conclusion: string | null; url: string } | null;
|
||||
}
|
||||
|
||||
interface Pull {
|
||||
number: number;
|
||||
html_url: string;
|
||||
body: string | null;
|
||||
head: { ref: string; sha: string };
|
||||
base: { ref: string };
|
||||
}
|
||||
|
||||
export async function publishStatus(token: string): Promise<PublishStatus> {
|
||||
const [contentRef, gitlink, pulls, runs] = await Promise.all([
|
||||
request<{ commit: { id: string } }>(token, `${CONTENT_REPO}/branches/${BRANCH}`),
|
||||
request<{ sha: string }>(token, `${SITE_REPO}/contents/src/content?ref=${BRANCH}`),
|
||||
request<Pull[]>(token, `${SITE_REPO}/pulls?state=open&limit=50`),
|
||||
request<{ workflow_runs?: { status: string; conclusion: string | null; html_url: string }[] }>(
|
||||
token,
|
||||
`${SITE_REPO}/actions/workflows/content-bump.yml/runs?limit=1`,
|
||||
),
|
||||
]);
|
||||
|
||||
let pr: PublishStatus["pr"] = null;
|
||||
const open = pulls.find((p) => p.head.ref === "content/bump" && p.base.ref === BRANCH);
|
||||
if (open) {
|
||||
const combined = await request<{ statuses: { context: string; status: string }[] | null }>(
|
||||
token,
|
||||
`${SITE_REPO}/commits/${open.head.sha}/status`,
|
||||
);
|
||||
const build = (combined.statuses ?? []).find((s) => BUILD_CHECK.test(s.context));
|
||||
pr = {
|
||||
number: open.number,
|
||||
url: open.html_url,
|
||||
autoMerge: (open.body ?? "").includes(AUTO_MARK),
|
||||
checks: !build
|
||||
? null
|
||||
: build.status === "pending"
|
||||
? "pending"
|
||||
: build.status === "success"
|
||||
? "success"
|
||||
: "failure",
|
||||
};
|
||||
}
|
||||
const last = runs.workflow_runs?.[0];
|
||||
return {
|
||||
contentHead: contentRef.commit.id,
|
||||
published: gitlink.sha,
|
||||
pr,
|
||||
run: last ? { status: last.status, conclusion: last.conclusion, url: last.html_url } : null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ContentCommit {
|
||||
sha: string;
|
||||
/** First line of the message. */
|
||||
message: string;
|
||||
author: string;
|
||||
date: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/** The latest commits on the content repo's main: admin saves and hand edits alike. */
|
||||
export async function recentContentCommits(token: string, count = 20): Promise<ContentCommit[]> {
|
||||
const commits = await request<
|
||||
{
|
||||
sha: string;
|
||||
html_url: string;
|
||||
commit: { message: string; author: { name: string; date: string } | null };
|
||||
}[]
|
||||
>(
|
||||
token,
|
||||
`${CONTENT_REPO}/commits?sha=${BRANCH}&limit=${count}&stat=false&verification=false&files=false`,
|
||||
);
|
||||
return commits.map((c) => ({
|
||||
sha: c.sha,
|
||||
message: c.commit.message.split("\n")[0],
|
||||
author: c.commit.author?.name ?? "",
|
||||
date: c.commit.author?.date ?? "",
|
||||
url: c.html_url,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Start the publish workflow (bump the submodule PR on the site repo). */
|
||||
export async function dispatchPublish(token: string): Promise<void> {
|
||||
await request(token, `${SITE_REPO}/actions/workflows/content-bump.yml/dispatches`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ref: BRANCH }),
|
||||
});
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
// GitHub access for the admin, with two fine-grained tokens — a fine-grained token's
|
||||
// permissions apply to EVERY repository it covers, so one token can't be "write here,
|
||||
// dispatch only there":
|
||||
// - GITHUB_CONTENT_TOKEN: only poli0981/content, Contents read & write (saves);
|
||||
// - GITHUB_PUBLISH_TOKEN: only poli0981/poli0981-dev, Actions read & write (dispatches
|
||||
// .github/workflows/content-bump.yml). It has no Contents permission, so even leaked
|
||||
// it can't push code here. Status reads need nothing: both repos are public.
|
||||
|
||||
const API = "https://api.github.com";
|
||||
const CONTENT_REPO = { owner: "poli0981", name: "content" } as const;
|
||||
const SITE_REPO = { owner: "poli0981", name: "poli0981-dev" } as const;
|
||||
const BRANCH = "main";
|
||||
|
||||
export class GitHubError extends Error {
|
||||
readonly status: number;
|
||||
/** What GitHub says the call needed (X-Accepted-GitHub-Permissions), e.g. "contents=write". */
|
||||
readonly needs: string | null;
|
||||
|
||||
constructor(message: string, status: number, needs: string | null = null) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.needs = needs;
|
||||
}
|
||||
}
|
||||
|
||||
/** The content changed under us since the editor loaded it. */
|
||||
export class ConflictError extends Error {}
|
||||
|
||||
/** A GitHub call that hangs must not hold the admin request (or the isolate) open. */
|
||||
const TIMEOUT_MS = 15_000;
|
||||
|
||||
async function request<T>(token: string, path: string, init: RequestInit = {}): Promise<T> {
|
||||
const res = await fetch(`${API}${path}`, {
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
...init,
|
||||
headers: {
|
||||
accept: "application/vnd.github+json",
|
||||
authorization: `Bearer ${token}`,
|
||||
"x-github-api-version": "2022-11-28",
|
||||
"user-agent": "poli0981-admin",
|
||||
...(init.body ? { "content-type": "application/json" } : {}),
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const detail = await res.text().catch(() => "");
|
||||
throw new GitHubError(
|
||||
`GitHub ${init.method ?? "GET"} ${path} → ${res.status} ${detail.slice(0, 300)}`,
|
||||
res.status,
|
||||
res.headers.get("x-accepted-github-permissions"),
|
||||
);
|
||||
}
|
||||
return (res.status === 204 ? null : await res.json()) as T;
|
||||
}
|
||||
|
||||
async function graphql<T>(
|
||||
token: string,
|
||||
query: string,
|
||||
variables: Record<string, unknown>,
|
||||
): Promise<T> {
|
||||
const data = await request<{ data?: T; errors?: { message: string }[] }>(token, "/graphql", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ query, variables }),
|
||||
});
|
||||
if (data.errors?.length || !data.data) {
|
||||
throw new GitHubError(`GitHub GraphQL: ${data.errors?.map((e) => e.message).join("; ")}`, 502);
|
||||
}
|
||||
return data.data;
|
||||
}
|
||||
|
||||
export interface RepoFile {
|
||||
path: string;
|
||||
/** Git blob sha — the optimistic-concurrency token for edits. */
|
||||
sha: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface TreeEntry {
|
||||
path: string;
|
||||
type: string;
|
||||
object: { oid?: string; text?: string | null; entries?: TreeEntry[] } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every text file of the content repo's main branch — or of one commit, `at` — in ONE
|
||||
* GraphQL request (three directory levels: collection/series/file), plus the commit it was
|
||||
* read at.
|
||||
*/
|
||||
export async function listContentFiles(
|
||||
token: string,
|
||||
at?: string,
|
||||
): Promise<{ head: string; files: RepoFile[] }> {
|
||||
const blob = "... on Blob { oid text }";
|
||||
const level = (inner: string) => `entries { path type object { ${blob} ${inner} } }`;
|
||||
const query = `query($owner: String!, $name: String!, $expr: String!) {
|
||||
repository(owner: $owner, name: $name) {
|
||||
ref(qualifiedName: "refs/heads/${BRANCH}") { target { oid } }
|
||||
object(expression: $expr) { ... on Tree {
|
||||
${level(`... on Tree { ${level(`... on Tree { ${level("")} }`)} }`)}
|
||||
} }
|
||||
}
|
||||
}`;
|
||||
const data = await graphql<{
|
||||
repository: { ref: { target: { oid: string } }; object: { entries: TreeEntry[] } | null };
|
||||
}>(token, query, { ...CONTENT_REPO, expr: `${at ?? BRANCH}:` });
|
||||
// A commit the repo doesn't have (yet) has no tree: report it as empty, not as a crash.
|
||||
if (!data.repository.object) return { head: at ?? data.repository.ref.target.oid, files: [] };
|
||||
|
||||
const files: RepoFile[] = [];
|
||||
const walk = (entries: TreeEntry[]) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.type === "tree" && entry.object?.entries) walk(entry.object.entries);
|
||||
else if (
|
||||
entry.type === "blob" &&
|
||||
entry.object?.oid &&
|
||||
typeof entry.object.text === "string"
|
||||
) {
|
||||
files.push({ path: entry.path, sha: entry.object.oid, text: entry.object.text });
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(data.repository.object.entries);
|
||||
return { head: at ?? data.repository.ref.target.oid, files };
|
||||
}
|
||||
|
||||
/** One file of the content repo at main, or null if it doesn't exist. */
|
||||
export async function readContentFile(token: string, path: string): Promise<RepoFile | null> {
|
||||
try {
|
||||
const file = await request<{ sha: string; content: string; encoding: string }>(
|
||||
token,
|
||||
`/repos/${CONTENT_REPO.owner}/${CONTENT_REPO.name}/contents/${encodeURI(path)}?ref=${BRANCH}`,
|
||||
);
|
||||
const bytes = Uint8Array.from(atob(file.content.replace(/\n/g, "")), (c) => c.charCodeAt(0));
|
||||
return { path, sha: file.sha, text: new TextDecoder().decode(bytes) };
|
||||
} catch (error) {
|
||||
if (error instanceof GitHubError && error.status === 404) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export interface FileChange {
|
||||
path: string;
|
||||
/** New text, or null to delete the file. */
|
||||
text: string | null;
|
||||
/** Blob sha the editor started from; null = the file must not exist yet. */
|
||||
expectSha: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commit several files to the content repo's main branch atomically (Git Data API:
|
||||
* tree → commit → fast-forward ref). Refuses with ConflictError when any file isn't at
|
||||
* the sha the caller expects; retries once if main moved between read and update.
|
||||
*/
|
||||
export async function commitContent(
|
||||
token: string,
|
||||
message: string,
|
||||
changes: FileChange[],
|
||||
): Promise<string> {
|
||||
const repo = `/repos/${CONTENT_REPO.owner}/${CONTENT_REPO.name}`;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const ref = await request<{ object: { sha: string } }>(
|
||||
token,
|
||||
`${repo}/git/ref/heads/${BRANCH}`,
|
||||
);
|
||||
const head = ref.object.sha;
|
||||
const commit = await request<{ tree: { sha: string } }>(token, `${repo}/git/commits/${head}`);
|
||||
|
||||
for (const change of changes) {
|
||||
const current = await readContentFile(token, change.path);
|
||||
if ((current?.sha ?? null) !== change.expectSha) {
|
||||
throw new ConflictError(`${change.path} changed since it was opened`);
|
||||
}
|
||||
}
|
||||
|
||||
const tree = await request<{ sha: string }>(token, `${repo}/git/trees`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
base_tree: commit.tree.sha,
|
||||
tree: changes.map((change) =>
|
||||
change.text === null
|
||||
? { path: change.path, mode: "100644", type: "blob", sha: null }
|
||||
: { path: change.path, mode: "100644", type: "blob", content: change.text },
|
||||
),
|
||||
}),
|
||||
});
|
||||
const created = await request<{ sha: string }>(token, `${repo}/git/commits`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ message, tree: tree.sha, parents: [head] }),
|
||||
});
|
||||
try {
|
||||
await request(token, `${repo}/git/refs/heads/${BRANCH}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ sha: created.sha, force: false }),
|
||||
});
|
||||
return created.sha;
|
||||
} catch (error) {
|
||||
// 422 = not a fast-forward: someone pushed in between. Re-read and try once more.
|
||||
if (!(error instanceof GitHubError && error.status === 422) || attempt === 1) throw error;
|
||||
}
|
||||
}
|
||||
throw new GitHubError("unreachable", 500);
|
||||
}
|
||||
|
||||
export interface PublishStatus {
|
||||
contentHead: string;
|
||||
/**
|
||||
* The content commit the site repo's main points at (the src/content gitlink): merged, but
|
||||
* live only once Workers Builds has deployed that main — compare with versionInfo().content.
|
||||
*/
|
||||
published: string;
|
||||
pr: {
|
||||
number: number;
|
||||
url: string;
|
||||
autoMerge: boolean;
|
||||
checks: "pending" | "success" | "failure" | null;
|
||||
} | null;
|
||||
run: { status: string; conclusion: string | null; url: string } | null;
|
||||
}
|
||||
|
||||
export async function publishStatus(token: string): Promise<PublishStatus> {
|
||||
const site = `/repos/${SITE_REPO.owner}/${SITE_REPO.name}`;
|
||||
const [contentRef, gitlink, pulls, runs] = await Promise.all([
|
||||
request<{ object: { sha: string } }>(
|
||||
token,
|
||||
`/repos/${CONTENT_REPO.owner}/${CONTENT_REPO.name}/git/ref/heads/${BRANCH}`,
|
||||
),
|
||||
request<{ sha: string }>(token, `${site}/contents/src/content?ref=${BRANCH}`),
|
||||
request<{ number: number; html_url: string; auto_merge: unknown; head: { sha: string } }[]>(
|
||||
token,
|
||||
`${site}/pulls?state=open&head=${SITE_REPO.owner}:content/bump`,
|
||||
),
|
||||
request<{ workflow_runs: { status: string; conclusion: string | null; html_url: string }[] }>(
|
||||
token,
|
||||
`${site}/actions/workflows/content-bump.yml/runs?per_page=1`,
|
||||
),
|
||||
]);
|
||||
|
||||
let pr: PublishStatus["pr"] = null;
|
||||
const open = pulls[0];
|
||||
if (open) {
|
||||
const checks = await request<{
|
||||
check_runs: { name: string; status: string; conclusion: string | null }[];
|
||||
}>(token, `${site}/commits/${open.head.sha}/check-runs?check_name=build`);
|
||||
const build = checks.check_runs[0];
|
||||
pr = {
|
||||
number: open.number,
|
||||
url: open.html_url,
|
||||
autoMerge: Boolean(open.auto_merge),
|
||||
checks: !build
|
||||
? null
|
||||
: build.status !== "completed"
|
||||
? "pending"
|
||||
: build.conclusion === "success"
|
||||
? "success"
|
||||
: "failure",
|
||||
};
|
||||
}
|
||||
const last = runs.workflow_runs[0];
|
||||
return {
|
||||
contentHead: contentRef.object.sha,
|
||||
published: gitlink.sha,
|
||||
pr,
|
||||
run: last ? { status: last.status, conclusion: last.conclusion, url: last.html_url } : null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ContentCommit {
|
||||
sha: string;
|
||||
/** First line of the message. */
|
||||
message: string;
|
||||
author: string;
|
||||
date: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/** The latest commits on the content repo's main: admin saves and hand edits alike. */
|
||||
export async function recentContentCommits(token: string, count = 20): Promise<ContentCommit[]> {
|
||||
const commits = await request<
|
||||
{
|
||||
sha: string;
|
||||
html_url: string;
|
||||
commit: { message: string; author: { name: string; date: string } | null };
|
||||
}[]
|
||||
>(
|
||||
token,
|
||||
`/repos/${CONTENT_REPO.owner}/${CONTENT_REPO.name}/commits?sha=${BRANCH}&per_page=${count}`,
|
||||
);
|
||||
return commits.map((c) => ({
|
||||
sha: c.sha,
|
||||
message: c.commit.message.split("\n")[0],
|
||||
author: c.commit.author?.name ?? "",
|
||||
date: c.commit.author?.date ?? "",
|
||||
url: c.html_url,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Start the publish workflow (bump the submodule PR on the site repo). */
|
||||
export async function dispatchPublish(token: string): Promise<void> {
|
||||
await request(
|
||||
token,
|
||||
`/repos/${SITE_REPO.owner}/${SITE_REPO.name}/actions/workflows/content-bump.yml/dispatches`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ ref: BRANCH }),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { BodyTooLargeError, isJsonRequest, readJsonLimited } from "../body";
|
||||
import { log } from "../log";
|
||||
import { ConflictError, GitHubError } from "./github";
|
||||
import { ConflictError, GiteaError } from "./gitea";
|
||||
|
||||
/** Largest JSON body any admin endpoint accepts (a long post is ~50 KB of Markdown). */
|
||||
const MAX_ADMIN_JSON_BYTES = 512 * 1024;
|
||||
@@ -18,13 +18,14 @@ export function errorResponse(error: unknown): Response {
|
||||
if (error instanceof BodyTooLargeError) return json({ error: "too_large" }, 413);
|
||||
if (error instanceof ConflictError)
|
||||
return json({ error: "conflict", message: error.message }, 409);
|
||||
if (error instanceof GitHubError) {
|
||||
log.error("admin.github_failed", { status: error.status, needs: error.needs, error });
|
||||
// 401/403 from a fine-grained token = missing permission or repo not selected.
|
||||
if (error instanceof GiteaError) {
|
||||
log.error("admin.gitea_failed", { status: error.status, error });
|
||||
// 401/403 = a wrong or expired token, a scope below write:repository, or a bot that is
|
||||
// not a Write collaborator on the repository.
|
||||
if (error.status === 401 || error.status === 403) {
|
||||
return json({ error: "github_permission", needs: error.needs, message: error.message }, 502);
|
||||
return json({ error: "gitea_permission", message: error.message }, 502);
|
||||
}
|
||||
return json({ error: "github", message: error.message }, 502);
|
||||
return json({ error: "gitea", message: error.message }, 502);
|
||||
}
|
||||
log.error("admin.failed", { error });
|
||||
return json({ error: "internal" }, 500);
|
||||
|
||||
@@ -3,9 +3,8 @@ import {
|
||||
ADMIN_EMAILS,
|
||||
DISCORD_WEBHOOK_BUG,
|
||||
GATE_SECRET,
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
GITHUB_ISSUES_TOKEN,
|
||||
GITHUB_PUBLISH_TOKEN,
|
||||
GITEA_BOT_TOKEN,
|
||||
GITLAB_ISSUES_TOKEN,
|
||||
TURNSTILE_SECRET,
|
||||
} from "astro:env/server";
|
||||
import { gateSettings } from "../gate/policy";
|
||||
@@ -19,8 +18,6 @@ export interface ConfigStatus {
|
||||
gate: { mode: string; active: boolean };
|
||||
/** Secret name → set or not. */
|
||||
secrets: Record<string, boolean>;
|
||||
/** Publishing dispatches with the content token (no GITHUB_PUBLISH_TOKEN). */
|
||||
singleToken: boolean;
|
||||
}
|
||||
|
||||
export function configStatus(): ConfigStatus {
|
||||
@@ -33,14 +30,12 @@ export function configStatus(): ConfigStatus {
|
||||
active: gateSettings({ GATE_MODE: mode, GATE_SECRET, TURNSTILE_SECRET }) !== null,
|
||||
},
|
||||
secrets: {
|
||||
GITHUB_CONTENT_TOKEN: Boolean(GITHUB_CONTENT_TOKEN),
|
||||
GITHUB_PUBLISH_TOKEN: Boolean(GITHUB_PUBLISH_TOKEN),
|
||||
GITHUB_ISSUES_TOKEN: Boolean(GITHUB_ISSUES_TOKEN),
|
||||
GITEA_BOT_TOKEN: Boolean(GITEA_BOT_TOKEN),
|
||||
GITLAB_ISSUES_TOKEN: Boolean(GITLAB_ISSUES_TOKEN),
|
||||
DISCORD_WEBHOOK_BUG: Boolean(DISCORD_WEBHOOK_BUG),
|
||||
TURNSTILE_SECRET: Boolean(TURNSTILE_SECRET),
|
||||
GATE_SECRET: Boolean(GATE_SECRET),
|
||||
ADMIN_EMAILS: Boolean(ADMIN_EMAILS),
|
||||
},
|
||||
singleToken: Boolean(GITHUB_CONTENT_TOKEN) && !GITHUB_PUBLISH_TOKEN,
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -39,7 +39,7 @@ function cssVar(name: string, fallback: string): string {
|
||||
function banner(): void {
|
||||
// Two args, one %c run: keeps it to a single console entry instead of a wall.
|
||||
console.log(
|
||||
`%c${SKULL}\n poli0981.dev — mã nguồn: https://github.com/poli0981/poli0981-dev\n Thấy gì lạ? /legal/ai-usage · báo lỗi ở footer.\n`,
|
||||
`%c${SKULL}\n poli0981.dev — mã nguồn: https://git.poli0981.dev/poli0981/poli0981-dev\n Thấy gì lạ? /legal/ai-usage · báo lỗi ở footer.\n`,
|
||||
`color:${cssVar("--accent", PALETTE.dark.accent)};font-family:ui-monospace,monospace;line-height:1.15`,
|
||||
);
|
||||
}
|
||||
|
||||
+7
-6
@@ -19,9 +19,10 @@ export interface SocialLink {
|
||||
}
|
||||
|
||||
/**
|
||||
* Social + community links, grouped by persona. GitHub was already confirmed; the rest
|
||||
* come from the owner's real accounts (info.txt). Note: the SkullMute channel and the
|
||||
* Kokone/dev identity keep separate accounts on most platforms, hence the `persona` split.
|
||||
* Social + community links, grouped by persona. The code lives on the owner's own Gitea since
|
||||
* the GitHub account went (2026-11); the rest come from the owner's real accounts (info.txt).
|
||||
* Note: the SkullMute channel and the Kokone/dev identity keep separate accounts on most
|
||||
* platforms, hence the `persona` split.
|
||||
* (A personal Facebook profile exists but is intentionally kept off the public list.)
|
||||
*/
|
||||
export const SOCIAL_LINKS: SocialLink[] = [
|
||||
@@ -98,10 +99,10 @@ export const SOCIAL_LINKS: SocialLink[] = [
|
||||
|
||||
// ── Kokone — Dev / đời thường ─────────────────────────────────────
|
||||
{
|
||||
name: "GitHub — poli0981",
|
||||
href: "https://github.com/poli0981",
|
||||
name: "Gitea — poli0981",
|
||||
href: "https://git.poli0981.dev/poli0981",
|
||||
persona: "dev",
|
||||
platform: "github",
|
||||
platform: "gitea",
|
||||
desc: { vi: "Mã nguồn & dự án mở.", en: "Source code & open projects." },
|
||||
},
|
||||
{
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ export interface VersionInfo {
|
||||
id: string | null;
|
||||
tag: string | null;
|
||||
timestamp: string | null;
|
||||
/** The commit Workers Builds built (astro.config.mjs defines __BUILD_COMMIT__). */
|
||||
/** The commit CI built and deployed (astro.config.mjs defines __BUILD_COMMIT__). */
|
||||
commit: string | null;
|
||||
/**
|
||||
* The poli0981/content commit that build's src/content pointed at (__CONTENT_COMMIT__):
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { listAudit } from "@/lib/admin/audit";
|
||||
import { recentContentCommits } from "@/lib/admin/github";
|
||||
import { recentContentCommits } from "@/lib/admin/gitea";
|
||||
import { errorResponse, json } from "@/lib/admin/http";
|
||||
|
||||
// The activity page: the admin's own audit log (KV, 90 days) next to the content repo's
|
||||
// latest commits, which also show edits made outside the admin (GitHub, a local clone).
|
||||
// latest commits, which also show edits made outside the admin (Gitea's web editor, a local clone).
|
||||
export const prerender = false;
|
||||
|
||||
export const GET: APIRoute = async () => {
|
||||
@@ -14,7 +14,7 @@ export const GET: APIRoute = async () => {
|
||||
const kv = env.KV as KVNamespace | undefined;
|
||||
const [audit, commits] = await Promise.all([
|
||||
kv ? listAudit(kv) : [],
|
||||
GITHUB_CONTENT_TOKEN ? recentContentCommits(GITHUB_CONTENT_TOKEN) : [],
|
||||
GITEA_BOT_TOKEN ? recentContentCommits(GITEA_BOT_TOKEN) : [],
|
||||
]);
|
||||
return json({ audit, commits });
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { autoPublish } from "@/lib/admin/autopublish";
|
||||
import {
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type FieldError,
|
||||
} from "@/lib/admin/collections";
|
||||
import { buildFile, splitFile, type Frontmatter } from "@/lib/admin/frontmatter";
|
||||
import { commitContent, listContentFiles, readContentFile } from "@/lib/admin/github";
|
||||
import { commitContent, listContentFiles, readContentFile } from "@/lib/admin/gitea";
|
||||
import { errorResponse, isPlainObject, json, readJson } from "@/lib/admin/http";
|
||||
import { localPhotoCount } from "@/lib/gallery";
|
||||
import { log } from "@/lib/log";
|
||||
@@ -33,19 +33,19 @@ async function albumProblem(token: string, album: unknown): Promise<FieldError |
|
||||
const MAX_FILE_BYTES = 200_000;
|
||||
|
||||
export const GET: APIRoute = async ({ url }) => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const path = url.searchParams.get("path");
|
||||
if (path) {
|
||||
const collection = collectionOf(path);
|
||||
if (!collection) return json({ error: "not_editable" }, 400);
|
||||
const file = await readContentFile(GITHUB_CONTENT_TOKEN, path);
|
||||
const file = await readContentFile(GITEA_BOT_TOKEN, path);
|
||||
if (!file) return json({ error: "not_found" }, 404);
|
||||
const { data, body } = splitFile(file.text);
|
||||
return json({ path, sha: file.sha, collection: collection.id, frontmatter: data, body });
|
||||
}
|
||||
|
||||
const { head, files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
const { head, files } = await listContentFiles(GITEA_BOT_TOKEN);
|
||||
const entries = files.flatMap((file) => {
|
||||
const collection = collectionOf(file.path);
|
||||
if (!collection) return [];
|
||||
@@ -77,7 +77,7 @@ interface SaveBody {
|
||||
}
|
||||
|
||||
export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const input = await readJson<SaveBody>(request);
|
||||
if (
|
||||
@@ -100,14 +100,14 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
}
|
||||
const errors = validateFrontmatter(collection, input.frontmatter);
|
||||
if (errors.length === 0 && collection.id === "gallery") {
|
||||
const problem = await albumProblem(GITHUB_CONTENT_TOKEN, input.frontmatter.album);
|
||||
const problem = await albumProblem(GITEA_BOT_TOKEN, input.frontmatter.album);
|
||||
if (problem) errors.push(problem);
|
||||
}
|
||||
if (errors.length > 0) return json({ error: "invalid_fields", fields: errors }, 400);
|
||||
|
||||
const original = input.sha ? await readContentFile(GITHUB_CONTENT_TOKEN, input.path) : null;
|
||||
const original = input.sha ? await readContentFile(GITEA_BOT_TOKEN, input.path) : null;
|
||||
// Creating a slug that already exists is its own error, not an edit conflict.
|
||||
if (input.sha === null && (await readContentFile(GITHUB_CONTENT_TOKEN, input.path))) {
|
||||
if (input.sha === null && (await readContentFile(GITEA_BOT_TOKEN, input.path))) {
|
||||
return json({ error: "already_exists" }, 409);
|
||||
}
|
||||
const text = buildFile(original?.text ?? null, input.frontmatter, input.body);
|
||||
@@ -119,11 +119,11 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
// The content repo is public: the commit says it came through the admin, but who it was
|
||||
// stays in the private audit log below.
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
GITEA_BOT_TOKEN,
|
||||
`content(${collection.id}): ${verb} ${input.path}\n\nvia admin`,
|
||||
[{ path: input.path, text, expectSha: input.sha }],
|
||||
);
|
||||
const saved = await readContentFile(GITHUB_CONTENT_TOKEN, input.path);
|
||||
const saved = await readContentFile(GITEA_BOT_TOKEN, input.path);
|
||||
await recordAudit(env.KV, {
|
||||
admin: email,
|
||||
action: "content.save",
|
||||
@@ -139,7 +139,7 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
};
|
||||
|
||||
export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const input = await readJson<{ path: string; sha: string }>(request);
|
||||
if (!input || typeof input.path !== "string" || typeof input.sha !== "string") {
|
||||
@@ -152,7 +152,7 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
if (!collection.creatable) return json({ error: "not_deletable" }, 400);
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
GITEA_BOT_TOKEN,
|
||||
`content: delete ${input.path}\n\nvia admin`,
|
||||
[{ path: input.path, text: null, expectSha: input.sha }],
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { autoPublish } from "@/lib/admin/autopublish";
|
||||
import { galleryPhotosPath, SLUG_PATTERN } from "@/lib/admin/collections";
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
readContentFile,
|
||||
type FileChange,
|
||||
type RepoFile,
|
||||
} from "@/lib/admin/github";
|
||||
} from "@/lib/admin/gitea";
|
||||
import { errorResponse, isPlainObject, json, readJson } from "@/lib/admin/http";
|
||||
import { localPhotoCount } from "@/lib/gallery";
|
||||
import { log } from "@/lib/log";
|
||||
@@ -44,9 +44,9 @@ interface AlbumSummary {
|
||||
}
|
||||
|
||||
export const GET: APIRoute = async () => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const { files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
const { files } = await listContentFiles(GITEA_BOT_TOKEN);
|
||||
const albums = new Map<string, AlbumSummary>();
|
||||
const albumFor = (album: string): AlbumSummary => {
|
||||
let entry = albums.get(album);
|
||||
@@ -115,7 +115,7 @@ const isTitled = (value: unknown): value is { title: string; description?: strin
|
||||
(value.description === undefined || typeof value.description === "string");
|
||||
|
||||
export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const input = await readJson<SaveBody>(request);
|
||||
const path =
|
||||
@@ -148,7 +148,7 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
}
|
||||
const files = [`gallery/${input.album}.md`, `gallery/${input.album}-en.md`];
|
||||
for (const file of files) {
|
||||
if (await readContentFile(GITHUB_CONTENT_TOKEN, file)) {
|
||||
if (await readContentFile(GITEA_BOT_TOKEN, file)) {
|
||||
return json({ error: "already_exists", path: file }, 409);
|
||||
}
|
||||
}
|
||||
@@ -169,7 +169,7 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
}
|
||||
} else if (coverIndex !== undefined) {
|
||||
// A new cover rewrites coverIndex in both language entries, in the same commit.
|
||||
const { files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
const { files } = await listContentFiles(GITEA_BOT_TOKEN);
|
||||
for (const file of albumEntries(files, input.album)) {
|
||||
const { data, body } = splitFile(file.text);
|
||||
if (data.coverIndex === coverIndex) continue;
|
||||
@@ -181,7 +181,7 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const verb = input.create ? "create" : "update";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
GITEA_BOT_TOKEN,
|
||||
`content(gallery): ${verb} album ${input.album}\n\nvia admin`,
|
||||
changes,
|
||||
);
|
||||
@@ -201,13 +201,13 @@ export const PUT: APIRoute = async ({ request, locals }) => {
|
||||
|
||||
/** Remove an album: its R2 photo list and both entries (the photos stay in the library). */
|
||||
export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const input = await readJson<{ album: string }>(request);
|
||||
const album = typeof input?.album === "string" ? input.album : "";
|
||||
const listPath = galleryPhotosPath(album);
|
||||
if (!listPath) return json({ error: "invalid" }, 400);
|
||||
const { files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
const { files } = await listContentFiles(GITEA_BOT_TOKEN);
|
||||
const doomed = [
|
||||
...albumEntries(files, album),
|
||||
...files.filter((file) => file.path === listPath),
|
||||
@@ -215,7 +215,7 @@ export const DELETE: APIRoute = async ({ request, locals }) => {
|
||||
if (doomed.length === 0) return json({ error: "not_found" }, 404);
|
||||
const email = locals.admin?.email ?? "unknown";
|
||||
const commit = await commitContent(
|
||||
GITHUB_CONTENT_TOKEN,
|
||||
GITEA_BOT_TOKEN,
|
||||
`content(gallery): delete album ${album}\n\nvia admin`,
|
||||
doomed.map((file) => ({ path: file.path, text: null, expectSha: file.sha })),
|
||||
);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { listContentFiles } from "@/lib/admin/github";
|
||||
import { listContentFiles } from "@/lib/admin/gitea";
|
||||
import { errorResponse, json, readJson } from "@/lib/admin/http";
|
||||
import { assertDeclaredSize, BodyTooLargeError } from "@/lib/body";
|
||||
import { log } from "@/lib/log";
|
||||
@@ -47,8 +47,8 @@ export const GET: APIRoute = async ({ url }) => {
|
||||
// ?usage: which content files mention each image (the library's "used in" line, and
|
||||
// the same test DELETE applies before removing one).
|
||||
const usage: Record<string, string[]> = {};
|
||||
if (GITHUB_CONTENT_TOKEN) {
|
||||
const { files } = await listContentFiles(GITHUB_CONTENT_TOKEN);
|
||||
if (GITEA_BOT_TOKEN) {
|
||||
const { files } = await listContentFiles(GITEA_BOT_TOKEN);
|
||||
for (const item of items) {
|
||||
usage[item.id] = files.filter((file) => file.text.includes(item.id)).map((f) => f.path);
|
||||
}
|
||||
@@ -133,8 +133,8 @@ export const DELETE: APIRoute = async ({ request, url, locals }) => {
|
||||
}
|
||||
// Refuse while any content still points at it — the live site would break, and a
|
||||
// publish would fail the build anyway.
|
||||
if (GITHUB_CONTENT_TOKEN) {
|
||||
const usedIn = await filesUsing(GITHUB_CONTENT_TOKEN, input.id);
|
||||
if (GITEA_BOT_TOKEN) {
|
||||
const usedIn = await filesUsing(GITEA_BOT_TOKEN, input.id);
|
||||
if (usedIn.length) return json({ error: "in_use", usedIn }, 409);
|
||||
}
|
||||
await deleteMedia(env, input.id, url.origin);
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { GITHUB_CONTENT_TOKEN } from "astro:env/server";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { COLLECTIONS, collectionOf, type CollectionId } from "@/lib/admin/collections";
|
||||
import { splitFile } from "@/lib/admin/frontmatter";
|
||||
import { listContentFiles } from "@/lib/admin/github";
|
||||
import { listContentFiles } from "@/lib/admin/gitea";
|
||||
import { errorResponse, json } from "@/lib/admin/http";
|
||||
import { configStatus } from "@/lib/admin/status";
|
||||
import { listMedia } from "@/lib/media/process";
|
||||
@@ -27,7 +27,7 @@ export const GET: APIRoute = async () => {
|
||||
try {
|
||||
const kv = env.KV as KVNamespace | undefined;
|
||||
const [content, media, widgets] = await Promise.all([
|
||||
GITHUB_CONTENT_TOKEN ? listContentFiles(GITHUB_CONTENT_TOKEN) : null,
|
||||
GITEA_BOT_TOKEN ? listContentFiles(GITEA_BOT_TOKEN) : null,
|
||||
listMedia(env),
|
||||
kv ? kv.get<WidgetsStatus>("widgets:status", "json") : null,
|
||||
]);
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { recordAudit } from "@/lib/admin/audit";
|
||||
import { GITHUB_CONTENT_TOKEN, GITHUB_PUBLISH_TOKEN } from "astro:env/server";
|
||||
import { publishToken } from "@/lib/admin/autopublish";
|
||||
import { dispatchPublish, publishStatus } from "@/lib/admin/github";
|
||||
import { GITEA_BOT_TOKEN } from "astro:env/server";
|
||||
import { dispatchPublish, publishStatus } from "@/lib/admin/gitea";
|
||||
import { errorResponse, json } from "@/lib/admin/http";
|
||||
import { publishPhase } from "@/lib/admin/publish-phase";
|
||||
import { log } from "@/lib/log";
|
||||
import { versionInfo } from "@/lib/version";
|
||||
|
||||
// Publish = run .github/workflows/content-bump.yml on the site repo: it points the
|
||||
// src/content submodule at content's main, opens/updates the content/bump PR, and lets
|
||||
// CI + auto-merge deploy it (Workers Builds). Edits that touch .mdx wait for review.
|
||||
// Publish = run .gitea/workflows/content-bump.yml on the site repo: it points the
|
||||
// src/content submodule at content's main, opens/updates the content/bump PR, and CI merges
|
||||
// it and deploys main (ci.yml's publish and deploy jobs). Edits that touch .mdx wait for
|
||||
// review.
|
||||
// Saves and deletes start it on their own (lib/admin/autopublish); POST is the manual retry.
|
||||
export const prerender = false;
|
||||
|
||||
export const GET: APIRoute = async () => {
|
||||
if (!GITHUB_CONTENT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
const status = await publishStatus(GITHUB_CONTENT_TOKEN);
|
||||
const status = await publishStatus(GITEA_BOT_TOKEN);
|
||||
// The admin runs in the same Worker as the public site, so the content commit this
|
||||
// build was made from is exactly what visitors are seeing.
|
||||
const live = versionInfo(env as unknown as Parameters<typeof versionInfo>[0]).content;
|
||||
@@ -26,9 +26,6 @@ export const GET: APIRoute = async () => {
|
||||
...status,
|
||||
live,
|
||||
phase: publishPhase({ ...status, live }),
|
||||
// Without its own publish token, the content token is doing the dispatching — which
|
||||
// means it has rights on this repo too. The admin shows a warning for this.
|
||||
singleToken: !GITHUB_PUBLISH_TOKEN,
|
||||
});
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
@@ -36,21 +33,16 @@ export const GET: APIRoute = async () => {
|
||||
};
|
||||
|
||||
export const POST: APIRoute = async ({ locals }) => {
|
||||
// Dispatching needs Actions write on the site repo — the publish token's only power.
|
||||
// Falls back to the content token for single-token setups.
|
||||
const token = publishToken();
|
||||
if (!token) return json({ error: "not_configured" }, 503);
|
||||
// Dispatching needs the bot's Write access on the site repo; it pushes nothing there.
|
||||
if (!GITEA_BOT_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
try {
|
||||
await dispatchPublish(token);
|
||||
await dispatchPublish(GITEA_BOT_TOKEN);
|
||||
await recordAudit(env.KV, {
|
||||
admin: locals.admin?.email ?? "unknown",
|
||||
action: "publish",
|
||||
target: "content → site",
|
||||
});
|
||||
log.info("admin.publish_dispatched", {
|
||||
admin: locals.admin?.email,
|
||||
singleToken: !GITHUB_PUBLISH_TOKEN,
|
||||
});
|
||||
log.info("admin.publish_dispatched", { admin: locals.admin?.email });
|
||||
return json({ dispatched: true }, 202);
|
||||
} catch (error) {
|
||||
return errorResponse(error);
|
||||
|
||||
+35
-22
@@ -1,18 +1,23 @@
|
||||
import type { APIRoute } from "astro";
|
||||
import { env } from "cloudflare:workers";
|
||||
import { z } from "zod";
|
||||
import { TURNSTILE_SECRET, GITHUB_ISSUES_TOKEN, DISCORD_WEBHOOK_BUG } from "astro:env/server";
|
||||
import { TURNSTILE_SECRET, GITLAB_ISSUES_TOKEN, DISCORD_WEBHOOK_BUG } from "astro:env/server";
|
||||
import { BodyTooLargeError, readTextLimited } from "@/lib/body";
|
||||
import { log } from "@/lib/log";
|
||||
import { verifyTurnstile } from "@/lib/turnstile-server";
|
||||
|
||||
// On-demand so middleware runs (RL_REPORT: 5 per 60 s per client). Secrets are optional
|
||||
// at build so the site ships before they're provisioned; when TURNSTILE_SECRET or the GitHub
|
||||
// at build so the site ships before they're provisioned; when TURNSTILE_SECRET or the GitLab
|
||||
// token is missing this route replies 503 and the client dialog degrades to a Discord fallback.
|
||||
export const prerender = false;
|
||||
|
||||
/** Private repo (wrangler.jsonc var): reports carry browser details and are never public. */
|
||||
const DEFAULT_REPORT_REPO = "poli0981/site-reports";
|
||||
/**
|
||||
* The GitLab project (wrangler.jsonc var REPORT_PROJECT): the public mirror of this repo. The
|
||||
* GitHub repository the reports used to go to went with the account; on GitLab every report
|
||||
* is a CONFIDENTIAL issue, because reports carry browser details and are never public.
|
||||
*/
|
||||
const DEFAULT_REPORT_PROJECT = "poli0981/poli0981-dev";
|
||||
const GITLAB_API = "https://gitlab.com/api/v4";
|
||||
const MAX_BODY = 32_000;
|
||||
const TIMEOUT_MS = 10_000;
|
||||
|
||||
@@ -53,11 +58,13 @@ function json(data: unknown, status: number): Response {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reporter-supplied text is rendered as Markdown on GitHub. Break `@user` mentions (a zero-
|
||||
* width space after "@" — nobody gets pinged by a stranger's report) and backticks in
|
||||
* values that sit inside inline code.
|
||||
* Reporter-supplied text is rendered as Markdown on GitLab. Break `@user` mentions (a zero-
|
||||
* width space after "@" — nobody gets pinged by a stranger's report), quick actions (GitLab
|
||||
* runs a line that starts with "/", such as `/close`, as a command: a zero-width space goes
|
||||
* in front) and backticks in values that sit inside inline code.
|
||||
*/
|
||||
const noMentions = (text: string) => text.replace(/@(?=[\w-])/g, "@");
|
||||
const noMentions = (text: string) =>
|
||||
text.replace(/@(?=[\w-])/g, "@").replace(/^(\s*)\//gm, "$1/");
|
||||
const inlineCode = (text: string) => `\`${text.replace(/`/g, "'")}\``;
|
||||
|
||||
/** A code fence longer than any backtick run inside, so the log can't close it early. */
|
||||
@@ -100,31 +107,32 @@ function issueBody(body: ReportBody): string {
|
||||
}
|
||||
|
||||
async function createIssue(body: ReportBody, token: string): Promise<string | null> {
|
||||
const repo = (env as { REPORT_REPO?: string }).REPORT_REPO || DEFAULT_REPORT_REPO;
|
||||
const project = (env as { REPORT_PROJECT?: string }).REPORT_PROJECT || DEFAULT_REPORT_PROJECT;
|
||||
try {
|
||||
const res = await fetch(`https://api.github.com/repos/${repo}/issues`, {
|
||||
const res = await fetch(`${GITLAB_API}/projects/${encodeURIComponent(project)}/issues`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
accept: "application/vnd.github+json",
|
||||
"private-token": token,
|
||||
accept: "application/json",
|
||||
"content-type": "application/json",
|
||||
"user-agent": "poli0981-dev-report-bot",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: issueTitle(body),
|
||||
body: issueBody(body),
|
||||
labels: ["bug", "from-site"],
|
||||
description: issueBody(body),
|
||||
labels: "bug,from-site",
|
||||
confidential: true,
|
||||
}),
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
if (!res.ok) {
|
||||
log.error("report.github_failed", { status: res.status, repo });
|
||||
log.error("report.gitlab_failed", { status: res.status, project });
|
||||
return null;
|
||||
}
|
||||
const data = (await res.json()) as { html_url?: string };
|
||||
return data.html_url ?? null;
|
||||
const data = (await res.json()) as { web_url?: string };
|
||||
return data.web_url ?? null;
|
||||
} catch (error) {
|
||||
log.error("report.github_failed", { repo, error });
|
||||
log.error("report.gitlab_failed", { project, error });
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -163,7 +171,12 @@ async function notifyDiscord(
|
||||
}
|
||||
|
||||
export const POST: APIRoute = async ({ request }) => {
|
||||
if (!TURNSTILE_SECRET || !GITHUB_ISSUES_TOKEN) return json({ error: "not_configured" }, 503);
|
||||
// Somewhere to put the report: the GitLab issue, or at least the Discord notice. Without
|
||||
// the GitLab token (not provisioned yet, or revoked) reports still reach Discord, as they
|
||||
// did while the GitHub tracker was gone.
|
||||
if (!TURNSTILE_SECRET || (!GITLAB_ISSUES_TOKEN && !DISCORD_WEBHOOK_BUG)) {
|
||||
return json({ error: "not_configured" }, 503);
|
||||
}
|
||||
|
||||
let raw: string;
|
||||
try {
|
||||
@@ -189,12 +202,12 @@ export const POST: APIRoute = async ({ request }) => {
|
||||
});
|
||||
if (!verdict.ok) return json({ error: "turnstile_failed", reason: verdict.reason }, 400);
|
||||
|
||||
const issueUrl = await createIssue(parsed, GITHUB_ISSUES_TOKEN);
|
||||
const issueUrl = GITLAB_ISSUES_TOKEN ? await createIssue(parsed, GITLAB_ISSUES_TOKEN) : null;
|
||||
if (DISCORD_WEBHOOK_BUG) await notifyDiscord(parsed, issueUrl, DISCORD_WEBHOOK_BUG);
|
||||
log.info("report.received", { route: parsed.meta.route, filed: issueUrl !== null });
|
||||
|
||||
// GitHub failed but Discord fired — the report is not lost (docs 10 §3). The issue lives
|
||||
// in a private repo, so its URL is not echoed back to the reporter.
|
||||
// GitLab failed but Discord fired — the report is not lost (docs 10 §3). The issue is
|
||||
// confidential, so its URL is not echoed back to the reporter.
|
||||
if (!issueUrl) return json({ ok: true, degraded: true }, 202);
|
||||
return json({ ok: true }, 201);
|
||||
};
|
||||
+15
-14
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, it } from "node:test";
|
||||
import type { APIContext } from "astro";
|
||||
import { setServerEnv } from "./support/stubs/astro-env-server.ts";
|
||||
import { setWorkerEnv } from "./support/stubs/cloudflare-workers.ts";
|
||||
import { FakeGitHub } from "./support/github.ts";
|
||||
import { FakeGitea } from "./support/gitea.ts";
|
||||
import { captureLogs, FakeKV, FakeR2 } from "./support/fakes.ts";
|
||||
|
||||
// gallery.ts reads the local album folders at module load: two local photos in "game".
|
||||
@@ -28,10 +28,10 @@ const overviewApi = await import("../src/pages/api/admin/overview.ts");
|
||||
const publishApi = await import("../src/pages/api/admin/publish.ts");
|
||||
const securityApi = await import("../src/pages/api/admin/security.ts");
|
||||
|
||||
const TOKEN = "content-token";
|
||||
const TOKEN = "bot-token";
|
||||
const OWNER = "owner@example.com";
|
||||
|
||||
let github: FakeGitHub | null = null;
|
||||
let github: FakeGitea | null = null;
|
||||
afterEach(() => github?.restore());
|
||||
|
||||
const ctx = (request: Request) =>
|
||||
@@ -105,7 +105,7 @@ describe("/api/admin/security", () => {
|
||||
beforeEach(() => {
|
||||
kv = new FakeKV();
|
||||
setWorkerEnv({ KV: kv.asBinding(), GATE_MODE: "on" });
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN, GATE_SECRET: "g", TURNSTILE_SECRET: "t" });
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN, GATE_SECRET: "g", TURNSTILE_SECRET: "t" });
|
||||
});
|
||||
|
||||
it("shows the list and the configuration — secret names, never values", async () => {
|
||||
@@ -115,9 +115,9 @@ describe("/api/admin/security", () => {
|
||||
};
|
||||
assert.deepEqual(body.denylist, []);
|
||||
assert.deepEqual(body.config.gate, { mode: "on", active: true });
|
||||
assert.equal(body.config.secrets.GITHUB_CONTENT_TOKEN, true);
|
||||
assert.equal(body.config.secrets.GITEA_BOT_TOKEN, true);
|
||||
assert.equal(body.config.secrets.ADMIN_EMAILS, false);
|
||||
assert.doesNotMatch(JSON.stringify(body), /content-token/);
|
||||
assert.doesNotMatch(JSON.stringify(body), /bot-token/);
|
||||
});
|
||||
|
||||
it("adds, replaces and removes entries, logging each change", async () => {
|
||||
@@ -192,8 +192,8 @@ describe("/api/admin/overview and /api/admin/activity", () => {
|
||||
beforeEach(() => {
|
||||
kv = new FakeKV();
|
||||
setWorkerEnv({ KV: kv.asBinding(), MEDIA: new FakeR2().asBinding() });
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
github = new FakeGitHub({
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github = new FakeGitea({
|
||||
"blog/a.md": "---\ntitle: A\nlang: vi\ndraft: true\n---\n",
|
||||
"blog/b.md": "---\ntitle: B\nlang: en\n---\n",
|
||||
"now/now.md": "---\ntitle: Now\nlang: vi\n---\n",
|
||||
@@ -213,14 +213,15 @@ describe("/api/admin/overview and /api/admin/activity", () => {
|
||||
};
|
||||
media: { count: number };
|
||||
widgets: { steam: string };
|
||||
config: { singleToken: boolean };
|
||||
config: { secrets: Record<string, boolean> };
|
||||
};
|
||||
const blog = body.content.collections.find((c) => c.id === "blog");
|
||||
assert.deepEqual(blog && [blog.total, blog.drafts, blog.vi, blog.en], [2, 1, 1, 1]);
|
||||
assert.equal(body.content.collections.find((c) => c.id === "now")?.total, 1);
|
||||
assert.equal(body.media.count, 0);
|
||||
assert.equal(body.widgets.steam, "stale");
|
||||
assert.equal(body.config.singleToken, true);
|
||||
assert.equal(body.config.secrets.GITEA_BOT_TOKEN, true);
|
||||
assert.equal(body.config.secrets.GITLAB_ISSUES_TOKEN, false);
|
||||
|
||||
setServerEnv({});
|
||||
setWorkerEnv({ MEDIA: new FakeR2().asBinding() });
|
||||
@@ -287,8 +288,8 @@ describe("/api/admin/media?usage", () => {
|
||||
customMetadata: { w: "8", h: "6", name: "b.png", alt: "", createdAt: "t" },
|
||||
});
|
||||
setWorkerEnv({ MEDIA: r2.asBinding() });
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
github = new FakeGitHub({ "blog/a.md": "<img src=/media/v1/0123456789abcdef/webp-800>" });
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github = new FakeGitea({ "blog/a.md": "<img src=/media/v1/0123456789abcdef/webp-800>" });
|
||||
const body = (await (await call(mediaApi.GET, get("/api/admin/media?usage"))).json()) as {
|
||||
items: unknown[];
|
||||
usage: Record<string, string[]>;
|
||||
@@ -311,8 +312,8 @@ describe("/api/admin/gallery covers and deletion", () => {
|
||||
beforeEach(() => {
|
||||
kv = new FakeKV();
|
||||
setWorkerEnv({ KV: kv.asBinding() });
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
github = new FakeGitHub({
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github = new FakeGitea({
|
||||
"gallery/game.md": "---\ntitle: Game\nlang: vi\nalbum: game\ncoverIndex: 0\n---\n",
|
||||
"gallery/game-en.md": "---\ntitle: Games\nlang: en\nalbum: game\n---\n",
|
||||
"gallery-photos/game.json": JSON.stringify({ photos }),
|
||||
|
||||
+72
-56
@@ -1,4 +1,4 @@
|
||||
// The admin: GitHub access (lib/admin/github), HTTP helpers, Access JWT verification and the
|
||||
// The admin: Gitea access (lib/admin/gitea), HTTP helpers, Access JWT verification and the
|
||||
// /api/admin/* routes, against an in-memory content repo.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, afterEach, before, beforeEach, describe, it } from "node:test";
|
||||
@@ -6,7 +6,7 @@ import type { APIContext } from "astro";
|
||||
import { exportJWK, generateKeyPair, SignJWT } from "jose";
|
||||
import { setServerEnv } from "./support/stubs/astro-env-server.ts";
|
||||
import { setWorkerEnv } from "./support/stubs/cloudflare-workers.ts";
|
||||
import { FakeGitHub } from "./support/github.ts";
|
||||
import { FakeGitea } from "./support/gitea.ts";
|
||||
import {
|
||||
captureLogs,
|
||||
FakeCache,
|
||||
@@ -20,11 +20,11 @@ import {
|
||||
commitContent,
|
||||
ConflictError,
|
||||
dispatchPublish,
|
||||
GitHubError,
|
||||
GiteaError,
|
||||
listContentFiles,
|
||||
publishStatus,
|
||||
readContentFile,
|
||||
} from "../src/lib/admin/github.ts";
|
||||
} from "../src/lib/admin/gitea.ts";
|
||||
import { errorResponse, isPlainObject, json, readJson } from "../src/lib/admin/http.ts";
|
||||
import { BodyTooLargeError } from "../src/lib/body.ts";
|
||||
import * as contentApi from "../src/pages/api/admin/content.ts";
|
||||
@@ -32,10 +32,11 @@ import * as galleryApi from "../src/pages/api/admin/gallery.ts";
|
||||
import * as mediaApi from "../src/pages/api/admin/media.ts";
|
||||
import * as publishApi from "../src/pages/api/admin/publish.ts";
|
||||
|
||||
const TOKEN = "content-token";
|
||||
const TOKEN = "bot-token";
|
||||
const POST_MD = `---\ntitle: "Đêm đầu"\ndescription: Mô tả\nlang: vi\ndate: 2026-10-01\ntags: [dev, diary]\n---\n\nThân bài.\n`;
|
||||
const GITEA = "https://git.poli0981.dev";
|
||||
|
||||
let github: FakeGitHub;
|
||||
let github: FakeGitea;
|
||||
afterEach(() => github?.restore());
|
||||
|
||||
const admin = { admin: { email: "owner@example.com" } };
|
||||
@@ -50,20 +51,33 @@ const jsonRequest = (method: string, body: unknown, path = "/api/admin/content")
|
||||
const call = async (handler: unknown, request: Request) =>
|
||||
(await (handler as (c: APIContext) => Promise<Response>)(ctx(request))) as Response;
|
||||
|
||||
describe("lib/admin/github", () => {
|
||||
describe("lib/admin/gitea", () => {
|
||||
beforeEach(() => {
|
||||
github = new FakeGitHub({
|
||||
github = new FakeGitea({
|
||||
"blog/dem-dau.md": POST_MD,
|
||||
"stories/series/c1.md": "---\ntitle: C1\n---\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("lists every text file of the content repo in one GraphQL call", async () => {
|
||||
it("lists every text file of the content repo: head, tree, then the contents", async () => {
|
||||
const { head, files } = await listContentFiles(TOKEN);
|
||||
assert.equal(head, "commit-0");
|
||||
assert.deepEqual(files.map((f) => f.path).sort(), ["blog/dem-dau.md", "stories/series/c1.md"]);
|
||||
assert.equal(github.calls.length, 1);
|
||||
assert.equal(github.calls[0].headers.get("authorization"), `Bearer ${TOKEN}`);
|
||||
assert.equal(files.find((f) => f.path === "blog/dem-dau.md")?.text, POST_MD);
|
||||
assert.equal(github.calls.length, 3);
|
||||
assert.equal(github.calls[0].headers.get("authorization"), `token ${TOKEN}`);
|
||||
});
|
||||
|
||||
it("reads the contents in batches of 50, and an unknown commit as empty", async () => {
|
||||
for (let i = 0; i < 60; i++) github.files.set(`now/n${i}.md`, `# ${i}`);
|
||||
const { files } = await listContentFiles(TOKEN);
|
||||
assert.equal(files.length, 62);
|
||||
const batches = github.calls.filter((c) => new URL(c.url).pathname.endsWith("/file-contents"));
|
||||
assert.equal(batches.length, 2);
|
||||
assert.deepEqual(await listContentFiles(TOKEN, "commit-unknown"), {
|
||||
head: "commit-unknown",
|
||||
files: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("reads one file (UTF-8) or null when it is missing", async () => {
|
||||
@@ -73,14 +87,16 @@ describe("lib/admin/github", () => {
|
||||
assert.equal(await readContentFile(TOKEN, "blog/none.md"), null);
|
||||
});
|
||||
|
||||
it("commits atomically, refuses stale edits and retries one race", async () => {
|
||||
it("commits several files at once, each checked against the sha the editor saw", async () => {
|
||||
const sha = github.sha("blog/dem-dau.md");
|
||||
github.raceRefUpdates = 1;
|
||||
const commit = await commitContent(TOKEN, "msg", [
|
||||
{ path: "blog/dem-dau.md", text: "new", expectSha: sha },
|
||||
{ path: "blog/dem-dau.md", text: "new — mới", expectSha: sha },
|
||||
{ path: "blog/moi.md", text: "x", expectSha: null },
|
||||
]);
|
||||
assert.equal(commit, "commit-1");
|
||||
assert.equal(github.files.get("blog/dem-dau.md"), "new");
|
||||
assert.equal(github.files.get("blog/dem-dau.md"), "new — mới");
|
||||
assert.equal(github.files.get("blog/moi.md"), "x");
|
||||
assert.equal(github.commits, 1);
|
||||
|
||||
await assert.rejects(
|
||||
commitContent(TOKEN, "msg", [{ path: "blog/dem-dau.md", text: "x", expectSha: sha }]),
|
||||
@@ -92,44 +108,46 @@ describe("lib/admin/github", () => {
|
||||
assert.equal(github.files.has("blog/dem-dau.md"), false);
|
||||
});
|
||||
|
||||
it("gives up after a second race and reports GitHub's needed permission", async () => {
|
||||
github.raceRefUpdates = 2;
|
||||
it("turns Gitea's own sha check into a conflict, other refusals into GiteaError", async () => {
|
||||
github.staleCommits = 1;
|
||||
await assert.rejects(
|
||||
commitContent(TOKEN, "msg", [{ path: "blog/x.md", text: "x", expectSha: null }]),
|
||||
(error: unknown) => error instanceof GitHubError && error.status === 422,
|
||||
ConflictError,
|
||||
);
|
||||
assert.equal(github.commits, 0);
|
||||
github.failAll = { status: 403 };
|
||||
await assert.rejects(
|
||||
listContentFiles(TOKEN),
|
||||
(error: unknown) => error instanceof GiteaError && error.status === 403,
|
||||
);
|
||||
github.failAll = { status: 403, needs: "contents=write" };
|
||||
await assert.rejects(listContentFiles(TOKEN), (error: unknown) => {
|
||||
return (
|
||||
error instanceof GitHubError && error.status === 403 && error.needs === "contents=write"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("maps publish state: open PR, build check and the last workflow run", async () => {
|
||||
it("maps publish state: open PR, its build status and the last workflow run", async () => {
|
||||
github.files.set("blog/new.md", "x"); // content main moved on
|
||||
github.head = "commit-9";
|
||||
github.openPr = { number: 120, headSha: "abc", autoMerge: true };
|
||||
github.buildCheck = { status: "completed", conclusion: "success" };
|
||||
github.buildCheck = "success";
|
||||
github.lastRun = { status: "completed", conclusion: "success" };
|
||||
const status = await publishStatus(TOKEN);
|
||||
assert.equal(status.contentHead, "commit-9");
|
||||
assert.equal(status.published, "commit-0");
|
||||
assert.deepEqual(status.pr, {
|
||||
number: 120,
|
||||
url: "https://github.com/poli0981/poli0981-dev/pull/120",
|
||||
url: `${GITEA}/poli0981/poli0981-dev/pulls/120`,
|
||||
autoMerge: true,
|
||||
checks: "success",
|
||||
});
|
||||
assert.equal(status.run?.url, "https://github.com/run/1");
|
||||
assert.equal(status.run?.url, `${GITEA}/poli0981/poli0981-dev/actions/runs/1`);
|
||||
|
||||
github.buildCheck = { status: "in_progress", conclusion: null };
|
||||
github.buildCheck = "pending";
|
||||
assert.equal((await publishStatus(TOKEN)).pr?.checks, "pending");
|
||||
github.buildCheck = { status: "completed", conclusion: "failure" };
|
||||
github.buildCheck = "failure";
|
||||
assert.equal((await publishStatus(TOKEN)).pr?.checks, "failure");
|
||||
github.buildCheck = null;
|
||||
github.openPr = { number: 121, headSha: "def", autoMerge: false };
|
||||
assert.equal((await publishStatus(TOKEN)).pr?.checks, null);
|
||||
const review = await publishStatus(TOKEN);
|
||||
assert.equal(review.pr?.checks, null);
|
||||
assert.equal(review.pr?.autoMerge, false);
|
||||
github.openPr = null;
|
||||
github.lastRun = null;
|
||||
const idle = await publishStatus(TOKEN);
|
||||
@@ -149,20 +167,19 @@ describe("lib/admin/http", () => {
|
||||
const { result, logs } = await captureLogs(() => [
|
||||
statusOf(new BodyTooLargeError()),
|
||||
statusOf(new ConflictError("changed")),
|
||||
statusOf(new GitHubError("no", 403, "contents=write")),
|
||||
statusOf(new GitHubError("down", 500)),
|
||||
statusOf(new GiteaError("no", 403)),
|
||||
statusOf(new GiteaError("down", 500)),
|
||||
statusOf(new Error("boom")),
|
||||
]);
|
||||
assert.deepEqual(result, [413, 409, 502, 502, 500]);
|
||||
assert.deepEqual(
|
||||
logs.map((line) => line.event),
|
||||
["admin.github_failed", "admin.github_failed", "admin.failed"],
|
||||
["admin.gitea_failed", "admin.gitea_failed", "admin.failed"],
|
||||
);
|
||||
const permission = (await errorResponse(
|
||||
new GitHubError("no", 401, "actions=write"),
|
||||
).json()) as Record<string, unknown>;
|
||||
assert.equal(permission.error, "github_permission");
|
||||
assert.equal(permission.needs, "actions=write");
|
||||
const body = async (error: GiteaError) =>
|
||||
(await errorResponse(error).json()) as Record<string, unknown>;
|
||||
assert.equal((await body(new GiteaError("no", 401))).error, "gitea_permission");
|
||||
assert.equal((await body(new GiteaError("down", 500))).error, "gitea");
|
||||
});
|
||||
|
||||
it("reads JSON only from JSON requests, within the size limit", async () => {
|
||||
@@ -259,8 +276,8 @@ describe("lib/admin/access", () => {
|
||||
|
||||
describe("/api/admin/content", () => {
|
||||
beforeEach(() => {
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
github = new FakeGitHub({
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github = new FakeGitea({
|
||||
"blog/dem-dau.md": POST_MD,
|
||||
"legal/terms.md": "---\ntitle: Terms\n---\n",
|
||||
"README.md": "# not content",
|
||||
@@ -468,8 +485,8 @@ describe("/api/admin/content", () => {
|
||||
assert.equal(github.files.has("blog/dem-dau.md"), false);
|
||||
});
|
||||
|
||||
it("turns GitHub failures into 502s", async () => {
|
||||
github.failAll = { status: 403, needs: "contents=write" };
|
||||
it("turns Gitea failures into 502s", async () => {
|
||||
github.failAll = { status: 403 };
|
||||
const { result } = await captureLogs(() =>
|
||||
call(contentApi.GET, new Request("https://admin.poli0981.dev/api/admin/content")),
|
||||
);
|
||||
@@ -481,8 +498,8 @@ describe("/api/admin/gallery", () => {
|
||||
const photos = [{ id: "0123456789abcdef", w: 800, h: 600, caption: { vi: "Ảnh", en: "Photo" } }];
|
||||
|
||||
beforeEach(() => {
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
github = new FakeGitHub({
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github = new FakeGitea({
|
||||
"gallery/game.md": "---\ntitle: Game\nlang: vi\nalbum: game\n---\n",
|
||||
"gallery/game-en.md": "---\ntitle: Games\nlang: en\nalbum: game\n---\n",
|
||||
"gallery-photos/game.json": JSON.stringify({ photos }),
|
||||
@@ -612,8 +629,8 @@ describe("/api/admin/media", () => {
|
||||
r2 = new FakeR2();
|
||||
cache = installCaches();
|
||||
setWorkerEnv({ MEDIA: r2.asBinding(), IMAGES: new FakeImages().asBinding() });
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
github = new FakeGitHub({ "blog/a.md": "uses 0123456789abcdef" });
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github = new FakeGitea({ "blog/a.md": "uses 0123456789abcdef" });
|
||||
});
|
||||
|
||||
const upload = (bytes: Uint8Array<ArrayBuffer>, headers: Record<string, string> = {}) => {
|
||||
@@ -738,31 +755,30 @@ describe("/api/admin/media", () => {
|
||||
|
||||
describe("/api/admin/publish", () => {
|
||||
beforeEach(() => {
|
||||
github = new FakeGitHub({});
|
||||
github = new FakeGitea({});
|
||||
});
|
||||
|
||||
it("reports status (flagging single-token mode) and dispatches", async () => {
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
it("reports status and dispatches with the bot token", async () => {
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
const read = async () =>
|
||||
(await (
|
||||
await call(publishApi.GET, new Request("https://admin.poli0981.dev/api/admin/publish"))
|
||||
).json()) as { singleToken: boolean; phase: string; live: string | null };
|
||||
).json()) as { phase: string; live: string | null };
|
||||
const status = await read();
|
||||
assert.equal(status.singleToken, true);
|
||||
assert.equal(status.live, null);
|
||||
assert.equal(status.phase, "live");
|
||||
github.head = "commit-9";
|
||||
assert.equal((await read()).phase, "pending");
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN, GITHUB_PUBLISH_TOKEN: "publish-token" });
|
||||
const dispatched = await call(
|
||||
publishApi.POST,
|
||||
new Request("https://admin.poli0981.dev/api/admin/publish", { method: "POST" }),
|
||||
);
|
||||
assert.equal(dispatched.status, 202);
|
||||
assert.equal(github.calls.at(-1)?.headers.get("authorization"), "Bearer publish-token");
|
||||
assert.equal(github.calls.at(-1)?.headers.get("authorization"), `token ${TOKEN}`);
|
||||
assert.deepEqual(github.dispatched, ["main"]);
|
||||
});
|
||||
|
||||
it("is unavailable without tokens and maps GitHub errors", async () => {
|
||||
it("is unavailable without the token and maps Gitea errors", async () => {
|
||||
setServerEnv({});
|
||||
assert.equal(
|
||||
(await call(publishApi.GET, new Request("https://admin.poli0981.dev/api/admin/publish")))
|
||||
@@ -778,7 +794,7 @@ describe("/api/admin/publish", () => {
|
||||
).status,
|
||||
503,
|
||||
);
|
||||
setServerEnv({ GITHUB_CONTENT_TOKEN: TOKEN });
|
||||
setServerEnv({ GITEA_BOT_TOKEN: TOKEN });
|
||||
github.failAll = { status: 403 };
|
||||
const { result } = await captureLogs(() =>
|
||||
call(
|
||||
|
||||
+43
-22
@@ -100,7 +100,7 @@ describe("POST /api/gate", () => {
|
||||
|
||||
describe("POST /api/report", () => {
|
||||
const report = {
|
||||
description: "The gallery lightbox closes when I press @someone's arrow keys",
|
||||
description: "The gallery lightbox closes when I press @someone's arrow keys\n/close",
|
||||
console: [{ ts: "2026-10-24T00:00:00Z", type: "error", message: "boom ``` breakout" }],
|
||||
meta: {
|
||||
route: "/gallery/`x`/",
|
||||
@@ -126,52 +126,73 @@ describe("POST /api/report", () => {
|
||||
beforeEach(() => {
|
||||
setServerEnv({
|
||||
TURNSTILE_SECRET: TEST_SECRET,
|
||||
GITHUB_ISSUES_TOKEN: "issues-token",
|
||||
GITLAB_ISSUES_TOKEN: "issues-token",
|
||||
DISCORD_WEBHOOK_BUG: "https://discord.example/webhook",
|
||||
});
|
||||
setWorkerEnv({ REPORT_REPO: "poli0981/site-reports" });
|
||||
setWorkerEnv({ REPORT_PROJECT: "poli0981/site-reports" });
|
||||
});
|
||||
|
||||
it("is unavailable without its secrets, and refuses bad input", async () => {
|
||||
setServerEnv({ TURNSTILE_SECRET: TEST_SECRET });
|
||||
assert.equal((await post("{}")).status, 503);
|
||||
setServerEnv({ TURNSTILE_SECRET: TEST_SECRET, GITHUB_ISSUES_TOKEN: "t" });
|
||||
setServerEnv({ TURNSTILE_SECRET: TEST_SECRET, GITLAB_ISSUES_TOKEN: "t" });
|
||||
assert.equal((await post("x".repeat(40_000))).status, 413);
|
||||
assert.equal((await post("{", { "content-length": "1" })).status, 400);
|
||||
assert.equal((await post(JSON.stringify({ ...report, description: "short" }))).status, 400);
|
||||
});
|
||||
|
||||
it("files a private issue that can't ping anyone, then notifies Discord", async () => {
|
||||
it("still takes reports to Discord while the GitLab token is missing", async () => {
|
||||
setServerEnv({
|
||||
TURNSTILE_SECRET: TEST_SECRET,
|
||||
DISCORD_WEBHOOK_BUG: "https://discord.example/webhook",
|
||||
});
|
||||
const { calls } = route({
|
||||
[SITEVERIFY]: siteverify({ action: "report" }),
|
||||
"https://api.github.com/": () => jsonResponse({ html_url: "https://github.com/x/1" }, 201),
|
||||
"https://discord.example/": () => new Response(null, { status: 204 }),
|
||||
});
|
||||
const { result } = await captureLogs(() => post(JSON.stringify(report)));
|
||||
assert.equal(result.status, 202);
|
||||
assert.deepEqual(await result.json(), { ok: true, degraded: true });
|
||||
assert.ok(!calls.some((c) => c.url.startsWith("https://gitlab.com/")));
|
||||
assert.ok(calls.some((c) => c.url.startsWith("https://discord.example/")));
|
||||
});
|
||||
|
||||
it("files a confidential issue that can't ping or command, then notifies Discord", async () => {
|
||||
const { calls } = route({
|
||||
[SITEVERIFY]: siteverify({ action: "report" }),
|
||||
"https://gitlab.com/": () =>
|
||||
jsonResponse({ web_url: "https://gitlab.com/poli0981/site-reports/-/issues/1" }, 201),
|
||||
"https://discord.example/": () => new Response(null, { status: 204 }),
|
||||
});
|
||||
const response = await post(JSON.stringify(report));
|
||||
assert.equal(response.status, 201);
|
||||
assert.deepEqual(await response.json(), { ok: true });
|
||||
|
||||
const issue = calls.find((c) => c.url.startsWith("https://api.github.com/"));
|
||||
assert.equal(issue?.url, "https://api.github.com/repos/poli0981/site-reports/issues");
|
||||
const issue = calls.find((c) => c.url.startsWith("https://gitlab.com/"));
|
||||
assert.equal(issue?.url, "https://gitlab.com/api/v4/projects/poli0981%2Fsite-reports/issues");
|
||||
assert.equal(issue?.headers.get("private-token"), "issues-token");
|
||||
const body = JSON.parse(issue?.body ?? "{}") as {
|
||||
title: string;
|
||||
body: string;
|
||||
labels: string[];
|
||||
description: string;
|
||||
labels: string;
|
||||
confidential: boolean;
|
||||
};
|
||||
assert.match(body.title, /^\[web-report\] /);
|
||||
assert.doesNotMatch(body.body, /@someone/); // the mention is broken up
|
||||
assert.match(body.body, /- Route: `\/gallery\/'x'\/`/);
|
||||
assert.match(body.body, /````\n\[2026-10-24T00:00:00Z\] error: boom ``` breakout\n````/);
|
||||
assert.deepEqual(body.labels, ["bug", "from-site"]);
|
||||
assert.doesNotMatch(body.description, /@someone/); // the mention is broken up
|
||||
assert.doesNotMatch(body.description, /^\/close/m); // no quick action at a line's start
|
||||
assert.match(body.description, /- Route: `\/gallery\/'x'\/`/);
|
||||
assert.match(body.description, /````\n\[2026-10-24T00:00:00Z\] error: boom ``` breakout\n````/);
|
||||
assert.equal(body.labels, "bug,from-site");
|
||||
assert.equal(body.confidential, true);
|
||||
|
||||
const discord = calls.find((c) => c.url.startsWith("https://discord.example/"));
|
||||
assert.deepEqual(JSON.parse(discord?.body ?? "{}").allowed_mentions, { parse: [] });
|
||||
});
|
||||
|
||||
it("still succeeds (degraded) when GitHub fails, and survives Discord failing", async () => {
|
||||
it("still succeeds (degraded) when GitLab fails, and survives Discord failing", async () => {
|
||||
route({
|
||||
[SITEVERIFY]: siteverify({ action: "report" }),
|
||||
"https://api.github.com/": () => jsonResponse({ message: "nope" }, 404),
|
||||
"https://gitlab.com/": () => jsonResponse({ message: "nope" }, 404),
|
||||
"https://discord.example/": () => {
|
||||
throw new Error("discord down");
|
||||
},
|
||||
@@ -180,26 +201,26 @@ describe("POST /api/report", () => {
|
||||
assert.equal(result.status, 202);
|
||||
assert.deepEqual(
|
||||
logs.map((line) => line.event),
|
||||
["report.github_failed", "report.discord_failed", "report.received"],
|
||||
["report.gitlab_failed", "report.discord_failed", "report.received"],
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the default repo and survives a GitHub network error", async () => {
|
||||
it("falls back to the mirror project and survives a GitLab network error", async () => {
|
||||
setWorkerEnv({});
|
||||
setServerEnv({ TURNSTILE_SECRET: TEST_SECRET, GITHUB_ISSUES_TOKEN: "t" });
|
||||
setServerEnv({ TURNSTILE_SECRET: TEST_SECRET, GITLAB_ISSUES_TOKEN: "t" });
|
||||
const { calls } = route({
|
||||
[SITEVERIFY]: siteverify({ action: "report" }),
|
||||
"https://api.github.com/": () => {
|
||||
"https://gitlab.com/": () => {
|
||||
throw new Error("network");
|
||||
},
|
||||
});
|
||||
const { result } = await captureLogs(() => post(JSON.stringify(report)));
|
||||
assert.equal(result.status, 202);
|
||||
assert.ok(calls.some((c) => c.url.includes("/repos/poli0981/site-reports/issues")));
|
||||
assert.ok(calls.some((c) => c.url.includes("/projects/poli0981%2Fpoli0981-dev/issues")));
|
||||
});
|
||||
|
||||
it("rejects a token minted for another form (with a real, non-test secret)", async () => {
|
||||
setServerEnv({ TURNSTILE_SECRET: "0x4AAAAAAA-real-secret", GITHUB_ISSUES_TOKEN: "t" });
|
||||
setServerEnv({ TURNSTILE_SECRET: "0x4AAAAAAA-real-secret", GITLAB_ISSUES_TOKEN: "t" });
|
||||
route({ [SITEVERIFY]: siteverify({ action: "gate" }) });
|
||||
const response = await post(JSON.stringify(report));
|
||||
assert.equal(response.status, 400);
|
||||
|
||||
@@ -225,10 +225,7 @@ describe("admin API client", () => {
|
||||
describe(400, { error: "invalid_fields", fields: [{ field: "lang" }, { field: "date" }] }),
|
||||
/lang, date/,
|
||||
);
|
||||
assert.match(
|
||||
describe(502, { error: "github_permission", needs: "contents=write" }),
|
||||
/contents=write/,
|
||||
);
|
||||
assert.match(describe(502, { error: "gitea_permission" }), /write:repository/);
|
||||
assert.match(describe(409), /Xung đột/);
|
||||
assert.match(describe(413), /20 MB/);
|
||||
assert.match(describe(415), /không được hỗ trợ/);
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// The Gitea half of a content publish (scripts/content-publish.mjs): the PR that
|
||||
// content-bump.yml opens, and the merge + deploy dispatch that ci.yml's publish job does.
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
BUILD_CONTEXT,
|
||||
gitea,
|
||||
isAuto,
|
||||
MARK_AUTO,
|
||||
MARK_REVIEW,
|
||||
merge,
|
||||
open,
|
||||
prBody,
|
||||
} from "../scripts/content-publish.mjs";
|
||||
|
||||
interface Sent {
|
||||
method: string;
|
||||
path: string;
|
||||
body: unknown;
|
||||
}
|
||||
|
||||
/** A fake Gitea for the site repo's pulls, comments and workflow dispatches. */
|
||||
function fakeGitea(pulls: Record<string, unknown>[], refuse: Record<string, number> = {}) {
|
||||
const sent: Sent[] = [];
|
||||
const fetch = async (url: string, init: RequestInit = {}) => {
|
||||
const { pathname, search } = new URL(url);
|
||||
const path = pathname.replace("/api/v1/repos/poli0981/poli0981-dev", "") + search;
|
||||
const method = init.method ?? "GET";
|
||||
sent.push({ method, path, body: init.body ? JSON.parse(String(init.body)) : undefined });
|
||||
assert.equal(new Headers(init.headers).get("authorization"), "token job-token");
|
||||
const status = refuse[`${method} ${path}`];
|
||||
if (status) return new Response(JSON.stringify({ message: "refused" }), { status });
|
||||
if (method === "GET" && path.startsWith("/pulls?")) return Response.json(pulls);
|
||||
if (method === "POST" && path === "/pulls") {
|
||||
return Response.json({ number: 7, html_url: "u" }, { status: 201 });
|
||||
}
|
||||
return new Response(null, { status: method === "POST" ? 201 : 200 });
|
||||
};
|
||||
const call = gitea({
|
||||
api: "https://git.poli0981.dev/api/v1",
|
||||
repo: "poli0981/poli0981-dev",
|
||||
token: "job-token",
|
||||
fetch: fetch as typeof globalThis.fetch,
|
||||
});
|
||||
return { call, sent };
|
||||
}
|
||||
|
||||
const bumpPull = (body: string, sha = "head-sha") => ({
|
||||
number: 5,
|
||||
title: "chore(content): publish from admin",
|
||||
body,
|
||||
head: { ref: "content/bump", sha },
|
||||
base: { ref: "main" },
|
||||
});
|
||||
const quiet = () => {};
|
||||
|
||||
describe("content publish: the PR body", () => {
|
||||
it("says whether CI merges it, in a marker the admin reads", () => {
|
||||
const auto = prBody("abc123", true);
|
||||
assert.match(auto, /poli0981\/content@abc123/);
|
||||
assert.ok(auto.endsWith(MARK_AUTO));
|
||||
assert.ok(isAuto(auto));
|
||||
const review = prBody("abc123", false);
|
||||
assert.ok(review.endsWith(MARK_REVIEW));
|
||||
assert.match(review, /waits for a review/);
|
||||
assert.equal(isAuto(review), false);
|
||||
assert.equal(isAuto(null), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("content publish: open", () => {
|
||||
it("opens the PR when there is none, then dispatches CI on the branch", async () => {
|
||||
const { call, sent } = fakeGitea([{ ...bumpPull(""), head: { ref: "other", sha: "x" } }]);
|
||||
assert.equal(await open({ call, contentCommit: "abc", auto: true, log: quiet }), 7);
|
||||
assert.deepEqual(
|
||||
sent.map((s) => `${s.method} ${s.path}`),
|
||||
[
|
||||
"GET /pulls?state=open&limit=50",
|
||||
"POST /pulls",
|
||||
"POST /actions/workflows/ci.yml/dispatches",
|
||||
],
|
||||
);
|
||||
assert.deepEqual(sent[1].body, {
|
||||
base: "main",
|
||||
head: "content/bump",
|
||||
title: "chore(content): publish from admin",
|
||||
body: prBody("abc", true),
|
||||
});
|
||||
assert.deepEqual(sent[2].body, { ref: "content/bump" });
|
||||
});
|
||||
|
||||
it("updates an open PR, and comments once when it turns to review", async () => {
|
||||
const { call, sent } = fakeGitea([bumpPull(prBody("old", true))]);
|
||||
await open({ call, contentCommit: "new", auto: false, log: quiet });
|
||||
assert.deepEqual(
|
||||
sent.map((s) => `${s.method} ${s.path}`),
|
||||
[
|
||||
"GET /pulls?state=open&limit=50",
|
||||
"PATCH /pulls/5",
|
||||
"POST /issues/5/comments",
|
||||
"POST /actions/workflows/ci.yml/dispatches",
|
||||
],
|
||||
);
|
||||
const again = fakeGitea([bumpPull(prBody("new", false))]);
|
||||
await open({ call: again.call, contentCommit: "newer", auto: false, log: quiet });
|
||||
assert.ok(!again.sent.some((s) => s.path.includes("/comments")));
|
||||
});
|
||||
|
||||
it("fails loudly when Gitea refuses", async () => {
|
||||
const { call } = fakeGitea([], { "POST /actions/workflows/ci.yml/dispatches": 403 });
|
||||
await assert.rejects(open({ call, contentCommit: "abc", auto: true, log: quiet }), /403/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("content publish: merge", () => {
|
||||
const RUN = "https://git.poli0981.dev/poli0981/poli0981-dev/actions/runs/7";
|
||||
|
||||
it("records the build as the required status, merges an auto PR, then dispatches main", async () => {
|
||||
const { call, sent } = fakeGitea([bumpPull(prBody("abc", true))]);
|
||||
assert.equal(await merge({ call, sha: "head-sha", runUrl: RUN, log: quiet }), "merged");
|
||||
assert.deepEqual(
|
||||
sent.map((s) => `${s.method} ${s.path}`),
|
||||
[
|
||||
"POST /statuses/head-sha",
|
||||
"GET /pulls?state=open&limit=50",
|
||||
"POST /pulls/5/merge",
|
||||
"POST /actions/workflows/ci.yml/dispatches",
|
||||
],
|
||||
);
|
||||
assert.deepEqual(sent[0].body, {
|
||||
state: "success",
|
||||
context: BUILD_CONTEXT,
|
||||
description: "build passed in this dispatched run",
|
||||
target_url: RUN,
|
||||
});
|
||||
// Branch protection requires "CI / build (*)"; the status must match it.
|
||||
assert.ok(BUILD_CONTEXT.startsWith("CI / build (") && BUILD_CONTEXT.endsWith(")"));
|
||||
assert.deepEqual(sent[2].body, {
|
||||
Do: "squash",
|
||||
MergeTitleField: "chore(content): publish from admin (#5)",
|
||||
head_commit_id: "head-sha",
|
||||
delete_branch_after_merge: true,
|
||||
});
|
||||
assert.deepEqual(sent[3].body, { ref: "main" });
|
||||
});
|
||||
|
||||
it("records a failed build and merges nothing; a cancelled one is left alone", async () => {
|
||||
const failed = fakeGitea([bumpPull(prBody("abc", true))]);
|
||||
assert.equal(
|
||||
await merge({ call: failed.call, sha: "head-sha", build: "failure", log: quiet }),
|
||||
"failed",
|
||||
);
|
||||
assert.deepEqual(
|
||||
failed.sent.map((s) => `${s.method} ${s.path}`),
|
||||
["POST /statuses/head-sha"],
|
||||
);
|
||||
assert.equal((failed.sent[0].body as { state: string }).state, "failure");
|
||||
const cancelled = fakeGitea([bumpPull(prBody("abc", true))]);
|
||||
assert.equal(
|
||||
await merge({ call: cancelled.call, sha: "head-sha", build: "cancelled", log: quiet }),
|
||||
"skipped",
|
||||
);
|
||||
assert.deepEqual(cancelled.sent, []);
|
||||
});
|
||||
|
||||
it("leaves alone: no PR, a PR that moved on, a PR waiting for review", async () => {
|
||||
assert.equal(await merge({ call: fakeGitea([]).call, sha: "s", log: quiet }), "none");
|
||||
const moved = fakeGitea([bumpPull(prBody("abc", true), "newer-sha")]);
|
||||
assert.equal(await merge({ call: moved.call, sha: "head-sha", log: quiet }), "moved");
|
||||
const review = fakeGitea([bumpPull(prBody("abc", false))]);
|
||||
assert.equal(await merge({ call: review.call, sha: "head-sha", log: quiet }), "review");
|
||||
for (const fake of [moved, review]) {
|
||||
// The status is still recorded (the owner's merge by hand needs it); nothing else.
|
||||
assert.deepEqual(
|
||||
fake.sent.filter((s) => s.method !== "GET").map((s) => s.path),
|
||||
["/statuses/head-sha"],
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("says so on the PR when the merge is refused, and fails", async () => {
|
||||
const { call, sent } = fakeGitea([bumpPull(prBody("abc", true))], {
|
||||
"POST /pulls/5/merge": 405,
|
||||
});
|
||||
await assert.rejects(merge({ call, sha: "head-sha", log: quiet }), /405/);
|
||||
const comment = sent.find((s) => s.path === "/issues/5/comments");
|
||||
assert.match(String((comment?.body as { body: string }).body), /Merge it by hand/);
|
||||
assert.ok(!sent.some((s) => s.path.includes("/dispatches")));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
// A fake Gitea API (git.poli0981.dev) holding the poli0981/content repo in memory — enough of
|
||||
// the REST API for src/lib/admin/gitea.ts — wired up through mockFetch().
|
||||
import { jsonResponse, mockFetch, type FetchCall } from "./fakes.ts";
|
||||
|
||||
const ORIGIN = "https://git.poli0981.dev";
|
||||
const CONTENT = "/api/v1/repos/poli0981/content";
|
||||
const SITE = "/api/v1/repos/poli0981/poli0981-dev";
|
||||
|
||||
const shaOf = (text: string) => {
|
||||
let hash = 0;
|
||||
for (const char of text) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) | 0;
|
||||
return `sha-${(hash >>> 0).toString(16)}`;
|
||||
};
|
||||
|
||||
const toBase64 = (text: string) => {
|
||||
let binary = "";
|
||||
for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
|
||||
return btoa(binary);
|
||||
};
|
||||
|
||||
const fromBase64 = (data: string) =>
|
||||
new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0)));
|
||||
|
||||
interface ChangeFile {
|
||||
operation: "create" | "update" | "delete";
|
||||
path: string;
|
||||
content?: string;
|
||||
sha?: string | null;
|
||||
}
|
||||
|
||||
export class FakeGitea {
|
||||
readonly files = new Map<string, string>();
|
||||
head = "commit-0";
|
||||
commits = 0;
|
||||
/** Answer the next commits with 422 "sha does not match" (a save raced another). */
|
||||
staleCommits = 0;
|
||||
/** Answer every call with this status (e.g. 403 for a token without access). */
|
||||
failAll: { status: number } | null = null;
|
||||
publishedSha = "commit-0";
|
||||
openPr: { number: number; headSha: string; autoMerge: boolean } | null = null;
|
||||
/** The `CI / build` commit status on the PR's head: pending | success | failure | error. */
|
||||
buildCheck: string | null = null;
|
||||
lastRun: { status: string; conclusion: string | null } | null = null;
|
||||
readonly dispatched: string[] = [];
|
||||
/** Answer workflow dispatches with this status instead of 204 (a bot without access). */
|
||||
failDispatch: number | null = null;
|
||||
/** The repo's files at older commits, for reads `at` a sha (listContentFiles). */
|
||||
readonly snapshots = new Map<string, Record<string, string>>();
|
||||
/** Commits made through the API, newest first (GET …/commits). */
|
||||
readonly history: { sha: string; message: string }[] = [];
|
||||
readonly calls: FetchCall[];
|
||||
readonly restore: () => void;
|
||||
|
||||
constructor(files: Record<string, string> = {}) {
|
||||
for (const [path, text] of Object.entries(files)) this.files.set(path, text);
|
||||
const mock = mockFetch((call) => this.route(call));
|
||||
this.calls = mock.calls;
|
||||
this.restore = mock.restore;
|
||||
}
|
||||
|
||||
sha(path: string): string | null {
|
||||
const text = this.files.get(path);
|
||||
return text === undefined ? null : shaOf(text);
|
||||
}
|
||||
|
||||
/** The files at a ref: main or the head commit, a snapshot, or null (no such commit). */
|
||||
private filesAt(ref: string): Map<string, string> | null {
|
||||
if (ref === "main" || ref === this.head) return this.files;
|
||||
const snapshot = this.snapshots.get(ref);
|
||||
return snapshot ? new Map(Object.entries(snapshot)) : null;
|
||||
}
|
||||
|
||||
private route(call: FetchCall): Response {
|
||||
const url = new URL(call.url);
|
||||
if (url.origin !== ORIGIN) throw new Error(`unexpected fetch ${call.url}`);
|
||||
if (this.failAll)
|
||||
return jsonResponse({ message: "token does not have access" }, this.failAll.status);
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
const body = call.body ? (JSON.parse(call.body) as Record<string, unknown>) : {};
|
||||
|
||||
if (path === `${CONTENT}/branches/main`) return jsonResponse({ commit: { id: this.head } });
|
||||
if (path.startsWith(`${CONTENT}/git/trees/`)) {
|
||||
const files = this.filesAt(path.slice(`${CONTENT}/git/trees/`.length));
|
||||
if (!files) return jsonResponse({ message: "sha not found" }, 404);
|
||||
const tree = [...files.entries()].sort().map(([file, text]) => ({
|
||||
path: file,
|
||||
type: "blob",
|
||||
sha: shaOf(text),
|
||||
size: new TextEncoder().encode(text).length,
|
||||
}));
|
||||
return jsonResponse({
|
||||
sha: "tree",
|
||||
tree,
|
||||
truncated: false,
|
||||
page: 1,
|
||||
total_count: tree.length,
|
||||
});
|
||||
}
|
||||
if (path === `${CONTENT}/file-contents` && call.method === "POST") {
|
||||
const files = this.filesAt(url.searchParams.get("ref") ?? "main") ?? new Map();
|
||||
return jsonResponse(
|
||||
(body.files as string[]).map((file) => {
|
||||
const text = files.get(file);
|
||||
return text === undefined
|
||||
? null
|
||||
: {
|
||||
path: file,
|
||||
type: "file",
|
||||
sha: shaOf(text),
|
||||
encoding: "base64",
|
||||
content: toBase64(text),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (path.startsWith(`${CONTENT}/contents/`) && call.method === "GET") {
|
||||
const file = path.slice(`${CONTENT}/contents/`.length);
|
||||
const text = this.files.get(file);
|
||||
if (text === undefined) return jsonResponse({ message: "object does not exist" }, 404);
|
||||
return jsonResponse({
|
||||
path: file,
|
||||
type: "file",
|
||||
sha: shaOf(text),
|
||||
content: toBase64(text),
|
||||
encoding: "base64",
|
||||
});
|
||||
}
|
||||
if (path === `${CONTENT}/contents` && call.method === "POST") return this.changeFiles(body);
|
||||
if (path === `${CONTENT}/commits`) {
|
||||
return jsonResponse(
|
||||
this.history.map((c) => ({
|
||||
sha: c.sha,
|
||||
html_url: `${ORIGIN}/poli0981/content/commit/${c.sha}`,
|
||||
commit: { message: c.message, author: { name: "admin", date: "2026-10-24T00:00:00Z" } },
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
if (path === `${SITE}/contents/src/content`) {
|
||||
return jsonResponse({ path: "src/content", type: "submodule", sha: this.publishedSha });
|
||||
}
|
||||
if (path === `${SITE}/pulls`) {
|
||||
return jsonResponse(
|
||||
this.openPr
|
||||
? [
|
||||
{
|
||||
number: this.openPr.number,
|
||||
html_url: `${ORIGIN}/poli0981/poli0981-dev/pulls/${this.openPr.number}`,
|
||||
body: `Bumps src/content.\n\n${this.openPr.autoMerge ? "<!-- publish: auto -->" : "<!-- publish: review -->"}`,
|
||||
head: { ref: "content/bump", sha: this.openPr.headSha },
|
||||
base: { ref: "main" },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
if (path.startsWith(`${SITE}/commits/`) && path.endsWith("/status")) {
|
||||
return jsonResponse({
|
||||
state: this.buildCheck ?? "pending",
|
||||
statuses: this.buildCheck
|
||||
? [
|
||||
{ context: "Security / security (workflow_dispatch)", status: "success" },
|
||||
{ context: "CI / build (workflow_dispatch)", status: this.buildCheck },
|
||||
]
|
||||
: [],
|
||||
});
|
||||
}
|
||||
if (path === `${SITE}/actions/workflows/content-bump.yml/runs`) {
|
||||
return jsonResponse({
|
||||
workflow_runs: this.lastRun
|
||||
? [{ ...this.lastRun, html_url: `${ORIGIN}/poli0981/poli0981-dev/actions/runs/1` }]
|
||||
: [],
|
||||
total_count: this.lastRun ? 1 : 0,
|
||||
});
|
||||
}
|
||||
if (
|
||||
path === `${SITE}/actions/workflows/content-bump.yml/dispatches` &&
|
||||
call.method === "POST"
|
||||
) {
|
||||
if (this.failDispatch) {
|
||||
return jsonResponse({ message: "user does not have permission" }, this.failDispatch);
|
||||
}
|
||||
this.dispatched.push(String(body.ref));
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
throw new Error(`FakeGitea: unhandled ${call.method} ${path}`);
|
||||
}
|
||||
|
||||
/** POST /repos/{owner}/{repo}/contents: several files in one commit, each sha checked. */
|
||||
private changeFiles(body: Record<string, unknown>): Response {
|
||||
const changes = body.files as ChangeFile[];
|
||||
if (this.staleCommits > 0) {
|
||||
this.staleCommits -= 1;
|
||||
return jsonResponse({ message: "sha does not match [given: x, expected: y]" }, 422);
|
||||
}
|
||||
for (const change of changes) {
|
||||
const current = this.sha(change.path);
|
||||
if (change.operation === "create" && current !== null) {
|
||||
return jsonResponse(
|
||||
{ message: `repository file already exists [path: ${change.path}]` },
|
||||
422,
|
||||
);
|
||||
}
|
||||
if (change.operation !== "create" && current === null) {
|
||||
return jsonResponse({ message: `file does not exist [path: ${change.path}]` }, 404);
|
||||
}
|
||||
if (change.operation !== "create" && change.sha !== current) {
|
||||
return jsonResponse({ message: "sha does not match" }, 422);
|
||||
}
|
||||
}
|
||||
for (const change of changes) {
|
||||
if (change.operation === "delete") this.files.delete(change.path);
|
||||
else this.files.set(change.path, fromBase64(String(change.content)));
|
||||
}
|
||||
this.commits += 1;
|
||||
this.head = `commit-${this.commits}`;
|
||||
this.history.unshift({ sha: this.head, message: String(body.message) });
|
||||
return jsonResponse({ commit: { sha: this.head } }, 201);
|
||||
}
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
// A fake GitHub API holding the poli0981/content repo in memory — enough REST, Git Data and
|
||||
// GraphQL for src/lib/admin/github.ts — wired up through mockFetch().
|
||||
import { jsonResponse, mockFetch, type FetchCall } from "./fakes.ts";
|
||||
|
||||
const CONTENT = "/repos/poli0981/content";
|
||||
const SITE = "/repos/poli0981/poli0981-dev";
|
||||
|
||||
const shaOf = (text: string) => {
|
||||
let hash = 0;
|
||||
for (const char of text) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) | 0;
|
||||
return `sha-${(hash >>> 0).toString(16)}`;
|
||||
};
|
||||
|
||||
const toBase64 = (text: string) => btoa(String.fromCharCode(...new TextEncoder().encode(text)));
|
||||
|
||||
export class FakeGitHub {
|
||||
readonly files = new Map<string, string>();
|
||||
head = "commit-0";
|
||||
commits = 0;
|
||||
/** Make the next ref update answer 422 (someone pushed in between) this many times. */
|
||||
raceRefUpdates = 0;
|
||||
/** Answer every call with this status (e.g. 403 for a token without permission). */
|
||||
failAll: { status: number; needs?: string } | null = null;
|
||||
publishedSha = "commit-0";
|
||||
openPr: { number: number; headSha: string; autoMerge: boolean } | null = null;
|
||||
buildCheck: { status: string; conclusion: string | null } | null = null;
|
||||
lastRun: { status: string; conclusion: string | null } | null = null;
|
||||
readonly dispatched: string[] = [];
|
||||
/** Answer workflow dispatches with this status instead of 204 (a token without Actions). */
|
||||
failDispatch: number | null = null;
|
||||
/** The repo's files at older commits, for GraphQL reads `at` a sha (listContentFiles). */
|
||||
readonly snapshots = new Map<string, Record<string, string>>();
|
||||
/** Commits made through the API, newest first (GET …/commits). */
|
||||
readonly history: { sha: string; message: string }[] = [];
|
||||
private pendingMessage = "";
|
||||
readonly calls: FetchCall[];
|
||||
readonly restore: () => void;
|
||||
|
||||
constructor(files: Record<string, string> = {}) {
|
||||
for (const [path, text] of Object.entries(files)) this.files.set(path, text);
|
||||
const mock = mockFetch((call) => this.route(call));
|
||||
this.calls = mock.calls;
|
||||
this.restore = mock.restore;
|
||||
}
|
||||
|
||||
sha(path: string): string | null {
|
||||
const text = this.files.get(path);
|
||||
return text === undefined ? null : shaOf(text);
|
||||
}
|
||||
|
||||
private route(call: FetchCall): Response {
|
||||
const url = new URL(call.url);
|
||||
if (url.origin !== "https://api.github.com") throw new Error(`unexpected fetch ${call.url}`);
|
||||
if (this.failAll) {
|
||||
return jsonResponse(
|
||||
{ message: "Resource not accessible by personal access token" },
|
||||
this.failAll.status,
|
||||
{
|
||||
...(this.failAll.needs ? { "x-accepted-github-permissions": this.failAll.needs } : {}),
|
||||
},
|
||||
);
|
||||
}
|
||||
const path = decodeURIComponent(url.pathname);
|
||||
const body = call.body ? (JSON.parse(call.body) as Record<string, unknown>) : {};
|
||||
|
||||
if (path === "/graphql") {
|
||||
const expr = String((body.variables as { expr?: string } | undefined)?.expr ?? "main:");
|
||||
const at = expr.slice(0, -1);
|
||||
if (at === "main" || at === this.head) return jsonResponse({ data: this.graphqlTree() });
|
||||
const snapshot = this.snapshots.get(at);
|
||||
return jsonResponse({
|
||||
data: this.graphqlTree(snapshot ? new Map(Object.entries(snapshot)) : null),
|
||||
});
|
||||
}
|
||||
|
||||
if (path.startsWith(`${CONTENT}/contents/`)) {
|
||||
const file = path.slice(`${CONTENT}/contents/`.length);
|
||||
const text = this.files.get(file);
|
||||
if (text === undefined) return jsonResponse({ message: "Not Found" }, 404);
|
||||
return jsonResponse({ sha: shaOf(text), content: toBase64(text), encoding: "base64" });
|
||||
}
|
||||
if (path === `${CONTENT}/git/ref/heads/main`)
|
||||
return jsonResponse({ object: { sha: this.head } });
|
||||
if (path.startsWith(`${CONTENT}/git/commits/`))
|
||||
return jsonResponse({ tree: { sha: `tree-of-${this.head}` } });
|
||||
if (path === `${CONTENT}/git/trees` && call.method === "POST") {
|
||||
this.pendingTree = body.tree as { path: string; sha?: null; content?: string }[];
|
||||
return jsonResponse({ sha: "new-tree" }, 201);
|
||||
}
|
||||
if (path === `${CONTENT}/git/commits` && call.method === "POST") {
|
||||
this.pendingMessage = String(body.message);
|
||||
return jsonResponse({ sha: `commit-${this.commits + 1}`, message: body.message }, 201);
|
||||
}
|
||||
if (path === `${CONTENT}/git/refs/heads/main` && call.method === "PATCH") {
|
||||
if (this.raceRefUpdates > 0) {
|
||||
this.raceRefUpdates -= 1;
|
||||
return jsonResponse({ message: "Update is not a fast forward" }, 422);
|
||||
}
|
||||
for (const entry of this.pendingTree) {
|
||||
if (entry.content === undefined) this.files.delete(entry.path);
|
||||
else this.files.set(entry.path, entry.content);
|
||||
}
|
||||
this.commits += 1;
|
||||
this.head = String(body.sha);
|
||||
this.history.unshift({ sha: this.head, message: this.pendingMessage });
|
||||
return jsonResponse({ object: { sha: this.head } });
|
||||
}
|
||||
|
||||
if (path === `${CONTENT}/commits`) {
|
||||
return jsonResponse(
|
||||
this.history.map((c) => ({
|
||||
sha: c.sha,
|
||||
html_url: `https://github.com/poli0981/content/commit/${c.sha}`,
|
||||
commit: { message: c.message, author: { name: "admin", date: "2026-10-24T00:00:00Z" } },
|
||||
})),
|
||||
);
|
||||
}
|
||||
if (path === `${SITE}/contents/src/content`) return jsonResponse({ sha: this.publishedSha });
|
||||
if (path === `${SITE}/pulls`) {
|
||||
return jsonResponse(
|
||||
this.openPr
|
||||
? [
|
||||
{
|
||||
number: this.openPr.number,
|
||||
html_url: `https://github.com/poli0981/poli0981-dev/pull/${this.openPr.number}`,
|
||||
auto_merge: this.openPr.autoMerge ? { method: "squash" } : null,
|
||||
head: { sha: this.openPr.headSha },
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
if (path.startsWith(`${SITE}/commits/`) && path.endsWith("/check-runs")) {
|
||||
return jsonResponse({
|
||||
check_runs: this.buildCheck ? [{ name: "build", ...this.buildCheck }] : [],
|
||||
});
|
||||
}
|
||||
if (path === `${SITE}/actions/workflows/content-bump.yml/runs`) {
|
||||
return jsonResponse({
|
||||
workflow_runs: this.lastRun
|
||||
? [{ ...this.lastRun, html_url: "https://github.com/run/1" }]
|
||||
: [],
|
||||
});
|
||||
}
|
||||
if (
|
||||
path === `${SITE}/actions/workflows/content-bump.yml/dispatches` &&
|
||||
call.method === "POST"
|
||||
) {
|
||||
if (this.failDispatch) {
|
||||
return jsonResponse({ message: "Resource not accessible" }, this.failDispatch);
|
||||
}
|
||||
this.dispatched.push(String(body.ref));
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
throw new Error(`FakeGitHub: unhandled ${call.method} ${path}`);
|
||||
}
|
||||
|
||||
private pendingTree: { path: string; sha?: null; content?: string }[] = [];
|
||||
|
||||
/**
|
||||
* The GraphQL tree query's answer: collection/series/file, three levels deep — of the
|
||||
* current files, of a snapshot, or (null) a commit the repo doesn't have: no tree at all.
|
||||
*/
|
||||
private graphqlTree(files: Map<string, string> | null = this.files) {
|
||||
if (!files) return { repository: { ref: { target: { oid: this.head } }, object: null } };
|
||||
type Node = { path: string; type: string; object: Record<string, unknown> };
|
||||
const root: Node[] = [];
|
||||
const dirs = new Map<string, Node[]>([["", root]]);
|
||||
const ensureDir = (dir: string): Node[] => {
|
||||
const existing = dirs.get(dir);
|
||||
if (existing) return existing;
|
||||
const parent = dir.includes("/") ? dir.slice(0, dir.lastIndexOf("/")) : "";
|
||||
const entries: Node[] = [];
|
||||
ensureDir(parent).push({ path: dir, type: "tree", object: { entries } });
|
||||
dirs.set(dir, entries);
|
||||
return entries;
|
||||
};
|
||||
for (const [path, text] of [...files.entries()].sort()) {
|
||||
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
|
||||
ensureDir(dir).push({ path, type: "blob", object: { oid: shaOf(text), text } });
|
||||
}
|
||||
return { repository: { ref: { target: { oid: this.head } }, object: { entries: root } } };
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,17 @@
|
||||
// with setServerEnv(), and modules that imported the names see the change (ES live bindings).
|
||||
|
||||
export let TURNSTILE_SECRET: string | undefined;
|
||||
export let GITHUB_ISSUES_TOKEN: string | undefined;
|
||||
export let GITLAB_ISSUES_TOKEN: string | undefined;
|
||||
export let DISCORD_WEBHOOK_BUG: string | undefined;
|
||||
export let GITHUB_CONTENT_TOKEN: string | undefined;
|
||||
export let GITHUB_PUBLISH_TOKEN: string | undefined;
|
||||
export let GITEA_BOT_TOKEN: string | undefined;
|
||||
export let ADMIN_EMAILS: string | undefined;
|
||||
export let GATE_SECRET: string | undefined;
|
||||
|
||||
export interface ServerEnv {
|
||||
TURNSTILE_SECRET?: string;
|
||||
GITHUB_ISSUES_TOKEN?: string;
|
||||
GITLAB_ISSUES_TOKEN?: string;
|
||||
DISCORD_WEBHOOK_BUG?: string;
|
||||
GITHUB_CONTENT_TOKEN?: string;
|
||||
GITHUB_PUBLISH_TOKEN?: string;
|
||||
GITEA_BOT_TOKEN?: string;
|
||||
ADMIN_EMAILS?: string;
|
||||
GATE_SECRET?: string;
|
||||
}
|
||||
@@ -22,10 +20,9 @@ export interface ServerEnv {
|
||||
/** Replace the whole server env: names not given become unset. */
|
||||
export function setServerEnv(values: ServerEnv = {}): void {
|
||||
TURNSTILE_SECRET = values.TURNSTILE_SECRET;
|
||||
GITHUB_ISSUES_TOKEN = values.GITHUB_ISSUES_TOKEN;
|
||||
GITLAB_ISSUES_TOKEN = values.GITLAB_ISSUES_TOKEN;
|
||||
DISCORD_WEBHOOK_BUG = values.DISCORD_WEBHOOK_BUG;
|
||||
GITHUB_CONTENT_TOKEN = values.GITHUB_CONTENT_TOKEN;
|
||||
GITHUB_PUBLISH_TOKEN = values.GITHUB_PUBLISH_TOKEN;
|
||||
GITEA_BOT_TOKEN = values.GITEA_BOT_TOKEN;
|
||||
ADMIN_EMAILS = values.ADMIN_EMAILS;
|
||||
GATE_SECRET = values.GATE_SECRET;
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
// Maintenance-mode triage (scripts/triage.mjs): which issues and pull requests the bot closes
|
||||
// as feature requests, and which it must leave alone.
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { closingComment, decide, LABELS } from "../scripts/triage.mjs";
|
||||
|
||||
const outsider = { labels: [] as string[], author: "someone", association: "NONE" };
|
||||
|
||||
describe("triage", () => {
|
||||
it("closes clear feature requests, in either language", () => {
|
||||
for (const title of [
|
||||
"feat: dark mode for the admin",
|
||||
"feat(ui)!: new home page",
|
||||
"[Feature] Comments under posts",
|
||||
"[đề xuất] thêm trang tìm kiếm nâng cao",
|
||||
"Feature request: RSS for the gallery",
|
||||
"Add a feature to export posts",
|
||||
"Đề xuất tính năng: chế độ đọc to",
|
||||
"Thêm tính năng bình luận",
|
||||
"Tính năng mới: newsletter",
|
||||
]) {
|
||||
assert.equal(decide({ ...outsider, title }).action, "close", title);
|
||||
}
|
||||
assert.equal(
|
||||
decide({ ...outsider, title: "Comments please", labels: ["Enhancement"] }).action,
|
||||
"close",
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves bugs, fixes and questions alone, even when they say 'add'", () => {
|
||||
for (const title of [
|
||||
"[web-report] Menu does not close on iPhone",
|
||||
"[a11y] Focus lost after closing the viewer",
|
||||
"fix: wrong date on the now page",
|
||||
"Typo in the privacy policy (vi)",
|
||||
"Please add alt text to the gallery cover",
|
||||
"How do I run the site locally?",
|
||||
"Lỗi chính tả trong trang giới thiệu",
|
||||
]) {
|
||||
assert.equal(decide({ ...outsider, title }).action, "none", title);
|
||||
}
|
||||
});
|
||||
|
||||
it("never closes the owner's items, bots, exceptions, or anything already closed", () => {
|
||||
const title = "feat: something new";
|
||||
assert.equal(decide({ ...outsider, title, association: "OWNER" }).reason, "trusted author");
|
||||
assert.equal(decide({ ...outsider, title, author: "dependabot[bot]" }).reason, "bot");
|
||||
assert.equal(
|
||||
decide({ ...outsider, title, labels: ["maintenance-exception"] }).reason,
|
||||
"owner's exception",
|
||||
);
|
||||
assert.equal(
|
||||
decide({ ...outsider, title, sender: "poli0981", owner: "poli0981" }).reason,
|
||||
"the owner acted on it",
|
||||
);
|
||||
assert.equal(decide({ ...outsider, title, state: "closed" }).reason, "not open");
|
||||
assert.equal(decide({ ...outsider, title, state: "open" }).action, "close");
|
||||
});
|
||||
|
||||
it("explains itself in Vietnamese and English and links the policy", () => {
|
||||
const issue = closingComment("issue");
|
||||
assert.match(issue, /chế độ bảo trì/);
|
||||
assert.match(issue, /maintenance mode/);
|
||||
assert.match(issue, /this issue was closed/);
|
||||
assert.match(closingComment("pull_request"), /this pull request was closed/);
|
||||
assert.match(issue, /CONTRIBUTING\.md/);
|
||||
assert.deepEqual(Object.values(LABELS), [
|
||||
"enhancement",
|
||||
"out-of-scope",
|
||||
"maintenance-exception",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,12 @@ import { afterEach, beforeEach, describe, it } from "node:test";
|
||||
import { captureLogs, FakeKV, jsonResponse, mockFetch, type FetchCall } from "./support/fakes.ts";
|
||||
import {
|
||||
decodeXml,
|
||||
fetchGitHub,
|
||||
fetchGitea,
|
||||
GITEA_FEED,
|
||||
fetchSteam,
|
||||
fetchYouTube,
|
||||
mirrorImage,
|
||||
normalizeGitHub,
|
||||
normalizeGitea,
|
||||
normalizeSteam,
|
||||
parseYouTube,
|
||||
refresh,
|
||||
@@ -51,25 +52,27 @@ function upstream(
|
||||
},
|
||||
})
|
||||
);
|
||||
if (url.startsWith("https://api.github.com/"))
|
||||
if (url.startsWith("https://git.poli0981.dev/"))
|
||||
return (
|
||||
overrides.gh?.(call) ??
|
||||
jsonResponse([
|
||||
{
|
||||
type: "PushEvent",
|
||||
repo: { name: "poli0981/a" },
|
||||
created_at: "t1",
|
||||
payload: { commits: [1, 2] },
|
||||
op_type: "commit_repo",
|
||||
repo: { full_name: "poli0981/a" },
|
||||
ref_name: "refs/heads/main",
|
||||
created: "t1",
|
||||
content: JSON.stringify({ Commits: [{}, {}], Len: 2 }),
|
||||
},
|
||||
{ type: "WatchEvent" },
|
||||
{ op_type: "delete_branch", repo: { full_name: "poli0981/a" } },
|
||||
{
|
||||
type: "ReleaseEvent",
|
||||
repo: { name: "poli0981/b" },
|
||||
created_at: "t2",
|
||||
payload: { release: { tag_name: "v1" } },
|
||||
op_type: "publish_release",
|
||||
repo: { full_name: "poli0981/b" },
|
||||
ref_name: "refs/tags/v1",
|
||||
created: "t2",
|
||||
content: "v1",
|
||||
},
|
||||
{ type: "ReleaseEvent", payload: {} },
|
||||
{ type: "PushEvent" },
|
||||
{ op_type: "publish_release" },
|
||||
{ op_type: "commit_repo", content: "" },
|
||||
])
|
||||
);
|
||||
if (
|
||||
@@ -107,7 +110,7 @@ describe("widget sources", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes Steam games and GitHub events", () => {
|
||||
it("normalizes Steam games and Gitea activity", () => {
|
||||
const games = normalizeSteam({
|
||||
response: { games: [{ appid: 1, img_icon_url: HASH }, { appid: 2 }] },
|
||||
});
|
||||
@@ -119,18 +122,31 @@ describe("widget sources", () => {
|
||||
],
|
||||
);
|
||||
assert.deepEqual(normalizeSteam({}), []);
|
||||
const events = normalizeGitHub([
|
||||
{ type: "PushEvent", repo: { name: "r" }, created_at: "t", payload: { commits: [1] } },
|
||||
{ type: "IssuesEvent" },
|
||||
{ type: "ReleaseEvent", payload: {} },
|
||||
{ type: "PushEvent" },
|
||||
{ type: "PushEvent" },
|
||||
const push = (content: string) => ({ op_type: "commit_repo", content });
|
||||
const events = normalizeGitea([
|
||||
{ ...push(JSON.stringify({ Commits: [{}], Len: 28 })), repo: { full_name: "r" } },
|
||||
{ op_type: "create_pull_request" },
|
||||
push(""), // Gitea lists some pushes twice, the second time without content
|
||||
push("{not json"),
|
||||
push(JSON.stringify({ Commits: [] })), // nothing pushed: skipped
|
||||
{ op_type: "publish_release", content: "Title" },
|
||||
push(JSON.stringify({ Commits: [{}, {}] })), // no Len: count the commits
|
||||
{ op_type: "publish_release", ref_name: "refs/tags/v2" },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
events.map((e) => e.detail),
|
||||
["1 commits", "release", "0 commits"],
|
||||
events.map((e) => [e.type, e.detail]),
|
||||
[
|
||||
["PushEvent", "28 commits"],
|
||||
["ReleaseEvent", "Title"],
|
||||
["PushEvent", "2 commits"],
|
||||
],
|
||||
);
|
||||
assert.equal(events[0].repo, "r");
|
||||
assert.equal(events[1].repo, "N/A");
|
||||
assert.deepEqual(
|
||||
normalizeGitea([{ op_type: "publish_release" }]).map((e) => e.detail),
|
||||
["release"],
|
||||
);
|
||||
});
|
||||
|
||||
it("mirrors pictures into KV under the /ext-img keys, refusing junk", async () => {
|
||||
@@ -200,15 +216,18 @@ describe("widget sources", () => {
|
||||
[`/ext-img/steam/570/${HASH}`, ""],
|
||||
);
|
||||
assert.ok(calls.some((c) => c.url.includes("key=key%26x")));
|
||||
// Push, release, release-without-a-tag — WatchEvent skipped, capped at three.
|
||||
// Push, release, release-without-a-tag — the branch deletion skipped, capped at three.
|
||||
assert.deepEqual(
|
||||
(await fetchGitHub({})).map((e) => e.detail),
|
||||
["2 commits", "v1", "release"],
|
||||
(await fetchGitea()).map((e) => [e.repo, e.detail]),
|
||||
[
|
||||
["poli0981/a", "2 commits"],
|
||||
["poli0981/b", "v1"],
|
||||
["N/A", "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");
|
||||
const gh = calls.find((c) => c.url.startsWith("https://git.poli0981.dev/"));
|
||||
assert.equal(gh?.url, GITEA_FEED);
|
||||
assert.equal(gh?.headers.get("authorization"), null); // public data: no token
|
||||
assert.ok(kv.store.has(`widgets:img:steam:570:${HASH}`));
|
||||
});
|
||||
|
||||
@@ -231,7 +250,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(fetchGitea(), /gitea 503/);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -25,12 +25,6 @@ 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;
|
||||
@@ -42,13 +36,9 @@ 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, token?: string) =>
|
||||
const get = (url: string, accept?: string) =>
|
||||
fetch(url, {
|
||||
headers: {
|
||||
"user-agent": UA,
|
||||
...(accept ? { accept } : {}),
|
||||
...(token ? { authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
headers: { "user-agent": UA, ...(accept ? { accept } : {}) },
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
|
||||
@@ -98,24 +88,51 @@ export function normalizeSteam(data: SteamResp): (GameItem & { iconHash: string
|
||||
}));
|
||||
}
|
||||
|
||||
export interface GhEvent {
|
||||
type?: string;
|
||||
repo?: { name?: string };
|
||||
created_at?: string;
|
||||
payload?: { commits?: unknown[]; release?: { tag_name?: string } };
|
||||
/** One entry of Gitea's activity feed (GET /users/{user}/activities/feeds). */
|
||||
export interface GiteaActivity {
|
||||
op_type?: string;
|
||||
repo?: { full_name?: string };
|
||||
/** `refs/heads/<branch>` for a push, `refs/tags/<tag>` for a release. */
|
||||
ref_name?: string;
|
||||
/** A push: JSON with `Len` (commits pushed) and up to five `Commits`. A release: its title. */
|
||||
content?: string;
|
||||
created?: string;
|
||||
}
|
||||
|
||||
/** The three newest pushes/releases from a public event list. */
|
||||
export function normalizeGitHub(events: GhEvent[]): GhItem[] {
|
||||
/**
|
||||
* Commits in a push, from the feed entry's JSON. null when there is none to read: the feed
|
||||
* lists some pushes a second time with empty content, and those are skipped.
|
||||
*/
|
||||
function pushedCommits(content: string | undefined): number | null {
|
||||
if (!content) return null;
|
||||
try {
|
||||
const data = JSON.parse(content) as { Len?: unknown; Commits?: unknown };
|
||||
if (typeof data.Len === "number") return data.Len;
|
||||
return Array.isArray(data.Commits) ? data.Commits.length : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The three newest pushes/releases from a public activity feed, in the shape the widget has
|
||||
* always stored (`PushEvent` / `ReleaseEvent`, GitHub's names), so a feed kept in KV from
|
||||
* before the move to Gitea still renders.
|
||||
*/
|
||||
export function normalizeGitea(activities: GiteaActivity[]): GhItem[] {
|
||||
const items: GhItem[] = [];
|
||||
for (const e of events) {
|
||||
for (const a of activities) {
|
||||
if (items.length >= 3) break;
|
||||
if (e.type !== "PushEvent" && e.type !== "ReleaseEvent") continue;
|
||||
const detail =
|
||||
e.type === "PushEvent"
|
||||
? `${e.payload?.commits?.length ?? 0} commits`
|
||||
: (e.payload?.release?.tag_name ?? "release");
|
||||
items.push({ type: e.type, repo: e.repo?.name ?? "N/A", ts: e.created_at ?? "", detail });
|
||||
const repo = a.repo?.full_name ?? "N/A";
|
||||
const ts = a.created ?? "";
|
||||
if (a.op_type === "commit_repo") {
|
||||
const commits = pushedCommits(a.content);
|
||||
if (!commits) continue;
|
||||
items.push({ type: "PushEvent", repo, ts, detail: `${commits} commits` });
|
||||
} else if (a.op_type === "publish_release") {
|
||||
const tag = (a.ref_name ?? "").replace(/^refs\/tags\//, "") || a.content || "release";
|
||||
items.push({ type: "ReleaseEvent", repo, ts, detail: tag });
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
@@ -196,14 +213,18 @@ export async function fetchSteam(env: WidgetsEnv): Promise<GameItem[]> {
|
||||
);
|
||||
}
|
||||
|
||||
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[]);
|
||||
/**
|
||||
* The owner's own public activity on git.poli0981.dev, where the repositories live since the
|
||||
* move from GitHub. No token: the feed answers anonymously and lists only public repositories
|
||||
* (checked 2026-11-24). `only-performed-by` leaves out what bots do in the owner's repos.
|
||||
*/
|
||||
export const GITEA_FEED =
|
||||
"https://git.poli0981.dev/api/v1/users/poli0981/activities/feeds?only-performed-by=true&limit=30";
|
||||
|
||||
export async function fetchGitea(): Promise<GhItem[]> {
|
||||
const res = await get(GITEA_FEED, "application/json");
|
||||
if (!res.ok) throw new Error(`gitea ${res.status}`);
|
||||
return normalizeGitea((await res.json()) as GiteaActivity[]);
|
||||
}
|
||||
|
||||
/** Status of a source whose refresh failed, from the age of the feed it kept. */
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// Cron worker (every 45 min): fetch YouTube / Steam / GitHub, normalize, mirror the pictures,
|
||||
// Cron worker (every 45 min): fetch YouTube / Steam / Gitea, normalize, mirror the pictures,
|
||||
// and write `widgets:*` keys to the shared KV namespace. The site reads them via /api/widgets
|
||||
// and serves the pictures from /ext-img. Deployed by hand:
|
||||
// npx wrangler deploy --config workers/widgets/wrangler.jsonc
|
||||
// Bindings: see WidgetsEnv in ./feeds (KV, the YT_CHANNEL_ID var, STEAM_*/DISCORD_WEBHOOK_CI secrets).
|
||||
import type { WidgetsStatus } from "../../../src/lib/widgets-types";
|
||||
import {
|
||||
fetchGitHub,
|
||||
fetchGitea,
|
||||
fetchSteam,
|
||||
fetchYouTube,
|
||||
refresh,
|
||||
@@ -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(env)],
|
||||
["gh", "widgets:gh", () => fetchGitea()],
|
||||
];
|
||||
const results = await Promise.all(
|
||||
sources.map(([src, key, fetcher]) => refresh(env.KV, key, src, status, now, fetcher)),
|
||||
|
||||
+5
-4
@@ -89,10 +89,11 @@
|
||||
// Not secrets: the AUD tag only says which app a token must be minted for.
|
||||
"ACCESS_TEAM_DOMAIN": "https://polished-hall-48fd.cloudflareaccess.com",
|
||||
"ACCESS_AUD": "197ec8eae1275e465623bdb77f88238b9b01dd66eec0be2e8c13ccd7b13e48b7",
|
||||
// Where /api/report files bug reports. A PRIVATE repo: reports carry the reporter's
|
||||
// description, route and browser details, and the privacy policy promises they are not
|
||||
// public. GITHUB_ISSUES_TOKEN must have Issues: read & write on it.
|
||||
"REPORT_REPO": "poli0981/site-reports",
|
||||
// Where /api/report files bug reports: the GitLab mirror of this repo, as CONFIDENTIAL
|
||||
// issues (src/pages/api/report.ts). Reports carry the reporter's description, route and
|
||||
// browser details, and the privacy policy promises only the owner sees them.
|
||||
// GITLAB_ISSUES_TOKEN must be allowed to open issues there (Reporter role, scope api).
|
||||
"REPORT_PROJECT": "poli0981/poli0981-dev",
|
||||
},
|
||||
// Uploaded images (src/lib/media): public AVIF/WebP variants under v1/, private
|
||||
// metadata-free masters and per-image metadata elsewhere. The bucket has no public
|
||||
|
||||
Reference in new issue
Block a user