Add control-plane (plan, execution with consent per action, remediation recipes and proof, compliance report, console) and readiness (the post-quantum readiness scanner of a hostname)

This commit is contained in:
Aere Network committed 2026-09-29 21:21:59 +03:00
1 parent 3465550e91
commit a7165164eb
22 files changed
+2743 -1

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
# Post-quantum readiness scanner
`readiness-service.mjs` measures, for one public hostname, whether its TLS edge is ready for post-quantum key exchange. It does not
estimate: it opens real connections and reports what the server did.
1. a TLS 1.3 handshake with the usual classical groups: the baseline (protocol, cipher, group, the certificate and its chain);
2. a TLS 1.3 handshake offering **only** `X25519MLKEM768` (then `SecP256r1MLKEM768`): does the server know the hybrid key exchange?
3. a TLS 1.3 handshake offering the hybrid group first, with classical fallbacks: does it **prefer** it? (OpenSSL does not name the
hybrid group in the ephemeral key information, so the preference is inferred; the method control is that the classical baseline
comes back with a named group, and without it no claim about preference is made);
4. a TLS 1.2-only handshake: is a version without post-quantum key exchange still accepted?
5. an HTTPS `HEAD /` for HSTS.
From these it reports the harvest-now-decrypt-later exposure (no post-quantum key exchange: traffic recorded today can be read once a
cryptographically relevant quantum computer exists), classical certificate authentication (reported, not penalized: no public CA
issues post-quantum certificates yet), expiry, TLS 1.2, HSTS, a score and concrete recommendations. Every finding has a stable `id`;
the control plane's planner classifies exactly these ids, and its test derives them from this file.
It needs Node.js 24 with OpenSSL 3.5 or later (the ML-KEM groups) and refuses to start otherwise, instead of reporting "no
post-quantum" about everyone.
## As a service
PORT=8797 AERE_READINESS_FROM="your label" AERE_READINESS_DIR=/var/lib/aere/readiness node readiness-service.mjs
curl -s -H 'content-type: application/json' -d '{"domain":"example.com"}' http://127.0.0.1:8797/scan
It listens on 127.0.0.1 only; put your own proxy in front. Endpoints: `POST /scan {"domain": ..., "fresh": true?}`, `GET /scan/<domain>`
(the cached report), `GET /health`. Reports are cached for six hours; a failed scan is not cached.
- **No connection to anything that is not proven public.** A hostname that resolves, even partly, to a loopback, private, link-local,
CGNAT, documentation, multicast or reserved address (IPv4 or IPv6, including mapped and NAT64 forms) gets no connection, and the
answer does not name its addresses. The connections then go to the address that was checked, so the name is not resolved a second
time between the check and the connection (`adrese-private.mjs`).
- **Rate limit per client:** at most 12 scans per minute. The client is the value of the `x-aere-client` header set by the front that
calls the service (it listens on 127.0.0.1, so only something on the same host can set it), otherwise the connecting address.
`X-Forwarded-For` is never read: its first element is chosen by the client, and a limit keyed on it could be bypassed by changing it
(fixed on 2026-09-29).
- **Bounded work:** at most 4 scans at a time and 32 waiting; past that the answer is `503 busy`, not an unbounded wait.
`scaneaza(domain)` and `scaneazaAdresa(domain, address, { port })` can also be imported as functions; the second one has no
private-address guard (it is for callers that checked the target themselves, such as local tests on 127.0.0.1).
## Tests
node proba-adrese-private.mjs # the private-address rules, and a local listener that must never be touched by a scan
The control plane's tests (`../control-plane/`) also run this scanner against real TLS servers on 127.0.0.1. The rate limit and the
queue bound are tested by the service that runs it in production (`proba-client-real.mjs` in the Aere Network repository, not
included here); here they are documented, not measured. No third party has reviewed it.
+62
View File
@@ -0,0 +1,62 @@
// O adresa IP la care un serviciu PUBLIC al nostru nu are voie sa se conecteze in numele unui strain: loopback, retele private,
// link-local, CGNAT, adrese de documentatie si de test, multicast, rezervate, si formele IPv6 ale acelorasi (inclusiv IPv4 mapat
// si NAT64). UN singur loc, folosit de gateway (tintele webhook-urilor) si de scanerul de pregatire post-cuantica: doua copii ale
// aceleiasi liste diverg, iar cea din gateway nu stia de CGNAT (100.64/10), de IPv4 mapat in IPv6 privat si de `::`.
//
// Scris 2026-09-18, dupa ce scanerul PUBLIC, fara cheie, a fost prins (masurat pe serviciul viu) rezolvand o gazda straina la
// 127.0.0.1 si ::1 si INCERCAND conexiunea: oricine isi putea indrepta un nume spre o adresa interna si afla din raspuns daca
// portul 443 e deschis acolo si ce certificat poarta. Regula: orice nu e DOVEDIT public e privat (o adresa pe care nu o inteleg
// nu primeste conexiune).
const v4 = (ip) => { const p = ip.split('.'); if (p.length !== 4) return null; const n = p.map((x) => (/^\d{1,3}$/.test(x) ? Number(x) : NaN)); return n.every((x) => x >= 0 && x <= 255) ? n : null; };
function v4Privat([a, b, c]) {
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 192 && b === 0 && c === 2) || (a === 192 && b === 88 && c === 99) ||
(a === 198 && (b === 18 || b === 19)) || (a === 198 && b === 51 && c === 100) || (a === 203 && b === 0 && c === 113) || a >= 224;
}
// IPv6 desfacut in 8 grupuri de 16 biti; null daca textul nu e o adresa IPv6
function v6Grupuri(ip) {
let t = ip.toLowerCase(); const zona = t.indexOf('%'); if (zona >= 0) t = t.slice(0, zona);
let coada4 = null;
const m = /^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(t);
if (m) { coada4 = v4(m[2]); if (!coada4) return null; t = m[1] + ((coada4[0] << 8) | coada4[1]).toString(16) + ':' + ((coada4[2] << 8) | coada4[3]).toString(16); }
if ((t.match(/::/g) || []).length > 1) return null;
const [st, dr] = t.includes('::') ? t.split('::') : [t, null];
const a = st ? st.split(':') : [], b = dr === null ? [] : (dr ? dr.split(':') : []);
if (dr === null ? a.length !== 8 : a.length + b.length > 7) return null;
const g = [...a, ...Array(8 - a.length - b.length).fill('0'), ...b];
if (!g.every((x) => /^[0-9a-f]{1,4}$/.test(x))) return null;
return g.map((x) => parseInt(x, 16));
}
export function ipPrivat(ip) {
const text = String(ip || '').trim();
const p4 = v4(text);
if (p4) return v4Privat(p4);
const g = v6Grupuri(text);
if (!g) return true; // nu e o adresa pe care o inteleg: nu primeste conexiune
const ultimele4 = [g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255];
if (g.slice(0, 5).every((x) => x === 0)) {
if (g[5] === 0xffff) return v4Privat(ultimele4); // ::ffff:a.b.c.d, IPv4 mapat: il judeca regula IPv4
if (g[5] === 0) return true; // ::, ::1 si vechiul ::a.b.c.d (retras): nimic public acolo
}
if (g[0] === 0x64 && g[1] === 0xff9b) return v4Privat(ultimele4); // NAT64 64:ff9b::/96 (si 64:ff9b:1::/48)
if (g[0] === 0x2002) return v4Privat([g[1] >> 8, g[1] & 255, g[2] >> 8, g[2] & 255]); // 6to4 poarta un IPv4 in el
if ((g[0] & 0xfe00) === 0xfc00) return true; // fc00::/7 unique local
if ((g[0] & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local
if ((g[0] & 0xff00) === 0xff00) return true; // ff00::/8 multicast
if (g[0] === 0x2001 && g[1] === 0x0db8) return true; // documentatie
if (g[0] === 0x3fff && (g[1] & 0xf000) === 0) return true; // 3fff::/20, documentatie (RFC 9637); prins de proba, nu de mine
if (g[0] === 0x2001 && g[1] === 0) return true; // Teredo
if ((g[0] & 0xe000) !== 0x2000) return true; // in afara 2000::/3 (unicast global) nu e public
return false;
}
// Un `lookup` pentru tls.connect / https.request care intoarce NUMAI adresa deja verificata: intre verificare si conexiune
// numele nu mai e rezolvat a doua oara, deci un DNS care isi schimba raspunsul (rebinding) nu mai are ce sa mute.
export const lookupFixat = (adresa) => (gazda, optiuni, cb) => {
if (typeof optiuni === 'function') { cb = optiuni; optiuni = {}; }
if (optiuni && optiuni.all) cb(null, [{ address: adresa.address, family: adresa.family }]);
else cb(null, adresa.address, adresa.family);
};
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env node
// Probele gardei de adrese private (adrese-private.mjs) si ale scanerului care o foloseste. Offline: rezolvarea DNS se
// injecteaza, iar "conexiunea" se masoara pe un server TLS local care NUMARA cine il atinge.
// node aerenew/cloud-gateway/proba-adrese-private.mjs
import assert from 'node:assert';
import net from 'node:net';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
process.env.AERE_READINESS_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-readiness-'));
const { ipPrivat, lookupFixat } = await import('./adrese-private.mjs');
const { scaneaza } = await import('./readiness-service.mjs');
let treceri = 0; const esecuri = [];
async function test(nume, fn) { try { await fn(); treceri++; console.log(' OK ' + nume); } catch (e) { esecuri.push(nume); console.log(' ESEC ' + nume + ' -> ' + String(e.message || e).slice(0, 260)); } }
const PRIVATE = ['127.0.0.1', '127.255.255.254', '10.10.0.23', '10.0.0.1', '172.16.0.1', '172.31.255.255', '192.168.1.1', '169.254.169.254', '100.64.0.1', '100.127.255.255', // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
'0.0.0.0', '192.0.0.1', '192.0.2.5', '198.18.0.1', '198.19.255.255', '198.51.100.7', '203.0.113.9', '224.0.0.1', '255.255.255.255', // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
'::1', '::', '::ffff:127.0.0.1', '::ffff:10.10.0.23', '::ffff:a0a:17', '::10.0.0.1', 'fe80::1', 'fe80::1%eth0', 'fc00::1', 'fd12:3456::1', 'ff02::1', '2001:db8::1', '2001::1', // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
'64:ff9b::10.0.0.1', '64:ff9b::7f00:1', '2002:0a0a:0017::1', '3fff::1', '4000::1', 'nu-e-adresa', '', '1.2.3', '1.2.3.4.5', '256.1.1.1', '12345::1', ':::1']; // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
const PUBLICE = ['1.1.1.1', '8.8.8.8', '172.15.255.255', '172.32.0.1', '100.63.255.255', '100.128.0.1', '192.167.255.255', '169.253.0.1', '198.17.255.255', '198.20.0.1', '223.255.255.255', // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
'2606:4700:4700::1111', '2a01:4f8::1', '::ffff:8.8.8.8', '64:ff9b::8.8.8.8', '2002:0808:0808::1']; // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
await test(`predicatul: ${PRIVATE.length} adrese care NU primesc conexiune (loopback, private, CGNAT, link-local, documentatie, multicast, formele lor IPv6, si orice text care nu e adresa)`, () => {
const scapate = PRIVATE.filter((a) => !ipPrivat(a)); assert.deepStrictEqual(scapate, []);
});
await test(`predicatul: ${PUBLICE.length} adrese publice, inclusiv vecinele de granita ale fiecarui bloc privat, NU sunt refuzate`, () => {
const refuzate = PUBLICE.filter((a) => ipPrivat(a)); assert.deepStrictEqual(refuzate, []);
});
await test('regula veche a gateway-ului lasa sa treaca exact ce s-a adaugat (CGNAT, IPv4 privat mapat, ::): proba deosebeste cele doua reguli', () => {
const veche = (ip) => { if (ip.includes(':')) return ip === '::1' || ip.startsWith('fe80') || ip.startsWith('fc') || ip.startsWith('fd') || ip.startsWith('::ffff:127.'); const [a, b] = ip.split('.').map(Number); return a === 127 || a === 10 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254); };
for (const a of ['100.64.0.1', '::ffff:10.10.0.23', '::', '198.18.0.1', '64:ff9b::10.0.0.1']) { assert.strictEqual(veche(a), false, a + ': regula veche o lasa'); assert.strictEqual(ipPrivat(a), true, a); } // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
});
// un ascultator local care numara conexiunile: daca scanerul il atinge, garda nu a tinut
let atingeri = 0; const srv = net.createServer((s) => { atingeri++; s.destroy(); });
await new Promise((r) => srv.listen(0, '127.0.0.1', r)); // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
await test('scanerul: o gazda rezolvata la o adresa privata -> private_target, FARA adrese in raspuns si fara nicio conexiune', async () => {
for (const adrese of [[{ address: '10.10.0.23', family: 4 }], [{ address: '::1', family: 6 }, { address: '127.0.0.1', family: 4 }], [{ address: '1.1.1.1', family: 4 }, { address: '169.254.169.254', family: 4 }]]) { // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
const t0 = Date.now(); const r = await scaneaza('intern.example', { rezolva: async () => adrese });
assert.strictEqual(r.error, 'private_target', JSON.stringify(r)); assert.strictEqual(r.addresses, undefined, 'raspunsul nu are voie sa spuna adresele'); assert.doesNotMatch(JSON.stringify(r), /10\.10\.0\.23|169\.254|127\.0\.0\.1/);
assert.ok(Date.now() - t0 < 1000, 'a durat ' + (Date.now() - t0) + ' ms: a incercat o conexiune');
}
assert.strictEqual(atingeri, 0);
});
await test('scanerul: o rezolvare goala sau cazuta e eroare de DNS, nu o scanare', async () => {
assert.strictEqual((await scaneaza('gol.example', { rezolva: async () => [] })).error, 'dns');
assert.strictEqual((await scaneaza('cade.example', { rezolva: async () => { const e = new Error('x'); e.code = 'ENOTFOUND'; throw e; } })).detail, 'ENOTFOUND');
});
await test('lookupFixat: conexiunea merge pe adresa VERIFICATA, in amandoua formele de apel (cu si fara all), oricare ar fi numele', async () => {
const l = lookupFixat({ address: '1.1.1.1', family: 4 }); // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
await new Promise((ok, rau) => l('se-schimba.example', { all: true }, (e, v) => { try { assert.deepStrictEqual(v, [{ address: '1.1.1.1', family: 4 }]); ok(); } catch (x) { rau(x); } })); // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
await new Promise((ok, rau) => l('se-schimba.example', {}, (e, a, f) => { try { assert.deepStrictEqual([a, f], ['1.1.1.1', 4]); ok(); } catch (x) { rau(x); } })); // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
await new Promise((ok, rau) => l('se-schimba.example', (e, a, f) => { try { assert.deepStrictEqual([a, f], ['1.1.1.1', 4]); ok(); } catch (x) { rau(x); } })); // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
// si chiar foloseste adresa: o conexiune net cu lookup fixat pe ascultatorul local ajunge la el, desi numele nu exista
const inainte = atingeri;
await new Promise((ok) => { const s = net.connect({ host: 'nume-care-nu-exista.invalid', port: srv.address().port, lookup: lookupFixat({ address: '127.0.0.1', family: 4 }) }); s.on('close', ok); s.on('error', ok); }); // AERE-SINTETIC: adrese de granita ale regulii (vectori de proba), nu gazde
assert.strictEqual(atingeri, inainte + 1, 'lookup-ul fixat nu a fost folosit');
});
srv.close();
fs.rmSync(process.env.AERE_READINESS_DIR, { recursive: true, force: true });
console.log(`\n${treceri} treceri, ${esecuri.length} esecuri`);
process.exitCode = esecuri.length ? 1 : 0;
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env node
// AERE Quantum Readiness: scanerul public al pregatirii post-cuantice a unui domeniu. MASOARA, nu estimeaza:
// pentru gazda data, patru strangeri de mana TLS reale de pe gazda Cloud (EU) si o cerere HEAD:
// 1. TLS 1.3 cu grupurile obisnuite -> linia de baza: protocol, cifru, grupul clasic, certificatul si lantul lui
// 2. TLS 1.3 oferind NUMAI X25519MLKEM768 -> serverul stie schimbul de chei hibrid post-cuantic? (da/nu)
// 3. TLS 1.3 cu hibridul oferit primul + clasice -> il PREFERA cand i se ofera? (dedus: OpenSSL nu numeste grupul hibrid
// in getEphemeralKeyInfo, deci "reusit si fara nume" = ne-clasic; controlul
// pozitiv al metodei e ca grupurile clasice IES cu nume)
// 4. numai TLS 1.2 -> mai accepta o versiune fara schimb de chei post-cuantic?
// 5. HEAD https://gazda/ -> HSTS
// De aici: expunerea la "recolteaza acum, decripteaza mai tarziu" (fara schimb de chei PQ, tot traficul inregistrat azi se
// poate citi cand exista un calculator cuantic), autentificarea clasica a certificatului (azi TOATE certificatele WebPKI
// sunt ECDSA/RSA: se raporteaza, nu se penalizeaza, fiindca nu exista inca alternativa emisa de CA-uri), expirarea,
// TLS 1.2, HSTS; un scor si recomandari concrete. Cere Node cu OpenSSL >= 3.5 (grupurile ML-KEM); altfel refuza sa
// porneasca, in loc sa raporteze "fara PQ" despre toata lumea.
import http from 'node:http';
import tls from 'node:tls';
import dns from 'node:dns/promises';
import https from 'node:https';
import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
import { ipPrivat, lookupFixat } from './adrese-private.mjs';
const PORT = Number(process.env.PORT || 8797);
const FROM = process.env.AERE_READINESS_FROM || 'AERE Cloud, EU';
const JURNAL_DIR = process.env.AERE_READINESS_DIR || '/var/lib/aere/readiness';
const ADOPTIE_DIR = process.env.AERE_ADOPTIE_DIR || '/var/lib/aere/readiness/adoptie';
const TTL_MS = 6 * 3600e3;
const PQ_GROUP = 'X25519MLKEM768';
const PQ_GROUP_2 = 'SecP256r1MLKEM768';
const [oMaj, oMin] = String(process.versions.openssl).split('.').map(Number);
if (oMaj < 3 || (oMaj === 3 && oMin < 5)) {
console.error(`REFUSED: OpenSSL ${process.versions.openssl} does not know the ML-KEM groups; 3.5 or later is required`);
process.exit(2);
}
try { mkdirSync(JURNAL_DIR, { recursive: true }); } catch {}
const cache = new Map(); // domeniu -> { at, report }
const ritm = new Map(); // ip -> [timestamps]
// B-16 (2026-09-29): coada de asteptare e MARGINITA; fara margine, cereri trimise mai repede decat se scaneaza tineau fiecare o
// conexiune si memorie la nesfarsit. Peste margine raspunsul e 503 busy, spus, nu o asteptare fara capat.
let inLucru = 0; const MAX_PARALEL = 4; const coada = []; export const MAX_COADA = 32;
const domeniuValid = (d) => /^(?=.{1,253}$)(?!-)([a-z0-9-]{1,63}\.)+[a-z]{2,63}$/i.test(d) && !/^\d+\.\d+\.\d+\.\d+$/.test(d);
function probe(host, opts, adresa, port = 443) {
return new Promise((res) => {
const t0 = Date.now();
let done = false;
const fin = (v) => { if (!done) { done = true; res(v); } };
let s;
try {
s = tls.connect({ host, port, servername: host, timeout: 8000, ALPNProtocols: ['h2', 'http/1.1'], rejectUnauthorized: false, ...(adresa ? { lookup: lookupFixat(adresa) } : {}), ...opts }, () => {
const c = s.getPeerCertificate(true) || {};
const e = s.getEphemeralKeyInfo() || {};
const chain = []; let x = c; const seen = new Set();
while (x && x.fingerprint256 && !seen.has(x.fingerprint256)) { seen.add(x.fingerprint256); chain.push({ subject: x.subject?.CN || null, issuer: x.issuer?.O || x.issuer?.CN || null, keyType: x.asn1Curve ? 'EC/' + x.asn1Curve : (x.bits ? 'RSA' : 'other'), bits: x.bits || null, validTo: x.valid_to || null }); if (!x.issuerCertificate || x.issuerCertificate === x) break; x = x.issuerCertificate; }
fin({ ok: true, ms: Date.now() - t0, protocol: s.getProtocol(), cipher: s.getCipher()?.name || null, groupName: e.name || null, alpn: s.alpnProtocol || null, authorized: s.authorized, authError: s.authorized ? null : (s.authorizationError ? String(s.authorizationError) : null), chain });
s.end();
});
} catch (e) { return fin({ ok: false, ms: Date.now() - t0, err: e.code || e.message }); }
s.on('error', (e) => fin({ ok: false, ms: Date.now() - t0, err: e.code || String(e.message).slice(0, 80) }));
s.on('timeout', () => { s.destroy(); fin({ ok: false, ms: Date.now() - t0, err: 'timeout' }); });
});
}
function head(host, adresa, port = 443) {
return new Promise((res) => {
const t0 = Date.now();
const req = https.request({ host, port, servername: host, path: '/', method: 'HEAD', timeout: 8000, ...(adresa ? { lookup: lookupFixat(adresa) } : {}), headers: { 'user-agent': 'aere-quantum-readiness/1 (+https://aere.network/quantum-readiness.html)' }, rejectUnauthorized: false }, (r) => {
res({ ok: true, status: r.statusCode, hsts: r.headers['strict-transport-security'] || null, ms: Date.now() - t0 }); r.resume();
});
req.on('error', (e) => res({ ok: false, err: e.code || String(e.message).slice(0, 60) })); req.on('timeout', () => { req.destroy(); res({ ok: false, err: 'timeout' }); }); req.end();
});
}
export async function scaneaza(domain, { rezolva = (d) => dns.lookup(d, { all: true }) } = {}) {
const measuredAt = new Date().toISOString();
let addrs;
try { addrs = await rezolva(domain); } catch (e) { return { domain, measuredAt, from: FROM, error: 'dns', detail: e.code || 'unresolvable' }; }
// GARDA (2026-09-18): scanerul e public si fara cheie. O gazda care se rezolva, fie si PARTIAL, la o adresa care nu e dovedit
// publica nu primeste NICIO conexiune si raspunsul nu ii spune adresele: altfel oricine isi indreapta un nume spre reteaua
// noastra interna si afla din raport ce porturi 443 sunt deschise acolo si ce certificate poarta (masurat pe serviciul viu:
// o gazda straina rezolvata la 127.0.0.1 si ::1 a fost sondata). Conexiunile merg apoi pe adresa VERIFICATA, nu pe nume:
// intre verificare si conexiune numele nu se mai rezolva a doua oara.
if (!Array.isArray(addrs) || !addrs.length) return { domain, measuredAt, from: FROM, error: 'dns', detail: 'unresolvable' };
if (addrs.some((a) => ipPrivat(a.address))) return { domain, measuredAt, from: FROM, error: 'private_target', detail: 'the hostname resolves to an address that is not public; nothing was connected to' };
const tinta = addrs.find((a) => a.family === 4) || addrs[0];
return scaneazaAdresa(domain, tinta, { measuredAt, addrs });
}
// scaneazaAdresa: masuratoarea propriu-zisa pe o adresa DEJA verificata. NU are garda de adrese private: serviciul HTTP cheama numai
// `scaneaza` (de mai sus), care o pune; aceasta e pentru apelantii care au verificat singuri tinta si pentru probele locale ale
// remedierii (2026-09-28, control-plane/remediere.mjs: un server TLS pe 127.0.0.1, pe alt port decat 443, fara jurnalul serviciului).
export async function scaneazaAdresa(domain, tinta, { port = 443, measuredAt = new Date().toISOString(), addrs = [tinta], jurnal = true } = {}) {
// linia de baza cere EXPLICIT grupurile clasice: grupul implicit al lui OpenSSL 3.5 pune hibridul primul, deci fara
// lista explicita chiar linia de baza ar negocia ML-KEM si controlul metodei (grupul clasic are nume) ar cadea
const base = await probe(domain, { minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3', ecdhCurve: 'X25519:P-256:P-384' }, tinta, port);
const modern = await probe(domain, { minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3' }, tinta, port); // ce primeste un client OpenSSL 3.5 la zi
const pq1 = await probe(domain, { minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3', ecdhCurve: PQ_GROUP }, tinta, port);
const pq2 = pq1.ok ? null : await probe(domain, { minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3', ecdhCurve: PQ_GROUP_2 }, tinta, port);
const pref = await probe(domain, { minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3', ecdhCurve: `${PQ_GROUP}:X25519:P-256` }, tinta, port);
const t12 = await probe(domain, { minVersion: 'TLSv1.2', maxVersion: 'TLSv1.2' }, tinta, port);
const h = await head(domain, tinta, port);
const tls13 = base.ok;
const pqKex = pq1.ok ? PQ_GROUP : (pq2 && pq2.ok ? PQ_GROUP_2 : null);
// controlul pozitiv al metodei de deducere: grupul clasic trebuie sa iasa CU nume; daca nu iese, deducerea nu e valida
const metodaOk = base.ok && typeof base.groupName === 'string' && base.groupName.length > 0;
const prefersPq = pqKex && pref.ok ? (metodaOk ? (pref.groupName === null) : null) : (pqKex ? false : null);
const leaf = (base.ok ? base : t12).chain?.[0] || null;
const daysLeft = leaf?.validTo ? Math.floor((Date.parse(leaf.validTo) - Date.now()) / 86400e3) : null;
const findings = []; let score = 100;
const add = (id, severity, title, detail, recommendation, penalty) => { findings.push({ id, severity, title, detail, recommendation }); score -= penalty; };
if (!tls13 && !t12.ok) return { domain, measuredAt, from: FROM, error: 'no_tls', detail: base.err || t12.err, addresses: addrs.map((a) => a.address) };
if (!tls13) add('tls13-missing', 'high', 'TLS 1.3 is not offered', `Only TLS 1.2 handshakes succeeded (${t12.err ? '' : t12.cipher}). Post-quantum key exchange exists only in TLS 1.3.`, 'Enable TLS 1.3 on the edge or load balancer; then enable a hybrid post-quantum group.', 15);
if (!pqKex) add('hndl-exposed', 'high', 'No post-quantum key exchange: harvest-now-decrypt-later exposure', `The server refused a TLS 1.3 handshake offering only ${PQ_GROUP} (${pq1.err || 'handshake failure'})${pq2 ? ` and ${PQ_GROUP_2} (${pq2.err || 'handshake failure'})` : ''}. Every session recorded today is decryptable once a cryptographically relevant quantum computer exists.`, `Enable the hybrid group ${PQ_GROUP} (X25519 + ML-KEM-768, FIPS 203). Cloudflare, Google, Amazon and modern OpenSSL/BoringSSL stacks support it; browsers already send it.`, 45);
else if (prefersPq === false) add('pq-not-preferred', 'medium', 'Post-quantum key exchange is supported but not preferred', `With ${PQ_GROUP} offered first alongside classical groups, the server picked ${pref.groupName || 'a classical group'}.`, 'Order the hybrid group first in the server preference list so every capable client gets it.', 10);
else if (prefersPq === null && pqKex) add('pq-preference-unmeasured', 'info', 'Post-quantum key exchange is supported; preference could not be inferred', 'The method control (a classical group must report its name) did not pass, so no claim is made about preference.', null, 0);
if (t12.ok) add('tls12-accepted', 'medium', 'TLS 1.2 is still accepted', `A TLS 1.2-only client was served (${t12.cipher}). Such sessions never get post-quantum key exchange.`, 'Retire TLS 1.2 once your client population allows it, or at least prefer TLS 1.3.', 10);
if (h.ok && !h.hsts) add('hsts-missing', 'low', 'No HSTS header', 'Strict-Transport-Security is absent on the front page, so a first visit can be downgraded to plaintext.', 'Send Strict-Transport-Security with a max-age of at least one year.', 5);
if (leaf) {
if (daysLeft !== null && daysLeft < 7) add('cert-expiring', 'high', 'Certificate expires in less than 7 days', `Leaf certificate valid to ${leaf.validTo}.`, 'Renew now and automate renewal.', 20);
else if (daysLeft !== null && daysLeft < 30) add('cert-expiring', 'medium', 'Certificate expires in less than 30 days', `Leaf certificate valid to ${leaf.validTo}.`, 'Automate renewal (ACME) so rotation never depends on a person.', 10);
if (/^RSA$/.test(leaf.keyType) && leaf.bits && leaf.bits < 3072) add('rsa-short', 'low', `RSA-${leaf.bits} leaf key`, 'Below the 3072-bit size recommended for keys living past 2030 (classical strength).', 'Move to ECDSA P-256/P-384 or RSA-3072+ at the next issuance.', 5);
add('auth-classical', 'info', `Certificate authentication is classical (${leaf.keyType}${leaf.bits ? '-' + leaf.bits : ''})`, 'Every public web certificate today is signed with ECDSA or RSA; a quantum adversary could forge such signatures in the future, but unlike encryption this cannot be exploited retroactively on recorded traffic.', 'Keep certificate agility: short-lived, automatically issued certificates, so switching to hybrid or post-quantum certificates is a configuration change when CAs offer them.', 0);
}
if (!base.authorized && base.ok) add('chain-untrusted', 'medium', 'Certificate chain not trusted by a standard root store', String(base.authError || ''), 'Serve the full intermediate chain from a publicly trusted CA.', 10);
score = Math.max(0, score);
const verdict = score >= 80 ? 'post-quantum key exchange in place' : score >= 50 ? 'partially prepared' : 'exposed';
const report = {
domain, measuredAt, from: FROM, addresses: addrs.map((a) => a.address), score, verdict,
summary: { tls13, pqKeyExchange: pqKex, prefersPqWhenOffered: prefersPq, tls12Accepted: t12.ok, hsts: h.ok ? !!h.hsts : null, harvestNowDecryptLater: pqKex ? 'protected for TLS 1.3 clients that offer the hybrid group' : 'exposed', certificate: leaf ? { keyType: leaf.keyType, bits: leaf.bits, issuer: leaf.issuer, validTo: leaf.validTo, daysLeft } : null },
handshakes: { classicalBaseline: base, modernClientDefault: modern, pqOnly: pq1, pqOnlyAlt: pq2, pqPreferredOffer: pref, tls12Only: t12, head: h },
findings,
method: 'Five real connections from the AERE Cloud host (EU): a TLS 1.3 baseline; TLS 1.3 offering only X25519MLKEM768 (then SecP256r1MLKEM768); TLS 1.3 offering the hybrid group first with classical fallbacks (preference inferred, with a method control); TLS 1.2 only; and an HTTPS HEAD for HSTS. Certificate facts come from the served chain. This measures the public TLS edge of one hostname; it does not measure your applications, keys at rest, internal services or code, which a full quantum readiness assessment covers.',
};
if (jurnal) try { appendFileSync(`${JURNAL_DIR}/scanari.jsonl`, JSON.stringify({ t: measuredAt, domain, score, pqKex: !!pqKex }) + '\n'); } catch {}
return report;
}
function ritmOk(ip) {
const now = Date.now(); const l = (ritm.get(ip) || []).filter((t) => now - t < 60e3);
if (l.length >= 12) { ritm.set(ip, l); return false; }
l.push(now); ritm.set(ip, l); return true;
}
function json(res, cod, obj) { const b = JSON.stringify(obj); res.writeHead(cod, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(b), 'cache-control': 'no-store' }); res.end(b); }
const corp = (req) => new Promise((res, rej) => { let s = ''; req.on('data', (d) => { s += d; if (s.length > 4096) { rej(new Error('too_big')); req.destroy(); } }); req.on('end', () => res(s)); req.on('error', rej); });
export async function cuLimita(fn) {
if (inLucru >= MAX_PARALEL) {
if (coada.length >= MAX_COADA) { const e = new Error('busy'); e.busy = true; throw e; }
await new Promise((r) => coada.push(r));
}
inLucru++;
try { return await fn(); } finally { inLucru--; const n = coada.shift(); if (n) n(); }
}
const RULAT_DIRECT = process.argv[1] && process.argv[1].replace(/\\/g, '/').endsWith('/readiness-service.mjs');
if (RULAT_DIRECT) http.createServer(async (req, res) => {
try {
const url = new URL(req.url, 'http://localhost');
if (req.method === 'GET' && url.pathname === '/health') return json(res, 200, { ok: true, openssl: process.versions.openssl, pqGroup: PQ_GROUP, cached: cache.size, inProgress: inLucru });
// seria de adoptie PQ (adoptie-pq.mjs): editia cea mai noua sau una datata; numai agregatul public, niciodata dosarul privat
const editie = /^\/adoption(?:\/(\d{4}-\d{2}-\d{2}))?$/.exec(url.pathname);
if (req.method === 'GET' && editie) {
try { return json(res, 200, JSON.parse(readFileSync(`${ADOPTIE_DIR}/${editie[1] || 'latest'}.json`, 'utf8'))); }
catch { return json(res, 404, { error: 'no_edition', hint: editie[1] ? 'no edition was published on that date' : 'the first weekly edition is not published yet' }); }
}
// B-16 (2026-09-29): limita de ritm se tine pe clientul numit de gateway (x-aere-client, calculat din Cloudflare si nginx), NU pe
// X-Forwarded-For: primul lui element il alege clientul, deci limita se ocolea schimbandu-l. Serviciul asculta numai pe
// 127.0.0.1, deci antetul il poate pune numai cine ruleaza pe gazda (gateway-ul).
const ip = String(req.headers['x-aere-client'] || req.socket.remoteAddress || '').trim();
let domain = null, fresh = false;
if (req.method === 'POST' && url.pathname === '/scan') {
let b; try { b = JSON.parse((await corp(req)) || 'null'); } catch { return json(res, 400, { error: 'bad_json' }); }
domain = String(b?.domain || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/.*$/, '').replace(/:\d+$/, '');
fresh = b?.fresh === true;
} else if (req.method === 'GET' && url.pathname.startsWith('/scan/')) {
domain = decodeURIComponent(url.pathname.slice(6)).trim().toLowerCase();
} else return json(res, 404, { error: 'not_found' });
if (!domeniuValid(domain)) return json(res, 400, { error: 'bad_domain', hint: 'a public hostname, e.g. example.com' });
const c = cache.get(domain);
if (c && !fresh && Date.now() - c.at < TTL_MS) return json(res, 200, { ...c.report, cached: true });
if (req.method === 'GET') return json(res, 404, { error: 'not_scanned_yet', hint: 'POST /scan {"domain": "..."}' });
if (!ritmOk(ip)) return json(res, 429, { error: 'rate_limited', hint: 'at most 12 scans per minute per client' });
let report;
try { report = await cuLimita(() => scaneaza(domain)); } catch (e) { if (e && e.busy) return json(res, 503, { error: 'busy', hint: 'too many scans are waiting; retry in a minute' }); throw e; }
if (!report.error) cache.set(domain, { at: Date.now(), report });
if (cache.size > 5000) { const k = cache.keys().next().value; cache.delete(k); }
return json(res, report.error ? 422 : 200, report);
} catch (e) { return json(res, 500, { error: 'internal', detail: String(e.message || e).slice(0, 80) }); }
}).listen(PORT, '127.0.0.1', () => console.log(`aere-quantum-readiness on 127.0.0.1:${PORT}, OpenSSL ${process.versions.openssl}, group ${PQ_GROUP}`));