forked from jo-inc/camofox-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6171 lines (5696 loc) · 213 KB
/
Copy pathserver.js
File metadata and controls
6171 lines (5696 loc) · 213 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Camoufox, launchOptions } from 'camoufox-js';
import { VirtualDisplay } from 'camoufox-js/dist/virtdisplay.js';
import { firefox } from 'playwright-core';
import express from 'express';
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import { expandMacro } from './lib/macros.js';
import { loadConfig } from './lib/config.js';
import { normalizePlaywrightProxy, createProxyPool, buildProxyUrl } from './lib/proxy.js';
import { createFlyHelpers } from './lib/fly.js';
import { createPluginEvents, loadPlugins } from './lib/plugins.js';
import { requireAuth, accessKeyMiddleware, timingSafeCompare as _timingSafeCompare, isLoopbackAddress as _isLoopbackAddress } from './lib/auth.js';
import { windowSnapshot } from './lib/snapshot.js';
import {
MAX_DOWNLOAD_INLINE_BYTES,
clearTabDownloads,
clearSessionDownloads,
attachDownloadListener,
getDownloadsList,
} from './lib/downloads.js';
import { extractPageImages } from './lib/images.js';
import { extractDeterministic, validateSchema as validateExtractSchema } from './lib/extract.js';
import {
ensureTracesDir, resolveTracePath, tracePathFor, makeTraceFilename,
listUserTraces, statTrace, deleteTrace, sweepOldTraces,
} from './lib/tracing.js';
import {
initMetrics, getRegister, isMetricsEnabled, createMetric,
startMemoryReporter, stopMemoryReporter,
} from './lib/metrics.js';
import { actionFromReq, classifyError, validateUrl } from './lib/request-utils.js';
import { cleanupOrphanedTempFiles, cleanupStaleFirefoxProfiles } from './lib/tmp-cleanup.js';
import { coalesceInflight } from './lib/inflight.js';
import { createReporter, createTabHealthTracker, collectResourceSnapshot, classifyProxyError, browserProcessTreeRssMb } from './lib/reporter.js';
import { mountDocs } from './lib/openapi.js';
import { initSentry, captureException as sentryCaptureException, setupExpressErrorHandler as setupSentryErrorHandler, flush as sentryFlush } from './lib/sentry.js';
import { prepareExternalCamoufoxExecutable } from './lib/camoufox-executable.js';
const CONFIG = loadConfig();
// --- Crash reporter (opt-in, anonymized GitHub issues) ---
import { readFileSync } from 'fs';
const _pkgVersion = (() => { try { return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version; } catch { return 'unknown'; } })();
// --- Sentry error tracking ---
initSentry({ ...CONFIG, version: _pkgVersion });
const reporter = createReporter({ ...CONFIG, version: _pkgVersion });
function _countTabs() {
let total = 0;
for (const session of sessions.values()) {
for (const group of session.tabGroups.values()) total += group.size;
}
return total;
}
function _browserPid() {
try { return browser?.process?.()?.pid ?? null; } catch { return null; }
}
function _resourceOpts() {
return { sessionCount: sessions.size, tabCount: _countTabs(), browserPid: _browserPid() };
}
reporter.startWatchdog(30_000, () => {
const summary = [];
for (const [sid, session] of sessions) {
const tabUrls = [];
for (const group of session.tabGroups.values()) {
for (const tab of group.values()) {
try {
const url = tab.page?.url?.() || 'unknown';
tabUrls.push(url);
} catch { tabUrls.push('error'); }
}
}
if (tabUrls.length > 0) summary.push({ session: sid, tabs: tabUrls.length, urls: tabUrls });
}
return { resourceOpts: _resourceOpts(), sessions: summary.length, summary };
});
// --- Plugin event bus ---
const pluginEvents = createPluginEvents();
// --- Shared auth middleware ---
const authMiddleware = () => requireAuth(CONFIG);
const {
requestsTotal, requestDuration, pageLoadDuration, snapshotBytes,
activeTabsGauge, tabLockQueueDepth,
tabLockTimeoutsTotal,
failuresTotal, browserRestartsTotal, tabsDestroyedTotal,
sessionsExpiredTotal, tabsReapedTotal, tabsRecycledTotal,
} = await initMetrics({ enabled: CONFIG.prometheusEnabled });
// --- Structured logging ---
function log(level, msg, fields = {}) {
const entry = {
ts: new Date().toISOString(),
level,
msg,
...fields,
};
const line = JSON.stringify(entry);
if (level === 'error') {
process.stderr.write(line + '\n');
} else {
process.stdout.write(line + '\n');
}
}
const app = express();
app.use(express.json({ limit: '100kb' }));
// Request logging + metrics middleware
app.use((req, res, next) => {
const reqId = crypto.randomUUID().slice(0, 8);
req.reqId = reqId;
req.startTime = Date.now();
const userId = req.body?.userId || req.query?.userId || '-';
if (req.path !== '/health') {
log('info', 'req', { reqId, method: req.method, path: req.path, userId });
}
const action = actionFromReq(req);
reporter.trackRoute(`${req.method} ${req.route?.path || '[unmatched]'}`);
const done = requestDuration.startTimer({ action });
const origEnd = res.end.bind(res);
res.end = function (...args) {
const ms = Date.now() - req.startTime;
const isErrorStatus = res.statusCode >= 400;
requestsTotal.labels(action, isErrorStatus ? 'error' : 'success').inc();
done();
if (req.path !== '/health') {
log('info', 'res', { reqId, status: res.statusCode, ms });
}
return origEnd(...args);
};
next();
});
// --- Horizontal scaling (Fly.io multi-machine) ---
const fly = createFlyHelpers(CONFIG);
const FLY_MACHINE_ID = fly.machineId;
// Route tab requests to the owning machine via fly-replay header.
app.use('/tabs/:tabId', fly.replayMiddleware(log));
// Access-key middleware: gates every route when CAMOFOX_ACCESS_KEY is set.
// Exempts /health (Docker healthcheck) and routes that have their own
// dedicated keys (cookie import -> CAMOFOX_API_KEY, /stop -> CAMOFOX_ADMIN_KEY)
// so each key gates a distinct surface. When unset, behavior is unchanged.
app.use(accessKeyMiddleware(CONFIG));
// Interactive roles to include - exclude combobox to avoid opening complex widgets
// (date pickers, dropdowns) that can interfere with navigation
const INTERACTIVE_ROLES = [
'button', 'link', 'textbox', 'checkbox', 'radio',
'menuitem', 'tab', 'searchbox', 'slider', 'spinbutton', 'switch'
// 'combobox' excluded - can trigger date pickers and complex dropdowns
];
// Patterns to skip (date pickers, calendar widgets -- NOT expiration/expiry fields)
const SKIP_PATTERNS = [
/datepicker/i, /date.?picker/i, /calendar/i, /^date$/i
];
// Iframe support: URL patterns to SKIP (tracking, analytics, pixels)
const IFRAME_SKIP_PATTERNS = [
/web-pixel/i, /analytics/i, /tracking/i, /gtm/i, /facebook/i,
/doubleclick/i, /google.*tag/i, /hotjar/i, /segment/i, /sentry/i,
/recaptcha/i, /gstatic/i, /app-bridge/i, /extensions\.shopifycdn/i,
];
const MAX_IFRAMES_TO_PROCESS = 8;
const IFRAME_SNAPSHOT_TIMEOUT_MS = 3000;
// timingSafeCompare and isLoopbackAddress imported from lib/auth.js
const timingSafeCompare = _timingSafeCompare;
const isLoopbackAddress = _isLoopbackAddress;
// Custom error for stale/unknown element refs -- returned as 422 instead of 500
class StaleRefsError extends Error {
constructor(ref, maxRef, totalRefs) {
super(`Unknown ref: ${ref} (valid refs: e1-${maxRef}, ${totalRefs} total). Refs reset after navigation - call snapshot first.`);
this.name = 'StaleRefsError';
this.code = 'stale_refs';
this.ref = ref;
}
}
function safeError(err) {
if (CONFIG.nodeEnv === 'production') {
log('error', 'internal error', { error: err.message, stack: err.stack });
return 'Internal server error';
}
return err.message;
}
// Send error response with appropriate status code (422 for stale refs, 500 otherwise)
function sendError(res, err, extraFields = {}) {
const status = err instanceof StaleRefsError ? 422 : (err.statusCode || 500);
const body = { error: safeError(err), ...extraFields };
if (err instanceof StaleRefsError) {
body.code = 'stale_refs';
body.ref = err.ref;
}
// Report unexpected 500s to Sentry (skip intentional admission-control 503s)
if (status >= 500 && !err.statusCode) {
sentryCaptureException(err, {
path: res.req?.originalUrl,
method: res.req?.method,
userId: res.req?.query?.userId || res.req?.body?.userId,
reqId: res.req?.reqId,
});
}
res.status(status).json(body);
}
// validateUrl -- now imported from lib/request-utils.js (allows about:blank)
// isLoopbackAddress -- now imported from lib/auth.js (see top of file)
// Import cookies into a user's browser context (Playwright cookies format)
// POST /sessions/:userId/cookies { cookies: Cookie[] }
//
// SECURITY:
// Cookie injection moves this from "anonymous browsing" to "authenticated browsing".
/**
* @openapi
* /sessions/{userId}/cookies:
* post:
* tags: [Sessions]
* summary: Import cookies into a user session
* description: Import cookies for authenticated browsing. Requires BearerAuth in production.
* security:
* - BearerAuth: []
* parameters:
* - name: userId
* in: path
* required: true
* schema:
* type: string
* description: Session owner identifier.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [cookies]
* properties:
* cookies:
* type: array
* maxItems: 500
* items:
* type: object
* required: [name, value, domain]
* properties:
* name:
* type: string
* value:
* type: string
* domain:
* type: string
* path:
* type: string
* expires:
* type: number
* httpOnly:
* type: boolean
* secure:
* type: boolean
* sameSite:
* type: string
* enum: [Strict, Lax, None]
* responses:
* 200:
* description: Cookies imported.
* content:
* application/json:
* schema:
* type: object
* properties:
* ok:
* type: boolean
* userId:
* type: string
* count:
* type: integer
* 400:
* description: Invalid cookie data.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 403:
* description: Forbidden.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.post('/sessions/:userId/cookies', authMiddleware(), express.json({ limit: '512kb' }), async (req, res) => {
try {
const userId = req.params.userId;
if (!req.body || !('cookies' in req.body)) {
return res.status(400).json({ error: 'Missing "cookies" field in request body' });
}
const cookies = req.body.cookies;
if (!Array.isArray(cookies)) {
return res.status(400).json({ error: 'cookies must be an array' });
}
if (cookies.length > 500) {
return res.status(400).json({ error: 'Too many cookies. Maximum 500 per request.' });
}
const invalid = [];
for (let i = 0; i < cookies.length; i++) {
const c = cookies[i];
const missing = [];
if (!c || typeof c !== 'object') {
invalid.push({ index: i, error: 'cookie must be an object' });
continue;
}
if (typeof c.name !== 'string' || !c.name) missing.push('name');
if (typeof c.value !== 'string') missing.push('value');
if (typeof c.domain !== 'string' || !c.domain) missing.push('domain');
if (missing.length) invalid.push({ index: i, missing });
}
if (invalid.length) {
return res.status(400).json({
error: 'Invalid cookie objects: each cookie must include name, value, and domain',
invalid,
});
}
const allowedFields = ['name', 'value', 'domain', 'path', 'expires', 'httpOnly', 'secure', 'sameSite'];
const sanitized = cookies.map(c => {
const clean = {};
for (const k of allowedFields) {
if (c[k] !== undefined) clean[k] = c[k];
}
return clean;
});
const session = await getSession(userId);
await session.context.addCookies(sanitized);
const result = { ok: true, userId: String(userId), count: sanitized.length };
log('info', 'cookies imported', { reqId: req.reqId, userId: String(userId), count: sanitized.length });
pluginEvents.emit('session:cookies:import', { userId: String(userId), count: sanitized.length });
res.json(result);
} catch (err) {
failuresTotal.labels(classifyError(err), 'set_cookies').inc();
log('error', 'cookie import failed', { reqId: req.reqId, error: err.message });
res.status(500).json({ error: safeError(err) });
}
});
let browser = null;
let _lastBrowserPid = null; // Track PID independently for force-kill after close
let _browserClosePromise = null; // Shared promise for concurrent close serialization
let _lastBrowserRestartAt = 0; // Timestamp of last browser relaunch (for stale tab detection)
// userId -> { context, tabGroups: Map<sessionKey, Map<tabId, TabState>>, lastAccess }
// TabState = { page, refs: Map<refId, {role, name, nth}>, visitedUrls: Set, downloads: Array, toolCalls: number }
// Note: sessionKey was previously called listItemId - both are accepted for backward compatibility
const sessions = new Map();
const SESSION_TIMEOUT_MS = CONFIG.sessionTimeoutMs;
const MAX_SNAPSHOT_NODES = 500;
const TAB_INACTIVITY_MS = CONFIG.tabInactivityMs;
const MAX_SESSIONS = CONFIG.maxSessions;
const MAX_TABS_PER_SESSION = CONFIG.maxTabsPerSession;
const MAX_TABS_GLOBAL = CONFIG.maxTabsGlobal;
const HANDLER_TIMEOUT_MS = CONFIG.handlerTimeoutMs;
const MAX_CONCURRENT_PER_USER = CONFIG.maxConcurrentPerUser;
const PAGE_CLOSE_TIMEOUT_MS = 5000;
const NAVIGATE_TIMEOUT_MS = CONFIG.navigateTimeoutMs;
const BUILDREFS_TIMEOUT_MS = CONFIG.buildrefsTimeoutMs;
const NATIVE_MEM_RESTART_THRESHOLD_MB = CONFIG.nativeMemRestartThresholdMb;
let _nativeMemBaseline = null; // RSS - heapUsed at first idle measurement
const FAILURE_THRESHOLD = 3;
const MAX_CONSECUTIVE_TIMEOUTS = 3;
const TAB_LOCK_TIMEOUT_MS = 35000; // Must be > HANDLER_TIMEOUT_MS so active op times out first
// Proper mutex for tab serialization. The old Promise-chain lock on timeout proceeded
// WITHOUT the lock, allowing concurrent Playwright operations that corrupt CDP state.
class TabLock {
constructor() {
this.queue = [];
this.active = false;
}
acquire(timeoutMs) {
return new Promise((resolve, reject) => {
const entry = { resolve, reject, timer: null };
entry.timer = setTimeout(() => {
const idx = this.queue.indexOf(entry);
if (idx !== -1) this.queue.splice(idx, 1);
tabLockTimeoutsTotal.inc();
refreshTabLockQueueDepth();
reject(new Error('Tab lock queue timeout'));
}, timeoutMs);
this.queue.push(entry);
refreshTabLockQueueDepth();
this._tryNext();
});
}
release() {
this.active = false;
this._tryNext();
refreshTabLockQueueDepth();
}
_tryNext() {
if (this.active || this.queue.length === 0) return;
this.active = true;
const entry = this.queue.shift();
clearTimeout(entry.timer);
refreshTabLockQueueDepth();
entry.resolve();
}
drain() {
this.active = true;
for (const entry of this.queue) {
clearTimeout(entry.timer);
entry.reject(new Error('Tab destroyed'));
}
this.queue = [];
refreshTabLockQueueDepth();
}
}
// Per-tab locks to serialize operations on the same tab
const tabLocks = new Map(); // tabId -> TabLock
function getTabLock(tabId) {
if (!tabLocks.has(tabId)) tabLocks.set(tabId, new TabLock());
return tabLocks.get(tabId);
}
// Timeout is INSIDE the lock so each operation gets its full budget
// regardless of how long it waited in the queue.
async function withTabLock(tabId, operation, timeoutMs = HANDLER_TIMEOUT_MS) {
const lock = getTabLock(tabId);
await lock.acquire(TAB_LOCK_TIMEOUT_MS);
try {
return await withTimeout(operation(), timeoutMs, 'action');
} finally {
lock.release();
}
}
function withTimeout(promise, ms, label) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
)
]);
}
function requestTimeoutMs(baseMs = HANDLER_TIMEOUT_MS) {
return proxyPool?.canRotateSessions ? Math.max(baseMs, 180000) : baseMs;
}
const userConcurrency = new Map();
async function withUserLimit(userId, operation) {
const key = normalizeUserId(userId);
let state = userConcurrency.get(key);
if (!state) {
state = { active: 0, queue: [] };
userConcurrency.set(key, state);
}
if (state.active >= MAX_CONCURRENT_PER_USER) {
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('User concurrency limit reached, try again')), 30000);
state.queue.push(() => { clearTimeout(timer); resolve(); });
});
}
state.active++;
healthState.activeOps++;
try {
const result = await operation();
healthState.lastSuccessfulNav = Date.now();
return result;
} finally {
healthState.activeOps--;
state.active--;
if (state.queue.length > 0) {
const next = state.queue.shift();
next();
}
if (state.active === 0 && state.queue.length === 0) {
userConcurrency.delete(key);
}
}
}
async function safePageClose(page) {
if (!page || page.isClosed()) return;
try {
await Promise.race([
page.close({ runBeforeUnload: false }),
new Promise((_, reject) => setTimeout(() => reject(new Error('page close timed out')), PAGE_CLOSE_TIMEOUT_MS)),
]);
} catch (e) {
log('warn', 'page close timed out or failed, force-closing', { error: e.message });
try { await page.close({ runBeforeUnload: false }); } catch (_) {}
page.removeAllListeners();
}
}
// Detect host OS for fingerprint generation
function getHostOS() {
const platform = os.platform();
if (platform === 'darwin') return 'macos';
if (platform === 'win32') return 'windows';
return 'linux';
}
// Proxy strategy for outbound browsing.
const proxyPool = createProxyPool(CONFIG.proxy);
if (proxyPool) {
log('info', 'proxy pool created', {
mode: proxyPool.mode,
host: proxyPool.canRotateSessions ? CONFIG.proxy.backconnectHost : CONFIG.proxy.host,
ports: proxyPool.canRotateSessions ? [CONFIG.proxy.backconnectPort] : CONFIG.proxy.ports,
poolSize: proxyPool.size,
country: CONFIG.proxy.country || null,
state: CONFIG.proxy.state || null,
city: CONFIG.proxy.city || null,
});
} else {
log('info', 'no proxy configured');
}
const BROWSER_IDLE_TIMEOUT_MS = CONFIG.browserIdleTimeoutMs;
let browserIdleTimer = null;
let browserLaunchPromise = null;
let browserWarmRetryTimer = null;
if (BROWSER_IDLE_TIMEOUT_MS <= 0) {
log('info', 'browser idle shutdown disabled (BROWSER_IDLE_TIMEOUT_MS=0)');
}
function scheduleBrowserIdleShutdown() {
if (BROWSER_IDLE_TIMEOUT_MS <= 0) return;
if (browserIdleTimer || sessions.size > 0 || !browser) return;
browserIdleTimer = setTimeout(async () => {
browserIdleTimer = null;
if (sessions.size === 0 && browser) {
log('info', 'browser idle shutdown (no sessions)');
await closeBrowserFully('idle_shutdown');
}
}, BROWSER_IDLE_TIMEOUT_MS);
}
function clearBrowserIdleTimer() {
if (browserIdleTimer) {
clearTimeout(browserIdleTimer);
browserIdleTimer = null;
}
}
// Detects errors that retrying cannot recover from (e.g., Camoufox binary
// missing because postinstall was skipped). The user must run
// `npx camoufox-js fetch` and restart; looping on this wastes resources
// and buries the actionable error under noise.
//
// Sentinel: matches the human-readable message thrown by camoufox-js's
// FileNotFoundError in dist/pkgman.js (Version.fromPath). FileNotFoundError
// is not exported from the public API, so substring matching is the only
// available hook. If the upstream message changes, this regex needs an
// update; the dependency range in package.json controls exposure.
function isFatalInstallError(err) {
return /Version information not found/i.test(err?.message || '');
}
function camoufoxInstallRemediation() {
if (CONFIG.camoufoxExecutablePath) {
return 'verify CAMOUFOX_EXECUTABLE points to a Camoufox bundle with properties.json, version.json, and fontconfig/';
}
return 'run `npx camoufox-js fetch` then restart the server';
}
function scheduleBrowserWarmRetry(delayMs = 5000) {
if (browserWarmRetryTimer || browser || browserLaunchPromise) return;
browserWarmRetryTimer = setTimeout(async () => {
browserWarmRetryTimer = null;
try {
const start = Date.now();
await ensureBrowser();
log('info', 'background browser warm retry succeeded', { ms: Date.now() - start });
} catch (err) {
if (isFatalInstallError(err)) {
log('error', 'browser unavailable: Camoufox binaries are not installed; aborting retry loop', {
error: err.message,
remediation: camoufoxInstallRemediation(),
});
return;
}
log('warn', 'background browser warm retry failed', { error: err.message, nextDelayMs: delayMs });
scheduleBrowserWarmRetry(Math.min(delayMs * 2, 30000));
}
}, delayMs);
}
// --- Browser health tracking ---
const healthState = {
consecutiveNavFailures: 0,
lastSuccessfulNav: Date.now(),
isRecovering: false,
activeOps: 0,
};
function recordNavSuccess() {
healthState.consecutiveNavFailures = 0;
healthState.lastSuccessfulNav = Date.now();
}
function recordNavFailure() {
healthState.consecutiveNavFailures++;
return healthState.consecutiveNavFailures >= FAILURE_THRESHOLD;
}
async function restartBrowser(reason) {
if (healthState.isRecovering) return;
healthState.isRecovering = true;
browserRestartsTotal.labels(reason).inc();
log('error', 'restarting browser', { reason, failures: healthState.consecutiveNavFailures });
pluginEvents.emit('browser:restart', { reason });
try {
await closeAllSessions(`browser_restart:${reason}`, { clearDownloads: true, clearLocks: true });
await closeBrowserFully(`browser_restart:${reason}`);
pluginEvents.emit('browser:closed', { reason });
browserLaunchPromise = null;
await ensureBrowser();
healthState.consecutiveNavFailures = 0;
healthState.lastSuccessfulNav = Date.now();
log('info', 'browser restarted successfully');
} catch (err) {
log('error', 'browser restart failed', { error: err.message });
} finally {
healthState.isRecovering = false;
}
}
function getTotalTabCount() {
let total = 0;
for (const session of sessions.values()) {
try {
// Use real Playwright page count so leaked pages exert backpressure
// on MAX_TABS_GLOBAL, surfacing leaks before Firefox starves.
total += session.context.pages().length;
} catch (_) {
// Context is dead — fall back to bookkeeping count for this session.
for (const group of session.tabGroups.values()) total += group.size;
}
}
return total;
}
// Virtual display for WebGL support and anti-detection.
// Xvfb gives Firefox a real X display with GLX, enabling software-rendered WebGL
// via Mesa llvmpipe. Without this, WebGL returns "no context" -- a massive bot signal.
let virtualDisplay = null;
let browserLaunchProxy = null;
let externalCamoufoxLaunch = null;
function getExternalCamoufoxLaunch() {
if (!CONFIG.camoufoxExecutablePath) return null;
if (!externalCamoufoxLaunch) {
externalCamoufoxLaunch = prepareExternalCamoufoxExecutable(CONFIG.camoufoxExecutablePath, {
cacheDir: CONFIG.camoufoxCacheDir,
});
log('info', 'using external camoufox executable', {
executablePath: externalCamoufoxLaunch.executablePath,
resourceDir: externalCamoufoxLaunch.resourceDir,
});
}
return externalCamoufoxLaunch;
}
async function probeGoogleSearch(candidateBrowser) {
let context = null;
try {
context = await candidateBrowser.newContext({
viewport: { width: 1280, height: 720 },
permissions: ['geolocation'],
});
const page = await context.newPage();
await page.goto('https://www.google.com/', { waitUntil: 'domcontentloaded', timeout: 30000 });
await page.waitForTimeout(1200);
await page.goto('https://www.google.com/search?q=weather%20today', { waitUntil: 'domcontentloaded', timeout: 30000 });
await page.waitForTimeout(4000);
const blocked = await isGoogleSearchBlocked(page);
return {
ok: !blocked && isGoogleSerp(page.url()),
url: page.url(),
blocked,
};
} finally {
await context?.close().catch(() => {});
}
}
function attachBrowserCleanup(candidateBrowser, localVirtualDisplay) {
const origClose = candidateBrowser.close.bind(candidateBrowser);
candidateBrowser.close = async (...args) => {
await origClose(...args);
browserLaunchProxy = null;
if (localVirtualDisplay) {
localVirtualDisplay.kill();
if (virtualDisplay === localVirtualDisplay) virtualDisplay = null;
}
};
}
/**
* Close browser with full process-tree cleanup. Handles the race where
* browser.close() fails/hangs but process tree survives.
*
* Serialized: concurrent callers await the same promise (no double-close).
*
* Order: capture PID -> close browser -> force-kill survivors ->
* clean temp profiles -> verify FD/handle drop.
*/
async function closeBrowserFully(reason) {
if (_browserClosePromise) return _browserClosePromise;
_browserClosePromise = _closeBrowserFullyImpl(reason);
try {
return await _browserClosePromise;
} finally {
_browserClosePromise = null;
}
}
async function _closeBrowserFullyImpl(reason) {
const b = browser;
if (!b) return;
clearBrowserIdleTimer();
// Capture PID before nulling browser ref -- we need it for force-kill
const pid = _lastBrowserPid;
const preCloseFds = _countOpenFds();
const preCloseHandles = _countActiveHandles();
// Null the ref so new requests don't use a dying browser
browser = null;
_lastBrowserPid = null;
// Close through Playwright (sends CDP Browser.close, then SIGKILL process group)
let closeTimer;
try {
await Promise.race([
b.close(),
new Promise((_, reject) => { closeTimer = setTimeout(() => reject(new Error('browser.close() timeout')), 10000); }),
]);
} catch (err) {
log('warn', 'browser.close() failed or timed out', { reason, error: err.message, pid });
} finally {
clearTimeout(closeTimer);
}
// Force-kill browser survivors. Playwright's Firefox launcher can return no
// process PID, so fall back to scanning the container for Camoufox/Xvfb.
if (pid) {
await _forceKillProcessTree(pid, reason);
}
await _forceKillBrowserProcesses(reason, pid);
// Clean up stale Firefox temp profiles (enable_cache: true accumulates data)
try {
const cleaned = cleanupStaleFirefoxProfiles();
if (cleaned.removed > 0) {
log('info', 'cleaned stale firefox profiles after browser close', cleaned);
}
} catch { /* best effort */ }
// Reset native memory baseline so next browser measures from fresh
reporter.resetNativeMemBaseline();
_nativeMemBaseline = null;
// Verify cleanup: check FD/handle counts dropped (after force-kill completes)
const postCloseFds = _countOpenFds();
const postCloseHandles = _countActiveHandles();
if (postCloseFds !== null && preCloseFds !== null) {
const fdDelta = postCloseFds - preCloseFds;
// After close we expect fewer FDs. If more leaked, warn.
if (fdDelta > 10) {
log('warn', 'FD leak detected after browser close', {
reason, preCloseFds, postCloseFds, delta: fdDelta,
preCloseHandles, postCloseHandles,
});
}
}
log('info', 'browser closed fully', {
reason, pid, preCloseFds, postCloseFds, preCloseHandles, postCloseHandles,
});
}
/**
* Force-kill a browser process tree by PID. On Linux, kills the process group
* (SIGKILL -pid) then scans /proc for any orphaned children.
*/
async function _forceKillProcessTree(pid, reason) {
if (!pid || pid <= 1) return;
// Kill the specific browser process first (positive PID = single process)
try {
process.kill(pid, 'SIGKILL');
log('info', 'sent SIGKILL to browser process', { pid, reason });
} catch (err) {
if (err.code !== 'ESRCH') {
log('warn', 'failed to kill browser process', { pid, error: err.message });
}
}
// Then try the process group (Playwright launches with detached:true on Linux,
// making the browser a process group leader)
try {
process.kill(-pid, 'SIGKILL');
} catch {
// ESRCH = group doesn't exist (browser wasn't a group leader), which is fine
}
// Wait for kernel to reparent children to PID 1 before scanning
await new Promise(r => setTimeout(r, 200));
// On Linux: scan /proc for orphaned children that escaped the process group
// (reparented to PID 1 by init/systemd, common with Firefox content processes).
// Also checks PPid === Node PID for containerized environments without init.
if (process.platform === 'linux') {
const myPid = process.pid;
// Snapshot the current browser PID to avoid killing a newly launched browser
const currentBrowserPid = _lastBrowserPid;
try {
const procDirs = fs.readdirSync('/proc').filter(d => /^\d+$/.test(d));
const orphans = [];
for (const procPid of procDirs) {
const numPid = parseInt(procPid);
// Never kill ourselves, the old PID (already killed), or the new browser
if (numPid === myPid || numPid === pid || numPid === currentBrowserPid) continue;
try {
const status = fs.readFileSync(`/proc/${procPid}/status`, 'utf8');
const ppidMatch = status.match(/PPid:\s+(\d+)/);
const ppid = ppidMatch ? parseInt(ppidMatch[1]) : -1;
// Orphaned to init (PID 1) or reparented to us (Node is PID 1 in containers)
if (ppid === 1 || ppid === myPid) {
const cmdline = fs.readFileSync(`/proc/${procPid}/cmdline`, 'utf8');
// Firefox-specific: binary name or Gecko child process marker
if (/firefox-esr|firefox|camoufox|libxul\.so|GeckoChildProcess/i.test(cmdline)) {
orphans.push(numPid);
}
}
} catch { /* process vanished or permission denied */ }
}
if (orphans.length > 0) {
log('warn', 'killing orphaned browser child processes', { orphans, reason });
for (const orphanPid of orphans) {
try { process.kill(orphanPid, 'SIGKILL'); } catch { /* already dead */ }
}
}
} catch (err) {
log('warn', 'failed to scan for orphaned browser processes', { error: err.message });
}
}
// Give the OS a moment to reclaim resources
await new Promise(r => setTimeout(r, 300));
}
async function _forceKillBrowserProcesses(reason, excludePid = null) {
if (process.platform !== 'linux') return;
const myPid = process.pid;
const victims = [];
try {
const procDirs = fs.readdirSync('/proc').filter(d => /^\d+$/.test(d));
for (const procPid of procDirs) {
const numPid = parseInt(procPid);
if (numPid === myPid || numPid === excludePid) continue;
try {
const cmdline = fs.readFileSync(`/proc/${procPid}/cmdline`, 'utf8');
if (/camoufox-bin|\/usr\/bin\/Xvfb\b/.test(cmdline)) {
victims.push(numPid);
}
} catch { /* process vanished or permission denied */ }
}
} catch (err) {
log('warn', 'failed to scan for browser survivor processes', { reason, error: err.message });
return;
}
if (victims.length > 0) {
log('warn', 'killing browser survivor processes', { reason, victims });
for (const victimPid of victims) {
try { process.kill(victimPid, 'SIGKILL'); } catch { /* already dead */ }
}
await new Promise(r => setTimeout(r, 300));
}
}
function _countOpenFds() {
try {
if (process.platform === 'linux') return fs.readdirSync('/proc/self/fd').length;
} catch { /* unavailable */ }
return null;
}
function _countActiveHandles() {
try { return process._getActiveHandles().length; } catch { return null; }
}
async function launchBrowserInstance() {
const hostOS = getHostOS();
const maxAttempts = proxyPool?.launchRetries ?? 1;
let lastError = null;
const externalCamoufox = getExternalCamoufoxLaunch();
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const launchProxy = proxyPool
? proxyPool.getLaunchProxy(proxyPool.canRotateSessions ? `browser-${crypto.randomUUID().replace(/-/g, '').slice(0, 12)}` : undefined)
: null;
let localVirtualDisplay = null;
let vdDisplay = undefined;
let candidateBrowser = null;
try {
if (os.platform() === 'linux') {
localVirtualDisplay = pluginCtx.createVirtualDisplay();
vdDisplay = localVirtualDisplay.get();
log('info', 'xvfb virtual display started', { display: vdDisplay, attempt });
}
} catch (err) {
log('warn', 'xvfb not available, falling back to headless', { error: err.message, attempt });
localVirtualDisplay = null;
}
const useVirtualDisplay = !!vdDisplay;
log('info', 'launching camoufox', {
hostOS,
attempt,
maxAttempts,
geoip: !!launchProxy,
proxyMode: proxyPool?.mode || null,
proxyServer: launchProxy?.server || null,
proxySession: launchProxy?.sessionId || null,
proxyPoolSize: proxyPool?.size || 0,
virtualDisplay: useVirtualDisplay,
});
try {
const options = await launchOptions({
executable_path: externalCamoufox?.executablePath,
headless: useVirtualDisplay ? false : true,
os: hostOS,
humanize: true,
enable_cache: true,
proxy: launchProxy,
geoip: !!launchProxy,
virtual_display: vdDisplay,
window: CONFIG.persistentProfiles ? persistentWindowSize() : undefined,
});
options.proxy = normalizePlaywrightProxy(options.proxy);
await pluginEvents.emitAsync('browser:launching', { options });
candidateBrowser = await firefox.launch(options);
if (proxyPool?.canRotateSessions) {
const probe = await probeGoogleSearch(candidateBrowser);
if (!probe.ok) {
log('warn', 'browser launch google probe failed', {
attempt,
maxAttempts,
proxySession: launchProxy?.sessionId || null,
url: probe.url,
});
if (attempt < maxAttempts) {
await candidateBrowser.close().catch(() => {});
if (localVirtualDisplay) localVirtualDisplay.kill();
continue;
}
// Last attempt: accept browser in degraded mode rather than death-spiraling.
// Non-Google sites will still work; Google requests will get blocked responses.
log('error', 'all proxy sessions Google-blocked, accepting browser in degraded mode', {
maxAttempts,
proxySession: launchProxy?.sessionId || null,
});