@hardkeel/quantum-scan 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,333 @@
1
+ // This machine: reads local encryption settings only. No network connections, no changes,
2
+ // and private keys are never opened (only .pub files and certificates).
3
+ import { execFileSync } from "node:child_process";
4
+ import { X509Certificate } from "node:crypto";
5
+ import { readdirSync, readFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { ALGORITHMS } from "./rules.js";
9
+ import { emptyResult } from "./map-types.js";
10
+ import { certKey, certSignature, sshFindings } from "./map-web.js";
11
+ export const realIO = {
12
+ platform: process.platform,
13
+ home: homedir(),
14
+ read(p) {
15
+ try {
16
+ return readFileSync(p, "utf8");
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ },
22
+ list(d) {
23
+ try {
24
+ return readdirSync(d);
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ },
30
+ run(cmd, args) {
31
+ try {
32
+ return execFileSync(cmd, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 15000, windowsHide: true });
33
+ }
34
+ catch (e) {
35
+ // ssh -V prints to stderr and some tools exit non-zero while still answering.
36
+ const err = e;
37
+ const out = `${err.stdout ?? ""}${err.stderr ?? ""}`;
38
+ return out || null;
39
+ }
40
+ },
41
+ };
42
+ /** First value of each setting wins, as in sshd. Follows Include lines one level deep. */
43
+ export function parseSshd(text, io, dir, out = {}) {
44
+ for (const raw of text.split(/\r?\n/)) {
45
+ const line = raw.trim();
46
+ if (!line || line.startsWith("#"))
47
+ continue;
48
+ if (/^match\s/i.test(line))
49
+ break; // settings after Match apply only to some users
50
+ const m = line.match(/^(\S+)\s+(.+)$/);
51
+ if (!m)
52
+ continue;
53
+ const key = m[1].toLowerCase();
54
+ const val = m[2].trim();
55
+ if (key === "include" && io && dir) {
56
+ for (const pattern of val.split(/\s+/)) {
57
+ const full = pattern.startsWith("/") || /^[A-Za-z]:/.test(pattern) ? pattern : join(dir, pattern);
58
+ const star = full.lastIndexOf("*");
59
+ if (star >= 0) {
60
+ const folder = full.slice(0, full.lastIndexOf("/", star));
61
+ const suffix = full.slice(star + 1);
62
+ for (const f of (io.list(folder) ?? []).filter((n) => n.endsWith(suffix)).sort()) {
63
+ const t = io.read(join(folder, f));
64
+ if (t)
65
+ parseSshd(t, undefined, undefined, out);
66
+ }
67
+ }
68
+ else {
69
+ const t = io.read(full);
70
+ if (t)
71
+ parseSshd(t, undefined, undefined, out);
72
+ }
73
+ }
74
+ }
75
+ if (key === "kexalgorithms")
76
+ out.kex ??= val;
77
+ if (key === "ciphers")
78
+ out.ciphers ??= val;
79
+ if (key === "macs")
80
+ out.macs ??= val;
81
+ if (key === "hostkeyalgorithms")
82
+ out.hostKeyAlgorithms ??= val;
83
+ }
84
+ return out;
85
+ }
86
+ /** OpenSSH version from `ssh -V`, e.g. 9.6. */
87
+ export function opensshVersion(text) {
88
+ const m = text?.match(/OpenSSH_for_Windows_(\d+)\.(\d+)|OpenSSH_(\d+)\.(\d+)/);
89
+ if (!m)
90
+ return null;
91
+ return Number(m[1] ?? m[3]) + Number(m[2] ?? m[4]) / 10;
92
+ }
93
+ const explicit = (v) => (v && !/^[+\-^]/.test(v) ? v.split(",").map((s) => s.trim()) : null);
94
+ function checkSshd(io, log, res) {
95
+ const dir = io.platform === "win32" ? "C:/ProgramData/ssh" : "/etc/ssh";
96
+ const path = `${dir}/sshd_config`;
97
+ const text = io.read(path);
98
+ if (text === null)
99
+ return; // no SSH server here
100
+ log.record("host", path, "read SSH server settings");
101
+ res.checked.push(path);
102
+ const s = parseSshd(text, io, dir);
103
+ const version = opensshVersion(io.run("ssh", ["-V"]));
104
+ log.record("host", "ssh -V", "read the installed OpenSSH version");
105
+ const kex = explicit(s.kex);
106
+ // Defaults: OpenSSH 9.0 added sntrup761x25519 by default, 9.9 added mlkem768x25519.
107
+ const defaultPqc = version !== null && version >= 9.0;
108
+ const lists = {
109
+ kex: kex ?? (defaultPqc ? ["sntrup761x25519-sha512"] : ["curve25519-sha256"]),
110
+ ciphers: explicit(s.ciphers) ?? [],
111
+ macs: explicit(s.macs) ?? [],
112
+ hostKeys: explicit(s.hostKeyAlgorithms) ?? [],
113
+ };
114
+ const r = sshFindings(lists, "host", path, false);
115
+ // Host keys are judged from the key files below, not the algorithm list.
116
+ res.findings.push(...r.findings.filter((f) => f.ruleId !== "ssh-host-key"));
117
+ if (r.pqc)
118
+ res.strengths.push({ area: "host", target: path, algorithm: "Hybrid SSH key exchange", title: kex ? "SSH server allows quantum-safe hybrid key exchange" : `SSH server uses quantum-safe hybrid key exchange by default (OpenSSH ${version})` });
119
+ if (!kex && version === null)
120
+ res.skipped.push({ target: path, reason: "couldn't read the OpenSSH version, so the default key exchange is a guess" });
121
+ }
122
+ // ---------- public key files ----------
123
+ /** Type and size of an OpenSSH public key line. Never reads private keys. */
124
+ export function sshPublicKey(line) {
125
+ const m = line.trim().match(/^(ssh-rsa|ssh-dss|ssh-ed25519|ssh-ed448|ecdsa-sha2-nistp\d+|sk-[a-z0-9@.-]+)\s+([A-Za-z0-9+/=]+)/);
126
+ if (!m)
127
+ return null;
128
+ if (m[1] !== "ssh-rsa")
129
+ return { type: m[1] };
130
+ try {
131
+ const b = Buffer.from(m[2], "base64");
132
+ let off = 0;
133
+ const next = () => {
134
+ const len = b.readUInt32BE(off);
135
+ const v = b.subarray(off + 4, off + 4 + len);
136
+ off += 4 + len;
137
+ return v;
138
+ };
139
+ next(); // "ssh-rsa"
140
+ next(); // e
141
+ const n = next();
142
+ const lead = n[0] === 0 ? 1 : 0;
143
+ const bytes = n.length - lead;
144
+ const topBits = 8 - Math.clz32(n[lead]) + 24;
145
+ return { type: "ssh-rsa", bits: (bytes - 1) * 8 + topBits };
146
+ }
147
+ catch {
148
+ return { type: "ssh-rsa" };
149
+ }
150
+ }
151
+ function keyFinding(path, k, role) {
152
+ const base = { area: "host", target: path, internetFacing: false };
153
+ if (k.type === "ssh-dss")
154
+ return { ...base, ruleId: "host-key-dsa", title: `${role} uses DSA`, algorithm: "DSA", primitive: "signature", risk: "weak-now", severity: "high", fix: ALGORITHMS.DSA.fix };
155
+ if (k.type === "ssh-rsa" && k.bits && k.bits < 2048)
156
+ return { ...base, ruleId: "host-key-small-rsa", title: `${role} uses a ${k.bits}-bit RSA key`, algorithm: "RSA", primitive: "signature", risk: "weak-now", severity: "high", keySize: k.bits, fix: "Replace with an Ed25519 key, or RSA of at least 3072 bits." };
157
+ const alg = k.type === "ssh-rsa" ? "RSA signature" : k.type.includes("ed25519") ? "Ed25519" : k.type.includes("ed448") ? "Ed448" : "ECDSA";
158
+ return { ...base, ruleId: "host-key-quantum", title: `${role} uses ${alg === "RSA signature" ? `${k.bits ?? ""}-bit RSA`.trim() : alg}`, algorithm: alg, primitive: "signature", risk: "quantum-vulnerable", severity: "medium", keySize: k.bits, fix: "Keep it for now; plan to move to post-quantum signatures once OpenSSH supports them." };
159
+ }
160
+ function checkKeyFiles(io, log, res) {
161
+ const dirs = [
162
+ [io.platform === "win32" ? "C:/ProgramData/ssh" : "/etc/ssh", "SSH host key"],
163
+ [join(io.home, ".ssh"), "Your SSH key"],
164
+ ];
165
+ for (const [dir, role] of dirs) {
166
+ const names = io.list(dir);
167
+ if (!names)
168
+ continue;
169
+ for (const name of names.filter((n) => n.endsWith(".pub")).sort()) {
170
+ const path = join(dir, name).split("\\").join("/");
171
+ const text = io.read(path);
172
+ if (!text)
173
+ continue;
174
+ log.record("host", path, "read public key type and size");
175
+ const k = sshPublicKey(text);
176
+ if (!k)
177
+ continue;
178
+ res.checked.push(path);
179
+ res.findings.push(keyFinding(path, k, role));
180
+ }
181
+ }
182
+ }
183
+ // ---------- OpenSSL and system policy ----------
184
+ export function opensslPolicyFindings(text, path) {
185
+ const out = [];
186
+ const base = { area: "host", target: path, internetFacing: false };
187
+ const min = text.match(/^\s*MinProtocol\s*=\s*(\S+)/im)?.[1];
188
+ if (min && /^(TLSv1|TLSv1\.1|SSLv3)$/i.test(min)) {
189
+ const a = ALGORITHMS["TLS 1.0/1.1"];
190
+ out.push({ ...base, ruleId: "host-openssl-old-tls", title: `OpenSSL allows ${min} system-wide`, algorithm: "TLS 1.0/1.1", primitive: a.primitive, risk: a.risk, severity: a.severity, fix: "Set MinProtocol = TLSv1.2 in the OpenSSL config." });
191
+ }
192
+ const level = text.match(/^\s*CipherString\s*=.*@SECLEVEL=(\d)/im)?.[1];
193
+ if (level !== undefined && Number(level) < 2) {
194
+ out.push({ ...base, ruleId: "host-openssl-seclevel", title: `OpenSSL security level lowered to ${level}`, algorithm: "Weak TLS ciphers", primitive: "protocol", risk: "weak-now", severity: "medium", fix: "Use @SECLEVEL=2 or higher, which blocks SHA-1 and keys under 2048 bits." });
195
+ }
196
+ return out;
197
+ }
198
+ function checkOpenssl(io, log, res) {
199
+ if (io.platform === "win32")
200
+ return;
201
+ for (const path of ["/etc/ssl/openssl.cnf", "/usr/lib/ssl/openssl.cnf", "/etc/pki/tls/openssl.cnf", "/opt/homebrew/etc/openssl@3/openssl.cnf"]) {
202
+ const text = io.read(path);
203
+ if (text === null)
204
+ continue;
205
+ log.record("host", path, "read OpenSSL settings");
206
+ res.checked.push(path);
207
+ res.findings.push(...opensslPolicyFindings(text, path));
208
+ }
209
+ const policy = io.read("/etc/crypto-policies/config");
210
+ if (policy !== null) {
211
+ log.record("host", "/etc/crypto-policies/config", "read the system encryption policy");
212
+ res.checked.push("/etc/crypto-policies/config");
213
+ if (/^\s*LEGACY/m.test(policy)) {
214
+ res.findings.push({ area: "host", target: "/etc/crypto-policies/config", internetFacing: false, ruleId: "host-crypto-policy-legacy", title: "System encryption policy is LEGACY", algorithm: "Weak TLS ciphers", primitive: "protocol", risk: "weak-now", severity: "medium", fix: "Run update-crypto-policies --set DEFAULT (or FUTURE)." });
215
+ }
216
+ }
217
+ }
218
+ // ---------- certificates ----------
219
+ function certFromPem(pem) {
220
+ try {
221
+ return new X509Certificate(pem);
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ }
227
+ export function localCertFindings(c, now = Date.now()) {
228
+ const base = { area: "host", target: c.target, internetFacing: false };
229
+ const out = [];
230
+ if (c.notAfter < now)
231
+ out.push({ ...base, ruleId: "host-cert-expired", title: `${c.label} has expired`, algorithm: "Expired certificate", primitive: "protocol", risk: "weak-now", severity: "medium", fix: "Renew or remove the expired certificate." });
232
+ if (c.sigWeak)
233
+ out.push({ ...base, ruleId: "host-cert-weak-signature", title: `${c.label} is signed with SHA-1`, algorithm: "SHA-1", primitive: "hash", risk: "weak-now", severity: "high", fix: "Reissue it signed with SHA-256 or stronger." });
234
+ if (c.keyType === "RSA" && c.bits && c.bits < 2048)
235
+ out.push({ ...base, ruleId: "host-cert-small-rsa", title: `${c.label} uses a ${c.bits}-bit RSA key`, algorithm: "RSA", primitive: "signature", risk: "weak-now", severity: "high", keySize: c.bits, fix: "Reissue with at least a 2048-bit RSA key, or ECDSA P-256." });
236
+ else if (c.keyType === "RSA" || c.keyType === "ECDSA" || c.keyType === "Ed25519") {
237
+ out.push({ ...base, ruleId: c.isCa ? "host-ca-quantum" : "host-cert-quantum", title: `${c.label} uses ${c.keyType === "RSA" ? `${c.bits ?? ""}-bit RSA`.trim() : c.keyType}`, algorithm: c.keyType === "RSA" ? "RSA signature" : c.keyType, primitive: "signature", risk: "quantum-vulnerable", severity: "medium", keySize: c.bits, longLived: c.isCa, fix: c.isCa ? "Certificate authorities stay trusted for years: plan an ML-DSA authority by 2030." : "Plan to move to ML-DSA certificates once your certificate authority offers them." });
238
+ }
239
+ return out;
240
+ }
241
+ function checkLinuxCerts(io, log, res) {
242
+ if (io.platform === "win32")
243
+ return;
244
+ const live = "/etc/letsencrypt/live";
245
+ for (const name of io.list(live) ?? []) {
246
+ const path = `${live}/${name}/cert.pem`;
247
+ const pem = io.read(path);
248
+ if (!pem)
249
+ continue;
250
+ log.record("host", path, "read certificate details");
251
+ const cert = certFromPem(pem);
252
+ if (!cert)
253
+ continue;
254
+ res.checked.push(path);
255
+ const k = certKey(cert);
256
+ res.findings.push(...localCertFindings({ keyType: k.type, bits: k.bits, sigWeak: Boolean(certSignature(Buffer.from(cert.raw))?.weak), notAfter: Date.parse(cert.validTo), label: `Certificate for ${name}`, target: path }));
257
+ }
258
+ }
259
+ // ---------- Windows ----------
260
+ /** Protocols and ciphers explicitly turned on in the Schannel registry. Missing keys mean the Windows default. */
261
+ export function parseSchannel(text) {
262
+ const enabledProtocols = [];
263
+ const enabledCiphers = [];
264
+ let key = "";
265
+ for (const raw of text.split(/\r?\n/)) {
266
+ const line = raw.trim();
267
+ if (/^HKEY_/i.test(line)) {
268
+ key = line;
269
+ continue;
270
+ }
271
+ const m = line.match(/^Enabled\s+REG_DWORD\s+0x([0-9a-f]+)/i);
272
+ if (!m || Number.parseInt(m[1], 16) === 0)
273
+ continue;
274
+ const proto = key.match(/\\Protocols\\(SSL 2\.0|SSL 3\.0|TLS 1\.0|TLS 1\.1)\\Server$/i);
275
+ if (proto)
276
+ enabledProtocols.push(proto[1]);
277
+ const cipher = key.match(/\\Ciphers\\(Triple DES 168|DES 56\/56|RC4 [0-9/]+|NULL)$/i);
278
+ if (cipher)
279
+ enabledCiphers.push(cipher[1]);
280
+ }
281
+ return { enabledProtocols, enabledCiphers };
282
+ }
283
+ const CERT_PS = "Get-ChildItem Cert:\\LocalMachine\\My | ForEach-Object { $s = $null; try { $s = $_.PublicKey.Key.KeySize } catch {}; [pscustomobject]@{ Subject = $_.Subject; NotAfter = $_.NotAfter.ToUniversalTime().ToString('o'); Sig = $_.SignatureAlgorithm.FriendlyName; Key = $_.PublicKey.Oid.FriendlyName; Size = $s } } | ConvertTo-Json -Compress";
284
+ export function parseWindowsCerts(json) {
285
+ try {
286
+ const v = JSON.parse(json.trim() || "[]");
287
+ const list = Array.isArray(v) ? v : [v];
288
+ return list.map((c) => ({ subject: String(c.Subject ?? ""), notAfter: Date.parse(c.NotAfter), sig: String(c.Sig ?? ""), key: String(c.Key ?? ""), size: typeof c.Size === "number" ? c.Size : undefined }));
289
+ }
290
+ catch {
291
+ return [];
292
+ }
293
+ }
294
+ function checkWindows(io, log, res) {
295
+ if (io.platform !== "win32")
296
+ return;
297
+ const reg = "HKLM\\SYSTEM\\CurrentControlSet\\Control\\SecurityProviders\\SCHANNEL";
298
+ const text = io.run("reg", ["query", reg, "/s"]);
299
+ log.record("host", reg, "read Windows TLS (Schannel) settings");
300
+ if (text) {
301
+ res.checked.push(reg);
302
+ const s = parseSchannel(text);
303
+ const base = { area: "host", target: reg, internetFacing: false };
304
+ if (s.enabledProtocols.length) {
305
+ const a = ALGORITHMS["TLS 1.0/1.1"];
306
+ res.findings.push({ ...base, ruleId: "host-schannel-old-tls", title: `Windows has ${s.enabledProtocols.join(" and ")} turned on for servers`, algorithm: "TLS 1.0/1.1", primitive: a.primitive, risk: a.risk, severity: a.severity, fix: "Set Enabled to 0 for these protocols under SCHANNEL\\Protocols, or remove the keys on Windows Server 2022 and later." });
307
+ }
308
+ if (s.enabledCiphers.length) {
309
+ res.findings.push({ ...base, ruleId: "host-schannel-weak-cipher", title: `Windows has ${s.enabledCiphers.join(" and ")} turned on`, algorithm: "Weak TLS ciphers", primitive: "protocol", risk: "weak-now", severity: "high", fix: "Set Enabled to 0 for these ciphers under SCHANNEL\\Ciphers." });
310
+ }
311
+ }
312
+ const json = io.run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", CERT_PS]);
313
+ log.record("host", "Cert:\\LocalMachine\\My", "read this machine's certificate details");
314
+ for (const c of parseWindowsCerts(json ?? "")) {
315
+ const keyType = /RSA/i.test(c.key) ? "RSA" : /EC|ECC|ECDSA/i.test(c.key) ? "ECDSA" : "other";
316
+ const cn = c.subject.match(/CN=([^,]+)/)?.[1] ?? "a certificate";
317
+ res.findings.push(...localCertFindings({ keyType, bits: keyType === "RSA" ? c.size : undefined, sigWeak: /sha1|md5/i.test(c.sig), notAfter: c.notAfter, label: `Certificate for ${cn}`, target: "Cert:\\LocalMachine\\My" }));
318
+ }
319
+ if (json !== null)
320
+ res.checked.push("Cert:\\LocalMachine\\My");
321
+ }
322
+ export function runHost(log, io = realIO) {
323
+ const res = emptyResult("host");
324
+ for (const step of [checkSshd, checkKeyFiles, checkOpenssl, checkLinuxCerts, checkWindows]) {
325
+ try {
326
+ step(io, log, res);
327
+ }
328
+ catch (e) {
329
+ res.errors.push({ area: "host", target: step.name, kind: "read", message: e instanceof Error ? e.message : String(e) });
330
+ }
331
+ }
332
+ return res;
333
+ }
@@ -0,0 +1,48 @@
1
+ // Ranks every finding by what breaks first, and turns code findings into map findings.
2
+ export function tierOf(f) {
3
+ if (f.risk !== "quantum-vulnerable")
4
+ return 1;
5
+ if ((f.primitive === "key-agreement" || f.primitive === "public-key-encryption") && f.internetFacing)
6
+ return 2;
7
+ if (f.primitive === "signature" && f.longLived)
8
+ return 3;
9
+ return 4;
10
+ }
11
+ const SEV = { critical: 0, high: 1, medium: 2, low: 3 };
12
+ export function rank(findings) {
13
+ return findings
14
+ .map((f) => ({ ...f, tier: tierOf(f) }))
15
+ .sort((a, b) => a.tier - b.tier || SEV[a.severity] - SEV[b.severity] || a.area.localeCompare(b.area) || a.target.localeCompare(b.target));
16
+ }
17
+ export function fromCodeFinding(f) {
18
+ return {
19
+ area: "code",
20
+ target: `${f.file}:${f.line}`,
21
+ ruleId: f.ruleId,
22
+ title: f.title,
23
+ algorithm: f.algorithm,
24
+ primitive: f.primitive,
25
+ risk: f.risk,
26
+ severity: f.severity,
27
+ fix: f.fix,
28
+ internetFacing: false,
29
+ keySize: f.keySize,
30
+ };
31
+ }
32
+ /** Back to the code scanner's shape, so the CycloneDX inventory builder can be reused. */
33
+ export function toFinding(f) {
34
+ return {
35
+ kind: f.risk === "secret" ? "secret" : f.risk === "exposed" || f.primitive === "setting" ? "config" : "crypto",
36
+ ruleId: f.ruleId,
37
+ title: f.title,
38
+ algorithm: f.algorithm,
39
+ primitive: f.primitive,
40
+ risk: f.risk,
41
+ severity: f.severity,
42
+ file: f.target,
43
+ line: 0,
44
+ snippet: "",
45
+ fix: f.fix,
46
+ keySize: f.keySize,
47
+ };
48
+ }
@@ -0,0 +1,138 @@
1
+ // The encryption map report: text for the terminal, one self-contained HTML page, and JSON.
2
+ // Written to the customer's own disk. Nothing here is sent anywhere.
3
+ import { TIER_NOTES, TIER_TITLES } from "./map-types.js";
4
+ import { toFinding } from "./map-rank.js";
5
+ import { gradeSentence, readinessScore } from "./score.js";
6
+ /** Post-quantum methods already in use count toward the score the same way they do in a code scan. */
7
+ function strengthSignals(strengths) {
8
+ return strengths.map((s) => ({ algorithm: s.algorithm, use: /DSA/.test(s.algorithm) ? "signature" : "key-establishment", file: s.target, line: 0 }));
9
+ }
10
+ const AREA_TITLES = { code: "Code and config", web: "Websites and public services", host: "This machine", network: "Internal network", vpn: "VPNs", cloud: "Cloud" };
11
+ export function buildMapReport(results, ranked, version, now = new Date(), accepted = []) {
12
+ const strengths = results.flatMap((r) => r.strengths);
13
+ const counts = { 1: 0, 2: 0, 3: 0, 4: 0 };
14
+ for (const f of ranked)
15
+ counts[f.tier]++;
16
+ return {
17
+ tool: "hard-keel-quantum-scan",
18
+ version,
19
+ createdAt: now.toISOString(),
20
+ areas: results.map((r) => ({ area: r.area, checked: r.checked.length, skipped: r.skipped, errors: r.errors.map(({ target, kind, message }) => ({ target, kind, message })) })),
21
+ score: readinessScore(ranked.map(toFinding), strengthSignals(strengths)),
22
+ counts,
23
+ findings: ranked,
24
+ strengths,
25
+ accepted,
26
+ };
27
+ }
28
+ export function mapText(r) {
29
+ const out = ["Hard Keel Quantum Scan · encryption map", "", gradeSentence(r.score), ""];
30
+ for (const a of r.areas) {
31
+ const bits = [`${a.checked} checked`];
32
+ if (a.skipped.length)
33
+ bits.push(`${a.skipped.length} skipped`);
34
+ if (a.errors.length)
35
+ bits.push(`${a.errors.length} couldn't be checked`);
36
+ out.push(` ${AREA_TITLES[a.area] ?? a.area}: ${bits.join(", ")}`);
37
+ }
38
+ const total = r.findings.length;
39
+ out.push("", total ? `${total} finding${total === 1 ? "" : "s"}, ranked by what breaks first.` : "Nothing found in the areas checked.");
40
+ for (const t of [1, 2, 3, 4]) {
41
+ const list = r.findings.filter((f) => f.tier === t);
42
+ if (!list.length)
43
+ continue;
44
+ out.push("", `${t}. ${TIER_TITLES[t]} (${list.length})`, ` ${TIER_NOTES[t]}`);
45
+ for (const f of list.slice(0, 25))
46
+ out.push(` ${f.target} ${f.title}`, ` ${f.fix}`);
47
+ if (list.length > 25)
48
+ out.push(` ...and ${list.length - 25} more in the report.`);
49
+ }
50
+ if (r.strengths.length) {
51
+ out.push("", `Already quantum-safe (${r.strengths.length})`);
52
+ for (const s of r.strengths.slice(0, 10))
53
+ out.push(` ${s.target} ${s.title}`);
54
+ }
55
+ if (r.accepted.length) {
56
+ out.push("", `Accepted as known leftovers (${r.accepted.length}), from ${".quantum-scan-ignore"}; not counted in the score`);
57
+ for (const f of r.accepted.slice(0, 10))
58
+ out.push(` ${f.target} ${f.title}`);
59
+ }
60
+ const errors = r.areas.flatMap((a) => a.errors);
61
+ if (errors.length) {
62
+ out.push("", "Couldn't check");
63
+ for (const e of errors.slice(0, 10))
64
+ out.push(` ${e.target}: ${e.message}`);
65
+ if (errors.length > 10)
66
+ out.push(` ...and ${errors.length - 10} more in the report.`);
67
+ }
68
+ const skipped = r.areas.flatMap((a) => a.skipped);
69
+ if (skipped.length) {
70
+ out.push("", "Skipped");
71
+ for (const s of skipped.slice(0, 10))
72
+ out.push(` ${s.target}: ${s.reason}`);
73
+ if (skipped.length > 10)
74
+ out.push(` ...and ${skipped.length - 10} more in the report.`);
75
+ }
76
+ return out.join("\n");
77
+ }
78
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
79
+ export function mapHtml(r, activity) {
80
+ const row = (f) => `<tr><td class="area">${esc(AREA_TITLES[f.area] ?? f.area)}</td><td class="mono">${esc(f.target)}</td><td>${esc(f.title)}<div class="fix">${esc(f.fix)}</div></td></tr>`;
81
+ const table = (list) => `<table><thead><tr><th class="area">Area</th><th>Where</th><th>What and how to fix it</th></tr></thead><tbody>${list.map(row).join("")}</tbody></table>`;
82
+ const tiers = [1, 2, 3, 4]
83
+ .map((t) => {
84
+ const list = r.findings.filter((f) => f.tier === t);
85
+ if (!list.length)
86
+ return "";
87
+ return `<section><h2><span class="n">${t}</span>${esc(TIER_TITLES[t])} <span class="count">${list.length}</span></h2><p class="note">${esc(TIER_NOTES[t])}</p>${table(list)}</section>`;
88
+ })
89
+ .join("");
90
+ const strengths = r.strengths.length
91
+ ? `<section><h2>Already quantum-safe <span class="count">${r.strengths.length}</span></h2><ul>${r.strengths.map((s) => `<li><span class="mono">${esc(s.target)}</span> ${esc(s.title)}</li>`).join("")}</ul></section>`
92
+ : "";
93
+ const accepted = r.accepted.length
94
+ ? `<section><h2>Accepted as known leftovers <span class="count">${r.accepted.length}</span></h2><p class="note">Marked in .quantum-scan-ignore. Listed here so nothing is hidden, but left out of the counts and the score.</p>${table(r.accepted)}</section>`
95
+ : "";
96
+ const areas = r.areas
97
+ .map((a) => {
98
+ const extra = [...a.skipped.map((s) => `${s.target}: ${s.reason}`), ...a.errors.map((e) => `${e.target}: couldn't check (${e.message})`)];
99
+ return `<li><strong>${esc(AREA_TITLES[a.area] ?? a.area)}</strong>: ${a.checked} checked${extra.length ? `<ul>${extra.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>` : ""}</li>`;
100
+ })
101
+ .join("");
102
+ const summary = [1, 2, 3, 4].map((t) => `<div class="tile t${t}"><div class="big">${r.counts[t]}</div><div>${esc(TIER_TITLES[t])}</div></div>`).join("");
103
+ const g = r.score;
104
+ const gradeClass = g.grade.startsWith("A") ? "good" : g.grade === "B" ? "ok" : "bad";
105
+ return `<!doctype html>
106
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
107
+ <meta name="color-scheme" content="light dark">
108
+ <title>Encryption map · Hard Keel Quantum Scan</title>
109
+ <style>
110
+ :root{--bg:#ffffff;--fg:#111a21;--muted:#5b6873;--accent:#2f7d71;--line:rgba(0,0,0,.1);--bad:#b4412f;--warn:#93630f;--good:#2f7d71}
111
+ @media (prefers-color-scheme:dark){:root{--bg:#0a0e12;--fg:#eef2f5;--muted:#8f9da9;--accent:#5aa99d;--line:rgba(255,255,255,.09);--bad:#e07a6a;--warn:#e0b25a;--good:#5aa99d}}
112
+ @media print{:root{--bg:#fff;--fg:#000;--muted:#444;--accent:#2f7d71;--line:#ccc;--bad:#a0301f;--warn:#7a520c;--good:#2f7d71}details{display:none}section{break-inside:auto}tr{break-inside:avoid}}
113
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.6 Inter,system-ui,-apple-system,sans-serif}
114
+ main{max-width:1000px;margin:0 auto;padding:40px 20px 80px}h1{font-size:28px;margin:0}h2{font-size:18px;margin:40px 0 4px;display:flex;align-items:center;gap:10px}
115
+ .eyebrow{font:12px "IBM Plex Mono",ui-monospace,monospace;letter-spacing:.3em;color:var(--accent);text-transform:uppercase}
116
+ .muted,.note{color:var(--muted)}.note{margin:0 0 12px}.n{display:inline-grid;place-items:center;width:26px;height:26px;border-radius:50%;border:1px solid var(--accent);color:var(--accent);font-size:13px;flex:none}
117
+ .count{color:var(--muted);font-weight:400}.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin:20px 0 28px}
118
+ .tile{border:1px solid var(--line);border-radius:10px;padding:14px}.big{font-size:28px;font-weight:600}.t1 .big{color:var(--bad)}.t2 .big{color:var(--warn)}
119
+ .score{display:flex;gap:18px;align-items:center;border:1px solid var(--line);border-radius:12px;padding:16px 18px;margin-top:28px}
120
+ .grade{font-size:40px;font-weight:700;line-height:1;min-width:64px;text-align:center}.grade.good{color:var(--good)}.grade.ok{color:var(--warn)}.grade.bad{color:var(--bad)}
121
+ table{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;vertical-align:top;padding:9px 8px;border-top:1px solid var(--line)}th{color:var(--muted);font-weight:500}
122
+ .mono{font-family:"IBM Plex Mono",ui-monospace,monospace;font-size:12.5px;word-break:break-all}.fix{color:var(--muted);margin-top:2px}
123
+ details{margin-top:40px}pre{white-space:pre-wrap;font-size:12px;color:var(--muted)}a{color:var(--accent)}
124
+ @media (max-width:640px){.area{display:none}td.mono{width:38%}h1{font-size:24px}.grade{font-size:32px;min-width:48px}}
125
+ </style></head><body><main>
126
+ <div class="eyebrow">Hard Keel Quantum Scan</div><h1>Encryption map</h1>
127
+ <p class="muted">Created ${esc(r.createdAt.slice(0, 16).replace("T", " "))} UTC on this machine. This report stays on your computer unless you share it.</p>
128
+ <div class="score"><div class="grade ${gradeClass}">${esc(g.grade)}</div><div><strong>Quantum readiness ${g.score}/100</strong><div class="muted">${esc(gradeSentence(g).replace(/^Quantum readiness: [^.]+\.\s*/, ""))} Hard Keel method v${esc(g.method)}, the same as a code scan, across every area checked.</div></div></div>
129
+ <div class="tiles">${summary}</div>
130
+ ${tiers || "<p>Nothing found in the areas checked.</p>"}
131
+ ${strengths}
132
+ ${accepted}
133
+ <section><h2>What was checked</h2><ul>${areas}</ul></section>
134
+ <details><summary>Activity log (${activity.length} entries)</summary><pre>${esc(activity.join("\n"))}</pre></details>
135
+ <p class="muted" style="margin-top:40px">Look-only checks: normal connections and local settings. No logins, changes or attack traffic. <a href="https://hardkeel.com/quantum-scan/">hardkeel.com</a></p>
136
+ </main></body></html>
137
+ `;
138
+ }