AtlatestRepositorysigil-quic
sigil-quic / tree / scriptsinject-handshake-spy.mjs
1
// Test-only result observation and subsequent-operation faults. Run remotely2
// with distinct input/output paths; never rewrite the shipped module in place.3
import { readFileSync, writeFileSync } from 'node:fs';5
const [input, output] = process.argv.slice(2);6
if (!input || !output || input === output) {7
throw new Error('Usage: inject-handshake-spy.mjs INPUT OUTPUT');8
}9
let source = readFileSync(input, 'utf8');10
const imported = '(import (sigil crypto)';11
const start = source.indexOf(' (define (derive-handshake! engine peer-public)');12
const end = source.indexOf(' (define (derive-application! engine)');13
if (start < 0 || end <= start || source.includes('handshake-spy') ||14
source.split(imported).length !== 2) {15
throw new Error('Expected an uninstrumented TLS handshake');16
}17
let derivation = source.slice(start, end);18
for (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);31
}32
source = source.slice(0, start) + derivation + source.slice(end);33
const keyGeneration = /\(x25519-public-key(?=\s)/g;34
if ([...source.matchAll(keyGeneration)].length !== 1) {35
throw new Error('Key-generation primitive site changed');36
}37
source = source.replace(keyGeneration, '(handshake-spy-public');38
source = source.replace(imported,39
'(import (sigil quic tests handshake spy)\n (sigil crypto)');40
writeFileSync(output,41
';;; TEST ONLY: observed handshake intermediates; never ship this variant.\n' + source);