An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(extension): blocked sites — a list of sites Browsentic will not read or act on, kept in this browser only and enforced in the extension before any tool runs, so neither the daemon nor the agent it spawns can see or loosen it (#53)
Shahriar00a459c8d6ea
diff --git a/src/extension/components/blocked-site-note.tsx b/src/extension/components/blocked-site-note.tsxnew file mode 100644index 0000000..527e527--- /dev/null+++ b/src/extension/components/blocked-site-note.tsx@@ -0,0 +1,26 @@+import { Ban } from 'lucide-react';+import { openBlockedSites } from '@/lib/bridge/use-extension-settings';++export const BLOCKED_HERE = 'This site is on your Blocked sites list, so Browsentic won’t read or act on it.';++export function BlockedSiteNote({ pattern }: { pattern: string }) {+ return (+ <div className="enters mb-2 flex items-start gap-2 rounded-xl border border-amber/30 bg-amber/8 px-3 py-2.5">+ <Ban className="mt-0.5 size-3.5 shrink-0 text-amber" />+ <div className="min-w-0 flex-1">+ <p className="text-xs font-medium text-ink">Browsentic is blocked on this site</p>+ <p className="mt-0.5 text-[11px] leading-relaxed text-ink-dim">+ It matches <span className="font-mono text-ink">{pattern}</span>, so nothing here is read or touched. The agent+ can still work in other tabs.+ </p>+ </div>+ <button+ type="button"+ className="shrink-0 text-[11px] font-medium text-brand hover:underline"+ onClick={openBlockedSites}+ >+ Manage+ </button>+ </div>+ );+}diff --git a/src/extension/components/blocked-sites-settings.tsx b/src/extension/components/blocked-sites-settings.tsxnew file mode 100644index 0000000..c528e45--- /dev/null+++ b/src/extension/components/blocked-sites-settings.tsx@@ -0,0 +1,265 @@+import { useMemo, useState, type FormEvent, type KeyboardEvent } from 'react';+import { Ban, Check, CircleCheck, Pencil, Plus, X } from 'lucide-react';++import { SettingsGroup } from '@/extension/components/extension-settings';+import { Button } from '@/extension/components/ui/button';+import { Input } from '@/extension/components/ui/input';+import { useBlockedSites } from '@/lib/bridge/use-extension-settings';+import {+ BLOCKED_SITES_LIMITS,+ blockedBy,+ compileBlockedSites,+ describePattern,+ parseBlockedPattern,+} from '@/lib/settings/blocked-sites';+import { cn } from '@/lib/utils';++const EXAMPLES: [pattern: string, blocks: string][] = [+ ['mybank.com', 'the whole site, every subdomain and every page'],+ ['mail.example.com', 'that subdomain and anything below it'],+ ['example.com/admin', '/admin and everything under it — not /administrator'],+ ['github.com/*/settings', '* stands for anything, slashes included'],+ ['shop.*', 'the same name on any domain ending'],+ ['localhost:3000', 'one port; with no port, every port'],+];++type Admitted = { ok: true; pattern: string } | { ok: false; reason: string };++function admit(entry: string, patterns: readonly string[], replacing?: number): Admitted {+ const parsed = parseBlockedPattern(entry);+ if (!parsed.ok) return parsed;+ const clash = patterns.findIndex((pattern, index) => index !== replacing && pattern === parsed.pattern);+ if (clash !== -1) return { ok: false, reason: `${parsed.pattern} is already on the list.` };+ if (replacing === undefined && patterns.length >= BLOCKED_SITES_LIMITS.entries) {+ return { ok: false, reason: `The list holds up to ${BLOCKED_SITES_LIMITS.entries} patterns.` };+ }+ return { ok: true, pattern: parsed.pattern };+}++export function BlockedSitesSettings() {+ const [patterns, setPatterns] = useBlockedSites();++ return (+ <div className="space-y-8">+ <SettingsGroup+ title="Blocked"+ note="Every page that matches is off-limits: nothing is read, clicked, typed, screenshotted, recorded or watched there, and its tabs never show up in the agent’s tab list."+ >+ <AddPattern patterns={patterns} onAdd={(pattern) => setPatterns([...patterns, pattern])} />+ {patterns.length ? (+ patterns.map((pattern, index) => (+ <PatternRow+ key={pattern}+ pattern={pattern}+ admit={(entry) => admit(entry, patterns, index)}+ onSave={(next) => setPatterns(patterns.map((existing, at) => (at === index ? next : existing)))}+ onRemove={() => setPatterns(patterns.filter((_, at) => at !== index))}+ />+ ))+ ) : (+ <p className="px-4 py-6 text-center text-sm text-ink-faint">Nothing is blocked yet.</p>+ )}+ </SettingsGroup>++ <SettingsGroup title="Check a page" note="Paste an address to see whether Browsentic would act on it.">+ <Tester patterns={patterns} />+ </SettingsGroup>++ <SettingsGroup title="Writing a pattern">+ <dl className="divide-y divide-line">+ {EXAMPLES.map(([pattern, blocks]) => (+ <div key={pattern} className="flex flex-wrap items-baseline gap-x-4 gap-y-0.5 px-4 py-2.5">+ <dt className="w-44 shrink-0 font-mono text-xs text-ink">{pattern}</dt>+ <dd className="min-w-0 flex-1 text-xs leading-relaxed text-ink-dim">{blocks}</dd>+ </div>+ ))}+ </dl>+ </SettingsGroup>++ <p className="text-xs leading-relaxed text-ink-faint">+ Kept in this browser only and checked inside the extension before any page action runs, whoever asked for it — a+ side-panel run, an MCP client, a schedule, an instant command or a saved tool. The daemon, the agent and the desktop+ app can neither read this list nor change it. A site’s IP address or another of its domains is a different site and+ needs its own pattern.+ </p>+ </div>+ );+}++function AddPattern({ patterns, onAdd }: { patterns: readonly string[]; onAdd: (pattern: string) => void }) {+ const [entry, setEntry] = useState('');+ const [reason, setReason] = useState<string | null>(null);++ function submit(event: FormEvent) {+ event.preventDefault();+ const admitted = admit(entry, patterns);+ if (!admitted.ok) {+ setReason(admitted.reason);+ return;+ }+ onAdd(admitted.pattern);+ setEntry('');+ setReason(null);+ }++ return (+ <form onSubmit={submit} className="space-y-1.5 px-4 py-3.5">+ <div className="flex items-center gap-2">+ <Input+ aria-label="Site or pattern to block"+ placeholder="mybank.com, example.com/admin, github.com/*/settings"+ className="font-mono text-xs"+ value={entry}+ maxLength={BLOCKED_SITES_LIMITS.length}+ spellCheck={false}+ autoCapitalize="off"+ aria-invalid={Boolean(reason)}+ onChange={(event) => {+ setEntry(event.target.value);+ setReason(null);+ }}+ />+ <Button type="submit" size="sm" disabled={!entry.trim()}>+ <Plus /> Block+ </Button>+ </div>+ {reason && <p className="text-xs text-destructive">{reason}</p>}+ </form>+ );+}++function PatternRow({+ pattern,+ admit: check,+ onSave,+ onRemove,+}: {+ pattern: string;+ admit: (entry: string) => Admitted;+ onSave: (pattern: string) => void;+ onRemove: () => void;+}) {+ const [draft, setDraft] = useState<string | null>(null);+ const [reason, setReason] = useState<string | null>(null);++ function save() {+ if (draft === null) return;+ const admitted = check(draft);+ if (!admitted.ok) {+ setReason(admitted.reason);+ return;+ }+ if (admitted.pattern !== pattern) onSave(admitted.pattern);+ setDraft(null);+ setReason(null);+ }++ function cancel() {+ setDraft(null);+ setReason(null);+ }++ function keys(event: KeyboardEvent<HTMLInputElement>) {+ if (event.key === 'Enter') {+ event.preventDefault();+ save();+ } else if (event.key === 'Escape') {+ cancel();+ }+ }++ if (draft !== null) {+ return (+ <div className="space-y-1.5 px-4 py-3">+ <div className="flex items-center gap-2">+ <Input+ aria-label={`Edit ${pattern}`}+ className="font-mono text-xs"+ value={draft}+ maxLength={BLOCKED_SITES_LIMITS.length}+ spellCheck={false}+ autoCapitalize="off"+ autoFocus+ aria-invalid={Boolean(reason)}+ onChange={(event) => {+ setDraft(event.target.value);+ setReason(null);+ }}+ onKeyDown={keys}+ />+ <Button type="button" variant="ghost" size="icon-sm" aria-label="Save" onClick={save}>+ <Check />+ </Button>+ <Button type="button" variant="ghost" size="icon-sm" aria-label="Cancel" onClick={cancel}>+ <X />+ </Button>+ </div>+ {reason && <p className="text-xs text-destructive">{reason}</p>}+ </div>+ );+ }++ return (+ <div className="flex items-center gap-3 px-4 py-2.5">+ <Ban className="size-3.5 shrink-0 text-amber" />+ <div className="min-w-0 flex-1">+ <p className="truncate font-mono text-xs text-ink">{pattern}</p>+ <p className="mt-0.5 truncate text-[11px] text-ink-faint">{describePattern(pattern)}</p>+ </div>+ <Button type="button" variant="ghost" size="icon-sm" aria-label={`Edit ${pattern}`} onClick={() => setDraft(pattern)}>+ <Pencil />+ </Button>+ <Button type="button" variant="ghost" size="icon-sm" aria-label={`Unblock ${pattern}`} onClick={onRemove}>+ <X />+ </Button>+ </div>+ );+}++function Tester({ patterns }: { patterns: readonly string[] }) {+ const [address, setAddress] = useState('');+ const compiled = useMemo(() => compileBlockedSites(patterns) ?? [], [patterns]);+ const url = asWebAddress(address);+ const match = url ? blockedBy(url, compiled) : null;++ return (+ <div className="space-y-2 px-4 py-3.5">+ <Input+ aria-label="Address to check"+ placeholder="https://www.example.com/admin/users"+ className="font-mono text-xs"+ value={address}+ spellCheck={false}+ autoCapitalize="off"+ onChange={(event) => setAddress(event.target.value)}+ />+ {address.trim() && (+ <p className={cn('flex items-center gap-1.5 text-xs', !url ? 'text-ink-faint' : match ? 'text-amber' : 'text-brand')}>+ {!url ? (+ 'That is not a web address.'+ ) : match ? (+ <>+ <Ban className="size-3.5" /> Blocked by <span className="font-mono">{match}</span>+ </>+ ) : (+ <>+ <CircleCheck className="size-3.5" /> Not blocked — Browsentic can act here.+ </>+ )}+ </p>+ )}+ </div>+ );+}++function asWebAddress(text: string): string | null {+ const trimmed = text.trim();+ if (!trimmed) return null;+ const candidate = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^[^/]+:\d/.test(trimmed) ? trimmed : `https://${trimmed}`;+ try {+ const parsed = new URL(candidate);+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : null;+ } catch {+ return null;+ }+}diff --git a/src/extension/entrypoints/background.ts b/src/extension/entrypoints/background.tsindex 8f2fc13..b0ec3bb 100644--- a/src/extension/entrypoints/background.ts+++ b/src/extension/entrypoints/background.ts@@ -72,12 +72,12 @@ export default defineBackground(() => {return;}if (message.op === 'recordEvents' && Array.isArray(message.events)) {- void appendEvents(sender.tab?.id, message.events);+ void appendEvents(sender.tab?.id, message.events, sender.url);sendResponse(success(true));return;}if (message.op === 'recordingState') {- recordingStateFor(sender.tab?.id)+ recordingStateFor(sender.tab?.id, sender.url).then((state) => sendResponse(success(state))).catch(() => sendResponse(success({ recording: false, captureValues: false })));return true;@@ -88,12 +88,12 @@ export default defineBackground(() => {return;}if (message.op === 'monitorSample' && typeof message.monitorId === 'string') {- void ingestSample(sender.tab?.id, message.monitorId, message.sample);+ void ingestSample(sender.tab?.id, message.monitorId, message.sample, sender.url);sendResponse(success(true));return;}if (message.op === 'monitorState') {- monitorsForTab(sender.tab?.id)+ monitorsForTab(sender.tab?.id, sender.url).then(sendResponse).catch(() => sendResponse(success({ monitors: [] })));return true;diff --git a/src/extension/entrypoints/options/App.tsx b/src/extension/entrypoints/options/App.tsxindex ba0b995..d53b9da 100644--- a/src/extension/entrypoints/options/App.tsx+++ b/src/extension/entrypoints/options/App.tsx@@ -1,8 +1,9 @@import { useEffect, useState, type ComponentType, type ReactNode } from 'react';-import { Link2, Puzzle, ShieldCheck, Sparkles, UserRound, type LucideIcon } from 'lucide-react';+import { Ban, Link2, Puzzle, ShieldCheck, Sparkles, UserRound, type LucideIcon } from 'lucide-react';import { browser } from 'wxt/browser';import { AgentPicker } from '@/extension/components/agent-picker';+import { BlockedSitesSettings } from '@/extension/components/blocked-sites-settings';import { Wordmark } from '@/extension/components/brand';import { DaemonLink } from '@/extension/components/daemon-link';import { ExtensionSettings, SettingsGroup } from '@/extension/components/extension-settings';@@ -14,7 +15,7 @@ import { useDaemonState } from '@/lib/bridge/use-daemon-state';import { useTheme } from '@/lib/bridge/use-theme';import { cn } from '@/lib/utils';-type SectionId = 'extension' | 'profile' | 'guardrails' | 'agent' | 'connection';+type SectionId = 'extension' | 'profile' | 'guardrails' | 'blocked' | 'agent' | 'connection';const SECTIONS: { id: SectionId; label: string; icon: LucideIcon; blurb: string; View: ComponentType }[] = [{@@ -38,6 +39,13 @@ const SECTIONS: { id: SectionId; label: string; icon: LucideIcon; blurb: string;blurb: 'What the agent may do without asking you first. A run takes its policy when it starts, so a change applies to the next one. The desktop app’s Settings tab edits the same rows.',View: GuardrailSettings,},+ {+ id: 'blocked',+ label: 'Blocked sites',+ icon: Ban,+ blurb: 'Sites Browsentic will never read or act on — no agent, schedule or saved tool can override it. Kept in this browser only; the daemon, the agent and the desktop app cannot see or change it.',+ View: BlockedSitesSettings,+ },{id: 'agent',label: 'Agent',diff --git a/src/extension/entrypoints/sidepanel/App.tsx b/src/extension/entrypoints/sidepanel/App.tsxindex a850a18..b42cb52 100644--- a/src/extension/entrypoints/sidepanel/App.tsx+++ b/src/extension/entrypoints/sidepanel/App.tsx@@ -8,6 +8,7 @@ import { getPageInfo } from '@/lib/actions/page/get-page-info';import { BRIDGE_CHANNEL, type FocusedElement } from '@/lib/actions/protocol';import { MAX_STORED_FILE_BYTES } from '@/lib/files/report';import { Wordmark } from '@/extension/components/brand';+import { BLOCKED_HERE, BlockedSiteNote } from '@/extension/components/blocked-site-note';import { Composer, type AttachedSkill } from '@/extension/components/composer';import { ConnectionSheet } from '@/extension/components/connection-sheet';import { DetachVeil } from '@/extension/components/detach-veil';@@ -33,6 +34,7 @@ import { putBytes } from '@/lib/bridge/file-store';import { removeRecording, type StoredRecordingMeta } from '@/lib/bridge/recording-store';import { removeSession } from '@/lib/bridge/session-store';import { useActiveTabUrl } from '@/lib/bridge/use-active-tab-url';+import { useBlockedPattern } from '@/lib/bridge/use-extension-settings';import { useDaemonState } from '@/lib/bridge/use-daemon-state';import { useFileDrop } from '@/lib/bridge/use-file-drop';import { closeSidePanel } from '@/lib/bridge/side-panel';@@ -69,6 +71,7 @@ export default function App() {const [scheduling, setScheduling] = useState(false);const takeSeed = useCallback(() => setTaskSeed(null), []);const tabUrl = useActiveTabUrl();+ const blockedHere = useBlockedPattern(tabUrl);const [attachError, setAttachError] = useState<string | null>(null);const [attachedSkill, setAttachedSkill] = useState<AttachedSkill | null>(null);const [focus, setFocus] = useState<FocusedElement | null>(null);@@ -222,6 +225,10 @@ export default function App() {async function pointAtElement() {if (picking) return;+ if (blockedHere) {+ setAttachError(BLOCKED_HERE);+ return;+ }setAttachError(null);setPicking(true);const outcome = await pickFocus();@@ -231,6 +238,10 @@ export default function App() {}async function attachPageContext() {+ if (blockedHere) {+ setAttachError(BLOCKED_HERE);+ return;+ }const result = await invokeInActiveTab(getPageInfo, {});if (!result.ok) {voice.setInput(`${voice.input}\n[couldn’t read this page: ${result.error.message}]\n`);@@ -453,6 +464,7 @@ export default function App() {{tab === 'chat' && (<footer className="shrink-0 border-t border-line p-3">+ {blockedHere && <BlockedSiteNote pattern={blockedHere} />}{run.toolOffer && (<KeepToolPromptoffer={run.toolOffer}diff --git a/src/lib/actions/host.test.ts b/src/lib/actions/host.test.tsnew file mode 100644index 0000000..d104cc3--- /dev/null+++ b/src/lib/actions/host.test.ts@@ -0,0 +1,37 @@+import { afterEach, beforeEach, expect, test, vi } from 'vitest';+import { fakeBrowser } from 'wxt/testing';+import { BLOCKED_SITES_KEY, SITE_BLOCKED } from '@/lib/settings/blocked-sites';+import { exposeActions } from './host';+import { ACTION_CHANNEL, type ActionResult } from './protocol';++type Listener = (message: unknown, sender: unknown, reply: (result: ActionResult) => void) => unknown;++let listener: Listener;++function ask(action: string): Promise<ActionResult> {+ return new Promise((resolve) => listener({ channel: ACTION_CHANNEL, action, input: {} }, {}, resolve));+}++beforeEach(async () => {+ fakeBrowser.reset();+ await fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: ['mybank.com'] });+ vi.spyOn(fakeBrowser.runtime.onMessage, 'addListener').mockImplementation((added) => {+ listener = added as Listener;+ });+ exposeActions();+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++test('a page on a blocked site refuses on its own, whatever the background decided', async () => {+ vi.stubGlobal('location', new URL('https://secure.mybank.com/accounts'));+ expect(await ask('page.extractText')).toMatchObject({ ok: false, error: { code: SITE_BLOCKED } });+});++test('any other page hands the action on as before', async () => {+ vi.stubGlobal('location', new URL('https://example.com/'));+ expect(await ask('page.noSuchAction')).toMatchObject({ ok: false, error: { code: 'UNKNOWN_ACTION' } });+});diff --git a/src/lib/actions/host.ts b/src/lib/actions/host.tsindex e57e585..1e8aac9 100644--- a/src/lib/actions/host.ts+++ b/src/lib/actions/host.ts@@ -1,11 +1,17 @@import { browser } from 'wxt/browser';+import { refusalFor } from '@/lib/bridge/site-guard';import { dispatch } from './dispatch';-import { isActionInvocation } from './protocol';+import { isActionInvocation, type ActionInvocation, type ActionResult } from './protocol';export function exposeActions() {browser.runtime.onMessage.addListener((message, _sender, sendResponse) => {if (!isActionInvocation(message)) return;- void dispatch(message.action, message.input).then(sendResponse);+ void answer(message).then(sendResponse);return true;});}++/** The page's own word on where it is, checked again whatever the background already decided. */+async function answer({ action, input }: ActionInvocation): Promise<ActionResult> {+ return (await refusalFor(location.href)) ?? dispatch(action, input);+}diff --git a/src/lib/bridge/auto-run.test.ts b/src/lib/bridge/auto-run.test.tsindex 80dbf06..2195536 100644--- a/src/lib/bridge/auto-run.test.ts+++ b/src/lib/bridge/auto-run.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';import type { Browser } from 'wxt/browser';import { fakeBrowser } from 'wxt/testing';+import { BLOCKED_SITES_KEY, blockedBy, compileBlockedSites, patternsFor } from '@/lib/settings/blocked-sites';import { autoRunSource, QUIET_MS, SETTLE_CAP_MS, syncAutoRuns } from './auto-run';import { saveTool, scopeMatches, type SavedTool } from './saved-tools';@@ -32,7 +33,7 @@ interface FakePage {load: () => void;}-function openPage(url: string, saved: SavedTool = tool(), readyState = 'complete'): FakePage {+function openPage(url: string, saved: SavedTool = tool(), readyState = 'complete', blocked: string[] = []): FakePage {const location = new URL(url);const document = { readyState, documentElement: {} };const marks: string[] = [];@@ -57,7 +58,7 @@ function openPage(url: string, saved: SavedTool = tool(), readyState = 'complete}const console = { warn: (...args: unknown[]) => warnings.push(args) };- new Function('location', 'document', 'window', 'MutationObserver', 'console', autoRunSource(saved))(+ new Function('location', 'document', 'window', 'MutationObserver', 'console', autoRunSource(saved, blocked))(location,document,window,@@ -178,6 +179,46 @@ describe('the script Chrome injects', () => {});});+describe('a blocked path on the tool’s own site', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ const sourcesFor = (patterns: string[], origin = 'https://www.youtube.com') =>+ patternsFor(origin, compileBlockedSites(patterns)!).map(({ source }) => source);++ test('is skipped on arrival and on a single-page move onto it', async () => {+ const blocked = sourcesFor(['youtube.com/watch?v=secret']);+ const page = openPage('https://www.youtube.com/watch?v=secret', tool(), 'complete', blocked);+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks).toEqual([]);++ page.go('https://www.youtube.com/watch?v=a');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ page.go('https://www.youtube.com/results');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ page.go('https://www.youtube.com/watch?v=secret&t=1');+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks).toEqual(['https://www.youtube.com/watch?v=a']);+ });++ test('only the patterns that could match the tool’s site travel with it', () => {+ expect(sourcesFor(['mybank.com', 'youtube.com/watch?v=secret', 'www.youtube.com:8443'])).toHaveLength(1);+ });++ test.each([+ 'https://www.youtube.com/watch?v=secret',+ 'https://www.youtube.com/watch/%73ecret',+ 'https://www.youtube.com//watch/secret',+ 'https://www.youtube.com/watch?v=open',+ 'https://www.youtube.com/watch/secrets',+ ])('the page decides %s the way the extension does', async (url) => {+ const patterns = ['youtube.com/watch?v=secret', 'youtube.com/watch/secret'];+ const page = openPage(url, tool(), 'complete', sourcesFor(patterns));+ await vi.advanceTimersByTimeAsync(QUIET_MS);+ expect(page.marks.length === 0).toBe(blockedBy(url, compileBlockedSites(patterns)!) !== null);+ });+});+function stubUserScripts(registered: UserScript[] = []) {const scripts = new Map(registered.map((script) => [script.id, script]));const api = {@@ -237,6 +278,26 @@ describe('keeping Chrome in step with the saved list', () => {expect(scripts.get('browsentic-tool-t1')?.js?.[0]?.code).toContain('tools.mark = () => 2;');});+ test('never registers a tool whose whole site is blocked, and brings it back once unblocked', async () => {+ const { scripts } = stubUserScripts();+ await saveTool(tool());+ await fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: ['youtube.com'] });+ await syncAutoRuns();+ expect(scripts.size).toBe(0);++ await fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: ['youtube.com/watch?v=secret'] });+ await syncAutoRuns();+ expect(scripts.get('browsentic-tool-t1')?.js?.[0]?.code).toContain('watch\\\\?v=secret');+ });++ test('registers nothing while the blocked list cannot be read', async () => {+ const { scripts } = stubUserScripts();+ await saveTool(tool());+ await fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: 'youtube.com' });+ await syncAutoRuns();+ expect(scripts.size).toBe(0);+ });+test('leaves scripts it did not register alone', async () => {const { scripts } = stubUserScripts([{ id: 'someone-else', matches: ['https://a.test/*'], js: [{ code: '' }] }]);await syncAutoRuns();diff --git a/src/lib/bridge/auto-run.ts b/src/lib/bridge/auto-run.tsindex 91dee64..ac4f902 100644--- a/src/lib/bridge/auto-run.ts+++ b/src/lib/bridge/auto-run.ts@@ -1,6 +1,8 @@import { browser, type Browser } from 'wxt/browser';+import { blockedBy, patternsFor } from '@/lib/settings/blocked-sites';import { MAX_SLUG, ROOT_SEGMENT } from '@/lib/skills/saved-tool';import { listSavedTools, onSavedToolsChange, type SavedTool } from './saved-tools';+import { onBlockedSitesChange, readBlockedSites } from './site-guard';const SCRIPT_PREFIX = 'browsentic-tool-';@@ -33,6 +35,7 @@ export function openUserScriptSettings(): void {export function serveAutoRuns(): void {if (import.meta.env.FIREFOX) return;onSavedToolsChange(() => void syncAutoRuns());+ onBlockedSitesChange(() => void syncAutoRuns());browser.alarms.create(SYNC_ALARM, { periodInMinutes: 1 });browser.alarms.onAlarm.addListener((alarm) => {if (alarm.name === SYNC_ALARM) void syncAutoRuns();@@ -49,8 +52,15 @@ export function syncAutoRuns(): Promise<void> {async function reconcile(): Promise<void> {if (import.meta.env.FIREFOX || !autoRunReady()) return;+ const blocked = await readBlockedSites();+ const runnable = blocked+ ? (await listSavedTools()).filter((tool) => tool.autoRun && !blockedBy(`${tool.origin}/`, blocked))+ : [];const wanted = new Map(- (await listSavedTools()).filter((tool) => tool.autoRun).map((tool) => [scriptIdOf(tool), scriptFor(tool)]),+ runnable.map((tool) => [+ scriptIdOf(tool),+ scriptFor(tool, patternsFor(tool.origin, blocked ?? []).map(({ source }) => source)),+ ]),);const ours = (await browser.userScripts.getScripts()).filter((script) => script.id.startsWith(SCRIPT_PREFIX));const current = new Set(ours.filter((script) => sameScript(script, wanted.get(script.id))).map((script) => script.id));@@ -66,11 +76,11 @@ function scriptIdOf(tool: SavedTool): string {return `${SCRIPT_PREFIX}${tool.id}`;}-function scriptFor(tool: SavedTool): UserScript {+function scriptFor(tool: SavedTool, blocked: readonly string[]): UserScript {return {id: scriptIdOf(tool),matches: [hostPattern(tool.origin)],- js: [{ code: autoRunSource(tool) }],+ js: [{ code: autoRunSource(tool, blocked) }],runAt: 'document_idle',world: 'MAIN',};@@ -91,17 +101,33 @@ function sameScript(registered: UserScript, wanted: UserScript | undefined): boo);}-export function autoRunSource(tool: AutoRunTool): string {+/**+ * A tool whose whole site is blocked is never registered. A path-level block can only be+ * honoured by the page itself, so the patterns for this origin travel with the script —+ * best-effort, since page code shares the world it runs in.+ */+export function autoRunSource(tool: AutoRunTool, blocked: readonly string[] = []): string {return `(() => {const origin = ${JSON.stringify(tool.origin)};const segment = ${JSON.stringify(tool.scope.segment)};const entry = ${JSON.stringify(tool.fn)};const label = ${JSON.stringify(tool.name)};+ const blocked = ${JSON.stringify(blocked)}.map((source) => new RegExp(source, 'i'));const slug = (text) =>text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, ${MAX_SLUG}).replace(/-+$/, '');+ const spelled = (escape, hex) => {+ const char = String.fromCharCode(parseInt(hex, 16));+ return /[a-z0-9._~-]/i.test(char) ? char : escape;+ };+ const here = () =>+ location.hostname.replace(/\\.+$/, '') ++ (location.port ? ':' + location.port : '') ++ location.pathname.replace(/%([0-9a-f]{2})/gi, spelled).replace(/\\/{2,}/g, '/') ++ location.search;const inScope = () => {if (location.origin !== origin) return false;+ if (blocked.some((rule) => rule.test(here()))) return false;const [first = ''] = location.pathname.split('/').filter(Boolean);return (slug(first) || ${JSON.stringify(ROOT_SEGMENT)}) === segment;};diff --git a/src/lib/bridge/blocked-follow-through.test.ts b/src/lib/bridge/blocked-follow-through.test.tsnew file mode 100644index 0000000..ff29d52--- /dev/null+++ b/src/lib/bridge/blocked-follow-through.test.ts@@ -0,0 +1,82 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { fakeBrowser } from 'wxt/testing';+import { BLOCKED_SITES_KEY, SITE_BLOCKED } from '@/lib/settings/blocked-sites';+import { completedMonitorStates, monitorsForTab, serveMonitor, startTabMonitor } from './monitor';+import { appendEvents, currentRecording, recordingStateFor, serveRecorder, startRecording } from './recorder';++const block = (...patterns: string[]) => fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: patterns });++const tabOn = async (url: string) => (await fakeBrowser.tabs.create({ url, active: true })).id!;++const settle = () => new Promise((resolve) => setTimeout(resolve, 20));++beforeEach(() => {+ fakeBrowser.reset();+ vi.spyOn(fakeBrowser.tabs, 'sendMessage').mockResolvedValue(undefined as never);+ vi.spyOn(fakeBrowser.runtime, 'getManifest').mockReturnValue({ content_scripts: [] } as never);+ Object.assign(fakeBrowser, { notifications: { create: vi.fn(async () => ''), clear: vi.fn(), onClicked: { addListener: vi.fn() } } });+});++afterEach(() => vi.restoreAllMocks());++describe('a monitor', () => {+ const until = { kind: 'text-matches' as const, pattern: 'Done', threshold: 1 };++ test('ends when its tab moves onto a blocked site, without naming where it went', async () => {+ serveMonitor();+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/upload');+ expect(await startTabMonitor({ until, timeoutMs: 60_000 }, tabId)).toMatchObject({ ok: true });++ await fakeBrowser.tabs.update(tabId, { url: 'https://mybank.com/statement' });+ await settle();++ const [ended] = await completedMonitorStates();+ expect(ended).toMatchObject({ phase: 'tab-navigated' });+ expect(JSON.stringify(ended)).not.toContain('mybank');+ });++ test('ends when the site it watches is blocked while it runs', async () => {+ serveMonitor();+ const tabId = await tabOn('https://example.com/upload');+ await startTabMonitor({ until, timeoutMs: 60_000 }, tabId);+ await block('example.com');+ await settle();+ expect(await completedMonitorStates()).toMatchObject([{ phase: 'tab-navigated' }]);+ });++ test('a page on a blocked site is told there is nothing to watch', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/upload');+ await startTabMonitor({ until, timeoutMs: 60_000 }, tabId);+ expect(await monitorsForTab(tabId, 'https://mybank.com/')).toMatchObject({ ok: true, data: { monitors: [] } });+ expect(await monitorsForTab(tabId, 'https://example.com/upload')).toMatchObject({ ok: true, data: { monitors: [{}] } });+ });+});++describe('a recording', () => {+ test('cannot start on a blocked site', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://mybank.com/');+ expect(await startRecording({ tabId, url: 'https://mybank.com/', captureValues: false })).toMatchObject({+ ok: false,+ error: { code: SITE_BLOCKED },+ });+ expect(await currentRecording()).toBeNull();+ });++ test('stops before a blocked page is written into it, and ignores what that page sends', async () => {+ serveRecorder();+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ await startRecording({ tabId, url: 'https://example.com/', captureValues: false });++ await appendEvents(tabId, [{ t: 1, kind: 'navigate', url: 'https://example.com/elsewhere' }], 'https://mybank.com/');+ expect((await currentRecording())?.events).toBe(1);+ expect(await recordingStateFor(tabId, 'https://mybank.com/')).toEqual({ recording: false, captureValues: false });++ await fakeBrowser.tabs.update(tabId, { url: 'https://mybank.com/login' });+ await settle();+ expect(await currentRecording()).toBeNull();+ });+});diff --git a/src/lib/bridge/code-toolkit.ts b/src/lib/bridge/code-toolkit.tsindex b924148..0e4f289 100644--- a/src/lib/bridge/code-toolkit.ts+++ b/src/lib/bridge/code-toolkit.ts@@ -20,6 +20,7 @@ import { scopeOf, slugFromPurpose } from '@/lib/skills/saved-tool';import { send, withDebugger } from './cdp';import { mainWorldOf, type FrameContext } from './frame-context';import { getSavedTool, scopeMatches } from './saved-tools';+import { refusalForTab } from './site-guard';const TOOLKITS_KEY = 'browsentic/codeToolkits';@@ -171,9 +172,12 @@ function offerToKeep(toolkit: StoredToolkit, url: string | undefined, called: st/*** The `/` path. No guardrail runs here and none should: this code was read and approved* when it was saved, the user asked for it by name just now, and the daemon is not in the- * loop at all — which is also what keeps it out of reach of an MCP client.+ * loop at all — which is also what keeps it out of reach of an MCP client. Blocked sites+ * are the exception: they bind the user's own tools too.*/export async function runSavedTool(tabId: number, url: string | undefined, toolId: string): Promise<ActionResult> {+ const refused = await refusalForTab(tabId);+ if (refused) return refused;const tool = await getSavedTool(toolId);if (!tool) return failure('UNKNOWN_TOOL', 'That tool is no longer saved.');if (!scopeMatches(tool, url)) {diff --git a/src/lib/bridge/diagnostics.ts b/src/lib/bridge/diagnostics.tsindex f6c80cf..606c057 100644--- a/src/lib/bridge/diagnostics.ts+++ b/src/lib/bridge/diagnostics.ts@@ -55,10 +55,14 @@ import {} from '@/lib/diagnostics/events';import { hostOf } from '@/lib/recordings/events';import { attachToTab, detachFromTab, onDebuggerEvent, send, serveDetachEvents, settle } from './cdp';+import { onBlockedSitesChange, refusalFor, siteBlocked, tabUrls } from './site-guard';import { watchForLoad } from './tabs';const DIAGNOSTICS_KEY = 'browsentic/diagnostics';+const MOVED_TO_BLOCKED =+ 'Stopped because the tab moved to a site on the Blocked sites list. Everything it had collected was discarded with it.';+const MAX_HEADERS = 30;const MAX_HEADER_CHARS = 400;@@ -119,6 +123,8 @@ export async function startTabDiagnostics(if (!/^https?:/i.test(tab.url)) {return failure('UNSUPPORTED', 'Only http(s) pages report a console and network activity — browser pages do not.');}+ const refused = await refusalFor(...tabUrls(tab));+ if (refused) return refused;if (!input.capture.length) {return failure('INVALID_INPUT', 'Give "capture" at least one of "console" or "network" — there is nothing to record otherwise.');}@@ -209,6 +215,7 @@ export async function readConsoleFor(input: {const picked = await pick(input.diagnosticsId);if (!picked.ok) return picked;const session = picked.data as DiagnosticsSession;+ await stopIfOnBlockedSite(session);const needle = input.contains?.toLowerCase();const matched = session.console.filter(@@ -249,6 +256,7 @@ export async function readNetworkFor(input: {const picked = await pick(input.diagnosticsId);if (!picked.ok) return picked;const session = picked.data as DiagnosticsSession;+ await stopIfOnBlockedSite(session);const needle = input.urlContains?.toLowerCase();const method = input.method?.toUpperCase();@@ -466,6 +474,32 @@ export function serveDiagnostics(): void {});browser.tabs.onRemoved.addListener((tabId) => void dropDiagnosticsForTab(tabId));++ browser.tabs.onUpdated.addListener((tabId, change) => {+ if (!change.url) return;+ void siteBlocked(change.url).then((blocked) => (blocked ? discardForTab(tabId) : undefined));+ });++ onBlockedSitesChange(() => {+ void store().then(async (map) => {+ for (const session of watching(map)) await stopIfOnBlockedSite(session);+ });+ });+}++/** The blocked page's own requests arrive before the tab reports its new address, so nothing collected is kept. */+async function discardForTab(tabId: number): Promise<void> {+ const session = forTab(await store(), tabId);+ if (!session) return;+ session.console = [];+ session.network = [];+ await finish(session.diagnosticsId, 'stopped', MOVED_TO_BLOCKED);+}++async function stopIfOnBlockedSite(session: DiagnosticsSession): Promise<void> {+ if (session.phase !== 'watching') return;+ const tab = await browser.tabs.get(session.tabId).catch(() => null);+ if (await siteBlocked(...tabUrls(tab))) await discardForTab(session.tabId);}function receive(tabId: number, method: string, params: Record<string, unknown>): void {diff --git a/src/lib/bridge/fast-path.ts b/src/lib/bridge/fast-path.tsindex 99b573f..da6dcf9 100644--- a/src/lib/bridge/fast-path.ts+++ b/src/lib/bridge/fast-path.ts@@ -3,6 +3,7 @@ import { routeIntent } from '@/lib/intent';import { START_RECORDING_ACTION, STOP_RECORDING_ACTION } from '@/lib/recordings/events';import { invokeForHarness } from './invoke';import { startActiveTabRecording, stopRecording } from './recorder';+import { isBlockedRefusal } from './site-guard';export async function tryFastPath(text: string,@@ -27,7 +28,7 @@ export async function tryFastPath(});if (!result.ok) {- if (isRecordingAction(action)) return true;+ if (isRecordingAction(action) || isBlockedRefusal(result)) return true;console.debug(`[browsentic] fast path ${ruleId} (${score}) failed, escalating:`, result.error.code);return false;}diff --git a/src/lib/bridge/frames.ts b/src/lib/bridge/frames.tsindex 7b4480d..e618eb9 100644--- a/src/lib/bridge/frames.ts+++ b/src/lib/bridge/frames.ts@@ -3,6 +3,7 @@ import { injectContentScript, invokeInTab } from '@/lib/actions/client';import { switchFrame } from '@/lib/actions/page/switch-frame';import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { describeFrame, framePath, setFramePath, TOP_FRAME, type FrameStep } from './frame-focus';+import { refusalFor } from './site-guard';interface EnteredFrame {frameId: number;@@ -39,6 +40,9 @@ export async function switchFrameInTab(tabId: number, topUrl: string | undefined);}+ const refused = await refusalFor(reached.url);+ if (refused) return refused;+const next = [...path, { frameId: entered.frameId, url: reached.url, selector: entered.selector }];await setFramePath(tabId, next);return success({ entered: planned.data, ...focusOf(next, topUrl) });diff --git a/src/lib/bridge/invoke.ts b/src/lib/bridge/invoke.tsindex 5d65c6a..c7661b0 100644--- a/src/lib/bridge/invoke.ts+++ b/src/lib/bridge/invoke.ts@@ -42,7 +42,8 @@ import { findCaptchaInTab, solveCaptchaInTab } from '@/lib/bridge/captcha';import { installToolkit, runToolkit } from '@/lib/bridge/code-toolkit';import { callSiteToolInTab, listSiteToolsInTab, pageInfoWithSiteTools } from '@/lib/bridge/site-tools';import { captureFromPage } from '@/lib/bridge/downloads';-import { focusedUrl, forgetFrameFocus, TOP_FRAME } from '@/lib/bridge/frame-focus';+import { focusedUrl, forgetFrameFocus, framePath, TOP_FRAME } from '@/lib/bridge/frame-focus';+import { blockedRefusal, refusalFor, refusalForTab, siteCheck, tabUrls } from '@/lib/bridge/site-guard';import { switchFrameInTab } from '@/lib/bridge/frames';import { listMeta, readBytes } from '@/lib/bridge/file-store';import {@@ -53,7 +54,7 @@ import {} from '@/lib/bridge/diagnostics';import { awaitMonitorDone, monitorStatusFor, startTabMonitor, stopTabMonitor } from '@/lib/bridge/monitor';import { startJobTimer, stopJobTimer, timerStatusFor } from '@/lib/bridge/timer';-import { listRecordings as listStoredMeta, readRecordingBody } from '@/lib/bridge/recording-store';+import { listRecordings as listStoredMeta, readRecordingBody, recordedOnBlockedSite } from '@/lib/bridge/recording-store';import { pickInTab } from '@/lib/bridge/pick';import { screenshotTab } from '@/lib/bridge/screenshot';import { dragInTab, trustedClickInTab } from '@/lib/bridge/trusted-input';@@ -74,15 +75,116 @@ export async function invokeForHarness(tabId?: number,runId?: string,): Promise<ActionResult> {+ const refused = await guardTarget(action, input, tabId, runId);+ if (refused) return refused;+const release = await releaseForAction(action, input);if (release.refused.length) return failure('SECRET_NOT_RELEASABLE', REFUSED_MESSAGE);if (release.unresolved.length) return failure('SECRET_EXPIRED', EXPIRED_MESSAGE);const result = await dispatch(action, release.input, tabId, runId);+ const landed = await guardLanding(action, result, tabId, runId);+ if (landed) return landed;const { value } = await sealForPage(result, await targetOrigin(tabId, runId));return value;}+/** Answered from extension storage alone — they never touch a tab, and what they hand back is filtered where it is kept. */+const TAB_FREE = new Set(+ [+ listFiles,+ listRecordings,+ readRecording,+ readConsole,+ readNetwork,+ stopDiagnostics,+ monitorStatus,+ stopMonitor,+ awaitMonitor,+ startTimer,+ timerStatus,+ stopTimer,+ ].map((action) => action.name),+);++/** These pick another tab to land on or close, and check that tab where they pick it — in tabs.ts. */+const PICKS_ITS_TAB = new Set([openTab, switchTab, closeTab].map((action) => action.name));++const WATCHES_A_TAB = new Set([startMonitor, startDiagnostics].map((action) => action.name));++/**+ * The blocked-sites gate. Every action is checked unless it is named above, so an action+ * added later is covered without anyone remembering to. The checks are the tab's address,+ * where it is about to go, every frame on the focused path, and wherever the action itself+ * would send the browser.+ */+async function guardTarget(action: string, input: unknown, tabId?: number, runId?: string): Promise<ActionResult | null> {+ if (TAB_FREE.has(action) || PICKS_ITS_TAB.has(action)) return null;+ const owner = runId ? await sessionForRun(runId) : null;++ if (WATCHES_A_TAB.has(action)) {+ const watched = (input as { tabId?: unknown } | undefined)?.tabId;+ const tab = typeof watched === 'number' ? await pinnedTab(watched) : await resolveTab(tabId, owner);+ return refusalFor(...tabUrls(tab));+ }++ const tab = await resolveTab(tabId, owner);+ if (tab?.id == null) return null;+ if (action !== navigate.name && !isWebPage(tab.url || tab.pendingUrl)) {+ return failure(+ 'TAB_UNREACHABLE',+ `Tab ${tab.id} is a browser page, not a web page — page actions cannot read or act on it. page.navigate to an absolute http(s) URL first.`,+ );+ }+ const frames = (await framePath(tab.id)).map((step) => step.url);+ return refusalFor(...tabUrls(tab), ...frames, ...destinationsOf(action, input, tab.url));+}++/** A redirect, a form or a slow screenshot can leave the tab somewhere blocked; nothing read there goes back. */+async function guardLanding(action: string, result: ActionResult, tabId?: number, runId?: string): Promise<ActionResult | null> {+ if (!result.ok || TAB_FREE.has(action) || WATCHES_A_TAB.has(action)) return null;+ if (action === switchTab.name || action === closeTab.name) return null;+ const reported = result.data as { tabId?: unknown; finalUrl?: unknown; landedOn?: unknown } | undefined;++ if (action === openTab.name) {+ return typeof reported?.tabId === 'number' ? refusalFor(...tabUrls(await pinnedTab(reported.tabId))) : null;+ }+ const owner = runId ? await sessionForRun(runId) : null;+ const tab = await resolveTab(tabId, owner);+ const reportedUrls = [textOf(reported?.finalUrl), textOf(reported?.landedOn)];+ return tab?.id != null ? refusalForTab(tab.id, ...reportedUrls) : refusalFor(...reportedUrls);+}++function destinationsOf(action: string, input: unknown, base?: string): (string | undefined)[] {+ if (action === navigate.name) {+ const parsed = navigate.input.safeParse(input ?? {});+ if (!parsed.success) return [];+ try {+ const plan = resolveNavigation(parsed.data as NavigateInput, base);+ return plan.kind === 'url' ? [plan.href] : [];+ } catch {+ return [];+ }+ }+ if (action === captureDownload.name) {+ const url = (input as { url?: unknown } | undefined)?.url;+ return typeof url === 'string' ? [absoluteUrl(url, base)] : [];+ }+ return [];+}++function absoluteUrl(url: string, base?: string): string | undefined {+ try {+ return new URL(url, base).href;+ } catch {+ return undefined;+ }+}++const textOf = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined);++const isWebPage = (url: string | undefined): boolean => !!url && /^https?:/i.test(url);+async function targetOrigin(tabId?: number, runId?: string): Promise<string | undefined> {const owner = runId ? await sessionForRun(runId) : null;const tab = await resolveTab(tabId, owner);@@ -285,7 +387,9 @@ async function listStoredRecordings(input: unknown): Promise<ActionResult> {const filters = input as { host?: unknown; nameContains?: unknown } | undefined;const host = typeof filters?.host === 'string' ? filters.host.toLowerCase() : null;const needle = typeof filters?.nameContains === 'string' ? filters.nameContains.toLowerCase() : null;+ const blocked = await siteCheck();const recordings = (await listStoredMeta())+ .filter((r) => !blocked(r.startUrl)).filter((r) => !host || r.host.toLowerCase() === host).filter((r) => !needle || `${r.name} ${r.goal ?? ''}`.toLowerCase().includes(needle)).map(({ id, name, host: on, status, goal, summary, steps, capturedValues, durationMs, createdAt }) => ({@@ -311,6 +415,7 @@ async function readStoredRecording(input: unknown): Promise<ActionResult> {const meta = (await listStoredMeta()).find((r) => r.id === id);if (!meta) return failure('RECORDING_NOT_FOUND', `No recording with id "${id}".`);const body = await readRecordingBody(id);+ if (await recordedOnBlockedSite(meta.startUrl, body?.events)) return blockedRefusal();if (!body?.workflow) {return failure('RECORDING_NOT_READY',diff --git a/src/lib/bridge/monitor.ts b/src/lib/bridge/monitor.tsindex 338dfe7..e0e6561 100644--- a/src/lib/bridge/monitor.ts+++ b/src/lib/bridge/monitor.ts@@ -28,12 +28,15 @@ import {} from '@/lib/monitor/events';import { hostOf, originOf } from '@/lib/recordings/events';import { showToast } from '@/lib/bridge/toast';+import { onBlockedSitesChange, refusalFor, siteBlocked, tabUrls } from '@/lib/bridge/site-guard';const MONITORS_KEY = 'browsentic/monitors';const DONE_KEY = 'browsentic/monitorsDone';const NO_CONTENT_SCRIPT = 'Receiving end does not exist';+const MOVED_TO_BLOCKED = 'The tab moved to a site on the Blocked sites list.';+interface ActiveMonitor {id: string;tabId: number;@@ -142,6 +145,8 @@ export async function startTabMonitor(if (!/^https?:/i.test(tab.url)) {return failure('UNSUPPORTED', 'Only http(s) pages can be watched — browser pages expose nothing to observe.');}+ const refused = await refusalFor(...tabUrls(tab));+ if (refused) return refused;const outcome = await locked(async () => {const map = await readMonitors();@@ -212,7 +217,9 @@ export async function ingestSample(tabId: number | undefined,monitorId: string,sample: MonitorSample,+ pageUrl?: string,): Promise<void> {+ if (await siteBlocked(pageUrl)) return;const updated = await locked(async () => {const map = await readMonitors();const monitor = map[monitorId];@@ -389,8 +396,8 @@ export async function awaitMonitorDone(monitorId: string, timeoutMs: number): Pr});}-export async function monitorsForTab(tabId: number | undefined): Promise<ActionResult> {- if (tabId == null) return success({ monitors: [] });+export async function monitorsForTab(tabId: number | undefined, pageUrl?: string): Promise<ActionResult> {+ if (tabId == null || (await siteBlocked(pageUrl))) return success({ monitors: [] });const map = await readMonitors();const monitors = Object.values(map).filter((monitor) => monitor.tabId === tabId)@@ -425,9 +432,12 @@ export function serveMonitor(): void {browser.tabs.onUpdated.addListener((tabId, changeInfo) => {if (!changeInfo.url) return;void (async () => {+ const blocked = await siteBlocked(changeInfo.url);for (const monitor of Object.values(await readMonitors())) {if (monitor.tabId !== tabId) continue;- if (originOf(changeInfo.url!) === monitor.origin) {+ if (blocked) {+ await finishMonitor(monitor.id, 'tab-navigated', MOVED_TO_BLOCKED);+ } else if (originOf(changeInfo.url!) === monitor.origin) {const noted = await locked(async () => {const map = await readMonitors();const current = map[monitor.id];@@ -448,6 +458,15 @@ export function serveMonitor(): void {})();});+ onBlockedSitesChange(() => {+ void (async () => {+ for (const monitor of Object.values(await readMonitors())) {+ const tab = await browser.tabs.get(monitor.tabId).catch(() => null);+ if (await siteBlocked(...tabUrls(tab))) await finishMonitor(monitor.id, 'tab-navigated', MOVED_TO_BLOCKED);+ }+ })();+ });+browser.alarms.onAlarm.addListener((alarm) => {if (alarm.name.startsWith(TIMEOUT_ALARM_PREFIX)) {void finishMonitor(alarm.name.slice(TIMEOUT_ALARM_PREFIX.length), 'timeout');diff --git a/src/lib/bridge/pick.ts b/src/lib/bridge/pick.tsindex ba9052a..ee4d048 100644--- a/src/lib/bridge/pick.ts+++ b/src/lib/bridge/pick.ts@@ -3,6 +3,7 @@ import { pickElement } from '@/lib/actions/page/pick-element';import { success, type ActionResult } from '@/lib/actions/protocol';import { describeFrame, focusedFrame, frameOffset, TOP_FRAME } from './frame-focus';import { blobToDataUrl, captureViewport } from './screenshot';+import { refusalForTab } from './site-guard';export interface PickShot {dataUrl: string;@@ -30,9 +31,13 @@ export async function pickInTab(tab: { id: number; windowId?: number },input?: unknown,): Promise<ActionResult> {+ const refused = await refusalForTab(tab.id);+ if (refused) return refused;const picked = await invokeInTab(tab.id, pickElement.name, input);if (!picked.ok) return picked;+ const moved = await refusalForTab(tab.id);+ if (moved) return moved;const { capture, ...data } = picked.data as { capture?: PickCapture } & Record<string, unknown>;const placed = capture ? await inTabViewport(tab.id, capture) : null;const shot = placed ? await shootRegion(tab.windowId, placed).catch(() => null) : null;diff --git a/src/lib/bridge/recorder.ts b/src/lib/bridge/recorder.tsindex 0dae0c8..61751f9 100644--- a/src/lib/bridge/recorder.ts+++ b/src/lib/bridge/recorder.ts@@ -1,5 +1,6 @@import { browser } from 'wxt/browser';import { failure, success, type ActionResult } from '@/lib/actions/protocol';+import { SITE_BLOCKED } from '@/lib/settings/blocked-sites';import {MAX_EVENTS,MAX_RECORDING_MS,@@ -15,12 +16,15 @@ import {putRecording,type StoredRecordingMeta,} from './recording-store';+import { onBlockedSitesChange, siteBlocked, tabUrls } from './site-guard';const ACTIVE_KEY = 'browsentic/recording';export const WARN_ALARM = 'browsentic/recording-warn';export const STOP_ALARM = 'browsentic/recording-stop';-export type StopReason = 'user' | 'timeout' | 'tab-closed';+export type StopReason = 'user' | 'timeout' | 'tab-closed' | 'site-blocked';++const NOT_RECORDED = 'This site is on your Blocked sites list, so Browsentic will not record it.';export interface ActiveRecording {id: string;@@ -69,9 +73,10 @@ export async function currentRecording(): Promise<RecordingState | null> {export async function recordingStateFor(tabId: number | undefined,+ pageUrl?: string,): Promise<{ recording: boolean; captureValues: boolean }> {const active = await readActive();- const match = !!active && active.tabId === tabId;+ const match = !!active && active.tabId === tabId && !(await siteBlocked(pageUrl));return { recording: match, captureValues: match ? active!.captureValues : false };}@@ -92,6 +97,7 @@ export async function startRecording(opts: {if (!/^https?:/.test(opts.url)) {return failure('UNSUPPORTED', 'Only http(s) pages can be recorded.');}+ if (await siteBlocked(opts.url)) return failure(SITE_BLOCKED, NOT_RECORDED);const active: ActiveRecording = {id: crypto.randomUUID(),@@ -113,10 +119,10 @@ export async function startRecording(opts: {return success(state);}-export async function appendEvents(tabId: number | undefined, events: RecordedEvent[]): Promise<void> {+export async function appendEvents(tabId: number | undefined, events: RecordedEvent[], pageUrl?: string): Promise<void> {if (!events.length) return;const active = await readActive();- if (!active || active.tabId !== tabId) return;+ if (!active || active.tabId !== tabId || (await siteBlocked(pageUrl))) return;if (active.events.length >= MAX_EVENTS) {await stopRecording('timeout');return;@@ -167,6 +173,10 @@ export function serveRecorder(): void {void (async () => {const active = await readActive();if (!active || active.tabId !== tabId) return;+ if (await siteBlocked(changeInfo.url)) {+ await stopRecording('site-blocked');+ return;+ }const last = active.events[active.events.length - 1];if (last?.kind === 'navigate' && last.url === changeInfo.url) return;await appendEvents(tabId, [{ t: Date.now(), kind: 'navigate', url: changeInfo.url! }]);@@ -180,6 +190,15 @@ export function serveRecorder(): void {})();});+ onBlockedSitesChange(() => {+ void (async () => {+ const active = await readActive();+ if (!active) return;+ const tab = await browser.tabs.get(active.tabId).catch(() => null);+ if (await siteBlocked(...tabUrls(tab))) await stopRecording('site-blocked');+ })();+ });+browser.alarms.onAlarm.addListener((alarm) => {if (alarm.name === STOP_ALARM) {void stopRecording('timeout');diff --git a/src/lib/bridge/recording-store.ts b/src/lib/bridge/recording-store.tsindex f4652c3..20e2b7a 100644--- a/src/lib/bridge/recording-store.ts+++ b/src/lib/bridge/recording-store.ts@@ -2,6 +2,7 @@ import { browser } from 'wxt/browser';import type { SavedRecording } from '@/lib/actions/protocol';import { hostOf, originOf, type RecordedEvent } from '@/lib/recordings/events';import { validateRecordingWorkflow, type RecordingWorkflow } from '@/lib/recordings/workflow';+import { siteBlocked } from './site-guard';import { analyzeRecording } from './socket';export const RECORDINGS_INDEX_KEY = 'browsentic:recordings';@@ -93,6 +94,14 @@ export async function analyzeStoredRecording(recordingId: string): Promise<void>return;}+ if (await recordedOnBlockedSite(meta.startUrl, body.events)) {+ await updateRecordingMeta(recordingId, {+ status: 'error',+ error: 'It visits a site on the Blocked sites list, so it was not sent to be turned into steps.',+ });+ return;+ }+await updateRecordingMeta(recordingId, { status: 'analyzing', error: undefined });const result = await analyzeRecording({id: meta.id,@@ -162,3 +171,7 @@ export function asSavedRecording(meta: StoredRecordingMeta): SavedRecording {durationMs: meta.durationMs,};}++export function recordedOnBlockedSite(startUrl: string, events: readonly RecordedEvent[] = []): Promise<boolean> {+ return siteBlocked(startUrl, ...events.flatMap((event) => (event.kind === 'navigate' ? [event.url] : [])));+}diff --git a/src/lib/bridge/run-port.ts b/src/lib/bridge/run-port.tsindex 5f0e4a2..b838e7c 100644--- a/src/lib/bridge/run-port.ts+++ b/src/lib/bridge/run-port.ts@@ -56,6 +56,7 @@ import {titleDueAt,type StoredSessionMeta,} from './session-store';+import { isBlockedRefusal, refusalFor, siteBlocked, siteCheck, tabUrls } from './site-guard';import { recordGeneratedSkill } from './skill-store';import { dropTimersForSession, onTimerFire, type TimerHandoff } from './timer';import { announceTask, askTaskApproval, dropTaskApproval, takeApprovalAnswer } from './task-notices';@@ -598,14 +599,16 @@ async function startTurn(return 'local';}+ const current = await browser.tabs.get(session.currentTabId).catch(() => null);+ const hidden = await siteBlocked(session.url, ...tabUrls(current), focus?.url);const runId = sendInstruction(text, {- url: session.url,+ url: hidden ? undefined : session.url,tabId: session.currentTabId,sessionId,agent: session.agent,agentSessionId: session.agentSessionId,agentSkillId,- focus,+ focus: hidden ? undefined : focus,liveTools,files: await attachedFiles(session),recordings: await attachedRecordings(),@@ -852,6 +855,8 @@ async function beginRecording(captureValues: boolean): Promise<void> {}async function startTaskRun(order: TaskOrder): Promise<ActionResult> {+ const refused = await refusalFor(order.url);+ if (refused) return refused;const opened = await serialized(() => openTaskSession(order));if (!opened.ok) return opened;await loaded(opened.data.tabId);@@ -971,16 +976,19 @@ async function replay();if (!result.ok) {const error = `${result.error.code}: ${result.error.message}`;- return handOver(sessionId, order, handOverPrompt({ ...recording, ...call, total: calls.length, error }), {- outcome: 'failed',- reason: `Step ${call.ordinal} (${call.intent}) failed — ${error}`,- });+ const verdict: TaskVerdict = { outcome: 'failed', reason: `Step ${call.ordinal} (${call.intent}) failed — ${error}` };+ if (isBlockedRefusal(result)) return endTask(sessionId, verdict);+ return handOver(sessionId, order, handOverPrompt({ ...recording, ...call, total: calls.length, error }), verdict);}if (call.action === 'page.extractText') extracted = (result.data as { content?: string } | null)?.content;}- await serialized(async () => {+ await endTask(sessionId, replayVerdict(calls.length, extracted));+}++function endTask(sessionId: string, verdict: TaskVerdict): Promise<void> {+ return serialized(async () => {const session = (await readTabSessions())[sessionId];- if (session) await finishTask(session, replayVerdict(calls.length, extracted));+ if (session) await finishTask(session, verdict);});}@@ -1052,8 +1060,9 @@ const MAX_CONTEXT_RECORDINGS = 8;async function attachedRecordings(): Promise<SavedRecording[]> {try {+ const blocked = await siteCheck();return (await listRecordings())- .filter((recording) => recording.status === 'ready')+ .filter((recording) => recording.status === 'ready' && !blocked(recording.startUrl)).slice(0, MAX_CONTEXT_RECORDINGS).map(asSavedRecording);} catch {diff --git a/src/lib/bridge/session-store.ts b/src/lib/bridge/session-store.tsindex c0ed0f8..9431bf8 100644--- a/src/lib/bridge/session-store.ts+++ b/src/lib/bridge/session-store.ts@@ -3,6 +3,7 @@ import type { TokenUsage } from '@/lib/actions/protocol';import type { AgentKind } from '@/lib/agents/catalog';import { removeFilesFor } from './file-store';import type { RunItem } from './run-items';+import { siteBlocked } from './site-guard';import { nameSession } from './socket';export const SESSIONS_INDEX_KEY = 'browsentic:sessions';@@ -111,7 +112,7 @@ export async function nameStoredSession(sessionId: string): Promise<void> {const turns = meta.turns;await updateSessionMeta(sessionId, { namingAt: Date.now() });- const result = await nameSession({ host: meta.host, messages });+ const result = await nameSession({ host: (await siteBlocked(meta.url)) ? undefined : meta.host, messages });if (result.ok && result.data.title.trim()) {await updateSessionMeta(sessionId, {title: result.data.title.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE_CHARS),diff --git a/src/lib/bridge/site-guard.test.ts b/src/lib/bridge/site-guard.test.tsnew file mode 100644index 0000000..042a520--- /dev/null+++ b/src/lib/bridge/site-guard.test.ts@@ -0,0 +1,173 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';+import { fakeBrowser } from 'wxt/testing';+import { success, type ActionResult } from '@/lib/actions/protocol';+import { BLOCKED_SITES_KEY, LIST_UNREADABLE_MESSAGE, SITE_BLOCKED } from '@/lib/settings/blocked-sites';+import { setFramePath } from './frame-focus';+import { invokeForHarness } from './invoke';++const block = (...patterns: string[]) => fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: patterns });++const tabOn = async (url: string) => (await fakeBrowser.tabs.create({ url, active: true })).id!;++const refusedAsBlocked = (result: ActionResult) => !result.ok && result.error.code === SITE_BLOCKED;++let sent: ReturnType<typeof vi.fn>;++beforeEach(() => {+ fakeBrowser.reset();+ sent = vi.fn(async () => success({ text: 'the page' }));+ vi.spyOn(fakeBrowser.tabs, 'sendMessage').mockImplementation(sent as never);+});++afterEach(() => vi.restoreAllMocks());++describe('the tab an action would touch', () => {+ test('a blocked tab is refused before the page hears anything', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://www.mybank.com/accounts');+ expect(refusedAsBlocked(await invokeForHarness('page.extractText', {}, tabId))).toBe(true);+ expect(sent).not.toHaveBeenCalled();+ });++ test('an allowed tab goes through as before', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ expect(await invokeForHarness('page.extractText', {}, tabId)).toMatchObject({ ok: true });+ expect(sent).toHaveBeenCalledOnce();+ });++ test('a tab on its way to a blocked page is refused already', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ const tab = await fakeBrowser.tabs.get(tabId);+ vi.spyOn(fakeBrowser.tabs, 'get').mockResolvedValue({ ...tab, pendingUrl: 'https://mybank.com/login' } as never);+ expect(refusedAsBlocked(await invokeForHarness('page.clickElement', { target: { text: 'Go' } }, tabId))).toBe(true);+ });++ test('a blocked frame inside an allowed page is refused while it holds the focus', async () => {+ await block('pay.mybank.com');+ const tabId = await tabOn('https://shop.example.com/checkout');+ await setFramePath(tabId, [{ frameId: 7, url: 'https://pay.mybank.com/widget', selector: 'iframe#pay' }]);+ expect(refusedAsBlocked(await invokeForHarness('page.fillInput', { target: { text: 'Card' }, value: '1' }, tabId))).toBe(true);+ });++ test('a browser page is refused outright, so the settings page can never be driven', async () => {+ const tabId = await tabOn('chrome-extension://abcdef/options.html#blocked');+ for (const action of ['page.findCaptcha', 'page.injectCode', 'page.screenshot', 'page.extractText']) {+ expect(await invokeForHarness(action, {}, tabId)).toMatchObject({ ok: false, error: { code: 'TAB_UNREACHABLE' } });+ }+ expect(sent).not.toHaveBeenCalled();+ });++ test('an unreadable list refuses every page action, and says why', async () => {+ const tabId = await tabOn('https://example.com/');+ await fakeBrowser.storage.local.set({ [BLOCKED_SITES_KEY]: 'not a list' });+ expect(await invokeForHarness('page.extractText', {}, tabId)).toMatchObject({+ ok: false,+ error: { code: SITE_BLOCKED, message: LIST_UNREADABLE_MESSAGE },+ });+ });++ test('actions that never touch a tab still answer', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://mybank.com/');+ expect(await invokeForHarness('page.listFiles', {}, tabId)).toMatchObject({ ok: true });+ expect(await invokeForHarness('page.timerStatus', {}, tabId)).toMatchObject({ ok: true });+ });++ test('watching a blocked tab is refused, whichever tab the run is on', async () => {+ await block('mybank.com');+ const current = await tabOn('https://example.com/');+ const watched = await tabOn('https://mybank.com/transfer');+ const until = { kind: 'text-matches', pattern: 'Done', threshold: 1 };+ expect(refusedAsBlocked(await invokeForHarness('page.startMonitor', { tabId: watched, until }, current))).toBe(true);+ });+});++describe('where an action would send the browser', () => {+ test('navigating to a blocked address is refused, and the tab stays put', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ expect(refusedAsBlocked(await invokeForHarness('page.navigate', { url: 'https://mybank.com/' }, tabId))).toBe(true);+ expect((await fakeBrowser.tabs.get(tabId)).url).toBe('https://example.com/');+ });++ test('a relative address is resolved against the page first', async () => {+ await block('example.com/admin');+ const tabId = await tabOn('https://example.com/home');+ expect(refusedAsBlocked(await invokeForHarness('page.navigate', { url: '/admin/users' }, tabId))).toBe(true);+ expect(refusedAsBlocked(await invokeForHarness('page.navigate', { url: '/%61dmin' }, tabId))).toBe(true);+ });++ test('a download from a blocked address is refused before the browser sends its cookies', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ const download = vi.spyOn(fakeBrowser.downloads, 'download');+ expect(refusedAsBlocked(await invokeForHarness('page.captureDownload', { url: 'https://mybank.com/statement.pdf' }, tabId))).toBe(true);+ expect(download).not.toHaveBeenCalled();+ });++ test('opening a blocked site in a new tab is refused before the tab exists', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ const before = (await fakeBrowser.tabs.query({})).length;+ expect(refusedAsBlocked(await invokeForHarness('page.openTab', { url: 'https://mybank.com/' }, tabId))).toBe(true);+ expect(await fakeBrowser.tabs.query({})).toHaveLength(before);+ });++ test('an action that lands the tab on a blocked site hands back nothing from it', async () => {+ await block('mybank.com');+ const tabId = await tabOn('https://example.com/');+ sent.mockImplementation(async () => {+ await fakeBrowser.tabs.update(tabId, { url: 'https://mybank.com/after-redirect' });+ return success({ text: 'what the bank page said' });+ });+ const result = await invokeForHarness('page.clickElement', { target: { text: 'Continue' } }, tabId);+ expect(refusedAsBlocked(result)).toBe(true);+ expect(JSON.stringify(result)).not.toContain('what the bank page said');+ });+});++describe('other tabs', () => {+ async function window() {+ const current = await tabOn('https://example.com/');+ const bank = await tabOn('https://mybank.com/accounts');+ await fakeBrowser.tabs.update(current, { active: true });+ return { current, bank };+ }++ test('a blocked tab is left out of the list, counted as hidden, and never named', async () => {+ await block('mybank.com');+ const { current } = await window();+ const result = await invokeForHarness('page.switchTab', {}, current);+ expect(result).toMatchObject({ ok: true, data: { tabs: [{ url: 'https://example.com/' }] } });+ expect((result as { data: { hidden: number } }).data.hidden).toBeGreaterThanOrEqual(1);+ expect(JSON.stringify(result)).not.toContain('mybank');+ });++ test('switching to it by id is refused, and matching its title or address finds nothing', async () => {+ await block('mybank.com');+ const { current, bank } = await window();+ expect(refusedAsBlocked(await invokeForHarness('page.switchTab', { tabId: bank }, current))).toBe(true);+ const matched = await invokeForHarness('page.switchTab', { match: 'mybank' }, current);+ expect(matched).toMatchObject({ ok: false, error: { code: 'TARGET_NOT_FOUND' } });+ expect(JSON.stringify(matched)).not.toContain('accounts');+ });++ test('closing it is refused', async () => {+ await block('mybank.com');+ const { current, bank } = await window();+ expect(refusedAsBlocked(await invokeForHarness('page.closeTab', { tabId: bank }, current))).toBe(true);+ expect(await fakeBrowser.tabs.get(bank)).toBeDefined();+ });++ test('a run on a blocked tab can still leave it for an allowed site', async () => {+ await block('mybank.com');+ const bank = await tabOn('https://mybank.com/');+ vi.spyOn(fakeBrowser.tabs, 'create').mockImplementation(async (props) => ({ id: 99, index: 1, windowId: 1, ...props }) as never);+ vi.spyOn(fakeBrowser.tabs, 'get').mockImplementation(async (id) =>+ ({ id, windowId: 1, url: id === 99 ? 'https://example.com/' : 'https://mybank.com/', status: 'complete' }) as never,+ );+ expect(await invokeForHarness('page.openTab', { url: 'https://example.com/' }, bank)).toMatchObject({ ok: true });+ });+});diff --git a/src/lib/bridge/site-guard.ts b/src/lib/bridge/site-guard.tsnew file mode 100644index 0000000..3ad4cff--- /dev/null+++ b/src/lib/bridge/site-guard.ts@@ -0,0 +1,59 @@+import { browser } from 'wxt/browser';+import { failure, type ActionResult } from '@/lib/actions/protocol';+import {+ BLOCKED_SITES_KEY,+ LIST_UNREADABLE_MESSAGE,+ SITE_BLOCKED,+ SITE_BLOCKED_MESSAGE,+ blockedBy,+ compileBlockedSites,+ subjectOf,+ type BlockedPattern,+} from '@/lib/settings/blocked-sites';+import { framePath } from './frame-focus';++type Url = string | undefined;++/** Read on every check: a worker that slept has no memory worth trusting, and the list can change at any moment. */+export async function readBlockedSites(): Promise<BlockedPattern[] | null> {+ try {+ return compileBlockedSites((await browser.storage.local.get(BLOCKED_SITES_KEY))[BLOCKED_SITES_KEY]);+ } catch {+ return null;+ }+}++/** One read, many checks — for walking every tab in a window. An unreadable list blocks every web page. */+export async function siteCheck(): Promise<(...urls: Url[]) => boolean> {+ const list = await readBlockedSites();+ return (...urls) => urls.some((url) => (list ? blockedBy(url, list) !== null : subjectOf(url) !== null));+}++export async function siteBlocked(...urls: Url[]): Promise<boolean> {+ return (await siteCheck())(...urls);+}++export async function refusalFor(...urls: Url[]): Promise<ActionResult<never> | null> {+ const list = await readBlockedSites();+ if (!list) return urls.some((url) => subjectOf(url) !== null) ? failure(SITE_BLOCKED, LIST_UNREADABLE_MESSAGE) : null;+ return urls.some((url) => blockedBy(url, list) !== null) ? blockedRefusal() : null;+}++/** The tab as it is right now — its address, where it is headed, and every frame on the focused path. */+export async function refusalForTab(tabId: number, ...also: Url[]): Promise<ActionResult<never> | null> {+ const tab = await browser.tabs.get(tabId).catch(() => null);+ const frames = (await framePath(tabId)).map((step) => step.url);+ return refusalFor(...tabUrls(tab), ...frames, ...also);+}++export const blockedRefusal = (): ActionResult<never> => failure(SITE_BLOCKED, SITE_BLOCKED_MESSAGE);++export const isBlockedRefusal = (result: ActionResult): boolean => !result.ok && result.error.code === SITE_BLOCKED;++export const tabUrls = (tab: { url?: string; pendingUrl?: string } | null | undefined): Url[] => [tab?.url, tab?.pendingUrl];++export function onBlockedSitesChange(listener: () => void): void {+ browser.storage.local.onChanged.addListener((changes) => {+ if (BLOCKED_SITES_KEY in changes) listener();+ });+}diff --git a/src/lib/bridge/tabs.ts b/src/lib/bridge/tabs.tsindex a4b73c9..433c855 100644--- a/src/lib/bridge/tabs.ts+++ b/src/lib/bridge/tabs.ts@@ -7,6 +7,7 @@ import { openTab } from '@/lib/actions/page/open-tab';import { switchTab } from '@/lib/actions/page/switch-tab';import { failure, success, type ActionResult } from '@/lib/actions/protocol';import { recordingStateFor } from '@/lib/bridge/recorder';+import { refusalFor, siteCheck, tabUrls } from '@/lib/bridge/site-guard';export const LOAD_TIMEOUT_MS = 10_000;@@ -25,6 +26,7 @@ interface TabInfo {windowId?: number;index?: number;url?: string;+ pendingUrl?: string;title?: string;active?: boolean;pinned?: boolean;@@ -46,7 +48,8 @@ export async function openNewTab(input: unknown, anchor?: TabRef): Promise<Actioconst current = (anchor? await browser.tabs.get(anchor.id).catch(() => undefined): (await browser.tabs.query({ active: true, currentWindow: true }))[0]) as TabInfo | undefined;- const base = current?.url && isPageUrl(current.url) ? current.url : undefined;+ const usable = await usableTabs();+ const base = current && usable(current) ? current.url : undefined;let href: string;try {@@ -56,6 +59,8 @@ export async function openNewTab(input: unknown, anchor?: TabRef): Promise<Actio} catch (error) {return error instanceof ActionError ? failure(error.code, error.message) : failure('ACTION_FAILED', String(error));}+ const refused = await refusalFor(href);+ if (refused) return refused;const opener =current?.id != null && current.windowId != null@@ -92,11 +97,14 @@ export async function switchToTab(current: TabRef, input: unknown): Promise<Acti}const tabs = await windowTabs(current);- if (tabId == null && match == null) return success(inventory(tabs, current));+ const usable = await usableTabs();+ if (tabId == null && match == null) return success(inventory(tabs, current, usable));- const picked = await pickTab(tabs, { tabId, match }, 'switch to');+ const picked = await pickTab(tabs, { tabId, match }, 'switch to', usable);if (!picked.ok) return picked.result;const target = picked.tab;+ const refused = await refusalFor(...tabUrls(target));+ if (refused) return refused;if (!isPageUrl(target.url)) {return failure(@@ -127,12 +135,15 @@ export async function closeOpenTab(current: TabRef, input: unknown): Promise<Act}const tabs = await windowTabs(current);+ const usable = await usableTabs();const picked =tabId == null && match == null? pickCurrent(tabs, current)- : await pickTab(tabs, { tabId, match }, 'close');+ : await pickTab(tabs, { tabId, match }, 'close', usable);if (!picked.ok) return picked.result;const target = picked.tab;+ const refused = await refusalFor(...tabUrls(target));+ if (refused) return refused;if (tabs.length <= 1) {return failure(@@ -166,7 +177,7 @@ export async function closeOpenTab(current: TabRef, input: unknown): Promise<Act}const after = await settleAfterClose(current, target.id!);- const nowOn = after.active?.url ? clip(after.active.url) : undefined;+ const nowOn = after.active?.url && usable(after.active) ? clip(after.active.url) : undefined;return success({performed: nowOn ? `closed ${label(target)} — now on ${nowOn}` : `closed ${label(target)}`,closed: describeTab(target),@@ -217,6 +228,7 @@ async function pickTab(tabs: TabInfo[],selector: { tabId?: number; match?: string },verb: string,+ usable: Usable,): Promise<Picked> {if (selector.tabId != null) {const hit = tabs.find((t) => t.id === selector.tabId);@@ -227,24 +239,22 @@ async function pickTab(result: elsewhere? failure('INVALID_TARGET',- `Tab ${selector.tabId} is in a different browser window. Browsentic only acts within the window it was opened in — ${openTabsLine(tabs)}`,+ `Tab ${selector.tabId} is in a different browser window. Browsentic only acts within the window it was opened in — ${openTabsLine(tabs, usable)}`,): failure('TARGET_NOT_FOUND',- `No tab with id ${selector.tabId} — it has probably been closed. ${openTabsLine(tabs)}`,+ `No tab with id ${selector.tabId} — it has probably been closed. ${openTabsLine(tabs, usable)}`,),};}const needle = selector.match!.trim().toLowerCase();if (!needle) return { ok: false, result: failure('INVALID_INPUT', '"match" cannot be empty.') };- const hits = tabs- .filter(isPageTab)- .filter((t) => `${t.title ?? ''} ${t.url ?? ''}`.toLowerCase().includes(needle));+ const hits = tabs.filter(usable).filter((t) => `${t.title ?? ''} ${t.url ?? ''}`.toLowerCase().includes(needle));if (!hits.length) {return {ok: false,- result: failure('TARGET_NOT_FOUND', `No open tab matches "${clip(selector.match!)}". ${openTabsLine(tabs)}`),+ result: failure('TARGET_NOT_FOUND', `No open tab matches "${clip(selector.match!)}". ${openTabsLine(tabs, usable)}`),};}if (hits.length > 1) {@@ -259,16 +269,16 @@ async function pickTab(return { ok: true, tab: hits[0] };}-function inventory(tabs: TabInfo[], current: TabRef) {- const usable = tabs.filter(isPageTab);- const hidden = tabs.length - usable.length;- const shown = usable.slice(0, MAX_LISTED);+function inventory(tabs: TabInfo[], current: TabRef, usable: Usable) {+ const listed = tabs.filter(usable);+ const hidden = tabs.length - listed.length;+ const shown = listed.slice(0, MAX_LISTED);return {- performed: `${usable.length} open tab${usable.length === 1 ? '' : 's'} in this window`,+ performed: `${listed.length} open tab${listed.length === 1 ? '' : 's'} in this window`,activeTabId: current.id,tabs: shown.map(describeTab),...(hidden ? { hidden } : {}),- ...(shown.length < usable.length ? { truncated: true } : {}),+ ...(shown.length < listed.length ? { truncated: true } : {}),};}@@ -315,12 +325,18 @@ function tabLines(tabs: TabInfo[]): string {return shown.length < tabs.length ? `${lines}; …and ${tabs.length - shown.length} more` : lines;}-function openTabsLine(tabs: TabInfo[]): string {- const usable = tabs.filter(isPageTab);- return usable.length ? `Open tabs: ${tabLines(usable)}` : 'No other web page is open in this window.';+function openTabsLine(tabs: TabInfo[], usable: Usable): string {+ const listed = tabs.filter(usable);+ return listed.length ? `Open tabs: ${tabLines(listed)}` : 'No other web page is open in this window.';}-const isPageTab = (tab: TabInfo) => isPageUrl(tab.url);+type Usable = (tab: TabInfo) => boolean;++/** A tab on a blocked site is treated like a browser page: never listed, never matched, never named. */+async function usableTabs(): Promise<Usable> {+ const blocked = await siteCheck();+ return (tab) => isPageUrl(tab.url) && !blocked(...tabUrls(tab));+}const isPageUrl = (url: string | undefined): boolean => !!url && /^https?:/i.test(url);diff --git a/src/lib/bridge/use-extension-settings.ts b/src/lib/bridge/use-extension-settings.tsindex f0f70bf..170f035 100644--- a/src/lib/bridge/use-extension-settings.ts+++ b/src/lib/bridge/use-extension-settings.ts@@ -1,5 +1,6 @@-import { useCallback, useEffect, useState } from 'react';+import { useCallback, useEffect, useMemo, useState } from 'react';import { browser } from 'wxt/browser';+import { BLOCKED_SITES_KEY, blockedBy, compileBlockedSites } from '@/lib/settings/blocked-sites';import { shortcutsOf, shortcutsPageFor, type Shortcut } from '@/lib/settings/shortcuts';import { CONTEXT_MENU_KEY, asContextMenuChoice, type ContextMenuChoice } from './context-menu';import { brandFrom } from './identity';@@ -41,6 +42,21 @@ export const useContextMenuChoice = (): [ContextMenuChoice, (next: ContextMenuChexport const usePushToTalk = (): [boolean, (on: boolean) => void] => useLocalSetting(PUSH_TO_TALK_KEY, isOn);+const asPatterns = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];++/** The one writer of the blocked-sites list. Nothing on the daemon's side of the socket can reach this key. */+export const useBlockedSites = (): [string[], (next: string[]) => void] => useLocalSetting(BLOCKED_SITES_KEY, asPatterns);++export function useBlockedPattern(url: string | undefined): string | null {+ const [patterns] = useBlockedSites();+ return useMemo(() => blockedBy(url, compileBlockedSites(patterns) ?? []), [url, patterns]);+}++export function openBlockedSites(): void {+ void browser.tabs.create({ url: `${browser.runtime.getURL('/options.html')}#blocked` });+}+export function useShortcuts(): Shortcut[] | undefined {const [shortcuts, setShortcuts] = useState<Shortcut[]>();diff --git a/src/lib/settings/blocked-sites.test.ts b/src/lib/settings/blocked-sites.test.tsnew file mode 100644index 0000000..fa6d75b--- /dev/null+++ b/src/lib/settings/blocked-sites.test.ts@@ -0,0 +1,154 @@+import { describe, expect, test } from 'vitest';+import {+ BLOCKED_SITES_LIMITS,+ blockedBy,+ compileBlockedSites,+ describePattern,+ parseBlockedPattern,+ subjectOf,+} from './blocked-sites';++const blocks = (pattern: string, url: string) => blockedBy(url, compileBlockedSites([pattern])!) !== null;++function normalized(entry: string): string {+ const parsed = parseBlockedPattern(entry);+ if (!parsed.ok) throw new Error(parsed.reason);+ return parsed.pattern;+}++describe('what an entry is stored as', () => {+ test.each([+ ['example.com', 'example.com'],+ [' Example.COM ', 'example.com'],+ ['https://www.example.com/', 'example.com'],+ ['http://example.com', 'example.com'],+ ['*://example.com/admin', 'example.com/admin'],+ ['*.example.com', 'example.com'],+ ['www.com', 'www.com'],+ ['example.com./admin/', 'example.com/admin'],+ ['example.com/%61dmin', 'example.com/admin'],+ ['example.com//admin', 'example.com/admin'],+ ['example.com?q=1', 'example.com/?q=1'],+ ['example.com/admin#section', 'example.com/admin'],+ ['localhost:3000', 'localhost:3000'],+ ['example.com:443', 'example.com'],+ ['bücher.de', 'xn--bcher-kva.de'],+ ['bank.*', 'bank.*'],+ ['[::1]:8080', '[::1]:8080'],+ ['GitHub.com/*/Settings', 'github.com/*/Settings'],+ ])('%s → %s', (entry, pattern) => {+ expect(normalized(entry)).toBe(pattern);+ });++ test.each([+ [''],+ [' '],+ ['*'],+ ['*.*'],+ ['ftp://example.com'],+ ['chrome-extension://abc/options.html'],+ ['javascript:alert(1)'],+ ['exa mple.com'],+ ['[email protected]'],+ ['example.com:99999'],+ ['%%%'],+ ['bü*cher.de'],+ ['x'.repeat(BLOCKED_SITES_LIMITS.length + 1)],+ ])('%j is refused with a reason', (entry) => {+ const parsed = parseBlockedPattern(entry);+ expect(parsed.ok).toBe(false);+ expect(!parsed.ok && parsed.reason).toBeTruthy();+ });+});++describe('which pages a pattern blocks', () => {+ test.each([+ ['example.com', 'https://example.com/', true],+ ['example.com', 'https://mail.example.com/inbox?x=1', true],+ ['example.com', 'http://example.com:8080/any/where', true],+ ['example.com', 'https://EXAMPLE.com/', true],+ ['example.com', 'https://example.com./', true],+ ['example.com', 'https://user:[email protected]/', true],+ ['example.com', 'https://notexample.com/', false],+ ['example.com', 'https://example.com.evil.net/', false],+ ['example.com', 'https://evil.net/example.com', false],+ ['example.com', 'https://evil.net/?next=https://example.com', false],+ ['mail.example.com', 'https://mail.example.com/x', true],+ ['mail.example.com', 'https://a.mail.example.com/', true],+ ['mail.example.com', 'https://example.com/', false],+ ['example.com/admin', 'https://example.com/admin', true],+ ['example.com/admin', 'https://example.com/admin/users', true],+ ['example.com/admin', 'https://example.com/admin?tab=1', true],+ ['example.com/admin', 'https://example.com/Admin', true],+ ['example.com/admin', 'https://example.com/%61dmin', true],+ ['example.com/admin', 'https://example.com//admin', true],+ ['example.com/admin', 'https://example.com/admin;jsessionid=1', true],+ ['example.com/admin', 'https://example.com/administrator', false],+ ['example.com/admin', 'https://example.com/', false],+ ['example.com/admin/', 'https://example.com/admin', true],+ ['example.com/checkout*', 'https://example.com/checkout-step-2', true],+ ['github.com/*/settings', 'https://github.com/acme/settings/keys', true],+ ['github.com/*/settings', 'https://github.com/acme/issues', false],+ ['example.com/search?q=secret', 'https://example.com/search?q=secret&page=2', true],+ ['example.com/search?q=secret', 'https://example.com/search?q=other', false],+ ['bank.*', 'https://bank.co.uk/', true],+ ['bank.*', 'https://www.bank.com/login', true],+ ['bank.*', 'https://bank/', false],+ ['*shop*.com', 'https://myshop-eu.com/', true],+ ['*shop*.com', 'https://shop.example.org/', false],+ ['localhost:3000', 'http://localhost:3000/app', true],+ ['localhost:3000', 'http://localhost:3001/app', false],+ ['bücher.de', 'https://xn--bcher-kva.de/', true],+ ['127.0.0.1', 'http://127.0.0.1:5173/', true],+ ['example.com/a+b(c)', 'https://example.com/a+b(c)/d', true],+ ['example.com/a+b(c)', 'https://example.com/aab(c)', false],+ ])('%s on %s → %s', (pattern, url, want) => {+ expect(blocks(pattern, url)).toBe(want);+ });++ test('only web pages can be blocked', () => {+ const list = compileBlockedSites(['example.com'])!;+ expect(blockedBy('chrome://settings', list)).toBeNull();+ expect(blockedBy('file:///example.com/x', list)).toBeNull();+ expect(blockedBy(undefined, list)).toBeNull();+ expect(blockedBy('not a url', list)).toBeNull();+ });++ test('the first matching pattern is named', () => {+ const list = compileBlockedSites(['other.org', 'example.com/admin', 'example.com'])!;+ expect(blockedBy('https://example.com/admin/x', list)).toBe('example.com/admin');+ expect(blockedBy('https://example.com/home', list)).toBe('example.com');+ });+});++describe('reading the stored list', () => {+ test('nothing stored blocks nothing', () => {+ expect(compileBlockedSites(undefined)).toEqual([]);+ });++ test('a stored value that is not a list is refused, so the caller fails closed', () => {+ expect(compileBlockedSites('example.com')).toBeNull();+ expect(compileBlockedSites({ 0: 'example.com' })).toBeNull();+ expect(compileBlockedSites(null)).toBeNull();+ });++ test('entries that do not parse are skipped, the rest still apply', () => {+ expect(compileBlockedSites(['example.com', 42, '*', 'ftp://x.org'])!.map((p) => p.pattern)).toEqual(['example.com']);+ });+});++test('the subject is host, port, path and query — never the hash', () => {+ expect(subjectOf('https://Example.com:8443/a//b?c=1#frag')).toBe('example.com:8443/a/b?c=1');+ expect(subjectOf('http://example.com:80/')).toBe('example.com/');+});++test.each([+ ['example.com', 'Every page on example.com and its subdomains'],+ ['localhost:3000', 'Every page on localhost, port 3000'],+ ['127.0.0.1:8080/admin', 'Pages under /admin on 127.0.0.1, port 8080'],+ ['example.com/admin', 'Pages under /admin on example.com and its subdomains'],+ ['github.com/*/settings', 'Pages matching /*/settings on github.com and its subdomains'],+ ['bank.*', 'Every page on sites matching bank.*'],+])('%s is described as “%s”', (pattern, caption) => {+ expect(describePattern(pattern)).toBe(caption);+});diff --git a/src/lib/settings/blocked-sites.ts b/src/lib/settings/blocked-sites.tsnew file mode 100644index 0000000..993cab5--- /dev/null+++ b/src/lib/settings/blocked-sites.ts@@ -0,0 +1,194 @@+/**+ * The blocked-sites list: patterns of pages Browsentic never reads or acts on.+ *+ * It lives in this browser's `storage.local` and nowhere else. No socket frame carries it,+ * so neither the daemon nor the agent it spawns can see or loosen it — the extension checks+ * it before every page action, whoever asked for that action.+ */++export const BLOCKED_SITES_KEY = 'browsentic/blockedSites';++export const BLOCKED_SITES_LIMITS = { entries: 500, length: 200 } as const;++export const SITE_BLOCKED = 'SITE_BLOCKED';++export const SITE_BLOCKED_MESSAGE =+ 'This site is on the user’s Blocked sites list, so Browsentic will not read or act on it. ' ++ 'Do not retry or reach it another way (another URL, a search, another tab) — tell the user, or carry on with work that does not need it.';++export const LIST_UNREADABLE_MESSAGE =+ 'Browsentic could not read the user’s Blocked sites list, so it is refusing page actions until it can. ' ++ 'Ask the user to open Settings → Blocked sites.';++export interface BlockedPattern {+ readonly pattern: string;+ readonly source: string;+ readonly regex: RegExp;+ readonly site: RegExp;+}++export type ParsedPattern =+ | { readonly ok: true; readonly pattern: string; readonly source: string }+ | { readonly ok: false; readonly reason: string };++interface PatternParts {+ readonly host: string;+ readonly port?: string;+ readonly path?: string;+}++const WEB_SCHEME = /^(?:https?|\*):\/\//i;+const ANY_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;+const DEFAULT_PORTS = new Set(['80', '443']);+const WILDCARD_HOST = /^[a-z0-9*.-]+$/;+const BOUNDARY = '(?:[/?&;].*)?$';++export function parseBlockedPattern(entry: string): ParsedPattern {+ const parts = partsOf(entry);+ if ('reason' in parts) return { ok: false, reason: parts.reason };+ return { ok: true, pattern: patternOf(parts), source: sourceOf(parts) };+}++/** `null` when the stored value is not a list at all — the caller must refuse, not guess. */+export function compileBlockedSites(raw: unknown): BlockedPattern[] | null {+ if (raw === undefined) return [];+ if (!Array.isArray(raw)) return null;+ return raw.flatMap((entry) => {+ if (typeof entry !== 'string') return [];+ const parts = partsOf(entry);+ if ('reason' in parts) return [];+ const source = sourceOf(parts);+ const site = new RegExp(`${siteSource(parts)}$`, 'i');+ return [{ pattern: patternOf(parts), source, regex: new RegExp(source, 'i'), site }];+ });+}++/** The patterns that could match somewhere on this origin — all a page on it ever needs to be told. */+export function patternsFor(origin: string, list: readonly BlockedPattern[]): BlockedPattern[] {+ const site = subjectOf(`${origin}/`)?.slice(0, -1);+ return site === undefined ? [] : list.filter((pattern) => pattern.site.test(site));+}++export function blockedBy(url: string | undefined, list: readonly BlockedPattern[]): string | null {+ const subject = subjectOf(url);+ if (subject === null) return null;+ return list.find(({ regex }) => regex.test(subject))?.pattern ?? null;+}++/** What a pattern is matched against: host, port and path with the query — never the hash. */+export function subjectOf(url: string | undefined): string | null {+ if (!url) return null;+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ return null;+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;+ const host = parsed.hostname.replace(/\.+$/, '');+ return `${host}${parsed.port ? `:${parsed.port}` : ''}${normalizePath(parsed.pathname)}${parsed.search}`;+}++export function describePattern(pattern: string): string {+ const parsed = partsOf(pattern);+ if ('reason' in parsed) return pattern;+ const { host, port, path } = parsed;+ const name = host.includes('*') ? `sites matching ${host}` : hasSubdomains(host) ? `${host} and its subdomains` : host;+ const site = `${name}${port ? `, port ${port}` : ''}`;+ if (!path) return `Every page on ${site}`;+ return `${path.includes('*') ? 'Pages matching' : 'Pages under'} ${path} on ${site}`;+}++const hasSubdomains = (host: string): boolean => host.includes('.') && !/^[\d.]+$|^\[/.test(host);++function partsOf(entry: string): PatternParts | { reason: string } {+ const trimmed = entry.trim();+ if (!trimmed) return { reason: 'Type a site, like example.com.' };+ if (trimmed.length > BLOCKED_SITES_LIMITS.length) {+ return { reason: `Keep it under ${BLOCKED_SITES_LIMITS.length} characters.` };+ }+ if (/\s/.test(trimmed)) return { reason: 'A pattern has no spaces.' };+ if (!WEB_SCHEME.test(trimmed) && ANY_SCHEME.test(trimmed)) {+ return { reason: 'Only web pages (http and https) can be blocked.' };+ }++ const bare = trimmed.replace(WEB_SCHEME, '').replace(/#.*$/, '');+ const split = bare.search(/[/?]/);+ const authority = (split === -1 ? bare : bare.slice(0, split)).toLowerCase();+ const rest = split === -1 ? '' : bare.slice(split);++ if (authority.includes('@')) return { reason: 'Leave out any user name — block the site itself.' };+ const hostPort = /^(\[[0-9a-f:.]+\]|[^:]+)(?::(\d{1,5}))?$/.exec(authority);+ if (!hostPort || Number(hostPort[2] ?? 0) > 65535) {+ return { reason: 'That is not a site name, like example.com or localhost:3000.' };+ }++ const host = normalizeHost(hostPort[1]);+ if (!host) return { reason: 'That is not a site name, like example.com or localhost:3000.' };+ if (/^[*.]+$/.test(host)) return { reason: 'That would block every site.' };++ const port = hostPort[2] && !DEFAULT_PORTS.has(hostPort[2]) ? String(Number(hostPort[2])) : undefined;+ const path = normalizePatternPath(rest);+ return { host, ...(port ? { port } : {}), ...(path ? { path } : {}) };+}++function normalizeHost(raw: string): string | null {+ const host = raw.replace(/\.+$/, '').replace(/^\*\./, '');+ const dropped = host.startsWith('www.') && host.slice(4).includes('.') ? host.slice(4) : host;+ if (!dropped) return null;+ if (!dropped.includes('*')) return asciiHost(dropped);+ const labels = dropped.split('.').map((label) => (label.includes('*') ? label : asciiHost(label)));+ if (labels.some((label) => !label || !WILDCARD_HOST.test(label))) return null;+ return labels.join('.');+}++function asciiHost(host: string): string | null {+ try {+ return new URL(`http://${host}/`).hostname.replace(/\.+$/, '') || null;+ } catch {+ return null;+ }+}++function normalizePatternPath(rest: string): string | undefined {+ if (!rest) return undefined;+ const withSlash = rest.startsWith('?') ? `/${rest}` : rest;+ const query = withSlash.indexOf('?');+ const pathname = normalizePath(query === -1 ? withSlash : withSlash.slice(0, query)).replace(/(.)\/$/, '$1');+ const path = `${pathname}${query === -1 ? '' : withSlash.slice(query)}`;+ return path === '/' ? undefined : path;+}++/** Collapses `//` and decodes escapes that spell plain characters, so `/%61dmin` is `/admin`. */+function normalizePath(path: string): string {+ return path+ .replace(/%([0-9a-f]{2})/gi, (escape, hex: string) => {+ const char = String.fromCharCode(parseInt(hex, 16));+ return /[a-z0-9\-._~]/i.test(char) ? char : escape;+ })+ .replace(/\/{2,}/g, '/');+}++function patternOf({ host, port, path }: PatternParts): string {+ return `${host}${port ? `:${port}` : ''}${path ?? ''}`;+}++function sourceOf(parts: PatternParts): string {+ return `${siteSource(parts)}${pathSource(parts.path)}`;+}++function siteSource({ host, port }: PatternParts): string {+ return `^(?:[^/:]*\\.)?${glob(host, '[^/:]*')}${port ? `:${port}` : '(?::\\d+)?'}`;+}++function pathSource(path: string | undefined): string {+ if (!path) return BOUNDARY;+ return `${glob(path, '.*')}${path.endsWith('*') ? '$' : BOUNDARY}`;+}++function glob(text: string, star: string): string {+ return text+ .split('*')+ .map((piece) => piece.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'))+ .join(star);+}