Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

refactor(workers): reorganize the crawler worker for readability (#3160)

Mohamed Bassem9e9ece6c3dc6
diff --git a/apps/workers/scripts/crawlAdhoc.ts b/apps/workers/scripts/crawlAdhoc.ts
index b322e9f3..b5a4ffa7 100644
--- a/apps/workers/scripts/crawlAdhoc.ts
+++ b/apps/workers/scripts/crawlAdhoc.ts
@@ -16,9 +16,10 @@ import { parseArgs } from "node:util";
* queue, DB job, or downstream (inference/search/archival) machinery. Meant for
* manual debugging and for the crawler A/B test (021-crawler-stealth-ab-test).
*
- * DB safety: crawlPage() with the override does NOT read or write any app data
- * (the per-user lookup is skipped; asset/bookmark/search/webhook writes live in
- * downstream functions this CLI never calls). BUT importing the crawler module
+ * DB safety: crawlPage() does NOT read or write any app data (the per-user
+ * browserCrawlingEnabled lookup happens in runCrawler and the
+ * asset/bookmark/search/webhook writes live in downstream functions, none of
+ * which this CLI calls). BUT importing the crawler module
* transitively opens a SQLite connection (packages/db/drizzle.ts) against
* DATA_DIR. To guarantee we never touch the real DB, this bootstrap repoints
* DATA_DIR at a throwaway temp dir BEFORE any app module is imported. Set
@@ -90,7 +91,8 @@ async function main() {
// Dynamic imports so the DATA_DIR override above takes effect first.
const { default: serverConfig } = await import("@karakeep/shared/config");
const { selectRunProxies } = await import("network");
- const { crawlPage, CrawlerWorker } = await import("workers/crawlerWorker");
+ const { crawlPage, crawlLogger, CrawlerWorker } =
+ await import("workers/crawlerWorker");
const { values } = parseArgs({
options: {
@@ -141,14 +143,18 @@ async function main() {
let record: Record<string, unknown>;
try {
const res = await crawlPage(
- jobId,
- url,
- "adhoc",
+ {
+ jobId,
+ bookmarkId: "adhoc",
+ userId: "adhoc",
+ url,
+ abortSignal: abort.signal,
+ runProxy,
+ // Force the full browser path.
+ browserCrawlingEnabled: true,
+ log: crawlLogger(jobId),
+ },
values.pdf,
- abort.signal,
- runProxy,
- // Force the full browser path and skip the per-user DB lookup.
- true,
);
const { blocked, marker } = scoreHtml(res.statusCode, res.htmlContent);
if (screenshotDir && res.screenshot) {
diff --git a/apps/workers/workers/crawler/assetStorage.ts b/apps/workers/workers/crawler/assetStorage.ts
deleted file mode 100644
index 6f059fb9..00000000
--- a/apps/workers/workers/crawler/assetStorage.ts
+++ /dev/null
@@ -1,575 +0,0 @@
-// Everything that persists crawl outputs as assets: screenshots, PDFs,
-// banner images (including data: URIs from precrawled archives), large HTML
-// content, downloaded files, and monolith full-page archives. All of these
-// are quota-checked before writing.
-import { promises as fs } from "fs";
-import * as fsSync from "fs";
-import * as path from "node:path";
-import * as os from "os";
-import { Transform } from "stream";
-import { pipeline } from "stream/promises";
-import { dataUriToBuffer } from "data-uri-to-buffer";
-import type { MimeBuffer } from "data-uri-to-buffer";
-import { execa } from "execa";
-import { fetchWithProxy, getBookmarkDomain } from "network";
-import type { RunProxyConfig } from "network";
-
-import { db } from "@karakeep/db";
-import {
- ASSET_TYPES,
- getAssetSize,
- getTracer,
- IMAGE_ASSET_TYPES,
- newAssetId,
- QuotaService,
- saveAsset,
- saveAssetFromFile,
- withSpan,
-} from "@karakeep/shared-server";
-import serverConfig from "@karakeep/shared/config";
-import logger from "@karakeep/shared/logger";
-import { tryCatch } from "@karakeep/shared/tryCatch";
-
-import { normalizeContentType, truncateUrl } from "./utils";
-
-const tracer = getTracer("@karakeep/workers");
-
-export async function storeScreenshot(
- screenshot: Buffer | undefined,
- userId: string,
- jobId: string,
-) {
- return await withSpan(
- tracer,
- "crawlerWorker.storeScreenshot",
- {
- attributes: {
- "job.id": jobId,
- "user.id": userId,
- "asset.size": screenshot?.byteLength ?? 0,
- },
- },
- async () => {
- if (!serverConfig.crawler.storeScreenshot) {
- logger.info(
- `[Crawler][${jobId}] Skipping storing the screenshot as per the config.`,
- );
- return null;
- }
- if (!screenshot) {
- logger.info(
- `[Crawler][${jobId}] Skipping storing the screenshot as it's empty.`,
- );
- return null;
- }
- const assetId = newAssetId();
- const contentType = "image/jpeg";
- const fileName = "screenshot.jpeg";
-
- // Check storage quota before saving the screenshot
- const { data: quotaApproved, error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, screenshot.byteLength),
- );
-
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping screenshot storage due to quota exceeded: ${quotaError.message}`,
- );
- return null;
- }
-
- await saveAsset({
- userId,
- assetId,
- metadata: { contentType, fileName },
- asset: screenshot,
- quotaApproved,
- });
- logger.info(
- `[Crawler][${jobId}] Stored the screenshot as assetId: ${assetId} (${screenshot.byteLength} bytes)`,
- );
- return { assetId, contentType, fileName, size: screenshot.byteLength };
- },
- );
-}
-
-export async function storePdf(
- pdf: Buffer | undefined,
- userId: string,
- jobId: string,
-) {
- return await withSpan(
- tracer,
- "crawlerWorker.storePdf",
- {
- attributes: {
- "job.id": jobId,
- "user.id": userId,
- "asset.size": pdf?.byteLength ?? 0,
- },
- },
- async () => {
- if (!pdf) {
- logger.info(
- `[Crawler][${jobId}] Skipping storing the PDF as it's empty.`,
- );
- return null;
- }
- const assetId = newAssetId();
- const contentType = "application/pdf";
- const fileName = "page.pdf";
-
- // Check storage quota before saving the PDF
- const { data: quotaApproved, error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, pdf.byteLength),
- );
-
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping PDF storage due to quota exceeded: ${quotaError.message}`,
- );
- return null;
- }
-
- await saveAsset({
- userId,
- assetId,
- metadata: { contentType, fileName },
- asset: pdf,
- quotaApproved,
- });
- logger.info(
- `[Crawler][${jobId}] Stored the PDF as assetId: ${assetId} (${pdf.byteLength} bytes)`,
- );
- return { assetId, contentType, fileName, size: pdf.byteLength };
- },
- );
-}
-
-/**
- * SingleFile / precrawled archives inline images as `data:` URIs, so the image
- * URL metascraper extracts can be a base64 blob rather than something fetchable
- * over the network. Decode it locally and store it as an asset instead of
- * failing on the unsupported protocol.
- */
-async function storeDataUriAsset(
- url: string,
- userId: string,
- jobId: string,
- fileType: string,
-) {
- const maxBytes = serverConfig.maxAssetSizeMb * 1024 * 1024;
-
- // Guardrail 1: cap the size *before* decoding into memory. base64 encodes 3
- // bytes per 4 chars, so a URI longer than 4/3 the limit (plus header slack)
- // must decode past it; the exact check below handles the rest.
- if (url.length > Math.ceil((maxBytes * 4) / 3) + 1024) {
- logger.warn(
- `[Crawler][${jobId}] Skipping data URI ${fileType}: encoded size (${url.length} chars) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
- );
- return null;
- }
-
- let asset: MimeBuffer;
- try {
- asset = dataUriToBuffer(url);
- } catch (e) {
- logger.error(
- `[Crawler][${jobId}] Failed to decode data URI ${fileType}: ${e}`,
- );
- return null;
- }
-
- // Guardrail 2: never trust the declared mediatype for anything but the raster
- // image types we actually serve as banners. Rejects svg/html/etc.;
- // saveAsset's SUPPORTED_ASSET_TYPES check is the backstop.
- const contentType = normalizeContentType(asset.type);
- if (!contentType || !IMAGE_ASSET_TYPES.has(contentType)) {
- logger.warn(
- `[Crawler][${jobId}] Skipping data URI ${fileType} with unsupported content type: ${contentType}`,
- );
- return null;
- }
-
- if (asset.byteLength > maxBytes) {
- logger.warn(
- `[Crawler][${jobId}] Skipping data URI ${fileType}: decoded size (${asset.byteLength} bytes) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
- );
- return null;
- }
-
- const { data: quotaApproved, error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, asset.byteLength),
- );
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping data URI ${fileType} storage due to quota exceeded: ${quotaError.message}`,
- );
- return null;
- }
-
- const assetId = newAssetId();
- await saveAsset({
- userId,
- assetId,
- metadata: { contentType },
- asset,
- quotaApproved,
- });
- logger.info(
- `[Crawler][${jobId}] Stored data URI ${fileType} as assetId: ${assetId} (${asset.byteLength} bytes)`,
- );
- return { assetId, userId, contentType, size: asset.byteLength };
-}
-
-export async function downloadAndStoreFile(
- url: string,
- userId: string,
- jobId: string,
- fileType: string,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
-) {
- return await withSpan(
- tracer,
- "crawlerWorker.downloadAndStoreFile",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- "user.id": userId,
- "asset.type": fileType,
- },
- },
- async () => {
- let assetPath: string | undefined;
- try {
- if (url.startsWith("data:")) {
- return await storeDataUriAsset(url, userId, jobId, fileType);
- }
- logger.info(
- `[Crawler][${jobId}] Downloading ${fileType} from "${truncateUrl(url)}"`,
- );
- const response = await fetchWithProxy(
- url,
- {
- signal: abortSignal,
- },
- runProxy,
- );
- if (!response.ok || response.body == null) {
- throw new Error(`Failed to download ${fileType}: ${response.status}`);
- }
-
- const contentType = normalizeContentType(
- response.headers.get("content-type"),
- );
- if (!contentType) {
- throw new Error("No content type in the response");
- }
-
- const assetId = newAssetId();
- assetPath = path.join(os.tmpdir(), assetId);
-
- let bytesRead = 0;
- const contentLengthEnforcer = new Transform({
- transform(chunk, _, callback) {
- bytesRead += chunk.length;
-
- if (abortSignal.aborted) {
- callback(new Error("AbortError"));
- } else if (bytesRead > serverConfig.maxAssetSizeMb * 1024 * 1024) {
- callback(
- new Error(
- `Content length exceeds maximum allowed size: ${serverConfig.maxAssetSizeMb}MB`,
- ),
- );
- } else {
- callback(null, chunk); // pass data along unchanged
- }
- },
- flush(callback) {
- callback();
- },
- });
-
- await pipeline(
- response.body,
- contentLengthEnforcer,
- fsSync.createWriteStream(assetPath),
- );
-
- // Check storage quota before saving the asset
- const { data: quotaApproved, error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, bytesRead),
- );
-
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping ${fileType} storage due to quota exceeded: ${quotaError.message}`,
- );
- return null;
- }
-
- await saveAssetFromFile({
- userId,
- assetId,
- metadata: { contentType },
- assetPath,
- quotaApproved,
- });
-
- logger.info(
- `[Crawler][${jobId}] Downloaded ${fileType} as assetId: ${assetId} (${bytesRead} bytes)`,
- );
-
- return { assetId, userId, contentType, size: bytesRead };
- } catch (e) {
- logger.error(
- `[Crawler][${jobId}] Failed to download and store ${fileType}: ${e}`,
- );
- // A crawler timeout aborts the job-wide signal. Do not turn that abort
- // into a best-effort download miss: the queue runner must observe it so
- // the crawl is retried and is not reported as successfully completed.
- abortSignal.throwIfAborted();
- return null;
- } finally {
- if (assetPath) {
- await tryCatch(fs.unlink(assetPath));
- }
- }
- },
- );
-}
-
-export async function downloadAndStoreImage(
- url: string,
- userId: string,
- jobId: string,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
-) {
- if (!serverConfig.crawler.downloadBannerImage) {
- logger.info(
- `[Crawler][${jobId}] Skipping downloading the image as per the config.`,
- );
- return null;
- }
- return downloadAndStoreFile(
- url,
- userId,
- jobId,
- "image",
- abortSignal,
- runProxy,
- );
-}
-
-export async function archiveWebpage(
- html: string,
- url: string,
- userId: string,
- jobId: string,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
-) {
- return await withSpan(
- tracer,
- "crawlerWorker.archiveWebpage",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- "user.id": userId,
- },
- },
- async () => {
- logger.info(`[Crawler][${jobId}] Will attempt to archive page ...`);
-
- {
- // Archival is a heavy operation, so we need to check if the user is within reasonable quota before proceeding
- const { error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, /* estimated size */ 1024),
- );
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping archival as the user has exceeded their quota: ${quotaError.message}`,
- );
- return null;
- }
- }
-
- const assetId = newAssetId();
- const assetPath = path.join(os.tmpdir(), assetId);
-
- let res = await execa({
- input: html,
- cancelSignal: abortSignal,
- env: {
- https_proxy: runProxy.httpsProxy,
- http_proxy: runProxy.httpProxy,
- no_proxy: runProxy.noProxy?.join(","),
- },
- })("monolith", [
- "-",
- "-Ije",
- "-t",
- String(serverConfig.crawler.monolithTimeoutSec),
- ...serverConfig.crawler.monolithArguments,
- "-b",
- url,
- "-o",
- assetPath,
- ]);
-
- if (res.isCanceled) {
- logger.error(
- `[Crawler][${jobId}] Canceled archiving the page as we hit global timeout.`,
- );
- await tryCatch(fs.unlink(assetPath));
- return null;
- }
-
- if (res.exitCode !== 0) {
- logger.error(
- `[Crawler][${jobId}] Failed to archive the page as the command exited with code ${res.exitCode}`,
- );
- await tryCatch(fs.unlink(assetPath));
- return null;
- }
-
- const contentType = "text/html";
-
- // Get file size and check quota before saving
- const stats = await fs.stat(assetPath);
- const fileSize = stats.size;
-
- // Discard oversized archives: media-rich pages can produce 1GB+
- // monolith files that never render and only hang/crash browsers.
- // 0 (default) disables the limit.
- const maxArchiveSizeMb = serverConfig.crawler.fullPageArchiveMaxSizeMb;
- if (maxArchiveSizeMb > 0 && fileSize > maxArchiveSizeMb * 1024 * 1024) {
- logger.warn(
- `[Crawler][${jobId}] Discarding page archive of ${fileSize} bytes as it exceeds CRAWLER_FULL_PAGE_ARCHIVE_MAX_SIZE_MB=${maxArchiveSizeMb}.`,
- );
- await tryCatch(fs.unlink(assetPath));
- return null;
- }
-
- const { data: quotaApproved, error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, fileSize),
- );
-
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping page archive storage due to quota exceeded: ${quotaError.message}`,
- );
- await tryCatch(fs.unlink(assetPath));
- return null;
- }
-
- await saveAssetFromFile({
- userId,
- assetId,
- assetPath,
- metadata: {
- contentType,
- },
- quotaApproved,
- });
-
- logger.info(
- `[Crawler][${jobId}] Done archiving the page as assetId: ${assetId}`,
- );
-
- return {
- assetId,
- contentType,
- size: await getAssetSize({ userId, assetId }),
- };
- },
- );
-}
-
-export type StoreHtmlResult =
- | { result: "stored"; assetId: string; size: number }
- | { result: "store_inline" }
- | { result: "not_stored" };
-
-export async function storeHtmlContent(
- htmlContent: string | undefined,
- userId: string,
- jobId: string,
-): Promise<StoreHtmlResult> {
- return await withSpan(
- tracer,
- "crawlerWorker.storeHtmlContent",
- {
- attributes: {
- "job.id": jobId,
- "user.id": userId,
- "bookmark.content.size": htmlContent
- ? Buffer.byteLength(htmlContent, "utf8")
- : 0,
- },
- },
- async () => {
- if (!htmlContent) {
- return { result: "not_stored" };
- }
-
- const contentSize = Buffer.byteLength(htmlContent, "utf8");
-
- // Only store in assets if content is >= 50KB
- if (contentSize < serverConfig.crawler.htmlContentSizeThreshold) {
- logger.info(
- `[Crawler][${jobId}] HTML content size (${contentSize} bytes) is below threshold, storing inline`,
- );
- return { result: "store_inline" };
- }
-
- const { data: quotaApproved, error: quotaError } = await tryCatch(
- QuotaService.checkStorageQuota(db, userId, contentSize),
- );
- if (quotaError) {
- logger.warn(
- `[Crawler][${jobId}] Skipping HTML content storage due to quota exceeded: ${quotaError.message}`,
- );
- return { result: "not_stored" };
- }
-
- const assetId = newAssetId();
-
- const { error: saveError } = await tryCatch(
- saveAsset({
- userId,
- assetId,
- asset: Buffer.from(htmlContent, "utf8"),
- metadata: {
- contentType: ASSET_TYPES.TEXT_HTML,
- fileName: null,
- },
- quotaApproved,
- }),
- );
- if (saveError) {
- logger.error(
- `[Crawler][${jobId}] Failed to store HTML content as asset: ${saveError}`,
- );
- throw saveError;
- }
-
- logger.info(
- `[Crawler][${jobId}] Stored large HTML content (${contentSize} bytes) as asset: ${assetId}`,
- );
-
- return {
- result: "stored",
- assetId,
- size: contentSize,
- };
- },
- );
-}
diff --git a/apps/workers/workers/crawler/crawlAndParse.ts b/apps/workers/workers/crawler/crawlAndParse.ts
deleted file mode 100644
index a157182f..00000000
--- a/apps/workers/workers/crawler/crawlAndParse.ts
+++ /dev/null
@@ -1,532 +0,0 @@
-// Orchestrates a single bookmark crawl: fetches the page (browser render or
-// precrawled archive), parses it, merges the probe/render metadata, and
-// persists the results (metadata first for fast feedback, then contents and
-// assets). Also handles URLs that turn out to be plain assets (pdf/image) by
-// converting the link bookmark into an asset bookmark.
-import * as path from "node:path";
-import { eq } from "drizzle-orm";
-import { crawlerStatusCodeCounter } from "metrics";
-import { getBookmarkDomain } from "network";
-import type { RunProxyConfig } from "network";
-import { abortRace, raceWith } from "utils";
-import { updateAsset } from "workerUtils";
-
-import { db } from "@karakeep/db";
-import {
- assets,
- AssetTypes,
- bookmarkAssets,
- bookmarkLinks,
- bookmarks,
-} from "@karakeep/db/schema";
-import {
- addLogFields,
- ASSET_TYPES,
- AssetPreprocessingQueue,
- getTracer,
- readAsset,
- setSpanAttributes,
- silentDeleteAsset,
- withSpan,
-} from "@karakeep/shared-server";
-import serverConfig from "@karakeep/shared/config";
-import logger from "@karakeep/shared/logger";
-import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
-import type { ZReaderViewReason } from "@karakeep/shared/types/bookmarks";
-
-import type { ParseSubprocessOutput } from "../utils/parseHtmlSubprocessIpc";
-import {
- isLikelyChallengePage,
- resolveMetadata,
-} from "../utils/metadataResolver";
-import {
- archiveWebpage,
- downloadAndStoreFile,
- downloadAndStoreImage,
- storeHtmlContent,
- storePdf,
- storeScreenshot,
-} from "./assetStorage";
-import { crawlPage } from "./crawlPage";
-import { runParseSubprocess } from "./parseSubprocess";
-import { redactUrlCredentials, shouldRetryCrawlStatusCode } from "./utils";
-
-const tracer = getTracer("@karakeep/workers");
-
-type DBAssetType = typeof assets.$inferInsert;
-
-/**
- * Downloads the asset from the URL and transforms the linkBookmark to an assetBookmark
- * @param url the url the user provided
- * @param assetType the type of the asset we're downloading
- * @param userId the id of the user
- * @param jobId the id of the job for logging
- * @param bookmarkId the id of the bookmark
- */
-export async function handleAsAssetBookmark(
- url: string,
- assetType: "image" | "pdf",
- userId: string,
- jobId: string,
- bookmarkId: string,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
-) {
- return await withSpan(
- tracer,
- "crawlerWorker.handleAsAssetBookmark",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- "user.id": userId,
- "bookmark.id": bookmarkId,
- "asset.type": assetType,
- },
- },
- async () => {
- const downloaded = await downloadAndStoreFile(
- url,
- userId,
- jobId,
- assetType,
- abortSignal,
- runProxy,
- );
- if (!downloaded) {
- // Unlike screenshots and banner images, this download is the crawl's
- // primary result. Without it the bookmark cannot be converted to an
- // asset and none of the preprocessing/inference jobs can run.
- throw new Error(
- `[Crawler][${jobId}] Failed to download required ${assetType} asset`,
- );
- }
- const fileName = path.basename(new URL(url).pathname);
- await db.transaction((trx) => {
- updateAsset(
- undefined,
- {
- id: downloaded.assetId,
- bookmarkId,
- userId,
- assetType: AssetTypes.BOOKMARK_ASSET,
- contentType: downloaded.contentType,
- size: downloaded.size,
- fileName,
- },
- trx,
- );
- trx
- .insert(bookmarkAssets)
- .values({
- id: bookmarkId,
- assetType,
- assetId: downloaded.assetId,
- content: null,
- fileName,
- sourceUrl: url,
- })
- .run();
- // Switch the type of the bookmark from LINK to ASSET
- trx
- .update(bookmarks)
- .set({ type: BookmarkTypes.ASSET })
- .where(eq(bookmarks.id, bookmarkId))
- .run();
- trx.delete(bookmarkLinks).where(eq(bookmarkLinks.id, bookmarkId)).run();
- });
- await AssetPreprocessingQueue.enqueue(
- {
- bookmarkId,
- fixMode: false,
- },
- {
- groupId: userId,
- },
- );
- },
- );
-}
-
-export interface CrawlAndParseUrlArgs {
- url: string;
- userId: string;
- jobId: string;
- bookmarkId: string;
- /** Asset ids from a previous crawl of this bookmark, replaced (and deleted) on success. */
- oldAssets: {
- screenshotAssetId: string | undefined;
- pdfAssetId: string | undefined;
- imageAssetId: string | undefined;
- fullPageArchiveAssetId: string | undefined;
- contentAssetId: string | undefined;
- };
- precrawledArchiveAssetId: string | undefined;
- archiveFullPage: boolean;
- forceStorePdf: boolean;
- numRetriesLeft: number;
- abortSignal: AbortSignal;
- runProxy: RunProxyConfig;
- probeMetadataPromise: Promise<ParseSubprocessOutput["metadata"] | null>;
-}
-
-/**
- * Crawls the url, parses it, and persists the bookmark's metadata, content,
- * and assets. Returns a closure that runs the (failure-prone) full-page
- * archival, so the caller can defer it to the very end of the job.
- */
-export async function crawlAndParseUrl(
- args: CrawlAndParseUrlArgs,
-): Promise<() => Promise<void>> {
- const {
- url,
- userId,
- jobId,
- bookmarkId,
- oldAssets,
- precrawledArchiveAssetId,
- archiveFullPage,
- forceStorePdf,
- numRetriesLeft,
- abortSignal,
- runProxy,
- probeMetadataPromise,
- } = args;
- const sanitizedProxyUrl = redactUrlCredentials(
- runProxy.httpsProxy ?? runProxy.httpProxy ?? "",
- );
-
- return await withSpan(
- tracer,
- "crawlerWorker.crawlAndParseUrl",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- "user.id": userId,
- "bookmark.id": bookmarkId,
- "crawler.archiveFullPage": archiveFullPage,
- "crawler.forceStorePdf": forceStorePdf,
- "crawler.hasPrecrawledArchive": !!precrawledArchiveAssetId,
- "crawler.proxy": sanitizedProxyUrl,
- },
- },
- async () => {
- let result: {
- htmlContent: string;
- screenshot: Buffer | undefined;
- pdf: Buffer | undefined;
- statusCode: number | null;
- url: string;
- };
-
- if (precrawledArchiveAssetId) {
- logger.info(
- `[Crawler][${jobId}] The page has been precrawled. Will use the precrawled archive instead.`,
- );
- const asset = await readAsset({
- userId,
- assetId: precrawledArchiveAssetId,
- });
- result = {
- htmlContent: asset.asset.toString(),
- screenshot: undefined,
- pdf: undefined,
- statusCode: 200,
- url,
- };
- } else {
- result = await crawlPage(
- jobId,
- url,
- userId,
- forceStorePdf,
- abortSignal,
- runProxy,
- );
- }
- abortSignal.throwIfAborted();
-
- const {
- htmlContent,
- screenshot,
- pdf,
- statusCode,
- url: browserUrl,
- } = result;
-
- // Track status code in Prometheus
- if (statusCode !== null) {
- crawlerStatusCodeCounter
- .labels(statusCode.toString(), sanitizedProxyUrl)
- .inc();
- setSpanAttributes({
- "crawler.statusCode": statusCode,
- });
- }
- addLogFields<"crawlerWorker.run">({
- "crawler.status_code": statusCode,
- });
-
- if (shouldRetryCrawlStatusCode(statusCode)) {
- if (numRetriesLeft > 0) {
- throw new Error(
- `[Crawler][${jobId}] Received status code ${statusCode}. Will retry crawl. Retries left: ${numRetriesLeft}`,
- );
- }
- logger.info(
- `[Crawler][${jobId}] Received status code ${statusCode} on latest retry attempt. Proceeding without retry.`,
- );
- }
-
- const {
- metadata: renderMeta,
- readableContent: parsedReadableContent,
- readerViewAssessment,
- } = await runParseSubprocess(htmlContent, browserUrl, jobId, abortSignal);
- abortSignal.throwIfAborted();
-
- // The probe metadata extraction has been running alongside the crawl;
- // this is the point where it's needed. The promise never rejects and
- // all its underlying work is time-bounded.
- const probeMetadata = await probeMetadataPromise;
- abortSignal.throwIfAborted();
-
- // On the last retry attempt the crawl proceeds despite a blocked status
- // code, and some bot walls serve their challenge page with a 200; in
- // both cases don't let that page's metadata override clean values from
- // the preflight probe.
- const renderIsChallengePage = isLikelyChallengePage({
- title: renderMeta.title,
- htmlContent,
- });
- const renderBlocked =
- shouldRetryCrawlStatusCode(statusCode) || renderIsChallengePage;
- addLogFields<"crawlerWorker.run">({
- "crawler.render_blocked": renderBlocked,
- });
- if (renderBlocked && probeMetadata) {
- logger.info(
- `[Crawler][${jobId}] The rendered page looks blocked (status ${statusCode}); preferring preflight probe metadata.`,
- );
- }
- const meta = resolveMetadata(renderMeta, probeMetadata, renderBlocked);
- const readerViewReasons: ZReaderViewReason[] | null = readerViewAssessment
- ? renderIsChallengePage &&
- !readerViewAssessment.reasons.includes("challenge_page")
- ? [...readerViewAssessment.reasons, "challenge_page"]
- : readerViewAssessment.reasons
- : null;
-
- const parseDate = (date: string | null | undefined) => {
- if (!date) {
- return null;
- }
- try {
- return new Date(date);
- } catch {
- return null;
- }
- };
-
- // Phase 1: Write metadata immediately for fast user feedback.
- // Content and asset storage happen later and can be slow (banner
- // image download, screenshot/pdf upload, etc.).
- await db
- .update(bookmarkLinks)
- .set({
- title: meta.title,
- description: meta.description,
- // Don't store data URIs as they're not valid URLs and are usually quite large
- imageUrl: meta.image?.startsWith("data:") ? null : meta.image,
- favicon: meta.logo,
- crawlStatusCode: statusCode,
- author: meta.author,
- publisher: meta.publisher,
- datePublished: parseDate(meta.datePublished),
- dateModified: parseDate(meta.dateModified),
- })
- .where(eq(bookmarkLinks.id, bookmarkId));
-
- let readableContent = parsedReadableContent;
-
- const screenshotAssetInfo = await raceWith(
- storeScreenshot(screenshot, userId, jobId),
- abortRace(abortSignal),
- );
- abortSignal.throwIfAborted();
-
- const pdfAssetInfo = await raceWith(
- storePdf(pdf, userId, jobId),
- abortRace(abortSignal),
- );
- abortSignal.throwIfAborted();
-
- const htmlContentAssetInfo = await storeHtmlContent(
- readableContent?.content,
- userId,
- jobId,
- );
- abortSignal.throwIfAborted();
- let imageAssetInfo: DBAssetType | null = null;
- if (meta.image) {
- const downloaded = await downloadAndStoreImage(
- meta.image,
- userId,
- jobId,
- abortSignal,
- runProxy,
- );
- if (downloaded) {
- imageAssetInfo = {
- id: downloaded.assetId,
- bookmarkId,
- userId,
- assetType: AssetTypes.LINK_BANNER_IMAGE,
- contentType: downloaded.contentType,
- size: downloaded.size,
- };
- }
- }
- abortSignal.throwIfAborted();
-
- // Phase 2: Write content and asset references.
- // TODO(important): Restrict the size of content to store
- const assetIdsToDelete: (string | undefined)[] = [];
- const inlineHtmlContent =
- htmlContentAssetInfo.result === "store_inline"
- ? (readableContent?.content ?? null)
- : null;
- readableContent = null;
- await db.transaction((txn) => {
- txn
- .update(bookmarkLinks)
- .set({
- crawledAt: new Date(),
- htmlContent: inlineHtmlContent,
- contentAssetId:
- htmlContentAssetInfo.result === "stored"
- ? htmlContentAssetInfo.assetId
- : null,
- readerViewStatus: readerViewAssessment?.status ?? null,
- readerViewScore: readerViewAssessment?.score ?? null,
- readerViewReasons,
- readerViewClassifierVersion:
- readerViewAssessment?.classifierVersion ?? null,
- })
- .where(eq(bookmarkLinks.id, bookmarkId))
- .run();
-
- if (screenshotAssetInfo) {
- updateAsset(
- oldAssets.screenshotAssetId,
- {
- id: screenshotAssetInfo.assetId,
- bookmarkId,
- userId,
- assetType: AssetTypes.LINK_SCREENSHOT,
- contentType: screenshotAssetInfo.contentType,
- size: screenshotAssetInfo.size,
- fileName: screenshotAssetInfo.fileName,
- },
- txn,
- );
- assetIdsToDelete.push(oldAssets.screenshotAssetId);
- }
- if (pdfAssetInfo) {
- updateAsset(
- oldAssets.pdfAssetId,
- {
- id: pdfAssetInfo.assetId,
- bookmarkId,
- userId,
- assetType: AssetTypes.LINK_PDF,
- contentType: pdfAssetInfo.contentType,
- size: pdfAssetInfo.size,
- fileName: pdfAssetInfo.fileName,
- },
- txn,
- );
- assetIdsToDelete.push(oldAssets.pdfAssetId);
- }
- if (imageAssetInfo) {
- updateAsset(oldAssets.imageAssetId, imageAssetInfo, txn);
- assetIdsToDelete.push(oldAssets.imageAssetId);
- }
- if (htmlContentAssetInfo.result === "stored") {
- updateAsset(
- oldAssets.contentAssetId,
- {
- id: htmlContentAssetInfo.assetId,
- bookmarkId,
- userId,
- assetType: AssetTypes.LINK_HTML_CONTENT,
- contentType: ASSET_TYPES.TEXT_HTML,
- size: htmlContentAssetInfo.size,
- fileName: null,
- },
- txn,
- );
- assetIdsToDelete.push(oldAssets.contentAssetId);
- } else if (oldAssets.contentAssetId) {
- // Unlink the old content asset
- txn
- .delete(assets)
- .where(eq(assets.id, oldAssets.contentAssetId))
- .run();
- assetIdsToDelete.push(oldAssets.contentAssetId);
- }
- });
-
- // Delete the old assets if any
- await Promise.all(
- assetIdsToDelete.map((assetId) => silentDeleteAsset(userId, assetId)),
- );
-
- return async () => {
- if (
- !precrawledArchiveAssetId &&
- (serverConfig.crawler.fullPageArchive || archiveFullPage)
- ) {
- const archiveResult = await archiveWebpage(
- htmlContent,
- browserUrl,
- userId,
- jobId,
- abortSignal,
- runProxy,
- );
-
- if (archiveResult) {
- const {
- assetId: fullPageArchiveAssetId,
- size,
- contentType,
- } = archiveResult;
-
- await db.transaction((txn) => {
- updateAsset(
- oldAssets.fullPageArchiveAssetId,
- {
- id: fullPageArchiveAssetId,
- bookmarkId,
- userId,
- assetType: AssetTypes.LINK_FULL_PAGE_ARCHIVE,
- contentType,
- size,
- fileName: null,
- },
- txn,
- );
- });
- if (oldAssets.fullPageArchiveAssetId) {
- await silentDeleteAsset(userId, oldAssets.fullPageArchiveAssetId);
- }
- }
- }
- };
- },
- );
-}
diff --git a/apps/workers/workers/crawler/crawlPage.ts b/apps/workers/workers/crawler/crawlPage.ts
deleted file mode 100644
index 82692ea6..00000000
--- a/apps/workers/workers/crawler/crawlPage.ts
+++ /dev/null
@@ -1,805 +0,0 @@
-// The browser-based page fetch: navigates to the URL in a Playwright context
-// (with redirect/sub-request SSRF guards, adblocking, and proxy auth) and
-// captures the page's HTML, an optional screenshot, and an optional PDF.
-// Falls back to a plain HTTP fetch when no browser is available or the user
-// has browser crawling disabled.
-import { eq } from "drizzle-orm";
-import {
- fetchWithProxy,
- getBookmarkDomain,
- matchesNoProxy,
- validateUrl,
-} from "network";
-import type { RunProxyConfig } from "network";
-import {
- Browser,
- BrowserContext,
- BrowserContextOptions,
- CDPSession,
- Page,
-} from "patchright";
-import { abortRace, abortRaceResolve, raceWith, timeoutRace } from "utils";
-
-import { db } from "@karakeep/db";
-import { users } from "@karakeep/db/schema";
-import {
- getTracer,
- setSpanAttributes,
- withSpan,
-} from "@karakeep/shared-server";
-import serverConfig from "@karakeep/shared/config";
-import logger from "@karakeep/shared/logger";
-import { tryCatch } from "@karakeep/shared/tryCatch";
-
-import {
- installAutoconsent,
- waitForPageLoadAndAutoconsent,
-} from "./autoconsent";
-import {
- CONTEXT_CLOSE_TIMEOUT_MS,
- PAGE_CLOSE_TIMEOUT_MS,
- getGlobalBlocker,
- getGlobalBrowser,
- getBrowserUserAgent,
- getGlobalCookies,
- getPlaywrightProxyConfig,
- startBrowserInstance,
- trackContext,
- untrackContext,
-} from "./browser";
-import { waitForChallengeToClear } from "./challenge";
-import { truncateUrl } from "./utils";
-
-const tracer = getTracer("@karakeep/workers");
-
-export interface CrawlPageResult {
- htmlContent: string;
- screenshot: Buffer | undefined;
- pdf: Buffer | undefined;
- statusCode: number;
- url: string;
-}
-
-function getHeaderValue(
- headers: { name: string; value: string }[] | undefined,
- name: string,
-): string | undefined {
- return headers?.find((header) => header.name.toLowerCase() === name)?.value;
-}
-
-async function browserlessCrawlPage(
- jobId: string,
- url: string,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
-): Promise<CrawlPageResult> {
- return await withSpan(
- tracer,
- "crawlerWorker.browserlessCrawlPage",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- },
- },
- async () => {
- logger.info(
- `[Crawler][${jobId}] Running in browserless mode. Will do a plain http request to "${truncateUrl(url)}". Screenshots will be disabled.`,
- );
- const response = await fetchWithProxy(
- url,
- {
- signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),
- },
- runProxy,
- );
- logger.info(
- `[Crawler][${jobId}] Successfully fetched the content of "${truncateUrl(url)}". Status: ${response.status}, Size: ${response.size}`,
- );
- return {
- htmlContent: await response.text(),
- statusCode: response.status,
- screenshot: undefined,
- pdf: undefined,
- url: response.url,
- };
- },
- );
-}
-
-/**
- * Installs a CDP-level guard that validates every redirect target before the
- * browser follows it (blocking redirects into disallowed/internal addresses)
- * and answers proxy auth challenges with the run's proxy credentials.
- */
-async function installRedirectGuard(
- context: BrowserContext,
- page: Page,
- jobId: string,
- proxyConfig: BrowserContextOptions["proxy"],
-): Promise<CDPSession | undefined> {
- let cdpSession: CDPSession | undefined;
-
- try {
- cdpSession = await context.newCDPSession(page);
- const continuePausedRequest = async (requestId: string) => {
- await cdpSession
- ?.send("Fetch.continueRequest", { requestId })
- .catch(() => {
- // Ignore errors — the request may have been canceled.
- });
- };
- const failPausedRequest = async (requestId: string) => {
- await cdpSession
- ?.send("Fetch.failRequest", {
- requestId,
- errorReason: "BlockedByClient",
- })
- .catch(() => {
- // Ignore errors — the request may have been canceled.
- });
- };
- cdpSession.on("Fetch.authRequired", async (event) => {
- const authChallengeResponse =
- event.authChallenge.source === "Proxy" &&
- (proxyConfig?.username || proxyConfig?.password)
- ? {
- response: "ProvideCredentials" as const,
- username: proxyConfig.username ?? "",
- password: proxyConfig.password ?? "",
- }
- : { response: "Default" as const };
- await cdpSession
- ?.send("Fetch.continueWithAuth", {
- requestId: event.requestId,
- authChallengeResponse,
- })
- .catch(() => {
- // Ignore errors — the request may have been canceled.
- });
- });
- cdpSession.on("Fetch.requestPaused", async (event) => {
- try {
- const status = event.responseStatusCode;
- if (!status || status < 300 || status >= 400) {
- await continuePausedRequest(event.requestId);
- return;
- }
-
- const location = getHeaderValue(event.responseHeaders, "location");
- if (!location) {
- await continuePausedRequest(event.requestId);
- return;
- }
-
- const redirectUrl = new URL(location, event.request.url).toString();
- const redirectIsRunningInProxyContext =
- proxyConfig !== undefined &&
- !matchesNoProxy(redirectUrl, proxyConfig.bypass?.split(",") ?? []);
- const validation = await validateUrl(
- redirectUrl,
- redirectIsRunningInProxyContext,
- );
-
- if (validation.ok) {
- await continuePausedRequest(event.requestId);
- return;
- }
-
- logger.warn(
- `[Crawler][${jobId}] Blocking redirect to disallowed URL "${redirectUrl}": ${validation.reason}`,
- );
- await failPausedRequest(event.requestId);
- } catch (e) {
- logger.warn(
- `[Crawler][${jobId}] Blocking redirect after redirect guard failed: ${e}`,
- );
- await failPausedRequest(event.requestId);
- }
- });
- await cdpSession.send("Fetch.enable", {
- handleAuthRequests: true,
- patterns: [
- { urlPattern: "*", requestStage: "Request" },
- { urlPattern: "*", requestStage: "Response" },
- ],
- });
- } catch (e) {
- logger.warn(`[Crawler][${jobId}] Failed to install redirect guard: ${e}`);
- }
-
- return cdpSession;
-}
-
-/**
- * Creates and configures the page: redirect guard, adblocking, dialog
- * auto-dismissal, media/SSRF request blocking, and abort wiring.
- */
-interface SetupPageResult {
- page: Page;
- autoconsentEnabled: boolean;
-}
-
-async function setupPage(
- context: BrowserContext,
- jobId: string,
- proxyConfig: BrowserContextOptions["proxy"],
- abortSignal: AbortSignal,
-): Promise<SetupPageResult> {
- return await withSpan(
- tracer,
- "crawlerWorker.crawlPage.setupPage",
- {
- attributes: {
- "job.id": jobId,
- },
- },
- async () => {
- // Create a new page in the context
- const nextPage = await context.newPage();
- const cdpSession = await installRedirectGuard(
- context,
- nextPage,
- jobId,
- proxyConfig,
- );
-
- // Apply ad blocking
- const globalBlocker = getGlobalBlocker();
- if (globalBlocker) {
- await globalBlocker.enableBlockingInPage(nextPage);
- }
-
- // Auto-dismiss JavaScript dialogs (alert, confirm, prompt)
- // to prevent pages from hanging during crawl.
- nextPage.on("dialog", (dialog) => {
- dialog.dismiss().catch(() => {
- // Ignore errors — the dialog may have already been closed.
- });
- });
-
- // Block audio/video resources and disallowed sub-requests
- await nextPage.route("**/*", async (route) => {
- if (abortSignal.aborted) {
- await route.abort("aborted");
- return;
- }
- const request = route.request();
- const resourceType = request.resourceType();
-
- // Block audio/video resources
- if (
- resourceType === "media" ||
- request.headers()["content-type"]?.includes("video/") ||
- request.headers()["content-type"]?.includes("audio/")
- ) {
- await route.abort("aborted");
- return;
- }
-
- const requestUrl = request.url();
- const requestIsRunningInProxyContext =
- proxyConfig !== undefined &&
- !matchesNoProxy(requestUrl, proxyConfig.bypass?.split(",") ?? []);
- if (
- requestUrl.startsWith("http://") ||
- requestUrl.startsWith("https://")
- ) {
- const validation = await validateUrl(
- requestUrl,
- requestIsRunningInProxyContext,
- );
- if (!validation.ok) {
- logger.warn(
- `[Crawler][${jobId}] Blocking sub-request to disallowed URL "${requestUrl}": ${validation.reason}`,
- );
- await route.abort("blockedbyclient");
- return;
- }
- }
-
- // Continue with other requests
- 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 autoconsentEnabled = await installAutoconsent(nextPage, jobId);
-
- // On abort, immediately stop intercepting requests so that
- // in-flight route handlers don't block page/context closure.
- abortSignal.addEventListener(
- "abort",
- () => {
- cdpSession?.detach().catch(() => {
- // Ignore errors — the session may already be detached.
- });
- nextPage.unrouteAll({ behavior: "ignoreErrors" }).catch(() => {
- // Ignore errors — the page may already be closed.
- });
- },
- { once: true },
- );
-
- return { page: nextPage, autoconsentEnabled };
- },
- );
-}
-
-/**
- * Extracts the page HTML and (depending on config) captures a screenshot and
- * a PDF, all in parallel.
- */
-async function capturePageAssets(
- activePage: Page,
- jobId: string,
- forceStorePdf: boolean,
- abortSignal: AbortSignal,
-): Promise<[string, Buffer | undefined, Buffer | undefined]> {
- return await withSpan(
- tracer,
- "crawlerWorker.crawlPage.captureAssets",
- {
- attributes: {
- "job.id": jobId,
- },
- },
- async () => {
- const htmlPromise = withSpan(
- tracer,
- "crawlerWorker.crawlPage.extractHtml",
- {
- attributes: {
- "job.id": jobId,
- },
- },
- async () => {
- const content = await activePage.content();
- abortSignal.throwIfAborted();
- logger.info(
- `[Crawler][${jobId}] Successfully fetched the page content.`,
- );
- return content;
- },
- );
-
- const screenshotPromise: Promise<Buffer | undefined> = serverConfig
- .crawler.storeScreenshot
- ? withSpan(
- tracer,
- "crawlerWorker.crawlPage.captureScreenshot",
- {
- attributes: {
- "job.id": jobId,
- "asset.type": "image",
- },
- },
- async () => {
- const { data: screenshotData, error: screenshotError } =
- await tryCatch(
- raceWith<Buffer>(
- activePage.screenshot({
- // If you change this, you need to change the asset type in the store function.
- type: "jpeg",
- fullPage: serverConfig.crawler.fullPageScreenshot,
- quality: 80,
- }),
- timeoutRace<Buffer>(
- serverConfig.crawler.screenshotTimeoutSec * 1000,
- () => {
- throw new Error(
- "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
- );
- },
- ),
- abortRaceResolve(abortSignal, Buffer.from("")),
- ),
- );
- abortSignal.throwIfAborted();
- if (screenshotError) {
- logger.warn(
- `[Crawler][${jobId}] Failed to capture the screenshot. Reason: ${screenshotError}`,
- );
- return undefined;
- }
- setSpanAttributes({
- "asset.size": screenshotData.byteLength,
- });
- logger.info(
- `[Crawler][${jobId}] Finished capturing page content and a screenshot. FullPageScreenshot: ${serverConfig.crawler.fullPageScreenshot}`,
- );
- return screenshotData;
- },
- )
- : Promise.resolve(undefined);
-
- const pdfPromise: Promise<Buffer | undefined> =
- serverConfig.crawler.storePdf || forceStorePdf
- ? withSpan(
- tracer,
- "crawlerWorker.crawlPage.capturePdf",
- {
- attributes: {
- "job.id": jobId,
- "asset.type": "pdf",
- },
- },
- async () => {
- const { data: pdfData, error: pdfError } = await tryCatch(
- raceWith<Buffer>(
- activePage.pdf({
- format: "A4",
- printBackground: true,
- }),
- timeoutRace<Buffer>(
- serverConfig.crawler.screenshotTimeoutSec * 1000,
- () => {
- throw new Error(
- "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
- );
- },
- ),
- abortRaceResolve(abortSignal, Buffer.from("")),
- ),
- );
- abortSignal.throwIfAborted();
- if (pdfError) {
- logger.warn(
- `[Crawler][${jobId}] Failed to capture the PDF. Reason: ${pdfError}`,
- );
- return undefined;
- }
- setSpanAttributes({
- "asset.size": pdfData.byteLength,
- });
- logger.info(
- `[Crawler][${jobId}] Finished capturing page content as PDF`,
- );
- return pdfData;
- },
- )
- : Promise.resolve(undefined);
-
- const captureResults = await Promise.all([
- htmlPromise,
- screenshotPromise,
- pdfPromise,
- ] as const);
- abortSignal.throwIfAborted();
- return captureResults;
- },
- );
-}
-
-/**
- * Closes the page and its context with timeouts so a hung close can't wedge
- * the job; contexts that fail to close stay tracked for the reaper. Also
- * closes the browser itself when it was connected on demand.
- */
-async function closePageAndContext(
- page: Page | undefined,
- context: BrowserContext,
- browser: Browser,
- jobId: string,
-): Promise<void> {
- await withSpan(
- tracer,
- "crawlerWorker.crawlPage.cleanup",
- {
- attributes: {
- "job.id": jobId,
- "crawler.cleanup.hasPage": !!page,
- },
- },
- async () => {
- // Explicitly close the page first (with timeout) to release resources
- // even if context.close() later hangs.
- if (page) {
- const pageToClose = page;
- const pageClosed = await withSpan(
- tracer,
- "crawlerWorker.crawlPage.cleanup.closePage",
- { attributes: { "job.id": jobId } },
- async () =>
- raceWith<boolean>(
- pageToClose
- .close()
- .then(() => true)
- .catch((e: unknown) => {
- logger.warn(`[Crawler][${jobId}] page.close() failed: ${e}`);
- return true;
- }),
- timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),
- ),
- );
- setSpanAttributes({ "crawler.cleanup.pageClosed": pageClosed });
- if (!pageClosed) {
- logger.warn(`[Crawler][${jobId}] page.close() timed out`);
- }
- }
-
- // Close the context (with timeout) to avoid hanging on in-flight ops.
- // Only remove from tracking if close actually succeeded; otherwise
- // the reaper will retry the close later.
- const contextClosed = await withSpan(
- tracer,
- "crawlerWorker.crawlPage.cleanup.closeContext",
- { attributes: { "job.id": jobId } },
- async () =>
- raceWith<boolean>(
- context
- .close()
- .then(() => true)
- .catch((e: unknown) => {
- logger.warn(`[Crawler][${jobId}] context.close() failed: ${e}`);
- return true; // Error means it's likely already closed
- }),
- timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),
- ),
- );
- setSpanAttributes({
- "crawler.cleanup.contextClosed": contextClosed,
- });
-
- if (contextClosed) {
- untrackContext(jobId);
- } else {
- logger.warn(
- `[Crawler][${jobId}] context.close() timed out — leaving in active set for reaper`,
- );
- }
-
- // Only close the browser if it was created on demand
- if (serverConfig.crawler.browserConnectOnDemand) {
- await withSpan(
- tracer,
- "crawlerWorker.crawlPage.cleanup.closeBrowser",
- { attributes: { "job.id": jobId } },
- async () =>
- browser
- .close()
- .then(() => {
- untrackContext(jobId);
- })
- .catch((e: unknown) => {
- logger.warn(`[Crawler][${jobId}] browser.close() failed: ${e}`);
- }),
- );
- }
- },
- );
-}
-
-export async function crawlPage(
- jobId: string,
- url: string,
- userId: string,
- forceStorePdf: boolean,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
- // When set, skips the per-user browserCrawlingEnabled DB lookup and uses this
- // value instead. Used by the adhoc crawl CLI, which has no user row.
- browserCrawlingEnabledOverride?: boolean,
-): Promise<CrawlPageResult> {
- return await withSpan(
- tracer,
- "crawlerWorker.crawlPage",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- "user.id": userId,
- "crawler.forceStorePdf": forceStorePdf,
- },
- },
- async () => {
- let browserCrawlingEnabled: boolean | null;
- if (browserCrawlingEnabledOverride !== undefined) {
- browserCrawlingEnabled = browserCrawlingEnabledOverride;
- } else {
- const userData = await db.query.users.findFirst({
- where: eq(users.id, userId),
- columns: { browserCrawlingEnabled: true },
- });
- if (!userData) {
- logger.error(`[Crawler][${jobId}] User ${userId} not found`);
- throw new Error(`User ${userId} not found`);
- }
- browserCrawlingEnabled = userData.browserCrawlingEnabled;
- }
-
- if (browserCrawlingEnabled !== null && !browserCrawlingEnabled) {
- return browserlessCrawlPage(jobId, url, abortSignal, runProxy);
- }
-
- const browser = await withSpan(
- tracer,
- "crawlerWorker.crawlPage.getBrowserInstance",
- {
- attributes: {
- "job.id": jobId,
- },
- },
- async () => {
- if (serverConfig.crawler.browserConnectOnDemand) {
- return startBrowserInstance();
- }
- return getGlobalBrowser();
- },
- );
- if (!browser) {
- return browserlessCrawlPage(jobId, url, abortSignal, runProxy);
- }
-
- const proxyConfig = getPlaywrightProxyConfig(runProxy);
- const userAgent = await getBrowserUserAgent(browser);
- const isRunningInProxyContext =
- proxyConfig !== undefined &&
- !matchesNoProxy(url, proxyConfig.bypass?.split(",") ?? []);
- const context = await withSpan(
- tracer,
- "crawlerWorker.crawlPage.createContext",
- {
- attributes: {
- "job.id": jobId,
- },
- },
- async () =>
- browser.newContext({
- viewport: { width: 1440, height: 900 },
- userAgent,
- // A UTC browser behind a proxy that geolocates elsewhere is a
- // strong bot signal; this should match the proxy's location.
- timezoneId: serverConfig.crawler.browserTimezone,
- proxy: proxyConfig,
- serviceWorkers: "block",
- }),
- );
-
- trackContext(jobId, context);
- let page: Page | undefined;
- try {
- const globalCookies = getGlobalCookies();
- if (globalCookies.length > 0) {
- await context.addCookies(globalCookies);
- logger.info(
- `[Crawler][${jobId}] Cookies successfully loaded into browser context`,
- );
- }
-
- const setup = await setupPage(context, jobId, proxyConfig, abortSignal);
- page = setup.page;
-
- // page is guaranteed to be assigned here; alias to a const for
- // TypeScript narrowing so the rest of the try block sees `Page`.
- const activePage = page;
-
- // Navigate to the target URL
- const navigationValidation = await withSpan(
- tracer,
- "crawlerWorker.crawlPage.validateNavigationTarget",
- {
- attributes: {
- "job.id": jobId,
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- },
- },
- async () => validateUrl(url, isRunningInProxyContext),
- );
- if (!navigationValidation.ok) {
- throw new Error(
- `Disallowed navigation target "${truncateUrl(url)}": ${navigationValidation.reason}`,
- );
- }
- const targetUrl = navigationValidation.url.toString();
- // Tracks the status of the latest main-frame document, which differs
- // from the initial navigation's when a bot challenge clears and
- // reloads into the real page.
- let mainDocumentStatus: number | undefined;
- activePage.on("response", (res) => {
- if (
- res.request().isNavigationRequest() &&
- res.frame() === activePage.mainFrame()
- ) {
- mainDocumentStatus = res.status();
- }
- });
- logger.info(`[Crawler][${jobId}] Navigating to "${targetUrl}"`);
- const response = await withSpan(
- tracer,
- "crawlerWorker.crawlPage.navigate",
- {
- attributes: {
- "job.id": jobId,
- "bookmark.url": targetUrl,
- "bookmark.domain": getBookmarkDomain(targetUrl),
- },
- },
- async () =>
- raceWith(
- activePage.goto(targetUrl, {
- timeout: serverConfig.crawler.navigateTimeoutSec * 1000,
- waitUntil: "domcontentloaded",
- }),
- abortRaceResolve(abortSignal, null),
- ),
- );
- setSpanAttributes({
- "crawler.statusCode": response?.status() ?? 0,
- });
-
- logger.info(
- `[Crawler][${jobId}] Successfully navigated to "${targetUrl}". Waiting for the page to load ...`,
- );
-
- // Wait until network is relatively idle or timeout after 5 seconds
- const pageLoad = withSpan(
- tracer,
- "crawlerWorker.crawlPage.waitForLoadState",
- {
- attributes: {
- "job.id": jobId,
- "bookmark.url": targetUrl,
- "bookmark.domain": getBookmarkDomain(targetUrl),
- },
- },
- async () => {
- await raceWith<unknown>(
- activePage
- .waitForLoadState("networkidle", { timeout: 5000 })
- .catch(() => ({})),
- timeoutRace<unknown>(5000, () => undefined),
- abortRace(abortSignal),
- );
- },
- );
-
- await waitForPageLoadAndAutoconsent(
- activePage,
- pageLoad,
- setup.autoconsentEnabled,
- abortSignal,
- );
- abortSignal.throwIfAborted();
-
- await withSpan(
- tracer,
- "crawlerWorker.crawlPage.waitForChallenge",
- { attributes: { "job.id": jobId } },
- () =>
- waitForChallengeToClear(
- activePage,
- mainDocumentStatus ?? response?.status() ?? 0,
- jobId,
- abortSignal,
- ),
- );
-
- logger.info(
- `[Crawler][${jobId}] Finished waiting for the page to load.`,
- );
-
- const [htmlContent, screenshot, pdf] = await capturePageAssets(
- activePage,
- jobId,
- forceStorePdf,
- abortSignal,
- );
-
- return {
- htmlContent,
- statusCode: mainDocumentStatus ?? response?.status() ?? 0,
- screenshot,
- pdf,
- url: activePage.url(),
- };
- } finally {
- await closePageAndContext(page, context, browser, jobId);
- }
- },
- );
-}
diff --git a/apps/workers/workers/crawler/probe.ts b/apps/workers/workers/crawler/probe.ts
deleted file mode 100644
index aa114f53..00000000
--- a/apps/workers/workers/crawler/probe.ts
+++ /dev/null
@@ -1,315 +0,0 @@
-// The pre-crawl probe: a plain GET that determines the URL's content type
-// (deciding asset-bookmark vs webpage routing) and, for HTML pages,
-// opportunistically extracts preview metadata in the background so the
-// bookmark gets a title/thumbnail before the slow browser render finishes.
-import { eq, sql } from "drizzle-orm";
-import { fetchWithProxy, getBookmarkDomain } from "network";
-import type { RunProxyConfig } from "network";
-import { raceWith, timeoutRejectRace } from "utils";
-
-import { db } from "@karakeep/db";
-import { bookmarkLinks } from "@karakeep/db/schema";
-import {
- addLogFields,
- ASSET_TYPES,
- getTracer,
- setSpanAttributes,
- withSpan,
-} from "@karakeep/shared-server";
-import serverConfig from "@karakeep/shared/config";
-import logger from "@karakeep/shared/logger";
-import { tryCatch } from "@karakeep/shared/tryCatch";
-
-import type { ParseSubprocessOutput } from "../utils/parseHtmlSubprocessIpc";
-import { isLikelyChallengePage } from "../utils/metadataResolver";
-import { runParseSubprocess } from "./parseSubprocess";
-import {
- normalizeContentType,
- shouldRetryCrawlStatusCode,
- truncateUrl,
-} from "./utils";
-
-const tracer = getTracer("@karakeep/workers");
-
-// Cap how much of the probed page we buffer for metadata extraction.
-// Preview metadata lives in <head>, so a couple of MB is plenty.
-const PROBE_MAX_BODY_BYTES = 2 * 1024 * 1024;
-// The content-type routing decision needs only the response headers, so it
-// keeps the tight timeout the probe always had. The body download (for
-// metadata extraction) runs alongside the browser crawl, so it gets a more
-// generous overall budget.
-const PROBE_HEADERS_TIMEOUT_MS = 5_000;
-const PROBE_TIMEOUT_MS = 30_000;
-
-const PROBE_HTML_CONTENT_TYPES = new Set<string>([
- ASSET_TYPES.TEXT_HTML,
- "application/xhtml+xml",
-]);
-
-export interface UrlProbeResult {
- contentType: string | null;
- /**
- * Resolves with the page's preview metadata (or null). The extraction runs
- * in the background so it can overlap with the browser crawl — await it
- * only when the metadata is actually needed. Never rejects.
- */
- metadata: Promise<ParseSubprocessOutput["metadata"] | null>;
-}
-
-/**
- * Probes the URL with a plain GET to determine its content type. When the
- * response is an HTML page, the body is also parsed (via the parse subprocess
- * in metadata-only mode) so callers get the page's preview metadata without
- * waiting for the full browser render. The returned promise resolves once the
- * content type is known; the metadata extraction keeps running in the
- * background behind `metadata`. Extraction is best-effort and never affects
- * the returned content type.
- */
-export async function getContentTypeAndMetadata(
- url: string,
- jobId: string,
- abortSignal: AbortSignal,
- runProxy: RunProxyConfig,
- opts?: { skipMetadataExtraction?: boolean },
-): Promise<UrlProbeResult> {
- return await withSpan(
- tracer,
- "crawlerWorker.getContentTypeAndMetadata",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- },
- },
- async () => {
- // The request-level signal uses the long budget (it also governs the
- // body read); the wait for the headers is raced separately against the
- // short timeout so a dead host can't delay the routing decision.
- const probeAbort = new AbortController();
- let response;
- try {
- logger.info(
- `[Crawler][${jobId}] Attempting to determine the content-type for the url ${truncateUrl(url)}`,
- );
- response = await raceWith(
- fetchWithProxy(
- url,
- {
- method: "GET",
- signal: AbortSignal.any([
- AbortSignal.timeout(PROBE_TIMEOUT_MS),
- abortSignal,
- probeAbort.signal,
- ]),
- size: PROBE_MAX_BODY_BYTES,
- headers: serverConfig.crawler.preflightUserAgent
- ? { "User-Agent": serverConfig.crawler.preflightUserAgent }
- : undefined,
- },
- runProxy,
- ),
- timeoutRejectRace(
- PROBE_HEADERS_TIMEOUT_MS,
- `Timed out after ${PROBE_HEADERS_TIMEOUT_MS}ms waiting for the response headers`,
- ),
- );
- } catch (e) {
- // Stop the underlying fetch if it's still in flight (header timeout).
- probeAbort.abort();
- logger.error(
- `[Crawler][${jobId}] Failed to determine the content-type for the url ${truncateUrl(url)}: ${e}`,
- );
- return { contentType: null, metadata: Promise.resolve(null) };
- }
- setSpanAttributes({
- "crawler.getContentType.statusCode": response.status,
- });
- const rawContentType = response.headers.get("content-type");
- const contentType = normalizeContentType(rawContentType);
- setSpanAttributes({
- "crawler.contentType": contentType ?? undefined,
- });
- logger.info(
- `[Crawler][${jobId}] Content-type for the url ${truncateUrl(url)} is "${contentType}"`,
- );
-
- if (!contentType || !PROBE_HTML_CONTENT_TYPES.has(contentType)) {
- return { contentType, metadata: Promise.resolve(null) };
- }
-
- // A previous run already extracted and stored this page's metadata; the
- // probe was only needed for the content-type routing decision.
- if (opts?.skipMetadataExtraction) {
- logger.info(
- `[Crawler][${jobId}] Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} as it was already fetched by a previous run`,
- );
- addLogFields<"crawlerWorker.run">({
- "crawler.probe.metadata": "reused_stored",
- });
- return { contentType, metadata: Promise.resolve(null) };
- }
-
- // A blocked/retryable status usually means a challenge or error page
- // whose metadata would be junk — don't extract it.
- if (shouldRetryCrawlStatusCode(response.status)) {
- logger.info(
- `[Crawler][${jobId}] Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} due to status code ${response.status}`,
- );
- addLogFields<"crawlerWorker.run">({
- "crawler.probe.metadata": "blocked_status",
- });
- return { contentType, metadata: Promise.resolve(null) };
- }
-
- // The response is an HTML page: parse its metadata from the body we've
- // already fetched. This is deliberately NOT awaited so it runs alongside
- // the browser crawl. It must never reject (callers may await it late or
- // not at all) and any failure here must not lose the content type, as
- // that would regress the asset-vs-webpage routing decision.
- const metadata = (async () => {
- try {
- const htmlContent = await response.text();
- const { metadata: parsedMetadata } = await runParseSubprocess(
- htmlContent,
- response.url,
- jobId,
- abortSignal,
- { metadataOnly: true },
- );
- if (
- isLikelyChallengePage({ title: parsedMetadata.title, htmlContent })
- ) {
- logger.info(
- `[Crawler][${jobId}] The content-type probe response for the url ${truncateUrl(url)} looks like a bot-challenge page; ignoring its metadata`,
- );
- addLogFields<"crawlerWorker.run">({
- "crawler.probe.metadata": "challenge_page",
- });
- return null;
- }
- logger.info(
- `[Crawler][${jobId}] Extracted page metadata from the content-type probe for the url ${truncateUrl(url)}`,
- );
- addLogFields<"crawlerWorker.run">({
- "crawler.probe.metadata": "extracted",
- });
- return parsedMetadata;
- } catch (e) {
- logger.warn(
- `[Crawler][${jobId}] Failed to extract page metadata from the content-type probe for the url ${truncateUrl(url)}: ${e}`,
- );
- addLogFields<"crawlerWorker.run">({
- "crawler.probe.metadata": "failed",
- });
- return null;
- }
- })();
- return { contentType, metadata };
- },
- );
-}
-
-/**
- * Writes the preview metadata extracted by the pre-crawl probe so the bookmark
- * gets a title/thumbnail before the (slow) browser render finishes.
- *
- * The write is strictly fill-only: each field is wrapped in
- * COALESCE(NULLIF(existing, ''), new) so it can only populate fields that are
- * currently empty and never override an existing value. This matters because
- * the probe extraction runs detached from the crawl attempt's lifecycle — if
- * an attempt fails early, this write can fire after a *retry* (possibly on
- * another worker) has already stored its final metadata, and it must not
- * clobber it. The post-render metadata write refines these values within the
- * owning attempt.
- */
-export async function writeProbeMetadata(
- bookmarkId: string,
- metadata: ParseSubprocessOutput["metadata"],
- jobId: string,
-) {
- // Don't store data URIs as they're not valid URLs and are usually quite large
- const image =
- metadata.image && !metadata.image.startsWith("data:")
- ? metadata.image
- : null;
- if (!metadata.title && !metadata.description && !image && !metadata.logo) {
- return;
- }
- await db
- .update(bookmarkLinks)
- .set({
- ...(metadata.title
- ? {
- title: sql`COALESCE(NULLIF(${bookmarkLinks.title}, ''), ${metadata.title})`,
- }
- : {}),
- ...(metadata.description
- ? {
- description: sql`COALESCE(NULLIF(${bookmarkLinks.description}, ''), ${metadata.description})`,
- }
- : {}),
- ...(image
- ? {
- imageUrl: sql`COALESCE(NULLIF(${bookmarkLinks.imageUrl}, ''), ${image})`,
- }
- : {}),
- ...(metadata.logo
- ? {
- favicon: sql`COALESCE(NULLIF(${bookmarkLinks.favicon}, ''), ${metadata.logo})`,
- }
- : {}),
- // Also record that the probe metadata has been fetched and stored, so
- // crawl retries can skip re-fetching it (see loadStoredProbeMetadata).
- probeMetadataAt: new Date(),
- })
- .where(eq(bookmarkLinks.id, bookmarkId));
- logger.info(
- `[Crawler][${jobId}] Wrote early metadata from the content-type probe.`,
- );
-}
-
-/**
- * Reloads previously stored probe metadata from the bookmark row. Used on
- * crawl retries (where `probeMetadataAt` shows a probe already succeeded)
- * instead of re-fetching and re-parsing the page, so the blocked-render merge
- * protection keeps working without the extra fetch. Never rejects.
- */
-export async function loadStoredProbeMetadata(
- bookmarkId: string,
- jobId: string,
-): Promise<ParseSubprocessOutput["metadata"] | null> {
- const { data: row, error } = await tryCatch(
- db.query.bookmarkLinks.findFirst({
- where: eq(bookmarkLinks.id, bookmarkId),
- columns: {
- title: true,
- description: true,
- imageUrl: true,
- favicon: true,
- author: true,
- publisher: true,
- datePublished: true,
- dateModified: true,
- },
- }),
- );
- if (error || !row) {
- if (error) {
- logger.warn(
- `[Crawler][${jobId}] Failed to load stored probe metadata: ${error}`,
- );
- }
- return null;
- }
- return {
- title: row.title,
- description: row.description,
- image: row.imageUrl,
- logo: row.favicon,
- author: row.author,
- publisher: row.publisher,
- datePublished: row.datePublished?.toISOString() ?? null,
- dateModified: row.dateModified?.toISOString() ?? null,
- };
-}
diff --git a/apps/workers/workers/crawlerWorker.ts b/apps/workers/workers/crawlerWorker.ts
index b19c13b4..a2366d64 100644
--- a/apps/workers/workers/crawlerWorker.ts
+++ b/apps/workers/workers/crawlerWorker.ts
@@ -1,24 +1,82 @@
-// The crawler worker's queue wiring and per-job orchestration. The heavy
-// lifting lives in ./crawler/: browser lifecycle (browser.ts), the browser
-// fetch itself (crawlPage.ts), the pre-crawl probe (probe.ts), HTML parsing
-// (parseSubprocess.ts), asset persistence (assetStorage.ts), and the
-// per-bookmark crawl flow (crawlAndParse.ts).
-import { and, eq } from "drizzle-orm";
-import { bookmarkCrawlLatencyHistogram, workerStatsCounter } from "metrics";
-import { getBookmarkDomain, selectRunProxies } from "network";
-import { withWorkerTracing, withWorkerEventLog } from "workerTracing";
-import { getBookmarkDetails } from "workerUtils";
+// The crawler worker. Read top-down: the queue wiring and runCrawler (the
+// whole job) come first, then the steps in the order they run:
+// 1. Before crawling: domain rate limit, and a probe that decides between an
+// asset bookmark (pdf/image) and a webpage, extracting early metadata.
+// 2a. The URL is a file: download it and turn the bookmark into an asset.
+// 2b. The URL is a webpage: fetch it in the browser (or use a precrawled
+// archive), parse it in a subprocess, and store metadata, content and
+// assets. The full-page archive runs last as it's the most failure-prone.
+// 3. After crawling: enqueue inference, search, video and webhook jobs.
+// The asset storage helpers are at the bottom.
+
+import { promises as fs } from "fs";
+import * as fsSync from "fs";
+import * as path from "node:path";
+import * as os from "os";
+import { Transform } from "stream";
+import { pipeline } from "stream/promises";
+import { dataUriToBuffer } from "data-uri-to-buffer";
+import type { MimeBuffer } from "data-uri-to-buffer";
+import { and, eq, sql } from "drizzle-orm";
+import { execa } from "execa";
+import {
+ bookmarkCrawlLatencyHistogram,
+ crawlerStatusCodeCounter,
+ workerStatsCounter,
+} from "metrics";
+import {
+ fetchWithProxy,
+ getBookmarkDomain,
+ matchesNoProxy,
+ selectRunProxies,
+ validateUrl,
+} from "network";
+import type { RunProxyConfig } from "network";
+// patchright is a drop-in Playwright fork that drives Chrome without enabling
+// the CDP Runtime domain, the most widely checked automation signal.
+import {
+ Browser,
+ BrowserContext,
+ BrowserContextOptions,
+ Page,
+} from "patchright";
+import {
+ abortRace,
+ abortRaceResolve,
+ raceWith,
+ timeoutRace,
+ timeoutRejectRace,
+} from "utils";
+import { withWorkerEventLog, withWorkerTracing } from "workerTracing";
+import { getBookmarkDetails, updateAsset } from "workerUtils";
import type { ZCrawlLinkRequest } from "@karakeep/shared-server";
+import type { ZReaderViewReason } from "@karakeep/shared/types/bookmarks";
import { db } from "@karakeep/db";
-import { bookmarkLinks, bookmarks } from "@karakeep/db/schema";
+import {
+ assets,
+ AssetTypes,
+ bookmarkAssets,
+ bookmarkLinks,
+ bookmarks,
+ users,
+} from "@karakeep/db/schema";
import {
addLogFields,
ASSET_TYPES,
+ AssetPreprocessingQueue,
EmbeddingsQueue,
+ getAssetSize,
getTracer,
IMAGE_ASSET_TYPES,
+ newAssetId,
OpenAIQueue,
+ QuotaService,
+ readAsset,
+ saveAsset,
+ saveAssetFromFile,
+ setSpanAttributes,
+ silentDeleteAsset,
SUPPORTED_UPLOAD_ASSET_TYPES,
triggerSearchReindex,
VideoWorkerQueue,
@@ -37,29 +95,95 @@ import {
} from "@karakeep/shared/queueing";
import { getRateLimitClient } from "@karakeep/shared/ratelimiting";
import { tryCatch } from "@karakeep/shared/tryCatch";
+import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import { WebhooksService } from "@karakeep/trpc/models/webhooks.service";
+import type { ParseSubprocessOutput } from "./utils/parseHtmlSubprocessIpc";
+import {
+ normalizeContentType,
+ redactUrlCredentials,
+ shouldRetryCrawlStatusCode,
+ truncateUrl,
+} from "./utils/crawlerUtils";
+import {
+ installAutoconsent,
+ waitForPageLoadAndAutoconsent,
+} from "./utils/autoconsent";
+import { waitForChallengeToClear } from "./utils/botChallenge";
import {
+ CONTEXT_CLOSE_TIMEOUT_MS,
+ getBrowserUserAgent,
+ getGlobalBlocker,
getGlobalBrowser,
+ getGlobalCookies,
+ getPlaywrightProxyConfig,
initializeBrowserEnvironment,
-} from "./crawler/browser";
+ PAGE_CLOSE_TIMEOUT_MS,
+ startBrowserInstance,
+ trackContext,
+ untrackContext,
+} from "./utils/browser";
import {
- crawlAndParseUrl,
- handleAsAssetBookmark,
-} from "./crawler/crawlAndParse";
-import {
- getContentTypeAndMetadata,
- loadStoredProbeMetadata,
- writeProbeMetadata,
-} from "./crawler/probe";
-import type { UrlProbeResult } from "./crawler/probe";
-import { redactUrlCredentials, truncateUrl } from "./crawler/utils";
-
-// Re-exported for the adhoc crawl CLI (scripts/crawlAdhoc.ts).
-export { crawlPage } from "./crawler/crawlPage";
+ isLikelyChallengePage,
+ resolveMetadata,
+} from "./utils/metadataResolver";
+import { runParseSubprocess } from "./utils/parseSubprocess";
+import { installRedirectGuard } from "./utils/redirectGuard";
const tracer = getTracer("@karakeep/workers");
+// Runs fn in a "crawlerWorker.<name>" span, a child of the current span.
+// Job-level attributes (job, bookmark, user) live on the root
+// crawlerWorker.run span; child spans only add their own specifics.
+function span<T>(name: string, fn: () => Promise<T>): Promise<T> {
+ return withSpan(tracer, `crawlerWorker.${name}`, {}, fn);
+}
+
+// Wraps fn so that every call runs in its own span (see span()).
+function traced<A extends unknown[], R>(
+ name: string,
+ fn: (...args: A) => Promise<R>,
+): (...args: A) => Promise<R> {
+ return (...args) => span(name, () => fn(...args));
+}
+
+/**
+ * What every step of a crawl needs to know about the job. Built once in
+ * runCrawler and passed as the first argument to each step.
+ */
+export interface CrawlContext {
+ jobId: string;
+ bookmarkId: string;
+ userId: string;
+ /** The bookmark's URL, before any redirects. */
+ url: string;
+ abortSignal: AbortSignal;
+ /** Picked once per run so that every request in the run uses the same proxy. */
+ runProxy: RunProxyConfig;
+ /**
+ * False when the user has browser crawling disabled, in which case pages
+ * are fetched over plain HTTP instead of with the browser.
+ */
+ browserCrawlingEnabled: boolean;
+ log: CrawlLogger;
+}
+
+type CrawlLogger = Record<"info" | "warn" | "error", (message: string) => void>;
+
+/** Logs with the "[Crawler][<jobId>]" prefix that all crawler log lines use. */
+export function crawlLogger(jobId: string): CrawlLogger {
+ const prefix = `[Crawler][${jobId}]`;
+ return {
+ info: (message) => logger.info(`${prefix} ${message}`),
+ warn: (message) => logger.warn(`${prefix} ${message}`),
+ error: (message) => logger.error(`${prefix} ${message}`),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Worker
+// ---------------------------------------------------------------------------
+
interface CrawlerRunResult {
status: "completed";
}
@@ -202,144 +326,17 @@ export class CrawlerWorker {
}
}
-/**
- * Checks if the domain should be rate limited and throws QueueRetryAfterError if needed.
- * @throws {QueueRetryAfterError} if the domain is rate limited
- */
-async function checkDomainRateLimit(url: string, jobId: string): Promise<void> {
- return await withSpan(
- tracer,
- "crawlerWorker.checkDomainRateLimit",
- {
- attributes: {
- "bookmark.url": url,
- "bookmark.domain": getBookmarkDomain(url),
- "job.id": jobId,
- },
- },
- async () => {
- const crawlerDomainRateLimitConfig =
- serverConfig.crawler.domainRatelimiting;
- if (!crawlerDomainRateLimitConfig) {
- return;
- }
-
- const rateLimitClient = await getRateLimitClient();
- if (!rateLimitClient) {
- return;
- }
-
- const hostname = new URL(url).hostname;
- const rateLimitResult = await rateLimitClient.checkRateLimit(
- {
- name: "domain-ratelimit",
- maxRequests: crawlerDomainRateLimitConfig.maxRequests,
- windowMs: crawlerDomainRateLimitConfig.windowMs,
- },
- hostname,
- );
-
- if (!rateLimitResult.allowed) {
- const resetInSeconds = rateLimitResult.resetInSeconds;
- // Add jitter to prevent thundering herd: +40% random variation
- const jitterFactor = 1.0 + Math.random() * 0.4; // Random value between 1.0 and 1.4
- const delayMs = Math.floor(resetInSeconds * 1000 * jitterFactor);
- logger.info(
- `[Crawler][${jobId}] Domain "${hostname}" is rate limited. Will retry in ${(delayMs / 1000).toFixed(2)} seconds (with jitter).`,
- );
- throw new QueueRetryAfterError(
- `Domain "${hostname}" is rate limited`,
- delayMs,
- );
- }
- },
- );
-}
-
-/**
- * Enqueues the follow-up work after a successful webpage crawl: inference
- * (tagging/summarization/embeddings), search reindexing, video download, and
- * the "crawled" webhook.
- */
-async function enqueuePostCrawlJobs(
- job: DequeuedJob<ZCrawlLinkRequest>,
- bookmarkId: string,
- userId: string,
- url: string,
-): Promise<void> {
- // Propagate priority to child jobs
- const enqueueOpts: EnqueueOptions = {
- priority: job.priority,
- groupId: userId,
- };
-
- // Enqueue openai job (if not set, assume it's true for backward compatibility)
- if (job.data.runInference !== false) {
- if (serverConfig.embedding.enableAutoIndexing) {
- await EmbeddingsQueue.enqueue(
- {
- bookmarkId,
- type: "embed",
- runTaggingOnComplete: true,
- },
- enqueueOpts,
- );
- } else {
- await OpenAIQueue.enqueue(
- {
- bookmarkId,
- type: "tag",
- },
- enqueueOpts,
- );
- }
- await OpenAIQueue.enqueue(
- {
- bookmarkId,
- type: "summarize",
- },
- enqueueOpts,
- );
- }
-
- // Update the search index
- await triggerSearchReindex(bookmarkId, enqueueOpts);
-
- if (serverConfig.crawler.downloadVideo) {
- // Trigger a potential download of a video from the URL
- await VideoWorkerQueue.enqueue(
- {
- bookmarkId,
- url,
- },
- enqueueOpts,
- );
- }
-
- // Trigger a webhook
- {
- const webhookService = new WebhooksService(db);
- await webhookService.triggerWebhook(
- bookmarkId,
- "crawled",
- userId,
- enqueueOpts,
- );
- }
-}
-
async function runCrawler(
job: DequeuedJob<ZCrawlLinkRequest>,
maxRetries: number,
): Promise<CrawlerRunResult> {
const jobId = `${job.id}:${job.runNumber}`;
+ const log = crawlLogger(jobId);
const numRetriesLeft = Math.max(maxRetries - job.runNumber, 0);
const request = zCrawlLinkRequestSchema.safeParse(job.data);
if (!request.success) {
- logger.error(
- `[Crawler][${jobId}] Got malformed job request: ${request.error.toString()}`,
- );
+ log.error(`Got malformed job request: ${request.error.toString()}`);
return { status: "completed" };
}
@@ -363,10 +360,27 @@ async function runCrawler(
probeMetadataAt,
} = await getBookmarkDetails(bookmarkId);
- await checkDomainRateLimit(url, jobId);
+ const userData = await db.query.users.findFirst({
+ where: eq(users.id, userId),
+ columns: { browserCrawlingEnabled: true },
+ });
+ if (!userData) {
+ log.error(`User ${userId} not found`);
+ throw new Error(`User ${userId} not found`);
+ }
- // Select proxy URLs once for the entire run so all requests use the same proxy.
const runProxy = selectRunProxies();
+ const ctx: CrawlContext = {
+ jobId,
+ bookmarkId,
+ userId,
+ url,
+ abortSignal: job.abortSignal,
+ runProxy,
+ // null means the user has no explicit setting, which defaults to enabled.
+ browserCrawlingEnabled: userData.browserCrawlingEnabled !== false,
+ log,
+ };
addLogFields<"crawlerWorker.run">({
"user.id": userId,
@@ -376,14 +390,22 @@ async function runCrawler(
runProxy.httpsProxy ?? runProxy.httpProxy ?? "",
),
});
+ setSpanAttributes({
+ "bookmark.id": bookmarkId,
+ "bookmark.url": url,
+ "bookmark.domain": getBookmarkDomain(url),
+ "user.id": userId,
+ "crawler.proxy": redactUrlCredentials(
+ runProxy.httpsProxy ?? runProxy.httpProxy ?? "",
+ ),
+ });
- logger.info(
- `[Crawler][${jobId}] Will crawl "${truncateUrl(url)}" for link with id "${bookmarkId}"`,
- );
+ log.info(`Will crawl "${truncateUrl(url)}" for link with id "${bookmarkId}"`);
+ await checkDomainRateLimit(ctx);
if (precrawledArchiveAssetId) {
- logger.info(
- `[Crawler][${jobId}] Skipped fetching content-type for the url ${url} as precrawledArchiveAssetId exists`,
+ log.info(
+ `Skipped fetching content-type for the url ${url} as precrawledArchiveAssetId exists`,
);
}
// Retry runs re-probe for the content type, but if a previous run already
@@ -394,7 +416,7 @@ async function runCrawler(
const { contentType, metadata: probeMetadata }: UrlProbeResult =
precrawledArchiveAssetId
? { contentType: ASSET_TYPES.TEXT_HTML, metadata: Promise.resolve(null) }
- : await getContentTypeAndMetadata(url, jobId, job.abortSignal, runProxy, {
+ : await getContentTypeAndMetadata(ctx, {
skipMetadataExtraction: reuseStoredProbeMetadata,
});
job.abortSignal.throwIfAborted();
@@ -403,29 +425,13 @@ async function runCrawler(
const isPdf = contentType === ASSET_TYPES.APPLICATION_PDF;
if (isPdf) {
- await handleAsAssetBookmark(
- url,
- "pdf",
- userId,
- jobId,
- bookmarkId,
- job.abortSignal,
- runProxy,
- );
+ await handleAsAssetBookmark(ctx, "pdf");
} else if (
contentType &&
IMAGE_ASSET_TYPES.has(contentType) &&
SUPPORTED_UPLOAD_ASSET_TYPES.has(contentType)
) {
- await handleAsAssetBookmark(
- url,
- "image",
- userId,
- jobId,
- bookmarkId,
- job.abortSignal,
- runProxy,
- );
+ await handleAsAssetBookmark(ctx, "image");
} else {
// Chain the early metadata write onto the (still running) probe
// extraction so a title/thumbnail lands as soon as it's ready, while the
@@ -438,25 +444,17 @@ async function runCrawler(
// metadata was already stored, reload it from the bookmark row instead.
// Never rejects.
const probeMetadataPromise = reuseStoredProbeMetadata
- ? loadStoredProbeMetadata(bookmarkId, jobId)
+ ? loadStoredProbeMetadata(ctx)
: probeMetadata.then(async (metadata) => {
if (metadata) {
- const { error } = await tryCatch(
- writeProbeMetadata(bookmarkId, metadata, jobId),
- );
+ const { error } = await tryCatch(writeProbeMetadata(ctx, metadata));
if (error) {
- logger.warn(
- `[Crawler][${jobId}] Failed to write early probe metadata: ${error}`,
- );
+ log.warn(`Failed to write early probe metadata: ${error}`);
}
}
return metadata;
});
- const archivalLogic = await crawlAndParseUrl({
- url,
- userId,
- jobId,
- bookmarkId,
+ const archivalLogic = await crawlAndParseUrl(ctx, {
oldAssets: {
screenshotAssetId: oldScreenshotAssetId,
pdfAssetId: oldPdfAssetId,
@@ -468,12 +466,10 @@ async function runCrawler(
archiveFullPage,
forceStorePdf: storePdf ?? false,
numRetriesLeft,
- abortSignal: job.abortSignal,
- runProxy,
probeMetadataPromise,
});
- await enqueuePostCrawlJobs(job, bookmarkId, userId, url);
+ await enqueuePostCrawlJobs(ctx, job);
// Do the archival as a separate last step as it has the potential for failure
await archivalLogic();
@@ -488,3 +484,1686 @@ async function runCrawler(
return { status: "completed" };
}
+
+// ---------------------------------------------------------------------------
+// 1. Before crawling
+// ---------------------------------------------------------------------------
+
+/**
+ * Checks if the domain should be rate limited and throws QueueRetryAfterError if needed.
+ * @throws {QueueRetryAfterError} if the domain is rate limited
+ */
+const checkDomainRateLimit = traced(
+ "checkDomainRateLimit",
+ async (ctx: CrawlContext): Promise<void> => {
+ const { url, log } = ctx;
+ const crawlerDomainRateLimitConfig =
+ serverConfig.crawler.domainRatelimiting;
+ if (!crawlerDomainRateLimitConfig) {
+ return;
+ }
+
+ const rateLimitClient = await getRateLimitClient();
+ if (!rateLimitClient) {
+ return;
+ }
+
+ const hostname = new URL(url).hostname;
+ const rateLimitResult = await rateLimitClient.checkRateLimit(
+ {
+ name: "domain-ratelimit",
+ maxRequests: crawlerDomainRateLimitConfig.maxRequests,
+ windowMs: crawlerDomainRateLimitConfig.windowMs,
+ },
+ hostname,
+ );
+
+ if (!rateLimitResult.allowed) {
+ const resetInSeconds = rateLimitResult.resetInSeconds;
+ // Add jitter to prevent thundering herd: +40% random variation
+ const jitterFactor = 1.0 + Math.random() * 0.4; // Random value between 1.0 and 1.4
+ const delayMs = Math.floor(resetInSeconds * 1000 * jitterFactor);
+ log.info(
+ `Domain "${hostname}" is rate limited. Will retry in ${(delayMs / 1000).toFixed(2)} seconds (with jitter).`,
+ );
+ throw new QueueRetryAfterError(
+ `Domain "${hostname}" is rate limited`,
+ delayMs,
+ );
+ }
+ },
+);
+
+// Cap how much of the probed page we buffer for metadata extraction.
+// Preview metadata lives in <head>, so a couple of MB is plenty.
+const PROBE_MAX_BODY_BYTES = 2 * 1024 * 1024;
+// The content-type routing decision needs only the response headers, so it
+// keeps the tight timeout the probe always had. The body download (for
+// metadata extraction) runs alongside the browser crawl, so it gets a more
+// generous overall budget.
+const PROBE_HEADERS_TIMEOUT_MS = 5_000;
+const PROBE_TIMEOUT_MS = 30_000;
+
+const PROBE_HTML_CONTENT_TYPES = new Set<string>([
+ ASSET_TYPES.TEXT_HTML,
+ "application/xhtml+xml",
+]);
+
+interface UrlProbeResult {
+ contentType: string | null;
+ /**
+ * Resolves with the page's preview metadata (or null). The extraction runs
+ * in the background so it can overlap with the browser crawl — await it
+ * only when the metadata is actually needed. Never rejects.
+ */
+ metadata: Promise<ParseSubprocessOutput["metadata"] | null>;
+}
+
+/**
+ * Probes the URL with a plain GET to determine its content type. When the
+ * response is an HTML page, the body is also parsed (via the parse subprocess
+ * in metadata-only mode) so callers get the page's preview metadata without
+ * waiting for the full browser render. The returned promise resolves once the
+ * content type is known; the metadata extraction keeps running in the
+ * background behind `metadata`. Extraction is best-effort and never affects
+ * the returned content type.
+ */
+const getContentTypeAndMetadata = traced(
+ "getContentTypeAndMetadata",
+ async (
+ ctx: CrawlContext,
+ opts?: { skipMetadataExtraction?: boolean },
+ ): Promise<UrlProbeResult> => {
+ const { url, jobId, abortSignal, runProxy, log } = ctx;
+ // The request-level signal uses the long budget (it also governs the
+ // body read); the wait for the headers is raced separately against the
+ // short timeout so a dead host can't delay the routing decision.
+ const probeAbort = new AbortController();
+ let response;
+ try {
+ log.info(
+ `Attempting to determine the content-type for the url ${truncateUrl(url)}`,
+ );
+ response = await raceWith(
+ fetchWithProxy(
+ url,
+ {
+ method: "GET",
+ signal: AbortSignal.any([
+ AbortSignal.timeout(PROBE_TIMEOUT_MS),
+ abortSignal,
+ probeAbort.signal,
+ ]),
+ size: PROBE_MAX_BODY_BYTES,
+ headers: serverConfig.crawler.preflightUserAgent
+ ? { "User-Agent": serverConfig.crawler.preflightUserAgent }
+ : undefined,
+ },
+ runProxy,
+ ),
+ timeoutRejectRace(
+ PROBE_HEADERS_TIMEOUT_MS,
+ `Timed out after ${PROBE_HEADERS_TIMEOUT_MS}ms waiting for the response headers`,
+ ),
+ );
+ } catch (e) {
+ // Stop the underlying fetch if it's still in flight (header timeout).
+ probeAbort.abort();
+ log.error(
+ `Failed to determine the content-type for the url ${truncateUrl(url)}: ${e}`,
+ );
+ return { contentType: null, metadata: Promise.resolve(null) };
+ }
+ setSpanAttributes({
+ "crawler.getContentType.statusCode": response.status,
+ });
+ const rawContentType = response.headers.get("content-type");
+ const contentType = normalizeContentType(rawContentType);
+ setSpanAttributes({
+ "crawler.contentType": contentType ?? undefined,
+ });
+ log.info(
+ `Content-type for the url ${truncateUrl(url)} is "${contentType}"`,
+ );
+
+ if (!contentType || !PROBE_HTML_CONTENT_TYPES.has(contentType)) {
+ return { contentType, metadata: Promise.resolve(null) };
+ }
+
+ // A previous run already extracted and stored this page's metadata; the
+ // probe was only needed for the content-type routing decision.
+ if (opts?.skipMetadataExtraction) {
+ log.info(
+ `Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} as it was already fetched by a previous run`,
+ );
+ addLogFields<"crawlerWorker.run">({
+ "crawler.probe.metadata": "reused_stored",
+ });
+ return { contentType, metadata: Promise.resolve(null) };
+ }
+
+ // A blocked/retryable status usually means a challenge or error page
+ // whose metadata would be junk — don't extract it.
+ if (shouldRetryCrawlStatusCode(response.status)) {
+ log.info(
+ `Skipping metadata extraction from the content-type probe for the url ${truncateUrl(url)} due to status code ${response.status}`,
+ );
+ addLogFields<"crawlerWorker.run">({
+ "crawler.probe.metadata": "blocked_status",
+ });
+ return { contentType, metadata: Promise.resolve(null) };
+ }
+
+ // The response is an HTML page: parse its metadata from the body we've
+ // already fetched. This is deliberately NOT awaited so it runs alongside
+ // the browser crawl. It must never reject (callers may await it late or
+ // not at all) and any failure here must not lose the content type, as
+ // that would regress the asset-vs-webpage routing decision.
+ const metadata = (async () => {
+ try {
+ const htmlContent = await response.text();
+ const { metadata: parsedMetadata } = await runParseSubprocess(
+ htmlContent,
+ response.url,
+ jobId,
+ abortSignal,
+ { metadataOnly: true },
+ );
+ if (
+ isLikelyChallengePage({ title: parsedMetadata.title, htmlContent })
+ ) {
+ log.info(
+ `The content-type probe response for the url ${truncateUrl(url)} looks like a bot-challenge page; ignoring its metadata`,
+ );
+ addLogFields<"crawlerWorker.run">({
+ "crawler.probe.metadata": "challenge_page",
+ });
+ return null;
+ }
+ log.info(
+ `Extracted page metadata from the content-type probe for the url ${truncateUrl(url)}`,
+ );
+ addLogFields<"crawlerWorker.run">({
+ "crawler.probe.metadata": "extracted",
+ });
+ return parsedMetadata;
+ } catch (e) {
+ log.warn(
+ `Failed to extract page metadata from the content-type probe for the url ${truncateUrl(url)}: ${e}`,
+ );
+ addLogFields<"crawlerWorker.run">({
+ "crawler.probe.metadata": "failed",
+ });
+ return null;
+ }
+ })();
+ return { contentType, metadata };
+ },
+);
+
+/**
+ * Writes the preview metadata extracted by the pre-crawl probe so the bookmark
+ * gets a title/thumbnail before the (slow) browser render finishes.
+ *
+ * The write is strictly fill-only: each field is wrapped in
+ * COALESCE(NULLIF(existing, ''), new) so it can only populate fields that are
+ * currently empty and never override an existing value. This matters because
+ * the probe extraction runs detached from the crawl attempt's lifecycle — if
+ * an attempt fails early, this write can fire after a *retry* (possibly on
+ * another worker) has already stored its final metadata, and it must not
+ * clobber it. The post-render metadata write refines these values within the
+ * owning attempt.
+ */
+async function writeProbeMetadata(
+ ctx: CrawlContext,
+ metadata: ParseSubprocessOutput["metadata"],
+) {
+ const { bookmarkId, log } = ctx;
+ // Don't store data URIs as they're not valid URLs and are usually quite large
+ const image =
+ metadata.image && !metadata.image.startsWith("data:")
+ ? metadata.image
+ : null;
+ if (!metadata.title && !metadata.description && !image && !metadata.logo) {
+ return;
+ }
+ await db
+ .update(bookmarkLinks)
+ .set({
+ ...(metadata.title
+ ? {
+ title: sql`COALESCE(NULLIF(${bookmarkLinks.title}, ''), ${metadata.title})`,
+ }
+ : {}),
+ ...(metadata.description
+ ? {
+ description: sql`COALESCE(NULLIF(${bookmarkLinks.description}, ''), ${metadata.description})`,
+ }
+ : {}),
+ ...(image
+ ? {
+ imageUrl: sql`COALESCE(NULLIF(${bookmarkLinks.imageUrl}, ''), ${image})`,
+ }
+ : {}),
+ ...(metadata.logo
+ ? {
+ favicon: sql`COALESCE(NULLIF(${bookmarkLinks.favicon}, ''), ${metadata.logo})`,
+ }
+ : {}),
+ // Also record that the probe metadata has been fetched and stored, so
+ // crawl retries can skip re-fetching it (see loadStoredProbeMetadata).
+ probeMetadataAt: new Date(),
+ })
+ .where(eq(bookmarkLinks.id, bookmarkId));
+ log.info(`Wrote early metadata from the content-type probe.`);
+}
+
+/**
+ * Reloads previously stored probe metadata from the bookmark row. Used on
+ * crawl retries (where `probeMetadataAt` shows a probe already succeeded)
+ * instead of re-fetching and re-parsing the page, so the blocked-render merge
+ * protection keeps working without the extra fetch. Never rejects.
+ */
+async function loadStoredProbeMetadata(
+ ctx: CrawlContext,
+): Promise<ParseSubprocessOutput["metadata"] | null> {
+ const { bookmarkId, log } = ctx;
+ const { data: row, error } = await tryCatch(
+ db.query.bookmarkLinks.findFirst({
+ where: eq(bookmarkLinks.id, bookmarkId),
+ columns: {
+ title: true,
+ description: true,
+ imageUrl: true,
+ favicon: true,
+ author: true,
+ publisher: true,
+ datePublished: true,
+ dateModified: true,
+ },
+ }),
+ );
+ if (error || !row) {
+ if (error) {
+ log.warn(`Failed to load stored probe metadata: ${error}`);
+ }
+ return null;
+ }
+ return {
+ title: row.title,
+ description: row.description,
+ image: row.imageUrl,
+ logo: row.favicon,
+ author: row.author,
+ publisher: row.publisher,
+ datePublished: row.datePublished?.toISOString() ?? null,
+ dateModified: row.dateModified?.toISOString() ?? null,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// 2a. The URL is a file (pdf/image)
+// ---------------------------------------------------------------------------
+
+/**
+ * Downloads the asset from the URL and transforms the linkBookmark to an assetBookmark
+ * @param url the url the user provided
+ * @param assetType the type of the asset we're downloading
+ * @param userId the id of the user
+ * @param jobId the id of the job for logging
+ * @param bookmarkId the id of the bookmark
+ */
+const handleAsAssetBookmark = traced(
+ "handleAsAssetBookmark",
+ async (ctx: CrawlContext, assetType: "image" | "pdf") => {
+ const { url, userId, jobId, bookmarkId } = ctx;
+ setSpanAttributes({ "asset.type": assetType });
+ const downloaded = await downloadAndStoreFile(ctx, url, assetType);
+ if (!downloaded) {
+ // Unlike screenshots and banner images, this download is the crawl's
+ // primary result. Without it the bookmark cannot be converted to an
+ // asset and none of the preprocessing/inference jobs can run.
+ throw new Error(
+ `[Crawler][${jobId}] Failed to download required ${assetType} asset`,
+ );
+ }
+ const fileName = path.basename(new URL(url).pathname);
+ await db.transaction((trx) => {
+ updateAsset(
+ undefined,
+ {
+ id: downloaded.assetId,
+ bookmarkId,
+ userId,
+ assetType: AssetTypes.BOOKMARK_ASSET,
+ contentType: downloaded.contentType,
+ size: downloaded.size,
+ fileName,
+ },
+ trx,
+ );
+ trx
+ .insert(bookmarkAssets)
+ .values({
+ id: bookmarkId,
+ assetType,
+ assetId: downloaded.assetId,
+ content: null,
+ fileName,
+ sourceUrl: url,
+ })
+ .run();
+ // Switch the type of the bookmark from LINK to ASSET
+ trx
+ .update(bookmarks)
+ .set({ type: BookmarkTypes.ASSET })
+ .where(eq(bookmarks.id, bookmarkId))
+ .run();
+ trx.delete(bookmarkLinks).where(eq(bookmarkLinks.id, bookmarkId)).run();
+ });
+ await AssetPreprocessingQueue.enqueue(
+ {
+ bookmarkId,
+ fixMode: false,
+ },
+ {
+ groupId: userId,
+ },
+ );
+ },
+);
+
+// ---------------------------------------------------------------------------
+// 2b. The URL is a webpage
+// ---------------------------------------------------------------------------
+
+type DBAssetType = typeof assets.$inferInsert;
+
+interface CrawlAndParseUrlArgs {
+ /** Asset ids from a previous crawl of this bookmark, replaced (and deleted) on success. */
+ oldAssets: {
+ screenshotAssetId: string | undefined;
+ pdfAssetId: string | undefined;
+ imageAssetId: string | undefined;
+ fullPageArchiveAssetId: string | undefined;
+ contentAssetId: string | undefined;
+ };
+ precrawledArchiveAssetId: string | undefined;
+ archiveFullPage: boolean;
+ forceStorePdf: boolean;
+ numRetriesLeft: number;
+ probeMetadataPromise: Promise<ParseSubprocessOutput["metadata"] | null>;
+}
+
+/**
+ * Crawls the url, parses it, and persists the bookmark's metadata, content,
+ * and assets. Returns a closure that runs the (failure-prone) full-page
+ * archival, so the caller can defer it to the very end of the job.
+ */
+const crawlAndParseUrl = traced(
+ "crawlAndParseUrl",
+ async (
+ ctx: CrawlContext,
+ args: CrawlAndParseUrlArgs,
+ ): Promise<() => Promise<void>> => {
+ const { url, userId, jobId, bookmarkId, abortSignal, runProxy, log } = ctx;
+ const {
+ oldAssets,
+ precrawledArchiveAssetId,
+ archiveFullPage,
+ forceStorePdf,
+ numRetriesLeft,
+ probeMetadataPromise,
+ } = args;
+ const sanitizedProxyUrl = redactUrlCredentials(
+ runProxy.httpsProxy ?? runProxy.httpProxy ?? "",
+ );
+
+ setSpanAttributes({
+ "crawler.archiveFullPage": archiveFullPage,
+ "crawler.forceStorePdf": forceStorePdf,
+ "crawler.hasPrecrawledArchive": !!precrawledArchiveAssetId,
+ });
+ let result: {
+ htmlContent: string;
+ screenshot: Buffer | undefined;
+ pdf: Buffer | undefined;
+ statusCode: number | null;
+ url: string;
+ };
+
+ if (precrawledArchiveAssetId) {
+ log.info(
+ `The page has been precrawled. Will use the precrawled archive instead.`,
+ );
+ const asset = await readAsset({
+ userId,
+ assetId: precrawledArchiveAssetId,
+ });
+ result = {
+ htmlContent: asset.asset.toString(),
+ screenshot: undefined,
+ pdf: undefined,
+ statusCode: 200,
+ url,
+ };
+ } else {
+ result = await crawlPage(ctx, forceStorePdf);
+ }
+ abortSignal.throwIfAborted();
+
+ const {
+ htmlContent,
+ screenshot,
+ pdf,
+ statusCode,
+ url: browserUrl,
+ } = result;
+
+ // Track status code in Prometheus
+ if (statusCode !== null) {
+ crawlerStatusCodeCounter
+ .labels(statusCode.toString(), sanitizedProxyUrl)
+ .inc();
+ setSpanAttributes({
+ "crawler.statusCode": statusCode,
+ });
+ }
+ addLogFields<"crawlerWorker.run">({
+ "crawler.status_code": statusCode,
+ });
+
+ if (shouldRetryCrawlStatusCode(statusCode)) {
+ if (numRetriesLeft > 0) {
+ throw new Error(
+ `[Crawler][${jobId}] Received status code ${statusCode}. Will retry crawl. Retries left: ${numRetriesLeft}`,
+ );
+ }
+ log.info(
+ `Received status code ${statusCode} on latest retry attempt. Proceeding without retry.`,
+ );
+ }
+
+ const {
+ metadata: renderMeta,
+ readableContent: parsedReadableContent,
+ readerViewAssessment,
+ } = await runParseSubprocess(htmlContent, browserUrl, jobId, abortSignal);
+ abortSignal.throwIfAborted();
+
+ // The probe metadata extraction has been running alongside the crawl;
+ // this is the point where it's needed. The promise never rejects and
+ // all its underlying work is time-bounded.
+ const probeMetadata = await probeMetadataPromise;
+ abortSignal.throwIfAborted();
+
+ // On the last retry attempt the crawl proceeds despite a blocked status
+ // code, and some bot walls serve their challenge page with a 200; in
+ // both cases don't let that page's metadata override clean values from
+ // the preflight probe.
+ const renderIsChallengePage = isLikelyChallengePage({
+ title: renderMeta.title,
+ htmlContent,
+ });
+ const renderBlocked =
+ shouldRetryCrawlStatusCode(statusCode) || renderIsChallengePage;
+ addLogFields<"crawlerWorker.run">({
+ "crawler.render_blocked": renderBlocked,
+ });
+ if (renderBlocked && probeMetadata) {
+ log.info(
+ `The rendered page looks blocked (status ${statusCode}); preferring preflight probe metadata.`,
+ );
+ }
+ const meta = resolveMetadata(renderMeta, probeMetadata, renderBlocked);
+ const readerViewReasons: ZReaderViewReason[] | null = readerViewAssessment
+ ? renderIsChallengePage &&
+ !readerViewAssessment.reasons.includes("challenge_page")
+ ? [...readerViewAssessment.reasons, "challenge_page"]
+ : readerViewAssessment.reasons
+ : null;
+
+ const parseDate = (date: string | null | undefined) => {
+ if (!date) {
+ return null;
+ }
+ try {
+ return new Date(date);
+ } catch {
+ return null;
+ }
+ };
+
+ // Phase 1: Write metadata immediately for fast user feedback.
+ // Content and asset storage happen later and can be slow (banner
+ // image download, screenshot/pdf upload, etc.).
+ await db
+ .update(bookmarkLinks)
+ .set({
+ title: meta.title,
+ description: meta.description,
+ // Don't store data URIs as they're not valid URLs and are usually quite large
+ imageUrl: meta.image?.startsWith("data:") ? null : meta.image,
+ favicon: meta.logo,
+ crawlStatusCode: statusCode,
+ author: meta.author,
+ publisher: meta.publisher,
+ datePublished: parseDate(meta.datePublished),
+ dateModified: parseDate(meta.dateModified),
+ })
+ .where(eq(bookmarkLinks.id, bookmarkId));
+
+ let readableContent = parsedReadableContent;
+
+ const screenshotAssetInfo = await raceWith(
+ storeCapturedAsset(ctx, "screenshot", screenshot),
+ abortRace(abortSignal),
+ );
+ abortSignal.throwIfAborted();
+
+ const pdfAssetInfo = await raceWith(
+ storeCapturedAsset(ctx, "pdf", pdf),
+ abortRace(abortSignal),
+ );
+ abortSignal.throwIfAborted();
+
+ const htmlContentAssetInfo = await storeHtmlContent(
+ ctx,
+ readableContent?.content,
+ );
+ abortSignal.throwIfAborted();
+ let imageAssetInfo: DBAssetType | null = null;
+ if (meta.image && serverConfig.crawler.downloadBannerImage) {
+ const downloaded = await downloadAndStoreFile(ctx, meta.image, "image");
+ if (downloaded) {
+ imageAssetInfo = {
+ id: downloaded.assetId,
+ bookmarkId,
+ userId,
+ assetType: AssetTypes.LINK_BANNER_IMAGE,
+ contentType: downloaded.contentType,
+ size: downloaded.size,
+ };
+ }
+ }
+ abortSignal.throwIfAborted();
+
+ // Phase 2: Write content and asset references.
+ // TODO(important): Restrict the size of content to store
+ const assetIdsToDelete: (string | undefined)[] = [];
+ const inlineHtmlContent =
+ htmlContentAssetInfo.result === "store_inline"
+ ? (readableContent?.content ?? null)
+ : null;
+ readableContent = null;
+ await db.transaction((txn) => {
+ txn
+ .update(bookmarkLinks)
+ .set({
+ crawledAt: new Date(),
+ htmlContent: inlineHtmlContent,
+ contentAssetId:
+ htmlContentAssetInfo.result === "stored"
+ ? htmlContentAssetInfo.assetId
+ : null,
+ readerViewStatus: readerViewAssessment?.status ?? null,
+ readerViewScore: readerViewAssessment?.score ?? null,
+ readerViewReasons,
+ readerViewClassifierVersion:
+ readerViewAssessment?.classifierVersion ?? null,
+ })
+ .where(eq(bookmarkLinks.id, bookmarkId))
+ .run();
+
+ if (screenshotAssetInfo) {
+ updateAsset(
+ oldAssets.screenshotAssetId,
+ {
+ id: screenshotAssetInfo.assetId,
+ bookmarkId,
+ userId,
+ assetType: AssetTypes.LINK_SCREENSHOT,
+ contentType: screenshotAssetInfo.contentType,
+ size: screenshotAssetInfo.size,
+ fileName: screenshotAssetInfo.fileName,
+ },
+ txn,
+ );
+ assetIdsToDelete.push(oldAssets.screenshotAssetId);
+ }
+ if (pdfAssetInfo) {
+ updateAsset(
+ oldAssets.pdfAssetId,
+ {
+ id: pdfAssetInfo.assetId,
+ bookmarkId,
+ userId,
+ assetType: AssetTypes.LINK_PDF,
+ contentType: pdfAssetInfo.contentType,
+ size: pdfAssetInfo.size,
+ fileName: pdfAssetInfo.fileName,
+ },
+ txn,
+ );
+ assetIdsToDelete.push(oldAssets.pdfAssetId);
+ }
+ if (imageAssetInfo) {
+ updateAsset(oldAssets.imageAssetId, imageAssetInfo, txn);
+ assetIdsToDelete.push(oldAssets.imageAssetId);
+ }
+ if (htmlContentAssetInfo.result === "stored") {
+ updateAsset(
+ oldAssets.contentAssetId,
+ {
+ id: htmlContentAssetInfo.assetId,
+ bookmarkId,
+ userId,
+ assetType: AssetTypes.LINK_HTML_CONTENT,
+ contentType: ASSET_TYPES.TEXT_HTML,
+ size: htmlContentAssetInfo.size,
+ fileName: null,
+ },
+ txn,
+ );
+ assetIdsToDelete.push(oldAssets.contentAssetId);
+ } else if (oldAssets.contentAssetId) {
+ // Unlink the old content asset
+ txn.delete(assets).where(eq(assets.id, oldAssets.contentAssetId)).run();
+ assetIdsToDelete.push(oldAssets.contentAssetId);
+ }
+ });
+
+ // Delete the old assets if any
+ await Promise.all(
+ assetIdsToDelete.map((assetId) => silentDeleteAsset(userId, assetId)),
+ );
+
+ return async () => {
+ if (
+ !precrawledArchiveAssetId &&
+ (serverConfig.crawler.fullPageArchive || archiveFullPage)
+ ) {
+ const archiveResult = await archiveWebpage(
+ ctx,
+ htmlContent,
+ browserUrl,
+ );
+
+ if (archiveResult) {
+ const {
+ assetId: fullPageArchiveAssetId,
+ size,
+ contentType,
+ } = archiveResult;
+
+ await db.transaction((txn) => {
+ updateAsset(
+ oldAssets.fullPageArchiveAssetId,
+ {
+ id: fullPageArchiveAssetId,
+ bookmarkId,
+ userId,
+ assetType: AssetTypes.LINK_FULL_PAGE_ARCHIVE,
+ contentType,
+ size,
+ fileName: null,
+ },
+ txn,
+ );
+ });
+ if (oldAssets.fullPageArchiveAssetId) {
+ await silentDeleteAsset(userId, oldAssets.fullPageArchiveAssetId);
+ }
+ }
+ }
+ };
+ },
+);
+
+interface CrawlPageResult {
+ htmlContent: string;
+ screenshot: Buffer | undefined;
+ pdf: Buffer | undefined;
+ statusCode: number;
+ url: string;
+}
+
+// Exported for the adhoc crawl CLI (scripts/crawlAdhoc.ts).
+export const crawlPage = traced(
+ "crawlPage",
+ async (
+ ctx: CrawlContext,
+ forceStorePdf: boolean,
+ ): Promise<CrawlPageResult> => {
+ const { url, jobId, abortSignal, runProxy, log } = ctx;
+ setSpanAttributes({ "crawler.forceStorePdf": forceStorePdf });
+
+ if (!ctx.browserCrawlingEnabled) {
+ return browserlessCrawlPage(ctx);
+ }
+
+ const browser = await span("crawlPage.getBrowserInstance", async () =>
+ serverConfig.crawler.browserConnectOnDemand
+ ? startBrowserInstance()
+ : getGlobalBrowser(),
+ );
+ if (!browser) {
+ return browserlessCrawlPage(ctx);
+ }
+
+ const proxyConfig = getPlaywrightProxyConfig(runProxy);
+ const userAgent = await getBrowserUserAgent(browser);
+ const isRunningInProxyContext =
+ proxyConfig !== undefined &&
+ !matchesNoProxy(url, proxyConfig.bypass?.split(",") ?? []);
+ const context = await span("crawlPage.createContext", () =>
+ browser.newContext({
+ viewport: { width: 1440, height: 900 },
+ userAgent,
+ // A UTC browser behind a proxy that geolocates elsewhere is a
+ // strong bot signal; this should match the proxy's location.
+ timezoneId: serverConfig.crawler.browserTimezone,
+ proxy: proxyConfig,
+ serviceWorkers: "block",
+ }),
+ );
+
+ trackContext(jobId, context);
+ let page: Page | undefined;
+ try {
+ const globalCookies = getGlobalCookies();
+ if (globalCookies.length > 0) {
+ await context.addCookies(globalCookies);
+ log.info(`Cookies successfully loaded into browser context`);
+ }
+
+ const setup = await setupPage(ctx, context, proxyConfig);
+ page = setup.page;
+
+ // page is guaranteed to be assigned here; alias to a const for
+ // TypeScript narrowing so the rest of the try block sees `Page`.
+ const activePage = page;
+
+ // Navigate to the target URL
+ const navigationValidation = await span(
+ "crawlPage.validateNavigationTarget",
+ () => validateUrl(url, isRunningInProxyContext),
+ );
+ if (!navigationValidation.ok) {
+ throw new Error(
+ `Disallowed navigation target "${truncateUrl(url)}": ${navigationValidation.reason}`,
+ );
+ }
+ const targetUrl = navigationValidation.url.toString();
+ // Tracks the status of the latest main-frame document, which differs
+ // from the initial navigation's when a bot challenge clears and
+ // reloads into the real page.
+ let mainDocumentStatus: number | undefined;
+ activePage.on("response", (res) => {
+ if (
+ res.request().isNavigationRequest() &&
+ res.frame() === activePage.mainFrame()
+ ) {
+ mainDocumentStatus = res.status();
+ }
+ });
+ log.info(`Navigating to "${targetUrl}"`);
+ const response = await span("crawlPage.navigate", () =>
+ raceWith(
+ activePage.goto(targetUrl, {
+ timeout: serverConfig.crawler.navigateTimeoutSec * 1000,
+ waitUntil: "domcontentloaded",
+ }),
+ abortRaceResolve(abortSignal, null),
+ ),
+ );
+ setSpanAttributes({ "crawler.statusCode": response?.status() ?? 0 });
+
+ log.info(
+ `Successfully navigated to "${targetUrl}". Waiting for the page to load ...`,
+ );
+
+ // Wait until network is relatively idle or timeout after 5 seconds
+ const pageLoad = span("crawlPage.waitForLoadState", () =>
+ raceWith<unknown>(
+ activePage
+ .waitForLoadState("networkidle", { timeout: 5000 })
+ .catch(() => ({})),
+ timeoutRace<unknown>(5000, () => undefined),
+ abortRace(abortSignal),
+ ),
+ );
+
+ await waitForPageLoadAndAutoconsent(
+ activePage,
+ pageLoad,
+ setup.autoconsentEnabled,
+ abortSignal,
+ );
+ abortSignal.throwIfAborted();
+
+ await span("crawlPage.waitForChallenge", () =>
+ waitForChallengeToClear(
+ activePage,
+ mainDocumentStatus ?? response?.status() ?? 0,
+ jobId,
+ abortSignal,
+ ),
+ );
+
+ log.info(`Finished waiting for the page to load.`);
+
+ const [htmlContent, screenshot, pdf] = await capturePageAssets(
+ ctx,
+ activePage,
+ forceStorePdf,
+ );
+
+ return {
+ htmlContent,
+ statusCode: mainDocumentStatus ?? response?.status() ?? 0,
+ screenshot,
+ pdf,
+ url: activePage.url(),
+ };
+ } finally {
+ await closePageAndContext(ctx, page, context, browser);
+ }
+ },
+);
+
+/**
+ * Creates and configures the page: redirect guard, adblocking, dialog
+ * auto-dismissal, media/SSRF request blocking, and abort wiring.
+ */
+const setupPage = traced(
+ "crawlPage.setupPage",
+ async (
+ ctx: CrawlContext,
+ context: BrowserContext,
+ proxyConfig: BrowserContextOptions["proxy"],
+ ): Promise<{ page: Page; autoconsentEnabled: boolean }> => {
+ const { jobId, abortSignal, log } = ctx;
+ // Create a new page in the context
+ const nextPage = await context.newPage();
+ const cdpSession = await installRedirectGuard(
+ context,
+ nextPage,
+ jobId,
+ proxyConfig,
+ );
+
+ // Apply ad blocking
+ const globalBlocker = getGlobalBlocker();
+ if (globalBlocker) {
+ await globalBlocker.enableBlockingInPage(nextPage);
+ }
+
+ // Auto-dismiss JavaScript dialogs (alert, confirm, prompt)
+ // to prevent pages from hanging during crawl.
+ nextPage.on("dialog", (dialog) => {
+ dialog.dismiss().catch(() => {
+ // Ignore errors — the dialog may have already been closed.
+ });
+ });
+
+ // Block audio/video resources and disallowed sub-requests
+ await nextPage.route("**/*", async (route) => {
+ if (abortSignal.aborted) {
+ await route.abort("aborted");
+ return;
+ }
+ const request = route.request();
+ const resourceType = request.resourceType();
+
+ // Block audio/video resources
+ if (
+ resourceType === "media" ||
+ request.headers()["content-type"]?.includes("video/") ||
+ request.headers()["content-type"]?.includes("audio/")
+ ) {
+ await route.abort("aborted");
+ return;
+ }
+
+ const requestUrl = request.url();
+ const requestIsRunningInProxyContext =
+ proxyConfig !== undefined &&
+ !matchesNoProxy(requestUrl, proxyConfig.bypass?.split(",") ?? []);
+ if (
+ requestUrl.startsWith("http://") ||
+ requestUrl.startsWith("https://")
+ ) {
+ const validation = await validateUrl(
+ requestUrl,
+ requestIsRunningInProxyContext,
+ );
+ if (!validation.ok) {
+ log.warn(
+ `Blocking sub-request to disallowed URL "${requestUrl}": ${validation.reason}`,
+ );
+ await route.abort("blockedbyclient");
+ return;
+ }
+ }
+
+ // Continue with other requests
+ 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 autoconsentEnabled = await installAutoconsent(nextPage, jobId);
+
+ // On abort, immediately stop intercepting requests so that
+ // in-flight route handlers don't block page/context closure.
+ abortSignal.addEventListener(
+ "abort",
+ () => {
+ cdpSession?.detach().catch(() => {
+ // Ignore errors — the session may already be detached.
+ });
+ nextPage.unrouteAll({ behavior: "ignoreErrors" }).catch(() => {
+ // Ignore errors — the page may already be closed.
+ });
+ },
+ { once: true },
+ );
+
+ return { page: nextPage, autoconsentEnabled };
+ },
+);
+
+/**
+ * Extracts the page HTML and (depending on config) captures a screenshot and
+ * a PDF, all in parallel.
+ */
+const capturePageAssets = traced(
+ "crawlPage.captureAssets",
+ async (
+ ctx: CrawlContext,
+ activePage: Page,
+ forceStorePdf: boolean,
+ ): Promise<[string, Buffer | undefined, Buffer | undefined]> => {
+ const { abortSignal, log } = ctx;
+ const htmlPromise = span("crawlPage.extractHtml", async () => {
+ const content = await activePage.content();
+ abortSignal.throwIfAborted();
+ log.info(`Successfully fetched the page content.`);
+ return content;
+ });
+
+ const screenshotPromise: Promise<Buffer | undefined> = serverConfig.crawler
+ .storeScreenshot
+ ? span("crawlPage.captureScreenshot", async () => {
+ const { data: screenshotData, error: screenshotError } =
+ await tryCatch(
+ raceWith<Buffer>(
+ activePage.screenshot({
+ // If you change this, change the content type in CAPTURED_ASSETS too.
+ type: "jpeg",
+ fullPage: serverConfig.crawler.fullPageScreenshot,
+ quality: 80,
+ }),
+ timeoutRace<Buffer>(
+ serverConfig.crawler.screenshotTimeoutSec * 1000,
+ () => {
+ throw new Error(
+ "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
+ );
+ },
+ ),
+ abortRaceResolve(abortSignal, Buffer.from("")),
+ ),
+ );
+ abortSignal.throwIfAborted();
+ if (screenshotError) {
+ log.warn(
+ `Failed to capture the screenshot. Reason: ${screenshotError}`,
+ );
+ return undefined;
+ }
+ setSpanAttributes({ "asset.size": screenshotData.byteLength });
+ log.info(
+ `Finished capturing page content and a screenshot. FullPageScreenshot: ${serverConfig.crawler.fullPageScreenshot}`,
+ );
+ return screenshotData;
+ })
+ : Promise.resolve(undefined);
+
+ const pdfPromise: Promise<Buffer | undefined> =
+ serverConfig.crawler.storePdf || forceStorePdf
+ ? span("crawlPage.capturePdf", async () => {
+ const { data: pdfData, error: pdfError } = await tryCatch(
+ raceWith<Buffer>(
+ activePage.pdf({
+ format: "A4",
+ printBackground: true,
+ }),
+ timeoutRace<Buffer>(
+ serverConfig.crawler.screenshotTimeoutSec * 1000,
+ () => {
+ throw new Error(
+ "TIMED_OUT, consider increasing CRAWLER_SCREENSHOT_TIMEOUT_SEC",
+ );
+ },
+ ),
+ abortRaceResolve(abortSignal, Buffer.from("")),
+ ),
+ );
+ abortSignal.throwIfAborted();
+ if (pdfError) {
+ log.warn(`Failed to capture the PDF. Reason: ${pdfError}`);
+ return undefined;
+ }
+ setSpanAttributes({ "asset.size": pdfData.byteLength });
+ log.info(`Finished capturing page content as PDF`);
+ return pdfData;
+ })
+ : Promise.resolve(undefined);
+
+ const captureResults = await Promise.all([
+ htmlPromise,
+ screenshotPromise,
+ pdfPromise,
+ ] as const);
+ abortSignal.throwIfAborted();
+ return captureResults;
+ },
+);
+
+/**
+ * Closes the page and its context with timeouts so a hung close can't wedge
+ * the job; contexts that fail to close stay tracked for the reaper. Also
+ * closes the browser itself when it was connected on demand.
+ */
+const closePageAndContext = traced(
+ "crawlPage.cleanup",
+ async (
+ ctx: CrawlContext,
+ page: Page | undefined,
+ context: BrowserContext,
+ browser: Browser,
+ ): Promise<void> => {
+ const { jobId, log } = ctx;
+ setSpanAttributes({ "crawler.cleanup.hasPage": !!page });
+
+ // Explicitly close the page first (with timeout) to release resources
+ // even if context.close() later hangs.
+ if (page) {
+ const pageToClose = page;
+ const pageClosed = await span("crawlPage.cleanup.closePage", () =>
+ raceWith<boolean>(
+ pageToClose
+ .close()
+ .then(() => true)
+ .catch((e: unknown) => {
+ log.warn(`page.close() failed: ${e}`);
+ return true;
+ }),
+ timeoutRace<boolean>(PAGE_CLOSE_TIMEOUT_MS, () => false),
+ ),
+ );
+ setSpanAttributes({ "crawler.cleanup.pageClosed": pageClosed });
+ if (!pageClosed) {
+ log.warn(`page.close() timed out`);
+ }
+ }
+
+ // Close the context (with timeout) to avoid hanging on in-flight ops.
+ // Only remove from tracking if close actually succeeded; otherwise
+ // the reaper will retry the close later.
+ const contextClosed = await span("crawlPage.cleanup.closeContext", () =>
+ raceWith<boolean>(
+ context
+ .close()
+ .then(() => true)
+ .catch((e: unknown) => {
+ log.warn(`context.close() failed: ${e}`);
+ return true; // Error means it's likely already closed
+ }),
+ timeoutRace<boolean>(CONTEXT_CLOSE_TIMEOUT_MS, () => false),
+ ),
+ );
+ setSpanAttributes({ "crawler.cleanup.contextClosed": contextClosed });
+
+ if (contextClosed) {
+ untrackContext(jobId);
+ } else {
+ log.warn(`context.close() timed out — leaving in active set for reaper`);
+ }
+
+ // Only close the browser if it was created on demand
+ if (serverConfig.crawler.browserConnectOnDemand) {
+ await span("crawlPage.cleanup.closeBrowser", () =>
+ browser
+ .close()
+ .then(() => {
+ untrackContext(jobId);
+ })
+ .catch((e: unknown) => {
+ log.warn(`browser.close() failed: ${e}`);
+ }),
+ );
+ }
+ },
+);
+
+const browserlessCrawlPage = traced(
+ "browserlessCrawlPage",
+ async (ctx: CrawlContext): Promise<CrawlPageResult> => {
+ const { url, abortSignal, runProxy, log } = ctx;
+ log.info(
+ `Running in browserless mode. Will do a plain http request to "${truncateUrl(url)}". Screenshots will be disabled.`,
+ );
+ const response = await fetchWithProxy(
+ url,
+ {
+ signal: AbortSignal.any([AbortSignal.timeout(5000), abortSignal]),
+ },
+ runProxy,
+ );
+ log.info(
+ `Successfully fetched the content of "${truncateUrl(url)}". Status: ${response.status}, Size: ${response.size}`,
+ );
+ return {
+ htmlContent: await response.text(),
+ statusCode: response.status,
+ screenshot: undefined,
+ pdf: undefined,
+ url: response.url,
+ };
+ },
+);
+
+// ---------------------------------------------------------------------------
+// 3. After crawling
+// ---------------------------------------------------------------------------
+
+/**
+ * Enqueues the follow-up work after a successful webpage crawl: inference
+ * (tagging/summarization/embeddings), search reindexing, video download, and
+ * the "crawled" webhook.
+ */
+async function enqueuePostCrawlJobs(
+ ctx: CrawlContext,
+ job: DequeuedJob<ZCrawlLinkRequest>,
+): Promise<void> {
+ const { bookmarkId, userId, url } = ctx;
+ // Propagate priority to child jobs
+ const enqueueOpts: EnqueueOptions = {
+ priority: job.priority,
+ groupId: userId,
+ };
+
+ // Enqueue openai job (if not set, assume it's true for backward compatibility)
+ if (job.data.runInference !== false) {
+ if (serverConfig.embedding.enableAutoIndexing) {
+ await EmbeddingsQueue.enqueue(
+ {
+ bookmarkId,
+ type: "embed",
+ runTaggingOnComplete: true,
+ },
+ enqueueOpts,
+ );
+ } else {
+ await OpenAIQueue.enqueue(
+ {
+ bookmarkId,
+ type: "tag",
+ },
+ enqueueOpts,
+ );
+ }
+ await OpenAIQueue.enqueue(
+ {
+ bookmarkId,
+ type: "summarize",
+ },
+ enqueueOpts,
+ );
+ }
+
+ // Update the search index
+ await triggerSearchReindex(bookmarkId, enqueueOpts);
+
+ if (serverConfig.crawler.downloadVideo) {
+ // Trigger a potential download of a video from the URL
+ await VideoWorkerQueue.enqueue(
+ {
+ bookmarkId,
+ url,
+ },
+ enqueueOpts,
+ );
+ }
+
+ // Trigger a webhook
+ {
+ const webhookService = new WebhooksService(db);
+ await webhookService.triggerWebhook(
+ bookmarkId,
+ "crawled",
+ userId,
+ enqueueOpts,
+ );
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Asset storage: screenshots, PDFs, images, HTML content, archives
+// ---------------------------------------------------------------------------
+
+const CAPTURED_ASSETS = {
+ screenshot: {
+ spanName: "storeScreenshot",
+ label: "screenshot",
+ // Must match the format capturePageAssets takes the screenshot in.
+ contentType: "image/jpeg",
+ fileName: "screenshot.jpeg",
+ },
+ pdf: {
+ spanName: "storePdf",
+ label: "PDF",
+ contentType: "application/pdf",
+ fileName: "page.pdf",
+ },
+} as const;
+
+/** Stores a screenshot or PDF captured from the page, if within quota. */
+function storeCapturedAsset(
+ ctx: CrawlContext,
+ kind: keyof typeof CAPTURED_ASSETS,
+ data: Buffer | undefined,
+) {
+ const { userId, log } = ctx;
+ const { spanName, label, contentType, fileName } = CAPTURED_ASSETS[kind];
+ return span(spanName, async () => {
+ setSpanAttributes({ "asset.size": data?.byteLength ?? 0 });
+ if (!data) {
+ log.info(`Skipping storing the ${label} as it's empty.`);
+ return null;
+ }
+
+ const { data: quotaApproved, error: quotaError } = await tryCatch(
+ QuotaService.checkStorageQuota(db, userId, data.byteLength),
+ );
+ if (quotaError) {
+ log.warn(
+ `Skipping ${label} storage due to quota exceeded: ${quotaError.message}`,
+ );
+ return null;
+ }
+
+ const assetId = newAssetId();
+ await saveAsset({
+ userId,
+ assetId,
+ metadata: { contentType, fileName },
+ asset: data,
+ quotaApproved,
+ });
+ log.info(
+ `Stored the ${label} as assetId: ${assetId} (${data.byteLength} bytes)`,
+ );
+ return { assetId, contentType, fileName, size: data.byteLength };
+ });
+}
+
+/**
+ * SingleFile / precrawled archives inline images as `data:` URIs, so the image
+ * URL metascraper extracts can be a base64 blob rather than something fetchable
+ * over the network. Decode it locally and store it as an asset instead of
+ * failing on the unsupported protocol.
+ */
+async function storeDataUriAsset(
+ ctx: CrawlContext,
+ url: string,
+ fileType: string,
+) {
+ const { userId, log } = ctx;
+ const maxBytes = serverConfig.maxAssetSizeMb * 1024 * 1024;
+
+ // Guardrail 1: cap the size *before* decoding into memory. base64 encodes 3
+ // bytes per 4 chars, so a URI longer than 4/3 the limit (plus header slack)
+ // must decode past it; the exact check below handles the rest.
+ if (url.length > Math.ceil((maxBytes * 4) / 3) + 1024) {
+ log.warn(
+ `Skipping data URI ${fileType}: encoded size (${url.length} chars) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
+ );
+ return null;
+ }
+
+ let asset: MimeBuffer;
+ try {
+ asset = dataUriToBuffer(url);
+ } catch (e) {
+ log.error(`Failed to decode data URI ${fileType}: ${e}`);
+ return null;
+ }
+
+ // Guardrail 2: never trust the declared mediatype for anything but the raster
+ // image types we actually serve as banners. Rejects svg/html/etc.;
+ // saveAsset's SUPPORTED_ASSET_TYPES check is the backstop.
+ const contentType = normalizeContentType(asset.type);
+ if (!contentType || !IMAGE_ASSET_TYPES.has(contentType)) {
+ log.warn(
+ `Skipping data URI ${fileType} with unsupported content type: ${contentType}`,
+ );
+ return null;
+ }
+
+ if (asset.byteLength > maxBytes) {
+ log.warn(
+ `Skipping data URI ${fileType}: decoded size (${asset.byteLength} bytes) exceeds maximum allowed size of ${serverConfig.maxAssetSizeMb}MB`,
+ );
+ return null;
+ }
+
+ const { data: quotaApproved, error: quotaError } = await tryCatch(
+ QuotaService.checkStorageQuota(db, userId, asset.byteLength),
+ );
+ if (quotaError) {
+ log.warn(
+ `Skipping data URI ${fileType} storage due to quota exceeded: ${quotaError.message}`,
+ );
+ return null;
+ }
+
+ const assetId = newAssetId();
+ await saveAsset({
+ userId,
+ assetId,
+ metadata: { contentType },
+ asset,
+ quotaApproved,
+ });
+ log.info(
+ `Stored data URI ${fileType} as assetId: ${assetId} (${asset.byteLength} bytes)`,
+ );
+ return { assetId, userId, contentType, size: asset.byteLength };
+}
+
+const downloadAndStoreFile = traced(
+ "downloadAndStoreFile",
+ async (ctx: CrawlContext, url: string, fileType: string) => {
+ const { userId, abortSignal, runProxy, log } = ctx;
+ setSpanAttributes({
+ "bookmark.url": url,
+ "bookmark.domain": getBookmarkDomain(url),
+ "asset.type": fileType,
+ });
+ let assetPath: string | undefined;
+ try {
+ if (url.startsWith("data:")) {
+ return await storeDataUriAsset(ctx, url, fileType);
+ }
+ log.info(`Downloading ${fileType} from "${truncateUrl(url)}"`);
+ const response = await fetchWithProxy(
+ url,
+ {
+ signal: abortSignal,
+ },
+ runProxy,
+ );
+ if (!response.ok || response.body == null) {
+ throw new Error(`Failed to download ${fileType}: ${response.status}`);
+ }
+
+ const contentType = normalizeContentType(
+ response.headers.get("content-type"),
+ );
+ if (!contentType) {
+ throw new Error("No content type in the response");
+ }
+
+ const assetId = newAssetId();
+ assetPath = path.join(os.tmpdir(), assetId);
+
+ let bytesRead = 0;
+ const contentLengthEnforcer = new Transform({
+ transform(chunk, _, callback) {
+ bytesRead += chunk.length;
+
+ if (abortSignal.aborted) {
+ callback(new Error("AbortError"));
+ } else if (bytesRead > serverConfig.maxAssetSizeMb * 1024 * 1024) {
+ callback(
+ new Error(
+ `Content length exceeds maximum allowed size: ${serverConfig.maxAssetSizeMb}MB`,
+ ),
+ );
+ } else {
+ callback(null, chunk); // pass data along unchanged
+ }
+ },
+ flush(callback) {
+ callback();
+ },
+ });
+
+ await pipeline(
+ response.body,
+ contentLengthEnforcer,
+ fsSync.createWriteStream(assetPath),
+ );
+
+ // Check storage quota before saving the asset
+ const { data: quotaApproved, error: quotaError } = await tryCatch(
+ QuotaService.checkStorageQuota(db, userId, bytesRead),
+ );
+
+ if (quotaError) {
+ log.warn(
+ `Skipping ${fileType} storage due to quota exceeded: ${quotaError.message}`,
+ );
+ return null;
+ }
+
+ await saveAssetFromFile({
+ userId,
+ assetId,
+ metadata: { contentType },
+ assetPath,
+ quotaApproved,
+ });
+
+ log.info(
+ `Downloaded ${fileType} as assetId: ${assetId} (${bytesRead} bytes)`,
+ );
+
+ return { assetId, userId, contentType, size: bytesRead };
+ } catch (e) {
+ log.error(`Failed to download and store ${fileType}: ${e}`);
+ // A crawler timeout aborts the job-wide signal. Do not turn that abort
+ // into a best-effort download miss: the queue runner must observe it so
+ // the crawl is retried and is not reported as successfully completed.
+ abortSignal.throwIfAborted();
+ return null;
+ } finally {
+ if (assetPath) {
+ await tryCatch(fs.unlink(assetPath));
+ }
+ }
+ },
+);
+
+const archiveWebpage = traced(
+ "archiveWebpage",
+ async (ctx: CrawlContext, html: string, url: string) => {
+ const { userId, abortSignal, runProxy, log } = ctx;
+ log.info(`Will attempt to archive page ...`);
+
+ {
+ // Archival is a heavy operation, so we need to check if the user is within reasonable quota before proceeding
+ const { error: quotaError } = await tryCatch(
+ QuotaService.checkStorageQuota(db, userId, /* estimated size */ 1024),
+ );
+ if (quotaError) {
+ log.warn(
+ `Skipping archival as the user has exceeded their quota: ${quotaError.message}`,
+ );
+ return null;
+ }
+ }
+
+ const assetId = newAssetId();
+ const assetPath = path.join(os.tmpdir(), assetId);
+
+ let res = await execa({
+ input: html,
+ cancelSignal: abortSignal,
+ env: {
+ https_proxy: runProxy.httpsProxy,
+ http_proxy: runProxy.httpProxy,
+ no_proxy: runProxy.noProxy?.join(","),
+ },
+ })("monolith", [
+ "-",
+ "-Ije",
+ "-t",
+ String(serverConfig.crawler.monolithTimeoutSec),
+ ...serverConfig.crawler.monolithArguments,
+ "-b",
+ url,
+ "-o",
+ assetPath,
+ ]);
+
+ if (res.isCanceled) {
+ log.error(`Canceled archiving the page as we hit global timeout.`);
+ await tryCatch(fs.unlink(assetPath));
+ return null;
+ }
+
+ if (res.exitCode !== 0) {
+ log.error(
+ `Failed to archive the page as the command exited with code ${res.exitCode}`,
+ );
+ await tryCatch(fs.unlink(assetPath));
+ return null;
+ }
+
+ const contentType = "text/html";
+
+ // Get file size and check quota before saving
+ const stats = await fs.stat(assetPath);
+ const fileSize = stats.size;
+
+ // Discard oversized archives: media-rich pages can produce 1GB+
+ // monolith files that never render and only hang/crash browsers.
+ // 0 (default) disables the limit.
+ const maxArchiveSizeMb = serverConfig.crawler.fullPageArchiveMaxSizeMb;
+ if (maxArchiveSizeMb > 0 && fileSize > maxArchiveSizeMb * 1024 * 1024) {
+ log.warn(
+ `Discarding page archive of ${fileSize} bytes as it exceeds CRAWLER_FULL_PAGE_ARCHIVE_MAX_SIZE_MB=${maxArchiveSizeMb}.`,
+ );
+ await tryCatch(fs.unlink(assetPath));
+ return null;
+ }
+
+ const { data: quotaApproved, error: quotaError } = await tryCatch(
+ QuotaService.checkStorageQuota(db, userId, fileSize),
+ );
+
+ if (quotaError) {
+ log.warn(
+ `Skipping page archive storage due to quota exceeded: ${quotaError.message}`,
+ );
+ await tryCatch(fs.unlink(assetPath));
+ return null;
+ }
+
+ await saveAssetFromFile({
+ userId,
+ assetId,
+ assetPath,
+ metadata: {
+ contentType,
+ },
+ quotaApproved,
+ });
+
+ log.info(`Done archiving the page as assetId: ${assetId}`);
+
+ return {
+ assetId,
+ contentType,
+ size: await getAssetSize({ userId, assetId }),
+ };
+ },
+);
+
+type StoreHtmlResult =
+ | { result: "stored"; assetId: string; size: number }
+ | { result: "store_inline" }
+ | { result: "not_stored" };
+
+const storeHtmlContent = traced(
+ "storeHtmlContent",
+ async (
+ ctx: CrawlContext,
+ htmlContent: string | undefined,
+ ): Promise<StoreHtmlResult> => {
+ const { userId, log } = ctx;
+ setSpanAttributes({
+ "bookmark.content.size": htmlContent
+ ? Buffer.byteLength(htmlContent, "utf8")
+ : 0,
+ });
+ if (!htmlContent) {
+ return { result: "not_stored" };
+ }
+
+ const contentSize = Buffer.byteLength(htmlContent, "utf8");
+
+ // Only store in assets if content is >= 50KB
+ if (contentSize < serverConfig.crawler.htmlContentSizeThreshold) {
+ log.info(
+ `HTML content size (${contentSize} bytes) is below threshold, storing inline`,
+ );
+ return { result: "store_inline" };
+ }
+
+ const { data: quotaApproved, error: quotaError } = await tryCatch(
+ QuotaService.checkStorageQuota(db, userId, contentSize),
+ );
+ if (quotaError) {
+ log.warn(
+ `Skipping HTML content storage due to quota exceeded: ${quotaError.message}`,
+ );
+ return { result: "not_stored" };
+ }
+
+ const assetId = newAssetId();
+
+ const { error: saveError } = await tryCatch(
+ saveAsset({
+ userId,
+ assetId,
+ asset: Buffer.from(htmlContent, "utf8"),
+ metadata: {
+ contentType: ASSET_TYPES.TEXT_HTML,
+ fileName: null,
+ },
+ quotaApproved,
+ }),
+ );
+ if (saveError) {
+ log.error(`Failed to store HTML content as asset: ${saveError}`);
+ throw saveError;
+ }
+
+ log.info(
+ `Stored large HTML content (${contentSize} bytes) as asset: ${assetId}`,
+ );
+
+ return {
+ result: "stored",
+ assetId,
+ size: contentSize,
+ };
+ },
+);
diff --git a/apps/workers/workers/crawler/autoconsent.ts b/apps/workers/workers/utils/autoconsent.ts
similarity index 100%
rename from apps/workers/workers/crawler/autoconsent.ts
rename to apps/workers/workers/utils/autoconsent.ts
diff --git a/apps/workers/workers/crawler/challenge.ts b/apps/workers/workers/utils/botChallenge.ts
similarity index 96%
rename from apps/workers/workers/crawler/challenge.ts
rename to apps/workers/workers/utils/botChallenge.ts
index 939b9844..ebdc8e7b 100644
--- a/apps/workers/workers/crawler/challenge.ts
+++ b/apps/workers/workers/utils/botChallenge.ts
@@ -11,10 +11,7 @@ import { setSpanAttributes } from "@karakeep/shared-server";
import serverConfig from "@karakeep/shared/config";
import logger from "@karakeep/shared/logger";
-import {
- isLikelyChallengePage,
- isWaitableChallenge,
-} from "../utils/metadataResolver";
+import { isLikelyChallengePage, isWaitableChallenge } from "./metadataResolver";
// Statuses bot-protection vendors serve their interstitials with.
const CHALLENGE_STATUS_CODES = new Set([401, 403, 429, 503]);
diff --git a/apps/workers/workers/crawler/browser.ts b/apps/workers/workers/utils/browser.ts
similarity index 99%
rename from apps/workers/workers/crawler/browser.ts
rename to apps/workers/workers/utils/browser.ts
index efb873c0..96192428 100644
--- a/apps/workers/workers/crawler/browser.ts
+++ b/apps/workers/workers/utils/browser.ts
@@ -29,7 +29,10 @@ import { setUrlHostnameFromResolvedAddress } from "@karakeep/shared/utils/url";
import { tryCatch } from "@karakeep/shared/tryCatch";
import { loadAutoconsent } from "./autoconsent";
-import { normalizeBrowserUserAgent, redactUrlCredentials } from "./utils";
+import {
+ normalizeBrowserUserAgent,
+ redactUrlCredentials,
+} from "./crawlerUtils";
interface Cookie {
name: string;
diff --git a/apps/workers/workers/crawler/utils.test.ts b/apps/workers/workers/utils/crawlerUtils.test.ts
similarity index 94%
rename from apps/workers/workers/crawler/utils.test.ts
rename to apps/workers/workers/utils/crawlerUtils.test.ts
index d941ca82..46127fb5 100644
--- a/apps/workers/workers/crawler/utils.test.ts
+++ b/apps/workers/workers/utils/crawlerUtils.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { normalizeBrowserUserAgent } from "./utils";
+import { normalizeBrowserUserAgent } from "./crawlerUtils";
describe("normalizeBrowserUserAgent", () => {
it("drops the headless marker and reduces the version", () => {
diff --git a/apps/workers/workers/crawler/utils.ts b/apps/workers/workers/utils/crawlerUtils.ts
similarity index 100%
rename from apps/workers/workers/crawler/utils.ts
rename to apps/workers/workers/utils/crawlerUtils.ts
diff --git a/apps/workers/workers/crawler/parseSubprocess.ts b/apps/workers/workers/utils/parseSubprocess.ts
similarity index 97%
rename from apps/workers/workers/crawler/parseSubprocess.ts
rename to apps/workers/workers/utils/parseSubprocess.ts
index e0be558d..84e6ded2 100644
--- a/apps/workers/workers/crawler/parseSubprocess.ts
+++ b/apps/workers/workers/utils/parseSubprocess.ts
@@ -11,12 +11,12 @@ import logger from "@karakeep/shared/logger";
import type {
ParseSubprocessError,
ParseSubprocessOutput,
-} from "../utils/parseHtmlSubprocessIpc";
+} from "./parseHtmlSubprocessIpc";
import {
parseSubprocessErrorSchema,
parseSubprocessOutputSchema,
-} from "../utils/parseHtmlSubprocessIpc";
-import { truncateUrl } from "./utils";
+} from "./parseHtmlSubprocessIpc";
+import { truncateUrl } from "./crawlerUtils";
const tracer = getTracer("@karakeep/workers");
diff --git a/apps/workers/workers/utils/redirectGuard.ts b/apps/workers/workers/utils/redirectGuard.ts
new file mode 100644
index 00000000..817908ef
--- /dev/null
+++ b/apps/workers/workers/utils/redirectGuard.ts
@@ -0,0 +1,123 @@
+// A CDP-level guard on the crawler's browser page: blocks redirects into
+// disallowed (internal/private) addresses, which Playwright's request routing
+// doesn't see, and answers proxy auth challenges with the run's credentials.
+import { matchesNoProxy, validateUrl } from "network";
+import type {
+ BrowserContext,
+ BrowserContextOptions,
+ CDPSession,
+ Page,
+} from "patchright";
+
+import logger from "@karakeep/shared/logger";
+
+function getHeaderValue(
+ headers: { name: string; value: string }[] | undefined,
+ name: string,
+): string | undefined {
+ return headers?.find((header) => header.name.toLowerCase() === name)?.value;
+}
+
+/**
+ * Installs a CDP-level guard that validates every redirect target before the
+ * browser follows it (blocking redirects into disallowed/internal addresses)
+ * and answers proxy auth challenges with the run's proxy credentials.
+ */
+export async function installRedirectGuard(
+ context: BrowserContext,
+ page: Page,
+ jobId: string,
+ proxyConfig: BrowserContextOptions["proxy"],
+): Promise<CDPSession | undefined> {
+ let cdpSession: CDPSession | undefined;
+
+ try {
+ cdpSession = await context.newCDPSession(page);
+ const continuePausedRequest = async (requestId: string) => {
+ await cdpSession
+ ?.send("Fetch.continueRequest", { requestId })
+ .catch(() => {
+ // Ignore errors — the request may have been canceled.
+ });
+ };
+ const failPausedRequest = async (requestId: string) => {
+ await cdpSession
+ ?.send("Fetch.failRequest", {
+ requestId,
+ errorReason: "BlockedByClient",
+ })
+ .catch(() => {
+ // Ignore errors — the request may have been canceled.
+ });
+ };
+ cdpSession.on("Fetch.authRequired", async (event) => {
+ const authChallengeResponse =
+ event.authChallenge.source === "Proxy" &&
+ (proxyConfig?.username || proxyConfig?.password)
+ ? {
+ response: "ProvideCredentials" as const,
+ username: proxyConfig.username ?? "",
+ password: proxyConfig.password ?? "",
+ }
+ : { response: "Default" as const };
+ await cdpSession
+ ?.send("Fetch.continueWithAuth", {
+ requestId: event.requestId,
+ authChallengeResponse,
+ })
+ .catch(() => {
+ // Ignore errors — the request may have been canceled.
+ });
+ });
+ cdpSession.on("Fetch.requestPaused", async (event) => {
+ try {
+ const status = event.responseStatusCode;
+ if (!status || status < 300 || status >= 400) {
+ await continuePausedRequest(event.requestId);
+ return;
+ }
+
+ const location = getHeaderValue(event.responseHeaders, "location");
+ if (!location) {
+ await continuePausedRequest(event.requestId);
+ return;
+ }
+
+ const redirectUrl = new URL(location, event.request.url).toString();
+ const redirectIsRunningInProxyContext =
+ proxyConfig !== undefined &&
+ !matchesNoProxy(redirectUrl, proxyConfig.bypass?.split(",") ?? []);
+ const validation = await validateUrl(
+ redirectUrl,
+ redirectIsRunningInProxyContext,
+ );
+
+ if (validation.ok) {
+ await continuePausedRequest(event.requestId);
+ return;
+ }
+
+ logger.warn(
+ `[Crawler][${jobId}] Blocking redirect to disallowed URL "${redirectUrl}": ${validation.reason}`,
+ );
+ await failPausedRequest(event.requestId);
+ } catch (e) {
+ logger.warn(
+ `[Crawler][${jobId}] Blocking redirect after redirect guard failed: ${e}`,
+ );
+ await failPausedRequest(event.requestId);
+ }
+ });
+ await cdpSession.send("Fetch.enable", {
+ handleAuthRequests: true,
+ patterns: [
+ { urlPattern: "*", requestStage: "Request" },
+ { urlPattern: "*", requestStage: "Response" },
+ ],
+ });
+ } catch (e) {
+ logger.warn(`[Crawler][${jobId}] Failed to install redirect guard: ${e}`);
+ }
+
+ return cdpSession;
+}