5 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 2c40baf5c0 v1.1: Harbor UI refresh, Contact page, feed guard, CHANGELOG 1.1.0 (#25)
- docs: CHANGELOG for 1.1.0; README and CLAUDE.md caught up
- fix(sonar): Number.NaN over the global NaN (S7773)
- feat(gate): an icon tile on each step of the legal gate
- feat(build): check-feed — assert the emitted RSS that notify.py trusts
- feat(contact): /contact and /vi/contact — one address per purpose (D27)
- feat(ui): "Harbor" refresh — tokens, header, home, cards, detail, footer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:13:40 +07:00
poli0981andClaude Opus 5.5 0c6e5bc85d v1.1: Turnstile human check (+ /api/verify Worker), GPC-aware Web Analytics, legal rewrite, contacts (#24)
- test(e2e): match Cloudflare hosts by hostname, not substring
- docs: amend hard rules 1 and 7; decision log D25–D27
- docs(legal): v1.1 legal set — Cloudflare services, operator, notices, contacts
- feat(gate,analytics): Turnstile human check after consent; GPC-aware Web Analytics
- feat(worker): POST /api/verify — server-side Turnstile check (D25)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:56:21 +07:00
poli0981andClaude Opus 5.5 3743cfbfe0 v1.1: native view transitions, CSP-first head, PWA, search, i18n/a11y, display menu, data rules, e2e (#23)
- fix(check-csp): match end tags the way the HTML tokenizer does
- ci(deps): keep @types/node on the Node major in .nvmrc
- test: Playwright + axe e2e, script tests, island coverage, CI gates
- fix(sort): pin the category-page and API orders to the data
- fix(a11y): keep the visible EN/VI code in the switcher's accessible name
- fix(nav): reliable cross-document View Transitions opt-in
- feat(data): enforce the data rules CONTRIBUTING promised; fix quarantine flow
- feat(prefs): display menu with theme, custom scrollbar and motion choices
- fix(i18n,a11y): real small type, translated chips and errors, nav semantics
- fix(search): race-free search with URL state, stable sort and relevance
- fix(pwa): installable app, styled offline page, prompt SW updates, head fixes
- refactor(scripts): hashed pre-paint scripts, CSP meta first, richer error log
- refactor(nav): replace <ClientRouter /> with native cross-document view transitions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 22:22:48 +07:00
poli0981andClaude Opus 5.5 ff95578f48 fix: unblock CI — close every dependency advisory, pin actions, fix asset caching (#21)
Squashed from 8 signed commits:

- chore: normalise line endings to LF with .gitattributes
- fix(deps): refresh dependencies and close every open advisory
- style: adopt prettier-plugin-astro 1.x formatting
- fix: resolve the SonarCloud findings in scripts and issueUrl
- ci: pin actions to SHAs, fix notify/quarantine/link-check, add Dependabot config
- fix(headers): stop Cache-Control concatenation that disabled asset caching
- fix(theme): guard storage access in the pre-paint theme script
- chore(config): TS6-safe tsconfig, type-aware lint, gated build script

Each commit's full rationale is preserved on the PR (#21).
Verified on the Workers Builds preview: hashed assets now carry a single
`Cache-Control: public, max-age=31536000, immutable`, the JSON feeds a single
`max-age=300`, security.txt is utf-8, and preview hosts send noindex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:10:17 +07:00
poli0981 017b07232c fix(seo): per-page descriptions and titles; run codeql on PRs
47 pages (/apps, /categories, 24 category pages, all legal pages) shared
site.tagline as their meta description. Four new bilingual keys take the
build from 654 to 694 distinct descriptions across 699 pages; the rest are
the home page and noindex error pages. Legal pages also gain the
"— SoftHarbor" title suffix.

Audit found the rest of docs/16 §7 already correct: sitemap, hreflang,
canonicals, JSON-LD, and offers omitted for paid apps.

Also: codeql now runs on pull_request. It was a required status check that
only ever ran on push to main, which made it unsatisfiable and deadlocked
merging the moment branch protection went active.
2026-07-30 18:12:46 +07:00
169 changed files with 11281 additions and 3994 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# Local secrets for `wrangler dev` — copy to .dev.vars (git-ignored).
# Cloudflare's always-pass Turnstile TEST secret; pairs with the test
# sitekey the gate uses on localhost (src/lib/turnstile.ts). Production uses
# a runtime secret set in the dashboard, never a file.
TURNSTILE_SECRET=1x0000000000000000000000000000000AA
+18
View File
@@ -0,0 +1,18 @@
# Normalise line endings to LF in the repo AND the working tree, on every OS.
# Without this, Windows checkouts with core.autocrlf=true get CRLF files and
# Prettier (endOfLine: lf) fails locally while CI on Linux passes.
* text=auto eol=lf
# Binary assets — never touch.
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.webp binary
*.avif binary
*.ico binary
*.woff binary
*.woff2 binary
*.ttf binary
*.otf binary
*.pdf binary
+6 -1
View File
@@ -1,7 +1,12 @@
# docs/12 §8 — T6: a malicious PR must not be able to alter what runs.
* @poli0981
# Highest-risk paths, called out explicitly so a review is always required.
# Highest-risk paths, called out explicitly so GitHub always requests the
# owner's review on them. The "Run" ruleset does not REQUIRE an approval
# (single-maintainer repository, 0 required reviews, code-owner review off);
# what it does require is a PR, signed commits and the build / gates / codeql
# checks — see docs/12 §8.
/.github/** @poli0981
/scripts/** @poli0981
/src/data/** @poli0981
/worker/** @poli0981
+57
View File
@@ -0,0 +1,57 @@
# docs/12 §6 — dependency updates.
#
# Replaces renovate.json (removed 2026-10-21). Renovate was never installed on
# this repository: no renovate/* branch, Dependency Dashboard or PR ever
# appeared, so for three months nothing kept versions or action pins current
# while Dependabot security updates — already enabled in Settings — quietly
# failed on transitive packages. One bot, configured here, instead of two.
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
day: monday
time: '05:00'
timezone: Asia/Ho_Chi_Minh
# pnpm 11 rejects any release younger than 24 h (minimumReleaseAge) and CI
# installs with --frozen-lockfile under that policy, so a PR opened on
# release day fails before a single test runs — exactly what killed #14
# and #15. Two days of cooldown keeps every update PR installable.
cooldown:
default-days: 2
open-pull-requests-limit: 10
versioning-strategy: increase
groups:
minor-and-patch:
update-types: [minor, patch]
ignore:
# D21 — TypeScript 7's native compiler does not expose the API that
# `astro check` needs, so `pnpm check` fails on it. Hold at 6.x.
- dependency-name: typescript
update-types: ['version-update:semver-major']
# The Node typings track the Node major in .nvmrc (24 LTS), not the
# newest Node: @types/node 26 types APIs the runtime does not have.
# Bump both together when .nvmrc moves (docs/01 §4).
- dependency-name: '@types/node'
update-types: ['version-update:semver-major']
commit-message:
prefix: 'fix(deps)'
prefix-development: 'chore(deps)'
# Workflow actions are pinned to full commit SHAs (SonarCloud S7637); this
# bumps the SHA and its `# vX.Y.Z` comment together.
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
day: monday
time: '05:00'
timezone: Asia/Ho_Chi_Minh
cooldown:
default-days: 2
groups:
actions:
patterns: ['*']
commit-message:
prefix: 'ci'
+88 -32
View File
@@ -17,16 +17,26 @@
# globs matching nothing, an unregistered service worker, CSP-dropped
# inline styles). A silently-skipping CI is the wrong tool here.
#
# The duplicated "logic" is six pnpm invocations. That is a fair price for a
# gate that fails loudly.
# The duplicated "logic" is a handful of pnpm invocations. That is a fair
# price for a gate that fails loudly.
#
# Every `uses:` is pinned to a full commit SHA with the release tag in a
# comment (SonarCloud githubactions:S7637). Dependabot's github-actions
# ecosystem bumps the SHA and the comment together.
name: ci
on:
pull_request:
push:
branches: [main]
# Lets quarantine.yml run the required checks on the PR it opens: a PR
# created with GITHUB_TOKEN triggers no `pull_request` workflows, but a
# `workflow_dispatch` is the documented exception (docs/12 §4).
workflow_dispatch:
# Explicit — a workflow without its own block defaults every scope to `none`.
# Explicit least privilege. This repository's default workflow token is
# read-WRITE (Settings → Actions → Workflow permissions), so a workflow
# without this block would get far more than it needs.
permissions:
contents: read
@@ -37,10 +47,17 @@ concurrency:
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v7
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# No `version:` — the action reads package.json `packageManager`
# (pnpm@11.x), so CI, Dependabot, Workers Builds and laptops all run the
# same pnpm. 6.0.10+ bootstraps with pnpm 11, which is what silenced the
# "pnpm v10 installation layout at PNPM_HOME" warning on every run.
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
cache: pnpm
@@ -50,29 +67,64 @@ jobs:
run: pnpm lint
- name: Types
run: pnpm check
- name: Unit tests
run: pnpm test
- name: Build
# `coverage` IS the unit run (vitest run --coverage): one pass, and it
# fails below the thresholds in vitest.config.ts.
- name: Unit tests (with coverage thresholds)
run: pnpm coverage
# `pnpm build` is the SAME command Cloudflare Workers Builds runs, and it
# carries its own gates: data + i18n before `astro build`, the CSP and
# service-worker checks on dist/ after it (package.json). Running the
# composite here means CI and production can never diverge on what
# "a good build" means.
- name: Build (with data, i18n, CSP and service-worker gates)
run: pnpm build
# Must run AFTER build — it inspects dist/. CSP style-src drops inline
# style attributes silently, so this is the only thing that catches them.
- name: No inline style attributes
run: pnpm check:styles
# Also post-build, and for the same reason: every service-worker failure
# this project has had was silent (docs/08 Part D).
- name: Service worker shape
run: pnpm check:sw
# Bundles worker/ and validates wrangler.jsonc (bindings, assets,
# run_worker_first) exactly as Workers Builds will, without credentials
# or a deploy. A config error then fails here instead of in production.
- name: Worker bundle (wrangler deploy --dry-run)
run: pnpm exec wrangler deploy --dry-run --outdir "$RUNNER_TEMP/worker"
- name: Dead code
run: pnpm knip
# End-to-end on the build above (docs/11): every page type in both
# locales and colour schemes, desktop + mobile, failing on any console
# error, CSP violation or serious axe finding. The browser download is
# ~150 MB and versioned with @playwright/test, so it is cached per
# version; on a hit only the OS libraries still need installing.
- name: Playwright version
id: pw
run: echo "version=$(pnpm exec playwright --version | awk '{print $2}')" >> "$GITHUB_OUTPUT"
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
id: pw-cache
with:
path: ~/.cache/ms-playwright
key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}
- name: Install Chromium
if: steps.pw-cache.outputs.cache-hit != 'true'
run: pnpm exec playwright install --with-deps chromium
- name: Install Chromium system libraries
if: steps.pw-cache.outputs.cache-hit == 'true'
run: pnpm exec playwright install-deps chromium
- name: End-to-end (Playwright + axe on the built site)
run: pnpm e2e
- name: Upload the Playwright report
if: failure()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: playwright-report
path: playwright-report/
retention-days: 7
gates:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0 # extract-urls --changed diffs against origin/main
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
fetch-depth: 0 # the changed-links step diffs against the PR base
persist-credentials: false
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
cache: pnpm
@@ -85,9 +137,9 @@ jobs:
# The action lives in a SUBDIRECTORY of the repo and there is no rolling
# `v2` tag — only full versions. `…/osv-scanner-action@v2` does not
# resolve. Renovate keeps this pinned version current.
# resolve.
- name: Vulnerability scan
uses: google/osv-scanner-action/osv-scanner-action@v2.3.8
uses: google/osv-scanner-action/osv-scanner-action@b1d267aea5211fa648d9d442fa64b90dbdcbdd36 # v2.7.0
with:
scan-args: |-
--lockfile=pnpm-lock.yaml
@@ -95,12 +147,17 @@ jobs:
run: pnpm audit --prod
# PR-time link check over changed data files only; link-check.yml owns
# the weekly full sweep (docs/12 §5).
# the weekly full sweep (docs/12 §5). git runs HERE, under pipefail, so a
# failed diff stops the job instead of silently widening the sweep.
- name: Collect changed official links
id: urls
if: github.event_name == 'pull_request'
env:
BASE_REF: ${{ github.base_ref }}
run: |
node scripts/extract-urls.mjs --changed > /tmp/urls.txt
set -euo pipefail
git diff --name-only "origin/${BASE_REF}...HEAD" -- src/data/apps \
| node scripts/extract-urls.mjs --changed > /tmp/urls.txt
count=$(grep -c . /tmp/urls.txt || true)
echo "count=$count" >> "$GITHUB_OUTPUT"
echo "$count changed URL(s) to check"
@@ -121,16 +178,15 @@ jobs:
#
# Skipped when the PR changes no app data — lychee treats an empty input
# as a configuration error and fails. A code-only PR legitimately has
# zero URLs to check, and this gate had failed every one of them since it
# was written; nothing noticed because every PR until now touched data.
# Skipping rather than `failIfEmpty: false` keeps the zero visible: a
# skipped step is obvious in the checks list, whereas a green "0 links"
# is exactly the kind of quiet pass this repo keeps getting caught by.
# zero URLs to check. Skipping rather than `failIfEmpty: false` keeps the
# zero visible: a skipped step is obvious in the checks list, whereas a
# green "0 links" is exactly the kind of quiet pass this repo keeps
# getting caught by.
- name: Link check
if: github.event_name == 'pull_request' && steps.urls.outputs.count != '0'
uses: lycheeverse/lychee-action@v2
uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
with:
args: >-
--max-concurrency 4 --retry-wait-time 2 --max-retries 3 --timeout 45
--max-concurrency 4 --retry-wait-time 5 --max-retries 4 --timeout 45
--accept '200..=299,403,429'
/tmp/urls.txt
+13
View File
@@ -4,8 +4,19 @@ name: codeql
on:
push:
branches: [main]
# `pull_request` is REQUIRED, not optional. Branch protection lists
# `codeql / Analyze (javascript-typescript)` as a required status check, and
# a required check that the workflow never produces on a PR is unsatisfiable
# — it deadlocks the repo: no PR can ever merge (hit 2026-07-30).
#
# It is also the point of the tool. Scanning only after the merge tells you
# about a vulnerability that is already on main.
pull_request:
schedule:
- cron: '31 3 * * 1'
# quarantine.yml dispatches this on the PR it opens (GITHUB_TOKEN-created PRs
# trigger no pull_request runs, so the required check would never appear).
workflow_dispatch:
# Required matrix — security-events: write is what lets results upload.
# Must be a SUPERSET of what the reusable workflow's jobs declare — a called
@@ -20,6 +31,8 @@ permissions:
jobs:
codeql:
# First-party org workflow, deliberately tracked at @main so org-wide fixes
# land everywhere at once. Third-party actions are SHA-pinned instead.
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
with:
# A JSON ARRAY STRING, not a bare value — the reusable workflow feeds it
+54 -13
View File
@@ -1,5 +1,11 @@
# docs/12 §5 — weekly full sweep of every official link in the dataset.
# PR-time checking covers only changed files, inside ci.yml's `gates` job.
#
# ONE tracking issue, not one per week. The previous version called
# create-issue-from-file on every red run, which left 12 duplicate
# "link-check: broken official links" issues open (#7–#20) — the latest of
# them for a single transient 502. Now the open issue is refreshed in place,
# and closed automatically the first week the sweep comes back clean.
name: link-check
on:
@@ -11,30 +17,65 @@ permissions:
contents: read
issues: write
concurrency:
group: link-check
cancel-in-progress: false
jobs:
lychee:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# extract-urls.mjs is plain Node, but it should run on the project's
# Node (.nvmrc), not whatever the runner image happens to ship.
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
- run: node scripts/extract-urls.mjs > /tmp/urls.txt
- id: lychee
uses: lycheeverse/lychee-action@v2
uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0
with:
# Kept in step with ci.yml's PR sweep — see the note there for why
# 403/429 are accepted. The weekly run covers the whole catalogue
# (~1 150 URLs), so a false-positive rate that looks tolerable per-PR
# turns into an unreadable issue every Monday.
# 403/429 are accepted. More retries with a longer wait than before:
# vendor sites blip (inkscape.org's 502 opened #20 on its own), and
# a weekly job has the time to ride that out.
args: >-
--max-concurrency 4 --retry-wait-time 2 --max-retries 3 --timeout 45
--max-concurrency 4 --retry-wait-time 10 --max-retries 5 --timeout 45
--accept '200..=299,403,429'
/tmp/urls.txt
# Link rot is triage, not a build break — it opens an issue instead.
output: ./lychee/out.md
# Link rot is triage, not a build break — it updates an issue instead.
fail: false
- if: steps.lychee.outputs.exit_code != 0
uses: peter-evans/create-issue-from-file@v5
with:
title: 'link-check: broken official links'
content-filepath: ./lychee/out.md
labels: link-rot
- name: Refresh the tracking issue
env:
GH_TOKEN: ${{ github.token }}
EXIT_CODE: ${{ steps.lychee.outputs.exit_code }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
title='link-check: broken official links'
existing=$(gh issue list --repo "$GITHUB_REPOSITORY" --label link-rot --state open \
--json number,title --jq "map(select(.title == \"$title\")) | .[0].number // empty")
if [ "$EXIT_CODE" != "0" ]; then
if [ -n "$existing" ]; then
gh issue edit "$existing" --repo "$GITHUB_REPOSITORY" --body-file ./lychee/out.md
gh issue comment "$existing" --repo "$GITHUB_REPOSITORY" \
--body "Still failing in $RUN_URL — the report above was refreshed."
echo "Refreshed #$existing"
else
gh issue create --repo "$GITHUB_REPOSITORY" --title "$title" \
--label link-rot --body-file ./lychee/out.md
fi
elif [ -n "$existing" ]; then
gh issue close "$existing" --repo "$GITHUB_REPOSITORY" \
--comment "Every official link resolved in $RUN_URL. Closing; the next failure reopens a fresh report."
echo "Closed #$existing"
else
echo "All links healthy; nothing to report."
fi
+10 -1
View File
@@ -12,6 +12,7 @@ on:
workflow_dispatch:
inputs:
tag:
description: Release tag to (re-)announce, e.g. v1.1.0
required: true
type: string
@@ -21,4 +22,12 @@ permissions:
jobs:
announce:
uses: poli0981/.github/.github/workflows/announce-release.yml@main
secrets: inherit
with:
# The reusable workflow reads `tag_override`, falling back to the
# release event's tag. This input was never passed before, so every
# manual re-run died with "No release tag available."
tag_override: ${{ inputs.tag || '' }}
# Only what the announcement needs, instead of `secrets: inherit`
# handing every repository secret to code tracked at @main.
secrets:
DISCORD_RELEASES_WEBHOOK: ${{ secrets.DISCORD_RELEASES_WEBHOOK }}
+83 -34
View File
@@ -1,8 +1,21 @@
# docs/12 §4 — enforces hard rule 5 mechanically.
#
# Runs on data pushes AND nightly. The nightly cron is the point: it guarantees
# a flagged entry never survives more than 24 h even if a reviewer missed it.
# It opens a PR rather than pushing to main, so a human stays in the loop.
# Runs on data pushes AND nightly. The nightly cron re-checks main so a
# flagged entry that slipped past review is moved within a day — as a PR, not
# a push to main, so a human stays in the loop and the ruleset's required
# checks still apply.
#
# Fixed 2026-10-21 (audit):
# - A PR opened with GITHUB_TOKEN triggers no `pull_request` workflows, so its
# required checks (build, gates, codeql) never ran and it could not merge.
# The job now dispatches ci.yml and codeql.yml on the PR branch —
# `workflow_dispatch` is the documented exception to that rule.
# - The ruleset requires signed commits: create-pull-request now signs via the
# API (`sign-commits`).
# - Every nightly run re-opened `[quarantine] <slug>` issues while the PR was
# pending; issues are now created only when none is open.
# - Step outputs no longer reach `run:`/`script:` bodies through `${{ }}`
# (expression injection); they pass through `env:` and slugs are validated.
name: quarantine
on:
@@ -14,16 +27,28 @@ on:
workflow_dispatch:
permissions:
contents: write
issues: write
pull-requests: write
contents: read
concurrency:
group: quarantine
cancel-in-progress: false
jobs:
sweep:
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write # create-pull-request commits to quarantine/auto
pull-requests: write # …and opens the PR
issues: write # tracking issue per slug
actions: write # dispatch the required checks onto the PR branch
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v6
# No persisted token while repository code (quarantine.mjs) runs;
# create-pull-request authenticates with its own `token` input.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
@@ -31,12 +56,13 @@ jobs:
run: node scripts/quarantine.mjs
# NOTE: requires Settings → Actions → General → "Allow GitHub Actions to
# create and approve pull requests" (action item H10). Without it this
# step fails even with the permissions block above.
- if: steps.sweep.outputs.moved != ''
uses: peter-evans/create-pull-request@v7
# create and approve pull requests" (action item H10 — enabled).
- id: cpr
if: steps.sweep.outputs.moved != ''
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8.1.1
with:
branch: quarantine/auto
sign-commits: true
title: 'data: quarantine flagged entries'
commit-message: 'data: quarantine ${{ steps.sweep.outputs.moved }}'
labels: security, quarantine
@@ -48,25 +74,48 @@ jobs:
Nothing was deleted. Restoring is a `git mv` plus a status edit;
the reason and evidence live in the linked tracking issue.
- if: steps.sweep.outputs.moved != ''
uses: actions/github-script@v7
with:
script: |
for (const slug of `${{ steps.sweep.outputs.moved }}`.trim().split(/\s+/)) {
if (!slug) continue;
await github.rest.issues.create({ ...context.repo,
title: `[quarantine] ${slug}`,
labels: ['security', 'quarantine'],
body: [
`\`${slug}\` was flagged and moved to \`data/quarantine/\`.`,
'',
'Record here before closing:',
'- [ ] Reason it was flagged',
'- [ ] Evidence link (VirusTotal / vendor advisory)',
'- [ ] Date checked',
'- [ ] Whether users were plausibly exposed (docs/13 §7)',
'',
'Restoring is a reviewed PR: status back to `clean`/`unverified`,',
'a fresh `checkedAt`, and the file moved back (docs/03 §5).',
].join('\n') });
}
- name: Run the required checks on the PR branch
if: steps.cpr.outputs.pull-request-branch != ''
env:
GH_TOKEN: ${{ github.token }}
BRANCH: ${{ steps.cpr.outputs.pull-request-branch }}
run: |
set -euo pipefail
gh workflow run ci.yml --repo "$GITHUB_REPOSITORY" --ref "$BRANCH"
gh workflow run codeql.yml --repo "$GITHUB_REPOSITORY" --ref "$BRANCH"
- name: Open one tracking issue per newly quarantined slug
if: steps.sweep.outputs.moved != ''
env:
GH_TOKEN: ${{ github.token }}
MOVED: ${{ steps.sweep.outputs.moved }}
run: |
set -euo pipefail
for slug in $MOVED; do
# Same shape validate:data enforces on filenames; anything else is
# not ours and must not reach a shell command or issue title.
if ! [[ "$slug" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; then
echo "::warning::skipping unexpected slug '$slug'"
continue
fi
title="[quarantine] $slug"
open=$(gh issue list --repo "$GITHUB_REPOSITORY" --label quarantine --state open \
--json title --jq "map(select(.title == \"$title\")) | length")
if [ "$open" != "0" ]; then
echo "#$title already tracked"
continue
fi
gh issue create --repo "$GITHUB_REPOSITORY" --title "$title" \
--label security --label quarantine --body-file - <<EOF
\`$slug\` was flagged and moved to \`data/quarantine/\`.
Record here before closing:
- [ ] Reason it was flagged
- [ ] Evidence link (VirusTotal / vendor advisory)
- [ ] Date checked
- [ ] Whether users were plausibly exposed (docs/13 §7)
Restoring is a reviewed PR: status back to \`clean\`/\`unverified\`,
a fresh \`checkedAt\`, and the file moved back (docs/03 §5).
EOF
done
+3
View File
@@ -14,6 +14,9 @@ worker-configuration.d.ts
# Test & tooling output
coverage/
playwright-report/
test-results/
blob-report/
.vitest/
lychee/
*.tsbuildinfo
+8 -7
View File
@@ -1,9 +1,10 @@
# Deliberately NO `ignore-scripts=true` — see docs/09 §7.
#
# pnpm >= 10 already blocks dependency lifecycle scripts by default and
# requires an explicit `pnpm.onlyBuiltDependencies` allowlist in package.json.
# That is a strictly better version of what ignore-scripts bought us: the
# allowlist is reviewable, per-package, and committed. Setting ignore-scripts
# on top of it is worse than redundant — it also suppresses the allowlist, so
# esbuild never links its native binary and `pnpm build` cannot run at all
# (found in spike S1, 2026-07-27).
# pnpm >= 10 already blocks dependency lifecycle scripts by default, and pnpm 11
# takes the explicit allowlist from `allowBuilds` in pnpm-workspace.yaml (the
# old `pnpm.onlyBuiltDependencies` field in package.json is ignored there).
# That allowlist is a strictly better version of what ignore-scripts bought us:
# reviewable, per-package, and committed. Setting ignore-scripts on top of it
# is worse than redundant — it also suppresses the allowlist, so esbuild never
# links its native binary and `pnpm build` cannot run at all (found in spike
# S1, 2026-07-27).
+12
View File
@@ -0,0 +1,12 @@
# SonarCloud automatic analysis (project poli0981_softharbor).
# https://docs.sonarsource.com/sonarqube-cloud/advanced-setup/automatic-analysis/
#
# Sources stay rooted at the repo so workflow files under .github/ keep being
# analysed (the githubactions rules found unpinned actions there). Tests are
# split out so test files are judged by test rules, and the curated dataset is
# excluded: it is CC BY-SA content validated by Zod + validate:data, not code.
sonar.sources=.
sonar.tests=.
sonar.exclusions=src/data/**,data/**,docs/**,dist/**,coverage/**,node_modules/**,**/*.test.ts,**/*.test.mjs,e2e/**
sonar.test.inclusions=**/*.test.ts,**/*.test.mjs,e2e/**
sonar.cpd.exclusions=src/data/**,src/i18n/**
+94
View File
@@ -0,0 +1,94 @@
# Changelog
All notable changes to SoftHarbor. The site is continuously deployed; a
version marks a release announced in the repository (docs/13). Dates are
UTC.
## [1.1.0] — 2026-10-21
A full review of the site after launch: security advisories closed, real
production bugs fixed, a new look, and two Cloudflare services added with a
privacy policy rewritten to match.
### Privacy — read this if you read nothing else
v1.0 said "no analytics". That changed, deliberately and narrowly:
- **Cloudflare Web Analytics** (cookieless, nothing stored in your browser)
now counts page views. It does **not load at all** if your browser sends
**Global Privacy Control**, and never on preview or local hosts.
- **Cloudflare Turnstile** runs once in the legal gate, **only after** you
accept the terms, to tell people from bots. It usually needs no click. A
pass is remembered for 48 hours. If it cannot run — blocked, offline, or our
endpoint down — you are let in anyway.
- The [Privacy Policy](https://softharbor.net/legal/privacy) was rewritten to
say exactly what each of these sees and what we keep (nothing identifying),
and the legal version was bumped, so everyone is asked to accept once more.
### Added
- **A new look ("Harbor")**: cool chart-paper light theme and a navy night
theme, hairline rules, soft shadows, a frosted header, a home page with a
live "manifest" of the catalogue and a category grid, redesigned app cards
and detail pages, a five-column footer, and Lucide icons that move a little
on hover or focus — and not at all if you ask for reduced motion.
- **Display menu**: theme (system/light/dark), scrollbar (default, thin or
hidden — scrolling still works), and motion (system or reduced). Applied
before the first paint, so nothing flashes.
- **Contact page** (`/contact`, `/vi/contact`) with one address per purpose:
security, privacy, legal, copyright (DMCA), listing takedowns, licensing,
Code of Conduct, press and collaboration — all `@poli0981.dev`.
- **Shareable search**: the query, filters and sort are kept in the URL; a
"Best match" order while searching; Vietnamese searches ignore diacritics.
- **Installable app**: the PWA manifest is linked, with proper icons; the
offline page now comes with its styles.
- **Third-party notices** now list every package the site is built from,
generated at build time.
- **More "in this category"** on every app page, and a panel explaining what
the security status does and does not mean.
### Fixed
- Hashed assets were served with two contradictory `Cache-Control` values,
so browsers revalidated them on every visit; the JSON feeds were never
cached. Each now gets exactly one.
- The legal gate could be dismissed with Esc in Chromium; its exemptions
missed the real 404 and offline pages; its links looked like plain text.
- Search: a late result could filter the grid after the box was cleared;
"Clear all" left the search text in place; a Czech-locale browser sorted 81
of the 326 apps differently; the page announced the count twice per key.
- Small type (14 px and 12.5 px) was rendering at 16 px across the site.
- The language switcher marked English as current on Vietnamese pages and
linked VI to the home page; its accessible name now keeps the visible code.
- Theme flicker on navigation, a growing pile of CSP tags and a sort menu that
disagreed with the grid — all from the old soft-navigation router, now
replaced by native page transitions.
- Pages no longer overflow sideways on phones.
- Error, 404 and offline pages are bilingual; "1 apps" is "1 app".
### Security & maintenance
- Every open Dependabot advisory closed (including a critical Astro RCE);
dependencies refreshed; GitHub Actions pinned to commit SHAs; Dependabot
configured (Renovate had never run).
- A tiny Worker (`worker/`, `POST /api/verify`) is the only server code; every
page is still served as a static asset.
- The CSP now covers every script in the page head, and the build fails on
anything the policy would silently refuse.
- Data rules enforced at build time: official links only (download portals,
tracking parameters, look-alike hosts and invisible characters rejected),
real dates, evidence required for a security status.
- Tests: 340+ unit, component, build-script and Worker tests (≈95 % coverage of
shipped code, enforced), plus a Playwright + axe suite that loads every page
type in both languages and both themes on desktop and mobile, and fails on
any console error, CSP violation, accessibility violation or sideways
overflow.
## [1.0.0] — 2026-07-30
First public release: 326 apps in 12 categories, English and Vietnamese,
official links only, dated security statuses with their scans linked. See the
[release notes](https://github.com/poli0981/softharbor/releases/tag/v1.0.0).
[1.1.0]: https://github.com/poli0981/softharbor/releases/tag/v1.1.0
[1.0.0]: https://github.com/poli0981/softharbor/releases/tag/v1.0.0
+32 -18
View File
@@ -2,7 +2,7 @@
> Root instruction file for AI-assisted development (Claude Code).
> Read this first. Detailed specs live in `docs/00–16`.
> Suite version: 1.2 (2026-07-27) · Author: poli0981 / SkullMute
> Suite version: 1.3 (2026-10-21, site v1.1) · Author: poli0981 / SkullMute
## What this project is
@@ -16,17 +16,22 @@ googling every tool one by one.
- Repo: `poli0981/softharbor` · License: code **GPL-3.0-only**, data **CC BY-SA 4.0**
- Hosting: **Cloudflare Workers Static Assets** on canonical
**`https://softharbor.net`** (Free zone; `www` 301s to apex; workers.dev
route disabled, PR previews only — see `docs/16`). No Worker script, no
backend, no database.
- Stack: Node 24 LTS · pnpm 10 · Astro 7 (static output) · Svelte 5 islands ·
route disabled, PR previews only — see `docs/16`), deployed by Cloudflare
Workers Builds when `main` changes. One tiny Worker answers
`POST /api/verify` only (D25); no backend, no database.
- Stack: Node 24 LTS · pnpm 11 · Astro 7 (static output) · Svelte 5 islands ·
Tailwind CSS 4.3 · TypeScript strict · Wrangler 4 — full table in `docs/01`
## Hard rules (never violate)
1. **Static-first.** No `main` Worker script, no SSR, no server code, no
database, no serverless functions. All interactivity is client-side Svelte
islands. If a feature seems to need a server, redesign it or move it to a
GitHub Actions workflow.
1. **Static-first.** No SSR, no database, no serverless functions; all
interactivity is client-side Svelte islands. The ONE exception (D25) is
`worker/`: a minimal Worker that answers only `POST /api/verify` (the
legal gate's Turnstile check) and runs only for the paths in
`assets.run_worker_first`. It never serves pages, never gates content, and
every failure on its side must fail OPEN. Anything else that seems to need
a server: redesign it or move it to a GitHub Actions workflow — a second
Worker route needs a decision-log entry.
2. **Data is law.** Every listed app is exactly one JSON file in
`src/data/apps/<slug>.json`, validated by the Zod schema in
`src/content.config.ts`. Invalid data must fail the build. Never bypass the
@@ -46,9 +51,14 @@ googling every tool one by one.
`src/i18n/en.json` and `src/i18n/vi.json`; every app has `summary.en` and
`summary.vi`. A missing key in either language fails CI.
7. **Self-host everything.** Fonts (Fontsource), logos (Simple Icons /
`src/assets/logos/`), scripts, styles. Zero third-party requests at
runtime. `Content-Security-Policy: default-src 'self'` must keep passing
(`docs/09 §4`).
`src/assets/logos/`), scripts, styles. The only third-party runtime
requests are two Cloudflare services, each started by our own code:
Web Analytics (`src/scripts/analytics.js` — never under Global Privacy
Control, production host only; D26) and Turnstile (`src/lib/turnstile.ts`
— only after the legal gate is accepted; D25). Adding a third needs a
decision-log entry. The CSP (`default-src 'self'` plus exactly those
origins, `docs/09 §4`) must keep passing `pnpm check:csp` and the e2e
suite.
8. **Official links only, original words only.** `links.*` must point to the
developer's official domain or official repo. Summaries are written from
scratch — never paste vendor marketing copy or Wikipedia text (data is
@@ -76,21 +86,25 @@ pnpm dev # astro dev
pnpm build # astro build → dist/
pnpm preview # astro preview
pnpm lint # eslint + prettier --check
pnpm test # vitest run
pnpm test # vitest run (unit, islands, scripts, worker)
pnpm coverage # vitest run --coverage (thresholds in vitest.config.ts)
pnpm e2e # playwright + axe against astro preview (build first)
pnpm validate:data # node scripts/validate-data.mjs (L2 data rules)
pnpm i18n:check # node scripts/check-i18n-parity.mjs (EN/VI key parity)
pnpm deploy # wrangler deploy (CI does this on main)
pnpm deploy # build + wrangler deploy (Workers Builds does this on main)
```
## Naming & identifiers (locked)
- Component prefix `Sh*`: `ShAppCard.astro`, `ShSearch.svelte`,
`ShLegalGate.svelte`, `ShFilterSheet.svelte`, `ShLangSwitch.svelte`,
`ShThemeToggle.svelte`
- CSS custom properties: `--sh-*` · localStorage keys: `sh:legal`, `sh:lang`,
`sh:theme`
- Worker name: `softharbor` · Data: `src/data/apps/` · Quarantine:
`data/quarantine/`
`ShPrefs.svelte` (display menu; replaced `ShThemeToggle`)
- CSS custom properties: `--sh-*` · localStorage keys: `sh:legal`, `sh:human`,
`sh:lang`, `sh:theme`, `sh:scrollbar`, `sh:motion`
- Worker name: `softharbor` (code in `worker/`, endpoint `/api/verify`) ·
Data: `src/data/apps/` · Quarantine: `data/quarantine/`
- Contacts: one `@poli0981.dev` address per purpose — `src/lib/contacts.ts`
(D27)
## Document map
+1 -1
View File
@@ -6,7 +6,7 @@ Please read it there; it applies in full and is not restated here.
It covers every project space — issues, pull requests, commit messages,
discussions — and any place someone is representing the project.
Reports go to **contact@softharbor.net**. They are read by the maintainer
Reports go to **code@poli0981.dev**. They are read by the maintainer
(@poli0981) and are not shared further. If your report concerns the
maintainer, say so and you will get a plain answer about what can be done,
rather than a process that reviews itself.
+2 -1
View File
@@ -9,7 +9,8 @@ under **GPL-3.0-only**, dataset entries under **CC BY-SA 4.0**.
- Code of Conduct: [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)
- Security vulnerabilities: [SECURITY.md](SECURITY.md) — **never** a public issue
- Contact: **contact@softharbor.net**
- Contact: Code of Conduct reports **code@poli0981.dev**, licensing questions
**copyright@poli0981.dev**; anything else, open an issue
## Suggesting an app
+2
View File
@@ -18,3 +18,5 @@ structure). It does **not** cover the listed applications, their names, or
their logos, which belong to their respective owners (see /legal/trademarks).
Everything in this repository outside `src/data/` is licensed under
GPL-3.0-only — see `LICENSE`.
Questions about this license or how to attribute: copyright@poli0981.dev.
+24 -4
View File
@@ -28,11 +28,18 @@ explaining it away. The scan is linked either way — judge it yourself.
## How it is built
Fully static. No server, no database, no backend, no tracking, and no
third-party request at runtime — fonts, icons and scripts are all self-hosted.
Static. No database, no accounts, no cookies; fonts, icons and scripts are
self-hosted. The exceptions are deliberate and small: one tiny Worker endpoint
that checks the legal gate's Cloudflare Turnstile token (`worker/`, and the
gate lets you in even if the check cannot run), and cookieless Cloudflare Web
Analytics, which does not load at all when your browser sends Global Privacy
Control. The [Privacy Policy](https://softharbor.net/legal/privacy) has the
details.
Astro 7 (static) · Svelte 5 islands · Tailwind CSS 4 · TypeScript strict ·
Node 24 · pnpm 10 · deployed to Cloudflare Workers Static Assets.
Node 24 · pnpm 11 · Cloudflare Workers Static Assets (+ one Worker route).
Tested with Vitest (unit, islands, build scripts, the Worker) and Playwright +
axe on the built site.
```bash
pnpm install
@@ -85,4 +92,17 @@ AI was used to build this project; where and how is disclosed at
## Contact
**contact@softharbor.net** · maintained by [@poli0981](https://github.com/poli0981)
Maintained by [@poli0981](https://github.com/poli0981). One address per
purpose, so a message reaches the right queue:
| About | Address |
| --------------------------------------------------- | ---------------------- |
| A vulnerability, or a hijacked or malicious listing | security@poli0981.dev |
| Privacy | privacy@poli0981.dev |
| Terms, disclaimer, other legal | legal@poli0981.dev |
| A copyright complaint | dmca@poli0981.dev |
| Changing or removing your app's listing or logo | takedown@poli0981.dev |
| Licensing of the code or the dataset | copyright@poli0981.dev |
| Code of Conduct | code@poli0981.dev |
| Press | press@poli0981.dev |
| Collaboration | collab@poli0981.dev |
+5 -3
View File
@@ -9,7 +9,7 @@ versions to patch (docs/13 §1).
## Reporting a vulnerability
Please use **GitHub's private vulnerability reporting** on this repository
(Security → Report a vulnerability), or email `contact@softharbor.net`.
(Security → Report a vulnerability), or email `security@poli0981.dev`.
Acknowledgement within **72 hours**. Machine-readable contact details are in
[`/.well-known/security.txt`](https://softharbor.net/.well-known/security.txt).
@@ -32,8 +32,10 @@ Acknowledgement within **72 hours**. Machine-readable contact details are in
- Vulnerabilities in the **listed third-party applications themselves**.
Report those to their vendors — but please tell us too, so we can flag the
entry while it is unresolved.
- Anything requiring a server: there is no backend, no database, no accounts,
no cookies, and no user input parsing (docs/09 §3).
- Server-side issues beyond one endpoint: the site is static except for
`POST /api/verify`, the legal gate's Turnstile check (`worker/`, D25),
which **is** in scope. There is no database, no accounts and no cookies
(docs/09 §3).
## What we do not claim
+89 -46
View File
@@ -1,12 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
import { createHash } from 'node:crypto';
import { defineConfig } from 'astro/config';
import svelte from '@astrojs/svelte';
import sitemap from '@astrojs/sitemap';
import AstroPWA from '@vite-pwa/astro';
import tailwindcss from '@tailwindcss/vite';
import Icons from 'unplugin-icons/vite';
import { VIEW_TRANSITION_OPT_IN } from './src/lib/inlineCss';
// Reachable but meaningless in SERPs — noindex'd (docs/16 §7) AND kept out of
// the sitemap, or GSC reports "Submitted URL marked noindex" forever.
@@ -31,38 +33,31 @@ export default defineConfig({
// html_handling: "drop-trailing-slash" in wrangler.jsonc, /apps/ redirects
// to /apps and the canonical URL is the one that serves.
trailingSlash: 'never',
// `inlineStylesheets: 'never'` is a CSP decision, not a perf one.
// `inlineStylesheets: 'never'` began as a CSP fix and stays as a cache one.
//
// Astro's default inlines small stylesheets, and its CSP hashes them into
// the meta tag of the page that carries them. That is fine on a hard load
// and broken under `<ClientRouter />`: a soft navigation never re-applies
// the meta CSP, so the policy in force stays the one from the page you
// STARTED on. Arriving at a page with a style the origin page lacked means
// the browser refuses it.
//
// That is exactly what happened to `/apps`. It alone carried ShAppCard's
// scoped CSS — the stretched-link `::after{inset:0}` and `.sr-only` — so
// navigating there from any detail page silently dropped the whole-card
// click target and unhid screen-reader-only text.
//
// External stylesheets are covered by `style-src 'self'` with no hash at
// all, so every page's policy accepts them and the class of bug disappears.
// They also cache once across ~700 pages instead of shipping per page.
// Under the former `<ClientRouter />`, a soft navigation never re-applied
// the meta CSP, so a small stylesheet Astro had inlined (and hashed into ONE
// page's policy) was refused on arrival from any page that lacked it — which
// silently dropped ShAppCard's stretched link and `.sr-only` on /apps.
// ClientRouter is gone since v1.1 (every navigation is a real document load
// with its own policy), but external stylesheets are still the better
// shape: covered by `style-src 'self'` with no hash at all, and cached once
// across ~700 pages instead of shipping inside each one.
build: { format: 'file', inlineStylesheets: 'never' },
// OFF because the platform refuses it, not because it is unwanted.
// `<ClientRouter />` turns prefetching on by default and hovering a link
// then issues a speculative GET carrying `Sec-Purpose: prefetch`. Cloudflare
// answers those with a bare **503** and the header
// `Cf-Speculation-Refused: prefetch refused: disabled for worker requests` —
// reproducible on demand, and nothing to do with rate limiting:
// OFF because the platform refuses it, not because it is unwanted. A
// speculative GET carrying `Sec-Purpose: prefetch` is answered by Cloudflare
// with a bare **503** and `Cf-Speculation-Refused: prefetch refused:
// disabled for worker requests` — reproducible on demand, and nothing to do
// with rate limiting:
//
// curl -I -H 'Sec-Purpose: prefetch' https://softharbor.net/apps → 503
// curl -I https://softharbor.net/apps → 200
//
// So every hover cost a failed request and a red console line while
// delivering no prefetch at all. Real navigations were never affected.
// Revisit if Cloudflare ever allows speculation on Worker routes.
// So prefetching would cost a failed request and a red console line per
// hover while delivering nothing. (The zone's Speed Brain feature hits the
// same refusal and should be off — docs/16 §9.) Revisit if Cloudflare ever
// allows speculation on Worker routes.
prefetch: false,
i18n: {
@@ -85,12 +80,35 @@ export default defineConfig({
"default-src 'self'",
"img-src 'self' data:",
"font-src 'self'",
"connect-src 'self'",
// Cloudflare Web Analytics posts its beacon to cloudflareinsights.com
// (src/scripts/analytics.js; skipped under GPC).
"connect-src 'self' https://cloudflareinsights.com",
// The Turnstile widget is an iframe (legal gate step 2, after consent).
'frame-src https://challenges.cloudflare.com',
"manifest-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"object-src 'none'",
],
// The two third-party script origins, both loaded by our own code
// rather than by markup: the analytics beacon (src/scripts/analytics.js)
// and Turnstile's api.js (src/lib/turnstile.ts). `resources` REPLACES
// Astro's default, so 'self' must be listed or every same-origin
// script — islands included — is refused (docs/09 §4).
scriptDirective: {
resources: [
"'self'",
'https://static.cloudflareinsights.com',
'https://challenges.cloudflare.com',
],
},
// The one `is:inline` <style> (src/lib/inlineCss.ts) — Astro hashes
// only what it bundles, so this hash is ours to supply.
styleDirective: {
hashes: [
`sha256-${createHash('sha256').update(VIEW_TRANSITION_OPT_IN).digest('base64')}` as const,
],
},
},
},
@@ -111,24 +129,28 @@ export default defineConfig({
// one of them (docs/09 §4, D20).
injectRegister: 'script',
manifest: {
id: '/',
name: 'SoftHarbor',
short_name: 'SoftHarbor',
description: 'Free & buy-once desktop software, one page.',
theme_color: '#f7f4ee',
background_color: '#f7f4ee',
// The existing SVG, used as-is. A single scalable icon covers every
// size, and `purpose: 'any maskable'` lets platforms that crop to a
// shape do so without a separate asset. Browsers with no SVG-manifest
// support simply fall back to the favicon — strictly better than the
// empty array that shipped in M5, which suppressed the install prompt
// entirely. Raster PNGs remain the eventual upgrade (docs/13 §2).
lang: 'en',
// The tile colour of the mark (scripts/gen-icons.mjs), so the install
// splash and title bar match the icon rather than the page.
theme_color: '#0B4F7A',
background_color: '#0B4F7A',
// Raster icons generated from one vector mark (`pnpm icons`). Until
// v1.1 the only icon was the SVG favicon drawn in currentColor —
// black in launchers — declared 'any maskable' with no safe zone.
icons: [
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
{
src: '/favicon.svg',
sizes: 'any',
type: 'image/svg+xml',
purpose: 'any maskable',
src: '/icons/maskable-512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'maskable',
},
{ src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' },
],
},
workbox: {
@@ -138,11 +160,32 @@ export default defineConfig({
// original patterns ('offline/**', 'fonts/*.woff2') matched nothing,
// which is a silent failure: the build succeeds and the offline page
// simply is not there (found in M1 and S5).
globPatterns: ['offline.html', '_astro/*.woff2', 'favicon.svg'],
//
// What the offline page actually needs, and nothing more:
// - its stylesheets. Missing until v1.1 — once inlineStylesheets went
// 'never', /offline linked CSS the SW never cached, so it rendered
// unstyled exactly when it was needed;
// - the two pre-paint scripts it loads (errors.js, theme.js);
// - the latin + Vietnamese body and display faces. Precaching all 13
// font files (211 KB, latin-ext and mono included) on a visitor's
// first page view was a lot of bandwidth for a fallback page; the
// rest falls back to system fonts.
globPatterns: [
'offline.html',
'_astro/*.css',
'_astro/{errors,theme,analytics}.*.js',
'_astro/be-vietnam-pro-{latin,vietnamese}-400-normal.*.woff2',
'_astro/bricolage-grotesque-{latin,vietnamese}-wght-normal.*.woff2',
'favicon.svg',
],
// skipWaiting is already true under registerType 'autoUpdate', but
// clientsClaim is not — without it the SW controls only pages loaded
// AFTER activation, so a first-time visitor who loses connection mid
// A new SW takes over as soon as it is installed. registerSW.js never
// posts SKIP_WAITING, so without this a fixed SW waited until every
// SoftHarbor tab was closed (an older comment here wrongly claimed
// 'autoUpdate' implied it).
skipWaiting: true,
// Without clientsClaim the SW controls only pages loaded AFTER
// activation, so a first-time visitor who loses connection mid
// session gets the browser's error page instead of ours (S5).
clientsClaim: true,
@@ -179,9 +222,9 @@ export default defineConfig({
],
vite: {
plugins: [tailwindcss(), Icons({ compiler: 'astro' })],
// `~icons/<set>/<name>` imports compile to Svelte 5 components: usable in
// islands, and in .astro files (rendered to static SVG at build time).
// Data-driven icons (app logos, category icons) go through src/lib/icon.ts.
plugins: [tailwindcss(), Icons({ compiler: 'svelte' })],
},
// No CSP config: nothing inline ships, so `script-src 'self'` in
// public/_headers is the whole story — docs/09 §4, decision D18.
});
+4
View File
@@ -176,6 +176,10 @@ rule 8) · ads/affiliate links (conflicts with the trust proposition).
| 2026-07-28 | **`CLOUDFLARE_API_TOKEN` lacks zone permissions** — CI deploy fails with `Authentication error [code: 10000]` on `/workers/routes`. Local deploys worked because wrangler uses OAuth, which masked it | ⛔ moot — deploy workflow removed (below) |
| 2026-07-28 | **Deployment moved to Cloudflare Workers Builds** (dashboard git integration). `deploy.yml` and `preview.yml` deleted: they duplicated a pipeline the dashboard already runs, and needed a token with zone-write scopes nothing else requires. `wrangler.jsonc` remains the source of truth for routes; the build environment is now Cloudflare's and must match `.nvmrc` | ✅ Kokone |
| 2026-07-28 | `CLOUDFLARE_API_TOKEN` / `CLOUDFLARE_ACCOUNT_ID` repo secrets are now unused by any workflow — **delete them** unless something else claims them (action item H3 is retired) | ⚠ Kokone |
| 2026-10-21 | **D25 — one Worker, for `POST /api/verify` only** (amends hard rule 1). The legal gate gains a step 2: Cloudflare Turnstile, loaded only after the documents are accepted, its token checked server-side by `worker/verify.ts` against Siteverify (host, `action: legal_gate`, age ≤ 300 s), rate-limited per IP/64 by the Workers Rate Limiting binding. `assets.run_worker_first: ["/api/verify"]` keeps every page and asset on the unbilled asset path. It gates nothing: a pass is remembered 48 h (`sh:human`), and every failure on our side — no secret, Siteverify down, script blocked, 10 s timeout — **fails open** with a 1 h retry, so a person is never locked out. `TURNSTILE_SECRET` is a *runtime* secret (a Workers Builds build variable is invisible to the Worker) | ✅ (user, 2026-10-21) |
| 2026-10-21 | **D26 — Cloudflare Web Analytics, honouring Global Privacy Control** (supersedes "No analytics in v1"; amends hard rule 7). Cookieless beacon injected by `src/scripts/analytics.js` only when `navigator.globalPrivacyControl` is not set and the host is `softharbor.net` (never previews, localhost or e2e). CSP gains exactly `static.cloudflareinsights.com` (script), `cloudflareinsights.com` (connect) and `challenges.cloudflare.com` (script + frame, for D25) — nothing else third-party | ✅ (user, 2026-10-21) |
| 2026-10-21 | **D27 — one contact address per purpose** at `poli0981.dev` (supersedes the `contact@softharbor.net` row of 2026-07-20): security, privacy, legal, dmca, takedown, copyright, code (CoC), press, collab — `src/lib/contacts.ts`. `sponsor@` deliberately unused: a neutral directory takes no paid placement. Mail is hosted by Google (MX), which the Privacy Policy now says | ✅ (user, 2026-10-21) |
| 2026-10-21 | **`LEGAL_VERSION` → 2026-10-21** with per-document "Last updated" dates (`LEGAL_UPDATED`): Privacy covers D25/D26 and names the operator; Terms gain the operator and a copyright-complaint procedure (`dmca@`); nine EN/VI wording gaps and two false AI-Disclosure claims fixed. A test now fails if an accepted document is dated after the version | ✅ |
## 5. Open questions for Kokone
+9
View File
@@ -181,6 +181,15 @@ the same PR — the current policy would junk such mail by design.
- **OG/meta:** `og:site_name`, `og:title`, `og:description` (locale
summary), `og:url` (canonical), `og:locale` + `og:locale:alternate`,
`twitter:card=summary`. Per-app OG images stay post-v1 (docs/15 §2).
- **Every indexable page needs its OWN description.** App pages get the
locale summary for free, but `/apps`, `/categories`, the 24 category pages
and the legal pages all fell through to `site.tagline` — 47 pages sharing
one string, which Google treats as a quality signal and usually rewrites.
They now build from `meta.apps`, `meta.categories`, `meta.category` and
`meta.legal`, so 694 of 699 pages are unique; the remainder are the home
page (where the tagline *is* the description) and the noindex error pages.
Legal pages also carry the `— SoftHarbor` title suffix now: an unbranded
`<title>` in a SERP reads as somebody else's document.
## 8. Search-engine plumbing
+151
View File
@@ -0,0 +1,151 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// Shared e2e fixture: every test fails if its page logged a console error, an
// uncaught exception or a Content-Security-Policy violation.
//
// CSP violations are collected from the `securitypolicyviolation` event — the
// policy is a <meta> tag, which cannot carry report-uri/report-to, so the
// event is the only signal (errors.js records the same thing for bug reports).
//
// Messages from inside Cloudflare's Turnstile iframe are ignored: that frame
// enforces its own CSP and logs violations for probes it makes itself
// (hagen./brunhild.challenges.cloudflare.com), which no page can change.
import { expect, test as base, type Page } from '@playwright/test';
import { PASS_TTL_MS } from '../src/lib/human';
import { LEGAL_VERSION } from '../src/lib/legal';
/** Cloudflare's challenge hosts (the Turnstile frame and its probes). */
function fromTurnstileFrame(url: string): boolean {
try {
const host = new URL(url).hostname;
return host === 'challenges.cloudflare.com' || host.endsWith('.challenges.cloudflare.com');
} catch {
return false; // no location at all — not the frame's
}
}
declare global {
interface Window {
__shCsp?: string[];
}
}
export const test = base.extend<{ issues: string[]; allowConsole: RegExp[] }>({
/**
* Console errors a test EXPECTS, e.g. Chrome's "status of 404" line for a
* 404 document. Set with `test.use({ allowConsole: [/…/] })`.
*/
allowConsole: [[], { option: true }],
issues: [
async ({ page, allowConsole }, use) => {
const issues: string[] = [];
await page.addInitScript(() => {
window.__shCsp = [];
document.addEventListener('securitypolicyviolation', (e) => {
window.__shCsp?.push(`${e.effectiveDirective} blocked ${e.blockedURI || 'inline'}`);
});
});
page.on('console', (msg) => {
if (msg.type() !== 'error') return;
if (fromTurnstileFrame(msg.location().url)) return;
if (allowConsole.some((re) => re.test(msg.text()))) return;
issues.push(`console: ${msg.text()}`);
});
page.on('pageerror', (err) => issues.push(`pageerror: ${err.message}`));
await use(issues);
const csp = await page.evaluate(() => window.__shCsp ?? []).catch(() => []);
expect(
[...issues, ...csp.map((c) => `csp: ${c}`)],
'console errors / CSP violations',
).toEqual([]);
},
{ auto: true },
],
});
export { expect };
/**
* Waits until an island has hydrated (Astro removes `ssr` from its
* <astro-island>). `client:idle` islands hydrate after load, so acting on
* them straight after `goto` races the hydration.
*/
export async function waitForIsland(page: Page, name: string): Promise<void> {
await page.waitForFunction((n) => {
const island = document.querySelector(`astro-island[component-url*="${n}"]`);
return island !== null && !island.hasAttribute('ssr');
}, name);
}
/**
* Resolves once every finite animation on the page has finished. The pages
* rise into place on load (global.css `sh-rise`); axe measures colour
* contrast with the element's CURRENT opacity, so scanning mid-fade reports
* contrast failures that no settled page has.
*/
export async function settled(page: Page): Promise<void> {
await page.evaluate(() =>
Promise.all(
document
.getAnimations()
.filter((a) => a.effect?.getComputedTiming().iterations !== Infinity)
.map((a) => a.finished.catch(() => undefined)),
),
);
}
/**
* Pre-accept the legal gate (the current version) AND its human check, before
* the page loads — for tests about something other than the gate.
*/
export async function acceptGate(page: Page): Promise<void> {
await page.addInitScript(
([version, ttl]) => {
try {
localStorage.setItem('sh:legal', version);
localStorage.setItem('sh:human', String(Date.now() + ttl));
} catch {
/* storage blocked: the gate will show, and the test will say so */
}
},
[LEGAL_VERSION, PASS_TTL_MS - 60_000] as const,
);
}
/** A stand-in for Cloudflare's api.js: a widget that hands over a token at once. */
const FAKE_TURNSTILE = `window.turnstile = {
render(el, options) { setTimeout(() => options.callback('e2e-token'), 50); return 'w1'; },
reset() {},
remove() {},
};`;
/**
* Stands in for Cloudflare in the gate's step 2: api.js becomes FAKE_TURNSTILE
* (served from its real URL, so the page's CSP is still exercised), and
* /api/verify — which `astro preview` does not run — answers `status`.
* `'blocked'` makes api.js fail to load instead. Returns the tokens posted.
*/
export async function stubTurnstile(
page: Page,
status: number | 'blocked' = 200,
): Promise<string[]> {
const tokens: string[] = [];
await page.route('https://challenges.cloudflare.com/turnstile/v0/api.js*', (route) =>
status === 'blocked'
? route.abort('blockedbyclient')
: route.fulfill({ contentType: 'text/javascript', body: FAKE_TURNSTILE }),
);
await page.route('**/api/verify', async (route) => {
tokens.push(String((route.request().postDataJSON() as { token?: unknown }).token));
await route.fulfill({
status: status === 'blocked' ? 503 : status,
contentType: 'application/json',
body: status === 200 ? '{"ok":true}' : '{"error":"unavailable"}',
});
});
return tokens;
}
+112
View File
@@ -0,0 +1,112 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// The legal gate in a real browser: top layer, the platform's Esc handling
// (closedby="none" + re-open), persistence, page-declared exemptions — and
// step 2, the Turnstile check, with Cloudflare stood in for (fixtures.ts
// stubTurnstile): only after acceptance, remembered when it passes, and never
// a dead end when it cannot run.
import type { Page } from '@playwright/test';
import { LEGAL_VERSION } from '../src/lib/legal';
import { expect, stubTurnstile, test } from './fixtures';
const HOUR = 3_600_000;
/** Milliseconds until the stored check lapses, read from the page. */
const humanFor = (page: Page) =>
page.evaluate(() => Number(localStorage.getItem('sh:human')) - Date.now());
test('blocks a first-time visitor until accepted and checked, and remembers both', async ({
page,
}) => {
const tokens = await stubTurnstile(page);
const scripts: string[] = [];
page.on('request', (r) => {
if (new URL(r.url()).hostname === 'challenges.cloudflare.com') scripts.push(r.url());
});
await page.goto('/apps');
const gate = page.getByRole('dialog', { name: 'Before you continue' });
await expect(gate).toBeVisible();
// Esc twice — Chromium's close watcher only honours preventDefault() on
// `cancel` after user activation; the gate must survive either way.
await page.keyboard.press('Escape');
await page.keyboard.press('Escape');
await expect(gate).toBeVisible();
// Nothing of Cloudflare's is fetched before the documents are accepted.
expect(scripts).toEqual([]);
await page.getByTestId('sh-legal-accept').click();
await expect(page.getByTestId('sh-legal-gate')).toBeHidden();
expect(tokens).toEqual(['e2e-token']);
expect(scripts).toHaveLength(1);
expect(await humanFor(page)).toBeGreaterThan(47 * HOUR);
await page.reload();
await expect(page.getByTestId('sh-legal-gate')).toHaveCount(1); // still rendered…
await expect(page.getByTestId('sh-legal-gate')).toBeHidden(); // …but not shown again
});
test.describe('when the check cannot run', () => {
// The browser reports the blocked script itself; that line is the scenario.
test.use({ allowConsole: [/ERR_BLOCKED_BY_CLIENT/] });
test('lets the person through, says so, and asks again within the hour', async ({ page }) => {
await stubTurnstile(page, 'blocked');
await page.goto('/vi/apps');
await page.getByTestId('sh-legal-accept').click();
await expect(page.getByTestId('sh-gate-status')).toHaveText(
'Không chạy được bước kiểm tra nên đã bỏ qua. Mời bạn vào trang.',
);
await expect(page.getByTestId('sh-legal-gate')).toBeHidden();
const left = await humanFor(page);
expect(left).toBeGreaterThan(0);
expect(left).toBeLessThanOrEqual(HOUR);
});
});
test.describe('when /api/verify is down', () => {
test.use({ allowConsole: [/status of 503/] });
test('fails open the same way', async ({ page }) => {
await stubTurnstile(page, 503);
await page.goto('/apps');
await page.getByTestId('sh-legal-accept').click();
await expect(page.getByTestId('sh-legal-gate')).toBeHidden();
expect(await humanFor(page)).toBeLessThanOrEqual(HOUR);
});
});
test('a lapsed check re-runs step 2 only', async ({ page }) => {
const tokens = await stubTurnstile(page);
await page.addInitScript((version) => localStorage.setItem('sh:legal', version), LEGAL_VERSION);
await page.goto('/categories');
const gate = page.getByTestId('sh-legal-gate');
await expect(gate).toHaveAttribute('data-step', 'verify');
await expect(page.getByTestId('sh-legal-accept')).toHaveCount(0);
await expect(gate).toBeHidden();
expect(tokens).toEqual(['e2e-token']);
});
test('links the documents it asks you to accept, which are exempt', async ({ page }) => {
await page.goto('/vi/apps');
const gate = page.getByRole('dialog');
await expect(gate).toBeVisible();
await gate.getByRole('link', { name: 'Chính sách quyền riêng tư' }).click();
await expect(page).toHaveURL(/\/vi\/legal\/privacy$/);
// Legal pages never render the gate island at all.
await expect(page.getByTestId('sh-legal-gate')).toHaveCount(0);
});
test.describe('exempt pages', () => {
test.use({ allowConsole: [/status of 404/] });
test('error and offline pages are exempt', async ({ page }) => {
await page.goto('/offline');
await expect(page.getByTestId('sh-legal-gate')).toHaveCount(0);
await page.goto('/no-such-page');
await expect(page.getByTestId('sh-legal-gate')).toHaveCount(0);
});
});
+70
View File
@@ -0,0 +1,70 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// Display preferences and search, end to end.
import { acceptGate, expect, test, waitForIsland } from './fixtures';
test.beforeEach(async ({ page }) => {
await acceptGate(page);
});
test('display choices apply at once and are restored before paint', async ({ page }) => {
await page.goto('/');
await waitForIsland(page, 'ShPrefs');
await page.getByRole('button', { name: 'Display settings' }).click();
const panel = page.getByTestId('sh-prefs');
await expect(panel).toBeVisible();
await panel.getByRole('radio', { name: 'Dark' }).check();
await panel.getByRole('radio', { name: 'Hidden' }).check();
await panel.getByRole('radio', { name: 'Reduce' }).check();
const html = page.locator('html');
await expect(html).toHaveAttribute('data-theme', 'dark');
await expect(html).toHaveAttribute('data-scrollbar', 'hidden');
await expect(html).toHaveAttribute('data-motion', 'reduce');
// A fresh document: theme.js must re-apply all three before any island.
await page.goto('/apps');
await expect(html).toHaveAttribute('data-theme', 'dark');
await expect(html).toHaveAttribute('data-scrollbar', 'hidden');
await expect(html).toHaveAttribute('data-motion', 'reduce');
});
test('"/" from any page goes to search', async ({ page }) => {
await page.goto('/categories');
await waitForIsland(page, 'ShPrefs');
await page.keyboard.press('/');
await expect(page).toHaveURL(/\/apps#search$/);
await expect(page.locator('#sh-search')).toBeFocused();
});
test('Vietnamese search ignores diacritics and lands in the URL', async ({ page }) => {
await page.goto('/vi/apps');
await waitForIsland(page, 'ShSearch');
const box = page.locator('#sh-search');
await box.fill('trinh duyet');
await expect(page.locator('[data-slug="firefox"]')).toBeVisible();
await expect(page.locator('[data-slug="7-zip"]')).toBeHidden();
await expect(page).toHaveURL(/\?q=trinh\+duyet/);
await expect(page.locator('#sh-sort')).toHaveValue('relevance');
});
test('a shared URL restores the view, and "Clear all" really clears it', async ({ page }) => {
await page.goto('/apps?q=gimp&platform=linux');
await waitForIsland(page, 'ShSearch');
await waitForIsland(page, 'ShFilterSheet');
await expect(page.locator('#sh-search')).toHaveValue('gimp');
await expect(page.locator('[data-slug="gimp"]')).toBeVisible();
await expect(page.locator('[data-slug="7-zip"]')).toBeHidden();
await page.getByRole('button', { name: /^Filters/ }).click();
await page.getByRole('button', { name: 'Clear all' }).click();
await page.keyboard.press('Escape');
await expect(page.locator('#sh-search')).toHaveValue('');
await expect(page.locator('[data-slug="7-zip"]')).toBeVisible();
// Every card is back (no hard-coded total: the catalogue grows).
await expect(page.locator('#sh-grid [data-slug][hidden]')).toHaveCount(0);
});
+74
View File
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// Every page type, both locales, both colour schemes: renders, no console
// errors, no CSP violations (fixture), and no serious/critical axe findings.
import AxeBuilder from '@axe-core/playwright';
import { acceptGate, expect, settled, test } from './fixtures';
const PAGES = [
'/',
'/apps',
'/apps/7-zip',
'/categories',
'/categories/browser',
'/legal/privacy',
'/legal/terms',
'/vi',
'/vi/apps',
'/vi/apps/7-zip',
'/vi/categories/security-privacy',
'/vi/legal/disclaimer',
'/offline',
'/contact',
'/vi/contact',
];
for (const path of PAGES) {
test(`${path} renders cleanly`, async ({ page }) => {
await acceptGate(page);
const res = await page.goto(path);
expect(res?.status()).toBeLessThan(400);
await expect(page.locator('h1').first()).toBeVisible();
// The pre-paint script ran: a theme is always resolved.
await expect(page.locator('html')).toHaveAttribute('data-theme', /^(light|dark)$/);
// Nothing pokes past the right edge. On a phone that is not a scrollbar
// but a zoomed-out page (the layout viewport widens to fit), and it
// happened twice in v1.1 — a grid sized by min-content, then decoration.
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth - document.documentElement.clientWidth,
);
expect(overflow, 'horizontal overflow in px').toBeLessThanOrEqual(0);
});
}
test.describe('404', () => {
// Chrome logs every 404 document as a console error; that one is expected.
test.use({ allowConsole: [/status of 404/] });
test('an unknown URL gets the 404 page, without the gate', async ({ page }) => {
const res = await page.goto('/this-page-does-not-exist');
expect(res?.status()).toBe(404);
await expect(page.locator('h1')).toContainText("That page isn't here");
await expect(page.getByTestId('sh-legal-gate')).toHaveCount(0);
});
});
for (const scheme of ['light', 'dark'] as const) {
for (const path of ['/', '/apps', '/apps/7-zip', '/vi/apps', '/legal/privacy']) {
test(`${path} has no serious accessibility violations (${scheme})`, async ({ page }) => {
await page.emulateMedia({ colorScheme: scheme });
await acceptGate(page);
await page.goto(path);
await settled(page);
const results = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'])
.analyze();
const serious = results.violations
.filter((v) => v.impact === 'serious' || v.impact === 'critical')
.map((v) => `${v.id}: ${v.nodes.length} node(s) — ${v.nodes[0]?.target.join(' ')}`);
expect(serious).toEqual([]);
});
}
}
+37 -7
View File
@@ -10,13 +10,27 @@ import svelteParser from 'svelte-eslint-parser';
import globals from 'globals';
export default tseslint.config(
{ ignores: ['dist/', '.astro/', 'node_modules/'] },
// `.claude/` holds agent worktrees — full copies of the repo that `eslint .`
// would otherwise lint a second (or third) time.
{
// Unbundled scripts shipped verbatim from public/. They must stay plain
// browser JS — no imports, no TypeScript — because they load before the
// bundle and at a stable path (docs/05 §A8, §A5). Previously theme.js was
// simply ignored; linting them is better than exempting them.
files: ['public/*.js'],
ignores: [
'dist/',
'.astro/',
// wrangler dev / deploy --dry-run scratch bundles.
'.wrangler/',
'node_modules/',
'.claude/',
'coverage/',
'lychee/',
'playwright-report/',
'test-results/',
],
},
{
// Pre-paint scripts Base.astro loads via `?url&no-inline`: Vite copies them
// verbatim (no transform), so they must stay plain classic browser JS — no
// imports, no TypeScript (docs/05 §A8, §A5).
files: ['src/scripts/*.js'],
languageOptions: {
globals: globals.browser,
sourceType: 'script',
@@ -42,6 +56,10 @@ export default tseslint.config(
files: ['**/*.astro'],
rules: {
'astro/no-set-html-directive': 'error',
// CSP: Astro hashes only the scripts it bundles, so a hand-written
// inline <script> body ships unhashed and the browser refuses it with
// nothing in CI noticing. JSON-LD data blocks are allowed by default.
'astro/no-unsafe-inline-scripts': 'error',
},
},
{
@@ -55,14 +73,19 @@ export default tseslint.config(
// the monochrome theming docs/04 §2 and docs/14 §3d require.
files: [
'src/components/ShAppCard.astro',
// The single UI-icon component (src/lib/icon.ts behind it).
'src/components/ShIcon.astro',
'src/components/pages/AppDetailPage.astro',
'src/components/pages/CategoriesPage.astro',
// ShJsonLd emits JSON.stringify() of an object it builds itself into a
// <script type="application/ld+json">. That is a DATA block, not
// executable script (docs/09 §4), and Astro's normal escaping would
// corrupt the JSON — &quot; is not valid inside it. Values come from the
// schema-validated collection, never from a request.
'src/components/ShJsonLd.astro',
// Base.astro writes ONE compile-time constant (src/lib/inlineCss.ts)
// into an inline <style> — set:html keeps the bytes exactly the ones
// astro.config.ts hashes into the CSP. No runtime or data input at all.
'src/layouts/Base.astro',
],
rules: {
'astro/no-set-html-directive': 'off',
@@ -78,6 +101,13 @@ export default tseslint.config(
},
rules: {
'@typescript-eslint/consistent-type-imports': 'error',
// The reason projectService is on at all: promise misuse is invisible
// to non-type-aware linting, and every island here awaits a fetch or a
// dynamic import.
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': 'error',
'@typescript-eslint/await-thenable': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
},
},
{
+8 -4
View File
@@ -1,13 +1,17 @@
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"ignoreExportsUsedInFile": true,
"entry": ["src/pages/**/*.{astro,ts}", "scripts/*.mjs"],
"project": ["src/**/*.{ts,astro,svelte}", "scripts/**/*.mjs"],
"entry": ["src/pages/**/*.{astro,ts}", "scripts/*.mjs", "src/scripts/*.js"],
"project": [
"src/**/*.{ts,astro,svelte}",
"scripts/**/*.{mjs,ts}",
"e2e/**/*.ts",
"worker/**/*.ts"
],
"ignoreDependencies": [
"tailwindcss",
"@fontsource-variable/bricolage-grotesque",
"@fontsource/be-vietnam-pro",
"@fontsource/ibm-plex-mono",
"lefthook"
"@fontsource/ibm-plex-mono"
]
}
+38 -27
View File
@@ -1,6 +1,6 @@
{
"name": "softharbor",
"version": "0.1.0",
"version": "1.1.0",
"private": true,
"type": "module",
"description": "Bilingual (EN/VI) directory of free and buy-once desktop software",
@@ -12,59 +12,70 @@
},
"//": "Dependency build-script policy lives in pnpm-workspace.yaml (allowBuilds) — pnpm 11 ignores a \"pnpm\" field here.",
"scripts": {
"build": "astro build",
"build": "pnpm run validate:data && pnpm run i18n:check && astro build && pnpm run postbuild:html && pnpm run check:csp && pnpm run check:assets && pnpm run check:sw && pnpm run check:feed",
"build:site": "astro build",
"check": "astro check",
"check:styles": "node scripts/check-no-inline-styles.mjs",
"check:assets": "node scripts/check-assets.mjs",
"check:csp": "node scripts/check-csp.mjs",
"check:feed": "node scripts/check-feed.mjs",
"check:sw": "node scripts/check-service-worker.mjs",
"coverage": "vitest run --coverage",
"deploy": "wrangler deploy",
"deploy": "pnpm run build && wrangler deploy",
"dev": "astro dev",
"e2e": "playwright test",
"format": "prettier --write .",
"i18n:check": "node scripts/check-i18n-parity.mjs",
"icons": "node scripts/gen-icons.mjs",
"knip": "knip",
"lint": "eslint . && prettier --check .",
"postbuild:html": "node scripts/postbuild.mjs",
"preview": "astro preview",
"quarantine": "node scripts/quarantine.mjs",
"test": "vitest run",
"test:watch": "vitest",
"validate:data": "node scripts/validate-data.mjs"
},
"dependencies": {
"@astrojs/rss": "^4.0.19",
"@astrojs/sitemap": "^3.7.3",
"@astrojs/svelte": "^9.0.1",
"@astrojs/sitemap": "^3.7.4",
"@astrojs/svelte": "^9.1.0",
"@fontsource-variable/bricolage-grotesque": "^5.3.0",
"@fontsource/be-vietnam-pro": "^5.3.0",
"@fontsource/ibm-plex-mono": "^5.3.0",
"@iconify-json/lucide": "^1.2.120",
"@iconify-json/simple-icons": "^1.2.92",
"@iconify-json/lucide": "^1.2.146",
"@iconify-json/simple-icons": "^1.2.100",
"@tailwindcss/vite": "^4.3.3",
"@vite-pwa/astro": "^1.2.0",
"astro": "^7.1.3",
"astro": "^7.4.1",
"minisearch": "^7.2.0",
"nanostores": "^1.4.1",
"svelte": "^5.56.8",
"nanostores": "^1.5.5",
"svelte": "^5.57.2",
"tailwindcss": "^4.3.3",
"unplugin-icons": "^23.0.1"
"unplugin-icons": "^24.0.0"
},
"devDependencies": {
"@astrojs/check": "^0.9.9",
"@astrojs/check": "^0.9.11",
"@axe-core/playwright": "^4.14.0",
"@eslint/js": "^10.0.1",
"@types/node": "^26.1.1",
"eslint": "^10.8.0",
"eslint-plugin-astro": "^3.0.1",
"eslint-plugin-svelte": "^3.22.0",
"globals": "^17.7.0",
"happy-dom": "^20.11.1",
"knip": "^6.29.0",
"lefthook": "^2.1.10",
"prettier": "^3.9.6",
"prettier-plugin-astro": "^0.14.1",
"@playwright/test": "^1.64.1",
"@types/node": "^24.19.2",
"@vitest/coverage-v8": "5.0.5",
"eslint": "^10.13.0",
"eslint-plugin-astro": "^3.2.1",
"eslint-plugin-svelte": "^3.23.1",
"globals": "^17.13.0",
"happy-dom": "^21.0.3",
"knip": "^6.42.1",
"lefthook": "^2.2.2",
"prettier": "^3.9.10",
"prettier-plugin-astro": "^1.1.1",
"prettier-plugin-svelte": "^4.1.1",
"prettier-plugin-tailwindcss": "^0.8.1",
"svelte-eslint-parser": "^1.8.0",
"sharp": "^0.35.5",
"svelte-eslint-parser": "^1.9.0",
"typescript": "^6.0.3",
"typescript-eslint": "^8.65.0",
"vitest": "^4.1.10",
"wrangler": "^4.114.0"
"typescript-eslint": "^8.72.0",
"vitest": "^5.0.5",
"wrangler": "^4.151.3"
}
}
+43
View File
@@ -0,0 +1,43 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// docs/11 — end-to-end smoke suite against the BUILT site (`astro preview`
// serves dist/ exactly as built, including the per-page meta CSP).
//
// What it exists to catch is the class of bug this project kept shipping with
// every unit test green: a script or style the CSP silently refused, a dialog
// the platform could dismiss, an island that threw on hydration. The shared
// fixture (e2e/fixtures.ts) fails any test whose page logged a console error
// or a CSP violation.
//
// Not covered here, by design: _headers and the Worker (`astro preview`
// applies neither) — those are verified on the Workers Builds preview URL.
import { defineConfig, devices } from '@playwright/test';
const PORT = 4321;
export default defineConfig({
testDir: 'e2e',
fullyParallel: true,
forbidOnly: Boolean(process.env['CI']),
retries: process.env['CI'] ? 1 : 0,
reporter: process.env['CI'] ? [['github'], ['html', { open: 'never' }]] : 'list',
use: {
baseURL: `http://127.0.0.1:${PORT}`,
trace: 'retain-on-failure',
},
projects: [
{ name: 'desktop', use: { ...devices['Desktop Chrome'] } },
// Bottom sheets, the wrapped header and touch targets live here.
{ name: 'mobile', use: { ...devices['Pixel 7'] } },
],
webServer: {
command: `pnpm exec astro preview --port ${PORT} --host 127.0.0.1`,
url: `http://127.0.0.1:${PORT}`,
reuseExistingServer: !process.env['CI'],
timeout: 60_000,
// Astro ≥ 7.2 backgrounds `astro preview` when it detects an AI agent or
// CI; Playwright needs it in the foreground to own its lifetime.
env: { ASTRO_PREVIEW_BACKGROUND: '0' },
},
});
+1999 -2030
View File
File diff suppressed because it is too large. Load diff
+26 -8
View File
@@ -17,12 +17,30 @@ allowBuilds:
# binary is dead weight. False is a decision, not an oversight.
workerd: false
# Security override — GHSA-mh99-v99m-4gvg (CVSS 7.5) affects brace-expansion
# <5.0.8, and no patched 2.x exists. It reaches us only through
# @vite-pwa/astro -> vite-plugin-pwa -> workbox-build -> ... -> minimatch@5,
# i.e. BUILD tooling; nothing here ships to a visitor. Forcing 5.x across a
# three-major gap is only acceptable because the package's surface is a single
# `expand()` function — and because the build and full test suite are run
# against it below. Remove once upstream moves.
# Security overrides. Both packages reach us only through
# @vite-pwa/astro -> vite-plugin-pwa -> workbox-build, i.e. BUILD tooling;
# nothing here ships to a visitor. Each floor is the first release that fixes
# every advisory listed. Remove a line once upstream's own range moves past it
# (`pnpm why <pkg>` shows who still pins the old version).
#
# brace-expansion — GHSA-mh99-v99m-4gvg (<5.0.8), GHSA-rgw5-rvv9-x895 (<5.0.9),
# GHSA-6j4f-fj2g-mc7p (<5.0.10), GHSA-qhr7-859c-m2p7 (<5.0.11),
# GHSA-q2hr-2g5m-vwhr (<5.0.12). No patched 2.x exists, so minimatch@5 is forced
# across a three-major gap; acceptable only because the package's surface is a
# single `expand()` function and the build plus full test suite run against it.
#
# fast-uri — GHSA-7p8r-x3mc-p8w7, GHSA-5jgf-p345-68v8, GHSA-f65p-4m7j-42xc,
# GHSA-fph4-wmhf-6fwf, GHSA-jqff-g426-hqxp, GHSA-qw65-cvwx-89v3 (<3.1.7) and
# GHSA-hrr3-gc8f-f4qj (<3.1.8). Same major as ajv@8's `^3.0.1` range; pnpm kept
# the locked 3.1.4 even under `update --depth Infinity`, hence the override.
overrides:
brace-expansion: '^5.0.8'
brace-expansion: '^5.0.12'
fast-uri: '^3.1.9'
# @vite-pwa/astro 1.2.0 is the latest release (2025-11) and its peer range stops
# at Astro 5. It works on Astro 7 — `pnpm build` and `check:sw` exercise the
# generated service worker on every CI run — so the mismatch is accepted
# explicitly here instead of surfacing as an unexplained install warning.
peerDependencyRules:
allowedVersions:
'@vite-pwa/astro>astro': '7'
+1 -1
View File
@@ -1,4 +1,4 @@
Contact: mailto:contact@softharbor.net
Contact: mailto:security@poli0981.dev
Contact: https://github.com/poli0981/softharbor/security/advisories/new
Preferred-Languages: en, vi
Expires: 2027-07-28T00:00:00.000Z
+31 -1
View File
@@ -11,6 +11,21 @@
# script-src or style-src — the intersection would drop Astro's hashes and
# break every island.
#
# HOW RULES COMBINE (Cloudflare docs, verified live 2026-10-21): every rule
# whose path matches a request contributes its headers, and a header set by
# more than one matching rule is JOINED WITH A COMMA — it is not overridden.
# `/*` used to set `Cache-Control: public, max-age=0, must-revalidate` and
# `/_astro/*` set `public, max-age=31536000, immutable`, so hashed assets were
# served with BOTH. Browsers honour the first max-age (RFC 9111 §4.2.1 even
# says to treat conflicting directives as stale), so every "immutable" asset
# was revalidated on every load and the JSON feeds were never cached at all.
# Fixed two ways at once:
# * `/*` no longer sets Cache-Control. Cloudflare's default for static
# assets is exactly `public, max-age=0, must-revalidate`, which is still
# what HTML, sw.js and the manifest get.
# * Each specific rule detaches any inherited value with `! Cache-Control`
# before setting its own, so a future `/*` line cannot reintroduce this.
#
# The pre-launch `X-Robots-Tag: noindex` was REMOVED on 2026-07-28. It existed
# only while the dataset was empty, where an indexed blank site can linger as
# "Crawled — currently not indexed". With real entries, legal pages and a
@@ -25,17 +40,32 @@
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=(), usb=()
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Cache-Control: public, max-age=0, must-revalidate
# Content-hashed by Vite — this covers JS, CSS *and* the self-hosted fonts,
# which Astro emits into /_astro/ rather than a /fonts/ directory. An earlier
# spec had a separate /fonts/* rule; it matched nothing (found in M1).
/_astro/*
! Cache-Control
Cache-Control: public, max-age=31536000, immutable
/api/apps.json
! Cache-Control
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=300
/search-index.json
! Cache-Control
Cache-Control: public, max-age=300
# RFC 9116 §3: security.txt MUST be served as text/plain with charset=utf-8;
# the platform's inferred type omits the charset.
/.well-known/security.txt
Content-Type: text/plain; charset=utf-8
# PR preview versions (`wrangler versions upload`) are public on workers.dev
# because `preview_urls: true`. Their canonicals already point at
# softharbor.net, but a preview should never be indexed in its own right.
# Absolute-URL patterns with placeholders are supported by _headers; the
# production custom domain never matches this host pattern.
https://:version.:subdomain.workers.dev/*
X-Robots-Tag: noindex
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

-36
View File
@@ -1,36 +0,0 @@
/* SPDX-License-Identifier: GPL-3.0-only
Copyright (C) 2026 poli0981 (SkullMute)
Console ring buffer — docs/05 §A5.
This runs from a deferred external script, NOT from inside ShBugReport,
because that island is client:visible in the footer (docs/02 §5): if the
listeners attached on hydration they would miss every error that happened
before the user scrolled down — which is most of them, and precisely the
ones a bug report needs.
The buffer lives on window so the island reads the same instance a module
import could not share with a plain script. External file, so it satisfies
script-src without a hash (docs/09 §4, D20).
Privacy (docs/09 §8): exception text from our own origin only. It never
wraps console.*, never reads input values, and never leaves the page until
the user explicitly opens a bug report. */
(() => {
var CAP = 20;
var MAX_LINE = 500;
var buf = (window.__shErrors = window.__shErrors || []);
function push(line) {
buf.push(('[' + new Date().toISOString() + '] ' + line).slice(0, MAX_LINE));
if (buf.length > CAP) buf.shift();
}
window.addEventListener('error', function (e) {
push('error: ' + e.message + ' @ ' + e.filename + ':' + e.lineno);
});
window.addEventListener('unhandledrejection', function (e) {
push('unhandledrejection: ' + String(e.reason).slice(0, 400));
});
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

+14 -12
View File
@@ -1,14 +1,16 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="SoftHarbor">
<!-- Placeholder mark: an anchor, matching the "safe berth after a reinstall"
idea behind the name (docs/00 §5 D1). The real wordmark and the PNG PWA
icons (192/512/maskable) are a design deliverable, not something to
fabricate — tracked in docs/13 §2. Uses currentColor so it inherits the
theme like every other icon on the site. -->
<g fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"
stroke-linejoin="round">
<circle cx="16" cy="6" r="3" />
<path d="M16 9v18" />
<path d="M9 14h14" />
<path d="M5 19a11 11 0 0 0 22 0" />
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<defs>
<linearGradient id="sh-tile" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#1C93B8" />
<stop offset="1" stop-color="#0B4F7A" />
</linearGradient>
</defs>
<rect width="32" height="32" rx="7" fill="url(#sh-tile)" />
<g fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"
transform="translate(0 0) scale(1)">
<circle cx="16" cy="8.5" r="2.6" />
<path d="M16 11.1v13.4" />
<path d="M10.5 15h11" />
<path d="M7.5 18.5a8.5 8.5 0 0 0 17 0" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 718 B

After

Width:  |  Height:  |  Size: 614 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

-13
View File
@@ -1,13 +0,0 @@
/* SPDX-License-Identifier: GPL-3.0-only
Copyright (C) 2026 poli0981 (SkullMute)
No-flash theme resolution — docs/05 §A8.
Loaded as a BLOCKING <script src> in <head> (no defer, no async) so it runs
before first paint. It lives in public/ and is deliberately NOT bundled:
the strict CSP is `script-src 'self'` with no hashes (docs/09 §4, D18), so
nothing inline may ship, and the path must stay stable. */
(() => {
const s = localStorage.getItem('sh:theme'); // 'light' | 'dark' | null
const dark = s ? s === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
})();
-25
View File
@@ -1,25 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:best-practices",
":pinAllExceptPeerDependencies",
"helpers:pinGitHubActionDigests"
],
"schedule": ["before 6am on monday"],
"packageRules": [
{ "groupName": "minor+patch", "matchUpdateTypes": ["minor", "patch"] },
{ "matchUpdateTypes": ["major"], "dependencyDashboardApproval": true },
{
"description": "TypeScript 7's native compiler does not expose the API astro check needs, so pnpm check fails on it. Hold at 6.x until Astro supports it (docs/01 §2, D21).",
"matchPackageNames": ["typescript"],
"allowedVersions": "<7"
},
{
"description": "Astro/Vite/Tailwind majors must re-run spike S1 before merge (docs/01 §5.5).",
"matchPackageNames": ["astro", "vite", "tailwindcss", "@tailwindcss/vite"],
"matchUpdateTypes": ["major"],
"dependencyDashboardApproval": true,
"addLabels": ["needs-spike-s1"]
}
]
}
+82
View File
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* Build guard: every same-origin asset a page references must exist in dist/,
* and no script may ship as a data: URL.
*
* WHY THIS EXISTS. Two failure modes that a green `astro build` hides:
*
* - Vite inlines any `?url` import under `build.assetsInlineLimit` (4 KiB) as
* a `data:` URL. Base.astro's pre-paint scripts are smaller than that; as
* `<script src="data:…">` they would be refused by `script-src 'self'` on
* every page. The `&no-inline` suffix prevents it — this proves it did.
* - Astro moves assets emitted from the prerender build into dist/ after the
* fact; if that step ever drops a file, the page references a URL that
* 404s, and only a visitor notices.
*
* Checks the asset-bearing attributes only (script src, link href for
* stylesheets/icons/manifest, img src) — page-to-page links are lychee's job.
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
const DIST = join(process.cwd(), 'dist');
const SCRIPT_SRC = /<script\b[^>]*\ssrc="([^"]+)"/gi;
const LINK_TAG = /<link\b[^>]*>/gi;
const IMG_SRC = /<img\b[^>]*\ssrc="([^"]+)"/gi;
const ASSET_RELS = new Set(['stylesheet', 'icon', 'manifest', 'apple-touch-icon', 'modulepreload']);
function walk(dir) {
const out = [];
for (const entry of readdirSync(dir)) {
const p = join(dir, entry);
if (statSync(p).isDirectory()) out.push(...walk(p));
else if (p.endsWith('.html')) out.push(p);
}
return out;
}
const problems = [];
const checked = new Set();
function checkUrl(rel, url, kind) {
if (url.startsWith('data:')) {
problems.push(`${rel}: ${kind} is a data: URL (${url.slice(0, 40)}…) — CSP refuses it`);
return;
}
// Same-origin, root-relative only; absolute third-party URLs are the CSP's
// concern, and protocol-relative `//host` is not ours either.
if (!url.startsWith('/') || url.startsWith('//')) return;
const path = decodeURIComponent(url.split(/[?#]/)[0]);
if (checked.has(path)) return;
checked.add(path);
if (!existsSync(join(DIST, path)))
problems.push(`${rel}: ${kind} ${path} does not exist in dist/`);
}
let pages = 0;
for (const file of walk(DIST)) {
pages++;
const html = readFileSync(file, 'utf8');
const rel = relative(process.cwd(), file);
for (const m of html.matchAll(SCRIPT_SRC)) checkUrl(rel, m[1], 'script');
for (const m of html.matchAll(IMG_SRC)) checkUrl(rel, m[1], 'image');
for (const [tag] of html.matchAll(LINK_TAG)) {
const relAttr = /\srel="([^"]+)"/i.exec(tag)?.[1] ?? '';
const href = /\shref="([^"]+)"/i.exec(tag)?.[1];
if (href && relAttr.split(/\s+/).some((r) => ASSET_RELS.has(r)))
checkUrl(rel, href, `link[${relAttr}]`);
}
}
if (pages === 0) problems.push('found no HTML pages under dist/ — run `astro build` first');
if (problems.length > 0) {
console.error(`check-assets — ${problems.length} problem(s):`);
for (const p of problems.slice(0, 20)) console.error(` ✗ ${p}`);
process.exitCode = 1;
} else {
console.log(
`check-assets — OK (${pages} pages, ${checked.size} distinct same-origin assets exist)`,
);
}
+159
View File
@@ -0,0 +1,159 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* Build guard: every page's markup must be allowed by that page's own CSP
* (docs/09 §4). Formerly check-no-inline-styles.mjs.
*
* WHY THIS EXISTS. The CSP is a per-page <meta> that Astro generates with
* hashes for the inline code it knows about. Anything it does NOT know about
* is refused by the browser SILENTLY — the build passes, the source looks
* right, and the page renders without it:
*
* - an inline `style="…"` attribute (hashes never apply to attributes, and
* the policy has neither 'unsafe-inline' nor 'unsafe-hashes'): that is how
* the sticky header shipped transparent (2026-07-28);
* - a <style> element Astro did not hash: `transition:name` once shipped
* 1.5 MB of CSS refused on every page with all gates green;
* - an inline <script> body Astro did not hash (Astro only hashes scripts it
* bundles itself, so a hand-written `is:inline` body would be refused).
*
* It also fails when a page has NO CSP meta (formerly a silent skip that still
* printed OK), and when anything executable precedes the meta tag — a meta
* policy only governs what comes after it (see scripts/postbuild.mjs).
*
* Fix for a style failure: use a Tailwind utility. Every design token is
* exposed as one (`text-sh-muted`, `bg-sh-surface`, …) in
* src/styles/global.css.
*/
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
const DIST = join(process.cwd(), 'dist');
const CSP_META = /<meta http-equiv="content-security-policy" content="([^"]+)"/i;
/**
* <style> and <script> elements; external scripts (with `src`) are skipped in
* the code below. The end tags accept what the HTML tokenizer accepts —
* `</script >`, `</script foo>` — so an oddly written end tag cannot hide an
* element's content from the hash check (CodeQL js/bad-tag-filter). This
* reads our own build output, but a checker must not have blind spots.
*/
const STYLE_EL = /<style\b[^>]*>([\s\S]*?)<\/style\b[^>]*>/gi;
const SCRIPT_EL = /<script\b([^>]*)>([\s\S]*?)<\/script\b[^>]*>/gi;
const HAS_SRC = /\ssrc\s*=/i;
const DATA_BLOCK = /\stype="application\/(?:ld\+)?json"/i;
/** Every start tag. `[^>]*` is a single linear run — no nested quantifiers. */
const START_TAG = /<[a-z][^>]*>/gi;
/**
* A `style` attribute in any of HTML's three value syntaxes — double-quoted,
* single-quoted or unquoted — and any letter case. Applied to one bounded tag
* string at a time, which keeps it linear (SonarCloud S8786).
*/
const STYLE_ATTR = /\sstyle\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/i;
const sha256 = (s) => `sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}`;
function walk(dir) {
const out = [];
for (const entry of readdirSync(dir)) {
const p = join(dir, entry);
if (statSync(p).isDirectory()) out.push(...walk(p));
else if (p.endsWith('.html')) out.push(p);
}
return out;
}
const problems = {
styleAttr: [],
unhashedStyle: [],
unhashedScript: [],
missingCsp: [],
lateCsp: [],
};
let pages = 0;
const styleHashes = new Set();
for (const file of walk(DIST)) {
pages++;
const html = readFileSync(file, 'utf8');
const rel = relative(process.cwd(), file);
for (const [tag] of html.matchAll(START_TAG)) {
const m = STYLE_ATTR.exec(tag);
if (!m) continue;
const decl = m[1] ?? m[2] ?? m[3] ?? '';
// An empty style="" is harmless noise from a framework; a declaration is not.
if (decl.trim() !== '')
problems.styleAttr.push({ rel, detail: `style="${decl.slice(0, 70)}"` });
}
const cspMatch = CSP_META.exec(html);
if (!cspMatch) {
problems.missingCsp.push({ rel, detail: 'no <meta http-equiv="content-security-policy">' });
continue;
}
const csp = cspMatch[1];
const firstScript = html.search(/<script[\s>]/i);
if (firstScript !== -1 && firstScript < cspMatch.index) {
problems.lateCsp.push({ rel, detail: 'a <script> precedes the CSP meta tag' });
}
for (const m of html.matchAll(STYLE_EL)) {
const hash = sha256(m[1]);
styleHashes.add(hash);
if (!csp.includes(`'${hash}'`)) {
problems.unhashedStyle.push({ rel, detail: `${hash} ${JSON.stringify(m[1].slice(0, 60))}` });
}
}
for (const m of html.matchAll(SCRIPT_EL)) {
if (HAS_SRC.test(m[1])) continue; // external: covered by script-src, not a hash
if (DATA_BLOCK.test(m[1])) continue; // JSON-LD is data, not script
const hash = sha256(m[2]);
if (!csp.includes(`'${hash}'`)) {
problems.unhashedScript.push({ rel, detail: `${hash} ${JSON.stringify(m[2].slice(0, 60))}` });
}
}
}
const advice = {
styleAttr:
'CSP style-src drops these silently. Use a Tailwind utility — the design tokens are\n exposed as one in src/styles/global.css.',
unhashedStyle:
'Astro hashes the styles it knows about; anything it misses must be removed or added\n via security.csp.styleDirective.hashes (docs/09 §4).',
unhashedScript:
'Astro only hashes scripts it bundles. Move the code into a file and reference it with\n `?url&no-inline` (see Base.astro), or add its hash to security.csp.scriptDirective.',
missingCsp:
"Astro's security.csp emits the policy per page; a page without it is unprotected and\n invisible to every other check here.",
lateCsp:
'A meta CSP only governs what follows it. scripts/postbuild.mjs moves it to the top of\n <head> — did it run?',
};
let failed = false;
for (const [kind, list] of Object.entries(problems)) {
if (list.length === 0) continue;
failed = true;
console.error(`check-csp — ${list.length} problem(s): ${kind}`);
const seen = new Set();
for (const { rel, detail } of list) {
if (seen.has(detail)) continue;
seen.add(detail);
if (seen.size > 10) break;
console.error(` ✗ ${rel}\n ${detail}`);
}
console.error(` ${advice[kind]}\n`);
}
if (pages === 0) {
console.error('check-csp — found no HTML pages under dist/. Run `astro build` first.');
failed = true;
}
if (failed) {
process.exitCode = 1;
} else {
console.log(
`check-csp — OK (${pages} pages: policy first in <head>, no style attributes, ` +
`${styleHashes.size} <style> hash(es) and every inline script allowed by its own page)`,
);
}
+132
View File
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// check-csp.mjs and postbuild.mjs together: postbuild puts the policy first,
// check-csp proves every page's markup is allowed by its own policy. Plus
// check-assets.mjs, the other guard over dist/ HTML.
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { project, run } from './fixture';
const sha = (s: string): string => `'sha256-${createHash('sha256').update(s).digest('base64')}'`;
const CHARSET = '<meta charset="utf-8">';
const meta = (policy: string): string =>
`<meta http-equiv="content-security-policy" content="${policy}">`;
const page = (policy: string, head = '', body = ''): string =>
`<!doctype html><html><head>${CHARSET}${meta(policy)}${head}</head><body>${body}</body></html>`;
describe('check-csp', () => {
it('passes a page whose inline style and script are hashed', () => {
const css = 'a{color:red}';
const js = 'console.log(1)';
const root = project({
'dist/index.html': page(
`script-src 'self' ${sha(js)}; style-src 'self' ${sha(css)}`,
`<style>${css}</style><script src="/a.js"></script>`,
`<script>${js}</script><script type="application/ld+json">{"@type":"Thing"}</script>`,
),
});
const r = run('check-csp.mjs', root);
expect(r.code).toBe(0);
expect(r.out).toContain('OK (1 pages');
});
it('refuses an unhashed <style> or inline <script>', () => {
const root = project({
'dist/index.html': page("script-src 'self'", '<style>a{}</style>', '<script>x()</script>'),
});
const r = run('check-csp.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('unhashedStyle');
expect(r.out).toContain('unhashedScript');
});
it('still sees inline code behind an unusual end tag', () => {
const root = project({
'dist/index.html': page(
"script-src 'self'",
'<STYLE media="all">a{}</style >',
'<script>x()</script foo>',
),
});
const r = run('check-csp.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('unhashedStyle');
expect(r.out).toContain('unhashedScript');
});
it.each(['style="color:red"', "STYLE='color:red'", 'style=color:red'])(
'refuses the style attribute %s',
(attr) => {
const root = project({ 'dist/a.html': page("default-src 'self'", '', `<p ${attr}>x</p>`) });
const r = run('check-csp.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('styleAttr');
},
);
it('lets an empty style attribute through', () => {
const root = project({ 'dist/a.html': page("default-src 'self'", '', '<p style="">x</p>') });
expect(run('check-csp.mjs', root).code).toBe(0);
});
it('fails a page without a policy, and a dist/ without pages', () => {
const missing = project({ 'dist/a.html': `<html><head>${CHARSET}</head></html>` });
expect(run('check-csp.mjs', missing).out).toContain('missingCsp');
const r = run('check-csp.mjs', project({ 'dist/sw.js': '' }));
expect(r.code).toBe(1);
expect(r.out).toContain('found no HTML pages');
});
it('fails when a script precedes the policy, until postbuild moves it first', () => {
const late =
`<!doctype html><html><head>${CHARSET}<script src="/t.js"></script>` +
`${meta("script-src 'self'")}</head><body></body></html>`;
const root = project({ 'dist/index.html': late, 'dist/vi/index.html': late });
expect(run('check-csp.mjs', root).out).toContain('lateCsp');
expect(run('postbuild.mjs', root).out).toContain('moved to the top of <head> on 2 of 2 pages');
const html = readFileSync(join(root, 'dist/index.html'), 'utf8');
expect(html.indexOf(meta("script-src 'self'"))).toBe(html.indexOf(CHARSET) + CHARSET.length);
expect(run('check-csp.mjs', root).code).toBe(0);
// Idempotent: a second pass changes nothing.
expect(run('postbuild.mjs', root).out).toContain('on 0 of 2 pages');
});
});
describe('check-assets', () => {
const html = (head: string): string => page("default-src 'self'", head);
it('passes when every same-origin asset exists', () => {
const root = project({
'dist/index.html': html(
'<script src="/_astro/a.js?v=1"></script><link rel="stylesheet" href="/_astro/a.css">' +
'<link rel="canonical" href="/not-an-asset"><link rel="icon" href="https://x.test/i.png">' +
'<img src="//cdn.test/x.png">',
),
'dist/_astro/a.js': '',
'dist/_astro/a.css': '',
});
const r = run('check-assets.mjs', root);
expect(r.code).toBe(0);
expect(r.out).toContain('OK (1 pages, 2 distinct same-origin assets exist)');
});
it('fails on a missing asset and on a data: script', () => {
const root = project({
'dist/index.html': html(
'<script src="data:text/javascript,1"></script><link rel="stylesheet" href="/gone.css">' +
'<img src="/logo%20x.svg">',
),
});
const r = run('check-assets.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('script is a data: URL');
expect(r.out).toContain('link[stylesheet] /gone.css does not exist');
expect(r.out).toContain('image /logo x.svg does not exist');
});
});
+85
View File
@@ -0,0 +1,85 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* Build guard: dist/rss.xml must be the feed notify.py can trust.
*
* WHY THIS EXISTS. A cross-poster (notify.py) reads /rss.xml on a schedule
* and announces every <guid> it has not seen before — to Telegram, Discord,
* Bluesky, Mastodon, X and Facebook. So the feed's failure modes are public
* and irreversible: a GUID that changes shape (a URL instead of the slug, a
* slug with a different case) re-announces the whole window, and a GUID that
* names no app announces a dead link. src/lib/feed.ts builds the items and is
* unit-tested; this asserts what actually got EMITTED, because @astrojs/rss
* has no guid option and the slug guid is injected through customData
* (src/pages/rss.xml.ts) — exactly the kind of seam a dependency update
* breaks with every test still green.
*
* Checks: 1–50 items; every item has exactly one <guid isPermaLink="false">
* holding a slug of an app in src/data/apps; guids are unique; <link> is
* that app's page; <pubDate> parses and items run newest first.
*/
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
const FEED = join(process.cwd(), 'dist/rss.xml');
const APPS_DIR = join(process.cwd(), 'src/data/apps');
const SITE = 'https://softharbor.net';
const LIMIT = 50;
const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const problems = [];
let items = [];
if (existsSync(FEED)) {
const xml = readFileSync(FEED, 'utf8');
items = [...xml.matchAll(/<item>([\s\S]*?)<\/item>/g)].map((m) => m[1]);
if (items.length === 0) problems.push('the feed has no <item>');
if (items.length > LIMIT) problems.push(`${items.length} items — the window is ${LIMIT}`);
const seen = new Set();
let previous = Infinity;
for (const [i, item] of items.entries()) {
const where = `item ${i + 1}`;
const guids = [...item.matchAll(/<guid\b([^>]*)>([^<]*)<\/guid>/g)];
if (guids.length !== 1) {
problems.push(`${where}: ${guids.length} <guid> elements (want exactly 1)`);
continue;
}
const [, attrs, slug] = guids[0];
if (!/\bisPermaLink="false"/.test(attrs)) {
problems.push(
`${where}: <guid> is not isPermaLink="false" — a URL guid changes with the URL`,
);
}
if (!SLUG_RE.test(slug)) {
problems.push(`${where}: guid "${slug}" is not a slug`);
} else if (!existsSync(join(APPS_DIR, `${slug}.json`))) {
problems.push(`${where}: guid "${slug}" names no app in src/data/apps`);
}
if (seen.has(slug)) problems.push(`${where}: duplicate guid "${slug}"`);
seen.add(slug);
const link = /<link>([^<]*)<\/link>/.exec(item)?.[1];
if (link !== `${SITE}/apps/${slug}`) {
problems.push(`${where}: <link> ${link ?? '(none)'} is not ${SITE}/apps/${slug}`);
}
const when = Date.parse(/<pubDate>([^<]*)<\/pubDate>/.exec(item)?.[1] ?? '');
if (Number.isNaN(when)) problems.push(`${where}: missing or unparseable <pubDate>`);
else if (when > previous) problems.push(`${where}: newer than the item before it`);
else previous = when;
}
} else {
problems.push('dist/rss.xml does not exist — run `astro build` first');
}
if (problems.length > 0) {
console.error(`check-feed — ${problems.length} problem(s):`);
for (const p of problems.slice(0, 20)) console.error(` ✗ ${p}`);
console.error(
'\n notify.py announces every new guid; see docs/05 §A4 before changing the feed.',
);
process.exitCode = 1;
} else {
console.log(`check-feed — OK (${items.length} items, slug guids, newest first)`);
}
+84
View File
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
import { describe, expect, it } from 'vitest';
import { project, run } from './fixture';
const item = (slug: string, date = 'Tue, 28 Jul 2026 00:00:00 GMT', guid?: string) =>
`<item><title>${slug}</title><link>https://softharbor.net/apps/${slug}</link>` +
`${guid ?? `<guid isPermaLink="false">${slug}</guid>`}<pubDate>${date}</pubDate></item>`;
const feed = (...items: string[]) =>
`<?xml version="1.0"?><rss version="2.0"><channel><title>t</title>${items.join('')}</channel></rss>`;
const apps = (...slugs: string[]) =>
Object.fromEntries(slugs.map((s) => [`src/data/apps/${s}.json`, '{}']));
describe('check-feed', () => {
it('passes the shape notify.py relies on', () => {
const root = project({
...apps('gimp', 'vlc'),
'dist/rss.xml': feed(item('vlc', 'Wed, 29 Jul 2026 00:00:00 GMT'), item('gimp')),
});
const r = run('check-feed.mjs', root);
expect(r.code).toBe(0);
expect(r.out).toContain('OK (2 items');
});
it.each([
[
'a URL guid',
item('vlc', undefined, '<guid>https://softharbor.net/apps/vlc</guid>'),
'isPermaLink',
],
['a guid naming no app', item('ghost'), 'names no app'],
['no guid at all', item('vlc', undefined, ''), '0 <guid> elements'],
[
'a capitalised guid',
item('vlc', undefined, '<guid isPermaLink="false">VLC</guid>'),
'is not a slug',
],
['an unparseable date', item('vlc', 'yesterday'), 'unparseable <pubDate>'],
])('fails on %s', (_name, bad, message) => {
const r = run('check-feed.mjs', project({ ...apps('vlc'), 'dist/rss.xml': feed(bad) }));
expect(r.code).toBe(1);
expect(r.out).toContain(message);
});
it('fails on duplicates, older-before-newer, a wrong link and an empty feed', () => {
const dup = run(
'check-feed.mjs',
project({ ...apps('vlc'), 'dist/rss.xml': feed(item('vlc'), item('vlc')) }),
);
expect(dup.out).toContain('duplicate guid "vlc"');
const order = run(
'check-feed.mjs',
project({
...apps('vlc', 'gimp'),
'dist/rss.xml': feed(item('vlc'), item('gimp', 'Wed, 29 Jul 2026 00:00:00 GMT')),
}),
);
expect(order.out).toContain('newer than the item before it');
const link = run(
'check-feed.mjs',
project({
...apps('vlc'),
'dist/rss.xml': feed(item('vlc').replace('/apps/vlc', '/apps/vlc-player')),
}),
);
expect(link.out).toContain('is not https://softharbor.net/apps/vlc');
const empty = run('check-feed.mjs', project({ 'dist/rss.xml': feed() }));
expect(empty.code).toBe(1);
expect(empty.out).toContain('no <item>');
});
it('fails when the window grows past 50', () => {
const slugs = Array.from({ length: 51 }, (_, i) => `app-${i}`);
const r = run(
'check-feed.mjs',
project({ ...apps(...slugs), 'dist/rss.xml': feed(...slugs.map((s) => item(s))) }),
);
expect(r.out).toContain('51 items');
});
});
+56 -19
View File
@@ -15,34 +15,71 @@ import { join } from 'node:path';
const root = join(process.cwd(), 'src/i18n');
const BASE = 'en';
/** Locale dictionaries only — `xx.json` or `xx-YY.json`, never helper files. */
const LOCALE_FILE = /^([a-z]{2}(?:-[A-Z]{2})?)\.json$/;
const PLACEHOLDER = /\{(\w+)\}/g;
/** Dot-flatten so nested objects can never hide a missing leaf. */
/** Plain UTF-16 order — identical to the default sort, but explicit (S2871). */
const byCodeUnit = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
/**
* Dot-flatten so nested objects can never hide a missing leaf. An EMPTY object
* or array is reported as its own key, otherwise `"x": {}` flattens to nothing
* and a locale could carry it unnoticed.
*/
function flatten(value, prefix = '') {
if (value === null || typeof value !== 'object') return [prefix];
return Object.entries(value).flatMap(([k, v]) => flatten(v, prefix ? `${prefix}.${k}` : k));
if (value === null || typeof value !== 'object') return [[prefix, value]];
const entries = Object.entries(value);
if (entries.length === 0) return [[prefix, value]];
return entries.flatMap(([k, v]) => flatten(v, prefix ? `${prefix}.${k}` : k));
}
const keysFor = (lang) =>
new Set(flatten(JSON.parse(readFileSync(join(root, `${lang}.json`), 'utf8'))));
const locales = readdirSync(root)
.filter((f) => f.endsWith('.json'))
.map((f) => f.replace(/\.json$/, ''));
const baseKeys = keysFor(BASE);
const errors = [];
function load(lang) {
const file = join(root, `${lang}.json`);
// Windows editors like to prepend a UTF-8 BOM, which JSON.parse rejects
// with a stack trace instead of a readable gate failure.
const text = readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
try {
return new Map(flatten(JSON.parse(text)));
} catch (err) {
errors.push(`${lang}.json → not valid JSON (${err.message})`);
return new Map();
}
}
const placeholders = (s) =>
typeof s === 'string' ? [...s.matchAll(PLACEHOLDER)].map((m) => m[1]).sort(byCodeUnit) : [];
const locales = readdirSync(root)
.map((f) => LOCALE_FILE.exec(f)?.[1])
.filter(Boolean);
const dicts = new Map(locales.map((lang) => [lang, load(lang)]));
const base = dicts.get(BASE) ?? new Map();
for (const lang of locales.filter((l) => l !== BASE)) {
const langKeys = keysFor(lang);
for (const k of baseKeys) if (!langKeys.has(k)) errors.push(`${lang}.json → missing "${k}"`);
for (const k of langKeys) if (!baseKeys.has(k)) errors.push(`${lang}.json → extra "${k}"`);
const dict = dicts.get(lang);
for (const [k, v] of base) {
if (!dict.has(k)) {
errors.push(`${lang}.json → missing "${k}"`);
continue;
}
// `t()` substitutes {name} placeholders (src/i18n/index.ts); a translation
// that drops or renames one renders the literal braces to the visitor.
const want = placeholders(v).join(',');
const got = placeholders(dict.get(k)).join(',');
if (want !== got) errors.push(`${lang}.json → "${k}" placeholders {${got}} ≠ en {${want}}`);
}
for (const k of dict.keys()) if (!base.has(k)) errors.push(`${lang}.json → extra "${k}"`);
}
// Alphabetical order is a review aid, not cosmetics: it keeps diffs of a
// 200-key dictionary readable (docs/07 §3).
for (const lang of locales) {
const keys = [...keysFor(lang)];
const sorted = [...keys].sort();
// large dictionary readable (docs/07 §3).
for (const [lang, dict] of dicts) {
const keys = [...dict.keys()];
const sorted = [...keys].sort(byCodeUnit);
const at = keys.findIndex((k, i) => k !== sorted[i]);
if (at !== -1) errors.push(`${lang}.json → keys not alphabetised (first: "${keys[at]}")`);
}
@@ -52,5 +89,5 @@ if (errors.length > 0) {
for (const e of errors) console.error(` ✗ ${e}`);
process.exitCode = 1;
} else {
console.log(`i18n:check — OK (${baseKeys.size} keys × ${locales.length} locales)`);
console.log(`i18n:check — OK (${base.size} keys × ${locales.length} locales)`);
}
+64
View File
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
import { describe, expect, it } from 'vitest';
import { project, run } from './fixture';
const BOM = String.fromCharCode(0xfeff);
const dicts = (en: unknown, vi: unknown): Record<string, string> => ({
'src/i18n/en.json': JSON.stringify(en),
'src/i18n/vi.json': JSON.stringify(vi),
});
describe('check-i18n-parity', () => {
it('passes when every locale mirrors English, nested keys included', () => {
const root = project(dicts({ a: 'A', b: { c: 'C {n}' } }, { a: 'Á', b: { c: 'Cê {n}' } }));
const r = run('check-i18n-parity.mjs', root);
expect(r.code).toBe(0);
expect(r.out).toContain('OK (2 keys × 2 locales)');
});
it('reports missing and extra keys', () => {
const root = project(dicts({ a: 'A', b: 'B' }, { a: 'A', z: 'Z' }));
const r = run('check-i18n-parity.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('vi.json → missing "b"');
expect(r.out).toContain('vi.json → extra "z"');
});
it('reports an empty object as its own key instead of flattening it away', () => {
const root = project(dicts({ a: 'A', x: {} }, { a: 'A' }));
expect(run('check-i18n-parity.mjs', root).out).toContain('vi.json → missing "x"');
});
it('catches a translation that drops or renames a {placeholder}', () => {
const root = project(dicts({ n: '{count} apps' }, { n: '{total} ứng dụng' }));
const r = run('check-i18n-parity.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('"n" placeholders {total} ≠ en {count}');
});
it('requires alphabetised keys', () => {
const root = project(dicts({ b: 'B', a: 'A' }, { a: 'A', b: 'B' }));
expect(run('check-i18n-parity.mjs', root).out).toContain(
'en.json → keys not alphabetised (first: "b")',
);
});
it('accepts a UTF-8 BOM and reports broken JSON without a stack trace', () => {
const root = project({
'src/i18n/en.json': `${BOM}{"a":"A"}`,
'src/i18n/vi.json': '{"a": ',
});
const r = run('check-i18n-parity.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('vi.json → not valid JSON');
expect(r.out).not.toContain('en.json → not valid JSON');
expect(r.out).not.toMatch(/^\s+at /m);
});
it('ignores helper files that are not locale dictionaries', () => {
const root = project({ ...dicts({ a: 'A' }, { a: 'A' }), 'src/i18n/index.json': '{}' });
expect(run('check-i18n-parity.mjs', root).out).toContain('× 2 locales');
});
});
-140
View File
@@ -1,140 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* Build guard: no inline `style` attributes may reach dist/ (docs/09 §4).
*
* WHY THIS EXISTS. CSP `style-src` governs inline style ATTRIBUTES, not just
* <style> blocks, and hashes do not apply to attributes — only
* 'unsafe-hashes' or 'unsafe-inline' would permit them. Our policy has
* neither, so any `style="…"` is silently DROPPED by the browser. Nothing
* errors: the build passes, the markup looks right in source, and the page
* renders with the declaration missing.
*
* That is exactly how the sticky header shipped transparent and let content
* bleed through it (2026-07-28). A visual bug from an invisible cause is worth
* a permanent check, so this runs in CI beside the other gates.
*
* Fix for a failure: use a Tailwind utility. Every design token is exposed as
* one (`text-sh-muted`, `bg-sh-surface`, `border-sh-border`) in
* src/styles/global.css.
*/
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
const DIST = join(process.cwd(), 'dist');
const CSP_META = /<meta http-equiv="content-security-policy" content="([^"]+)"/i;
const STYLE_EL = /<style[^>]*>([\s\S]*?)<\/style>/gi;
const sha256 = (s) => `sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}`;
function walk(dir) {
const out = [];
for (const entry of readdirSync(dir)) {
const p = join(dir, entry);
if (statSync(p).isDirectory()) out.push(...walk(p));
else if (p.endsWith('.html')) out.push(p);
}
return out;
}
const offenders = [];
/** `<style>` elements whose hash is absent from their own page's CSP. */
const unhashed = [];
/** hash -> a page that emits it; and every page's allowed set, for the
* cross-page check below. */
const emittedBy = new Map();
const allowedBy = new Map();
for (const file of walk(DIST)) {
const html = readFileSync(file, 'utf8');
for (const m of html.matchAll(/<[^>]*\sstyle="([^"]*)"[^>]*>/g)) {
// An empty style="" is harmless noise from a framework; a declaration is not.
if (m[1].trim() === '') continue;
offenders.push({ file: relative(process.cwd(), file), decl: m[1].slice(0, 70) });
}
// The attribute sweep above misses a whole second category: a `<style>`
// ELEMENT whose content Astro forgot to hash. `transition:name` shipped
// exactly that — 1.5 MB of CSS the browser refused on every page, with all
// eight gates green, because nothing compared the emitted styles against the
// policy that governs them.
const csp = CSP_META.exec(html)?.[1];
if (!csp) continue;
const rel = relative(process.cwd(), file);
allowedBy.set(rel, new Set(csp.match(/'sha256-[^']+'/g)?.map((h) => h.slice(1, -1)) ?? []));
for (const m of html.matchAll(STYLE_EL)) {
const hash = sha256(m[1]);
if (!emittedBy.has(hash)) emittedBy.set(hash, { file: rel, head: m[1].slice(0, 70) });
if (!csp.includes(hash)) unhashed.push({ file: rel, hash, head: m[1].slice(0, 70) });
}
}
// A meta CSP is applied when the document PARSES. `<ClientRouter />` swaps
// without reparsing, so the policy in force stays the one from the page the
// visitor started on. A style that only some pages carry is therefore refused
// on arrival from any page that lacked it — invisible to the per-page check
// above, because on a hard load that page allows its own style just fine.
//
// `/apps` hit this: it alone carried ShAppCard's scoped CSS, so soft-navigating
// there from a detail page silently dropped the stretched-link `::after` (the
// whole-card click target) and unhid `.sr-only` text.
const universal = [...emittedBy.keys()].filter((h) =>
[...allowedBy.values()].every((s) => s.has(h)),
);
const pageSpecific = [...emittedBy.keys()].filter((h) => !universal.includes(h));
if (offenders.length > 0) {
console.error(
`check-no-inline-styles — ${offenders.length} inline style attribute(s) in dist:\n`,
);
const seen = new Set();
for (const o of offenders) {
const key = o.decl;
if (seen.has(key)) continue;
seen.add(key);
console.error(` ✗ ${o.file}\n style="${o.decl}"`);
}
console.error('\n CSP style-src drops these silently. Use a Tailwind utility instead');
console.error(' — the design tokens are exposed as one in src/styles/global.css.');
process.exitCode = 1;
}
if (unhashed.length > 0) {
console.error(`check-no-inline-styles — ${unhashed.length} <style> element(s) the page's own`);
console.error('CSP does not allow. The browser refuses these; the build never notices:\n');
const seen = new Set();
for (const u of unhashed) {
if (seen.has(u.hash)) continue;
seen.add(u.hash);
console.error(` ✗ ${u.file}\n ${u.hash}\n ${JSON.stringify(u.head)}`);
}
console.error(`\n ${unhashed.length} occurrence(s), ${seen.size} distinct.`);
console.error(' Astro hashes the styles it knows about; anything it misses must either be');
console.error(' removed or added via security.csp.styleDirective.hashes (docs/09 §4).');
process.exitCode = 1;
}
if (pageSpecific.length > 0) {
console.error(
`check-no-inline-styles — ${pageSpecific.length} <style> element(s) that only SOME`,
);
console.error("pages allow. A ClientRouter swap keeps the origin page's policy, so arriving");
console.error('at the page carrying these from a page without them gets them refused:\n');
for (const hash of pageSpecific) {
const { file, head } = emittedBy.get(hash) ?? {};
const short = [...allowedBy].filter(([, s]) => !s.has(hash)).length;
console.error(` ✗ ${file}\n ${hash}\n ${JSON.stringify(head)}`);
console.error(` refused when arriving from ${short} of ${allowedBy.size} pages`);
}
console.error("\n Emit the CSS as an external stylesheet instead — style-src 'self' covers it");
console.error(" on every page with no hash at all (build.inlineStylesheets: 'never').");
process.exitCode = 1;
}
if (offenders.length === 0 && unhashed.length === 0 && pageSpecific.length === 0) {
console.log(
`check-no-inline-styles — OK (no style attributes; ${universal.length} <style> hash(es), ` +
`allowed on all ${allowedBy.size} pages)`,
);
}
+47 -7
View File
@@ -65,17 +65,54 @@ if (!existsSync(SW)) {
);
}
if (!urls.some((u) => u.endsWith('.woff2'))) {
problems.push('no fonts precached — the offline shell would render unstyled');
problems.push('no fonts precached — the offline shell would render in fallback fonts only');
}
// (5) Everything the offline page itself loads must be precached, or it
// renders broken exactly when it is shown. Checking the fonts alone missed
// this for months: with inlineStylesheets 'never', /offline linked CSS the
// SW never cached, so the fallback page was unstyled.
const offlineFile = join(process.cwd(), 'dist/offline.html');
if (existsSync(offlineFile)) {
const offline = readFileSync(offlineFile, 'utf8');
const needs = [
...[...offline.matchAll(/<link\b[^>]*rel="stylesheet"[^>]*href="\/([^"]+)"/g)].map(
(m) => m[1],
),
...[...offline.matchAll(/<script\b[^>]*\ssrc="\/(_astro\/[^"]+)"/g)].map((m) => m[1]),
];
for (const asset of needs) {
if (!urls.includes(asset)) {
problems.push(`/offline loads /${asset} but the SW does not precache it`);
}
}
} else {
problems.push('dist/offline.html does not exist');
}
// (6) An updated SW must take over without waiting for every tab to close:
// registerSW.js never posts SKIP_WAITING (workbox.skipWaiting).
if (!sw.includes('skipWaiting')) {
problems.push('the SW does not call skipWaiting() — fixes would wait for every tab to close');
}
}
// (1) The registration script must be referenced by a page, or the SW is dead
// code no matter how correct it is.
// code no matter how correct it is. (7) Same for the manifest: emitted but
// unlinked means "not installable", silently.
const home = join(process.cwd(), 'dist/index.html');
if (existsSync(home) && !readFileSync(home, 'utf8').includes('registerSW.js')) {
problems.push(
"registerSW.js is not referenced from dist/index.html — set injectRegister: 'script'",
);
if (!existsSync(home)) {
problems.push('dist/index.html does not exist — run `astro build` first');
} else {
const html = readFileSync(home, 'utf8');
if (!html.includes('registerSW.js')) {
problems.push(
"registerSW.js is not referenced from dist/index.html — set injectRegister: 'script'",
);
}
if (!html.includes('rel="manifest"')) {
problems.push('dist/index.html does not link the web app manifest');
}
}
if (problems.length > 0) {
@@ -84,5 +121,8 @@ if (problems.length > 0) {
console.error('\n Every one of these fails silently at build time. See docs/08 Part D.');
process.exitCode = 1;
} else {
console.log('check-service-worker — OK (no navigation fallback, offline path precached)');
console.log(
'check-service-worker — OK (no navigation fallback; /offline and everything it loads ' +
'precached; skipWaiting; manifest linked)',
);
}
+75
View File
@@ -0,0 +1,75 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
import { describe, expect, it } from 'vitest';
import { project, run } from './fixture';
const GOOD_SW =
'precacheAndRoute([{url:"offline.html"},{url:"_astro/f.woff2"},{url:"_astro/a.css"},' +
'{url:"_astro/theme.js"}]);new NetworkOnly();handlerDidError("/offline");self.skipWaiting();';
const OFFLINE =
'<link rel="stylesheet" href="/_astro/a.css"><script src="/_astro/theme.js"></script>';
const HOME = '<script defer src="/registerSW.js"></script><link rel="manifest" href="/m.json">';
const dist = (over: Record<string, string> = {}): Record<string, string> => ({
'dist/sw.js': GOOD_SW,
'dist/offline.html': OFFLINE,
'dist/index.html': HOME,
...over,
});
describe('check-service-worker', () => {
it('passes the shape docs/08 Part D describes', () => {
const r = run('check-service-worker.mjs', project(dist()));
expect(r.code).toBe(0);
expect(r.out).toContain('check-service-worker — OK');
});
it.each([
{
name: 'a navigation fallback',
over: { 'dist/sw.js': `${GOOD_SW}new NavigationRoute(h)` },
message: 'NavigationRoute is registered',
},
{
name: 'an unstyled offline page',
over: { 'dist/sw.js': GOOD_SW.replace('{url:"_astro/a.css"},', '') },
message: '/offline loads /_astro/a.css but the SW does not precache it',
},
{
name: 'no precached fonts',
over: { 'dist/sw.js': GOOD_SW.replace('{url:"_astro/f.woff2"},', '') },
message: 'no fonts precached',
},
{
name: 'no skipWaiting',
over: { 'dist/sw.js': GOOD_SW.replace('self.skipWaiting();', '') },
message: 'does not call skipWaiting',
},
{
name: 'no NetworkOnly navigation route',
over: { 'dist/sw.js': GOOD_SW.replace('NetworkOnly', 'CacheFirst') },
message: 'no NetworkOnly navigation route',
},
{
name: 'an unlinked manifest',
over: { 'dist/index.html': '<script src="/registerSW.js"></script>' },
message: 'does not link the web app manifest',
},
{
name: 'an unregistered service worker',
over: { 'dist/index.html': '<link rel="manifest" href="/m.json">' },
message: 'registerSW.js is not referenced',
},
])('fails on $name', ({ over, message }) => {
const r = run('check-service-worker.mjs', project(dist(over)));
expect(r.code).toBe(1);
expect(r.out).toContain(message);
});
it('fails when there is no service worker at all', () => {
const r = run('check-service-worker.mjs', project({ 'dist/index.html': HOME }));
expect(r.code).toBe(1);
expect(r.out).toContain('dist/sw.js does not exist');
});
});
+31 -21
View File
@@ -5,43 +5,53 @@
* (docs/12 §5). L3 of the validation stack.
*
* node scripts/extract-urls.mjs → all entries (weekly sweep)
* node scripts/extract-urls.mjs --changed → only files changed vs origin/main
* git diff --name-only … | node scripts/extract-urls.mjs --changed
* → only the files named on stdin
*
* The --changed mode keeps PR feedback fast; the weekly job owns the full run.
*
* The changed-file list arrives on stdin rather than from a `git diff` spawned
* here. Spawning `git` meant resolving it through PATH (SonarCloud S4036), and
* the old catch-all fallback turned ANY git failure into a silent full sweep of
* ~1 150 URLs. The workflow now runs git itself under `set -euo pipefail`, so a
* broken diff fails loudly where it happens.
*/
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { basename, join } from 'node:path';
const APPS_DIR = join(process.cwd(), 'src/data/apps');
const changedOnly = process.argv.includes('--changed');
/** Plain UTF-16 order — identical to the default sort, but explicit (S2871). */
const byCodeUnit = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
let files = existsSync(APPS_DIR) ? readdirSync(APPS_DIR).filter((f) => f.endsWith('.json')) : [];
if (changedOnly) {
try {
const diff = execSync('git diff --name-only origin/main...HEAD -- src/data/apps', {
encoding: 'utf8',
});
const changed = new Set(
diff
.split('\n')
.map((l) => l.trim().split('/').pop())
.filter(Boolean),
);
files = files.filter((f) => changed.has(f));
} catch {
// No origin/main (fresh clone, detached CI checkout): fall back to the
// full set rather than silently checking nothing.
console.error('extract-urls: could not diff against origin/main, using all entries');
}
const changed = new Set(
readFileSync(0, 'utf8')
.split('\n')
.map((l) => l.trim())
.filter(Boolean)
.map((p) => basename(p)),
);
files = files.filter((f) => changed.has(f));
}
const urls = new Set();
for (const file of files) {
const app = JSON.parse(readFileSync(join(APPS_DIR, file), 'utf8'));
let app;
try {
app = JSON.parse(readFileSync(join(APPS_DIR, file), 'utf8'));
} catch (err) {
// validate:data reports malformed JSON with context; here it must not
// abort the whole sweep, but it must not pass unnoticed either.
console.error(`extract-urls: skipping ${file} (${err.message})`);
process.exitCode = 1;
continue;
}
for (const v of Object.values(app.links ?? {})) if (v) urls.add(v);
if (app.security?.evidence) urls.add(app.security.evidence);
}
for (const u of [...urls].sort()) console.log(u);
for (const u of [...urls].sort(byCodeUnit)) console.log(u);
+58
View File
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// Test kit for the build scripts. Every script resolves its inputs from
// process.cwd() (dist/, src/i18n/, src/data/…), so a test writes a throwaway
// project tree and runs the REAL script in it as a child process — the same
// way `pnpm build` and CI invoke it, exit code and all.
import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { onTestFinished } from 'vitest';
const SCRIPTS = dirname(fileURLToPath(import.meta.url));
/** A temporary project root holding `files` (path → contents), removed after the test. */
export function project(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), 'sh-script-'));
onTestFinished(() => {
rmSync(root, { recursive: true, force: true });
});
write(root, files);
return root;
}
export function write(root: string, files: Record<string, string>): void {
for (const [path, contents] of Object.entries(files)) {
mkdirSync(dirname(join(root, path)), { recursive: true });
writeFileSync(join(root, path), contents);
}
}
export interface Run {
code: number | null;
stdout: string;
/** stdout + stderr, for assertions that do not care which stream. */
out: string;
}
export function run(
script: string,
root: string,
opts: { args?: string[]; input?: string; env?: Record<string, string> } = {},
): Run {
// Never inherit GITHUB_OUTPUT: under Actions, quarantine.mjs would append to
// the CI job's real output file.
const env = { ...process.env };
Reflect.deleteProperty(env, 'GITHUB_OUTPUT');
const r = spawnSync(process.execPath, [join(SCRIPTS, script), ...(opts.args ?? [])], {
cwd: root,
input: opts.input ?? '',
encoding: 'utf8',
env: { ...env, ...opts.env },
});
return { code: r.status, stdout: r.stdout, out: r.stdout + r.stderr };
}
+106
View File
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* Generates the raster icons from one vector mark: `pnpm icons`.
*
* The mark is the anchor SoftHarbor has always used ("a safe berth after a
* reinstall", docs/00 D1), now on a fixed harbour-blue tile. The previous
* favicon drew the anchor in `currentColor`, which renders BLACK in a browser
* tab or launcher (there is no CSS context there) — invisible on dark tab
* strips — and it was also the only, unsafe, "maskable" PWA icon.
*
* Output is committed (public/), so builds never depend on this script or on
* sharp's native binary; re-run it only when the mark changes.
*
* public/favicon.svg tab icon (vector, rounded tile)
* public/favicon.ico 16/32/48 px, for clients that ask for /favicon.ico
* public/apple-touch-icon.png 180 px, full-bleed (iOS applies its own mask)
* public/icons/icon-192.png PWA "any"
* public/icons/icon-512.png PWA "any"
* public/icons/maskable-512.png PWA "maskable": full-bleed, mark inside the 80 % safe zone
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import sharp from 'sharp';
const OUT = join(process.cwd(), 'public');
const DEEP = '#0B4F7A';
const LIGHT = '#1C93B8';
/** The anchor, drawn on a 32-unit grid centred at (16, 16). */
const ANCHOR = `
<circle cx="16" cy="8.5" r="2.6" />
<path d="M16 11.1v13.4" />
<path d="M10.5 15h11" />
<path d="M7.5 18.5a8.5 8.5 0 0 0 17 0" />`;
/**
* @param {{ rounded: boolean, scale: number }} opts
* rounded — rounded tile on transparency (tab/"any") vs full-bleed square;
* scale — anchor size relative to the tile (maskable keeps it in the safe zone).
*/
function mark({ rounded, scale }) {
const offset = 16 - 16 * scale;
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<defs>
<linearGradient id="sh-tile" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="${LIGHT}" />
<stop offset="1" stop-color="${DEEP}" />
</linearGradient>
</defs>
<rect width="32" height="32" ${rounded ? 'rx="7"' : ''} fill="url(#sh-tile)" />
<g fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"
transform="translate(${offset} ${offset}) scale(${scale})">${ANCHOR}
</g>
</svg>
`;
}
const png = (svg, size) =>
sharp(Buffer.from(svg), { density: 72 * (size / 32) * 2 })
.resize(size, size)
.png({ compressionLevel: 9 })
.toBuffer();
/** Minimal ICO container: a directory of PNG-encoded images (Vista+). */
function ico(images) {
const header = Buffer.alloc(6);
header.writeUInt16LE(0, 0); // reserved
header.writeUInt16LE(1, 2); // type: icon
header.writeUInt16LE(images.length, 4);
const entries = [];
let offset = 6 + 16 * images.length;
for (const { size, data } of images) {
const e = Buffer.alloc(16);
e.writeUInt8(size >= 256 ? 0 : size, 0);
e.writeUInt8(size >= 256 ? 0 : size, 1);
e.writeUInt8(0, 2); // palette
e.writeUInt8(0, 3); // reserved
e.writeUInt16LE(1, 4); // colour planes
e.writeUInt16LE(32, 6); // bits per pixel
e.writeUInt32LE(data.length, 8);
e.writeUInt32LE(offset, 12);
offset += data.length;
entries.push(e);
}
return Buffer.concat([header, ...entries, ...images.map((i) => i.data)]);
}
const tile = mark({ rounded: true, scale: 1 });
const bleed = mark({ rounded: false, scale: 1 });
const maskable = mark({ rounded: false, scale: 0.72 });
mkdirSync(join(OUT, 'icons'), { recursive: true });
writeFileSync(join(OUT, 'favicon.svg'), tile);
writeFileSync(join(OUT, 'icons/icon-192.png'), await png(tile, 192));
writeFileSync(join(OUT, 'icons/icon-512.png'), await png(tile, 512));
writeFileSync(join(OUT, 'icons/maskable-512.png'), await png(maskable, 512));
writeFileSync(join(OUT, 'apple-touch-icon.png'), await png(bleed, 180));
writeFileSync(
join(OUT, 'favicon.ico'),
ico(await Promise.all([16, 32, 48].map(async (size) => ({ size, data: await png(tile, size) })))),
);
console.log(
'icons — wrote favicon.svg, favicon.ico, apple-touch-icon.png, icons/{icon-192,icon-512,maskable-512}.png',
);
+52
View File
@@ -0,0 +1,52 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* Post-build HTML fix-ups. Runs between `astro build` and the dist/ checks.
*
* 1. Move the CSP <meta> to the top of <head>.
*
* A meta-tag CSP only governs what the parser meets AFTER it. Astro appends
* its generated tag at the END of <head>, behind every blocking and
* deferred script there (errors.js, theme.js, registerSW.js) — so those
* loaded under no policy at all. They are our own same-origin files and
* would pass `script-src 'self'` anyway; the point is that NOTHING in the
* document should precede the policy that is supposed to cover it. Placing
* the tag right after `<meta charset>` (which must stay first, within the
* first 1024 bytes) makes the whole head subject to it. check-csp.mjs
* asserts the result on every page.
*
* Idempotent: a page whose meta already follows the charset is left alone.
*/
import { readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
const DIST = join(process.cwd(), 'dist');
const CHARSET = '<meta charset="utf-8">';
const CSP_META = /<meta http-equiv="content-security-policy" content="[^"]*">/i;
function walk(dir) {
const out = [];
for (const entry of readdirSync(dir)) {
const p = join(dir, entry);
if (statSync(p).isDirectory()) out.push(...walk(p));
else if (p.endsWith('.html')) out.push(p);
}
return out;
}
let moved = 0;
let pages = 0;
for (const file of walk(DIST)) {
pages++;
const html = readFileSync(file, 'utf8');
const meta = CSP_META.exec(html)?.[0];
const at = html.indexOf(CHARSET);
if (!meta || at === -1) continue; // check-csp.mjs reports both cases
if (html.indexOf(meta) === at + CHARSET.length) continue;
const without = html.replace(meta, '');
const insertAt = without.indexOf(CHARSET) + CHARSET.length;
writeFileSync(file, without.slice(0, insertAt) + meta + without.slice(insertAt));
moved++;
}
console.log(`postbuild — CSP meta moved to the top of <head> on ${moved} of ${pages} pages`);
+21 -5
View File
@@ -9,11 +9,18 @@
* rendering on the next build.
*
* MOVE, never delete: the file keeps its schema so restoring is a plain
* `git mv` plus a status edit, and the reason lives in the tracking issue and
* the commit message. History is the audit trail.
* move back plus a status edit, and the reason lives in the tracking issue and
* the commit message. History is the audit trail. (A plain filesystem rename;
* git records it as a rename when the move is committed.)
*
* Idempotent; exits 0 when there is nothing to do. Writes the moved slugs to
* the `moved` GitHub output so the workflow can open a PR and one issue each.
* Two callers:
* - a maintainer, locally: set `security.status` to "flagged", run
* `pnpm quarantine`, commit both the flag and the move in one PR — the
* `gates` check (validate:data) rejects a flagged entry left in place;
* - .github/workflows/quarantine.yml, nightly and on data pushes, as the
* safety net. It reads the moved slugs from the `moved` GitHub output.
*
* Idempotent; exits 0 when there is nothing to do.
*/
import {
appendFileSync,
@@ -28,6 +35,7 @@ import { join } from 'node:path';
const APPS_DIR = join(process.cwd(), 'src/data/apps');
const QUARANTINE_DIR = join(process.cwd(), 'data/quarantine');
const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const moved = [];
if (existsSync(APPS_DIR)) {
@@ -49,8 +57,16 @@ if (existsSync(APPS_DIR)) {
console.error(`quarantine: ${file} already in quarantine — leaving both for review`);
continue;
}
const slug = file.replace(/\.json$/, '');
// The slug reaches a workflow output, a commit message and an issue title;
// anything that is not a plain kebab-case slug is left for a human.
if (!SLUG_RE.test(slug)) {
console.error(`quarantine: refusing to move ${file} — not a valid slug`);
process.exitCode = 1;
continue;
}
renameSync(path, dest);
moved.push(file.replace(/\.json$/, ''));
moved.push(slug);
console.log(`quarantine: moved ${file} → data/quarantine/`);
}
}
+89
View File
@@ -0,0 +1,89 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// quarantine.mjs (hard rule 5: move, never delete) and extract-urls.mjs (the
// lychee feed) — the two scripts the scheduled workflows run.
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { project, run } from './fixture';
const entry = (status: string, links: Record<string, string | null> = {}, evidence?: string) =>
JSON.stringify({ name: 'X', links, security: { status, evidence } });
describe('quarantine', () => {
it('moves flagged entries out of the content tree and reports them to the workflow', () => {
const root = project({
'src/data/apps/bad-app.json': entry('flagged'),
'src/data/apps/good-app.json': entry('clean'),
'src/data/apps/broken.json': '{ nope',
});
const r = run('quarantine.mjs', root, { env: { GITHUB_OUTPUT: join(root, 'out.txt') } });
expect(r.code).toBe(0);
expect(r.out).toContain('moved bad-app.json → data/quarantine/');
expect(r.out).toContain('skipping unparseable broken.json');
expect(existsSync(join(root, 'src/data/apps/bad-app.json'))).toBe(false);
expect(readFileSync(join(root, 'data/quarantine/bad-app.json'), 'utf8')).toBe(entry('flagged'));
expect(existsSync(join(root, 'src/data/apps/good-app.json'))).toBe(true);
expect(readFileSync(join(root, 'out.txt'), 'utf8')).toBe('moved=bad-app\n');
});
it('is idempotent, and reports an empty move list', () => {
const root = project({ 'src/data/apps/good-app.json': entry('clean') });
const r = run('quarantine.mjs', root, { env: { GITHUB_OUTPUT: join(root, 'out.txt') } });
expect(r.out).toContain('nothing flagged');
expect(readFileSync(join(root, 'out.txt'), 'utf8')).toBe('moved=\n');
});
it('never overwrites a quarantined file, and never moves a malformed slug', () => {
const root = project({
'src/data/apps/twice.json': entry('flagged'),
'data/quarantine/twice.json': entry('flagged', { homepage: 'https://old.test/' }),
'src/data/apps/Not A Slug.json': entry('flagged'),
});
const r = run('quarantine.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('twice.json already in quarantine — leaving both for review');
expect(r.out).toContain('refusing to move Not A Slug.json');
expect(existsSync(join(root, 'src/data/apps/twice.json'))).toBe(true);
expect(readFileSync(join(root, 'data/quarantine/twice.json'), 'utf8')).toContain('old.test');
});
});
describe('extract-urls', () => {
const apps = {
'src/data/apps/a.json': entry(
'clean',
{ homepage: 'https://b.test/', repo: null },
'https://vt.test/a',
),
'src/data/apps/b.json': entry('clean', {
homepage: 'https://a.test/',
download: 'https://b.test/',
}),
};
it('prints every official URL once, sorted', () => {
const r = run('extract-urls.mjs', project(apps));
expect(r.code).toBe(0);
expect(r.stdout).toBe('https://a.test/\nhttps://b.test/\nhttps://vt.test/a\n');
});
it('limits itself to the files named on stdin with --changed', () => {
const r = run('extract-urls.mjs', project(apps), {
args: ['--changed'],
input: 'src/data/apps/b.json\nREADME.md\n',
});
expect(r.stdout).toBe('https://a.test/\nhttps://b.test/\n');
});
it('keeps going past a malformed file, but fails the run', () => {
const root = project({ ...apps, 'src/data/apps/c.json': '{' });
const r = run('extract-urls.mjs', root);
expect(r.code).toBe(1);
expect(r.out).toContain('skipping c.json');
expect(r.stdout).toContain('https://vt.test/a');
});
});
+127 -27
View File
@@ -2,11 +2,12 @@
// Copyright (C) 2026 poli0981 (SkullMute)
/**
* L2 data validation (docs/03 §2). Catches what the Zod schema structurally
* cannot: rules that span files, or that involve the filename, or the
* filesystem.
* cannot: rules that span files, involve the filename or the filesystem, or
* judge a URL's provenance rather than its syntax.
*
* Plain Node — runs OUTSIDE Astro, so it must never import astro:content.
* Prints `file → rule → detail` and exits non-zero.
* Prints `file → rule → detail` and exits non-zero on any error. Warnings
* (staleness) are printed but do not fail the build.
*/
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
@@ -18,34 +19,100 @@ const CATEGORIES = join(process.cwd(), 'src/data/categories.json');
const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
const SLUG_MAX = 40;
/** Workers Static Assets caps a deploy; warn well before it (docs/08 A5). */
const FILE_WARN_THRESHOLD = 15_000;
/** docs/13 §6 — a security check older than this is due for a re-check. */
const STALE_DAYS = 180;
const TODAY = new Date().toISOString().slice(0, 10);
/**
* Download portals and mirror sites (CONTRIBUTING: "official links only").
* They repackage installers, bundle adware, or simply are not the developer.
* Matched on the host and its subdomains.
*/
const PORTALS = [
'softpedia.com',
'filehorse.com',
'uptodown.com',
'download.cnet.com',
'majorgeeks.com',
'filehippo.com',
'softonic.com',
'fosshub.com',
'techspot.com',
'malavida.com',
'chip.de',
'portableapps.com',
'apkmirror.com',
'getintopc.com',
];
/** Analytics and affiliate parameters have no place in an "official" link. */
const TRACKING_PARAM =
/^(utm_[a-z]+|fbclid|gclid|dclid|msclkid|mc_eid|ref|aff|affiliate|partner)$/i;
/** Zero-width and bidi-control characters: invisible, and a classic spoofing tool. */
const INVISIBLE = /[\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]/;
const errors = [];
const warnings = [];
const fail = (file, rule, detail) => errors.push({ file, rule, detail });
const warn = (file, rule, detail) => warnings.push({ file, rule, detail });
/** Same fold as src/lib/normalize.ts — duplicated only because this script
* runs in plain Node and must not import from src/ (kept in sync by test). */
/** Same fold as src/lib/normalize.ts — duplicated because this script runs in
* plain Node and must not import from src/. Only used for duplicate names. */
const normalizeViet = (s) =>
s
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[\u0300-\u036f]/g, '')
.replace(/đ/g, 'd')
.replace(/Đ/g, 'D')
.toLowerCase()
.replace(/\s+/g, ' ')
.trim();
const daysBetween = (a, b) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
/** Every string value in an entry, with its JSON path, for character checks. */
function* strings(value, path = '') {
if (typeof value === 'string') {
yield [path, value];
} else if (Array.isArray(value)) {
for (const [i, v] of value.entries()) yield* strings(v, `${path}[${i}]`);
} else if (value && typeof value === 'object') {
for (const [k, v] of Object.entries(value)) yield* strings(v, path ? `${path}.${k}` : k);
}
}
function checkUrl(file, field, raw) {
let url;
try {
url = new URL(raw);
} catch {
fail(file, 'bad-url', `${field} = ${raw}`);
return;
}
if (url.protocol !== 'https:') fail(file, 'insecure-link', `${field} = ${raw}`);
if (url.hostname.split('.').some((label) => label.startsWith('xn--'))) {
fail(
file,
'punycode-host',
`${field} uses an IDN host (${url.hostname}) — check for a lookalike`,
);
}
const host = url.hostname.replace(/^www\./, '');
const portal = PORTALS.find((p) => host === p || host.endsWith(`.${p}`));
if (portal) fail(file, 'download-portal', `${field} points at ${portal}, not the developer`);
for (const key of url.searchParams.keys()) {
if (TRACKING_PARAM.test(key)) fail(file, 'tracking-param', `${field} carries ?${key}=`);
}
}
const categoryIds = new Set(JSON.parse(readFileSync(CATEGORIES, 'utf8')).map((c) => c.id));
const logoFiles = existsSync(LOGOS_DIR) ? new Set(readdirSync(LOGOS_DIR)) : new Set();
const files = existsSync(APPS_DIR) ? readdirSync(APPS_DIR).filter((f) => f.endsWith('.json')) : [];
const seenSlug = new Map();
const seenName = new Map();
const slugs = new Set();
for (const file of files) {
const slug = file.replace(/\.json$/, '');
slugs.add(slug);
let app;
try {
app = JSON.parse(readFileSync(join(APPS_DIR, file), 'utf8'));
@@ -55,18 +122,18 @@ for (const file of files) {
}
// Zod never sees the filename, but the filename IS the slug — it is the URL
// and the RSS guid (docs/04 §2).
// and the RSS guid (docs/04 §2). (Duplicate slugs cannot happen: filenames
// in one directory are unique — the old check for them could never fire.)
if (!SLUG_RE.test(slug)) fail(file, 'slug-format', `"${slug}" is not kebab-case [a-z0-9-]`);
if (slug.length > SLUG_MAX) fail(file, 'slug-length', `${slug.length} chars, max ${SLUG_MAX}`);
if (seenSlug.has(slug)) fail(file, 'duplicate-slug', `also ${seenSlug.get(slug)}`);
seenSlug.set(slug, file);
// Two entries for the same product, differing only by accent or case, is a
// curation error a human reviewer reliably misses.
if (typeof app.name === 'string') {
const key = normalizeViet(app.name);
if (seenName.has(key))
if (seenName.has(key)) {
fail(file, 'duplicate-name', `"${app.name}" collides with ${seenName.get(key)}`);
}
seenName.set(key, file);
}
@@ -75,24 +142,54 @@ for (const file of files) {
}
for (const [k, v] of Object.entries(app.links ?? {})) {
if (v !== null && !String(v).startsWith('https://'))
fail(file, 'insecure-link', `links.${k} = ${v}`);
if (v !== null) checkUrl(file, `links.${k}`, String(v));
}
if (app.security?.evidence) checkUrl(file, 'security.evidence', app.security.evidence);
for (const [path, value] of strings(app)) {
if (INVISIBLE.test(value)) {
fail(file, 'invisible-char', `${path} contains a zero-width or bidi control character`);
}
}
// Hard rule 5: a flagged entry must be in data/quarantine/, never here.
// `pnpm quarantine` moves it; the PR then carries both the flag and the move.
if (app.security?.status === 'flagged') {
fail(file, 'flagged-in-main-tree', 'move to data/quarantine/ (docs/03 §5)');
fail(
file,
'flagged-in-main-tree',
'run `pnpm quarantine` to move it to data/quarantine/ (docs/03 §5)',
);
}
// A local: logo that does not exist fails the build far away from the cause.
// A local: logo that does not exist fails the build far away from the
// cause. Compared against the directory listing, not existsSync, because
// Windows' case-insensitive filesystem would accept a wrong-case name that
// Linux CI and Workers Builds then reject.
const local = /^local:(.+)$/.exec(app.logo ?? '');
if (local && !existsSync(join(LOGOS_DIR, local[1]))) {
fail(file, 'missing-logo', `src/assets/logos/${local[1]} not found`);
if (local && !logoFiles.has(local[1])) {
fail(file, 'missing-logo', `src/assets/logos/${local[1]} not found (names are case-sensitive)`);
}
for (const field of ['addedAt', 'updatedAt']) {
if (app[field] && app[field] > TODAY) {
fail(file, 'future-date', `${field} ${app[field]} is after today`);
}
}
if (app.security?.checkedAt && app.security.checkedAt > TODAY) {
fail(file, 'future-date', `security.checkedAt ${app.security.checkedAt} is after today`);
}
if (app.updatedAt && app.addedAt && app.updatedAt < app.addedAt) {
fail(file, 'date-order', `updatedAt ${app.updatedAt} precedes addedAt ${app.addedAt}`);
}
// "No known warnings as of <date>" is only honest while <date> is recent.
if (app.security?.checkedAt) {
const age = daysBetween(app.security.checkedAt, TODAY);
if (age > STALE_DAYS) {
warn(file, 'stale-check', `security checked ${age} days ago — re-verify (docs/13 §6)`);
}
}
}
// Quarantined entries must keep status flagged, or restoring them silently
@@ -108,7 +205,7 @@ if (existsSync(QUARANTINE_DIR)) {
`status is "${q.security?.status}"`,
);
}
if (seenSlug.has(file.replace(/\.json$/, ''))) {
if (slugs.has(file.replace(/\.json$/, ''))) {
fail(`data/quarantine/${file}`, 'slug-in-both-trees', 'same slug is live and quarantined');
}
} catch (e) {
@@ -117,17 +214,20 @@ if (existsSync(QUARANTINE_DIR)) {
}
}
if (files.length > FILE_WARN_THRESHOLD) {
warnings.push(`${files.length} app files — approaching the Workers per-deploy cap (docs/08 A5)`);
if (warnings.length > 0) {
// Grouped: 326 identical "stale" lines on the same day would help nobody.
for (const [rule, list] of Map.groupBy(warnings, (w) => w.rule)) {
const plural = list.length === 1 ? 'entry' : 'entries';
console.warn(` ! ${rule}: ${list.length} ${plural} — e.g. ${list[0].file}: ${list[0].detail}`);
}
}
for (const w of warnings) console.warn(` ! ${w}`);
if (errors.length > 0) {
console.error(`validate:data — ${errors.length} problem(s):\n`);
const w = Math.max(...errors.map((e) => e.file.length));
for (const e of errors)
for (const e of errors) {
console.error(` ✗ ${e.file.padEnd(w)} ${e.rule.padEnd(22)} ${e.detail}`);
}
process.exitCode = 1;
} else {
console.log(`validate:data — OK (${files.length} apps, ${categoryIds.size} categories)`);
+128
View File
@@ -0,0 +1,128 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// The L2 rules (docs/03 §2) — the ones the Zod schema cannot express — each
// proven to fire, plus the clean case proven NOT to.
import { describe, expect, it } from 'vitest';
import { project, run } from './fixture';
const day = (offset: number): string =>
new Date(Date.now() + offset * 86_400_000).toISOString().slice(0, 10);
const TODAY = day(0);
const ZWSP = String.fromCharCode(0x200b);
type App = Record<string, unknown>;
const app = (over: App = {}): App => ({
name: 'Firefox',
categories: ['browser'],
links: { homepage: 'https://www.firefox.com/', repo: null },
logo: 'simple-icons:firefox',
addedAt: TODAY,
updatedAt: TODAY,
summary: { en: 'A browser.', vi: 'Trình duyệt.' },
security: {
status: 'clean',
checkedAt: TODAY,
evidence: 'https://www.virustotal.com/gui/url/abc',
},
...over,
});
/** A project with categories.json and the given apps (slug → entry, or raw text). */
function data(apps: Record<string, App | string>, extra: Record<string, string> = {}): string {
const files: Record<string, string> = {
'src/data/categories.json': JSON.stringify([{ id: 'browser' }, { id: 'security-privacy' }]),
...extra,
};
for (const [slug, entry] of Object.entries(apps)) {
files[`src/data/apps/${slug}.json`] = typeof entry === 'string' ? entry : JSON.stringify(entry);
}
return project(files);
}
const validate = (root: string) => run('validate-data.mjs', root);
describe('validate-data', () => {
it('passes a clean dataset', () => {
const r = validate(data({ firefox: app(), 'tor-browser': app({ name: 'Tor Browser' }) }));
expect(r.code).toBe(0);
expect(r.out).toContain('validate:data — OK (2 apps, 2 categories)');
});
it.each([
{ rule: 'slug-format', apps: { Fire_Fox: app() } },
{ rule: 'slug-length', apps: { [`a${'-b'.repeat(20)}`]: app() } },
{ rule: 'parse', apps: { firefox: '{ not json' } },
{ rule: 'duplicate-name', apps: { firefox: app(), 'firefox-2': app({ name: 'FÍREFOX ' }) } },
{ rule: 'unknown-category', apps: { firefox: app({ categories: ['browsers'] }) } },
{ rule: 'bad-url', apps: { firefox: app({ links: { homepage: 'firefox.com' } }) } },
{ rule: 'insecure-link', apps: { firefox: app({ links: { homepage: 'http://x.org/' } }) } },
{
rule: 'punycode-host',
apps: { firefox: app({ links: { homepage: 'https://xn--80ak6aa92e.com/' } }) },
},
{
rule: 'download-portal',
apps: { firefox: app({ links: { download: 'https://en.softonic.com/firefox' } }) },
},
{
rule: 'tracking-param',
apps: { firefox: app({ links: { homepage: 'https://www.firefox.com/?utm_source=x' } }) },
},
{
rule: 'invisible-char',
apps: { firefox: app({ summary: { en: `A${ZWSP}browser.`, vi: 'Trình duyệt.' } }) },
},
{
rule: 'flagged-in-main-tree',
apps: { firefox: app({ security: { status: 'flagged', checkedAt: TODAY } }) },
},
{ rule: 'future-date', apps: { firefox: app({ addedAt: day(3), updatedAt: day(3) }) } },
{ rule: 'date-order', apps: { firefox: app({ addedAt: TODAY, updatedAt: day(-1) }) } },
])('fails $rule', ({ rule, apps }) => {
const r = validate(data(apps));
expect(r.code).toBe(1);
expect(r.out).toContain(rule);
});
it('checks the evidence link like any other', () => {
const security = { status: 'clean', checkedAt: TODAY, evidence: 'http://vt.test/x' };
expect(validate(data({ firefox: app({ security }) })).out).toContain(
'insecure-link security.evidence',
);
});
it('compares local logos case-sensitively, as Linux CI and Workers Builds do', () => {
const extra = { 'src/assets/logos/Firefox.svg': '<svg/>' };
const wrongCase = validate(data({ firefox: app({ logo: 'local:firefox.svg' }) }, extra));
expect(wrongCase.code).toBe(1);
expect(wrongCase.out).toContain('missing-logo');
expect(validate(data({ firefox: app({ logo: 'local:Firefox.svg' }) }, extra)).code).toBe(0);
});
it('warns, without failing, when a security check is due', () => {
const security = { status: 'clean', checkedAt: day(-200), evidence: 'https://vt.test/x' };
const r = validate(data({ firefox: app({ addedAt: day(-300), security }) }));
expect(r.code).toBe(0);
expect(r.out).toMatch(
/stale-check: 1 entry — e\.g\. firefox\.json: security checked 20\d days ago/,
);
});
it('keeps quarantine honest: flagged only, and never live at the same time', () => {
const flagged = JSON.stringify(app({ security: { status: 'flagged', checkedAt: TODAY } }));
const ok = validate(
data({ other: app({ name: 'Other' }) }, { 'data/quarantine/firefox.json': flagged }),
);
expect(ok.code).toBe(0);
const restored = JSON.stringify(app());
const unflagged = validate(data({}, { 'data/quarantine/firefox.json': restored }));
expect(unflagged.out).toContain('unflagged-in-quarantine');
const both = validate(data({ firefox: app() }, { 'data/quarantine/firefox.json': flagged }));
expect(both.code).toBe(1);
expect(both.out).toContain('slug-in-both-trees');
});
});
+79 -64
View File
@@ -1,17 +1,34 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/06 §6 — card anatomy.
import type { CollectionEntry } from 'astro:content';
// docs/06 §6 — card anatomy: logo tile, name and developer, the price in its
// own colour, licence and platforms, two lines of summary, then the dated
// status and the categories along a ruled foot.
import { getCollection, type CollectionEntry } from 'astro:content';
import ShIcon from './ShIcon.astro';
import { logoSvg } from '../lib/logo';
import { localePath, t, type Locale } from '../i18n';
interface Props {
app: CollectionEntry<'apps'>;
locale: Locale;
/**
* Card titles sit directly under the page's h1 on /apps and category pages
* (h2); a card listed inside an h2 section uses 3. Hard-coded h3 used to skip
* a level on every grid page.
*/
headingLevel?: 2 | 3;
}
const { app, locale } = Astro.props;
const { app, locale, headingLevel = 2 } = Astro.props;
const d = app.data;
const Heading = headingLevel === 3 ? 'h3' : 'h2';
// Chips show the category's NAME in the page's language (they used to print
// the raw id, e.g. "security-privacy", on Vietnamese pages too). Astro caches
// getCollection per build, so this is not a query per card.
const categoryLabels = new Map(
(await getCollection('categories')).map((c) => [c.id, c.data.label[locale]]),
);
const dateFmt = new Intl.DateTimeFormat(locale === 'vi' ? 'vi-VN' : 'en-GB', {
dateStyle: 'medium',
@@ -21,10 +38,17 @@ const fmt = (iso: string) => dateFmt.format(new Date(`${iso}T00:00:00Z`));
// Each string renders the date field it actually NAMES — the dated-honesty
// claim is the product (hard rule 4, docs/06 §6).
const security =
d.security.status === 'clean'
? `${t(locale, 'card.security.clean')} · ${t(locale, 'card.checked', { date: fmt(d.security.checkedAt) })}`
: `${t(locale, 'card.security.unverified')} · ${t(locale, 'card.listed', { date: fmt(d.addedAt) })}`;
const clean = d.security.status === 'clean';
const security = clean
? `${t(locale, 'card.security.clean')} · ${t(locale, 'card.checked', { date: fmt(d.security.checkedAt) })}`
: `${t(locale, 'card.security.unverified')} · ${t(locale, 'card.listed', { date: fmt(d.addedAt) })}`;
/** Free reads green, free-with-a-paid-tier blue, buy-once amber. */
const priceTone = {
free: 'sh-tone-ok',
'free-onetime': 'sh-tone-accent',
onetime: 'sh-tone-warn',
}[d.pricing];
---
<!--
@@ -38,7 +62,7 @@ const security =
keep working if search is never used.
-->
<article
class="sh-panel sh-lift sh-card relative flex flex-col gap-3 p-5"
class="sh-panel sh-lift sh-anim sh-card relative flex flex-col gap-3 p-5"
data-slug={app.id}
data-categories={d.categories.map((c) => c.id).join(' ')}
data-platforms={d.platforms.join(' ')}
@@ -47,76 +71,67 @@ const security =
data-name={d.name}
>
<div class="flex items-start gap-3">
{
/* Build-time SVG from a vendored icon set, a vendored asset, or a
generated monogram — never user input. The set:html carve-out is
scoped to this file in eslint.config.js. */
}
<Fragment
set:html={logoSvg(d.logo, d.name, {
class: 'mt-0.5 size-10 shrink-0',
'aria-hidden': 'true',
fill: 'currentColor',
})}
/>
<div class="min-w-0">
<h3 class="sh-card-title text-[17px] leading-tight font-semibold">
<a href={localePath(locale, `/apps/${app.id}`)}>{d.name}</a>
</h3>
<p class="text-sh-muted truncate text-[var(--text-small)]">{d.developer}</p>
<span class="sh-tile size-12">
{/* Build-time SVG from a vendored icon set, a vendored asset, or a
generated monogram — never user input. The set:html carve-out is
scoped to this file in eslint.config.js. */}
<Fragment
set:html={logoSvg(d.logo, d.name, {
class: 'size-7 sh-pop',
'aria-hidden': 'true',
fill: 'currentColor',
})}
/>
</span>
<div class="min-w-0 flex-1">
<Heading class="text-[1.0625rem] leading-snug font-semibold">
<a href={localePath(locale, `/apps/${app.id}`)} class="sh-stretch">
{d.name}
</a>
</Heading>
<p class="text-sh-muted truncate text-small">{d.developer}</p>
</div>
<span class:list={['sh-pill shrink-0', priceTone]}>{t(locale, `pricing.${d.pricing}`)}</span>
</div>
<div class="flex flex-wrap items-center gap-2">
<span class="sh-pill">{t(locale, `pricing.${d.pricing}`)}</span>
<p class="text-sh-muted line-clamp-2 text-small">{d.summary[locale]}</p>
<div class="flex flex-wrap items-center gap-x-3 gap-y-1.5">
{d.license && <span class="sh-pill">{d.license}</span>}
<span class="text-sh-muted font-mono text-[var(--text-badge)]">
<span class="text-sh-muted inline-flex items-center gap-1.5 font-mono text-badge">
<ShIcon name="monitor" class="size-3.5" />
{d.platforms.map((p) => t(locale, `platform.${p}`)).join(' · ')}
</span>
</div>
<p class="text-sh-muted line-clamp-2 text-[var(--text-small)]">
{d.summary[locale]}
</p>
<hr class="border-sh-border opacity-35" />
<p class="text-sh-muted font-mono text-[var(--text-badge)]">
{
/* Conditional CLASS, not a conditional style attribute — CSP style-src
drops inline style attributes silently (docs/09 §4). */
}
<span aria-hidden="true" class={d.security.status === 'clean' ? 'text-sh-ok' : 'text-sh-warn'}
>●</span
>
{security}
</p>
<p class="flex flex-wrap gap-2 text-[var(--text-badge)]">
{
d.categories.map((c) => (
<div class="border-sh-border mt-auto flex flex-col gap-2 border-t border-dashed pt-3">
<p class="text-sh-muted flex items-center gap-1.5 font-mono text-badge">
{/* Shape AND colour: a shield with a tick or a question mark, so the
status never rests on colour alone (WCAG 1.4.1). */}
<ShIcon
name={clean ? 'shield-check' : 'shield-question'}
class={`size-4 shrink-0 ${clean ? 'text-sh-ok' : 'text-sh-warn'}`}
/>
{security}
</p>
<p class="flex flex-wrap gap-x-3 gap-y-1 text-badge">
{d.categories.map((c) => (
<a
href={localePath(locale, `/categories/${c.id}`)}
class="sh-chip text-sh-accent hover:underline"
class="text-sh-accent relative z-1 font-medium hover:underline"
>
{c.id}
{categoryLabels.get(c.id) ?? c.id}
</a>
))
}
</p>
))}
</p>
</div>
</article>
<style>
/* The overlay that makes the whole card clickable while keeping exactly one
link in the accessibility tree. */
.sh-card-title a::after {
content: '';
position: absolute;
inset: 0;
}
/* Chips must sit above that overlay to stay independently clickable. */
.sh-chip {
position: relative;
z-index: 1;
/* 326 cards on /apps: let the browser skip layout and paint for the ones
off screen. The intrinsic size keeps the scrollbar honest meanwhile. */
.sh-card {
content-visibility: auto;
contain-intrinsic-size: auto 15rem;
}
</style>
+98 -37
View File
@@ -1,7 +1,9 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/06 §4 — footer. ShBugReport lands in M5 (docs/02 §5).
// docs/06 §4 — footer: the site in one line, then four short columns —
// browse, open data, legal, project.
import ShIcon from './ShIcon.astro';
import ShBugReport from './islands/ShBugReport.svelte';
import { localePath, t, type Locale } from '../i18n';
@@ -9,6 +11,7 @@ interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const REPO = 'https://github.com/poli0981/softharbor';
const legal = [
['/legal/disclaimer', 'footer.legal.disclaimer'],
@@ -27,44 +30,102 @@ const built = new Intl.DateTimeFormat(locale === 'vi' ? 'vi-VN' : 'en-GB', {
}).format(new Date());
---
<footer class="border-sh-border mt-16 border-t-2">
<div
class="mx-auto flex max-w-[1360px] flex-col gap-4 px-4 py-8 md:flex-row md:justify-between md:px-6"
>
<nav aria-label={t(locale, 'footer.legal.heading')} class="flex flex-wrap gap-x-4 gap-y-2">
{
legal.map(([path, key]) => (
<a href={localePath(locale, path)} class="hover:underline">
{t(locale, key)}
</a>
))
}
<footer class="border-sh-border bg-sh-surface mt-24 border-t">
<div class="mx-auto grid max-w-[1360px] grid-cols-2 gap-10 px-4 py-12 md:grid-cols-[1.4fr_repeat(4,1fr)] md:px-6">
<div class="col-span-2 flex flex-col gap-3 md:col-span-1">
<a href={localePath(locale, '/')} class="sh-anim flex w-fit items-center gap-2.5">
<span class="sh-tile bg-sh-accent text-sh-accent-ink size-8 border-transparent">
<ShIcon name="anchor" class="size-[18px]" motion="pop" />
</span>
<span class="font-display text-[1.1875rem] font-semibold">{t(locale, 'site.name')}</span>
</a>
<p class="text-sh-muted max-w-xs text-small">{t(locale, 'site.tagline')}</p>
<p class="sh-eyebrow mt-auto">{t(locale, 'footer.license')}</p>
<p class="sh-eyebrow">{t(locale, 'footer.builtAt', { date: built })}</p>
</div>
<nav aria-labelledby="sh-foot-browse" class="sh-foot">
<h2 id="sh-foot-browse" class="sh-eyebrow">
{t(locale, 'footer.browse')}
</h2>
<a href={localePath(locale, '/apps')}>{t(locale, 'nav.apps')}</a>
<a href={localePath(locale, '/categories')}>{t(locale, 'nav.categories')}</a>
<a href={`${localePath(locale, '/apps')}#search`}>{t(locale, 'search.label')}</a>
</nav>
<div class="text-sh-muted flex flex-col gap-1 md:items-end">
<span class="font-mono text-[var(--text-badge)]">{t(locale, 'footer.license')}</span>
<a
href="https://github.com/poli0981/softharbor"
rel="noopener"
class="font-mono text-[var(--text-badge)] hover:underline"
>
{t(locale, 'footer.github')}
<nav aria-labelledby="sh-foot-data" class="sh-foot">
<h2 id="sh-foot-data" class="sh-eyebrow">
{t(locale, 'footer.data')}
</h2>
<a href="/api/apps.json" class="sh-anim">
<ShIcon name="braces" class="size-4" motion="pop" />
{t(locale, 'footer.api')}
</a>
{
/* client:visible — it lives at the bottom and nothing depends on it
until seen. The ring buffer it reads is filled from /errors.js, which
loads early, so scrolling late does not lose errors (docs/05 §A5). */
}
<span class="font-mono text-[var(--text-badge)]">
<ShBugReport
client:visible
label={t(locale, 'bug.report')}
countLabel={t(locale, 'bug.errorCount')}
/>
</span>
<span class="font-mono text-[var(--text-badge)]">
{t(locale, 'footer.builtAt', { date: built })}
</span>
</div>
<a href="/rss.xml" class="sh-anim">
<ShIcon name="rss" class="size-4" motion="pop" />
{t(locale, 'footer.rss')}
</a>
<a href={`${REPO}/blob/main/LICENSE-DATA.md`} rel="noopener">
CC BY-SA 4.0
</a>
</nav>
<nav aria-labelledby="sh-foot-legal" class="sh-foot">
<h2 id="sh-foot-legal" class="sh-eyebrow">
{t(locale, 'footer.legal.heading')}
</h2>
{legal.map(([path, key]) => (
<a href={localePath(locale, path)}>{t(locale, key)}</a>
))}
</nav>
<nav aria-labelledby="sh-foot-project" class="sh-foot">
<h2 id="sh-foot-project" class="sh-eyebrow">
{t(locale, 'footer.project')}
</h2>
<a href={localePath(locale, '/contact')}>{t(locale, 'footer.contact')}</a>
<a href={REPO} rel="noopener" class="sh-anim">
{t(locale, 'footer.github')}
<ShIcon name="arrow-up-right" class="size-3.5" motion="nudge-diag" />
</a>
<a href={`${REPO}/releases`} rel="noopener" class="sh-anim">
{t(locale, 'footer.releases')}
<ShIcon name="arrow-up-right" class="size-3.5" motion="nudge-diag" />
</a>
{/* client:visible — it lives at the bottom and nothing depends on it
until seen. The ring buffer it reads is filled by errors.js, which
loads first, so scrolling late does not lose errors (docs/05 §A5). */}
<ShBugReport
client:visible
label={t(locale, 'bug.report')}
countLabel={t(locale, 'bug.errorCount')}
/>
</nav>
</div>
</footer>
<style>
.sh-foot {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.55rem;
font-size: var(--text-small);
}
.sh-foot h2 {
font-family: var(--font-mono);
margin-bottom: 0.25rem;
}
.sh-foot :global(a) {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: var(--sh-ink);
text-decoration: none;
text-underline-offset: 0.2em;
}
.sh-foot :global(a:hover) {
color: var(--sh-accent);
text-decoration: underline;
}
</style>
+140 -32
View File
@@ -1,67 +1,175 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/06 §4 — sticky header.
// docs/06 §4 — sticky header: frosted glass over the page, the anchor mark,
// two sections, a search shortcut, then language and display settings.
import ShIcon from './ShIcon.astro';
import ShLangSwitch from './islands/ShLangSwitch.svelte';
import ShThemeToggle from './islands/ShThemeToggle.svelte';
import ShPrefs from './islands/ShPrefs.svelte';
import { localePath, t, type Locale } from '../i18n';
import { canonicalPath } from '../lib/locale';
interface Props {
locale: Locale;
/** The EN/VI pair Base.astro also writes into the hreflang alternates. */
pair: Record<Locale, string>;
}
const { locale } = Astro.props;
const { locale, pair } = Astro.props;
const home = localePath(locale, '/');
// The section the page belongs to, for aria-current on the nav links.
const here = canonicalPath(Astro.url.pathname).replace(/^\/vi(?=\/|$)/, '') || '/';
const section = here.startsWith('/apps')
? 'apps'
: here.startsWith('/categories')
? 'categories'
: null;
const apps = localePath(locale, '/apps');
const themeLabels = {
system: t(locale, 'theme.system'),
light: t(locale, 'theme.light'),
dark: t(locale, 'theme.dark'),
};
const nav = [
{ key: 'apps', href: apps, icon: 'layout-grid', label: t(locale, 'nav.apps') },
{
key: 'categories',
href: localePath(locale, '/categories'),
icon: 'shapes',
label: t(locale, 'nav.categories'),
},
] as const;
---
<header class="bg-sh-bg border-sh-border sticky top-0 z-30 border-b-2">
<div class="mx-auto flex max-w-[1360px] flex-wrap items-center gap-4 px-4 py-3 md:px-6">
<a href={home} class="font-display text-[1.375rem] font-semibold tracking-tight">
{t(locale, 'site.name')}
<header class="sh-glass sticky top-0 z-30">
<div class="mx-auto flex max-w-[1360px] items-center gap-2 px-4 py-2.5 md:gap-4 md:px-6">
<a
href={home}
class="sh-anim group flex items-center gap-2.5 rounded-[var(--radius-btn)] py-1 pr-2"
>
<span class="sh-tile bg-sh-accent text-sh-accent-ink size-9 border-transparent">
<ShIcon name="anchor" class="size-5" motion="pop" />
</span>
<span class="font-display hidden text-[1.3125rem] font-semibold tracking-tight sm:inline">
{t(locale, 'site.name')}
</span>
<span class="sr-only sm:hidden">{t(locale, 'site.name')}</span>
</a>
<nav aria-label={t(locale, 'nav.apps')} class="flex items-center gap-4">
<a href={apps} class="hover:underline">{t(locale, 'nav.apps')}</a>
<a href={localePath(locale, '/categories')} class="hover:underline">
{t(locale, 'nav.categories')}
</a>
<nav aria-label={t(locale, 'nav.main')} class="flex items-center gap-1">
{nav.map((item) => (
<a
href={item.href}
class="sh-nav sh-anim"
aria-current={section === item.key ? 'page' : undefined}
>
<ShIcon name={item.icon} class="hidden size-[18px] sm:block" motion="pop" />
{item.label}
</a>
))}
</nav>
<span class="sh-pill text-sh-muted border-sh-muted ml-auto hidden lg:inline-block">
{t(locale, 'search.hint')}
</span>
{/* A real link, so it works before any island hydrates and with JS off;
ShPrefs/ShSearch add the "/" shortcut on top (docs/06 §9). */}
<a
href={`${apps}#search`}
class="sh-searchlink sh-anim ml-auto hidden items-center gap-2 lg:inline-flex"
>
<ShIcon name="search" class="size-4" motion="pop" />
<span>{t(locale, 'search.label')}</span>
<kbd class="sh-kbd ml-6" aria-hidden="true">
/
</kbd>
</a>
{
/*
{/*
client:idle — both are preferences, not gates: the page is fully usable
before they hydrate, and /theme.js has already applied the right theme
before they hydrate, and theme.js has already applied the right theme
pre-paint (docs/02 §5, docs/05 §A8).
*/
}
<div class="ml-auto flex items-center gap-3 lg:ml-0">
{
/*
*/}
<div class="ml-auto flex items-center gap-2 lg:ml-0">
{/*
The suggestion banner is resolved with t('vi', …) regardless of page
locale — deliberately. It only ever renders to someone whose browser is
Vietnamese while they are on an EN page (docs/07 §2), so addressing them
in English would be exactly backwards. The EN entries for those keys
exist for dictionary parity and are never rendered.
*/
}
*/}
<ShLangSwitch
client:idle
{locale}
{pair}
label={t(locale, 'lang.label')}
suggestText={t('vi', 'lang.suggest.text')}
suggestAccept={t('vi', 'lang.suggest.accept')}
suggestDismiss={t('vi', 'lang.suggest.dismiss')}
/>
<ShThemeToggle client:idle label={t(locale, 'theme.label')} labels={themeLabels} />
<ShPrefs
client:idle
label={t(locale, 'prefs.label')}
themeLabel={t(locale, 'theme.label')}
themes={{
system: t(locale, 'theme.system'),
light: t(locale, 'theme.light'),
dark: t(locale, 'theme.dark'),
}}
scrollbarLabel={t(locale, 'prefs.scrollbar')}
scrollbars={{
auto: t(locale, 'prefs.scrollbar.auto'),
thin: t(locale, 'prefs.scrollbar.thin'),
hidden: t(locale, 'prefs.scrollbar.hidden'),
}}
motionLabel={t(locale, 'prefs.motion')}
motions={{
system: t(locale, 'prefs.motion.system'),
reduce: t(locale, 'prefs.motion.reduce'),
}}
searchHref={`${apps}#search`}
/>
</div>
</div>
</header>
<style>
.sh-nav {
display: inline-flex;
align-items: center;
gap: 0.4rem;
min-height: 2.5rem;
padding: 0 0.7rem;
border-radius: var(--radius-btn);
color: var(--sh-muted);
font-weight: 500;
white-space: nowrap;
text-decoration: none;
transition:
color var(--duration-fast) var(--ease-sh),
background-color var(--duration-fast) var(--ease-sh);
}
.sh-nav:hover {
color: var(--sh-ink);
background: var(--sh-surface-2);
}
/* The current section: ink text over a short accent rule, so it is not
colour alone (WCAG 1.4.1). */
.sh-nav[aria-current='page'] {
color: var(--sh-ink);
box-shadow: inset 0 -2px 0 var(--sh-accent);
border-end-start-radius: 0;
border-end-end-radius: 0;
}
.sh-searchlink {
min-height: 2.5rem;
padding: 0 0.5rem 0 0.75rem;
border: 1px solid var(--sh-control);
border-radius: var(--radius-btn);
background: var(--sh-surface);
color: var(--sh-muted);
font-size: var(--text-small);
text-decoration: none;
transition: border-color var(--duration-fast) var(--ease-sh);
}
.sh-searchlink:hover {
border-color: var(--sh-accent);
color: var(--sh-ink);
}
@media (width < 30rem) {
.sh-nav {
padding: 0 0.5rem;
}
}
</style>
+30
View File
@@ -0,0 +1,30 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// A Lucide icon, inlined at build time (src/lib/icon.ts) — the one place UI
// icons are rendered, so the set:html carve-out (eslint.config.js) covers a
// single component rather than every page. Decorative by default; pass
// `label` when the icon is the only thing naming a control.
//
// `motion` names one of the hover/focus effects in global.css (it reacts to
// the nearest `.sh-anim` ancestor): nudge-x for "go there", nudge-diag for
// "leaves the site", pop for tiles, draw for a stroke-by-stroke redraw.
import { iconSvg } from '../lib/icon';
interface Props {
/** Lucide name without the set prefix, e.g. `arrow-right`. */
name: string;
class?: string;
label?: string;
motion?: 'nudge-x' | 'nudge-diag' | 'pop' | 'draw';
}
const { name, class: cls = 'size-5', label, motion } = Astro.props;
const svg = iconSvg(`lucide:${name}`, {
class: [cls, motion && `sh-${motion}`].filter(Boolean).join(' '),
...(label ? { role: 'img', 'aria-label': label } : { 'aria-hidden': 'true' }),
focusable: 'false',
});
---
<Fragment set:html={svg} />
+24 -9
View File
@@ -8,7 +8,7 @@
// script, so the strict CSP needs no hash for it (docs/09 §4) — confirmed in
// the S1 build.
import type { CollectionEntry } from 'astro:content';
import { localePath, type Locale } from '../i18n';
import { localePath, t, type Locale } from '../i18n';
// `| undefined` is explicit because tsconfig sets exactOptionalPropertyTypes
// (docs/10 §1): there, `foo?: string` means "absent or string", NOT "may be
@@ -33,7 +33,7 @@ if (website) {
nodes.push({
'@context': 'https://schema.org',
'@type': 'WebSite',
name: 'SoftHarbor',
name: t(locale, 'site.name'),
url: abs(localePath(locale, '/')),
inLanguage: locale === 'vi' ? 'vi-VN' : 'en-GB',
});
@@ -65,16 +65,31 @@ if (app) {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: [
{ '@type': 'ListItem', position: 1, name: 'SoftHarbor', item: abs(localePath(locale, '/')) },
{ '@type': 'ListItem', position: 2, name: 'Apps', item: abs(localePath(locale, '/apps')) },
{
'@type': 'ListItem',
position: 1,
name: t(locale, 'site.name'),
item: abs(localePath(locale, '/')),
},
{
'@type': 'ListItem',
position: 2,
name: t(locale, 'nav.apps'),
item: abs(localePath(locale, '/apps')),
},
{ '@type': 'ListItem', position: 3, name: d.name },
],
});
}
---
{
nodes.map((node) => (
<script type="application/ld+json" is:inline set:html={JSON.stringify(node)} />
))
}
{/* `<` is escaped as \u003c: JSON.stringify leaves it alone, so a name or
summary containing `</script>` would end the data block early and inject
markup. CSP would stop an injected script, but not an injected link. */}
{nodes.map((node) => (
<script
type="application/ld+json"
is:inline
set:html={JSON.stringify(node).replace(/</g, '\\u003c')}
/>
))}
+1 -1
View File
@@ -46,7 +46,7 @@
onclick={refresh}
class="hover:underline"
>
{label}{#if count > 0}<span class="ml-1 font-mono text-[var(--text-badge)]"
{label}{#if count > 0}<span class="text-badge ml-1 font-mono"
>({countLabel.replaceAll('{n}', String(count))})</span
>{/if}
</a>
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// ShBugReport — a plain link whose prefilled GitHub URL is built at the last
// moment (hover / focus / click), from the page and the ring buffer as they
// are THEN. Nothing is sent anywhere until the visitor submits on GitHub.
import { flushSync, mount, unmount } from 'svelte';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import ShBugReport from './ShBugReport.svelte';
let app: Record<string, unknown> | undefined;
let link: HTMLAnchorElement;
beforeEach(() => {
document.body.innerHTML = '';
document.documentElement.lang = 'vi';
history.replaceState(null, '', '/vi/apps?q=gimp');
const target = document.createElement('div');
document.body.appendChild(target);
app = mount(ShBugReport, { target, props: { label: 'Báo lỗi', countLabel: '{n} lỗi' } });
flushSync();
link = document.querySelector<HTMLAnchorElement>('[data-testid="sh-bug-report"]')!;
});
afterEach(async () => {
if (app) await unmount(app);
app = undefined;
Reflect.deleteProperty(globalThis, '__shErrors');
});
describe('ShBugReport', () => {
it('is an inert link until the visitor reaches for it', () => {
expect(link.getAttribute('href')).toBe('#');
expect(link.getAttribute('rel')).toBe('noopener');
expect(link.textContent?.trim()).toBe('Báo lỗi');
});
it('prefills the issue form with the page as it is on focus', () => {
link.dispatchEvent(new FocusEvent('focus'));
flushSync();
const url = new URL(link.href);
expect(`${url.origin}${url.pathname}`).toBe(
'https://github.com/poli0981/softharbor/issues/new',
);
expect(url.searchParams.get('template')).toBe('bug_report.yml');
expect(url.searchParams.get('page-url')).toBe(location.href);
expect(url.searchParams.get('environment')).toContain('lang=vi');
expect(url.searchParams.get('console-output')).toBe('(buffer empty)');
});
it('shows how many errors the buffer caught, and sends them along', () => {
(globalThis as Record<string, unknown>)['__shErrors'] = ['[error] a', '[error] b'];
link.dispatchEvent(new MouseEvent('mouseenter'));
flushSync();
expect(link.textContent).toContain('(2 lỗi)');
expect(new URL(link.href).searchParams.get('console-output')).toBe('[error] a\n[error] b');
});
});
+43 -19
View File
@@ -3,6 +3,8 @@
docs/06 §5 — facets. Desktop: side panel; mobile: bottom sheet. Native
<dialog> so focus trapping and Esc come from the platform (docs/06 §9). -->
<script lang="ts">
import { onMount } from 'svelte';
import IconFilter from '~icons/lucide/sliders-horizontal';
// Imported without the `$` prefix — Svelte reserves it, and `$name` below is
// what auto-subscribes to these atoms (see src/lib/stores.ts).
import {
@@ -22,16 +24,21 @@
label: string;
}
interface Props {
/** Button text AND the dialog's accessible name ("Filters"). */
openLabel: string;
closeLabel: string;
clearLabel: string;
/** "Show {n} apps" (plural "other") and "Show {n} app" (plural "one"). */
showLabel: string;
showLabelOne: string;
headings: { categories: string; platforms: string; pricing: string };
options: { categories: Option[]; platforms: Option[]; pricing: Option[] };
}
const { openLabel, closeLabel, clearLabel, showLabel, headings, options }: Props = $props();
const { openLabel, clearLabel, showLabel, showLabelOne, headings, options }: Props = $props();
let dialog: HTMLDialogElement | undefined = $state();
/** Resolved on mount from <html lang>; SSR renders the "other" form. */
let rules: Intl.PluralRules | null = $state(null);
let numbers: Intl.NumberFormat | null = $state(null);
// Re-read on every store change so checkboxes reflect an external clearAll().
const selection = $derived(
@@ -43,26 +50,46 @@
);
const isOn = (facet: Facet, value: string): boolean => selection.has(`${facet}:${value}`);
const groups: Array<{ facet: Facet; heading: string; items: Option[] }> = [
const showText = $derived(
(rules?.select($visibleCount) === 'one' ? showLabelOne : showLabel).replaceAll(
'{n}',
numbers ? numbers.format($visibleCount) : String($visibleCount),
),
);
const groups: Array<{ facet: Facet; heading: string; items: Option[] }> = $derived([
{ facet: 'categories', heading: headings.categories, items: options.categories },
{ facet: 'platforms', heading: headings.platforms, items: options.platforms },
{ facet: 'pricing', heading: headings.pricing, items: options.pricing },
];
]);
onMount(() => {
const lang = document.documentElement.lang || 'en';
rules = new Intl.PluralRules(lang);
numbers = new Intl.NumberFormat(lang);
});
</script>
<button
type="button"
class="bg-sh-surface border-sh-border rounded-[var(--radius-card)] border-2 px-4 py-3"
class="bg-sh-surface border-sh-control shadow-sh-1 inline-flex items-center gap-2 rounded-[var(--radius-card)] border px-4 py-3"
aria-haspopup="dialog"
onclick={() => dialog?.showModal()}
>
<IconFilter aria-hidden="true" class="size-[18px]" />
{openLabel}
{#if $activeFilterCount > 0}
<span class="sh-pill bg-sh-accent text-sh-accent-ink ml-2">{$activeFilterCount}</span>
<span class="sh-pill bg-sh-accent text-sh-accent-ink border-transparent"
>{$activeFilterCount}</span
>
{/if}
</button>
<dialog bind:this={dialog} class="sh-sheet">
<dialog bind:this={dialog} class="sh-sheet" aria-labelledby="sh-filters-title">
<form method="dialog" class="flex h-full flex-col gap-6">
<h2 id="sh-filters-title" class="font-display text-[length:var(--text-h2)] font-semibold">
{openLabel}
</h2>
{#each groups as group (group.facet)}
<fieldset>
<legend class="font-display text-[length:var(--text-h3)] font-semibold">
@@ -84,18 +111,14 @@
{/each}
<footer class="mt-auto flex gap-3 pt-4">
<button
type="button"
class="border-sh-border rounded-[var(--radius-card)] border-2 px-4 py-2"
disabled={!$hasActiveFilters}
onclick={clearAll}>{clearLabel}</button
<button type="button" class="sh-btn" disabled={!$hasActiveFilters} onclick={clearAll}
>{clearLabel}</button
>
<button
type="submit"
class="bg-sh-accent text-sh-accent-ink border-sh-border ml-auto rounded-[var(--radius-card)] border-2 px-4 py-2 font-medium"
aria-label={closeLabel}
>
{showLabel.replaceAll('{n}', String($visibleCount))}
<!-- The visible text IS the accessible name ("Show 42 apps"). It used to
carry aria-label="Close filters", which hid the count from screen
readers and broke WCAG 2.5.3 Label in Name for voice control. -->
<button type="submit" class="sh-btn sh-btn-primary ml-auto">
{showText}
</button>
</footer>
</form>
@@ -108,9 +131,10 @@
max-height: 100dvh;
width: min(24rem, 100vw);
max-width: 100vw;
border: 2px solid var(--sh-border);
border: 1px solid var(--sh-border);
background: var(--sh-surface);
color: var(--sh-ink);
box-shadow: var(--sh-shadow-3);
padding: 1.5rem;
overflow-y: auto;
}
@@ -0,0 +1,121 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// ShFilterSheet — facets in a native <dialog>. Checkboxes and the stores stay
// in step in BOTH directions, and the submit button's text (its accessible
// name) is pluralised and number-formatted in the page language.
import { flushSync, mount, unmount } from 'svelte';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { categories, clearAll, pricing, query, visibleCount } from '../../lib/stores';
import ShFilterSheet from './ShFilterSheet.svelte';
const PROPS = {
openLabel: 'Filters',
clearLabel: 'Clear all',
showLabel: 'Show {n} apps',
showLabelOne: 'Show {n} app',
headings: { categories: 'Category', platforms: 'Platform', pricing: 'Pricing' },
options: {
categories: [
{ value: 'browser', label: 'Browsers' },
{ value: 'office', label: 'Office' },
],
platforms: [{ value: 'linux', label: 'Linux' }],
pricing: [{ value: 'free', label: 'Free' }],
},
};
let app: Record<string, unknown> | undefined;
function start(lang = 'en'): void {
document.documentElement.lang = lang;
const target = document.createElement('div');
document.body.appendChild(target);
app = mount(ShFilterSheet, { target, props: PROPS });
flushSync();
}
const box = (label: string) =>
[...document.querySelectorAll('label')]
.find((l) => l.textContent?.trim() === label)
?.querySelector('input') as HTMLInputElement;
const button = (text: RegExp) =>
[...document.querySelectorAll('button')].find((b) => text.test(b.textContent ?? ''))!;
beforeEach(() => {
document.body.innerHTML = '';
});
afterEach(async () => {
if (app) await unmount(app);
app = undefined;
clearAll();
visibleCount.set(0);
});
describe('ShFilterSheet', () => {
it('opens as a modal dialog named by its heading', () => {
start();
button(/^\s*Filters/).click();
const dialog = document.querySelector('dialog')!;
expect(dialog.open).toBe(true);
const title = document.getElementById(dialog.getAttribute('aria-labelledby')!);
expect(title?.textContent?.trim()).toBe('Filters');
});
it('toggles facets and counts them on the opening button', () => {
start();
box('Browsers').click();
box('Free').click();
flushSync();
expect(categories.get()).toEqual(new Set(['browser']));
expect(pricing.get()).toEqual(new Set(['free']));
expect(button(/^\s*Filters/).textContent).toContain('2');
});
it('"Clear all" is only enabled with something to clear, and clears it everywhere', () => {
start();
const clear = button(/Clear all/);
expect(clear.disabled).toBe(true);
box('Office').click();
query.set('gimp');
flushSync();
expect(clear.disabled).toBe(false);
clear.click();
flushSync();
expect(categories.get().size).toBe(0);
expect(query.get()).toBe('');
expect(box('Office').checked).toBe(false);
});
it('follows the stores when they change from outside', () => {
start();
categories.set(new Set(['office']));
flushSync();
expect(box('Office').checked).toBe(true);
expect(box('Browsers').checked).toBe(false);
});
it('pluralises and formats the count in the page language', () => {
start('en');
visibleCount.set(1);
flushSync();
expect(button(/^\s*Show/).textContent?.trim()).toBe('Show 1 app');
visibleCount.set(1234);
flushSync();
expect(button(/^\s*Show/).textContent?.trim()).toBe('Show 1,234 apps');
});
it('uses the single Vietnamese plural form and Vietnamese digit grouping', () => {
start('vi');
visibleCount.set(1);
flushSync();
expect(button(/^\s*Show/).textContent?.trim()).toBe('Show 1 apps');
visibleCount.set(1234);
flushSync();
expect(button(/^\s*Show/).textContent?.trim()).toBe('Show 1.234 apps');
});
});
Binary file not shown.
+131
View File
@@ -0,0 +1,131 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// ShLangSwitch — EN | VI with the current language marked, links that keep
// the visitor's query and fragment, and the one-time suggestion banner
// (docs/07 §2): VI browser AND an English page AND no stored answer. There is
// never an automatic redirect.
import { flushSync, mount, unmount } from 'svelte';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import ShLangSwitch from './ShLangSwitch.svelte';
const PAIR = { en: '/apps', vi: '/vi/apps' };
const BANNER = {
suggestText: 'Xem SoftHarbor bằng tiếng Việt?',
suggestAccept: 'Chuyển sang tiếng Việt',
suggestDismiss: 'Không, cảm ơn',
};
let app: Record<string, unknown> | undefined;
/** The page's storage, as a Map — `sh:lang` is the only key this island touches. */
let store: Map<string, string>;
function stubStorage(): Map<string, string> {
const map = new Map<string, string>();
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
getItem: (k: string) => map.get(k) ?? null,
setItem: (k: string, v: string) => void map.set(k, v),
},
});
return map;
}
function start(locale: 'en' | 'vi', url = PAIR[locale]): void {
history.replaceState(null, '', url);
const target = document.createElement('div');
document.body.appendChild(target);
app = mount(ShLangSwitch, {
target,
props: { locale, pair: PAIR, label: 'Language', ...BANNER },
});
flushSync();
}
function browserLanguage(lang: string): void {
Object.defineProperty(navigator, 'language', { configurable: true, get: () => lang });
}
const banner = () => document.querySelector('[data-testid="sh-lang-suggest"]');
beforeEach(() => {
document.body.innerHTML = '';
store = stubStorage();
browserLanguage('en-GB');
});
afterEach(async () => {
if (app) await unmount(app);
app = undefined;
Reflect.deleteProperty(navigator, 'language');
Reflect.deleteProperty(globalThis, 'localStorage');
});
describe('ShLangSwitch', () => {
it('marks English current on an English page and links its Vietnamese pair', () => {
start('en');
const current = document.querySelector('[aria-current="true"]')!;
expect(current.getAttribute('lang')).toBe('en');
const link = document.querySelector<HTMLAnchorElement>('[data-testid="sh-lang-vi"]')!;
expect(link.getAttribute('href')).toBe('/vi/apps');
expect(link.getAttribute('hreflang')).toBe('vi');
// The visible code stays in the accessible name; the endonym follows it.
expect(link.textContent).toBe('VI — Tiếng Việt');
});
it('marks Vietnamese current on a Vietnamese page', () => {
start('vi');
expect(document.querySelector('[aria-current="true"]')?.getAttribute('lang')).toBe('vi');
expect(document.querySelector('[data-testid="sh-lang-en"]')?.getAttribute('href')).toBe(
'/apps',
);
});
it('carries the query and fragment across, so a filtered view survives', () => {
start('en', '/apps?q=gimp&platform=linux#search');
expect(document.querySelector('[data-testid="sh-lang-vi"]')?.getAttribute('href')).toBe(
'/vi/apps?q=gimp&platform=linux#search',
);
});
it('suggests Vietnamese once to a Vietnamese browser on an English page', () => {
browserLanguage('vi-VN');
start('en');
expect(banner()?.getAttribute('lang')).toBe('vi');
[...banner()!.querySelectorAll('button')][0]!.click();
flushSync();
expect(banner()).toBeNull();
// Dismissing is an answer too: it is never asked again.
expect(store.get('sh:lang')).toBe('en');
});
it('remembers acceptance', () => {
browserLanguage('vi');
start('en');
banner()!
.querySelector('a')!
.addEventListener('click', (e) => e.preventDefault());
banner()!.querySelector('a')!.click();
expect(store.get('sh:lang')).toBe('vi');
});
it('never suggests on a Vietnamese page, to other languages, or after an answer', () => {
browserLanguage('vi-VN');
start('vi');
expect(banner()).toBeNull();
document.body.innerHTML = '';
store.set('sh:lang', 'en');
start('en');
expect(banner()).toBeNull();
document.body.innerHTML = '';
store.clear();
browserLanguage('fr-FR');
start('en');
expect(banner()).toBeNull();
});
});
+197 -85
View File
@@ -1,9 +1,13 @@
<!-- SPDX-License-Identifier: GPL-3.0-only
Copyright (C) 2026 poli0981 (SkullMute)
docs/14 Part 2 — first-visit legal gate. Spike S4. -->
docs/14 Part 2 — first-visit legal gate; docs/09 §4a — its human check. -->
<script lang="ts">
import { onMount } from 'svelte';
import { acceptLegal, isAccepted, isExempt } from '../../lib/legal';
import { onMount, tick } from 'svelte';
import IconScale from '~icons/lucide/scale';
import IconShield from '~icons/lucide/shield-check';
import { acceptLegal, isAccepted } from '../../lib/legal';
import { isHuman, PASS_TTL_MS, rememberHuman, UNVERIFIED_TTL_MS } from '../../lib/human';
import { runHumanCheck, sitekeyFor } from '../../lib/turnstile';
interface GateStrings {
title: string;
@@ -12,134 +16,242 @@
disclaimer: string;
terms: string;
privacy: string;
/** Joins the last two document links: "and" / "và". */
and: string;
/** Locale-prefixed base of the legal routes, e.g. `/legal` or `/vi/legal`. */
base: string;
/** Step 2 — the human check. */
verifyTitle: string;
verifyBody: string;
/** Shown briefly when the check could not run and the visitor is let through. */
verifySkipped: string;
/** The page language, passed to the widget so it speaks the same one. */
lang: string;
}
interface Props {
/** Locale of the page that first rendered the island (SSR correctness). */
locale?: 'en' | 'vi';
/**
* BOTH locales' strings, resolved server-side from src/i18n.
*
* Passed as a prop rather than importing `t` here on purpose: the gate is
* persisted across navigations and must be able to switch language without
* a reload, but importing the dictionaries would bundle all ~65 keys into
* this island. Props ship only the seven strings it actually renders.
* The page's own locale only. Before v1.1 the gate was `transition:persist`ed
* across <ClientRouter /> swaps and had to carry BOTH locales to follow the
* URL; with plain cross-document navigation every page mounts its own gate,
* so it ships just the strings it renders.
*/
strings: Record<'en' | 'vi', GateStrings>;
strings: GateStrings;
}
const { locale: initialLocale = 'en', strings }: Props = $props();
const { strings }: Props = $props();
/** How long the "check skipped" note stays up before the gate closes. */
const SKIPPED_NOTE_MS = 1500;
let dialogEl: HTMLDialogElement | undefined = $state();
let shouldShow = $state(false);
let verifyHeading: HTMLHeadingElement | undefined = $state();
let widgetEl: HTMLDivElement | undefined = $state();
/**
* Locale is tracked from the URL, not just the prop.
*
* `transition:persist` keeps this island across navigations — including
* /apps → /vi/apps. The prop is only ever the value from the page that
* FIRST rendered it, so a persisted gate would keep showing English copy on
* a Vietnamese page. Re-deriving on every swap is what makes the gate
* bilingual in practice (found in spike S4).
* `legal` — the documents and "I understand and accept" (step 1).
* `verify` — Turnstile, loaded only now that they are accepted (step 2).
* A returning visitor whose check has lapsed (48 h) starts at step 2.
*/
// svelte-ignore state_referenced_locally
// Capturing only the initial value is the intent: this is a seed for the
// first paint, and evaluate() re-derives it from the URL on every swap.
let locale = $state<'en' | 'vi'>(initialLocale);
let step: 'legal' | 'verify' = $state('legal');
let skipped = $state(false);
function localeFromPath(pathname: string): 'en' | 'vi' {
return pathname === '/vi' || pathname.startsWith('/vi/') ? 'vi' : 'en';
}
/** Whether the gate must currently be shown. */
const required = (): boolean => !isAccepted() || !isHuman();
/**
* Re-assert the dialog's state against the CURRENT route.
*
* This runs on mount and after every ClientRouter swap. Both halves matter:
* the route changes under a persisted island (so an exempt page must close
* the gate), and a <dialog> that was in the top layer can come out of a
* document swap with `open` cleared — re-calling showModal() is what makes
* `transition:persist` actually persist the *modal* state, not just the DOM.
*/
function evaluate(): void {
locale = localeFromPath(location.pathname);
shouldShow = !isExempt(location.pathname) && !isAccepted();
if (!dialogEl) return;
if (shouldShow) {
if (!dialogEl.open) dialogEl.showModal();
} else if (dialogEl.open) {
dialogEl.close();
}
// Hook for global shortcuts: `/` must not reach the search box while the
// gate is up (docs/06 §9). Exposed on <body> so non-island code can read it.
document.body.dataset.shGate = shouldShow ? 'open' : 'closed';
function open(): void {
if (dialogEl && !dialogEl.open) dialogEl.showModal();
// Global shortcuts read this: `/` must not reach content behind an
// un-accepted modal (docs/06 §9).
document.body.dataset['shGate'] = 'open';
}
function onCancel(event: Event): void {
// Esc must not dismiss the gate before acceptance (docs/14 Part 2).
if (shouldShow) event.preventDefault();
// `closedby="none"` is the primary guard; this covers browsers without it.
if (required()) event.preventDefault();
}
function onClose(): void {
// Chromium's close-watcher rules only honour preventDefault() on `cancel`
// after a recent user activation, so a dialog opened from onMount can still
// be closed by Esc. If it closed while acceptance is still outstanding,
// put it straight back.
if (required()) queueMicrotask(open);
else document.body.dataset['shGate'] = 'closed';
}
async function verify(): Promise<void> {
step = 'verify';
await tick();
verifyHeading?.focus();
if (!widgetEl) return;
const result = await runHumanCheck(widgetEl, {
sitekey: sitekeyFor(location.hostname),
theme: document.documentElement.dataset['theme'] === 'dark' ? 'dark' : 'light',
language: strings.lang,
});
if (result === 'passed') {
rememberHuman(PASS_TTL_MS);
} else {
// Fail open (docs/09 §4a): a blocked script or an outage never keeps a
// person out. Remembered for an hour only, so it is retried soon.
rememberHuman(UNVERIFIED_TTL_MS);
skipped = true;
await new Promise((r) => setTimeout(r, SKIPPED_NOTE_MS));
}
dialogEl?.close();
}
function onAccept(): void {
acceptLegal();
evaluate();
if (isHuman()) dialogEl?.close();
else void verify();
}
onMount(() => {
evaluate();
document.addEventListener('astro:after-swap', evaluate);
document.addEventListener('astro:page-load', evaluate);
return () => {
document.removeEventListener('astro:after-swap', evaluate);
document.removeEventListener('astro:page-load', evaluate);
};
if (!isAccepted()) {
open();
} else if (!isHuman()) {
open();
void verify();
} else {
document.body.dataset['shGate'] = 'closed';
}
});
const copy = $derived(strings[locale]);
</script>
<!-- No decline button by design: leaving the site is the alternative, and the
copy says so (docs/14 Part 2). -->
copy says so (docs/14 Part 2). Exempt pages (legal documents, error and
offline pages) never render this island at all — see Base.astro. -->
<dialog
bind:this={dialogEl}
closedby="none"
oncancel={onCancel}
onclose={onClose}
aria-labelledby="sh-gate-title"
aria-describedby="sh-gate-body"
data-testid="sh-legal-gate"
data-step={step}
class="sh-gate"
>
<h2 id="sh-gate-title">{copy.title}</h2>
<p>
{copy.body}
<a href="{copy.base}/disclaimer">{copy.disclaimer}</a>,
<a href="{copy.base}/terms">{copy.terms}</a>,
<a href="{copy.base}/privacy">{copy.privacy}</a>.
</p>
<button type="button" onclick={onAccept} data-testid="sh-legal-accept">
{copy.accept}
</button>
{#if step === 'legal'}
<!-- Focus lands on the heading, not on the first link or the accept button:
a screen reader then reads the notice before any control. Autofocus is
the dialog's own focusing step here, not a page-load focus grab. -->
<span class="sh-gate-icon" aria-hidden="true"><IconScale /></span>
<h2 id="sh-gate-title" tabindex="-1" autofocus>{strings.title}</h2>
<p id="sh-gate-body">
{strings.body}
<a href="{strings.base}/disclaimer">{strings.disclaimer}</a>,
<a href="{strings.base}/terms">{strings.terms}</a>
{strings.and}
<a href="{strings.base}/privacy">{strings.privacy}</a>.
</p>
<button type="button" onclick={onAccept} data-testid="sh-legal-accept">
{strings.accept}
</button>
{:else}
<span class="sh-gate-icon" aria-hidden="true"><IconShield /></span>
<h2 id="sh-gate-title" tabindex="-1" bind:this={verifyHeading}>{strings.verifyTitle}</h2>
<!-- A live region: the "skipped" note replaces the explanation in place. -->
<p id="sh-gate-body" role="status" data-testid="sh-gate-status">
{#if skipped}
{strings.verifySkipped}
{:else}
<span class="sh-gate-spinner" aria-hidden="true"></span>
{strings.verifyBody}
<a href="{strings.base}/privacy#turnstile">{strings.privacy}</a>.
{/if}
</p>
<!-- The widget shows itself here only if it needs a click
(interaction-only); most people never see it. -->
<div class="sh-gate-widget" bind:this={widgetEl} data-testid="sh-gate-widget"></div>
{/if}
</dialog>
<style>
dialog {
.sh-gate {
/* Tailwind's preflight zeroes margins globally, which kills the UA
stylesheet's `margin: auto` that centres a modal <dialog>. Without this
the gate renders in the top-left corner. */
stylesheet's `margin: auto` that centres a modal <dialog>. */
margin: auto;
max-width: 32rem;
border: 2px solid var(--sh-border);
border-radius: 10px;
border: 1px solid var(--sh-border);
border-radius: var(--radius-card);
background: var(--sh-surface);
color: var(--sh-ink);
padding: 1.5rem;
box-shadow: var(--sh-shadow-3);
padding: 1.75rem;
}
dialog::backdrop {
background: rgb(0 0 0 / 0.5);
.sh-gate::backdrop {
background: oklch(0.17 0.03 255 / 0.6);
backdrop-filter: blur(3px);
}
.sh-gate-icon {
display: inline-grid;
place-items: center;
inline-size: 2.75rem;
block-size: 2.75rem;
margin-block-end: 0.75rem;
border-radius: var(--radius-tile);
background: var(--sh-accent-soft);
color: var(--sh-accent);
font-size: 1.375rem;
}
h2 {
font-family: var(--font-display);
font-size: var(--text-h3);
font-weight: 600;
margin-bottom: 0.5rem;
outline: none;
}
/* Preflight strips link colour and underline; in running text a link must
not rely on colour alone (WCAG 1.4.1), so the underline comes back. */
a {
color: var(--sh-accent);
text-decoration: underline;
text-underline-offset: 0.15em;
}
button {
margin-top: 1rem;
border: 2px solid var(--sh-border);
border-radius: 999px;
margin-top: 1.25rem;
border: 1px solid var(--sh-accent);
border-radius: var(--radius-btn);
background: var(--sh-accent);
color: var(--sh-accent-ink, #fff);
padding: 0.5rem 1rem;
color: var(--sh-accent-ink);
font-weight: 600;
padding: 0.55rem 1.25rem;
min-height: 44px;
box-shadow: var(--sh-shadow-1);
}
button:hover {
background: color-mix(in oklch, var(--sh-accent) 88%, var(--sh-ink));
}
.sh-gate-widget:not(:empty) {
margin-top: 1rem;
}
.sh-gate-spinner {
display: inline-block;
width: 0.9em;
height: 0.9em;
margin-inline-end: 0.4em;
vertical-align: -0.1em;
border: 2px solid var(--sh-border);
border-top-color: var(--sh-accent);
border-radius: 50%;
animation: sh-gate-spin 0.8s linear infinite;
}
@keyframes sh-gate-spin {
to {
transform: rotate(1turn);
}
}
/* Phones: a bottom sheet is reachable with one thumb and does not cover
the content it is asking about. */
@media (width < 40rem) {
.sh-gate {
margin: auto 0 0;
width: 100%;
max-width: none;
border-radius: var(--radius-card) var(--radius-card) 0 0;
}
}
</style>
+182 -116
View File
@@ -1,53 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// Spike S4 — docs/11 §3, docs/14 Part 2.
// docs/11 §3, docs/14 Part 2, docs/09 §4a.
//
// Drives the real component through Svelte's mount() in happy-dom. Covers the
// interaction contract (blocks pre-accept, Esc intercepted, exemptions, no
// re-flash across a simulated ClientRouter swap). Real top-layer stacking and
// "no visual flash" are NOT covered here — see the manual note in docs/11 §3.
// interaction contract: blocks before acceptance, Esc cannot dismiss it, a
// premature close is undone, acceptance persists, the copy is the
// dictionary's — and the human check: Turnstile only AFTER acceptance, a pass
// remembered for 48 h, a failure that lets the visitor through anyway. The
// check itself (src/lib/turnstile.ts) is stubbed here and tested on its own.
// Real top-layer stacking, the native `closedby` behaviour and "no visual
// flash" need a real browser — they are covered by e2e/gate.spec.ts.
//
// Route exemptions are not the island's job: exempt pages (legal documents,
// error and offline pages) never render it (Base.astro `gateExempt`).
import { flushSync, mount, unmount } from 'svelte';
import { afterEach, beforeEach, describe, expect, it, vi as vitestVi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PASS_TTL_MS, UNVERIFIED_TTL_MS } from '../../lib/human';
import { LEGAL_VERSION } from '../../lib/legal';
import { runHumanCheck, type HumanResult } from '../../lib/turnstile';
import ShLegalGate from './ShLegalGate.svelte';
import en from '../../i18n/en.json';
import vi from '../../i18n/vi.json';
import viDict from '../../i18n/vi.json';
vi.mock('../../lib/turnstile', () => ({
runHumanCheck: vi.fn(),
sitekeyFor: () => 'test-sitekey',
}));
/**
* Real dictionary strings, so these tests break if a gate key is renamed or
* dropped — the point of moving the copy out of the island in M4.
* dropped — the point of keeping the copy out of the island.
*/
const STRINGS = {
en: {
title: en['gate.title'],
body: en['gate.body'],
accept: en['gate.accept'],
disclaimer: en['gate.link.disclaimer'],
terms: en['gate.link.terms'],
privacy: en['gate.link.privacy'],
base: '/legal',
},
vi: {
title: vi['gate.title'],
body: vi['gate.body'],
accept: vi['gate.accept'],
disclaimer: vi['gate.link.disclaimer'],
terms: vi['gate.link.terms'],
privacy: vi['gate.link.privacy'],
base: '/vi/legal',
},
};
const strings = (d: typeof en, base: string, lang: string) => ({
title: d['gate.title'],
body: d['gate.body'],
accept: d['gate.accept'],
disclaimer: d['gate.link.disclaimer'],
terms: d['gate.link.terms'],
privacy: d['gate.link.privacy'],
and: d['gate.and'],
base,
verifyTitle: d['gate.verify.title'],
verifyBody: d['gate.verify.body'],
verifySkipped: d['gate.verify.skipped'],
lang,
});
const STRINGS = { en: strings(en, '/legal', 'en'), vi: strings(viDict, '/vi/legal', 'vi') };
/** mount() schedules effects in a microtask; flush so assertions see onMount. */
function mountGate(target: HTMLElement) {
const instance = mount(ShLegalGate, { target, props: { strings: STRINGS } });
function mountGate(target: HTMLElement, locale: 'en' | 'vi' = 'en') {
const instance = mount(ShLegalGate, { target, props: { strings: STRINGS[locale] } });
flushSync();
return instance;
}
function stubStorage(seed?: string) {
function stubStorage(seed: { legal?: string; humanUntil?: number } = {}) {
const map = new Map<string, string>();
if (seed !== undefined) map.set('sh:legal', seed);
if (seed.legal !== undefined) map.set('sh:legal', seed.legal);
if (seed.humanUntil !== undefined) map.set('sh:human', String(seed.humanUntil));
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
@@ -58,16 +69,18 @@ function stubStorage(seed?: string) {
return map;
}
function goto(pathname: string) {
// happy-dom allows navigation via history without a real load.
history.replaceState({}, '', pathname);
/** The human check's answer, held until the test releases it. */
function pendingCheck() {
let answer: (r: HumanResult) => void = () => undefined;
vi.mocked(runHumanCheck).mockReturnValue(new Promise((r) => (answer = r)));
return (r: HumanResult) => answer(r);
}
/** Simulate what ClientRouter does to a `transition:persist`ed island. */
function clientRouterSwapTo(pathname: string) {
goto(pathname);
document.dispatchEvent(new Event('astro:after-swap'));
}
/** Lets queued microtasks (the gate's re-open, the check's promise) run. */
const settle = async () => {
for (let i = 0; i < 5; i++) await new Promise<void>((r) => queueMicrotask(r));
flushSync();
};
let target: HTMLElement;
let app: Record<string, unknown> | undefined;
@@ -75,33 +88,42 @@ let app: Record<string, unknown> | undefined;
const gate = () => document.querySelector<HTMLDialogElement>('[data-testid="sh-legal-gate"]')!;
const acceptBtn = () =>
document.querySelector<HTMLButtonElement>('[data-testid="sh-legal-accept"]')!;
const human = () => Date.now() + PASS_TTL_MS - 1000;
beforeEach(() => {
document.body.innerHTML = '';
delete document.body.dataset['shGate'];
document.documentElement.dataset['theme'] = 'dark';
target = document.createElement('div');
document.body.appendChild(target);
});
afterEach(() => {
if (app) unmount(app);
afterEach(async () => {
if (app) await unmount(app);
app = undefined;
vi.useRealTimers();
vi.clearAllMocks();
Reflect.deleteProperty(globalThis, 'localStorage');
Reflect.deleteProperty(globalThis, '__shLegalAcceptedThisSession');
vitestVi.resetModules();
Reflect.deleteProperty(globalThis, '__shHumanUntil');
});
describe('ShLegalGate — blocks before acceptance', () => {
it('opens modally on a gated route for a first-time visitor', () => {
it('opens modally for a first-time visitor', () => {
stubStorage();
goto('/apps');
app = mountGate(target);
expect(gate().open).toBe(true);
expect(document.body.dataset['shGate']).toBe('open');
});
it('declares closedby="none" so the platform offers no dismissal', () => {
stubStorage();
app = mountGate(target);
expect(gate().getAttribute('closedby')).toBe('none');
});
it('intercepts Esc — the cancel event is prevented pre-accept', () => {
stubStorage();
goto('/apps');
app = mountGate(target);
const cancel = new Event('cancel', { cancelable: true });
gate().dispatchEvent(cancel);
@@ -109,107 +131,151 @@ describe('ShLegalGate — blocks before acceptance', () => {
expect(gate().open).toBe(true);
});
it('closes and persists on accept', () => {
it('re-opens itself if something closes it before acceptance', async () => {
// Chromium can close a modal dialog on Esc despite preventDefault() when
// there was no recent user activation. The close handler must undo that.
stubStorage();
app = mountGate(target);
gate().close();
await settle();
expect(gate().open).toBe(true);
expect(document.body.dataset['shGate']).toBe('open');
});
it('never loads Turnstile before the documents are accepted', () => {
stubStorage();
app = mountGate(target);
expect(runHumanCheck).not.toHaveBeenCalled();
expect(gate().dataset['step']).toBe('legal');
});
});
describe('ShLegalGate — acceptance and the human check', () => {
it('accept → checks → closes, remembering both for their own lifetimes', async () => {
const store = stubStorage();
goto('/apps');
const answer = pendingCheck();
app = mountGate(target);
acceptBtn().click();
flushSync();
await settle();
expect(store.get('sh:legal')).toBe(LEGAL_VERSION);
expect(gate().dataset['step']).toBe('verify');
expect(gate().open).toBe(true);
expect(runHumanCheck).toHaveBeenCalledWith(
document.querySelector('[data-testid="sh-gate-widget"]'),
{ sitekey: 'test-sitekey', theme: 'dark', language: 'en' },
);
// The step-2 heading takes focus, so a screen reader hears what is happening.
expect(document.activeElement?.id).toBe('sh-gate-title');
answer('passed');
await settle();
expect(gate().open).toBe(false);
expect(document.body.dataset['shGate']).toBe('closed');
expect(store.get('sh:legal')).toBeDefined();
});
});
describe('ShLegalGate — exemptions (docs/14 Part 2)', () => {
it('never opens on a legal page, even unaccepted — the gate links there', () => {
stubStorage();
goto('/legal/disclaimer');
app = mountGate(target);
expect(gate().open).toBe(false);
const until = Number(store.get('sh:human'));
expect(until - Date.now()).toBeGreaterThan(PASS_TTL_MS - 5000);
});
it('never opens on /offline — an error state must not dead-lock', () => {
it('cannot be dismissed while the check runs', async () => {
stubStorage();
goto('/offline');
app = mountGate(target);
expect(gate().open).toBe(false);
});
});
describe('ShLegalGate — across ClientRouter navigations (the S4 question)', () => {
it('does NOT re-flash after acceptance', () => {
stubStorage();
goto('/');
pendingCheck();
app = mountGate(target);
acceptBtn().click();
flushSync();
expect(gate().open).toBe(false);
clientRouterSwapTo('/apps');
flushSync();
expect(gate().open).toBe(false);
clientRouterSwapTo('/apps/7-zip');
flushSync();
expect(gate().open).toBe(false);
});
it('re-asserts the modal if a swap leaves the persisted dialog closed', () => {
stubStorage();
goto('/');
app = mountGate(target);
expect(gate().open).toBe(true);
// Reproduce the hazard S4 exists to catch: a persisted <dialog> coming out
// of a document swap with `open` cleared. Without the re-assert in
// evaluate(), the site would be usable without accepting.
await settle();
const cancel = new Event('cancel', { cancelable: true });
gate().dispatchEvent(cancel);
expect(cancel.defaultPrevented).toBe(true);
gate().close();
clientRouterSwapTo('/apps');
flushSync();
await settle();
expect(gate().open).toBe(true);
});
it('closes when navigating from a gated route ONTO an exempt one', () => {
stubStorage();
goto('/apps');
app = mountGate(target);
expect(gate().open).toBe(true);
it('lets the visitor through when the check cannot run, and says so briefly', async () => {
vi.useFakeTimers();
const store = stubStorage();
const answer = pendingCheck();
app = mountGate(target, 'vi');
acceptBtn().click();
await settle();
answer('unverified');
await settle();
clientRouterSwapTo('/legal/terms');
const status = document.querySelector('[data-testid="sh-gate-status"]')!;
expect(status.getAttribute('role')).toBe('status');
expect(status.textContent?.trim()).toBe(viDict['gate.verify.skipped']);
expect(gate().open).toBe(true);
const until = Number(store.get('sh:human'));
expect(until - Date.now()).toBeLessThanOrEqual(UNVERIFIED_TTL_MS);
await vi.advanceTimersByTimeAsync(1500);
flushSync();
expect(gate().open).toBe(false);
});
it('re-opens when navigating back off an exempt route unaccepted', () => {
stubStorage();
goto('/legal/terms');
it('skips straight to the check for a returning visitor whose check lapsed', async () => {
stubStorage({ legal: LEGAL_VERSION });
const answer = pendingCheck();
app = mountGate(target, 'vi');
await settle();
expect(gate().open).toBe(true);
expect(gate().dataset['step']).toBe('verify');
expect(acceptBtn()).toBeNull();
expect(vi.mocked(runHumanCheck).mock.calls[0]?.[1]).toMatchObject({ language: 'vi' });
answer('passed');
await settle();
expect(gate().open).toBe(false);
});
it('closes on accept without a check when one already passed', async () => {
stubStorage({ humanUntil: human() });
app = mountGate(target);
acceptBtn().click();
await settle();
expect(gate().open).toBe(false);
expect(runHumanCheck).not.toHaveBeenCalled();
});
it('stays closed for a visitor who accepted and passed recently', () => {
stubStorage({ legal: LEGAL_VERSION, humanUntil: human() });
app = mountGate(target);
expect(gate().open).toBe(false);
clientRouterSwapTo('/apps');
flushSync();
expect(gate().open).toBe(true);
expect(document.body.dataset['shGate']).toBe('closed');
expect(runHumanCheck).not.toHaveBeenCalled();
});
it('re-opens for everyone when LEGAL_VERSION moves on', () => {
stubStorage('2020-01-01'); // accepted an older draft
goto('/apps');
stubStorage({ legal: '2020-01-01', humanUntil: human() }); // accepted an older draft
app = mountGate(target);
expect(gate().open).toBe(true);
expect(gate().dataset['step']).toBe('legal');
});
});
it('follows the locale across a swap, not the prop it first rendered with', () => {
// transition:persist keeps this island alive across /apps -> /vi/apps.
// The `locale` prop is frozen at the first render, so without deriving
// from the URL a Vietnamese page would show the English gate.
describe('ShLegalGate — copy', () => {
it('links all three documents under the locale base, joined with "and"', () => {
stubStorage();
goto('/apps');
app = mountGate(target, 'vi');
const links = [...gate().querySelectorAll('a')].map((a) => a.getAttribute('href'));
expect(links).toEqual(['/vi/legal/disclaimer', '/vi/legal/terms', '/vi/legal/privacy']);
expect(gate().textContent).toContain('Trước khi tiếp tục');
expect(gate().textContent).toMatch(/Điều khoản sử dụng\s+và\s+Chính sách quyền riêng tư/);
});
it('describes itself with the body text for assistive tech', () => {
stubStorage();
app = mountGate(target);
expect(gate().textContent).toContain('Before you continue');
const describedBy = gate().getAttribute('aria-describedby');
expect(describedBy).toBeTruthy();
expect(document.getElementById(describedBy!)?.textContent).toContain(en['gate.body']);
});
clientRouterSwapTo('/vi/apps');
flushSync();
expect(gate().textContent).toContain('Trước khi tiếp tục');
expect(gate().querySelector('a')?.getAttribute('href')).toBe('/vi/legal/disclaimer');
it('explains the check and links where the Privacy Policy describes it', async () => {
stubStorage({ legal: LEGAL_VERSION });
pendingCheck();
app = mountGate(target);
await settle();
const body = document.getElementById(gate().getAttribute('aria-describedby')!)!;
expect(body.textContent).toContain(en['gate.verify.body']);
expect(body.querySelector('a')?.getAttribute('href')).toBe('/legal/privacy#turnstile');
});
});
+302
View File
@@ -0,0 +1,302 @@
<!-- SPDX-License-Identifier: GPL-3.0-only
Copyright (C) 2026 poli0981 (SkullMute)
Display preferences (v1.1) — theme, scrollbar and motion in one menu.
Replaces ShThemeToggle, so the island budget stays at six (docs/02 §5). -->
<script lang="ts">
import { onMount } from 'svelte';
import IconSliders from '~icons/lucide/sliders-horizontal';
import {
applyTheme,
prefersDark,
readChoice,
resolve,
writeChoice,
type ThemeChoice,
} from '../../lib/theme';
import {
applyMotion,
applyScrollbar,
readMotion,
readScrollbar,
writeMotion,
writeScrollbar,
type MotionChoice,
type ScrollbarChoice,
} from '../../lib/prefs';
interface Props {
/** Accessible name of the button and title of the panel. */
label: string;
themeLabel: string;
themes: Record<ThemeChoice, string>;
scrollbarLabel: string;
scrollbars: Record<ScrollbarChoice, string>;
motionLabel: string;
motions: Record<MotionChoice, string>;
/** Localized /apps#search — where `/` goes from pages without a search box. */
searchHref: string;
}
const {
label,
themeLabel,
themes,
scrollbarLabel,
scrollbars,
motionLabel,
motions,
searchHref,
}: Props = $props();
// SSR renders the defaults; the real values are read on mount. The panel is
// closed until then, so nothing visibly changes — and the button itself is
// a fixed-size icon, unlike the old toggle whose label width changed on
// hydration and shifted the header on every page load.
let theme = $state<ThemeChoice>('system');
let scrollbar = $state<ScrollbarChoice>('auto');
let motion = $state<MotionChoice>('system');
const root = (): HTMLElement => document.documentElement;
function setTheme(next: ThemeChoice): void {
theme = next;
writeChoice(next);
applyTheme(resolve(next), root());
}
function setScrollbar(next: ScrollbarChoice): void {
scrollbar = next;
writeScrollbar(next);
applyScrollbar(next, root());
}
function setMotion(next: MotionChoice): void {
motion = next;
writeMotion(next);
applyMotion(next, root());
}
/**
* `/` jumps to search from any page (docs/06 §9). On /apps ShSearch owns the
* key and focuses its box; everywhere else the header hint used to promise a
* shortcut that did nothing.
*/
function onGlobalKeydown(e: KeyboardEvent): void {
if (e.key !== '/' || e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented) return;
if (document.getElementById('sh-search')) return;
const t = e.target as HTMLElement | null;
if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
if (document.body.dataset['shGate'] === 'open') return;
e.preventDefault();
location.assign(searchHref);
}
onMount(() => {
theme = readChoice();
scrollbar = readScrollbar();
motion = readMotion();
// While in system mode the OS can flip underneath us — follow it live
// (docs/05 §A8). Once the visitor picks explicitly, stop following it.
const mq = matchMedia('(prefers-color-scheme: dark)');
const onSystemChange = () => {
if (theme === 'system') applyTheme(resolve('system', mq.matches), root());
};
// Another tab changed a preference: follow it here too.
const onStorage = (e: StorageEvent) => {
if (e.key === 'sh:theme') setTheme(readChoice());
else if (e.key === 'sh:scrollbar') setScrollbar(readScrollbar());
else if (e.key === 'sh:motion') setMotion(readMotion());
};
mq.addEventListener('change', onSystemChange);
window.addEventListener('storage', onStorage);
document.addEventListener('keydown', onGlobalKeydown);
return () => {
mq.removeEventListener('change', onSystemChange);
window.removeEventListener('storage', onStorage);
document.removeEventListener('keydown', onGlobalKeydown);
};
});
const themeChoices: ThemeChoice[] = ['system', 'light', 'dark'];
const scrollbarChoices: ScrollbarChoice[] = ['auto', 'thin', 'hidden'];
const motionChoices: MotionChoice[] = ['system', 'reduce'];
/** For the button's tooltip: what "system" currently resolves to. */
const resolvedTheme = $derived(
theme === 'system' && typeof matchMedia === 'function'
? prefersDark()
? themes.dark
: themes.light
: themes[theme],
);
</script>
<button
type="button"
class="sh-prefs-button"
popovertarget="sh-prefs"
aria-label={label}
title={`${label} · ${themeLabel}: ${resolvedTheme}`}
data-testid="sh-prefs-button"
>
<IconSliders aria-hidden="true" width="1.25em" height="1.25em" />
</button>
<div
id="sh-prefs"
popover="auto"
class="sh-prefs-panel"
role="dialog"
aria-labelledby="sh-prefs-title"
data-testid="sh-prefs"
>
<h2 id="sh-prefs-title" class="sh-prefs-title">{label}</h2>
<fieldset>
<legend>{themeLabel}</legend>
<div class="sh-seg">
{#each themeChoices as value (value)}
<label>
<input
type="radio"
name="sh-theme"
{value}
checked={theme === value}
onchange={() => setTheme(value)}
/>
<span>{themes[value]}</span>
</label>
{/each}
</div>
</fieldset>
<fieldset>
<legend>{scrollbarLabel}</legend>
<div class="sh-seg">
{#each scrollbarChoices as value (value)}
<label>
<input
type="radio"
name="sh-scrollbar"
{value}
checked={scrollbar === value}
onchange={() => setScrollbar(value)}
/>
<span>{scrollbars[value]}</span>
</label>
{/each}
</div>
</fieldset>
<fieldset>
<legend>{motionLabel}</legend>
<div class="sh-seg">
{#each motionChoices as value (value)}
<label>
<input
type="radio"
name="sh-motion"
{value}
checked={motion === value}
onchange={() => setMotion(value)}
/>
<span>{motions[value]}</span>
</label>
{/each}
</div>
</fieldset>
</div>
<style>
.sh-prefs-button {
display: inline-grid;
place-items: center;
inline-size: 2.5rem;
block-size: 2.5rem;
border: 1px solid var(--sh-control);
border-radius: var(--radius-btn);
background: var(--sh-surface);
color: var(--sh-ink);
transition: border-color var(--duration-fast) var(--ease-sh);
}
.sh-prefs-button:hover {
border-color: var(--sh-accent);
background: var(--sh-surface-2);
}
/* A popover is in the top layer and starts as a centred box with margin
auto; pin it under the header's right edge instead. */
.sh-prefs-panel {
position: fixed;
inset: 4.25rem 1rem auto auto;
margin: 0;
inline-size: min(22rem, calc(100vw - 2rem));
padding: 1.25rem;
border: 1px solid var(--sh-border);
border-radius: var(--radius-card);
background: var(--sh-surface);
color: var(--sh-ink);
box-shadow: var(--sh-shadow-3);
}
.sh-prefs-title {
font-family: var(--font-display);
font-size: var(--text-h3);
font-weight: 600;
}
fieldset {
margin-block-start: 1rem;
}
legend {
font-size: var(--text-small);
color: var(--sh-muted);
margin-block-end: 0.375rem;
}
/* Segmented control built from real radio buttons: native keyboard
behaviour (arrow keys), one tab stop per group, form semantics for free. */
.sh-seg {
display: flex;
border: 1px solid var(--sh-control);
border-radius: var(--radius-btn);
overflow: hidden;
}
.sh-seg label {
flex: 1;
position: relative;
}
.sh-seg input {
position: absolute;
inset: 0;
opacity: 0;
margin: 0;
cursor: pointer;
}
.sh-seg span {
display: grid;
place-items: center;
min-block-size: 2.5rem;
padding: 0 0.5rem;
font-size: var(--text-small);
text-align: center;
}
.sh-seg label + label span {
border-inline-start: 1px solid var(--sh-border);
}
.sh-seg input:checked + span {
background: var(--sh-accent);
color: var(--sh-accent-ink);
font-weight: 600;
}
.sh-seg input:focus-visible + span {
outline: 2px solid var(--sh-accent);
outline-offset: -4px;
}
@media (width < 40rem) {
.sh-prefs-panel {
inset: auto 0 0 0;
inline-size: 100%;
border-radius: var(--radius-card) var(--radius-card) 0 0;
}
}
</style>
+106
View File
@@ -0,0 +1,106 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// ShPrefs — the display menu. Drives the real component in happy-dom: the
// choices apply to <html> at once and persist. Popover placement, light
// dismiss and the `/` shortcut's navigation need a real browser and are
// covered by the Playwright suite.
import { flushSync, mount, unmount } from 'svelte';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import ShPrefs from './ShPrefs.svelte';
const PROPS = {
label: 'Display settings',
themeLabel: 'Theme',
themes: { system: 'System', light: 'Light', dark: 'Dark' },
scrollbarLabel: 'Scrollbar',
scrollbars: { auto: 'Default', thin: 'Thin', hidden: 'Hidden' },
motionLabel: 'Motion',
motions: { system: 'System', reduce: 'Reduce' },
searchHref: '/apps#search',
};
function stubStorage(seed: Record<string, string> = {}) {
const map = new Map(Object.entries(seed));
Object.defineProperty(globalThis, 'localStorage', {
configurable: true,
value: {
getItem: (k: string) => map.get(k) ?? null,
setItem: (k: string, v: string) => void map.set(k, v),
removeItem: (k: string) => void map.delete(k),
},
});
return map;
}
let target: HTMLElement;
let app: Record<string, unknown> | undefined;
const radio = (name: string, value: string) =>
document.querySelector<HTMLInputElement>(`input[name="${name}"][value="${value}"]`)!;
function choose(name: string, value: string) {
const input = radio(name, value);
input.checked = true;
input.dispatchEvent(new Event('change', { bubbles: true }));
flushSync();
}
beforeEach(() => {
document.body.innerHTML = '';
for (const a of ['data-theme', 'data-scrollbar', 'data-motion']) {
document.documentElement.removeAttribute(a);
}
target = document.createElement('div');
document.body.appendChild(target);
});
afterEach(async () => {
if (app) await unmount(app);
app = undefined;
Reflect.deleteProperty(globalThis, 'localStorage');
});
describe('ShPrefs', () => {
it('renders an icon button that names the panel it opens', () => {
stubStorage();
app = mount(ShPrefs, { target, props: PROPS });
flushSync();
const button = document.querySelector('[data-testid="sh-prefs-button"]')!;
expect(button.getAttribute('aria-label')).toBe('Display settings');
expect(button.getAttribute('popovertarget')).toBe('sh-prefs');
expect(document.getElementById('sh-prefs')?.getAttribute('popover')).toBe('auto');
});
it('reflects stored choices once mounted', () => {
stubStorage({ 'sh:theme': 'dark', 'sh:scrollbar': 'thin', 'sh:motion': 'reduce' });
app = mount(ShPrefs, { target, props: PROPS });
flushSync();
expect(radio('sh-theme', 'dark').checked).toBe(true);
expect(radio('sh-scrollbar', 'thin').checked).toBe(true);
expect(radio('sh-motion', 'reduce').checked).toBe(true);
});
it('applies and persists each choice immediately', () => {
const store = stubStorage();
app = mount(ShPrefs, { target, props: PROPS });
flushSync();
choose('sh-theme', 'dark');
expect(document.documentElement.dataset['theme']).toBe('dark');
expect(store.get('sh:theme')).toBe('dark');
choose('sh-scrollbar', 'hidden');
expect(document.documentElement.dataset['scrollbar']).toBe('hidden');
expect(store.get('sh:scrollbar')).toBe('hidden');
choose('sh-motion', 'reduce');
expect(document.documentElement.dataset['motion']).toBe('reduce');
expect(store.get('sh:motion')).toBe('reduce');
choose('sh-scrollbar', 'auto');
expect(document.documentElement.dataset['scrollbar']).toBeUndefined();
expect(store.has('sh:scrollbar')).toBe(false);
});
});
+144 -47
View File
@@ -2,81 +2,110 @@
Copyright (C) 2026 poli0981 (SkullMute)
docs/05 §A2/§A3, docs/06 §5 — search input + grid controller. -->
<script lang="ts">
import MiniSearch from 'minisearch';
import { onMount } from 'svelte';
import { miniSearchOptions, type SearchDoc } from '../../lib/search';
import IconSearch from '~icons/lucide/search';
import { mountGrid, type GridHandle } from '../../lib/grid';
import { query, sort, type SortOrder } from '../../lib/stores';
import { loadSearchIndex } from '../../lib/searchIndex';
import { categories, platforms, pricing, query, sort, type SortOrder } from '../../lib/stores';
import { parseViewState, serializeViewState } from '../../lib/urlstate';
interface Props {
placeholder: string;
label: string;
loadingLabel: string;
/** Shown when the index cannot be loaded; facet filters keep working. */
errorLabel: string;
sortLabel: string;
sortName: string;
sortAdded: string;
sortLabel: string;
sortRelevance: string;
}
const { placeholder, label, loadingLabel, sortName, sortAdded, sortLabel }: Props = $props();
const {
placeholder,
label,
loadingLabel,
errorLabel,
sortLabel,
sortName,
sortAdded,
sortRelevance,
}: Props = $props();
/** Typing settles before the index is queried and the grid reordered. */
const SEARCH_DEBOUNCE_MS = 150;
/** The URL is updated after the view stops changing, not per keystroke. */
const URL_DEBOUNCE_MS = 300;
let value = $state('');
let loading = $state(false);
let failed = $state(false);
let input: HTMLInputElement | undefined = $state();
let grid: GridHandle | null = null;
let mini: MiniSearch<SearchDoc> | null = null;
let indexPromise: Promise<void> | null = null;
/**
* The index is fetched on FIRST interaction, not on mount (docs/05 §A2):
* a visitor who never searches never pays for it, and facet filtering works
* without it because the facets come from the DOM (§A3).
*/
function loadIndex(): Promise<void> {
indexPromise ??= (async () => {
loading = true;
try {
const res = await fetch('/search-index.json');
mini = MiniSearch.loadJSON<SearchDoc>(await res.text(), miniSearchOptions as never);
} catch {
// Offline or blocked: leave `mini` null so search stays inert and the
// facet filters keep working, rather than emptying the grid.
indexPromise = null;
} finally {
loading = false;
}
})();
return indexPromise;
}
/** Bumped per query; a result for an older query is dropped on arrival. */
let seq = 0;
let searchTimer: ReturnType<typeof setTimeout> | undefined;
let urlTimer: ReturnType<typeof setTimeout> | undefined;
/** Whether the visitor chose an order; if not, searching switches to relevance. */
let userSorted = false;
async function run(raw: string): Promise<void> {
const q = raw.trim();
query.set(q);
const mine = ++seq;
if (q.length === 0) {
grid?.setSearchHits(null); // empty query constrains nothing
if (!userSorted && sort.get() === 'relevance') sort.set('name');
return;
}
await loadIndex();
if (!mini) return;
grid?.setSearchHits(new Set(mini.search(q).map((r) => String(r.id))));
loading = true;
try {
const index = await loadSearchIndex();
// The race this guards: type "g", delete it before the index arrives,
// and the late result for "g" used to land on an empty box and filter
// the grid anyway.
if (mine !== seq || q !== query.get()) return;
failed = false;
if (!userSorted && sort.get() === 'name') sort.set('relevance');
grid?.setSearchHits(index.search(q).map((r) => String(r.id)));
} catch {
// Offline or blocked: say so, and leave the facets working rather than
// emptying the grid. The next keystroke retries the download.
if (mine === seq) failed = true;
} finally {
if (mine === seq) loading = false;
}
}
function schedule(raw: string): void {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => void run(raw), SEARCH_DEBOUNCE_MS);
}
function onInput(e: Event): void {
value = (e.currentTarget as HTMLInputElement).value;
void run(value);
schedule(value);
}
function onKeydown(e: KeyboardEvent): void {
if (e.key === 'Escape') {
if (value !== '') {
value = '';
void run('');
} else {
input?.blur();
}
if (e.key !== 'Escape') return;
if (value !== '') {
value = '';
clearTimeout(searchTimer);
void run('');
} else {
input?.blur();
}
}
/** `/` focuses search from anywhere (docs/06 §9). */
function onSortChange(e: Event): void {
userSorted = true;
sort.set((e.currentTarget as HTMLSelectElement).value as SortOrder);
}
/** `/` focuses search from anywhere on /apps (docs/06 §9). */
function onGlobalKeydown(e: KeyboardEvent): void {
if (e.key !== '/' || e.metaKey || e.ctrlKey || e.altKey) return;
// Never steal the key from a field the user is typing in...
@@ -90,11 +119,65 @@
input?.focus();
}
function writeUrl(): void {
clearTimeout(urlTimer);
urlTimer = setTimeout(() => {
const next =
location.pathname +
serializeViewState({
q: query.get(),
categories: [...categories.get()],
platforms: [...platforms.get()],
pricing: [...pricing.get()],
// An automatic relevance order is implied by `q`; only a deliberate
// choice belongs in a shared link.
sort: userSorted ? sort.get() : null,
}) +
location.hash;
if (next !== location.pathname + location.search + location.hash) {
history.replaceState(history.state, '', next);
}
}, URL_DEBOUNCE_MS);
}
onMount(() => {
grid = mountGrid();
// Restore a shared / reloaded / back-navigated view.
const state = parseViewState(location.search);
categories.set(new Set(state.categories));
platforms.set(new Set(state.platforms));
pricing.set(new Set(state.pricing));
if (state.sort) {
userSorted = true;
sort.set(state.sort);
}
grid?.apply();
if (state.q) {
value = state.q;
void run(state.q);
}
// The welcome page's search field is a plain link to /apps#search.
if (location.hash === '#search') input?.focus();
const unsubs = [
// "Clear all" (or anything else) emptying the query empties the box too.
query.listen((q) => {
if (q === '' && value !== '') value = '';
writeUrl();
}),
categories.listen(writeUrl),
platforms.listen(writeUrl),
pricing.listen(writeUrl),
sort.listen(writeUrl),
];
document.addEventListener('keydown', onGlobalKeydown);
return () => {
clearTimeout(searchTimer);
clearTimeout(urlTimer);
for (const off of unsubs) off();
document.removeEventListener('keydown', onGlobalKeydown);
grid?.destroy();
};
@@ -104,6 +187,10 @@
<div class="flex flex-wrap items-center gap-3">
<div class="relative min-w-0 flex-1">
<label class="sr-only" for="sh-search">{label}</label>
<IconSearch
aria-hidden="true"
class="text-sh-muted pointer-events-none absolute top-1/2 left-3.5 size-5 -translate-y-1/2"
/>
<input
id="sh-search"
bind:this={input}
@@ -111,16 +198,18 @@
type="search"
autocomplete="off"
spellcheck="false"
class="bg-sh-surface border-sh-border w-full rounded-[var(--radius-card)] border-2 px-4 py-3"
enterkeyhint="search"
class="bg-sh-surface border-sh-control shadow-sh-1 w-full rounded-[var(--radius-card)] border py-3 pr-4 pl-11"
{value}
oninput={onInput}
onkeydown={onKeydown}
onfocus={() => void loadIndex()}
onfocus={() => void loadSearchIndex().catch(() => undefined)}
aria-describedby={failed ? 'sh-search-status' : undefined}
/>
{#if loading}
<span
class="text-sh-muted absolute top-1/2 right-3 -translate-y-1/2 font-mono text-[var(--text-badge)]"
>{loadingLabel}</span
class="text-sh-muted text-badge absolute top-1/2 right-3 -translate-y-1/2 font-mono"
aria-hidden="true">{loadingLabel}</span
>
{/if}
</div>
@@ -128,14 +217,22 @@
<label class="sr-only" for="sh-sort">{sortLabel}</label>
<select
id="sh-sort"
class="bg-sh-surface border-sh-border rounded-[var(--radius-card)] border-2 px-3 py-3"
onchange={(e) => sort.set((e.currentTarget as HTMLSelectElement).value as SortOrder)}
class="bg-sh-surface border-sh-control shadow-sh-1 rounded-[var(--radius-card)] border px-3 py-3"
value={$sort}
onchange={onSortChange}
>
{#if $query !== '' || $sort === 'relevance'}
<option value="relevance">{sortRelevance}</option>
{/if}
<option value="name">{sortName}</option>
<option value="added">{sortAdded}</option>
</select>
</div>
{#if failed}
<p id="sh-search-status" class="text-sh-muted text-small mt-2" role="status">{errorLabel}</p>
{/if}
<style>
.sr-only {
position: absolute;
+172
View File
@@ -0,0 +1,172 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// ShSearch — the search box and grid controller. The grid (src/lib/grid.ts)
// and the index download are stubbed, so these pin the island's own
// contract: debounce, the stale-result race, failure reporting, URL state and
// the keyboard. Real typing against the real index runs in Playwright
// (e2e/prefs-search.spec.ts).
import { flushSync, mount, unmount } from 'svelte';
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { mountGrid, type GridHandle } from '../../lib/grid';
import { loadSearchIndex, type SearchIndex } from '../../lib/searchIndex';
import { clearAll, platforms, query, sort } from '../../lib/stores';
import ShSearch from './ShSearch.svelte';
vi.mock('../../lib/grid', () => ({ mountGrid: vi.fn() }));
vi.mock('../../lib/searchIndex', () => ({ loadSearchIndex: vi.fn() }));
const PROPS = {
placeholder: 'Search apps',
label: 'Search',
loadingLabel: 'Loading…',
errorLabel: 'Search is unavailable right now.',
sortLabel: 'Sort',
sortName: 'A–Z',
sortAdded: 'Newest',
sortRelevance: 'Relevance',
};
let grid: { [K in keyof GridHandle]: Mock<GridHandle[K]> };
let app: Record<string, unknown> | undefined;
const index = (...ids: string[]): SearchIndex =>
({ search: vi.fn(() => ids.map((id) => ({ id }))) }) as unknown as SearchIndex;
function start(url = '/apps'): HTMLInputElement {
history.replaceState(null, '', url);
const target = document.createElement('div');
document.body.appendChild(target);
app = mount(ShSearch, { target, props: PROPS });
flushSync();
return document.querySelector<HTMLInputElement>('#sh-search')!;
}
function type(input: HTMLInputElement, text: string): void {
input.value = text;
input.dispatchEvent(new Event('input', { bubbles: true }));
}
const key = (el: EventTarget, k: string) =>
el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }));
beforeEach(() => {
vi.useFakeTimers();
document.body.innerHTML = '';
grid = {
setSearchHits: vi.fn<GridHandle['setSearchHits']>(),
apply: vi.fn<GridHandle['apply']>(),
destroy: vi.fn<GridHandle['destroy']>(),
};
vi.mocked(mountGrid).mockReturnValue(grid);
vi.mocked(loadSearchIndex).mockResolvedValue(index('gimp', 'krita'));
});
afterEach(async () => {
if (app) await unmount(app);
app = undefined;
clearAll();
sort.set('name');
delete document.body.dataset['shGate'];
vi.useRealTimers();
vi.clearAllMocks();
});
describe('ShSearch', () => {
it('waits for typing to settle, then ranks the grid and switches to relevance', async () => {
const input = start();
type(input, 'gim');
type(input, 'gimp');
await vi.advanceTimersByTimeAsync(100);
expect(grid.setSearchHits).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(50);
expect(query.get()).toBe('gimp');
expect(grid.setSearchHits).toHaveBeenCalledTimes(1);
expect(grid.setSearchHits).toHaveBeenLastCalledWith(['gimp', 'krita']);
expect(sort.get()).toBe('relevance');
});
it('drops a result that arrives after the box was cleared', async () => {
let arrive: (i: SearchIndex) => void = () => undefined;
vi.mocked(loadSearchIndex).mockReturnValue(new Promise((r) => (arrive = r)));
const input = start();
type(input, 'g');
await vi.advanceTimersByTimeAsync(150); // "g" is now waiting on the download
key(input, 'Escape'); // …and is cleared before it lands
arrive(index('gimp'));
await vi.advanceTimersByTimeAsync(0);
expect(input.value).toBe('');
expect(grid.setSearchHits.mock.calls).toEqual([[null]]);
expect(sort.get()).toBe('name');
});
it('says so when the index cannot load, and leaves the grid alone', async () => {
vi.mocked(loadSearchIndex).mockRejectedValue(new Error('offline'));
const input = start();
type(input, 'gimp');
await vi.advanceTimersByTimeAsync(150);
flushSync();
const status = document.getElementById('sh-search-status');
expect(status?.getAttribute('role')).toBe('status');
expect(status?.textContent).toBe(PROPS.errorLabel);
expect(input.getAttribute('aria-describedby')).toBe('sh-search-status');
expect(grid.setSearchHits).not.toHaveBeenCalled();
});
it('restores a shared view, keeping a deliberately chosen order', async () => {
const input = start('/apps?q=gimp&platform=linux&sort=added');
expect(platforms.get()).toEqual(new Set(['linux']));
expect(input.value).toBe('gimp');
expect(grid.apply).toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(0);
expect(grid.setSearchHits).toHaveBeenLastCalledWith(['gimp', 'krita']);
expect(sort.get()).toBe('added');
});
it('writes the settled view to the URL, keeping the fragment', async () => {
const input = start('/apps#search');
type(input, 'trinh duyet');
await vi.advanceTimersByTimeAsync(150 + 300);
expect(location.search).toBe('?q=trinh+duyet');
expect(location.hash).toBe('#search');
});
it('empties the box when something else clears the query', async () => {
const input = start();
type(input, 'gimp');
await vi.advanceTimersByTimeAsync(150);
clearAll();
flushSync();
expect(input.value).toBe('');
});
it('focuses on "/", except from another field or behind the legal gate', () => {
const input = start();
const other = document.body.appendChild(document.createElement('textarea'));
key(document, '/');
expect(document.activeElement).toBe(input);
other.focus();
key(other, '/');
expect(document.activeElement).toBe(other);
other.blur();
document.body.dataset['shGate'] = 'open';
key(document, '/');
expect(document.activeElement).not.toBe(input);
});
it('Escape on an empty box gives focus back to the page', () => {
const input = start();
input.focus();
key(input, 'Escape');
expect(document.activeElement).not.toBe(input);
});
});
@@ -1,67 +0,0 @@
<!-- SPDX-License-Identifier: GPL-3.0-only
Copyright (C) 2026 poli0981 (SkullMute)
docs/05 §A8, docs/06 §4 — cycles system → light → dark. -->
<script lang="ts">
import { onMount } from 'svelte';
import {
applyTheme,
nextChoice,
prefersDark,
readChoice,
resolve,
writeChoice,
type ThemeChoice,
} from '../../lib/theme';
interface Props {
labels: Record<ThemeChoice, string>;
/** Accessible name for the control itself, e.g. "Theme". */
label: string;
}
const { labels, label }: Props = $props();
let choice = $state<ThemeChoice>('system');
function set(next: ThemeChoice): void {
choice = next;
writeChoice(next);
applyTheme(resolve(next), document.documentElement);
}
onMount(() => {
choice = readChoice();
// theme.js already applied the right value pre-paint; re-applying here
// keeps the two in agreement if storage changed in another tab.
applyTheme(resolve(choice), document.documentElement);
// While in system mode the OS can flip underneath us — follow it live
// (docs/05 §A8). Once the user picks explicitly, stop listening to it.
const mq = matchMedia('(prefers-color-scheme: dark)');
const onSystemChange = () => {
if (choice === 'system') applyTheme(resolve('system', mq.matches), document.documentElement);
};
mq.addEventListener('change', onSystemChange);
return () => mq.removeEventListener('change', onSystemChange);
});
// The button announces what is ACTIVE, not what clicking will do — a toggle
// labelled with its next state is a well-known screen-reader trap.
const current = $derived(labels[choice]);
const resolved = $derived(choice === 'system' ? (prefersDarkSafe() ? 'dark' : 'light') : choice);
function prefersDarkSafe(): boolean {
return typeof matchMedia === 'function' ? prefersDark() : false;
}
</script>
<button
type="button"
class="sh-pill border-sh-muted text-sh-muted min-h-11 px-3"
aria-label={`${label}: ${current}`}
data-testid="sh-theme-toggle"
data-choice={choice}
onclick={() => set(nextChoice(choice))}
>
<span aria-hidden="true">{resolved === 'dark' ? '◑' : '◐'}</span>
<span>{current}</span>
</button>
+30 -39
View File
@@ -8,7 +8,8 @@
// project grant CC BY-SA 4.0 on the dataset only if the words in it are its
// own, and the site's whole proposition is that a reader can check what they
// are told. Both of those are worth less if the reader does not know how the
// thing was made.
// thing was made — so every claim here must stay literally true. Name each
// model whose work lands, and update the claims when a process changes.
import type { Locale } from '../../i18n';
interface Props {
locale: Locale;
@@ -22,63 +23,59 @@ const rows = [
{
area: { en: 'Source code', vi: 'Mã nguồn' },
how: {
en: 'Written with AI assistance, then reviewed and run by the maintainer. Every change passes the same automated gates as any other: lint, type-check, unit tests, schema validation, EN/VI parity, a build, and a CSP guard.',
vi: 'Viết với sự hỗ trợ của AI, sau đó người bảo trì đọc lại và chạy thử. Mọi thay đổi đều qua đúng bộ kiểm tra tự động như bình thường: lint, kiểm tra kiểu, unit test, kiểm tra schema, đối chiếu EN/VI, build và kiểm tra CSP.',
en: 'Written with AI assistance, then reviewed and run by the maintainer. Every change passes the same automated gates as any other: lint, type-check, unit and browser tests, schema validation, EN/VI parity, a build, and a CSP guard.',
vi: 'Viết với sự hỗ trợ của AI, sau đó người bảo trì đọc lại và chạy thử. Mọi thay đổi đều qua đúng bộ kiểm tra tự động như bình thường: lint, kiểm tra kiểu, unit test và kiểm thử trên trình duyệt, kiểm tra schema, đối chiếu EN/VI, build và kiểm tra CSP.',
},
},
{
area: { en: 'Tests', vi: 'Kiểm thử' },
how: {
en: 'Test cases were drafted with AI assistance and are checked against the behaviour they describe — a test is only kept once it has been seen to fail on the bug it claims to cover.',
vi: 'Các ca kiểm thử được soạn với hỗ trợ của AI và được đối chiếu với hành vi mà chúng mô tả — một bài kiểm thử chỉ được giữ lại sau khi đã thấy nó thất bại đúng với lỗi mà nó tuyên bố phát hiện.',
en: 'Test cases were drafted with AI assistance and are reviewed against the behaviour they describe. They run on every change, and a change cannot be merged while any of them fails.',
vi: 'Các ca kiểm thử được soạn với sự hỗ trợ của AI và được đối chiếu với hành vi mà chúng mô tả. Chúng chạy ở mọi thay đổi, và không thay đổi nào được hợp nhất khi còn một bài kiểm thử thất bại.',
},
},
{
area: { en: 'Finding the software', vi: 'Tìm danh sách phần mềm' },
how: {
en: 'The candidate list was assembled with AI assistance. Inclusion is a human decision against the published criteria, and every homepage, repository and download link is machine-checked on each pull request and again weekly.',
vi: 'Danh sách ứng viên được tập hợp với hỗ trợ của AI. Việc đưa vào danh sách là quyết định của con người theo bộ tiêu chí đã công bố, và mọi liên kết trang chủ, kho mã nguồn và tải về đều được máy kiểm tra ở mỗi pull request và hàng tuần.',
en: 'The candidate list was assembled with AI assistance. Inclusion is a human decision against the published criteria. Links are machine-checked: a pull request checks the entries it changes, and a weekly run checks the whole catalogue. A site that answers automated checkers with "forbidden" or "too many requests" is counted as reachable, since many developers block bots.',
vi: 'Danh sách ứng viên được tập hợp với sự hỗ trợ của AI. Việc đưa vào danh sách là quyết định của con người theo bộ tiêu chí đã công bố. Liên kết được máy kiểm tra: mỗi pull request kiểm tra các mục nó thay đổi, và một lượt chạy hàng tuần kiểm tra toàn bộ danh mục. Trang nào trả lời công cụ kiểm tra tự động bằng "bị cấm" hoặc "quá nhiều yêu cầu" vẫn được tính là truy cập được, vì nhiều nhà phát triển chặn bot.',
},
},
{
area: { en: 'Summaries', vi: 'Mô tả ứng dụng' },
how: {
en: 'Written from scratch in both languages, never pasted from vendor marketing or an encyclopaedia. That is what allows the dataset to carry CC BY-SA 4.0 at all. Vietnamese is reviewed by a native speaker rather than machine-translated.',
vi: 'Được viết mới hoàn toàn ở cả hai ngôn ngữ, không sao chép từ quảng cáo của nhà phát triển hay bách khoa toàn thư. Chính điều đó cho phép dữ liệu mang giấy phép CC BY-SA 4.0. Phần tiếng Việt do người bản ngữ đọc duyệt chứ không dịch máy.',
vi: 'Được viết mới hoàn toàn ở cả hai ngôn ngữ, không sao chép từ quảng cáo của nhà phát triển hay bách khoa toàn thư. Chính điều đó cho phép bộ dữ liệu mang giấy phép CC BY-SA 4.0. Phần tiếng Việt do người bản ngữ đọc duyệt chứ không dịch máy.',
},
},
{
area: { en: 'Security status', vi: 'Trạng thái bảo mật' },
how: {
en: 'Not AI-decided. Each entry is checked by the maintainer against the published vetting checklist, and the scan behind every status is linked from the app page so you can read it yourself.',
vi: 'Không do AI quyết định. Mỗi mục được người bảo trì kiểm tra theo quy trình đã công bố, và kết quả quét đứng sau mỗi trạng thái đều có liên kết ngay trên trang ứng dụng để bạn tự đọc.',
en: 'Not AI-decided. Each entry is checked by the maintainer against the published vetting checklist, and the scan behind every status is linked from the app page so you can read it yourself. Where a link has changed since its scan, the linked scan is of the earlier link until the next re-check.',
vi: 'Không do AI quyết định. Mỗi mục được người bảo trì kiểm tra theo quy trình đã công bố, và kết quả quét đứng sau mỗi trạng thái đều có liên kết ngay trên trang ứng dụng để bạn tự đọc. Nếu một liên kết đã đổi sau lần quét, kết quả được liên kết là của liên kết cũ cho tới lần kiểm tra lại kế tiếp.',
},
},
];
---
<p>
{
en
? 'SoftHarbor is built with AI assistance, and this page says where and how. It is published because the site asks you to trust a set of links and a dated security note — and that request is worth less if you do not know how the list was put together.'
: 'SoftHarbor được xây dựng với sự hỗ trợ của AI, và trang này nói rõ ở đâu và như thế nào. Chúng tôi công bố điều đó vì trang web đang đề nghị bạn tin vào một tập liên kết và một ghi chú bảo mật có ghi ngày — lời đề nghị ấy sẽ kém giá trị nếu bạn không biết danh sách được tạo ra ra sao.'
}
{en
? 'SoftHarbor is built with AI assistance, and this page says where and how. It is published because the site asks you to trust a set of links and a dated security note — and that request is worth less if you do not know how the list was put together.'
: 'SoftHarbor được xây dựng với sự hỗ trợ của AI, và trang này nói rõ ở đâu và như thế nào. Chúng tôi công bố điều đó vì trang web đang đề nghị bạn tin vào một tập liên kết và một ghi chú bảo mật có ghi ngày — lời đề nghị ấy sẽ kém giá trị nếu bạn không biết danh sách được tạo ra như thế nào.'}
</p>
<h2>{en ? 'Tools used' : 'Công cụ đã dùng'}</h2>
<p>
{
en
? 'Claude Opus 5 (model identifier claude-opus-5), developed by Anthropic, used through Claude Code — Anthropic’s command-line coding tool. Earlier work on the project used Claude models through the same tool. No other AI system contributed to this site.'
: 'Claude Opus 5 (mã định danh mô hình claude-opus-5) do Anthropic phát triển, sử dụng thông qua Claude Code — công cụ lập trình dòng lệnh của Anthropic. Các giai đoạn trước của dự án cũng dùng mô hình Claude qua chính công cụ này. Không có hệ thống AI nào khác tham gia vào trang web này.'
}
{en
? 'Claude models developed by Anthropic, used through Claude Code — Anthropic’s command-line coding tool: Claude Opus 5 (model identifier claude-opus-5) for the site and catalogue through v1.0, and Claude Opus 5.5 (claude-opus-5-5) for the v1.1 work of October 2026. Earlier work on the project used Claude models through the same tool. No other AI system contributed to this site.'
: 'Các mô hình Claude do Anthropic phát triển, sử dụng qua Claude Code — công cụ lập trình dòng lệnh của Anthropic: Claude Opus 5 (mã định danh mô hình claude-opus-5) cho trang web và danh mục đến hết v1.0, và Claude Opus 5.5 (claude-opus-5-5) cho phần việc v1.1 vào tháng 10/2026. Các giai đoạn trước của dự án cũng dùng mô hình Claude qua chính công cụ này. Không có hệ thống AI nào khác tham gia vào trang web này.'}
</p>
<h2>{en ? 'Where it was used' : 'Đã dùng ở đâu'}</h2>
<div class="-mx-4 overflow-x-auto px-4">
<table class="w-full border-collapse text-[var(--text-small)]">
<table class="w-full border-collapse text-small">
<thead>
<tr class="border-sh-border border-b-2 text-left">
<th class="w-1/4 py-2 pr-4">{en ? 'Area' : 'Hạng mục'}</th>
@@ -86,14 +83,12 @@ const rows = [
</tr>
</thead>
<tbody>
{
rows.map((r) => (
<tr class="border-sh-border border-b opacity-95">
<td class="py-2 pr-4 align-top">{r.area[locale]}</td>
<td class="text-sh-muted py-2 align-top">{r.how[locale]}</td>
</tr>
))
}
{rows.map((r) => (
<tr class="border-sh-border border-b opacity-95">
<td class="py-2 pr-4 align-top">{r.area[locale]}</td>
<td class="text-sh-muted py-2 align-top">{r.how[locale]}</td>
</tr>
))}
</tbody>
</table>
</div>
@@ -101,17 +96,13 @@ const rows = [
<h2>{en ? 'What this does not mean' : 'Điều này không có nghĩa là'}</h2>
<p>
{
en
? 'AI assistance is not a warranty and not an excuse. Nothing here is checked less carefully because a model helped write it, and a mistake on this site is the maintainer’s, not a tool’s. The limits already stated in the Disclaimer apply unchanged: SoftHarbor hosts no downloads, cannot guarantee third-party software, and reports a security status only as of the date shown.'
: 'Việc dùng AI không phải là bảo đảm, cũng không phải là cái cớ. Không có thứ gì ở đây được kiểm tra qua loa hơn chỉ vì có mô hình tham gia viết, và mọi sai sót trên trang này thuộc về người bảo trì chứ không phải công cụ. Các giới hạn đã nêu trong Tuyên bố miễn trừ vẫn giữ nguyên: SoftHarbor không lưu trữ tệp cài đặt, không thể bảo đảm cho phần mềm của bên thứ ba, và chỉ nêu trạng thái bảo mật tính đến ngày được hiển thị.'
}
{en
? 'AI assistance is not a warranty and not an excuse. Nothing here is checked less carefully because a model helped write it, and a mistake on this site is the maintainer’s, not a tool’s. The limits already stated in the Disclaimer apply unchanged: SoftHarbor hosts no downloads, cannot guarantee third-party software, and reports a security status only as of the date shown.'
: 'Việc dùng AI không phải là bảo đảm, cũng không phải là cái cớ. Không có thứ gì ở đây được kiểm tra qua loa hơn chỉ vì có mô hình tham gia viết, và mọi sai sót trên trang này thuộc về người bảo trì chứ không phải công cụ. Các giới hạn đã nêu trong Tuyên bố miễn trừ vẫn giữ nguyên: SoftHarbor không lưu trữ tệp cài đặt, không thể bảo đảm cho phần mềm của bên thứ ba, và chỉ nêu trạng thái bảo mật tính đến ngày được hiển thị.'}
</p>
<p class="text-sh-muted">
{
en
? 'Found something wrong? Every app page has a "Report a bug" link, and the full history of how each entry got here is public in the repository.'
: 'Phát hiện điều gì chưa đúng? Mỗi trang ứng dụng đều có liên kết "Báo lỗi", và toàn bộ lịch sử hình thành của từng mục đều công khai trong kho mã nguồn.'
}
{en
? 'Found something wrong? The "Report a bug" link at the foot of every page opens a prefilled report, and the full history of how each entry got here is public in the repository.'
: 'Phát hiện điều gì chưa đúng? Liên kết "Báo lỗi" ở cuối mỗi trang mở sẵn một báo cáo được điền trước, và toàn bộ lịch sử hình thành của từng mục đều công khai trong kho mã nguồn.'}
</p>
+85 -74
View File
@@ -3,84 +3,95 @@
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/14 §3a. EN is canonical (docs/07 §8); both locales kept in one file so
// a change to one is visibly a change to the other during review.
// The reporting routes match SECURITY.md: a dangerous listing is a security
// report (private), wrong information is an ordinary issue.
import { CONTACTS } from '../../lib/contacts';
import type { Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const CONTACT = 'contact@softharbor.net';
const { security: SECURITY, takedown: TAKEDOWN } = CONTACTS;
const ISSUES = 'https://github.com/poli0981/softharbor/issues';
const base = locale === 'vi' ? '/vi/legal' : '/legal';
---
{
locale === 'en' ? (
<>
<p>SoftHarbor is an independent, non-commercial directory of desktop software.</p>
<ol>
<li>
<strong>No affiliation:</strong> we are not affiliated with, endorsed by, or sponsored by
any listed developer; names and logos identify products only (see Trademarks).
</li>
<li>
<strong>No hosting:</strong> we host no installers; all download links lead to third-party
sites we do not control.
</li>
<li>
<strong>No warranty on information:</strong> listings — including pricing, license,
platform availability, and security status — are provided "as is" and may be outdated or
wrong; pricing models change without notice.
</li>
<li>
<strong>Security statuses are not guarantees:</strong> "No known warnings — checked
&lt;date&gt;" means our checklist found nothing <em>on that date</em>; it is not an audit,
a certification, or a promise of safety. Software can be compromised after our check.
Always download from official sources, verify signatures or checksums where offered, and
use your own judgment.
</li>
<li>
<strong>Your risk:</strong> installing third-party software is entirely at your own risk;
to the maximum extent permitted by law we accept no liability for damages arising from
software you obtain via links on this site.
</li>
<li>
Report dangerous or incorrect listings: GitHub issues or{' '}
<a href={`mailto:${CONTACT}`}>{CONTACT}</a>.
</li>
</ol>
</>
) : (
<>
<p>SoftHarbor là trang tổng hợp phần mềm desktop độc lập, phi thương mại.</p>
<ol>
<li>
<strong>Không liên kết:</strong> chúng tôi không liên kết, không được bảo trợ hay tài trợ
bởi bất kỳ nhà phát triển nào; tên và logo chỉ nhằm nhận diện sản phẩm (xem Thương hiệu).
</li>
<li>
<strong>Không lưu trữ:</strong> chúng tôi không lưu trữ tệp cài đặt; mọi liên kết tải về
dẫn tới trang bên thứ ba ngoài tầm kiểm soát của chúng tôi.
</li>
<li>
<strong>Không bảo đảm thông tin:</strong> thông tin — gồm giá, giấy phép, nền tảng hỗ trợ,
trạng thái bảo mật — được cung cấp "nguyên trạng", có thể lỗi thời hoặc sai; mô hình giá
có thể thay đổi bất kỳ lúc nào.
</li>
<li>
<strong>Trạng thái bảo mật không phải bảo chứng:</strong> "Không có cảnh báo đã biết — đã
kiểm tra &lt;ngày&gt;" nghĩa là quy trình kiểm tra của chúng tôi không phát hiện gì{' '}
<em>tại ngày đó</em>; đây không phải kiểm định hay cam kết an toàn. Phần mềm có thể bị xâm
phạm sau thời điểm kiểm tra. Hãy luôn tải từ nguồn chính thức, xác minh chữ ký/checksum
nếu có, và tự cân nhắc.
</li>
<li>
<strong>Rủi ro của bạn:</strong> việc cài đặt phần mềm bên thứ ba hoàn toàn thuộc rủi ro
của bạn; trong phạm vi tối đa pháp luật cho phép, chúng tôi không chịu trách nhiệm cho
thiệt hại phát sinh.
</li>
<li>
Báo cáo mục nguy hiểm hoặc sai: GitHub issues hoặc{' '}
<a href={`mailto:${CONTACT}`}>{CONTACT}</a>.
</li>
</ol>
</>
)
}
{locale === 'en' ? (
<>
<p>SoftHarbor is an independent, non-commercial directory of desktop software.</p>
<ol>
<li>
<strong>No affiliation:</strong> we are not affiliated with, endorsed by, or sponsored by
any listed developer; names and logos identify products only (see{' '}
<a href={`${base}/trademarks`}>Trademarks</a>).
</li>
<li>
<strong>No hosting:</strong> we host no installers; all download links lead to third-party
sites we do not control.
</li>
<li>
<strong>No warranty on information:</strong> listings — including pricing, license, platform
availability, and security status — are provided "as is" and may be outdated or wrong;
pricing models change without notice.
</li>
<li>
<strong>Security statuses are not guarantees:</strong> "No known warnings · checked
&lt;date&gt;" means our checklist found nothing <em>on that date</em>; it is not an audit, a
certification, or a promise of safety. Software can be compromised after our check. Always
download from official sources, verify signatures or checksums where offered, and use your
own judgment.
</li>
<li>
<strong>Your risk:</strong> installing third-party software is entirely at your own risk; to
the maximum extent permitted by law we accept no liability for damages arising from software
you obtain via links on this site.
</li>
<li id="report">
<strong>Reporting a listing:</strong> a dangerous one — a hijacked, look-alike or malicious
download link — goes privately to <a href={`mailto:${SECURITY}`}>{SECURITY}</a>, not to a
public issue, so the bad link is not spread further. Outdated or wrong information goes to a{' '}
<a href={ISSUES}>GitHub issue</a>; a developer who wants their entry changed or removed can
write to <a href={`mailto:${TAKEDOWN}`}>{TAKEDOWN}</a>.
</li>
</ol>
</>
) : (
<>
<p>SoftHarbor là trang tổng hợp phần mềm desktop độc lập, phi thương mại.</p>
<ol>
<li>
<strong>Không liên kết:</strong> chúng tôi không liên kết với, không được chứng thực, bảo
trợ hay tài trợ bởi bất kỳ nhà phát triển nào được liệt kê; tên và logo chỉ nhằm nhận diện
sản phẩm (xem <a href={`${base}/trademarks`}>Thương hiệu</a>).
</li>
<li>
<strong>Không lưu trữ:</strong> chúng tôi không lưu trữ tệp cài đặt; mọi liên kết tải về dẫn
tới trang của bên thứ ba ngoài tầm kiểm soát của chúng tôi.
</li>
<li>
<strong>Không bảo đảm thông tin:</strong> thông tin — gồm giá, giấy phép, nền tảng hỗ trợ và
trạng thái bảo mật — được cung cấp "nguyên trạng", có thể lỗi thời hoặc sai; mô hình giá có
thể thay đổi mà không báo trước.
</li>
<li>
<strong>Trạng thái bảo mật không phải bảo chứng:</strong> "Không có cảnh báo đã biết · đã
kiểm tra &lt;ngày&gt;" nghĩa là quy trình kiểm tra của chúng tôi không phát hiện gì{' '}
<em>vào ngày đó</em>; đây không phải là một cuộc kiểm toán, một chứng nhận hay một lời hứa
về an toàn. Phần mềm có thể bị xâm phạm sau thời điểm kiểm tra. Hãy luôn tải từ nguồn chính
thức, xác minh chữ ký hoặc checksum nếu có, và tự cân nhắc.
</li>
<li>
<strong>Rủi ro của bạn:</strong> việc cài đặt phần mềm của bên thứ ba hoàn toàn thuộc rủi ro
của bạn; trong phạm vi tối đa pháp luật cho phép, chúng tôi không chịu trách nhiệm cho thiệt
hại phát sinh từ phần mềm bạn tải qua các liên kết trên trang này.
</li>
<li id="report">
<strong>Báo cáo một mục:</strong> mục nguy hiểm — liên kết tải về bị chiếm quyền, giả mạo
hoặc độc hại — hãy báo riêng tới <a href={`mailto:${SECURITY}`}>{SECURITY}</a>, đừng mở
issue công khai, để liên kết xấu không bị lan rộng thêm. Thông tin lỗi thời hoặc sai hãy báo
qua <a href={ISSUES}>GitHub issue</a>; nhà phát triển muốn sửa hoặc gỡ mục của mình có thể
viết tới <a href={`mailto:${TAKEDOWN}`}>{TAKEDOWN}</a>.
</li>
</ol>
</>
)}
+251 -86
View File
@@ -1,96 +1,261 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/14 §3b. The storage inventory here must stay in step with docs/09 §8.
// docs/14 §3b. The storage inventory here must stay in step with docs/09 §8,
// and the two Cloudflare sections with src/scripts/analytics.js and
// src/lib/turnstile.ts + worker/verify.ts. Section ids are link targets:
// the gate's step 2 links to #turnstile.
import { CONTACTS } from '../../lib/contacts';
import type { Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const CONTACT = 'contact@softharbor.net';
const PRIVACY = CONTACTS.privacy;
---
{
locale === 'en' ? (
<>
<p>
<strong>Short version: we collect nothing.</strong>
</p>
<ol>
<li>
<strong>No accounts, no forms, no analytics, no ads, no cookies.</strong>
</li>
<li>
<strong>Local preferences only:</strong> language, theme, and legal-acceptance version are
stored in your browser's localStorage (<code>sh:lang</code>, <code>sh:theme</code>,{' '}
<code>sh:legal</code>) and never transmitted; clearing site data removes them. A service
worker caches a small offline page.
</li>
<li>
<strong>Infrastructure:</strong> the site is served by Cloudflare, which processes
connection data (such as IP addresses) as a network provider under its own privacy policy.
We do not receive or store this data; aggregate request counts are visible to us in
Cloudflare's dashboard.
</li>
<li>
<strong>Bug reports:</strong> the "Report a bug" button opens a{' '}
<strong>prefilled GitHub issue in your browser</strong> containing the page URL, your
browser/OS string, and recent console error lines from this site. Nothing is sent until
you review and submit it on GitHub, under GitHub's terms and privacy policy.
</li>
<li>
<strong>Third-party links</strong> lead to sites with their own policies.
</li>
<li>
<strong>Changes</strong> to this policy bump the version date and re-show the consent
gate.
</li>
</ol>
<p>
Contact: <a href={`mailto:${CONTACT}`}>{CONTACT}</a>.
</p>
</>
) : (
<>
<p>
<strong>Phiên bản ngắn gọn: chúng tôi không thu thập gì.</strong>
</p>
<ol>
<li>
<strong>
Không tài khoản, không biểu mẫu, không analytics, không quảng cáo, không cookie.
</strong>
</li>
<li>
<strong>Chỉ lưu tuỳ chọn cục bộ:</strong> ngôn ngữ, giao diện sáng/tối và phiên bản điều
khoản đã chấp nhận được lưu trong localStorage của trình duyệt (<code>sh:lang</code>,{' '}
<code>sh:theme</code>, <code>sh:legal</code>), không bao giờ được truyền đi; xoá dữ liệu
trang sẽ xoá chúng. Service worker lưu một trang offline nhỏ.
</li>
<li>
<strong>Hạ tầng:</strong> trang được phục vụ bởi Cloudflare — đơn vị xử lý dữ liệu kết nối
(như địa chỉ IP) theo chính sách riêng của họ với vai trò nhà cung cấp hạ tầng. Chúng tôi
không nhận hay lưu dữ liệu này; chỉ thấy số liệu truy cập tổng hợp trong bảng điều khiển
Cloudflare.
</li>
<li>
<strong>Báo lỗi:</strong> nút "Report a bug" mở một{' '}
<strong>issue GitHub được điền sẵn trong trình duyệt của bạn</strong> gồm URL trang, chuỗi
trình duyệt/hệ điều hành và các dòng lỗi console gần đây của trang này. Không có gì được
gửi đi cho tới khi bạn xem lại và tự đăng trên GitHub, theo điều khoản và chính sách của
GitHub.
</li>
<li>
<strong>Liên kết bên thứ ba</strong> có chính sách riêng.
</li>
<li>
<strong>Thay đổi</strong> chính sách sẽ cập nhật ngày phiên bản và hiển thị lại hộp thoại
chấp nhận.
</li>
</ol>
<p>
Liên hệ: <a href={`mailto:${CONTACT}`}>{CONTACT}</a>.
</p>
</>
)
}
{locale === 'en' ? (
<>
<p>
<strong>Short version:</strong> no accounts, no ads, no cookies, and nothing sold or shared
for advertising. Two Cloudflare services see limited data — visitor statistics that skip you
if your browser sends Global Privacy Control, and a bot check that runs only after you accept
these documents. Your settings stay in your browser.
</p>
<h2 id="who">Who runs this site</h2>
<p>
SoftHarbor is a non-commercial project run by an individual developer, poli0981 (SkullMute),
in Vietnam, who decides how the little data described here is handled. Privacy questions:{' '}
<a href={`mailto:${PRIVACY}`}>{PRIVACY}</a>.
</p>
<h2 id="storage">What stays in your browser</h2>
<p>
These are kept in your browser's localStorage and never sent anywhere; clearing this site's
data removes them:
</p>
<ul>
<li>
<code>sh:legal</code> — the version of these documents you accepted;
</li>
<li>
<code>sh:human</code> — until when the bot check below counts as done;
</li>
<li>
<code>sh:lang</code> — that you answered the language suggestion;
</li>
<li>
<code>sh:theme</code>, <code>sh:scrollbar</code>, <code>sh:motion</code> — your display
choices.
</li>
</ul>
<p>
A service worker also stores the offline page and the site's styles and fonts, so the site
still opens without a connection. There are no cookies.
</p>
<h2 id="analytics">Visitor statistics</h2>
<p>
We use Cloudflare Web Analytics to see which pages are read and how fast they load. It sets no
cookies and stores nothing in your browser. When a page loads, a script from Cloudflare
reports the page address, the address you came from, page-load timings and your browser's
user-agent string; Cloudflare derives a country from your connection and shows us totals only
— we never see individual visits or IP addresses.
</p>
<p>
It does not run at all if your browser sends <strong>Global Privacy Control</strong>, nor on
any host other than softharbor.net. We use it out of a legitimate interest in knowing whether
the site works and is used.
</p>
<h2 id="turnstile">The bot check (Cloudflare Turnstile)</h2>
<p>
After you accept these documents — never before — the gate runs Cloudflare Turnstile once to
tell people from automated traffic. It usually finishes on its own; occasionally it asks for a
click. Turnstile runs in a frame from challenges.cloudflare.com and evaluates signals from
your browser and device; Cloudflare states that it uses them only to tell people from bots,
not to track you or to target advertising.
</p>
<p>
The one-time token it produces is sent to this site's verification endpoint,{' '}
<code>/api/verify</code>, which forwards it — with your IP address — to Cloudflare's
Siteverify service to confirm it. To prevent abuse, the endpoint counts requests per IP
address (per /64 network for IPv6) for one minute. We keep no record of either: the endpoint
logs only whether a check succeeded and how long it took.
</p>
<p>
A pass is remembered in your browser for 48 hours (<code>sh:human</code>). If the check cannot
run — blocked, offline, or our endpoint is down — you are let in anyway, and it is tried again
after an hour. We use it out of a legitimate interest in keeping automated abuse off a public
service.
</p>
<h2 id="hosting">Hosting</h2>
<p>
Cloudflare serves the site and the endpoint above. As a network provider it processes
connection data, such as IP addresses, to deliver and protect the site, under its own privacy
policy. We do not receive those logs; Cloudflare shows us aggregate request counts.
</p>
<h2 id="email">If you email us</h2>
<p>
Addresses at poli0981.dev are delivered to a mailbox hosted by Google. We use your address and
message only to deal with what you wrote, and delete them once they are no longer needed for
that — or sooner, if you ask.
</p>
<h2 id="bug-reports">Bug reports</h2>
<p>
"Report a bug" is a link to a prefilled GitHub issue form. Its address contains the page's
URL, your browser's user-agent string and recent error lines from this site, so{' '}
<strong>GitHub receives them as soon as you open the link</strong>. Nothing is filed until you
review and submit the form, under GitHub's terms and privacy policy — remove anything you
would rather not share first.
</p>
<h2 id="links">Other sites</h2>
<p>Links to developers' sites lead to services with privacy policies of their own.</p>
<h2 id="rights">Your choices and rights</h2>
<p>
Turn on Global Privacy Control to switch the statistics off; block challenges.cloudflare.com
if you prefer — the gate still lets you in. Clearing this site's data removes everything
stored in your browser. We hold nothing that identifies you except email you send; to see,
correct or delete it, or to object to anything here, write to{' '}
<a href={`mailto:${PRIVACY}`}>{PRIVACY}</a>. You may also complain to your data protection
authority.
</p>
<h2 id="changes">Changes</h2>
<p>
When this policy changes, the date above changes with it, and the gate asks everyone to accept
the new version.
</p>
</>
) : (
<>
<p>
<strong>Tóm tắt:</strong> không tài khoản, không quảng cáo, không cookie, và không bán hay
chia sẻ dữ liệu cho quảng cáo. Hai dịch vụ của Cloudflare thấy một ít dữ liệu — thống kê truy
cập sẽ bỏ qua bạn nếu trình duyệt gửi tín hiệu Global Privacy Control, và một bước kiểm tra
bot chỉ chạy sau khi bạn chấp nhận các văn bản này. Các tuỳ chọn của bạn nằm lại trong trình
duyệt.
</p>
<h2 id="who">Ai vận hành trang này</h2>
<p>
SoftHarbor là dự án phi thương mại do một nhà phát triển cá nhân, poli0981 (SkullMute), tại
Việt Nam vận hành; người này quyết định cách xử lý số ít dữ liệu được mô tả ở đây. Câu hỏi về
quyền riêng tư: <a href={`mailto:${PRIVACY}`}>{PRIVACY}</a>.
</p>
<h2 id="storage">Những gì nằm lại trong trình duyệt của bạn</h2>
<p>
Các mục sau được lưu trong localStorage của trình duyệt và không bao giờ được gửi đi; xoá dữ
liệu của trang này sẽ xoá chúng:
</p>
<ul>
<li>
<code>sh:legal</code> — phiên bản các văn bản này mà bạn đã chấp nhận;
</li>
<li>
<code>sh:human</code> — thời điểm bước kiểm tra bot bên dưới hết hiệu lực;
</li>
<li>
<code>sh:lang</code> — việc bạn đã trả lời gợi ý ngôn ngữ;
</li>
<li>
<code>sh:theme</code>, <code>sh:scrollbar</code>, <code>sh:motion</code> — các tuỳ chọn hiển
thị của bạn.
</li>
</ul>
<p>
Service worker cũng lưu trang offline cùng kiểu dáng và phông chữ của trang, để trang vẫn mở
được khi mất kết nối. Không có cookie nào.
</p>
<h2 id="analytics">Thống kê truy cập</h2>
<p>
Chúng tôi dùng Cloudflare Web Analytics để biết trang nào được đọc và tải nhanh đến đâu. Công
cụ này không đặt cookie và không lưu gì trong trình duyệt. Khi một trang tải xong, một đoạn mã
của Cloudflare gửi địa chỉ trang, địa chỉ trang bạn đến từ đó, thời gian tải trang và chuỗi
user-agent của trình duyệt; Cloudflare suy ra quốc gia từ kết nối của bạn và chỉ cho chúng tôi
xem số liệu tổng hợp — chúng tôi không bao giờ thấy từng lượt truy cập hay địa chỉ IP.
</p>
<p>
Công cụ này hoàn toàn không chạy nếu trình duyệt của bạn gửi tín hiệu{' '}
<strong>Global Privacy Control</strong>, và cũng không chạy trên tên miền nào khác
softharbor.net. Chúng tôi dùng nó vì lợi ích chính đáng: biết trang có hoạt động tốt và có
người dùng hay không.
</p>
<h2 id="turnstile">Bước kiểm tra bot (Cloudflare Turnstile)</h2>
<p>
Sau khi bạn chấp nhận các văn bản này — không bao giờ trước đó — cổng chạy Cloudflare
Turnstile một lần để phân biệt người với lưu lượng tự động. Thường nó tự hoàn tất; đôi khi nó
yêu cầu bạn bấm một lần. Turnstile chạy trong một khung từ challenges.cloudflare.com và đánh
giá các tín hiệu từ trình duyệt và thiết bị của bạn; Cloudflare cho biết họ chỉ dùng chúng để
phân biệt người với bot, không để theo dõi bạn hay nhắm quảng cáo.
</p>
<p>
Mã dùng một lần mà nó tạo ra được gửi tới điểm xác minh của trang (<code>/api/verify</code>);
điểm này chuyển mã — kèm địa chỉ IP của bạn — tới dịch vụ Siteverify của Cloudflare để xác
nhận. Để chống lạm dụng, điểm này đếm số yêu cầu theo từng địa chỉ IP (theo dải /64 với IPv6)
trong một phút. Chúng tôi không lưu lại cả hai: điểm xác minh chỉ ghi nhật ký việc kiểm tra
thành công hay không và mất bao lâu.
</p>
<p>
Kết quả đạt được ghi nhớ trong trình duyệt của bạn trong 48 giờ (<code>sh:human</code>). Nếu
bước kiểm tra không chạy được — bị chặn, mất mạng, hoặc điểm xác minh của chúng tôi gặp sự cố
— bạn vẫn được vào trang, và việc kiểm tra sẽ được thử lại sau một giờ. Chúng tôi dùng nó vì
lợi ích chính đáng: giữ cho một dịch vụ công cộng không bị lạm dụng tự động.
</p>
<h2 id="hosting">Lưu trữ và phân phối</h2>
<p>
Cloudflare phục vụ trang web và điểm xác minh nói trên. Với vai trò nhà cung cấp mạng,
Cloudflare xử lý dữ liệu kết nối, như địa chỉ IP, để phân phối và bảo vệ trang, theo chính
sách quyền riêng tư của riêng họ. Chúng tôi không nhận các nhật ký đó; Cloudflare chỉ cho
chúng tôi xem số lượng yêu cầu tổng hợp.
</p>
<h2 id="email">Nếu bạn gửi email cho chúng tôi</h2>
<p>
Thư gửi tới các địa chỉ @poli0981.dev được chuyển vào một hộp thư do Google lưu trữ. Chúng tôi
chỉ dùng địa chỉ và nội dung thư của bạn để giải quyết việc bạn viết, và xoá chúng khi không
còn cần cho việc đó — hoặc sớm hơn, nếu bạn yêu cầu.
</p>
<h2 id="bug-reports">Báo lỗi</h2>
<p>
"Báo lỗi" là liên kết tới một biểu mẫu issue GitHub được điền sẵn. Địa chỉ của liên kết chứa
URL của trang, chuỗi user-agent của trình duyệt và các dòng lỗi gần đây của trang này, nên{' '}
<strong>GitHub nhận được chúng ngay khi bạn mở liên kết</strong>. Không có gì được đăng cho
tới khi bạn xem lại và tự gửi biểu mẫu, theo điều khoản và chính sách quyền riêng tư của
GitHub — hãy xoá những gì bạn không muốn chia sẻ trước khi gửi.
</p>
<h2 id="links">Trang web khác</h2>
<p>
Liên kết tới trang của các nhà phát triển dẫn tới những dịch vụ có chính sách quyền riêng tư
riêng.
</p>
<h2 id="rights">Lựa chọn và quyền của bạn</h2>
<p>
Bật Global Privacy Control để tắt thống kê truy cập; chặn challenges.cloudflare.com nếu bạn
muốn — cổng vẫn cho bạn vào. Xoá dữ liệu của trang sẽ xoá mọi thứ được lưu trong trình duyệt.
Chúng tôi không giữ thông tin nào nhận diện được bạn ngoài email bạn gửi; để xem, sửa hoặc xoá
thông tin đó, hay để phản đối bất kỳ điều gì ở đây, hãy viết tới{' '}
<a href={`mailto:${PRIVACY}`}>{PRIVACY}</a>. Bạn cũng có thể khiếu nại tới cơ quan bảo vệ dữ
liệu có thẩm quyền.
</p>
<h2 id="changes">Thay đổi</h2>
<p>
Khi chính sách này thay đổi, ngày cập nhật ở trên sẽ đổi theo, và cổng sẽ đề nghị mọi người
chấp nhận phiên bản mới.
</p>
</>
)}
+119 -79
View File
@@ -2,90 +2,130 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/14 §3c. Governing law (Vietnam) is a Kokone sign-off item — docs/14 Part 4.
// `#copyright` is the notice-and-takedown procedure the Contact page links to.
import { CONTACTS } from '../../lib/contacts';
import type { Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const CONTACT = 'contact@softharbor.net';
const SITE = 'https://softharbor.net';
const LICENSE_DATA = 'https://github.com/poli0981/softharbor/blob/main/LICENSE-DATA.md';
const { legal: LEGAL, dmca: DMCA, takedown: TAKEDOWN } = CONTACTS;
const base = locale === 'vi' ? '/vi/legal' : '/legal';
---
{
locale === 'en' ? (
<ol>
<li>
<strong>Acceptance:</strong> using <a href={SITE}>{SITE}</a> means you accept these terms,
the Disclaimer, and the Privacy Policy; the consent dialog records acceptance in your
browser.
</li>
<li>
<strong>The service:</strong> an informational directory of links and metadata; no downloads
are hosted; availability is not guaranteed and the service may change or stop at any time.
</li>
<li>
<strong>Acceptable use:</strong> no scraping at abusive rates (the public dataset at{' '}
<a href="/api/apps.json">/api/apps.json</a> exists — use it), no attempts to disrupt the
service, no misrepresentation of SoftHarbor as affiliated with listed vendors.
</li>
<li>
<strong>Intellectual property:</strong> site code is GPL-3.0-only; the dataset is CC BY-SA
4.0 (see LICENSE-DATA); third-party names and logos remain their owners' property.
</li>
<li>
<strong>No warranty / limitation of liability:</strong> the service is provided "as is"
without warranties of any kind; to the maximum extent permitted by law, the operator is not
liable for any damages arising from use of the service or of third-party software reached
through it.
</li>
<li>
<strong>Changes:</strong> material changes bump the version and re-show the consent dialog.
</li>
<li>
<strong>Governing law:</strong> the laws of Vietnam, without regard to conflict-of-law
rules; if a provision is unenforceable, the remainder stands.
</li>
<li>
Contact: <a href={`mailto:${CONTACT}`}>{CONTACT}</a>.
</li>
</ol>
) : (
<ol>
<li>
<strong>Chấp nhận:</strong> việc sử dụng <a href={SITE}>{SITE}</a> đồng nghĩa bạn chấp nhận
các điều khoản này, Tuyên bố miễn trừ và Chính sách quyền riêng tư; hộp thoại đồng ý ghi
nhận việc chấp nhận trong trình duyệt của bạn.
</li>
<li>
<strong>Dịch vụ:</strong> trang thông tin tổng hợp liên kết và siêu dữ liệu; không lưu trữ
tệp tải về; không bảo đảm tính khả dụng; dịch vụ có thể thay đổi hoặc dừng bất kỳ lúc nào.
</li>
<li>
<strong>Sử dụng hợp lệ:</strong> không scrape với tần suất gây hại (đã có bộ dữ liệu công
khai tại <a href="/api/apps.json">/api/apps.json</a> — hãy dùng nó), không phá hoại dịch vụ,
không mạo nhận SoftHarbor liên kết với các nhà phát triển được liệt kê.
</li>
<li>
<strong>Sở hữu trí tuệ:</strong> mã nguồn theo GPL-3.0-only; bộ dữ liệu theo CC BY-SA 4.0
(xem LICENSE-DATA); tên và logo bên thứ ba thuộc chủ sở hữu tương ứng.
</li>
<li>
<strong>Không bảo đảm / giới hạn trách nhiệm:</strong> dịch vụ cung cấp "nguyên trạng" không
kèm bất kỳ bảo đảm nào; trong phạm vi tối đa pháp luật cho phép, người vận hành không chịu
trách nhiệm cho thiệt hại phát sinh từ việc dùng dịch vụ hoặc phần mềm bên thứ ba truy cập
qua dịch vụ.
</li>
<li>
<strong>Thay đổi:</strong> thay đổi trọng yếu sẽ nâng phiên bản và hiển thị lại hộp thoại
đồng ý.
</li>
<li>
<strong>Luật áp dụng:</strong> pháp luật Việt Nam; nếu một điều khoản vô hiệu, các điều
khoản còn lại vẫn giữ hiệu lực.
</li>
<li>
Liên hệ: <a href={`mailto:${CONTACT}`}>{CONTACT}</a>.
</li>
</ol>
)
}
{locale === 'en' ? (
<ol>
<li id="operator">
<strong>Who we are:</strong> <a href={SITE}>{SITE}</a> ("SoftHarbor") is a non-commercial
project run by an individual developer, poli0981 (SkullMute), in Vietnam — "we" or "the
operator" below.
</li>
<li>
<strong>Acceptance:</strong> using the site means you accept these terms, the{' '}
<a href={`${base}/disclaimer`}>Disclaimer</a>, and the{' '}
<a href={`${base}/privacy`}>Privacy Policy</a>; the consent dialog records acceptance in your
browser, then runs the automatic bot check the Privacy Policy describes.
</li>
<li>
<strong>The service:</strong> an informational directory of links and metadata; no downloads
are hosted; availability is not guaranteed and the service may change or stop at any time.
</li>
<li>
<strong>Acceptable use:</strong> no scraping at abusive rates (the public dataset at{' '}
<a href="/api/apps.json">/api/apps.json</a> exists — use it), no attempts to disrupt the
service or to get past its bot check by automated means, no misrepresentation of SoftHarbor as
affiliated with listed vendors.
</li>
<li>
<strong>Intellectual property:</strong> site code is GPL-3.0-only; the dataset is CC BY-SA 4.0
(see <a href={LICENSE_DATA}>LICENSE-DATA</a>); third-party names and logos remain their
owners' property (see <a href={`${base}/trademarks`}>Trademarks</a>).
</li>
<li id="copyright">
<strong>Copyright complaints:</strong> if you believe something on SoftHarbor infringes your
copyright, email <a href={`mailto:${DMCA}`}>{DMCA}</a> with: the work you own; the material
and its address on this site; your name and contact details; a statement that you believe in
good faith the use is not authorised; a statement that the notice is accurate and that you own
the right or may act for its owner; and your signature (a typed full name is enough). We
remove or disable the material promptly and tell whoever added it, who may answer with a
counter-notice to the same address. A developer who wants a listing or logo changed or removed
writes to <a href={`mailto:${TAKEDOWN}`}>{TAKEDOWN}</a> instead.
</li>
<li>
<strong>No warranty / limitation of liability:</strong> the service is provided "as is"
without warranties of any kind; to the maximum extent permitted by law, the operator is not
liable for any damages arising from use of the service or of third-party software reached
through it.
</li>
<li>
<strong>Changes:</strong> material changes bump the version and re-show the consent dialog.
</li>
<li>
<strong>Governing law:</strong> the laws of Vietnam, without regard to conflict-of-law rules;
if a provision is unenforceable, the remainder stands.
</li>
<li>
Contact: <a href={`mailto:${LEGAL}`}>{LEGAL}</a>.
</li>
</ol>
) : (
<ol>
<li id="operator">
<strong>Chúng tôi là ai:</strong> <a href={SITE}>{SITE}</a> ("SoftHarbor") là dự án phi thương
mại do một nhà phát triển cá nhân, poli0981 (SkullMute), tại Việt Nam vận hành — dưới đây gọi
là "chúng tôi" hoặc "người vận hành".
</li>
<li>
<strong>Chấp nhận:</strong> việc sử dụng trang đồng nghĩa bạn chấp nhận các điều khoản này,{' '}
<a href={`${base}/disclaimer`}>Tuyên bố miễn trừ</a> và{' '}
<a href={`${base}/privacy`}>Chính sách quyền riêng tư</a>; hộp thoại đồng ý ghi nhận việc chấp
nhận trong trình duyệt của bạn, rồi chạy bước kiểm tra bot tự động mà Chính sách quyền riêng
tư mô tả.
</li>
<li>
<strong>Dịch vụ:</strong> trang thông tin tổng hợp liên kết và siêu dữ liệu; không lưu trữ tệp
tải về; không bảo đảm tính khả dụng; dịch vụ có thể thay đổi hoặc dừng bất kỳ lúc nào.
</li>
<li>
<strong>Sử dụng hợp lệ:</strong> không scrape với tần suất gây hại (đã có bộ dữ liệu công khai
tại <a href="/api/apps.json">/api/apps.json</a> — hãy dùng nó), không tìm cách phá hoại dịch
vụ hay dùng phương tiện tự động để vượt qua bước kiểm tra bot, không mạo nhận SoftHarbor liên
kết với các nhà phát triển được liệt kê.
</li>
<li>
<strong>Sở hữu trí tuệ:</strong> mã nguồn theo GPL-3.0-only; bộ dữ liệu theo CC BY-SA 4.0 (xem{' '}
<a href={LICENSE_DATA}>LICENSE-DATA</a>); tên và logo của bên thứ ba thuộc chủ sở hữu tương
ứng (xem <a href={`${base}/trademarks`}>Thương hiệu</a>).
</li>
<li id="copyright">
<strong>Khiếu nại bản quyền:</strong> nếu bạn cho rằng nội dung nào đó trên SoftHarbor xâm
phạm bản quyền của bạn, hãy email tới <a href={`mailto:${DMCA}`}>{DMCA}</a>, gồm: tác phẩm bạn
sở hữu; nội dung bị khiếu nại và địa chỉ của nó trên trang này; họ tên và thông tin liên hệ
của bạn; lời khẳng định bạn tin một cách thiện chí rằng việc sử dụng đó chưa được phép; lời
khẳng định thông báo là chính xác và bạn là chủ sở hữu quyền hoặc được phép đại diện chủ sở
hữu; và chữ ký của bạn (gõ đầy đủ họ tên là đủ). Chúng tôi sẽ nhanh chóng gỡ hoặc vô hiệu hoá
nội dung đó và báo cho người đã thêm nó, người này có thể gửi phản hồi phản đối tới cùng địa
chỉ. Nhà phát triển muốn sửa hoặc gỡ mục giới thiệu hay logo của mình thì viết tới{' '}
<a href={`mailto:${TAKEDOWN}`}>{TAKEDOWN}</a>.
</li>
<li>
<strong>Không bảo đảm / giới hạn trách nhiệm:</strong> dịch vụ được cung cấp "nguyên trạng",
không kèm bất kỳ bảo đảm nào; trong phạm vi tối đa pháp luật cho phép, người vận hành không
chịu trách nhiệm cho thiệt hại phát sinh từ việc dùng dịch vụ hoặc phần mềm của bên thứ ba
truy cập qua dịch vụ.
</li>
<li>
<strong>Thay đổi:</strong> thay đổi trọng yếu sẽ nâng phiên bản và hiển thị lại hộp thoại đồng
ý.
</li>
<li>
<strong>Luật áp dụng:</strong> pháp luật Việt Nam, không xét đến quy tắc xung đột pháp luật;
nếu một điều khoản không thể thi hành, các điều khoản còn lại vẫn giữ hiệu lực.
</li>
<li>
Liên hệ: <a href={`mailto:${LEGAL}`}>{LEGAL}</a>.
</li>
</ol>
)}
+89 -23
View File
@@ -2,11 +2,18 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/14 §3e. The Simple Icons caveat is shown verbatim, as the doc requires.
// The package table is generated at build time (src/lib/licenses.ts), so it
// lists what this build was actually made from.
import { CONTACTS } from '../../lib/contacts';
import { productionLicenses } from '../../lib/licenses';
import type { Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const en = locale === 'en';
const COPYRIGHT = CONTACTS.copyright;
const privacy = en ? '/legal/privacy' : '/vi/legal/privacy';
const rows = [
{
@@ -33,43 +40,102 @@ const rows = [
note: { en: 'self-hosted via Fontsource', vi: 'tự lưu trữ qua Fontsource' },
},
];
/** Services that receive requests while you use the site (see the Privacy Policy). */
const services = [
{
name: 'Cloudflare',
what: {
en: 'Hosting and delivery (Workers, Static Assets), the /api/verify endpoint, Web Analytics, and Turnstile.',
vi: 'Lưu trữ và phân phối (Workers, Static Assets), điểm /api/verify, Web Analytics và Turnstile.',
},
policy: 'https://www.cloudflare.com/privacypolicy/',
},
{
name: 'GitHub',
what: {
en: 'The source repository, issues, and the prefilled "Report a bug" form.',
vi: 'Kho mã nguồn, issue và biểu mẫu "Báo lỗi" được điền sẵn.',
},
policy:
'https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement',
},
];
const packages = productionLicenses();
---
<p>
{
locale === 'en'
? 'SoftHarbor is built with open-source software. Runtime and asset dependencies and their licenses:'
: 'SoftHarbor được xây dựng trên phần mềm mã nguồn mở. Các thành phần và giấy phép tương ứng:'
}
{en
? 'SoftHarbor is built with open-source software. Runtime and asset dependencies and their licenses:'
: 'SoftHarbor được xây dựng trên phần mềm mã nguồn mở. Các thành phần và giấy phép tương ứng:'}
</p>
<div class="-mx-4 overflow-x-auto px-4">
<table class="w-full border-collapse text-[var(--text-small)]">
<table class="w-full border-collapse text-small">
<thead>
<tr class="border-sh-border border-b-2 text-left">
<th class="py-2 pr-4">{locale === 'en' ? 'Component' : 'Thành phần'}</th>
<th class="py-2 pr-4">{locale === 'en' ? 'License' : 'Giấy phép'}</th>
<th class="py-2">{locale === 'en' ? 'Note' : 'Ghi chú'}</th>
<th class="py-2 pr-4">{en ? 'Component' : 'Thành phần'}</th>
<th class="py-2 pr-4">{en ? 'License' : 'Giấy phép'}</th>
<th class="py-2">{en ? 'Note' : 'Ghi chú'}</th>
</tr>
</thead>
<tbody>
{
rows.map((r) => (
<tr class="border-sh-border border-b opacity-95">
<td class="py-2 pr-4 align-top">{r.component}</td>
<td class="py-2 pr-4 align-top font-mono whitespace-nowrap">{r.license}</td>
<td class="text-sh-muted py-2 align-top">{r.note[locale]}</td>
</tr>
))
}
{rows.map((r) => (
<tr class="border-sh-border border-b opacity-95">
<td class="py-2 pr-4 align-top">{r.component}</td>
<td class="py-2 pr-4 align-top font-mono whitespace-nowrap">{r.license}</td>
<td class="text-sh-muted py-2 align-top">{r.note[locale]}</td>
</tr>
))}
</tbody>
</table>
</div>
<h2 id="services">{en ? 'Services' : 'Dịch vụ'}</h2>
<p>
{en
? 'These services receive requests while you use the site. What each one sees is set out in the '
: 'Các dịch vụ sau nhận yêu cầu khi bạn dùng trang. Mỗi dịch vụ thấy những gì được nêu trong '}
<a href={privacy}>{en ? 'Privacy Policy' : 'Chính sách quyền riêng tư'}</a>.
</p>
<ul>
{services.map((s) => (
<li>
<strong>{s.name}</strong> — {s.what[locale]}{' '}
<a href={s.policy}>{en ? 'Its privacy policy' : 'Chính sách quyền riêng tư của họ'}</a>.
</li>
))}
</ul>
<h2 id="packages">{en ? 'Every package in this build' : 'Mọi gói trong bản dựng này'}</h2>
<p class="text-sh-muted">
{en
? 'Generated when the site is built, from package.json and the installed packages, so it always matches the code you are looking at.'
: 'Được tạo tự động mỗi lần dựng trang, từ package.json và các gói đã cài, nên luôn khớp với mã nguồn bạn đang xem.'}
</p>
<div class="-mx-4 overflow-x-auto px-4">
<table class="w-full border-collapse text-small">
<thead>
<tr class="border-sh-border border-b-2 text-left">
<th class="py-2 pr-4">{en ? 'Package' : 'Gói'}</th>
<th class="py-2 pr-4">{en ? 'Version' : 'Phiên bản'}</th>
<th class="py-2">{en ? 'License' : 'Giấy phép'}</th>
</tr>
</thead>
<tbody>
{packages.map((p) => (
<tr class="border-sh-border border-b opacity-95">
<td class="py-2 pr-4 align-top font-mono">{p.name}</td>
<td class="py-2 pr-4 align-top font-mono">{p.version}</td>
<td class="py-2 align-top font-mono whitespace-nowrap">{p.license}</td>
</tr>
))}
</tbody>
</table>
</div>
<p class="text-sh-muted">
{
locale === 'en'
? 'A full machine-generated dependency list is regenerated each release.'
: 'Danh sách phụ thuộc đầy đủ được tạo tự động mỗi bản phát hành.'
}
{en ? 'Questions about licensing: ' : 'Câu hỏi về giấy phép: '}
<a href={`mailto:${COPYRIGHT}`}>{COPYRIGHT}</a>.
</p>
+46 -47
View File
@@ -3,57 +3,56 @@
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/14 §3d. The logo-handling rules here are the ones src/lib/icon.ts and
// the Simple Icons caveat in §3e depend on.
import { CONTACTS } from '../../lib/contacts';
import type { Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const CONTACT = 'contact@softharbor.net';
const TAKEDOWN = CONTACTS.takedown;
const ISSUES = 'https://github.com/poli0981/softharbor/issues';
---
{
locale === 'en' ? (
<>
<p>
All product names, brands, and logos on SoftHarbor are trademarks or registered trademarks
of their respective owners. They are used solely for{' '}
<strong>nominative identification</strong> — to state truthfully which software an entry
describes — which does not imply affiliation, sponsorship, or endorsement in either
direction.
</p>
<h2>Logo handling rules we hold ourselves to</h2>
<p>
Logos are shown unmodified (no recoloring beyond monochrome rendering of vector marks, no
distortion), at reasonable UI sizes, next to accurate information, sourced from the Simple
Icons set or the vendor's official brand assets. "SoftHarbor" and the SoftHarbor wordmark
identify this project.
</p>
<h2>Takedown</h2>
<p>
If you own a mark and want its use changed or removed, email{' '}
<a href={`mailto:${CONTACT}`}>{CONTACT}</a> or open a GitHub issue — we comply promptly and
remove the entry's logo (or the entry) while discussing.
</p>
</>
) : (
<>
<p>
Mọi tên sản phẩm, thương hiệu và logo trên SoftHarbor là nhãn hiệu hoặc nhãn hiệu đã đăng ký
của chủ sở hữu tương ứng, chỉ được dùng nhằm <strong>nhận diện đúng sản phẩm</strong> mà mục
tương ứng mô tả — không hàm ý liên kết, tài trợ hay chứng thực theo bất kỳ chiều nào.
</p>
<h2>Nguyên tắc với logo</h2>
<p>
Hiển thị nguyên bản (không đổi màu ngoài việc render đơn sắc với logo vector, không biến
dạng), ở kích thước hợp lý, đi kèm thông tin chính xác, lấy từ bộ Simple Icons hoặc bộ nhận
diện chính thức của nhà phát triển. "SoftHarbor" và wordmark SoftHarbor nhận diện dự án này.
</p>
<h2>Yêu cầu gỡ bỏ</h2>
<p>
Nếu bạn là chủ sở hữu nhãn hiệu và muốn thay đổi hoặc gỡ việc sử dụng, hãy email{' '}
<a href={`mailto:${CONTACT}`}>{CONTACT}</a> hoặc mở GitHub issue — chúng tôi sẽ xử lý nhanh
chóng và tạm gỡ logo (hoặc mục liên quan) trong quá trình trao đổi.
</p>
</>
)
}
{locale === 'en' ? (
<>
<p>
All product names, brands, and logos on SoftHarbor are trademarks or registered trademarks of
their respective owners. They are used solely for <strong>nominative identification</strong> —
to state truthfully which software an entry describes — which does not imply affiliation,
sponsorship, or endorsement in either direction.
</p>
<h2>Logo handling rules we hold ourselves to</h2>
<p>
Logos are shown unmodified (no recoloring beyond monochrome rendering of vector marks, no
distortion), at reasonable UI sizes, next to accurate information, sourced from the Simple
Icons set or the vendor's official brand assets. "SoftHarbor" and the SoftHarbor wordmark
identify this project.
</p>
<h2 id="takedown">Takedown</h2>
<p>
If you own a mark and want its use changed or removed, email{' '}
<a href={`mailto:${TAKEDOWN}`}>{TAKEDOWN}</a> or open a <a href={ISSUES}>GitHub issue</a> — we
comply promptly and remove the entry's logo (or the entry) while we discuss it.
</p>
</>
) : (
<>
<p>
Mọi tên sản phẩm, thương hiệu và logo trên SoftHarbor là nhãn hiệu hoặc nhãn hiệu đã đăng ký
của chủ sở hữu tương ứng, chỉ được dùng nhằm <strong>nhận diện đúng sản phẩm</strong> mà mục
tương ứng mô tả — không hàm ý liên kết, tài trợ hay chứng thực theo bất kỳ chiều nào.
</p>
<h2>Nguyên tắc với logo</h2>
<p>
Hiển thị nguyên bản (không đổi màu ngoài việc hiển thị đơn sắc với logo vector, không biến
dạng), ở kích thước hợp lý, đi kèm thông tin chính xác, lấy từ bộ Simple Icons hoặc bộ nhận
diện chính thức của nhà phát triển. "SoftHarbor" và wordmark SoftHarbor nhận diện dự án này.
</p>
<h2 id="takedown">Yêu cầu gỡ bỏ</h2>
<p>
Nếu bạn là chủ sở hữu nhãn hiệu và muốn thay đổi hoặc gỡ việc sử dụng, hãy email tới{' '}
<a href={`mailto:${TAKEDOWN}`}>{TAKEDOWN}</a> hoặc mở <a href={ISSUES}>GitHub issue</a> —
chúng tôi đáp ứng kịp thời và gỡ logo của mục (hoặc cả mục) trong khi trao đổi.
</p>
</>
)}
+190 -91
View File
@@ -2,10 +2,16 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/06 §5 — detail page. Shared by /apps/[slug] and /vi/apps/[slug].
// Hero (logo, name, price, summary) → the official links, Download loudest →
// the facts in a ruled ledger → what the security line means → neighbours
// from the same category.
import type { CollectionEntry } from 'astro:content';
import { getEntry } from 'astro:content';
import { getCollection, getEntry } from 'astro:content';
import Base from '../../layouts/Base.astro';
import ShAppCard from '../ShAppCard.astro';
import ShIcon from '../ShIcon.astro';
import ShJsonLd from '../ShJsonLd.astro';
import { compareNames } from '../../lib/filter';
import { logoSvg } from '../../lib/logo';
import { localePath, t, type Locale } from '../../i18n';
@@ -21,18 +27,33 @@ const d = app.data;
const [primaryRef] = d.categories;
const primary = primaryRef ? await getEntry('categories', primaryRef.id) : undefined;
const RELATED = 4;
const related = primary
? (await getCollection('apps'))
.filter((a) => a.id !== app.id && a.data.categories.some((c) => c.id === primary.id))
.sort((a, b) => compareNames(a.data.name, b.data.name))
.slice(0, RELATED)
: [];
const dateFmt = new Intl.DateTimeFormat(locale === 'vi' ? 'vi-VN' : 'en-GB', {
dateStyle: 'medium',
timeZone: 'UTC',
});
const fmt = (iso: string) => dateFmt.format(new Date(`${iso}T00:00:00Z`));
const security =
d.security.status === 'clean'
? `${t(locale, 'card.security.clean')} · ${t(locale, 'card.checked', { date: fmt(d.security.checkedAt) })}`
: `${t(locale, 'card.security.unverified')} · ${t(locale, 'card.listed', { date: fmt(d.addedAt) })}`;
const clean = d.security.status === 'clean';
const security = clean
? `${t(locale, 'card.security.clean')} · ${t(locale, 'card.checked', { date: fmt(d.security.checkedAt) })}`
: `${t(locale, 'card.security.unverified')} · ${t(locale, 'card.listed', { date: fmt(d.addedAt) })}`;
const priceTone = {
free: 'sh-tone-ok',
'free-onetime': 'sh-tone-accent',
onetime: 'sh-tone-warn',
}[d.pricing];
interface MetaRow {
icon: string;
label: string;
value: string;
/** Outbound link for the row. Only the security row uses it, to reach the
@@ -43,18 +64,26 @@ interface MetaRow {
}
const meta: MetaRow[] = [
{ icon: 'user-round', label: t(locale, 'detail.developer'), value: d.developer },
{
icon: 'monitor',
label: t(locale, 'detail.platforms'),
value: d.platforms.map((p) => t(locale, `platform.${p}`)).join(' · '),
},
...(d.tags.length ? [{ label: t(locale, 'detail.tags'), value: d.tags.join(' · ') }] : []),
...(d.license ? [{ icon: 'scale', label: t(locale, 'detail.license'), value: d.license }] : []),
...(d.tags.length
? [{ icon: 'tags', label: t(locale, 'detail.tags'), value: d.tags.join(' · ') }]
: []),
{
icon: clean ? 'shield-check' : 'shield-question',
label: t(locale, 'detail.security'),
value: security,
...(d.security.evidence ? { href: d.security.evidence } : {}),
},
{ label: t(locale, 'detail.added'), value: fmt(d.addedAt) },
...(d.updatedAt ? [{ label: t(locale, 'detail.updated'), value: fmt(d.updatedAt) }] : []),
{ icon: 'calendar-plus', label: t(locale, 'detail.added'), value: fmt(d.addedAt) },
...(d.updatedAt
? [{ icon: 'calendar-clock', label: t(locale, 'detail.updated'), value: fmt(d.updatedAt) }]
: []),
];
---
@@ -65,98 +94,168 @@ const meta: MetaRow[] = [
{app}
categoryLabelEn={primary?.data.label.en}
/>
<nav aria-label="Breadcrumb" class="text-sh-muted text-[var(--text-small)]">
<a href={localePath(locale, '/apps')} class="hover:underline">{t(locale, 'apps.title')}</a>
<span aria-hidden="true"> / </span>
{
primary && (
<a href={localePath(locale, `/categories/${primary.id}`)} class="hover:underline">
{primary.data.label[locale]}
<nav aria-label={t(locale, 'nav.breadcrumb')} class="text-sh-muted text-small">
<ol class="flex flex-wrap items-center gap-1.5">
<li>
<a href={localePath(locale, '/apps')} class="hover:underline">
{t(locale, 'apps.title')}
</a>
)
}
</li>
{primary && (
<li class="flex items-center gap-1.5">
<ShIcon name="chevron-right" class="size-3.5" />
<a href={localePath(locale, `/categories/${primary.id}`)} class="hover:underline">
{primary.data.label[locale]}
</a>
</li>
)}
<li class="flex items-center gap-1.5" aria-current="page">
<ShIcon name="chevron-right" class="size-3.5" />
<span class="text-sh-ink">{d.name}</span>
</li>
</ol>
</nav>
{
/* No `transition:name` here. Astro generates a per-slug <style> for it and
{/* No `transition:name` here. Astro generates a per-slug <style> for it and
does not add that style's hash to the page's own CSP, so the browser
refused it on every hard load and every ClientRouter swap — the one
console error left after D20. Nothing was lost by removing it: a morph
needs the same name on both sides and ShAppCard never carried one, so it
had never animated. See docs/06 §7. */
}
<header class="mt-4 flex items-start gap-4">
<Fragment
set:html={logoSvg(d.logo, d.name, {
class: 'size-16 shrink-0',
'aria-hidden': 'true',
fill: 'currentColor',
})}
/>
<div>
<h1 class="text-[length:var(--text-h1)] font-semibold">{d.name}</h1>
<p class="text-sh-muted">
<span class="font-mono text-[var(--text-badge)]">{t(locale, 'detail.developer')}:</span>
{d.developer}
</p>
<p class="mt-2 flex flex-wrap gap-2">
<span class="sh-pill">{t(locale, `pricing.${d.pricing}`)}</span>
{d.license && <span class="sh-pill">{d.license}</span>}
</p>
refused it on every load — see docs/06 §7. */}
<section class="sh-panel sh-rise mt-5 p-6 md:p-8">
<div class="flex flex-wrap items-start gap-5">
<span class="sh-tile size-20">
<Fragment
set:html={logoSvg(d.logo, d.name, {
class: 'size-12',
'aria-hidden': 'true',
fill: 'currentColor',
})}
/>
</span>
<div class="min-w-0 flex-1">
<h1 class="text-[length:var(--text-h1)] font-semibold">{d.name}</h1>
<p class="text-sh-muted mt-1">{d.developer}</p>
<p class="mt-3 flex flex-wrap gap-2">
<span class:list={['sh-pill', priceTone]}>{t(locale, `pricing.${d.pricing}`)}</span>
{d.license && <span class="sh-pill">{d.license}</span>}
</p>
</div>
</div>
</header>
<p class="mt-6 max-w-2xl text-[length:var(--text-h3)]">{d.summary[locale]}</p>
<p class="mt-6 max-w-3xl text-[length:var(--text-h3)] leading-relaxed">{d.summary[locale]}</p>
{/* Link rail — Download is the page's one loud element (docs/06 §5). */}
<div class="mt-8 flex flex-wrap gap-3">
<a
href={d.links.homepage}
rel="noopener"
class="sh-lift border-sh-border rounded-[var(--radius-card)] border-2 px-4 py-3"
>{t(locale, 'detail.homepage')} ↗</a
>
{
d.links.repo && (
<a
href={d.links.repo}
rel="noopener"
class="sh-lift border-sh-border rounded-[var(--radius-card)] border-2 px-4 py-3"
>
{t(locale, 'detail.repo')} ↗
{/* Link rail — Download is the page's one loud element (docs/06 §5). */}
<div class="mt-7 flex flex-wrap gap-3">
<a href={d.links.download} rel="noopener" class="sh-btn sh-btn-primary sh-anim">
<ShIcon name="download" class="size-[18px]" motion="pop" />
{t(locale, 'detail.download')}
<ShIcon name="arrow-up-right" class="size-4" motion="nudge-diag" />
</a>
<a href={d.links.homepage} rel="noopener" class="sh-btn sh-anim">
<ShIcon name="globe" class="size-[18px]" motion="pop" />
{t(locale, 'detail.homepage')}
<ShIcon name="arrow-up-right" class="size-4" motion="nudge-diag" />
</a>
{d.links.repo && (
<a href={d.links.repo} rel="noopener" class="sh-btn sh-anim">
<ShIcon name="code-xml" class="size-[18px]" motion="pop" />
{t(locale, 'detail.repo')}
<ShIcon name="arrow-up-right" class="size-4" motion="nudge-diag" />
</a>
)
}
<a
href={d.links.download}
rel="noopener"
class="sh-lift bg-sh-accent text-sh-accent-ink border-sh-border rounded-[var(--radius-card)] border-2 px-4 py-3 font-medium"
>{t(locale, 'detail.download')} ↗</a
)}
</div>
<p class="text-sh-muted mt-4 flex items-center gap-1.5 text-small">
<ShIcon name="badge-check" class="text-sh-accent size-4 shrink-0" />
{t(locale, 'detail.officialNote')}
</p>
</section>
<div class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-[1.4fr_1fr]">
<section class="sh-panel p-6" aria-labelledby="sh-facts">
<h2 id="sh-facts" class="sh-eyebrow">
{t(locale, 'detail.facts')}
</h2>
<dl class="mt-3">
{meta.map((row) => (
<div class="sh-fact">
<dt class="text-sh-muted flex items-center gap-2">
<ShIcon name={row.icon} class="size-4 shrink-0" />
{row.label}
</dt>
<dd class="font-mono text-small">
{row.value}
{row.href && (
<>
{' · '}
<a
href={row.href}
rel="noopener"
class="sh-anim text-sh-accent inline-flex items-center gap-0.5 underline"
>
{t(locale, 'detail.evidence')}
<ShIcon name="arrow-up-right" class="size-3.5" motion="nudge-diag" />
</a>
</>
)}
</dd>
</div>
))}
</dl>
</section>
<aside
class:list={[
'sh-panel p-6',
clean ? 'bg-sh-ok-soft border-transparent' : 'bg-sh-warn-soft border-transparent',
]}
aria-labelledby="sh-status"
>
<h2 id="sh-status" class="flex items-center gap-2 font-semibold">
<ShIcon
name={clean ? 'shield-check' : 'shield-question'}
class={`size-5 ${clean ? 'text-sh-ok' : 'text-sh-warn'}`}
/>
{t(locale, 'detail.securityNote.title')}
</h2>
<p class="mt-3 text-small leading-relaxed">
{t(locale, clean ? 'detail.securityNote.clean' : 'detail.securityNote.unverified')}
</p>
<a
href={localePath(locale, '/legal/disclaimer')}
class="sh-anim mt-4 inline-flex items-center gap-1 text-small font-medium underline"
>
{t(locale, 'detail.disclaimerLink')}
<ShIcon name="arrow-right" class="size-4" motion="nudge-x" />
</a>
</aside>
</div>
<dl class="sh-panel mt-8 grid max-w-2xl gap-2 p-5 font-mono text-[var(--text-badge)]">
{
meta.map((row) => (
<div class="flex flex-wrap gap-x-3">
<dt class="text-sh-muted min-w-28">{row.label}</dt>
<dd>
{row.value}
{row.href && (
<>
{' · '}
<a href={row.href} rel="noopener" class="underline">
{t(locale, 'detail.evidence')} ↗
</a>
</>
)}
</dd>
</div>
))
}
</dl>
<p class="text-sh-muted mt-6 max-w-2xl text-[var(--text-small)]">
{t(locale, 'detail.officialNote')}
</p>
{primary && related.length > 0 && (
<section class="mt-14" aria-labelledby="sh-related">
<h2 id="sh-related" class="text-[length:var(--text-h2)] font-semibold">
{t(locale, 'detail.related', { category: primary.data.label[locale] })}
</h2>
<div class="mt-5 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{related.map((r) => (
<ShAppCard app={r} {locale} headingLevel={3} />
))}
</div>
</section>
)}
</Base>
<style>
.sh-fact {
display: grid;
grid-template-columns: minmax(8rem, 11rem) 1fr;
gap: 0.25rem 1rem;
padding: 0.65rem 0;
border-bottom: 1px dashed var(--sh-border);
}
.sh-fact:last-child {
border-bottom: 0;
}
@media (width < 30rem) {
.sh-fact {
grid-template-columns: 1fr;
}
}
</style>
+52 -24
View File
@@ -2,22 +2,38 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/06 §5 — grid + toolbar. The grid is server-rendered with ALL apps,
// unfiltered: the islands hide cards by toggling [hidden] and reorder with CSS
// `order`, so the no-JS experience stays whole (docs/03 §8, docs/05 §A3).
// unfiltered: the islands hide cards by toggling [hidden] and reorder the
// card nodes, so the no-JS experience stays whole (docs/03 §8, docs/05 §A3).
import { getCollection } from 'astro:content';
import Base from '../../layouts/Base.astro';
import ShAppCard from '../ShAppCard.astro';
import ShSearch from '../islands/ShSearch.svelte';
import ShFilterSheet from '../islands/ShFilterSheet.svelte';
import { byAddedDesc } from '../../lib/paths';
import { t, type Locale } from '../../i18n';
import { sortCards } from '../../lib/filter';
import { appCount, t, type Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const apps = (await getCollection('apps')).sort(byAddedDesc);
// Server order == the client's default order (A–Z, same comparator), so
// hydration never reshuffles the grid. It used to render newest-first while
// the client defaulted to A–Z — invisible only because every entry shares one
// addedAt; the first entry with a different date would have moved 326 cards.
const all = await getCollection('apps');
const bySlug = new Map(all.map((a) => [a.id, a]));
const apps = sortCards(
all.map((a) => ({
slug: a.id,
name: a.data.name,
categories: a.data.categories.map((c) => c.id),
platforms: a.data.platforms,
pricing: a.data.pricing,
added: a.data.addedAt,
})),
'name',
).flatMap((c) => bySlug.get(c.slug) ?? []);
const categories = (await getCollection('categories')).sort((a, b) => a.data.order - b.data.order);
const nf = new Intl.NumberFormat(locale === 'vi' ? 'vi-VN' : 'en-GB');
@@ -35,29 +51,37 @@ const facetOptions = {
};
---
<Base title={`${t(locale, 'apps.title')} — ${t(locale, 'site.name')}`} {locale}>
<h1 class="text-[length:var(--text-h1)] font-semibold">{t(locale, 'apps.title')}</h1>
<Base
title={`${t(locale, 'apps.title')} — ${t(locale, 'site.name')}`}
description={t(locale, 'meta.apps', { n: nf.format(apps.length) })}
{locale}
>
<p class="sh-eyebrow">{t(locale, 'welcome.manifest')}</p>
<h1 class="mt-2 text-[length:var(--text-h1)] font-semibold">{t(locale, 'apps.title')}</h1>
<p class="text-sh-muted mt-2 max-w-2xl">{t(locale, 'apps.intro')}</p>
{/* client:idle — the grid is readable without either island (docs/02 §5). */}
<div class="mt-6 flex flex-wrap items-center gap-3">
<div class="min-w-0 flex-1">
{/* client:idle — the grid is readable without either island (docs/02 §5).
#search is where the welcome page's search field points. */}
<div id="search" class="mt-6 flex scroll-mt-24 flex-wrap items-center gap-3">
<div class="min-w-0 flex-1 basis-full sm:basis-0">
<ShSearch
client:idle
placeholder={t(locale, 'search.placeholder')}
label={t(locale, 'search.label')}
loadingLabel={t(locale, 'search.loading')}
errorLabel={t(locale, 'search.error')}
sortLabel={t(locale, 'sort.label')}
sortName={t(locale, 'sort.name')}
sortAdded={t(locale, 'sort.added')}
sortRelevance={t(locale, 'sort.relevance')}
/>
</div>
<ShFilterSheet
client:idle
openLabel={t(locale, 'filters.open')}
closeLabel={t(locale, 'filters.close')}
clearLabel={t(locale, 'filters.clear')}
showLabel={t(locale, 'filters.show')}
showLabelOne={t(locale, 'filters.show.one')}
headings={{
categories: t(locale, 'filters.categories'),
platforms: t(locale, 'filters.platforms'),
@@ -67,28 +91,32 @@ const facetOptions = {
/>
</div>
{
/*
{/*
Server-rendered with the true total so a no-JS visitor sees a correct
number; the grid controller rewrites it from data-count-template, which is
how the island stays locale-agnostic (docs/07 §3).
*/
}
number; the grid controller rewrites it from the per-plural templates,
which is how the island stays locale-agnostic (docs/07 §3).
*/}
<p
id="sh-count"
class="text-sh-muted mt-6 font-mono text-[var(--text-badge)]"
class="text-sh-muted text-badge mt-6 font-mono"
aria-live="polite"
data-count-template={t(locale, 'apps.count', { n: '{n}' })}
data-count-one={t(locale, 'apps.count.one', { n: '{n}' })}
data-count-other={t(locale, 'apps.count', { n: '{n}' })}
>
{t(locale, 'apps.count', { n: nf.format(apps.length) })}
{appCount(locale, apps.length)}
</p>
<div id="sh-grid" class="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{apps.map((app) => <ShAppCard {app} {locale} />)}
<div
id="sh-grid"
class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
>
{apps.map((app) => (
<ShAppCard {app} {locale} />
))}
</div>
{/* Hidden until filtering actually yields nothing (docs/06 §5). */}
<p id="sh-empty" class="sh-panel text-sh-muted mt-8 p-6" hidden={apps.length > 0}>
{t(locale, 'apps.empty')}
<p id="sh-empty" class="sh-panel text-sh-muted mt-8 p-6" hidden>
{t(locale, 'apps.noResults')}
</p>
</Base>
+51 -36
View File
@@ -1,12 +1,13 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// Category index. The header has always linked here (docs/06 §4); until M2 the
// link 404'd.
// Category index — one tile per category: its icon, its name, how many apps,
// and the first few names, so the tile says what is inside before a click.
import { getCollection } from 'astro:content';
import Base from '../../layouts/Base.astro';
import { iconSvg } from '../../lib/icon';
import { localePath, t, type Locale } from '../../i18n';
import ShIcon from '../ShIcon.astro';
import { compareNames } from '../../lib/filter';
import { appCount, localePath, t, type Locale } from '../../i18n';
interface Props {
locale: Locale;
@@ -15,44 +16,58 @@ const { locale } = Astro.props;
const categories = (await getCollection('categories')).sort((a, b) => a.data.order - b.data.order);
const apps = await getCollection('apps');
const countFor = (id: string) =>
apps.filter((a) => a.data.categories.some((c) => c.id === id)).length;
const inCategory = (id: string) =>
apps
.filter((a) => a.data.categories.some((c) => c.id === id))
.sort((a, b) => compareNames(a.data.name, b.data.name));
const SAMPLE = 3;
---
<Base title={`${t(locale, 'categories.title')} — ${t(locale, 'site.name')}`} {locale}>
<h1 class="text-[length:var(--text-h1)] font-semibold">{t(locale, 'categories.title')}</h1>
<Base
title={`${t(locale, 'categories.title')} — ${t(locale, 'site.name')}`}
description={t(locale, 'meta.categories')}
{locale}
>
<p class="sh-eyebrow">{t(locale, 'welcome.manifest')}</p>
<h1 class="mt-2 text-[length:var(--text-h1)] font-semibold">{t(locale, 'categories.title')}</h1>
<p class="text-sh-muted mt-2 max-w-2xl">{t(locale, 'categories.intro')}</p>
<ul class="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{
categories.map((c) => (
<li class="sh-panel sh-lift relative p-5">
<div class="flex items-center gap-3">
<Fragment
set:html={iconSvg(`lucide:${c.data.icon}`, {
class: 'size-6 shrink-0',
'aria-hidden': 'true',
})}
<ul class="sh-stagger mt-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{categories.map((c) => {
const members = inCategory(c.id);
return (
<li class="sh-panel sh-lift sh-anim relative flex flex-col gap-4 p-5">
<div class="flex items-center gap-4">
<span class="sh-tile text-sh-accent size-12">
<ShIcon name={c.data.icon} class="size-6" motion="pop" />
</span>
<div class="min-w-0">
<h2 class="text-[length:var(--text-h3)] font-semibold">
<a href={localePath(locale, `/categories/${c.id}`)} class="sh-stretch">
{c.data.label[locale]}
</a>
</h2>
<p class="sh-eyebrow mt-0.5 normal-case tracking-normal">
{appCount(locale, members.length)}
</p>
</div>
<ShIcon
name="arrow-right"
class="text-sh-muted ml-auto size-4 shrink-0"
motion="nudge-x"
/>
<h2 class="text-[length:var(--text-h3)] font-semibold">
<a href={localePath(locale, `/categories/${c.id}`)} class="sh-stretch">
{c.data.label[locale]}
</a>
</h2>
</div>
<p class="text-sh-muted mt-2 font-mono text-[var(--text-badge)]">
{t(locale, 'apps.count', { n: countFor(c.id) })}
</p>
{members.length > 0 && (
<p class="text-sh-muted border-sh-border border-t border-dashed pt-3 text-small">
{members
.slice(0, SAMPLE)
.map((a) => a.data.name)
.join(' · ')}
{members.length > SAMPLE && ' …'}
</p>
)}
</li>
))
}
);
})}
</ul>
</Base>
<style>
.sh-stretch::after {
content: '';
position: absolute;
inset: 0;
}
</style>
+31 -19
View File
@@ -7,7 +7,8 @@ import { getCollection } from 'astro:content';
import Base from '../../layouts/Base.astro';
import ShAppCard from '../ShAppCard.astro';
import { byAddedDesc } from '../../lib/paths';
import { localePath, t, type Locale } from '../../i18n';
import ShIcon from '../ShIcon.astro';
import { appCount, localePath, t, type Locale } from '../../i18n';
interface Props {
category: CollectionEntry<'categories'>;
@@ -23,27 +24,38 @@ const label = category.data.label[locale];
const count = new Intl.NumberFormat(locale === 'vi' ? 'vi-VN' : 'en-GB').format(apps.length);
---
<Base title={`${label} — ${t(locale, 'site.name')}`} {locale}>
<nav aria-label="Breadcrumb" class="text-sh-muted text-[var(--text-small)]">
<a href={localePath(locale, '/categories')} class="hover:underline">
<Base
title={`${label} — ${t(locale, 'site.name')}`}
description={t(locale, 'meta.category', { n: count, label })}
{locale}
>
<nav aria-label={t(locale, 'nav.breadcrumb')} class="text-sh-muted text-small">
<a
href={localePath(locale, '/categories')}
class="sh-anim inline-flex items-center gap-1 hover:underline"
>
<ShIcon name="arrow-left" class="size-4" />
{t(locale, 'categories.title')}
</a>
</nav>
<h1 class="mt-4 text-[length:var(--text-h1)] font-semibold">{label}</h1>
<p class="text-sh-muted mt-2 font-mono text-[var(--text-badge)]">
{t(locale, 'apps.count', { n: count })}
</p>
<div class="mt-5 flex items-center gap-4">
<span class="sh-tile bg-sh-accent-soft text-sh-accent size-14 border-transparent">
<ShIcon name={category.data.icon} class="size-7" />
</span>
<div>
<h1 class="text-[length:var(--text-h1)] font-semibold">{label}</h1>
<p class="sh-eyebrow mt-1 normal-case tracking-normal">{appCount(locale, apps.length)}</p>
</div>
</div>
{
apps.length === 0 ? (
<p class="sh-panel text-sh-muted mt-8 p-6">{t(locale, 'apps.empty')}</p>
) : (
<div class="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{apps.map((app) => (
<ShAppCard {app} {locale} />
))}
</div>
)
}
{apps.length === 0 ? (
<p class="sh-panel text-sh-muted mt-8 p-6">{t(locale, 'categories.empty')}</p>
) : (
<div class="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{apps.map((app) => (
<ShAppCard {app} {locale} />
))}
</div>
)}
</Base>
+86
View File
@@ -0,0 +1,86 @@
---
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// /contact and /vi/contact (D27): one address per purpose, all reaching the
// one maintainer. Exempt from the legal gate — a copyright or security notice
// must never wait behind "I understand and accept".
import Base from '../../layouts/Base.astro';
import ShIcon from '../ShIcon.astro';
import { CONTACTS } from '../../lib/contacts';
import { localePath, t, type Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const ISSUES = 'https://github.com/poli0981/softharbor/issues/new/choose';
/** Order is urgency: what can hurt someone first, press and collaboration last. */
const rows = [
{ key: 'security', icon: 'shield-alert' },
{ key: 'privacy', icon: 'eye-off' },
{ key: 'dmca', icon: 'copyright', more: '/legal/terms#copyright' },
{ key: 'takedown', icon: 'flag' },
{ key: 'legal', icon: 'scale' },
{ key: 'copyright', icon: 'scroll-text' },
{ key: 'conduct', icon: 'handshake' },
{ key: 'press', icon: 'newspaper' },
{ key: 'collab', icon: 'sparkles' },
] as const;
---
<Base
title={`${t(locale, 'contact.title')} — ${t(locale, 'site.name')}`}
description={t(locale, 'meta.contact')}
{locale}
gateExempt
>
<p class="sh-eyebrow">{t(locale, 'site.name')}</p>
<h1 class="mt-2 text-[length:var(--text-h1)] font-semibold">{t(locale, 'contact.title')}</h1>
<p class="text-sh-muted mt-3 max-w-2xl">{t(locale, 'contact.intro')}</p>
<ul class="sh-stagger mt-8 grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
{rows.map((row) => {
const address = CONTACTS[row.key];
return (
<li class="sh-panel flex gap-4 p-5">
<span class="sh-tile text-sh-accent size-11">
<ShIcon name={row.icon} class="size-5" />
</span>
<div class="min-w-0">
<p class="font-medium">{t(locale, `contact.${row.key}`)}</p>
<a
href={`mailto:${address}`}
class="text-sh-accent mt-1 inline-block font-mono text-small break-all underline"
>
{address}
</a>
{'more' in row && (
<a
href={localePath(locale, row.more)}
class="sh-anim text-sh-muted mt-1 flex items-center gap-1 text-small hover:underline"
>
{t(locale, 'legal.title.terms')}
<ShIcon name="arrow-right" class="size-3.5" motion="nudge-x" />
</a>
)}
</div>
</li>
);
})}
</ul>
<section class="sh-panel bg-sh-accent-soft mt-8 flex flex-wrap items-center gap-4 border-transparent p-6">
<span class="sh-tile text-sh-accent size-11">
<ShIcon name="message-square-text" class="size-5" />
</span>
<p class="min-w-0 flex-1">{t(locale, 'contact.issues')}</p>
<a href={ISSUES} rel="noopener" class="sh-btn sh-btn-primary sh-anim">
{t(locale, 'contact.issuesLink')}
<ShIcon name="arrow-up-right" class="size-4" motion="nudge-diag" />
</a>
</section>
<p class="text-sh-muted mt-6 max-w-2xl text-small">{t(locale, 'contact.languages')}</p>
</Base>
+70 -25
View File
@@ -6,40 +6,85 @@
//
// Bilingual on ONE page rather than per-locale: an error can be reached from
// either locale (and /offline is reached with no network at all), so there is
// no safe moment to pick one.
// no safe moment to pick one. Copy lives in the dictionaries (error.<kind>.*)
// like every other UI string, so i18n:check covers it.
import Base from '../../layouts/Base.astro';
import ShIcon from '../ShIcon.astro';
import { t } from '../../i18n';
type Kind = '404' | 'offline' | '403' | '429' | '500';
interface Props {
code: string;
titleEn: string;
titleVi: string;
bodyEn: string;
bodyVi: string;
/** 404 needs none — its status code already excludes it (docs/16 §7). */
kind: Kind;
/**
* Default true for every error shell. 404 used to opt out on the grounds that
* its status code excludes it from SERPs — but /404 requested directly is
* served with 200, so it needs the tag like the others.
*/
noindex?: boolean;
}
const { code, titleEn, titleVi, bodyEn, bodyVi, noindex = true } = Astro.props;
const { kind, noindex = true } = Astro.props;
const ICON: Record<Kind, string> = {
'404': 'map-pinned',
offline: 'wifi-off',
'403': 'lock',
'429': 'hourglass',
'500': 'life-buoy',
};
---
<Base title={`${titleEn} — SoftHarbor`} locale="en" {noindex}>
<div class="relative">
{/* Giant clipped status code at 40% opacity, behind the text (docs/06 §5). */}
<span
<Base
title={`${t('en', `error.${kind}.title`)} — SoftHarbor`}
locale="en"
{noindex}
gateExempt
alternates={false}
>
<section class="sh-contours py-6 md:py-14">
{/* The status code, set large in the ledger's mono and fading behind the
text (docs/06 §5) — decoration, so hidden from assistive tech. */}
<p
aria-hidden="true"
class="text-sh-muted pointer-events-none absolute -top-10 -left-2 font-mono text-[8rem] leading-none opacity-40 select-none"
>{code}</span
class="text-sh-accent pointer-events-none font-mono text-[clamp(5rem,18vw,10rem)] leading-none font-medium tracking-tight opacity-25 select-none"
>
<div class="relative">
<h1 class="text-[length:var(--text-h1)] font-semibold">{titleEn}</h1>
<p class="text-sh-muted mt-3 max-w-xl">{bodyEn}</p>
{kind === 'offline' ? '···' : kind}
</p>
<h2 class="mt-8 text-[length:var(--text-h3)] font-semibold" lang="vi">{titleVi}</h2>
<p class="text-sh-muted mt-2 max-w-xl" lang="vi">{bodyVi}</p>
<p class="mt-8 flex flex-wrap gap-4">
<a href="/" class="text-sh-accent underline">SoftHarbor</a>
<a href="/apps" class="text-sh-accent underline">Apps</a>
</p>
<div class="mt-2 grid max-w-4xl grid-cols-1 gap-6 md:grid-cols-2">
<div class="sh-panel p-6">
<span class="sh-tile bg-sh-accent-soft text-sh-accent size-11 border-transparent">
<ShIcon name={ICON[kind]} class="size-[22px]" />
</span>
<h1 class="mt-4 text-[length:var(--text-h2)] font-semibold">
{t('en', `error.${kind}.title`)}
</h1>
<p class="text-sh-muted mt-2">{t('en', `error.${kind}.body`)}</p>
</div>
<div class="sh-panel p-6" lang="vi">
<span class="sh-tile bg-sh-accent-soft text-sh-accent size-11 border-transparent">
<ShIcon name={ICON[kind]} class="size-[22px]" />
</span>
<h2 class="mt-4 text-[length:var(--text-h2)] font-semibold">
{t('vi', `error.${kind}.title`)}
</h2>
<p class="text-sh-muted mt-2">{t('vi', `error.${kind}.body`)}</p>
</div>
</div>
</div>
<p class="mt-8 flex flex-wrap gap-3">
<a href="/" class="sh-btn sh-btn-primary sh-anim">
<ShIcon name="anchor" class="size-[18px]" motion="pop" />
{t('en', 'error.home')}
</a>
<a href="/apps" class="sh-btn sh-anim">
<ShIcon name="layout-grid" class="size-[18px]" motion="pop" />
{t('en', 'nav.apps')}
</a>
<a href="/vi" class="sh-btn sh-anim" lang="vi">
<ShIcon name="languages" class="size-[18px]" motion="pop" />
{t('vi', 'error.home')}
</a>
</p>
</section>
</Base>
+56 -24
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
//
// docs/14 — shared chrome for the five legal documents. Prose lives per
// docs/14 — shared chrome for the six legal documents. Prose lives per
// locale in src/components/legal/, not in the i18n dictionaries: docs/07 §1
// puts legal in its own layer precisely because multi-paragraph documents are
// content, not UI strings, and the English text is canonical (docs/07 §8).
@@ -10,44 +10,53 @@
// These routes are EXEMPT from the legal gate (docs/14 Part 2) — the gate
// links here, so gating them would dead-lock acceptance.
import Base from '../../layouts/Base.astro';
import { LEGAL_VERSION } from '../../lib/legal';
import { LEGAL_UPDATED, type LegalDoc } from '../../lib/legal';
import { t, type Locale } from '../../i18n';
interface Props {
title: string;
/** Which document; its title comes from the dictionary (legal.title.<doc>). */
doc: LegalDoc;
locale: Locale;
}
const { title, locale } = Astro.props;
const { doc, locale } = Astro.props;
const title = t(locale, `legal.title.${doc}`);
const updated = new Intl.DateTimeFormat(locale === 'vi' ? 'vi-VN' : 'en-GB', {
dateStyle: 'medium',
timeZone: 'UTC',
}).format(new Date(`${LEGAL_VERSION}T00:00:00Z`));
}).format(new Date(`${LEGAL_UPDATED[doc]}T00:00:00Z`));
---
<Base {title} {locale}>
{/* Suffixed like every other page: an unbranded <title> in a SERP reads as
someone else's document. The description names the document too, so the
six legal pages are not six copies of the site tagline. */}
<Base
title={`${title} — ${t(locale, 'site.name')}`}
description={t(locale, 'meta.legal', { title })}
{locale}
gateExempt
>
<article class="sh-prose max-w-2xl">
<h1 class="text-[length:var(--text-h1)] font-semibold">{title}</h1>
<p class="sh-eyebrow">{t(locale, 'footer.legal.heading')}</p>
<h1 class="mt-2 text-[length:var(--text-h1)] font-semibold">{title}</h1>
<p class="text-sh-muted mt-2 font-mono text-[var(--text-badge)]">
<p class="text-sh-muted mt-2 font-mono text-badge">
{t(locale, 'legal.lastUpdated', { date: updated })}
</p>
{
locale === 'vi' && (
<p class="sh-panel text-sh-muted mt-6 p-4 text-[var(--text-small)]" lang="vi">
{/* Fixed notice required on every VI legal page (docs/07 §8). */}
{t('vi', 'legal.viNotice')}
</p>
)
}
{locale === 'vi' && (
<p class="sh-panel text-sh-muted mt-6 p-4 text-small" lang="vi">
{/* Fixed notice required on every VI legal page (docs/07 §8). */}
{t('vi', 'legal.viNotice')}
</p>
)}
{
/* No inter-document nav here: ShFooter already lists all of them on
{/* No inter-document nav here: ShFooter already lists all of them on
every page, and repeating the same six links a screen apart is just
noise. */
}
<div class="mt-8 flex flex-col gap-4"><slot /></div>
noise. */}
<div class="mt-8 flex flex-col gap-4">
<slot />
</div>
</article>
</Base>
@@ -68,13 +77,36 @@ const updated = new Intl.DateTimeFormat(locale === 'vi' ? 'vi-VN' : 'en-GB', {
color: var(--sh-accent);
text-decoration: underline;
}
.sh-prose ol {
/* Tailwind's preflight strips list markers. Numbered clauses in a legal
text must stay numbered — they are referred to by number. */
.sh-prose ol,
.sh-prose ul {
display: flex;
flex-direction: column;
gap: 0.75rem;
counter-reset: item;
padding-inline-start: 1.5rem;
}
.sh-prose ol > li {
.sh-prose ol {
list-style: decimal;
}
.sh-prose ul {
list-style: disc;
}
.sh-prose li {
max-width: 65ch;
}
.sh-prose li::marker {
color: var(--sh-muted);
}
.sh-prose code {
font-family: var(--font-mono);
font-size: 0.9em;
background: var(--sh-surface-2);
border: 1px solid var(--sh-border);
border-radius: 6px;
padding: 0.05em 0.35em;
}
.sh-prose h2[id] {
scroll-margin-top: 6rem;
}
</style>
+189 -25
View File
@@ -4,46 +4,210 @@
// docs/06 §5 — Welcome. Rendered by BOTH /src/pages/index.astro and
// /src/pages/vi/index.astro; the locale is the only difference, so the markup
// lives here exactly once (docs/07 §2).
//
// The search "field" in the hero is a LINK to /apps#search, styled as an
// input: the real search is an island on /apps, and docs/02 §5 caps islands
// at six — so the home page stays island-free and works with JS off.
import { getCollection } from 'astro:content';
import Base from '../../layouts/Base.astro';
import ShIcon from '../ShIcon.astro';
import ShJsonLd from '../ShJsonLd.astro';
import { localePath, t, type Locale } from '../../i18n';
import { appCount, localePath, t, type Locale } from '../../i18n';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const how = ['welcome.how.official', 'welcome.how.pricing', 'welcome.how.security'] as const;
const apps = await getCollection('apps');
const categories = (await getCollection('categories')).sort((a, b) => a.data.order - b.data.order);
const nf = new Intl.NumberFormat(locale === 'vi' ? 'vi-VN' : 'en-GB');
const count = (pred: (a: (typeof apps)[number]) => boolean) => nf.format(apps.filter(pred).length);
const perCategory = (id: string) =>
apps.filter((a) => a.data.categories.some((c) => c.id === id)).length;
// The ledger: every figure counted from the data at build time.
const manifest = [
{ icon: 'package', label: t(locale, 'welcome.manifest.apps'), value: nf.format(apps.length) },
{
icon: 'gift',
label: t(locale, 'welcome.manifest.free'),
value: count((a) => a.data.pricing === 'free'),
},
{
icon: 'receipt',
label: t(locale, 'welcome.manifest.once'),
value: count((a) => a.data.pricing !== 'free'),
},
{
icon: 'shield-check',
label: t(locale, 'welcome.manifest.clean'),
value: count((a) => a.data.security.status === 'clean'),
},
{
icon: 'monitor-smartphone',
label: t(locale, 'welcome.manifest.platforms'),
value: (['windows', 'macos', 'linux'] as const)
.map((p) => count((a) => a.data.platforms.includes(p)))
.join(' · '),
},
];
const how = [
{ key: 'welcome.how.official', icon: 'badge-check' },
{ key: 'welcome.how.pricing', icon: 'hand-coins' },
{ key: 'welcome.how.security', icon: 'calendar-check' },
] as const;
const appsHref = localePath(locale, '/apps');
---
<Base title={`${t(locale, 'site.name')} — ${t(locale, 'site.tagline')}`} {locale}>
<ShJsonLd {locale} site={Astro.site ?? new URL('https://softharbor.net')} website />
<section class="max-w-3xl">
<h1 class="text-[length:var(--text-display)] font-semibold">
{t(locale, 'welcome.hero.title')}
</h1>
<p class="text-sh-muted mt-4 text-[length:var(--text-h3)]">
{t(locale, 'welcome.hero.sub')}
</p>
<a
href={localePath(locale, '/apps')}
class="sh-lift bg-sh-accent text-sh-accent-ink border-sh-border mt-8 inline-block rounded-[var(--radius-card)] border-2 px-5 py-3 font-medium"
>
{t(locale, 'welcome.cta')}
</a>
<section class="sh-contours grid grid-cols-1 items-center gap-10 pt-4 lg:grid-cols-[1.3fr_1fr] lg:gap-14 lg:pt-14">
<div class="sh-stagger">
<p class="sh-eyebrow flex items-center gap-2">
<ShIcon name="compass" class="text-sh-accent size-4" />
{t(locale, 'welcome.hero.eyebrow')}
</p>
<h1 class="mt-5 text-[length:var(--text-hero)] leading-[1.06] font-bold tracking-[-0.035em]">
{t(locale, 'welcome.hero.title')}
</h1>
<p class="text-sh-muted mt-5 max-w-xl text-[length:var(--text-h3)] leading-relaxed">
{t(locale, 'welcome.hero.sub')}
</p>
<a href={`${appsHref}#search`} class="sh-searchbox sh-anim mt-8">
<ShIcon name="search" class="text-sh-accent size-5" motion="pop" />
<span>{t(locale, 'welcome.search', { n: nf.format(apps.length) })}</span>
<kbd class="sh-kbd ml-auto" aria-hidden="true">
/
</kbd>
</a>
<div class="mt-5 flex flex-wrap gap-3">
<a href={appsHref} class="sh-btn sh-btn-primary sh-anim">
{t(locale, 'welcome.cta')}
<ShIcon name="arrow-right" class="size-[18px]" motion="nudge-x" />
</a>
<a href={localePath(locale, '/categories')} class="sh-btn sh-anim">
<ShIcon name="shapes" class="size-[18px]" motion="pop" />
{t(locale, 'welcome.categories.all')}
</a>
</div>
</div>
<aside class="sh-panel sh-rise p-6 lg:p-7" aria-labelledby="sh-manifest">
<h2 id="sh-manifest" class="sh-eyebrow flex items-center gap-2">
<ShIcon name="scroll-text" class="size-4" />
{t(locale, 'welcome.manifest')}
</h2>
<dl class="mt-4">
{manifest.map((row) => (
<div class="sh-ledger">
<dt class="flex items-center gap-2.5">
<ShIcon name={row.icon} class="text-sh-accent size-[18px]" />
{row.label}
</dt>
<dd class="font-mono font-medium tabular-nums">{row.value}</dd>
</div>
))}
</dl>
<p class="text-sh-muted mt-4 text-small">{t(locale, 'welcome.manifest.note')}</p>
</aside>
</section>
<section class="mt-16">
<h2 class="text-[length:var(--text-h2)] font-semibold">{t(locale, 'welcome.how.title')}</h2>
<ul class="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{
how.map((key) => (
<li class="sh-panel p-5">
<p>{t(locale, key)}</p>
</li>
))
}
<section class="mt-20" aria-labelledby="sh-cats">
<div class="flex flex-wrap items-end justify-between gap-3">
<h2 id="sh-cats" class="text-[length:var(--text-h2)] font-semibold">
{t(locale, 'welcome.categories')}
</h2>
<a
href={localePath(locale, '/categories')}
class="sh-anim text-sh-accent inline-flex items-center gap-1.5 font-medium hover:underline"
>
{t(locale, 'welcome.categories.all')}
<ShIcon name="arrow-right" class="size-4" motion="nudge-x" />
</a>
</div>
<ul class="sh-stagger mt-6 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{categories.map((c) => (
<li class="sh-panel sh-lift sh-anim relative flex items-center gap-4 p-4">
<span class="sh-tile text-sh-accent size-12">
<ShIcon name={c.data.icon} class="size-6" motion="pop" />
</span>
<div class="min-w-0">
<h3 class="text-[length:var(--text-body)] font-semibold">
<a href={localePath(locale, `/categories/${c.id}`)} class="sh-stretch">
{c.data.label[locale]}
</a>
</h3>
<p class="sh-eyebrow mt-0.5 normal-case tracking-normal">
{appCount(locale, perCategory(c.id))}
</p>
</div>
<ShIcon
name="arrow-right"
class="text-sh-muted ml-auto size-4 shrink-0"
motion="nudge-x"
/>
</li>
))}
</ul>
</section>
<section class="mt-20" aria-labelledby="sh-how">
<h2 id="sh-how" class="text-[length:var(--text-h2)] font-semibold">
{t(locale, 'welcome.how.title')}
</h2>
<ol class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-3">
{how.map((item, i) => (
<li class="sh-panel flex gap-4 p-5">
<span class="sh-tile bg-sh-accent-soft text-sh-accent size-11 border-transparent">
<ShIcon name={item.icon} class="size-[22px]" />
</span>
<div>
<p class="sh-eyebrow">{`0${i + 1}`}</p>
<p class="mt-1">{t(locale, item.key)}</p>
</div>
</li>
))}
</ol>
</section>
</Base>
<style>
.sh-searchbox {
display: flex;
align-items: center;
gap: 0.75rem;
max-width: 34rem;
min-height: 3.5rem;
padding: 0 0.75rem 0 1rem;
border: 1px solid var(--sh-control);
border-radius: var(--radius-card);
background: var(--sh-surface);
box-shadow: var(--sh-shadow-1);
color: var(--sh-muted);
text-decoration: none;
transition:
border-color var(--duration-fast) var(--ease-sh),
box-shadow var(--duration-slow) var(--ease-sh);
}
.sh-searchbox:hover {
border-color: var(--sh-accent);
box-shadow: var(--sh-shadow-2);
}
/* A ruled ledger line: label left, figure right, a hairline between rows. */
.sh-ledger {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.7rem 0;
border-bottom: 1px dashed var(--sh-border);
}
.sh-ledger:last-child {
border-bottom: 0;
}
</style>
+36 -3
View File
@@ -11,8 +11,21 @@
import { defineCollection, reference, z } from 'astro:content';
import { glob, file } from 'astro/loaders';
const DATE = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, 'YYYY-MM-DD');
const HTTPS = z.string().url().startsWith('https://');
/** Today in UTC, at build time: data dated after the build is a typo. */
const TODAY = new Date().toISOString().slice(0, 10);
/**
* A real calendar date in YYYY-MM-DD, not in the future. The regex alone let
* `2026-02-31` through; round-tripping through Date catches impossible days.
*/
const DATE = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, 'YYYY-MM-DD')
.refine((d) => new Date(`${d}T00:00:00Z`).toISOString().slice(0, 10) === d, {
message: 'not a real calendar date',
})
.refine((d) => d <= TODAY, { message: 'date is in the future' });
const HTTPS = z.url().refine((u) => u.startsWith('https://'), { message: 'https:// only' });
const categories = defineCollection({
loader: file('./src/data/categories.json'),
@@ -63,7 +76,27 @@ const apps = defineCollection({
})
// Deliberate: unknown keys fail the build, so the public export contract
// (docs/03 §6) can never silently grow.
.strict(),
.strict()
.superRefine((app, ctx) => {
// A status that makes a claim must link the evidence behind it: "no
// known warnings" is only worth something when the reader can check
// it (hard rule 4), and a flag needs its reason. CONTRIBUTING closed
// these on sight, but nothing enforced it. `unverified` claims nothing.
if (app.security.status !== 'unverified' && app.security.evidence === null) {
ctx.addIssue({
code: 'custom',
path: ['security', 'evidence'],
message: `status "${app.security.status}" requires an evidence URL`,
});
}
if (app.updatedAt && app.updatedAt < app.addedAt) {
ctx.addIssue({
code: 'custom',
path: ['updatedAt'],
message: `updatedAt ${app.updatedAt} precedes addedAt ${app.addedAt}`,
});
}
}),
});
export const collections = { apps, categories };
+1 -1
View File
@@ -1,2 +1,2 @@
/// <reference types="astro/client" />
/// <reference types="unplugin-icons/types/astro" />
/// <reference types="unplugin-icons/types/svelte5" />
+84 -3
View File
@@ -1,7 +1,8 @@
{
"apps.count": "{n} apps",
"apps.empty": "No apps yet — the directory is being seeded.",
"apps.count.one": "{n} app",
"apps.intro": "Every link goes to the developer's official page. SoftHarbor hosts no downloads.",
"apps.noResults": "No apps match. Try fewer filters or a different word.",
"apps.title": "Apps",
"bug.errorCount": "{n} errors",
"bug.report": "Report a bug",
@@ -9,27 +10,67 @@
"card.listed": "listed {date}",
"card.security.clean": "No known warnings",
"card.security.unverified": "Not yet verified",
"categories.empty": "No apps in this category yet.",
"categories.intro": "Twelve categories, each linking straight to official pages.",
"categories.title": "Categories",
"contact.address": "Address",
"contact.collab": "Collaboration",
"contact.conduct": "A Code of Conduct report",
"contact.copyright": "Licensing of the code or the dataset",
"contact.dmca": "A copyright complaint",
"contact.intro": "SoftHarbor is run by one person. Each address below reaches the same maintainer, sorted by purpose, so your message is read in the right context.",
"contact.issues": "Wrong information, a broken link, or an app to suggest? Open a GitHub issue — it is public, and usually faster.",
"contact.issuesLink": "Open an issue",
"contact.languages": "We read and reply in English and Vietnamese. Email is handled as the Privacy Policy describes.",
"contact.legal": "Terms, the disclaimer and other legal questions",
"contact.press": "Press",
"contact.privacy": "Privacy and your data",
"contact.purpose": "About",
"contact.security": "A security vulnerability, or a hijacked or malicious listing",
"contact.takedown": "Changing or removing your app’s listing or logo",
"contact.title": "Contact",
"detail.added": "Added",
"detail.developer": "Developer",
"detail.disclaimerLink": "Read the Disclaimer",
"detail.download": "Download",
"detail.evidence": "View scan",
"detail.facts": "At a glance",
"detail.homepage": "Homepage",
"detail.license": "License",
"detail.officialNote": "Links go to the official site. SoftHarbor hosts no downloads.",
"detail.platforms": "Platforms",
"detail.related": "More in {category}",
"detail.repo": "Repository",
"detail.security": "Security",
"detail.securityNote.clean": "On the date shown, this entry went through our published checklist and nothing worrying turned up. It is not an audit or a guarantee — software can change after a check. Download only from the official link, and verify signatures or checksums where the developer offers them.",
"detail.securityNote.title": "What this status means",
"detail.securityNote.unverified": "The checklist has not been completed for this entry, or something it found needs a closer look. It meets every other rule of the list. Take the care you would with any download, and prefer the official link.",
"detail.tags": "Tags",
"detail.updated": "Updated",
"error.403.body": "Nothing on SoftHarbor requires permission, so this is unexpected. If you reached this page, please report it.",
"error.403.title": "Access denied",
"error.404.body": "The link may be old, or the entry may have been removed — flagged apps are quarantined rather than kept live.",
"error.404.title": "That page isn't here",
"error.429.body": "You have been rate limited. The public dataset at /api/apps.json exists precisely so tools do not have to scrape the pages.",
"error.429.title": "Too many requests",
"error.500.body": "SoftHarbor is a static site, so this should be impossible. If you are seeing it, the report button in the footer helps.",
"error.500.title": "Something broke",
"error.home": "Home",
"error.offline.body": "SoftHarbor needs a connection to load new pages. It is a directory of links, so there is nothing useful to show you offline.",
"error.offline.title": "You appear to be offline",
"feed.title": "SoftHarbor — newly listed apps",
"filters.categories": "Category",
"filters.clear": "Clear all",
"filters.close": "Close filters",
"filters.open": "Filters",
"filters.platforms": "Platform",
"filters.pricing": "Pricing",
"filters.show": "Show {n} apps",
"filters.show.one": "Show {n} app",
"footer.api": "JSON dataset",
"footer.browse": "Browse",
"footer.builtAt": "Built {date}",
"footer.contact": "Contact",
"footer.data": "Open data",
"footer.github": "Source on GitHub",
"footer.legal.aiDisclosure": "AI disclosure",
"footer.legal.disclaimer": "Disclaimer",
@@ -39,27 +80,56 @@
"footer.legal.thirdParty": "Third-party",
"footer.legal.trademarks": "Trademarks",
"footer.license": "Code GPL-3.0 · Data CC BY-SA 4.0",
"footer.project": "Project",
"footer.releases": "Releases",
"footer.rss": "RSS feed",
"gate.accept": "I understand and accept",
"gate.and": "and",
"gate.body": "SoftHarbor is a link directory. We don't host downloads, and we can't guarantee third-party software. Statuses like \"no known warnings\" reflect checks on the date shown — verify anything you install. By continuing you accept the",
"gate.link.disclaimer": "Disclaimer",
"gate.link.privacy": "Privacy Policy",
"gate.link.terms": "Terms of Use",
"gate.title": "Before you continue",
"gate.verify.body": "A quick automatic check by Cloudflare Turnstile that you are a person, not a bot. It usually takes a second and needs nothing from you — see the",
"gate.verify.skipped": "The check could not run, so it was skipped. Come on in.",
"gate.verify.title": "One moment",
"lang.label": "Language",
"lang.suggest.accept": "Switch to Vietnamese",
"lang.suggest.dismiss": "Stay in English",
"lang.suggest.text": "This page is available in Vietnamese.",
"legal.lastUpdated": "Last updated {date}",
"legal.title.aiDisclosure": "AI Disclosure",
"legal.title.disclaimer": "Disclaimer",
"legal.title.privacy": "Privacy Policy",
"legal.title.terms": "Terms of Use",
"legal.title.thirdParty": "Third-Party Notices",
"legal.title.trademarks": "Trademarks",
"legal.viNotice": "The Vietnamese version is provided for reference only; if there is any discrepancy, the English version prevails.",
"meta.apps": "Browse {n} desktop apps that are free or buy-once, filtered by category, platform and pricing. Every link goes to the developer's official page.",
"meta.categories": "Twelve categories of desktop software that is free or buy-once — browsers, developer tools, graphics, media, security and more.",
"meta.category": "{label}: {n} desktop apps that are free or buy-once. Every link goes to the developer's own site — SoftHarbor hosts no downloads.",
"meta.contact": "How to reach SoftHarbor: one address per purpose — security, privacy, legal, copyright, listings, press and collaboration.",
"meta.legal": "{title} for SoftHarbor, a directory of desktop software that is free or buy-once.",
"nav.apps": "Apps",
"nav.breadcrumb": "Breadcrumb",
"nav.categories": "Categories",
"nav.main": "Main",
"nav.skipToContent": "Skip to content",
"platform.linux": "Linux",
"platform.macos": "macOS",
"platform.windows": "Windows",
"prefs.label": "Display settings",
"prefs.motion": "Motion",
"prefs.motion.reduce": "Reduce",
"prefs.motion.system": "System",
"prefs.scrollbar": "Scrollbar",
"prefs.scrollbar.auto": "Default",
"prefs.scrollbar.hidden": "Hidden",
"prefs.scrollbar.thin": "Thin",
"pricing.free": "FREE",
"pricing.free-onetime": "FREE + ONE-TIME",
"pricing.onetime": "ONE-TIME",
"search.error": "Search is unavailable right now — the filters still work.",
"search.hint": "Press / to search",
"search.label": "Search apps",
"search.loading": "loading index…",
@@ -69,16 +139,27 @@
"sort.added": "Newest",
"sort.label": "Sort",
"sort.name": "A–Z",
"sort.relevance": "Best match",
"theme.dark": "Dark",
"theme.label": "Theme",
"theme.light": "Light",
"theme.system": "System",
"welcome.categories": "Browse by category",
"welcome.categories.all": "All categories",
"welcome.cta": "Browse all apps",
"welcome.hero.eyebrow": "Free or buy-once · Windows · macOS · Linux",
"welcome.hero.sub": "A bilingual directory of desktop software that is free, or yours after a single payment — never subscription-only. Straight to every official download page.",
"welcome.hero.title": "Set up a new machine without googling ten tools.",
"welcome.how.official": "Official links only. Every link points at the developer's own site or repository — never a download portal.",
"welcome.how.pricing": "Free or own it once. Subscription-only software never enters the list.",
"welcome.how.security": "Dated, honest status. We show when an entry was last checked — never a promise that it is safe.",
"welcome.how.title": "How this list works"
"welcome.how.title": "How this list works",
"welcome.manifest": "Manifest",
"welcome.manifest.apps": "Apps listed",
"welcome.manifest.clean": "No known warnings",
"welcome.manifest.free": "Completely free",
"welcome.manifest.note": "Counted when this page was built. Subscription-only software: none, by rule.",
"welcome.manifest.once": "Buy once, own it",
"welcome.manifest.platforms": "Windows · macOS · Linux",
"welcome.search": "Search {n} apps…"
}
+1
View File
@@ -47,6 +47,7 @@ describe('dictionary parity (hard rule 6 — same check CI runs)', () => {
'platform.windows',
'site.name',
'sort.name', // "A–Z" — the Latin range reads the same in Vietnamese
'welcome.manifest.platforms', // "Windows · macOS · Linux" — three platform names
];
const identical = Object.keys(en).filter(
(k) => en[k as keyof typeof en] === vi[k as keyof typeof vi],
+12
View File
@@ -24,3 +24,15 @@ export function t(locale: Locale, key: Key, vars: Record<string, string | number
for (const [k, v] of Object.entries(vars)) s = s.replaceAll(`{${k}}`, String(v));
return s;
}
/**
* "1 app" / "326 apps" / "326 ứng dụng": the plural rule and the digit
* grouping of the page's language. One helper, so no page can print "1 apps".
*/
export function appCount(locale: Locale, n: number): string {
const lang = locale === 'vi' ? 'vi-VN' : 'en-GB';
const one = new Intl.PluralRules(lang).select(n) === 'one';
return t(locale, one ? 'apps.count.one' : 'apps.count', {
n: new Intl.NumberFormat(lang).format(n),
});
}
+84 -3
View File
@@ -1,7 +1,8 @@
{
"apps.count": "{n} ứng dụng",
"apps.empty": "Chưa có ứng dụng nào — danh sách đang được bổ sung.",
"apps.count.one": "{n} ứng dụng",
"apps.intro": "Mọi liên kết đều dẫn tới trang chính thức của nhà phát triển. SoftHarbor không lưu trữ tệp cài đặt.",
"apps.noResults": "Không có ứng dụng nào khớp. Hãy bỏ bớt bộ lọc hoặc thử từ khác.",
"apps.title": "Ứng dụng",
"bug.errorCount": "{n} lỗi",
"bug.report": "Báo lỗi",
@@ -9,27 +10,67 @@
"card.listed": "đưa vào danh sách {date}",
"card.security.clean": "Không có cảnh báo đã biết",
"card.security.unverified": "Chưa kiểm chứng",
"categories.empty": "Danh mục này chưa có ứng dụng nào.",
"categories.intro": "Mười hai danh mục, mỗi mục dẫn thẳng tới trang chính thức.",
"categories.title": "Danh mục",
"contact.address": "Địa chỉ",
"contact.collab": "Hợp tác",
"contact.conduct": "Báo cáo vi phạm Quy tắc ứng xử",
"contact.copyright": "Giấy phép của mã nguồn hoặc bộ dữ liệu",
"contact.dmca": "Khiếu nại bản quyền",
"contact.intro": "SoftHarbor do một người vận hành. Mỗi địa chỉ dưới đây đều tới cùng người bảo trì, được chia theo mục đích để thư của bạn được đọc đúng ngữ cảnh.",
"contact.issues": "Thông tin sai, liên kết hỏng, hay muốn đề xuất một ứng dụng? Hãy mở GitHub issue — công khai và thường nhanh hơn.",
"contact.issuesLink": "Mở issue",
"contact.languages": "Chúng tôi đọc và trả lời bằng tiếng Anh và tiếng Việt. Email được xử lý như Chính sách quyền riêng tư mô tả.",
"contact.legal": "Điều khoản, tuyên bố miễn trừ và các câu hỏi pháp lý khác",
"contact.press": "Báo chí",
"contact.privacy": "Quyền riêng tư và dữ liệu của bạn",
"contact.purpose": "Về việc",
"contact.security": "Lỗ hổng bảo mật, hoặc một mục bị chiếm quyền hay độc hại",
"contact.takedown": "Sửa hoặc gỡ mục giới thiệu hay logo ứng dụng của bạn",
"contact.title": "Liên hệ",
"detail.added": "Thêm ngày",
"detail.developer": "Nhà phát triển",
"detail.disclaimerLink": "Đọc Tuyên bố miễn trừ",
"detail.download": "Tải về",
"detail.evidence": "Xem kết quả quét",
"detail.facts": "Tóm lược",
"detail.homepage": "Trang chủ",
"detail.license": "Giấy phép",
"detail.officialNote": "Các liên kết dẫn tới trang chính thức. SoftHarbor không lưu trữ tệp cài đặt.",
"detail.platforms": "Nền tảng",
"detail.related": "Thêm trong {category}",
"detail.repo": "Kho mã nguồn",
"detail.security": "Bảo mật",
"detail.securityNote.clean": "Vào ngày được ghi, mục này đã qua quy trình kiểm tra công khai của chúng tôi và không phát hiện điều gì đáng lo. Đây không phải kiểm toán hay bảo đảm — phần mềm có thể thay đổi sau lần kiểm tra. Chỉ tải từ liên kết chính thức, và xác minh chữ ký hoặc checksum nếu nhà phát triển cung cấp.",
"detail.securityNote.title": "Trạng thái này nghĩa là gì",
"detail.securityNote.unverified": "Quy trình kiểm tra chưa hoàn tất cho mục này, hoặc có điều cần xem kỹ hơn. Mục này đáp ứng mọi quy tắc khác của danh sách. Hãy cẩn trọng như với bất kỳ tệp tải về nào, và ưu tiên liên kết chính thức.",
"detail.tags": "Thẻ",
"detail.updated": "Cập nhật",
"error.403.body": "Không phần nào của SoftHarbor yêu cầu quyền truy cập, nên đây là tình huống bất thường. Nếu bạn gặp trang này, hãy báo cho chúng tôi.",
"error.403.title": "Truy cập bị từ chối",
"error.404.body": "Liên kết có thể đã cũ, hoặc mục tương ứng đã được gỡ — ứng dụng bị gắn cờ sẽ được đưa vào khu cách ly thay vì giữ lại.",
"error.404.title": "Không tìm thấy trang",
"error.429.body": "Bạn đã bị giới hạn tần suất truy cập. Bộ dữ liệu công khai tại /api/apps.json tồn tại để công cụ không phải quét từng trang.",
"error.429.title": "Quá nhiều yêu cầu",
"error.500.body": "SoftHarbor là trang tĩnh nên lỗi này gần như không thể xảy ra. Nếu bạn gặp, hãy dùng nút báo lỗi ở chân trang.",
"error.500.title": "Đã xảy ra lỗi",
"error.home": "Trang chủ",
"error.offline.body": "SoftHarbor cần kết nối mạng để tải trang mới. Đây là trang tổng hợp liên kết nên không có nội dung hữu ích khi ngoại tuyến.",
"error.offline.title": "Bạn đang ngoại tuyến",
"feed.title": "SoftHarbor — ứng dụng mới được thêm",
"filters.categories": "Danh mục",
"filters.clear": "Xoá tất cả",
"filters.close": "Đóng bộ lọc",
"filters.open": "Bộ lọc",
"filters.platforms": "Nền tảng",
"filters.pricing": "Giá",
"filters.show": "Xem {n} ứng dụng",
"filters.show.one": "Xem {n} ứng dụng",
"footer.api": "Bộ dữ liệu JSON",
"footer.browse": "Khám phá",
"footer.builtAt": "Dựng ngày {date}",
"footer.contact": "Liên hệ",
"footer.data": "Dữ liệu mở",
"footer.github": "Mã nguồn trên GitHub",
"footer.legal.aiDisclosure": "Công bố AI",
"footer.legal.disclaimer": "Tuyên bố miễn trừ",
@@ -39,27 +80,56 @@
"footer.legal.thirdParty": "Bên thứ ba",
"footer.legal.trademarks": "Thương hiệu",
"footer.license": "Mã nguồn GPL-3.0 · Dữ liệu CC BY-SA 4.0",
"footer.project": "Dự án",
"footer.releases": "Các bản phát hành",
"footer.rss": "Nguồn RSS",
"gate.accept": "Tôi hiểu và chấp nhận",
"gate.and": "và",
"gate.body": "SoftHarbor là trang tổng hợp liên kết. Chúng tôi không lưu trữ tệp cài đặt và không thể bảo đảm cho phần mềm bên thứ ba. Trạng thái như \"không có cảnh báo đã biết\" chỉ phản ánh việc kiểm tra tại ngày ghi kèm — hãy tự xác minh trước khi cài đặt. Khi tiếp tục, bạn chấp nhận",
"gate.link.disclaimer": "Tuyên bố miễn trừ",
"gate.link.privacy": "Chính sách quyền riêng tư",
"gate.link.terms": "Điều khoản sử dụng",
"gate.title": "Trước khi tiếp tục",
"gate.verify.body": "Cloudflare Turnstile đang tự động kiểm tra để xác nhận bạn là người chứ không phải bot. Thường chỉ mất một giây và bạn không cần làm gì — xem",
"gate.verify.skipped": "Không chạy được bước kiểm tra nên đã bỏ qua. Mời bạn vào trang.",
"gate.verify.title": "Chờ một chút",
"lang.label": "Ngôn ngữ",
"lang.suggest.accept": "Chuyển sang tiếng Việt",
"lang.suggest.dismiss": "Giữ tiếng Anh",
"lang.suggest.text": "Trang này có bản tiếng Việt.",
"legal.lastUpdated": "Cập nhật lần cuối {date}",
"legal.title.aiDisclosure": "Công bố về việc dùng AI",
"legal.title.disclaimer": "Tuyên bố miễn trừ",
"legal.title.privacy": "Chính sách quyền riêng tư",
"legal.title.terms": "Điều khoản sử dụng",
"legal.title.thirdParty": "Thông báo bên thứ ba",
"legal.title.trademarks": "Thương hiệu",
"legal.viNotice": "Bản tiếng Việt chỉ nhằm mục đích tham khảo; nếu có khác biệt, bản tiếng Anh được ưu tiên áp dụng.",
"meta.apps": "Duyệt {n} ứng dụng desktop miễn phí hoặc mua đứt, lọc theo danh mục, nền tảng và giá. Mọi liên kết đều dẫn tới trang chính thức của nhà phát triển.",
"meta.categories": "Mười hai danh mục phần mềm desktop miễn phí hoặc mua đứt — trình duyệt, công cụ lập trình, đồ hoạ, đa phương tiện, bảo mật và nhiều hơn nữa.",
"meta.category": "{label}: {n} ứng dụng desktop miễn phí hoặc mua đứt. Mọi liên kết đều dẫn tới trang của chính nhà phát triển — SoftHarbor không lưu trữ tệp cài đặt.",
"meta.contact": "Cách liên hệ SoftHarbor: mỗi mục đích một địa chỉ — bảo mật, quyền riêng tư, pháp lý, bản quyền, mục giới thiệu, báo chí và hợp tác.",
"meta.legal": "{title} của SoftHarbor, thư mục phần mềm desktop miễn phí hoặc mua đứt.",
"nav.apps": "Ứng dụng",
"nav.breadcrumb": "Đường dẫn",
"nav.categories": "Danh mục",
"nav.main": "Điều hướng chính",
"nav.skipToContent": "Tới nội dung chính",
"platform.linux": "Linux",
"platform.macos": "macOS",
"platform.windows": "Windows",
"prefs.label": "Tuỳ chỉnh hiển thị",
"prefs.motion": "Chuyển động",
"prefs.motion.reduce": "Giảm",
"prefs.motion.system": "Theo hệ thống",
"prefs.scrollbar": "Thanh cuộn",
"prefs.scrollbar.auto": "Mặc định",
"prefs.scrollbar.hidden": "Ẩn",
"prefs.scrollbar.thin": "Mảnh",
"pricing.free": "MIỄN PHÍ",
"pricing.free-onetime": "MIỄN PHÍ + MUA ĐỨT",
"pricing.onetime": "MUA ĐỨT",
"search.error": "Tạm thời không tìm kiếm được — bộ lọc vẫn hoạt động.",
"search.hint": "Nhấn / để tìm kiếm",
"search.label": "Tìm ứng dụng",
"search.loading": "đang tải chỉ mục…",
@@ -69,16 +139,27 @@
"sort.added": "Mới nhất",
"sort.label": "Sắp xếp",
"sort.name": "A–Z",
"sort.relevance": "Phù hợp nhất",
"theme.dark": "Tối",
"theme.label": "Giao diện",
"theme.light": "Sáng",
"theme.system": "Theo hệ thống",
"welcome.categories": "Xem theo danh mục",
"welcome.categories.all": "Tất cả danh mục",
"welcome.cta": "Xem tất cả ứng dụng",
"welcome.hero.eyebrow": "Miễn phí hoặc mua một lần · Windows · macOS · Linux",
"welcome.hero.sub": "Trang tổng hợp song ngữ về phần mềm desktop miễn phí, hoặc thuộc về bạn sau một lần trả tiền — không bao giờ chỉ có thuê bao. Dẫn thẳng tới trang tải chính thức.",
"welcome.hero.title": "Cài máy mới mà không phải google từng phần mềm một.",
"welcome.how.official": "Chỉ liên kết chính thức. Mọi liên kết đều trỏ tới trang hoặc kho mã của chính nhà phát triển — không qua trang tải trung gian.",
"welcome.how.pricing": "Miễn phí hoặc mua đứt. Phần mềm chỉ bán theo thuê bao không bao giờ được đưa vào danh sách.",
"welcome.how.security": "Trạng thái có ghi ngày, trung thực. Chúng tôi cho biết mục đó được kiểm tra lần cuối khi nào — không cam kết rằng nó an toàn.",
"welcome.how.title": "Danh sách này hoạt động thế nào"
"welcome.how.title": "Danh sách này hoạt động thế nào",
"welcome.manifest": "Bản kê",
"welcome.manifest.apps": "Ứng dụng trong danh sách",
"welcome.manifest.clean": "Không có cảnh báo đã biết",
"welcome.manifest.free": "Hoàn toàn miễn phí",
"welcome.manifest.note": "Số liệu tính lúc dựng trang. Phần mềm chỉ bán theo thuê bao: không có, theo quy tắc.",
"welcome.manifest.once": "Mua một lần, dùng mãi",
"welcome.manifest.platforms": "Windows · macOS · Linux",
"welcome.search": "Tìm trong {n} ứng dụng…"
}
+95 -57
View File
@@ -2,12 +2,18 @@
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 poli0981 (SkullMute)
// docs/02 §4, docs/06 §4, docs/07 §6.
import { ClientRouter } from 'astro:transitions';
import ShLegalGate from '../components/islands/ShLegalGate.svelte';
import ShHeader from '../components/ShHeader.astro';
import ShFooter from '../components/ShFooter.astro';
import { localePair, localePath, t, type Locale } from '../i18n';
import { canonicalPath } from '../lib/locale';
// Pre-paint scripts, emitted verbatim as content-hashed /_astro/ files.
// `no-inline` is load-bearing: plain `?url` inlines files under 4 KiB as data:
// URLs, which `script-src 'self'` refuses (scripts/check-assets.mjs guards it).
import errorsUrl from '../scripts/errors.js?url&no-inline';
import themeUrl from '../scripts/theme.js?url&no-inline';
import analyticsUrl from '../scripts/analytics.js?url&no-inline';
import { VIEW_TRANSITION_OPT_IN } from '../lib/inlineCss';
import '../styles/global.css';
interface Props {
@@ -16,34 +22,54 @@ interface Props {
locale?: Locale;
/** Reachable but meaningless in SERPs — /offline, /errors/* (docs/16 §7). */
noindex?: boolean;
/**
* Pages the legal gate must never cover (docs/14 Part 2): the legal
* documents it links to, and error/offline pages, which would otherwise
* dead-lock. Declared by the PAGE, because Workers serves 404.html and the
* service worker serves the offline page at whatever URL was requested — a
* path rule can never recognise them.
*/
gateExempt?: boolean;
/**
* Whether this page exists in BOTH locales. Error and offline pages are
* single, bilingual documents: advertising hreflang alternates for them
* pointed crawlers at /vi/404 and /vi/offline, which do not exist, and the
* language switcher there leads to the other locale's home instead.
*/
alternates?: boolean;
}
const { title, description, locale = 'en', noindex = false } = Astro.props;
const {
title,
description,
locale = 'en',
noindex = false,
gateExempt = false,
alternates = true,
} = Astro.props;
const site = Astro.site ?? new URL('https://softharbor.net');
// canonicalPath, never Astro.url.pathname directly: with build.format 'file'
// the latter is the emitted FILE name (/apps.html), which would make every
// canonical disagree with the sitemap and with the URL actually served.
const pair = localePair(Astro.url.pathname);
const pair = alternates ? localePair(Astro.url.pathname) : { en: '/', vi: '/vi' };
const canonical = new URL(canonicalPath(Astro.url.pathname), site);
const desc = description ?? t(locale, 'site.tagline');
// Both locales resolved here, server-side: the gate is persisted across
// navigations and must switch language without a reload, but importing the
// dictionaries into the island would bundle every key (docs/07 §3).
// Built as an explicit record rather than Object.fromEntries, which widens to
// { [k: string]: … } and no longer satisfies the island's Record<Locale, …>.
const gateStringsFor = (l: Locale) => ({
title: t(l, 'gate.title'),
body: t(l, 'gate.body'),
accept: t(l, 'gate.accept'),
disclaimer: t(l, 'gate.link.disclaimer'),
terms: t(l, 'gate.link.terms'),
privacy: t(l, 'gate.link.privacy'),
base: localePath(l, '/legal'),
});
const gateStrings: Record<Locale, ReturnType<typeof gateStringsFor>> = {
en: gateStringsFor('en'),
vi: gateStringsFor('vi'),
// Resolved server-side for the page's locale only: importing the dictionaries
// into the island would bundle every key (docs/07 §3).
const gateStrings = {
title: t(locale, 'gate.title'),
body: t(locale, 'gate.body'),
accept: t(locale, 'gate.accept'),
disclaimer: t(locale, 'gate.link.disclaimer'),
terms: t(locale, 'gate.link.terms'),
privacy: t(locale, 'gate.link.privacy'),
and: t(locale, 'gate.and'),
base: localePath(locale, '/legal'),
verifyTitle: t(locale, 'gate.verify.title'),
verifyBody: t(locale, 'gate.verify.body'),
verifySkipped: t(locale, 'gate.verify.skipped'),
lang: locale,
};
---
@@ -56,15 +82,31 @@ const gateStrings: Record<Locale, ReturnType<typeof gateStringsFor>> = {
<meta name="description" content={desc} />
<link rel="canonical" href={canonical.href} />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
{/* @vite-pwa/astro emits the manifest but, like registerSW.js, links it
from no page — so the site was never installable (audit, 2026-10). */}
<link rel="manifest" href="/manifest.webmanifest" />
{/* Browser chrome follows the page background in each scheme. */}
<meta name="theme-color" content="#f2f8fb" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#06101c" media="(prefers-color-scheme: dark)" />
<link
rel="alternate"
type="application/rss+xml"
title={t(locale, 'feed.title')}
href="/rss.xml"
/>
{noindex && <meta name="robots" content="noindex" />}
{
/* Canonical is self-per-locale; alternates come from the single
localePair() source the switcher will also use (docs/07 §5/§6). */
}
<link rel="alternate" hreflang="en" href={new URL(pair.en, site).href} />
<link rel="alternate" hreflang="vi" href={new URL(pair.vi, site).href} />
<link rel="alternate" hreflang="x-default" href={new URL(pair.en, site).href} />
{/* Canonical is self-per-locale; alternates come from the single
localePair() source the switcher will also use (docs/07 §5/§6). */}
{alternates && (
<>
<link rel="alternate" hreflang="en" href={new URL(pair.en, site).href} />
<link rel="alternate" hreflang="vi" href={new URL(pair.vi, site).href} />
<link rel="alternate" hreflang="x-default" href={new URL(pair.en, site).href} />
</>
)}
<meta property="og:site_name" content={t(locale, 'site.name')} />
<meta property="og:title" content={title} />
@@ -74,45 +116,41 @@ const gateStrings: Record<Locale, ReturnType<typeof gateStringsFor>> = {
<meta property="og:locale:alternate" content={locale === 'vi' ? 'en_GB' : 'vi_VN'} />
<meta name="twitter:card" content="summary" />
{/* Blocking, same-origin, NOT inline — docs/05 §A8, docs/09 §4 (D20). */}
<script is:inline src="/theme.js"></script>
{
/*
{/* View Transitions opt-in — inline on purpose, see src/lib/inlineCss.ts. */}
<style is:inline set:html={VIEW_TRANSITION_OPT_IN} />
{/*
Console ring buffer FIRST (docs/05 §A5): it must already be listening when
theme.js or an island bootstrap throws. Blocking and tiny on purpose.
*/}
<script is:inline src={errorsUrl}></script>
{/* No-flash theme, blocking, before first paint — docs/05 §A8. */}
<script is:inline src={themeUrl}></script>
{/*
Service-worker registration. @vite-pwa/astro EMITS /registerSW.js and
/sw.js but never references them from any page — the build reports
success while the SW silently never registers, so the offline fallback
would not exist in production (found in spike S5). We load the emitted
file ourselves. External, not inline, to satisfy script-src (docs/09 §4).
*/
}
*/}
<script is:inline defer src="/registerSW.js"></script>
{
/*
Console ring buffer (docs/05 §A5). Loaded here rather than inside
ShBugReport because that island is client:visible in the footer — a
listener attached at hydration would miss every error that happened
before the user scrolled, which is most of them.
*/
}
<script is:inline defer src="/errors.js"></script>
<ClientRouter />
{/*
Cloudflare Web Analytics — the loader decides (GPC, production host only)
before anything third-party is requested. Not render-blocking.
*/}
<script is:inline defer src={analyticsUrl}></script>
</head>
<body class="flex min-h-dvh flex-col">
{
/*
client:load — must block interaction immediately, not on idle.
transition:persist — survives ClientRouter navigations so acceptance
never re-flashes; it re-asserts modal state after each swap
(docs/02 §5, docs/14 Part 2, spike S4).
*/
}
<ShLegalGate client:load transition:persist {locale} strings={gateStrings} />
{/*
client:load — must block interaction immediately, not on idle. Every
page is a full document load now (no <ClientRouter />), so each page
mounts its own gate; there is nothing to persist across navigations.
*/}
{!gateExempt && <ShLegalGate client:load strings={gateStrings} />}
<a href="#main" class="sh-skip">{t(locale, 'nav.skipToContent')}</a>
<ShHeader {locale} />
<a href="#main" class="sh-skip">
{t(locale, 'nav.skipToContent')}
</a>
<ShHeader {locale} {pair} />
<main id="main" class="mx-auto w-full max-w-[1360px] flex-1 px-4 py-8 md:px-6">
<slot />
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more