main
27
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
66443e1153
|
fix(publish): record the build as the status main's protection requires
The first publish from the admin after the move stopped at its pull request: CI's publish job tried to merge twice and Gitea answered 405 "Not all required status checks successful". Gitea 28.4 writes commit statuses for push and pull_request runs only, never for a dispatched run, so the content/bump commit never got the `CI / build (*)` status branch protection requires. The publish job (needs: build, now if: always()) records build's result as `CI / build (workflow_dispatch)` on the commit it built, with a link to the run, and only then merges and dispatches the deploy. A failed build is recorded as a failure and merges nothing, so the admin shows "xuất bản lỗi" instead of building forever; a cancelled one records nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7215d59f31
|
ci(content): the admin's publish runs on Gitea's API
content-bump.yml used `gh` to open the content/bump PR, enable GitHub's auto-merge and dispatch CI. On Gitea the same steps are calls to Gitea's API with the job token, in scripts/content-publish.mjs (unit-tested): - `open` (content-bump.yml): open or update the PR, write in its body whether it merges itself (<!-- publish: auto --> for Markdown/JSON, <!-- publish: review --> when MDX changed, with a comment), and dispatch ci.yml on content/bump: a PR the job token opens starts no workflow. - `merge` (ci.yml's new publish job, after `build` passed on the dispatched run): squash-merge the PR at the commit CI built when its body says auto, then dispatch ci.yml on main, because the job token's merge commit starts no workflow either; that run deploys. A refused merge fails the job and says so on the PR; merging by hand deploys as usual. Decision D5 named Gitea's merge_when_checks_succeed. The merge happens in CI instead: the scheduled merge would also be the job token's push, so nothing would deploy it, and the body marker gives the admin the "merges itself" flag Gitea's API lacks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7db93e2b3b
|
ci: remove the maintenance-mode triage, which needs GitHub
triage.yml ran on GitHub's issue and pull_request_target events with actions/github-script. On Gitea outsiders cannot open issues or PRs (registration is off), and the GitLab mirror's issues never reach Gitea Actions, so the bot has nothing to watch. Decision D2 of the migration: the workflow and its script go; the policy stays in CONTRIBUTING.md, and out-of-scope requests on the mirror are closed by hand. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7bcbcf59dd |
docs: maintenance mode — policy, triage bot, issue forms, status badge, docs for 2.3.0 (#139)
* docs: maintenance mode — policy, triage bot, issue forms, status badge, docs for 2.3.0 From v2.3.0 the project takes no new features (CONTRIBUTING.md, in Vietnamese and English). Accepted: scheduled dependency updates; security fixes (High/Critical advisories, runtime vulnerabilities); major language/runtime/framework upgrades; bug fixes including UI/UX and accessibility; language fixes. - .github/workflows/triage.yml + scripts/triage.mjs (unit-tested): an issue or pull request whose title or label asks for a feature is labelled enhancement + out-of-scope, answered in both languages and closed (issues as "not planned"). The owner's items, bots, `maintenance-exception` and anything the owner does are left alone. It runs on pull_request_target but checks out only that one script from the default branch, never a pull request's code; workflow_dispatch is a dry run. - Issue forms: blank issues off, questions and ideas to Discussions, security to the private policy; a new language-problem form; the bug form no longer claims the site's report button fills it (those reports go to a private repository). The pull request template asks which of the five kinds of change it is. - README: a maintenance-mode badge and a Status section; the admin paragraph describes auto-publish. SECURITY.md: High/Critical fixes ship out of schedule; the age-check answer is local storage only. - Docs: decisions D21–D24, maintenance policy and cadence (17 §0, QODANA_TOKEN rotation), roadmap frozen, CI (Qodana, whole-tree licences, triage, merge rules), architecture tree, the Workers Builds deploy command, licence notes without the stale license-checker/GSAP lines. - CHANGELOG [2.3.0]; sonar.projectVersion 2.3.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: link #138 in the 2.3.0 changelog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: album labels come from both language entries Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ci): triage without a checkout, and linear title patterns SonarCloud and Qodana on #139: - githubactions:S7631 flags any checkout in a pull_request_target workflow, even of the default branch. The workflow now reads scripts/triage.mjs from the default branch through the API and imports it from a data: URL — nothing is checked out at all. - javascript:S8786: `\s+a?\s*` let two quantifiers compete for the same spaces. The title is trimmed once and the patterns are written so no two quantifiers overlap. - Qodana RegExpRedundantEscape: the bot check is `endsWith("[bot]")`, no regex. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
484907439a |
feat(content): content labels, an age check, blurred images and a warning banner (#138)
* feat(content): content labels, an age check, blurred images and a warning banner Posts, chapters and albums can carry content labels and an age rating: - Labels (src/lib/content-labels.ts, names in src/i18n `labels`): horror, blood, jumpscare, violence, self-harm, death — banner and blurred images; politics, religion, strong-language, flashing-lights, spoilers — banner only. `contentWarning` moves from stories to every long-form entry and albums, and single gallery photos can carry their own (R2 list or captions.json). Unknown labels fail the build. - Banner (ContentNotice.astro, replaces ContentWarning.astro): names every label in the page's language, skipped by search. Images in a labelled region are blurred in plain CSS by default — nothing sharp flashes before a script — and a real "Hiện ảnh" checkbox un-blurs them through :has(), so it works with the keyboard and with JavaScript off. A region without pictures shows no such line. - Age check (AgeGate.astro, src/lib/age-gate.ts) for `ageRating` 13+/16+/18+: the text sits in a closed <details> (search indexes the title, not the text); its summary asks in a native modal <dialog> — focus starts on "No", Esc cancels and never means yes, "No" explains and offers to choose again — and the answer is kept in localStorage only (age thresholds, never an age or birth date). It never pops up on its own, and without JavaScript the summary simply opens the text. - Everywhere else: story/post/album cards name the labels (blurred covers), the lightbox shows labelled photos blurred behind "Hiện ảnh", RSS descriptions start with the warning in the item's language, OG cards carry it for blog posts too, JSON-LD contentRating. The post page now uses the cover's alt text when there is one. - Admin: a `multiselect` field for labels (with Vietnamese names), an age-rating select, and per-photo labels in the gallery manager. - Content (poli0981/content 98f7692): privacy policy §6 lists the age-check answer; "Đêm không tiếng" chapters 1–2 are rated 16+. - Tests: label and age-check logic, admin validation, labels kept on album save, RSS prefix; the accessibility suite scans the gate folded and asked, checks focus, Esc, No/Yes/reset and the keyboard reveal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(a11y): appendChild for the blur probe (astro check's DOM typing) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(content): findings from an independent review of the labels branch - Album pages: the lightbox now sits outside the labelled section, whose blur rule also blurred the viewer's photo — its "show" button removed the veil but not the blur. - Age check: the browser opens a <details> by itself (find-in-page, a #:~:text= link from a search engine, an #id inside the text); without a "yes" on record the gate now folds it straight back. After "Chọn lại" → "Có", focus moves to the summary instead of being lost with the row that just hid. - Search indexes nothing inside the gate, not even its status lines, which could have become the excerpt of a page the reader has not been let into. - Albums take their labels and age rating from BOTH language entries (same photos, two pages; the stricter rating wins), on the album page and on its card. - An age-rated post folds its cover away with the text (PostCover.astro), and post and album cards blur the cover of age-rated items too. The album card names the cover photo's own labels, not only the album's. - Tests: the gate re-folds an unasked open and keeps focus after choosing again; albumWarning merges both languages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
0c56acd806 |
ci: Qodana analysis and a licence check over the whole dependency tree (#135)
* ci: Qodana analysis and a licence check over the whole dependency tree - Qodana (JetBrains, Qodana for JS) runs on every PR, on main and by hand (.github/workflows/qodana.yml, settings in qodana.yaml): native mode on the runner's Node 26 after `npm ci --ignore-scripts` and the generated types, profile qodana.recommended over the whole repository, build output, generated files, the content submodule and the design docs excluded, spelling/grammar checks off (they do not read Vietnamese). Results go to Qodana Cloud and, for main, to code scanning as SARIF. Dependabot and fork PRs skip it (no secrets), so it stays advisory. - Licences: the allowlist moves to scripts/license-policy.mjs, shared by gen-notices (direct dependencies, THIRD-PARTY-NOTICES.md) and a new check-licenses step in the build job that reads every package in package-lock.json — transitive ones and every platform binary — with a small SPDX evaluator (OR, AND, WITH, parentheses). Packages with no licence fail; reviews are per package with a reason instead of per licence (an MPL note written for satori used to clear @axe-core/playwright too). Today: 735 packages, 42 cleared (MPL-2.0 build/test tools, sharp's LGPL libvips). - README badges and Quality row, THIRD-PARTY-NOTICES tool list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: Qodana's first findings, and a zero-problem quality gate The first Qodana run reported 11 problems; all are handled: - scripts/smoke-worker.mjs: the forged Access JWT is now built from its JSON parts at run time (same bytes) instead of sitting in the source as a token literal, which secret scanners rightly flag; the "did not come up" case reports through the same helper as any other failure instead of throwing into its own catch. - scripts/check-csp-hashes.mjs: ("|') → ["'] in the JSON-LD matcher. - src/lib/format.ts: drop the two escapes of `]` outside a character class (a lone `]` is a literal there); the classes keep theirs. - src/lib/legal-lang.ts: the heading → language table is a Map, so "Tiếng Việt" is data, not a property name mixing scripts. - qodana.yaml: ES6PreferShortImport off, with the reason — the build scripts and astro.config.mjs run under plain Node, where the `@/` alias doesn't resolve and a TypeScript import keeps its `.ts`. - failThreshold: 0, so any new problem turns the check red. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: sort the licence report with an explicit compare function Sonar S2871: Array#sort() without a compare function sorts by UTF-16 code units, which is not alphabetical for every name. Both lists now sort with localeCompare. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
846e5ec17d |
Site-wide rate limit: 429 for every request the Worker sees (#106)
* feat(security): site-wide rate limit for every request the Worker sees Only the /api groups were rate-limited; pages, /media, /ext-img and the search index had no limit at all (a 200-request burst against production answered 200 every time). A new RL_SITE binding (100 requests per 10 s per client, IPv6 per /64) is checked by the Worker entry right after the IP denylist. Over it: the 429 page, no-store, Retry-After: 10, its countdown rewritten to 10 s. The admin host is exempt (behind Access, RL_ADMIN per account). A throwing limiter fails open without skipping the Turnstile gate. - tests: worker spam/keys/exemptions/fail-open; Retry-After constants are checked against the periods in wrangler.jsonc - smoke: a fourth phase spams the built Worker until the limit answers - scripts/probe-ratelimit.mjs: tell the Worker's 429 from the WAF's 1015 - docs 06/07/02/09/00: three layers (WAF → RL_SITE → /api groups) and the Free plan's real WAF limits; CHANGELOG 2.1.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(sonar): project version 2.1.0 for the release Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(worker): stay a 429 if the rate-limit page can't be built Review follow-ups on the site-wide limit: - If fetching or rewriting the 429 page threw, the error reached the edge fail-open path, which hands the request to the Astro app and skips the Turnstile gate. It now answers a plain-text 429 (no-store, Retry-After). - Drop Last-Modified and Content-Length with the ETag, as the gate does: the countdown rewrite only kept the length by luck ("60" vs "10"). - Docs: the WAF rule can't filter by host on Free, so it counts admin.* too; 09 lists the worker entry as a 429 source and the probe checks; CHANGELOG says what was unlimited before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
bf66593c7d |
Faster first paint on phones: inline CSS, idle hydration (#105)
* perf: inline page CSS, hydrate the theme toggle and hero wave when idle Lighthouse puts every page's LCP (a text block) about 2.4 s after the first byte on a throttled phone, almost all of it render delay: two render-blocking stylesheets (34 KB raw, 9 KB brotli) cost a round trip before first paint, and the theme toggle's client:load pulled the Svelte runtime into the same window on every page. Inline every page's CSS (build.inlineStylesheets "always"; the CSP check still finds every style block hashed) and hydrate ThemeToggle and the home hero's Waveline on idle: CSS already shows the toggle's icon from data-theme-pref, and the wave renders as a flatline until it hydrates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci(lighthouse): measure through a compressing proxy, like production astro preview serves HTML, CSS and JS uncompressed; Cloudflare's edge compresses every text response with brotli. Measured straight off the preview, the simulated phone downloaded three to four times the bytes a real one does (home HTML 108 KB vs 25 KB), so LCP overshot on transfer time alone. scripts/compress-proxy.mjs sits in front of the preview in the Lighthouse job and compresses text responses with br or gzip; fonts, images, redirects and HEAD pass through untouched. Docs 14 and the changelog describe the inline CSS, the idle islands and how CI now measures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci(lighthouse): compress through nginx instead of a Node proxy Sonar's taint rules flagged the hand-written proxy (the request URL and upstream headers flowing into an outgoing request and into response headers: S5144, S5146, S6109) and failed the gate, though it only ever joined two ports on the CI runner. nginx is preinstalled on the Ubuntu runner: the step writes a short config that gzips text responses from the preview and listens on 127.0.0.1 only. gzip is a little larger than the edge's brotli, so the numbers stay slightly pessimistic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8aa760a5af |
fix(i18n): serve an English 404 page under /en/ (#104)
Any missing /en/ path got the Vietnamese 404 page. Both 404s now share components/pages/NotFoundPage.astro (links, recent posts and a search over the page language's Pagefind index, the heading echoed in the other language), and ErrorLayout takes a locale. The asset layer answers a miss with the nearest 404.html up the path, so an integration moves Astro's en/404/index.html to en/404.html. The Worker now returns that asset 404 for every missing page instead of handing it to the app, whose localized error page lookup (/en/404/index) is answered with a redirect. A test keeps every on-demand route under APP_PREFIXES, which is what makes skipping the app safe. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
1b1e922fe2 |
Docs for v2.0, plus widget and CSP fixes (#100)
* docs: README, CHANGELOG and the docs suite brought up to v2.0 - README.md (new): what the site is, stack, how the Worker fits together, getting started on Node 26, commands, deploying with Workers Builds, the admin, security and licensing. - CHANGELOG.md (new): v2.0.0 in Keep a Changelog form, plus a summary of the untagged 1.x months. - SECURITY.md: admin.poli0981.dev, the bot gate and the widgets worker are in scope; tagged releases; reports go to a private repository; what the admin stores. - THIRD-PARTY-NOTICES.md: every infrastructure service, with what each one is used for. CONTENT-LICENSE.md: the content submodule and /media images. - poli0981.dev-docs v2.0: decision log D16–D19; architecture (worker entry, stack, repo layout, dev setup, ADR 09–11); design system (Glacier Teal tokens, theme modes, a11y rules); security (headers, single-key CIDR denylist, body limits, secrets table, supply chain on a public repo, admin hardening and Access recommendations, structured logs); Cloudflare setup (correct Workers Builds commands and the deploy incident, ADMIN_EMAILS, Access settings, observability); CI/CD as it runs today; bug reports, widgets, error pages, routes, roadmap with status and next steps, maintenance (TypeScript 7 bumps, rollback, R2/KV backup). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): link the documentation PR Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(widgets): Steam icons via Steam's Cloudflare CDN; optional GitHub token Found by watching the first cron run of the new worker in production: no image had been mirrored and two sources were stale. - media.steampowered.com answers requests from Workers with 403, so every Steam icon mirror failed. cdn.cloudflare.steamstatic.com serves the same files to Workers (probed from Cloudflare's network). - The GitHub events API allows 60 unauthenticated requests an hour per IP and Workers share egress IPs, so the feed was 403 for hours at a time. The worker now sends GITHUB_TOKEN when that optional secret exists (a fine-grained token with no permissions is enough for public data). - YouTube's feeds/videos.xml currently answers 404 for both the channel and the uploads-playlist URL, from Cloudflare and from elsewhere; the worker already keeps the last good feed, so nothing changes there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(csp): callout styles were blocked; the CSP check now covers styles Lighthouse flagged a CSP violation on the one MDX post. Astro hashes the styles of the components a page renders, but not of a component that only appears inside MDX content: Callout's inline <style> shipped without its hash and the browser refused it, so callouts were unstyled in production. - Callout's rules move to src/styles/prose.css (the stylesheet Prose loads on every long-form page); the component has no <style> block any more. - scripts/check-csp-hashes.mjs now hashes every inline <style> block against the page's policy and fails on any style attribute (a policy without 'unsafe-inline' never allows one), with self-tests for both matchers. The build reports 339 style blocks across 64 pages, all hashed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(og): Number.parseInt in the colour mixer (Sonar S7773) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
71e6c11de3 |
Glacier Teal UI, theme that follows the OS, a11y fixes and a redesigned admin (#99)
* refactor(pages): share vi/en page components Eleven pages existed as two near-identical copies, one per locale. Each now has one component under src/components/pages/ that takes `locale`, and the vi and en routes are thin wrappers (the pattern DevPage already used; it and GamingPage, NowPage and UsesPage move into the same folder). The legal routes share a `legalPaths()` builder. The built HTML of all 64 pages is unchanged apart from build noise (scope ids, asset and CSP hashes). The one visible difference: the vi stories and projects pages now use the boxed empty state the en pages had, which only shows when a section has no entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(ui): Glacier Teal palette, theme that follows the OS The warm "midnight ink / old paper" palette gives way to a cool one: navy and teal in dark, frost white and deep teal in light. src/lib/palette.ts holds the values for code outside CSS (theme-color, OG images, the console egg) and tests/palette.test.ts fails if it and global.css drift, or if any text or control colour drops below WCAG AA on bg, surface or elevated. New tokens: --line-strong for control edges (3:1), --accent-contrast for text on an accent fill, --overlay for modal backdrops, --shadow-color. The undefined --text-small becomes --text-meta, native controls take accent-color. The theme now defaults to the OS setting and keeps following it. The toggle cycles system → light → dark, picks its icon in CSS before hydrating, and points both theme-color metas at a pinned choice. The bootstrap moves to src/lib/theme.ts and tests run the exact string that ships. The admin gets the same toggle. Hard-coded colours go: the reader's paper and dark backgrounds reuse the site palettes (sepia stays its own, now with a 3:1 edge), the lightbox pins the dark palette for photos, backdrops use --overlay, and the favicon, mini-game, OG cards and easter egg read the palette. The service worker cache is bumped for the new favicon and game. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ui): language switch, one-shot stories, reader bar, a11y and i18n - The header's language switch goes to a page's real translation, or to the same section in the other language when there is none, instead of 404ing on every post whose slugs differ (sectionFallbackPath). - Stories outside a series folder get a reader route (/truyen/[slug]); their cards linked to a 404. All four story routes share StoryChapterPage. - The story reader bar docks under the sticky header (--header-h) instead of sliding behind it; in-page anchors stop below the header too. - The header keeps the menu button below 960px: the full nav needs ~900px in English and overflowed between 768 and 900. - The 500 page shows the Cloudflare Ray ID, stamped by the Worker, instead of a random code nobody could look up; bug reports carry it. - Gallery thumbnails are links to the full image, so albums work without JS; the lightbox still takes plain clicks and leaves modified clicks alone. - Contact lines on /qa and the 403 page are real mailto/Discord/links links. - A11y: the search is an ARIA combobox (activedescendant, labelled groups, status outside the listbox, a visible focus ring) and reports index failures; the mobile menu is a modal dialog with a focus trap that returns focus to its trigger; the lightbox trap skips disabled arrows and keeps focus at either end; the report dialog and its textarea are labelled and the copy button says "copied" (or why not) instead of "sent"; Esc acknowledges the legal notice only from inside it; reading options expose aria-pressed. - Landmark names, project "repo/site" links (with their project and a new-tab note) and the legal-notice labels come from the i18n dictionaries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ui): centre modal dialogs, bring back list markers in posts Two old bugs that Tailwind's preflight caused, found while testing the admin: - It zeroes every margin, which also removes the browser's `margin: auto` on modal dialogs, so the public "report a bug" dialog opened stuck in the top-left corner. Dialogs get their auto margins back. - It strips list-style everywhere, so bulleted and numbered lists in blog posts and stories rendered without markers. .prose restores them. The prose rules move from Prose.astro into src/styles/prose.css so the admin editor's preview can use the same stylesheet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(admin): audit log, dashboard, activity and denylist APIs; stricter Access Security: - Access tokens older than 24 hours are refused (jose maxTokenAge), and ADMIN_EMAILS is now required: without an allowlist nobody gets in, so an Access policy widened by mistake no longer opens the admin. (The secret is already set in production.) - Every admin action — content save/delete, media upload/alt/delete, album save/delete, publish, denylist changes — lands in a KV audit log (audit:*, 90 days, newest first via inverted keys, one list() to read). New endpoints: - /api/admin/overview: content counts per collection and language, drafts, library size, the widgets cron's last run, and the deployment's configuration (secret names only, gate state, version, single-token mode). - /api/admin/activity: the audit log next to the content repo's commits. - /api/admin/security: read, add (with reason and expiry) and remove denylist entries; refuses a range that contains the admin's own address. - /api/admin/media?usage: which content files use each image. - /api/admin/gallery: albums report their cover and how many repo photos come first; PUT can move the cover (rewriting coverIndex in both language entries in the same commit); DELETE removes an album's list and entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(admin): redesigned admin with dashboard, activity, security pages Layout: a two-row header (brand, publish status, theme toggle, account menu; then a tab row that scrolls sideways on a phone), a skip link, and one AdminChrome island that renders toasts (polite for confirmations, alert for failures), a <dialog> confirm in place of window.confirm, and a "sign in again" banner. The API client detects a lapsed Access session (Access's redirect, seen through redirect: "manual", or a 403) instead of failing with a JSON parse error. Pages: /admin/ is now an overview (content per collection, drafts, publish state, library, widgets cron, gate and secrets); the list moves to /admin/content/ with collection/language/draft filters, sorting, an empty state and a slug check before creating; /admin/activity/ shows the audit log and content commits; /admin/security/ manages the IP denylist and shows the configuration. Editor: local draft autosave with a restore prompt, Ctrl/⌘+S, field errors from the same validator the server uses, a preview in a sandboxed frame (no scripts can run, the site's prose styles apply), a retry instead of an empty form when loading fails, and edit mode after the first save. Media: search, an "unused only" filter, where each image is used, up to three uploads at once with a status per file, and clipboard failures reported. The picker reuses the loaded library, searches, and can pick several images. Gallery: unsaved-change tracking with a prompt before leaving, drag-and-drop or arrow reordering, a cover picker, deleting an album, adding several photos at once. Publish bar: polls every 5 s while a run or build is moving, 30 s with unpublished changes, 60 s when in sync, never in a hidden tab; links a failed run, and flags single-token mode. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
8a1316280f |
Platform 2026-10: Node 26, TypeScript 7, SonarCloud + 99% coverage, edge & API hardening (#98)
* chore: add .gitattributes so working trees are LF on every OS core.autocrlf=true (the Windows default) checked 144 text files out as CRLF, which made `prettier --check` and `gen-notices --check` fail locally while CI on Linux passed. The index was already LF, so this changes no content. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * build: Node 26, TypeScript 7 next to TS6, ES2025, latest dependencies - Node 26 (.nvmrc, engines); Workers Builds already builds with NODE_VERSION=26. - TypeScript 7.0 ships no JS API, so the tools that need one (astro check/Volar, typescript-eslint, svelte2tsx) keep the real typescript@6 package, while @typescript/native (npm:typescript@7) type-checks every .ts file: `npm run typecheck`. Called by path so the outcome never depends on which package wins the shared `tsc` bin link. - tsconfig: target/lib ES2025, no baseUrl (removed in TS 7; Astro's alias plugin falls back to the tsconfig directory), explicit `types: ["node"]` (TS 6+ default is []), and erasableSyntaxOnly so Node can strip types for the unit tests — which meant turning three constructor parameter properties into plain fields. - Dependencies to current: astro 7.4.2, @astrojs/cloudflare 14.4.2, mdx 8.1.1, svelte 9.1.1, check 0.9.12, zod 4.6.7 (GHSA-mrhx-c7xc-m3w5), wrangler 4.152.0, eslint 10.13, typescript-eslint 8.72 (the Svelte false positives that pinned 8.70 are gone), knip 6.42, lefthook 2.2, prettier 3.9.10, satori 0.63. - Override miniflare's pinned undici to ^7.30.1 (GHSA-xjj6-f33q-929c and two more, published 2026-10-23). `npm audit`: 0 vulnerabilities. - ESLint: defineConfig from eslint/config (tseslint.config is deprecated). - wrangler.jsonc: compatibility date 2026-10-15, version_metadata binding, Workers Logs with invocation logs and redacted query strings, sampled traces, REPORT_REPO. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * ci: SonarCloud analysis, no npx or install scripts in CI, Dependabot-proof notices - New `sonarcloud` job (SonarSource/sonarqube-scan-action v8.3.0, pinned) fed with the lcov report from the build job; sonar-project.properties carries the whole setup and waits for the quality gate. Skipped where SONAR_TOKEN can't exist (Dependabot, forks) and for content/bump dispatches. - `npm ci --ignore-scripts`: esbuild, workerd and sharp take their binaries from optionalDependencies, so CI needs no lifecycle script at all (verified with a clean install + full build). Every `npx` became an npm script, and the TS 7 compiler gets its own step. Jobs have timeouts. - Lighthouse runs through treosh/lighthouse-ci-action (pinned) instead of fetching @lhci/cli with npx at run time, and measures mobile as docs 14 says (it was desktop). - gen-notices no longer prints the resolved-package count inside the checked block: every Dependabot PR that changed one transitive package failed CI on it (PR #94). - Dependabot: a 3-day cooldown on both ecosystems, a typescript group, the TS 6 pin explained, and the typescript-eslint pin dropped (8.72 lints Svelte cleanly). - osv-scanner-action v2.7.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(edge): denylist on every route, a gate that fails closed, /ext-img, version reporting - IP denylist moved from the middleware (on-demand routes only — pages were never covered) into the worker entry, for every route. One `denylist` KV key with CIDR ranges and expiry (lib/denylist), memoized per isolate for a minute, failing open on KV errors. - The Turnstile gate fails CLOSED: if deciding or rendering it throws, the visitor gets a 503, never the page behind it. Pass signatures must be exactly 43 characters. - frame-ancestors 'none' as a header-only CSP (it cannot work from <meta>); appended, so /media's and /ext-img's own sandbox CSP stays. Admin responses add CORP same-origin. - /ext-img: the widgets' YouTube thumbnails and Steam icons are mirrored into KV by the cron worker and served from this origin, so a page never contacts Google or Steam before the visitor presses play; img-src is back to 'self' data:. The route only reads KV — nothing a visitor sends makes the Worker fetch anything. - /api/health reports the Worker version (version_metadata) and the git commit it was built from (Workers Builds' WORKERS_CI_COMMIT_SHA), so a deploy is verifiable from outside. Structured JSON logs (lib/log) for denylist, gate, admin and rate limits. - Middleware error pages keep their status under `astro dev` (a rewrite used to answer 200). - Widgets cron: parallel sources, 10 s timeouts, per-source error logs, the KV contract in one shared types module, its bindings typed locally (WidgetsEnv). - gate.js: Turnstile follows the theme actually shown (system preference included). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): bounded bodies, timeouts, server-side validation, private bug reports - Request bodies are refused by Content-Length before anything is buffered, and streamed bodies stop at the limit (lib/body): report 32 KB, gate 8 KB, admin JSON 512 KB, upload 20 MB. The old code read the whole body first, whatever its size. - Every outbound fetch has a timeout: GitHub (admin, 15 s), GitHub issues and Discord (10 s). - /api/report files into REPORT_REPO — the private poli0981/site-reports, as the privacy policy always said — breaks @mentions, fences the console log so it can't escape its code block, sends allowed_mentions: none to Discord, and no longer echoes the issue URL. - Admin content API: frontmatter validated against the collection's fields (the same validateFrontmatter the editor will use), plain objects only, JSON content type required, "already exists" instead of a misleading edit conflict when creating, and legal / now / album entries can no longer be deleted from the admin. - Admin gallery and media APIs: the same JSON/size rules, existing-album check on create, oversized uploads refused before formData() parses them. - Publish status says when the content token is doing the dispatching (no publish token). - Structured logs for saves, deletes, uploads, publishes and every GitHub failure. - Admin client: specific messages for the new error codes; a failed Turnstile load is retried instead of replayed until reload. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: SonarCloud findings, two checks that passed without checking, RepoLens link Checks that silently checked nothing: - check-exif handed exifr file paths; its reader throws on current Node and the old `.catch(() => null)` read that as "no EXIF" — CI never inspected a single image. It now reads the bytes itself, fails on unreadable images, honours --changed (it ignored the flag) and stops git from octal-quoting Vietnamese file names out of its filter. - check-csp-hashes skipped any page whose CSP meta it failed to parse and reported "ok — 0 pages". The meta tag is now found in any attribute order or quoting (self-tested), a page without one fails, and zero checked pages fails. SonarCloud (29 open issues): - Six super-linear regexes rewritten linearly (format, bugbuffer, access, cookie, new-post); the email mask works token by token. - smoke-worker runs wrangler via process.execPath + its CLI file (no PATH lookup, and it finally works on Windows: no `npx` without a shell, taskkill instead of a POSIX process group), sends `%2e%2e` raw instead of letting fetch normalize it, has a deadline, and covers /ext-img, frame-ancestors, oversized bodies, malformed gate passes and the denylist (a third phase). KV seeding names the namespace, as wrangler 4.152 requires. - strip-exif only walks src/assets (path traversal), recurses, and actually enforces its 1.5 MB budget; sw.js keeps the worker alive until cache.put settles and caps the warm cache; gate.js rejects with Errors; the mini-game draws obstacles from the CSPRNG. - new check-install-scripts: CI installs with --ignore-scripts, which also switches off npm's own strict-allow-scripts — this keeps the "unreviewed install script" alarm. - gen-og imports ogKey() from src/lib/og.ts instead of keeping a copy in sync by hand; new-post parses flags anywhere and escapes titles for YAML properly. Also: the "all repositories" link now points at https://repolens.poli0981.dev/repos. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: run the TypeScript sources under node:test with Astro/Workers stand-ins No new dependencies. tests/support/register.mjs installs Node 26 module hooks: - `@/…` and extensionless/directory imports resolve to the .ts sources; - astro:env/*, astro:content, astro:middleware, cloudflare:workers and the Cloudflare adapter's handler resolve to small stubs whose values tests change at run time; - `import.meta.env` / `import.meta.glob` are rewritten to same-length globals, so V8 coverage still maps character for character onto the files on disk. tests/support/fakes.ts provides KV, R2, Images, the Cache API, ASSETS, rate limiters, a minimal HTMLRewriter and a fetch router; tests/support/github.ts an in-memory content repo speaking REST, Git Data and GraphQL. 162 tests across the worker entry, middleware, every API route, the admin libraries (including real RS256 Access JWTs), media, gate rendering, content queries, RSS, the client modules and the widgets cron: 99.5% of lines, 94.6% of branches. Writing them found the middleware's error pages losing their status under `astro dev`. The frontmatter round-trip test used to skip itself on Windows (`URL.pathname` → "/E:/…"). `npm run test:coverage` writes coverage/lcov.info (80% line floor) for SonarCloud, with the same exclusions as sonar-project.properties, which now also analyzes .github, versions the project, and waits for the quality gate on pull requests only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(content): publish 9265c94 — legal pages for this release Private bug reports, widget images served by the site, Workers Logs and IP blocks disclosed, the AI disclosure's merge policy, and the full third-party/service list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: match script end tags loosely in the HTMLRewriter fake CodeQL (js/bad-tag-filter) flagged the fake's script regexes because they miss end tags such as `</script >` or `</SCRIPT>`. The fake only rewrites HTML this repo builds, but there is no reason to keep a pattern the analyzer rightly calls fragile. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: cut script elements by offset in the HTMLRewriter fake The looser end-tag regex did not satisfy CodeQL's js/bad-tag-filter, which distrusts any regex that matches whole <script>…</script> elements. The fake now finds each element with indexOf and checks the opening tag's attributes, so there is no tag-filtering regex left to flag. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
2d53af534f |
fix(gate): a malformed pass cookie must not bypass the Turnstile gate (#97)
A signature atob cannot decode made verifyPass() throw past the gate into the worker's fail-open path, which served the real page. Decoding now never throws, signatures must be 43 characters, and the smoke test covers it. Also bumps zod and patches undici so the required npm audit step passes again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
7ec559d216 |
feat(admin): admin.poli0981.dev — editor, R2 media library, gallery albums, publish (#83)
An admin for the owner, on its own host behind Cloudflare Access.
Security
- src/lib/hosts.ts: admin.poli0981.dev serves only /admin*, /api/admin* and /media/*
(other paths 301 to the site); poli0981.dev/admin* 301s to the admin host and
/api/admin* 404s there. Same origin would let any XSS on a public page drive the
admin API with the Access cookie.
- Every admin route (matched on Astro's routePattern) needs a valid Cloudflare Access
JWT, verified in the Worker with jose against the team JWKS: aud = ACCESS_AUD, iss =
team domain, RS256, unexpired; optional ADMIN_EMAILS allowlist. So a forged header,
another app's token or any non-Access URL gets 403 even though Access already guards
the edge. State-changing requests must be same-origin (Sec-Fetch-Site + Origin);
RL_ADMIN is keyed by email; responses are no-store + noindex. `astro dev` gets a
stand-in identity only under import.meta.env.DEV.
- GITHUB_CONTENT_TOKEN (fine-grained) writes ONLY poli0981/content, plus dispatching the
publish workflow on this repo. A leak means content edits, never code pushed here.
Content (src/lib/admin/{collections,frontmatter,github}.ts, api/admin/content.ts)
- One GraphQL request lists every entry with its frontmatter; edits commit straight to
content's main through the Git Data API (tree → commit → fast-forward ref, one atomic
commit for multi-file changes), refusing with 409 when a file moved since it was
opened. New entries are .md only (MDX runs code at build).
- Frontmatter round-trips through yaml's Document API and only rewrites keys whose
value changed: all 28 content entries come back byte-for-byte when unedited (unit
test against the real submodule), flow lists and quoting survive edits.
Media (src/lib/media/process.ts, api/admin/media.ts)
- Upload: magic-byte sniffing (no SVG), ≤ 20 MB, id = SHA-256 prefix — the same file
again returns the existing record without a single new transformation. A full-size
WebP master (re-encoded: EXIF/GPS gone; no original kept) and the fixed variants
(AVIF 480/800/1200, WebP 800/1600) are made once with the Images binding and stored
in R2 with their real content type; sizes come from the output, after EXIF rotation.
- Library: list from R2 metadata, edit alt, copy the <picture> snippet, delete (refused
while any content still references the id; purges this colo's cache).
Gallery (api/admin/gallery.ts): albums from gallery/*.md + gallery-photos/<album>.json;
reorder, caption (vi + en required), add from the library; a new album writes its vi/en
entries and photo list in one commit and needs at least one photo.
Publish (.github/workflows/content-bump.yml, api/admin/publish.ts): the admin
dispatches the workflow, which points src/content at content's main on content/bump,
opens/updates the PR, enables auto-merge only when the diff is .md/.json, and runs
ci.yml on the bump commit (GITHUB_TOKEN PRs don't trigger pull_request workflows) so
the required `build` check exists. ci.yml gains workflow_dispatch. "Allow GitHub
Actions to create pull requests" is enabled on the repo; default token stays read.
UI: AdminLayout + Svelte islands (client:only) — content list with search and "new",
editor (schema-driven form, Markdown with marked preview, image insert, cover picker,
unsaved-changes guard), media library (drag-and-drop), gallery manager, and a publish
bar that shows pending changes, the bump PR and its build status.
Also
- wrangler: Images binding, ACCESS_TEAM_DOMAIN/ACCESS_AUD vars (not secrets), and
run_worker_first now excludes /@*, /src/*, /node_modules/* — in `astro dev` the
Cloudflare Vite plugin applied "/*" before Vite's own middleware, so /@vite/client
and every module 404'd and no island hydrated (dev-only regression from #79).
- robots.txt disallows /admin/. Deps: jose, marked; yaml moves to dependencies.
- Tests: hosts routing (unit), frontmatter round-trip (unit), smoke: admin 403
without/with a forged JWT. Verified locally on astro dev: upload → 5 variants of the
right sizes with no EXIF, re-upload deduped, CSRF refused, alt edit, delete → 404;
editor defaults, preview and picker work.
- Docs: 00 (D2, D11–D15), 01, 02 (ADR-04, ADR-08), 04 §5a, 06 §9, 07 §13b + checklist,
08 §0 (what actually runs), 16, 17.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
b160b6b3b3 |
feat(media): R2-backed images — /media route with a year-long cache, coverMedia, R2 gallery photos (#81)
Uploaded images (the admin comes next) live in the new R2 bucket poli0981-media
(APAC, no public URL). Each upload is transformed ONCE into a fixed set of variants, so
nothing is ever re-processed: AVIF 480/800/1200 (Cloudflare's AVIF encoder stops at
1,200 px) and WebP 800/1600 as the fallback, capped at the source width. Anything that
knows an image's id and size can build its URLs and srcsets without a lookup
(src/lib/media.ts).
- GET/HEAD /media/v1/<id>/<avif|webp>-<w> (src/lib/media/serve.ts, routed by the worker
entry): strict path regex, so the private prefixes and traversal attempts can't reach
R2; Cache API in front of R2; `Cache-Control: public, max-age=31536000, immutable`,
ETag/304, nosniff and a `default-src 'none'; sandbox` CSP on every image. Ids are
content hashes and a pipeline change gets a new prefix (v2/…) instead of overwriting,
so "immutable" is true.
- Content: `coverMedia: { id, w, h, alt? }` for blog/stories/projects (a refine rejects
having both `cover` and `coverMedia`), rendered by src/components/MediaImage.astro —
a <picture> with AVIF first, WebP fallback and width/height. PostCard and PostLayout
render it.
- Gallery: the content repo's gallery-photos/<album>.json lists an album's R2 photos
with {vi, en} captions; src/lib/gallery.ts merges them after the local photos and
validates them with zod (read via import.meta.glob like captions.json, so a repo
without the folder builds without warnings). Album-only-on-R2 is valid; an album
with no photos at all still fails the build. Lightbox uses the WebP variants.
- wrangler: r2_buckets MEDIA → poli0981-media.
Smoke test: /media seeds a local R2 object and checks 200 + type, year-long immutable
caching, sandbox CSP, nosniff, 304, HEAD, 404 for missing/private/encoded-traversal/
other-version paths and 405 for POST. Verified with a temporary R2 album + coverMedia
post: srcsets come out capped at the source width (1000 px → avif 480/800/1000).
Docs: 04 §6b (how R2 images work), 16 (R2 + Images costs), 00 D10.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
af4cf073df |
feat(gate): Turnstile bot check before any page, 48-hour pass (ships switched off) (#80)
Visitors without a pass get a "checking you're human" step instead of the page; solving
Turnstile earns a signed 48-hour cookie. Lives in the worker entry, since static pages
never reach Astro middleware.
How a page request is decided (src/lib/gate/policy.ts):
- off unless GATE_MODE is "on"/"force" AND GATE_SECRET and TURNSTILE_SECRET exist — CI,
Lighthouse and branch previews are never gated;
- never gated: non-GET, the admin host, /api, /admin, /media and the legal pages (the
privacy policy must be readable first); feeds, sitemap, robots, OG images, hashed
assets, sw.js and /offline/ don't even reach the Worker (run_worker_first);
- `x-verified-bot: true` passes. A zone Transform Rule sets that header on every request
to to_string(cf.client.bot), so clients can't forge it. No header at all means the rule
isn't deployed: fail OPEN and log, rather than lock search engines out ("force" skips
this for local testing);
- a valid `__Host-gate` pass passes (src/lib/gate/cookie.ts: v1.<exp>.<nonce>.<HMAC>,
Max-Age 172800, Secure, HttpOnly, SameSite=Lax; expiry can't be extended or pushed
past one TTL; rotating GATE_SECRET voids every pass).
The gate page (src/lib/gate/render.ts) is the requested page with its <body> swapped by
HTMLRewriter. The <head> stays as built — title, description, canonical, OG/Twitter,
CSS, fonts, theme bootstrap and the CSP meta — so link previews from bots that aren't
"verified" (Zalo, Telegram…) still show the real title, and the page's own CSP already
allows /gate.js ('self') and Turnstile. External scripts, modulepreloads and JSON-LD
(the Q&A page carries every answer in it) are dropped. It answers 200 — preview bots
ignore non-2xx — with no-store, noindex and no validators. Only 200 text/html becomes
the gate; redirects, 304s and 404s pass through. /pagefind/* (full text of every page)
is 403 without a pass.
public/gate.js renders Turnstile (action "gate", page language, current theme), trades
the token at POST /api/gate (rate-limited by RL_GATE, same-origin only, verified with
action + hostname) for the cookie and reloads. Strings in i18n `humanCheck`; styles in
global.css (the gate can't add a <style> without breaking the page's CSP hashes).
Ships with GATE_MODE "off". Turning it on is a one-line follow-up once the Transform
Rule is confirmed to reach the Worker.
Legal: privacy §1/§3/§8 (content#2, bumped) disclose Turnstile, the one strictly
necessary cookie and that JS is needed once; the legal sheet's line 3 and SECURITY.md
no longer say "cookieless" / "no cookies". Docs: 06 §3b (flow, kill switch), 07 §8/§8b
(reusing the widget, GATE_SECRET, the exact Transform Rule), 09.
Tests: `npm test` (node --test, 11 cases: pass lifetime, wrong secret, tampered/too-far
expiry, garbage, cookie format/parsing, settings, decisions) and smoke phase 2, which
forces the gate on with Turnstile's always-pass test secret and walks the whole flow
against the built worker (gate page, exemptions, 403 pagefind, cross-site rejection,
/api/gate → cookie → real page, tampered cookie → gate).
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
||
|
|
b1020e6357 |
feat(edge): custom worker entry in front of every page (no gate yet) (#79)
Prerendered pages are served by the adapter's static-asset lookup before the Astro middleware runs, so nothing at runtime could touch them — the www→apex redirect, the denylist and the security headers only ever applied to /api routes (the headers reached pages through public/_headers). The upcoming Turnstile gate and /media route need a hook there, so this adds one. - wrangler `main` → src/worker.ts, which wraps `handle()` from @astrojs/cloudflare/handler (the adapter's documented custom-entry API; the build-time prerender worker still uses the adapter's own entry, so nothing here runs at build). - `assets.run_worker_first`: every path except hashed /_astro assets, OG images, the favicon, sw.js/skullhop.js/gate.js, /offline/, robots/sitemaps/feeds and /.well-known — those stay on the asset layer (unbilled, unaffected by any gate). /pagefind/* goes through the Worker on purpose: its fragments hold every page's full text. - Pages are fetched from ASSETS with the original request. The adapter's own lookup fetches by URL string, which drops the method and conditional headers: once pages run through the Worker, every revalidation would have become a full 200 and HEAD a GET. - www→apex moves from the middleware into the entry, so it covers static pages too. - Security headers come from src/lib/security-headers.ts, shared with the middleware, and are set on every response leaving the entry (copying immutable asset responses). - Edge logic fails open to `handle()`; a bug there must not take the site down. - `preview_urls: false`: per-version preview URLs live on workers.dev, outside the zone's WAF, Transform Rules and Access. Explicit because an omitted key keeps the current setting. CI: `wrangler types --strict-vars=false` (vars typed as string, not literals), and a smoke test (scripts/smoke-worker.mjs, `npm run smoke`) boots the built worker with `wrangler dev` and checks /, headers, 304 revalidation, HEAD, the trailing-slash 307, 404, /api/health, sw.js, a hashed asset, RSS and security.txt. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
637dac67ff |
fix(deps): clear every open Dependabot/OSV advisory and unblock CI (#74)
main has been red since September: the `npm audit --omit=dev --audit-level=high` gate in ci.yml tripped on advisories that piled up, so every PR failed — including the 13 Dependabot PRs, each of which only fixed one package and so could never go green on its own. This bumps everything in one go. - astro 7.2.0 → 7.3.6 (critical RCE via AVIF image optimization, GHSA-26w7-cxv4-gfx2; path-segment auth bypass GHSA-376h-93r7-7g6f), @astrojs/cloudflare 14.3.4, @astrojs/mdx 8.0.3 (Astro 7.3 ships markdown-satteri 0.4, which mdx 7 can't peer with), @astrojs/sitemap, svelte 5.57.2, zod 4.6.5, sharp 0.35.5, wrangler 4.148. - Transitive fixes now come from the parents (svgo 4.1, devalue 5.9.4, undici 7.29.1/ 8.x, fast-uri 3.1.8, http-cache-semantics 4.3, source-map-js 1.2.2, …), so the old overrides are gone. Two remain because a parent pins an exact vulnerable version: fflate (satori → 0.7.3) and sharp (miniflare → 0.35.4, librsvg CVE fixed in 0.35.5). The old `undici` override also forced 7.x onto unifont's ^8 range — that's fixed. - gray-matter → yaml in scripts/gen-og.mjs: gray-matter's js-yaml@3 → argparse@1 → sprintf-js chain carries an advisory with no fixed version. Only frontmatter is read. - Dev tools bumped; typescript-eslint held at 8.70.x (8.71 reports 131 false `no-unused-vars` in Svelte files) and prettier-plugin-astro at 0.14 (1.x reflows inline expressions in 50 .astro files — a visual change). Both are in Dependabot's ignore list with the reason. - `z` now comes from astro/zod (the astro:content re-export is deprecated). CI: - ci.yml no longer path-filters pull_request: `build` is a required check, so a docs-only PR could never merge. - OSV now uses the reusable SARIF workflow (repo is public → code scanning is free); findings land in Security → Code scanning and still fail the run. v2.6.0 (#70). npm audit: 0 vulnerabilities (prod and dev). Build: 63 pages, sitemap unchanged, CSP guard ok, OG images generated. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
5468359bde |
feat(content): add npm run new:post and the four frontmatter templates
docs 04 §5 promises `docs/templates/{blog,story-chapter,project,faq}.md` and §5's
utility note promises `npm run new:post`. Neither existed, so every new entry
started by copy-pasting an old file and hoping the schema had not moved.
The templates are the single source of truth; the script only substitutes
placeholders. Adding a field to a Zod schema means editing one template and the
scaffolder follows, rather than the two drifting apart — which is the failure mode
that made a hand-maintained THIRD-PARTY-NOTICES.md credit a package we never used.
npm run new:post -- blog "Đêm render đầu tiên"
npm run new:post -- story "Chương 3" --series dem-khong-tieng
npm run new:post -- project "RepoLens" --lang en
npm run new:post -- faq "Bạn dùng công cụ gì?"
Slugs are stripped of diacritics per docs 04 §7. NFD handles the combining marks,
but đ/Đ is its own codepoint rather than d-plus-a-mark, so it is mapped by hand —
"Đêm render đầu tiên" becomes dem-render-dau-tien, not "-m-render-d-u-tien".
Each template carries a comment block explaining the non-obvious fields
(translationKey pairing, contentWarning, the stories folder = series segment,
draft visibility), because that knowledge previously lived only in the schema file.
Refuses to overwrite an existing file. That is not hypothetical: the first test run
tried to scaffold "Đêm render đầu tiên" and hit the real post of that name.
Because src/content is now a submodule, the script prints where the commit actually
belongs — writing to a submodule and committing in the parent is an easy way to
lose an afternoon's writing.
Verified: all four types scaffold, slugs correct across diacritics/đ/punctuation,
bad input rejected with usage, and a full build passes with the generated files in
place (Astro validates draft frontmatter at collection load).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
||
|
|
c324a4231a |
feat(ci): generate THIRD-PARTY-NOTICES.md and fail CI when it drifts
docs 08 §6 specifies `node scripts/gen-notices.mjs --check` as a CI gate and it never existed, so the notices file was hand-maintained — which is how it ended up crediting `@vite-pwa/astro`, a package this repo has never depended on. The file now follows the A/B split docs 12 describes: hand-written framing outside the BEGIN/END markers, generated table inside. `--check` regenerates in memory and diffs, so a dependency change without a regenerate fails the build. Licenses are read from each package's own package.json rather than via `license-checker` — same source of truth, one fewer dependency to vet, which is rather the point of a licence audit. Two things fell out of building it: 1. **The survey has to be deterministic or the gate is useless.** npm installs only the platform-matching binaries (`@img/sharp-*`, `*-msvc`), so a disk-based walk of the resolved tree produces a different file on Windows than in Linux CI and `--check` could never pass. The table is therefore built from direct dependencies, which are installed everywhere; the transitive tree contributes a count straight from the lockfile. Verified: every row corresponds to a package.json entry, 31/31. 2. **sharp's prebuilt binaries are Apache-2.0 AND LGPL-3.0-or-later** — they bundle libvips. Nobody had noticed. It is fine here (build-time only, never served, LGPL attaches to distributing the library) but it is now written down instead of waiting to be rediscovered. Documented in prose alongside the MPL-2.0 build tools, since platform binaries are outside the generated block. Licenses outside the allowlist are reported and fail `--check` unless they carry an explicit REVIEWED entry with a reason. THIRD-PARTY-NOTICES.md is added to .prettierignore: prettier re-aligns markdown tables, so leaving it in put the two tools in permanent disagreement — prettier rewrites the block, then --check reports drift, every run. Confirmed by running the full CI order twice. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
14a7c326b1 |
fix(ci): follow HTML's end-tag grammar, and make the guard prove it every run
Third js/bad-tag-filter alert on the same line: `</script\t\n bar>`. An HTML end tag may carry attributes after the name — the parser discards them, but it is still a valid `</script>`. So `<\/script\s*>` was still too narrow. The pattern now mirrors the grammar on both sides: /<script(\s[^>]*)?>([\s\S]*?)<\/script(\s[^>]*)?>/gi `(\s[^>]*)?` means "either `>` immediately, or whitespace then anything" — requiring that whitespace is what keeps `<scripting>` from matching. More usefully: this is the third one-line patch to the same regex, each written from reasoning about the grammar and each wrong. So the grammar is now asserted rather than argued. SELFTEST holds ten tag forms — plain, uppercase, mixed case, attributes, typed, newlines inside the start tag, spaced end tag, end tag with junk, plus `<scripting>`/`<noscript>` as negative controls — and runs before every real check. A mismatch exits 1 before any "ok" can be printed. Verified by sabotage, not by reading it: restoring the original pattern makes the selftest fail with exit 1 and name all four holes at once; the correct pattern passes and the real 61-page build still reports 343/343. This is the failure mode the guard itself exists to prevent — a checker that quietly passes because it cannot see the thing it is checking for. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
0b4edf3e5e |
fix(ci): match every script-tag form a browser executes, not just the tidy one
Second CodeQL js/bad-tag-filter alert on the same line: `</script >` — HTML
allows whitespace before a closing tag's `>`, and the previous pattern required
`</script>` exactly. Fixing only the casing last time addressed one symptom of
the same underlying mistake: matching what Astro emits rather than what a
browser runs.
/<script(\s[^>]*)?>([\s\S]*?)<\/script\s*>/gi
/i <SCRIPT> executes
(\s[^>]*)? requires whitespace or `>` after the name, so `<scripting>` is
NOT treated as a script (the old `([^>]*)` matched it)
<\/script\s*> tolerates `</script >`
Tested against every variant a browser would run rather than eyeballing the
regex — lowercase, uppercase, spaced end tag, mixed-case + spaced, and with
attributes: 5/5 now caught, 0/5 of the last three before. Negative control
`<scripting>not a script</scripting>` correctly ignored, and the real 61-page
build still passes 343/343.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
||
|
|
46c62cc21a |
fix(ci): make the CSP guard's script matcher case-insensitive
CodeQL (js/bad-tag-filter, high) on its first run after the repo went public: `/<script([^>]*)>([\s\S]*?)<\/script>/g` does not match `<SCRIPT>`. Astro only ever emits lowercase, so this changes nothing about today's output — but it matters more than a "not currently reachable" finding usually would, because this guard's entire job is to notice inline scripts nobody expected. A matcher that only sees the expected casing would report "all clear" on exactly the surprise it exists to catch. Raw HTML in a markdown body, or any future tool in the build chain, is enough to produce one. Verified both directions rather than just adding the flag: a synthetic page containing `<SCRIPT>alert(1)</SCRIPT>` now fails the guard (it did not before), and the real 61-page build still passes 343/343. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
209e5fa80e |
feat(gallery): replace the demo album with 34 real photos in 5 albums
The gallery has been live since PR #10 showing five machine-generated gradient JPGs. This swaps in the real set from the owner's photo folder. Albums (34 photos): home 7, game 20, portrait 3, dev 2, meal 2. Files are renamed to `<album>-NN.jpg` — lowercase and zero-padded — so the numeric sort in lib/gallery.ts is stable and the `Meal-1.jpg` vs `meal-1.jpg` case mismatch in the source notes can't bite. Game files keep their original numbering so the captions map 1:1. Captions: every file has a vi + en pair (the schema build-fails otherwise). They are translated from the owner's own notes; the five game screenshots whose title was not recorded get an honest "a screenshot from another game" rather than an invented one. The game album description carries the developer/publisher attribution the source notes asked for, and Disclaimer §3 already covers it. **strip-exif now also enforces the size budget.** docs 04 §5 states two rules for a committed photo — no metadata, and max 2560px / ~1.5MB — but only the first was implemented, so the second had never actually been applied. Phone photos arrive at 6048x8064 and 2.5MB. The script now resizes the long edge to 2560 and re-encodes JPEG with mozjpeg at q85; mozjpeg specifically, because stripping metadata always costs one re-encode generation and plain q82 was coming out *larger* than the input on already-compressed files. Result: 10.9MB -> 6.9MB, largest file 932KB (was 2.5MB), nothing over 2560px. Demo album retired: `src/assets/gallery/demo/`, both content entries, and `scripts/gen-demo-gallery.mjs` + its npm script are removed. They existed only to give the gallery something to render before real photos arrived. Verified: 59 pages build (was 51), 5 albums x 2 locales, 241 optimized derivatives, `check-exif` passes over every tracked asset (0 GPS, 0 serials), CSP guard 331/331, check/lint/knip/prettier green. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
901763b72f |
fix(csp,router): hash every inline script, drop ClientRouter, canonical hrefs
Three production bugs, all verified against the live site before and after.
1. CSP violations in the console
Two separate causes, only one of which is ours:
- The theme bootstrap was `<script is:inline>`, which Astro never hashes
(core/csp/common.js `trackScriptHashes` walks bundled scripts, client
directives, island prebuilts and settings.scripts — `is:inline` is in
none of them). It survived only because a <meta> CSP does not govern
markup that precedes it, and the script happened to sit at byte 237 with
the meta at byte 16119. Fragile by accident.
- The same trick did NOT save /500 and /429, whose `is:inline` scripts sit
in the body, after the meta. Verified in dist: meta@8777, script@14554.
The 500 reference code and the 429 countdown have never run in
production.
Fixes: the theme bootstrap moves to `injectScript("head-inline", ...)` via
a tiny local integration — the one path that is both rendered verbatim
inline (no FOUC) and hashed from that same string, so the CSP cannot drift.
The two error-page scripts become processed `<script>` and get bundled and
hashed; deferring is harmless for a span fill and a 1s countdown.
`scripts/check-csp-hashes.mjs` now fails the build if any inline script is
missing from its page CSP. Currently: 283 scripts / 51 pages, 0 unhashed.
NOTE: the violation actually visible in the browser console is Cloudflare's
Browser Insights beacon (`window.__CF$cv$params`), which embeds the CF-RAY
so its hash changes per request and can never be allowlisted. That one is a
dashboard setting, not code.
2. Hovering any link logged a 503
`<ClientRouter />` force-enables prefetch with `prefetchAll: true` and a
hover strategy. Cloudflare's zone Speculation Rules then refuses every
`Sec-Purpose: prefetch` request to a Worker origin:
curl -H 'Sec-Purpose: prefetch' /gaming/ -> 503 Cf-Speculation-Refused
Both /gaming and /gaming/ 503, so this was never a trailing-slash problem.
`prefetch: false` is pinned so re-adding the router cannot silently switch
hover-prefetch back on. The zone toggle still has to be turned off too.
3. Pages not finishing render on route change
Astro documents `<ClientRouter />` as unsupported with `security.csp`, and
the mechanism is concrete: swapHeadElements removes the old <meta> CSP, but
removing a meta does not revoke an enforced policy — so each navigation
ANDs another policy onto the document. style-src genuinely differs per page
(58 distinct hashes site-wide, 45-47 per page), so after one soft nav the
destination loses stylesheets. Removing the router is the fix; CSP-as-header
is not available here (the Cloudflare adapter declares no
adapterFeatures.staticHeaders, so prerendered routes are forced to meta).
Nothing used transition:persist/name/animate, so only the default fade is
lost — and 16KB of the 81KB client JS budget goes with it.
Also in this pass:
- Trailing slash: `sectionPath`/`alternatePath` now emit the canonical form, so
nav hrefs match canonicals and the sitemap instead of costing a 307 each.
`isActivePath` had to change with them or every aria-current would silently
disappear (`"/blog/" + "/"` never matches). Deliberately NOT setting
`trailingSlash: "always"`: create-manifest.js gives extension-less endpoints
the config value, which would make POST /api/report 404.
- Pre-existing bug: middleware served `/403` and `/429` through ASSETS, but
those build to `403/index.html` and `html_handling: "auto-trailing-slash"`
answers the slash-less form with a 307 and an EMPTY body — which the handler
re-wrapped as a blank 403/429. Confirmed live: `/403` -> 307, 0 bytes.
Denylisted and rate-limited visitors have been getting a blank page.
Verified: build, astro check (0 errors), eslint, prettier, knip all green;
CSP guard passes; no slash-less internal hrefs remain in the built HTML.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
|
||
|
|
a8c48d6dd4 |
feat(og): build-time Open Graph images (Satori + resvg)
- scripts/gen-og.mjs: renders a 1200x630 card per blog/story/project entry (both locales) + a default card into dist/client/og/. Ink-night background, Waveline motif, Bricolage title, section badge, CW strip for stories. - Runs in Node from the build script: a prerendered endpoint runs in workerd (no sharp/fs), verified — so generation is a post-build Node step. - Static Bricolage TTFs (instanced from the variable font via fonttools) committed for Satori (it can't read WOFF2 or variable fonts). - src/lib/og.ts: pure ogUrl()/DEFAULT_OG. seo.ts defaults og:image to the default card; Post/Story/Project layouts pass per-entry images. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
432d57f216 |
feat: gallery + lightbox + EXIF pipeline
Album index + album detail pages with an image lightbox (doc 04/05 P2), plus the
EXIF hygiene tooling and an AI-crawler robots.txt.
Gallery:
- src/lib/gallery.ts: import.meta.glob resolver mapping src/assets/gallery/<album>/
→ sorted ImageMetadata joined with a sibling captions.json (build-fails on a
missing vi/en key). getGalleryAlbums/galleryAlbumPaths mirror the projects helpers.
- Routes gallery/{index,[album]} + /en mirrors. Album route param = the shared
`album` folder name so /gallery/demo ↔ /en/gallery/demo share a slug (LangSwitch
works, no findTranslation change). GalleryCard mirrors ProjectCard.
- Lightbox.svelte island (client:idle): full AVIF slides generated via getImage() in
the page and passed as plain props; thumbnails are <button data-lightbox-index> and
the island attaches one delegated document click listener (CSP-safe, no inline
onclick). Keyboard ←/→/Esc, focus trap, pointer swipe (offset via CSSOM var),
x/y counter, caption, reduced-motion branch. No GSAP.
- Nav: Gallery added to primaryNav (Header + menu). i18n `gallery` block in vi/en.
- CSP unchanged (self-hosted /_astro images covered by 'self').
Demo content: scripts/gen-demo-gallery.mjs generates 5 EXIF-clean gradient placeholder
JPGs (swap for real photos later) + captions.json + vi/en album entries.
EXIF + robots:
- scripts/strip-exif.mjs (sharp re-encode, manual pre-commit) + scripts/check-exif.mjs
(exifr devDep; fails CI if a changed src/assets image carries GPS/serial).
- CI: checkout fetch-depth 0 + Check EXIF step (before Build). knip entry scripts/*.mjs.
eslint ignore widened to **/.wrangler/ (nested widgets worker temp files).
- public/robots.txt: block /api + AI-training crawlers (ARR content) + sitemap.
Gates green: prettier, eslint, astro check (0 errors), knip, npm audit, build, check-exif.
Built HTML verified: 4 gallery routes, thumbnails + island present, robots + sitemap OK.
(Local astro preview is broken on this Win/Node25 box — interactive lightbox verified
on the live deploy.)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|