AtlatestRepositorysigil-quic

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

1// Test-only result observation and subsequent-operation faults. Run remotely
2// with distinct input/output paths; never rewrite 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-handshake-spy.mjs INPUT OUTPUT');
8}
9let source = readFileSync(input, 'utf8');
10const imported = '(import (sigil crypto)';
11const start = source.indexOf(' (define (derive-handshake! engine peer-public)');
12const end = source.indexOf(' (define (derive-application! engine)');
13if (start < 0 || end <= start || source.includes('handshake-spy') ||
14 source.split(imported).length !== 2) {
15 throw new Error('Expected an uninstrumented TLS handshake');
17let derivation = source.slice(start, end);
18for (const [primitive, alias, expected] of [
19 ['x25519-shared-secret', 'handshake-spy-shared', 1],
20 ['early-secret', 'handshake-spy-early', 1],
21 ['handshake-secret', 'handshake-spy-handshake', 1],
22 ['tls-transcript-hash', 'handshake-spy-transcript', 1],
23 ['derive-secret', 'handshake-spy-derive', 2],
24 ['master-secret', 'handshake-spy-master', 1],
25]) {
26 const pattern = new RegExp('\\(' + primitive + '(?=\\s)', 'g');
27 if ([...derivation.matchAll(pattern)].length !== expected) {
28 throw new Error('Handshake primitive sites changed: ' + primitive);
29 }
30 derivation = derivation.replace(pattern, '(' + alias);
32source = source.slice(0, start) + derivation + source.slice(end);
33const keyGeneration = /\(x25519-public-key(?=\s)/g;
34if ([...source.matchAll(keyGeneration)].length !== 1) {
35 throw new Error('Key-generation primitive site changed');
37source = source.replace(keyGeneration, '(handshake-spy-public');
38source = source.replace(imported,
39 '(import (sigil quic tests handshake spy)\n (sigil crypto)');
40writeFileSync(output,
41 ';;; TEST ONLY: observed handshake intermediates; never ship this variant.\n' + source);