Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5 94f957f705 fix(ci): grant contents: write so the reusable build job can start at all
The first real run of ci.yml was a startup_failure — no jobs, no log, just
"this run likely failed because of a workflow file issue".

reusable-chrome-extension.yml declares two mutually exclusive jobs: `build`
(contents: read, `if: !inputs.release`) and `release` (contents: write,
`if: inputs.release`). GitHub validates the caller's grant against EVERY job
the reusable declares, before evaluating any `if:` — so passing `release: false`
does not exempt the caller from the release job's requirement, and the
least-privilege `contents: read` in docs/12 §2.1's sample rejects the whole run.

CodeQL succeeded on the same push because its caller happened to grant a
superset of what its single job needs, which is what isolated the cause.

docs/12 §2.1 updated with the same grant and a warning, since its sample is
what this stub was written from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:54:58 +07:00
poli0981andClaude Opus 5 9e9107093e fix: close the eight findings the Phase 5 review confirmed
Five lenses filed 20; 8 survived verification.

**release.yml would have failed on the first tag.** The `announce` job called
the ops reusable with no `with:` block, but that reusable resolves
TAG="${INPUT_TAG:-$EVENT_TAG}" where EVENT_TAG is github.event.release.tag_name
-- empty, because this workflow is triggered by `on: push: tags`, not
`on: release`. The job would have exited 1 on "No release tag available" for
every release. Filed independently by three lenses and confirmed against the
reusable's actual source; docs/12 §2.3 had the same omission and is fixed too.
Ironically the comment right above it explains why the workflow deliberately is
not event-driven -- which is exactly what makes tag_override mandatory.

**Nothing checked the BUILT manifest.** The unit test reads wxt.config.ts,
which proves what we ask for, not what WXT emits. Those differ: a dev build of
this same config carries ["bookmarks","storage","tabs","scripting"] and
host_permissions ["http://localhost/*"]. Production is clean, but that is
WXT's behaviour, not ours. scripts/check-manifest.mjs now gates the artifact
and runs in both CI and release; verified by editing a built manifest. The
README sentence claiming a test asserted the built manifest was false and is
corrected -- the same overclaim I had already made once verbally.

**The contrast test I added last commit could not see its own bypass.**
TabBar's `.locked { opacity: 0.65 }` composites --fg-muted against the page and
drops the label to 2.83:1. The test reads token values, so alpha applied on top
is invisible to it. Opacity removed; the padlock and title already carried the
signal. TEXT_PAIRS also widened to check the status colours on --bg, not only
--bg-raised.

**docs/09 T3 was signed off with half its mitigation unbuilt.** The row has
always specified a ⚠ badge for dangerous schemes; only the blocking existed. A
`javascript:` bookmark titled "Your bank" rendered identically to a safe one
and its Open button silently did nothing. isBlockedUrl now drives a badge, and
a refused open raises a toast.

Also: the five row action buttons had glyphs as their accessible names (content
beats title in accname), so voice control could not address them; the manifest
test's literal-harvesting regex would have passed a spread or identifier;
resolveNewFolderParent returned a focused unmodifiable folder's id, which every
create rejects; and clipboard.ts was the only new module with no test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:44:08 +07:00
poli0981andClaude Opus 5 29254c7d04 feat(security): close the two gaps the T1-T8 pass found
Walking docs/09's threat model against the shipped code turned up two things
that had gone unnoticed because nothing mechanical was watching either.

**The permission list had no test.** "Exactly bookmarks + storage" is
CLAUDE.md's first hard rule, the README's headline privacy claim, the store's
privacy-tab answer and a line in the privacy policy -- and a single added
string in wxt.config.ts would have shipped silently. tests/unit/manifest.test.ts
now asserts the list exactly, plus the absence of host_permissions,
content_scripts, a background worker and eight other reach-widening keys.
Verified to fail by sneaking in 'tabs'. It reads the config as text, with
comments stripped, so the assertion cannot be satisfied by something computed
at build time -- and because the file's own header says "No host_permissions,
no content_scripts", a naive substring check failed on the prose promising the
very thing it checks.

**"Copy URL" was never built.** docs/06 §3.3 lists it in the row menu and
docs/09 T8 describes its mitigation, so the threat model documented a control
for a feature that did not exist. Now implemented in browser/clipboard.ts:
write-only, on an explicit click, never reads the clipboard, and needs no
permission because a transient user activation grants clipboard-write.

Also records the measured pass in docs/09 §2 and the reproducibility finding in
§5: content-identical rebuilds (every zip entry matches by CRC32) but not
byte-identical, because wxt zip records mtimes. The old wording implied more
than is true.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:17:21 +07:00
poli0981andClaude Opus 5 7884d7c14d ci: add the four caller workflows
Per docs/12 §2, with every input checked against the ops repo's actual
workflow_call blocks rather than the doc — docs/12 originally described a
template family that had never existed.

