A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(workers): auto-dismiss consent dialogs with autoconsent (#2973)
Mohamed Bassemc333f240a8fe
diff --git a/apps/workers/package.json b/apps/workers/package.jsonindex a5239675..fb8c75c2 100644--- a/apps/workers/package.json+++ b/apps/workers/package.json@@ -5,6 +5,7 @@"private": true,"type": "module","dependencies": {+ "@duckduckgo/autoconsent": "^16.6.0","@ghostery/adblocker-playwright": "^2.5.1","@hono/node-server": "^1.19.11","@hono/prometheus": "^1.0.2",diff --git a/apps/workers/workers/crawler/autoconsent.ts b/apps/workers/workers/crawler/autoconsent.tsnew file mode 100644index 00000000..2c7062d1--- /dev/null+++ b/apps/workers/workers/crawler/autoconsent.ts@@ -0,0 +1,249 @@+// Auto-dismisses consent-management-platform (CMP) dialogs in the crawler's+// browser using DuckDuckGo's autoconsent (Consent-O-Matic-style opt-out rules).+// This runs entirely in the page (DOM manipulation, no network requests of its+// own), so it improves screenshots, PDFs, monolith archives AND the captured+// HTML that feeds extraction. Gated by CRAWLER_ENABLE_AUTOCONSENT.+//+// Integration follows autoconsent's headless guide (docs/puppeteer.md): the+// bundled content script is injected via addInitScript and talks to Node over+// an exposed binding; Node replies with the config + rule bundle.+import { readFileSync } from "node:fs";+import { createRequire } from "node:module";+import * as path from "node:path";+import type { Frame, Page } from "playwright";+import { abortRaceResolve, raceWith, timeoutRace } from "utils";+import { z } from "zod";++import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";++// The content script exposes/consumes these on the page's global object. In a+// browser `globalThis === window`; declaring them here keeps the injected+// callbacks typed without pulling the DOM lib into the workers tsconfig.+declare global {+ // eslint-disable-next-line no-var+ var autoconsentReceiveMessage: ((message: unknown) => unknown) | undefined;+}++// Cap on how long we wait for autoconsent to finish detection and, when a CMP+// is found, finish opting out.+const AUTOCONSENT_WAIT_MS = 3000;++// Mirrors autoconsent's documented headless config with automatic opt-out.+const autoconsentConfig = {+ enabled: true,+ autoAction: "optOut",+ disabledCmps: [],+ enablePrehide: true,+ enableCosmeticRules: true,+ enableGeneratedRules: true,+ detectRetries: 20,+ isMainWorld: false,+ prehideTimeout: 2000,+ enableHeuristicDetection: true,+ heuristicMode: "tier2",+ logs: {+ lifecycle: false,+ rulesteps: false,+ detectionsteps: false,+ evals: false,+ errors: true,+ messages: false,+ waits: false,+ },+};++const autoconsentMessageSchema = z+ .object({+ type: z.string(),+ code: z.string().optional(),+ id: z.union([z.string(), z.number()]).optional(),+ cmp: z.string().optional(),+ details: z.unknown().optional(),+ mainFrame: z.boolean().optional(),+ state: z+ .object({+ lifecycle: z.string(),+ })+ .optional(),+ })+ .passthrough();++interface AutoconsentBundle {+ script: string;+ rules: unknown;+}++let bundle: AutoconsentBundle | undefined;+let loadAttempted = false;++/**+ * Loads the autoconsent content-script bundle and rule set once (module-level,+ * like the adblocker). No-op when CRAWLER_ENABLE_AUTOCONSENT is false or on any+ * load error (autoconsent is then simply disabled — never fatal).+ */+export function loadAutoconsent(): void {+ if (loadAttempted) {+ return;+ }+ loadAttempted = true;+ if (!serverConfig.crawler.enableAutoconsent) {+ return;+ }+ try {+ const require = createRequire(import.meta.url);+ // The playwright bundle is a sibling of the package's main entry; it is not+ // a declared export, so resolve the package then walk to the sibling file.+ const pkgMain = require.resolve("@duckduckgo/autoconsent");+ const scriptPath = path.join(+ path.dirname(pkgMain),+ "autoconsent.playwright.js",+ );+ const rulesPath =+ require.resolve("@duckduckgo/autoconsent/rules/rules.json");+ const script = readFileSync(scriptPath, "utf8");+ const rules: unknown = JSON.parse(readFileSync(rulesPath, "utf8"));+ bundle = { script, rules };+ logger.info("[crawler] Loaded autoconsent CMP opt-out rules.");+ } catch (e) {+ logger.error(+ `[crawler] Failed to load autoconsent. CMP auto-opt-out disabled: ${e}`,+ );+ }+}++export interface AutoconsentHandle {+ cmpDetected: () => boolean;+ detectionComplete: Promise<boolean>;+ done: Promise<void>;+}++/**+ * Installs autoconsent on a freshly-created page. Must be called AFTER the SSRF+ * request router and redirect guard are in place (autoconsent injects scripts;+ * conservative ordering). Returns a handle whose `done` promise resolves when+ * autoconsent finishes (or errors), or undefined when autoconsent is+ * unavailable/disabled or installation fails (never fatal to a crawl).+ */+export async function installAutoconsent(+ page: Page,+ jobId: string,+): Promise<AutoconsentHandle | undefined> {+ if (!bundle) {+ return undefined;+ }+ const { script, rules } = bundle;++ let cmpDetected = false;+ let resolveDetectionComplete: (detected: boolean) => void = () => undefined;+ const detectionComplete = new Promise<boolean>((resolve) => {+ resolveDetectionComplete = resolve;+ });+ let resolveDone: () => void = () => undefined;+ const done = new Promise<void>((resolve) => {+ resolveDone = resolve;+ });++ const sendToFrame = (frame: Frame, message: unknown) =>+ frame+ .evaluate((msg) => {+ const receive = globalThis.autoconsentReceiveMessage;+ return receive ? receive(msg) : undefined;+ }, message)+ .catch(() => {+ // Page may have navigated/closed; nothing actionable.+ });++ try {+ await page.exposeBinding(+ "autoconsentSendMessage",+ async ({ frame }, raw: unknown): Promise<unknown> => {+ const parsed = autoconsentMessageSchema.safeParse(raw);+ if (!parsed.success) {+ return undefined;+ }+ const message = parsed.data;+ switch (message.type) {+ case "init":+ return sendToFrame(frame, {+ type: "initResp",+ config: autoconsentConfig,+ rules, // must include rules or no CMPs will be detected+ });+ case "eval": {+ if (typeof message.code !== "string") {+ return undefined;+ }+ const result = await frame.evaluate(message.code).catch(() => null);+ return sendToFrame(frame, {+ type: "evalResp",+ id: message.id,+ result,+ });+ }+ case "cmpDetected":+ case "popupFound":+ cmpDetected = true;+ resolveDetectionComplete(true);+ return undefined;+ case "autoconsentDone":+ resolveDetectionComplete(true);+ resolveDone();+ return undefined;+ case "autoconsentError":+ logger.warn(+ `[Crawler][${jobId}] autoconsent error: ${JSON.stringify(+ message.details,+ )}`,+ );+ resolveDetectionComplete(cmpDetected);+ resolveDone();+ return undefined;+ case "report":+ // A report from the main frame is authoritative for the page-level+ // "no CMP" result. Child frames can finish detection earlier while+ // the main frame is still looking for a delayed dialog.+ if (+ message.mainFrame === true &&+ message.state?.lifecycle === "nothingDetected"+ ) {+ resolveDetectionComplete(false);+ }+ return undefined;+ default:+ return undefined;+ }+ },+ );+ await page.addInitScript(script);+ } catch (e) {+ logger.warn(+ `[Crawler][${jobId}] Failed to install autoconsent on the page: ${e}`,+ );+ return undefined;+ }++ return { cmpDetected: () => cmpDetected, detectionComplete, done };+}++/**+ * Waits (capped at AUTOCONSENT_WAIT_MS, abort-aware) for detection to finish.+ * If a CMP is detected, also waits for autoconsent to finish opting out.+ */+export async function waitForAutoconsent(+ handle: AutoconsentHandle | undefined,+ abortSignal: AbortSignal,+): Promise<void> {+ if (!handle) {+ return;+ }++ const completion = handle.detectionComplete.then((detected) =>+ detected ? handle.done : undefined,+ );+ await raceWith<void>(+ completion,+ timeoutRace<void>(AUTOCONSENT_WAIT_MS, () => undefined),+ abortRaceResolve(abortSignal, undefined),+ );+}diff --git a/apps/workers/workers/crawler/browser.ts b/apps/workers/workers/crawler/browser.tsindex 4a96b0d6..fe47d7ee 100644--- a/apps/workers/workers/crawler/browser.ts+++ b/apps/workers/workers/crawler/browser.ts@@ -22,6 +22,7 @@ import logger from "@karakeep/shared/logger";import { setUrlHostnameFromResolvedAddress } from "@karakeep/shared/utils/url";import { tryCatch } from "@karakeep/shared/tryCatch";+import { loadAutoconsent } from "./autoconsent";import { redactUrlCredentials } from "./utils";interface Cookie {@@ -273,6 +274,7 @@ async function loadCookiesFromFile(): Promise<void> {export async function initializeBrowserEnvironment(): Promise<void> {chromium.use(StealthPlugin());await loadAdblocker();+ loadAutoconsent();if (!serverConfig.crawler.browserConnectOnDemand) {await launchBrowser();} else {diff --git a/apps/workers/workers/crawler/crawlPage.ts b/apps/workers/workers/crawler/crawlPage.tsindex e17a1338..d2fb64dc 100644--- a/apps/workers/workers/crawler/crawlPage.ts+++ b/apps/workers/workers/crawler/crawlPage.ts@@ -31,6 +31,8 @@ import serverConfig from "@karakeep/shared/config";import logger from "@karakeep/shared/logger";import { tryCatch } from "@karakeep/shared/tryCatch";+import type { AutoconsentHandle } from "./autoconsent";+import { installAutoconsent, waitForAutoconsent } from "./autoconsent";import {CONTEXT_CLOSE_TIMEOUT_MS,PAGE_CLOSE_TIMEOUT_MS,@@ -210,12 +212,17 @@ async function installRedirectGuard(* Creates and configures the page: redirect guard, adblocking, dialog* auto-dismissal, media/SSRF request blocking, and abort wiring.*/+interface SetupPageResult {+ page: Page;+ autoconsent: AutoconsentHandle | undefined;+}+async function setupPage(context: BrowserContext,jobId: string,proxyConfig: BrowserContextOptions["proxy"],abortSignal: AbortSignal,-): Promise<Page> {+): Promise<SetupPageResult> {return await withSpan(tracer,"crawlerWorker.crawlPage.setupPage",@@ -292,6 +299,11 @@ async function setupPage(await route.fallback();});+ // Install autoconsent AFTER the redirect guard and SSRF request router+ // are in place (conservative ordering; it injects scripts). No-op unless+ // enabled and the bundle loaded.+ const autoconsent = await installAutoconsent(nextPage, jobId);+// On abort, immediately stop intercepting requests so that// in-flight route handlers don't block page/context closure.abortSignal.addEventListener(@@ -307,7 +319,7 @@ async function setupPage({ once: true },);- return nextPage;+ return { page: nextPage, autoconsent };},);}@@ -651,7 +663,9 @@ export async function crawlPage();}- page = await setupPage(context, jobId, proxyConfig, abortSignal);+ const setup = await setupPage(context, jobId, proxyConfig, abortSignal);+ page = setup.page;+ const autoconsentHandle = setup.autoconsent;// page is guaranteed to be assigned here; alias to a const for// TypeScript narrowing so the rest of the try block sees `Page`.@@ -732,6 +746,12 @@ export async function crawlPage(`[Crawler][${jobId}] Finished waiting for the page to load.`,);+ // If a consent dialog was detected, give autoconsent up to 3s to finish+ // opting out before we capture the HTML/screenshot/PDF. No CMP → no+ // added latency.+ await waitForAutoconsent(autoconsentHandle, abortSignal);+ abortSignal.throwIfAborted();+const [htmlContent, screenshot, pdf] = await capturePageAssets(activePage,jobId,diff --git a/docs/docs/03-configuration/01-environment-variables.md b/docs/docs/03-configuration/01-environment-variables.mdindex c97fbc7c..6a9a977c 100644--- a/docs/docs/03-configuration/01-environment-variables.md+++ b/docs/docs/03-configuration/01-environment-variables.md@@ -151,6 +151,7 @@ Either `OPENAI_API_KEY` or `OLLAMA_BASE_URL` need to be set for automatic taggin| CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE | No | 50 | The maximum file size for the downloaded video. The quality will be chosen accordingly. Use -1 to disable the limit. || CRAWLER_VIDEO_DOWNLOAD_TIMEOUT_SEC | No | 600 | How long to wait for the video download to finish || CRAWLER_ENABLE_ADBLOCKER | No | true | Whether to enable an adblocker in the crawler or not. If you're facing troubles downloading the adblocking lists on worker startup, you can disable this. |+| CRAWLER_ENABLE_AUTOCONSENT | No | true | Whether to automatically opt out of supported consent dialogs during browser-based crawls. When a consent management platform is detected, the crawler waits up to 3 seconds for the opt-out to finish before extracting content and capturing page assets. Set to `false` to disable this behavior. || CRAWLER_YTDLP_ARGS | No | [] | Include additional yt-dlp arguments to be passed at crawl time separated by %%: https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#general-options || CRAWLER_MONOLITH_TIMEOUT_SEC | No | 5 | How long to let monolith run when archiving the full page before timing out (in seconds). Increase this if bookmarks from slow servers frequently fail to archive. Monolith's own default is 120 seconds. || CRAWLER_MONOLITH_ARGS | No | [] | Include additional monolith arguments to be passed when archiving a full page, separated by `%%`. For example, `--no-fonts%%--no-audio%%--no-video` to exclude web fonts, audio, and video from archives. Do not re-specify `-t`, `-b`, or `-o` as these are managed internally. See [monolith options](https://github.com/Y2Z/monolith#command-line-options). |diff --git a/packages/shared/config.ts b/packages/shared/config.tsindex 3a6e9365..95f830af 100644--- a/packages/shared/config.ts+++ b/packages/shared/config.ts@@ -120,6 +120,7 @@ const allEnv = z.object({CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE: z.coerce.number().default(50),CRAWLER_VIDEO_DOWNLOAD_TIMEOUT_SEC: z.coerce.number().default(10 * 60),CRAWLER_ENABLE_ADBLOCKER: stringBool("true"),+ CRAWLER_ENABLE_AUTOCONSENT: stringBool("true"),CRAWLER_YTDLP_ARGS: z.string().prefault("")@@ -367,6 +368,7 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {maxVideoDownloadSize: val.CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE,downloadVideoTimeout: val.CRAWLER_VIDEO_DOWNLOAD_TIMEOUT_SEC,enableAdblocker: val.CRAWLER_ENABLE_ADBLOCKER,+ enableAutoconsent: val.CRAWLER_ENABLE_AUTOCONSENT,ytDlpArguments: val.CRAWLER_YTDLP_ARGS,monolithTimeoutSec: val.CRAWLER_MONOLITH_TIMEOUT_SEC,monolithArguments: val.CRAWLER_MONOLITH_ARGS,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c5cbff55..f344f745 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -890,6 +890,9 @@ importers:apps/workers:dependencies:+ '@duckduckgo/autoconsent':+ specifier: ^16.6.0+ version: 16.6.0'@ghostery/adblocker-playwright':specifier: ^2.5.1version: 2.7.0([email protected])@@ -3658,6 +3661,9 @@ packages:'@drizzle-team/[email protected]':resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==}+ '@duckduckgo/[email protected]':+ resolution: {integrity: sha512-l+OiSHuyWWYCmwoNtAuyAwyPSjfOja0bu0HNY1wYXgO1vq8LJXp1Y5H6Zj4F47i187KchJlpS3q5GnvRnbsANA==}+'@egjs/[email protected]':resolution: {integrity: sha512-XQsZgjm2EcVUiZQf11UBJQfmZeEmOW8DpI1gsFeln6w0ae0ii4dMQEQ0kjl6DspdWX1aGY1/loyXnP0JS06e/A==}engines: {node: '>=0.8.0'}@@ -16786,9 +16792,15 @@ packages:resolution: {integrity: sha512-Ze39mm8EtocSXPbH6cv5rDeBBhehp8OLxWJKZXLEyv2dKMlblJsoAw2gmA0ZaU6iOwNlCZ4LrmaTW1reUQEmJw==}+ resolution: {integrity: sha512-TkQNGJIhlEphpHCjKodMTSe23egUZr/g+flI2qkLgiJ/maAzSgXypSLRTNH3nCmqgayEmtcJBiLcfODSAr1xoA==}+resolution: {integrity: sha512-47LInzMIelfHqD1Gx5+PRYQBl6vU3Xt5KYY6AhqITIKldzu/ctwzdUpbm7AdmsRyzxnly9YH4GLHTtXPwhQhTw==}+ resolution: {integrity: sha512-229vm2Ce4YwD/Tys0Y9WEfKG8gSAfuH9n22rntRvFqfzydJSLk/ihl1aD2kp0Q7d0dktwf1YzYhZ5FmVQwGCCQ==}+resolution: {integrity: sha512-8PWx8tvC4jDB39BQw1m4x8y5MH1BcQ5xHeL2n7UVFulMPH/3Q0uiamahFJ3lXA0zO2SUyRXuVVbWSDmstlt9YA==}hasBin: true@@ -21300,6 +21312,10 @@ snapshots:'@drizzle-team/[email protected]': {}+ '@duckduckgo/[email protected]':+ dependencies:+ tldts-experimental: 7.4.6+'@egjs/[email protected]':dependencies:'@types/hammerjs': 2.0.46@@ -36480,10 +36496,16 @@ snapshots:+ [email protected]: {}+dependencies:tldts-core: 7.0.8+ dependencies:+ tldts-core: 7.4.6+dependencies:tldts-core: 7.0.19