glidercli 0.4.35 → 0.4.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,43 +1,126 @@
1
1
  'use strict';
2
2
 
3
3
  const { spawn } = require('node:child_process');
4
+ const crypto = require('node:crypto');
4
5
  const fs = require('node:fs');
5
6
  const fsp = require('node:fs/promises');
6
- const os = require('node:os');
7
+ const net = require('node:net');
7
8
  const path = require('node:path');
9
+ const { StringDecoder } = require('node:string_decoder');
8
10
  const { pathToFileURL } = require('node:url');
9
11
 
10
12
  const SUBSCRIBER_API = 'headless-subscriber/v1';
13
+ const MITMPROXY_VERSION = '12.3.1';
14
+ const PROXY_EXACT_SCHEMA = 'glider-mitm-exact/v1';
11
15
 
12
16
  function delay(milliseconds) {
13
17
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
14
18
  }
15
19
 
20
+ async function withTimeout(promise, timeoutMs, description) {
21
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
22
+ throw new Error(`${description} timed out`);
23
+ }
24
+ let timer;
25
+ try {
26
+ return await Promise.race([
27
+ promise,
28
+ new Promise((_, reject) => {
29
+ timer = setTimeout(
30
+ () => reject(new Error(`${description} timed out after ${timeoutMs}ms`)),
31
+ timeoutMs,
32
+ );
33
+ }),
34
+ ]);
35
+ } finally {
36
+ if (timer) clearTimeout(timer);
37
+ }
38
+ }
39
+
40
+ class CdpJournal {
41
+ constructor(outputDir) {
42
+ this.partialPath = path.join(outputDir, 'cdp-stream.jsonl.partial');
43
+ this.finalPath = path.join(outputDir, 'cdp-stream.jsonl');
44
+ this.fd = fs.openSync(this.partialPath, 'wx', 0o600);
45
+ this.digest = crypto.createHash('sha256');
46
+ this.count = 0;
47
+ this.directionCounts = { in: 0, out: 0 };
48
+ this.methodCounts = new Map();
49
+ this.closed = false;
50
+ }
51
+
52
+ record(direction, raw) {
53
+ if (this.closed) throw new Error('CDP journal is closed');
54
+ const sequence = ++this.count;
55
+ const observedAt = new Date().toISOString();
56
+ const monotonicNanoseconds = process.hrtime.bigint().toString();
57
+ const message = JSON.parse(raw);
58
+ const method = message.method || (message.id !== undefined ? 'response' : 'unknown');
59
+ this.directionCounts[direction] = (this.directionCounts[direction] || 0) + 1;
60
+ this.methodCounts.set(method, (this.methodCounts.get(method) || 0) + 1);
61
+ this.digest.update(direction);
62
+ this.digest.update('\0');
63
+ this.digest.update(raw);
64
+ this.digest.update('\0');
65
+ fs.writeSync(this.fd, `${JSON.stringify({
66
+ sequence,
67
+ observedAt,
68
+ monotonicNanoseconds,
69
+ direction,
70
+ raw,
71
+ })}\n`);
72
+ return sequence;
73
+ }
74
+
75
+ close() {
76
+ if (this.closed) throw new Error('CDP journal is already closed');
77
+ fs.fsyncSync(this.fd);
78
+ fs.closeSync(this.fd);
79
+ fs.renameSync(this.partialPath, this.finalPath);
80
+ this.closed = true;
81
+ return {
82
+ artifact: path.basename(this.finalPath),
83
+ messages: this.count,
84
+ directions: this.directionCounts,
85
+ methods: Object.fromEntries(
86
+ [...this.methodCounts.entries()].sort(([left], [right]) => left.localeCompare(right)),
87
+ ),
88
+ sha256: this.digest.digest('hex'),
89
+ };
90
+ }
91
+ }
92
+
16
93
  class CdpClient {
17
- constructor(commandStream, eventStream) {
94
+ constructor(commandStream, eventStream, journal = null) {
18
95
  this.commandStream = commandStream;
19
96
  this.eventStream = eventStream;
97
+ this.journal = journal;
20
98
  this.sessionId = null;
21
99
  this.nextId = 1;
22
100
  this.pending = new Map();
23
101
  this.listeners = new Map();
102
+ this.decoder = new StringDecoder('utf8');
24
103
  this.buffer = '';
104
+ this.fatalError = null;
25
105
  }
26
106
 
27
107
  async connect() {
28
- const rejectPending = (error) => {
29
- for (const pending of this.pending.values()) pending.reject(error);
30
- this.pending.clear();
31
- };
108
+ const rejectPending = (error) => this.fail(error);
32
109
  this.eventStream.on('data', (chunk) => {
33
- this.buffer += chunk.toString('utf8');
34
- let delimiter;
35
- while ((delimiter = this.buffer.indexOf('\0')) !== -1) {
36
- const raw = this.buffer.slice(0, delimiter);
37
- this.buffer = this.buffer.slice(delimiter + 1);
38
- if (!raw) continue;
39
- const message = JSON.parse(raw);
40
- this.handleMessage(message);
110
+ if (this.fatalError) return;
111
+ try {
112
+ this.buffer += this.decoder.write(chunk);
113
+ let delimiter;
114
+ while ((delimiter = this.buffer.indexOf('\0')) !== -1) {
115
+ const raw = this.buffer.slice(0, delimiter);
116
+ this.buffer = this.buffer.slice(delimiter + 1);
117
+ if (!raw) continue;
118
+ const journalSequence = this.journal?.record('in', raw) || null;
119
+ const message = JSON.parse(raw);
120
+ this.handleMessage(message, { journalSequence });
121
+ }
122
+ } catch (error) {
123
+ this.fail(error);
41
124
  }
42
125
  });
43
126
  this.eventStream.once('error', rejectPending);
@@ -47,8 +130,15 @@ class CdpClient {
47
130
  this.commandStream.once('error', rejectPending);
48
131
  }
49
132
 
50
- handleMessage(message) {
51
- if (message.id) {
133
+ fail(error) {
134
+ if (this.fatalError) return;
135
+ this.fatalError = error;
136
+ for (const pending of this.pending.values()) pending.reject(error);
137
+ this.pending.clear();
138
+ }
139
+
140
+ handleMessage(message, envelope = {}) {
141
+ if (message.id !== undefined) {
52
142
  const pending = this.pending.get(message.id);
53
143
  if (!pending) return;
54
144
  this.pending.delete(message.id);
@@ -60,18 +150,35 @@ class CdpClient {
60
150
  return;
61
151
  }
62
152
  for (const listener of this.listeners.get(message.method) || []) {
63
- listener(message.params || {});
153
+ listener(message.params || {}, {
154
+ method: message.method,
155
+ sessionId: message.sessionId || null,
156
+ cdpSequence: envelope.journalSequence || null,
157
+ });
64
158
  }
65
159
  }
66
160
 
67
161
  call(method, params = {}, options = {}) {
162
+ if (this.fatalError) return Promise.reject(this.fatalError);
68
163
  const id = this.nextId++;
69
164
  return new Promise((resolve, reject) => {
70
165
  this.pending.set(id, { method, resolve, reject });
71
166
  const message = { id, method, params };
72
- const sessionId = options.browserCommand ? null : this.sessionId;
167
+ const sessionId = Object.prototype.hasOwnProperty.call(options, 'sessionId')
168
+ ? options.sessionId
169
+ : options.browserCommand
170
+ ? null
171
+ : this.sessionId;
73
172
  if (sessionId) message.sessionId = sessionId;
74
- this.commandStream.write(`${JSON.stringify(message)}\0`);
173
+ const raw = JSON.stringify(message);
174
+ try {
175
+ this.journal?.record('out', raw);
176
+ this.commandStream.write(`${raw}\0`);
177
+ } catch (error) {
178
+ this.pending.delete(id);
179
+ this.fail(error);
180
+ reject(error);
181
+ }
75
182
  });
76
183
  }
77
184
 
@@ -232,6 +339,7 @@ async function atomicWrite(filePath, data, mode = 0o600) {
232
339
 
233
340
  async function prepareOutputDir(outputDir) {
234
341
  const uid = typeof process.getuid === 'function' ? process.getuid() : null;
342
+ const enforcePosixPermissions = process.platform !== 'win32';
235
343
  const assertTrustedAncestors = async (target) => {
236
344
  let current = path.resolve(target);
237
345
  while (true) {
@@ -240,7 +348,7 @@ async function prepareOutputDir(outputDir) {
240
348
  if (stat.isSymbolicLink()) {
241
349
  throw new Error(`headless output ancestor is a symlink: ${current}`);
242
350
  }
243
- if ((stat.mode & 0o022) !== 0) {
351
+ if (enforcePosixPermissions && (stat.mode & 0o022) !== 0) {
244
352
  throw new Error(`headless output ancestor is group/world writable: ${current}`);
245
353
  }
246
354
  if (uid != null && stat.uid !== uid && stat.uid !== 0) {
@@ -310,24 +418,468 @@ function resolveBrowserBinary(configured) {
310
418
  return resolved;
311
419
  }
312
420
 
313
- async function stopProcess(child) {
314
- if (!child || child.exitCode !== null || child.signalCode !== null) return;
315
- const exited = new Promise((resolve) => child.once('exit', resolve));
316
- child.kill('SIGTERM');
317
- let timer;
318
- const graceful = await Promise.race([
319
- exited.then(() => true),
320
- new Promise((resolve) => {
321
- timer = setTimeout(() => resolve(false), 5_000);
322
- }),
421
+ async function stopProcess(child, timeoutMs = 5_000) {
422
+ if (!child) return;
423
+ const processGroup = child.gliderProcessGroup === true && process.platform !== 'win32';
424
+ const groupRunning = () => {
425
+ if (!processGroup) return child.exitCode === null && child.signalCode === null;
426
+ try {
427
+ process.kill(-child.pid, 0);
428
+ return true;
429
+ } catch (error) {
430
+ if (error.code === 'ESRCH') return false;
431
+ if (
432
+ error.code === 'EPERM'
433
+ && (child.exitCode !== null || child.signalCode !== null)
434
+ ) {
435
+ return false;
436
+ }
437
+ throw error;
438
+ }
439
+ };
440
+ const signal = (name) => {
441
+ if (processGroup) {
442
+ try {
443
+ process.kill(-child.pid, name);
444
+ } catch (error) {
445
+ if (error.code === 'EPERM' && child.exitCode === null && child.signalCode === null) {
446
+ child.kill(name);
447
+ } else if (error.code !== 'ESRCH' && error.code !== 'EPERM') {
448
+ throw error;
449
+ }
450
+ }
451
+ } else if (child.exitCode === null && child.signalCode === null) {
452
+ child.kill(name);
453
+ }
454
+ };
455
+ const waitUntilStopped = async (limitMs) => {
456
+ const deadline = Date.now() + limitMs;
457
+ while (groupRunning() && Date.now() < deadline) await delay(50);
458
+ return !groupRunning();
459
+ };
460
+ if (!groupRunning()) return;
461
+ signal('SIGTERM');
462
+ const graceful = await waitUntilStopped(timeoutMs);
463
+ if (!graceful) {
464
+ signal('SIGKILL');
465
+ if (!await waitUntilStopped(2_000)) {
466
+ throw new Error('process shutdown after SIGKILL timed out after 2000ms');
467
+ }
468
+ }
469
+ }
470
+
471
+ function findExecutable(command, envPath = process.env.PATH || '') {
472
+ if (path.isAbsolute(command) || command.includes(path.sep)) {
473
+ const resolved = path.resolve(command);
474
+ fs.accessSync(resolved, fs.constants.X_OK);
475
+ return resolved;
476
+ }
477
+ for (const directory of envPath.split(path.delimiter).filter(Boolean)) {
478
+ const candidate = path.join(directory, command);
479
+ try {
480
+ fs.accessSync(candidate, fs.constants.X_OK);
481
+ return candidate;
482
+ } catch {
483
+ // Continue through PATH.
484
+ }
485
+ }
486
+ return '';
487
+ }
488
+
489
+ async function runCommand(command, args, timeoutMs, description) {
490
+ const child = spawn(command, args, {
491
+ detached: false,
492
+ stdio: ['ignore', 'pipe', 'pipe'],
493
+ });
494
+ const stdout = [];
495
+ const stderr = [];
496
+ child.stdout.on('data', (chunk) => stdout.push(chunk));
497
+ child.stderr.on('data', (chunk) => stderr.push(chunk));
498
+ const exit = new Promise((resolve, reject) => {
499
+ child.once('error', reject);
500
+ child.once('exit', (code, signal) => resolve({ code, signal }));
501
+ });
502
+ let outcome;
503
+ try {
504
+ outcome = await withTimeout(exit, timeoutMs, description);
505
+ } catch (error) {
506
+ await stopProcess(child, 1_000);
507
+ throw error;
508
+ }
509
+ const result = {
510
+ ...outcome,
511
+ stdout: Buffer.concat(stdout).toString('utf8'),
512
+ stderr: Buffer.concat(stderr).toString('utf8'),
513
+ };
514
+ if (result.code !== 0 || result.signal) {
515
+ throw new Error(
516
+ `${description} failed (${result.signal || `exit ${result.code}`}): ${
517
+ (result.stderr || result.stdout).trim() || 'no output'
518
+ }`,
519
+ );
520
+ }
521
+ return result;
522
+ }
523
+
524
+ function resolveMitmproxyCommand(configured = {}) {
525
+ const requestedMitmdump = configured.mitmdumpBinary || 'mitmdump';
526
+ let mitmdump = '';
527
+ try {
528
+ mitmdump = findExecutable(requestedMitmdump);
529
+ } catch (error) {
530
+ if (configured.mitmdumpBinary) throw error;
531
+ }
532
+ if (mitmdump) {
533
+ return {
534
+ command: mitmdump,
535
+ prefixArgs: [],
536
+ source: 'installed-mitmdump',
537
+ verifyVersion: true,
538
+ };
539
+ }
540
+ const requestedUv = configured.uvBinary || 'uv';
541
+ let uv = '';
542
+ try {
543
+ uv = findExecutable(requestedUv);
544
+ } catch (error) {
545
+ if (configured.uvBinary) throw error;
546
+ }
547
+ if (!uv) {
548
+ throw new Error(
549
+ `proxy capture requires mitmdump ${MITMPROXY_VERSION} or uv on PATH`,
550
+ );
551
+ }
552
+ return {
553
+ command: uv,
554
+ prefixArgs: [
555
+ 'tool',
556
+ 'run',
557
+ '--from',
558
+ `mitmproxy==${MITMPROXY_VERSION}`,
559
+ 'mitmdump',
560
+ ],
561
+ source: 'uv-pinned-fallback',
562
+ verifyVersion: false,
563
+ };
564
+ }
565
+
566
+ async function reserveLoopbackPort() {
567
+ const server = net.createServer();
568
+ await new Promise((resolve, reject) => {
569
+ server.once('error', reject);
570
+ server.listen(0, '127.0.0.1', resolve);
571
+ });
572
+ const address = server.address();
573
+ const port = address && typeof address === 'object' ? address.port : 0;
574
+ await new Promise((resolve, reject) => server.close((error) => (
575
+ error ? reject(error) : resolve()
576
+ )));
577
+ if (!port) throw new Error('failed to reserve an ephemeral proxy port');
578
+ return port;
579
+ }
580
+
581
+ function computeCertificateSpkiHash(pem) {
582
+ const certificate = new crypto.X509Certificate(pem);
583
+ const spki = certificate.publicKey.export({ type: 'spki', format: 'der' });
584
+ return crypto.createHash('sha256').update(spki).digest('base64');
585
+ }
586
+
587
+ function buildMitmproxyArgs(paths, port, upstream = '') {
588
+ const args = [
589
+ '--listen-host',
590
+ '127.0.0.1',
591
+ '--listen-port',
592
+ String(port),
593
+ '--set',
594
+ `confdir=${paths.confDir}`,
595
+ '--set',
596
+ `hardump=${paths.harPath}`,
597
+ '--set',
598
+ 'termlog_verbosity=info',
599
+ '--set',
600
+ 'websocket=true',
601
+ '--set',
602
+ `glider_capture_dir=${paths.exactDir}`,
603
+ '-s',
604
+ paths.addonPath,
605
+ '-w',
606
+ paths.flowPath,
607
+ ];
608
+ if (upstream) args.push('--mode', `upstream:${upstream}`);
609
+ return args;
610
+ }
611
+
612
+ function proxyBrowserArgs(proxy) {
613
+ if (!proxy?.port || !proxy?.spkiHash) {
614
+ throw new Error('proxy browser arguments require a ready proxy and CA SPKI hash');
615
+ }
616
+ return [
617
+ `--proxy-server=http://127.0.0.1:${proxy.port}`,
618
+ '--proxy-bypass-list=<-loopback>',
619
+ '--disable-quic',
620
+ `--ignore-certificate-errors-spki-list=${proxy.spkiHash}`,
621
+ ];
622
+ }
623
+
624
+ function installProxyTerminationHandlers(proxy) {
625
+ const handlers = new Map();
626
+ let stopping = false;
627
+ const restore = () => {
628
+ for (const [signal, handler] of handlers) {
629
+ process.removeListener(signal, handler);
630
+ }
631
+ handlers.clear();
632
+ };
633
+ for (const signal of ['SIGINT', 'SIGTERM']) {
634
+ const handler = () => {
635
+ if (stopping) return;
636
+ stopping = true;
637
+ restore();
638
+ stopProcess(proxy.child, 2_000)
639
+ .catch(() => {})
640
+ .finally(() => {
641
+ process.kill(process.pid, signal);
642
+ });
643
+ };
644
+ handlers.set(signal, handler);
645
+ process.once(signal, handler);
646
+ }
647
+ return restore;
648
+ }
649
+
650
+ async function waitForProxyReady(proxy, timeoutMs) {
651
+ const deadline = Date.now() + timeoutMs;
652
+ let lastError = 'proxy did not accept a connection';
653
+ while (Date.now() < deadline) {
654
+ if (proxy.child.exitCode !== null || proxy.child.signalCode !== null) {
655
+ throw new Error(
656
+ `mitmproxy exited before readiness (${
657
+ proxy.child.signalCode || `exit ${proxy.child.exitCode}`
658
+ })`,
659
+ );
660
+ }
661
+ try {
662
+ await new Promise((resolve, reject) => {
663
+ const socket = net.createConnection({
664
+ host: '127.0.0.1',
665
+ port: proxy.port,
666
+ });
667
+ const timer = setTimeout(() => {
668
+ socket.destroy();
669
+ reject(new Error('proxy readiness connection timed out'));
670
+ }, 250);
671
+ socket.once('connect', () => {
672
+ clearTimeout(timer);
673
+ socket.end();
674
+ resolve();
675
+ });
676
+ socket.once('error', (error) => {
677
+ clearTimeout(timer);
678
+ reject(error);
679
+ });
680
+ });
681
+ await fsp.access(proxy.paths.caPath, fs.constants.R_OK);
682
+ await fsp.access(proxy.paths.exactReadyPath, fs.constants.R_OK);
683
+ return;
684
+ } catch (error) {
685
+ lastError = error.message;
686
+ await delay(100);
687
+ }
688
+ }
689
+ throw new Error(`mitmproxy readiness timed out after ${timeoutMs}ms: ${lastError}`);
690
+ }
691
+
692
+ async function enforcePrivateTree(root) {
693
+ const entries = await fsp.readdir(root, { withFileTypes: true });
694
+ await fsp.chmod(root, 0o700);
695
+ for (const entry of entries) {
696
+ const entryPath = path.join(root, entry.name);
697
+ if (entry.isSymbolicLink()) {
698
+ throw new Error(`proxy artifact must not be a symlink: ${entryPath}`);
699
+ }
700
+ if (entry.isDirectory()) await enforcePrivateTree(entryPath);
701
+ else if (entry.isFile()) await fsp.chmod(entryPath, 0o600);
702
+ }
703
+ }
704
+
705
+ async function startProxyCapture(outputDir, configured = {}) {
706
+ const rootDir = path.join(outputDir, 'proxy');
707
+ const confDir = path.join(rootDir, 'conf');
708
+ const exactDir = path.join(rootDir, 'exact');
709
+ await Promise.all([
710
+ fsp.mkdir(confDir, { recursive: true, mode: 0o700 }),
711
+ fsp.mkdir(exactDir, { recursive: true, mode: 0o700 }),
712
+ ]);
713
+ await Promise.all([
714
+ fsp.chmod(rootDir, 0o700),
715
+ fsp.chmod(confDir, 0o700),
716
+ fsp.chmod(exactDir, 0o700),
323
717
  ]);
324
- if (timer) clearTimeout(timer);
325
- if (!graceful && child.exitCode === null && child.signalCode === null) {
326
- child.kill('SIGKILL');
327
- await exited;
718
+ const paths = {
719
+ rootDir,
720
+ confDir,
721
+ exactDir,
722
+ addonPath: path.join(__dirname, 'mitmproxy-exact-capture.py'),
723
+ caPath: path.join(confDir, 'mitmproxy-ca-cert.pem'),
724
+ flowPath: path.join(rootDir, 'flows.mitm'),
725
+ harPath: path.join(rootDir, 'traffic.har'),
726
+ logPath: path.join(rootDir, 'mitmdump.log'),
727
+ exactIndexPath: path.join(exactDir, 'flows.jsonl'),
728
+ exactReadyPath: path.join(exactDir, 'ready.json'),
729
+ exactFinalPath: path.join(exactDir, 'final.json'),
730
+ };
731
+ await fsp.access(paths.addonPath, fs.constants.R_OK);
732
+ const upstream = Object.prototype.hasOwnProperty.call(configured, 'proxyUpstream')
733
+ ? configured.proxyUpstream
734
+ : process.env.HTTPS_PROXY
735
+ || process.env.https_proxy
736
+ || process.env.HTTP_PROXY
737
+ || process.env.http_proxy
738
+ || '';
739
+ if (upstream) {
740
+ const parsedUpstream = new URL(upstream);
741
+ if (!['http:', 'https:'].includes(parsedUpstream.protocol)) {
742
+ throw new Error(`unsupported mitmproxy upstream protocol: ${parsedUpstream.protocol}`);
743
+ }
744
+ }
745
+ const command = resolveMitmproxyCommand(configured);
746
+ if (command.verifyVersion) {
747
+ const version = await runCommand(
748
+ command.command,
749
+ ['--version'],
750
+ configured.proxyCommandTimeoutMs || 10_000,
751
+ 'mitmdump version check',
752
+ );
753
+ const reported = `${version.stdout}\n${version.stderr}`;
754
+ if (!new RegExp(`\\b${MITMPROXY_VERSION.replace(/\./g, '\\.')}\\b`).test(reported)) {
755
+ throw new Error(
756
+ `installed mitmdump must be ${MITMPROXY_VERSION}; reported: ${reported.trim()}`,
757
+ );
758
+ }
759
+ }
760
+ const port = await reserveLoopbackPort();
761
+ const logFd = fs.openSync(paths.logPath, 'wx', 0o600);
762
+ const args = [...command.prefixArgs, ...buildMitmproxyArgs(paths, port, upstream)];
763
+ const useProcessGroup = process.platform !== 'win32';
764
+ const child = spawn(command.command, args, {
765
+ detached: useProcessGroup,
766
+ stdio: ['ignore', logFd, logFd],
767
+ env: {
768
+ ...process.env,
769
+ PYTHONDONTWRITEBYTECODE: '1',
770
+ },
771
+ });
772
+ child.gliderProcessGroup = useProcessGroup;
773
+ const proxy = {
774
+ child,
775
+ logFd,
776
+ port,
777
+ paths,
778
+ command: {
779
+ source: command.source,
780
+ executable: command.command,
781
+ version: MITMPROXY_VERSION,
782
+ },
783
+ upstream: upstream ? true : false,
784
+ };
785
+ let spawnError;
786
+ child.once('error', (error) => { spawnError = error; });
787
+ try {
788
+ await waitForProxyReady(proxy, configured.proxyStartupTimeoutMs || 30_000);
789
+ if (spawnError) throw spawnError;
790
+ await enforcePrivateTree(rootDir);
791
+ const caPem = await fsp.readFile(paths.caPath, 'utf8');
792
+ proxy.spkiHash = computeCertificateSpkiHash(caPem);
793
+ return proxy;
794
+ } catch (error) {
795
+ try {
796
+ await stopProcess(child, 2_000);
797
+ } finally {
798
+ fs.closeSync(logFd);
799
+ proxy.logClosed = true;
800
+ await enforcePrivateTree(rootDir);
801
+ }
802
+ throw error;
328
803
  }
329
804
  }
330
805
 
806
+ async function finalizeProxyCapture(proxy, timeoutMs = 15_000) {
807
+ if (!proxy) return null;
808
+ try {
809
+ await stopProcess(proxy.child, timeoutMs);
810
+ } finally {
811
+ if (!proxy.logClosed) {
812
+ fs.closeSync(proxy.logFd);
813
+ proxy.logClosed = true;
814
+ }
815
+ }
816
+ const requiredArtifacts = [
817
+ proxy.paths.harPath,
818
+ proxy.paths.flowPath,
819
+ proxy.paths.exactIndexPath,
820
+ proxy.paths.exactFinalPath,
821
+ ];
822
+ const deadline = Date.now() + timeoutMs;
823
+ while (Date.now() < deadline) {
824
+ const present = await Promise.all(requiredArtifacts.map(async (artifact) => {
825
+ try {
826
+ return (await fsp.stat(artifact)).isFile();
827
+ } catch (error) {
828
+ if (error.code === 'ENOENT') return false;
829
+ throw error;
830
+ }
831
+ }));
832
+ if (present.every(Boolean)) break;
833
+ await delay(50);
834
+ }
835
+ await enforcePrivateTree(proxy.paths.rootDir);
836
+ const [harStat, flowStat, exactIndexStat, exactFinal] = await Promise.all([
837
+ fsp.stat(proxy.paths.harPath),
838
+ fsp.stat(proxy.paths.flowPath),
839
+ fsp.stat(proxy.paths.exactIndexPath),
840
+ fsp.readFile(proxy.paths.exactFinalPath, 'utf8').then(JSON.parse),
841
+ ]);
842
+ if (!harStat.isFile()) throw new Error('mitmproxy HAR was not finalized as a file');
843
+ if (!flowStat.isFile()) throw new Error('mitmproxy flow capture was not finalized as a file');
844
+ if (!exactIndexStat.isFile()) {
845
+ throw new Error('mitmproxy exact flow index was not finalized as a file');
846
+ }
847
+ if (exactFinal.schema !== PROXY_EXACT_SCHEMA) {
848
+ throw new Error(`unexpected mitmproxy exact capture schema: ${exactFinal.schema}`);
849
+ }
850
+ if (exactFinal.captureErrorCount !== 0) {
851
+ throw new Error(
852
+ `mitmproxy exact capture reported ${exactFinal.captureErrorCount} capture errors`,
853
+ );
854
+ }
855
+ return {
856
+ enabled: true,
857
+ version: proxy.command.version,
858
+ launch: proxy.command.source,
859
+ endpoint: `127.0.0.1:${proxy.port}`,
860
+ upstreamProxy: proxy.upstream,
861
+ caTrust: {
862
+ mechanism: 'chromium-spki-allowlist',
863
+ sha256Base64: proxy.spkiHash,
864
+ },
865
+ artifacts: {
866
+ log: path.relative(path.dirname(proxy.paths.rootDir), proxy.paths.logPath),
867
+ flows: path.relative(path.dirname(proxy.paths.rootDir), proxy.paths.flowPath),
868
+ har: path.relative(path.dirname(proxy.paths.rootDir), proxy.paths.harPath),
869
+ confdir: path.relative(path.dirname(proxy.paths.rootDir), proxy.paths.confDir),
870
+ exactIndex: path.relative(
871
+ path.dirname(proxy.paths.rootDir),
872
+ proxy.paths.exactIndexPath,
873
+ ),
874
+ exactBodies: path.relative(
875
+ path.dirname(proxy.paths.rootDir),
876
+ path.join(proxy.paths.exactDir, 'bodies'),
877
+ ),
878
+ },
879
+ exactCapture: exactFinal,
880
+ };
881
+ }
882
+
331
883
  function parseRuntimeArgs(argv) {
332
884
  const separator = argv.indexOf('--');
333
885
  const runtimeArgs = separator === -1 ? argv : argv.slice(0, separator);
@@ -485,6 +1037,644 @@ function compileBodyPatterns(patterns) {
485
1037
  ));
486
1038
  }
487
1039
 
1040
+ function sha256(value) {
1041
+ return crypto.createHash('sha256').update(value).digest('hex');
1042
+ }
1043
+
1044
+ function responseCanHaveBody(record) {
1045
+ const status = Number(record.response?.status);
1046
+ return record.method !== 'HEAD'
1047
+ && status !== 101
1048
+ && status !== 204
1049
+ && status !== 205
1050
+ && status !== 304
1051
+ && !record.redirectedTo
1052
+ && !String(record.url || '').startsWith('data:');
1053
+ }
1054
+
1055
+ function redirectCanHaveBody(record) {
1056
+ const status = Number(record.response?.status);
1057
+ return Boolean(record.redirectedTo)
1058
+ && record.method !== 'HEAD'
1059
+ && status !== 101
1060
+ && status !== 204
1061
+ && status !== 205
1062
+ && status !== 304
1063
+ && !String(record.url || '').startsWith('data:');
1064
+ }
1065
+
1066
+ async function storePayload(outputDir, state, kind, value, options = {}) {
1067
+ const buffer = Buffer.isBuffer(value)
1068
+ ? value
1069
+ : options.base64Encoded
1070
+ ? Buffer.from(value || '', 'base64')
1071
+ : Buffer.from(value || '', 'utf8');
1072
+ const digest = sha256(buffer);
1073
+ const sequence = String(++state.sequence).padStart(6, '0');
1074
+ const filename = `${sequence}-${kind}-${digest.slice(0, 16)}.body`;
1075
+ const relativePath = path.join('network', 'bodies', filename);
1076
+ await atomicWrite(path.join(outputDir, relativePath), buffer);
1077
+ return {
1078
+ artifact: relativePath,
1079
+ bytes: buffer.length,
1080
+ sha256: digest,
1081
+ cdpBase64Encoded: options.base64Encoded === true,
1082
+ origin: options.origin || 'cdp',
1083
+ ...(options.originMetadata || {}),
1084
+ };
1085
+ }
1086
+
1087
+ function proxyHarEntries(document) {
1088
+ const entries = document?.log?.entries;
1089
+ if (!Array.isArray(entries)) throw new Error('proxy HAR has no log.entries array');
1090
+ return entries.map((entry, index) => ({
1091
+ index,
1092
+ startedAt: entry.startedDateTime || null,
1093
+ startedMilliseconds: Number.isFinite(Date.parse(entry.startedDateTime))
1094
+ ? Date.parse(entry.startedDateTime)
1095
+ : null,
1096
+ method: String(entry.request?.method || ''),
1097
+ url: String(entry.request?.url || ''),
1098
+ status: Number(entry.response?.status),
1099
+ entry,
1100
+ }));
1101
+ }
1102
+
1103
+ async function proxyExactEntries(exactDir, finalSummary = null) {
1104
+ const indexPath = path.join(exactDir, 'flows.jsonl');
1105
+ const text = await fsp.readFile(indexPath, 'utf8');
1106
+ const rows = text.split(/\r?\n/).filter(Boolean).map((line, index) => {
1107
+ try {
1108
+ return JSON.parse(line);
1109
+ } catch (error) {
1110
+ throw new Error(`invalid proxy exact index JSON at line ${index + 1}: ${error.message}`);
1111
+ }
1112
+ });
1113
+ if (
1114
+ finalSummary
1115
+ && Number(finalSummary.terminalCount) !== rows.length
1116
+ ) {
1117
+ throw new Error(
1118
+ `proxy exact index count ${rows.length} did not match terminal count ${
1119
+ finalSummary.terminalCount
1120
+ }`,
1121
+ );
1122
+ }
1123
+ const flowIds = new Set();
1124
+ const validateBody = async (body, rowIndex, kind) => {
1125
+ if (body == null) return null;
1126
+ if (
1127
+ typeof body.artifact !== 'string'
1128
+ || !Number.isInteger(body.bytes)
1129
+ || body.bytes < 0
1130
+ || !/^[a-f0-9]{64}$/.test(body.sha256 || '')
1131
+ ) {
1132
+ throw new Error(`invalid ${kind} body metadata in proxy exact index row ${rowIndex + 1}`);
1133
+ }
1134
+ const absolute = path.resolve(exactDir, body.artifact);
1135
+ if (!absolute.startsWith(`${path.resolve(exactDir)}${path.sep}`)) {
1136
+ throw new Error(`proxy exact body escapes capture directory: ${body.artifact}`);
1137
+ }
1138
+ const stat = await fsp.lstat(absolute);
1139
+ if (!stat.isFile() || stat.isSymbolicLink()) {
1140
+ throw new Error(`proxy exact body is not a regular file: ${body.artifact}`);
1141
+ }
1142
+ const buffer = await fsp.readFile(absolute);
1143
+ const digest = sha256(buffer);
1144
+ if (buffer.length !== body.bytes || digest !== body.sha256) {
1145
+ throw new Error(`proxy exact body failed hash/length validation: ${body.artifact}`);
1146
+ }
1147
+ return {
1148
+ ...body,
1149
+ buffer,
1150
+ };
1151
+ };
1152
+ return Promise.all(rows.map(async (row, index) => {
1153
+ if (row.schema !== PROXY_EXACT_SCHEMA) {
1154
+ throw new Error(`unexpected proxy exact schema in row ${index + 1}: ${row.schema}`);
1155
+ }
1156
+ if (!['response', 'error'].includes(row.terminal)) {
1157
+ throw new Error(`invalid proxy terminal state in row ${index + 1}: ${row.terminal}`);
1158
+ }
1159
+ if (!row.flowId || flowIds.has(row.flowId)) {
1160
+ throw new Error(`duplicate or missing proxy flow ID in row ${index + 1}`);
1161
+ }
1162
+ flowIds.add(row.flowId);
1163
+ if (!row.method || !row.url) {
1164
+ throw new Error(`proxy exact row ${index + 1} has no method or URL`);
1165
+ }
1166
+ const status = row.status == null ? null : Number(row.status);
1167
+ if (status != null && !Number.isFinite(status)) {
1168
+ throw new Error(`proxy exact row ${index + 1} has an invalid status`);
1169
+ }
1170
+ const requestBody = await validateBody(row.requestBody, index, 'request');
1171
+ const responseBody = await validateBody(row.responseBody, index, 'response');
1172
+ return {
1173
+ index,
1174
+ flowId: row.flowId,
1175
+ terminal: row.terminal,
1176
+ observedAt: row.observedAt || null,
1177
+ method: String(row.method),
1178
+ url: String(row.url),
1179
+ status,
1180
+ startedMilliseconds: Number.isFinite(Number(row.timestamps?.requestStart))
1181
+ ? Number(row.timestamps.requestStart) * 1_000
1182
+ : null,
1183
+ timestamps: row.timestamps || {},
1184
+ requestBody,
1185
+ responseBody,
1186
+ error: row.error || null,
1187
+ };
1188
+ }));
1189
+ }
1190
+
1191
+ function networkHarKey(method, url, status) {
1192
+ return `${method}\0${url}\0${status == null ? '<none>' : Number(status)}`;
1193
+ }
1194
+
1195
+ function resolveCaptureIssue(captureIssues, predicate, resolution) {
1196
+ for (const issue of captureIssues) {
1197
+ if (!issue.resolved && predicate(issue)) {
1198
+ issue.resolved = true;
1199
+ issue.resolution = resolution;
1200
+ issue.resolvedAt = new Date().toISOString();
1201
+ }
1202
+ }
1203
+ }
1204
+
1205
+ function classifySourceMapReference(script) {
1206
+ if (script.sourceMapURL.startsWith('data:')) {
1207
+ return { resolvedURL: script.sourceMapURL };
1208
+ }
1209
+ const scriptUrl = new URL(script.url);
1210
+ const candidate = new URL(script.sourceMapURL, scriptUrl);
1211
+ if (['webpack:', 'webpack-internal:'].includes(candidate.protocol) && script.source) {
1212
+ return {
1213
+ result: {
1214
+ kind: 'non-fetchable-virtual-reference',
1215
+ protocol: candidate.protocol,
1216
+ reference: script.sourceMapURL,
1217
+ resolvedURL: candidate.href,
1218
+ reason: 'webpack virtual source-map reference retained with captured script source',
1219
+ scriptSourceArtifact: script.source.artifact,
1220
+ },
1221
+ };
1222
+ }
1223
+ if (!['http:', 'https:'].includes(candidate.protocol)) {
1224
+ throw new Error(`unsupported source-map protocol: ${candidate.protocol}`);
1225
+ }
1226
+ if (candidate.origin !== scriptUrl.origin) {
1227
+ throw new Error(
1228
+ `cross-origin source map is outside the loaded script origin: ${candidate.href}`,
1229
+ );
1230
+ }
1231
+ return { resolvedURL: candidate.href };
1232
+ }
1233
+
1234
+ async function reconcileNetworkWithProxyHar(
1235
+ outputDir,
1236
+ payloadState,
1237
+ network,
1238
+ harEntries,
1239
+ exactEntries,
1240
+ captureIssues,
1241
+ artifacts = {},
1242
+ ) {
1243
+ const harArtifact = artifacts.harArtifact || path.join('proxy', 'traffic.har');
1244
+ const exactIndexArtifact = artifacts.exactIndexArtifact
1245
+ || path.join('proxy', 'exact', 'flows.jsonl');
1246
+ const recordGroups = new Map();
1247
+ for (const record of network) {
1248
+ const key = networkHarKey(record.method, record.url, record.response?.status ?? null);
1249
+ const group = recordGroups.get(key) || [];
1250
+ group.push(record);
1251
+ recordGroups.set(key, group);
1252
+ }
1253
+ const exactGroups = new Map();
1254
+ for (const entry of exactEntries) {
1255
+ if (!entry.method || !entry.url) continue;
1256
+ const key = networkHarKey(entry.method, entry.url, entry.status);
1257
+ const group = exactGroups.get(key) || [];
1258
+ group.push(entry);
1259
+ exactGroups.set(key, group);
1260
+ }
1261
+ let matchedRecords = 0;
1262
+ let fallbackBodies = 0;
1263
+ let redirectBodies = 0;
1264
+ let requestBodies = 0;
1265
+ let partialResponseBodies = 0;
1266
+ let closedResponses = 0;
1267
+ let terminalErrors = 0;
1268
+ let coverageGaps = 0;
1269
+ let ambiguities = 0;
1270
+ for (const [key, records] of recordGroups) {
1271
+ const candidates = exactGroups.get(key) || [];
1272
+ const needsProxy = records.filter((record) => (
1273
+ /^https?:\/\//i.test(record.url || '')
1274
+ ||
1275
+ (!record.responseBody && responseCanHaveBody(record))
1276
+ || (redirectCanHaveBody(record) && !record.redirectResponseBody)
1277
+ || record.captureEndedWhileOpen
1278
+ || (record.request?.hasPostData && (!record.requestBody || record.requestBodyError))
1279
+ || record.crossSessionEvents?.length
1280
+ || (record.failure && record.response)
1281
+ ));
1282
+ if (!needsProxy.length) continue;
1283
+ if (!candidates.length) {
1284
+ coverageGaps += needsProxy.length;
1285
+ captureIssues.push({
1286
+ surface: 'proxy-exact-coverage',
1287
+ key,
1288
+ recordKeys: needsProxy.map((record) => record.key),
1289
+ error: 'proxy-eligible CDP traffic had no byte-exact proxy flow',
1290
+ });
1291
+ continue;
1292
+ }
1293
+ if (records.length > candidates.length) {
1294
+ ambiguities += 1;
1295
+ captureIssues.push({
1296
+ surface: 'proxy-exact-correlation',
1297
+ key,
1298
+ recordKeys: records.map((record) => record.key),
1299
+ proxyFlowIds: candidates.map((entry) => entry.flowId),
1300
+ error: 'fewer exact proxy flows than matching CDP records',
1301
+ });
1302
+ continue;
1303
+ }
1304
+ if (
1305
+ records.length > 1
1306
+ && (
1307
+ records.some((record) => !Number.isFinite(Number(record.wallTime)))
1308
+ || candidates.some((candidate) => candidate.startedMilliseconds == null)
1309
+ )
1310
+ ) {
1311
+ ambiguities += 1;
1312
+ captureIssues.push({
1313
+ surface: 'proxy-exact-correlation',
1314
+ key,
1315
+ recordKeys: records.map((record) => record.key),
1316
+ proxyFlowIds: candidates.map((entry) => entry.flowId),
1317
+ error: 'repeated occurrences lacked comparable chronological timestamps',
1318
+ });
1319
+ continue;
1320
+ }
1321
+ const orderedRecords = [...records].sort((left, right) => (
1322
+ Number(left.wallTime || 0) - Number(right.wallTime || 0)
1323
+ ));
1324
+ let orderedCandidates = [...candidates].sort((left, right) => (
1325
+ (left.startedMilliseconds ?? 0) - (right.startedMilliseconds ?? 0)
1326
+ || left.index - right.index
1327
+ ));
1328
+ if (candidates.length > records.length) {
1329
+ const remaining = [...orderedCandidates];
1330
+ const matched = [];
1331
+ let unsafe = false;
1332
+ for (const record of orderedRecords) {
1333
+ const recordStart = Number(record.wallTime) * 1_000;
1334
+ if (!Number.isFinite(recordStart)) {
1335
+ unsafe = true;
1336
+ break;
1337
+ }
1338
+ const ranked = remaining
1339
+ .map((candidate) => ({
1340
+ candidate,
1341
+ delta: Math.abs(candidate.startedMilliseconds - recordStart),
1342
+ }))
1343
+ .sort((left, right) => left.delta - right.delta);
1344
+ if (
1345
+ !ranked.length
1346
+ || ranked[0].delta > 100
1347
+ || (ranked[1] && ranked[1].delta - ranked[0].delta < 10)
1348
+ ) {
1349
+ unsafe = true;
1350
+ break;
1351
+ }
1352
+ matched.push(ranked[0].candidate);
1353
+ remaining.splice(remaining.indexOf(ranked[0].candidate), 1);
1354
+ }
1355
+ if (unsafe) {
1356
+ ambiguities += 1;
1357
+ captureIssues.push({
1358
+ surface: 'proxy-exact-correlation',
1359
+ key,
1360
+ recordKeys: records.map((record) => record.key),
1361
+ proxyFlowIds: candidates.map((entry) => entry.flowId),
1362
+ error: 'extra exact proxy flows could not be uniquely matched by start time',
1363
+ });
1364
+ continue;
1365
+ }
1366
+ orderedCandidates = matched;
1367
+ }
1368
+ for (let index = 0; index < orderedRecords.length; index += 1) {
1369
+ const record = orderedRecords[index];
1370
+ const candidate = orderedCandidates[index];
1371
+ record.proxyCapture = {
1372
+ harArtifact,
1373
+ exactIndexArtifact,
1374
+ exactIndexRow: candidate.index,
1375
+ flowId: candidate.flowId,
1376
+ terminal: candidate.terminal,
1377
+ startedAt: candidate.timestamps.requestStart || null,
1378
+ method: candidate.method,
1379
+ url: candidate.url,
1380
+ status: candidate.status,
1381
+ responseBodyRetained: Boolean(candidate.responseBody),
1382
+ requestBodyRetained: Boolean(candidate.requestBody),
1383
+ error: candidate.error,
1384
+ };
1385
+ matchedRecords += 1;
1386
+ if (record.request?.hasPostData && candidate.requestBody) {
1387
+ const proxyRequestBody = await storePayload(
1388
+ outputDir,
1389
+ payloadState,
1390
+ 'request-proxy-exact',
1391
+ candidate.requestBody.buffer,
1392
+ {
1393
+ origin: 'proxy-addon',
1394
+ originMetadata: {
1395
+ proxyExactIndexArtifact: exactIndexArtifact,
1396
+ proxyExactIndexRow: candidate.index,
1397
+ proxyFlowId: candidate.flowId,
1398
+ proxySourceArtifact: candidate.requestBody.artifact,
1399
+ },
1400
+ },
1401
+ );
1402
+ record.proxyCapture.requestBody = proxyRequestBody;
1403
+ if (record.requestBody) record.cdpRequestBody = record.requestBody;
1404
+ record.requestBody = proxyRequestBody;
1405
+ requestBodies += 1;
1406
+ resolveCaptureIssue(
1407
+ captureIssues,
1408
+ (issue) => issue.surface === 'request-body' && issue.requestKey === record.key,
1409
+ 'byte-exact proxy addon supplied and validated the request body',
1410
+ );
1411
+ }
1412
+ let responsePayload = null;
1413
+ if (candidate.responseBody && (
1414
+ (redirectCanHaveBody(record) && !record.redirectResponseBody)
1415
+ || (!record.responseBody && responseCanHaveBody(record))
1416
+ || record.captureEndedWhileOpen
1417
+ || (record.failure && record.response)
1418
+ )) {
1419
+ responsePayload = await storePayload(
1420
+ outputDir,
1421
+ payloadState,
1422
+ candidate.terminal === 'response'
1423
+ ? record.redirectedTo
1424
+ ? 'redirect-proxy-exact'
1425
+ : 'response-proxy-exact'
1426
+ : 'response-proxy-partial',
1427
+ candidate.responseBody.buffer,
1428
+ {
1429
+ origin: 'proxy-addon',
1430
+ originMetadata: {
1431
+ proxyExactIndexArtifact: exactIndexArtifact,
1432
+ proxyExactIndexRow: candidate.index,
1433
+ proxyFlowId: candidate.flowId,
1434
+ proxySourceArtifact: candidate.responseBody.artifact,
1435
+ proxyTerminal: candidate.terminal,
1436
+ },
1437
+ },
1438
+ );
1439
+ record.proxyCapture.responseBody = responsePayload;
1440
+ }
1441
+ if (candidate.terminal === 'response') {
1442
+ if (redirectCanHaveBody(record) && responsePayload) {
1443
+ record.redirectResponseBody = responsePayload;
1444
+ redirectBodies += 1;
1445
+ } else if (
1446
+ !record.responseBody
1447
+ && responseCanHaveBody(record)
1448
+ && responsePayload
1449
+ ) {
1450
+ record.responseBody = responsePayload;
1451
+ fallbackBodies += 1;
1452
+ resolveCaptureIssue(
1453
+ captureIssues,
1454
+ (issue) => issue.surface === 'response-body' && issue.requestKey === record.key,
1455
+ 'byte-exact proxy addon supplied a complete validated response body',
1456
+ );
1457
+ }
1458
+ const completeBody = responsePayload
1459
+ || (!responseCanHaveBody(record) && !redirectCanHaveBody(record));
1460
+ if (record.captureEndedWhileOpen && completeBody) {
1461
+ delete record.captureEndedWhileOpen;
1462
+ record.proxyCompletion = {
1463
+ exactIndexArtifact,
1464
+ exactIndexRow: candidate.index,
1465
+ flowId: candidate.flowId,
1466
+ terminal: 'response',
1467
+ completed: true,
1468
+ };
1469
+ record.completedAt ||= candidate.timestamps.responseEnd
1470
+ || candidate.observedAt
1471
+ || new Date().toISOString();
1472
+ closedResponses += 1;
1473
+ }
1474
+ if (record.failure && record.response && completeBody) {
1475
+ record.proxyCompletion ||= {
1476
+ exactIndexArtifact,
1477
+ exactIndexRow: candidate.index,
1478
+ flowId: candidate.flowId,
1479
+ terminal: 'response',
1480
+ completed: true,
1481
+ };
1482
+ resolveCaptureIssue(
1483
+ captureIssues,
1484
+ (issue) => (
1485
+ issue.surface === 'response-transfer'
1486
+ && issue.requestKey === record.key
1487
+ ),
1488
+ 'byte-exact proxy addon proved a terminal complete response',
1489
+ );
1490
+ }
1491
+ } else {
1492
+ terminalErrors += 1;
1493
+ record.proxyTransfer = {
1494
+ exactIndexArtifact,
1495
+ exactIndexRow: candidate.index,
1496
+ flowId: candidate.flowId,
1497
+ terminal: 'error',
1498
+ error: candidate.error,
1499
+ partialResponseBody: responsePayload,
1500
+ };
1501
+ if (responsePayload) partialResponseBodies += 1;
1502
+ }
1503
+ resolveCaptureIssue(
1504
+ captureIssues,
1505
+ (issue) => (
1506
+ issue.surface === 'network-correlation'
1507
+ && issue.requestKey === record.key
1508
+ ),
1509
+ 'validated byte-exact proxy flow proved the cross-session request identity',
1510
+ );
1511
+ }
1512
+ }
1513
+ return {
1514
+ harEntries: harEntries.length,
1515
+ exactEntries: exactEntries.length,
1516
+ matchedRecords,
1517
+ fallbackBodies,
1518
+ redirectBodies,
1519
+ requestBodies,
1520
+ partialResponseBodies,
1521
+ closedResponses,
1522
+ terminalErrors,
1523
+ coverageGaps,
1524
+ ambiguities,
1525
+ };
1526
+ }
1527
+
1528
+ async function reconcileSourceMapsWithProxyHar(
1529
+ outputDir,
1530
+ payloadState,
1531
+ scripts,
1532
+ harEntries,
1533
+ exactEntries,
1534
+ captureIssues,
1535
+ artifacts = {},
1536
+ ) {
1537
+ const harArtifact = artifacts.harArtifact || path.join('proxy', 'traffic.har');
1538
+ const exactIndexArtifact = artifacts.exactIndexArtifact
1539
+ || path.join('proxy', 'exact', 'flows.jsonl');
1540
+ const groups = new Map();
1541
+ for (const script of scripts.filter((item) => (
1542
+ item.sourceMapAttempt
1543
+ && !item.sourceMap
1544
+ && !item.sourceMapResult
1545
+ && item.sourceMapResolvedURL
1546
+ ))) {
1547
+ const attempt = script.sourceMapAttempt;
1548
+ const key = `${script.sessionId}\0${script.sourceMapResolvedURL}\0${
1549
+ attempt.startedAt || ''
1550
+ }`;
1551
+ const group = groups.get(key) || {
1552
+ url: script.sourceMapResolvedURL,
1553
+ attempt,
1554
+ scripts: [],
1555
+ };
1556
+ group.scripts.push(script);
1557
+ groups.set(key, group);
1558
+ }
1559
+ let dispositions = 0;
1560
+ let terminalErrors = 0;
1561
+ let ambiguities = 0;
1562
+ let sequence = 0;
1563
+ for (const group of groups.values()) {
1564
+ const started = Date.parse(group.attempt.startedAt);
1565
+ const finished = Date.parse(group.attempt.finishedAt);
1566
+ const candidates = exactEntries.filter((entry) => (
1567
+ entry.method === 'GET'
1568
+ && entry.url === group.url
1569
+ && (
1570
+ !Number.isFinite(started)
1571
+ || entry.startedMilliseconds == null
1572
+ || (
1573
+ entry.startedMilliseconds >= started - 2_000
1574
+ && (!Number.isFinite(finished) || entry.startedMilliseconds <= finished + 2_000)
1575
+ )
1576
+ )
1577
+ ));
1578
+ if (candidates.length !== 1) {
1579
+ if (candidates.length > 1) {
1580
+ ambiguities += 1;
1581
+ captureIssues.push({
1582
+ surface: 'source-map-proxy-correlation',
1583
+ sourceMapURL: group.url,
1584
+ proxyFlowIds: candidates.map((entry) => entry.flowId),
1585
+ error: 'multiple byte-exact proxy flows matched the source-map attempt window',
1586
+ });
1587
+ }
1588
+ continue;
1589
+ }
1590
+ const candidate = candidates[0];
1591
+ if (!candidate.responseBody) continue;
1592
+ const responseBody = await storePayload(
1593
+ outputDir,
1594
+ payloadState,
1595
+ candidate.terminal === 'response'
1596
+ ? 'source-map-response-exact'
1597
+ : 'source-map-response-partial',
1598
+ candidate.responseBody.buffer,
1599
+ {
1600
+ origin: 'proxy-addon',
1601
+ originMetadata: {
1602
+ proxyExactIndexArtifact: exactIndexArtifact,
1603
+ proxyExactIndexRow: candidate.index,
1604
+ proxyFlowId: candidate.flowId,
1605
+ proxySourceArtifact: candidate.responseBody.artifact,
1606
+ proxyTerminal: candidate.terminal,
1607
+ },
1608
+ },
1609
+ );
1610
+ if (candidate.terminal !== 'response') {
1611
+ const transfer = {
1612
+ kind: 'terminal-proxy-error',
1613
+ url: group.url,
1614
+ method: candidate.method,
1615
+ status: candidate.status,
1616
+ proxyExactIndexArtifact: exactIndexArtifact,
1617
+ proxyExactIndexRow: candidate.index,
1618
+ proxyFlowId: candidate.flowId,
1619
+ error: candidate.error,
1620
+ partialResponseBody: responseBody,
1621
+ attemptedError: group.attempt.error,
1622
+ };
1623
+ for (const script of group.scripts) script.sourceMapTransfer = transfer;
1624
+ terminalErrors += 1;
1625
+ continue;
1626
+ }
1627
+ const disposition = {
1628
+ kind: 'http-terminal-disposition',
1629
+ url: group.url,
1630
+ method: candidate.method,
1631
+ status: candidate.status,
1632
+ startedAt: candidate.timestamps.requestStart || null,
1633
+ proxyHarArtifact: harArtifact,
1634
+ proxyExactIndexArtifact: exactIndexArtifact,
1635
+ proxyExactIndexRow: candidate.index,
1636
+ proxyFlowId: candidate.flowId,
1637
+ responseBody,
1638
+ attemptedError: group.attempt.error,
1639
+ };
1640
+ const digest = sha256(Buffer.from(JSON.stringify(disposition)));
1641
+ const relativePath = path.join(
1642
+ 'source-maps',
1643
+ `${String(++sequence).padStart(6, '0')}-${digest.slice(0, 16)}-disposition.json`,
1644
+ );
1645
+ await atomicWrite(
1646
+ path.join(outputDir, relativePath),
1647
+ `${JSON.stringify(disposition, null, 2)}\n`,
1648
+ );
1649
+ const result = { ...disposition, artifact: relativePath };
1650
+ for (const script of group.scripts) script.sourceMapResult = result;
1651
+ resolveCaptureIssue(
1652
+ captureIssues,
1653
+ (issue) => (
1654
+ issue.surface === 'source-map'
1655
+ && issue.sourceMapAttemptId === group.attempt.id
1656
+ && !issue.resolved
1657
+ ),
1658
+ 'byte-exact proxy addon retained the terminal HTTP disposition and body',
1659
+ );
1660
+ dispositions += 1;
1661
+ }
1662
+ return {
1663
+ harEntries: harEntries.length,
1664
+ exactEntries: exactEntries.length,
1665
+ dispositions,
1666
+ terminalErrors,
1667
+ ambiguities,
1668
+ };
1669
+ }
1670
+
1671
+ function safeCheckpointName(name) {
1672
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name || '')) {
1673
+ throw new Error(`checkpoint name is invalid: ${name}`);
1674
+ }
1675
+ return name;
1676
+ }
1677
+
488
1678
  async function runSubscriber(options) {
489
1679
  const { subscriber, resolved: subscriberPath } = await loadSubscriber(options.subscriber);
490
1680
  const configured = await subscriber.configure({
@@ -508,20 +1698,90 @@ async function runSubscriber(options) {
508
1698
  const cookieExport = options.cookieExport && configured.cookieExport !== false;
509
1699
  const bodyPatterns = compileBodyPatterns(configured.responseBodyPatterns);
510
1700
  const requiredCookieNames = configured.requiredCookieNames || [];
1701
+ const captureMode = configured.captureMode || 'selective';
1702
+ if (!['selective', 'exhaustive'].includes(captureMode)) {
1703
+ throw new Error(`unsupported headless capture mode: ${captureMode}`);
1704
+ }
1705
+ const exhaustiveCapture = captureMode === 'exhaustive';
1706
+ const requireCompleteCapture = configured.requireCompleteCapture === true;
1707
+ const captureAdvertisedSourceMaps = configured.captureAdvertisedSourceMaps === true;
1708
+ const captureProxyTraffic = configured.captureProxyTraffic === true;
1709
+ if (captureProxyTraffic && !exhaustiveCapture) {
1710
+ throw new Error('captureProxyTraffic requires captureMode="exhaustive"');
1711
+ }
1712
+ const configuredBrowserArgs = configured.browserArgs || [];
1713
+ if (captureProxyTraffic) {
1714
+ const conflicting = configuredBrowserArgs.find((argument) => (
1715
+ argument === '--ignore-certificate-errors'
1716
+ || argument.startsWith('--ignore-certificate-errors=')
1717
+ || argument.startsWith('--ignore-certificate-errors-spki-list')
1718
+ || argument.startsWith('--proxy-server')
1719
+ || argument === '--no-proxy-server'
1720
+ || argument.startsWith('--proxy-pac-url')
1721
+ || argument.startsWith('--proxy-bypass-list')
1722
+ || argument === '--proxy-auto-detect'
1723
+ ));
1724
+ if (conflicting) {
1725
+ throw new Error(`captureProxyTraffic conflicts with browser argument: ${conflicting}`);
1726
+ }
1727
+ }
511
1728
 
512
- const profileDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'glider-headless-'));
1729
+ const profileDir = path.join(outputDir, '.browser-profile');
1730
+ await fsp.mkdir(profileDir, { mode: 0o700 });
513
1731
  const stderrPath = path.join(outputDir, 'browser.stderr.log');
514
1732
  const stderrFd = fs.openSync(stderrPath, 'wx', 0o600);
1733
+ let stderrClosed = false;
1734
+ if (exhaustiveCapture) {
1735
+ await Promise.all([
1736
+ fsp.mkdir(path.join(outputDir, 'network', 'bodies'), { recursive: true, mode: 0o700 }),
1737
+ fsp.mkdir(path.join(outputDir, 'scripts'), { recursive: true, mode: 0o700 }),
1738
+ fsp.mkdir(path.join(outputDir, 'source-maps'), { recursive: true, mode: 0o700 }),
1739
+ fsp.mkdir(path.join(outputDir, 'checkpoints'), { recursive: true, mode: 0o700 }),
1740
+ ]);
1741
+ }
1742
+ const journal = exhaustiveCapture ? new CdpJournal(outputDir) : null;
515
1743
  let browser;
1744
+ let proxy;
1745
+ let proxySummary;
1746
+ let proxyReconciliation;
1747
+ let restoreProxyTerminationHandlers = () => {};
516
1748
  let client;
1749
+ let primaryTargetId;
517
1750
  let cookieSource;
1751
+ let browserVersion;
1752
+ let captureInitialized = false;
518
1753
  let authenticated = false;
519
1754
  let primaryError;
520
1755
  let cleanupError;
1756
+ let journalSummary;
1757
+ const captureStartedAt = new Date().toISOString();
1758
+ const captureIssues = [];
1759
+ const checkpoints = [];
1760
+ const checkpointNames = new Set();
521
1761
  const network = [];
522
1762
  const requests = new Map();
523
- const pendingBodyReads = new Set();
1763
+ const networkExtraInfo = [];
1764
+ const pendingCaptureWork = new Set();
1765
+ const payloadState = { sequence: 0 };
1766
+ const scripts = [];
1767
+ const sessionTargets = new Map();
1768
+ let acceptCaptureEvents = true;
1769
+ let requestSequence = 0;
1770
+ let scriptSequence = 0;
1771
+ let collectSourceMaps = async () => {};
524
1772
  try {
1773
+ if (captureProxyTraffic) {
1774
+ try {
1775
+ proxy = await startProxyCapture(outputDir, configured);
1776
+ restoreProxyTerminationHandlers = installProxyTerminationHandlers(proxy);
1777
+ } catch (error) {
1778
+ captureIssues.push({
1779
+ surface: 'proxy-startup',
1780
+ error: error.message,
1781
+ });
1782
+ throw error;
1783
+ }
1784
+ }
525
1785
  browser = spawn(browserBinary, [
526
1786
  '--headless=new',
527
1787
  '--remote-debugging-pipe',
@@ -533,56 +1793,252 @@ async function runSubscriber(options) {
533
1793
  '--disable-default-apps',
534
1794
  '--disable-sync',
535
1795
  '--metrics-recording-only',
536
- ...(configured.browserArgs || []),
1796
+ ...configuredBrowserArgs,
1797
+ ...(proxy ? proxyBrowserArgs(proxy) : []),
537
1798
  ], {
538
1799
  detached: false,
539
1800
  stdio: ['ignore', 'ignore', stderrFd, 'pipe', 'pipe'],
540
1801
  });
541
1802
  let spawnError;
542
1803
  browser.once('error', (error) => { spawnError = error; });
543
- client = new CdpClient(browser.stdio[3], browser.stdio[4]);
1804
+ client = new CdpClient(browser.stdio[3], browser.stdio[4], journal);
544
1805
  await client.connect();
545
1806
  await delay(0);
546
1807
  if (spawnError) throw spawnError;
1808
+ browserVersion = await client.call('Browser.getVersion', {}, { browserCommand: true });
547
1809
  const target = await client.call(
548
1810
  'Target.createTarget',
549
1811
  { url: 'about:blank' },
550
1812
  { browserCommand: true },
551
1813
  );
1814
+ primaryTargetId = target.targetId;
552
1815
  const attached = await client.call(
553
1816
  'Target.attachToTarget',
554
1817
  { targetId: target.targetId, flatten: true },
555
1818
  { browserCommand: true },
556
1819
  );
557
1820
  client.useSession(attached.sessionId);
558
- await Promise.all([
559
- client.call('Page.enable'),
560
- client.call('Runtime.enable'),
561
- client.call('Network.enable', {
562
- maxTotalBufferSize: 100_000_000,
563
- maxResourceBufferSize: 10_000_000,
564
- maxPostDataSize: 10_000_000,
565
- }),
566
- ]);
1821
+ sessionTargets.set(attached.sessionId, {
1822
+ targetId: target.targetId,
1823
+ type: 'page',
1824
+ });
1825
+ const requestKey = (requestId, metadata = {}) => (
1826
+ exhaustiveCapture
1827
+ ? `${metadata.sessionId || attached.sessionId}:${requestId}`
1828
+ : requestId
1829
+ );
1830
+ const resolveOpenRequest = (requestId, metadata = {}) => {
1831
+ const directKey = requestKey(requestId, metadata);
1832
+ const direct = requests.get(directKey);
1833
+ if (direct) return { key: directKey, record: direct };
1834
+ const candidates = [...requests.entries()]
1835
+ .filter(([, record]) => record.requestId === requestId);
1836
+ if (candidates.length === 1) {
1837
+ const [key, record] = candidates[0];
1838
+ if (exhaustiveCapture) {
1839
+ record.crossSessionEvents ||= [];
1840
+ record.crossSessionEvents.push({
1841
+ sessionId: metadata.sessionId || attached.sessionId,
1842
+ cdpSequence: metadata.cdpSequence,
1843
+ });
1844
+ if (!record.crossSessionCorrelationIssue) {
1845
+ record.crossSessionCorrelationIssue = true;
1846
+ captureIssues.push({
1847
+ surface: 'network-correlation',
1848
+ requestId,
1849
+ requestKey: record.key,
1850
+ requestSessionId: record.sessionId,
1851
+ eventSessionId: metadata.sessionId || attached.sessionId,
1852
+ error: 'request event crossed target sessions and requires proxy proof',
1853
+ });
1854
+ }
1855
+ }
1856
+ return { key, record };
1857
+ }
1858
+ if (candidates.length > 1 && exhaustiveCapture) {
1859
+ captureIssues.push({
1860
+ surface: 'network-correlation',
1861
+ requestId,
1862
+ sessionId: metadata.sessionId || attached.sessionId,
1863
+ candidates: candidates.map(([key]) => key),
1864
+ error: 'request ID matched multiple open target sessions',
1865
+ });
1866
+ }
1867
+ return { key: directKey, record: null };
1868
+ };
1869
+ const trackCaptureWork = (promise) => {
1870
+ pendingCaptureWork.add(promise);
1871
+ promise.finally(() => pendingCaptureWork.delete(promise));
1872
+ };
1873
+ const captureRequestBody = (record, metadata) => {
1874
+ if (!exhaustiveCapture || !record.request?.hasPostData) return;
1875
+ const work = (async () => {
1876
+ try {
1877
+ const contentType = Object.entries(record.request.headers || {})
1878
+ .find(([name]) => name.toLowerCase() === 'content-type')?.[1] || '';
1879
+ if (/^multipart\/form-data\b/i.test(contentType)) {
1880
+ throw new Error('multipart request body requires proxy evidence');
1881
+ }
1882
+ const entries = record.request.postDataEntries;
1883
+ let postData;
1884
+ let base64Encoded = false;
1885
+ if (
1886
+ Array.isArray(entries)
1887
+ && entries.length > 0
1888
+ && entries.every((entry) => typeof entry.bytes === 'string')
1889
+ ) {
1890
+ postData = Buffer.concat(
1891
+ entries.map((entry) => Buffer.from(entry.bytes, 'base64')),
1892
+ );
1893
+ } else if (record.request.postData !== undefined) {
1894
+ postData = record.request.postData;
1895
+ } else {
1896
+ const result = await client.call(
1897
+ 'Network.getRequestPostData',
1898
+ { requestId: record.requestId },
1899
+ { sessionId: metadata.sessionId || attached.sessionId },
1900
+ );
1901
+ postData = result.postData;
1902
+ base64Encoded = result.base64Encoded === true;
1903
+ }
1904
+ record.requestBody = await storePayload(
1905
+ outputDir,
1906
+ payloadState,
1907
+ 'request',
1908
+ postData,
1909
+ { base64Encoded },
1910
+ );
1911
+ } catch (error) {
1912
+ record.requestBodyError = error.message;
1913
+ captureIssues.push({
1914
+ surface: 'request-body',
1915
+ requestKey: record.key,
1916
+ error: error.message,
1917
+ });
1918
+ }
1919
+ })();
1920
+ trackCaptureWork(work);
1921
+ };
1922
+ const captureResponseBody = async (record, metadata) => {
1923
+ if (!record.response || !responseCanHaveBody(record)) return;
1924
+ const selected = exhaustiveCapture
1925
+ || bodyPatterns.some((pattern) => pattern.test(record.url || ''));
1926
+ if (!selected) return;
1927
+ try {
1928
+ const body = await client.call(
1929
+ 'Network.getResponseBody',
1930
+ { requestId: record.requestId },
1931
+ { sessionId: metadata.sessionId || attached.sessionId },
1932
+ );
1933
+ if (exhaustiveCapture) {
1934
+ record.responseBody = await storePayload(
1935
+ outputDir,
1936
+ payloadState,
1937
+ 'response',
1938
+ body.body,
1939
+ { base64Encoded: body.base64Encoded },
1940
+ );
1941
+ } else {
1942
+ record.response.body = body.body;
1943
+ record.response.base64Encoded = body.base64Encoded;
1944
+ }
1945
+ } catch (error) {
1946
+ if (exhaustiveCapture) {
1947
+ record.responseBodyError = error.message;
1948
+ captureIssues.push({
1949
+ surface: 'response-body',
1950
+ requestKey: record.key,
1951
+ error: error.message,
1952
+ });
1953
+ } else {
1954
+ record.response.bodyError = error.message;
1955
+ }
1956
+ }
1957
+ };
1958
+ const enableChildTarget = (event) => {
1959
+ if (!acceptCaptureEvents || !exhaustiveCapture) return;
1960
+ sessionTargets.set(event.sessionId, event.targetInfo || {});
1961
+ const work = (async () => {
1962
+ try {
1963
+ await client.call('Network.enable', {
1964
+ maxTotalBufferSize: 1_000_000_000,
1965
+ maxResourceBufferSize: 100_000_000,
1966
+ maxPostDataSize: 100_000_000,
1967
+ }, { sessionId: event.sessionId });
1968
+ await client.call(
1969
+ 'Network.setCacheDisabled',
1970
+ { cacheDisabled: true },
1971
+ { sessionId: event.sessionId },
1972
+ );
1973
+ const domainCalls = [
1974
+ client.call('Runtime.enable', {}, { sessionId: event.sessionId }),
1975
+ client.call('Debugger.enable', {
1976
+ maxScriptsCacheSize: 100_000_000,
1977
+ }, { sessionId: event.sessionId }),
1978
+ client.call('Log.enable', {}, { sessionId: event.sessionId }),
1979
+ client.call('Target.setAutoAttach', {
1980
+ autoAttach: true,
1981
+ waitForDebuggerOnStart: true,
1982
+ flatten: true,
1983
+ }, { sessionId: event.sessionId }),
1984
+ ];
1985
+ if (!String(event.targetInfo?.type || '').includes('worker')) {
1986
+ domainCalls.push(client.call('Page.enable', {}, { sessionId: event.sessionId }));
1987
+ }
1988
+ await Promise.all(domainCalls);
1989
+ } catch (error) {
1990
+ captureIssues.push({
1991
+ surface: 'child-target',
1992
+ targetId: event.targetInfo?.targetId,
1993
+ targetType: event.targetInfo?.type,
1994
+ error: error.message,
1995
+ });
1996
+ } finally {
1997
+ if (event.waitingForDebugger) {
1998
+ try {
1999
+ await client.call(
2000
+ 'Runtime.runIfWaitingForDebugger',
2001
+ {},
2002
+ { sessionId: event.sessionId },
2003
+ );
2004
+ } catch (error) {
2005
+ captureIssues.push({
2006
+ surface: 'child-target-resume',
2007
+ targetId: event.targetInfo?.targetId,
2008
+ targetType: event.targetInfo?.type,
2009
+ error: error.message,
2010
+ });
2011
+ }
2012
+ }
2013
+ }
2014
+ })();
2015
+ trackCaptureWork(work);
2016
+ };
567
2017
 
568
- client.on('Network.requestWillBeSent', (event) => {
2018
+ client.on('Target.attachedToTarget', enableChildTarget);
2019
+ client.on('Network.requestWillBeSent', (event, metadata) => {
2020
+ if (!acceptCaptureEvents) return;
2021
+ const key = requestKey(event.requestId, metadata);
569
2022
  if (event.redirectResponse) {
570
- const previous = requests.get(event.requestId);
2023
+ const previous = requests.get(key);
571
2024
  if (previous) {
572
- previous.response = {
573
- status: event.redirectResponse.status,
574
- statusText: event.redirectResponse.statusText,
575
- mimeType: event.redirectResponse.mimeType,
576
- protocol: event.redirectResponse.protocol,
577
- fromDiskCache: event.redirectResponse.fromDiskCache,
578
- fromServiceWorker: event.redirectResponse.fromServiceWorker,
579
- };
2025
+ previous.response = exhaustiveCapture
2026
+ ? event.redirectResponse
2027
+ : {
2028
+ status: event.redirectResponse.status,
2029
+ statusText: event.redirectResponse.statusText,
2030
+ mimeType: event.redirectResponse.mimeType,
2031
+ protocol: event.redirectResponse.protocol,
2032
+ fromDiskCache: event.redirectResponse.fromDiskCache,
2033
+ fromServiceWorker: event.redirectResponse.fromServiceWorker,
2034
+ };
580
2035
  previous.redirectedTo = event.request.url;
2036
+ if (exhaustiveCapture) previous.completedAt = new Date().toISOString();
581
2037
  network.push(previous);
582
- requests.delete(event.requestId);
2038
+ requests.delete(key);
583
2039
  }
584
2040
  }
585
- requests.set(event.requestId, {
2041
+ const record = {
586
2042
  requestId: event.requestId,
587
2043
  timestamp: event.timestamp,
588
2044
  wallTime: event.wallTime,
@@ -591,53 +2047,398 @@ async function runSubscriber(options) {
591
2047
  url: event.request.url,
592
2048
  postData: event.request.postData,
593
2049
  initiator: event.initiator,
2050
+ };
2051
+ if (exhaustiveCapture) {
2052
+ Object.assign(record, {
2053
+ key: `${key}:${++requestSequence}`,
2054
+ sessionId: metadata.sessionId || attached.sessionId,
2055
+ requestCdpSequence: metadata.cdpSequence,
2056
+ documentURL: event.documentURL,
2057
+ frameId: event.frameId,
2058
+ loaderId: event.loaderId,
2059
+ request: event.request,
2060
+ });
2061
+ }
2062
+ requests.set(key, record);
2063
+ captureRequestBody(record, metadata);
2064
+ });
2065
+ client.on('Network.requestWillBeSentExtraInfo', (event, metadata) => {
2066
+ if (!acceptCaptureEvents || !exhaustiveCapture) return;
2067
+ networkExtraInfo.push({
2068
+ type: 'request',
2069
+ sessionId: metadata.sessionId || attached.sessionId,
2070
+ requestId: event.requestId,
2071
+ cdpSequence: metadata.cdpSequence,
2072
+ event,
2073
+ });
2074
+ });
2075
+ client.on('Network.responseReceivedExtraInfo', (event, metadata) => {
2076
+ if (!acceptCaptureEvents || !exhaustiveCapture) return;
2077
+ networkExtraInfo.push({
2078
+ type: 'response',
2079
+ sessionId: metadata.sessionId || attached.sessionId,
2080
+ requestId: event.requestId,
2081
+ cdpSequence: metadata.cdpSequence,
2082
+ event,
594
2083
  });
595
2084
  });
596
- client.on('Network.responseReceived', (event) => {
597
- const record = requests.get(event.requestId) || {
2085
+ client.on('Network.responseReceived', (event, metadata) => {
2086
+ if (!acceptCaptureEvents) return;
2087
+ const resolved = resolveOpenRequest(event.requestId, metadata);
2088
+ const key = resolved.key;
2089
+ const record = resolved.record || {
598
2090
  requestId: event.requestId,
599
2091
  url: event.response.url,
600
2092
  };
601
- record.response = {
602
- status: event.response.status,
603
- statusText: event.response.statusText,
604
- mimeType: event.response.mimeType,
605
- protocol: event.response.protocol,
606
- fromDiskCache: event.response.fromDiskCache,
607
- fromServiceWorker: event.response.fromServiceWorker,
608
- };
609
- requests.set(event.requestId, record);
2093
+ if (exhaustiveCapture) {
2094
+ record.key ||= `${key}:${++requestSequence}`;
2095
+ record.method ||= '';
2096
+ record.sessionId ||= metadata.sessionId || attached.sessionId;
2097
+ record.responseSessionId = metadata.sessionId || attached.sessionId;
2098
+ record.responseCdpSequence = metadata.cdpSequence;
2099
+ record.response = event.response;
2100
+ } else {
2101
+ record.response = {
2102
+ status: event.response.status,
2103
+ statusText: event.response.statusText,
2104
+ mimeType: event.response.mimeType,
2105
+ protocol: event.response.protocol,
2106
+ fromDiskCache: event.response.fromDiskCache,
2107
+ fromServiceWorker: event.response.fromServiceWorker,
2108
+ };
2109
+ }
2110
+ if (exhaustiveCapture) record.responseTimestamp = event.timestamp;
2111
+ requests.set(key, record);
610
2112
  });
611
- client.on('Network.loadingFailed', (event) => {
612
- const record = requests.get(event.requestId) || { requestId: event.requestId };
613
- record.failure = {
614
- errorText: event.errorText,
615
- canceled: event.canceled,
616
- blockedReason: event.blockedReason,
2113
+ client.on('Network.loadingFailed', (event, metadata) => {
2114
+ if (!acceptCaptureEvents) return;
2115
+ const resolved = resolveOpenRequest(event.requestId, metadata);
2116
+ const key = resolved.key;
2117
+ const record = resolved.record || {
2118
+ requestId: event.requestId,
617
2119
  };
618
- requests.set(event.requestId, record);
2120
+ record.failure = exhaustiveCapture
2121
+ ? {
2122
+ ...event,
2123
+ cdpSequence: metadata.cdpSequence,
2124
+ sessionId: metadata.sessionId || attached.sessionId,
2125
+ }
2126
+ : {
2127
+ errorText: event.errorText,
2128
+ canceled: event.canceled,
2129
+ blockedReason: event.blockedReason,
2130
+ };
2131
+ if (exhaustiveCapture) {
2132
+ record.key ||= `${key}:${++requestSequence}`;
2133
+ if (record.response) {
2134
+ record.transferIncomplete = true;
2135
+ captureIssues.push({
2136
+ surface: 'response-transfer',
2137
+ requestKey: record.key,
2138
+ method: record.method,
2139
+ url: record.url,
2140
+ status: record.response.status,
2141
+ error: event.errorText || 'response transfer failed after headers',
2142
+ });
2143
+ }
2144
+ record.completedAt = new Date().toISOString();
2145
+ network.push(record);
2146
+ requests.delete(key);
2147
+ } else {
2148
+ requests.set(key, record);
2149
+ }
619
2150
  });
620
- client.on('Network.loadingFinished', (event) => {
2151
+ client.on('Network.loadingFinished', (event, metadata) => {
2152
+ if (!acceptCaptureEvents) return;
2153
+ const resolved = resolveOpenRequest(event.requestId, metadata);
2154
+ const key = resolved.key;
621
2155
  const work = (async () => {
622
- const record = requests.get(event.requestId);
2156
+ const record = resolved.record || requests.get(key);
623
2157
  if (!record) return;
624
- if (record.response && bodyPatterns.some((pattern) => pattern.test(record.url || ''))) {
625
- try {
626
- const body = await client.call('Network.getResponseBody', {
627
- requestId: event.requestId,
628
- });
629
- record.response.body = body.body;
630
- record.response.base64Encoded = body.base64Encoded;
631
- } catch (error) {
632
- record.response.bodyError = error.message;
633
- }
634
- }
2158
+ if (exhaustiveCapture) record.loadingFinished = event;
2159
+ await captureResponseBody(record, metadata);
2160
+ if (exhaustiveCapture) record.completedAt = new Date().toISOString();
635
2161
  network.push(record);
636
- requests.delete(event.requestId);
2162
+ requests.delete(key);
2163
+ })();
2164
+ trackCaptureWork(work);
2165
+ });
2166
+ client.on('Debugger.scriptParsed', (event, metadata) => {
2167
+ if (!acceptCaptureEvents) return;
2168
+ const script = {
2169
+ sequence: ++scriptSequence,
2170
+ sessionId: metadata.sessionId || attached.sessionId,
2171
+ ...event,
2172
+ };
2173
+ scripts.push(script);
2174
+ if (!exhaustiveCapture) return;
2175
+ const work = (async () => {
2176
+ try {
2177
+ const source = await client.call(
2178
+ 'Debugger.getScriptSource',
2179
+ { scriptId: event.scriptId },
2180
+ { sessionId: metadata.sessionId || attached.sessionId },
2181
+ );
2182
+ const base64Encoded = typeof source.bytecode === 'string';
2183
+ const value = base64Encoded ? source.bytecode : source.scriptSource || '';
2184
+ const buffer = base64Encoded
2185
+ ? Buffer.from(value, 'base64')
2186
+ : Buffer.from(value, 'utf8');
2187
+ const digest = sha256(buffer);
2188
+ const filename = `${String(script.sequence).padStart(6, '0')}-${digest.slice(0, 16)}${
2189
+ base64Encoded ? '.wasm' : '.js'
2190
+ }`;
2191
+ const relativePath = path.join('scripts', filename);
2192
+ await atomicWrite(path.join(outputDir, relativePath), buffer);
2193
+ script.source = {
2194
+ artifact: relativePath,
2195
+ bytes: buffer.length,
2196
+ sha256: digest,
2197
+ cdpBase64Encoded: base64Encoded,
2198
+ };
2199
+ } catch (error) {
2200
+ script.sourceError = error.message;
2201
+ captureIssues.push({
2202
+ surface: 'script-source',
2203
+ scriptId: event.scriptId,
2204
+ url: event.url,
2205
+ error: error.message,
2206
+ });
2207
+ }
637
2208
  })();
638
- pendingBodyReads.add(work);
639
- work.finally(() => pendingBodyReads.delete(work));
2209
+ trackCaptureWork(work);
640
2210
  });
2211
+ collectSourceMaps = async () => {
2212
+ if (!exhaustiveCapture || !captureAdvertisedSourceMaps) return;
2213
+ const collectionDeadline = Date.now() + 60_000;
2214
+ const grouped = new Map();
2215
+ for (const script of scripts.filter((item) => item.sourceMapURL)) {
2216
+ let resolved;
2217
+ try {
2218
+ const classification = classifySourceMapReference(script);
2219
+ if (classification.result) {
2220
+ script.sourceMapResult = classification.result;
2221
+ continue;
2222
+ }
2223
+ resolved = classification.resolvedURL;
2224
+ script.sourceMapResolvedURL = resolved;
2225
+ } catch (error) {
2226
+ script.sourceMapError = error.message;
2227
+ captureIssues.push({
2228
+ surface: 'source-map',
2229
+ scriptId: script.scriptId,
2230
+ url: script.url,
2231
+ sourceMapURL: script.sourceMapURL,
2232
+ error: error.message,
2233
+ });
2234
+ continue;
2235
+ }
2236
+ const key = `${script.sessionId}\0${resolved}`;
2237
+ const group = grouped.get(key) || {
2238
+ sessionId: script.sessionId,
2239
+ sourceMapUrl: resolved,
2240
+ scripts: [],
2241
+ };
2242
+ group.scripts.push(script);
2243
+ grouped.set(key, group);
2244
+ }
2245
+ let sourceMapSequence = 0;
2246
+ for (const group of grouped.values()) {
2247
+ const { sessionId, sourceMapUrl, scripts: matchingScripts } = group;
2248
+ const attemptedAt = new Date().toISOString();
2249
+ const sourceMapAttemptId = `${sessionId}:${attemptedAt}:${sourceMapUrl}`;
2250
+ try {
2251
+ const mapDeadline = Math.min(collectionDeadline, Date.now() + 15_000);
2252
+ const remaining = () => mapDeadline - Date.now();
2253
+ if (remaining() <= 0) throw new Error('source-map collection deadline reached');
2254
+ let buffer;
2255
+ let httpStatusCode = null;
2256
+ if (sourceMapUrl.startsWith('data:')) {
2257
+ const separator = sourceMapUrl.indexOf(',');
2258
+ if (separator === -1) throw new Error('malformed data URL source map');
2259
+ const metadata = sourceMapUrl.slice(5, separator);
2260
+ const payload = sourceMapUrl.slice(separator + 1);
2261
+ buffer = metadata.split(';').includes('base64')
2262
+ ? Buffer.from(payload, 'base64')
2263
+ : Buffer.from(decodeURIComponent(payload), 'utf8');
2264
+ } else {
2265
+ const targetInfo = sessionTargets.get(sessionId) || {};
2266
+ const workerTarget = String(targetInfo.type || '').includes('worker')
2267
+ || String(targetInfo.type || '').includes('worklet');
2268
+ if (workerTarget) {
2269
+ const loaded = await withTimeout(client.call('Runtime.evaluate', {
2270
+ expression: `(async () => {
2271
+ const controller = new AbortController();
2272
+ const timer = setTimeout(() => controller.abort(), 10000);
2273
+ try {
2274
+ const response = await fetch(${JSON.stringify(sourceMapUrl)}, {
2275
+ credentials: "include",
2276
+ cache: "no-store",
2277
+ signal: controller.signal,
2278
+ });
2279
+ const bytes = new Uint8Array(await response.arrayBuffer());
2280
+ let binary = "";
2281
+ for (let offset = 0; offset < bytes.length; offset += 32768) {
2282
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
2283
+ }
2284
+ return {
2285
+ ok: response.ok,
2286
+ status: response.status,
2287
+ body: btoa(binary),
2288
+ };
2289
+ } finally {
2290
+ clearTimeout(timer);
2291
+ }
2292
+ })()`,
2293
+ awaitPromise: true,
2294
+ returnByValue: true,
2295
+ }, { sessionId }), remaining(), 'worker source-map fetch');
2296
+ if (loaded.exceptionDetails) {
2297
+ throw new Error(
2298
+ loaded.exceptionDetails.exception?.description
2299
+ || loaded.exceptionDetails.text
2300
+ || 'worker source-map fetch failed',
2301
+ );
2302
+ }
2303
+ const resource = loaded.result?.value;
2304
+ httpStatusCode = resource?.status ?? null;
2305
+ if (!resource?.ok || typeof resource.body !== 'string') {
2306
+ throw new Error(
2307
+ `worker source-map load failed with HTTP ${httpStatusCode ?? 'unknown'}`,
2308
+ );
2309
+ }
2310
+ buffer = Buffer.from(resource.body, 'base64');
2311
+ } else {
2312
+ const frameTree = await withTimeout(client.call(
2313
+ 'Page.getFrameTree',
2314
+ {},
2315
+ { sessionId },
2316
+ ), remaining(), 'source-map frame lookup');
2317
+ const frameId = frameTree.frameTree?.frame?.id;
2318
+ if (!frameId) throw new Error('source-map target has no frame ID');
2319
+ const loaded = await withTimeout(client.call(
2320
+ 'Network.loadNetworkResource',
2321
+ {
2322
+ frameId,
2323
+ url: sourceMapUrl,
2324
+ options: {
2325
+ disableCache: true,
2326
+ includeCredentials: true,
2327
+ },
2328
+ },
2329
+ { sessionId },
2330
+ ), remaining(), 'source-map resource load');
2331
+ const resource = loaded.resource || {};
2332
+ httpStatusCode = resource.httpStatusCode ?? null;
2333
+ if (
2334
+ Number.isFinite(httpStatusCode)
2335
+ && (httpStatusCode < 200 || httpStatusCode >= 300)
2336
+ ) {
2337
+ throw new Error(`source-map load failed with HTTP ${httpStatusCode}`);
2338
+ }
2339
+ if (!resource.success || !resource.stream) {
2340
+ throw new Error(
2341
+ resource.netErrorName
2342
+ || `source-map load failed with HTTP ${httpStatusCode ?? 'unknown'}`,
2343
+ );
2344
+ }
2345
+ const chunks = [];
2346
+ try {
2347
+ while (true) {
2348
+ const chunk = await withTimeout(client.call(
2349
+ 'IO.read',
2350
+ { handle: resource.stream },
2351
+ { sessionId },
2352
+ ), remaining(), 'source-map stream read');
2353
+ chunks.push(chunk.base64Encoded
2354
+ ? Buffer.from(chunk.data || '', 'base64')
2355
+ : Buffer.from(chunk.data || '', 'utf8'));
2356
+ if (chunk.eof) break;
2357
+ }
2358
+ } finally {
2359
+ await withTimeout(client.call(
2360
+ 'IO.close',
2361
+ { handle: resource.stream },
2362
+ { sessionId },
2363
+ ), Math.max(1, Math.min(1_000, remaining())), 'source-map stream close');
2364
+ }
2365
+ buffer = Buffer.concat(chunks);
2366
+ }
2367
+ }
2368
+ const digest = sha256(buffer);
2369
+ const filename = `${String(++sourceMapSequence).padStart(6, '0')}-${
2370
+ digest.slice(0, 16)
2371
+ }.map`;
2372
+ const relativePath = path.join('source-maps', filename);
2373
+ await atomicWrite(path.join(outputDir, relativePath), buffer);
2374
+ const sourceMap = {
2375
+ url: sourceMapUrl,
2376
+ sessionId,
2377
+ targetType: sessionTargets.get(sessionId)?.type || null,
2378
+ artifact: relativePath,
2379
+ bytes: buffer.length,
2380
+ sha256: digest,
2381
+ httpStatusCode,
2382
+ };
2383
+ for (const script of matchingScripts) script.sourceMap = sourceMap;
2384
+ } catch (error) {
2385
+ const finishedAt = new Date().toISOString();
2386
+ for (const script of matchingScripts) {
2387
+ script.sourceMapError = error.message;
2388
+ script.sourceMapAttempt = {
2389
+ id: sourceMapAttemptId,
2390
+ startedAt: attemptedAt,
2391
+ finishedAt,
2392
+ error: error.message,
2393
+ };
2394
+ }
2395
+ captureIssues.push({
2396
+ surface: 'source-map',
2397
+ sourceMapAttemptId,
2398
+ sourceMapURL: sourceMapUrl,
2399
+ error: error.message,
2400
+ });
2401
+ }
2402
+ }
2403
+ };
2404
+
2405
+ const domainEnables = [
2406
+ client.call('Page.enable'),
2407
+ client.call('Runtime.enable'),
2408
+ client.call('Network.enable', {
2409
+ maxTotalBufferSize: 1_000_000_000,
2410
+ maxResourceBufferSize: 100_000_000,
2411
+ maxPostDataSize: 100_000_000,
2412
+ }),
2413
+ ];
2414
+ if (exhaustiveCapture) {
2415
+ await client.call(
2416
+ 'Target.setDiscoverTargets',
2417
+ { discover: true },
2418
+ { browserCommand: true },
2419
+ );
2420
+ domainEnables.push(
2421
+ client.call('Debugger.enable', {
2422
+ maxScriptsCacheSize: 100_000_000,
2423
+ }),
2424
+ client.call('Log.enable'),
2425
+ client.call('Performance.enable'),
2426
+ client.call('Security.enable'),
2427
+ client.call('ServiceWorker.enable'),
2428
+ client.call('DOM.enable'),
2429
+ client.call('Accessibility.enable'),
2430
+ client.call('Target.setAutoAttach', {
2431
+ autoAttach: true,
2432
+ waitForDebuggerOnStart: true,
2433
+ flatten: true,
2434
+ }),
2435
+ );
2436
+ }
2437
+ await Promise.all(domainEnables);
2438
+ if (exhaustiveCapture) {
2439
+ await client.call('Network.setCacheDisabled', { cacheDisabled: true });
2440
+ }
2441
+ captureInitialized = true;
641
2442
 
642
2443
  if (cookieJar) {
643
2444
  cookieSource = parseCookieSource(
@@ -657,10 +2458,195 @@ async function runSubscriber(options) {
657
2458
  }
658
2459
  return resolved;
659
2460
  };
2461
+ const captureCheckpoint = async (name) => {
2462
+ if (!exhaustiveCapture) {
2463
+ throw new Error('checkpoints require captureMode="exhaustive"');
2464
+ }
2465
+ let safeName;
2466
+ try {
2467
+ safeName = safeCheckpointName(name);
2468
+ } catch (error) {
2469
+ captureIssues.push({
2470
+ surface: 'checkpoint',
2471
+ name,
2472
+ error: error.message,
2473
+ });
2474
+ throw error;
2475
+ }
2476
+ if (checkpointNames.has(safeName)) {
2477
+ const error = new Error(`checkpoint name already used: ${safeName}`);
2478
+ captureIssues.push({
2479
+ surface: 'checkpoint',
2480
+ name: safeName,
2481
+ error: error.message,
2482
+ });
2483
+ throw error;
2484
+ }
2485
+ checkpointNames.add(safeName);
2486
+ const observedAt = new Date().toISOString();
2487
+ const attempt = {
2488
+ name: safeName,
2489
+ observedAt,
2490
+ status: 'started',
2491
+ };
2492
+ checkpoints.push(attempt);
2493
+ try {
2494
+ const pageStateExpression = `(async () => {
2495
+ const capture = async operation => {
2496
+ try {
2497
+ return { ok: true, value: await operation() };
2498
+ } catch (error) {
2499
+ return {
2500
+ ok: false,
2501
+ error: {
2502
+ name: error?.name || "Error",
2503
+ message: error?.message || String(error),
2504
+ },
2505
+ };
2506
+ }
2507
+ };
2508
+ const storage = source => {
2509
+ const result = {};
2510
+ for (let index = 0; index < source.length; index += 1) {
2511
+ const key = source.key(index);
2512
+ result[key] = source.getItem(key);
2513
+ }
2514
+ return result;
2515
+ };
2516
+ return {
2517
+ observedAt: new Date().toISOString(),
2518
+ href: location.href,
2519
+ origin: location.origin,
2520
+ title: document.title,
2521
+ readyState: document.readyState,
2522
+ html: document.documentElement?.outerHTML || "",
2523
+ documentCookie: await capture(() => document.cookie),
2524
+ localStorage: await capture(() => storage(localStorage)),
2525
+ sessionStorage: await capture(() => storage(sessionStorage)),
2526
+ indexedDatabases: await capture(() =>
2527
+ typeof indexedDB.databases === "function" ? indexedDB.databases() : []
2528
+ ),
2529
+ cacheNames: await capture(() =>
2530
+ "caches" in globalThis ? caches.keys() : []
2531
+ ),
2532
+ scripts: [...document.scripts].map(script => ({
2533
+ src: script.src,
2534
+ type: script.type,
2535
+ integrity: script.integrity,
2536
+ crossOrigin: script.crossOrigin,
2537
+ text: script.src ? "" : script.textContent,
2538
+ })),
2539
+ stylesheets: [...document.styleSheets].map(sheet => ({
2540
+ href: sheet.href,
2541
+ disabled: sheet.disabled,
2542
+ media: sheet.media?.mediaText || "",
2543
+ })),
2544
+ forms: [...document.forms].map(form => ({
2545
+ action: form.action,
2546
+ method: form.method,
2547
+ elements: [...form.elements].map(element => ({
2548
+ tag: element.tagName,
2549
+ type: element.type,
2550
+ name: element.name,
2551
+ value: element.value,
2552
+ checked: element.checked,
2553
+ disabled: element.disabled,
2554
+ required: element.required,
2555
+ validity: element.validity ? {
2556
+ valid: element.validity.valid,
2557
+ valueMissing: element.validity.valueMissing,
2558
+ typeMismatch: element.validity.typeMismatch,
2559
+ patternMismatch: element.validity.patternMismatch,
2560
+ customError: element.validity.customError,
2561
+ } : null,
2562
+ validationMessage: element.validationMessage,
2563
+ })),
2564
+ })),
2565
+ performanceEntries: performance.getEntries().map(entry =>
2566
+ typeof entry.toJSON === "function" ? entry.toJSON() : {
2567
+ name: entry.name,
2568
+ entryType: entry.entryType,
2569
+ startTime: entry.startTime,
2570
+ duration: entry.duration,
2571
+ }
2572
+ ),
2573
+ };
2574
+ })()`;
2575
+ const [
2576
+ frameTree,
2577
+ navigationHistory,
2578
+ resourceTree,
2579
+ domSnapshot,
2580
+ accessibilityTree,
2581
+ performanceMetrics,
2582
+ cookies,
2583
+ pageState,
2584
+ mhtml,
2585
+ ] = await Promise.all([
2586
+ client.call('Page.getFrameTree'),
2587
+ client.call('Page.getNavigationHistory'),
2588
+ client.call('Page.getResourceTree'),
2589
+ client.call('DOMSnapshot.captureSnapshot', {
2590
+ computedStyles: [],
2591
+ includePaintOrder: true,
2592
+ includeDOMRects: true,
2593
+ includeBlendedBackgroundColors: true,
2594
+ }),
2595
+ client.call('Accessibility.getFullAXTree'),
2596
+ client.call('Performance.getMetrics'),
2597
+ client.call('Network.getAllCookies'),
2598
+ evaluate(client, pageStateExpression),
2599
+ client.call('Page.captureSnapshot', { format: 'mhtml' }),
2600
+ ]);
2601
+ const mhtmlBuffer = Buffer.from(mhtml.data || '', 'utf8');
2602
+ const mhtmlRelativePath = path.join('checkpoints', `${safeName}.mhtml`);
2603
+ await atomicWrite(path.join(outputDir, mhtmlRelativePath), mhtmlBuffer);
2604
+ const checkpoint = {
2605
+ name: safeName,
2606
+ observedAt,
2607
+ frameTree,
2608
+ navigationHistory,
2609
+ resourceTree,
2610
+ domSnapshot,
2611
+ accessibilityTree,
2612
+ performanceMetrics,
2613
+ cookies,
2614
+ pageState,
2615
+ mhtml: {
2616
+ artifact: mhtmlRelativePath,
2617
+ bytes: mhtmlBuffer.length,
2618
+ sha256: sha256(mhtmlBuffer),
2619
+ },
2620
+ };
2621
+ const relativePath = path.join('checkpoints', `${safeName}.json`);
2622
+ await atomicWrite(
2623
+ path.join(outputDir, relativePath),
2624
+ `${JSON.stringify(checkpoint, null, 2)}\n`,
2625
+ );
2626
+ Object.assign(attempt, {
2627
+ status: 'captured',
2628
+ artifact: relativePath,
2629
+ mhtml: checkpoint.mhtml,
2630
+ });
2631
+ return checkpoint;
2632
+ } catch (error) {
2633
+ Object.assign(attempt, {
2634
+ status: 'failed',
2635
+ error: error.message,
2636
+ });
2637
+ captureIssues.push({
2638
+ surface: 'checkpoint',
2639
+ name: safeName,
2640
+ error: error.message,
2641
+ });
2642
+ throw error;
2643
+ }
2644
+ };
660
2645
  const context = {
661
2646
  apiVersion: SUBSCRIBER_API,
662
2647
  subscriberPath,
663
2648
  outputDir,
2649
+ captureMode,
664
2650
  network,
665
2651
  requests,
666
2652
  delay,
@@ -673,6 +2659,7 @@ async function runSubscriber(options) {
673
2659
  pressKey: (key, code, virtualKeyCode) => pressKey(client, key, code, virtualKeyCode),
674
2660
  pressTab: () => pressKey(client, 'Tab', 'Tab', 9),
675
2661
  markAuthenticated: () => { authenticated = true; },
2662
+ checkpoint: captureCheckpoint,
676
2663
  artifactPath,
677
2664
  writeArtifact: async (name, value) => {
678
2665
  const payload = Buffer.isBuffer(value)
@@ -723,18 +2710,47 @@ async function runSubscriber(options) {
723
2710
  primaryError = error;
724
2711
  throw error;
725
2712
  } finally {
2713
+ const rememberCleanupError = (error) => {
2714
+ if (!primaryError && !cleanupError) cleanupError = error;
2715
+ else console.error(`headless capture warning: ${error.message}`);
2716
+ };
2717
+ const drainCaptureWork = async (phase, timeoutMs, reportTimeout) => {
2718
+ const deadline = Date.now() + timeoutMs;
2719
+ while (pendingCaptureWork.size && Date.now() < deadline) {
2720
+ const remaining = Math.max(1, deadline - Date.now());
2721
+ await Promise.race([
2722
+ Promise.allSettled([...pendingCaptureWork]),
2723
+ delay(Math.min(250, remaining)),
2724
+ ]);
2725
+ }
2726
+ if (!pendingCaptureWork.size) return true;
2727
+ if (reportTimeout) {
2728
+ const error = new Error(
2729
+ `${phase} timed out with ${pendingCaptureWork.size} capture operations pending`,
2730
+ );
2731
+ if (exhaustiveCapture) {
2732
+ captureIssues.push({
2733
+ surface: 'capture-drain',
2734
+ phase,
2735
+ pending: pendingCaptureWork.size,
2736
+ error: error.message,
2737
+ });
2738
+ }
2739
+ rememberCleanupError(error);
2740
+ }
2741
+ return false;
2742
+ };
726
2743
  if (client) {
727
- await Promise.allSettled([...pendingBodyReads]);
728
- for (const record of requests.values()) network.push(record);
2744
+ await drainCaptureWork('pre-boundary settle', 5_000, false);
729
2745
  try {
730
- await atomicWrite(
731
- path.join(outputDir, 'network.json'),
732
- `${JSON.stringify(network, null, 2)}\n`,
733
- );
2746
+ await collectSourceMaps();
734
2747
  } catch (error) {
735
- if (!primaryError) cleanupError = error;
736
- else console.error(`headless capture warning: ${error.message}`);
2748
+ captureIssues.push({
2749
+ surface: 'source-map-collection',
2750
+ error: error.message,
2751
+ });
737
2752
  }
2753
+ await drainCaptureWork('source-map settle', 5_000, false);
738
2754
  if (authenticated && cookieJar && cookieSource && cookieExport) {
739
2755
  try {
740
2756
  const result = await client.call('Network.getAllCookies');
@@ -752,14 +2768,322 @@ async function runSubscriber(options) {
752
2768
  }
753
2769
  await atomicWrite(cookieJar, serializeCookies(cookieSource.format, cookies));
754
2770
  } catch (error) {
755
- if (!primaryError) cleanupError = error;
756
- else console.error(`headless cookie export warning: ${error.message}`);
2771
+ if (exhaustiveCapture) {
2772
+ captureIssues.push({
2773
+ surface: 'cookie-export',
2774
+ error: error.message,
2775
+ });
2776
+ }
2777
+ rememberCleanupError(error);
2778
+ }
2779
+ }
2780
+ if (primaryTargetId) {
2781
+ try {
2782
+ const closed = await withTimeout(client.call(
2783
+ 'Target.closeTarget',
2784
+ { targetId: primaryTargetId },
2785
+ { browserCommand: true },
2786
+ ), 5_000, 'capture target close');
2787
+ if (closed.success !== true) {
2788
+ throw new Error('capture target close returned success=false');
2789
+ }
2790
+ await delay(250);
2791
+ } catch (error) {
2792
+ if (exhaustiveCapture) {
2793
+ captureIssues.push({
2794
+ surface: 'capture-boundary',
2795
+ targetId: primaryTargetId,
2796
+ error: error.message,
2797
+ });
2798
+ }
2799
+ rememberCleanupError(error);
757
2800
  }
758
2801
  }
2802
+ await drainCaptureWork('post-boundary settle', 15_000, true);
2803
+ acceptCaptureEvents = false;
759
2804
  client.close();
2805
+ await drainCaptureWork('post-client-close settle', 2_000, true);
2806
+ }
2807
+ try {
2808
+ await stopProcess(browser);
2809
+ } catch (error) {
2810
+ captureIssues.push({
2811
+ surface: 'browser-shutdown',
2812
+ error: error.message,
2813
+ });
2814
+ rememberCleanupError(error);
2815
+ }
2816
+ if (!stderrClosed) {
2817
+ fs.closeSync(stderrFd);
2818
+ stderrClosed = true;
2819
+ }
2820
+ if (client) {
2821
+ for (const record of requests.values()) {
2822
+ record.captureEndedWhileOpen = true;
2823
+ network.push(record);
2824
+ }
2825
+ requests.clear();
2826
+ }
2827
+ if (proxy) {
2828
+ try {
2829
+ proxySummary = await finalizeProxyCapture(
2830
+ proxy,
2831
+ configured.proxyShutdownTimeoutMs || 15_000,
2832
+ );
2833
+ const harDocument = JSON.parse(await fsp.readFile(proxy.paths.harPath, 'utf8'));
2834
+ const harEntries = proxyHarEntries(harDocument);
2835
+ const exactEntries = await proxyExactEntries(
2836
+ proxy.paths.exactDir,
2837
+ proxySummary.exactCapture,
2838
+ );
2839
+ proxyReconciliation = {
2840
+ network: await reconcileNetworkWithProxyHar(
2841
+ outputDir,
2842
+ payloadState,
2843
+ network,
2844
+ harEntries,
2845
+ exactEntries,
2846
+ captureIssues,
2847
+ ),
2848
+ sourceMaps: await reconcileSourceMapsWithProxyHar(
2849
+ outputDir,
2850
+ payloadState,
2851
+ scripts,
2852
+ harEntries,
2853
+ exactEntries,
2854
+ captureIssues,
2855
+ ),
2856
+ };
2857
+ } catch (error) {
2858
+ captureIssues.push({
2859
+ surface: 'proxy-finalization',
2860
+ error: error.message,
2861
+ });
2862
+ rememberCleanupError(error);
2863
+ } finally {
2864
+ restoreProxyTerminationHandlers();
2865
+ }
2866
+ }
2867
+ try {
2868
+ await atomicWrite(
2869
+ path.join(outputDir, 'network.json'),
2870
+ `${JSON.stringify(network, null, 2)}\n`,
2871
+ );
2872
+ if (exhaustiveCapture) {
2873
+ await Promise.all([
2874
+ atomicWrite(
2875
+ path.join(outputDir, 'network-extra-info.json'),
2876
+ `${JSON.stringify(networkExtraInfo, null, 2)}\n`,
2877
+ ),
2878
+ atomicWrite(
2879
+ path.join(outputDir, 'scripts', 'index.json'),
2880
+ `${JSON.stringify(scripts, null, 2)}\n`,
2881
+ ),
2882
+ ]);
2883
+ }
2884
+ } catch (error) {
2885
+ captureIssues.push({
2886
+ surface: 'artifact-finalization',
2887
+ artifact: 'capture indexes',
2888
+ error: error.message,
2889
+ });
2890
+ rememberCleanupError(error);
2891
+ }
2892
+ if (journal) {
2893
+ try {
2894
+ journalSummary = journal.close();
2895
+ } catch (error) {
2896
+ captureIssues.push({
2897
+ surface: 'cdp-journal',
2898
+ error: error.message,
2899
+ });
2900
+ rememberCleanupError(error);
2901
+ }
2902
+ }
2903
+ if (exhaustiveCapture) {
2904
+ try {
2905
+ const responseBodyGaps = network
2906
+ .filter((record) => (
2907
+ record.response
2908
+ && responseCanHaveBody(record)
2909
+ && !record.responseBody
2910
+ ))
2911
+ .map((record) => ({
2912
+ key: record.key,
2913
+ method: record.method,
2914
+ url: record.url,
2915
+ status: record.response?.status,
2916
+ error: record.responseBodyError || 'response body was not captured',
2917
+ }));
2918
+ const requestBodyGaps = network
2919
+ .filter((record) => (
2920
+ record.request?.hasPostData
2921
+ && !record.requestBody
2922
+ ))
2923
+ .map((record) => ({
2924
+ key: record.key,
2925
+ method: record.method,
2926
+ url: record.url,
2927
+ error: record.requestBodyError || 'request body was not captured',
2928
+ }));
2929
+ const redirectBodyGaps = network
2930
+ .filter((record) => redirectCanHaveBody(record) && !record.redirectResponseBody)
2931
+ .map((record) => ({
2932
+ key: record.key,
2933
+ method: record.method,
2934
+ url: record.url,
2935
+ status: record.response?.status,
2936
+ redirectedTo: record.redirectedTo,
2937
+ error: 'CDP reuses the request ID before exposing the redirect response body',
2938
+ }));
2939
+ const scriptSourceGaps = scripts
2940
+ .filter((script) => !script.source)
2941
+ .map((script) => ({
2942
+ sessionId: script.sessionId,
2943
+ scriptId: script.scriptId,
2944
+ url: script.url,
2945
+ error: script.sourceError || 'script source was not captured',
2946
+ }));
2947
+ const sourceMapGaps = captureAdvertisedSourceMaps
2948
+ ? scripts
2949
+ .filter((script) => (
2950
+ script.sourceMapURL
2951
+ && !script.sourceMap
2952
+ && !script.sourceMapResult
2953
+ ))
2954
+ .map((script) => ({
2955
+ sessionId: script.sessionId,
2956
+ scriptId: script.scriptId,
2957
+ url: script.url,
2958
+ sourceMapURL: script.sourceMapURL,
2959
+ error: script.sourceMapError || 'advertised source map was not captured',
2960
+ }))
2961
+ : [];
2962
+ const openRequests = network
2963
+ .filter((record) => record.captureEndedWhileOpen)
2964
+ .map((record) => ({
2965
+ key: record.key,
2966
+ method: record.method,
2967
+ url: record.url,
2968
+ }));
2969
+ const failedTransfers = network
2970
+ .filter((record) => (
2971
+ record.failure
2972
+ && record.response
2973
+ && record.proxyCompletion?.completed !== true
2974
+ ))
2975
+ .map((record) => ({
2976
+ key: record.key,
2977
+ method: record.method,
2978
+ url: record.url,
2979
+ status: record.response.status,
2980
+ failure: record.failure,
2981
+ proxyTransfer: record.proxyTransfer || null,
2982
+ }));
2983
+ const unresolvedIssues = captureIssues.filter((issue) => !issue.resolved);
2984
+ const resolvedIssues = captureIssues.filter((issue) => issue.resolved);
2985
+ const complete = captureInitialized
2986
+ && !primaryError
2987
+ && Boolean(journalSummary?.messages)
2988
+ && (!captureProxyTraffic || Boolean(proxySummary && proxyReconciliation))
2989
+ && unresolvedIssues.length === 0
2990
+ && responseBodyGaps.length === 0
2991
+ && requestBodyGaps.length === 0
2992
+ && redirectBodyGaps.length === 0
2993
+ && scriptSourceGaps.length === 0
2994
+ && sourceMapGaps.length === 0
2995
+ && openRequests.length === 0
2996
+ && failedTransfers.length === 0;
2997
+ const manifest = {
2998
+ apiVersion: SUBSCRIBER_API,
2999
+ mode: captureMode,
3000
+ subscriber: subscriberPath,
3001
+ startedAt: captureStartedAt,
3002
+ finishedAt: new Date().toISOString(),
3003
+ captureInitialized,
3004
+ complete,
3005
+ browser: {
3006
+ binary: browserBinary,
3007
+ version: browserVersion || null,
3008
+ disposableProfile: true,
3009
+ transport: 'remote-debugging-pipe',
3010
+ cacheDisabled: true,
3011
+ },
3012
+ proxy: captureProxyTraffic
3013
+ ? {
3014
+ ...(proxySummary || { enabled: false }),
3015
+ reconciliation: proxyReconciliation || null,
3016
+ }
3017
+ : { enabled: false },
3018
+ journal: journalSummary || null,
3019
+ network: {
3020
+ records: network.length,
3021
+ payloadArtifacts: payloadState.sequence,
3022
+ responseBodyGaps,
3023
+ requestBodyGaps,
3024
+ redirectBodyGaps,
3025
+ openAtCaptureEnd: openRequests,
3026
+ failedTransfers,
3027
+ },
3028
+ scripts: {
3029
+ parsed: scripts.length,
3030
+ sourceArtifacts: scripts.filter((script) => script.source).length,
3031
+ sourceMapArtifacts: new Set(
3032
+ scripts
3033
+ .filter((script) => script.sourceMap)
3034
+ .map((script) => script.sourceMap.artifact),
3035
+ ).size,
3036
+ sourceMapReferences: scripts
3037
+ .filter((script) => script.sourceMapURL)
3038
+ .map((script) => ({
3039
+ url: script.url,
3040
+ sourceMapURL: script.sourceMapURL,
3041
+ resolvedURL: script.sourceMapResolvedURL || null,
3042
+ result: script.sourceMap
3043
+ ? { kind: 'captured-map', ...script.sourceMap }
3044
+ : script.sourceMapResult || null,
3045
+ })),
3046
+ scriptSourceGaps,
3047
+ sourceMapGaps,
3048
+ },
3049
+ checkpoints,
3050
+ issues: unresolvedIssues,
3051
+ resolvedIssues,
3052
+ observedBoundary: {
3053
+ included: [
3054
+ 'all CDP commands, responses, and events for the isolated browser sessions',
3055
+ 'obtainable HTTP request and response payloads after browser protocol decoding',
3056
+ 'byte-exact HTTP request and response bodies plus terminal proxy flow state',
3057
+ 'loaded script sources and configured captures of advertised source maps',
3058
+ 'subscriber-requested page checkpoints and browser stderr',
3059
+ ],
3060
+ excluded: [
3061
+ 'raw TLS records and transport packets',
3062
+ 'server-side and service-to-service activity not exposed to the browser',
3063
+ ],
3064
+ },
3065
+ runError: primaryError ? primaryError.message : null,
3066
+ };
3067
+ await atomicWrite(
3068
+ path.join(outputDir, 'capture-manifest.json'),
3069
+ `${JSON.stringify(manifest, null, 2)}\n`,
3070
+ );
3071
+ if (requireCompleteCapture && !complete) {
3072
+ rememberCleanupError(new Error(
3073
+ `exhaustive capture incomplete: ${unresolvedIssues.length} unresolved issues, `
3074
+ + `${responseBodyGaps.length} response-body gaps, `
3075
+ + `${requestBodyGaps.length} request-body gaps, `
3076
+ + `${redirectBodyGaps.length} redirect-body gaps, `
3077
+ + `${scriptSourceGaps.length} script-source gaps, `
3078
+ + `${sourceMapGaps.length} source-map gaps, `
3079
+ + `${openRequests.length} open requests, `
3080
+ + `${failedTransfers.length} failed transfers; see capture-manifest.json`,
3081
+ ));
3082
+ }
3083
+ } catch (error) {
3084
+ rememberCleanupError(error);
3085
+ }
760
3086
  }
761
- await stopProcess(browser);
762
- fs.closeSync(stderrFd);
763
3087
  await fsp.rm(profileDir, { recursive: true, force: true });
764
3088
  if (!primaryError && cleanupError) throw cleanupError;
765
3089
  if (
@@ -786,8 +3110,8 @@ async function cmdHeadless(argv) {
786
3110
  run: 'run(context, subscriberConfig) -> JSON-serializable result',
787
3111
  context: [
788
3112
  'cdp', 'evaluate', 'waitFor', 'click', 'pressKey', 'pressTab',
789
- 'navigate', 'screenshot', 'writeArtifact', 'markAuthenticated',
790
- 'network', 'requests', 'delay',
3113
+ 'navigate', 'screenshot', 'checkpoint', 'writeArtifact',
3114
+ 'markAuthenticated', 'captureMode', 'network', 'requests', 'delay',
791
3115
  ],
792
3116
  }, null, 2));
793
3117
  return;
@@ -802,13 +3126,25 @@ async function cmdHeadless(argv) {
802
3126
  module.exports = {
803
3127
  SUBSCRIBER_API,
804
3128
  CdpClient,
3129
+ CdpJournal,
805
3130
  atomicWrite,
3131
+ buildMitmproxyArgs,
3132
+ classifySourceMapReference,
806
3133
  cmdHeadless,
3134
+ computeCertificateSpkiHash,
3135
+ finalizeProxyCapture,
807
3136
  headlessHelp,
808
3137
  parseCookieSource,
809
3138
  parseNetscapeCookieJar,
810
3139
  parseRuntimeArgs,
811
3140
  prepareOutputDir,
3141
+ proxyBrowserArgs,
3142
+ proxyExactEntries,
3143
+ proxyHarEntries,
3144
+ reconcileNetworkWithProxyHar,
3145
+ reconcileSourceMapsWithProxyHar,
3146
+ responseCanHaveBody,
3147
+ startProxyCapture,
812
3148
  runSubscriber,
813
3149
  serializeCookies,
814
3150
  stopProcess,