import assert from 'node:assert/strict';
import test from 'node:test';
import { request as httpRequest } from 'node:http';
import { createHash } from 'node:crypto';
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';
import { createReportIndexHelper, decryptWithGpg } from '../scripts/report-index-helper.mjs';
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const origin = 'https://cheatsheet.daemon-sec.xyz';
const token = 'a'.repeat(48);
const fixture = Buffer.from(JSON.stringify({ version: 1, recipient: 'TEST', steps: [
{ order: 1, tool: 'Example', purpose: 'Test only', pages: '1', sheetId: 'tools/example' },
] }));
async function setup(t, decrypt) {
const dir = await mkdtemp(join(tmpdir(), 'report-helper-test-'));
const ciphertext = join(dir, 'fixture.gpg');
await writeFile(ciphertext, 'test ciphertext');
const lock = { recipient: 'TEST', plaintextSha256: hash(fixture), ciphertextSha256: hash(await readFile(ciphertext)) };
// Reserve a loopback port before configuring the helper's strict Host check.
const { createServer } = await import('node:net');
const reserve = createServer();
await new Promise(resolve => reserve.listen(0, '127.0.0.1', resolve));
const port = reserve.address().port;
await new Promise(resolve => reserve.close(resolve));
const { server } = createReportIndexHelper({ lock, ciphertext, token, port, decrypt });
await new Promise(resolve => server.listen(port, '127.0.0.1', resolve));
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await rm(dir, { recursive: true, force: true }); });
return { url: `http://127.0.0.1:${port}/unlock`, ciphertext };
}
const request = (url, body = { token }, extra = {}) => fetch(url, {
method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json', ...extra }, body: JSON.stringify(body),
});
test('helper requires the allowed origin, exact Host and pairing code before decryption', async t => {
let calls = 0;
const { url } = await setup(t, async () => { calls++; return fixture; });
for (const [body, headers, status] of [
[{ token }, { Origin: 'https://untrusted.example' }, 403],
[{ token: 'bad' }, {}, 403],
[{ token, file: '/etc/passwd' }, {}, 403],
[{ token }, { 'Content-Type': 'text/plain' }, 415],
[{ token, excess: 'x'.repeat(1100) }, {}, 413],
]) assert.equal((await request(url, body, headers)).status, status);
const hostStatus = await new Promise((resolve, reject) => {
const req = httpRequest(url, { method: 'POST', headers: { Host: 'rebinding.example', Origin: origin, 'Content-Type': 'application/json' } }, res => { res.resume(); resolve(res.statusCode); });
req.on('error', reject); req.end(JSON.stringify({ token }));
});
assert.equal(hostStatus, 403);
assert.equal(calls, 0);
const preflight = await fetch(url, { method: 'OPTIONS', headers: { Origin: origin, 'Access-Control-Request-Private-Network': 'true' } });
assert.equal(preflight.status, 204);
assert.equal(preflight.headers.get('access-control-allow-origin'), origin);
assert.equal(preflight.headers.get('access-control-allow-private-network'), 'true');
const response = await request(url);
assert.equal(response.status, 200);
assert.equal(response.headers.get('cache-control'), 'no-store');
assert.equal(hash(Buffer.from(await response.arrayBuffer())), hash(fixture));
assert.equal(calls, 1);
});
test('helper rejects modified assets and plaintext before returning content', async t => {
const { url, ciphertext } = await setup(t, async () => Buffer.from('wrong plaintext'));
assert.equal((await request(url)).status, 422);
await writeFile(ciphertext, 'modified');
assert.equal((await request(url)).status, 422);
});
test('disconnect cancels GPG and concurrent unlocks are rejected', async t => {
let begun;
const started = new Promise(resolve => { begun = resolve; });
let cancelled;
const stopped = new Promise(resolve => { cancelled = resolve; });
const { url } = await setup(t, (_file, signal) => new Promise((_resolve, reject) => {
begun(); signal.addEventListener('abort', () => { cancelled(); reject(new Error('Cancelled')); }, { once: true });
}));
const controller = new AbortController();
const pending = fetch(url, { method: 'POST', headers: { Origin: origin, 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), signal: controller.signal });
const rejected = assert.rejects(pending, /abort/i);
await started;
assert.equal((await request(url)).status, 409);
controller.abort();
await Promise.all([rejected, stopped]);
});
test('GPG decrypts a real message using an isolated disposable key', async t => {
const dir = await mkdtemp(join(tmpdir(), 'report-gpg-test-'));
t.after(async () => {
execFileSync('gpgconf', ['--homedir', dir, '--kill', 'gpg-agent']);
await rm(dir, { recursive: true, force: true });
});
const gpg = args => execFileSync('gpg', ['--homedir', dir, '--batch', '--pinentry-mode', 'loopback', '--passphrase', '', ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
gpg(['--quick-generate-key', 'Index test <test@example.invalid>', 'default', 'default', '1d']);
const plaintext = join(dir, 'fixture.json');
const ciphertext = join(dir, 'fixture.gpg');
await writeFile(plaintext, fixture);
gpg(['--trust-model', 'always', '--recipient', 'test@example.invalid', '--encrypt', '--output', ciphertext, plaintext]);
const old = process.env.GNUPGHOME;
process.env.GNUPGHOME = dir;
try { assert.equal(hash(await decryptWithGpg(ciphertext, new AbortController().signal)), hash(fixture)); }
finally { if (old === undefined) delete process.env.GNUPGHOME; else process.env.GNUPGHOME = old; }
});