Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82a46cf1a8
|
||
|
|
bc02c2ede7
|
||
|
|
e1a4163f74
|
||
|
|
3244aad002
|
||
|
|
32b5ab93b6
|
||
|
|
58f75232a1
|
||
|
|
96ac16bb38
|
||
|
|
d01e746644
|
||
|
|
919b79d3c0
|
No files matched your search
+7
-2
@@ -1,5 +1,10 @@
|
||||
# Default: normalize to LF in the repo, check out native.
|
||||
* text=auto
|
||||
# Default: normalize to LF in the repo AND in every checkout.
|
||||
#
|
||||
# `eol=lf` and not "check out native": Biome's formatter (and every gate built
|
||||
# on it) expects LF, so a Windows clone with core.autocrlf=true used to fail
|
||||
# `npm run lint` on all 114 files before a single line had been edited. The
|
||||
# two `#!/usr/bin/env node` scripts are also unusable from WSL with CRLF.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Fixtures are byte-exact samples of what real browsers and spreadsheets emit.
|
||||
# EOL normalization would rewrite the CRLF records in the CSV exports, so a
|
||||
|
||||
@@ -37,7 +37,9 @@ body:
|
||||
label: File format
|
||||
options:
|
||||
- HTML (the usual "bookmarks.html" export)
|
||||
- JSON
|
||||
- Chrome / Edge / Brave profile "Bookmarks" file
|
||||
- Firefox JSON backup (bookmarks-YYYY-MM-DD.json)
|
||||
- BookmarkMagic JSON
|
||||
- CSV
|
||||
- Not sure
|
||||
validations:
|
||||
|
||||
+30
-8
@@ -2,11 +2,16 @@
|
||||
# .github/workflows/.
|
||||
#
|
||||
# Note what this file cannot do: Dependabot *security* updates run from the
|
||||
# repo's alerts regardless of any config here. Several currently fail because
|
||||
# the advisories are against transitive dev dependencies with no reachable
|
||||
# patched version. That is noisy but not shipped — BookmarkMagic has zero
|
||||
# runtime dependencies, so `npm audit --omit=dev` reports 0 and nothing in the
|
||||
# published extension is affected (docs/09 T5).
|
||||
# repo's alerts regardless of any config here, and they ignore `cooldown`.
|
||||
# BookmarkMagic has zero runtime dependencies, so `npm audit --omit=dev`
|
||||
# reports 0 and an advisory against the dev toolchain never reaches the
|
||||
# published extension (docs/09 T5).
|
||||
#
|
||||
# `.npmrc` sets `min-release-age=7`, the same rule as `cooldown` below, for
|
||||
# installs made by hand. A security PR for a version younger than 7 days can
|
||||
# therefore fail to resolve until that version ages — the price of not being
|
||||
# the first to install a compromised release. `npm ci` is unaffected: it
|
||||
# installs whatever the lockfile pins.
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
@@ -16,6 +21,10 @@ updates:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 5
|
||||
# Supply-chain cooldown (docs/01 §6): only propose releases that have been
|
||||
# public for a week.
|
||||
cooldown:
|
||||
default-days: 7
|
||||
commit-message:
|
||||
# Conventional Commits — docs/10 §7 applies to bot commits too.
|
||||
prefix: chore
|
||||
@@ -29,12 +38,23 @@ updates:
|
||||
update-types:
|
||||
- minor
|
||||
- patch
|
||||
# WXT is 0.x, so its "minor" is semver's breaking slot, and every WXT
|
||||
# bump needs the BUILT manifest diffed by hand (docs/15 decision log,
|
||||
# 2026-08-03). It gets its own PR so it can never ride along unseen.
|
||||
exclude-patterns:
|
||||
- 'wxt'
|
||||
- '@wxt-dev/*'
|
||||
ignore:
|
||||
# Held deliberately: svelte-check and Volar need the TypeScript 6
|
||||
# programmatic API until TS 7.1 (docs/01). A major bump here breaks
|
||||
# `npm run check` rather than improving anything.
|
||||
# The TypeScript pair is held on purpose (docs/01 §2): `@typescript/native`
|
||||
# is the TS 7 `tsc`, `typescript` is the TS 6 API that svelte-check needs.
|
||||
# A major on either is a documented decision, not a weekly bump.
|
||||
- dependency-name: typescript
|
||||
update-types: [version-update:semver-major]
|
||||
- dependency-name: '@typescript/native'
|
||||
update-types: [version-update:semver-major]
|
||||
# Tracks the Node major in .nvmrc (docs/01 §2), so it moves with Node.
|
||||
- dependency-name: '@types/node'
|
||||
update-types: [version-update:semver-major]
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
@@ -42,6 +62,8 @@ updates:
|
||||
interval: weekly
|
||||
day: monday
|
||||
open-pull-requests-limit: 3
|
||||
cooldown:
|
||||
default-days: 7
|
||||
commit-message:
|
||||
prefix: ci
|
||||
include: scope
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
#
|
||||
# The `quality` job is local because the ops reusable runs NO quality gates at
|
||||
# all: its entire surface is install → build → assert manifest_version == 3 →
|
||||
# zip → upload. Lint, type-check, knip, coverage and the grep gate are ours.
|
||||
# zip → upload. Lint, type-check, knip, coverage, audit and the grep gate are
|
||||
# ours.
|
||||
name: CI
|
||||
|
||||
on:
|
||||
@@ -26,16 +27,29 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
|
||||
# --ignore-scripts: no dependency runs code at install time. `wxt prepare`
|
||||
# (our postinstall) generates .wxt/tsconfig.json, which tsconfig.json
|
||||
# extends, so it runs explicitly from the local binary.
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: npx --no-install wxt prepare
|
||||
|
||||
- run: npm run lint # biome check .
|
||||
- run: npm run check # svelte-check + tsc --noEmit
|
||||
- run: npm run check # svelte-check (TS 6 API) + tsc (TS 7) + scripts checkJs
|
||||
- run: npm run knip
|
||||
- run: npm run coverage # vitest --coverage, thresholds per docs/11 §1
|
||||
- run: npm run guard # the canonical grep gate, docs/08 §3
|
||||
- run: npm run guard # the zero-network / no-raw-HTML gate, docs/08 §3
|
||||
|
||||
# Zero runtime dependencies is a public claim (README, docs/09 T5); this
|
||||
# is the check that keeps it true. Dev-only advisories are tracked by
|
||||
# Dependabot and docs/09 §3.1, not here.
|
||||
- run: npm audit --omit=dev --audit-level=low
|
||||
|
||||
# The unit test proves what wxt.config.ts ASKS for. Only this proves what
|
||||
# WXT actually emitted — a dev build of the same config carries
|
||||
@@ -43,6 +57,28 @@ jobs:
|
||||
- run: npm run build
|
||||
- run: npm run check:manifest
|
||||
|
||||
windows:
|
||||
# Not a required check. The owner develops on Windows, and the paths that
|
||||
# only break there — drive letters and percent-encoding in script paths,
|
||||
# CRLF in a checkout — had no CI coverage at all.
|
||||
name: Windows smoke (guard + unit tests)
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: npx --no-install wxt prepare
|
||||
- run: npm run guard
|
||||
- run: npm test
|
||||
|
||||
build:
|
||||
name: Build + package
|
||||
needs: quality
|
||||
@@ -66,7 +102,9 @@ jobs:
|
||||
# 'none' default skips install and build, then fails on
|
||||
# `test -f ./manifest.json` — a file WXT never writes to the repo root.
|
||||
package-manager: 'npm'
|
||||
node-version: '24'
|
||||
# A string input, so it cannot read .nvmrc — keep it equal by hand
|
||||
# (docs/01 §2).
|
||||
node-version: '26'
|
||||
build-command: 'npm run build'
|
||||
source-dir: '.output/chrome-mv3'
|
||||
release: false
|
||||
@@ -39,4 +39,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
secrets: inherit
|
||||
# Named, not `inherit`: the reusable is pinned to a moving branch, so it gets
|
||||
# the one secret it declares and nothing else.
|
||||
secrets:
|
||||
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
|
||||
@@ -4,6 +4,12 @@
|
||||
# runs `gh release create --generate-notes`. It produces no SHA256SUMS.txt
|
||||
# (required by docs/09 §5), performs no store submission, and exposes no
|
||||
# `outputs:`, so a caller cannot reference the zip it built.
|
||||
#
|
||||
# Three jobs, least privilege first. `build` installs, runs every gate and
|
||||
# packages with a READ-ONLY token; only `publish`, which installs nothing and
|
||||
# runs no repository code, ever holds `contents: write`. Before this split one
|
||||
# job ran `npm ci` — every dependency's install script plus our own tests —
|
||||
# while holding a write token that checkout had also left in .git/config.
|
||||
name: Release
|
||||
|
||||
on:
|
||||
@@ -14,18 +20,22 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release:
|
||||
build:
|
||||
name: Gate + package
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: write # create the GitHub Release
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: npx --no-install wxt prepare
|
||||
|
||||
# The same gates as CI. A tag must never ship what a PR would have
|
||||
# blocked — pushing a tag skips the CI workflow's branch triggers.
|
||||
@@ -34,6 +44,7 @@ jobs:
|
||||
- run: npm run knip
|
||||
- run: npm run coverage
|
||||
- run: npm run guard
|
||||
- run: npm audit --omit=dev --audit-level=low
|
||||
|
||||
- run: npm run zip # wxt zip → .output/<name>-<version>-chrome.zip
|
||||
|
||||
@@ -53,67 +64,109 @@ jobs:
|
||||
working-directory: .output
|
||||
run: sha256sum *-chrome.zip > SHA256SUMS.txt
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-${{ github.ref_name }}
|
||||
path: |
|
||||
.output/*-chrome.zip
|
||||
.output/SHA256SUMS.txt
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
|
||||
publish:
|
||||
name: GitHub Release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write # create the GitHub Release — the only write in this file
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: release-${{ github.ref_name }}
|
||||
path: dist
|
||||
|
||||
# The bytes about to be published are the bytes the build job hashed.
|
||||
- name: Re-verify checksums
|
||||
working-directory: dist
|
||||
run: sha256sum -c SHA256SUMS.txt
|
||||
|
||||
# Idempotent on purpose. `gh release create` fails outright if a Release
|
||||
# for the tag already exists, so any failure AFTER this step — realistically
|
||||
# the CWS publish below, once CWS_AUTOPUBLISH is on — used to strand the
|
||||
# tag: re-running the workflow could not get past this line, and the only
|
||||
# recovery was deleting the Release and the tag by hand (docs/13 §7).
|
||||
- name: GitHub Release
|
||||
# the store job below, once CWS_AUTOPUBLISH is on — used to strand the tag:
|
||||
# re-running could not get past this line (docs/13 §7).
|
||||
- name: Create or update the Release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||
echo "Release $GITHUB_REF_NAME exists — re-uploading assets."
|
||||
gh release upload "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --clobber
|
||||
gh release upload "$GITHUB_REF_NAME" dist/*-chrome.zip dist/SHA256SUMS.txt --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
|
||||
gh release create "$GITHUB_REF_NAME" dist/*-chrome.zip dist/SHA256SUMS.txt \
|
||||
--verify-tag --generate-notes
|
||||
fi
|
||||
|
||||
# v1.0.x is published by hand (docs/12 §3) — first store reviews often
|
||||
# ask questions and want a human in the loop. Flipping the repo variable
|
||||
# CWS_AUTOPUBLISH to 'true' turns this on for v1.1+.
|
||||
- name: Publish to Chrome Web Store
|
||||
if: vars.CWS_AUTOPUBLISH == 'true'
|
||||
store:
|
||||
# v1.0.x/v1.1.x are published by hand (docs/12 §3). Flipping the repo
|
||||
# variable CWS_AUTOPUBLISH to 'true' turns this on once the four CHROME_*
|
||||
# secrets exist. A variable, not a secret: only variables are allowed here.
|
||||
name: Publish to Chrome Web Store
|
||||
needs: publish
|
||||
if: vars.CWS_AUTOPUBLISH == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
- run: npm ci --ignore-scripts
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: release-${{ github.ref_name }}
|
||||
path: dist
|
||||
- name: Submit the Release asset
|
||||
env:
|
||||
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
|
||||
CHROME_CLIENT_ID: ${{ secrets.CHROME_CLIENT_ID }}
|
||||
CHROME_CLIENT_SECRET: ${{ secrets.CHROME_CLIENT_SECRET }}
|
||||
CHROME_REFRESH_TOKEN: ${{ secrets.CHROME_REFRESH_TOKEN }}
|
||||
run: npx wxt submit --chrome-zip .output/*-chrome.zip
|
||||
# The locally installed wxt, never `npx wxt`: npx may fetch and run an
|
||||
# unpinned package with these four secrets in its environment.
|
||||
run: ./node_modules/.bin/wxt submit --chrome-zip dist/*-chrome.zip
|
||||
|
||||
# A job INSIDE this workflow, not an `on: release: [published]` caller.
|
||||
# A Release created by `gh release create` under the default GITHUB_TOKEN
|
||||
# emits no event that starts new workflow runs, so an event-driven caller
|
||||
# would silently never fire.
|
||||
announce:
|
||||
needs: release
|
||||
# A Discord notification is not part of the release. The reusable exits 1 on
|
||||
# "No webhooks configured" when DISCORD_RELEASES_WEBHOOK and
|
||||
# DISCORD_REPO_WEBHOOK are both unset (docs/12 §5 lists them as optional),
|
||||
# which turned the v1.0.0 run red even though the Release, the zip and
|
||||
# SHA256SUMS.txt had all published correctly. A red run on a good release is
|
||||
# worse than a missing announcement: it trains you to ignore the colour.
|
||||
#
|
||||
# ⚠️ This used to say `continue-on-error: true`, which GitHub REJECTS on a
|
||||
# job that calls a reusable workflow — "Property continue-on-error is not
|
||||
# allowed". The whole file is then invalid and the run is a startup_failure
|
||||
# with zero jobs and no log, exactly like the `contents: write` mistake in
|
||||
# 2c8fba9. It was never caught because that fix landed after the v1.0.0 tag
|
||||
# and no tag has been pushed since, so the first v1.0.1 tag would have been
|
||||
# its first execution. Gate on a repo VARIABLE instead — allowed in `if:`,
|
||||
# unlike a secret, and the same idiom as CWS_AUTOPUBLISH above.
|
||||
needs: publish
|
||||
# A Discord notification is not part of the release, so it can never turn a
|
||||
# good release red (docs/12 §2.3). Gated on a repo VARIABLE — GitHub REJECTS
|
||||
# `continue-on-error` on a job that calls a reusable workflow, which makes
|
||||
# the whole file a startup_failure with zero jobs and no log.
|
||||
if: vars.DISCORD_ANNOUNCE == 'true'
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
permissions:
|
||||
contents: read
|
||||
with:
|
||||
# REQUIRED here, and only because of the comment above. The reusable
|
||||
# resolves `TAG="${INPUT_TAG:-$EVENT_TAG}"` with EVENT_TAG =
|
||||
# github.event.release.tag_name — which is empty under `on: push: tags`,
|
||||
# so without this the job exits 1 on "No release tag available" and the
|
||||
# announcement never fires for any release.
|
||||
# REQUIRED here: the reusable resolves `TAG="${INPUT_TAG:-$EVENT_TAG}"`
|
||||
# with EVENT_TAG = github.event.release.tag_name — empty under
|
||||
# `on: push: tags` — so without this the job exits 1 and never announces.
|
||||
tag_override: ${{ github.ref_name }}
|
||||
secrets: inherit
|
||||
# Named, not `inherit`: the reusable is pinned to a moving branch, so it gets
|
||||
# only the two webhooks it reads — never the CHROME_* or SONAR secrets. The
|
||||
# names also differ: this repo stores RELEASES_WEBHOOK / REPO_WEBHOOK, while
|
||||
# the reusable reads DISCORD_* — with `inherit` it received neither and would
|
||||
# have failed on "No webhooks configured" the day DISCORD_ANNOUNCE was set.
|
||||
secrets:
|
||||
DISCORD_RELEASES_WEBHOOK: ${{ secrets.RELEASES_WEBHOOK }}
|
||||
DISCORD_REPO_WEBHOOK: ${{ secrets.REPO_WEBHOOK }}
|
||||
@@ -0,0 +1,79 @@
|
||||
# SonarCloud — docs/12 §2.5.
|
||||
#
|
||||
# A separate workflow on purpose, not a job in ci.yml: a SonarCloud outage or a
|
||||
# quality-gate opinion must never change the colour of CI, which is what branch
|
||||
# protection reads ("Quality gates", "Build + package / build"). The verdict
|
||||
# reaches the PR through the SonarCloud GitHub App's own check.
|
||||
#
|
||||
# ⚠️ Prerequisite: Automatic Analysis is OFF in the SonarCloud project
|
||||
# (Administration → Analysis Method). With it on, the scanner refuses to run.
|
||||
name: SonarCloud
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: sonarcloud-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: SonarCloud analysis
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
# Full history: Sonar's new-code detection and blame need it.
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
|
||||
# --ignore-scripts: no dependency gets to run code at install time. Our own
|
||||
# postinstall (`wxt prepare`) is the one script we need, so it runs
|
||||
# explicitly — from the local binary, never fetched on demand.
|
||||
- run: npm ci --ignore-scripts
|
||||
- run: npx --no-install wxt prepare
|
||||
|
||||
# lcov for Sonar; the docs/11 §1 thresholds still gate core here too.
|
||||
- run: npm run coverage
|
||||
|
||||
- name: Read the package version
|
||||
id: pkg
|
||||
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# The token is scoped to the two steps that need it, so the install and
|
||||
# the test run above never see it. Dependabot and fork PRs get no repo
|
||||
# secrets at all: they skip the scan with a notice instead of failing.
|
||||
- name: Check for SONAR_TOKEN
|
||||
id: token
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
if [ -n "$SONAR_TOKEN" ]; then
|
||||
echo "present=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "present=false" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::SonarCloud scan skipped — SONAR_TOKEN is not available to this run (Dependabot or fork PR)."
|
||||
fi
|
||||
|
||||
- name: SonarCloud scan
|
||||
if: steps.token.outputs.present == 'true'
|
||||
# Pinned to a commit, not a moving tag: this step holds a token. Dependabot
|
||||
# proposes updates (with the repo's 7-day cooldown).
|
||||
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
with:
|
||||
args: >
|
||||
-Dsonar.projectVersion=${{ steps.pkg.outputs.version }}
|
||||
+8
-4
@@ -7,10 +7,14 @@ node_modules/
|
||||
stats.html
|
||||
stats-*.json
|
||||
|
||||
# Test / coverage
|
||||
# Test / coverage (Vitest 5 writes reporter output under .vitest/)
|
||||
coverage/
|
||||
.vitest/
|
||||
*.tsbuildinfo
|
||||
|
||||
# WXT runner config — holds local browser paths, never shared
|
||||
web-ext.config.ts
|
||||
|
||||
# Editors
|
||||
.idea/
|
||||
.vs/
|
||||
@@ -33,8 +37,8 @@ npm-debug.log*
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Generated fixtures that are too big to commit (tests/fixtures/generate-huge.ts
|
||||
# writes here on demand — docs/11 §2)
|
||||
# Generated fixtures that are too big to commit (scripts/gen-fixture.mjs writes
|
||||
# here on demand — docs/11 §2)
|
||||
tests/fixtures/generated/
|
||||
|
||||
.claude/
|
||||
.claude/
|
||||
@@ -0,0 +1,6 @@
|
||||
# Supply-chain cooldown (docs/01 §6): resolve every install to the newest
|
||||
# release that has been public for at least 7 days. Malicious versions
|
||||
# published to npm have historically been caught and pulled within hours to
|
||||
# days; a week of age keeps this repo out of that window. Units are DAYS.
|
||||
# Dependabot applies the same rule through `cooldown` in dependabot.yml.
|
||||
min-release-age=7
|
||||
@@ -15,6 +15,9 @@ Nothing yet.
|
||||
|
||||
## [1.0.1] — 2026-08-03
|
||||
|
||||
Released and submitted 2026-08-03; live on the Chrome Web Store (confirmed on
|
||||
the listing 2026-10-28).
|
||||
|
||||
Stabilization, from the first pass over the shipped extension. No new features,
|
||||
no change to permissions, and nothing you have to do — Chrome updates itself.
|
||||
|
||||
|
||||
@@ -6,9 +6,10 @@ This file is the entry point; the `docs/` suite is the specification.
|
||||
|
||||
> ## ⚠️ This is shipped software
|
||||
>
|
||||
> **v1.0.0 is published on the Chrome Web Store and has real users** (submitted
|
||||
> 2026-07-26, live by 2026-08-03). Phases 0–5 are complete; the project is in
|
||||
> **maintenance**. That changes the rules of the game:
|
||||
> **BookmarkMagic is published on the Chrome Web Store and has real users**
|
||||
> (v1.0.0 live by 2026-08-03; v1.0.1 live, confirmed on the listing
|
||||
> 2026-10-28). Phases 0–6 are complete; the project is in **maintenance**.
|
||||
> That changes the rules of the game:
|
||||
>
|
||||
> - Every change now reaches installed users through a store review. It needs a
|
||||
> semver bump, a `CHANGELOG.md` entry and an update submission — `13 §1b`.
|
||||
@@ -110,10 +111,11 @@ install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
|
||||
clean-install test. Also carried in from the Phase 4 review:
|
||||
- ✔ About's "Changelog" link now targets `CHANGELOG.md`, pinned by
|
||||
`tests/unit/links.test.ts`;
|
||||
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). **It has since
|
||||
grown back to 481** (script block 300) via the Phase 5 review commits — 19
|
||||
lines of headroom against the hard 500. Anything added there now has to come
|
||||
out first; `src/lib/edit/` is where extracted logic goes;
|
||||
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). It grew back
|
||||
through the Phase 5 and 6 review commits — **476 lines with a 356-line script
|
||||
block** as of 2026-10-28, against a 150-line soft limit for script blocks
|
||||
(docs/10 §1). Anything added there has to come out first; `src/lib/edit/` is
|
||||
where extracted logic goes;
|
||||
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
|
||||
the build on any text pair under 4.5:1. Two blind spots to know about: it is
|
||||
token-level, so it cannot see the `opacity`-on-text bypass it was written to
|
||||
@@ -129,9 +131,8 @@ machinery (`.github/ISSUE_TEMPLATE`, `CONTRIBUTING.md`, the sanitizer — docs/1
|
||||
reporting and the routing deadlock → localized `#edit`/`#export` failures and
|
||||
bounded search expansion → cross-tab settings/legal sync → dependency bumps and
|
||||
CI hardening → the About store link → cut 1.0.1.
|
||||
**Exit:** `main` tag-ready, docs/11 §5 manual pass green including the
|
||||
**1.0.0 → 1.0.1 upgrade over an existing profile**; the human signs and pushes
|
||||
the tag and performs the store update per docs/13 §1b.
|
||||
**Exit:** ✔ v1.0.1 tagged and released 2026-08-03, live on the store
|
||||
(confirmed 2026-10-28).
|
||||
|
||||
## Working style
|
||||
|
||||
|
||||
+9
-2
@@ -21,8 +21,15 @@ node scripts/sanitize-bookmarks.mjs your-bookmarks.html
|
||||
It needs nothing installed — plain Node. It writes
|
||||
`your-bookmarks.sanitized.html` next to the original, and prints what it found.
|
||||
|
||||
It reads the usual `bookmarks.html` export, a BookmarkMagic JSON file, Chrome's
|
||||
profile `Bookmarks` file (also Edge, Brave and Vivaldi), a Firefox
|
||||
`bookmarks-YYYY-MM-DD.json` backup, and our CSV. It refuses anything else rather
|
||||
than guess, and it refuses to write if its own output still looks personal.
|
||||
|
||||
What it **destroys**: every hostname, path, query value and fragment; every
|
||||
bookmark and folder title; Firefox keywords and tags; favicon data.
|
||||
bookmark and folder title and description; Firefox keywords and tags; favicon
|
||||
data; local `file:` paths; in JSON, every string except structural fields
|
||||
(types, ids, timestamps), including Chrome's `meta_info` and sync blob.
|
||||
|
||||
What it **keeps**, because this is where the bug lives: the byte order mark, the
|
||||
doctype, the `<META>` line, comments, line endings, indentation, tag and
|
||||
@@ -110,7 +117,7 @@ The full ritual, in order, because it is easy to do four fifths of it:
|
||||
line-ending normalization cannot rewrite the CRLF or BOM bytes the bug may
|
||||
depend on — do not "fix" that.
|
||||
2. **Add the regression test** to `tests/unit/core/fixtures.test.ts`, the only
|
||||
fixture-driven suite. A browser export goes in its `BROWSER_EXPORTS` array,
|
||||
parser regression suite. A browser export goes in its `BROWSER_EXPORTS` array,
|
||||
which drives a shared set of assertions; anything else gets its own case.
|
||||
There is no shared fixture-loading helper — that file has its own loader.
|
||||
3. **Fix the parser** in `src/lib/core/parse/`. The test and the fix land in the
|
||||
|
||||
@@ -38,8 +38,10 @@ folder trees. English · Tiếng Việt · 日本語.
|
||||
This is the whole point of the project, so it is worth being precise.
|
||||
|
||||
- **No network access at all.** Not analytics, not telemetry, not update pings.
|
||||
There is no server. A grep gate (`npm run guard`) fails the build if anyone
|
||||
adds `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource` or `sendBeacon`.
|
||||
There is no server. The browser enforces it: the extension's content security
|
||||
policy sets `connect-src 'none'`, so Chrome itself refuses any request an
|
||||
extension page tries to make. On top of that, `npm run check:manifest` scans
|
||||
the shipped bundle for network APIs and `npm run guard` scans the source.
|
||||
- **Exactly two permissions**: `bookmarks` and `storage`. No host permissions,
|
||||
no content scripts, no background worker. Two gates enforce it: a unit test
|
||||
over `wxt.config.ts`, and `npm run check:manifest`, which CI runs against the
|
||||
@@ -64,7 +66,11 @@ Full policy: [`legal/PRIVACY.md`](legal/PRIVACY.md).
|
||||
|
||||
From the Chrome Web Store: [here](https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg)
|
||||
|
||||
From source:
|
||||
Requires Chrome 136 or later (April 2025), or any Chromium browser of the same
|
||||
vintage — Edge, Brave, Vivaldi, Opera. On an older browser the store keeps the
|
||||
version you already have and simply stops updating it.
|
||||
|
||||
From source (Node.js 26):
|
||||
|
||||
```bash
|
||||
npm ci && npm run build
|
||||
|
||||
+13
-2
@@ -1,9 +1,20 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/2.5.5/schema.json",
|
||||
"$schema": "https://biomejs.dev/schemas/2.6.2/schema.json",
|
||||
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
"includes": ["**", "!**/*.svelte", "!**/*.css", "!.output", "!.wxt", "!tests/fixtures"]
|
||||
"includes": [
|
||||
"**",
|
||||
"!**/*.svelte",
|
||||
"!**/*.css",
|
||||
"!**/*.md",
|
||||
"!**/*.yml",
|
||||
"!**/*.yaml",
|
||||
"!.output",
|
||||
"!.wxt",
|
||||
"!coverage",
|
||||
"!tests/fixtures"
|
||||
]
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
|
||||
+13
-18
@@ -12,17 +12,16 @@
|
||||
> Signed tag `v1.0.0`, GitHub Release with a checksum-verified zip. Verified
|
||||
> working on real Chrome and Brave.
|
||||
>
|
||||
> **v1.0.1 was tagged, released and submitted to the store on 2026-08-03** —
|
||||
> ⚠️ **in review, not yet approved.** Users are still on 1.0.0 until it clears.
|
||||
> Do not describe 1.0.1 as published anywhere until the listing says so; this
|
||||
> suite spent a week claiming "in review" *after* approval, and claiming the
|
||||
> reverse would be the worse half of the same mistake.
|
||||
> **v1.0.1 is PUBLISHED.** Tagged, released and submitted 2026-08-03; the
|
||||
> listing was observed showing **version 1.0.1** (`Updated: August 3, 2026`,
|
||||
> 5 users) on 2026-10-28. ⚠️ The exact approval date was never recorded — the
|
||||
> owner can read it from the dashboard. Installed users are on 1.0.1.
|
||||
>
|
||||
> The project is now in **maintenance**, not construction: every change from
|
||||
> here reaches installed users through a store review, so it needs a version
|
||||
> bump, a CHANGELOG entry and an update submission (`13 §1b`). Sequencing lives
|
||||
> in `/CLAUDE.md`; what is still open is in §10 below.
|
||||
> **Doc suite version:** 1.6 (2026-08-03 — v1.0.1 submitted)
|
||||
> **Doc suite version:** 1.7 (2026-10-28 — v1.0.1 published; v1.1.0 in progress)
|
||||
|
||||
---
|
||||
|
||||
@@ -173,10 +172,9 @@ Derived identifiers (canonical across docs and code):
|
||||
the four is already known — `CHROME_EXTENSION_ID` is the item id in §9. The
|
||||
other three come from `npx wxt submit init` (`12 §3`). Note there is no
|
||||
dry-run: the first time that step executes it makes a real submission.
|
||||
7. **Untested:** `npm run dev:firefox` against the `overrides` block in
|
||||
`09 §3.1`. Four of those overrides sit under `web-ext-run` and no gate
|
||||
exercises that script. Firefox is a v1.0 non-goal (§7), so this blocks
|
||||
nothing — but do not assume it works.
|
||||
7. **Untested:** `npm run dev:firefox`. No gate exercises it (Firefox is a
|
||||
non-goal, §7). The `overrides` block that used to threaten it is gone
|
||||
(`09 §3.1`), but do not assume it works.
|
||||
8. **Unmeasured:** the 2 s parse budget on a real browser (`11 §6`). The
|
||||
recorded 2869 ms is a jsdom figure and settles nothing. `scripts/gen-fixture.mjs`
|
||||
now produces the file needed to measure it.
|
||||
@@ -191,14 +189,11 @@ Derived identifiers (canonical across docs and code):
|
||||
tested.** `13 §1` step 8 became due at approval and no result is recorded.
|
||||
It is the only check that the artifact users actually receive matches what
|
||||
was tested. Now folded into `11 §5` as a standing pre/post-submission item.
|
||||
11. **v1.0.1 is in review — nothing records the outcome yet.** When it clears:
|
||||
add the "published" row to `15`'s progress table, note the date under the
|
||||
`1.0.1` CHANGELOG heading the way `1.0.0` carries one, and run `13 §1b`
|
||||
step 10 (dashboard shows the new version → install on a clean profile →
|
||||
re-run the upgrade check against the *published* build). If it is instead
|
||||
**rejected**, `13 §7` is the procedure — and the rejection and its
|
||||
resolution belong in `15`'s decision log, since that is the only memory this
|
||||
project has of what reviewers actually object to.
|
||||
11. ✔ **v1.0.1 cleared review** — the listing showed 1.0.1 when checked on
|
||||
2026-10-28, and the "published" row is in `15`'s progress table. ⚠️ Still
|
||||
open: the exact approval date, and `13 §1b` step 10 against the published
|
||||
build (install on a clean profile, re-run the upgrade check) — no result is
|
||||
recorded for either.
|
||||
|
||||
## 11. Reading order
|
||||
|
||||
|
||||
+31
-22
@@ -1,6 +1,7 @@
|
||||
# 01 — Tech Stack
|
||||
|
||||
> Versions verified against npm/official sources on **2026-07-25**.
|
||||
> Versions verified against npm/official sources on **2026-10-28** (first pass
|
||||
> 2026-07-25).
|
||||
> Rule: latest stable or LTS only, with any deliberate exception stated inline.
|
||||
> Re-verify minor/patch at scaffold time (`npm outdated`), but do NOT jump
|
||||
> majors without a doc update.
|
||||
@@ -10,26 +11,27 @@
|
||||
| Item | Choice | Rationale |
|
||||
|---|---|---|
|
||||
| Browser | Chrome / Chromium, **Manifest V3** | MV2 is fully retired. Edge/Brave/Vivaldi/Opera work from the same build. |
|
||||
| Min Chrome | `minimum_chrome_version: "120"` | Margin over our highest hard-floor API, `runtime.getContexts()` (116+). `scheduler.yield()` (129+) is used only behind a nullish fallback, so it does not raise the floor — see `08 §7`. |
|
||||
| Runtime deps | **0 (zero)** | `DOMParser`, `Blob`, `URL`, `crypto.randomUUID` cover all needs. |
|
||||
| Min Chrome | `minimum_chrome_version: "136"` (was `"120"` through v1.0.1) | The ES2025 floor: 136 is the first Chrome with every ES2025 built-in (`RegExp.escape` 136, `Float16Array` 135, `Promise.try` 128, iterator helpers and Set methods 122). The manifest floor, Vite's `build.target` (`chrome136`) and tsconfig's `lib: ["ES2025", …]` are one number stated three times — `wxt.config.ts` derives two of them from `CHROME_FLOOR`, and `tests/unit/manifest.test.ts` pins all three. Users on Chrome 120–135 keep the version they have and stop receiving updates; nothing is uninstalled. `scheduler.yield()` (129+) is now always present, though the write queue keeps its fallback because the test environment has no `scheduler`. |
|
||||
| Runtime deps | **0 (zero)** | `DOMParser`, `Blob`, `URL`, `showSaveFilePicker` and `navigator.clipboard` cover all needs. "Zero" means no npm `dependencies`: the compiled Svelte runtime still ships inside the bundle — see `legal/THIRD_PARTY_NOTICES.md`. |
|
||||
|
||||
## 2. Toolchain (dev dependencies)
|
||||
|
||||
| Tool | Version (2026-07) | Role |
|
||||
|---|---|---|
|
||||
| Node.js | **24.x (Active LTS)** | Build runtime. Active LTS until Oct 2026, maintained to 2028-04-30. Node 26 is *Current*, not LTS — do not use for production tooling yet. |
|
||||
| npm | bundled with Node 24 (v11) | Package manager. Commit `package-lock.json`. |
|
||||
| **WXT** | **^0.21.3** (was ^0.20.27 through v1.0.0) | Extension framework: entrypoints, manifest generation, HMR, `wxt zip`, `wxt submit`. **0.x, so a minor is semver's breaking slot** — and 0.21 was: `wxt/testing` split into `wxt/testing/fake-browser` and `wxt/testing/vitest-plugin`, and `tabs.create` is now typed as returning `void`. Both are dev-only. Never take a WXT bump without diffing the **built** manifest before and after (`12 §2.3`); `tests/unit/manifest.test.ts` reads `wxt.config.ts` and is structurally incapable of noticing. |
|
||||
| **TypeScript** | **~6.0.3** (strict) | Deliberate exception to "latest stable": TS **7.0 went GA 2026-07-08** (7.0.2 is `dist-tags.latest`), but the Go-native compiler exposes no stable programmatic API yet and Microsoft's own GA post says Svelte/Volar toolchains "can only currently rely on TypeScript 6.0" — full support is deferred to 7.1. Since `svelte-check` is our template type authority, we hold on 6.x. Pin with `~` (patch-only). Revisit when TS 7.1 ships **and** svelte-check declares support. |
|
||||
| **Svelte** | **^5.56.4** | UI, runes mode only (`$state`, `$derived`, `$effect`, `$props`). |
|
||||
| @wxt-dev/module-svelte | latest at scaffold | WXT ↔ Svelte integration. |
|
||||
| **Biome** | **2.5.2 (pinned exact)** | Lint + format (replaces ESLint + Prettier). Install with `npm i -D -E @biomejs/biome` per Biome guidance. |
|
||||
| svelte-check | ^4.7.4 | Type/template authority for `.svelte` files. |
|
||||
| **@types/node** | **^24** (matches the Node major) | Types for `node:fs`, `node:path`, `node:child_process` and `process`, which the test suite and `scripts/*.mjs` genuinely use. **Declared explicitly since 2026-08-03** — it used to arrive transitively, and WXT 0.21 stopped providing it. Types only: erased at build, so hard rule 2 (zero *runtime* dependencies) is untouched. |
|
||||
| jsdom | **^30** (was ^29 through v1.0.0) | Test DOM. Not interchangeable — `02 §3` picks jsdom over happy-dom because the Netscape walk depends on parse5's implied-end-tag behaviour. A major bump runs `tests/unit/dom-environment.test.ts` first; if that canary fails, pin rather than loosen the test. |
|
||||
| **Knip** | **^6** (6.29.0 latest as of 2026-07) | Dead code: unused files, exports, dependencies. Requires Node ≥ 20.19. v6 swapped the TypeScript backend for oxc-parser — confirm `compilers.svelte` is still the supported `.svelte` hook before scaffold (`10 §4`). |
|
||||
| **Vitest** | latest stable at scaffold | Unit tests for `src/lib/core`. |
|
||||
| @vitest/coverage-v8 | match Vitest | Coverage reporting. |
|
||||
| Node.js | **26.x (Active LTS)** (was 24.x through v1.0.1) | Build runtime. Node 26 entered Active LTS on 2026-10-28 (maintenance from 2027-10-20, end of life 2029-04-30); Node 24 moved to maintenance on 2026-10-20. `.nvmrc`, `engines` and every CI job say 26 — CI reads `.nvmrc` where it can, and passes `'26'` to the ops reusable, which takes a string input. |
|
||||
| npm | bundled with Node 26 (v11.20+) | Package manager. Commit `package-lock.json`. `.npmrc` sets `min-release-age=7` (§6). |
|
||||
| **WXT** | **^0.21.4** (was ^0.20.27 through v1.0.0) | Extension framework: entrypoints, manifest generation, HMR, `wxt zip`, `wxt submit`. **0.x, so a minor is semver's breaking slot** — and 0.21 was: `wxt/testing` split into `wxt/testing/fake-browser` and `wxt/testing/vitest-plugin`, and `tabs.create` is now typed as returning `void`. Both are dev-only. Never take a WXT bump without diffing the **built** manifest before and after (`12 §2.3`); `tests/unit/manifest.test.ts` reads `wxt.config.ts` and is structurally incapable of noticing. |
|
||||
| **TypeScript** | **7.0 for `tsc`, 6.0 for the API** (strict) | Two packages under two names, Microsoft's documented side-by-side setup for toolchains that embed the compiler: `"@typescript/native": "npm:typescript@~7.0.2"` provides the `tsc` binary (the Go-native 7.0 compiler that type-checks every `.ts` file in `npm run check`), and `"typescript": "npm:@typescript/typescript6@~6.0.2"` keeps the TS 6.0 programmatic API under the `typescript` module name (it re-exports the real `typescript@6.0.x` and adds a `tsc6` binary). svelte-check (peer `typescript ^5 || ^6`) and Volar need that API — TS 7 has none until 7.1 — so `.svelte` files are checked by 6.0 and `.ts` files by both. `tsc --version` must say 7.x and `tsc6 --version` 6.x. Drop the alias when svelte-check declares TS 7 support. Both pinned `~` (patch-only). |
|
||||
| **Svelte** | **^5.57.2** | UI, runes mode only (`$state`, `$derived`, `$effect`, `$props`). The compiled runtime ships in the bundle (MIT — `legal/THIRD_PARTY_NOTICES.md`). |
|
||||
| @sveltejs/vite-plugin-svelte | ^7.3.1 | Compiles `.svelte` and the runes in `.svelte.ts` stores for Vitest (`vitest.config.ts`). Its `deepmerge` dependency carries the one advisory with no fix (`09 §3.1`). |
|
||||
| @wxt-dev/module-svelte | ^2.0.5 | WXT ↔ Svelte integration. |
|
||||
| **Biome** | **2.6.2 (pinned exact)** | Lint + format (replaces ESLint + Prettier). Install with `npm i -D -E @biomejs/biome` per Biome guidance. 2.6 started formatting Markdown and YAML; both are excluded in `biome.json` so docs and workflows keep their hand layout (`10 §3`). |
|
||||
| svelte-check | ^4.7.7 | Type/template authority for `.svelte` files. Runs on the TS 6 API (see TypeScript above). |
|
||||
| **@types/node** | **^26** (matches the Node major) | Types for `node:fs`, `node:path`, `node:child_process` and `process`, which the test suite and `scripts/*.mjs` genuinely use. **Declared explicitly since 2026-08-03** — it used to arrive transitively, and WXT 0.21 stopped providing it. Types only: erased at build, so hard rule 2 (zero *runtime* dependencies) is untouched. |
|
||||
| jsdom | **^30.1** (was ^29 through v1.0.0) | Test DOM. Not interchangeable — `02 §3` picks jsdom over happy-dom because the Netscape walk depends on parse5's implied-end-tag behaviour. A major bump runs `tests/unit/dom-environment.test.ts` first; if that canary fails, pin rather than loosen the test. |
|
||||
| **Knip** | **^6** (6.42.1 as of 2026-10) | Dead code: unused files, exports, dependencies. Requires Node ≥ 20.19. v6 swapped the TypeScript backend for oxc-parser — confirm `compilers.svelte` is still the supported `.svelte` hook before scaffold (`10 §4`). |
|
||||
| **Vitest** | **^5.0.5** (was ^4 through v1.0.1) | Unit tests. 5.0 changed `clearMocks` to default `true`, requires `vi.mock` at top level and fails unawaited async assertions; the suite needed no changes. Requires Node ≥ 22.12. |
|
||||
| @vitest/coverage-v8 | match Vitest | Coverage reporting (`text` + `lcov` for SonarCloud, `12 §2.5`). |
|
||||
|
||||
## 3. Explicitly rejected
|
||||
|
||||
@@ -54,18 +56,21 @@
|
||||
```jsonc
|
||||
{
|
||||
"license": "GPL-3.0-or-later",
|
||||
"engines": { "node": ">=24" },
|
||||
"engines": { "node": ">=26" },
|
||||
"scripts": {
|
||||
"postinstall": "wxt prepare", // generates .wxt/tsconfig.json — 10 §2 extends it
|
||||
"dev": "wxt",
|
||||
"dev:firefox": "wxt -b firefox", // build sanity only, no store release
|
||||
"build": "wxt build",
|
||||
"zip": "wxt zip",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit && tsc -p tsconfig.scripts.json",
|
||||
// TS 6 API, the TS 7 tsc, then scripts/*.mjs via checkJs
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check --write .",
|
||||
"knip": "knip",
|
||||
"guard": "node scripts/guard.mjs", // canonical grep gate, 08 §3
|
||||
"guard": "node scripts/guard.mjs", // the source gate, 08 §3
|
||||
"check:manifest": "node scripts/check-manifest.mjs", // the built-artifact gate, 08 §3
|
||||
"icons": "node scripts/gen-icons.mjs", // regenerates the shipped icons (source of truth)
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"coverage": "vitest run --coverage",
|
||||
@@ -92,11 +97,15 @@ rule 8 requires before anything release-bearing.
|
||||
|
||||
Also set `repository`, `homepage` and `bugs` to
|
||||
`https://github.com/poli0981/bookmarkmagic` — `13`/`14` link to those URLs.
|
||||
Commit `.nvmrc` containing `24`.
|
||||
Commit `.nvmrc` containing `26`.
|
||||
|
||||
## 6. Version pinning policy
|
||||
|
||||
- `typescript` → `~` (patch only; TS minors can break svelte-check).
|
||||
- `@typescript/native` (TS 7 `tsc`) and `typescript` (the TS 6 API alias) → `~` (patch only; TS minors can break svelte-check). Dependabot ignores majors of both — a 7→8 or 6→7 jump is a doc decision, not a weekly bump.
|
||||
- `@biomejs/biome` → exact (`-E`), formatter output must be reproducible.
|
||||
- Everything else → `^`, with `package-lock.json` committed as source of truth.
|
||||
- Renovate/Dependabot: weekly, grouped, majors require manual review.
|
||||
- **Cooldown:** `.npmrc` `min-release-age=7` — installs resolve to the newest
|
||||
release that has been public for 7 days (npm counts days). Dependabot uses the
|
||||
same `cooldown`. Lockfile installs (`npm ci`) are not affected (`09 §3.1`).
|
||||
- Renovate/Dependabot: weekly, grouped, majors require manual review; WXT
|
||||
bumps arrive in their own PR (built-manifest diff, `12 §2.3`).
|
||||
+11
-6
@@ -46,11 +46,16 @@ log gives no warning — verify the output tree, not just the exit code.
|
||||
bookmarkmagic/
|
||||
├── CLAUDE.md # AI build instructions (root)
|
||||
├── wxt.config.ts # srcDir + manifest + svelte module
|
||||
├── biome.json / knip.json / tsconfig.json / vitest.config.ts
|
||||
├── .nvmrc # 24
|
||||
├── scripts/
|
||||
│ ├── guard.mjs # canonical grep gate (08 §3), run by npm run guard
|
||||
│ └── gen-icons.mjs # zero-dep placeholder PNG writer (16/32/48/128)
|
||||
├── biome.json / knip.json / tsconfig.json / tsconfig.scripts.json / vitest.config.ts
|
||||
├── sonar-project.properties # SonarCloud CI analysis (12 §2.5)
|
||||
├── .nvmrc / .npmrc # Node 26; min-release-age=7 (01 §2, §6)
|
||||
├── scripts/ # all plain .mjs, type-checked via checkJs
|
||||
│ ├── guard.mjs # the source gate (08 §3), run by npm run guard
|
||||
│ ├── check-manifest.mjs # the built-artifact gate (08 §3), npm run check:manifest
|
||||
│ ├── gen-icons.mjs # zero-dep PNG writer — the icons' source of truth
|
||||
│ ├── gen-fixture.mjs # large Netscape files for 11 §5/§6, never committed
|
||||
│ ├── sanitize-bookmarks.mjs # reporter-facing sanitizer (CLI entry, 09 §6)
|
||||
│ └── sanitize/ # its format modules: detect, mappers, spans, html, json, csv, leaks
|
||||
├── docs/ # this suite (00–15)
|
||||
├── legal/ # EULA.md, DISCLAIMER.md, PRIVACY.md, THIRD_PARTY_NOTICES.md
|
||||
├── src/
|
||||
@@ -220,7 +225,7 @@ submission (`08 §8`).
|
||||
|
||||
`browser/open-manager.ts`:
|
||||
1. `browser.runtime.getContexts({ contextTypes: ['TAB'] })` → find an existing
|
||||
manager context (requires Chrome 116+; we target 120+).
|
||||
manager context (requires Chrome 116+; the floor is 136 — `01 §1`).
|
||||
2. Found → `browser.tabs.update(tabId, { active: true })` +
|
||||
`browser.windows.update(windowId, { focused: true })` (no `tabs`
|
||||
permission needed for these calls).
|
||||
|
||||
+71
-29
@@ -11,7 +11,7 @@ export default defineConfig({
|
||||
name: '__MSG_appName__',
|
||||
description: '__MSG_appDesc__',
|
||||
default_locale: 'en',
|
||||
minimum_chrome_version: '120',
|
||||
minimum_chrome_version: String(CHROME_FLOOR), // 136 — the ES2025 floor, 01 §1
|
||||
permissions: ['bookmarks', 'storage'], // ← the complete list, forever (v1)
|
||||
action: { default_popup: 'popup.html' }, // WXT wires this automatically
|
||||
options_ui: { page: 'manager.html#settings', open_in_tab: true },
|
||||
@@ -34,32 +34,65 @@ deliberately avoids each (see `01_TECH_STACK.md §3`, `02_ARCHITECTURE.md §6`).
|
||||
## 3. Code integrity rules
|
||||
|
||||
- **No remotely hosted code.** All JS/CSS ships in the package. No CDN
|
||||
`<script>`, no `import()` of URLs, no `eval`, no `new Function`,
|
||||
no string `setTimeout`. MV3's default extension CSP —
|
||||
`script-src 'self' 'wasm-unsafe-eval'; object-src 'self';` — enforces this,
|
||||
and Chrome rejects any manifest that loosens it. Never add a custom
|
||||
`content_security_policy`.
|
||||
- **No runtime network requests at all** (stronger than required): no
|
||||
`fetch`, no remote favicons, no update pings. ⚠️ The default CSP does **not**
|
||||
help here — it has no `connect-src`/`img-src` at all and restricts code
|
||||
execution only, not network egress. The *only* thing enforcing the
|
||||
zero-network promise is the grep gate below.
|
||||
`<script>`, no `import()` of URLs, no `eval`, no `new Function`, no string
|
||||
`setTimeout`. The extension-page CSP (below) enforces this, and Chrome
|
||||
rejects any manifest that loosens the MV3 minimum.
|
||||
- **No runtime network requests at all** (stronger than required): no network
|
||||
calls, no remote favicons, no update pings. Three layers enforce it since
|
||||
v1.1.0 — the browser, a build gate and a source gate:
|
||||
|
||||
#### The canonical grep gate
|
||||
#### Layer 1 — the extension-page CSP (browser-enforced)
|
||||
|
||||
One pattern, defined **here and nowhere else**. `09 §1`, `09 §3`, `12 §2.1`
|
||||
and §8 below all reference this block rather than restating it — four
|
||||
divergent copies is exactly how a gate ends up weaker than the promise it
|
||||
guards.
|
||||
MV3's default extension CSP (`script-src 'self' 'wasm-unsafe-eval';
|
||||
object-src 'self';`) restricts code execution only; it has no `connect-src` or
|
||||
`img-src` at all. Until v1.0.1 that left a grep gate as the *only* thing between
|
||||
the product and its zero-network claim. The production manifest now declares:
|
||||
|
||||
```
|
||||
fetch\(|XMLHttpRequest|WebSocket|EventSource|sendBeacon|\beval\(|new Function|\{@html\}|(inner|outer)HTML\s*=|insertAdjacentHTML|import\s*\(
|
||||
script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:;
|
||||
style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none';
|
||||
worker-src 'self'; form-action 'none'; base-uri 'none'
|
||||
```
|
||||
|
||||
must return nothing across `src/` (which contains `entrypoints/` — `02 §2`
|
||||
sets `srcDir: 'src'`), excluding `*.test.ts`. Implemented as
|
||||
`scripts/guard.mjs` and run by `npm run guard`, so the same gate runs locally
|
||||
(in `npm run verify`) and in CI — it cannot drift between them.
|
||||
`connect-src 'none'` makes Chrome refuse every fetch, XHR, WebSocket,
|
||||
EventSource and beacon from an extension page; the rest closes remote images,
|
||||
stylesheets, fonts, media, frames and form posts. `style-src` keeps
|
||||
`'unsafe-inline'` because Svelte sets `style` attributes; there is **no
|
||||
`default-src`**, on purpose, because it would govern every unlisted directive. User-initiated
|
||||
navigation — an About link, or "Open" on a bookmark via `tabs.create` — is not
|
||||
governed by a page CSP and is not a request the extension makes (`09 §1`).
|
||||
|
||||
- **The rule is: only ever tighten.** Adding `'unsafe-*'`, a remote source, or
|
||||
removing a directive is a security regression, and `check:manifest` fails on
|
||||
any string other than the exact one above.
|
||||
- **Production builds only.** `wxt.config.ts` emits it when the command is
|
||||
`build` (so `npm run build` and `npm run zip`), because the dev server reloads
|
||||
the extension over a localhost websocket that `connect-src 'none'` blocks.
|
||||
- Vite's modulepreload polyfill is disabled (`modulePreload.polyfill: false`):
|
||||
it was the one network call in the shipped bundle, dead code for every Chrome
|
||||
at the floor.
|
||||
|
||||
#### Layer 2 — the built-artifact gate
|
||||
|
||||
`npm run check:manifest` (`scripts/check-manifest.mjs`) scans every `.js` file
|
||||
in `.output/chrome-mv3` for network APIs — including code that arrived through
|
||||
a dependency, which no source gate can see — and pins the manifest: MV3, the
|
||||
permission list, the exact key set, the Chrome floor, the exact CSP, and that
|
||||
every file the manifest and pages reference exists.
|
||||
|
||||
#### Layer 3 — the source gate
|
||||
|
||||
`npm run guard` (`scripts/guard.mjs`). **The rule set lives in that file, not
|
||||
here** — this section used to restate it, and the copy drifted (its `\{@html\}`
|
||||
matched only the literal `{@html}`). The script header explains each rule and
|
||||
`tests/unit/scripts/guard.test.ts` holds a passing and a failing case for every
|
||||
one, including the bypasses an audit found against the old line-by-line regexes
|
||||
(aliases, computed global access, multi-line calls, `+=`, `{ @html }`, remote
|
||||
`url()` in CSS, resource hints). It scans `src/**` — `.ts`, `.svelte`, `.html`,
|
||||
`.css` and friends — with no exemptions, matches across line breaks, and fails
|
||||
if it scanned nothing. Because identifiers are banned outright, the bare API
|
||||
names cannot appear in `src/` comments either; write "network call".
|
||||
|
||||
- **Minification: yes. Obfuscation: NO.** CWS has prohibited obfuscated code
|
||||
since 2018; WXT/Vite default minify (whitespace/identifier shortening) is
|
||||
allowed and sufficient. Never add an obfuscator plugin. Open-source repo +
|
||||
@@ -114,11 +147,19 @@ any of them changes (`09 §4`).
|
||||
event-driven only.
|
||||
- Extension pages (popup/manager) may use `DOMParser`, `Blob`, `<a download>`
|
||||
freely — these need no permissions.
|
||||
- `browser.runtime.getContexts()` (Chrome 116+) is our highest **hard**-floor
|
||||
API → `minimum_chrome_version: 120` gives margin. `scheduler.yield()`
|
||||
(Chrome 129+) is used only behind the nullish fallback in `05 §6`, so it does
|
||||
not raise the floor — but that fallback only works if it is written with
|
||||
explicit parentheses; see the warning there.
|
||||
- **The floor is Chrome 136** (`minimum_chrome_version: "136"`, since v1.1.0;
|
||||
120 before). It is set by the language, not by an extension API: 136 is the
|
||||
first Chrome with every ES2025 built-in, and tsconfig's `lib` is ES2025
|
||||
(`01 §1`). The highest extension-API floors are far below it —
|
||||
`browser.runtime.getContexts()` needs 116 and `scheduler.yield()` 129 — so
|
||||
`scheduler.yield()` is in fact always present. The write queue still keeps
|
||||
its nullish fallback (`05 §6`) because the test environment has no
|
||||
`scheduler`; it only works if written with explicit parentheses, see the
|
||||
warning there.
|
||||
- Raising the floor is a **user-visible** event even though it is not a
|
||||
permission change: a user below it keeps the installed version and simply
|
||||
stops receiving updates. Say so in the CHANGELOG, and never raise it in a
|
||||
patch release.
|
||||
|
||||
## 8. Review-readiness checklist (before every submission)
|
||||
|
||||
@@ -126,9 +167,10 @@ any of them changes (`09 §4`).
|
||||
"Load unpacked" on a fresh profile.
|
||||
- [ ] Manifest diff reviewed — permission list unchanged (`bookmarks`,
|
||||
`storage` only).
|
||||
- [ ] `npm run guard` passes (the canonical grep gate, §3). Note `{@html}` is
|
||||
**not** catchable by Biome — no such rule exists for Svelte — so this
|
||||
gate plus review is the whole enforcement.
|
||||
- [ ] `npm run guard` and `npm run check:manifest` pass (§3: the source gate,
|
||||
and the built-artifact gate that pins the CSP and scans the bundle). Note
|
||||
`{@html}` is **not** catchable by Biome — no such rule exists for Svelte —
|
||||
so the source gate plus review is its whole enforcement.
|
||||
- [ ] Right-click → Options lands on `#settings` both on a fresh profile and
|
||||
with a Manager tab already open on another route (§1 uses an undocumented
|
||||
URL fragment; `02 §5`).
|
||||
|
||||
+45
-33
@@ -4,9 +4,13 @@
|
||||
|
||||
1. **Zero data collection.** No analytics, no telemetry, no crash reporting,
|
||||
no update pings. There is no server.
|
||||
2. **Zero network activity at runtime.** Enforced by the canonical grep gate
|
||||
defined in `08_MV3 §3` — that block is the single source of truth for the
|
||||
pattern; do not restate it here.
|
||||
2. **Zero network activity at runtime.** Enforced in three layers, all in
|
||||
`08 §3`: the production CSP (`connect-src 'none'` — the browser itself
|
||||
refuses), `check:manifest`'s scan of the shipped bundle, and the source gate
|
||||
`scripts/guard.mjs`. Do not restate their rules here. Links the user
|
||||
chooses to open (About, the legal documents, "Open" on a bookmark) load in a
|
||||
browser tab; that is navigation the user asked for, not a request the
|
||||
extension makes.
|
||||
3. **Everything on-device.** Bookmarks are read/written via `chrome.bookmarks`
|
||||
locally; files are parsed in-page and downloaded via Blob URLs. `chrome.
|
||||
storage.local` holds only settings + legal flag (no `storage.sync` — even
|
||||
@@ -21,7 +25,7 @@
|
||||
| T2 | Malicious file — resource exhaustion (huge/deep/zip-bomb-style) | 500 MB file, 1M nodes, 10k-deep nesting | Pre-parse size cap 25 MB; node cap 100 000; depth cap 200 — typed errors, parse aborts early. Lazy tree rendering (§05 §9) bounds DOM size. |
|
||||
| T3 | Dangerous URLs in imported bookmarks (`javascript:`, `data:`) | Clicking them in #edit | Never rendered as `<a href>`; "Open" uses `tabs.create`, which refuses `javascript:`. UI marks non-http(s)/ftp/file/about/chrome schemes with a ⚠ badge; they are display-only. Imported URLs are stored verbatim (user's data, not ours to censor) — the browser's own bookmark UI applies its own rules. |
|
||||
| T4 | Data loss from destructive import | User picks "Replace all" casually | Non-skippable auto safety-backup (BM JSON download) *before* deletion; danger-styled confirm with exact counts; default mode is non-destructive new-folder. |
|
||||
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot + `npm audit` in CI; Biome installed exact-pinned. See §5.1 for the `overrides` block. |
|
||||
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot with a 7-day cooldown + `min-release-age=7`; `npm audit --omit=dev` in CI; Biome installed exact-pinned. See §3.1. |
|
||||
| T6 | Store-listing impersonation / trademark issues | — | Unique name + linked GitHub; report via CWS if cloned. |
|
||||
| T7 | XSS via filenames/titles echoed into UI (result cards, toasts) | Weird characters in file name | Same as T1 — text interpolation only; filenames additionally sanitized for the *download* name (`[\\/:*?"<>|]` → `_`). |
|
||||
| T8 | Clipboard abuse | "Copy URL" action | Uses `navigator.clipboard.writeText` on explicit user click only; never reads the clipboard. |
|
||||
@@ -61,11 +65,12 @@ mechanical was watching:
|
||||
|
||||
## 3. Secure coding rules (enforced)
|
||||
|
||||
- `{@html}` — **forbidden**. Enforced by the canonical grep gate (`08 §3`) and
|
||||
review. Biome has no rule for this: `noDangerouslySetInnerHtml` is a React
|
||||
- `{@html}` — **forbidden**. Enforced by the source gate (`scripts/guard.mjs`,
|
||||
`08 §3`) and review. Biome has no rule for this: `noDangerouslySetInnerHtml` is a React
|
||||
rule and does not see Svelte templates.
|
||||
- `innerHTML`, `outerHTML`, `insertAdjacentHTML` assignment — forbidden (same
|
||||
gate).
|
||||
- `innerHTML`, `outerHTML`, `insertAdjacentHTML`, `setHTMLUnsafe`,
|
||||
`createContextualFragment`, `srcdoc`, `document.write` — forbidden outright,
|
||||
reads included (same gate).
|
||||
- All user/file-derived strings cross into the DOM only via Svelte text
|
||||
bindings or `textContent`.
|
||||
- `URL` constructor for any URL handling; no string-splitting of URLs.
|
||||
@@ -77,32 +82,32 @@ mechanical was watching:
|
||||
≤120-char excerpt of the offending line (avoids log-injection weirdness in
|
||||
screenshots/issues).
|
||||
|
||||
### 3.1 The `package.json` `overrides` block
|
||||
### 3.1 Dev-dependency advisories
|
||||
|
||||
Six Dependabot alerts and six `npm audit` highs were all transitive **dev**
|
||||
dependencies that their parents pinned to vulnerable ranges, so Dependabot's own
|
||||
per-package PRs could not fix them — every one failed. `overrides` is the npm
|
||||
mechanism for exactly this, and it takes `npm audit` to **0**.
|
||||
**There is no `overrides` block any more** (removed 2026-10-28). The six pins
|
||||
added on 2026-07-26 (`shell-quote`, `adm-zip`, `tmp`, `uuid`, `esbuild`,
|
||||
`brace-expansion`) had all become dead: WXT 0.21 dropped `web-ext-run`, which
|
||||
four of them sat under, and Vite 8 bundles with rolldown rather than esbuild.
|
||||
None of the six packages was in the lockfile — and a stale override is worse
|
||||
than none, because the day the package returns it silently pins it.
|
||||
|
||||
| Override | Was | Reached through | Remove when |
|
||||
|---|---|---|---|
|
||||
| `shell-quote ^1.9.0` | 1.7.3 | `wxt > web-ext-run > fx-runner` | `web-ext-run` updates `fx-runner` |
|
||||
| `adm-zip ^0.6.0` | 0.5.18 | `wxt > web-ext-run > firefox-profile` | `web-ext-run` updates `firefox-profile` |
|
||||
| `tmp ^0.2.6` | 0.2.5 | `wxt > web-ext-run` | `web-ext-run` bumps `tmp` |
|
||||
| `uuid ^11.1.1` | 8.3.2 | `wxt > web-ext-run > node-notifier` | `web-ext-run` updates `node-notifier` |
|
||||
| `esbuild ^0.28.1` | 0.27.7 | `vite`, `wxt`, `unplugin` | vite/wxt allow 0.28.x |
|
||||
| `brace-expansion ^5.0.8` | 1.1.16 | `web-ext-run > multimatch > minimatch` | `multimatch` unpins `minimatch` |
|
||||
State after the v1.1.0 toolchain pass (Node 26, Vitest 5, Vite 8.3, WXT 0.21.4):
|
||||
|
||||
Four of the six exist only under **`web-ext-run`**, the Firefox dev runner
|
||||
behind `npm run dev:firefox` — which `00 §7` lists as a v1.0 non-goal, and which
|
||||
neither CI nor the Chrome build touches. ⚠️ **`npm run dev:firefox` is therefore
|
||||
the one script these overrides could plausibly break**, and it is the one script
|
||||
no gate exercises. Verify it by hand before relying on it.
|
||||
| Check | Result |
|
||||
|---|---|
|
||||
| `npm audit --omit=dev` | **0** — nothing third-party is a runtime dependency (CI runs this, `12 §2.1`) |
|
||||
| `npm audit` (dev included) | 3 low, one root cause: **`deepmerge`** (GHSA-gcqx-w48m-w2h4, prototype poisoning in `mergeObject`), reached through `@sveltejs/vite-plugin-svelte`. **No fixed version exists.** It merges the build's own plugin options at dev/build time — never user data, never in the shipped extension — so it is accepted and recorded rather than overridden. Re-check when the plugin drops or bumps it. |
|
||||
|
||||
Everything CI runs was re-verified after the overrides landed: lint, check,
|
||||
knip, coverage, guard, build, `check:manifest` and `zip`, plus a clean-room
|
||||
`npm ci`. Drop an override as soon as its parent ships the fix — a stale
|
||||
override silently holds a package back.
|
||||
How new advisories are kept out:
|
||||
|
||||
- `.npmrc` sets `min-release-age=7`, and Dependabot's `cooldown` is 7 days:
|
||||
a release must have been public for a week before this repo installs it. The
|
||||
2025 npm compromises were caught and pulled within hours to days, so that
|
||||
window is the point (`01 §6`).
|
||||
- `npm ci` installs exactly what the lockfile pins and is unaffected by the
|
||||
age rule — verified, not assumed.
|
||||
- Dependabot *security* PRs bypass `cooldown`; one for a version younger than
|
||||
a week may fail to resolve until it ages. That is the intended trade-off.
|
||||
|
||||
## 4. Permissions posture
|
||||
|
||||
@@ -140,9 +145,16 @@ a **minor-version** event at minimum.
|
||||
|
||||
**Sample files from reporters.** A bookmark file is a browsing history, so the
|
||||
policy asks reporters to run `scripts/sanitize-bookmarks.mjs` first — it rewrites
|
||||
every hostname, path, query value and title while preserving the structure,
|
||||
encoding, and timestamp magnitudes a parser bug depends on, so the sanitized file
|
||||
still reproduces. Anything received by email is kept only as long as needed to
|
||||
every hostname, path, query value, title, note, keyword and tag while preserving
|
||||
the structure, encoding, and timestamps a parser bug depends on, so the sanitized
|
||||
file still reproduces. It reads Netscape HTML, BookmarkMagic JSON, Chrome's
|
||||
profile `Bookmarks` file, Firefox `.json` backups and our CSV, and refuses
|
||||
anything else. JSON is rewritten default-deny (every string value except a short
|
||||
list of structural keys). Before writing, it checks its own output — no host but
|
||||
its `*.example` aliases, and for HTML no text left that is not a placeholder —
|
||||
and writes nothing if that check fails. Until 2026-10-28 it accepted any JSON
|
||||
and rewrote only `url`/`title`, so Chrome's profile file (titles under `name`)
|
||||
came out with every title intact. Anything received by email is kept only as long as needed to
|
||||
reproduce and fix, then deleted; `legal/PRIVACY.md` states the same to users.
|
||||
This is the receiving-side counterpart to §3's rule that error messages never
|
||||
echo more than a 120-character excerpt of file content.
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
| Unit | Soft limit | Hard limit |
|
||||
|---|---|---|
|
||||
| File (.ts / .svelte) | **300 lines** | **500 lines** — split before merging |
|
||||
| File (.ts / .svelte / .mjs) | **300 lines** | **500 lines** — split before merging |
|
||||
| Function / method | 50 lines | 80 lines |
|
||||
| Svelte component script block | 150 lines | move logic to a `.svelte.ts` store or `core/` |
|
||||
| Nesting depth | 3 | 4 |
|
||||
@@ -46,14 +46,18 @@ rather than assign `undefined`. Build nodes with conditional spreads
|
||||
- Discriminated unions over boolean flags for state
|
||||
(`{ kind: 'parsed', … } | { kind: 'error', … }`).
|
||||
|
||||
## 3. Biome — `biome.json` (2.5.x)
|
||||
## 3. Biome — `biome.json` (2.6.x)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/2.5.2/schema.json",
|
||||
"$schema": "https://biomejs.dev/schemas/2.6.2/schema.json",
|
||||
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||
// Svelte and CSS are excluded on purpose — see the note below.
|
||||
"files": { "includes": ["src/**", "tests/**", "*.ts", "!**/*.svelte", "!**/*.css"] },
|
||||
// Svelte, CSS, Markdown and YAML are excluded on purpose — see the notes below.
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
"includes": ["**", "!**/*.svelte", "!**/*.css", "!**/*.md", "!**/*.yml", "!**/*.yaml",
|
||||
"!.output", "!.wxt", "!coverage", "!tests/fixtures"]
|
||||
},
|
||||
"formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
|
||||
"javascript": { "formatter": { "quoteStyle": "single", "semicolons": "always", "trailingCommas": "all" } },
|
||||
"linter": {
|
||||
@@ -74,9 +78,13 @@ rather than assign `undefined`. Build nodes with conditional spreads
|
||||
(`switch-every-tab-hotkey`) excludes `.svelte` and `.css` instead, and we
|
||||
follow it rather than putting the build on an experimental flag.
|
||||
**`svelte-check` is the authority** for everything inside `.svelte`.
|
||||
- **Markdown and YAML are excluded since Biome 2.6**, which started formatting
|
||||
both. The docs and workflow files are laid out by hand (long explanatory
|
||||
comments, deliberate wrapping); letting a formatter own them would turn every
|
||||
doc edit into a reflow diff.
|
||||
- There is **no Biome rule that catches `{@html}`.** `noDangerouslySetInnerHtml`
|
||||
is a React rule and does not apply to Svelte. The ban in `09 §3` is enforced
|
||||
by the canonical grep gate (`08 §3`, run as `npm run guard`) and by review —
|
||||
by the source gate (`scripts/guard.mjs`, `08 §3`, run as `npm run guard`) and by review —
|
||||
not by the linter.
|
||||
- `overrides` block: `noDefaultExport` must be relaxed for **`**/*.svelte`**,
|
||||
not just `entrypoints/**` — every Svelte component is a default export,
|
||||
|
||||
+7
-4
@@ -9,10 +9,13 @@
|
||||
| Components/UI | Manual QA checklist (§5) | No component-test framework in v1 (cost/benefit) |
|
||||
| End-to-end | Out of scope v1 (Roadmap: Playwright + `--load-extension`) | — |
|
||||
|
||||
`vitest.config.ts`: `plugins: [WxtVitest()]` (WXT aliases/auto-imports resolve
|
||||
in tests), `environment: 'jsdom'`, `coverage.provider: 'v8'`,
|
||||
`coverage.thresholds: { lines: 90, functions: 90, branches: 85 }` scoped to
|
||||
`src/lib/core/**`.
|
||||
`vitest.config.ts`: `plugins: [svelte(), WxtVitest()]` (the svelte plugin
|
||||
compiles runes in `.svelte.ts` stores; WXT's resolves aliases and auto-imports),
|
||||
`environment: 'jsdom'`, `coverage.provider: 'v8'`. Coverage **measures** every
|
||||
`src/**/*.ts` module and writes `text` + `lcov` (SonarCloud reads the lcov,
|
||||
`12 §2.5`), but only core is **gated**: a glob threshold
|
||||
`'src/lib/core/**': { lines: 90, functions: 90, branches: 85 }`, so widening
|
||||
what is measured cannot change what is enforced.
|
||||
|
||||
**Environment canary.** Add one test asserting that a Chrome fixture parses to
|
||||
a `<DL>` nested *inside* its `<DT>` (`dl.querySelector('dt').querySelector(':scope > dl') !== null`).
|
||||
|
||||
+152
-247
@@ -27,72 +27,55 @@ workflows use the `reusable-*` naming family. There is **no
|
||||
|
||||
## 2. Workflows (caller stubs in this repo)
|
||||
|
||||
⚠️ **The YAML below is a copy of live files, and copies drift.** It has already
|
||||
happened twice: a Dependabot bump moved `actions/setup-node` from v6 to v7 in
|
||||
`.github/workflows/` and never touched this doc, and the `check:manifest` step
|
||||
added to the release job in `674ac34` was missing here. Because docs win over
|
||||
code in this project, someone reconciling in the wrong direction would have
|
||||
downgraded a pinned action and deleted a security gate. Both are corrected
|
||||
below (2026-08-03). **When these disagree again, read the workflow file first
|
||||
and fix this doc — that is the one place the docs-win rule inverts, because the
|
||||
running pipeline is the ground truth about itself.**
|
||||
**This chapter no longer copies the workflow YAML** (decided 2026-10-28). It
|
||||
used to, and the copies drifted three times: a Dependabot bump moved
|
||||
`actions/setup-node` v6 → v7 in `.github/workflows/` and never touched this doc,
|
||||
the `check:manifest` step added to the release job in `674ac34` was missing
|
||||
here, and a copy kept `continue-on-error` after the file had dropped it.
|
||||
Because docs win over code in this project, a stale copy is a standing
|
||||
invitation to "reconcile" a pinned action backwards or delete a security gate.
|
||||
**The workflow files are the ground truth about themselves.** What follows is
|
||||
what a YAML file cannot say: why each job exists, what it must keep doing, and
|
||||
the traps already stepped in.
|
||||
|
||||
### 2.1 `.github/workflows/ci.yml` — every push/PR to `main`
|
||||
Common to every job since v1.1.0:
|
||||
|
||||
The local `quality` job exists because the ops reusable workflow performs none
|
||||
of it (§1). The `build` job delegates packaging.
|
||||
- `actions/checkout` with `persist-credentials: false` — no job pushes, so no
|
||||
job leaves a token in `.git/config`.
|
||||
- `actions/setup-node` with `node-version-file: .nvmrc` (Node 26, `01 §2`).
|
||||
The ops reusable takes a string input and cannot read the file, so `ci.yml`
|
||||
passes it `'26'` — keep the two equal by hand.
|
||||
- `npm ci --ignore-scripts`, then `npx --no-install wxt prepare`. No dependency
|
||||
gets to run code at install time (SonarCloud S6505); our own `postinstall` is
|
||||
the one script we need, so it runs explicitly, from the local binary, never
|
||||
fetched. A local `npm ci` still runs `postinstall` normally.
|
||||
- Reusable workflows get **named** secrets, never `secrets: inherit`: they are
|
||||
pinned to the ops repo's moving `main`, so each one receives only what it
|
||||
declares.
|
||||
|
||||
```yaml
|
||||
name: CI
|
||||
### 2.1 `ci.yml` — every push/PR to `main`
|
||||
|
||||
on:
|
||||
push: { branches: [main] }
|
||||
pull_request:
|
||||
Three jobs. The two whose names branch protection requires (§5) are
|
||||
`Quality gates` and `Build + package / build`.
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Quality gates
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
with: { node-version: '24', cache: npm }
|
||||
- run: npm ci
|
||||
- run: npm run lint # biome check .
|
||||
- run: npm run check # svelte-check + tsc --noEmit
|
||||
- run: npm run knip
|
||||
- run: npm run coverage # vitest --coverage, thresholds per 11 §1
|
||||
- run: npm run guard # canonical grep gate, 08_MV3 §3
|
||||
- run: npm run build
|
||||
- run: npm run check:manifest # the BUILT artifact, not just the config
|
||||
|
||||
build:
|
||||
name: Build + package
|
||||
needs: quality
|
||||
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
|
||||
permissions:
|
||||
contents: write # see the warning below — `read` fails at startup
|
||||
with:
|
||||
package-manager: 'npm' # 01 §6 commits package-lock.json
|
||||
node-version: '24'
|
||||
build-command: 'npm run build'
|
||||
source-dir: '.output/chrome-mv3' # WXT emits the manifest here
|
||||
release: false
|
||||
```
|
||||
|
||||
All four `with:` values are required. Omitting `package-manager` defaults it to
|
||||
`'none'`, which skips install/build entirely and then fails on
|
||||
`test -f ./manifest.json` — a file WXT never writes to the repo root.
|
||||
- **`quality` — "Quality gates".** Local, because the ops reusable runs no
|
||||
quality gates at all (§1). In order: `lint`, `check` (svelte-check on the
|
||||
TS 6 API, then the TS 7 `tsc`), `knip`, `coverage` (`11 §1` thresholds),
|
||||
`guard` (`08 §3`), `npm audit --omit=dev --audit-level=low` (the
|
||||
zero-runtime-dependencies claim, `09 T5`), `build`, `check:manifest`. The last
|
||||
two exist because the unit test over `wxt.config.ts` proves what we *asked*
|
||||
for and only the built manifest proves what WXT *emitted* — a dev build of
|
||||
the same config carries `tabs`/`scripting`/`host_permissions`.
|
||||
- **`windows` — "Windows smoke (guard + unit tests)".** Not required. The owner
|
||||
develops on Windows, and the failures that only happen there — drive letters
|
||||
and percent-encoding in script paths, CRLF checkouts — had no CI coverage.
|
||||
- **`build` — "Build + package".** Delegates packaging to
|
||||
`reusable-chrome-extension.yml` with `package-manager: 'npm'`,
|
||||
`node-version: '26'`, `build-command: 'npm run build'`,
|
||||
`source-dir: '.output/chrome-mv3'`, `release: false`. All four are required in
|
||||
practice: leaving `package-manager` at its `'none'` default skips install and
|
||||
build, then fails on `test -f ./manifest.json`, a file WXT never writes to the
|
||||
repo root.
|
||||
|
||||
⚠️ **`contents: write` on the `build` job is not a mistake.** The reusable
|
||||
declares two mutually exclusive jobs — `build` (`contents: read`,
|
||||
@@ -105,210 +88,123 @@ likely failed because of a workflow file issue" in the UI. Verified 2026-07-26
|
||||
on the first real run of this workflow.
|
||||
|
||||
`npm run guard` runs the same script locally and in CI, so the gate cannot
|
||||
drift between the two (`10 §3`). It is the single canonical pattern defined in
|
||||
`08_MV3_COMPLIANCE.md §3`; do not restate the pattern here or anywhere else.
|
||||
drift between the two (`10 §3`).
|
||||
|
||||
### 2.2 `.github/workflows/codeql.yml`
|
||||
### 2.2 `codeql.yml`
|
||||
|
||||
Use the current reusable (`reusable-codeql.yml`, CodeQL Action v4). Its input is
|
||||
`languages` — a **JSON array encoded as a string**, not the singular `language`
|
||||
of the older `codeql.yml`.
|
||||
|
||||
```yaml
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
push: { branches: [main] }
|
||||
pull_request: { branches: [main] }
|
||||
schedule:
|
||||
- cron: '0 14 * * 1' # weekly, Monday
|
||||
|
||||
permissions:
|
||||
security-events: write
|
||||
actions: read
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
|
||||
permissions:
|
||||
security-events: write
|
||||
actions: read
|
||||
contents: read
|
||||
packages: read
|
||||
with:
|
||||
languages: '["javascript-typescript"]'
|
||||
```
|
||||
Calls the current reusable, `reusable-codeql.yml` (CodeQL Action v4). Its input
|
||||
is `languages` — a **JSON array encoded as a string**
|
||||
(`'["javascript-typescript"]'`), not the singular `language` of the older
|
||||
`codeql.yml`. Weekly schedule plus push/PR to `main`; the permission block
|
||||
(`security-events: write`, `actions: read`, `contents: read`, `packages: read`)
|
||||
is repeated on the job because reusable workflows do not inherit it.
|
||||
|
||||
⚠️ **Prerequisite:** repo Settings → Advanced Security → CodeQL **"Default
|
||||
setup" must be DISABLED**, or this advanced-setup workflow is rejected at SARIF
|
||||
upload time.
|
||||
|
||||
### 2.3 `.github/workflows/release.yml` — on tag `v*`
|
||||
### 2.3 `release.yml` — on tag `v*`
|
||||
|
||||
Standalone, **not** the ops reusable: the reusable's `release` job only does
|
||||
`gh release create --generate-notes`. It produces no `SHA256SUMS.txt`
|
||||
(required by `09 §5`), performs no store submission, and exposes no `outputs:`,
|
||||
so a caller cannot reference the zip it built.
|
||||
`gh release create --generate-notes`. It produces no `SHA256SUMS.txt` (required
|
||||
by `09 §5`), performs no store submission, and exposes no `outputs:`, so a
|
||||
caller cannot reference the zip it built.
|
||||
|
||||
```yaml
|
||||
name: Release
|
||||
Four jobs, least privilege first (split 2026-10-28):
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
| Job | Token | Does |
|
||||
|---|---|---|
|
||||
| `build` "Gate + package" | `contents: read` | install, **every CI gate again** (a tag skips the branch triggers, and must never ship what a PR would have blocked), `zip`, `check:manifest`, the tag ↔ manifest version check, `SHA256SUMS.txt`; uploads both files as the artifact `release-<tag>` |
|
||||
| `publish` "GitHub Release" | `contents: write` | downloads the artifact, `sha256sum -c` it, creates the Release with `--verify-tag` (or re-uploads to an existing one). Installs nothing and runs no repository code — the only job that ever holds a write token |
|
||||
| `store` "Publish to Chrome Web Store" | `contents: read` | only when the repo variable `CWS_AUTOPUBLISH` is `'true'`: `./node_modules/.bin/wxt submit` with the Release asset — the local binary, never `npx wxt`, which may fetch an unpinned package into an environment holding the four `CHROME_*` secrets (SonarCloud S6505/S8543) |
|
||||
| `announce` | `contents: read` | Discord, only when `DISCORD_ANNOUNCE` is `'true'` |
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: write # create the GitHub Release
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
with: { node-version: '24', cache: npm }
|
||||
- run: npm ci
|
||||
|
||||
# Same gates as CI — a tag must never ship what a PR would have blocked.
|
||||
- run: npm run lint
|
||||
- run: npm run check
|
||||
- run: npm run knip
|
||||
- run: npm run coverage
|
||||
- run: npm run guard
|
||||
|
||||
- run: npm run zip # wxt zip → .output/<name>-<version>-chrome.zip
|
||||
- run: npm run check:manifest # gate the artifact, not the config it came from
|
||||
|
||||
- name: Verify tag matches manifest version
|
||||
run: |
|
||||
set -euo pipefail
|
||||
MANIFEST_VERSION=$(jq -r '.version' .output/chrome-mv3/manifest.json)
|
||||
TAG_VERSION="${GITHUB_REF_NAME#v}"
|
||||
test "$MANIFEST_VERSION" = "$TAG_VERSION" \
|
||||
|| { echo "::error::tag $TAG_VERSION != manifest $MANIFEST_VERSION"; exit 1; }
|
||||
|
||||
- name: SHA256SUMS
|
||||
working-directory: .output
|
||||
run: sha256sum *-chrome.zip > SHA256SUMS.txt
|
||||
|
||||
- name: GitHub Release # idempotent — see below
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
|
||||
gh release upload "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --clobber
|
||||
else
|
||||
gh release create "$GITHUB_REF_NAME" \
|
||||
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
|
||||
fi
|
||||
|
||||
- name: Publish to Chrome Web Store
|
||||
if: vars.CWS_AUTOPUBLISH == 'true'
|
||||
env:
|
||||
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
|
||||
CHROME_CLIENT_ID: ${{ secrets.CHROME_CLIENT_ID }}
|
||||
CHROME_CLIENT_SECRET: ${{ secrets.CHROME_CLIENT_SECRET }}
|
||||
CHROME_REFRESH_TOKEN: ${{ secrets.CHROME_REFRESH_TOKEN }}
|
||||
run: npx wxt submit --chrome-zip .output/*-chrome.zip
|
||||
|
||||
announce:
|
||||
needs: release
|
||||
if: vars.DISCORD_ANNOUNCE == 'true' # see below — NOT continue-on-error
|
||||
uses: poli0981/.github/.github/workflows/announce-release.yml@main
|
||||
permissions:
|
||||
contents: read
|
||||
with:
|
||||
tag_override: ${{ github.ref_name }}
|
||||
secrets: inherit
|
||||
```
|
||||
Before the split, one job ran `npm ci` — every dependency's install script plus
|
||||
our own tests — while holding `contents: write`, with the token also left in
|
||||
`.git/config` by checkout.
|
||||
|
||||
**The Release step is idempotent deliberately.** `gh release create` fails
|
||||
outright when a Release for the tag already exists, so any failure *after* it —
|
||||
realistically the CWS publish step, once `CWS_AUTOPUBLISH` is on — stranded the
|
||||
tag: a re-run could not get past that line, and recovery meant deleting the
|
||||
Release and the tag by hand. `docs/13 §7` documents the manual escape; this
|
||||
removes the need for it in the common case.
|
||||
realistically the store job, once `CWS_AUTOPUBLISH` is on — stranded the tag: a
|
||||
re-run could not get past that line, and recovery meant deleting the Release
|
||||
and the tag by hand. `docs/13 §7` documents the manual escape; this removes the
|
||||
need for it in the common case.
|
||||
|
||||
The announcement is gated because the reusable exits 1 on "No webhooks
|
||||
configured" when both Discord secrets are unset — which §5 lists as optional. On
|
||||
the real v1.0.0 run the Release, the zip and `SHA256SUMS.txt` all published
|
||||
correctly and the run still showed red. A red run on a good release trains you
|
||||
to ignore the colour, so the notification must not be able to fail the release.
|
||||
configured". On the real v1.0.0 run the Release, the zip and `SHA256SUMS.txt`
|
||||
all published correctly and the run still showed red. A red run on a good
|
||||
release trains you to ignore the colour, so the notification must not be able
|
||||
to fail the release.
|
||||
|
||||
⚠️ **It is gated with `if:` on a repo VARIABLE, not with `continue-on-error`.**
|
||||
GitHub **rejects** `continue-on-error` on a job that calls a reusable workflow —
|
||||
`Property continue-on-error is not allowed` — and a rejected file does not fail
|
||||
one job, it makes the whole run a `startup_failure` with zero jobs and no log.
|
||||
That is the same silent shape as the `contents: write` mistake in §2.1, and it
|
||||
sat undetected in this repo from `5f4c6e7` until 2026-08-03 precisely because
|
||||
that commit landed *after* the `v1.0.0` tag and no tag was pushed in between —
|
||||
the first v1.0.1 tag would have been its first execution.
|
||||
GitHub **rejects** `continue-on-error` on a job that calls a reusable workflow
|
||||
(`Property continue-on-error is not allowed`), and a rejected file does not
|
||||
fail one job — the whole run is a `startup_failure` with zero jobs and no log.
|
||||
That sat undetected from `5f4c6e7` until 2026-08-03 because the commit landed
|
||||
after the `v1.0.0` tag and no tag was pushed in between. A variable and not a
|
||||
secret: secrets cannot be referenced in a job-level `if:`.
|
||||
|
||||
A **variable** and not a secret: secrets cannot be referenced in a job-level
|
||||
`if:`. `vars.DISCORD_ANNOUNCE` defaults to unset, so the announcement is skipped
|
||||
and the release stays green until the owner opts in — the same idiom as
|
||||
`CWS_AUTOPUBLISH`. Set the variable only once the webhook secrets exist.
|
||||
⚠️ **The webhook secrets are mapped by name.** This repo stores
|
||||
`RELEASES_WEBHOOK` and `REPO_WEBHOOK`; the reusable reads
|
||||
`DISCORD_RELEASES_WEBHOOK` and `DISCORD_REPO_WEBHOOK`. Under the old
|
||||
`secrets: inherit` the reusable received neither, so the day `DISCORD_ANNOUNCE`
|
||||
was set the job would have failed on "No webhooks configured". It now passes
|
||||
each one explicitly under the name the reusable reads — found 2026-10-28 by
|
||||
comparing the repo's secret list with the reusable's `workflow_call` block.
|
||||
|
||||
`tag_override` is **required here**, and for the same reason the announcement
|
||||
is a job rather than a caller. The reusable resolves
|
||||
`TAG="${INPUT_TAG:-$EVENT_TAG}"` with `EVENT_TAG = github.event.release.tag_name`
|
||||
— empty under `on: push: tags` — so omitting it makes the job exit 1 on
|
||||
"No release tag available" and the announcement never fires for any release.
|
||||
`tag_override` is **required**: the reusable resolves
|
||||
`TAG="${INPUT_TAG:-$EVENT_TAG}"` with `EVENT_TAG = github.event.release.tag_name`,
|
||||
which is empty under `on: push: tags`, so without it the job exits 1 on "No
|
||||
release tag available". The announcement is a **job inside this workflow**, not
|
||||
a separate `on: release: [published]` caller, because a Release created by
|
||||
`gh release create` under the default `GITHUB_TOKEN` emits no event that starts
|
||||
new workflow runs.
|
||||
|
||||
The announcement is a **job inside this workflow**, not a separate
|
||||
`on: release: [published]` caller. A Release created by `gh release create`
|
||||
under the default `GITHUB_TOKEN` does not emit an event that starts new
|
||||
workflow runs, so an event-driven caller would silently never fire.
|
||||
### 2.4 `notify-ci-failure.yml`
|
||||
|
||||
### 2.4 `.github/workflows/notify-ci-failure.yml`
|
||||
Runs on `workflow_run` of CI, gated on
|
||||
`conclusion == 'failure' && vars.DISCORD_CI_NOTIFY == 'true'`, and passes the
|
||||
one secret the reusable declares (`DISCORD_CI_WEBHOOK`) by name. The reusable
|
||||
declares that secret `required: true` and GitHub validates it before any of the
|
||||
reusable's own logic, so without the gate this caller failed on **every** CI
|
||||
completion, success included. `DISCORD_CI_WEBHOOK` exists (set 2026-07-26); the
|
||||
variable is still unset, so notifications stay off until the owner opts in. A
|
||||
notification must never be able to change the colour of the thing it reports
|
||||
on.
|
||||
|
||||
```yaml
|
||||
name: Notify CI failure
|
||||
### 2.5 `sonarcloud.yml` — SonarCloud CI analysis
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: ['CI']
|
||||
types: [completed]
|
||||
Added 2026-10-28, replacing SonarCloud's Automatic Analysis so the project gets
|
||||
**coverage** and a scan of exactly what CI builds. Project
|
||||
`poli0981_bookmarkmagic`, organisation `poli0981`; settings live in
|
||||
`sonar-project.properties`.
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
- **A separate workflow, not a job in `ci.yml`:** a Sonar outage or a
|
||||
quality-gate opinion must never turn CI red. The verdict reaches PRs as the
|
||||
SonarCloud GitHub App's own check. It is not a required check.
|
||||
- Steps: full-history checkout (`fetch-depth: 0`, for new-code detection), the
|
||||
common install, `npm run coverage` (which writes `coverage/lcov.info`), then the
|
||||
scan with `-Dsonar.projectVersion=<package.json version>`, so "new code" means
|
||||
"since the last release".
|
||||
- The scan action is **pinned to a commit** (`v8.3.0`): it is the step that
|
||||
holds `SONAR_TOKEN`, and the token is scoped to the two steps that need it.
|
||||
Dependabot and fork PRs get no repository secrets, so the scan is skipped with
|
||||
a notice instead of failing.
|
||||
- Coverage: `vitest.config.ts` measures every `src/**/*.ts` module and reports
|
||||
`text` + `lcov`; the CI *gate* is still the core-only glob threshold of
|
||||
`11 §1`. `sonar.coverage.exclusions` drops components, entrypoints and
|
||||
scripts — the same split as `11 §1`, where those are covered by the manual
|
||||
pass and the script tests. The three locale files are excluded from
|
||||
duplication detection: they are parallel by design.
|
||||
- No `sonar.qualitygate.wait`: an unreviewed Security Hotspot can only be
|
||||
cleared by a person in the Sonar UI, and a CI step that waits on a human is a
|
||||
step that is red for a reason nobody can fix from the repo.
|
||||
|
||||
jobs:
|
||||
notify:
|
||||
if: github.event.workflow_run.conclusion == 'failure' && vars.DISCORD_CI_NOTIFY == 'true'
|
||||
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
secrets: inherit
|
||||
```
|
||||
⚠️ **Prerequisite:** Automatic Analysis must be **off** in the SonarCloud project
|
||||
(Administration → Analysis Method). With it on, the scanner refuses to run.
|
||||
|
||||
The reusable filters to `conclusion == 'failure'` on the default branch
|
||||
internally, so the caller's `if:` is redundant *for behaviour* — but not for
|
||||
cost, and not for the failure below.
|
||||
|
||||
⚠️ **The reusable declares `DISCORD_CI_WEBHOOK` as `required: true`**, which
|
||||
GitHub validates before any of the reusable's own logic runs. With the secret
|
||||
unset (`00 §10.6`), the caller therefore failed on **every** CI completion —
|
||||
success or failure — from the first push after this file landed.
|
||||
|
||||
Both halves of the condition earn their place: the conclusion check stops it
|
||||
running on green CI at all, and `vars.DISCORD_CI_NOTIFY` keeps it off entirely
|
||||
until the secret actually exists. **Not `continue-on-error`** — see §2.3: GitHub
|
||||
rejects that keyword on a reusable-workflow caller and invalidates the file.
|
||||
|
||||
Same reasoning as §2.3's announce gate, learned the same way: a notification
|
||||
must never be able to change the colour of the thing it is reporting on, because
|
||||
a run that is red for a reason nobody acts on teaches everyone to stop reading
|
||||
the colour.
|
||||
Snyk is connected only as a GitHub App (the `security/snyk (poli0981)` PR
|
||||
check); there is no `SNYK_TOKEN` and no Snyk step in any workflow.
|
||||
|
||||
## 3. Chrome Web Store publishing automation
|
||||
|
||||
@@ -371,20 +267,29 @@ means "unknown", not "not done".
|
||||
- [ ] ⚠️ Actions secrets: the four `CHROME_*` values (after `wxt submit init`).
|
||||
`CHROME_EXTENSION_ID` is already known — it is the published item id in
|
||||
`00 §9`. Required before `CWS_AUTOPUBLISH` can be flipped for v1.1.
|
||||
- [ ] ⚠️ Actions secrets for Discord notifications. **`DISCORD_CI_WEBHOOK` is
|
||||
not optional in practice** — see §2.4. The rest are:
|
||||
`DISCORD_RELEASES_WEBHOOK`, `DISCORD_REPO_WEBHOOK`, `DISCORD_PING_ROLE_ID`.
|
||||
- [x] Actions secrets for Discord notifications — **present as of 2026-10-28:**
|
||||
`DISCORD_CI_WEBHOOK`, `RELEASES_WEBHOOK`, `REPO_WEBHOOK` (the last two under
|
||||
names the reusable does not read; `release.yml` maps them, §2.3).
|
||||
`DISCORD_PING_ROLE_ID` is optional and unset.
|
||||
- [x] `SONAR_TOKEN` — set 2026-10-28, used only by `sonarcloud.yml` (§2.5).
|
||||
- [ ] ⚠️ SonarCloud **Automatic Analysis OFF** (SonarCloud → bookmarkmagic →
|
||||
Administration → Analysis Method). Required for §2.5; with it on, the CI
|
||||
scan errors out. The owner agreed to switch it off on 2026-10-28.
|
||||
- [x] Private vulnerability reporting **enabled** (verified 2026-10-28 via the
|
||||
API) — `SECURITY.md` and the issue chooser send reporters there first.
|
||||
- [ ] ⚠️ Repo variable `CWS_AUTOPUBLISH=false` initially. Note that when the
|
||||
variable does not exist the expression is simply false, so "not configured"
|
||||
and "configured off" are indistinguishable from a run's output.
|
||||
- [ ] ⚠️ Repo variables `DISCORD_ANNOUNCE` and `DISCORD_CI_NOTIFY`. Leave both
|
||||
unset until the matching webhook secrets exist — the reusables declare
|
||||
those secrets required, so calling them without one fails the job, and a
|
||||
reusable-workflow caller cannot use `continue-on-error` to absorb it
|
||||
(§2.3). Unset means skipped, which is the safe default.
|
||||
- [ ] ⚠️ Repo variables `DISCORD_ANNOUNCE` and `DISCORD_CI_NOTIFY` — both still
|
||||
unset (2026-10-28), so no notification fires. The webhook secrets now
|
||||
exist, so either can be flipped to `true` whenever the owner wants the
|
||||
posts. Unset means skipped; a reusable-workflow caller cannot use
|
||||
`continue-on-error` to absorb a failure (§2.3).
|
||||
- [x] Dependabot: npm weekly, grouped dev minor+patch, `github-actions` too —
|
||||
`.github/dependabot.yml`. Note it has no awareness of the `package.json`
|
||||
`overrides` block, so those six pins must be reviewed by hand (`09 §3.1`).
|
||||
`.github/dependabot.yml`. Both ecosystems have a 7-day `cooldown`
|
||||
(matching `.npmrc` `min-release-age=7`, `09 §3.1`); WXT is excluded from
|
||||
the group so every WXT bump arrives alone and gets its built-manifest
|
||||
diff; majors of the TypeScript pair and `@types/node` are ignored.
|
||||
- [x] Issue templates: `.github/ISSUE_TEMPLATE/` — bug, parser report (requires
|
||||
a sanitized sample), translation, feature, plus a `config.yml` chooser.
|
||||
Landed 2026-08-03; `13 §6` had asserted they existed since before launch.
|
||||
|
||||
+22
-2
@@ -23,7 +23,8 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
|
||||
| **v1.0.0 published** | ✔ by 2026-08-03 | approved by CWS review with no rejection recorded; listing public, item id `eghnciphhegekmnofffpgbdfefckdhmg`, **real users installed** |
|
||||
| 6 — Post-launch stabilization | ✔ 2026-08-03 | doc reconciliation, user-intake machinery, the defects below, dependency bumps → v1.0.1 |
|
||||
| **v1.0.1 released** | ✔ 2026-08-03 | signed tag on `4654086`, GitHub Release with a `sha256sum -c`-verified zip; shipped manifest `1.0.1`, permissions unchanged. `announce` skipped (no `DISCORD_ANNOUNCE`), store publish skipped (no `CWS_AUTOPUBLISH`) |
|
||||
| **v1.0.1 submitted** | ✔ 2026-08-03 | uploaded to the CWS dashboard by hand (`13 §1b` step 6). ⚠️ **In review — not yet approved.** Add a "published" row only when the listing actually shows 1.0.1, and then run `13 §1b` step 10 |
|
||||
| **v1.0.1 submitted** | ✔ 2026-08-03 | uploaded to the CWS dashboard by hand (`13 §1b` step 6) |
|
||||
| **v1.0.1 published** | ✔ observed 2026-10-28 | listing shows version 1.0.1 (`Updated: August 3, 2026`), 5 users. ⚠️ Exact approval date not recorded; `13 §1b` step 10 (clean-profile install of the published build + upgrade re-check) has no recorded result |
|
||||
|
||||
**Verified on real browsers 2026-07-25:** Chrome and Brave, unpacked build.
|
||||
Until that point every phase had been tested only against a hand-rolled
|
||||
@@ -91,7 +92,9 @@ There is exactly one path, and every step has an owner in the repo:
|
||||
`tests/fixtures/** -text`, so EOL normalization cannot destroy the CRLF/BOM
|
||||
bytes the bug may depend on.
|
||||
3. A regression test lands in `tests/unit/core/fixtures.test.ts` — the only
|
||||
fixture-driven suite — **in the same PR** as the parser fix (`11 §2`).
|
||||
parser regression suite — **in the same PR** as the parser fix (`11 §2`). The
|
||||
sanitizer suite (`tests/unit/scripts/sanitize-bookmarks.test.ts`) also walks
|
||||
every fixture automatically, so the new file is covered there too.
|
||||
4. The quirk is noted in the parser source and in `04 §1.2` (`CLAUDE.md`
|
||||
working style makes this mandatory, not optional).
|
||||
5. `11 §2`'s inventory and `CHANGELOG.md [Unreleased]` are updated.
|
||||
@@ -208,3 +211,20 @@ independently of the package (`13 §5`), though the copy should still go through
|
||||
| 2026-08-03 | **`continue-on-error` is invalid on a job that calls a reusable workflow** — GitHub rejects the file with "Property continue-on-error is not allowed", and a rejected file is a `startup_failure` with zero jobs and no log, not a failed job. `release.yml`'s announce job had carried it since `5f4c6e7`; that commit landed *after* the `v1.0.0` tag and no tag was pushed since, so **the first v1.0.1 tag would have been its first execution**. Both notification jobs are now gated with `if:` on a repo variable — allowed there, unlike a secret — defaulting to skipped | 12 §2.3, 12 §2.4 |
|
||||
| 2026-08-03 | **A notification must never change the colour of the thing it reports on.** `notify-ci-failure.yml` had been failing on *every* CI completion, success included, because the reusable declares a secret that does not exist and GitHub validates that before the reusable's own success filter runs. Same lesson as `5f4c6e7`, learned twice | 12 §2.4 |
|
||||
| 2026-08-03 | **No support email on any in-product surface.** About links to the store listing, the repo, issues and the changelog. Publishing an address inside the extension invites unsanitized bookmark files by mail, which is the exact receipt-of-personal-data problem the privacy clause exists to bound. The address stays in `SECURITY.md`, `CONTRIBUTING.md` and the privacy policy | 06 §3.5, 09 §6 |
|
||||
| 2026-10-28 | **Node 26 LTS for the whole toolchain.** Node 26 entered Active LTS that day and Node 24 had gone to maintenance on 2026-10-20 — the "latest stable or LTS" rule of `01` moves with it | 01 §2 |
|
||||
| 2026-10-28 | **TypeScript 7 runs beside the TS 6 API instead of replacing it.** `@typescript/native` (`npm:typescript@~7.0.2`) owns `tsc`; `typescript` is aliased to `@typescript/typescript6`, which re-exports TS 6.0.3 for svelte-check and Volar. TS 7 has no programmatic API until 7.1, and svelte-check peers `^5 \|\| ^6`, so this is the only way to adopt 7 without losing template type-checking | 01 §2 |
|
||||
| 2026-10-28 | **ES2025, and the Chrome floor that makes it honest: 120 → 136.** A lib newer than the floor lets the compiler accept APIs the oldest allowed Chrome lacks (`RegExp.escape` is 136). `CHROME_FLOOR` in `wxt.config.ts` drives both `minimum_chrome_version` and Vite's `build.target`; `manifest.test.ts` pins those and tsconfig's `lib` together. A floor raise strands nobody — users below it keep their version and stop updating — but it is user-visible, so never in a patch | 01 §1, 08 §7 |
|
||||
| 2026-10-28 | **7-day supply-chain cooldown:** `.npmrc` `min-release-age=7` + Dependabot `cooldown: 7`. Verified that `npm ci` still installs whatever the lockfile pins, so the rule only shapes *what gets locked* | 01 §6, 09 §3.1 |
|
||||
| 2026-10-28 | **The `overrides` block is deleted.** All six pinned packages had left the tree (WXT 0.21 dropped `web-ext-run`; Vite 8 uses rolldown, not esbuild). `npm audit` 13 → 3 low, all one unfixable `deepmerge` advisory inside vite-plugin-svelte, accepted and documented; `--omit=dev` stays 0 | 09 §3.1 |
|
||||
| 2026-10-28 | **WXT 0.21.3 → 0.21.4 accepted after the built-manifest diff** the 2026-08-03 rule requires: identical key set and values (only the deliberate `minimum_chrome_version`), identical file inventory, chunk sizes within ±1.1 kB from the Svelte 5.57 runtime. Vitest 4 → 5 and jsdom 30.0 → 30.1 passed the whole suite unchanged, the `dom-environment` canary first | 01 §2 |
|
||||
| 2026-10-28 | **Biome ignores Markdown and YAML.** 2.6 began formatting both and flagged 35 hand-laid docs and workflows; formatting prose is not what the gate is for | 10 §3 |
|
||||
| 2026-10-28 | **SonarCloud moves from Automatic Analysis to a CI scan** (`sonarcloud.yml`, `sonar-project.properties`): coverage at last, and a scan of what CI actually builds. Its own workflow so it never colours CI; the scan action pinned to a commit because it holds `SONAR_TOKEN`; skipped, not failed, where secrets are absent | 12 §2.5 |
|
||||
| 2026-10-28 | **Coverage measures all of `src/**/*.ts`, but the gate stays core-only** via a glob threshold — verified to still fail a run below `src/lib/core/**`'s numbers, so widening what is measured cannot loosen what is enforced | 11 §1, 12 §2.5 |
|
||||
| 2026-10-28 | **CI installs with `--ignore-scripts` and runs `wxt prepare` explicitly; reusables get named secrets; checkouts drop credentials; the release's write token moves to a job that installs nothing.** The old release job ran every dependency's install script and our tests while holding `contents: write`. The announce job's `secrets: inherit` also passed nothing it could use — this repo's webhook secrets have different names than the reusable reads | 12 §2 |
|
||||
| 2026-10-28 | **docs/12 stops copying workflow YAML.** The copies drifted three times; with docs-win, a stale copy invites reverting a pinned action or deleting a gate. The chapter now records why each job exists and the traps already hit; the files are the ground truth about themselves | 12 §2 |
|
||||
| 2026-10-28 | **The zero-network promise becomes browser-enforced.** The production manifest gains an extension-page CSP that keeps the MV3 minimum and adds `connect-src 'none'` plus closed image/font/media/frame/form sources — no `default-src`, so styles are untouched; dev builds omit it so HMR works. Reverses `08 §3`'s old "never add a custom CSP", whose reason was that MV3 forbids *loosening*; tightening was always allowed. The rule now: only ever tighten, and `check:manifest` pins the exact string | 08 §3 |
|
||||
| 2026-10-28 | **Three gates instead of one grep:** the CSP (runtime), `check:manifest` scanning the shipped JS for network APIs (catches dependency code), and a rewritten `guard.mjs` — whole-file matching, identifiers banned outright, computed global access banned, `.html/.css` scanned, no test exemption, fails on zero files. The old one let all 28 audited bypasses through and printed "clean" for a checkout path with a space or diacritic. Vite's modulepreload polyfill (the one network call in the bundle) is off | 08 §3 |
|
||||
| 2026-10-28 | **The guard's rule list lives in `scripts/guard.mjs` only.** `08 §3` restating it was the "single source" that had already diverged (`\{@html\}` matched only the literal text) | 08 §3 |
|
||||
| 2026-10-28 | **The sanitizer reads the browser JSON formats and is default-deny for JSON.** It accepted any JSON and rewrote only `url`/`title`, so Chrome's profile `Bookmarks` file — titles under `name`, plus `meta_info` and a base64 sync blob — came out with every title intact and passed its own host check. JSON dialects are now recognised by shape (anything else refused), every string value is rewritten except structural keys, Firefox root GUIDs and the timestamps survive | 09 §6 |
|
||||
| 2026-10-28 | **The sanitizer's backstop reads the output's text, not just its hosts.** For HTML it strips markup and refuses on any word that is not a placeholder — independent of the rewriting rules, unlike the old check (and its test), which shared their blind spots. It also stopped overwriting the input when the output path equalled it, checks size before reading, decodes attributes once (CodeQL double-escaping) and finds `<DD>` notes in linear time (Sonar S8786), attributes included | 09 §6 |
|
||||
| 2026-10-28 | **`scripts/` obeys the size rule and is type-checked.** `docs/10 §1` now names `.mjs`; the 627-line sanitizer is split into `scripts/sanitize/` modules; every script carries `// @ts-check` and `tsconfig.scripts.json` runs them through the TS 7 `tsc` in `npm run check`. The sanitizer stays plain `.mjs` on purpose — reporters run it on whatever Node they have | 10 §1 |
|
||||
Generated
+1272
-1194
File diff suppressed because it is too large.
Load diff
+14
-21
@@ -15,7 +15,7 @@
|
||||
"url": "https://github.com/poli0981/bookmarkmagic/issues"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
"node": ">=26"
|
||||
},
|
||||
"scripts": {
|
||||
"postinstall": "wxt prepare",
|
||||
@@ -23,7 +23,7 @@
|
||||
"dev:firefox": "wxt -b firefox",
|
||||
"build": "wxt build",
|
||||
"zip": "wxt zip",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
|
||||
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit && tsc -p tsconfig.scripts.json",
|
||||
"lint": "biome check .",
|
||||
"lint:fix": "biome check --write .",
|
||||
"knip": "knip",
|
||||
@@ -37,25 +37,18 @@
|
||||
"verify:full": "npm run verify && npm run coverage && npm run build && npm run check:manifest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "2.5.5",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.2.0",
|
||||
"@types/node": "^24.13.3",
|
||||
"@vitest/coverage-v8": "^4.1.10",
|
||||
"@biomejs/biome": "2.6.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
||||
"@types/node": "^26.6.5",
|
||||
"@typescript/native": "npm:typescript@~7.0.2",
|
||||
"@vitest/coverage-v8": "^5.0.5",
|
||||
"@wxt-dev/module-svelte": "^2.0.5",
|
||||
"jsdom": "^30.0.1",
|
||||
"knip": "^6.29.0",
|
||||
"svelte": "^5.56.8",
|
||||
"svelte-check": "^4.7.4",
|
||||
"typescript": "~6.0.3",
|
||||
"vitest": "^4.1.10",
|
||||
"wxt": "^0.21.3"
|
||||
},
|
||||
"overrides": {
|
||||
"shell-quote": "^1.9.0",
|
||||
"adm-zip": "^0.6.0",
|
||||
"tmp": "^0.2.6",
|
||||
"uuid": "^11.1.1",
|
||||
"esbuild": "^0.28.1",
|
||||
"brace-expansion": "^5.0.8"
|
||||
"jsdom": "^30.1.3",
|
||||
"knip": "^6.42.1",
|
||||
"svelte": "^5.57.2",
|
||||
"svelte-check": "^4.7.7",
|
||||
"typescript": "npm:@typescript/typescript6@~6.0.2",
|
||||
"vitest": "^5.0.5",
|
||||
"wxt": "^0.21.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Types for scripts/check-manifest.mjs, so its tests can call it directly.
|
||||
* The script itself is plain JavaScript checked with `// @ts-check`.
|
||||
*/
|
||||
export function checkExtension(outDir: string): { problems: string[]; readError?: string };
|
||||
+188
-53
@@ -1,25 +1,45 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* Assert the BUILT manifest — CLAUDE.md hard rule 1, docs/08 §2.
|
||||
* Assert the BUILT extension — CLAUDE.md hard rule 1, docs/08 §2–§3.
|
||||
*
|
||||
* The unit test in `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which
|
||||
* proves what we ASKED for. It cannot prove what WXT emitted. Those differ:
|
||||
* a dev build of this exact config produces
|
||||
* `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which proves what we
|
||||
* ASKED for. It cannot prove what WXT emitted, and those differ: a dev build of
|
||||
* this exact config produces
|
||||
* "permissions": ["bookmarks","storage","tabs","scripting"]
|
||||
* "host_permissions": ["http://localhost/*"]
|
||||
* because WXT injects them for its dev server. Production is clean today, but
|
||||
* that is a property of WXT's dev/prod branch, not of anything this repo
|
||||
* enforces — so the shipped artifact needs its own gate.
|
||||
* because WXT injects them for its dev server. So the shipped artifact gets its
|
||||
* own gate, run after `npm run build` (or `npm run zip`):
|
||||
*
|
||||
* Run after `npm run build` (or `npm run zip`). Zero dependencies, Node stdlib.
|
||||
* 1. the manifest: MV3, the exact permission list, the exact top-level key
|
||||
* set, the Chrome floor, and the exact extension-page CSP;
|
||||
* 2. the file inventory: every file the manifest or the pages point at exists
|
||||
* (WXT drops `_locales/` and `icon/` silently when publicDir is wrong);
|
||||
* 3. the bundle: no network API anywhere in the shipped JavaScript.
|
||||
*
|
||||
* Usage: node scripts/check-manifest.mjs — checks <repo>/.output/chrome-mv3,
|
||||
* resolved from this file, not the cwd. It takes no arguments on purpose: a
|
||||
* path from the command line flowed straight into file reads (SonarCloud
|
||||
* S8707). Its tests call `checkExtension(dir)` directly instead.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const MANIFEST = join(process.cwd(), '.output', 'chrome-mv3', 'manifest.json');
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
|
||||
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
|
||||
|
||||
/** The ES2025 floor (docs/01 §1). Must equal CHROME_FLOOR in wxt.config.ts. */
|
||||
const CHROME_FLOOR = '136';
|
||||
|
||||
/**
|
||||
* The production extension-page CSP (docs/08 §3), character for character.
|
||||
* It may only ever get stricter. Never add 'unsafe-eval' or a remote source.
|
||||
*/
|
||||
const EXPECTED_CSP =
|
||||
"script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:; " +
|
||||
"style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none'; " +
|
||||
"worker-src 'self'; form-action 'none'; base-uri 'none'";
|
||||
|
||||
/**
|
||||
* The exact top-level key set the build is expected to emit.
|
||||
*
|
||||
@@ -27,13 +47,14 @@ const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
|
||||
* to enumerate. This catches the other direction — a build tool that starts
|
||||
* emitting a key nobody asked for, or stops emitting one the store requires.
|
||||
* WXT is a 0.x dependency, so a routine minor bump is exactly when that
|
||||
* happens, and the unit test over `wxt.config.ts` is structurally blind to it:
|
||||
* a WXT upgrade cannot change that file.
|
||||
* happens. `version_name` would appear if package.json ever carried a
|
||||
* prerelease version (WXT splits it out); release versions never do.
|
||||
*
|
||||
* Adding a key here is a deliberate act. Check docs/08 §1 first.
|
||||
*/
|
||||
const EXPECTED_KEYS = [
|
||||
'action',
|
||||
'content_security_policy',
|
||||
'default_locale',
|
||||
'description',
|
||||
'homepage_url',
|
||||
@@ -60,52 +81,166 @@ const FORBIDDEN_KEYS = [
|
||||
'chrome_url_overrides',
|
||||
];
|
||||
|
||||
let manifest;
|
||||
try {
|
||||
manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));
|
||||
} catch (cause) {
|
||||
console.error(`check-manifest: cannot read ${MANIFEST} — run \`npm run build\` first.`);
|
||||
console.error(` ${cause.message}`);
|
||||
process.exit(1);
|
||||
/** Files every build must contain besides what the manifest references. */
|
||||
const REQUIRED_FILES = [
|
||||
'manager.html',
|
||||
'popup.html',
|
||||
'_locales/en/messages.json',
|
||||
'_locales/vi/messages.json',
|
||||
'_locales/ja/messages.json',
|
||||
];
|
||||
|
||||
/**
|
||||
* Network APIs that must not appear in the shipped JavaScript — including code
|
||||
* that arrived through a dependency, which `npm run guard` (source only) never
|
||||
* sees. The CSP would refuse these at runtime; this refuses to ship them.
|
||||
*/
|
||||
const NETWORK_IN_BUNDLE =
|
||||
/\bfetch\s*\(|\bXMLHttpRequest\b|\bWebSocket\b|\bEventSource\b|\bsendBeacon\b|\bWebTransport\b/;
|
||||
|
||||
/** @param {string} a @param {string} b */
|
||||
const byName = (a, b) => a.localeCompare(b, 'en');
|
||||
|
||||
/** @param {string} dir @returns {string[]} */
|
||||
function listFiles(dir) {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
||||
const full = join(dir, entry.name);
|
||||
return entry.isDirectory() ? listFiles(full) : [full];
|
||||
});
|
||||
}
|
||||
|
||||
const problems = [];
|
||||
|
||||
if (manifest.manifest_version !== 3) {
|
||||
problems.push(`manifest_version is ${manifest.manifest_version}, expected 3`);
|
||||
/**
|
||||
* @param {string} outDir
|
||||
* @returns {Record<string, unknown> | string} the manifest, or why it could not be read
|
||||
*/
|
||||
function readManifest(outDir) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(join(outDir, 'manifest.json'), 'utf8'));
|
||||
} catch (cause) {
|
||||
return `cannot read manifest.json (${cause instanceof Error ? cause.message : cause})`;
|
||||
}
|
||||
}
|
||||
|
||||
const permissions = [...(manifest.permissions ?? [])].sort();
|
||||
if (permissions.join(',') !== [...ALLOWED_PERMISSIONS].sort().join(',')) {
|
||||
problems.push(
|
||||
`permissions are ${JSON.stringify(manifest.permissions)}, expected ${JSON.stringify(ALLOWED_PERMISSIONS)}`,
|
||||
/** @param {Record<string, unknown>} manifest @param {string[]} problems */
|
||||
function checkManifest(manifest, problems) {
|
||||
if (manifest.manifest_version !== 3) {
|
||||
problems.push(`manifest_version is ${manifest.manifest_version}, expected 3`);
|
||||
}
|
||||
|
||||
const permissions = Array.isArray(manifest.permissions) ? manifest.permissions : [];
|
||||
const actualPermissions = [...permissions].sort(byName).join(',');
|
||||
if (actualPermissions !== [...ALLOWED_PERMISSIONS].sort(byName).join(',')) {
|
||||
problems.push(
|
||||
`permissions are ${JSON.stringify(manifest.permissions)}, expected ${JSON.stringify(ALLOWED_PERMISSIONS)}`,
|
||||
);
|
||||
}
|
||||
|
||||
for (const key of FORBIDDEN_KEYS) {
|
||||
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
|
||||
}
|
||||
|
||||
const actualKeys = Object.keys(manifest);
|
||||
const unexpected = actualKeys.filter((key) => !EXPECTED_KEYS.includes(key)).sort(byName);
|
||||
const missing = EXPECTED_KEYS.filter((key) => !actualKeys.includes(key));
|
||||
if (unexpected.length > 0) {
|
||||
problems.push(`unexpected top-level key(s): ${unexpected.join(', ')} — see docs/08 §1`);
|
||||
}
|
||||
if (missing.length > 0) problems.push(`missing expected top-level key(s): ${missing.join(', ')}`);
|
||||
|
||||
if (manifest.minimum_chrome_version !== CHROME_FLOOR) {
|
||||
problems.push(
|
||||
`minimum_chrome_version is ${JSON.stringify(manifest.minimum_chrome_version)}, expected "${CHROME_FLOOR}" (docs/01 §1)`,
|
||||
);
|
||||
}
|
||||
|
||||
const csp = /** @type {{ extension_pages?: unknown } | undefined} */ (
|
||||
manifest.content_security_policy
|
||||
);
|
||||
if (csp?.extension_pages !== EXPECTED_CSP || Object.keys(csp).length !== 1) {
|
||||
problems.push(
|
||||
`content_security_policy is ${JSON.stringify(csp)}, expected exactly { extension_pages: "${EXPECTED_CSP}" } (docs/08 §3)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {Record<string, unknown>} manifest @returns {string[]} */
|
||||
function referencedFiles(manifest) {
|
||||
const icons = /** @type {Record<string, string>} */ (manifest.icons ?? {});
|
||||
const action = /** @type {{ default_popup?: string }} */ (manifest.action ?? {});
|
||||
const options = /** @type {{ page?: string }} */ (manifest.options_ui ?? {});
|
||||
return [...Object.values(icons), action.default_popup, options.page?.split('#')[0]].filter(
|
||||
(p) => typeof p === 'string',
|
||||
);
|
||||
}
|
||||
|
||||
for (const key of FORBIDDEN_KEYS) {
|
||||
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
|
||||
}
|
||||
|
||||
const actualKeys = Object.keys(manifest).sort();
|
||||
const expectedKeys = [...EXPECTED_KEYS].sort();
|
||||
const unexpected = actualKeys.filter((key) => !expectedKeys.includes(key));
|
||||
const missing = expectedKeys.filter((key) => !actualKeys.includes(key));
|
||||
if (unexpected.length > 0) {
|
||||
problems.push(`unexpected top-level key(s): ${unexpected.join(', ')} — see docs/08 §1`);
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
problems.push(`missing expected top-level key(s): ${missing.join(', ')}`);
|
||||
}
|
||||
|
||||
if (problems.length > 0) {
|
||||
for (const problem of problems) {
|
||||
console.error(`::error::check-manifest: ${problem}`);
|
||||
console.error(` ${problem}`);
|
||||
/** @param {string} outDir @param {Record<string, unknown>} manifest @param {string[]} problems */
|
||||
function checkInventory(outDir, manifest, problems) {
|
||||
for (const file of [...REQUIRED_FILES, ...referencedFiles(manifest)]) {
|
||||
const path = join(outDir, file.replace(/^\//, ''));
|
||||
if (!existsSync(path)) problems.push(`missing file in the build: ${file}`);
|
||||
}
|
||||
console.error('\nSee CLAUDE.md hard rule 1 and docs/09 §4 before changing this.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.warn(
|
||||
`check-manifest: clean — MV3, permissions ${JSON.stringify(manifest.permissions)}, no reach-widening keys.`,
|
||||
);
|
||||
/** @param {string} outDir @param {string[]} problems */
|
||||
function checkBundle(outDir, problems) {
|
||||
for (const file of listFiles(outDir).filter((f) => f.endsWith('.js'))) {
|
||||
const match = readFileSync(file, 'utf8').match(NETWORK_IN_BUNDLE);
|
||||
if (match) {
|
||||
const rel = relative(outDir, file).replace(/\\/g, '/');
|
||||
problems.push(`network API "${match[0]}" in the shipped bundle: ${rel} (docs/08 §3)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check one built extension directory.
|
||||
*
|
||||
* @param {string} outDir
|
||||
* @returns {{ problems: string[], readError?: string }} no problems and no read
|
||||
* error means the build is clean
|
||||
*/
|
||||
export function checkExtension(outDir) {
|
||||
const manifest = readManifest(outDir);
|
||||
if (typeof manifest === 'string') return { problems: [], readError: manifest };
|
||||
/** @type {string[]} */
|
||||
const problems = [];
|
||||
checkManifest(manifest, problems);
|
||||
checkInventory(outDir, manifest, problems);
|
||||
checkBundle(outDir, problems);
|
||||
return { problems };
|
||||
}
|
||||
|
||||
/** @returns {number} the exit code */
|
||||
function main() {
|
||||
const repo = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
||||
const { problems, readError } = checkExtension(join(repo, '.output', 'chrome-mv3'));
|
||||
if (readError !== undefined) {
|
||||
console.error(`check-manifest: ${readError} — run \`npm run build\` first.`);
|
||||
return 1;
|
||||
}
|
||||
if (problems.length > 0) {
|
||||
for (const problem of problems) {
|
||||
console.error(`::error::check-manifest: ${problem}`);
|
||||
console.error(` ${problem}`);
|
||||
}
|
||||
console.error('\nSee CLAUDE.md hard rule 1 and docs/09 §4 before changing this.');
|
||||
return 1;
|
||||
}
|
||||
// Constants only: the manifest has just passed every check, so its values ARE
|
||||
// these — and nothing read from a file is echoed into the log.
|
||||
console.warn(
|
||||
`check-manifest: clean — MV3, permissions exactly ${ALLOWED_PERMISSIONS.join(' + ')}, Chrome ≥${CHROME_FLOOR}, CSP pinned, inventory complete, no network API in the bundle.`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Run only as the entry point. Under a test runner `import.meta.url` may not
|
||||
// even be a file: URL, so it is not resolved until it is known to be one.
|
||||
const isEntry =
|
||||
import.meta.url.startsWith('file:') &&
|
||||
process.argv[1] !== undefined &&
|
||||
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
||||
if (isEntry) {
|
||||
// exitCode, not exit(): exit() can cut off piped stderr before CI reads it.
|
||||
process.exitCode = main();
|
||||
}
|
||||
+64
-25
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
// @ts-check
|
||||
/**
|
||||
* Generate a large Netscape bookmark file on demand.
|
||||
*
|
||||
@@ -20,7 +21,10 @@
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
/** Mulberry32 — small, seeded, and good enough for shaping test data. */
|
||||
/**
|
||||
* Mulberry32 — small, seeded, and good enough for shaping test data.
|
||||
* @param {number} seed
|
||||
*/
|
||||
function rng(seed) {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
@@ -31,17 +35,38 @@ function rng(seed) {
|
||||
};
|
||||
}
|
||||
|
||||
const USAGE =
|
||||
'usage: node scripts/gen-fixture.mjs --nodes <n> --out <path> [--per-folder <n>] [--seed <n>]';
|
||||
|
||||
/**
|
||||
* Strict flags: whole numbers >= 1, every flag needs a value, no unknown flags.
|
||||
* The old reader took arguments in blind pairs, so `--nodes 1.5` wrote 2 nodes,
|
||||
* `--per-folder abc` silently wrote no bookmarks, and one missing value shifted
|
||||
* every flag after it.
|
||||
*
|
||||
* @param {string[]} argv
|
||||
* @returns {{ nodes: number, perFolder: number, seed: number, out: string } | string}
|
||||
* the options, or an error message
|
||||
*/
|
||||
function parseArgs(argv) {
|
||||
const out = { nodes: 10_000, perFolder: 50, seed: 1, out: undefined };
|
||||
const out = { nodes: 10_000, perFolder: 50, seed: 1, out: '' };
|
||||
/** @type {Record<string, 'nodes' | 'perFolder' | 'seed'>} */
|
||||
const numeric = { '--nodes': 'nodes', '--per-folder': 'perFolder', '--seed': 'seed' };
|
||||
for (let i = 0; i < argv.length; i += 2) {
|
||||
const key = argv[i];
|
||||
const flag = argv[i] ?? '';
|
||||
const value = argv[i + 1];
|
||||
if (key === '--nodes') out.nodes = Number(value);
|
||||
else if (key === '--per-folder') out.perFolder = Number(value);
|
||||
else if (key === '--seed') out.seed = Number(value);
|
||||
else if (key === '--out') out.out = value;
|
||||
if (value === undefined || value.startsWith('--')) return `${flag} needs a value`;
|
||||
if (flag === '--out') {
|
||||
out.out = value;
|
||||
continue;
|
||||
}
|
||||
const key = numeric[flag];
|
||||
if (key === undefined) return `unknown flag ${flag}`;
|
||||
const n = Number(value);
|
||||
if (!Number.isInteger(n) || n < 1) return `${flag} must be a whole number >= 1, got "${value}"`;
|
||||
out[key] = n;
|
||||
}
|
||||
return out;
|
||||
return out.out === '' ? '--out is required' : out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +86,10 @@ const TITLE_POOL = [
|
||||
'A rather long bookmark title that wraps in most reasonable window widths',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {{ nodes: number, perFolder: number, seed: number }} options
|
||||
* @returns {string}
|
||||
*/
|
||||
function build({ nodes, perFolder, seed }) {
|
||||
const rand = rng(seed);
|
||||
const lines = [
|
||||
@@ -72,14 +101,21 @@ function build({ nodes, perFolder, seed }) {
|
||||
'<DL><p>',
|
||||
];
|
||||
|
||||
let written = 0;
|
||||
let folderIndex = 0;
|
||||
/** @param {number} depth */
|
||||
const indent = (depth) => ' '.repeat(depth);
|
||||
|
||||
// Depth 3 so the walk is exercised, but nowhere near the 200 cap — this file
|
||||
// is for measuring the common case, not the limit.
|
||||
const emitFolder = (depth) => {
|
||||
if (written >= nodes) return;
|
||||
/**
|
||||
* Write one folder (and, below depth 3, one nested folder chain) using at
|
||||
* most `budget` nodes. Returns how many it wrote — always at least 1, so the
|
||||
* caller's loop provably makes progress.
|
||||
*
|
||||
* @param {number} depth
|
||||
* @param {number} written nodes written before this call
|
||||
* @param {number} budget nodes this call may write
|
||||
* @returns {number}
|
||||
*/
|
||||
const emitFolder = (depth, written, budget) => {
|
||||
folderIndex++;
|
||||
const stamp = 1700000000 + folderIndex;
|
||||
lines.push(
|
||||
@@ -88,34 +124,37 @@ function build({ nodes, perFolder, seed }) {
|
||||
}>Folder ${folderIndex}</H3>`,
|
||||
`${indent(depth)}<DL><p>`,
|
||||
);
|
||||
written++;
|
||||
let used = 1;
|
||||
|
||||
const count = Math.min(perFolder, nodes - written);
|
||||
const count = Math.min(perFolder, budget - used);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const n = written + used;
|
||||
const title = TITLE_POOL[Math.floor(rand() * TITLE_POOL.length)];
|
||||
const stampB = 1700000000 + written;
|
||||
lines.push(
|
||||
`${indent(depth + 1)}<DT><A HREF="https://host${written % 997}.example/p${written}?q=${written}" ` +
|
||||
`ADD_DATE="${stampB}">${title}</A>`,
|
||||
`${indent(depth + 1)}<DT><A HREF="https://host${n % 997}.example/p${n}?q=${n}" ` +
|
||||
`ADD_DATE="${1700000000 + n}">${title}</A>`,
|
||||
);
|
||||
written++;
|
||||
used++;
|
||||
}
|
||||
|
||||
if (depth < 3 && written < nodes) emitFolder(depth + 1);
|
||||
// Depth 3 so the walk is exercised, but nowhere near the 200 cap — this
|
||||
// file is for measuring the common case, not the limit.
|
||||
if (depth < 3 && used < budget) used += emitFolder(depth + 1, written + used, budget - used);
|
||||
lines.push(`${indent(depth)}</DL><p>`);
|
||||
return used;
|
||||
};
|
||||
|
||||
while (written < nodes) emitFolder(1);
|
||||
let written = 0;
|
||||
while (written < nodes) written += emitFolder(1, written, nodes - written);
|
||||
lines.push('</DL><p>', '');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
|
||||
if (options.out === undefined || !Number.isFinite(options.nodes) || options.nodes < 1) {
|
||||
console.error(
|
||||
'usage: node scripts/gen-fixture.mjs --nodes <n> --out <path> [--per-folder <n>] [--seed <n>]',
|
||||
);
|
||||
if (typeof options === 'string') {
|
||||
console.error(`gen-fixture: ${options}
|
||||
${USAGE}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
const html = build(options);
|
||||
|
||||
+26
-9
@@ -1,20 +1,26 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* Generate placeholder extension icons — a rounded violet square with a white
|
||||
* bookmark ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is
|
||||
* written by hand (zlib deflate + a CRC32 table), so no image library enters
|
||||
* the tree.
|
||||
* Generate the extension icons — a rounded violet square with a white bookmark
|
||||
* ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is written by
|
||||
* hand (zlib deflate + a CRC32 table), so no image library enters the tree.
|
||||
*
|
||||
* These are functional placeholders so the manifest loads from Phase 0.
|
||||
* Replace with the designed icon before a store release (docs/00 §10 item 3,
|
||||
* docs/13 §2). Run: `npm run icons`.
|
||||
* THIS SCRIPT IS THE SOURCE OF TRUTH for the shipped icons: the owner adopted
|
||||
* its output as final on 2026-07-26 (docs/00 §10 item 3). There is no other
|
||||
* master file. `npm run icons` overwrites src/public/icon/*.png — review the
|
||||
* diff before committing, because those PNGs are what the store listing shows.
|
||||
*/
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { deflateSync } from 'node:zlib';
|
||||
|
||||
/** @typedef {readonly [number, number, number, number]} Rgba */
|
||||
|
||||
/** @type {Rgba} */
|
||||
const ACCENT = [0x6d, 0x4a, 0xff, 255]; // --accent, docs/06 §1
|
||||
/** @type {Rgba} */
|
||||
const WHITE = [255, 255, 255, 255];
|
||||
/** @type {Rgba} */
|
||||
const TRANSPARENT = [0, 0, 0, 0];
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
@@ -27,12 +33,14 @@ const CRC_TABLE = (() => {
|
||||
return table;
|
||||
})();
|
||||
|
||||
/** @param {Uint8Array} buf */
|
||||
function crc32(buf) {
|
||||
let c = 0xffffffff;
|
||||
for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
|
||||
for (const byte of buf) c = (CRC_TABLE[(c ^ byte) & 0xff] ?? 0) ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
/** @param {string} type @param {Buffer} data */
|
||||
function chunk(type, data) {
|
||||
const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
|
||||
const len = Buffer.alloc(4);
|
||||
@@ -42,6 +50,7 @@ function chunk(type, data) {
|
||||
return Buffer.concat([len, body, crc]);
|
||||
}
|
||||
|
||||
/** @param {number} x @param {number} y @param {number} size @param {number} radius */
|
||||
function insideRounded(x, y, size, radius) {
|
||||
const px = x + 0.5;
|
||||
const py = y + 0.5;
|
||||
@@ -50,7 +59,10 @@ function insideRounded(x, y, size, radius) {
|
||||
return dx * dx + dy * dy <= radius * radius;
|
||||
}
|
||||
|
||||
/** Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom. */
|
||||
/**
|
||||
* Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom.
|
||||
* @param {number} x @param {number} y @param {number} size
|
||||
*/
|
||||
function insideBookmark(x, y, size) {
|
||||
const u = (x + 0.5) / size;
|
||||
const v = (y + 0.5) / size;
|
||||
@@ -64,12 +76,17 @@ function insideBookmark(x, y, size) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} x @param {number} y @param {number} size
|
||||
* @returns {Rgba}
|
||||
*/
|
||||
function colorAt(x, y, size) {
|
||||
if (!insideRounded(x, y, size, size * 0.2)) return TRANSPARENT;
|
||||
if (insideBookmark(x, y, size)) return WHITE;
|
||||
return ACCENT;
|
||||
}
|
||||
|
||||
/** @param {number} size */
|
||||
function makePng(size) {
|
||||
const stride = size * 4;
|
||||
const raw = Buffer.alloc((stride + 1) * size);
|
||||
|
||||
+199
-51
@@ -1,51 +1,144 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* The canonical grep gate — docs/08_MV3_COMPLIANCE.md §3.
|
||||
* The zero-network / no-raw-HTML gate — docs/08 §3.
|
||||
*
|
||||
* This file is the single implementation of that pattern. It runs both locally
|
||||
* (`npm run verify`) and in CI (`npm run guard`), so the gate cannot drift
|
||||
* between the two. Zero dependencies, Node stdlib only.
|
||||
* This file IS the rule set; docs/08 §3 points here instead of restating it,
|
||||
* because two copies of a security pattern drift (they did: the doc's
|
||||
* `\{@html\}` matched only the literal `{@html}`, never `{@html x}`).
|
||||
*
|
||||
* Why a grep and not a lint rule: MV3's default CSP blocks remote code, but it
|
||||
* has no connect-src at all and does not restrict network egress. And no Biome
|
||||
* rule sees Svelte's {@html} — noDangerouslySetInnerHtml is a React rule. This
|
||||
* script plus review is the entire enforcement of the zero-network and
|
||||
* no-raw-HTML promises.
|
||||
* It runs locally (`npm run verify`) and in CI (`npm run guard`), so the gate
|
||||
* cannot differ between the two. Zero dependencies, Node stdlib only.
|
||||
*
|
||||
* It is no longer the ONLY enforcement: since v1.1.0 the production manifest
|
||||
* declares a CSP with `connect-src 'none'` (docs/08 §3), so the browser itself
|
||||
* refuses fetch/XHR/WebSocket/EventSource/beacons. This gate catches the rest —
|
||||
* raw HTML sinks, code execution, remote resources in markup and CSS — and
|
||||
* keeps network code out of review in the first place.
|
||||
*
|
||||
* Matching runs over the WHOLE file, not line by line, so `\s*` spans newlines
|
||||
* and splitting a call across two lines no longer gets past a rule. Identifiers
|
||||
* are banned outright where an alias would otherwise slip through
|
||||
* (`const go = fetch; go(u)`), which means the bare words are banned in
|
||||
* comments too — write "network call", not the API name, in prose.
|
||||
*
|
||||
* Usage: node scripts/guard.mjs [--root <dir>] (--root is for its own tests)
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
import { extname, join, relative } from 'node:path';
|
||||
import { extname, join, relative, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/**
|
||||
* fileURLToPath, never `new URL(...).pathname`: the pathname stays
|
||||
* percent-encoded, so a checkout under `C:\Users\Nguyễn\…` or `my dir` became a
|
||||
* path that does not exist — and the walker reported "clean" after scanning
|
||||
* nothing.
|
||||
*/
|
||||
const DEFAULT_ROOT = fileURLToPath(new URL('..', import.meta.url));
|
||||
|
||||
const ROOT = new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
|
||||
const SCAN_DIRS = ['src'];
|
||||
const SCAN_EXTS = new Set(['.ts', '.js', '.mjs', '.svelte']);
|
||||
const SCAN_EXTS = new Set([
|
||||
'.ts',
|
||||
'.mts',
|
||||
'.cts',
|
||||
'.js',
|
||||
'.mjs',
|
||||
'.cjs',
|
||||
'.svelte',
|
||||
'.html',
|
||||
'.css',
|
||||
]);
|
||||
const SKIP_DIRS = new Set(['node_modules', '.output', '.wxt', '.git']);
|
||||
|
||||
/** Each entry: [human-readable name, pattern]. Keep in sync with docs/08 §3. */
|
||||
const BANNED = [
|
||||
['network: fetch', /\bfetch\s*\(/],
|
||||
['network: XMLHttpRequest', /\bXMLHttpRequest\b/],
|
||||
['network: WebSocket', /\bWebSocket\b/],
|
||||
['network: EventSource', /\bEventSource\b/],
|
||||
['network: sendBeacon', /\bsendBeacon\b/],
|
||||
['remote code: eval', /\beval\s*\(/],
|
||||
['remote code: new Function', /\bnew\s+Function\s*\(/],
|
||||
['remote code: dynamic import', /(^|[^.\w])import\s*\(/],
|
||||
['raw HTML: {@html}', /\{@html\b/],
|
||||
['raw HTML: innerHTML assignment', /\b(?:inner|outer)HTML\s*=/],
|
||||
['raw HTML: insertAdjacentHTML', /\binsertAdjacentHTML\b/],
|
||||
/** A URL that leaves the extension: `https://`, `http://` or protocol-relative `//`. */
|
||||
const REMOTE = String.raw`(?:https?:)?\/\/`;
|
||||
|
||||
/**
|
||||
* [category, name, pattern, refine?]. Every pattern carries the `g` flag and is
|
||||
* run over the whole file; when `refine` is present, a match only counts if
|
||||
* `refine` also matches the matched text. Each rule has a positive and a
|
||||
* negative case in tests/unit/scripts/guard.test.ts — add both when adding one.
|
||||
*
|
||||
* No pattern may let two quantifiers compete for the same characters (a
|
||||
* `\s*` beside an optional quote beside another `\s*`): that backtracks
|
||||
* polynomially (SonarCloud S8786), and this script scans whatever lands in src/.
|
||||
*/
|
||||
const RULES = [
|
||||
// Network. Identifiers, not call shapes: aliasing, tagged templates and
|
||||
// `.call()` all start with the bare name.
|
||||
['network', 'fetch', /\bfetch\b/g],
|
||||
['network', 'XMLHttpRequest', /\bXMLHttpRequest\b/g],
|
||||
['network', 'WebSocket', /\bWebSocket\b/g],
|
||||
['network', 'WebTransport', /\bWebTransport\b/g],
|
||||
['network', 'EventSource', /\bEventSource\b/g],
|
||||
['network', 'sendBeacon', /\bsendBeacon\b/g],
|
||||
['network', 'RTCPeerConnection', /\bRTCPeerConnection\b/g],
|
||||
['network', 'importScripts', /\bimportScripts\b/g],
|
||||
// `globalThis['fe' + 'tch']` — computed access on a global is how every
|
||||
// identifier rule above is evaded, so it is banned as a shape.
|
||||
['network', 'computed global access', /\b(?:globalThis|window|self|navigator|document)\s*\[/g],
|
||||
// Resource hints fetch ahead of time. These words have no use in this
|
||||
// extension, so they are banned outright; `preload` is ordinary English, so
|
||||
// only as a rel value.
|
||||
[
|
||||
'network',
|
||||
'resource hint',
|
||||
/\b(?:prefetch|preconnect|prerender|dns-prefetch|modulepreload)\b|\brel\s*=\s*["'`]?preload\b/gi,
|
||||
],
|
||||
// Two linear steps: find a resource-loading tag, then look inside it.
|
||||
[
|
||||
'network',
|
||||
'remote resource in markup',
|
||||
/<(?:img|script|iframe|frame|link|source|video|audio|embed|object|track|image)\b[^>]*>/gi,
|
||||
new RegExp(String.raw`\b(?:src|href|srcset|data|poster)\s*=\s*(?:["'{]\s*)?` + REMOTE, 'i'),
|
||||
],
|
||||
['network', 'remote url() in CSS', new RegExp(String.raw`url\(\s*(?:["']\s*)?` + REMOTE, 'gi')],
|
||||
[
|
||||
'network',
|
||||
'remote @import',
|
||||
new RegExp(String.raw`@import\s+(?:url\(\s*)?(?:["']\s*)?` + REMOTE, 'gi'),
|
||||
],
|
||||
// Remote code.
|
||||
['remote code', 'eval', /\beval\b/g],
|
||||
['remote code', 'Function constructor', /\bFunction\s*\(/g],
|
||||
['remote code', 'string timer', /\bset(?:Timeout|Interval)\s*\(\s*["'`]/g],
|
||||
// `[ \t]*`, not `\s*`: prose that ends a line with "import" and opens the
|
||||
// next with "(" is common in comments, and the MV3 CSP already refuses any
|
||||
// remote script, so this rule is a second line of defence, not the only one.
|
||||
['remote code', 'dynamic import', /(?:^|[^.\w$])import[ \t]*\(/g],
|
||||
[
|
||||
'remote code',
|
||||
'import from URL',
|
||||
new RegExp(String.raw`\b(?:from|import)\s+["']` + REMOTE, 'g'),
|
||||
],
|
||||
// Raw HTML sinks.
|
||||
['raw HTML', '{@html}', /\{\s*@html\b/g],
|
||||
['raw HTML', 'innerHTML / outerHTML', /\b(?:inner|outer)HTML\b/g],
|
||||
['raw HTML', 'insertAdjacentHTML', /\binsertAdjacentHTML\b/g],
|
||||
['raw HTML', 'setHTMLUnsafe / parseHTMLUnsafe', /\b(?:set|parse)HTMLUnsafe\b/g],
|
||||
['raw HTML', 'createContextualFragment', /\bcreateContextualFragment\b/g],
|
||||
['raw HTML', 'srcdoc', /\bsrcdoc\b/gi],
|
||||
['raw HTML', 'document.write', /\bdocument\s*\.\s*write(?:ln)?\b/g],
|
||||
];
|
||||
|
||||
/** Test files may reference banned identifiers when asserting they are absent. */
|
||||
const isExempt = (path) => /\.(test|spec)\.ts$/.test(path);
|
||||
|
||||
async function* walk(dir) {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return; // directory not created yet — nothing to scan
|
||||
/** @param {string[]} argv */
|
||||
function rootFrom(argv) {
|
||||
const at = argv.indexOf('--root');
|
||||
if (at === -1) return DEFAULT_ROOT;
|
||||
const value = argv[at + 1];
|
||||
if (value === undefined || value.startsWith('--')) {
|
||||
console.error('guard: --root needs a directory');
|
||||
process.exit(2);
|
||||
}
|
||||
for (const entry of entries) {
|
||||
return resolve(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} dir
|
||||
* @returns {AsyncGenerator<string>}
|
||||
*/
|
||||
async function* walk(dir) {
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (!SKIP_DIRS.has(entry.name)) yield* walk(full);
|
||||
@@ -55,30 +148,85 @@ async function* walk(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every rule over one file's text.
|
||||
* @param {string} text
|
||||
* @returns {{ line: number, name: string, category: string, excerpt: string }[]}
|
||||
*/
|
||||
function scan(text) {
|
||||
const lines = text.split('\n');
|
||||
const lineStarts = [0];
|
||||
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 0x0a) lineStarts.push(i + 1);
|
||||
/** @param {number} index */
|
||||
const lineOf = (index) => {
|
||||
let lo = 0;
|
||||
let hi = lineStarts.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if ((lineStarts[mid] ?? 0) <= index) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo + 1;
|
||||
};
|
||||
|
||||
const found = [];
|
||||
const seen = new Set();
|
||||
for (const [category, name, pattern, refine] of RULES) {
|
||||
for (const match of text.matchAll(/** @type {RegExp} */ (pattern))) {
|
||||
if (refine instanceof RegExp && !refine.test(match[0])) continue;
|
||||
const line = lineOf(match.index ?? 0);
|
||||
const key = `${line}\u0000${name}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
const excerpt = (lines[line - 1] ?? '').trim().slice(0, 120);
|
||||
found.push({
|
||||
line,
|
||||
name: /** @type {string} */ (name),
|
||||
category: /** @type {string} */ (category),
|
||||
excerpt,
|
||||
});
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
const root = rootFrom(process.argv.slice(2));
|
||||
const violations = [];
|
||||
let scanned = 0;
|
||||
|
||||
for (const dir of SCAN_DIRS) {
|
||||
for await (const file of walk(join(ROOT, dir))) {
|
||||
const rel = relative(ROOT, file).replace(/\\/g, '/');
|
||||
if (isExempt(rel)) continue;
|
||||
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
|
||||
lines.forEach((line, i) => {
|
||||
for (const [name, pattern] of BANNED) {
|
||||
if (pattern.test(line)) violations.push({ rel, line: i + 1, name, text: line.trim() });
|
||||
}
|
||||
});
|
||||
const base = join(root, dir);
|
||||
try {
|
||||
for await (const file of walk(base)) {
|
||||
scanned++;
|
||||
const rel = relative(root, file).replace(/\\/g, '/');
|
||||
const text = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n');
|
||||
for (const hit of scan(text)) violations.push({ rel, ...hit });
|
||||
}
|
||||
} catch (cause) {
|
||||
// A missing src/ used to be "nothing to scan" and printed clean. A gate
|
||||
// that cannot see the code has not passed it.
|
||||
console.error(`guard: cannot scan ${base} — ${cause instanceof Error ? cause.message : cause}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (process.exitCode !== 1 && scanned === 0) {
|
||||
console.error(`guard: scanned 0 files under ${root} — refusing to report clean.`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
if (violations.length > 0) {
|
||||
for (const v of violations) {
|
||||
console.error(`::error file=${v.rel},line=${v.line}::[${v.name}] ${v.text}`);
|
||||
console.error(` ${v.rel}:${v.line} ${v.name}\n ${v.text}`);
|
||||
console.error(`::error file=${v.rel},line=${v.line}::[${v.category}: ${v.name}] ${v.excerpt}`);
|
||||
console.error(` ${v.rel}:${v.line} ${v.category}: ${v.name}\n ${v.excerpt}`);
|
||||
}
|
||||
console.error(
|
||||
`\nguard: ${violations.length} banned pattern(s) found. See docs/08_MV3_COMPLIANCE.md §3.`,
|
||||
);
|
||||
process.exit(1);
|
||||
console.error(`\nguard: ${violations.length} banned pattern(s). See docs/08 §3.`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
console.warn(`guard: clean — no banned patterns in ${SCAN_DIRS.join(', ')}`);
|
||||
if (process.exitCode !== 1) {
|
||||
console.warn(
|
||||
`guard: clean — ${scanned} files under ${SCAN_DIRS.join(', ')}, ${RULES.length} rules`,
|
||||
);
|
||||
}
|
||||
+79
-555
@@ -1,546 +1,51 @@
|
||||
#!/usr/bin/env node
|
||||
// @ts-check
|
||||
/**
|
||||
* Strip personal data from a bookmark file, keeping the bug.
|
||||
*
|
||||
* Purpose: make "attach a sanitized sample" (SECURITY.md, the parser issue
|
||||
* form) something a reporter can actually do, instead of an instruction they
|
||||
* have to interpret.
|
||||
* Inputs: a Netscape HTML, BookmarkMagic JSON, or CSV bookmark file.
|
||||
* Guarantees: every byte outside a replaced address or title is untouched —
|
||||
* including the BOM, the doctype, line endings, tag and attribute case,
|
||||
* quoting style, indentation, and every timestamp. Replacements are stable
|
||||
* per distinct input value, so "how many distinct hosts" and "which two
|
||||
* bookmarks are duplicates" survive.
|
||||
* Inputs: a Netscape HTML export, BookmarkMagic JSON, Chrome's profile
|
||||
* `Bookmarks` file (also Edge/Brave/Vivaldi), a Firefox `.json` backup, or a
|
||||
* docs/04 §3 CSV.
|
||||
* Guarantees: every byte outside a replaced address, title or note is untouched
|
||||
* — the BOM, the doctype, line endings, tag and attribute case, quoting style,
|
||||
* indentation, JSON key order and escapes, and every timestamp. Replacements
|
||||
* are stable per distinct input value, so "how many distinct hosts" and
|
||||
* "which two bookmarks are duplicates" survive. When the output still looks
|
||||
* personal, nothing is written at all.
|
||||
*
|
||||
* Zero dependencies, Node stdlib only, no network. It has to run from a fresh
|
||||
* clone with nothing installed, which is also why it re-implements a three-line
|
||||
* format sniff rather than importing `src/lib/core/detect-format.ts`.
|
||||
* Zero dependencies, Node stdlib only, no network, plain JavaScript: it has to
|
||||
* run from a fresh clone with nothing installed, on whatever Node the reporter
|
||||
* has. The format modules live in scripts/sanitize/.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/sanitize-bookmarks.mjs <input> [output]
|
||||
* node scripts/sanitize-bookmarks.mjs <input> --stdout
|
||||
* node scripts/sanitize-bookmarks.mjs <input> --check # report, write nothing
|
||||
*/
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { basename, extname } from 'node:path';
|
||||
import { readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { basename, extname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { sanitizeCsv } from './sanitize/csv.mjs';
|
||||
import { detectKind } from './sanitize/detect.mjs';
|
||||
import { sanitizeHtml } from './sanitize/html.mjs';
|
||||
import { sanitizeJson } from './sanitize/json.mjs';
|
||||
import { findLeakedHosts, findLeakedWords } from './sanitize/leaks.mjs';
|
||||
import { makeTitleMapper, makeUrlMapper } from './sanitize/mappers.mjs';
|
||||
|
||||
export { detectKind } from './sanitize/detect.mjs';
|
||||
export { findLeakedHosts, findLeakedWords } from './sanitize/leaks.mjs';
|
||||
|
||||
/** Matches docs/09's parse cap. A 25 MB attachment helps nobody anyway. */
|
||||
const MAX_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
/** 1×1 transparent PNG. Keeps ICON= present, which is what the parser reacts to. */
|
||||
const BLANK_ICON =
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
|
||||
|
||||
// ---------------------------------------------------------------- format sniff
|
||||
|
||||
/** The docs/04 §3 CSV header, in order. A file is CSV only if it says so. */
|
||||
const CSV_HEADER = ['folder_path', 'title', 'url', 'add_date'];
|
||||
|
||||
/**
|
||||
* Identify the format, or refuse.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {'html' | 'json' | 'csv' | null} `null` when nothing matched.
|
||||
*
|
||||
* Returning `null` rather than guessing is load-bearing. Every sanitizer below
|
||||
* finds what it must destroy *by format*, so a wrong guess destroys nothing and
|
||||
* emits the input verbatim — and the file would still be handed to the user as
|
||||
* "sanitized". The old `return 'csv'` fallback did exactly that for a truncated
|
||||
* JSON export, an HTML excerpt with no doctype, or a CSV with foreign headers:
|
||||
* byte-identical output, exit code 0, real hostnames intact.
|
||||
*
|
||||
* The people who run this tool are, by definition, the ones whose file did not
|
||||
* import — so a malformed or hand-trimmed file is the *typical* input here, not
|
||||
* an edge case. `src/lib/core/detect-format.ts` refuses these same inputs with
|
||||
* `UNKNOWN_FORMAT`; this must not be weaker than the parser it fronts.
|
||||
*/
|
||||
export function detectKind(text) {
|
||||
const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
||||
if (/NETSCAPE-Bookmark-file-1/i.test(body.slice(0, 512))) return 'html';
|
||||
const trimmed = body.trimStart();
|
||||
if (trimmed.startsWith('{')) {
|
||||
try {
|
||||
JSON.parse(trimmed);
|
||||
return 'json';
|
||||
} catch {
|
||||
// Not JSON after all; fall through.
|
||||
}
|
||||
}
|
||||
const firstLine = body.split(/\r?\n/, 1)[0] ?? '';
|
||||
for (const delimiter of [',', ';']) {
|
||||
const columns = firstLine
|
||||
.split(delimiter)
|
||||
.map((h) => h.trim().replace(/^"|"$/g, '').toLowerCase());
|
||||
if (columns.length === CSV_HEADER.length && CSV_HEADER.every((c, i) => columns[i] === c)) {
|
||||
return 'csv';
|
||||
}
|
||||
}
|
||||
if (/<\s*dl[\s>]/i.test(body)) return 'html';
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- mappers
|
||||
|
||||
/**
|
||||
* Replace addresses while preserving everything a parser branches on: the
|
||||
* scheme, whether there is a port, how deep the path is, whether it ends in a
|
||||
* slash, how many query parameters there are and in what order, and whether
|
||||
* there is a fragment. Percent-escapes are carried across literally, so a
|
||||
* decoding bug still reproduces.
|
||||
*/
|
||||
function makeUrlMapper() {
|
||||
const seen = new Map();
|
||||
const hosts = new Map();
|
||||
|
||||
const hostAlias = (host) => {
|
||||
let alias = hosts.get(host);
|
||||
if (alias === undefined) {
|
||||
const n = hosts.size;
|
||||
// a.example … z.example, then a1.example, a2.example …
|
||||
const letter = String.fromCharCode(97 + (n % 26));
|
||||
const round = Math.floor(n / 26);
|
||||
alias = round === 0 ? `${letter}.example` : `${letter}${round}.example`;
|
||||
hosts.set(host, alias);
|
||||
}
|
||||
return alias;
|
||||
};
|
||||
|
||||
const escapesIn = (segment) => (segment.match(/%[0-9a-fA-F]{2}/g) ?? []).join('');
|
||||
|
||||
const mapPath = (pathname) => {
|
||||
if (pathname === '' || pathname === '/') return pathname;
|
||||
const trailing = pathname.endsWith('/');
|
||||
const parts = pathname.replace(/^\//, '').replace(/\/$/, '').split('/');
|
||||
const mapped = parts.map((p, i) => (p === '' ? '' : `p${i + 1}${escapesIn(p)}`));
|
||||
return `/${mapped.join('/')}${trailing ? '/' : ''}`;
|
||||
};
|
||||
|
||||
const mapQuery = (search) => {
|
||||
if (search === '') return '';
|
||||
return `?${search
|
||||
.slice(1)
|
||||
.split('&')
|
||||
.map((pair, i) => (pair.includes('=') ? `q${i + 1}=v${i + 1}` : `q${i + 1}`))
|
||||
.join('&')}`;
|
||||
};
|
||||
|
||||
return (raw) => {
|
||||
if (raw === '') return raw;
|
||||
const cached = seen.get(raw);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
let out;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
url = undefined;
|
||||
}
|
||||
|
||||
if (url === undefined) {
|
||||
// Keep it unparseable, and keep distinct values distinct — the dedupe
|
||||
// path treats an unparseable URL as its own trimmed self.
|
||||
out = `not-a-url-${seen.size + 1}`;
|
||||
} else if (url.host === '') {
|
||||
// Opaque scheme (javascript:, data:, mailto:). The scheme is the whole
|
||||
// point for the T1/T3 threat cases; the payload is not ours to keep.
|
||||
out = `${url.protocol}sanitized-${seen.size + 1}`;
|
||||
} else {
|
||||
// Credentials are never round-tripped, not even as placeholders.
|
||||
const port = url.port === '' ? '' : `:${url.port}`;
|
||||
const hash = url.hash === '' ? '' : '#frag';
|
||||
out = `${url.protocol}//${hostAlias(url.host.replace(/:\d+$/, ''))}${port}${mapPath(url.pathname)}${mapQuery(url.search)}${hash}`;
|
||||
}
|
||||
|
||||
seen.set(raw, out);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace titles while preserving what encoding bugs live in: emptiness, the
|
||||
* scripts present (so a CJK or RTL or emoji bug still reproduces), and any HTML
|
||||
* entity references, which are carried across verbatim.
|
||||
*/
|
||||
function makeTitleMapper() {
|
||||
const seen = new Map();
|
||||
const SCRIPTS = [
|
||||
[/[一-鿿-ヿ]/, '文字'],
|
||||
[/[-ࣿ]/, 'شيء'],
|
||||
[/[\p{Extended_Pictographic}]/u, '🌸'],
|
||||
];
|
||||
|
||||
return (raw) => {
|
||||
if (raw.trim() === '') return raw;
|
||||
const cached = seen.get(raw);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const entities = (raw.match(/&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z]+);/g) ?? []).join('');
|
||||
const extras = SCRIPTS.filter(([re]) => re.test(raw))
|
||||
.map(([, sample]) => sample)
|
||||
.join('');
|
||||
const out = `Title ${seen.size + 1}${extras === '' ? '' : ` ${extras}`}${entities}`;
|
||||
seen.set(raw, out);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ span rewriting
|
||||
|
||||
/**
|
||||
* Apply replacements by character span, right to left.
|
||||
*
|
||||
* Everything this tool does is expressed as spans so that the bytes between
|
||||
* them are provably untouched — that is the property the whole exercise rests
|
||||
* on, and rebuilding the file from a parsed model would quietly lose it.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {{start: number, end: number, value: string}[]} spans
|
||||
*/
|
||||
function replaceSpans(text, spans) {
|
||||
// Overlaps are dropped, outermost first. Two patterns can legitimately claim
|
||||
// the same bytes — an <A> title containing `x="http://…"` matches both the
|
||||
// title rule and the generic attribute sweep — and applying both would splice
|
||||
// already-rewritten text using an `end` measured against the original,
|
||||
// silently eating or stranding bytes. The widest span sanitizes the most.
|
||||
const ordered = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
|
||||
const out = [];
|
||||
let cursor = 0;
|
||||
for (const span of ordered) {
|
||||
if (span.start < cursor) continue;
|
||||
out.push(text.slice(cursor, span.start), span.value);
|
||||
cursor = span.end;
|
||||
}
|
||||
out.push(text.slice(cursor));
|
||||
// Joined once rather than spliced per span: the old loop rebuilt the whole
|
||||
// string for every replacement, which is O(spans x file) and takes minutes on
|
||||
// a large export.
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect spans for one capture group of a global regex. `map` receives the
|
||||
* captured text.
|
||||
*
|
||||
* The group's offset is computed by re-scanning the match, so the regex must
|
||||
* capture a span that appears only once within it — true for every pattern
|
||||
* here, since each captures an attribute value or an element's text.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {RegExp} re
|
||||
* @param {(captured: string) => string} map
|
||||
* @param {number} [group]
|
||||
*/
|
||||
function spansFrom(text, re, map, group = 1) {
|
||||
// The `d` flag gives exact per-group offsets. The previous version searched
|
||||
// the match text for the captured substring, which lands on the wrong copy
|
||||
// whenever the capture also appears earlier in the match — e.g. a bookmark
|
||||
// whose title equals part of its own URL.
|
||||
const indexed = new RegExp(re.source, re.flags.includes('d') ? re.flags : `${re.flags}d`);
|
||||
const spans = [];
|
||||
for (const m of text.matchAll(indexed)) {
|
||||
const captured = m[group] ?? '';
|
||||
const at = m.indices?.[group];
|
||||
if (captured === '' || at === undefined) continue;
|
||||
spans.push({ start: at[0], end: at[1], value: map(captured) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/**
|
||||
* The inside of an opening tag, tolerating `>` within quoted attribute values.
|
||||
*
|
||||
* `data:text/html,<h1>hi</h1>` is a legal HREF and appears in the T1/T3
|
||||
* fixtures. A naive `[^>]*` stops inside it, silently leaving that bookmark's
|
||||
* title unsanitized — which is the one failure mode this tool must not have.
|
||||
*/
|
||||
const TAG_INNARDS = '(?:"[^"]*"|\'[^\']*\'|[^>"\'])*';
|
||||
|
||||
// ------------------------------------------------------------------ formats
|
||||
|
||||
/**
|
||||
* Decode an HTML attribute value, then re-encode the result the way the source
|
||||
* file encoded it.
|
||||
*
|
||||
* Netscape exports write `&` inside HREF, but not all of them do, and
|
||||
* whether a parser unescapes attribute values is itself something people report
|
||||
* bugs about. Emitting a bare `&` where the source had `&` would silently
|
||||
* repair the file being reported.
|
||||
*/
|
||||
function attrRewriter(map) {
|
||||
return (captured) => {
|
||||
const decoded = captured
|
||||
.replace(/&/gi, '&')
|
||||
.replace(/</gi, '<')
|
||||
.replace(/>/gi, '>')
|
||||
.replace(/"/gi, '"');
|
||||
const mapped = map(decoded);
|
||||
const escapesAmp = /&/i.test(captured) || !captured.includes('&');
|
||||
return escapesAmp ? mapped.replace(/&/g, '&') : mapped;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `name = value`, where the value is double-quoted, single-quoted or bare.
|
||||
*
|
||||
* Group 2/3/4 is the value, whichever quoting was used. Matching only `"…"`
|
||||
* left `HREF='https://…'` completely untouched — real exports in the wild use
|
||||
* single quotes, and that one is a straight leak.
|
||||
*/
|
||||
const ANY_ATTR = /\b([a-z_][a-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+))/dgi;
|
||||
|
||||
/**
|
||||
* Spans for every attribute whose name matches, at any quoting.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {RegExp} nameRe tested against the lower-cased attribute name
|
||||
* @param {(value: string) => string} map
|
||||
*/
|
||||
function attrSpans(text, nameRe, map) {
|
||||
const spans = [];
|
||||
for (const m of text.matchAll(ANY_ATTR)) {
|
||||
if (!nameRe.test((m[1] ?? '').toLowerCase())) continue;
|
||||
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
|
||||
const value = m[2] ?? m[3] ?? m[4] ?? '';
|
||||
if (at === undefined || value === '') continue;
|
||||
spans.push({ start: at[0], end: at[1], value: map(value) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/** Attributes handled explicitly; the generic URL sweep must not touch them. */
|
||||
const HANDLED_ATTRS = new Set(['href', 'icon']);
|
||||
|
||||
/**
|
||||
* Scrub any *other* attribute whose value is a URL with a host.
|
||||
*
|
||||
* Firefox alone writes `ICON_URI`, and `FEEDURL` and friends exist in the wild.
|
||||
* Enumerating them was already wrong once — `ICON_URI` leaked a real hostname
|
||||
* through a file that had passed every other check — so this sweeps by value
|
||||
* shape instead, and covers attributes nobody has thought of yet.
|
||||
*/
|
||||
function urlAttrSpans(text, mapUrl) {
|
||||
const spans = [];
|
||||
const rewrite = attrRewriter(mapUrl);
|
||||
for (const m of text.matchAll(ANY_ATTR)) {
|
||||
const name = (m[1] ?? '').toLowerCase();
|
||||
const value = m[2] ?? m[3] ?? m[4] ?? '';
|
||||
if (HANDLED_ATTRS.has(name) || value === '') continue;
|
||||
try {
|
||||
if (new URL(value).host === '') continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
|
||||
if (at === undefined) continue;
|
||||
spans.push({ start: at[0], end: at[1], value: rewrite(value) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
function sanitizeHtml(text, mapUrl, mapTitle) {
|
||||
let descriptions = 0;
|
||||
let keywords = 0;
|
||||
const spans = [
|
||||
// HREF and ICON, at any quoting — attribute name case is left as found.
|
||||
...attrSpans(text, /^href$/, attrRewriter(mapUrl)),
|
||||
...attrSpans(text, /^icon$/, () => BLANK_ICON),
|
||||
...urlAttrSpans(text, mapUrl),
|
||||
// Firefox keywords and tags are user-authored text, so they are personal
|
||||
// too. Tag count is preserved because it is the only part a parser sees.
|
||||
...attrSpans(text, /^shortcuturl$/, () => `kw${++keywords}`),
|
||||
...attrSpans(text, /^tags$/, (v) =>
|
||||
v
|
||||
.split(',')
|
||||
.map((_, i) => `tag${i + 1}`)
|
||||
.join(','),
|
||||
),
|
||||
// Bookmark titles: the text between <A …> and </A>.
|
||||
// `[\s\S]*?` and not `[^<]*`: a title containing a raw `<` made the whole
|
||||
// match fail, so that bookmark's title was left in the output untouched.
|
||||
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([\\s\\S]*?)</a>`, 'gi'), mapTitle),
|
||||
// Folder titles.
|
||||
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([\\s\\S]*?)</h3>`, 'gi'), mapTitle),
|
||||
// Folder/bookmark descriptions.
|
||||
// Runs to the next element, not to the end of the line: a description that
|
||||
// wrapped onto a second line left everything after the first newline in
|
||||
// place, and a `<DD>` is exactly where someone writes a private note.
|
||||
...spansFrom(
|
||||
text,
|
||||
// The `\s*` belongs in the lookahead, not the capture: leaving it inside
|
||||
// eats the newline and indentation before the next tag, which is exactly
|
||||
// the byte-level shape this tool promises not to touch.
|
||||
/<dd>([\s\S]*?)(?=\s*<\s*(?:dt|dd|dl|\/dl)\b|\s*$)/gi,
|
||||
() => `Description ${++descriptions}`,
|
||||
),
|
||||
];
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite only the *values* of `url` and `title` string properties, by walking
|
||||
* the raw text. Parsing and re-stringifying would normalize the indentation and
|
||||
* line endings, which is exactly what a whitespace-sensitive report needs kept.
|
||||
*/
|
||||
function sanitizeJson(text, mapUrl, mapTitle) {
|
||||
const spans = [];
|
||||
const re = /"(url|title)"\s*:\s*"((?:[^"\\]|\\.)*)"/g;
|
||||
for (const m of text.matchAll(re)) {
|
||||
const key = m[1];
|
||||
const rawValue = m[2] ?? '';
|
||||
const start = m.index + m[0].length - 1 - rawValue.length;
|
||||
let decoded;
|
||||
try {
|
||||
decoded = JSON.parse(`"${rawValue}"`);
|
||||
} catch {
|
||||
decoded = rawValue;
|
||||
}
|
||||
const mapped = key === 'url' ? mapUrl(decoded) : mapTitle(decoded);
|
||||
spans.push({ start, end: start + rawValue.length, value: JSON.stringify(mapped).slice(1, -1) });
|
||||
}
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk the CSV with a minimal RFC 4180 reader that records the span of each
|
||||
* field's *content* (inside the quotes, when quoted). Replacements never
|
||||
* contain a delimiter, quote or newline, so the original quoting survives
|
||||
* untouched — which matters, because CSV quoting is itself a common bug.
|
||||
*/
|
||||
function sanitizeCsv(text, mapUrl, mapTitle) {
|
||||
const delimiter = (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
|
||||
const fields = [];
|
||||
let row = 0;
|
||||
let col = 0;
|
||||
let i = 0;
|
||||
|
||||
while (i < text.length) {
|
||||
const quoted = text[i] === '"';
|
||||
if (quoted) i++;
|
||||
const start = i;
|
||||
while (i < text.length) {
|
||||
const ch = text[i];
|
||||
if (quoted) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === delimiter || ch === '\n' || ch === '\r') break;
|
||||
i++;
|
||||
}
|
||||
fields.push({ row, col, start, end: i, quoted });
|
||||
if (quoted && text[i] === '"') i++;
|
||||
|
||||
if (text[i] === delimiter) {
|
||||
col++;
|
||||
i++;
|
||||
} else {
|
||||
if (text[i] === '\r') i++;
|
||||
if (text[i] === '\n') i++;
|
||||
row++;
|
||||
col = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Column names per docs/04 §3 — `folder_path`, not `folder`.
|
||||
const header = fields.filter((f) => f.row === 0).map((f) => text.slice(f.start, f.end).trim());
|
||||
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^/, '') === name);
|
||||
const [folderCol, titleCol, urlCol] = [at('folder_path'), at('title'), at('url')];
|
||||
|
||||
const spans = [];
|
||||
for (const f of fields) {
|
||||
if (f.row === 0 || f.start === f.end) continue;
|
||||
const raw = text.slice(f.start, f.end);
|
||||
const value = raw.replace(/""/g, '"');
|
||||
let mapped;
|
||||
if (f.col === urlCol) mapped = mapUrl(value);
|
||||
else if (f.col === titleCol) mapped = mapTitle(value);
|
||||
else if (f.col === folderCol) mapped = mapFolderPath(value, mapTitle);
|
||||
else continue;
|
||||
spans.push({ start: f.start, end: f.end, value: mapped.replace(/"/g, '""') });
|
||||
}
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map each path segment separately so `\/` and `\\` escapes keep their meaning.
|
||||
*
|
||||
* A segment that contained a literal slash or backslash keeps one, so the
|
||||
* escape survives into the output. Without that, `Escaped\/slash` sanitizes to
|
||||
* a plain name and the escape branch of the CSV path parser — a real reason
|
||||
* someone would file a report — stops being exercised by the sample.
|
||||
*/
|
||||
function mapFolderPath(path, mapTitle) {
|
||||
const segments = [];
|
||||
let current = '';
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const ch = path[i];
|
||||
if (ch === '\\' && (path[i + 1] === '/' || path[i + 1] === '\\')) {
|
||||
current += path[i + 1];
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '/') {
|
||||
segments.push(current);
|
||||
current = '';
|
||||
continue;
|
||||
}
|
||||
current += ch;
|
||||
}
|
||||
segments.push(current);
|
||||
return segments
|
||||
.map((s) => {
|
||||
if (s === '') return '';
|
||||
const kept = `${s.includes('/') ? '/' : ''}${s.includes('\\') ? '\\' : ''}`;
|
||||
return `${mapTitle(s)}${kept}`.replace(/\\/g, '\\\\').replace(/\//g, '\\/');
|
||||
})
|
||||
.join('/');
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- entry points
|
||||
|
||||
/**
|
||||
* Everything in the OUTPUT that still looks like a real address.
|
||||
*
|
||||
* This is the backstop, and it is the only reason the rules above can be
|
||||
* trusted. They are regexes over untrusted markup, so each one has a shape it
|
||||
* does not match — a single-quoted attribute, a title containing `<`, a JSON
|
||||
* key nobody enumerated, a `<DD>` that wraps onto a second line. Every one of
|
||||
* those is a silent leak, and the only way to find them all by inspection is to
|
||||
* be sure you have thought of every one, which nobody is.
|
||||
*
|
||||
* So instead of trusting the rules, the output is checked: any host that is not
|
||||
* one of our own `*.example` aliases means something got through, and the file
|
||||
* is refused rather than handed over. A rule this misses degrades into a
|
||||
* refusal — annoying — instead of into a published browsing history.
|
||||
*
|
||||
* @param {string} text sanitized output
|
||||
* @returns {string[]} distinct suspicious hosts, empty when clean
|
||||
*/
|
||||
export function findLeakedHosts(text) {
|
||||
const leaked = new Set();
|
||||
for (const m of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/([^\s"'<>)\]}\\]+)/gi)) {
|
||||
const authority = (m[1] ?? '').split(/[/?#]/, 1)[0] ?? '';
|
||||
// Strip credentials and port; what remains is the host.
|
||||
const host = authority.split('@').pop()?.replace(/:\d+$/, '').toLowerCase() ?? '';
|
||||
if (host === '' || /^[a-z]\d*\.example$/.test(host)) continue;
|
||||
leaked.add(host);
|
||||
}
|
||||
return [...leaked];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize a bookmark file's text.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {{ text: string | null, kind: 'html' | 'json' | 'csv' | null, leaked: string[] }}
|
||||
* @returns {{ text: string | null, kind: import('./sanitize/detect.mjs').Kind | null, leaked: string[] }}
|
||||
* `text` is null when the format was not recognised, or when the output
|
||||
* failed its own leak check. Both mean: write nothing.
|
||||
*/
|
||||
@@ -550,17 +55,44 @@ export function sanitize(text) {
|
||||
|
||||
const mapUrl = makeUrlMapper();
|
||||
const mapTitle = makeTitleMapper();
|
||||
const out =
|
||||
kind === 'html'
|
||||
? sanitizeHtml(text, mapUrl, mapTitle)
|
||||
: kind === 'json'
|
||||
? sanitizeJson(text, mapUrl, mapTitle)
|
||||
: sanitizeCsv(text, mapUrl, mapTitle);
|
||||
let out;
|
||||
if (kind === 'html') out = sanitizeHtml(text, mapUrl, mapTitle);
|
||||
else if (kind === 'csv') out = sanitizeCsv(text, mapUrl, mapTitle);
|
||||
else out = sanitizeJson(text, mapUrl, mapTitle);
|
||||
|
||||
const leaked = findLeakedHosts(out);
|
||||
const leaked = [
|
||||
...findLeakedHosts(out),
|
||||
...(kind === 'html' ? findLeakedWords(out).map((word) => `text "${word}"`) : []),
|
||||
];
|
||||
return { text: leaked.length > 0 ? null : out, kind, leaked };
|
||||
}
|
||||
|
||||
/** @param {string} input */
|
||||
function refuseUnknown(input) {
|
||||
console.error(
|
||||
`${basename(input)} is not a bookmark file this tool recognises, so NOTHING WAS WRITTEN.\n` +
|
||||
' Expected one of: a Netscape HTML export (the usual bookmarks.html), a BookmarkMagic\n' +
|
||||
' JSON export, Chrome\'s profile "Bookmarks" file, a Firefox bookmarks-*.json backup,\n' +
|
||||
' or a CSV whose header is exactly "folder_path,title,url,add_date".\n' +
|
||||
' Refusing to hand you a file it cannot promise is clean. Please attach the export\n' +
|
||||
' exactly as your browser wrote it, or describe the problem in the issue instead.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** @param {string} input @param {string[]} leaked */
|
||||
function refuseLeak(input, leaked) {
|
||||
console.error(
|
||||
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${leaked.length} item(s) ` +
|
||||
`that look personal, so this file is not safe to attach.\n Found: ${leaked.slice(0, 5).join(', ')}` +
|
||||
`${leaked.length > 5 ? `, and ${leaked.length - 5} more` : ''}\n` +
|
||||
' This is a bug in the sanitizer, not in your file. Please report it (without the file)\n' +
|
||||
' at https://github.com/poli0981/bookmarkmagic/issues — the list above is enough.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** @param {string[]} argv */
|
||||
function main(argv) {
|
||||
const flags = argv.filter((a) => a.startsWith('--'));
|
||||
const [input, maybeOutput] = argv.filter((a) => !a.startsWith('--'));
|
||||
@@ -570,44 +102,28 @@ function main(argv) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
const raw = readFileSync(input);
|
||||
if (raw.byteLength > MAX_BYTES) {
|
||||
// Size first, from the file system: reading a 2 GB file to learn it is too
|
||||
// big is how the old version ran out of memory before its own check.
|
||||
const size = statSync(input).size;
|
||||
if (size > MAX_BYTES) {
|
||||
console.error(
|
||||
`${input} is ${(raw.byteLength / 1024 / 1024).toFixed(1)} MB. The extension itself refuses ` +
|
||||
`${input} is ${(size / 1024 / 1024).toFixed(1)} MB. The extension itself refuses ` +
|
||||
'anything over 25 MB, and a smaller file that still reproduces the bug is more useful. ' +
|
||||
'Please trim it first.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const text = raw.toString('utf8');
|
||||
const text = readFileSync(input).toString('utf8');
|
||||
const { text: out, kind, leaked } = sanitize(text);
|
||||
|
||||
if (kind === null) {
|
||||
console.error(
|
||||
`${basename(input)} is not a bookmark file this tool recognises, so NOTHING WAS WRITTEN.\n` +
|
||||
' Expected: a Netscape HTML export (the usual bookmarks.html), a BookmarkMagic JSON\n' +
|
||||
' export, or a CSV whose header is exactly "folder_path,title,url,add_date".\n' +
|
||||
' Refusing to hand you a file it cannot promise is clean. Please attach the export\n' +
|
||||
' exactly as your browser wrote it, or describe the problem in the issue instead.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (out === null) {
|
||||
console.error(
|
||||
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${leaked.length} real ` +
|
||||
`address(es), so this file is not safe to attach.\n Leaked: ${leaked.slice(0, 5).join(', ')}` +
|
||||
`${leaked.length > 5 ? `, and ${leaked.length - 5} more` : ''}\n` +
|
||||
' This is a bug in the sanitizer, not in your file. Please report it (without the file)\n' +
|
||||
' at https://github.com/poli0981/bookmarkmagic/issues — the address above is enough.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
if (kind === null) return refuseUnknown(input);
|
||||
if (out === null) return refuseLeak(input, leaked);
|
||||
|
||||
const eol = text.includes('\r\n') ? 'CRLF' : 'LF';
|
||||
const bom = text.charCodeAt(0) === 0xfeff ? ', BOM' : '';
|
||||
console.error(`${basename(input)}: ${kind}, ${eol}${bom} — ${out.length} bytes out, no leaks`);
|
||||
console.error(
|
||||
`${basename(input)}: ${kind}, ${eol}${bom} — ${Buffer.byteLength(out)} bytes out, no leaks`,
|
||||
);
|
||||
|
||||
if (flags.includes('--check')) return 0;
|
||||
if (flags.includes('--stdout')) {
|
||||
@@ -617,11 +133,19 @@ function main(argv) {
|
||||
|
||||
const ext = extname(input);
|
||||
const target = maybeOutput ?? `${input.slice(0, input.length - ext.length)}.sanitized${ext}`;
|
||||
// Never over the original: an output path equal to the input used to replace
|
||||
// the user's only copy of their real bookmarks with the placeholder version.
|
||||
if (resolve(target) === resolve(input)) {
|
||||
console.error(
|
||||
`refusing to overwrite ${input} with its sanitized copy — pick another output path.`,
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
writeFileSync(target, out);
|
||||
console.error(`wrote ${target}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* CSV (docs/04 §3): a minimal RFC 4180 reader that records the span of each
|
||||
* field's *content* (inside the quotes, when quoted). Replacements never
|
||||
* contain a delimiter, quote or newline, so the original quoting survives —
|
||||
* which matters, because CSV quoting is itself a common bug.
|
||||
*/
|
||||
import { replaceSpans } from './spans.mjs';
|
||||
|
||||
/** @typedef {import('./spans.mjs').Span} Span */
|
||||
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
|
||||
/** @typedef {{ row: number, col: number, start: number, end: number }} Field */
|
||||
|
||||
/**
|
||||
* @param {string} text
|
||||
* @param {string} delimiter
|
||||
* @returns {Field[]}
|
||||
*/
|
||||
function readFields(text, delimiter) {
|
||||
/** @type {Field[]} */
|
||||
const fields = [];
|
||||
let row = 0;
|
||||
let col = 0;
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const quoted = text[i] === '"';
|
||||
if (quoted) i++;
|
||||
const start = i;
|
||||
while (i < text.length) {
|
||||
const ch = text[i];
|
||||
if (quoted) {
|
||||
if (ch === '"' && text[i + 1] === '"') i += 2;
|
||||
else if (ch === '"') break;
|
||||
else i++;
|
||||
} else if (ch === delimiter || ch === '\n' || ch === '\r') {
|
||||
break;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
fields.push({ row, col, start, end: i });
|
||||
if (quoted && text[i] === '"') i++;
|
||||
if (text[i] === delimiter) {
|
||||
col++;
|
||||
i++;
|
||||
} else {
|
||||
if (text[i] === '\r') i++;
|
||||
if (text[i] === '\n') i++;
|
||||
row++;
|
||||
col = 0;
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map each path segment separately so `\/` and `\\` escapes keep their meaning.
|
||||
* A segment that contained a literal slash or backslash keeps one, so the
|
||||
* escape branch of the CSV path parser — a real reason someone files a report —
|
||||
* is still exercised by the sample.
|
||||
*
|
||||
* @param {string} path
|
||||
* @param {Mapper} mapTitle
|
||||
*/
|
||||
function mapFolderPath(path, mapTitle) {
|
||||
const segments = [];
|
||||
let current = '';
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const ch = path[i];
|
||||
if (ch === '\\' && (path[i + 1] === '/' || path[i + 1] === '\\')) {
|
||||
current += path[i + 1];
|
||||
i++;
|
||||
} else if (ch === '/') {
|
||||
segments.push(current);
|
||||
current = '';
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
}
|
||||
segments.push(current);
|
||||
return segments
|
||||
.map((s) => {
|
||||
if (s === '') return '';
|
||||
const kept = `${s.includes('/') ? '/' : ''}${s.includes('\\') ? '\\' : ''}`;
|
||||
return `${mapTitle(s)}${kept}`.replace(/\\/g, '\\\\').replace(/\//g, '\\/');
|
||||
})
|
||||
.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} text
|
||||
* @param {Mapper} mapUrl
|
||||
* @param {Mapper} mapTitle
|
||||
*/
|
||||
export function sanitizeCsv(text, mapUrl, mapTitle) {
|
||||
const delimiter = (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
|
||||
const fields = readFields(text, delimiter);
|
||||
|
||||
// Column names per docs/04 §3 — `folder_path`, not `folder`.
|
||||
const header = fields.filter((f) => f.row === 0).map((f) => text.slice(f.start, f.end).trim());
|
||||
/** @param {string} name */
|
||||
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^/, '') === name);
|
||||
const [folderCol, titleCol, urlCol] = [at('folder_path'), at('title'), at('url')];
|
||||
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
for (const f of fields) {
|
||||
if (f.row === 0 || f.start === f.end) continue;
|
||||
const value = text.slice(f.start, f.end).replace(/""/g, '"');
|
||||
let mapped;
|
||||
if (f.col === urlCol) mapped = mapUrl(value);
|
||||
else if (f.col === titleCol) mapped = mapTitle(value);
|
||||
else if (f.col === folderCol) mapped = mapFolderPath(value, mapTitle);
|
||||
else continue;
|
||||
spans.push({ start: f.start, end: f.end, value: mapped.replace(/"/g, '""') });
|
||||
}
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* Format sniffing for the sanitizer — refuse anything not positively known.
|
||||
*
|
||||
* Returning `null` rather than guessing is load-bearing. Every sanitizer finds
|
||||
* what it must destroy *by format*, so a wrong guess destroys nothing and emits
|
||||
* the input verbatim — and the file would still be handed over as "sanitized".
|
||||
* The old `return 'csv'` fallback did exactly that for a truncated JSON export.
|
||||
*
|
||||
* The same goes for JSON: the old check accepted ANY object, and the JSON
|
||||
* rewriter only knew BookmarkMagic's `title`/`url` keys — so Chrome's profile
|
||||
* `Bookmarks` file, which keeps titles under `name`, "sanitized" with every
|
||||
* title intact and passed the host check. Each JSON dialect is now recognised
|
||||
* by shape, and anything else is refused.
|
||||
*
|
||||
* Re-implemented rather than imported from `src/lib/core/detect-format.ts`:
|
||||
* this script must run from a fresh clone with nothing installed.
|
||||
*/
|
||||
|
||||
/** The docs/04 §3 CSV header, in order. A file is CSV only if it says so. */
|
||||
const CSV_HEADER = ['folder_path', 'title', 'url', 'add_date'];
|
||||
|
||||
/** @typedef {'html' | 'json' | 'chrome-json' | 'firefox-json' | 'csv'} Kind */
|
||||
|
||||
/**
|
||||
* @param {unknown} doc
|
||||
* @returns {'json' | 'chrome-json' | 'firefox-json' | null}
|
||||
*/
|
||||
export function jsonDialect(doc) {
|
||||
if (typeof doc !== 'object' || doc === null || Array.isArray(doc)) return null;
|
||||
const record = /** @type {Record<string, unknown>} */ (doc);
|
||||
if (record.format === 'bookmarkmagic') return 'json';
|
||||
const roots = record.roots;
|
||||
if (
|
||||
typeof roots === 'object' &&
|
||||
roots !== null &&
|
||||
!Array.isArray(roots) &&
|
||||
['bookmark_bar', 'other', 'synced'].some((key) => key in roots)
|
||||
) {
|
||||
return 'chrome-json';
|
||||
}
|
||||
const isPlacesRoot = record.type === 'text/x-moz-place-container' || record.root === 'placesRoot';
|
||||
if (isPlacesRoot && Array.isArray(record.children)) return 'firefox-json';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify the format, or refuse with `null`.
|
||||
*
|
||||
* The people who run this tool are, by definition, the ones whose file did not
|
||||
* import — so a malformed or hand-trimmed file is the typical input here.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {Kind | null}
|
||||
*/
|
||||
export function detectKind(text) {
|
||||
const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
||||
const trimmed = body.trimStart();
|
||||
// JSON first: a JSON title may legitimately contain the Netscape doctype
|
||||
// string, and nothing that starts with `{` is HTML or CSV.
|
||||
if (trimmed.startsWith('{')) {
|
||||
try {
|
||||
return jsonDialect(JSON.parse(trimmed));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (/NETSCAPE-Bookmark-file-1/i.test(body.slice(0, 512))) return 'html';
|
||||
const firstLine = body.split(/\r?\n/, 1)[0] ?? '';
|
||||
for (const delimiter of [',', ';']) {
|
||||
const columns = firstLine
|
||||
.split(delimiter)
|
||||
.map((h) => h.trim().replace(/^"|"$/g, '').toLowerCase());
|
||||
if (columns.length === CSV_HEADER.length && CSV_HEADER.every((c, i) => columns[i] === c)) {
|
||||
return 'csv';
|
||||
}
|
||||
}
|
||||
if (/<\s*dl[\s>]/i.test(body)) return 'html';
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* Netscape HTML: rewrite addresses, titles, descriptions and user-authored
|
||||
* attributes by span, leaving every other byte exactly as the browser wrote it.
|
||||
*/
|
||||
import { isAddressLike } from './mappers.mjs';
|
||||
import {
|
||||
ANY_ATTR,
|
||||
attrRewriter,
|
||||
attrSpans,
|
||||
replaceSpans,
|
||||
spansFrom,
|
||||
TAG_INNARDS,
|
||||
} from './spans.mjs';
|
||||
|
||||
/** @typedef {import('./spans.mjs').Span} Span */
|
||||
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
|
||||
|
||||
/** 1×1 transparent PNG. Keeps ICON= present, which is what the parser reacts to. */
|
||||
const BLANK_ICON =
|
||||
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
|
||||
|
||||
/** Attributes handled explicitly; the generic URL sweep must not touch them. */
|
||||
const HANDLED_ATTRS = new Set(['href', 'icon']);
|
||||
|
||||
/**
|
||||
* Scrub any *other* attribute whose value is an address. Firefox alone writes
|
||||
* `ICON_URI`, and `FEEDURL` and friends exist in the wild; enumerating them was
|
||||
* already wrong once, so this sweeps by value shape. `file:` counts: an
|
||||
* `ICON_URI="file:///C:/Users/<name>/…"` has no host, and used to pass.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {Mapper} mapUrl
|
||||
* @returns {Span[]}
|
||||
*/
|
||||
function urlAttrSpans(text, mapUrl) {
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
const rewrite = attrRewriter(mapUrl);
|
||||
for (const m of text.matchAll(ANY_ATTR)) {
|
||||
const name = (m[1] ?? '').toLowerCase();
|
||||
const value = m[2] ?? m[3] ?? m[4] ?? '';
|
||||
if (HANDLED_ATTRS.has(name) || value === '' || !isAddressLike(value)) continue;
|
||||
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
|
||||
if (at !== undefined) spans.push({ start: at[0], end: at[1], value: rewrite(value) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/** The next element that ends a description: `<DT>`, `<DD>`, `<DL>` or a close. */
|
||||
const DESCRIPTION_END = /<\s*(?:\/\s*)?(?:dt|dd|dl)\b/gi;
|
||||
|
||||
/**
|
||||
* `<DD>` descriptions, found in one linear pass.
|
||||
*
|
||||
* The description runs to the next `<DT>/<DD>/<DL>` (or a closing one), not to
|
||||
* the end of the line — a wrapped description used to leak its second line —
|
||||
* and trailing whitespace stays outside the span, because the newline and
|
||||
* indentation before the next tag are byte-level shape this tool keeps.
|
||||
*
|
||||
* Replaces `/<dd>([\s\S]*?)(?=\s*<…>|\s*$)/`, which backtracked polynomially
|
||||
* (SonarCloud S8786) and matched only a bare `<dd>` — `<DD class=n>Private
|
||||
* note` passed through untouched.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {() => string} next
|
||||
* @returns {Span[]}
|
||||
*/
|
||||
function descriptionSpans(text, next) {
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
for (const open of text.matchAll(/<dd\b[^>]*>/gi)) {
|
||||
const start = (open.index ?? 0) + open[0].length;
|
||||
DESCRIPTION_END.lastIndex = start;
|
||||
const close = DESCRIPTION_END.exec(text);
|
||||
let end = close === null ? text.length : close.index;
|
||||
while (end > start && /\s/.test(text.charAt(end - 1))) end--;
|
||||
if (end > start) spans.push({ start, end, value: next() });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/** A document heading that says nothing about its owner stays as it is. */
|
||||
const GENERIC_HEADING = /^\s*bookmarks(?:\s+menu)?\s*$/i;
|
||||
|
||||
/**
|
||||
* @param {string} text
|
||||
* @param {Mapper} mapUrl
|
||||
* @param {Mapper} mapTitle
|
||||
*/
|
||||
export function sanitizeHtml(text, mapUrl, mapTitle) {
|
||||
let descriptions = 0;
|
||||
let keywords = 0;
|
||||
/** @param {string} heading */
|
||||
const mapHeading = (heading) => (GENERIC_HEADING.test(heading) ? heading : mapTitle(heading));
|
||||
const spans = [
|
||||
// HREF and ICON, at any quoting — attribute name case is left as found.
|
||||
...attrSpans(text, /^href$/, attrRewriter(mapUrl)),
|
||||
...attrSpans(text, /^icon$/, () => BLANK_ICON),
|
||||
...urlAttrSpans(text, mapUrl),
|
||||
// Firefox keywords and tags are user-authored text, so they are personal
|
||||
// too. Tag count is preserved because it is the only part a parser sees.
|
||||
...attrSpans(text, /^shortcuturl$/, () => `kw${++keywords}`),
|
||||
...attrSpans(text, /^tags$/, (v) =>
|
||||
v
|
||||
.split(',')
|
||||
.map((_, i) => `tag${i + 1}`)
|
||||
.join(','),
|
||||
),
|
||||
// Bookmark and folder titles. `[\s\S]*?`, not `[^<]*`: a title holding a
|
||||
// raw `<` made the whole match fail and stay in the output.
|
||||
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([\\s\\S]*?)</a>`, 'gi'), mapTitle),
|
||||
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([\\s\\S]*?)</h3>`, 'gi'), mapTitle),
|
||||
// `<TITLE>` / `<H1>` — usually "Bookmarks", but an exporter can write the
|
||||
// owner's name there ("Jane Doe's bookmarks").
|
||||
...spansFrom(text, /<title\b[^>]*>([^<]*)<\/title>/gi, mapHeading),
|
||||
...spansFrom(text, /<h1\b[^>]*>([^<]*)<\/h1>/gi, mapHeading),
|
||||
...descriptionSpans(text, () => `Description ${++descriptions}`),
|
||||
];
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* JSON bookmark files — BookmarkMagic JSON, Chrome's profile `Bookmarks` file,
|
||||
* and Firefox's `bookmarks-YYYY-MM-DD.json` backup.
|
||||
*
|
||||
* Default-deny: every string VALUE is replaced unless its key is on the short
|
||||
* structural list below. The old rewriter was default-allow — it rewrote only
|
||||
* `"url"` and `"title"`, so Chrome's titles (under `"name"`), Firefox's `uri`,
|
||||
* `iconUri` and keywords, Chrome's `meta_info` and the base64 `sync_metadata`
|
||||
* blob all went through untouched, and the host check could not see a title.
|
||||
*
|
||||
* Values are rewritten by span over the raw text (a small tokenizer tracks
|
||||
* which key each string belongs to), so indentation, key order, escapes and
|
||||
* line endings stay byte-for-byte as the browser wrote them.
|
||||
*/
|
||||
import { isAddressLike, makeGuidMapper } from './mappers.mjs';
|
||||
import { replaceSpans } from './spans.mjs';
|
||||
|
||||
/** @typedef {import('./spans.mjs').Span} Span */
|
||||
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
|
||||
|
||||
/**
|
||||
* Keys whose string values are structure, not content, and are kept verbatim:
|
||||
* format markers, type tags, root identifiers, numeric ids and every timestamp
|
||||
* (Chrome stores dates as decimal strings). Nothing a person typed lives here.
|
||||
*/
|
||||
const STRUCTURAL = new Set([
|
||||
'format',
|
||||
'generator',
|
||||
'exportedAt',
|
||||
'version',
|
||||
'type',
|
||||
'root',
|
||||
'id',
|
||||
'date_added',
|
||||
'date_modified',
|
||||
'date_last_used',
|
||||
'charset',
|
||||
'source',
|
||||
]);
|
||||
|
||||
/** Keys whose value is an address, mapped even when it does not parse. */
|
||||
const ADDRESS = new Set(['url', 'uri', 'iconuri']);
|
||||
|
||||
/**
|
||||
* @typedef {{ kind: 'object' | 'array', key: string | null, expectKey: boolean, current: string | null }} Frame
|
||||
* @typedef {{ start: number, end: number, raw: string, key: string | null, parentKey: string | null }} StringToken
|
||||
*/
|
||||
|
||||
/**
|
||||
* Every string VALUE in a JSON text, with the key it sits under and the key of
|
||||
* the object that holds it (`annos[].value` → key "value", parentKey "annos").
|
||||
* The input has already passed `JSON.parse`, so it is well-formed.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {StringToken[]}
|
||||
*/
|
||||
export function stringValues(text) {
|
||||
/** @type {Frame[]} */
|
||||
const stack = [];
|
||||
/** @type {StringToken[]} */
|
||||
const out = [];
|
||||
// The key a new child sits under. Array elements inherit the array's key, so
|
||||
// every object inside `"annos": [...]` reports "annos" as its parent.
|
||||
const keyFor = () => {
|
||||
const top = stack.at(-1);
|
||||
return (top?.kind === 'object' ? top.current : top?.key) ?? null;
|
||||
};
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const ch = text[i];
|
||||
if (ch === '"') {
|
||||
i = readString(text, i, stack, out, keyFor);
|
||||
continue;
|
||||
}
|
||||
if (ch === '{' || ch === '[') {
|
||||
stack.push({
|
||||
kind: ch === '{' ? 'object' : 'array',
|
||||
key: keyFor(),
|
||||
expectKey: ch === '{',
|
||||
current: null,
|
||||
});
|
||||
} else if (ch === '}' || ch === ']') {
|
||||
stack.pop();
|
||||
} else if (ch === ',') {
|
||||
const top = stack.at(-1);
|
||||
if (top?.kind === 'object') top.expectKey = true;
|
||||
} else if (ch === ':') {
|
||||
const top = stack.at(-1);
|
||||
if (top !== undefined) top.expectKey = false;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* One string token starting at the quote at `start`: a key updates its object
|
||||
* frame, a value is recorded. Returns the index just past the closing quote.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {number} start
|
||||
* @param {Frame[]} stack
|
||||
* @param {StringToken[]} out
|
||||
* @param {() => string | null} keyFor
|
||||
*/
|
||||
function readString(text, start, stack, out, keyFor) {
|
||||
let end = start + 1;
|
||||
while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
|
||||
const raw = text.slice(start + 1, end);
|
||||
const top = stack.at(-1);
|
||||
if (top?.kind === 'object' && top.expectKey) {
|
||||
top.current = JSON.parse(`"${raw}"`);
|
||||
} else {
|
||||
const holder = top?.kind === 'object' ? top : stack.at(-2);
|
||||
out.push({ start: start + 1, end, raw, key: keyFor(), parentKey: holder?.key ?? null });
|
||||
}
|
||||
return end + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} text
|
||||
* @param {Mapper} mapUrl
|
||||
* @param {Mapper} mapTitle
|
||||
*/
|
||||
export function sanitizeJson(text, mapUrl, mapTitle) {
|
||||
const mapGuid = makeGuidMapper();
|
||||
let keywords = 0;
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
for (const token of stringValues(text)) {
|
||||
const key = token.key ?? '';
|
||||
const lower = key.toLowerCase();
|
||||
if (STRUCTURAL.has(key)) continue;
|
||||
// An anno's `name` is a schema id (bookmarkProperties/description); its
|
||||
// `value` is what the person wrote.
|
||||
if (token.parentKey === 'annos' && key === 'name') continue;
|
||||
|
||||
const value = /** @type {string} */ (JSON.parse(`"${token.raw}"`));
|
||||
let mapped;
|
||||
if (lower === 'guid') mapped = mapGuid(value);
|
||||
else if (lower === 'checksum' || lower === 'checksum_sha256') mapped = '0'.repeat(value.length);
|
||||
else if (lower === 'sync_metadata') mapped = '';
|
||||
else if (lower === 'keyword') mapped = value === '' ? '' : `kw${++keywords}`;
|
||||
else if (lower === 'tags')
|
||||
mapped =
|
||||
value === ''
|
||||
? ''
|
||||
: value
|
||||
.split(',')
|
||||
.map((_, i) => `tag${i + 1}`)
|
||||
.join(',');
|
||||
else if (ADDRESS.has(lower) || isAddressLike(value)) mapped = mapUrl(value);
|
||||
else mapped = mapTitle(value);
|
||||
|
||||
spans.push({ start: token.start, end: token.end, value: JSON.stringify(mapped).slice(1, -1) });
|
||||
}
|
||||
return replaceSpans(text, spans);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* The backstop: check the OUTPUT, not the rules that produced it.
|
||||
*
|
||||
* The rewriting rules are patterns over untrusted markup, so each one has a
|
||||
* shape it does not match — a single-quoted attribute, a title containing `<`,
|
||||
* a JSON key nobody enumerated, a `<DD class=…>`. Every one of those is a silent
|
||||
* leak, and nobody can honestly claim to have thought of every shape. So the
|
||||
* output is inspected independently, and anything that still looks personal
|
||||
* makes the tool refuse instead of handing the file over. A rule this misses
|
||||
* degrades into a refusal — annoying — instead of a published browsing history.
|
||||
*/
|
||||
import { TAG_INNARDS } from './spans.mjs';
|
||||
|
||||
/**
|
||||
* Hosts in the output that are not one of our own `*.example` aliases.
|
||||
*
|
||||
* @param {string} text sanitized output
|
||||
* @returns {string[]} distinct suspicious hosts, empty when clean
|
||||
*/
|
||||
export function findLeakedHosts(text) {
|
||||
const leaked = new Set();
|
||||
for (const m of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/([^\s"'<>)\]}\\]+)/gi)) {
|
||||
const authority = (m[1] ?? '').split(/[/?#]/, 1)[0] ?? '';
|
||||
// Strip credentials and port; what remains is the host.
|
||||
const host = authority.split('@').pop()?.replace(/:\d+$/, '').toLowerCase() ?? '';
|
||||
if (host === '' || /^[a-z]\d*\.example$/.test(host)) continue;
|
||||
leaked.add(host);
|
||||
}
|
||||
return [...leaked];
|
||||
}
|
||||
|
||||
/**
|
||||
* Words the sanitized TEXT of a Netscape file may legitimately contain: our
|
||||
* placeholders, the default heading, and the script samples the title mapper
|
||||
* adds so an encoding bug still reproduces.
|
||||
*/
|
||||
const ALLOWED_WORDS = new Set(['title', 'description', 'bookmarks', 'bookmark', 'menu', 'شيء']);
|
||||
|
||||
/**
|
||||
* Words in the document's text content — everything outside tags and comments —
|
||||
* that are not placeholders.
|
||||
*
|
||||
* Independent of the rewriting rules on purpose: it does not look for `<A>` or
|
||||
* `<H3>` at all, it strips markup and reads whatever text is left. The old
|
||||
* backstop matched only `scheme://host`, so an unsanitized title, a `<DD>` note
|
||||
* or an `<H1>Jane Doe's bookmarks</H1>` passed it, and the test that guarded it
|
||||
* reused the same pattern and could never notice.
|
||||
*
|
||||
* @param {string} html sanitized Netscape output
|
||||
* @returns {string[]} distinct offending words, empty when clean
|
||||
*/
|
||||
export function findLeakedWords(html) {
|
||||
const text = html
|
||||
.replace(/<!--[\s\S]*?-->/g, ' ')
|
||||
// Script and style bodies are code. A browser export never contains them;
|
||||
// the T1 injection fixtures do, and their payload is the point of the file.
|
||||
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, ' ')
|
||||
.replace(new RegExp(`<${TAG_INNARDS}>`, 'g'), ' ')
|
||||
.replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, ' ');
|
||||
const leaked = new Set();
|
||||
for (const [word] of text.matchAll(/\p{L}{3,}/gu)) {
|
||||
if (!ALLOWED_WORDS.has(word.toLowerCase())) leaked.add(word);
|
||||
}
|
||||
return [...leaked];
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* Value mappers: deterministic placeholders that keep what parsers branch on.
|
||||
*
|
||||
* Replacements are stable per distinct input value, so "how many distinct
|
||||
* hosts" and "which two bookmarks are duplicates" survive sanitizing.
|
||||
*/
|
||||
|
||||
/** @typedef {(raw: string) => string} Mapper */
|
||||
|
||||
/**
|
||||
* Replace addresses while preserving everything a parser branches on: the
|
||||
* scheme, whether there is a port, how deep the path is, whether it ends in a
|
||||
* slash, how many query parameters there are and in what order, and whether
|
||||
* there is a fragment. Percent-escapes are carried across literally, so a
|
||||
* decoding bug still reproduces.
|
||||
*
|
||||
* @returns {Mapper}
|
||||
*/
|
||||
export function makeUrlMapper() {
|
||||
/** @type {Map<string, string>} */
|
||||
const seen = new Map();
|
||||
/** @type {Map<string, string>} */
|
||||
const hosts = new Map();
|
||||
|
||||
/** @param {string} host */
|
||||
const hostAlias = (host) => {
|
||||
let alias = hosts.get(host);
|
||||
if (alias === undefined) {
|
||||
const n = hosts.size;
|
||||
// a.example … z.example, then a1.example, a2.example …
|
||||
const letter = String.fromCharCode(97 + (n % 26));
|
||||
const round = Math.floor(n / 26);
|
||||
alias = round === 0 ? `${letter}.example` : `${letter}${round}.example`;
|
||||
hosts.set(host, alias);
|
||||
}
|
||||
return alias;
|
||||
};
|
||||
|
||||
/** @param {string} segment */
|
||||
const escapesIn = (segment) => (segment.match(/%[0-9a-fA-F]{2}/g) ?? []).join('');
|
||||
|
||||
/** @param {string} pathname */
|
||||
const mapPath = (pathname) => {
|
||||
if (pathname === '' || pathname === '/') return pathname;
|
||||
const trailing = pathname.endsWith('/');
|
||||
const parts = pathname.replace(/^\//, '').replace(/\/$/, '').split('/');
|
||||
const mapped = parts.map((p, i) => (p === '' ? '' : `p${i + 1}${escapesIn(p)}`));
|
||||
return `/${mapped.join('/')}${trailing ? '/' : ''}`;
|
||||
};
|
||||
|
||||
/** @param {string} search */
|
||||
const mapQuery = (search) => {
|
||||
if (search === '') return '';
|
||||
return `?${search
|
||||
.slice(1)
|
||||
.split('&')
|
||||
.map((pair, i) => (pair.includes('=') ? `q${i + 1}=v${i + 1}` : `q${i + 1}`))
|
||||
.join('&')}`;
|
||||
};
|
||||
|
||||
return (raw) => {
|
||||
if (raw === '') return raw;
|
||||
const cached = seen.get(raw);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
let out;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
url = undefined;
|
||||
}
|
||||
|
||||
if (url === undefined) {
|
||||
// Keep it unparseable, and keep distinct values distinct — the dedupe
|
||||
// path treats an unparseable URL as its own trimmed self.
|
||||
out = `not-a-url-${seen.size + 1}`;
|
||||
} else if (url.host === '') {
|
||||
// Opaque or hostless scheme (javascript:, data:, mailto:, file:, place:).
|
||||
// The scheme is the whole point for the T1/T3 threat cases; the payload —
|
||||
// which for file: is a local path with a user name in it — is not ours.
|
||||
out = `${url.protocol}sanitized-${seen.size + 1}`;
|
||||
} else {
|
||||
// Credentials are never round-tripped, not even as placeholders.
|
||||
const port = url.port === '' ? '' : `:${url.port}`;
|
||||
const hash = url.hash === '' ? '' : '#frag';
|
||||
out = `${url.protocol}//${hostAlias(url.host.replace(/:\d+$/, ''))}${port}${mapPath(url.pathname)}${mapQuery(url.search)}${hash}`;
|
||||
}
|
||||
|
||||
seen.set(raw, out);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace titles while preserving what encoding bugs live in: emptiness, the
|
||||
* scripts present (so a CJK or RTL or emoji bug still reproduces), and any HTML
|
||||
* entity references, which are carried across verbatim.
|
||||
*
|
||||
* @returns {Mapper}
|
||||
*/
|
||||
export function makeTitleMapper() {
|
||||
/** @type {Map<string, string>} */
|
||||
const seen = new Map();
|
||||
/** @type {[RegExp, string][]} */
|
||||
const SCRIPTS = [
|
||||
[/[一-鿿-ヿ]/, '文字'],
|
||||
[/[-ࣿ]/, 'شيء'],
|
||||
[/[\p{Extended_Pictographic}]/u, '🌸'],
|
||||
];
|
||||
|
||||
return (raw) => {
|
||||
if (raw.trim() === '') return raw;
|
||||
const cached = seen.get(raw);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const entities = (raw.match(/&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z]+);/g) ?? []).join('');
|
||||
const extras = SCRIPTS.filter(([re]) => re.test(raw))
|
||||
.map(([, sample]) => sample)
|
||||
.join('');
|
||||
const out = `Title ${seen.size + 1}${extras === '' ? '' : ` ${extras}`}${entities}`;
|
||||
seen.set(raw, out);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
/** Firefox's fixed root GUIDs — structural, and the parser keys off them. */
|
||||
const RESERVED_GUID = /^(?:root|menu|toolbar|unfiled|mobile|tags)_+$/;
|
||||
|
||||
/**
|
||||
* Replace bookmark GUIDs with stable fakes of the same shape. They are random,
|
||||
* but they are also the identifier sync uses, so they could tie a public sample
|
||||
* to an account; the root GUIDs are kept because they carry meaning.
|
||||
*
|
||||
* @returns {Mapper}
|
||||
*/
|
||||
export function makeGuidMapper() {
|
||||
/** @type {Map<string, string>} */
|
||||
const seen = new Map();
|
||||
return (raw) => {
|
||||
if (raw === '' || RESERVED_GUID.test(raw)) return raw;
|
||||
const cached = seen.get(raw);
|
||||
if (cached !== undefined) return cached;
|
||||
const n = String(seen.size + 1);
|
||||
const out = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)
|
||||
? `00000000-0000-4000-8000-${n.padStart(12, '0')}`
|
||||
: `g${n.padStart(Math.max(raw.length - 1, n.length), '0')}`;
|
||||
seen.set(raw, out);
|
||||
return out;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a value is a URL whose payload could identify someone: it has a
|
||||
* host, or it is a `file:` path (`file:///C:/Users/<name>/…` has no host).
|
||||
*
|
||||
* @param {string} value
|
||||
*/
|
||||
export function isAddressLike(value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.host !== '' || url.protocol === 'file:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// @ts-check
|
||||
/**
|
||||
* Span rewriting: every change is a [start, end) → value replacement, so the
|
||||
* bytes between spans are provably untouched. Rebuilding the file from a parsed
|
||||
* model would quietly normalize them, and the byte-level shape is often the bug.
|
||||
*/
|
||||
|
||||
/** @typedef {{ start: number, end: number, value: string }} Span */
|
||||
|
||||
/**
|
||||
* Apply replacements right to left by character span.
|
||||
*
|
||||
* Overlaps are dropped, outermost first. Two patterns can legitimately claim
|
||||
* the same bytes — an <A> title containing `x="http://…"` matches both the
|
||||
* title rule and the generic attribute sweep — and applying both would splice
|
||||
* already-rewritten text using an `end` measured against the original. The
|
||||
* widest span sanitizes the most.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {Span[]} spans
|
||||
*/
|
||||
export function replaceSpans(text, spans) {
|
||||
const ordered = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
|
||||
const out = [];
|
||||
let cursor = 0;
|
||||
for (const span of ordered) {
|
||||
if (span.start < cursor) continue;
|
||||
out.push(text.slice(cursor, span.start), span.value);
|
||||
cursor = span.end;
|
||||
}
|
||||
out.push(text.slice(cursor));
|
||||
// Joined once rather than spliced per span: splicing is O(spans × file),
|
||||
// which took minutes on a large export.
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Spans for one capture group of a global regex; `map` receives the captured
|
||||
* text. The `d` flag gives exact per-group offsets — searching the match for
|
||||
* the captured substring lands on the wrong copy whenever the capture also
|
||||
* appears earlier in the match (a title equal to part of its own URL).
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {RegExp} re
|
||||
* @param {(captured: string) => string} map
|
||||
* @param {number} [group]
|
||||
* @returns {Span[]}
|
||||
*/
|
||||
export function spansFrom(text, re, map, group = 1) {
|
||||
const indexed = new RegExp(re.source, re.flags.includes('d') ? re.flags : `${re.flags}d`);
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
for (const m of text.matchAll(indexed)) {
|
||||
const captured = m[group] ?? '';
|
||||
const at = m.indices?.[group];
|
||||
if (captured === '' || at === undefined) continue;
|
||||
spans.push({ start: at[0], end: at[1], value: map(captured) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
/**
|
||||
* The inside of an opening tag, tolerating `>` within quoted attribute values.
|
||||
* `data:text/html,<h1>hi</h1>` is a legal HREF in the T1/T3 fixtures, and a
|
||||
* naive `[^>]*` stopped inside it, leaving that bookmark's title unsanitized.
|
||||
*/
|
||||
export const TAG_INNARDS = '(?:"[^"]*"|\'[^\']*\'|[^>"\'])*';
|
||||
|
||||
/** The four entities Netscape exporters write inside attribute values. */
|
||||
const ATTR_ENTITY = /&(amp|lt|gt|quot);/gi;
|
||||
/** @type {Record<string, string>} */
|
||||
const ATTR_DECODE = { amp: '&', lt: '<', gt: '>', quot: '"' };
|
||||
|
||||
/**
|
||||
* Decode an HTML attribute value, map it, then re-encode it the way the source
|
||||
* file encoded it.
|
||||
*
|
||||
* Decoding is ONE pass. Chained `.replace()` calls (`&` first, then `<`)
|
||||
* turned `&lt;` into `<` — a double unescape (CodeQL js/double-escaping).
|
||||
* Netscape exports write `&` inside HREF but not all of them do, and
|
||||
* emitting a bare `&` where the source had `&` would silently repair the
|
||||
* file being reported.
|
||||
*
|
||||
* @param {(value: string) => string} map
|
||||
* @returns {(captured: string) => string}
|
||||
*/
|
||||
export function attrRewriter(map) {
|
||||
return (captured) => {
|
||||
const decoded = captured.replace(
|
||||
ATTR_ENTITY,
|
||||
(_m, name) => ATTR_DECODE[name.toLowerCase()] ?? _m,
|
||||
);
|
||||
const mapped = map(decoded);
|
||||
const escapesAmp = /&/i.test(captured) || !captured.includes('&');
|
||||
return escapesAmp ? mapped.replace(/&/g, '&') : mapped;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `name = value`, where the value is double-quoted, single-quoted or bare.
|
||||
* Group 2/3/4 is the value, whichever quoting was used — matching only `"…"`
|
||||
* left `HREF='https://…'` completely untouched.
|
||||
*/
|
||||
export const ANY_ATTR = /\b([a-z_][a-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+))/dgi;
|
||||
|
||||
/**
|
||||
* Spans for every attribute whose (lower-cased) name matches, at any quoting.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {RegExp} nameRe
|
||||
* @param {(value: string) => string} map
|
||||
* @returns {Span[]}
|
||||
*/
|
||||
export function attrSpans(text, nameRe, map) {
|
||||
/** @type {Span[]} */
|
||||
const spans = [];
|
||||
for (const m of text.matchAll(ANY_ATTR)) {
|
||||
if (!nameRe.test((m[1] ?? '').toLowerCase())) continue;
|
||||
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
|
||||
const value = m[2] ?? m[3] ?? m[4] ?? '';
|
||||
if (at === undefined || value === '') continue;
|
||||
spans.push({ start: at[0], end: at[1], value: map(value) });
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
# SonarCloud — CI-based analysis (docs/12 §2.5). Read by
|
||||
# .github/workflows/sonarcloud.yml; Automatic Analysis must stay OFF in the
|
||||
# SonarCloud project (Administration → Analysis Method), or the scan errors out.
|
||||
sonar.projectKey=poli0981_bookmarkmagic
|
||||
sonar.organization=poli0981
|
||||
sonar.projectName=BookmarkMagic
|
||||
sonar.sourceEncoding=UTF-8
|
||||
|
||||
# What ships, plus the repo tooling that guards it.
|
||||
sonar.sources=src,scripts
|
||||
# Icons and the _locales message catalogues are data, not code.
|
||||
sonar.exclusions=src/public/**
|
||||
|
||||
sonar.tests=tests
|
||||
sonar.test.inclusions=tests/**/*.ts
|
||||
# Fixtures are byte-exact samples of what browsers emit — malformed on purpose
|
||||
# (a no-doctype HTML file is a test case, not a bug), never something to "fix".
|
||||
sonar.test.exclusions=tests/fixtures/**
|
||||
|
||||
# Coverage scope mirrors docs/11 §1: components, entrypoints and repo scripts
|
||||
# are verified by the manual QA pass and their own script tests, not by line
|
||||
# coverage. Everything else in src/ is unit-tested and counted.
|
||||
sonar.javascript.lcov.reportPaths=coverage/lcov.info
|
||||
sonar.coverage.exclusions=src/entrypoints/**,src/lib/components/**,**/*.svelte,scripts/**
|
||||
|
||||
# The three locale dictionaries are parallel by design (en is the schema, vi/ja
|
||||
# `satisfies Dict`); their "duplication" is the i18n contract working.
|
||||
sonar.cpd.exclusions=src/lib/i18n/locales/**
|
||||
@@ -77,6 +77,20 @@ function writeFlat(roots: readonly BookmarkNode[], out: string[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop trailing line feeds in one backward pass.
|
||||
*
|
||||
* Replaces `.replace(/\n+$/, '')`, which backtracks: for every newline in a
|
||||
* long run that is NOT at the end (a title holding thousands of them, say), the
|
||||
* engine re-scans the rest of the run before failing at `$` — quadratic in the
|
||||
* run length (SonarCloud S8786).
|
||||
*/
|
||||
function trimTrailingNewlines(text: string): string {
|
||||
let end = text.length;
|
||||
while (end > 0 && text.charCodeAt(end - 1) === 0x0a) end--;
|
||||
return text.slice(0, end);
|
||||
}
|
||||
|
||||
/** Serialize a tree to Markdown. */
|
||||
export function serializeMarkdown(
|
||||
roots: readonly BookmarkNode[],
|
||||
@@ -85,5 +99,5 @@ export function serializeMarkdown(
|
||||
const out: string[] = [`# Bookmarks — ${options.date}`, ''];
|
||||
if ((options.style ?? 'nested') === 'flat') writeFlat(roots, out);
|
||||
else writeNested(roots, 0, out);
|
||||
return `${out.join('\n').replace(/\n+$/, '')}\n`;
|
||||
return `${trimTrailingNewlines(out.join('\n'))}\n`;
|
||||
}
|
||||
@@ -9,8 +9,9 @@ import type { Locale } from './resolve-locale';
|
||||
*
|
||||
* chrome.i18n always follows the browser UI language and cannot be switched at
|
||||
* runtime, so every in-app string resolves through this store instead. The
|
||||
* dictionaries are static imports, not fetched — `fetch` is banned repo-wide
|
||||
* (docs/08 §3), and bundling three small dicts costs nothing at our size.
|
||||
* dictionaries are static imports, never loaded over the network — network
|
||||
* calls are banned repo-wide (docs/08 §3), and bundling three small dicts costs
|
||||
* nothing at our size.
|
||||
*/
|
||||
const dicts = { en, vi, ja };
|
||||
|
||||
|
||||
@@ -82,4 +82,21 @@ describe('markdown escaping', () => {
|
||||
});
|
||||
expect(md).toContain('- [\\[x\\]\\(y\\)](<https://a.example/(z)>)');
|
||||
});
|
||||
|
||||
it('ends with exactly one newline, however the tree ends', () => {
|
||||
for (const style of ['nested', 'flat'] as const) {
|
||||
expect(serializeMarkdown([], { date: 'd', style })).toBe('# Bookmarks — d\n');
|
||||
const md = serializeMarkdown([{ title: 'Empty', children: [] }], { date: 'd', style });
|
||||
expect(md.endsWith('\n')).toBe(true);
|
||||
expect(md.endsWith('\n\n')).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a long newline run that is not at the end (no backtracking trim)', () => {
|
||||
// The old `/\n+$/` re-scanned this run once per newline before failing.
|
||||
const run = '\n'.repeat(20_000);
|
||||
const md = serializeMarkdown([{ title: `a${run}b`, children: [] }], { date: 'd' });
|
||||
expect(md).toContain(`- **a${run}b**`);
|
||||
expect(md.endsWith('**\n')).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -28,7 +28,6 @@ const FORBIDDEN_KEYS = [
|
||||
'content_scripts',
|
||||
'web_accessible_resources',
|
||||
'externally_connectable',
|
||||
'content_security_policy',
|
||||
'declarative_net_request',
|
||||
'devtools_page',
|
||||
'chrome_url_overrides',
|
||||
@@ -72,6 +71,51 @@ describe('manifest', () => {
|
||||
expect(CONFIG).not.toMatch(/\bbackground\s*:/);
|
||||
});
|
||||
|
||||
it('states one runtime floor: Chrome 136, the first with every ES2025 built-in', () => {
|
||||
// The manifest floor, Vite's transpile target and tsconfig's lib must agree.
|
||||
// A lib newer than the floor lets the compiler accept APIs (RegExp.escape,
|
||||
// Float16Array) that throw on the oldest Chrome still allowed to install.
|
||||
expect(CONFIG).toMatch(/const CHROME_FLOOR = 136;/);
|
||||
expect(CONFIG).toMatch(/minimum_chrome_version:\s*String\(CHROME_FLOOR\)/);
|
||||
expect(CONFIG).toMatch(/target:\s*`chrome\$\{CHROME_FLOOR\}`/);
|
||||
// SAFETY: tsconfig.json is a committed file with exactly this shape; a
|
||||
// missing key fails the expectations below rather than passing silently.
|
||||
const tsconfig = JSON.parse(readFileSync(join(process.cwd(), 'tsconfig.json'), 'utf8')) as {
|
||||
compilerOptions: { target: string; lib: string[] };
|
||||
};
|
||||
expect(tsconfig.compilerOptions.target).toBe('ES2025');
|
||||
expect(tsconfig.compilerOptions.lib).toEqual(['ES2025', 'DOM', 'DOM.Iterable']);
|
||||
});
|
||||
|
||||
it('declares the extension-page CSP once, production-only, and only ever stricter', () => {
|
||||
// docs/08 §3: the CSP is what makes the zero-network promise browser-
|
||||
// enforced. check-manifest.mjs pins the exact built string; this pins the
|
||||
// shape of the config that produces it.
|
||||
expect(CONFIG.match(/content_security_policy/g)?.length ?? 0).toBe(1);
|
||||
expect(CONFIG).toMatch(/command === 'build' && \{\s*content_security_policy:/);
|
||||
// From the comment-stripped config: the explanatory comments beside the
|
||||
// directives mention default-src on purpose.
|
||||
const csp = CONFIG.slice(
|
||||
CONFIG.indexOf('const EXTENSION_PAGE_CSP'),
|
||||
CONFIG.indexOf("].join('; ')"),
|
||||
);
|
||||
for (const directive of [
|
||||
"script-src 'self'",
|
||||
"object-src 'none'",
|
||||
"connect-src 'none'",
|
||||
"img-src 'self' data: blob:",
|
||||
"form-action 'none'",
|
||||
]) {
|
||||
expect(csp).toContain(`"${directive}"`);
|
||||
}
|
||||
// Loosening is what MV3 forbids and what this test exists to stop. The one
|
||||
// 'unsafe-inline' allowed is for STYLE (Svelte sets style attributes) —
|
||||
// never for script.
|
||||
expect(csp).toContain(`"style-src 'self' 'unsafe-inline'"`);
|
||||
const withoutInlineStyle = csp.replace(`"style-src 'self' 'unsafe-inline'"`, '');
|
||||
expect(withoutInlineStyle).not.toMatch(/unsafe-|https?:|\*|default-src/);
|
||||
});
|
||||
|
||||
it('keeps the manifest at v3 by not overriding WXT’s default', () => {
|
||||
// WXT emits manifest_version 3 for the chrome-mv3 target. An explicit
|
||||
// downgrade here would be the only way to lose it.
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// @vitest-environment node
|
||||
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 { afterEach, describe, expect, it } from 'vitest';
|
||||
import { checkExtension } from '../../../scripts/check-manifest.mjs';
|
||||
|
||||
/**
|
||||
* scripts/check-manifest.mjs gates the BUILT extension (docs/08 §2–§3). It ran
|
||||
* in CI and on every tag with no test of its own. These build a fake
|
||||
* `.output/chrome-mv3` tree per case and call the script's `checkExtension`
|
||||
* on it — the CLI itself takes no path argument (SonarCloud S8707).
|
||||
*/
|
||||
|
||||
const SCRIPT = join(process.cwd(), 'scripts', 'check-manifest.mjs');
|
||||
const CSP =
|
||||
"script-src 'self'; object-src 'none'; connect-src 'none'; img-src 'self' data: blob:; " +
|
||||
"style-src 'self' 'unsafe-inline'; font-src 'self'; media-src 'none'; frame-src 'none'; " +
|
||||
"worker-src 'self'; form-action 'none'; base-uri 'none'";
|
||||
|
||||
const MANIFEST = {
|
||||
manifest_version: 3,
|
||||
name: '__MSG_appName__',
|
||||
description: '__MSG_appDesc__',
|
||||
version: '1.1.0',
|
||||
icons: { 16: '/icon/16.png', 32: '/icon/32.png', 48: '/icon/48.png', 128: '/icon/128.png' },
|
||||
default_locale: 'en',
|
||||
minimum_chrome_version: '136',
|
||||
permissions: ['bookmarks', 'storage'],
|
||||
options_ui: { page: 'manager.html#settings', open_in_tab: true },
|
||||
homepage_url: 'https://github.com/poli0981/bookmarkmagic',
|
||||
content_security_policy: { extension_pages: CSP },
|
||||
action: { default_title: 'BookmarkMagic', default_popup: 'popup.html' },
|
||||
};
|
||||
|
||||
const FILES: Record<string, string> = {
|
||||
'manager.html': '<!doctype html>',
|
||||
'popup.html': '<!doctype html>',
|
||||
'_locales/en/messages.json': '{}',
|
||||
'_locales/vi/messages.json': '{}',
|
||||
'_locales/ja/messages.json': '{}',
|
||||
'icon/16.png': 'x',
|
||||
'icon/32.png': 'x',
|
||||
'icon/48.png': 'x',
|
||||
'icon/128.png': 'x',
|
||||
'chunks/manager.js': 'const a=document.createElement("div");a.textContent="ok";',
|
||||
};
|
||||
|
||||
const dirs: string[] = [];
|
||||
|
||||
function build(manifest: unknown, overrides: Record<string, string | null> = {}): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'check-manifest-'));
|
||||
dirs.push(dir);
|
||||
const files = { ...FILES, 'manifest.json': JSON.stringify(manifest), ...overrides };
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
if (content === null) continue;
|
||||
mkdirSync(dirname(join(dir, rel)), { recursive: true });
|
||||
writeFileSync(join(dir, rel), content);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
function check(dir: string): { status: number; output: string } {
|
||||
const { problems, readError } = checkExtension(dir);
|
||||
const failed = readError !== undefined || problems.length > 0;
|
||||
return { status: failed ? 1 : 0, output: [readError ?? '', ...problems].join('\n') };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('check-manifest.mjs', () => {
|
||||
it('passes a correct build', () => {
|
||||
const { status, output } = check(build(MANIFEST));
|
||||
expect(status, output).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an extra permission', { permissions: ['bookmarks', 'storage', 'tabs'] }, 'permissions are'],
|
||||
['a missing permission', { permissions: ['bookmarks'] }, 'permissions are'],
|
||||
['host_permissions', { host_permissions: ['<all_urls>'] }, 'declares "host_permissions"'],
|
||||
['a background worker', { background: { service_worker: 'bg.js' } }, 'declares "background"'],
|
||||
[
|
||||
'an unexpected key',
|
||||
{ side_panel: { default_path: 'x.html' } },
|
||||
'unexpected top-level key(s): side_panel',
|
||||
],
|
||||
['MV2', { manifest_version: 2 }, 'manifest_version is 2'],
|
||||
['the old Chrome floor', { minimum_chrome_version: '120' }, 'minimum_chrome_version is "120"'],
|
||||
[
|
||||
'a loosened CSP',
|
||||
{
|
||||
content_security_policy: {
|
||||
extension_pages: "script-src 'self' 'unsafe-eval'; object-src 'self'",
|
||||
},
|
||||
},
|
||||
'content_security_policy is',
|
||||
],
|
||||
[
|
||||
'a CSP with an extra key',
|
||||
{ content_security_policy: { extension_pages: CSP, sandbox: 'sandbox allow-scripts' } },
|
||||
'content_security_policy is',
|
||||
],
|
||||
])('fails on %s', (_label, change, message) => {
|
||||
const { status, output } = check(build({ ...MANIFEST, ...change }));
|
||||
expect(status, output).toBe(1);
|
||||
expect(output).toContain(message);
|
||||
});
|
||||
|
||||
it('fails when the CSP is missing (a dev build, or a config edit)', () => {
|
||||
const { content_security_policy: _dropped, ...noCsp } = MANIFEST;
|
||||
const { status, output } = check(build(noCsp));
|
||||
expect(status).toBe(1);
|
||||
expect(output).toContain('missing expected top-level key(s): content_security_policy');
|
||||
});
|
||||
|
||||
it.each(['_locales/vi/messages.json', 'icon/128.png', 'popup.html'])(
|
||||
'fails when %s is missing from the build',
|
||||
(file) => {
|
||||
const { status, output } = check(build(MANIFEST, { [file]: null }));
|
||||
expect(status).toBe(1);
|
||||
expect(output).toContain(
|
||||
`missing file in the build: ${file.startsWith('icon') ? `/${file}` : file}`,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['fetch', 'chunks/x.js', 'fetch("https://x.example")'],
|
||||
['XMLHttpRequest', 'chunks/x.js', 'new XMLHttpRequest'],
|
||||
['sendBeacon', 'assets/deep/y.js', 'navigator.sendBeacon(u)'],
|
||||
])('fails on %s anywhere in the shipped JavaScript', (api, file, code) => {
|
||||
const { status, output } = check(build(MANIFEST, { [file]: code }));
|
||||
expect(status).toBe(1);
|
||||
expect(output).toContain(`network API "${api}`);
|
||||
});
|
||||
|
||||
it('fails clearly when there is no build at all', () => {
|
||||
const empty = mkdtempSync(join(tmpdir(), 'check-manifest-empty-'));
|
||||
dirs.push(empty);
|
||||
const { status, output } = check(empty);
|
||||
expect(status).toBe(1);
|
||||
expect(output).toContain('cannot read manifest.json');
|
||||
});
|
||||
|
||||
it('runs as a CLI with no arguments, against the repository build', () => {
|
||||
// Whatever state .output/ is in, the CLI must exit cleanly or explain why —
|
||||
// never crash, and never read a path it was handed.
|
||||
const result = spawnSync(process.execPath, [SCRIPT, '/etc'], { encoding: 'utf8' });
|
||||
const output = `${result.stdout}${result.stderr}`;
|
||||
expect([0, 1]).toContain(result.status);
|
||||
expect(output).toMatch(/check-manifest: (clean|cannot read|.*permissions)/);
|
||||
expect(output).not.toContain('/etc');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
// @vitest-environment node
|
||||
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 { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* scripts/guard.mjs is the zero-network / no-raw-HTML gate (docs/08 §3). Until
|
||||
* v1.1.0 nothing tested it: an audit ran its exact patterns against 28 bypasses
|
||||
* and every one got through, and a checkout path with a space or a diacritic
|
||||
* made it scan nothing and print "clean".
|
||||
*
|
||||
* Each case writes a throwaway src/ tree and runs the real script on it.
|
||||
*/
|
||||
|
||||
const GUARD = join(process.cwd(), 'scripts', 'guard.mjs');
|
||||
const roots: string[] = [];
|
||||
|
||||
function makeRoot(files: Record<string, string>, dirName = 'guard-'): string {
|
||||
const root = mkdtempSync(join(tmpdir(), dirName));
|
||||
roots.push(root);
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
const path = join(root, rel);
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, content);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
function runGuard(root: string): { status: number | null; output: string } {
|
||||
const result = spawnSync(process.execPath, [GUARD, '--root', root], { encoding: 'utf8' });
|
||||
return { status: result.status, output: `${result.stdout}${result.stderr}` };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** [what it is, file name, content, rule name the output must mention]. */
|
||||
const BANNED: readonly (readonly [string, string, string, string])[] = [
|
||||
['a direct call', 'a.ts', 'fetch(u);', 'fetch'],
|
||||
['an alias', 'a.ts', 'const go = fetch;\ngo(u);', 'fetch'],
|
||||
['a tagged template', 'a.ts', 'fetch`https://x.example/`;', 'fetch'],
|
||||
['.call()', 'a.ts', 'fetch.call(null, u);', 'fetch'],
|
||||
['a call split over two lines', 'a.ts', 'fetch\n (u);', 'fetch'],
|
||||
['XMLHttpRequest', 'a.ts', 'new XMLHttpRequest();', 'XMLHttpRequest'],
|
||||
['WebSocket', 'a.ts', "new WebSocket('wss://x.example');", 'WebSocket'],
|
||||
['WebTransport', 'a.ts', 'new WebTransport(u);', 'WebTransport'],
|
||||
['EventSource', 'a.ts', 'new EventSource(u);', 'EventSource'],
|
||||
['sendBeacon', 'a.ts', 'navigator.sendBeacon(u, d);', 'sendBeacon'],
|
||||
['RTCPeerConnection', 'a.ts', 'new RTCPeerConnection({ iceServers: [] });', 'RTCPeerConnection'],
|
||||
['importScripts', 'a.ts', "importScripts('x.js');", 'importScripts'],
|
||||
['computed globalThis access', 'a.ts', "globalThis['fe' + 'tch'](u);", 'computed global access'],
|
||||
[
|
||||
'computed navigator access',
|
||||
'a.ts',
|
||||
"navigator['send' + 'Beacon'](u);",
|
||||
'computed global access',
|
||||
],
|
||||
[
|
||||
'computed window access',
|
||||
'a.ts',
|
||||
"new (window['XMLHttp' + 'Request'])();",
|
||||
'computed global access',
|
||||
],
|
||||
['a prefetch hint in markup', 'a.svelte', '<link rel="prefetch" href="/x">', 'resource hint'],
|
||||
['a prefetch hint in code', 'a.ts', "link.rel = 'prefetch';", 'resource hint'],
|
||||
['a preload rel', 'a.ts', "link.rel = 'preload';", 'resource hint'],
|
||||
['a dns-prefetch hint', 'a.html', '<link rel="dns-prefetch" href="/x">', 'resource hint'],
|
||||
['a remote <img>', 'a.svelte', '<img src="https://x.example/a.png" alt="">', 'remote resource'],
|
||||
[
|
||||
'a remote <img> padded inside its quotes',
|
||||
'a.svelte',
|
||||
'<img src=" https://x.example/a.png">',
|
||||
'remote resource',
|
||||
],
|
||||
['a protocol-relative <script>', 'a.html', '<script src="//x.example/a.js"></script>', 'remote'],
|
||||
['a remote url() in CSS', 'a.css', 'a { background: url(https://x.example/a.png); }', 'url()'],
|
||||
['a remote @import', 'a.css', '@import url("https://fonts.example/a.css");', '@import'],
|
||||
['eval', 'a.ts', 'eval(s);', 'eval'],
|
||||
['indirect eval', 'a.ts', '(0, eval)(s);', 'eval'],
|
||||
['optional-chained eval', 'a.ts', 'globalThis.eval?.(s);', 'eval'],
|
||||
['new Function', 'a.ts', "new Function('return 1');", 'Function constructor'],
|
||||
['bare Function()', 'a.ts', "Function('return 1')();", 'Function constructor'],
|
||||
['a string setTimeout', 'a.ts', "setTimeout('run()', 0);", 'string timer'],
|
||||
['a dynamic import', 'a.ts', "await import('./x');", 'dynamic import'],
|
||||
['an import from a URL', 'a.ts', "import x from 'https://x.example/m.js';", 'import from URL'],
|
||||
['innerHTML assignment', 'a.ts', 'el.innerHTML = h;', 'innerHTML'],
|
||||
['innerHTML +=', 'a.ts', 'el.innerHTML += h;', 'innerHTML'],
|
||||
['bracket innerHTML', 'a.ts', "el['innerHTML'] = h;", 'innerHTML'],
|
||||
['innerHTML via Object.assign', 'a.ts', 'Object.assign(el, { innerHTML: h });', 'innerHTML'],
|
||||
['outerHTML', 'a.ts', 'el.outerHTML = h;', 'innerHTML / outerHTML'],
|
||||
['insertAdjacentHTML', 'a.ts', "el.insertAdjacentHTML('beforeend', h);", 'insertAdjacentHTML'],
|
||||
['setHTMLUnsafe', 'a.ts', 'el.setHTMLUnsafe(h);', 'setHTMLUnsafe'],
|
||||
[
|
||||
'createContextualFragment',
|
||||
'a.ts',
|
||||
'range.createContextualFragment(h);',
|
||||
'createContextualFragment',
|
||||
],
|
||||
['srcdoc', 'a.ts', 'frame.srcdoc = h;', 'srcdoc'],
|
||||
['document.write', 'a.ts', 'document.write(h);', 'document.write'],
|
||||
['{@html}', 'a.svelte', '<p>{@html h}</p>', '{@html}'],
|
||||
['{ @html } with a space', 'a.svelte', '<p>{ @html h }</p>', '{@html}'],
|
||||
];
|
||||
|
||||
describe('guard.mjs — banned patterns', () => {
|
||||
it.each(BANNED)('fails on %s', (_label, file, content, rule) => {
|
||||
const { status, output } = runGuard(makeRoot({ [`src/${file}`]: content }));
|
||||
expect(status, output).toBe(1);
|
||||
expect(output).toContain(rule);
|
||||
});
|
||||
|
||||
it('scans test-named files inside src/ too (no exemption)', () => {
|
||||
// The old `*.test.ts` exemption could only ever skip files inside src/.
|
||||
const { status } = runGuard(makeRoot({ 'src/x.test.ts': 'fetch(u);' }));
|
||||
expect(status).toBe(1);
|
||||
});
|
||||
|
||||
it('reports the line of a match', () => {
|
||||
const { output } = runGuard(makeRoot({ 'src/a.ts': 'const a = 1;\n\nel.innerHTML = h;\n' }));
|
||||
expect(output).toContain('src/a.ts:3');
|
||||
});
|
||||
});
|
||||
|
||||
describe('guard.mjs — things that must stay allowed', () => {
|
||||
const ALLOWED: Record<string, string> = {
|
||||
'src/links.ts': "export const REPO = 'https://github.com/poli0981/bookmarkmagic';",
|
||||
'src/Link.svelte':
|
||||
'<a href="https://github.com/x" target="_blank" rel="noopener noreferrer">x</a>',
|
||||
'src/download.ts': "anchor.rel = 'noopener';\nlocation.hash = '#edit';",
|
||||
'src/base.css': "@import './tokens.css';\na { background: url(./icon.svg); }",
|
||||
'src/words.ts': [
|
||||
'const prefetched = 1;',
|
||||
'const evaluate = () => 0;',
|
||||
'const importance = 2;',
|
||||
'function myFunction() {}',
|
||||
'const transport = "web";',
|
||||
'// "network calls are banned" — prose without the API names',
|
||||
].join('\n'),
|
||||
};
|
||||
|
||||
it('passes a tree full of near-misses', () => {
|
||||
const { status, output } = runGuard(makeRoot(ALLOWED));
|
||||
expect(status, output).toBe(0);
|
||||
expect(output).toContain('guard: clean — 5 files');
|
||||
});
|
||||
});
|
||||
|
||||
describe('guard.mjs — refuses to pass what it could not see', () => {
|
||||
it('fails when src/ is missing', () => {
|
||||
const { status, output } = runGuard(makeRoot({ 'README.md': 'x' }));
|
||||
expect(status).toBe(1);
|
||||
expect(output).toContain('cannot scan');
|
||||
});
|
||||
|
||||
it('fails when src/ holds nothing it scans', () => {
|
||||
const { status, output } = runGuard(makeRoot({ 'src/notes.txt': 'fetch(u)' }));
|
||||
expect(status).toBe(1);
|
||||
expect(output).toContain('scanned 0 files');
|
||||
});
|
||||
|
||||
it('scans a checkout whose path has a space and a diacritic', () => {
|
||||
// `new URL(...).pathname` stayed percent-encoded here, so the walker found
|
||||
// nothing and the gate printed "clean".
|
||||
const { status } = runGuard(makeRoot({ 'src/a.ts': 'fetch(u);' }, 'Nguyễn dir-'));
|
||||
expect(status).toBe(1);
|
||||
});
|
||||
|
||||
it('passes the real src/ tree', () => {
|
||||
const result = spawnSync(process.execPath, [GUARD], { encoding: 'utf8' });
|
||||
expect(result.status, `${result.stdout}${result.stderr}`).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
/**
|
||||
* scripts/sanitize-bookmarks.mjs — the cases the fixture corpus cannot reach:
|
||||
* the two browser JSON formats (no committed fixture yet when these were
|
||||
* written), the leaks a 2026-10-28 audit found, and the CLI's own safety rules.
|
||||
*
|
||||
* Every personal string in these samples is something the output must NOT
|
||||
* contain, and each assertion checks the raw output text.
|
||||
*/
|
||||
|
||||
const SCRIPT = join(process.cwd(), 'scripts', 'sanitize-bookmarks.mjs');
|
||||
const dirs: string[] = [];
|
||||
|
||||
function tempFile(name: string, content: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'sanitize-'));
|
||||
dirs.push(dir);
|
||||
const path = join(dir, name);
|
||||
writeFileSync(path, content);
|
||||
return path;
|
||||
}
|
||||
|
||||
function run(args: string[]): { status: number | null; stdout: string; stderr: string } {
|
||||
const result = spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8' });
|
||||
return { status: result.status, stdout: result.stdout, stderr: result.stderr };
|
||||
}
|
||||
|
||||
function sanitizeText(name: string, content: string): { status: number | null; out: string } {
|
||||
const { status, stdout } = run([tempFile(name, content), '--stdout']);
|
||||
return { status, out: stdout };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const CHROME_PROFILE = `{
|
||||
"checksum": "4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a99",
|
||||
"roots": {
|
||||
"bookmark_bar": {
|
||||
"children": [ {
|
||||
"date_added": "13344473600000000",
|
||||
"date_last_used": "0",
|
||||
"guid": "5e1d9a62-1c3e-4c41-9d0b-6f2b8a1e7c33",
|
||||
"id": "5",
|
||||
"meta_info": { "Nickname": "oncology-portal", "Thumbnail": "https://thumbs.clinic.internal/1.png" },
|
||||
"name": "Dr Smith oncology results portal",
|
||||
"type": "url",
|
||||
"url": "https://portal.clinic.internal/results?patient=8812"
|
||||
} ],
|
||||
"date_added": "13344473600000000",
|
||||
"date_modified": "13344473700000000",
|
||||
"guid": "0bc5d13f-2cba-5d74-951f-3f233fe6c908",
|
||||
"id": "1",
|
||||
"name": "Bookmarks bar",
|
||||
"type": "folder"
|
||||
},
|
||||
"other": { "children": [], "date_added": "0", "guid": "82b081ec-3dd3-529c-8475-ab6c344590dd", "id": "2", "name": "Other bookmarks", "type": "folder" },
|
||||
"synced": { "children": [], "date_added": "0", "guid": "4cf2e351-0e85-532b-bb37-df045d8f8d0f", "id": "3", "name": "Mobile bookmarks", "type": "folder" }
|
||||
},
|
||||
"sync_metadata": "Q2hBSkVMa0JBdVlWa1Z3QmxBZ0xpbnVzLnRvcnZhbGRz",
|
||||
"version": 1
|
||||
}
|
||||
`;
|
||||
|
||||
const FIREFOX_BACKUP = JSON.stringify({
|
||||
guid: 'root________',
|
||||
title: '',
|
||||
index: 0,
|
||||
dateAdded: 1700000000000000,
|
||||
lastModified: 1700000000000000,
|
||||
id: 1,
|
||||
typeCode: 2,
|
||||
type: 'text/x-moz-place-container',
|
||||
root: 'placesRoot',
|
||||
children: [
|
||||
{
|
||||
guid: 'toolbar_____',
|
||||
title: 'toolbar',
|
||||
index: 1,
|
||||
typeCode: 2,
|
||||
type: 'text/x-moz-place-container',
|
||||
root: 'toolbarFolder',
|
||||
children: [
|
||||
{
|
||||
guid: 'Xk2pQ9vLm3Ta',
|
||||
title: 'Divorce lawyer shortlist',
|
||||
index: 0,
|
||||
dateAdded: 1700000000000000,
|
||||
typeCode: 1,
|
||||
type: 'text/x-moz-place',
|
||||
uri: 'https://lawyers.example-private.net/shortlist',
|
||||
iconUri: 'fake-favicon-uri:https://lawyers.example-private.net/favicon.ico',
|
||||
keyword: 'lawyerkw',
|
||||
tags: 'custody,urgent',
|
||||
charset: 'UTF-8',
|
||||
annos: [
|
||||
{
|
||||
name: 'bookmarkProperties/description',
|
||||
flags: 0,
|
||||
expires: 4,
|
||||
value: 'call before Friday hearing',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
describe('sanitizer — browser JSON formats', () => {
|
||||
it("rewrites every personal value in Chrome's profile Bookmarks file", () => {
|
||||
const { status, out } = sanitizeText('Bookmarks', CHROME_PROFILE);
|
||||
expect(status).toBe(0);
|
||||
for (const secret of [
|
||||
'Dr Smith',
|
||||
'oncology',
|
||||
'clinic.internal',
|
||||
'patient=8812',
|
||||
'5e1d9a62-1c3e-4c41-9d0b-6f2b8a1e7c33',
|
||||
'Q2hBSkVMa0JBdVlWa1Z3QmxBZ0xpbnVzLnRvcnZhbGRz',
|
||||
'4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a99',
|
||||
]) {
|
||||
expect(out, secret).not.toContain(secret);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the Chrome structure: keys, types, ids, timestamps and layout', () => {
|
||||
const { out } = sanitizeText('Bookmarks', CHROME_PROFILE);
|
||||
const before = JSON.parse(CHROME_PROFILE);
|
||||
const after = JSON.parse(out);
|
||||
expect(Object.keys(after)).toEqual(Object.keys(before));
|
||||
const node = after.roots.bookmark_bar.children[0];
|
||||
expect(node.type).toBe('url');
|
||||
expect(node.id).toBe('5');
|
||||
expect(node.date_added).toBe('13344473600000000');
|
||||
expect(after.roots.bookmark_bar.date_modified).toBe('13344473700000000');
|
||||
expect(after.version).toBe(1);
|
||||
expect(out.split('\n').length).toBe(CHROME_PROFILE.split('\n').length);
|
||||
expect(after.checksum).toMatch(/^0+$/);
|
||||
});
|
||||
|
||||
it('rewrites every personal value in a Firefox backup and keeps the root GUIDs', () => {
|
||||
const { status, out } = sanitizeText('bookmarks-2026-10-28.json', FIREFOX_BACKUP);
|
||||
expect(status).toBe(0);
|
||||
for (const secret of [
|
||||
'Divorce',
|
||||
'lawyer',
|
||||
'example-private.net',
|
||||
'lawyerkw',
|
||||
'custody',
|
||||
'Friday hearing',
|
||||
'Xk2pQ9vLm3Ta',
|
||||
]) {
|
||||
expect(out, secret).not.toContain(secret);
|
||||
}
|
||||
const after = JSON.parse(out);
|
||||
expect(after.guid).toBe('root________');
|
||||
expect(after.root).toBe('placesRoot');
|
||||
expect(after.children[0].guid).toBe('toolbar_____');
|
||||
const bookmark = after.children[0].children[0];
|
||||
expect(bookmark.type).toBe('text/x-moz-place');
|
||||
expect(bookmark.dateAdded).toBe(1700000000000000);
|
||||
expect(bookmark.tags).toBe('tag1,tag2');
|
||||
expect(bookmark.annos[0].name).toBe('bookmarkProperties/description');
|
||||
});
|
||||
|
||||
it('refuses JSON that is none of the three known formats', () => {
|
||||
const { status, out } = sanitizeText(
|
||||
'x.json',
|
||||
'{"items":[{"label":"Dr Smith","href":"https://clinic.internal/"}]}',
|
||||
);
|
||||
expect(status).toBe(1);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizer — HTML leaks found by the audit', () => {
|
||||
const html = (body: string) => `<!DOCTYPE NETSCAPE-Bookmark-file-1>\n${body}\n`;
|
||||
|
||||
it('sanitizes a <DD> that carries attributes', () => {
|
||||
const { status, out } = sanitizeText(
|
||||
'dd.html',
|
||||
html(
|
||||
'<DL><p>\n<DT><A HREF="https://a.invalid/">x</A>\n<DD class="n">Private note about my therapist\n</DL><p>',
|
||||
),
|
||||
);
|
||||
expect(status).toBe(0);
|
||||
expect(out).not.toContain('therapist');
|
||||
});
|
||||
|
||||
it('sanitizes a file: ICON_URI that names a local user', () => {
|
||||
const { out } = sanitizeText(
|
||||
'icon.html',
|
||||
html(
|
||||
'<DL><p>\n<DT><A HREF="https://a.invalid/" ICON_URI="file:///C:/Users/JaneDoe/icons/x.ico">x</A>\n</DL><p>',
|
||||
),
|
||||
);
|
||||
expect(out).not.toContain('JaneDoe');
|
||||
});
|
||||
|
||||
it('sanitizes a document heading that names its owner', () => {
|
||||
const { out } = sanitizeText(
|
||||
'h1.html',
|
||||
html(
|
||||
'<TITLE>Jane Doe bookmarks</TITLE>\n<H1>Jane Doe personal bookmarks</H1>\n<DL><p>\n<DT><A HREF="https://a.invalid/">x</A>\n</DL><p>',
|
||||
),
|
||||
);
|
||||
expect(out).not.toContain('Jane');
|
||||
expect(out).toContain('<TITLE>Title ');
|
||||
});
|
||||
|
||||
it('keeps the generic "Bookmarks" heading as it is', () => {
|
||||
const { out } = sanitizeText(
|
||||
'plain.html',
|
||||
html(
|
||||
'<TITLE>Bookmarks</TITLE>\n<H1>Bookmarks Menu</H1>\n<DL><p>\n<DT><A HREF="https://a.invalid/">x</A>\n</DL><p>',
|
||||
),
|
||||
);
|
||||
expect(out).toContain('<TITLE>Bookmarks</TITLE>');
|
||||
expect(out).toContain('<H1>Bookmarks Menu</H1>');
|
||||
});
|
||||
|
||||
it('refuses when personal text sits where no rewriting rule looks', () => {
|
||||
// Loose text in a <DT> is reached by no rule. The text check catches it
|
||||
// anyway — that independence is what makes the rules trustworthy.
|
||||
const { status, out } = sanitizeText(
|
||||
'loose.html',
|
||||
html(
|
||||
'<DL><p>\n<DT>Notes from Jane about the custody case\n<DT><A HREF="https://a.invalid/">x</A>\n</DL><p>',
|
||||
),
|
||||
);
|
||||
expect(status).toBe(1);
|
||||
expect(out).toBe('');
|
||||
});
|
||||
|
||||
it('decodes an attribute value once, never twice', () => {
|
||||
// `&lt;` is "<" after ONE decode. The old chained replaces turned it
|
||||
// into "<", which changed how many query parameters the URL had.
|
||||
const { out } = sanitizeText(
|
||||
'amp.html',
|
||||
html('<DL><p>\n<DT><A HREF="https://a.invalid/p?x=&lt;b">t</A>\n</DL><p>'),
|
||||
);
|
||||
expect(out).toContain('HREF="https://a.example/p1?q1=v1&q2"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizer — CLI safety', () => {
|
||||
it('refuses to overwrite the input file', () => {
|
||||
const content =
|
||||
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><A HREF="https://real.example.org/">Mine</A>\n</DL><p>\n';
|
||||
const path = tempFile('bookmarks.html', content);
|
||||
const { status, stderr } = run([path, path]);
|
||||
expect(status).toBe(1);
|
||||
expect(stderr).toContain('refusing to overwrite');
|
||||
expect(readFileSync(path, 'utf8')).toBe(content);
|
||||
});
|
||||
|
||||
it('reports the output size in bytes, not characters', () => {
|
||||
const path = tempFile(
|
||||
'b.html',
|
||||
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><A HREF="https://a.invalid/">ブックマーク</A>\n</DL><p>\n',
|
||||
);
|
||||
const { stderr, stdout } = run([path, '--stdout']);
|
||||
expect(stderr).toContain(`${Buffer.byteLength(stdout)} bytes out`);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"extends": "./.wxt/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"target": "ES2025",
|
||||
"lib": ["ES2025", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2025",
|
||||
"lib": ["ES2025"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"types": ["node"],
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noUncheckedIndexedAccess": true
|
||||
},
|
||||
"include": ["scripts/**/*.mjs"]
|
||||
}
|
||||
+12
-2
@@ -18,8 +18,18 @@ export default defineConfig({
|
||||
include: ['tests/unit/**/*.test.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
include: ['src/lib/core/**'],
|
||||
thresholds: { lines: 90, functions: 90, branches: 85 },
|
||||
// Every TypeScript module is MEASURED, so SonarCloud sees real numbers
|
||||
// for the browser layer, stores and edit logic too (docs/12 §2.5).
|
||||
// Components and entrypoints are excluded on Sonar's side, matching the
|
||||
// docs/11 §1 split: they are covered by the manual QA pass.
|
||||
include: ['src/**/*.ts'],
|
||||
reporter: ['text', 'lcov'],
|
||||
// Only core is GATED, and with a glob threshold rather than a global one,
|
||||
// so widening `include` cannot loosen or tighten the CI gate: the numbers
|
||||
// below apply to src/lib/core/** alone, exactly as before (docs/11 §1).
|
||||
thresholds: {
|
||||
'src/lib/core/**': { lines: 90, functions: 90, branches: 85 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
+56
-5
@@ -6,24 +6,72 @@ import { defineConfig } from 'wxt';
|
||||
* Hard constraints encoded here (docs/08 §1, CLAUDE.md hard rules):
|
||||
* - Permissions are exactly ["bookmarks", "storage"] — forever, for v1.
|
||||
* No host_permissions, no content_scripts, no background service worker.
|
||||
* - No remote code: everything ships in the package, and the MV3 default CSP
|
||||
* is never loosened.
|
||||
* - No remote code: everything ships in the package. The extension-page CSP
|
||||
* below only ever TIGHTENS the MV3 default; it never loosens it.
|
||||
* - srcDir: 'src' so entrypoints/, public/ and lib/ all live under src/ and
|
||||
* the `@` alias resolves there (docs/02 §2).
|
||||
* - One runtime floor, stated three times on purpose: `minimum_chrome_version`
|
||||
* below, Vite's `build.target`, and tsconfig's `ES2025` lib. Chrome 136 is
|
||||
* the first release with every ES2025 built-in (RegExp.escape landed in 136,
|
||||
* Float16Array in 135), so the types the compiler allows are exactly the
|
||||
* APIs the oldest supported browser has (docs/01 §1, docs/08 §7).
|
||||
*/
|
||||
const CHROME_FLOOR = 136;
|
||||
|
||||
/**
|
||||
* The zero-network promise, enforced by the browser — docs/08 §3.
|
||||
*
|
||||
* MV3's default extension-page CSP restricts code execution only; it has no
|
||||
* connect-src or img-src at all, so until v1.1.0 a grep gate was the only
|
||||
* thing between the product and its "no network" claim. `connect-src 'none'`
|
||||
* makes Chrome itself refuse every fetch, XHR, WebSocket, EventSource and
|
||||
* beacon; the other directives close remote images, fonts, media, frames and
|
||||
* form posts. There is deliberately no `default-src`, so Svelte's styles are
|
||||
* untouched. `scripts/check-manifest.mjs` pins this exact string in the built
|
||||
* manifest.
|
||||
*
|
||||
* Production builds only: the dev server (`wxt`, command "serve") reloads the
|
||||
* extension over a localhost websocket that `connect-src 'none'` would block.
|
||||
*/
|
||||
const EXTENSION_PAGE_CSP = [
|
||||
"script-src 'self'",
|
||||
"object-src 'none'",
|
||||
"connect-src 'none'",
|
||||
"img-src 'self' data: blob:",
|
||||
// Inline styles stay allowed (Svelte sets style attributes); remote
|
||||
// stylesheets do not — with no default-src, style-src was otherwise open.
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"font-src 'self'",
|
||||
"media-src 'none'",
|
||||
"frame-src 'none'",
|
||||
"worker-src 'self'",
|
||||
"form-action 'none'",
|
||||
"base-uri 'none'",
|
||||
].join('; ');
|
||||
|
||||
export default defineConfig({
|
||||
srcDir: 'src',
|
||||
vite: () => ({
|
||||
build: {
|
||||
target: `chrome${CHROME_FLOOR}`,
|
||||
// Vite's modulepreload polyfill is a network call (it fetches each chunk
|
||||
// ahead of time) for browsers without native `<link rel=modulepreload>`.
|
||||
// Every Chrome at or above the floor has it, so the polyfill is dead code
|
||||
// that would leave the one network API in the shipped bundle.
|
||||
modulePreload: { polyfill: false },
|
||||
},
|
||||
}),
|
||||
// publicDir is resolved against the project ROOT, not srcDir — WXT's default
|
||||
// is `<root>/public`, so this line is required to keep _locales/ and icon/
|
||||
// under src/. Without it they are silently omitted from the build and Chrome
|
||||
// refuses to load the extension (missing __MSG_appName__ and icons).
|
||||
publicDir: 'src/public',
|
||||
modules: ['@wxt-dev/module-svelte'],
|
||||
manifest: {
|
||||
manifest: ({ command }) => ({
|
||||
name: '__MSG_appName__',
|
||||
description: '__MSG_appDesc__',
|
||||
default_locale: 'en',
|
||||
minimum_chrome_version: '120',
|
||||
minimum_chrome_version: String(CHROME_FLOOR),
|
||||
permissions: ['bookmarks', 'storage'],
|
||||
// Deep-link lands on #settings only when no Manager tab is open — with
|
||||
// open_in_tab Chrome matches the singleton tab ignoring the fragment,
|
||||
@@ -36,5 +84,8 @@ export default defineConfig({
|
||||
128: '/icon/128.png',
|
||||
},
|
||||
homepage_url: 'https://github.com/poli0981/bookmarkmagic',
|
||||
},
|
||||
...(command === 'build' && {
|
||||
content_security_policy: { extension_pages: EXTENSION_PAGE_CSP },
|
||||
}),
|
||||
}),
|
||||
});
|
||||
Reference in new issue
Block a user