Verified before writing: reusable-chrome-extension.yml takes
package-manager/node-version/build-command/source-dir/release and declares NO
secrets block, so passing a named secret to it would be a compile error;
reusable-codeql.yml takes `languages` as a JSON-array string (the older
codeql.yml's singular `language` is the wrong one); notify-ci-failure.yml
declares DISCORD_CI_WEBHOOK required:true; announce-release.yml's secrets are
optional. actions/checkout@v7 and setup-node@v6 are what the ops repo itself
runs.

Three traps the comments now carry, because each costs a run to rediscover:
- 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;
- reusable workflows do not inherit the caller's permissions, so every caller
  repeats its permissions block on the job;
- the release announcement is a job INSIDE release.yml, not an
  `on: release: [published]` caller — a Release created by gh under the default
  GITHUB_TOKEN emits no event that starts new workflow runs, so the
  event-driven version silently never fires.

The quality job is local because the reusable runs no quality gates at all.
All four parse, and `npm run zip` emits .output/bookmarkmagic-0.1.0-chrome.zip,
matching the glob release.yml uses.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:09:45 +07:00
poli0981andClaude Opus 5 c367680838 docs: add CHANGELOG and README, and point About's link at the real file
CHANGELOG.md follows Keep a Changelog with the semver policy docs/12 §4
defines, and carries a marker for the human step at first release (rename
[Unreleased] to [1.0.0]).

README leads with what the project is actually for and then spends its longest
section on privacy, because that is the product's reason to exist and every
claim in it is mechanically enforced: the grep gate for network calls, the
manifest assertion for permissions, zero runtime dependencies. It also keeps
docs/13's honesty corner -- favicons, import dates, CSV flattening -- rather
than only listing what works.

src/lib/links.ts now points "Changelog" at blob/main/CHANGELOG.md instead of
the /releases placeholder it used through Phase 4, and the links test asserts
the file exists, the same way it already does for the four legal documents. A
link shipped inside the product must not 404 because someone renamed the
target.

Screenshots and the store URL are marked ⚠️ in the README -- both need a human
and neither blocks the code.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:07:34 +07:00
poli0981andClaude Opus 5 106f0ad337 refactor(edit): split EditTab under the size limit and test what came out
EditTab.svelte was 589 lines against the 500-line hard limit in docs/10 §1 --
the one place in the codebase that broke it. Now 459.

Extracted, in each case because the thing was genuinely cohesive rather than to
hit a number:

- src/lib/edit/edit-node.ts -- toEditNode, flattenTree, isEditable,
  resolveNewFolderParent, countDescendants, extraCopyIds. All pure, all
  previously inline and therefore untestable. resolveNewFolderParent in
  particular encodes a fixed bug (a focused root resolving to the synthetic
  root "0", which every create rejects) that nothing was pinning.
- src/lib/browser/open-url.ts -- the docs/09 T3 scheme allowlist, which is the
  only thing between a crafted `javascript:` bookmark in someone's import file
  and the browser acting on it. It had NO test. It does now, including the
  case-shouting dodge and data:/file:/chrome:.
- EditToolbar.svelte and MoveToDialog.svelte -- presentational, with their
  styles copied verbatim. This is a move, not a redesign.

The script block is still 279 lines against docs/10 §1's 150-line guidance. The
remainder is the mutation layer (guardEdit and the six operations), which is
coupled to reactive state and would need accessor indirection to move. Adding
that indirection to the app's delete paths immediately before a release is a
worse trade than the line count, so it stays and is recorded in CLAUDE.md
rather than quietly ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:05:50 +07:00
poli0981andClaude Opus 5 1589ea4209 fix(ui): make every colour token meet the contrast the spec has always required
docs/06 §5 has said "≥ 4.5:1 in both themes (tokens chosen accordingly)" since
the spec was written. Nothing enforced it, and the tokens were not chosen
accordingly. Measured:

  white on dark --accent      3.67:1   (fixed in Phase 4)
  white on dark --danger      2.74:1   Button/ConfirmDialog .danger
  light --warn on --bg-raised 3.40:1   WarningList summary
  light --success  "     "    3.26:1   TreePreviewNode badge, DuplicatePanel
  light --danger   "     "    4.27:1   DuplicatePanel count
  dark --accent    "     "    4.40:1   links inside raised panels

Adds --danger-fg, which like --accent-fg must be redefined in the dark block in
the OPPOSITE direction: dark mode lightens the colour for contrast against the
page, and that is exactly what breaks white ink sitting on it.

The light status colours are now darker than an eyeball would pick, because all
three are rendered as text on --bg-raised. Adjustments preserve hue and were
solved for numerically rather than guessed; each clears 4.5 with margin.

The real deliverable is tests/unit/styles/contrast.test.ts, which parses
tokens.css and fails on any text pair below 4.5:1 — verified to actually fail
by restoring the old --warn and watching it report 3.40:1. It also pins the two
dark blocks (explicit override and prefers-color-scheme) against each other,
because they already drifted once when --accent-fg was added to only one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:59:42 +07:00
35 changed files with 1484 additions and 202 deletions

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
# Caller stub — docs/12 §2.1.
#
# 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.
name: CI
on:
push:
branches: [main]
pull_request:
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@v6
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 docs/11 §1
- run: npm run guard # the canonical grep gate, docs/08 §3
# 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
# tabs/scripting/host_permissions that never appear in the config file.
- run: npm run build
- run: npm run check:manifest
build:
name: Build + package
needs: quality
# No `secrets:` here — the reusable declares no secrets block at all, and
# passing a named secret to it is a workflow-compile error.
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
permissions:
# `contents: write`, not `read`, even though nothing here writes.
#
# The reusable has two mutually exclusive jobs: `build` (contents: read,
# `if: !inputs.release`) and `release` (contents: write, `if:
# inputs.release`). GitHub validates the caller's grant against EVERY job
# the reusable declares, BEFORE evaluating any `if:` — so passing
# `release: false` does not exempt us from the release job's requirement.
# Granting only `contents: read` makes the whole run fail at startup with
# no jobs and no log, which is how this was found (docs/12 §2.1's sample
# had the same too-narrow grant).
contents: write
with:
# 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.
package-manager: 'npm'
node-version: '24'
build-command: 'npm run build'
source-dir: '.output/chrome-mv3'
release: false
+36
View File
@@ -0,0 +1,36 @@
# Caller stub — docs/12 §2.2.
#
# Uses `reusable-codeql.yml` (CodeQL Action v4), NOT the older `codeql.yml`,
# whose input is the singular `language`. This one takes `languages`: a JSON
# array encoded as a string.
#
# ⚠️ Prerequisite: repo Settings → Advanced Security → CodeQL "Default setup"
# must be DISABLED, or this advanced-setup workflow is rejected at SARIF upload.
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:
# Reusable workflows do not inherit the caller's permissions — the block
# below is repeated on the job on purpose.
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
permissions:
security-events: write
actions: read
contents: read
packages: read
with:
languages: '["javascript-typescript"]'
+25
View File
@@ -0,0 +1,25 @@
# Caller stub — docs/12 §2.4.
#
# The reusable already filters to `conclusion == 'failure'` on the default
# branch, so this caller needs no `if:`.
#
# ⚠️ It declares `DISCORD_CI_WEBHOOK` as `required: true`, so this workflow
# fails until that repo secret exists (docs/12 §5).
name: Notify CI failure
on:
workflow_run:
workflows: ['CI']
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
permissions:
contents: read
actions: read
secrets: inherit
+91
View File
@@ -0,0 +1,91 @@
# Release — docs/12 §2.3.
#
# Standalone rather than the ops reusable: the reusable's `release` job only
# 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.
name: Release
on:
push:
tags: ['v*']
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@v6
with:
node-version: '24'
cache: npm
- run: npm ci
# 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.
- 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
# Gate the artifact, not just the config it was built from. A tag is the
# last point at which an unintended permission can still be stopped.
- run: npm run check:manifest
- 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
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
# 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'
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
# 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
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.
tag_override: ${{ github.ref_name }}
secrets: inherit
+44
View File
@@ -0,0 +1,44 @@
# Changelog
All notable changes to BookmarkMagic are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Per `docs/12 §4`: **patch** = fixes and translations · **minor** = features, and
any change to the permission list or the store privacy tab · **major** =
breaking format or schema changes (a BM JSON version bump).
## [Unreleased]
### Added
- Import bookmark files (Netscape HTML, BookmarkMagic JSON, CSV) with a full
preview — counts, folder depth, duplicates and warnings — before anything is
written.
- Three import modes: into a new dated folder (the default), merge into
existing folders, or replace everything. Replace downloads a JSON safety
backup first and deletes nothing until that backup is proven.
- Skip bookmarks whose URL already exists in this browser.
- Export everything, or just the folders you pick, to HTML, JSON, CSV or
Markdown.
- Edit the bookmark tree: search, rename, create folders, delete, drag & drop,
a keyboard "Move to…" with full parity, and a duplicate-finder panel.
- English, Vietnamese and Japanese, switchable in Settings independently of the
browser's own language.
- Light, dark and system themes.
- A first-run legal gate covering the EULA, licence, disclaimer and privacy
policy.
### Security
- Imported URLs are never rendered as links. Opening one goes through an
`http(s)`-only allowlist, so a `javascript:` or `data:` bookmark in a crafted
file cannot be activated from the extension.
- Parsing is bounded: 25 MB per file, 100 000 nodes, 200 levels of nesting.
- No network access of any kind at runtime, enforced by a grep gate in CI.
<!-- ⚠️ Human: on the first release, rename [Unreleased] to [1.0.0] with the
release date, and add a fresh empty [Unreleased] section above it. -->
[Unreleased]: https://github.com/poli0981/bookmarkmagic/commits/main
+6 -5
View File
@@ -90,11 +90,12 @@ install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
clean-install test. Also carried in from the Phase 4 review:
- point About's "Changelog" link at `CHANGELOG.md` once it exists
(`src/lib/links.ts` currently targets `/releases`);
- split `EditTab.svelte`, which is past the 500-line hard limit;
- `Button.svelte`'s `.danger`/`.success` variants hardcode `color: #fff`, which
measures **2.75:1** on dark-theme `--danger` (#ff6b7d) — under the 4.5:1
docs/06 §5 requires. Phase 4 fixed the same class of bug for `--accent-fg`;
these need `--danger-fg`/`--success-fg` tokens and a visual decision.
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). Its script block
is still 279 lines against the 150-line guidance; the remainder is the
mutation layer, which is genuinely coupled to reactive state and was left
whole rather than split behind accessors on the app's delete paths;
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
the build on any text pair under 4.5:1.
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
## Working style
+109
View File
@@ -0,0 +1,109 @@
# BookmarkMagic
[![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-blue.svg)](LICENSE)
[![CI](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml)
[![CodeQL](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml)
[![Runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen.svg)](#privacy)
Move your bookmarks between browsers the simple way: with a file. No account,
no cloud sync, 100% offline.
A Chrome (MV3) extension for importing, exporting and editing bookmarks and
folder trees. English · Tiếng Việt · 日本語.
<!-- ⚠️ Human: add screenshots here before store submission — the manager's
import preview, the export picker, and the edit tree are the three that
matter. Icons are still generated placeholders (docs/00 §10 item 3). -->
## What it does
- **Import** HTML, JSON or CSV bookmark files, with a full preview first —
counts, folders, depth, duplicates and warnings before anything is written.
- **Choose how**: into a new dated folder (the safe default), merged into your
existing folders, or replacing everything. Replace saves a JSON safety backup
first and **deletes nothing until that backup is proven**.
- **Export** everything, or just the folders you pick, to HTML (Chrome, Edge,
Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV or Markdown.
- **Edit** the tree: search, rename, drag & drop, create folders, delete, and
find duplicate links — every action reachable from the keyboard.
## Privacy
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`.
- **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
**built** `manifest.json` — because a build can add what the config never
asked for.
- **Zero runtime dependencies.** Nothing third-party ships in the extension.
- Settings use `chrome.storage.local`, never `storage.sync`, so even your
preferences stay off any vendor cloud.
Full policy: [`legal/PRIVACY.md`](legal/PRIVACY.md).
## Honest limitations
- Favicons cannot be imported — the bookmarks API has no favicon field.
- Imported bookmarks get today's date. Chrome does not let an extension set a
bookmark's original creation date. Your **exported** files keep the real ones.
- CSV is a flattened view: empty folders and "which folder is the toolbar" are
not preserved. Use HTML or JSON for a faithful backup.
- Markdown is share-only — BookmarkMagic cannot read it back.
## Install
From the Chrome Web Store: ⚠️ *link once the listing is live.*
From source:
```bash
npm ci && npm run build
```
Then load `.output/chrome-mv3/` at `chrome://extensions` with Developer mode on.
## Development
```bash
npm run dev
```
`npm run verify` is the gate everything else answers to — lint, type-check,
knip, the grep gate and the test suite, in that order. It must be green before
every commit.
The [`docs/`](docs/) directory is the binding specification, not notes: where
code and docs disagree, the docs win. Start with [`CLAUDE.md`](CLAUDE.md), then
`docs/00`–`docs/02`.
## Contributing
Bug reports and translation fixes are welcome via
[issues](https://github.com/poli0981/bookmarkmagic/issues). A bug report about
parsing is far more useful with a sanitized sample of the file that broke.
Security issues: please follow [`SECURITY.md`](SECURITY.md) rather than opening
a public issue.
## Support development
Entirely optional — BookmarkMagic is free software either way.
[GitHub Sponsors](https://github.com/sponsors/poli0981) ·
[Ko-fi](https://ko-fi.com/skullmute) ·
[Buy Me a Coffee](https://www.buymeacoffee.com/skullmute) ·
[Patreon](https://www.patreon.com/skullmute) ·
[PayPal](https://paypal.me/DungDang212)
## Licence
[GPL-3.0-or-later](LICENSE). Also see [`legal/EULA.md`](legal/EULA.md),
[`legal/DISCLAIMER.md`](legal/DISCLAIMER.md) and
[`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md).
Not affiliated with or endorsed by Google, Chrome, or any browser vendor.
Browser names are trademarks of their respective owners.
+2 -1
View File
@@ -89,10 +89,11 @@ bookmarkmagic/
│ │ │ ├── download.ts # Blob → <a download>
│ │ │ ├── app-info.ts # manifest version — the ONE source (06 §3.5)
│ │ │ ├── errors.ts # BmBrowserError / BmBackupError / BmAborted (§7)
│ │ │ ├── open-url.ts # http(s) allowlist before tabs.create (09 T3)
│ │ │ └── open-manager.ts # getContexts() focus-or-create
│ │ ├── import/run-import.ts # the import pipeline (03 §1)
│ │ ├── export/run-export.ts # the export pipeline (03 §2)
│ │ ├── edit/ # patch-tree, move-target, tree-keyboard (03 §3)
│ │ ├── edit/ # edit-node, patch-tree, move-target, tree-keyboard (03 §3)
│ │ ├── settings/options.ts # the six Settings choice tables (06 §3.4)
│ │ ├── links.ts # repo / legal / donate URLs (14 §4, §5)
│ │ ├── stores/ # Svelte 5 runes state (.svelte.ts)
+23 -4
View File
@@ -11,7 +11,8 @@ framework.
--bg: #ffffff; --bg-raised: #f6f7f9; --border: #e2e5ea;
--fg: #1b1e24; --fg-muted: #5b6472;
--accent: #6d4aff; --accent-fg: #ffffff; /* violet — "magic" identity */
--danger: #d8384a; --success: #1f9d55; --warn: #b7791f;
--danger: #ce3547; --danger-fg: #ffffff;
--success: #198045; --warn: #99651a;
--radius: 10px; --radius-sm: 6px;
--font: system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--fs-0: 12px; --fs-1: 13.5px; --fs-2: 15px; --fs-3: 18px; --fs-4: 24px;
@@ -20,10 +21,27 @@ framework.
[data-theme="dark"] {
--bg: #16181d; --bg-raised: #1e2128; --border: #2b3039;
--fg: #e8eaee; --fg-muted: #9aa3b0;
--accent: #8b6dff; --danger: #ff6b7d; --success: #3ecf8e; --warn: #e2b93b;
--accent: #8f72ff; --accent-fg: #16181d;
--danger: #ff6b7d; --danger-fg: #16181d;
--success: #3ecf8e; --warn: #e2b93b;
}
```
⚠️ **`--accent-fg` and `--danger-fg` must be redefined in the dark block, in the
opposite direction to the colour they sit on.** Dark mode lightens `--accent`
and `--danger` for contrast against `--bg`, which is exactly what breaks white
ink on them — the original palette measured 3.67:1 and 2.74:1 there, against
the 4.5:1 §5 requires.
The light `--danger`/`--success`/`--warn` are darker than an eyeball would pick
because all three are rendered as **text** on `--bg-raised` (DuplicatePanel
counts, TreePreviewNode badges, WarningList's summary), where the original
values measured 4.27, 3.26 and 3.40.
None of these numbers is a matter of taste: `tests/unit/styles/contrast.test.ts`
parses `tokens.css` and fails the build if any text pair drops below 4.5:1, or
if the two dark blocks drift apart. Re-run it after changing a colour.
Theme: `data-theme` on `<html>`; default follows `prefers-color-scheme`,
manual override persisted in Settings. Focus rings always visible
(`:focus-visible` outline in accent).
@@ -182,8 +200,9 @@ read as a list of missing files:
| `AboutCard` | `AboutTab.svelte`, for symmetry with the other four tab shells |
| `TreeView` | inline in `EditTab.svelte`; the row is `TreeRow.svelte` and the flattening lives in `edit/tree-keyboard.ts` |
| `TreeNode` | `TreePreviewNode.svelte` (import preview) + `FolderPickNode.svelte` (export picker) |
| `ResultCard` / `SearchInput` | inline in `ImportTab` / `EditTab` |
| — | plus `SettingsTab.svelte`, the fifth tab shell |
| `ResultCard` | inline in `ImportTab` |
| `SearchInput` | inside `EditToolbar.svelte` |
| — | plus `SettingsTab.svelte` (the fifth tab shell), `EditToolbar.svelte` and `MoveToDialog.svelte` |
`Toast`'s queue and timers live in `stores/toast.svelte.ts`, not the component:
one `<Toast>` mounts at the App root while the route chain below it unmounts on
+42 -2
View File
@@ -26,6 +26,39 @@
| 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. |
### Pass performed 2026-07-26 (Phase 5)
| # | Now enforced by |
|---|---|
| T1 | `tests/unit/core/fixtures.test.ts` parses `malformed/script-injection.html` and asserts the payloads survive as inert text. `DOMParser('text/html')` never executes scripts, and `{@html}` is barred by `npm run guard`. |
| T2 | `tests/unit/core/limits.test.ts` plus the caps in `core/limits.ts`. Measured: a 100k-node file parses without exhausting anything (`11 §6`). |
| T3 | `malformed/js-url.html` at parse level, `tests/unit/browser/open-url.test.ts` at the point of use — `javascript:`, `data:`, `file:`, `chrome:`, `vbscript:` and case-shouted variants are refused before `tabs.create` — and the ⚠ badge this row has always specified, which `isBlockedUrl` now drives in `TreeRow`. A refused open also raises a toast; it used to do nothing at all, which read as a broken button rather than a deliberate refusal. |
| T4 | `tests/unit/import/safety-backup.test.ts`. |
| T5 | `npm audit --omit=dev` reports **0** — every open Dependabot alert is `development` scope. |
| T6 | Human; nothing in code. |
| T7 | `sanitizeFilename` (`tests/unit/browser/download.test.ts`); everything else reaches the DOM through Svelte text interpolation. |
| T8 | `browser/clipboard.ts` — write-only, click-only, never reads. Implemented in Phase 5; it had been specified in `06 §3.3` and here since the start but never built. |
Three gaps this pass closed, all of which had gone unnoticed because nothing
mechanical was watching:
- **The permission list had no gate at all.** Two now exist, and both are
needed. `tests/unit/manifest.test.ts` asserts `['bookmarks', 'storage']`
against `wxt.config.ts` — what we *ask* for. `scripts/check-manifest.mjs`
asserts the **built** artifact, which is not the same thing: a dev build of
this identical config emits
`"permissions": ["bookmarks","storage","tabs","scripting"]` and
`"host_permissions": ["http://localhost/*"]`, because WXT injects them.
Production is clean today, but that is WXT's behaviour, not our enforcement.
Both were verified to fail — one by adding `'tabs'` to the config, the other
by editing the built manifest.
- **"Copy URL" did not exist**, so T8 described the mitigation for a feature
that was never shipped.
- **T3's ⚠ badge did not exist either.** The blocking half was real and tested;
the "mark dangerous schemes in the UI" half was not, so a `javascript:`
bookmark titled "Your bank" rendered exactly like a safe one and its Open
button silently did nothing.
## 3. Secure coding rules (enforced)
- `{@html}` — **forbidden**. Enforced by the canonical grep gate (`08 §3`) and
@@ -52,9 +85,16 @@ a **minor-version** event at minimum.
## 5. Release integrity
- Builds are reproducible from a clean checkout: `npm ci && npm run zip`.
- Builds are **content**-reproducible from a clean checkout: `npm ci && npm run
zip`. Verified 2026-07-26 by building the same commit in a fresh clone and in
the working tree — every entry in the two zips has an identical name and
CRC32. The archives' SHA-256 hashes still differ, because `wxt zip` records
file mtimes and nothing normalizes them (there is no `SOURCE_DATE_EPOCH`
support). Do not claim byte-identical rebuilds.
- GitHub Releases attach the exact zip uploaded to CWS + `SHA256SUMS.txt`
so users can verify store build ↔ source correspondence.
so users can verify store build ↔ source correspondence. That works on the
released artifact itself, which is the same file in both places — it is not a
claim that a third party can rebuild the same hash.
- Tags are signed (GPG) — consistent with the tracker-repo signing practice.
## 6. Vulnerability reporting
+24
View File
@@ -150,3 +150,27 @@ generate-huge.ts # script: emits 100k+1 node file on demand
- Preview render after parse: < 500 ms (lazy tree).
- Manager cold open: interactive < 1 s.
- Import 10k nodes: progress visible ≤ 500 ms after start; cancel ≤ 1 s.
### Measured 2026-07-26 — Phase 5
A generated 100 000-node Netscape file (11.2 MB, 99 000 bookmarks in 1 000
folders), timed **under jsdom**:
| Stage | Time |
|---|---|
| `detectFormat` | 0 ms |
| `parseNetscapeHtml` | **2 869 ms** |
| `buildUrlIndex` | 42 ms |
| `diffAgainstBrowser` | 53 ms |
| `serializeNetscapeHtml` | 72 ms |
⚠️ **This does not settle the 2 s budget either way.** Everything except the
parse is pure JS and comfortably fast; the parse is dominated by `DOMParser`,
and jsdom's parse5 implementation is roughly an order of magnitude slower than
Chrome's native parser. The budget is about the real browser, so the honest
reading is "≤ 2.9 s in the slowest environment we can measure from a test".
The number that decides it has to come from Chrome. Added to the §5 checklist:
- [ ] Generate a 100k-node HTML file, import it in a real browser, and time
from drop to preview. Record the number here rather than re-deriving it.
+21 -1
View File
@@ -63,13 +63,15 @@ jobs:
- 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: read
contents: write # see the warning below — `read` fails at startup
with:
package-manager: 'npm' # 01 §6 commits package-lock.json
node-version: '24'
@@ -82,6 +84,16 @@ 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.
⚠️ **`contents: write` on the `build` job is not a mistake.** The reusable
declares two mutually exclusive jobs — `build` (`contents: read`,
`if: !inputs.release`) and `release` (`contents: write`, `if: inputs.release`).
GitHub validates the caller's grant against **every job the reusable declares,
before evaluating any `if:`**, so `release: false` does not exempt the caller
from the release job's requirement. Granting `contents: read` makes the entire
run fail with `startup_failure`: no jobs, no log, and only the generic "this run
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.
@@ -194,9 +206,17 @@ jobs:
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
with:
tag_override: ${{ github.ref_name }}
secrets: inherit
```
`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.
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
+1
View File
@@ -28,6 +28,7 @@
"lint:fix": "biome check --write .",
"knip": "knip",
"guard": "node scripts/guard.mjs",
"check:manifest": "node scripts/check-manifest.mjs",
"icons": "node scripts/gen-icons.mjs",
"test": "vitest run",
"test:watch": "vitest",
+74
View File
@@ -0,0 +1,74 @@
/**
* Assert the BUILT manifest — CLAUDE.md hard rule 1, docs/08 §2.
*
* 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
* "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.
*
* Run after `npm run build` (or `npm run zip`). Zero dependencies, Node stdlib.
*/
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const MANIFEST = join(process.cwd(), '.output', 'chrome-mv3', 'manifest.json');
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
/** Keys that would widen the extension's reach. None may be present. */
const FORBIDDEN_KEYS = [
'host_permissions',
'optional_permissions',
'optional_host_permissions',
'content_scripts',
'background',
'web_accessible_resources',
'externally_connectable',
'declarative_net_request',
'devtools_page',
'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);
}
const problems = [];
if (manifest.manifest_version !== 3) {
problems.push(`manifest_version is ${manifest.manifest_version}, expected 3`);
}
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)}`,
);
}
for (const key of FORBIDDEN_KEYS) {
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
}
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.');
process.exit(1);
}
console.warn(
`check-manifest: clean — MV3, permissions ${JSON.stringify(manifest.permissions)}, no reach-widening keys.`,
);
+23
View File
@@ -0,0 +1,23 @@
/**
* Copying a bookmark's URL — the docs/09 T8 surface.
*
* Purpose: the only place this extension touches the clipboard.
* Inputs: a URL string, from an explicit user click.
* Guarantees: **write only**. Nothing here ever reads the clipboard, and the
* write is never triggered by anything but a click, so no permission is
* needed — `clipboard-write` is granted to a transient user activation.
* Never throws; returns whether the copy landed.
*/
export async function copyToClipboard(text: string): Promise<boolean> {
const clipboard = globalThis.navigator?.clipboard;
// Absent in a non-secure context and in jsdom. A missing clipboard is a
// "could not copy", not a crash.
if (clipboard === undefined) return false;
try {
await clipboard.writeText(text);
return true;
} catch {
return false;
}
}
+54
View File
@@ -0,0 +1,54 @@
/**
* Opening a bookmarked URL — the docs/09 T3 control.
*
* Purpose: the single gate between a URL that came out of someone's import file
* and the browser actually navigating to it.
* Inputs: a URL string from untrusted file data.
* Guarantees: only `http:` and `https:` ever reach `tabs.create`. Nothing is
* opened for an unparseable URL, and nothing throws.
*/
import { browser } from 'wxt/browser';
/** Schemes allowed to reach the browser. Everything else is display-only. */
const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
/**
* Whether this URL would be refused — so the row can warn BEFORE the click.
*
* docs/09 T3 asks for both halves: block the navigation, and mark the bookmark
* so a `javascript:` entry titled "Your bank" does not look like an ordinary
* link that simply does nothing.
*/
export function isBlockedUrl(url: string | undefined): boolean {
if (url === undefined) return false;
try {
return !ALLOWED_SCHEMES.has(new URL(url).protocol);
} catch {
return true;
}
}
/**
* Open `url` in a new tab if its scheme is allowed.
*
* Returns whether it was opened, so callers and tests can tell "blocked" from
* "opened" rather than inferring it.
*
* Chromium also refuses `javascript:` from `tabs.create`, but this allowlist is
* the authoritative control: it is ours, it is testable, and it does not move
* when a browser changes its mind. `data:`, `file:` and `chrome:` are blocked
* here even though some are navigable, because a bookmark file is untrusted
* input and none of them are worth the surface.
*/
export async function openBookmarkUrl(url: string): Promise<boolean> {
let scheme: string;
try {
scheme = new URL(url).protocol;
} catch {
return false;
}
if (!ALLOWED_SCHEMES.has(scheme)) return false;
await browser.tabs.create({ url });
return true;
}
+3 -1
View File
@@ -44,6 +44,8 @@
.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
/* Not #fff: dark mode lightens --danger, where white ink measures 2.74:1
against the 4.5:1 docs/06 §5 requires. */
color: var(--danger-fg);
}
</style>
+1 -1
View File
@@ -77,6 +77,6 @@
.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
color: var(--danger-fg);
}
</style>
+53 -161
View File
@@ -1,19 +1,27 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from 'wxt/browser';
import {
create,
getRootChildren,
type LiveNode,
move,
remove,
removeTree,
subscribe,
update,
} from '../browser/bookmarks';
import { copyToClipboard } from '../browser/clipboard';
import { BmBrowserError } from '../browser/errors';
import { openBookmarkUrl } from '../browser/open-url';
import { findDuplicateGroups } from '../core/dedupe';
import { searchTree } from '../core/search';
import {
countDescendants,
extraCopyIds,
flattenTree,
isEditable as canEdit,
resolveNewFolderParent,
toEditNode,
} from '../edit/edit-node';
import {
changeNode,
type EditNode,
@@ -25,10 +33,12 @@
import { canMoveInto, moveTargets } from '../edit/move-target';
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
import { num, t } from '../i18n/index.svelte';
import Button from './Button.svelte';
import { pushToast } from '../stores/toast.svelte';
import Callout from './Callout.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import DuplicatePanel from './DuplicatePanel.svelte';
import EditToolbar from './EditToolbar.svelte';
import MoveToDialog from './MoveToDialog.svelte';
import TreeRow from './TreeRow.svelte';
let roots = $state<EditNode[]>([]);
@@ -78,16 +88,8 @@
};
});
function toEditNode(node: LiveNode): EditNode {
return {
id: node.id,
...(node.parentId !== undefined && { parentId: node.parentId }),
title: node.title,
...(node.url !== undefined && { url: node.url }),
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
};
}
/** Bound to the current tree, so callers pass only the node. */
const isEditable = (node: EditNode): boolean => canEdit(roots, node);
async function load(): Promise<void> {
try {
@@ -121,27 +123,9 @@
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
const duplicateGroups = $derived(
findDuplicateGroups(flatten(roots).filter((node) => node.url !== undefined)),
findDuplicateGroups(flattenTree(roots).filter((node) => node.url !== undefined)),
);
function flatten(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
for (const node of nodes) {
into.push(node);
flatten(node.children ?? [], into);
}
return into;
}
/**
* Permanent roots and policy-managed nodes reject every write, so the UI must
* not offer the affordance at all — optimistically mutating first and finding
* out on rejection is how the tree ends up disagreeing with the browser.
*/
function isEditable(node: EditNode): boolean {
if (node.unmodifiable !== undefined) return false;
return !roots.some((root) => root.id === node.id);
}
/**
* Run a mutation, and on failure resync from the browser — the only source of
* truth. A snapshot restore would resurrect rows that earlier iterations of a
@@ -207,19 +191,22 @@
}
/**
* Only http(s) reach the browser. `javascript:` and `data:` are display-only
* (docs/09 T3) — Chromium also rejects them, but the app-side allowlist is
* the authoritative control.
* Open a bookmark, saying so when the scheme is refused.
*
* The boolean was previously discarded with `void`, so clicking ↗ on a
* `javascript:` bookmark did nothing at all and looked like a broken button
* rather than a deliberate refusal (docs/09 T3).
*/
async function openUrl(url: string): Promise<void> {
let scheme = '';
try {
scheme = new URL(url).protocol;
} catch {
return;
}
if (scheme !== 'http:' && scheme !== 'https:') return;
await browser.tabs.create({ url });
if (url === '') return;
if (!(await openBookmarkUrl(url))) pushToast(t('edit.unsafeUrl'), 'danger');
}
/** docs/06 §3.3's "Copy URL". Write-only, on an explicit click (docs/09 T8). */
async function copyUrl(url: string): Promise<void> {
if (url === '') return;
const copied = await copyToClipboard(url);
pushToast(t(copied ? 'edit.copied' : 'edit.copyFailed'), copied ? 'success' : 'danger');
}
async function commitRename(id: string, title: string): Promise<void> {
@@ -246,17 +233,7 @@
}
async function newFolder(): Promise<void> {
// Into the focused FOLDER, or alongside the focused bookmark. Using the
// focused node's parent unconditionally meant selecting a root resolved to
// the synthetic root "0", which every create rejects.
const focused = findNode(roots, focusedId ?? '');
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
const parentId =
focused === undefined
? writableRoot
: focused.url === undefined
? focused.id
: (focused.parentId ?? writableRoot);
const parentId = resolveNewFolderParent(roots, findNode(roots, focusedId ?? ''));
if (parentId === undefined) return;
await guardEdit(async () => {
@@ -273,7 +250,7 @@
pendingKeepFirst = false;
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
// reading it inside the loop would recompute mid-iteration.
const doomed = duplicateGroups.flatMap((group) => group.nodes.slice(1).map((n) => n.id));
const doomed = extraCopyIds(duplicateGroups);
await guardEdit(async () => {
for (const id of doomed) {
roots = removeNode(roots, id);
@@ -319,30 +296,21 @@
searchInput?.select();
}
const descendantCount = $derived(
pendingDelete === undefined ? 0 : flatten(pendingDelete.children ?? []).length,
);
const descendantCount = $derived(countDescendants(pendingDelete));
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
{:else}
<div class="toolbar">
<input
bind:this={searchInput}
type="search"
placeholder={t('edit.search')}
aria-label={t('edit.search')}
value={query}
oninput={(e) => onQuery((e.currentTarget as HTMLInputElement).value)}
/>
<Button onclick={() => void newFolder()}>{t('edit.newFolder')}</Button>
<Button onclick={() => (showDuplicates = !showDuplicates)}>{t('edit.findDuplicates')}</Button>
<Button onclick={() => (expanded = new Set(flatten(roots).map((n) => n.id)))}
>{t('edit.expandAll')}</Button
>
<Button onclick={() => (expanded = new Set())}>{t('edit.collapseAll')}</Button>
</div>
<EditToolbar
bind:input={searchInput}
{query}
onquery={onQuery}
onnewFolder={() => void newFolder()}
ontoggleDuplicates={() => (showDuplicates = !showDuplicates)}
onexpandAll={() => (expanded = new Set(flattenTree(roots).map((node) => node.id)))}
oncollapseAll={() => (expanded = new Set())}
/>
{#if actionError !== undefined}
<div class="action-error">
@@ -388,6 +356,7 @@
oncancelRename={() => (renamingId = undefined)}
ondelete={() => (pendingDelete = row.node)}
onopen={() => void openUrl(row.node.url ?? '')}
oncopyUrl={() => void copyUrl(row.node.url ?? '')}
onmoveTo={() => (movingNode = row.node)}
ondragstart={() => (draggingId = row.node.id)}
ondropinto={() => onDrop(row.node.id)}
@@ -416,26 +385,16 @@
{/if}
{#if movingNode !== undefined}
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
<p>{t('edit.moveToBody', { title: movingNode.title })}</p>
<ul>
{#each targets as target (target.id)}
<li>
<button
onclick={() => {
const id = movingNode?.id;
movingNode = undefined;
if (id !== undefined) void moveInto(id, target.id);
}}>{target.label}</button
>
</li>
{/each}
{#if targets.length === 0}
<li class="muted">{t('edit.noMoveTargets')}</li>
{/if}
</ul>
<Button onclick={() => (movingNode = undefined)}>{t('common.cancel')}</Button>
</div>
<MoveToDialog
node={movingNode}
{targets}
onpick={(parentId) => {
const id = movingNode?.id;
movingNode = undefined;
if (id !== undefined) void moveInto(id, parentId);
}}
oncancel={() => (movingNode = undefined)}
/>
{/if}
<ConfirmDialog
@@ -465,24 +424,6 @@
/>
<style>
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.toolbar input {
font: inherit;
flex: 1;
min-width: 12ch;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
.split {
display: grid;
grid-template-columns: 1fr;
@@ -537,53 +478,4 @@
text-align: center;
}
.move-to {
position: fixed;
inset-block-end: var(--sp-4);
inset-inline-end: var(--sp-4);
width: min(360px, calc(100vw - var(--sp-6)));
max-height: 60vh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--accent);
border-radius: var(--radius);
padding: var(--sp-3);
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
}
.move-to p {
margin: 0 0 var(--sp-2);
font-size: var(--fs-1);
color: var(--fg-muted);
}
.move-to ul {
list-style: none;
margin: 0 0 var(--sp-3);
padding: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.move-to button {
font: inherit;
width: 100%;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--fg);
cursor: pointer;
padding: var(--sp-1) var(--sp-2);
}
.move-to button:hover {
background: var(--bg-raised);
}
.muted {
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
interface Props {
query: string;
/** Bound out so ⌘/Ctrl-F can focus it from the tab's window handler. */
input?: HTMLInputElement | undefined;
onquery: (value: string) => void;
onnewFolder: () => void;
ontoggleDuplicates: () => void;
onexpandAll: () => void;
oncollapseAll: () => void;
}
let {
query,
input = $bindable(),
onquery,
onnewFolder,
ontoggleDuplicates,
onexpandAll,
oncollapseAll,
}: Props = $props();
</script>
<div class="toolbar">
<input
bind:this={input}
type="search"
placeholder={t('edit.search')}
aria-label={t('edit.search')}
value={query}
oninput={(event) => onquery(event.currentTarget.value)}
/>
<Button onclick={onnewFolder}>{t('edit.newFolder')}</Button>
<Button onclick={ontoggleDuplicates}>{t('edit.findDuplicates')}</Button>
<Button onclick={onexpandAll}>{t('edit.expandAll')}</Button>
<Button onclick={oncollapseAll}>{t('edit.collapseAll')}</Button>
</div>
<style>
/* Copied verbatim from EditTab — this is a move, not a redesign. */
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.toolbar input {
font: inherit;
flex: 1;
min-width: 12ch;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg);
color: var(--fg);
}
</style>
+84
View File
@@ -0,0 +1,84 @@
<script lang="ts">
import type { MoveTarget } from '../edit/move-target';
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
import Button from './Button.svelte';
interface Props {
/** The node being moved. Rendering is caller-gated on this existing. */
node: EditNode;
targets: readonly MoveTarget[];
onpick: (parentId: string) => void;
oncancel: () => void;
}
let { node, targets, onpick, oncancel }: Props = $props();
</script>
<!-- Keyboard parity for drag & drop (docs/06 §3.3): every move reachable
without a mouse. -->
<div class="move-to" role="dialog" aria-label={t('edit.moveTo')}>
<p>{t('edit.moveToBody', { title: node.title })}</p>
<ul>
{#each targets as target (target.id)}
<li><button onclick={() => onpick(target.id)}>{target.label}</button></li>
{/each}
{#if targets.length === 0}
<li class="muted">{t('edit.noMoveTargets')}</li>
{/if}
</ul>
<Button onclick={oncancel}>{t('common.cancel')}</Button>
</div>
<style>
/* Copied verbatim from EditTab — this is a move, not a redesign. */
.move-to {
position: fixed;
inset-block-end: var(--sp-4);
inset-inline-end: var(--sp-4);
width: min(360px, calc(100vw - var(--sp-6)));
max-height: 60vh;
overflow: auto;
background: var(--bg);
border: 1px solid var(--accent);
border-radius: var(--radius);
padding: var(--sp-3);
box-shadow: 0 8px 32px rgb(0 0 0 / 0.25);
}
.move-to p {
margin: 0 0 var(--sp-2);
font-size: var(--fs-1);
color: var(--fg-muted);
}
.move-to ul {
list-style: none;
margin: 0 0 var(--sp-3);
padding: 0;
display: flex;
flex-direction: column;
gap: 2px;
}
.move-to button {
font: inherit;
width: 100%;
text-align: left;
background: none;
border: none;
border-radius: var(--radius-sm);
color: var(--fg);
cursor: pointer;
padding: var(--sp-1) var(--sp-2);
}
.move-to button:hover {
background: var(--bg-raised);
}
.muted {
color: var(--fg-muted);
font-size: var(--fs-1);
}
</style>
+6 -5
View File
@@ -69,11 +69,12 @@
cursor: not-allowed;
}
/* Reachable, but visibly not yet usable — clicking shows the gate. */
.locked {
opacity: 0.65;
}
/* Reachable, but visibly not yet usable — clicking shows the gate.
Deliberately NOT `opacity`, which composites the label against the page and
dropped --fg-muted from 5.98:1 to 2.83:1. The contrast test reads token
values out of tokens.css, so it cannot see an alpha applied on top: this
kind of dimming has to be avoided by hand. The padlock and the `title`
already carry the signal. */
.locked::after {
content: ' 🔒';
font-size: var(--fs-0);
+32 -4
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { isBlockedUrl } from '../browser/open-url';
import type { EditNode } from '../edit/patch-tree';
import { t } from '../i18n/index.svelte';
@@ -17,6 +18,7 @@
onstartRename: () => void;
ondelete: () => void;
onopen: () => void;
oncopyUrl: () => void;
onmoveTo: () => void;
ondragstart: () => void;
ondropinto: () => void;
@@ -41,6 +43,7 @@
onstartRename,
ondelete,
onopen,
oncopyUrl,
onmoveTo,
ondragstart,
ondropinto,
@@ -51,6 +54,7 @@
const isFolder = $derived(node.url === undefined);
const domain = $derived(hostOf(node.url));
const blocked = $derived(!isFolder && isBlockedUrl(node.url));
function hostOf(url: string | undefined): string {
if (url === undefined) return '';
@@ -117,40 +121,57 @@
{:else}
<span class="title">{node.title}</span>
{#if domain !== ''}<span class="domain">{domain}</span>{/if}
{#if blocked}
<!-- docs/09 T3: a javascript:/data: bookmark must not look like an
ordinary link that merely does nothing when clicked. -->
<span class="unsafe" title={t('edit.unsafeUrl')} aria-label={t('edit.unsafeUrl')}>⚠</span>
{/if}
<span class="actions">
{#if editable}
<button
title={t('edit.rename')}
aria-label={t('edit.rename')}
onclick={(e) => {
e.stopPropagation();
onstartRename();
}}>✎</button
}}><span aria-hidden="true">✎</span></button
>
{/if}
{#if !isFolder}
<button
title={t('edit.open')}
aria-label={t('edit.open')}
onclick={(e) => {
e.stopPropagation();
onopen();
}}>↗</button
}}><span aria-hidden="true">↗</span></button
>
<button
title={t('edit.copyUrl')}
aria-label={t('edit.copyUrl')}
onclick={(e) => {
e.stopPropagation();
oncopyUrl();
}}><span aria-hidden="true">⧉</span></button
>
{/if}
{#if editable}
<button
title={t('edit.moveTo')}
aria-label={t('edit.moveTo')}
onclick={(e) => {
e.stopPropagation();
onmoveTo();
}}>⇄</button
}}><span aria-hidden="true">⇄</span></button
>
<button
title={t('edit.delete')}
aria-label={t('edit.delete')}
onclick={(e) => {
e.stopPropagation();
ondelete();
}}>🗑</button
}}><span aria-hidden="true">🗑</span></button
>
{/if}
</span>
@@ -212,6 +233,13 @@
white-space: nowrap;
}
.unsafe {
flex-shrink: 0;
font-size: var(--fs-0);
color: var(--warn);
cursor: help;
}
.rename {
font: inherit;
flex: 1;
+82
View File
@@ -0,0 +1,82 @@
/**
* Pure helpers over the `#edit` tree — docs/03 §3.
*
* Purpose: the tree logic that used to sit inline in `EditTab.svelte`, where it
* was untestable and pushed the component past the docs/10 §1 size limits.
* Inputs: `EditNode` trees, plus `LiveNode`s straight from the bookmarks API.
* Guarantees: pure — no `chrome.*`, no Svelte, no mutation of the input.
*/
import type { LiveNode } from '../browser/bookmarks';
import type { EditNode } from './patch-tree';
/**
* Project a live bookmark node onto the editable model.
*
* Absent keys are omitted rather than set to `undefined`, per the
* `exactOptionalPropertyTypes` rule in docs/10 §2. `children` is set only for
* folders, which is what makes `url === undefined` a reliable folder test.
*/
export function toEditNode(node: LiveNode): EditNode {
return {
id: node.id,
...(node.parentId !== undefined && { parentId: node.parentId }),
title: node.title,
...(node.url !== undefined && { url: node.url }),
...(node.url === undefined && { children: (node.children ?? []).map(toEditNode) }),
...(node.unmodifiable !== undefined && { unmodifiable: node.unmodifiable }),
};
}
/** Depth-first list of every node in the forest, parents before children. */
export function flattenTree(nodes: readonly EditNode[], into: EditNode[] = []): EditNode[] {
for (const node of nodes) {
into.push(node);
flattenTree(node.children ?? [], into);
}
return into;
}
/**
* Whether a node may be renamed, moved or deleted.
*
* Permanent roots and policy-managed nodes reject every write, so the UI must
* not offer the affordance at all — mutating optimistically and finding out on
* rejection is exactly how the tree ends up disagreeing with the browser.
*/
export function isEditable(roots: readonly EditNode[], node: EditNode): boolean {
if (node.unmodifiable !== undefined) return false;
return !roots.some((root) => root.id === node.id);
}
/**
* Where a new folder should be created, given what is focused.
*
* Into the focused FOLDER, or alongside the focused bookmark. Using the focused
* node's parent unconditionally meant selecting a root resolved to the
* synthetic root id `"0"`, which every `create` rejects.
*
* Returns `undefined` when there is nowhere writable to put it.
*/
export function resolveNewFolderParent(
roots: readonly EditNode[],
focused: EditNode | undefined,
): string | undefined {
const writableRoot = roots.find((root) => root.unmodifiable === undefined)?.id;
if (focused === undefined) return writableRoot;
// A policy-managed folder rejects every create, so falling back is the only
// way "New folder" does anything at all while one is selected.
if (focused.unmodifiable !== undefined) return writableRoot;
if (focused.url === undefined) return focused.id;
return focused.parentId ?? writableRoot;
}
/** How many nodes sit inside `node`. Drives the delete confirmation's count. */
export function countDescendants(node: EditNode | undefined): number {
if (node === undefined) return 0;
return flattenTree(node.children ?? []).length;
}
/** Ids to delete so one copy of each duplicated link survives. */
export function extraCopyIds(groups: readonly { nodes: readonly EditNode[] }[]): string[] {
return groups.flatMap((group) => group.nodes.slice(1).map((node) => node.id));
}
+4
View File
@@ -110,6 +110,10 @@ const dict = {
collapseAll: 'Collapse all',
rename: 'Rename',
open: 'Open',
copyUrl: 'Copy link',
unsafeUrl: 'This address uses a scheme BookmarkMagic will not open.',
copied: 'Link copied',
copyFailed: 'Could not copy the link.',
moveTo: 'Move to…',
moveToBody: 'Move "{title}" into which folder?',
noMoveTargets: 'No other folder is available.',
+4
View File
@@ -103,6 +103,10 @@ export default {
collapseAll: 'すべて折りたたむ',
rename: '名前を変更',
open: '開く',
copyUrl: 'リンクをコピー',
unsafeUrl: 'このアドレスは BookmarkMagic が開かない形式です。',
copied: 'リンクをコピーしました',
copyFailed: 'リンクをコピーできませんでした。',
moveTo: '移動先…',
moveToBody: '「{title}」をどのフォルダへ移動しますか?',
noMoveTargets: '他に利用できるフォルダがありません。',
+4
View File
@@ -102,6 +102,10 @@ export default {
collapseAll: 'Thu gọn tất cả',
rename: 'Đổi tên',
open: 'Mở',
copyUrl: 'Sao chép liên kết',
unsafeUrl: 'Địa chỉ này dùng lược đồ mà BookmarkMagic sẽ không mở.',
copied: 'Đã sao chép liên kết',
copyFailed: 'Không sao chép được liên kết.',
moveTo: 'Chuyển tới…',
moveToBody: 'Chuyển "{title}" vào thư mục nào?',
noMoveTargets: 'Không có thư mục nào khác.',
+1 -6
View File
@@ -17,12 +17,7 @@
export const REPO_URL = 'https://github.com/poli0981/bookmarkmagic';
export const ISSUES_URL = `${REPO_URL}/issues`;
/**
* Releases, not `blob/main/CHANGELOG.md` — the changelog is authored in Phase 5
* and the file does not exist yet. A releases page renders as a valid (empty)
* page; a missing blob is a 404 shown from inside a legal-adjacent surface.
*/
export const CHANGELOG_URL = `${REPO_URL}/releases`;
export const CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`;
export interface LabelledLink {
labelKey: string;
+19 -8
View File
@@ -1,5 +1,10 @@
/* Design tokens — docs/06 §1. Theme via data-theme on <html>; default follows
prefers-color-scheme, manual override persisted in Settings. */
prefers-color-scheme, manual override persisted in Settings.
Every `*-fg`/`*` pair and every token used as TEXT clears 4.5:1 against both
--bg and --bg-raised, in both themes (docs/06 §5). The numbers are not a
matter of taste: tests/unit/styles/contrast.test.ts parses this file and
fails the build if any pair drops below. Re-run it after changing a colour. */
:root {
--bg: #ffffff;
@@ -9,9 +14,13 @@
--fg-muted: #5b6472;
--accent: #6d4aff; /* violet — "magic" identity */
--accent-fg: #ffffff;
--danger: #d8384a;
--success: #1f9d55;
--warn: #b7791f;
/* danger/success/warn are darker than an eyeball would pick, because all
three are used as text on --bg-raised: at the original values they measured
4.27, 3.26 and 3.40 against a 4.5 requirement. */
--danger: #ce3547;
--danger-fg: #ffffff;
--success: #198045;
--warn: #99651a;
--radius: 10px;
--radius-sm: 6px;
@@ -37,12 +46,13 @@
--border: #2b3039;
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
--accent: #8f72ff;
/* Dark mode lightens --accent for contrast against --bg, which drops white
ink on it to 3.67:1 — under the 4.5:1 docs/06 §5 requires. --accent-fg must
be redefined alongside it; dark ink on #8b6dff measures 4.84:1. */
ink on it under the 4.5:1 docs/06 §5 requires. --accent-fg must be
redefined alongside it, in the opposite direction. */
--accent-fg: #16181d;
--danger: #ff6b7d;
--danger-fg: #16181d;
--success: #3ecf8e;
--warn: #e2b93b;
}
@@ -54,10 +64,11 @@
--border: #2b3039;
--fg: #e8eaee;
--fg-muted: #9aa3b0;
--accent: #8b6dff;
--accent: #8f72ff;
/* Keep in step with the [data-theme='dark'] block above. */
--accent-fg: #16181d;
--danger: #ff6b7d;
--danger-fg: #16181d;
--success: #3ecf8e;
--warn: #e2b93b;
}
+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { copyToClipboard } from '@/lib/browser/clipboard';
/**
* The docs/09 T8 surface. jsdom provides no `navigator.clipboard`, so every
* case here installs one — which also exercises the "no clipboard at all" path
* that a non-secure context would take.
*/
function stubClipboard(impl: ((text: string) => Promise<void>) | undefined): string[] {
const written: string[] = [];
if (impl === undefined) {
Object.defineProperty(globalThis.navigator, 'clipboard', {
value: undefined,
configurable: true,
});
return written;
}
Object.defineProperty(globalThis.navigator, 'clipboard', {
value: {
writeText: async (text: string) => {
written.push(text);
await impl(text);
},
},
configurable: true,
});
return written;
}
afterEach(() => {
Reflect.deleteProperty(globalThis.navigator, 'clipboard');
vi.restoreAllMocks();
});
describe('copyToClipboard', () => {
it('writes the text and reports success', async () => {
const written = stubClipboard(async () => {});
expect(await copyToClipboard('https://example.com/')).toBe(true);
expect(written).toEqual(['https://example.com/']);
});
it('reports failure instead of throwing when the write rejects', async () => {
// The real one this guards: Chrome rejects with NotAllowedError
// ("Document is not focused") if the manager page lost focus between the
// click and the promise. The user gets a toast, not an unhandled rejection.
stubClipboard(async () => {
throw new DOMException('Document is not focused', 'NotAllowedError');
});
await expect(copyToClipboard('https://example.com/')).resolves.toBe(false);
});
it('reports failure when there is no clipboard API at all', async () => {
stubClipboard(undefined);
await expect(copyToClipboard('https://example.com/')).resolves.toBe(false);
});
it('never reads the clipboard', async () => {
// docs/09 T8 is explicit: write only. A readText call here would be a
// privacy regression that no other test would notice.
const readText = vi.fn();
Object.defineProperty(globalThis.navigator, 'clipboard', {
value: { writeText: async () => {}, readText },
configurable: true,
});
await copyToClipboard('https://example.com/');
expect(readText).not.toHaveBeenCalled();
});
});
+62
View File
@@ -0,0 +1,62 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { openBookmarkUrl } from '@/lib/browser/open-url';
/**
* The docs/09 T3 control: bookmark URLs come from someone's import file and are
* stored verbatim, so this allowlist is the only thing between a crafted
* `javascript:` bookmark and the browser acting on it. It had no test.
*/
let created: { url?: string }[] = [];
beforeEach(() => {
fakeBrowser.reset();
vi.restoreAllMocks();
created = [];
// fakeBrowser stubs tabs.* with "not implemented" throws.
vi.spyOn(fakeBrowser.tabs, 'create').mockImplementation(async (props) => {
created.push(props);
// SAFETY: the caller ignores the return value; only the recorded call
// matters, and building a full Tab here would assert nothing.
return {} as Awaited<ReturnType<typeof fakeBrowser.tabs.create>>;
});
});
describe('openBookmarkUrl', () => {
it.each([
'https://example.com/',
'http://example.com/path?q=1',
'https://example.com:8443/#frag',
])('opens %s', async (url) => {
expect(await openBookmarkUrl(url)).toBe(true);
expect(created).toEqual([{ url }]);
});
it.each([
['javascript:alert(1)', 'the classic bookmarklet payload'],
['data:text/html,<script>alert(1)</script>', 'inline document'],
['file:///etc/passwd', 'local file read'],
['chrome://settings', 'privileged browser page'],
['ftp://example.com/', 'not in the allowlist'],
['vbscript:msgbox(1)', 'legacy script scheme'],
])('refuses %s (%s)', async (url) => {
expect(await openBookmarkUrl(url)).toBe(false);
expect(created).toEqual([]);
});
it('refuses an unparseable URL without throwing', async () => {
for (const url of ['', 'not a url', '///', 'http://']) {
await expect(openBookmarkUrl(url)).resolves.toBe(false);
}
expect(created).toEqual([]);
});
it('is case-insensitive about the scheme, as the URL parser is', async () => {
// `new URL('JavaScript:…').protocol` normalizes to lowercase, so an
// attacker cannot dodge the allowlist by shouting.
expect(await openBookmarkUrl('JaVaScRiPt:alert(1)')).toBe(false);
expect(await openBookmarkUrl('HTTPS://example.com/')).toBe(true);
expect(created).toEqual([{ url: 'HTTPS://example.com/' }]);
});
});
+143
View File
@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import type { LiveNode } from '@/lib/browser/bookmarks';
import {
countDescendants,
extraCopyIds,
flattenTree,
isEditable,
resolveNewFolderParent,
toEditNode,
} from '@/lib/edit/edit-node';
import type { EditNode } from '@/lib/edit/patch-tree';
const BAR: EditNode = {
id: '1',
title: 'Bookmarks bar',
children: [
{
id: '10',
parentId: '1',
title: 'Docs',
children: [{ id: '11', parentId: '10', title: 'A', url: 'https://a.test/' }],
},
{ id: '12', parentId: '1', title: 'B', url: 'https://b.test/' },
],
};
const MANAGED: EditNode = { id: '2', title: 'Managed', unmodifiable: 'managed', children: [] };
const ROOTS: EditNode[] = [BAR, MANAGED];
describe('toEditNode', () => {
it('omits absent keys rather than setting them undefined', () => {
// exactOptionalPropertyTypes (docs/10 §2): an explicit undefined is a type
// error at every construction site, and `'url' in node` must stay reliable.
const live = { id: '5', title: 'Folder', children: [] } as LiveNode;
const node = toEditNode(live);
expect(Object.hasOwn(node, 'url')).toBe(false);
expect(Object.hasOwn(node, 'parentId')).toBe(false);
expect(Object.hasOwn(node, 'unmodifiable')).toBe(false);
});
it('gives folders children and bookmarks none, which is what folder tests rely on', () => {
const folder = toEditNode({ id: '5', title: 'F', children: [] } as LiveNode);
const link = toEditNode({ id: '6', title: 'L', url: 'https://x.test/' } as LiveNode);
expect(folder.children).toEqual([]);
expect(Object.hasOwn(link, 'children')).toBe(false);
});
it('recurses, preserving order', () => {
const live = {
id: '1',
title: 'root',
children: [
{ id: '2', parentId: '1', title: 'first', url: 'https://1.test/' },
{ id: '3', parentId: '1', title: 'second', children: [] },
],
} as LiveNode;
expect(toEditNode(live).children?.map((child) => child.id)).toEqual(['2', '3']);
});
it('carries unmodifiable through, since it gates every destructive affordance', () => {
const live = { id: '2', title: 'Managed', unmodifiable: 'managed', children: [] } as LiveNode;
expect(toEditNode(live).unmodifiable).toBe('managed');
});
});
describe('flattenTree', () => {
it('lists every node depth-first, parents before children', () => {
expect(flattenTree(ROOTS).map((node) => node.id)).toEqual(['1', '10', '11', '12', '2']);
});
it('handles an empty forest', () => {
expect(flattenTree([])).toEqual([]);
});
});
describe('isEditable', () => {
it('refuses the permanent roots', () => {
expect(isEditable(ROOTS, BAR)).toBe(false);
});
it('refuses policy-managed nodes', () => {
expect(isEditable(ROOTS, MANAGED)).toBe(false);
});
it('allows ordinary descendants', () => {
expect(isEditable(ROOTS, ROOTS[0]?.children?.[0] as EditNode)).toBe(true);
});
});
describe('resolveNewFolderParent', () => {
it('nests inside the focused folder', () => {
expect(resolveNewFolderParent(ROOTS, ROOTS[0]?.children?.[0])).toBe('10');
});
it('puts it beside a focused bookmark, not inside it', () => {
expect(resolveNewFolderParent(ROOTS, ROOTS[0]?.children?.[1])).toBe('1');
});
it('falls back to the first WRITABLE root when nothing is focused', () => {
// Using the focused node's parent unconditionally resolved a selected root
// to the synthetic root "0", which every create rejects.
expect(resolveNewFolderParent(ROOTS, undefined)).toBe('1');
expect(resolveNewFolderParent([MANAGED, BAR], undefined)).toBe('1');
});
it('returns undefined when every root is unmodifiable', () => {
expect(resolveNewFolderParent([MANAGED], undefined)).toBeUndefined();
});
it('treats a focused root as the target folder itself', () => {
expect(resolveNewFolderParent(ROOTS, BAR)).toBe('1');
});
it('falls back rather than targeting a focused UNMODIFIABLE folder', () => {
// A managed folder rejects every create, so returning its id made "New
// folder" silently do nothing whenever one happened to be selected.
expect(resolveNewFolderParent(ROOTS, MANAGED)).toBe('1');
});
});
describe('countDescendants', () => {
it('counts everything inside, at any depth', () => {
expect(countDescendants(BAR)).toBe(3);
});
it('is 0 for a bookmark and for nothing', () => {
expect(countDescendants(ROOTS[0]?.children?.[1])).toBe(0);
expect(countDescendants(undefined)).toBe(0);
});
});
describe('extraCopyIds', () => {
it('keeps the first of each group and names the rest', () => {
const groups = [
{ nodes: [{ id: 'a1' }, { id: 'a2' }, { id: 'a3' }] as EditNode[] },
{ nodes: [{ id: 'b1' }, { id: 'b2' }] as EditNode[] },
];
expect(extraCopyIds(groups)).toEqual(['a2', 'a3', 'b2']);
});
it('names nothing for a group of one', () => {
expect(extraCopyIds([{ nodes: [{ id: 'only' }] as EditNode[] }])).toEqual([]);
});
});
+10 -3
View File
@@ -70,9 +70,16 @@ describe('outbound links', () => {
]);
});
it('avoids linking a CHANGELOG.md that does not exist yet', () => {
// Phase 5 authors it; until then the releases page is the honest target.
expect(CHANGELOG_URL.endsWith('/releases')).toBe(true);
it('links a CHANGELOG.md that actually exists', () => {
// It pointed at /releases through Phase 4 because the file did not exist.
// Same check as the legal documents: a link from inside the product must
// not 404 because someone renamed or deleted the target.
expect(CHANGELOG_URL.endsWith('/blob/main/CHANGELOG.md')).toBe(true);
expect(existsSync(join(REPO_ROOT, 'CHANGELOG.md'))).toBe(true);
});
it('links a README the badges and install steps live in', () => {
expect(existsSync(join(REPO_ROOT, 'README.md'))).toBe(true);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* The permission list is the product's most load-bearing public claim: it is in
* the README, the privacy policy, the store listing's privacy tab, and
* CLAUDE.md's first hard rule. Until this file existed, nothing enforced it —
* a single added string in wxt.config.ts would have shipped silently.
*
* Read as text rather than imported, so the assertion cannot be satisfied by a
* value computed at build time; what ships is what is written here.
*/
const RAW = readFileSync(join(process.cwd(), 'wxt.config.ts'), 'utf8');
/**
* Comments stripped first. The file's own header says "No host_permissions, no
* content_scripts", so a naive substring check fails on the prose that promises
* the very thing it is checking.
*/
const CONFIG = RAW.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
/** Anything that widens the extension's reach beyond bookmarks + storage. */
const FORBIDDEN_KEYS = [
'host_permissions',
'optional_permissions',
'optional_host_permissions',
'content_scripts',
'web_accessible_resources',
'externally_connectable',
'content_security_policy',
'declarative_net_request',
'devtools_page',
'chrome_url_overrides',
];
describe('manifest', () => {
it('declares the permissions array exactly once', () => {
// Two arrays (e.g. a browser-specific override) would mean this file only
// ever checks the first, which might not be the one that ships.
expect(CONFIG.match(/(?<![a-z_])permissions:/gi)?.length ?? 0).toBe(1);
});
it('builds the permissions array from string literals only', () => {
// Without this, a spread, an identifier or a `.concat()` tail would be
// dropped by the literal-harvesting regex below and the assertion would
// still pass while extra permissions shipped.
const match = CONFIG.match(/permissions:\s*\[([^\]]*)\]/);
const residue = (match?.[1] ?? '').replace(/'[^']*'|"[^"]*"|[\s,]/g, '');
expect(residue, 'permissions array contains non-literal entries').toBe('');
});
it('requests exactly ["bookmarks", "storage"]', () => {
const match = CONFIG.match(/permissions:\s*\[([^\]]*)\]/);
expect(match?.[1], 'no permissions array found in wxt.config.ts').toBeDefined();
const requested = [...(match?.[1] ?? '').matchAll(/'([^']+)'|"([^"]+)"/g)].map(
(entry) => entry[1] ?? entry[2],
);
// Adding one is a minor-version event that also requires updating docs
// 08/09/13 and the store privacy tab (docs/09 §4). Update this list last.
expect(requested).toEqual(['bookmarks', 'storage']);
});
it.each(FORBIDDEN_KEYS)('declares no %s', (key) => {
expect(CONFIG).not.toContain(key);
});
it('declares no background service worker', () => {
// docs/15 decision log, 2026-07-03: no background worker in v1. One would
// also change the store review posture.
expect(CONFIG).not.toMatch(/\bbackground\s*:/);
});
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.
expect(CONFIG).not.toMatch(/manifest_version\s*:\s*2/);
});
it('still points default_locale at the three shipped dictionaries', () => {
expect(CONFIG).toMatch(/default_locale:\s*'en'/);
for (const locale of ['en', 'vi', 'ja']) {
const path = join(process.cwd(), 'src/public/_locales', locale, 'messages.json');
const messages: unknown = JSON.parse(readFileSync(path, 'utf8'));
expect(messages, `${locale}/messages.json`).toHaveProperty('appName');
expect(messages, `${locale}/messages.json`).toHaveProperty('appDesc');
}
});
});
+109
View File
@@ -0,0 +1,109 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
/**
* docs/06 §5 requires ≥ 4.5:1 contrast "in both themes (tokens chosen
* accordingly)". Nothing enforced that, and they were not: shipping code had
* white ink on the dark-theme accent at 3.67:1 and three status colours used as
* text between 3.26 and 4.27 in light theme.
*
* Parsing the stylesheet rather than hardcoding the palette is the point — the
* test fails when someone edits a colour, which is exactly when it matters.
*/
const TOKENS = readFileSync(join(process.cwd(), 'src/styles/tokens.css'), 'utf8');
const REQUIRED_RATIO = 4.5;
function blockOf(pattern: RegExp): Record<string, string> {
const match = TOKENS.match(pattern);
if (match?.[1] === undefined) throw new Error(`tokens.css: no block matching ${pattern}`);
const out: Record<string, string> = {};
for (const declaration of match[1].matchAll(/(--[a-z-]+):\s*(#[0-9a-f]{6})\b/gi)) {
const [, name, value] = declaration;
if (name !== undefined && value !== undefined) out[name] = value;
}
return out;
}
function relativeLuminance(hex: string): number {
const channels = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16) / 255);
const [r, g, b] = channels.map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
return 0.2126 * (r ?? 0) + 0.7152 * (g ?? 0) + 0.0722 * (b ?? 0);
}
function contrast(a: string, b: string): number {
const [lighter, darker] = [relativeLuminance(a), relativeLuminance(b)].sort((x, y) => y - x);
return ((lighter ?? 0) + 0.05) / ((darker ?? 0) + 0.05);
}
const light = blockOf(/:root\s*\{([\s\S]*?)\n\}/);
// The dark block overrides a subset; everything else inherits from :root.
const dark = { ...light, ...blockOf(/\[data-theme='dark'\]\s*\{([\s\S]*?)\n\}/) };
const darkMedia = {
...light,
...blockOf(/:root:not\(\[data-theme='light'\]\)\s*\{([\s\S]*?)\n\s{2}\}/),
};
/** [foreground, background] — every pair where the fg is rendered as TEXT. */
const TEXT_PAIRS: [fg: string, bg: string][] = [
['--fg', '--bg'],
['--fg', '--bg-raised'],
['--fg-muted', '--bg'],
['--fg-muted', '--bg-raised'],
// base.css colours every <a> with --accent, and rows/links sit on both.
['--accent', '--bg'],
['--accent', '--bg-raised'],
// Rendered as text: DuplicatePanel counts, TreePreviewNode badges,
// WarningList's summary, TreeRow's ⚠ unsafe-scheme marker. Checked against
// BOTH surfaces — a row sits on --bg until it is hovered or focused.
['--danger', '--bg-raised'],
['--danger', '--bg'],
['--success', '--bg-raised'],
['--success', '--bg'],
['--warn', '--bg-raised'],
['--warn', '--bg'],
// Ink on a filled control: Button .primary/.danger, ConfirmDialog .danger,
// ThemeToggle .selected.
['--accent-fg', '--accent'],
['--danger-fg', '--danger'],
];
const THEMES: [name: string, tokens: Record<string, string>][] = [
['light', light],
['dark (data-theme)', dark],
['dark (prefers-color-scheme)', darkMedia],
];
describe('token contrast', () => {
it.each(THEMES)('%s meets 4.5:1 on every text pair', (_name, tokens) => {
const failures: string[] = [];
for (const [fg, bg] of TEXT_PAIRS) {
const fgValue = tokens[fg];
const bgValue = tokens[bg];
if (fgValue === undefined || bgValue === undefined) {
failures.push(`${fg} or ${bg} is undefined in this theme`);
continue;
}
const ratio = contrast(fgValue, bgValue);
if (ratio < REQUIRED_RATIO) {
failures.push(`${fg} (${fgValue}) on ${bg} (${bgValue}) = ${ratio.toFixed(2)}:1`);
}
}
expect(failures).toEqual([]);
});
it('keeps the two dark blocks identical', () => {
// tokens.css carries the dark palette twice — once for the explicit
// override and once for prefers-color-scheme. They drifted once already:
// --accent-fg was added to one and not the other.
expect(darkMedia).toEqual(dark);
});
it('defines an explicit ink for every token used as a filled background', () => {
for (const pair of ['accent', 'danger']) {
expect(dark[`--${pair}-fg`], `--${pair}-fg missing from the dark block`).toBeDefined();
expect(light[`--${pair}-fg`], `--${pair}-fg missing from :root`).toBeDefined();
}
});
});