From 372741142eab549b8bff594ec66a678afd7abd27 Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Sun, 26 Jul 2026 12:57:56 +0700 Subject: [PATCH] feat(legal): the first-run Legal Gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/14 §1: the Chrome Web Store has no pre-install acceptance mechanism, so a first-run gate is what makes the terms reachable at all. Without it the extension cannot be submitted. acceptLegal writes, awaits, and flips to `accepted` ONLY once the write resolves. Getting this backwards is the exact defect shape the last three phase reviews kept finding: dismiss optimistically, await a chrome.* call that can reject, never handle the rejection. Here that would leave the user accepted in the UI and unaccepted on disk, so the gate would silently return next launch with no explanation. There is a test that rejects the write and asserts the gate stays up and storage stays empty. It fails CLOSED: an unreadable store gates. Showing the gate to someone who already accepted costs one click; skipping it for someone who has not is not recoverable. A stored version NEWER than LEGAL_VERSION still counts as accepted -- re-gating on a downgrade is noise, not consent. The gate fills the content region rather than covering the viewport. docs/06 §3 calls it "a full overlay", but docs/14 §2 -- echoed in docs/03 §4 and the docs/15 log -- requires #settings and #about to stay reachable while it is up, and a literal inset:0 scrim buries the footer links that get you there. The docs edit reconciling this follows in the docs commit. A side effect worth keeping: Import/Export/Edit never mount before acceptance, so nothing touches chrome.bookmarks until the user has agreed. "Close tab" does not bet the decline path on window.close(): the Manager is opened by tabs.create, so window.opener is null and close() may no-op. It waits 150 ms and says so plainly if the document is still there. tabs.remove is not an option -- that needs the `tabs` permission docs/08 §2 forbids. Also finally consumes TabBar's `blocked` prop, which has sat unused since Phase 2, and adds About's acceptance line -- showing the version the user ACCEPTED, not the current constant. Co-Authored-By: Claude Opus 5 --- src/entrypoints/manager/App.svelte | 29 ++++- src/entrypoints/manager/main.ts | 20 ++-- src/lib/components/AboutTab.svelte | 24 +++- src/lib/components/LegalGate.svelte | 173 ++++++++++++++++++++++++++++ src/lib/stores/legal.svelte.ts | 105 +++++++++++++++++ tests/unit/stores/legal.test.ts | 140 ++++++++++++++++++++++ 6 files changed, 478 insertions(+), 13 deletions(-) create mode 100644 src/lib/components/LegalGate.svelte create mode 100644 src/lib/stores/legal.svelte.ts create mode 100644 tests/unit/stores/legal.test.ts diff --git a/src/entrypoints/manager/App.svelte b/src/entrypoints/manager/App.svelte index d268b0e..a03baf3 100644 --- a/src/entrypoints/manager/App.svelte +++ b/src/entrypoints/manager/App.svelte @@ -6,6 +6,7 @@ import ExportTab from '@/lib/components/ExportTab.svelte'; import ImportTab from '@/lib/components/ImportTab.svelte'; import LanguageSwitcher from '@/lib/components/LanguageSwitcher.svelte'; + import LegalGate from '@/lib/components/LegalGate.svelte'; import SettingsTab from '@/lib/components/SettingsTab.svelte'; import TabBar from '@/lib/components/TabBar.svelte'; import ThemeToggle from '@/lib/components/ThemeToggle.svelte'; @@ -13,6 +14,12 @@ import { t } from '@/lib/i18n/index.svelte'; import { isWriting } from '@/lib/stores/import-session.svelte'; import { REPO_URL } from '@/lib/links'; + import { + getBlockedRoutes, + getLegalStatus, + isGatedRoute, + isGateRequired, + } from '@/lib/stores/legal.svelte'; import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte'; import { flushSettings, getSettings, updateSettings } from '@/lib/stores/settings.svelte'; import { pushToast } from '@/lib/stores/toast.svelte'; @@ -20,6 +27,10 @@ // Settings are loaded and awaited in main.ts, before this ever mounts. const settings = $derived(getSettings()); const version = getAppVersion(); + const legal = $derived(getLegalStatus()); + const gated = $derived(isGateRequired() && isGatedRoute(getRoute())); + + let mainEl: HTMLElement | undefined = $state(); onMount(() => { const stopRouting = startRouting(); @@ -61,15 +72,27 @@ {t('common.appName')} - +
save({ locale })} /> save({ theme })} />
-
- {#if getRoute() === 'import'} +
+ {#if gated && legal.kind === 'required'} + + mainEl?.focus()} /> + {:else if getRoute() === 'import'} {:else if getRoute() === 'export'} diff --git a/src/entrypoints/manager/main.ts b/src/entrypoints/manager/main.ts index 2bd15e1..3037819 100644 --- a/src/entrypoints/manager/main.ts +++ b/src/entrypoints/manager/main.ts @@ -1,4 +1,5 @@ import { mount } from 'svelte'; +import { loadLegal } from '@/lib/stores/legal.svelte'; import { loadSettings } from '@/lib/stores/settings.svelte'; import '@/styles/base.css'; import App from './App.svelte'; @@ -7,16 +8,17 @@ import App from './App.svelte'; // always exists by the time this module runs. const target = document.getElementById('app') as HTMLElement; -// Settings are read BEFORE the first render, on purpose. The alternative -- +// Both reads happen BEFORE the first render, on purpose. The alternative -- // mount, then hydrate -- paints one frame in the browser's UI language and the -// system theme, then flips to the persisted ones. Awaiting means that frame -// holds an empty #app instead: a blank moment rather than a visible EN->VI or -// light->dark flip for exactly the users who bothered to change the setting. +// system theme, then flips to the persisted ones, and flashes the legal gate at +// users who accepted it long ago. Awaiting means that frame holds an empty #app +// instead: a blank moment rather than visible EN->VI, light->dark or gate +// flicker. // -// readSettings never throws (browser/storage.ts) and applyLocale guards the -// i18n lookup, so this cannot leave the page unmounted. No timeout race: -// storage.local.get always settles, and racing it would just re-introduce the -// wrong-locale render this exists to prevent. -await loadSettings(); +// Neither loader can throw: readSettings and readLegal both swallow storage +// failures (browser/storage.ts) and applyLocale guards the i18n lookup. No +// timeout race either — storage.local.get always settles, and racing it would +// just re-introduce the wrong-locale render this exists to prevent. +await Promise.all([loadSettings(), loadLegal()]); export default mount(App, { target }); diff --git a/src/lib/components/AboutTab.svelte b/src/lib/components/AboutTab.svelte index 3c7bece..1e2668c 100644 --- a/src/lib/components/AboutTab.svelte +++ b/src/lib/components/AboutTab.svelte @@ -1,9 +1,16 @@
@@ -48,6 +55,21 @@ {/each}

{t('legal.englishNote')}

+

+ + {#if acceptance === undefined} + {t('about.notAccepted')} + {:else if acceptedOn === undefined} + {t('about.acceptedUndated', { version: acceptance.acceptedVersion })} + {:else} + {t('about.accepted', { + date: acceptedOn, + version: acceptance.acceptedVersion, + })} + {/if} +

diff --git a/src/lib/stores/legal.svelte.ts b/src/lib/stores/legal.svelte.ts new file mode 100644 index 0000000..61fdba8 --- /dev/null +++ b/src/lib/stores/legal.svelte.ts @@ -0,0 +1,105 @@ +/** + * First-run legal acceptance — docs/14 §2. + * + * Purpose: decide whether the gate is required, and record acceptance. + * Inputs: `chrome.storage.local` via `browser/storage.ts`. + * Guarantees: never throws and never rejects — a storage failure fails CLOSED + * (gate shown), and `acceptLegal` returns an outcome instead of rejecting. + * Acceptance is only reflected in state AFTER the write resolves. + */ +import { type LegalAcceptance, readLegal, writeLegal } from '../browser/storage'; +import { LEGAL_VERSION } from '../core/limits'; +import type { Route } from './route.svelte'; +import type { SaveOutcome } from './settings.svelte'; + +export type LegalStatus = + | { kind: 'loading' } + | { kind: 'accepted'; acceptance: LegalAcceptance } + | { kind: 'required'; reason: 'first-run' | 'updated' }; + +/** + * The three routes the gate blocks. + * + * Normative and stated identically in docs/03 §4, docs/14 §2 and the docs/15 + * decision log: `#settings` and `#about` stay reachable, `#about` so the linked + * documents can be read before accepting and `#settings` so a VI/JA user can + * switch language first — which is why the gate carries no switcher of its own. + */ +const GATED_ROUTES: readonly Route[] = Object.freeze(['import', 'export', 'edit']); +const UNGATED: readonly Route[] = Object.freeze([]); + +let status = $state({ kind: 'loading' }); + +/** + * Pure gate decision, so the rule is testable without touching storage. + * + * A stored version GREATER than the current one still counts as accepted: it + * means the user ran a newer build, and re-gating them on a downgrade would be + * noise, not consent. + */ +export function decideLegalStatus( + acceptance: LegalAcceptance | null, + currentVersion: number, +): LegalStatus { + if (acceptance === null) return { kind: 'required', reason: 'first-run' }; + if (acceptance.acceptedVersion < currentVersion) { + return { kind: 'required', reason: 'updated' }; + } + return { kind: 'accepted', acceptance }; +} + +export function getLegalStatus(): LegalStatus { + return status; +} + +export function isGateRequired(): boolean { + return status.kind === 'required'; +} + +export function getAcceptance(): LegalAcceptance | undefined { + return status.kind === 'accepted' ? status.acceptance : undefined; +} + +/** `[]` unless the gate is up. Never `undefined`, so the TabBar prop is simple. */ +export function getBlockedRoutes(): readonly Route[] { + return status.kind === 'required' ? GATED_ROUTES : UNGATED; +} + +export function isGatedRoute(route: Route): boolean { + return GATED_ROUTES.includes(route); +} + +/** + * Read the stored acceptance. Call once per page, before the first render. + * + * `readLegal` already swallows storage failures and returns null, so an + * unreadable store lands on `required`. That is the correct direction: showing + * the gate to someone who accepted is recoverable in one click; skipping it for + * someone who has not is not recoverable at all. + */ +export async function loadLegal(): Promise { + status = decideLegalStatus(await readLegal(), LEGAL_VERSION); +} + +/** + * Record acceptance. + * + * The ordering is the whole point: write, await, and flip to `accepted` ONLY + * once the write resolves. Dismissing optimistically would leave the user + * accepted in the UI and unaccepted on disk, so the gate would silently + * reappear on the next launch with no explanation. + * + * @param nowIso supplied by the caller so this module stays free of ambient + * time, matching the discipline `browser/storage.ts` set up. + */ +export async function acceptLegal(nowIso: string): Promise { + try { + await writeLegal(LEGAL_VERSION, nowIso); + } catch (err) { + // Returned, not thrown: a rejection here would need a .catch() at every + // call site, and one miss is an unhandled rejection with the gate stuck. + return { ok: false, ...(err instanceof Error && { detail: err.message }) }; + } + status = { kind: 'accepted', acceptance: { acceptedVersion: LEGAL_VERSION, acceptedAt: nowIso } }; + return { ok: true }; +} diff --git a/tests/unit/stores/legal.test.ts b/tests/unit/stores/legal.test.ts new file mode 100644 index 0000000..0f7723e --- /dev/null +++ b/tests/unit/stores/legal.test.ts @@ -0,0 +1,140 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fakeBrowser } from 'wxt/testing'; +import { LEGAL_VERSION } from '@/lib/core/limits'; +import { + acceptLegal, + decideLegalStatus, + getAcceptance, + getBlockedRoutes, + getLegalStatus, + isGatedRoute, + isGateRequired, + loadLegal, +} from '@/lib/stores/legal.svelte'; + +const ACCEPTED_AT = '2026-07-25T10:00:00.000Z'; + +beforeEach(() => { + fakeBrowser.reset(); + // reset() clears data but leaves spies, so a rejecting storage.local.set + // would otherwise leak into every later test in this file. + vi.restoreAllMocks(); +}); + +describe('decideLegalStatus', () => { + it('gates a fresh profile as first-run', () => { + expect(decideLegalStatus(null, 1)).toEqual({ kind: 'required', reason: 'first-run' }); + }); + + it('gates an older acceptance as an update', () => { + expect(decideLegalStatus({ acceptedVersion: 0, acceptedAt: ACCEPTED_AT }, 1)).toEqual({ + kind: 'required', + reason: 'updated', + }); + }); + + it('accepts a matching version', () => { + const acceptance = { acceptedVersion: 1, acceptedAt: ACCEPTED_AT }; + expect(decideLegalStatus(acceptance, 1)).toEqual({ kind: 'accepted', acceptance }); + }); + + it('accepts a version NEWER than the current one', () => { + // The user ran a newer build. Re-gating them on a downgrade would be noise, + // not consent. + const acceptance = { acceptedVersion: 2, acceptedAt: ACCEPTED_AT }; + expect(decideLegalStatus(acceptance, 1)).toEqual({ kind: 'accepted', acceptance }); + }); +}); + +describe('blocked routes', () => { + it('names exactly the three routes docs/14 §2 blocks', async () => { + await loadLegal(); + expect(isGateRequired()).toBe(true); + expect([...getBlockedRoutes()]).toEqual(['import', 'export', 'edit']); + }); + + it('leaves #settings and #about reachable', () => { + // Normative in docs/03 §4, docs/14 §2 and the docs/15 decision log: + // #about so the documents can be read first, #settings so a VI/JA user can + // switch language -- which is why the gate has no switcher of its own. + expect(isGatedRoute('settings')).toBe(false); + expect(isGatedRoute('about')).toBe(false); + expect(isGatedRoute('import')).toBe(true); + }); + + it('blocks nothing once accepted', async () => { + await fakeBrowser.storage.local.set({ + legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT }, + }); + await loadLegal(); + expect(isGateRequired()).toBe(false); + expect([...getBlockedRoutes()]).toEqual([]); + }); +}); + +describe('loadLegal', () => { + it('fails closed on a malformed record', async () => { + await fakeBrowser.storage.local.set({ legal: { acceptedVersion: 'yes' } }); + await loadLegal(); + expect(isGateRequired()).toBe(true); + }); + + it('fails closed, without throwing, when the read rejects', async () => { + vi.spyOn(fakeBrowser.storage.local, 'get').mockRejectedValue(new Error('storage disabled')); + await expect(loadLegal()).resolves.toBeUndefined(); + expect(getLegalStatus()).toEqual({ kind: 'required', reason: 'first-run' }); + }); + + it('exposes the stored acceptance for the About tab', async () => { + await fakeBrowser.storage.local.set({ + legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT }, + }); + await loadLegal(); + expect(getAcceptance()).toEqual({ acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT }); + }); +}); + +describe('acceptLegal', () => { + it('persists the version and timestamp, then unlocks', async () => { + await loadLegal(); + expect(await acceptLegal(ACCEPTED_AT)).toEqual({ ok: true }); + + const stored = await fakeBrowser.storage.local.get('legal'); + expect(stored.legal).toEqual({ acceptedVersion: LEGAL_VERSION, acceptedAt: ACCEPTED_AT }); + expect(isGateRequired()).toBe(false); + }); + + it('KEEPS THE GATE UP when the write rejects, and writes nothing', async () => { + // The flagship test of this phase. The recurring defect shape in this + // project is: dismiss optimistically, await a chrome.* call that can + // reject, never handle it. Here that would leave the user accepted in the + // UI and unaccepted on disk, with the gate silently back next launch. + await loadLegal(); + vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue( + new Error('QUOTA_BYTES quota exceeded'), + ); + + const outcome = await acceptLegal(ACCEPTED_AT); + expect(outcome.ok).toBe(false); + expect(outcome.detail).toContain('QUOTA_BYTES'); + expect(isGateRequired()).toBe(true); + expect(getAcceptance()).toBeUndefined(); + + const stored = await fakeBrowser.storage.local.get('legal'); + expect(stored.legal).toBeUndefined(); + }); + + it('never rejects, so no call site can leak an unhandled rejection', async () => { + vi.spyOn(fakeBrowser.storage.local, 'set').mockRejectedValue(new Error('nope')); + await expect(acceptLegal(ACCEPTED_AT)).resolves.toMatchObject({ ok: false }); + }); + + it('writes nothing at all when the user declines', async () => { + // docs/14 §2: "no nagging -- closing the tab is the decline. Nothing is + // written." Closing is a component action; the contract is that merely + // showing the gate never touches the legal key. + await loadLegal(); + const all = await fakeBrowser.storage.local.get(null); + expect(Object.keys(all)).not.toContain('legal'); + }); +});