AtlatestRepositorysigil-quic

sigil-quic / tree / scriptsinject-factory-spy.mjs

1// Observe returned allocations and fault the next operation in remote tests.
2// Never install as a package hook or modify the shipped module in place.
3import { readFileSync, writeFileSync } from 'node:fs';
4
5const [input, output] = process.argv.slice(2);
6if (!input || !output || input === output) {
7 throw new Error('Usage: inject-factory-spy.mjs INPUT OUTPUT');
8}
9let source = readFileSync(input, 'utf8');
10const imported = '(import (sigil crypto)';
11if (!source.includes('(define-library (sigil quic packet)') ||
12 source.includes('factory-spy') || source.split(imported).length !== 2) {
13 throw new Error('Expected an uninstrumented packet module');
15for (const [primitive, alias, count] of [
16 ['hkdf-sha256-extract', 'factory-spy-extract', 1],
17 ['hkdf-expand-label', 'factory-spy-expand', 7],
18]) {
19 const pattern = new RegExp('\\(' + primitive + '(?=\\s)', 'g');
20 if ([...source.matchAll(pattern)].length !== count) throw new Error('Packet derivation sites changed');
21 source = source.replace(pattern, '(' + alias);
23for (const [startMarker, endMarker, count] of [
24 [' (define (traffic-keys secret)', ' (define (require-keys! material)', 1],
25 [' (define (next-traffic-keys material)', ' (define (discard-packet-keys! material)', 2],
26]) {
27 const start = source.indexOf(startMarker), end = source.indexOf(endMarker);
28 if (start < 0 || end <= start) throw new Error('Packet factory boundaries changed');
29 let factory = source.slice(start, end);
30 const pattern = /\(bytevector-copy(?=\s)/g;
31 if ([...factory.matchAll(pattern)].length !== count) throw new Error('Packet copy sites changed');
32 factory = factory.replace(pattern, '(factory-spy-copy');
33 source = source.slice(0, start) + factory + source.slice(end);
35source = source.replace(imported,
36 '(import (sigil quic tests factory spy)\n (sigil crypto)');
37writeFileSync(output,
38 ';;; TEST ONLY: observed packet factory allocations; never ship this variant.\n' + source);