Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix: revoke cookie-handler coverage and harden consent regex

Emre Sokullu9848741a2f0f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1dabfa0e..4014f42b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ This changelog was generated from the repository Git history and release tags. V
## [Unreleased]
### Added
-- Cookie banners: Act and Dev runs decline cookie-consent banners automatically before the model looks at the page, so a banner no longer costs a step and the agent no longer accepts tracking to get past one. It uses DuckDuckGo's autoconsent rules, bundled unmodified (MPL-2.0) with no network requests, plus WebBrain's own rules for banners those miss (Efilli sites such as n11.com, migros.com.tr, teknosa.com and koton.com; hepsiburada.com; mediamarkt.com.tr) and autoconsent's reject-only heuristic for cookie popups no rule knows, with a WebBrain rule that does the same for Turkish banners until the heuristic reads Turkish. Settings → Advanced → **Cookie banners** can also turn it on for every website, or off. It never runs in CAPTCHA or bot-challenge frames, and banners it has no rule for still get the existing prompt guidance. See `docs/cookie-banners.md`.
+- Cookie banners: Act and Dev runs decline cookie-consent banners automatically before the model looks at the page, so a banner no longer costs a step and the agent no longer accepts tracking to get past one. It uses DuckDuckGo's autoconsent rules, bundled locally (MPL-2.0) with a documented regular-expression security patch with no network requests, plus WebBrain's own rules for banners those miss (Efilli sites such as n11.com, migros.com.tr, teknosa.com and koton.com; hepsiburada.com; mediamarkt.com.tr) and autoconsent's reject-only heuristic for cookie popups no rule knows, with a WebBrain rule that does the same for Turkish banners until the heuristic reads Turkish. Settings → Advanced → **Cookie banners** can also turn it on for every website, or off. It never runs in CAPTCHA or bot-challenge frames, and banners it has no rule for still get the existing prompt guidance. See `docs/cookie-banners.md`.
- Compass VLD Tiny v5, a new in-browser model for Chrome: one 2.2 GB WebGPU download that chats, reads screenshots and answers WebBrain's quick decision questions on your device, with no network once it is downloaded. It is WebBrain's fine-tune of MiniCPM-V-4.7-1B and the new default local model: the first-install guide's **Download local models** button downloads it, instead of D1 and Ternary Bonsai 2 2B Vision, and Apocalypse Mode's Text Model card and Providers → WebGPU list it first. Once, on the first start after the update, a WebGPU provider that was never set up moves to it when Compass Tiny v2.1, the previous default, was never downloaded on that device. Its files are fetched at a fixed revision and each is checked against a pinned size and SHA-256 before it is used; a dropped connection retries that file. Compass Tiny v2.1 and Ternary Bonsai 2 2B Vision stay available.
### Changed
diff --git a/docs/cookie-banners.md b/docs/cookie-banners.md
index 1ce6d58cb..ac9dc5ebb 100644
--- a/docs/cookie-banners.md
+++ b/docs/cookie-banners.md
@@ -3,7 +3,7 @@
WebBrain declines cookie-consent banners itself, so an Act run does not spend a
model step on them and does not accept tracking to get past one. It uses
DuckDuckGo's [autoconsent](https://github.com/duckduckgo/autoconsent) rules,
-vendored unmodified in `src/<browser>/vendor/autoconsent/` (MPL-2.0), plus a few
+vendored with a documented regular-expression security patch in `src/<browser>/vendor/autoconsent/` (MPL-2.0), plus a few
WebBrain rules for banners those miss (see [WebBrain's own rules](#webbrains-own-rules)).
Banners no rule knows get autoconsent's reject-only heuristic
(see [Heuristic](#heuristic-reject-only)).
@@ -21,11 +21,18 @@ Settings → Advanced → **Cookie banners** (storage key `cookieBanners`):
## How it works
- `src/<browser>/src/agent/cookie-banner-host.js` runs in the background. It
- injects `src/content/autoconsent-bridge.js` and
- `vendor/autoconsent/autoconsent.playwright.js` into covered tabs on each
+ injects `src/content/autoconsent-bridge.js` into covered tabs on each
`webNavigation.onCommitted`, and into a page that was already open when a run
- starts. Both files run in the extension's isolated world. Nothing is
- registered in the manifest.
+ starts. It imports WebBrain's `autoconsent-runtime.js` wrapper and the
+ upstream ESM module with that security patch in the extension's isolated world. Those two
+ modules are web-accessible resources for dynamic import; no cookie-handler
+ content script is registered in the manifest.
+- Before every click (including each click of a multi-element rule), the
+ wrapper asks the background whether this frame is still covered. Off
+ cancels existing handlers; in the default agent mode, Stop and the end of
+ an Act/Dev run do too. Cancellation removes pre-hiding and blocks pending
+ clicks. A new covered run starts a fresh
+ instance on the same document; an older instance stays cancelled.
- The bridge forwards autoconsent's messages as `webbrain-autoconsent` /
`webbrain-autoconsent-bg`, so autoconsent's generic types (`init`, `eval`,
`report`) never reach WebBrain's other listeners.
@@ -149,17 +156,21 @@ not try; users choose Off instead.
## Updating
Bump `VERSION` and `INTEGRITY` in `scripts/update-autoconsent.mjs` and run it.
-It copies the published files byte for byte into both trees and records their
-SHA-256 in `vendor-manifest.json`; `node scripts/update-autoconsent.mjs --check`
+It verifies the published package integrity, removes redundant cookie-noun
+alternatives from the acknowledgement regex (preventing exponential
+backtracking), and records both upstream and patched SHA-256 hashes in
+`vendor-manifest.json`; `node scripts/update-autoconsent.mjs --check`
and `test/cookie-banner-host.mjs` verify them. Read upstream's CHANGELOG for
message or rule-format changes before updating.
## License
autoconsent is MPL-2.0, a file-level copyleft. Its files keep their license
-(`vendor/autoconsent/LICENSE`, `LICENSES/MPL-2.0.txt`) and stay unmodified.
+(`vendor/autoconsent/LICENSE`, `LICENSES/MPL-2.0.txt`). The JavaScript bundles
+carry one documented WebBrain regex patch, remain MPL-2.0, and are published
+in full with this repository; the rules and license text are unmodified.
WebBrain's own files, including the bridge, the host and WebBrain's rules, are
under WebBrain's license, GPL-3.0-or-later; MPL-2.0 allows combining its files
-with GPL code (section 3.3, "Secondary Licenses"). If the vendored files are
-ever edited, the edited files stay MPL-2.0 and their source must be published
+with GPL code (section 3.3, "Secondary Licenses"). Further edits to the vendored
+files must also stay MPL-2.0 and be published
with the extension.
diff --git a/docs/security-model.md b/docs/security-model.md
index 4ff15b8e4..1bc3e8090 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -408,7 +408,7 @@ navigate directly or gain new authority.
## Cookie Banners
-Automatic cookie-banner declining (`docs/cookie-banners.md`) injects DuckDuckGo's autoconsent into the extension's isolated world, per navigation, only in tabs the `cookieBanners` setting covers: tabs an Act or Dev run is driving by default, every tab when the user opts in. Nothing is registered in the manifest. Page JavaScript is reached only through autoconsent's fixed eval snippets, run by name in the frame that asked; CAPTCHA and bot-challenge frames are never injected and their eval requests are refused. Subframes are injected only when a rule names their URL. Its clicks are not model actions and do not pass through guards: they only decline or hide consent dialogs that a bundled rule or one of WebBrain's own rules (`src/<browser>/src/agent/cookie-banner-rules.js`, DOM steps only) recognizes, or, for dialogs no rule knows, that autoconsent's reject-only heuristic recognizes from cookie wording (top frame only; it clicks a reject button and nothing else).
+Automatic cookie-banner declining (`docs/cookie-banners.md`) injects DuckDuckGo's autoconsent into the extension's isolated world, per navigation, only in tabs the `cookieBanners` setting covers: tabs an Act or Dev run is driving by default, every tab when the user opts in. No cookie-handler content script is registered in the manifest; the wrapper and upstream ESM module are web-accessible resources for dynamic import. The wrapper rechecks coverage before each click and cancels pending handlers whenever Off, Stop, or run completion revokes their coverage. Page JavaScript is reached only through autoconsent's fixed eval snippets, run by name in the frame that asked; CAPTCHA and bot-challenge frames are never injected and their eval requests are refused. Subframes are injected only when a rule names their URL. Its clicks are not model actions and do not pass through guards: they only decline or hide consent dialogs that a bundled rule or one of WebBrain's own rules (`src/<browser>/src/agent/cookie-banner-rules.js`, DOM steps only) recognizes, or, for dialogs no rule knows, that autoconsent's reject-only heuristic recognizes from cookie wording (top frame only; it clicks a reject button and nothing else).
## Firefox Differences
diff --git a/scripts/update-autoconsent.mjs b/scripts/update-autoconsent.mjs
index 4c6c6cc4f..234d05a36 100644
--- a/scripts/update-autoconsent.mjs
+++ b/scripts/update-autoconsent.mjs
@@ -5,7 +5,7 @@
* node scripts/update-autoconsent.mjs # copy the pinned version
* node scripts/update-autoconsent.mjs --check # verify the vendored copies, no network
*
- * Why copied byte for byte, with no bundler: MPL-2.0 keeps any edited
+ * Why vendored with a documented patch, with no bundler: MPL-2.0 keeps any edited
* autoconsent file under the MPL, and the extension loads from source with no
* build step (AGENT.md). WebBrain's glue lives in its own files, under
* WebBrain's license: src/<browser>/src/content/autoconsent-bridge.js,
@@ -42,6 +42,18 @@ export const FILES = Object.freeze({
LICENSE: 'LICENSE',
});
export const VENDOR_MANIFEST = 'vendor-manifest.json';
+export const REGEX_PATCH = 'deduplicate-acknowledgement-cookie-nouns';
+const PATCH_HEADER = '// WebBrain modification (MPL-2.0): remove redundant acknowledgement regex alternatives to prevent exponential backtracking.\n';
+const UPSTREAM_NOUNS = '|hier|des cookies|de cookies|x)';
+const PATCHED_NOUNS = '|hier|x)';
+
+// "des cookies" and "de cookies" are already matched by the optional
+// des/de article followed by cookie\\w*. Keeping both parses makes repeated
+// cookie phrases exponential on a non-matching suffix (CodeQL js/redos).
+export function patchAutoconsentRegex(source) {
+ if (source.split(UPSTREAM_NOUNS).length !== 2) throw new Error('Upstream acknowledgement regex changed; review the patch');
+ return PATCH_HEADER + source.replace(UPSTREAM_NOUNS, PATCHED_NOUNS);
+}
function sha256(file) {
return createHash('sha256').update(readFileSync(file)).digest('hex');
@@ -61,9 +73,13 @@ cookie-consent banners. WebBrain uses it for the "Cookie banners" setting; see
- Source: ${manifest.source}
- License: Mozilla Public License 2.0 (\`LICENSE\` here, and \`LICENSES/MPL-2.0.txt\` at the repository root)
-These files are copied from the npm package **unmodified**. Do not edit them:
-under the MPL an edited copy stays MPL-licensed and its changes must be
-published. WebBrain's own code that drives them lives outside this folder
+The JavaScript bundles carry one reproducible WebBrain patch: remove the
+redundant 'des cookies' / 'de cookies' acknowledgement-regex alternatives
+that cause exponential backtracking. The optional articles already cover
+those phrases. The patch is in 'scripts/update-autoconsent.mjs'; upstream
+and patched hashes are recorded in 'vendor-manifest.json'.
+These modified files remain MPL-2.0 and their complete source is published
+here. Rules and license text are copied unmodified. WebBrain's own code lives outside this folder
(\`src/content/autoconsent-bridge.js\`, \`src/agent/cookie-banner-host.js\`, and
WebBrain's own rules in \`src/agent/cookie-banner-rules.js\`) and is under
WebBrain's license, GPL-3.0-or-later; MPL-2.0 allows that combination
@@ -98,9 +114,12 @@ export function vendorAutoconsent(root = ROOT) {
try {
const pkg = fetchPackage(tmp);
const files = {};
+ const upstreamFiles = {};
for (const [from, to] of Object.entries(FILES)) {
const source = path.join(pkg, from);
if (!existsSync(source)) throw new Error(`${PACKAGE}@${VERSION} has no ${from}`);
+ upstreamFiles[to] = sha256(source);
+ if (to.endsWith('.js')) writeFileSync(source, patchAutoconsentRegex(readFileSync(source, 'utf8')));
files[to] = sha256(source);
}
const manifest = {
@@ -109,6 +128,8 @@ export function vendorAutoconsent(root = ROOT) {
integrity: INTEGRITY,
source: `https://github.com/duckduckgo/autoconsent/tree/v${VERSION}`,
license: 'MPL-2.0',
+ patches: [REGEX_PATCH],
+ upstreamFiles,
files,
};
for (const dir of VENDOR_DIRS) {
@@ -139,12 +160,20 @@ export function checkVendoredAutoconsent(root = ROOT) {
if (manifest.version !== VERSION || manifest.integrity !== INTEGRITY) {
problems.push(`${dir} holds ${manifest.version}, expected ${VERSION}`);
}
+ if (JSON.stringify(manifest.patches) !== JSON.stringify([REGEX_PATCH])) problems.push(`${dir} is missing the regex hardening patch`);
for (const name of Object.values(FILES)) {
const file = path.join(root, dir, name);
if (!existsSync(file)) {
problems.push(`${dir}/${name} is missing`);
} else if (sha256(file) !== manifest.files?.[name]) {
- problems.push(`${dir}/${name} differs from ${PACKAGE}@${manifest.version}; vendored files must stay unmodified`);
+ problems.push(`${dir}/${name} differs from its recorded patched hash`);
+ } else if (name.endsWith('.js')) {
+ const patched = readFileSync(file, 'utf8');
+ const original = patched.slice(PATCH_HEADER.length).replace(PATCHED_NOUNS, UPSTREAM_NOUNS);
+ if (!patched.startsWith(PATCH_HEADER) || patched.split(PATCHED_NOUNS).length !== 2
+ || createHash('sha256').update(original).digest('hex') !== manifest.upstreamFiles?.[name]) {
+ problems.push(`${dir}/${name} cannot be reconstructed as the pinned upstream file plus the documented patch`);
+ }
}
}
}
diff --git a/src/chrome/manifest.json b/src/chrome/manifest.json
index 914a85e27..a98ff9156 100644
--- a/src/chrome/manifest.json
+++ b/src/chrome/manifest.json
@@ -170,7 +170,7 @@
},
"web_accessible_resources": [
{
- "resources": ["vendor/pdfjs/pdf.mjs", "vendor/pdfjs/pdf.worker.mjs", "skills/*"],
+ "resources": ["src/content/autoconsent-runtime.js", "vendor/autoconsent/autoconsent.esm.js", "vendor/pdfjs/pdf.mjs", "vendor/pdfjs/pdf.worker.mjs", "skills/*"],
"matches": ["<all_urls>"]
}
]
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 1732d3b73..0a7ae26c6 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -6345,6 +6345,7 @@ export class Agent extends LoopDetector {
this._runAbortStates.delete(tabId);
this.abortFlags.delete(tabId);
this._runningTabs.delete(tabId);
+ this._cookieBannerHost?.refreshCoverage?.(tabId);
}
_runAbortSignal(tabId) {
@@ -21895,6 +21896,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this._revokeSocialPublicationAuditRetry(id);
this._ownedNativeChatReadRepairs.delete(id);
this.abortFlags.set(id, true);
+ this._cookieBannerHost?.refreshCoverage?.(id);
cdpClient.stopDialogHandling(id);
const controller = this._runAbortStates.get(id)?.controller;
if (controller && !controller.signal.aborted) {
diff --git a/src/chrome/src/agent/cookie-banner-host.js b/src/chrome/src/agent/cookie-banner-host.js
index 5cd7e746a..f30277e39 100644
--- a/src/chrome/src/agent/cookie-banner-host.js
+++ b/src/chrome/src/agent/cookie-banner-host.js
@@ -1,11 +1,11 @@
// Declines cookie-consent banners with DuckDuckGo's autoconsent (vendored,
-// unmodified, MPL-2.0; see vendor/autoconsent/README.md). This is the
+// regex-hardened, MPL-2.0; see vendor/autoconsent/README.md). This is the
// background half: it decides where the content half runs, answers its
// init/eval requests, and tells the agent what happened. docs/cookie-banners.md
// has the user-facing behavior.
//
// Why it is shaped this way:
-// - Nothing is registered in the manifest. The CAPTCHA callback bridge once ran
+// - No static content script is registered. The CAPTCHA callback bridge once ran
// on every site in every frame and broke hCaptcha/Turnstile pages, so these
// scripts are injected per navigation, only into tabs the setting covers:
// tabs an Act/Dev run is driving ('agent', the default) or every tab
@@ -32,7 +32,6 @@ export const COOKIE_BANNER_STATUS_MESSAGE = 'webbrain-cookie-banner-status';
const CONTENT_FILES = Object.freeze([
'src/content/autoconsent-bridge.js',
- 'vendor/autoconsent/autoconsent.playwright.js',
]);
const RULES_FILE = 'vendor/autoconsent/compact-rules.json';
const ACTION_MODES = new Set(['act', 'dev']);
@@ -538,6 +537,15 @@ export function createCookieBannerHost(api, options = {}) {
function onMessage(message, sender, sendResponse) {
if (message?.type === COOKIE_BANNER_CONTENT_MESSAGE) {
+ if (message.msg?.type === 'checkCoverage') {
+ const tabId = sender?.tab?.id;
+ const frame = tabState(tabId)?.frames.get(sender?.frameId);
+ const covered = Boolean(frame && !frame.failed && coversTab(tabId)
+ && !isChallengeFrameUrl(sender?.url));
+ sendResponse(covered);
+ if (!covered) refreshCoverage(tabId);
+ return;
+ }
onContentMessage(message, sender);
return;
}
@@ -561,12 +569,18 @@ export function createCookieBannerHost(api, options = {}) {
};
}
+ function refreshCoverage(tabId) {
+ if (coversTab(tabId)) return;
+ const state = tabState(tabId);
+ for (const frameId of state?.frames.keys() || []) send(tabId, frameId, { type: 'stop' });
+ tabs.delete(tabId);
+ notify(tabId);
+ }
+
function setMode(value) {
modeChanged = true;
mode = normalizeCookieBannerMode(value);
- if (mode === 'off') {
- for (const tabId of tabs.keys()) notify(tabId);
- }
+ for (const tabId of tabs.keys()) refreshCoverage(tabId);
return mode;
}
@@ -587,6 +601,7 @@ export function createCookieBannerHost(api, options = {}) {
api.storage?.onChanged?.addListener?.(onStorageChanged);
},
setMode,
+ refreshCoverage,
get mode() {
return mode;
},
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index bbac471f3..e6aa0a013 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -1262,7 +1262,7 @@ loadCaptchaSolver().catch(error => console.warn('[WebBrain] CAPTCHA settings cou
// that setting. Its listeners are registered here, at worker start, so a
// navigation can wake the worker.
const cookieBannerHost = createCookieBannerHost(chrome, {
- isRunActive: tabId => agent.isRunning(tabId),
+ isRunActive: tabId => agent.isRunning(tabId) && !agent.abortFlags.get(tabId),
runMode: tabId => agent._effectiveRunMode(tabId),
});
cookieBannerHost.start();
diff --git a/src/chrome/src/content/autoconsent-bridge.js b/src/chrome/src/content/autoconsent-bridge.js
index f06a83cd6..9e5c8715c 100644
--- a/src/chrome/src/content/autoconsent-bridge.js
+++ b/src/chrome/src/content/autoconsent-bridge.js
@@ -1,46 +1,49 @@
-// Injected by src/agent/cookie-banner-host.js into WebBrain's isolated world,
-// right before vendor/autoconsent/autoconsent.playwright.js. That upstream
-// script talks only through window.autoconsentSendMessage and
-// window.autoconsentReceiveMessage; in an isolated world those globals are
-// invisible to the page. Messages are namespaced so autoconsent's generic
-// types ('init', 'eval', 'report') never reach WebBrain's other listeners.
+// Per-frame isolated-world loader. A fresh instance is needed after coverage
+// is restored: an old instance's pending rule steps must stay cancelled.
(() => {
const existing = window.__webbrainAutoconsentBridge;
- if (existing) {
- // Injected again after the service worker restarted and lost its record
- // of this frame: tell it where this frame's run already is.
- existing.resync();
- return;
- }
+ if (existing) { existing.resync(); return; }
const api = globalThis.browser || globalThis.chrome;
const CONTENT_MESSAGE = 'webbrain-autoconsent';
const BACKGROUND_MESSAGE = 'webbrain-autoconsent-bg';
- let lastReport = null;
-
- const send = (msg) => {
- try {
- const sent = api.runtime.sendMessage({ type: CONTENT_MESSAGE, msg });
- sent?.catch?.(() => {});
- } catch {
- // The extension was reloaded; this frame's copy is orphaned.
- }
- };
-
- window.autoconsentSendMessage = async (msg) => {
- if (msg?.type === 'report') lastReport = msg;
- send(msg);
- };
+ let current;
+ const send = msg => api.runtime.sendMessage({ type: CONTENT_MESSAGE, msg });
- api.runtime.onMessage.addListener((message) => {
+ function stop() {
+ if (!current) return;
+ current.cancelled = true;
+ current.runtime?.stop();
+ current.lastReport = null;
+ }
+ function start() {
+ const owner = { cancelled: false, runtime: null, lastReport: null };
+ current = owner;
+ import(api.runtime.getURL('src/content/autoconsent-runtime.js')).then(({ createCookieBannerRuntime }) => {
+ if (owner.cancelled || current !== owner) return;
+ owner.runtime = createCookieBannerRuntime(msg => {
+ if (owner.cancelled || current !== owner) return;
+ if (msg.type === 'report') owner.lastReport = msg;
+ try { send(msg)?.catch?.(() => {}); } catch { stop(); }
+ }, () => send({ type: 'checkCoverage' }));
+ }).catch(() => { if (current === owner) stop(); });
+ }
+ api.runtime.onMessage.addListener(message => {
if (message?.type !== BACKGROUND_MESSAGE || !message.msg) return;
- const receive = window.autoconsentReceiveMessage;
- if (typeof receive !== 'function') return;
- Promise.resolve(receive(message.msg)).catch(() => {});
+ if (message.msg.type === 'stop') { stop(); return; }
+ Promise.resolve(current?.runtime?.receive(message.msg)).catch(() => stop());
});
-
+ api.storage.onChanged.addListener((changes, area) => {
+ if (area === 'local' && changes.cookieBanners?.newValue === 'off') stop();
+ });
+ // Kept in the isolated world for diagnostics; page JavaScript sees neither.
+ window.autoconsentReceiveMessage = message => current?.runtime?.receive(message);
window.__webbrainAutoconsentBridge = {
resync() {
- if (lastReport) send(lastReport);
+ if (current?.cancelled || current?.runtime?.stopped) start();
+ else if (current?.lastReport) {
+ try { send(current.lastReport)?.catch?.(() => {}); } catch { stop(); }
+ }
},
};
+ start();
})();
diff --git a/src/chrome/src/content/autoconsent-runtime.js b/src/chrome/src/content/autoconsent-runtime.js
new file mode 100644
index 000000000..0682a38a5
--- /dev/null
+++ b/src/chrome/src/content/autoconsent-runtime.js
@@ -0,0 +1,104 @@
+// Keep cancellation outside the upstream module. All clicks, including delayed
+// clicks in waitForThenClick and click-all rules, recheck background coverage.
+import AutoConsent from '../../vendor/autoconsent/autoconsent.esm.js';
+
+export function guardCookieBannerInstance(consent, hasCoverage) {
+ let stopped = false;
+ const cancelled = new Error('Cookie-banner coverage revoked');
+ function stop() {
+ if (stopped) return;
+ stopped = true;
+ try {
+ consent.config.enabled = false;
+ consent.config.autoAction = null;
+ consent.undoPrehide();
+ } catch {} // It may not have received its init response yet.
+ }
+ async function allowed() {
+ if (stopped) return false;
+ let covered = false;
+ try { covered = await hasCoverage() === true; } catch {}
+ if (stopped || !covered) {
+ stop();
+ return false;
+ }
+ return true;
+ }
+ async function requireCoverage() {
+ if (!await allowed()) throw cancelled;
+ }
+ for (const name of ['_start', 'doOptOut', 'doOptIn', 'handlePopup']) {
+ if (typeof consent[name] !== 'function') continue;
+ const original = consent[name].bind(consent);
+ consent[name] = async (...args) => {
+ try {
+ await requireCoverage();
+ return await original(...args);
+ } catch (error) {
+ if (error !== cancelled) throw error;
+ return false;
+ }
+ };
+ }
+ for (const name of ['findCmp', 'waitForPopup']) {
+ const original = consent[name].bind(consent);
+ consent[name] = (...args) => stopped ? Promise.resolve(name === 'findCmp' ? [] : false) : original(...args);
+ }
+ const dom = consent.domActions;
+ const clickElement = dom.clickElement.bind(dom);
+ dom.clickElement = async element => {
+ await requireCoverage();
+ const result = await clickElement(element);
+ await requireCoverage();
+ return result;
+ };
+ dom.click = async (selector, all = false) => {
+ const elements = dom.elementSelector(selector);
+ if (!elements.length) return false;
+ for (const element of all ? elements : elements.slice(0, 1)) {
+ if (!await dom.clickElement(element)) return false;
+ }
+ return true;
+ };
+ // Some upstream dynamic rules use raw element.click() after awaiting a
+ // helper. Unwind the rule at that boundary, rather than returning false
+ // and letting it continue into those direct mutations.
+ for (const name of ['wait', 'waitForElement', 'waitForVisible', 'waitForThenClick']) {
+ if (typeof dom[name] !== 'function') continue;
+ const original = dom[name].bind(dom);
+ dom[name] = async (...args) => {
+ await requireCoverage();
+ const result = await original(...args);
+ await requireCoverage();
+ return result;
+ };
+ }
+ // These upstream helpers are synchronous. Revocation also stops cosmetic
+ // changes and pre-hiding while an earlier rule is waiting for an element.
+ for (const name of ['hide', 'stylesheet', 'removeClass', 'setStyle', 'addStyle', 'prehide']) {
+ const original = dom[name].bind(dom);
+ dom[name] = (...args) => stopped ? false : original(...args);
+ }
+ const restoreFocus = consent.restoreFocus.bind(consent);
+ consent.restoreFocus = () => { if (!stopped) restoreFocus(); };
+ return { stop, get stopped() { return stopped; } };
+}
+
+export function createCookieBannerRuntime(send, hasCoverage) {
+ let guard;
+ const consent = new AutoConsent(message => {
+ if (!guard?.stopped) send(message);
+ }, null, { autoconsent: [] });
+ guard = guardCookieBannerInstance(consent, hasCoverage);
+ return {
+ stop: guard.stop,
+ get stopped() { return guard.stopped; },
+ receive(message) {
+ if (message.type === 'stop' || (message.type === 'initResp' && !message.config?.enabled)) {
+ guard.stop();
+ return;
+ }
+ if (!guard.stopped) return consent.receiveMessageCallback(message);
+ },
+ };
+}
diff --git a/src/chrome/vendor/autoconsent/README.md b/src/chrome/vendor/autoconsent/README.md
index fa9547ee5..085181787 100644
--- a/src/chrome/vendor/autoconsent/README.md
+++ b/src/chrome/vendor/autoconsent/README.md
@@ -8,9 +8,13 @@ cookie-consent banners. WebBrain uses it for the "Cookie banners" setting; see
- Source: https://github.com/duckduckgo/autoconsent/tree/v16.61.0
- License: Mozilla Public License 2.0 (`LICENSE` here, and `LICENSES/MPL-2.0.txt` at the repository root)
-These files are copied from the npm package **unmodified**. Do not edit them:
-under the MPL an edited copy stays MPL-licensed and its changes must be
-published. WebBrain's own code that drives them lives outside this folder
+The JavaScript bundles carry one reproducible WebBrain patch: remove the
+redundant 'des cookies' / 'de cookies' acknowledgement-regex alternatives
+that cause exponential backtracking. The optional articles already cover
+those phrases. The patch is in 'scripts/update-autoconsent.mjs'; upstream
+and patched hashes are recorded in 'vendor-manifest.json'.
+These modified files remain MPL-2.0 and their complete source is published
+here. Rules and license text are copied unmodified. WebBrain's own code lives outside this folder
(`src/content/autoconsent-bridge.js`, `src/agent/cookie-banner-host.js`, and
WebBrain's own rules in `src/agent/cookie-banner-rules.js`) and is under
WebBrain's license, GPL-3.0-or-later; MPL-2.0 allows that combination
@@ -22,7 +26,7 @@ verifies these copies against the hashes below.
| File | SHA-256 |
|---|---|
-| `autoconsent.playwright.js` | `acf22263a6e8d6e0485e162ac9c78974a148afb8051c4f67328dbb004f929484` |
-| `autoconsent.esm.js` | `47bed6a4229c7011c4656d9c1378a32c1a01aae0d59e1f10c180dbec1ba5285b` |
+| `autoconsent.playwright.js` | `c86e87c111ce52e627fa335a79a2190a48b45ebe3eb12831dd0e712c627046c1` |
+| `autoconsent.esm.js` | `96c2c07d6e224e96076815abb218178cb5883c27bc0690ae5613ca9d3d223b15` |
| `compact-rules.json` | `bc3e27b8e5a529be4db748ac8940f1ade9c848aeb3dce6cdd4807b9e03390647` |
| `LICENSE` | `fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85` |
diff --git a/src/chrome/vendor/autoconsent/autoconsent.esm.js b/src/chrome/vendor/autoconsent/autoconsent.esm.js
index ea86f0690..207d0cda3 100644
--- a/src/chrome/vendor/autoconsent/autoconsent.esm.js
+++ b/src/chrome/vendor/autoconsent/autoconsent.esm.js
@@ -1,3 +1,4 @@
+// WebBrain modification (MPL-2.0): remove redundant acknowledgement regex alternatives to prevent exponential backtracking.
var __typeError = (msg) => {
throw TypeError(msg);
};
@@ -1170,7 +1171,7 @@ var ACCEPT_PATTERNS = [
var ACKNOWLEDGE_PATTERNS = [
// close / dismiss the banner/dialog/message (multilingual). The negative lookahead avoids
// accept/save phrases (e.g. "agree and close", "akkoord en sluiten", "speichern schließen").
- /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|des cookies|de cookies|x))*\.?\s*$/is,
+ /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|x))*\.?\s*$/is,
// "ok" / "okay" / "oké" (optionally followed by a short acknowledgement)
/^(ok|okay|oké|okey|k)([ .!,]*)(got it|verstanden|compris|rozumiem|thanks|gracias|ik begrijp( dat| het)?|continue to website|pour moi|fermer)?[ .!]*$/is,
// "understood" / "got it" / "that's ok" (multilingual)
diff --git a/src/chrome/vendor/autoconsent/autoconsent.playwright.js b/src/chrome/vendor/autoconsent/autoconsent.playwright.js
index ae6381dff..08fe18a3d 100644
--- a/src/chrome/vendor/autoconsent/autoconsent.playwright.js
+++ b/src/chrome/vendor/autoconsent/autoconsent.playwright.js
@@ -1,3 +1,4 @@
+// WebBrain modification (MPL-2.0): remove redundant acknowledgement regex alternatives to prevent exponential backtracking.
"use strict";
(() => {
var __typeError = (msg) => {
@@ -1172,7 +1173,7 @@
var ACKNOWLEDGE_PATTERNS = [
// close / dismiss the banner/dialog/message (multilingual). The negative lookahead avoids
// accept/save phrases (e.g. "agree and close", "akkoord en sluiten", "speichern schließen").
- /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|des cookies|de cookies|x))*\.?\s*$/is,
+ /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|x))*\.?\s*$/is,
// "ok" / "okay" / "oké" (optionally followed by a short acknowledgement)
/^(ok|okay|oké|okey|k)([ .!,]*)(got it|verstanden|compris|rozumiem|thanks|gracias|ik begrijp( dat| het)?|continue to website|pour moi|fermer)?[ .!]*$/is,
// "understood" / "got it" / "that's ok" (multilingual)
diff --git a/src/chrome/vendor/autoconsent/vendor-manifest.json b/src/chrome/vendor/autoconsent/vendor-manifest.json
index 897505bb5..6b563535a 100644
--- a/src/chrome/vendor/autoconsent/vendor-manifest.json
+++ b/src/chrome/vendor/autoconsent/vendor-manifest.json
@@ -4,10 +4,19 @@
"integrity": "sha512-XRHCE4J9Q3tpF6TgbCilKDemBQsAWHBFR9S93UEwCnFA9jP54FTENz8nYez8/zyxh2O3O3r/K/gI8+DwtE4p6Q==",
"source": "https://github.com/duckduckgo/autoconsent/tree/v16.61.0",
"license": "MPL-2.0",
- "files": {
+ "patches": [
+ "deduplicate-acknowledgement-cookie-nouns"
+ ],
+ "upstreamFiles": {
"autoconsent.playwright.js": "acf22263a6e8d6e0485e162ac9c78974a148afb8051c4f67328dbb004f929484",
"autoconsent.esm.js": "47bed6a4229c7011c4656d9c1378a32c1a01aae0d59e1f10c180dbec1ba5285b",
"compact-rules.json": "bc3e27b8e5a529be4db748ac8940f1ade9c848aeb3dce6cdd4807b9e03390647",
"LICENSE": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85"
+ },
+ "files": {
+ "autoconsent.playwright.js": "c86e87c111ce52e627fa335a79a2190a48b45ebe3eb12831dd0e712c627046c1",
+ "autoconsent.esm.js": "96c2c07d6e224e96076815abb218178cb5883c27bc0690ae5613ca9d3d223b15",
+ "compact-rules.json": "bc3e27b8e5a529be4db748ac8940f1ade9c848aeb3dce6cdd4807b9e03390647",
+ "LICENSE": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85"
}
}
diff --git a/src/firefox/manifest.json b/src/firefox/manifest.json
index 989cfcedc..29c3d4a81 100644
--- a/src/firefox/manifest.json
+++ b/src/firefox/manifest.json
@@ -152,6 +152,8 @@
"128": "icons/icon128.png"
},
"web_accessible_resources": [
+ "src/content/autoconsent-runtime.js",
+ "vendor/autoconsent/autoconsent.esm.js",
"vendor/pdfjs/pdf.mjs",
"vendor/pdfjs/pdf.worker.mjs",
"src/agent/social-media-downloader.js",
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index 221f38929..17c15deea 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -5887,6 +5887,7 @@ export class Agent extends LoopDetector {
this._runAbortStates.delete(tabId);
this.abortFlags.delete(tabId);
this._runningTabs.delete(tabId);
+ this._cookieBannerHost?.refreshCoverage?.(tabId);
}
_runAbortSignal(tabId) {
@@ -18927,6 +18928,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this._revokeSocialPublicationAuditRetry(id);
this._ownedNativeChatReadRepairs.delete(id);
this.abortFlags.set(id, true);
+ this._cookieBannerHost?.refreshCoverage?.(id);
const controller = this._runAbortStates.get(id)?.controller;
if (controller && !controller.signal.aborted) {
const error = new Error('Stopped by user');
diff --git a/src/firefox/src/agent/cookie-banner-host.js b/src/firefox/src/agent/cookie-banner-host.js
index 5cd7e746a..f30277e39 100644
--- a/src/firefox/src/agent/cookie-banner-host.js
+++ b/src/firefox/src/agent/cookie-banner-host.js
@@ -1,11 +1,11 @@
// Declines cookie-consent banners with DuckDuckGo's autoconsent (vendored,
-// unmodified, MPL-2.0; see vendor/autoconsent/README.md). This is the
+// regex-hardened, MPL-2.0; see vendor/autoconsent/README.md). This is the
// background half: it decides where the content half runs, answers its
// init/eval requests, and tells the agent what happened. docs/cookie-banners.md
// has the user-facing behavior.
//
// Why it is shaped this way:
-// - Nothing is registered in the manifest. The CAPTCHA callback bridge once ran
+// - No static content script is registered. The CAPTCHA callback bridge once ran
// on every site in every frame and broke hCaptcha/Turnstile pages, so these
// scripts are injected per navigation, only into tabs the setting covers:
// tabs an Act/Dev run is driving ('agent', the default) or every tab
@@ -32,7 +32,6 @@ export const COOKIE_BANNER_STATUS_MESSAGE = 'webbrain-cookie-banner-status';
const CONTENT_FILES = Object.freeze([
'src/content/autoconsent-bridge.js',
- 'vendor/autoconsent/autoconsent.playwright.js',
]);
const RULES_FILE = 'vendor/autoconsent/compact-rules.json';
const ACTION_MODES = new Set(['act', 'dev']);
@@ -538,6 +537,15 @@ export function createCookieBannerHost(api, options = {}) {
function onMessage(message, sender, sendResponse) {
if (message?.type === COOKIE_BANNER_CONTENT_MESSAGE) {
+ if (message.msg?.type === 'checkCoverage') {
+ const tabId = sender?.tab?.id;
+ const frame = tabState(tabId)?.frames.get(sender?.frameId);
+ const covered = Boolean(frame && !frame.failed && coversTab(tabId)
+ && !isChallengeFrameUrl(sender?.url));
+ sendResponse(covered);
+ if (!covered) refreshCoverage(tabId);
+ return;
+ }
onContentMessage(message, sender);
return;
}
@@ -561,12 +569,18 @@ export function createCookieBannerHost(api, options = {}) {
};
}
+ function refreshCoverage(tabId) {
+ if (coversTab(tabId)) return;
+ const state = tabState(tabId);
+ for (const frameId of state?.frames.keys() || []) send(tabId, frameId, { type: 'stop' });
+ tabs.delete(tabId);
+ notify(tabId);
+ }
+
function setMode(value) {
modeChanged = true;
mode = normalizeCookieBannerMode(value);
- if (mode === 'off') {
- for (const tabId of tabs.keys()) notify(tabId);
- }
+ for (const tabId of tabs.keys()) refreshCoverage(tabId);
return mode;
}
@@ -587,6 +601,7 @@ export function createCookieBannerHost(api, options = {}) {
api.storage?.onChanged?.addListener?.(onStorageChanged);
},
setMode,
+ refreshCoverage,
get mode() {
return mode;
},
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 12ec75dda..61fd3fc33 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -1122,7 +1122,7 @@ loadCaptchaSolver().catch(error => console.warn('[WebBrain] CAPTCHA settings cou
// that setting. Its listeners are registered here, at worker start, so a
// navigation can wake the worker.
const cookieBannerHost = createCookieBannerHost(browser, {
- isRunActive: tabId => agent.isRunning(tabId),
+ isRunActive: tabId => agent.isRunning(tabId) && !agent.abortFlags.get(tabId),
runMode: tabId => agent._effectiveRunMode(tabId),
// Extension-root paths, as captcha-bridge-registration.js uses on Firefox.
absoluteFilePaths: true,
diff --git a/src/firefox/src/content/autoconsent-bridge.js b/src/firefox/src/content/autoconsent-bridge.js
index f06a83cd6..9e5c8715c 100644
--- a/src/firefox/src/content/autoconsent-bridge.js
+++ b/src/firefox/src/content/autoconsent-bridge.js
@@ -1,46 +1,49 @@
-// Injected by src/agent/cookie-banner-host.js into WebBrain's isolated world,
-// right before vendor/autoconsent/autoconsent.playwright.js. That upstream
-// script talks only through window.autoconsentSendMessage and
-// window.autoconsentReceiveMessage; in an isolated world those globals are
-// invisible to the page. Messages are namespaced so autoconsent's generic
-// types ('init', 'eval', 'report') never reach WebBrain's other listeners.
+// Per-frame isolated-world loader. A fresh instance is needed after coverage
+// is restored: an old instance's pending rule steps must stay cancelled.
(() => {
const existing = window.__webbrainAutoconsentBridge;
- if (existing) {
- // Injected again after the service worker restarted and lost its record
- // of this frame: tell it where this frame's run already is.
- existing.resync();
- return;
- }
+ if (existing) { existing.resync(); return; }
const api = globalThis.browser || globalThis.chrome;
const CONTENT_MESSAGE = 'webbrain-autoconsent';
const BACKGROUND_MESSAGE = 'webbrain-autoconsent-bg';
- let lastReport = null;
-
- const send = (msg) => {
- try {
- const sent = api.runtime.sendMessage({ type: CONTENT_MESSAGE, msg });
- sent?.catch?.(() => {});
- } catch {
- // The extension was reloaded; this frame's copy is orphaned.
- }
- };
-
- window.autoconsentSendMessage = async (msg) => {
- if (msg?.type === 'report') lastReport = msg;
- send(msg);
- };
+ let current;
+ const send = msg => api.runtime.sendMessage({ type: CONTENT_MESSAGE, msg });
- api.runtime.onMessage.addListener((message) => {
+ function stop() {
+ if (!current) return;
+ current.cancelled = true;
+ current.runtime?.stop();
+ current.lastReport = null;
+ }
+ function start() {
+ const owner = { cancelled: false, runtime: null, lastReport: null };
+ current = owner;
+ import(api.runtime.getURL('src/content/autoconsent-runtime.js')).then(({ createCookieBannerRuntime }) => {
+ if (owner.cancelled || current !== owner) return;
+ owner.runtime = createCookieBannerRuntime(msg => {
+ if (owner.cancelled || current !== owner) return;
+ if (msg.type === 'report') owner.lastReport = msg;
+ try { send(msg)?.catch?.(() => {}); } catch { stop(); }
+ }, () => send({ type: 'checkCoverage' }));
+ }).catch(() => { if (current === owner) stop(); });
+ }
+ api.runtime.onMessage.addListener(message => {
if (message?.type !== BACKGROUND_MESSAGE || !message.msg) return;
- const receive = window.autoconsentReceiveMessage;
- if (typeof receive !== 'function') return;
- Promise.resolve(receive(message.msg)).catch(() => {});
+ if (message.msg.type === 'stop') { stop(); return; }
+ Promise.resolve(current?.runtime?.receive(message.msg)).catch(() => stop());
});
-
+ api.storage.onChanged.addListener((changes, area) => {
+ if (area === 'local' && changes.cookieBanners?.newValue === 'off') stop();
+ });
+ // Kept in the isolated world for diagnostics; page JavaScript sees neither.
+ window.autoconsentReceiveMessage = message => current?.runtime?.receive(message);
window.__webbrainAutoconsentBridge = {
resync() {
- if (lastReport) send(lastReport);
+ if (current?.cancelled || current?.runtime?.stopped) start();
+ else if (current?.lastReport) {
+ try { send(current.lastReport)?.catch?.(() => {}); } catch { stop(); }
+ }
},
};
+ start();
})();
diff --git a/src/firefox/src/content/autoconsent-runtime.js b/src/firefox/src/content/autoconsent-runtime.js
new file mode 100644
index 000000000..0682a38a5
--- /dev/null
+++ b/src/firefox/src/content/autoconsent-runtime.js
@@ -0,0 +1,104 @@
+// Keep cancellation outside the upstream module. All clicks, including delayed
+// clicks in waitForThenClick and click-all rules, recheck background coverage.
+import AutoConsent from '../../vendor/autoconsent/autoconsent.esm.js';
+
+export function guardCookieBannerInstance(consent, hasCoverage) {
+ let stopped = false;
+ const cancelled = new Error('Cookie-banner coverage revoked');
+ function stop() {
+ if (stopped) return;
+ stopped = true;
+ try {
+ consent.config.enabled = false;
+ consent.config.autoAction = null;
+ consent.undoPrehide();
+ } catch {} // It may not have received its init response yet.
+ }
+ async function allowed() {
+ if (stopped) return false;
+ let covered = false;
+ try { covered = await hasCoverage() === true; } catch {}
+ if (stopped || !covered) {
+ stop();
+ return false;
+ }
+ return true;
+ }
+ async function requireCoverage() {
+ if (!await allowed()) throw cancelled;
+ }
+ for (const name of ['_start', 'doOptOut', 'doOptIn', 'handlePopup']) {
+ if (typeof consent[name] !== 'function') continue;
+ const original = consent[name].bind(consent);
+ consent[name] = async (...args) => {
+ try {
+ await requireCoverage();
+ return await original(...args);
+ } catch (error) {
+ if (error !== cancelled) throw error;
+ return false;
+ }
+ };
+ }
+ for (const name of ['findCmp', 'waitForPopup']) {
+ const original = consent[name].bind(consent);
+ consent[name] = (...args) => stopped ? Promise.resolve(name === 'findCmp' ? [] : false) : original(...args);
+ }
+ const dom = consent.domActions;
+ const clickElement = dom.clickElement.bind(dom);
+ dom.clickElement = async element => {
+ await requireCoverage();
+ const result = await clickElement(element);
+ await requireCoverage();
+ return result;
+ };
+ dom.click = async (selector, all = false) => {
+ const elements = dom.elementSelector(selector);
+ if (!elements.length) return false;
+ for (const element of all ? elements : elements.slice(0, 1)) {
+ if (!await dom.clickElement(element)) return false;
+ }
+ return true;
+ };
+ // Some upstream dynamic rules use raw element.click() after awaiting a
+ // helper. Unwind the rule at that boundary, rather than returning false
+ // and letting it continue into those direct mutations.
+ for (const name of ['wait', 'waitForElement', 'waitForVisible', 'waitForThenClick']) {
+ if (typeof dom[name] !== 'function') continue;
+ const original = dom[name].bind(dom);
+ dom[name] = async (...args) => {
+ await requireCoverage();
+ const result = await original(...args);
+ await requireCoverage();
+ return result;
+ };
+ }
+ // These upstream helpers are synchronous. Revocation also stops cosmetic
+ // changes and pre-hiding while an earlier rule is waiting for an element.
+ for (const name of ['hide', 'stylesheet', 'removeClass', 'setStyle', 'addStyle', 'prehide']) {
+ const original = dom[name].bind(dom);
+ dom[name] = (...args) => stopped ? false : original(...args);
+ }
+ const restoreFocus = consent.restoreFocus.bind(consent);
+ consent.restoreFocus = () => { if (!stopped) restoreFocus(); };
+ return { stop, get stopped() { return stopped; } };
+}
+
+export function createCookieBannerRuntime(send, hasCoverage) {
+ let guard;
+ const consent = new AutoConsent(message => {
+ if (!guard?.stopped) send(message);
+ }, null, { autoconsent: [] });
+ guard = guardCookieBannerInstance(consent, hasCoverage);
+ return {
+ stop: guard.stop,
+ get stopped() { return guard.stopped; },
+ receive(message) {
+ if (message.type === 'stop' || (message.type === 'initResp' && !message.config?.enabled)) {
+ guard.stop();
+ return;
+ }
+ if (!guard.stopped) return consent.receiveMessageCallback(message);
+ },
+ };
+}
diff --git a/src/firefox/vendor/autoconsent/README.md b/src/firefox/vendor/autoconsent/README.md
index fa9547ee5..085181787 100644
--- a/src/firefox/vendor/autoconsent/README.md
+++ b/src/firefox/vendor/autoconsent/README.md
@@ -8,9 +8,13 @@ cookie-consent banners. WebBrain uses it for the "Cookie banners" setting; see
- Source: https://github.com/duckduckgo/autoconsent/tree/v16.61.0
- License: Mozilla Public License 2.0 (`LICENSE` here, and `LICENSES/MPL-2.0.txt` at the repository root)
-These files are copied from the npm package **unmodified**. Do not edit them:
-under the MPL an edited copy stays MPL-licensed and its changes must be
-published. WebBrain's own code that drives them lives outside this folder
+The JavaScript bundles carry one reproducible WebBrain patch: remove the
+redundant 'des cookies' / 'de cookies' acknowledgement-regex alternatives
+that cause exponential backtracking. The optional articles already cover
+those phrases. The patch is in 'scripts/update-autoconsent.mjs'; upstream
+and patched hashes are recorded in 'vendor-manifest.json'.
+These modified files remain MPL-2.0 and their complete source is published
+here. Rules and license text are copied unmodified. WebBrain's own code lives outside this folder
(`src/content/autoconsent-bridge.js`, `src/agent/cookie-banner-host.js`, and
WebBrain's own rules in `src/agent/cookie-banner-rules.js`) and is under
WebBrain's license, GPL-3.0-or-later; MPL-2.0 allows that combination
@@ -22,7 +26,7 @@ verifies these copies against the hashes below.
| File | SHA-256 |
|---|---|
-| `autoconsent.playwright.js` | `acf22263a6e8d6e0485e162ac9c78974a148afb8051c4f67328dbb004f929484` |
-| `autoconsent.esm.js` | `47bed6a4229c7011c4656d9c1378a32c1a01aae0d59e1f10c180dbec1ba5285b` |
+| `autoconsent.playwright.js` | `c86e87c111ce52e627fa335a79a2190a48b45ebe3eb12831dd0e712c627046c1` |
+| `autoconsent.esm.js` | `96c2c07d6e224e96076815abb218178cb5883c27bc0690ae5613ca9d3d223b15` |
| `compact-rules.json` | `bc3e27b8e5a529be4db748ac8940f1ade9c848aeb3dce6cdd4807b9e03390647` |
| `LICENSE` | `fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85` |
diff --git a/src/firefox/vendor/autoconsent/autoconsent.esm.js b/src/firefox/vendor/autoconsent/autoconsent.esm.js
index ea86f0690..207d0cda3 100644
--- a/src/firefox/vendor/autoconsent/autoconsent.esm.js
+++ b/src/firefox/vendor/autoconsent/autoconsent.esm.js
@@ -1,3 +1,4 @@
+// WebBrain modification (MPL-2.0): remove redundant acknowledgement regex alternatives to prevent exponential backtracking.
var __typeError = (msg) => {
throw TypeError(msg);
};
@@ -1170,7 +1171,7 @@ var ACCEPT_PATTERNS = [
var ACKNOWLEDGE_PATTERNS = [
// close / dismiss the banner/dialog/message (multilingual). The negative lookahead avoids
// accept/save phrases (e.g. "agree and close", "akkoord en sluiten", "speichern schließen").
- /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|des cookies|de cookies|x))*\.?\s*$/is,
+ /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|x))*\.?\s*$/is,
// "ok" / "okay" / "oké" (optionally followed by a short acknowledgement)
/^(ok|okay|oké|okey|k)([ .!,]*)(got it|verstanden|compris|rozumiem|thanks|gracias|ik begrijp( dat| het)?|continue to website|pour moi|fermer)?[ .!]*$/is,
// "understood" / "got it" / "that's ok" (multilingual)
diff --git a/src/firefox/vendor/autoconsent/autoconsent.playwright.js b/src/firefox/vendor/autoconsent/autoconsent.playwright.js
index ae6381dff..08fe18a3d 100644
--- a/src/firefox/vendor/autoconsent/autoconsent.playwright.js
+++ b/src/firefox/vendor/autoconsent/autoconsent.playwright.js
@@ -1,3 +1,4 @@
+// WebBrain modification (MPL-2.0): remove redundant acknowledgement regex alternatives to prevent exponential backtracking.
"use strict";
(() => {
var __typeError = (msg) => {
@@ -1172,7 +1173,7 @@
var ACKNOWLEDGE_PATTERNS = [
// close / dismiss the banner/dialog/message (multilingual). The negative lookahead avoids
// accept/save phrases (e.g. "agree and close", "akkoord en sluiten", "speichern schließen").
- /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|des cookies|de cookies|x))*\.?\s*$/is,
+ /^(?!.*\b(accept\w*|accepter|accepteer|accepteren|agree|allow|akkoord|aanvaard\w*|zustimm\w*|annehm\w*|akzeptier\w*|aceptar|acepta|permit\w*|consent\w*|einverstanden|zezw\w*|zgadzam|zgoda|guardar|opslaan|enregistrer|speicher\w*|zapisz)\b)(x\s+|nee,?\s+)?(close|dismiss|schlie(ß|ss)en|sluiten|afsluiten|fermer|cerrar|tanca|beenden|masquer|zamknij)( (this|the|ce|le|el|de|des|het|la|een)?\s*(banner|bandeau|banier|bar|dialog|dialogue|window|okno|melding|message|notification|informa\w*|notificaci\w*|cookie\w*|bannière|rgpd|gdpr|hier|x))*\.?\s*$/is,
// "ok" / "okay" / "oké" (optionally followed by a short acknowledgement)
/^(ok|okay|oké|okey|k)([ .!,]*)(got it|verstanden|compris|rozumiem|thanks|gracias|ik begrijp( dat| het)?|continue to website|pour moi|fermer)?[ .!]*$/is,
// "understood" / "got it" / "that's ok" (multilingual)
diff --git a/src/firefox/vendor/autoconsent/vendor-manifest.json b/src/firefox/vendor/autoconsent/vendor-manifest.json
index 897505bb5..6b563535a 100644
--- a/src/firefox/vendor/autoconsent/vendor-manifest.json
+++ b/src/firefox/vendor/autoconsent/vendor-manifest.json
@@ -4,10 +4,19 @@
"integrity": "sha512-XRHCE4J9Q3tpF6TgbCilKDemBQsAWHBFR9S93UEwCnFA9jP54FTENz8nYez8/zyxh2O3O3r/K/gI8+DwtE4p6Q==",
"source": "https://github.com/duckduckgo/autoconsent/tree/v16.61.0",
"license": "MPL-2.0",
- "files": {
+ "patches": [
+ "deduplicate-acknowledgement-cookie-nouns"
+ ],
+ "upstreamFiles": {
"autoconsent.playwright.js": "acf22263a6e8d6e0485e162ac9c78974a148afb8051c4f67328dbb004f929484",
"autoconsent.esm.js": "47bed6a4229c7011c4656d9c1378a32c1a01aae0d59e1f10c180dbec1ba5285b",
"compact-rules.json": "bc3e27b8e5a529be4db748ac8940f1ade9c848aeb3dce6cdd4807b9e03390647",
"LICENSE": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85"
+ },
+ "files": {
+ "autoconsent.playwright.js": "c86e87c111ce52e627fa335a79a2190a48b45ebe3eb12831dd0e712c627046c1",
+ "autoconsent.esm.js": "96c2c07d6e224e96076815abb218178cb5883c27bc0690ae5613ca9d3d223b15",
+ "compact-rules.json": "bc3e27b8e5a529be4db748ac8940f1ade9c848aeb3dce6cdd4807b9e03390647",
+ "LICENSE": "fab3dd6bdab226f1c08630b1dd917e11fcb4ec5e1e020e2c16f83a0a13863e85"
}
}
diff --git a/test/cookie-banner-host.mjs b/test/cookie-banner-host.mjs
index c8fca57b5..225c55cd3 100644
--- a/test/cookie-banner-host.mjs
+++ b/test/cookie-banner-host.mjs
@@ -4,6 +4,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
+import { execFileSync } from 'node:child_process';
+import { runInNewContext } from 'node:vm';
import { checkVendoredAutoconsent } from '../scripts/update-autoconsent.mjs';
@@ -59,9 +61,11 @@ function fakeApi() {
for (const fn of listeners.committed) fn({ tabId, frameId, url });
},
content(tabId, frameId, url, msg) {
+ let response;
for (const fn of listeners.message) {
- fn({ type: 'webbrain-autoconsent', msg }, { tab: { id: tabId }, frameId, url }, () => {});
+ fn({ type: 'webbrain-autoconsent', msg }, { tab: { id: tabId }, frameId, url }, value => { response = value; });
}
+ return response;
},
status(tabId, senderUrl) {
let response;
@@ -78,6 +82,7 @@ for (const build of BUILDS) {
const { cookieBannerNoteText, settleCookieBannersForTurn } = await import(`../src/${build}/src/agent/cookie-banner-turn.js`);
const { evalSnippets } = await import(`../src/${build}/vendor/autoconsent/autoconsent.esm.js`);
const { WEBBRAIN_COOKIE_BANNER_RULES, cookieBannerRulesFor } = await import(`../src/${build}/src/agent/cookie-banner-rules.js`);
+ const { guardCookieBannerInstance } = await import(`../src/${build}/src/content/autoconsent-runtime.js`);
const rules = JSON.parse(await read(`src/${build}/vendor/autoconsent/compact-rules.json`));
const { createCookieBannerHost, normalizeCookieBannerMode, isChallengeFrameUrl } = hostModule;
@@ -96,6 +101,79 @@ for (const build of BUILDS) {
const injections = calls => calls.execute.filter(call => Array.isArray(call.files));
+ test(`${build}: revoking coverage stops injected frames and denies further actions`, async () => {
+ const runs = new Map([[201, 'act']]);
+ const { fake, host } = setup({ runs });
+ const url = 'https://shop.example/';
+ fake.commit(201, 0, url);
+ await until(() => injections(fake.calls).length === 1, 'injection');
+ assert.equal(fake.content(201, 0, url, { type: 'checkCoverage' }), true);
+ runs.delete(201);
+ host.refreshCoverage(201);
+ assert.ok(fake.calls.sent.some(call => call.tabId === 201 && call.message.msg.type === 'stop'));
+ assert.equal(fake.content(201, 0, url, { type: 'checkCoverage' }), false);
+ assert.deepEqual(host.status(201).frames, []);
+ runs.set(201, 'act');
+ fake.commit(201, 0, url);
+ await until(() => injections(fake.calls).length === 2, 'fresh injection');
+ host.setMode('off');
+ assert.equal(fake.content(201, 0, url, { type: 'checkCoverage' }), false);
+ assert.deepEqual(host.status(201).frames, []);
+ });
+
+ test(`${build}: cancellation survives a pending action grant and stops every click in a rule`, async () => {
+ let clicks = 0;
+ const elements = [{ click() { clicks += 1; } }, { click() { clicks += 1; } }];
+ const instance = () => ({
+ config: { enabled: true, autoAction: 'optOut' },
+ doOptOut() {}, doOptIn() {}, handlePopup() {}, findCmp() {}, waitForPopup() {},
+ undoPrehide() {}, restoreFocus() {},
+ domActions: {
+ elementSelector: () => elements,
+ clickElement: async element => { element.click(); return true; },
+ hide() {}, stylesheet() {}, removeClass() {}, setStyle() {}, addStyle() {}, prehide() {},
+ },
+ });
+ let grant;
+ const pending = instance();
+ const guard = guardCookieBannerInstance(pending, () => new Promise(resolve => { grant = resolve; }));
+ const action = pending.domActions.click('button', true);
+ guard.stop();
+ grant(true);
+ await assert.rejects(action, /Cookie-banner coverage revoked/);
+ assert.equal(clicks, 0, 'a grant already in transit cannot revive a stopped instance');
+ assert.deepEqual(await pending.findCmp(), []);
+ assert.equal(pending.domActions.hide('banner'), false);
+
+ let covered = true;
+ const active = instance();
+ elements[0].click = () => { clicks += 1; covered = false; };
+ guardCookieBannerInstance(active, async () => covered);
+ await assert.rejects(active.domActions.click('button', true), /Cookie-banner coverage revoked/);
+ assert.equal(clicks, 1, 'click-all rules recheck coverage for each element');
+
+ const disconnected = instance();
+ guardCookieBannerInstance(disconnected, async () => { throw new Error('worker gone'); });
+ await assert.rejects(disconnected.domActions.click('button'), /Cookie-banner coverage revoked/);
+ assert.equal(clicks, 1, 'loss of background coverage fails closed');
+
+ let resume;
+ const direct = instance();
+ direct.domActions.wait = () => new Promise(resolve => { resume = resolve; });
+ direct.doOptOut = async () => {
+ await direct.domActions.wait(500);
+ elements[1].click(); // Like Sourcepoint's direct toggles after wait().
+ return true;
+ };
+ const directGuard = guardCookieBannerInstance(direct, async () => true);
+ const delayed = direct.doOptOut();
+ await until(() => resume, 'the rule to enter its wait');
+ directGuard.stop();
+ resume(true);
+ assert.equal(await delayed, false);
+ assert.equal(clicks, 1, 'cancellation unwinds a rule before its direct DOM mutations');
+ });
+
test(`${build}: 'agent' mode injects only into tabs an Act or Dev run is driving`, async () => {
const { fake } = setup({ runs: new Map([[1, 'act'], [2, 'ask'], [4, 'dev']]) });
fake.commit(1, 0, 'https://shop.example/');
@@ -106,7 +184,7 @@ for (const build of BUILDS) {
await sleep(20);
const injected = injections(fake.calls);
assert.deepEqual(injected.map(call => call.target.tabId).sort(), [1, 4]);
- assert.deepEqual(injected[0].files, ['src/content/autoconsent-bridge.js', 'vendor/autoconsent/autoconsent.playwright.js']);
+ assert.deepEqual(injected[0].files, ['src/content/autoconsent-bridge.js']);
assert.deepEqual(injected[0].target.frameIds, [0]);
assert.equal(injected[0].injectImmediately, true);
assert.equal(injected[0].world, undefined, 'the content half must stay in the isolated world');
@@ -134,7 +212,7 @@ for (const build of BUILDS) {
fake.commit(9, 0, 'https://example.org/');
await until(() => injections(fake.calls).length === 1, 'injection');
assert.deepEqual(injections(fake.calls)[0].files,
- ['/src/content/autoconsent-bridge.js', '/vendor/autoconsent/autoconsent.playwright.js']);
+ ['/src/content/autoconsent-bridge.js']);
});
test(`${build}: 'everywhere' covers every tab, 'off' none, and the stored mode applies before the first injection`, async () => {
@@ -529,10 +607,28 @@ for (const build of BUILDS) {
});
}
-test('the vendored autoconsent copies are unmodified and the glue matches across browsers', async () => {
+test('the vendored autoconsent patch is reproducible and the glue matches across browsers', async () => {
assert.deepEqual(checkVendoredAutoconsent(), []);
for (const file of ['src/agent/cookie-banner-host.js', 'src/agent/cookie-banner-rules.js', 'src/agent/cookie-banner-turn.js',
- 'src/content/autoconsent-bridge.js']) {
+ 'src/content/autoconsent-bridge.js', 'src/content/autoconsent-runtime.js']) {
assert.equal(await read(`src/chrome/${file}`), await read(`src/firefox/${file}`), file);
}
});
+
+test('autoconsent acknowledgement regex rejects repeated cookie phrases without exponential backtracking', async () => {
+ for (const browser of BUILDS) {
+ for (const file of ['autoconsent.esm.js', 'autoconsent.playwright.js']) {
+ const source = await read(`src/${browser}/vendor/autoconsent/${file}`);
+ const expression = source.split('\n').find(line => line.includes('(close|dismiss|schlie')).trim().replace(/,$/, '');
+ const pattern = runInNewContext(expression);
+ for (const label of ['close', 'close de cookies', 'close des cookies', 'Fermer le bandeau', 'close this dialog.', 'cerrar el banner']) {
+ assert.equal(pattern.test(label), true, `${browser}/${file}: ${label}`);
+ }
+ for (const label of ['accept and close', 'agree and close', 'close marketing settings!']) assert.equal(pattern.test(label), false);
+ // An unpatched bundle hangs on this input. Keep it in a bounded child
+ // process so a regression cannot freeze the test runner itself.
+ execFileSync(process.execPath, ['--eval', `const pattern = ${expression};
+ if (pattern.test('close ' + 'de cookies '.repeat(2000) + '!')) process.exit(1);`], { timeout: 1500 });
+ }
+ }
+});
diff --git a/test/cookie-banner-ui.mjs b/test/cookie-banner-ui.mjs
index f9e83b982..6377178e9 100644
--- a/test/cookie-banner-ui.mjs
+++ b/test/cookie-banner-ui.mjs
@@ -192,10 +192,29 @@ document.addEventListener('click', (event) => {
event.target.closest('[data-banner]')?.remove();
});`;
+const lateBannerPage = `<!doctype html><html><head><title>Fixture shop</title></head><body>
+<h1>Fixture shop</h1><script src="/late-banner.js"></script></body></html>`;
+const lateBannerScript = `window.showCookieBanner = () => {
+ const banner = document.createElement('div');
+ banner.className = 'c-cookie-popup';
+ banner.style.cssText = 'position:fixed;bottom:0;padding:16px;background:white';
+ banner.innerHTML = 'We use cookies. <button data-role="refuse-cookies">Refuse</button>';
+ banner.querySelector('button').onclick = () => {
+ document.documentElement.dataset.consent = 'refused';
+ banner.remove();
+ };
+ document.body.append(banner);
+};`;
+
const server = createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const host = String(req.headers.host || '').split(':')[0];
const script = url.pathname.match(/^\/efilli-(stock|turkish|inline|hepsiburada)\.js$/);
+ if (url.pathname === '/late-banner.js') {
+ res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
+ res.end(lateBannerScript);
+ return;
+ }
if (url.pathname === '/shop.js' || url.pathname === '/blog.js' || url.pathname === '/choice.js' || script) {
res.setHeader('Content-Type', 'application/javascript; charset=utf-8');
res.end(script ? efilliScript(script[1]) : url.pathname === '/choice.js' ? choiceScript
@@ -203,7 +222,9 @@ const server = createServer((req, res) => {
return;
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
- if (url.pathname === '/index.html') {
+ if (url.pathname.startsWith('/late-banner')) {
+ res.end(lateBannerPage);
+ } else if (url.pathname === '/index.html') {
res.end(`<!doctype html><html><body><p>${host} frame</p></body></html>`);
} else if (host === HEPSIBURADA_HOST) {
res.end(efilliPage('hepsiburada'));
@@ -305,6 +326,20 @@ async function scenarios(name, driver) {
assert.equal(captchaStyles, 0, `${name}: autoconsent added nothing to the CAPTCHA frame`);
pass("'everywhere' declines the banner from the isolated world; the CAPTCHA frame is untouched");
+ // Revoking coverage must also stop a handler already searching this page.
+ const lateOffUrl = `${origin}/late-banner-off`;
+ await driver.open(lateOffUrl);
+ const lateOffTab = await tabIdFor(lateOffUrl);
+ await until(async () => (await status(lateOffTab)).frames.some(frame => frame.lifecycle === 'started'),
+ `${name}: detection to start before Off`);
+ await setMode('off');
+ await driver.page('window.showCookieBanner()');
+ await sleep(2500);
+ assert.equal(await consent(), '', `${name}: a previously injected handler must stop after Off`);
+ assert.equal(await driver.page(`document.querySelectorAll('.c-cookie-popup').length`), 1);
+ pass('Off stops a previously injected handler before a late banner appears');
+ await setMode('everywhere');
+
// A rule whose opt-out needs one of autoconsent's page-world snippets.
const blogUrl = `${origin}/blog`;
await driver.open(blogUrl);
@@ -432,19 +467,22 @@ async function scenarios(name, driver) {
assert.equal(await consent(), '', `${name}: before the run starts, the banner is left alone`);
const runTab = await tabIdFor(runUrl);
modelRequests.length = 0;
- // Started without waiting: a BiDi command must answer within 10 s.
- await driver.ext(`(() => {
+ const runAct = async (tabId, suffix) => {
+ // Started without waiting: a BiDi command must answer within 10 s.
+ await driver.ext(`(() => {
window.__cookieBannerRun = null;
- ${API}.runtime.sendMessage(${JSON.stringify({ target: 'background', action: 'chat', tabId: runTab,
- text: 'What is the heading of this page? Do not buy anything.', mode: 'act', requestId: `cookie-banner-run-${name}` })})
+ ${API}.runtime.sendMessage(${JSON.stringify({ target: 'background', action: 'chat', tabId,
+ text: 'What is the heading of this page? Do not buy anything.', mode: 'act', requestId: `cookie-banner-run-${name}-${suffix}` })})
.then((response) => {
window.__cookieBannerRunResult = JSON.stringify(response ?? null).slice(0, 400);
window.__cookieBannerRun = 'done';
}, error => { window.__cookieBannerRun = 'error: ' + error; });
return true;
})()`);
- const outcome = await until(() => driver.ext('window.__cookieBannerRun'), `${name}: the Act run to finish`, 60000);
- assert.equal(outcome, 'done', `${name}: ${outcome}`);
+ const outcome = await until(() => driver.ext('window.__cookieBannerRun'), `${name}: the Act run to finish`, 60000);
+ assert.equal(outcome, 'done', `${name}: ${outcome}`);
+ };
+ await runAct(runTab, 'banner');
assert.equal(await consent(), 'refused', `${name}: the Act run declined the banner`);
const firstToolTurn = modelRequests.find(input => input.tools?.length);
assert.ok(firstToolTurn, `${name}: the run reached a model turn with tools (model requests: ${modelRequests.length}; `
@@ -452,6 +490,19 @@ async function scenarios(name, driver) {
assert.ok(firstToolTurn.messages.some(entry => textOf(entry.content).includes('[Cookie banners: WebBrain automatically declined')),
`${name}: the first model turn is told the banner was declined`);
pass("'agent' mode declines the banner in an Act run and tells the model before its first turn");
+
+ const lateRunUrl = `${origin}/late-banner-run`;
+ await driver.open(lateRunUrl);
+ const lateRunTab = await tabIdFor(lateRunUrl);
+ await runAct(lateRunTab, 'late');
+ await until(async () => !(await status(lateRunTab)).covered, `${name}: the run to release its tab`);
+ await driver.page('window.showCookieBanner()');
+ await sleep(2500);
+ assert.equal(await consent(), '', `${name}: a finished run must not decline a late banner`);
+ pass('a finished Act run stops its pending handler before a late banner appears');
+ await runAct(lateRunTab, 'restart');
+ assert.equal(await consent(), 'refused', `${name}: a new run can decline the previously untouched banner`);
+ pass('a new Act run can handle banners again on the same document');
}
// --- Chromium (Playwright) --------------------------------------------------