Skip to content

Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥

chore: api and scrape fixes (#3885)

tomsideguideada260dbeb81
diff --git a/apps/api/scripts/knip-with-typescript5.cjs b/apps/api/scripts/knip-with-typescript5.cjs
index 548b386de..481589d72 100644
--- a/apps/api/scripts/knip-with-typescript5.cjs
+++ b/apps/api/scripts/knip-with-typescript5.cjs
@@ -7,6 +7,22 @@ const knipNodeModules = path.dirname(path.dirname(knipPackagePath));
const knipTypescriptPath = path.join(knipNodeModules, "typescript");
const typescript5Path = path.dirname(require.resolve("typescript5/package.json"));
+// Windows "dir" symlinks require Developer Mode / elevation; junctions do the
+// same thing for directories without any special privilege. The type argument
+// is ignored on non-Windows, so a normal symlink is created there as before.
+const linkType = process.platform === "win32" ? "junction" : "dir";
+
+// Remove a symlink/junction without touching its target. Junctions report as a
+// directory to lstat and must be removed with rmdirSync; symlinks use unlinkSync.
+function removeLink(linkPath) {
+ if (!fs.existsSync(linkPath)) return;
+ if (fs.lstatSync(linkPath).isDirectory()) {
+ fs.rmdirSync(linkPath);
+ } else {
+ fs.unlinkSync(linkPath);
+ }
+}
+
let originalTarget;
let hadOriginal = false;
@@ -14,10 +30,10 @@ try {
hadOriginal = fs.existsSync(knipTypescriptPath);
if (hadOriginal) {
originalTarget = fs.readlinkSync(knipTypescriptPath);
- fs.unlinkSync(knipTypescriptPath);
+ removeLink(knipTypescriptPath);
}
- fs.symlinkSync(typescript5Path, knipTypescriptPath, "dir");
+ fs.symlinkSync(typescript5Path, knipTypescriptPath, linkType);
const result = spawnSync(
process.execPath,
@@ -28,11 +44,12 @@ try {
process.exitCode = result.status ?? 1;
} finally {
try {
- if (fs.existsSync(knipTypescriptPath)) {
- fs.unlinkSync(knipTypescriptPath);
- }
+ removeLink(knipTypescriptPath);
if (hadOriginal) {
- fs.symlinkSync(originalTarget, knipTypescriptPath, "dir");
+ const restoreTarget = path.isAbsolute(originalTarget)
+ ? originalTarget
+ : path.resolve(path.dirname(knipTypescriptPath), originalTarget);
+ fs.symlinkSync(restoreTarget, knipTypescriptPath, linkType);
}
} catch (error) {
console.error("Failed to restore knip TypeScript peer link:", error);
diff --git a/apps/api/src/controllers/v1/batch-scrape.ts b/apps/api/src/controllers/v1/batch-scrape.ts
index 221214880..c43fb5f3d 100644
--- a/apps/api/src/controllers/v1/batch-scrape.ts
+++ b/apps/api/src/controllers/v1/batch-scrape.ts
@@ -167,6 +167,13 @@ export async function batchScrapeController(
webhook: req.body.webhook,
};
+ if (req.body.appendToId && (!sc || sc.team_id !== req.auth.team_id)) {
+ return res.status(404).json({
+ success: false,
+ error: "Job not found",
+ });
+ }
+
if (!req.body.appendToId) {
sc.queueBackend = await resolveNewGroupBackend(sc.team_id);
await crawlGroup.addGroup(
diff --git a/apps/api/src/controllers/v1/deep-research-status.ts b/apps/api/src/controllers/v1/deep-research-status.ts
index cff1d9500..9c6624ef2 100644
--- a/apps/api/src/controllers/v1/deep-research-status.ts
+++ b/apps/api/src/controllers/v1/deep-research-status.ts
@@ -11,7 +11,7 @@ export async function deepResearchStatusController(
) {
const research = await getDeepResearch(req.params.jobId);
- if (!research) {
+ if (!research || research.team_id !== req.auth.team_id) {
return res.status(404).json({
success: false,
error: "Deep research job not found",
diff --git a/apps/api/src/controllers/v1/generate-llmstxt-status.ts b/apps/api/src/controllers/v1/generate-llmstxt-status.ts
index 3909d5564..21bda0273 100644
--- a/apps/api/src/controllers/v1/generate-llmstxt-status.ts
+++ b/apps/api/src/controllers/v1/generate-llmstxt-status.ts
@@ -12,7 +12,7 @@ export async function generateLLMsTextStatusController(
const generation = await getGeneratedLlmsTxt(req.params.jobId);
const showFullText = generation?.showFullText ?? false;
- if (!generation) {
+ if (!generation || generation.team_id !== req.auth.team_id) {
return res.status(404).json({
success: false,
error: "llmsTxt generation job not found",
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 43c49da3c..364659d3e 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -77,7 +77,6 @@ if (config.EXPRESS_TRUST_PROXY) {
}
const serverAdapter = new ExpressAdapter();
-serverAdapter.setBasePath(`/admin/${config.BULL_AUTH_KEY}/queues`);
const { addQueue, removeQueue, setQueues, replaceQueues } = createBullBoard({
queues: [
@@ -89,7 +88,12 @@ const { addQueue, removeQueue, setQueues, replaceQueues } = createBullBoard({
serverAdapter: serverAdapter,
});
-app.use(`/admin/${config.BULL_AUTH_KEY}/queues`, serverAdapter.getRouter());
+if (config.BULL_AUTH_KEY) {
+ serverAdapter.setBasePath(`/admin/${config.BULL_AUTH_KEY}/queues`);
+ app.use(`/admin/${config.BULL_AUTH_KEY}/queues`, serverAdapter.getRouter());
+} else {
+ logger.warn("BULL_AUTH_KEY is not set; admin routes are disabled.");
+}
app.get("/", (_, res) => {
res.json({
diff --git a/apps/api/src/lib/extract/fire-0/helpers/transform-array-to-obj-f0.ts b/apps/api/src/lib/extract/fire-0/helpers/transform-array-to-obj-f0.ts
index 8ea286339..aeaaf5929 100644
--- a/apps/api/src/lib/extract/fire-0/helpers/transform-array-to-obj-f0.ts
+++ b/apps/api/src/lib/extract/fire-0/helpers/transform-array-to-obj-f0.ts
@@ -66,7 +66,7 @@ export function transformArrayToObject_F0(
// Initialize the array in the transformed result
let currentLevel = transformedResult;
arrayKeyParts.forEach(part => {
- if (!currentLevel[part]) {
+ if (!Object.prototype.hasOwnProperty.call(currentLevel, part)) {
currentLevel[part] = {};
}
currentLevel = currentLevel[part];
diff --git a/apps/api/src/lib/extract/helpers/transform-array-to-obj.ts b/apps/api/src/lib/extract/helpers/transform-array-to-obj.ts
index 1e0b5f92d..47e167c1d 100644
--- a/apps/api/src/lib/extract/helpers/transform-array-to-obj.ts
+++ b/apps/api/src/lib/extract/helpers/transform-array-to-obj.ts
@@ -66,7 +66,7 @@ export function transformArrayToObject(
// Initialize the array in the transformed result
let currentLevel = transformedResult;
arrayKeyParts.forEach(part => {
- if (!currentLevel[part]) {
+ if (!Object.prototype.hasOwnProperty.call(currentLevel, part)) {
currentLevel[part] = {};
}
currentLevel = currentLevel[part];
diff --git a/apps/api/src/routes/admin.ts b/apps/api/src/routes/admin.ts
index 1a36679e7..c3c198147 100644
--- a/apps/api/src/routes/admin.ts
+++ b/apps/api/src/routes/admin.ts
@@ -25,69 +25,74 @@ import { RateLimiterMode } from "../types";
export const adminRouter = express.Router();
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/redis-health`,
- redisHealthController,
-);
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/autumn-health`,
- autumnHealthController,
-);
-
-adminRouter.post(
- `/admin/${config.BULL_AUTH_KEY}/acuc-cache-clear`,
- wrap(acucCacheClearController),
-);
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/feng-check`,
- wrap(checkFireEngine),
-);
-
-adminRouter.get(`/admin/${config.BULL_AUTH_KEY}/cclog`, wrap(cclogController));
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/index-queue-prometheus`,
- wrap(indexQueuePrometheus),
-);
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/precrawl`,
- wrap(triggerPrecrawl),
-);
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/metrics`,
- wrap(metricsController),
-);
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/nuq-metrics`,
- wrap(nuqMetricsController),
-);
-
-adminRouter.get(
- `/admin/${config.BULL_AUTH_KEY}/nuq-fdb-metrics`,
- wrap(nuqFdbMetricsController),
-);
-
-adminRouter.post(
- `/admin/${config.BULL_AUTH_KEY}/fsearch`,
- wrap(realtimeSearchController),
-);
-
-adminRouter.post(
- `/admin/${config.BULL_AUTH_KEY}/concurrency-queue-backfill`,
- wrap(concurrencyQueueBackfillController),
-);
-
-adminRouter.post(
- `/admin/${config.BULL_AUTH_KEY}/crawl-monitor`,
- authMiddleware(RateLimiterMode.Crawl),
- checkCreditsMiddleware(2),
- wrap(crawlMonitorController),
-);
+if (config.BULL_AUTH_KEY) {
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/redis-health`,
+ redisHealthController,
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/autumn-health`,
+ autumnHealthController,
+ );
+
+ adminRouter.post(
+ `/admin/${config.BULL_AUTH_KEY}/acuc-cache-clear`,
+ wrap(acucCacheClearController),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/feng-check`,
+ wrap(checkFireEngine),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/cclog`,
+ wrap(cclogController),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/index-queue-prometheus`,
+ wrap(indexQueuePrometheus),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/precrawl`,
+ wrap(triggerPrecrawl),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/metrics`,
+ wrap(metricsController),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/nuq-metrics`,
+ wrap(nuqMetricsController),
+ );
+
+ adminRouter.get(
+ `/admin/${config.BULL_AUTH_KEY}/nuq-fdb-metrics`,
+ wrap(nuqFdbMetricsController),
+ );
+
+ adminRouter.post(
+ `/admin/${config.BULL_AUTH_KEY}/fsearch`,
+ wrap(realtimeSearchController),
+ );
+
+ adminRouter.post(
+ `/admin/${config.BULL_AUTH_KEY}/concurrency-queue-backfill`,
+ wrap(concurrencyQueueBackfillController),
+ );
+
+ adminRouter.post(
+ `/admin/${config.BULL_AUTH_KEY}/crawl-monitor`,
+ authMiddleware(RateLimiterMode.Crawl),
+ checkCreditsMiddleware(2),
+ wrap(crawlMonitorController),
+ );
+}
adminRouter.post(
`/admin/integration/create-user`,
diff --git a/apps/playwright-service-ts/api.ts b/apps/playwright-service-ts/api.ts
index 6f5b6ceee..73dc1f1e2 100644
--- a/apps/playwright-service-ts/api.ts
+++ b/apps/playwright-service-ts/api.ts
@@ -1,10 +1,18 @@
import express, { Request, Response } from 'express';
-import { chromium, Browser, BrowserContext, Route, Request as PlaywrightRequest, Page } from 'playwright';
+import {
+ chromium,
+ Browser,
+ BrowserContext,
+ Route,
+ Request as PlaywrightRequest,
+ Page,
+} from 'playwright';
import dotenv from 'dotenv';
import UserAgent from 'user-agents';
import { getError } from './helpers/get_error';
import { lookup } from 'dns/promises';
import IPAddr from 'ipaddr.js';
+import { Server, RequestError } from 'proxy-chain';
dotenv.config();
@@ -13,49 +21,47 @@ const port = process.env.PORT || 3003;
app.use(express.json());
-const BLOCK_MEDIA = (process.env.BLOCK_MEDIA || 'False').toUpperCase() === 'TRUE';
-const MAX_CONCURRENT_PAGES = Math.max(1, Number.parseInt(process.env.MAX_CONCURRENT_PAGES ?? '10', 10) || 10);
-const ALLOW_LOCAL_WEBHOOKS = (process.env.ALLOW_LOCAL_WEBHOOKS || 'False').toUpperCase() === 'TRUE';
-const DNS_CACHE_TTL_MS = 30_000;
+const BLOCK_MEDIA =
+ (process.env.BLOCK_MEDIA || 'False').toUpperCase() === 'TRUE';
+const MAX_CONCURRENT_PAGES = Math.max(
+ 1,
+ Number.parseInt(process.env.MAX_CONCURRENT_PAGES ?? '10', 10) || 10,
+);
+const ALLOW_LOCAL_WEBHOOKS =
+ (process.env.ALLOW_LOCAL_WEBHOOKS || 'False').toUpperCase() === 'TRUE';
const PROXY_SERVER = process.env.PROXY_SERVER || null;
const PROXY_USERNAME = process.env.PROXY_USERNAME || null;
const PROXY_PASSWORD = process.env.PROXY_PASSWORD || null;
-const dnsLookupCache = new Map<string, { addresses: string[]; expiresAt: number }>();
class InsecureConnectionError extends Error {
- constructor(public readonly blockedUrl: string, reason: string) {
+ constructor(
+ public readonly blockedUrl: string,
+ reason: string,
+ ) {
super(`Blocked insecure target URL "${blockedUrl}": ${reason}`);
this.name = 'InsecureConnectionError';
}
}
-const normalizeHostname = (hostname: string): string => hostname.toLowerCase().replace(/\.$/, '');
+const isInternalHost = async (hostname: string): Promise<boolean> => {
+ const host = hostname.toLowerCase().replace(/\.$/, '');
+ if (!host) return true;
-const isHttpProtocol = (protocol: string): boolean => protocol === 'http:' || protocol === 'https:';
-
-const isIPPrivate = (address: string): boolean => {
- if (!IPAddr.isValid(address)) return false;
- const parsedAddress = IPAddr.parse(address);
- return parsedAddress.range() !== 'unicast';
-};
-
-const isLocalHostname = (hostname: string): boolean =>
- hostname === 'localhost' || hostname.endsWith('.localhost');
-
-const lookupWithCache = async (hostname: string): Promise<string[]> => {
- const cached = dnsLookupCache.get(hostname);
- if (cached && cached.expiresAt > Date.now()) {
- return cached.addresses;
+ let addresses: string[];
+ if (IPAddr.isValid(host)) {
+ addresses = [host];
+ } else {
+ try {
+ addresses = (await lookup(host, { all: true })).map((a) => a.address);
+ } catch {
+ return true;
+ }
}
-
- const resolvedAddresses = await lookup(hostname, { all: true, verbatim: true });
- const uniqueAddresses = [...new Set(resolvedAddresses.map(x => x.address))];
- dnsLookupCache.set(hostname, {
- addresses: uniqueAddresses,
- expiresAt: Date.now() + DNS_CACHE_TTL_MS,
- });
- return uniqueAddresses;
+ return (
+ addresses.length === 0 ||
+ addresses.some((a) => IPAddr.parse(a).range() !== 'unicast')
+ );
};
const assertSafeTargetUrl = async (urlString: string): Promise<void> => {
@@ -65,53 +71,51 @@ const assertSafeTargetUrl = async (urlString: string): Promise<void> => {
} catch {
throw new InsecureConnectionError(urlString, 'URL is invalid');
}
-
- if (!isHttpProtocol(parsedUrl.protocol)) {
- throw new InsecureConnectionError(urlString, `unsupported protocol "${parsedUrl.protocol}"`);
- }
-
- if (ALLOW_LOCAL_WEBHOOKS) {
- return;
- }
-
- const hostname = normalizeHostname(parsedUrl.hostname);
- if (!hostname) {
- throw new InsecureConnectionError(urlString, 'hostname is missing');
- }
-
- if (isLocalHostname(hostname)) {
- throw new InsecureConnectionError(urlString, 'localhost targets are not allowed');
- }
-
- if (IPAddr.isValid(hostname)) {
- if (isIPPrivate(hostname)) {
- throw new InsecureConnectionError(urlString, `private IP "${hostname}" is not allowed`);
- }
- return;
- }
-
- let resolvedAddresses: string[];
- try {
- resolvedAddresses = await lookupWithCache(hostname);
- } catch {
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
throw new InsecureConnectionError(
urlString,
- `DNS lookup failed for "${hostname}", cannot verify target is safe`,
+ `unsupported protocol "${parsedUrl.protocol}"`,
);
}
-
- if (resolvedAddresses.length === 0) {
+ if (!ALLOW_LOCAL_WEBHOOKS && (await isInternalHost(parsedUrl.hostname))) {
throw new InsecureConnectionError(
urlString,
- `hostname "${hostname}" did not resolve to any IP address`,
+ 'resolves to a private/internal address',
);
}
+};
- if (resolvedAddresses.some(address => isIPPrivate(address))) {
- throw new InsecureConnectionError(urlString, `hostname "${hostname}" resolves to a private IP`);
- }
+const buildUpstreamProxyUrl = (): string | undefined => {
+ if (!PROXY_SERVER) return undefined;
+ const server = PROXY_SERVER.includes('://')
+ ? PROXY_SERVER
+ : `http://${PROXY_SERVER}`;
+ const url = new URL(server);
+ if (PROXY_USERNAME) url.username = PROXY_USERNAME;
+ if (PROXY_PASSWORD) url.password = PROXY_PASSWORD;
+ return url.toString();
};
+const startSSRFProxy = async (): Promise<number> => {
+ const server = new Server({
+ port: 0,
+ host: '127.0.0.1',
+ prepareRequestFunction: async ({ hostname }) => {
+ if (!ALLOW_LOCAL_WEBHOOKS && (await isInternalHost(hostname))) {
+ throw new RequestError(
+ 'Blocked: target resolves to a private/internal address',
+ 403,
+ );
+ }
+ return { upstreamProxyUrl: buildUpstreamProxyUrl() };
+ },
+ });
+ await server.listen();
+ return server.port;
+};
+
+let ssrfProxyPort: number;
+
type ContextSecurityState = {
blockedNavigationRequestUrl: string | null;
};
@@ -168,7 +172,7 @@ const AD_SERVING_DOMAINS = [
'ads-twitter.com',
'facebook.net',
'fbcdn.net',
- 'amazon-adsystem.com'
+ 'amazon-adsystem.com',
];
interface UrlModel {
@@ -192,12 +196,18 @@ const initializeBrowser = async () => {
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
- '--disable-gpu'
- ]
+ '--disable-gpu',
+ ],
});
};
-const createContext = async (skipTlsVerification: boolean = false, userAgentOverride?: string): Promise<{ context: BrowserContext; securityState: ContextSecurityState }> => {
+const createContext = async (
+ skipTlsVerification: boolean = false,
+ userAgentOverride?: string,
+): Promise<{
+ context: BrowserContext;
+ securityState: ContextSecurityState;
+}> => {
const userAgent = userAgentOverride || new UserAgent().toString();
const viewport = { width: 1280, height: 800 };
const securityState: ContextSecurityState = {
@@ -211,52 +221,49 @@ const createContext = async (skipTlsVerification: boolean = false, userAgentOver
serviceWorkers: 'block',
};
- if (PROXY_SERVER && PROXY_USERNAME && PROXY_PASSWORD) {
- contextOptions.proxy = {
- server: PROXY_SERVER,
- username: PROXY_USERNAME,
- password: PROXY_PASSWORD,
- };
- } else if (PROXY_SERVER) {
- contextOptions.proxy = {
- server: PROXY_SERVER,
- };
- }
+ contextOptions.proxy = {
+ server: `http://127.0.0.1:${ssrfProxyPort}`,
+ };
const newContext = await browser.newContext(contextOptions);
if (BLOCK_MEDIA) {
- await newContext.route('**/*.{png,jpg,jpeg,gif,svg,mp3,mp4,avi,flac,ogg,wav,webm}', async (route: Route, request: PlaywrightRequest) => {
- await route.abort();
- });
+ await newContext.route(
+ '**/*.{png,jpg,jpeg,gif,svg,mp3,mp4,avi,flac,ogg,wav,webm}',
+ async (route: Route, request: PlaywrightRequest) => {
+ await route.abort();
+ },
+ );
}
// Intercept all requests to avoid loading ads
- await newContext.route('**/*', async (route: Route, request: PlaywrightRequest) => {
- const requestUrlString = request.url();
- try {
- await assertSafeTargetUrl(requestUrlString);
- } catch (error) {
- if (error instanceof InsecureConnectionError) {
- if (request.isNavigationRequest()) {
- securityState.blockedNavigationRequestUrl = requestUrlString;
+ await newContext.route(
+ '**/*',
+ async (route: Route, request: PlaywrightRequest) => {
+ const requestUrlString = request.url();
+ try {
+ await assertSafeTargetUrl(requestUrlString);
+ } catch (error) {
+ if (error instanceof InsecureConnectionError) {
+ if (request.isNavigationRequest()) {
+ securityState.blockedNavigationRequestUrl = requestUrlString;
+ }
+ console.warn(`Blocked request: ${requestUrlString}`);
+ return route.abort('blockedbyclient');
}
- console.warn(`Blocked request: ${requestUrlString}`);
- return route.abort('blockedbyclient');
+ throw error;
}
- throw error;
- }
- const requestUrl = new URL(requestUrlString);
- const hostname = normalizeHostname(requestUrl.hostname);
+ const hostname = new URL(requestUrlString).hostname.toLowerCase();
+
+ if (AD_SERVING_DOMAINS.some((domain) => hostname.includes(domain))) {
+ console.log(hostname);
+ return route.abort();
+ }
+ return route.continue();
+ },
+ );
- if (AD_SERVING_DOMAINS.some(domain => hostname.includes(domain))) {
- console.log(hostname);
- return route.abort();
- }
- return route.continue();
- });
-
return { context: newContext, securityState };
};
@@ -284,7 +291,9 @@ const scrapePage = async (
checkSelector: string | undefined,
securityState: ContextSecurityState,
) => {
- console.log(`Navigating to ${url} with waitUntil: ${waitUntil} and timeout: ${timeout}ms`);
+ console.log(
+ `Navigating to ${url} with waitUntil: ${waitUntil} and timeout: ${timeout}ms`,
+ );
let response;
try {
response = await page.goto(url, { waitUntil, timeout });
@@ -310,13 +319,20 @@ const scrapePage = async (
}
}
- let headers = null, content = await page.content();
+ let headers = null,
+ content = await page.content();
let ct: string | undefined = undefined;
if (response) {
headers = await response.allHeaders();
- ct = Object.entries(headers).find(([key]) => key.toLowerCase() === "content-type")?.[1];
- if (ct && (ct.toLowerCase().includes("application/json") || ct.toLowerCase().includes("text/plain"))) {
- content = (await response.body()).toString("utf8"); // TODO: determine real encoding
+ ct = Object.entries(headers).find(
+ ([key]) => key.toLowerCase() === 'content-type',
+ )?.[1];
+ if (
+ ct &&
+ (ct.toLowerCase().includes('application/json') ||
+ ct.toLowerCase().includes('text/plain'))
+ ) {
+ content = (await response.body()).toString('utf8'); // TODO: determine real encoding
}
}
@@ -333,28 +349,35 @@ app.get('/health', async (req: Request, res: Response) => {
if (!browser) {
await initializeBrowser();
}
-
+
const { context: testContext } = await createContext();
const testPage = await testContext.newPage();
await testPage.close();
await testContext.close();
-
- res.status(200).json({
+
+ res.status(200).json({
status: 'healthy',
maxConcurrentPages: MAX_CONCURRENT_PAGES,
- activePages: MAX_CONCURRENT_PAGES - pageSemaphore.getAvailablePermits()
+ activePages: MAX_CONCURRENT_PAGES - pageSemaphore.getAvailablePermits(),
});
} catch (error) {
console.error('Health check failed:', error);
- res.status(503).json({
- status: 'unhealthy',
- error: error instanceof Error ? error.message : 'Unknown error occurred'
+ res.status(503).json({
+ status: 'unhealthy',
+ error: error instanceof Error ? error.message : 'Unknown error occurred',
});
}
});
app.post('/scrape', async (req: Request, res: Response) => {
- const { url, wait_after_load = 0, timeout = 15000, headers, check_selector, skip_tls_verification = false }: UrlModel = req.body;
+ const {
+ url,
+ wait_after_load = 0,
+ timeout = 15000,
+ headers,
+ check_selector,
+ skip_tls_verification = false,
+ }: UrlModel = req.body;
console.log(`================= Scrape Request =================`);
console.log(`URL: ${url}`);
@@ -387,7 +410,9 @@ app.post('/scrape', async (req: Request, res: Response) => {
}
if (!PROXY_SERVER) {
- console.warn('⚠️ WARNING: No proxy server provided. Your IP address may be blocked.');
+ console.warn(
+ '⚠️ WARNING: No proxy server provided. Your IP address may be blocked.',
+ );
}
if (!browser) {
@@ -395,7 +420,7 @@ app.post('/scrape', async (req: Request, res: Response) => {
}
await pageSemaphore.acquire();
-
+
let requestContext: BrowserContext | null = null;
let securityState: ContextSecurityState | null = null;
let page: Page | null = null;
@@ -405,10 +430,15 @@ app.post('/scrape', async (req: Request, res: Response) => {
// be applied at the context level. Playwright ignores user-agent in
// setExtraHTTPHeaders when the context already defines one (#2802).
const userAgentOverride = headers
- ? Object.entries(headers).find(([k]) => k.toLowerCase() === 'user-agent')?.[1]
+ ? Object.entries(headers).find(
+ ([k]) => k.toLowerCase() === 'user-agent',
+ )?.[1]
: undefined;
- const contextBundle = await createContext(skip_tls_verification, userAgentOverride);
+ const contextBundle = await createContext(
+ skip_tls_verification,
+ userAgentOverride,
+ );
requestContext = contextBundle.context;
securityState = contextBundle.securityState;
page = await requestContext.newPage();
@@ -421,7 +451,9 @@ app.post('/scrape', async (req: Request, res: Response) => {
// land on the login page. Seed the cookie jar instead so Chromium re-sends
// it on every request, including redirects — matching what a raw HTTP
// client does.
- const cookieHeader = Object.entries(headers).find(([k]) => k.toLowerCase() === 'cookie')?.[1];
+ const cookieHeader = Object.entries(headers).find(
+ ([k]) => k.toLowerCase() === 'cookie',
+ )?.[1];
if (cookieHeader) {
// Scope cookies to the registrable domain (e.g. ".example.com"), not
// host-only. Authenticated pages often 302 across sibling subdomains
@@ -438,10 +470,16 @@ app.post('/scrape', async (req: Request, res: Response) => {
} catch {
cookieDomain = undefined;
}
- type SeedCookie = { name: string; value: string; url?: string; domain?: string; path?: string };
+ type SeedCookie = {
+ name: string;
+ value: string;
+ url?: string;
+ domain?: string;
+ path?: string;
+ };
const cookies = cookieHeader
.split(';')
- .map(pair => pair.trim())
+ .map((pair) => pair.trim())
.filter(Boolean)
.map((pair): SeedCookie | null => {
const eq = pair.indexOf('=');
@@ -468,7 +506,7 @@ app.post('/scrape', async (req: Request, res: Response) => {
Object.entries(headers).filter(([k]) => {
const lower = k.toLowerCase();
return lower !== 'user-agent' && lower !== 'cookie';
- })
+ }),
);
if (Object.keys(filteredHeaders).length > 0) {
await page.setExtraHTTPHeaders(filteredHeaders);
@@ -484,21 +522,23 @@ app.post('/scrape', async (req: Request, res: Response) => {
check_selector,
securityState,
);
- const pageError = result.status !== 200 ? getError(result.status) : undefined;
+ const pageError =
+ result.status !== 200 ? getError(result.status) : undefined;
if (!pageError) {
console.log(`✅ Scrape successful!`);
} else {
- console.log(`🚨 Scrape failed with status code: ${result.status} ${pageError}`);
+ console.log(
+ `🚨 Scrape failed with status code: ${result.status} ${pageError}`,
+ );
}
res.json({
content: result.content,
pageStatusCode: result.status,
contentType: result.contentType,
- ...(pageError && { pageError })
+ ...(pageError && { pageError }),
});
-
} catch (error) {
if (error instanceof InsecureConnectionError) {
return res.json({
@@ -508,7 +548,9 @@ app.post('/scrape', async (req: Request, res: Response) => {
});
}
console.error('Scrape error:', error);
- res.status(500).json({ error: 'An error occurred while fetching the page.' });
+ res
+ .status(500)
+ .json({ error: 'An error occurred while fetching the page.' });
} finally {
if (page) await page.close();
if (requestContext) await requestContext.close();
@@ -516,10 +558,16 @@ app.post('/scrape', async (req: Request, res: Response) => {
}
});
-app.listen(port, () => {
- initializeBrowser().then(() => {
+const start = async () => {
+ ssrfProxyPort = await startSSRFProxy();
+ await initializeBrowser();
+ app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
+};
+start().catch((error) => {
+ console.error('Failed to start server:', error);
+ process.exit(1);
});
if (require.main === module) {
diff --git a/apps/playwright-service-ts/package.json b/apps/playwright-service-ts/package.json
index 1a7e5f88e..43e1418a9 100644
--- a/apps/playwright-service-ts/package.json
+++ b/apps/playwright-service-ts/package.json
@@ -16,6 +16,7 @@
"express": "^5.2.1",
"ipaddr.js": "^2.3.0",
"playwright": "^1.58.1",
+ "proxy-chain": "^2.7.1",
"user-agents": "^1.1.669"
},
"devDependencies": {
diff --git a/apps/playwright-service-ts/pnpm-lock.yaml b/apps/playwright-service-ts/pnpm-lock.yaml
index 72adf3040..4d5f3ef21 100644
--- a/apps/playwright-service-ts/pnpm-lock.yaml
+++ b/apps/playwright-service-ts/pnpm-lock.yaml
@@ -25,6 +25,9 @@ importers:
playwright:
specifier: ^1.58.1
version: 1.58.1
+ proxy-chain:
+ specifier: ^2.7.1
+ version: 2.7.1
user-agents:
specifier: ^1.1.669
version: 1.1.669
@@ -243,6 +246,10 @@ packages:
resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}
+ engines: {node: '>= 14'}
+
resolution: {integrity: sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==}
engines: {node: '>=18'}
@@ -390,6 +397,10 @@ packages:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
+ resolution: {integrity: sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==}
+ engines: {node: '>= 12'}
+
resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}
engines: {node: '>= 0.10'}
@@ -463,6 +474,10 @@ packages:
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
engines: {node: '>= 0.10'}
+ resolution: {integrity: sha512-LtXu0miohJYrHWJxv8wA6EoGreRcX1hxKb7qlE1pMFH+BXE7bqMvpyhzR/JvR6M5SzYKzyHFpvfmYJrZeMtwAg==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==}
engines: {node: '>=0.6'}
@@ -512,6 +527,18 @@ packages:
resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==}
+ engines: {node: '>= 6.0.0', npm: '>= 3.0.0'}
+
+ resolution: {integrity: sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==}
+ engines: {node: '>= 14'}
+
+ resolution: {integrity: sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==}
+ engines: {node: '>= 10.0.0', npm: '>= 3.0.0'}
+
resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==}
engines: {node: '>= 0.8'}
@@ -524,6 +551,9 @@ packages:
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
+
resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==}
engines: {node: '>=18.0.0'}
@@ -686,6 +716,8 @@ snapshots:
mime-types: 3.0.2
negotiator: 1.0.0
+
dependencies:
bytes: 3.1.2
@@ -882,6 +914,8 @@ snapshots:
+
@@ -933,6 +967,14 @@ snapshots:
forwarded: 0.2.0
ipaddr.js: 1.9.1
+ dependencies:
+ socks: 2.8.9
+ socks-proxy-agent: 8.0.5
+ tslib: 2.8.1
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
side-channel: 1.1.0
@@ -1015,12 +1057,29 @@ snapshots:
side-channel-map: 1.0.1
side-channel-weakmap: 1.0.2
+
+ dependencies:
+ agent-base: 7.1.4
+ debug: 4.4.3
+ socks: 2.8.9
+ transitivePeerDependencies:
+ - supports-color
+
+ dependencies:
+ ip-address: 10.2.0
+ smart-buffer: 4.2.0
+
+
dependencies:
esbuild: 0.28.1