import { createServer } from 'node:http';
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { readReportIndex, MAX_INDEX_BYTES } from '../src/lib/report-index.ts';
export const HELPER_PORT = 47631;
export const SITE_ORIGINS = new Set(['https://cheatsheet.daemon-sec.xyz', 'http://localhost:4321', 'http://127.0.0.1:4321']);
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const asBuffer = bytes => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
export function decryptWithGpg(ciphertext, signal) {
return new Promise((resolve, reject) => {
// GPG owns the key and opens its normal pinentry; the helper never receives a passphrase.
const child = spawn('gpg', ['--no-options', '--batch', '--max-output', String(MAX_INDEX_BYTES), '--decrypt', ciphertext], {
stdio: ['ignore', 'pipe', 'ignore'], signal,
});
let size = 0;
const chunks = [];
child.stdout.on('data', chunk => {
size += chunk.length;
if (size > MAX_INDEX_BYTES) child.kill();
else chunks.push(chunk);
});
child.on('error', () => reject(new Error('GPG is unavailable or the request was cancelled.')));
child.on('close', code => code === 0 && size <= MAX_INDEX_BYTES
? resolve(Buffer.concat(chunks))
: reject(new Error('GPG could not unlock the index. Check Main_Key and its pinentry, then retry.')));
});
}
// Exported for isolated tests with a disposable key; the CLI always uses this checkout's pinned asset.
export function createReportIndexHelper({ lock, ciphertext, token = randomBytes(24).toString('hex'),
origins = SITE_ORIGINS, port = HELPER_PORT, decrypt = decryptWithGpg }) {
const active = new Set();
let busy = false;
const server = createServer(async (req, res) => {
res.setHeader('Cache-Control', 'no-store');
res.setHeader('X-Content-Type-Options', 'nosniff');
const finish = (status, message) => {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ error: message }));
};
const origin = req.headers.origin;
if (req.headers.host !== `127.0.0.1:${port}` || !origins.has(origin)) return finish(403, 'This site is not paired with the helper.');
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');
if (req.url !== '/unlock') return finish(404, 'Unknown helper endpoint.');
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Private-Network', 'true');
res.writeHead(204); res.end(); return;
}
if (req.method !== 'POST') return finish(405, 'Use the unlock button.');
if (req.headers['content-type'] !== 'application/json') return finish(415, 'Expected a pairing request.');
let request;
try {
let size = 0;
const chunks = [];
for await (const chunk of req) {
size += chunk.length;
if (size > 1024) { finish(413, 'Pairing request is too large.'); return; }
chunks.push(chunk);
}
request = JSON.parse(Buffer.concat(chunks).toString('utf8'));
} catch { return finish(400, 'Invalid pairing request.'); }
const supplied = typeof request?.token === 'string' ? Buffer.from(request.token) : Buffer.alloc(0);
const expected = Buffer.from(token);
if (Object.keys(request ?? {}).length !== 1 || supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) {
return finish(403, 'Pairing code does not match. Copy the code from your helper terminal.');
}
if (busy) return finish(409, 'GPG is already unlocking the index.');
busy = true;
const controller = new AbortController();
active.add(controller);
const timeout = setTimeout(() => controller.abort(), 120_000);
const cancel = () => { if (!res.writableEnded) controller.abort(); };
res.on('close', cancel);
try {
if (hash(await readFile(ciphertext)) !== lock.ciphertextSha256) throw new Error('The encrypted asset has changed. Restart with the current checkout.');
const bytes = await decrypt(ciphertext, controller.signal);
await readReportIndex(asBuffer(bytes), lock.plaintextSha256, lock.recipient);
if (!controller.signal.aborted && !res.destroyed) {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(bytes);
}
} catch (error) {
if (!res.destroyed) finish(422, error instanceof Error ? error.message : 'Unable to unlock the index.');
} finally {
clearTimeout(timeout);
res.off('close', cancel);
active.delete(controller);
busy = false;
}
});
server.requestTimeout = 130_000;
server.headersTimeout = 10_000;
server.on('close', () => { for (const controller of active) controller.abort(); });
return { server, token };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const lock = JSON.parse(await readFile(new URL('../src/data/report-index-lock.json', import.meta.url), 'utf8'));
const ciphertext = fileURLToPath(new URL('../public/encrypted/report-index.gpg', import.meta.url));
const { server, token } = createReportIndexHelper({ lock, ciphertext });
server.on('error', () => { console.error('Cannot start the GPG helper. Check whether port 47631 is already in use.'); process.exitCode = 1; });
server.listen(HELPER_PORT, '127.0.0.1', () => {
console.log('GPG helper is ready. Keep this terminal open until the section unlocks.');
console.log(`Pairing code: ${token}`);
console.log(`Open: https://cheatsheet.daemon-sec.xyz/#gpg-pair=${token}`);
console.log('Your Main_Key stays in GPG. Press Ctrl+C to stop the helper.');
});
for (const event of ['SIGINT', 'SIGTERM']) process.once(event, () => {
server.close(); server.closeAllConnections();
});
}