@torrent-tv/proxy 2.55.14 → 2.57.0

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,406 +1,784 @@
1
- /**
2
- * @file Automatic packet witness for a send queue that stops draining.
3
- *
4
- * Roadmap item 10, occurrence 2026-08-24 (`research/dead-channel-2026-08-24.md`):
5
- * the proxy counted bytes as sent that never reached the viewer's SCTP stack,
6
- * and every counter above the wire reported success for 88 minutes. The two
7
- * candidate causes separate by ONE look at the packets repeated duplicate
8
- * SACKs naming a missing TSN with no retransmission (usrsctp retransmit
9
- * defect) versus SACKs advertising `a_rwnd=0` with no gaps (receiver stopped
10
- * reading). Occurrences are rare and unpredictable, so the witness fires by
11
- * itself: a send queue wedged longer than ~30 s starts a bounded tcpdump on
12
- * the WebRTC UDP port filtered to that session's remote address, writes a few
13
- * small rotating files, and stops. Where no tcpdump exists the whole thing
14
- * degrades to a single log line.
15
- *
16
- * Bounded three ways so it can never cost more than an episode is worth: the
17
- * process is killed after {@linkcode WITNESS_CAPTURE_SECONDS} plus grace; the
18
- * ring keeps at most {@linkcode WITNESS_RING_FILES} files of
19
- * {@linkcode WITNESS_ROTATE_SECONDS} each; and one capture runs at a time,
20
- * with a cooldown before the next. Captures land beside the core dumps
21
- * (`--state-dir`) and are pruned at startup the same way.
22
- */
23
-
24
- import { spawn } from "node:child_process";
25
- import { readdir, rm, stat } from "node:fs/promises";
26
- import os from "node:os";
27
- import path from "node:path";
28
-
29
- import { dumpsToRemove } from "./core-dumps.js";
30
-
31
- /** Per-packet capture length. Small: headers are what the signatures need. */
32
- export const WITNESS_SNAPLEN_BYTES = 128;
33
-
34
- /** One rotation step of the ring, in seconds. */
35
- export const WITNESS_ROTATE_SECONDS = 30;
36
-
37
- /** How many rotation steps stay on disk (30 s × 4 = 120 s of evidence). */
38
- export const WITNESS_RING_FILES = 4;
39
-
40
- /** Total wall-clock bound on one capture, seconds. */
41
- export const WITNESS_CAPTURE_SECONDS = WITNESS_ROTATE_SECONDS * WITNESS_RING_FILES;
42
-
43
- /** Extra time before the SIGKILL fallback lands on a hanging tcpdump. */
44
- export const WITNESS_KILL_GRACE_MS = 5_000;
45
-
46
- /** Minimum spacing between captures, whatever the reason for them. */
47
- export const WITNESS_COOLDOWN_MS = 10 * 60_000;
48
-
49
- /** How many old captures survive at startup, newest first. */
50
- export const WITNESS_CAPTURES_KEPT = 4;
51
-
52
- /**
53
- * The remote endpoint of a transport snapshot, already structured.
54
- *
55
- * @typedef {Object} WitnessRemoteEndpoint
56
- * @property {string} address - IP literal (may carry a `%zone` suffix).
57
- * @property {number} port
58
- */
59
-
60
- /**
61
- * What the watcher hands over when a wedge crosses the capture threshold.
62
- *
63
- * @typedef {Object} WitnessTrigger
64
- * @property {string} sessionId
65
- * @property {string} tag - Session id, first 8 characters.
66
- * @property {string} label - Data channel label ("proxy", "proxy-control").
67
- * @property {WitnessRemoteEndpoint | null} remote
68
- * @property {number} queuedBytes
69
- * @property {number} stuckForMs
70
- */
71
-
72
- /**
73
- * Strip a zone suffix and keep only IPv4/IPv6 literals.
74
- *
75
- * The address travels into a tcpdump BPF filter argument. The child is spawned
76
- * as an argv array (no shell), so injection is not reachable, but a garbage or
77
- * hostname value would produce a capture of nothing — rejected instead, so the
78
- * log can say why nothing was written.
79
- *
80
- * @param {unknown} raw - Address as libdatachannel reports it.
81
- * @returns {string | null} A clean literal, or null when not usable.
82
- */
83
- export function normalizeRemoteAddress(raw) {
84
- if (typeof raw !== "string") {
85
- return null;
86
- }
87
- const zoneFree = raw.replace(/%.*$/, "");
88
- if (zoneFree.length === 0 || zoneFree.length > 45) {
89
- return null;
90
- }
91
- const ipv4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
92
- // Hex groups and at most one "::" compression enough to keep hostnames,
93
- // decimal-octet junk and shell metacharacters out of the filter.
94
- const ipv6 = /^(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}$/;
95
- if (ipv4.test(zoneFree) || (zoneFree.includes(":") && ipv6.test(zoneFree))) {
96
- return zoneFree;
97
- }
98
- return null;
99
- }
100
-
101
- /**
102
- * The tcpdump command line for one bounded capture.
103
- *
104
- * `-i any` covers hosts where the UDP mux socket is not on a named interface;
105
- * `-n` keeps DNS out of the hot path; `-S` prints absolute sequence numbers so
106
- * duplicate SACKs across file rotations compare equal by eye.
107
- *
108
- * @param {Object} parts
109
- * @param {string} parts.host - Validated IP literal.
110
- * @param {number} parts.port - The WebRTC UDP port.
111
- * @param {string} parts.filePrefix - Path prefix; tcpdump appends timestamps.
112
- * @param {number} [parts.snaplen] - Bytes per packet to store.
113
- * @param {number} [parts.rotateSeconds]
114
- * @param {number} [parts.ringFiles]
115
- * @returns {string[]}
116
- */
117
- export function buildTcpdumpArgs({
118
- host,
119
- port,
120
- filePrefix,
121
- snaplen = WITNESS_SNAPLEN_BYTES,
122
- rotateSeconds = WITNESS_ROTATE_SECONDS,
123
- ringFiles = WITNESS_RING_FILES
124
- }) {
125
- return [
126
- "-n",
127
- "-S",
128
- "-s",
129
- String(snaplen),
130
- "-i",
131
- "any",
132
- "-w",
133
- filePrefix,
134
- "-G",
135
- String(rotateSeconds),
136
- "-W",
137
- String(ringFiles),
138
- "udp",
139
- "and",
140
- "host",
141
- host,
142
- "and",
143
- "port",
144
- String(port)
145
- ];
146
- }
147
-
148
- /**
149
- * Whether a new capture may start right now.
150
- *
151
- * Pure, so the gating rule is testable without clocks or processes: never two
152
- * at once, and none within the cooldown of the previous one. `lastStartedAt`
153
- * of 0 means this process has not captured yet.
154
- *
155
- * @param {{ running: boolean, lastStartedAt: number, now?: number, cooldownMs?: number }} state
156
- * @returns {boolean}
157
- */
158
- export function shouldStartCapture({ running, lastStartedAt, now = Date.now(), cooldownMs = WITNESS_COOLDOWN_MS }) {
159
- if (running) {
160
- return false;
161
- }
162
- return lastStartedAt <= 0 || now - lastStartedAt >= cooldownMs;
163
- }
164
-
165
- /**
166
- * Whether a file name is a capture this module wrote (including the
167
- * timestamp-suffixed rotations tcpdump appends under `-G`).
168
- *
169
- * @param {string} name
170
- * @returns {boolean}
171
- */
172
- export function isWitnessCapture(name) {
173
- return typeof name === "string" && /^packet-witness\.[^/\\]+\.pcap/.test(name);
174
- }
175
-
176
- /**
177
- * Delete all but the newest few captures in `dir`.
178
- *
179
- * Mirrors `pruneCoreDumps`: best-effort, never fatal, one summary line.
180
- *
181
- * @param {string} dir
182
- * @param {number} [keep]
183
- * @returns {Promise<void>}
184
- */
185
- export async function pruneWitnessCaptures(dir, keep = WITNESS_CAPTURES_KEPT) {
186
- if (typeof dir !== "string" || dir.length === 0) {
187
- return;
188
- }
189
- /** @type {Array<{ name: string, writtenAt: number, bytes: number }>} */
190
- const captures = [];
191
- try {
192
- for (const name of await readdir(dir)) {
193
- if (!isWitnessCapture(name)) {
194
- continue;
195
- }
196
- try {
197
- const info = await stat(path.join(dir, name));
198
- if (info.isFile()) {
199
- captures.push({ name, writtenAt: info.mtimeMs, bytes: info.size });
200
- }
201
- } catch {
202
- // silent-ok: vanished between listing and reading.
203
- }
204
- }
205
- } catch {
206
- return; // No such directory, or unreadable. Nothing to tidy.
207
- }
208
- if (captures.length === 0) {
209
- return;
210
- }
211
- const doomed = dumpsToRemove(captures, keep);
212
- const freed = captures
213
- .filter((capture) => doomed.includes(capture.name))
214
- .reduce((total, capture) => total + capture.bytes, 0);
215
- for (const name of doomed) {
216
- try {
217
- await rm(path.join(dir, name), { force: true });
218
- } catch {
219
- // silent-ok: best effort, retried at the next start.
220
- }
221
- }
222
- const keptBytes = captures
223
- .filter((capture) => !doomed.includes(capture.name))
224
- .reduce((total, capture) => total + capture.bytes, 0);
225
- if (freed > 0 || captures.length > keep) {
226
- logLine(
227
- `packet witness: ${captures.length} capture(s) present, keeping the newest ${Math.min(keep, captures.length)}, ` +
228
- `removed ${doomed.length} (${(freed / 1024).toFixed(1)} KB), keeping ${(keptBytes / 1024).toFixed(1)} KB`
229
- );
230
- }
231
- }
232
-
233
- /**
234
- * The logger handed to {@linkcode createPacketWitness}; module-level so the
235
- * pruner can speak without an options bag threaded everywhere.
236
- *
237
- * @type {(message: string) => void}
238
- */
239
- let logLine = () => {};
240
-
241
- /**
242
- * Create the witness.
243
- *
244
- * @param {Object} options
245
- * @param {(message: string) => void} options.log - Log sink (the shared logger).
246
- * @param {string} [options.dir] - Where captures go; empty means os.tmpdir().
247
- * @param {number} options.port - The WebRTC UDP port to filter on.
248
- * @returns {{ dir: string, maybeCapture: (trigger: WitnessTrigger) => boolean }}
249
- */
250
- export function createPacketWitness({ log, dir = "", port }) {
251
- logLine = typeof log === "function" ? log : logLine;
252
- const resolvedDir = typeof dir === "string" && dir.length > 0 ? dir : os.tmpdir();
253
-
254
- /** @type {{ running: boolean, lastStartedAt: number, availability: "unknown" | "yes" | "no" }} */
255
- const state = { running: false, lastStartedAt: 0, availability: "unknown" };
256
-
257
- /**
258
- * Ask whether tcpdump exists at all — once per process, whichever way it
259
- * answers. A host without it gets exactly one log line, ever.
260
- *
261
- * @returns {Promise<boolean>}
262
- */
263
- const probeAvailability = () =>
264
- new Promise((resolve) => {
265
- let settled = false;
266
- const done = (value) => {
267
- if (!settled) {
268
- settled = true;
269
- resolve(value);
270
- }
271
- };
272
- try {
273
- const probe = spawn("tcpdump", ["--version"], { stdio: "ignore" });
274
- probe.on("error", () => done(false));
275
- probe.on("spawn", () => done(true));
276
- probe.on("close", () => done(true));
277
- } catch {
278
- done(false);
279
- }
280
- });
281
-
282
- /**
283
- * Run one bounded capture and report what it wrote.
284
- *
285
- * @param {WitnessTrigger} trigger
286
- * @param {string} address - Validated remote IP literal.
287
- * @returns {Promise<void>}
288
- */
289
- const runCapture = async (trigger, address) => {
290
- const prefix = path.join(
291
- resolvedDir,
292
- `packet-witness.${trigger.tag}.${Math.floor(Date.now() / 1000)}.pcap`
293
- );
294
- const args = buildTcpdumpArgs({ host: address, port, filePrefix: prefix });
295
- logLine(
296
- `packet witness: capturing ${WITNESS_CAPTURE_SECONDS}s of udp port ${port} ${address} ` +
297
- `(session ${trigger.tag}, "${trigger.label}" queue ${trigger.queuedBytes}B wedged ` +
298
- `${Math.round(trigger.stuckForMs / 1000)}s) ${prefix}`
299
- );
300
- await new Promise((resolve) => {
301
- /** @type {ReturnType<typeof setTimeout> | null} */
302
- let killer = null;
303
- /** @type {NodeJS.Timeout | null} */
304
- let hardKill = null;
305
- let child;
306
- try {
307
- child = spawn("tcpdump", args, { stdio: "ignore" });
308
- } catch (error) {
309
- logLine(`packet witness: could not start tcpdump: ${error?.message ?? error}`);
310
- resolve();
311
- return;
312
- }
313
- const finish = () => {
314
- if (killer) {
315
- clearTimeout(killer);
316
- killer = null;
317
- }
318
- if (hardKill) {
319
- clearTimeout(hardKill);
320
- hardKill = null;
321
- }
322
- resolve();
323
- };
324
- child.on("error", (error) => {
325
- state.availability = "no";
326
- logLine(`packet witness: tcpdump failed to run: ${error?.message ?? error}`);
327
- finish();
328
- });
329
- child.on("close", (code, signal) => {
330
- logLine(
331
- `packet witness: capture ended${signal ? ` (${signal})` : ` (exit ${code ?? "?"})`}`
332
- );
333
- finish();
334
- });
335
- killer = setTimeout(() => {
336
- try { child.kill("SIGTERM"); } catch { /* already gone */ }
337
- hardKill = setTimeout(() => {
338
- try { child.kill("SIGKILL"); } catch { /* already gone */ }
339
- }, WITNESS_KILL_GRACE_MS);
340
- }, WITNESS_CAPTURE_SECONDS * 1000);
341
- });
342
- // Say what landed on disk, so whoever reads the log later knows whether
343
- // the evidence exists without listing the directory themselves.
344
- try {
345
- const names = (await readdir(resolvedDir)).filter((name) => isWitnessCapture(name));
346
- const mine = [];
347
- for (const name of names) {
348
- if (!name.startsWith(path.basename(prefix))) {
349
- continue;
350
- }
351
- try {
352
- const info = await stat(path.join(resolvedDir, name));
353
- mine.push(`${name} ${(info.size / 1024).toFixed(1)} KB`);
354
- } catch { /* gone between listing and reading */ }
355
- }
356
- logLine(`packet witness: wrote ${mine.length} file(s): ${mine.join(", ") || "none"}`);
357
- } catch {
358
- logLine("packet witness: could not list the capture directory");
359
- }
360
- };
361
-
362
- /**
363
- * Start a capture for this trigger, if the rules allow one.
364
- *
365
- * @param {WitnessTrigger} trigger
366
- * @returns {boolean} True when a capture actually started.
367
- */
368
- const maybeCapture = (trigger) => {
369
- const address = normalizeRemoteAddress(trigger?.remote?.address);
370
- const portNumber = trigger?.remote?.port;
371
- if (!address || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
372
- return false;
373
- }
374
- if (!shouldStartCapture(state)) {
375
- return false;
376
- }
377
- state.running = true;
378
- state.lastStartedAt = Date.now();
379
- const startedAt = state.lastStartedAt;
380
- void (async () => {
381
- try {
382
- if (state.availability === "unknown") {
383
- state.availability = (await probeAvailability()) ? "yes" : "no";
384
- }
385
- if (state.availability === "no") {
386
- logLine(
387
- "packet witness: unavailable — no tcpdump on this host; " +
388
- "the stuck-queue log lines remain the only evidence here"
389
- );
390
- return;
391
- }
392
- await runCapture(trigger, address);
393
- } finally {
394
- state.running = false;
395
- // Keep the requested spacing honest even when the capture ended early.
396
- const earliestNext = startedAt + WITNESS_COOLDOWN_MS;
397
- if (state.lastStartedAt < earliestNext) {
398
- state.lastStartedAt = earliestNext;
399
- }
400
- }
401
- })();
402
- return true;
403
- };
404
-
405
- return { dir: resolvedDir, maybeCapture };
406
- }
1
+ /**
2
+ * @file Packet witness for the delivery freeze: a ring that is always running,
3
+ * and a tail that outlasts the sender's own retransmission timeout.
4
+ *
5
+ * Roadmap item 11. Two captures taken by the earlier version of this file, read
6
+ * on 2026-08-26 (`research/delivery-freeze-sender-silent-2026-08-26.md`), place
7
+ * the failure: while a channel held 67 MB, the proxy put NO packet larger than
8
+ * 89 bytes of UDP payload on the wire for 28 s, twice, in two separate
9
+ * episodes. The receiver never had anything to drop, the path carried STUN and
10
+ * the browser's own requests throughout, and `usrsctp_sendv` refused every byte
11
+ * for 54 minutes. What those captures could NOT show is what happened at the
12
+ * ONSET, because they began 30 s after the queue was already declared stuck,
13
+ * and what happens beyond 28 s, because that is where they stopped.
14
+ *
15
+ * So the capture is in two halves now.
16
+ *
17
+ * The RING runs the whole time a data channel is open, size-bounded and
18
+ * wrapping, filtered to the WebRTC UDP port. It costs a rotating file on disk
19
+ * and nothing else, and it means the seconds BEFORE a freeze are already
20
+ * recorded when the freeze is noticed. On a wedge its files are copied aside
21
+ * before the wrap can reach them.
22
+ *
23
+ * The TAIL then records the wedged session's own 5-tuple for
24
+ * {@linkcode WITNESS_TAIL_SECONDS}, which is three times usrsctp's maximum
25
+ * retransmission timeout. That length is what turns "no zero-window probe in
26
+ * the 28 s we watched" into a statement about the sender: a stalled SCTP sender
27
+ * whose peer advertises a zero window MUST probe once per timeout, and the
28
+ * timeout cannot exceed {@linkcode WITNESS_RTO_CEILING_SECONDS}. Silence across
29
+ * three of those is not a sampling gap.
30
+ *
31
+ * Bounded so it can never cost more than an episode is worth: the ring is
32
+ * capped in bytes and deleted when the last channel closes, the tail process is
33
+ * killed after its window plus grace, one tail runs at a time with a cooldown,
34
+ * and old captures are pruned at startup like core dumps.
35
+ */
36
+
37
+ import { spawn } from "node:child_process";
38
+ import { copyFile, readdir, rename, rm, stat } from "node:fs/promises";
39
+ import os from "node:os";
40
+ import path from "node:path";
41
+
42
+ import { dumpsToRemove } from "./core-dumps.js";
43
+
44
+ /** Per-packet capture length. Small: headers are what the signatures need. */
45
+ export const WITNESS_SNAPLEN_BYTES = 128;
46
+
47
+ /**
48
+ * usrsctp's maximum retransmission timeout, seconds (its `RTO.max` default).
49
+ *
50
+ * Not ours to choose: it is the longest a stalled SCTP sender may wait before
51
+ * it must try again, so it is the shortest window in which silence means
52
+ * anything at all.
53
+ */
54
+ export const WITNESS_RTO_CEILING_SECONDS = 60;
55
+
56
+ /**
57
+ * How long the tail capture records the wedged session, seconds.
58
+ *
59
+ * Three retransmission timeouts. One would leave the answer to a single
60
+ * scheduling accident; three is silence that has had three chances to break.
61
+ */
62
+ export const WITNESS_TAIL_SECONDS = WITNESS_RTO_CEILING_SECONDS * 3;
63
+
64
+ /** Megabytes per ring file before tcpdump rotates to the next. */
65
+ export const WITNESS_RING_FILE_MB = 16;
66
+
67
+ /** How many ring files wrap around (16 MB × 4 = 64 MB of history). */
68
+ export const WITNESS_RING_FILES = 4;
69
+
70
+ /** Megabytes per tail file. A wedged session emits a few packets a second. */
71
+ export const WITNESS_TAIL_FILE_MB = 8;
72
+
73
+ /** How many tail files may be written before tcpdump stops on its own. */
74
+ export const WITNESS_TAIL_FILES = 2;
75
+
76
+ /** Extra time before the SIGKILL fallback lands on a hanging tcpdump. */
77
+ export const WITNESS_KILL_GRACE_MS = 5_000;
78
+
79
+ /** Minimum spacing between tail captures, whatever the reason for them. */
80
+ export const WITNESS_COOLDOWN_MS = 10 * 60_000;
81
+
82
+ /** How many old captures survive at startup, newest first. */
83
+ export const WITNESS_CAPTURES_KEPT = 8;
84
+
85
+ /** Base name of the rolling ring, before tcpdump appends its file number. */
86
+ export const WITNESS_RING_BASENAME = "packet-witness-ring.pcap";
87
+
88
+ /**
89
+ * The remote endpoint of a transport snapshot, already structured.
90
+ *
91
+ * @typedef {Object} WitnessRemoteEndpoint
92
+ * @property {string} address - IP literal (may carry a `%zone` suffix).
93
+ * @property {number} port
94
+ */
95
+
96
+ /**
97
+ * What the watcher hands over when a wedge crosses the capture threshold.
98
+ *
99
+ * @typedef {Object} WitnessTrigger
100
+ * @property {string} sessionId
101
+ * @property {string} tag - Session id, first 8 characters.
102
+ * @property {string} label - Data channel label ("proxy", "proxy-control").
103
+ * @property {WitnessRemoteEndpoint | null} remote
104
+ * @property {number} queuedBytes
105
+ * @property {number} stuckForMs
106
+ */
107
+
108
+ /**
109
+ * Strip a zone suffix and keep only IPv4/IPv6 literals.
110
+ *
111
+ * The address travels into a tcpdump BPF filter argument. The child is spawned
112
+ * as an argv array (no shell), so injection is not reachable, but a garbage or
113
+ * hostname value would produce a capture of nothing — rejected instead, so the
114
+ * log can say why nothing was written.
115
+ *
116
+ * @param {unknown} raw - Address as libdatachannel reports it.
117
+ * @returns {string | null} A clean literal, or null when not usable.
118
+ */
119
+ export function normalizeRemoteAddress(raw) {
120
+ if (typeof raw !== "string") {
121
+ return null;
122
+ }
123
+ const zoneFree = raw.replace(/%.*$/, "");
124
+ if (zoneFree.length === 0 || zoneFree.length > 45) {
125
+ return null;
126
+ }
127
+ const ipv4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
128
+ // Hex groups and at most one "::" compression — enough to keep hostnames,
129
+ // decimal-octet junk and shell metacharacters out of the filter.
130
+ const ipv6 = /^(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}$/;
131
+ if (ipv4.test(zoneFree) || (zoneFree.includes(":") && ipv6.test(zoneFree))) {
132
+ return zoneFree;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * The tcpdump command line for a size-rotated capture.
139
+ *
140
+ * `-i any` covers hosts where the UDP mux socket is not on a named interface;
141
+ * `-n` keeps DNS out of the hot path; `-S` prints absolute sequence numbers so
142
+ * duplicate SACKs across file rotations compare equal by eye.
143
+ *
144
+ * Rotation is by SIZE, not by time, and that is a correction rather than a
145
+ * preference. `-G <seconds>` with `-W <count>` and a file name carrying no
146
+ * strftime field makes every rotation write the SAME name: the four files the
147
+ * previous version believed it was keeping were one file overwritten four
148
+ * times, which is why both field captures hold 28 s and not the intended 120.
149
+ * `-C <megabytes>` with `-W <count>` appends a number to the name and wraps
150
+ * around, which is the ring this needs — and a byte bound is the right bound
151
+ * anyway, because the rate varies by two orders of magnitude between a wedged
152
+ * session and a healthy burst.
153
+ *
154
+ * @param {Object} parts
155
+ * @param {string} [parts.host] - Validated IP literal; omitted captures every peer.
156
+ * @param {number} parts.port - The WebRTC UDP port.
157
+ * @param {string} parts.filePrefix - Path prefix; tcpdump appends the file number.
158
+ * @param {number} [parts.snaplen] - Bytes per packet to store.
159
+ * @param {number} [parts.fileMegabytes]
160
+ * @param {number} [parts.files]
161
+ * @returns {string[]}
162
+ */
163
+ export function buildTcpdumpArgs({
164
+ host = "",
165
+ port,
166
+ filePrefix,
167
+ snaplen = WITNESS_SNAPLEN_BYTES,
168
+ fileMegabytes = WITNESS_RING_FILE_MB,
169
+ files = WITNESS_RING_FILES
170
+ }) {
171
+ const filter = ["udp", "and", "port", String(port)];
172
+ if (host) {
173
+ filter.push("and", "host", host);
174
+ }
175
+ return [
176
+ "-n",
177
+ "-S",
178
+ "-s",
179
+ String(snaplen),
180
+ "-i",
181
+ "any",
182
+ "-w",
183
+ filePrefix,
184
+ "-C",
185
+ String(fileMegabytes),
186
+ "-W",
187
+ String(files),
188
+ ...filter
189
+ ];
190
+ }
191
+
192
+ /**
193
+ * Whether a new capture may start right now.
194
+ *
195
+ * Pure, so the gating rule is testable without clocks or processes: never two
196
+ * at once, and none within the cooldown of the previous one. `lastStartedAt`
197
+ * of 0 means this process has not captured yet.
198
+ *
199
+ * @param {{ running: boolean, lastStartedAt: number, now?: number, cooldownMs?: number }} state
200
+ * @returns {boolean}
201
+ */
202
+ export function shouldStartCapture({ running, lastStartedAt, now = Date.now(), cooldownMs = WITNESS_COOLDOWN_MS }) {
203
+ if (running) {
204
+ return false;
205
+ }
206
+ return lastStartedAt <= 0 || now - lastStartedAt >= cooldownMs;
207
+ }
208
+
209
+ /**
210
+ * Whether a file name is a capture this module wrote (including the
211
+ * timestamp-suffixed rotations tcpdump appends under `-G`).
212
+ *
213
+ * @param {string} name
214
+ * @returns {boolean}
215
+ */
216
+ export function isWitnessCapture(name) {
217
+ return typeof name === "string" && /^packet-witness\.[^/\\]+\.pcap/.test(name);
218
+ }
219
+
220
+ /**
221
+ * Whether a file name is one of the rolling ring's own files.
222
+ *
223
+ * The ring is scratch, not evidence: it wraps, and it is deleted when the last
224
+ * channel closes. Only the copies taken at a wedge are kept, and those are
225
+ * named so that {@link isWitnessCapture} and therefore the pruner — sees
226
+ * them and the ring's own files are left alone.
227
+ *
228
+ * @param {string} name
229
+ * @returns {boolean}
230
+ */
231
+ export function isWitnessRingFile(name) {
232
+ return typeof name === "string" && name.startsWith(WITNESS_RING_BASENAME) && !name.includes("/") && !name.includes("\\");
233
+ }
234
+
235
+ /**
236
+ * Delete all but the newest few captures in `dir`.
237
+ *
238
+ * Mirrors `pruneCoreDumps`: best-effort, never fatal, one summary line.
239
+ *
240
+ * @param {string} dir
241
+ * @param {number} [keep]
242
+ * @returns {Promise<void>}
243
+ */
244
+ export async function pruneWitnessCaptures(dir, keep = WITNESS_CAPTURES_KEPT) {
245
+ if (typeof dir !== "string" || dir.length === 0) {
246
+ return;
247
+ }
248
+ /** @type {Array<{ name: string, writtenAt: number, bytes: number }>} */
249
+ const captures = [];
250
+ try {
251
+ for (const name of await readdir(dir)) {
252
+ if (!isWitnessCapture(name)) {
253
+ continue;
254
+ }
255
+ try {
256
+ const info = await stat(path.join(dir, name));
257
+ if (info.isFile()) {
258
+ captures.push({ name, writtenAt: info.mtimeMs, bytes: info.size });
259
+ }
260
+ } catch {
261
+ // silent-ok: vanished between listing and reading.
262
+ }
263
+ }
264
+ } catch {
265
+ return; // No such directory, or unreadable. Nothing to tidy.
266
+ }
267
+ if (captures.length === 0) {
268
+ return;
269
+ }
270
+ const doomed = dumpsToRemove(captures, keep);
271
+ const freed = captures
272
+ .filter((capture) => doomed.includes(capture.name))
273
+ .reduce((total, capture) => total + capture.bytes, 0);
274
+ for (const name of doomed) {
275
+ try {
276
+ await rm(path.join(dir, name), { force: true });
277
+ } catch {
278
+ // silent-ok: best effort, retried at the next start.
279
+ }
280
+ }
281
+ const keptBytes = captures
282
+ .filter((capture) => !doomed.includes(capture.name))
283
+ .reduce((total, capture) => total + capture.bytes, 0);
284
+ if (freed > 0 || captures.length > keep) {
285
+ logLine(
286
+ `packet witness: ${captures.length} capture(s) present, keeping the newest ${Math.min(keep, captures.length)}, ` +
287
+ `removed ${doomed.length} (${(freed / 1024).toFixed(1)} KB), keeping ${(keptBytes / 1024).toFixed(1)} KB`
288
+ );
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Turn ring files left by a previous process into evidence, at startup.
294
+ *
295
+ * The ring is scratch while a process lives, but a process that was KILLED —
296
+ * which the crash family of roadmap item 1 does regularly, seven times in a
297
+ * fortnight leaves behind the last seconds it recorded, and those seconds
298
+ * contain the death. Renaming them under a name the pruner recognises keeps
299
+ * them; without this the next viewer's first channel would delete them before
300
+ * anyone had looked.
301
+ *
302
+ * @param {string} dir
303
+ * @returns {Promise<string[]>} Names of the files adopted.
304
+ */
305
+ export async function adoptOrphanRingFiles(dir) {
306
+ if (typeof dir !== "string" || dir.length === 0) {
307
+ return [];
308
+ }
309
+ /** @type {string[]} */
310
+ const adopted = [];
311
+ let names;
312
+ try {
313
+ names = (await readdir(dir)).filter((name) => isWitnessRingFile(name)).sort();
314
+ } catch {
315
+ return adopted;
316
+ }
317
+ if (names.length === 0) {
318
+ return adopted;
319
+ }
320
+ const stampSeconds = Math.floor(Date.now() / 1000);
321
+ for (const name of names) {
322
+ const suffix = name.slice(WITNESS_RING_BASENAME.length) || "0";
323
+ const target = `packet-witness.orphan.${stampSeconds}.before${suffix}.pcap`;
324
+ try {
325
+ await rename(path.join(dir, name), path.join(dir, target));
326
+ adopted.push(target);
327
+ } catch {
328
+ // silent-ok: unreadable or already gone.
329
+ }
330
+ }
331
+ if (adopted.length > 0) {
332
+ logLine(
333
+ `packet witness: ${adopted.length} ring file(s) survived the previous process and were kept ` +
334
+ `as ${adopted.join(", ")} — whatever ended it is in them`
335
+ );
336
+ }
337
+ return adopted;
338
+ }
339
+
340
+ /**
341
+ * The logger handed to {@linkcode createPacketWitness}; module-level so the
342
+ * pruner can speak without an options bag threaded everywhere.
343
+ *
344
+ * @type {(message: string) => void}
345
+ */
346
+ let logLine = () => {};
347
+
348
+ /**
349
+ * Create the witness.
350
+ *
351
+ * @param {Object} options
352
+ * @param {(message: string) => void} options.log - Log sink (the shared logger).
353
+ * @param {string} [options.dir] - Where captures go; empty means os.tmpdir().
354
+ * @param {number} options.port - The WebRTC UDP port to filter on.
355
+ * @param {typeof spawn} [options.spawnProcess] - Seam for tests; defaults to node's spawn.
356
+ * @returns {{
357
+ * dir: string,
358
+ * maybeCapture: (trigger: WitnessTrigger) => boolean,
359
+ * holdRing: () => void,
360
+ * releaseRing: () => void
361
+ * }}
362
+ */
363
+ export function createPacketWitness({ log, dir = "", port, spawnProcess = spawn }) {
364
+ logLine = typeof log === "function" ? log : logLine;
365
+ const resolvedDir = typeof dir === "string" && dir.length > 0 ? dir : os.tmpdir();
366
+
367
+ /** @type {{ running: boolean, lastStartedAt: number, availability: "unknown" | "yes" | "no" }} */
368
+ const state = { running: false, lastStartedAt: 0, availability: "unknown" };
369
+
370
+ /**
371
+ * Ask whether tcpdump exists at all once per process, whichever way it
372
+ * answers. A host without it gets exactly one log line, ever.
373
+ *
374
+ * @returns {Promise<boolean>}
375
+ */
376
+ const probeAvailability = () =>
377
+ new Promise((resolve) => {
378
+ let settled = false;
379
+ const done = (value) => {
380
+ if (!settled) {
381
+ settled = true;
382
+ resolve(value);
383
+ }
384
+ };
385
+ try {
386
+ const probe = spawnProcess("tcpdump", ["--version"], { stdio: "ignore" });
387
+ probe.on("error", () => done(false));
388
+ probe.on("spawn", () => done(true));
389
+ probe.on("close", () => done(true));
390
+ } catch {
391
+ done(false);
392
+ }
393
+ });
394
+
395
+ /**
396
+ * Keep the ring's history: stop it, copy its files, start it again.
397
+ *
398
+ * This is the half of the evidence the earlier version never had — the
399
+ * seconds BEFORE the freeze. Stopping first is not tidiness: tcpdump buffers,
400
+ * so the newest packets are only on disk once it has been asked to finish,
401
+ * and the file it is currently writing is the one that holds the onset. The
402
+ * gap this leaves is a fraction of a second, and the tail capture that
403
+ * follows covers everything after it.
404
+ *
405
+ * @param {WitnessTrigger} trigger
406
+ * @param {number} stampSeconds - Shared with the tail, so the pair sorts together.
407
+ * @returns {Promise<string[]>} Names of the copies that landed.
408
+ */
409
+ const preserveRing = async (trigger, stampSeconds) => {
410
+ /** @type {string[]} */
411
+ const kept = [];
412
+ ring.preserving = true;
413
+ try {
414
+ await stopRingProcess();
415
+ let names;
416
+ try {
417
+ names = (await readdir(resolvedDir)).filter((name) => isWitnessRingFile(name)).sort();
418
+ } catch {
419
+ return kept;
420
+ }
421
+ for (const name of names) {
422
+ const suffix = name.slice(WITNESS_RING_BASENAME.length) || "0";
423
+ const target = `packet-witness.${trigger.tag}.${stampSeconds}.before${suffix}.pcap`;
424
+ try {
425
+ await copyFile(path.join(resolvedDir, name), path.join(resolvedDir, target));
426
+ kept.push(target);
427
+ } catch {
428
+ // silent-ok: nothing to copy, or it vanished under us.
429
+ }
430
+ }
431
+ return kept;
432
+ } finally {
433
+ ring.preserving = false;
434
+ // Back to recording, unless everyone has gone in the meantime.
435
+ if (ring.holders > 0) {
436
+ await startRingProcess();
437
+ } else {
438
+ await clearRingFiles();
439
+ }
440
+ }
441
+ };
442
+
443
+ /**
444
+ * Run one bounded capture and report what it wrote.
445
+ *
446
+ * @param {WitnessTrigger} trigger
447
+ * @param {string} address - Validated remote IP literal.
448
+ * @param {number} stampSeconds
449
+ * @returns {Promise<void>}
450
+ */
451
+ const runCapture = async (trigger, address, stampSeconds) => {
452
+ const prefix = path.join(
453
+ resolvedDir,
454
+ `packet-witness.${trigger.tag}.${stampSeconds}.tail.pcap`
455
+ );
456
+ const args = buildTcpdumpArgs({
457
+ host: address,
458
+ port,
459
+ filePrefix: prefix,
460
+ fileMegabytes: WITNESS_TAIL_FILE_MB,
461
+ files: WITNESS_TAIL_FILES
462
+ });
463
+ logLine(
464
+ `packet witness: capturing ${WITNESS_TAIL_SECONDS}s of udp port ${port} ↔ ${address} ` +
465
+ `(session ${trigger.tag}, "${trigger.label}" queue ${trigger.queuedBytes}B wedged ` +
466
+ `${Math.round(trigger.stuckForMs / 1000)}s; ${WITNESS_TAIL_SECONDS}s is three times ` +
467
+ `usrsctp's ${WITNESS_RTO_CEILING_SECONDS}s retransmission ceiling, so a zero-window ` +
468
+ `probe cannot hide inside it) → ${prefix}`
469
+ );
470
+ await new Promise((resolve) => {
471
+ /** @type {ReturnType<typeof setTimeout> | null} */
472
+ let killer = null;
473
+ /** @type {NodeJS.Timeout | null} */
474
+ let hardKill = null;
475
+ let child;
476
+ try {
477
+ child = spawnProcess("tcpdump", args, { stdio: "ignore" });
478
+ } catch (error) {
479
+ logLine(`packet witness: could not start tcpdump: ${error?.message ?? error}`);
480
+ resolve();
481
+ return;
482
+ }
483
+ const finish = () => {
484
+ if (killer) {
485
+ clearTimeout(killer);
486
+ killer = null;
487
+ }
488
+ if (hardKill) {
489
+ clearTimeout(hardKill);
490
+ hardKill = null;
491
+ }
492
+ resolve();
493
+ };
494
+ child.on("error", (error) => {
495
+ state.availability = "no";
496
+ logLine(`packet witness: tcpdump failed to run: ${error?.message ?? error}`);
497
+ finish();
498
+ });
499
+ child.on("close", (code, signal) => {
500
+ logLine(
501
+ `packet witness: capture ended${signal ? ` (${signal})` : ` (exit ${code ?? "?"})`}`
502
+ );
503
+ finish();
504
+ });
505
+ killer = setTimeout(() => {
506
+ try { child.kill("SIGTERM"); } catch { /* already gone */ }
507
+ hardKill = setTimeout(() => {
508
+ try { child.kill("SIGKILL"); } catch { /* already gone */ }
509
+ }, WITNESS_KILL_GRACE_MS);
510
+ }, WITNESS_TAIL_SECONDS * 1000);
511
+ });
512
+ // Say what landed on disk, so whoever reads the log later knows whether
513
+ // the evidence exists without listing the directory themselves.
514
+ try {
515
+ const names = (await readdir(resolvedDir)).filter((name) => isWitnessCapture(name));
516
+ const mine = [];
517
+ for (const name of names) {
518
+ if (!name.startsWith(path.basename(prefix))) {
519
+ continue;
520
+ }
521
+ try {
522
+ const info = await stat(path.join(resolvedDir, name));
523
+ mine.push(`${name} ${(info.size / 1024).toFixed(1)} KB`);
524
+ } catch { /* gone between listing and reading */ }
525
+ }
526
+ logLine(`packet witness: wrote ${mine.length} file(s): ${mine.join(", ") || "none"}`);
527
+ } catch {
528
+ logLine("packet witness: could not list the capture directory");
529
+ }
530
+ };
531
+
532
+ /**
533
+ * Start a capture for this trigger, if the rules allow one.
534
+ *
535
+ * @param {WitnessTrigger} trigger
536
+ * @returns {boolean} True when a capture actually started.
537
+ */
538
+ const maybeCapture = (trigger) => {
539
+ const address = normalizeRemoteAddress(trigger?.remote?.address);
540
+ const portNumber = trigger?.remote?.port;
541
+ if (!address || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
542
+ return false;
543
+ }
544
+ if (!shouldStartCapture(state)) {
545
+ return false;
546
+ }
547
+ state.running = true;
548
+ state.lastStartedAt = Date.now();
549
+ const startedAt = state.lastStartedAt;
550
+ void (async () => {
551
+ try {
552
+ if (state.availability === "unknown") {
553
+ state.availability = (await probeAvailability()) ? "yes" : "no";
554
+ }
555
+ if (state.availability === "no") {
556
+ logLine(
557
+ "packet witness: unavailable — no tcpdump on this host; " +
558
+ "the stuck-queue log lines remain the only evidence here"
559
+ );
560
+ return;
561
+ }
562
+ const stampSeconds = Math.floor(Date.now() / 1000);
563
+ const before = await preserveRing(trigger, stampSeconds);
564
+ logLine(
565
+ before.length > 0
566
+ ? `packet witness: kept ${before.length} ring file(s) from before the wedge: ${before.join(", ")}`
567
+ : "packet witness: no ring history to keep — the ring was not running"
568
+ );
569
+ await runCapture(trigger, address, stampSeconds);
570
+ // The disk bound has to hold between restarts too: one episode writes
571
+ // up to four ring copies and two tail files, and the cooldown allows
572
+ // six episodes an hour. Pruning only at startup let that accumulate.
573
+ await pruneWitnessCaptures(resolvedDir);
574
+ } finally {
575
+ state.running = false;
576
+ // Keep the requested spacing honest even when the capture ended early.
577
+ const earliestNext = startedAt + WITNESS_COOLDOWN_MS;
578
+ if (state.lastStartedAt < earliestNext) {
579
+ state.lastStartedAt = earliestNext;
580
+ }
581
+ }
582
+ })();
583
+ return true;
584
+ };
585
+
586
+ /**
587
+ * The rolling ring: one tcpdump, reference-counted by open data channels.
588
+ *
589
+ * @type {{
590
+ * child: import('node:child_process').ChildProcess | null,
591
+ * holders: number,
592
+ * starting: boolean,
593
+ * preserving: boolean,
594
+ * failed: boolean
595
+ * }}
596
+ */
597
+ const ring = { child: null, holders: 0, starting: false, preserving: false, failed: false };
598
+
599
+ /**
600
+ * Delete the ring's own files.
601
+ *
602
+ * Refused while a wedge is copying them out: the copies are the only reason
603
+ * the ring exists, and the viewer closing the tab is exactly when both happen
604
+ * at once. Deferred until the copy is done instead.
605
+ *
606
+ * @returns {Promise<void>}
607
+ */
608
+ const clearRingFiles = async () => {
609
+ if (ring.preserving) {
610
+ return;
611
+ }
612
+ try {
613
+ for (const name of await readdir(resolvedDir)) {
614
+ if (isWitnessRingFile(name)) {
615
+ await rm(path.join(resolvedDir, name), { force: true });
616
+ }
617
+ }
618
+ } catch {
619
+ // silent-ok: best effort, retried when the ring next stops.
620
+ }
621
+ };
622
+
623
+ /**
624
+ * Stop the ring's tcpdump and wait for it to flush and exit.
625
+ *
626
+ * The wait matters. tcpdump buffers its output, so the newest packets — the
627
+ * ONSET, which is the whole reason the ring runs — sit in that buffer until
628
+ * the process is asked to finish. `-U` would flush per packet instead, at one
629
+ * write syscall per packet, and at the measured 150 Mbps that is twelve
630
+ * thousand a second on a machine whose spare capacity is already the binding
631
+ * constraint. Stopping costs nothing while nothing is wrong.
632
+ *
633
+ * @returns {Promise<void>}
634
+ */
635
+ const stopRingProcess = () => {
636
+ const child = ring.child;
637
+ ring.child = null;
638
+ if (!child) {
639
+ return Promise.resolve();
640
+ }
641
+ return new Promise((resolve) => {
642
+ let settled = false;
643
+ const done = () => {
644
+ if (!settled) {
645
+ settled = true;
646
+ clearTimeout(hardKill);
647
+ resolve();
648
+ }
649
+ };
650
+ const hardKill = setTimeout(() => {
651
+ try { child.kill("SIGKILL"); } catch { /* already gone */ }
652
+ done();
653
+ }, WITNESS_KILL_GRACE_MS);
654
+ if (typeof hardKill.unref === "function") {
655
+ hardKill.unref();
656
+ }
657
+ child.on("close", done);
658
+ child.on("error", done);
659
+ try {
660
+ child.kill("SIGTERM");
661
+ } catch {
662
+ done();
663
+ }
664
+ });
665
+ };
666
+
667
+ /**
668
+ * Start the ring's tcpdump, if it is wanted and not already running.
669
+ *
670
+ * @returns {Promise<void>}
671
+ */
672
+ const startRingProcess = async () => {
673
+ if (ring.child !== null || ring.starting || ring.holders === 0) {
674
+ return;
675
+ }
676
+ ring.starting = true;
677
+ try {
678
+ if (state.availability === "unknown") {
679
+ state.availability = (await probeAvailability()) ? "yes" : "no";
680
+ }
681
+ // Everything above suspended; the last channel may have closed meanwhile.
682
+ // Without this second look the ring starts with nobody holding it and
683
+ // nobody left to stop it.
684
+ if (state.availability === "no" || ring.holders === 0) {
685
+ return;
686
+ }
687
+ const prefix = path.join(resolvedDir, WITNESS_RING_BASENAME);
688
+ const args = buildTcpdumpArgs({ port, filePrefix: prefix });
689
+ let child;
690
+ try {
691
+ child = spawnProcess("tcpdump", args, { stdio: "ignore" });
692
+ } catch (error) {
693
+ ring.failed = true;
694
+ logLine(`packet witness: the ring could not start: ${error?.message ?? error}`);
695
+ return;
696
+ }
697
+ ring.child = child;
698
+ child.on("error", (error) => {
699
+ ring.failed = true;
700
+ if (ring.child === child) {
701
+ ring.child = null;
702
+ }
703
+ logLine(`packet witness: the ring stopped: ${error?.message ?? error}`);
704
+ });
705
+ child.on("close", (code, signal) => {
706
+ if (ring.child !== child) {
707
+ return; // An orderly stop; it has already said what it needed to.
708
+ }
709
+ ring.child = null;
710
+ ring.failed = true;
711
+ // Ending on its own means it never recorded what it claimed to. A host
712
+ // with tcpdump installed but without the capability to capture answers
713
+ // `--version` happily and dies here, which would otherwise leave a
714
+ // "ring recording" line in the log and no history behind it.
715
+ logLine(
716
+ `packet witness: the ring ended on its own${signal ? ` (${signal})` : ` (exit ${code ?? "?"})`}` +
717
+ `${ring.holders > 0 ? " while a viewer was still being served — no history is being kept" : ""}`
718
+ );
719
+ });
720
+ logLine(
721
+ `packet witness: ring recording udp port ${port}, ` +
722
+ `${WITNESS_RING_FILES} × ${WITNESS_RING_FILE_MB} MB wrapping — ` +
723
+ "the seconds before a freeze, kept in advance"
724
+ );
725
+ } finally {
726
+ ring.starting = false;
727
+ // Holders may have gone while the probe or the spawn was in flight.
728
+ if (ring.holders === 0 && ring.child !== null) {
729
+ await stopRingProcess();
730
+ await clearRingFiles();
731
+ }
732
+ }
733
+ };
734
+
735
+ /**
736
+ * Begin recording, or note one more reason to keep recording.
737
+ *
738
+ * Reference-counted by open data channels, so the ring runs exactly while a
739
+ * viewer is being served and costs nothing on an idle proxy. Starting it is
740
+ * what makes the ONSET of a freeze readable: by the time a wedge is declared,
741
+ * the seconds before it are already on disk.
742
+ *
743
+ * @returns {void}
744
+ */
745
+ const holdRing = () => {
746
+ ring.holders += 1;
747
+ if (ring.holders !== 1) {
748
+ return;
749
+ }
750
+ void startRingProcess();
751
+ };
752
+
753
+ /**
754
+ * Release one reason to keep recording; the last one stops the ring.
755
+ *
756
+ * @returns {void}
757
+ */
758
+ const releaseRing = () => {
759
+ if (ring.holders > 0) {
760
+ ring.holders -= 1;
761
+ }
762
+ if (ring.holders > 0 || ring.starting) {
763
+ return;
764
+ }
765
+ void (async () => {
766
+ await stopRingProcess();
767
+ await clearRingFiles();
768
+ })();
769
+ };
770
+
771
+ /**
772
+ * Stop everything this witness owns. For process shutdown.
773
+ *
774
+ * @returns {Promise<void>}
775
+ */
776
+ const dispose = async () => {
777
+ ring.holders = 0;
778
+ await stopRingProcess();
779
+ await clearRingFiles();
780
+ };
781
+
782
+ return { dir: resolvedDir, maybeCapture, holdRing, releaseRing, dispose, ring };
783
+
784
+ }