@hardkeel/benthic 0.0.0-stage → 1.0.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/LICENSE +92 -0
  3. package/NOTICE +16 -0
  4. package/README.md +424 -2
  5. package/action.yml +54 -0
  6. package/dist/agility.js +80 -0
  7. package/dist/badge.js +62 -0
  8. package/dist/baseline.js +81 -0
  9. package/dist/cbom-diff.js +273 -0
  10. package/dist/cbom.js +418 -0
  11. package/dist/cli.js +834 -0
  12. package/dist/cloud-aws-services.js +375 -0
  13. package/dist/cloud-aws.js +354 -0
  14. package/dist/cloud-azure-services.js +73 -0
  15. package/dist/cloud-azure.js +144 -0
  16. package/dist/cloud-common.js +242 -0
  17. package/dist/cloud-gcp-services.js +90 -0
  18. package/dist/cloud-gcp.js +150 -0
  19. package/dist/comments.js +138 -0
  20. package/dist/community-rules.js +37 -0
  21. package/dist/community.js +30 -0
  22. package/dist/deps.js +406 -0
  23. package/dist/der.js +571 -0
  24. package/dist/evidence-cli.js +235 -0
  25. package/dist/evidence-live.js +109 -0
  26. package/dist/evidence.js +512 -0
  27. package/dist/ignore.js +90 -0
  28. package/dist/image.js +1224 -0
  29. package/dist/infra.js +635 -0
  30. package/dist/inventory.js +277 -0
  31. package/dist/map-activity.js +24 -0
  32. package/dist/map-areas.js +60 -0
  33. package/dist/map-cloud-keys.js +110 -0
  34. package/dist/map-cloud.js +34 -0
  35. package/dist/map-ct.js +107 -0
  36. package/dist/map-host.js +335 -0
  37. package/dist/map-network.js +520 -0
  38. package/dist/map-people.js +79 -0
  39. package/dist/map-rank.js +70 -0
  40. package/dist/map-report.js +304 -0
  41. package/dist/map-run.js +327 -0
  42. package/dist/map-sarif.js +61 -0
  43. package/dist/map-signin.js +247 -0
  44. package/dist/map-types.js +19 -0
  45. package/dist/map-web.js +666 -0
  46. package/dist/native.js +168 -0
  47. package/dist/policy.js +221 -0
  48. package/dist/pqc.js +46 -0
  49. package/dist/profile.js +65 -0
  50. package/dist/project.js +928 -0
  51. package/dist/prose.js +159 -0
  52. package/dist/protocols.js +207 -0
  53. package/dist/registry.js +326 -0
  54. package/dist/report.js +190 -0
  55. package/dist/rules.js +230 -0
  56. package/dist/sarif-common.js +30 -0
  57. package/dist/sarif.js +114 -0
  58. package/dist/scan.js +601 -0
  59. package/dist/score.js +124 -0
  60. package/dist/secrets.js +192 -0
  61. package/dist/share-config.js +129 -0
  62. package/dist/share-lists.js +19 -0
  63. package/dist/share.js +125 -0
  64. package/dist/sonar.js +83 -0
  65. package/dist/structure.js +218 -0
  66. package/dist/suites.js +402 -0
  67. package/dist/tls-check.js +122 -0
  68. package/dist/types.js +4 -0
  69. package/dist/walk.js +78 -0
  70. package/dist/yaml.js +173 -0
  71. package/package.json +73 -4
@@ -0,0 +1,277 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // The full encryption inventory: every algorithm the code uses, not only the ones to fix.
4
+ // Findings cover what quantum computers will break or what is weak now. This records the rest
5
+ // (AES, ChaCha20, SHA-2, SHA-3, HMAC, key derivation, and post-quantum algorithms) with key length,
6
+ // mode and what it's used for, so the CBOM is a complete list. Nothing here changes the grade.
7
+ import { langFor } from "./rules.js";
8
+ import { COMMENT_LINE, stripTrailingComment } from "./comments.js";
9
+ import { inDetectionTable, inProse, isTranslationFile } from "./prose.js";
10
+ import { latticeLevelCaution } from "./agility.js";
11
+ const CIPHER_FNS = ["encrypt", "decrypt"];
12
+ /** AES with a known key size and mode. */
13
+ function aes(bits, mode) {
14
+ const m = mode?.toLowerCase();
15
+ if (m === "ecb")
16
+ return null; // a finding already covers ECB
17
+ const ae = m === "gcm" || m === "ccm" || m === "siv" || m === "ocb" || m === "gcm-siv";
18
+ const name = `AES${bits ? `-${bits}` : ""}${m ? `-${m.toUpperCase()}` : ""}`;
19
+ return {
20
+ algorithm: name,
21
+ family: "AES",
22
+ primitive: ae ? "ae" : "block-cipher",
23
+ functions: CIPHER_FNS,
24
+ ...(bits ? { keySize: bits, nistQuantumLevel: bits === 128 ? 1 : bits === 192 ? 3 : bits === 256 ? 5 : undefined } : {}),
25
+ ...(m ? { mode: m } : {}),
26
+ ...(bits === 128 ? { note: "Fine today. Prefer AES-256 for data that must stay secret for decades." } : {}),
27
+ ...(!ae && m === "cbc" ? { note: "CBC has no built-in integrity check. Prefer GCM, or add an HMAC." } : {}),
28
+ };
29
+ }
30
+ /** SHA-2 and SHA-3 by any common spelling: sha256, SHA-384, sha3_256, SHA3-512. */
31
+ function sha(word) {
32
+ const w = word.toLowerCase().replace(/[^a-z0-9]/g, "");
33
+ const s3 = w.match(/^sha3(224|256|384|512)$/);
34
+ if (s3) {
35
+ const bits = Number(s3[1]);
36
+ return { algorithm: `SHA3-${bits}`, family: "SHA-3", primitive: "hash", functions: ["digest"], keySize: bits, ...level(bits) };
37
+ }
38
+ const s2 = w.match(/^sha(224|256|384|512)(?:224|256)?$/);
39
+ if (s2) {
40
+ const bits = Number(s2[1]);
41
+ const name = /^sha512(224|256)$/.test(w) ? `SHA-512/${w.slice(6)}` : `SHA-${bits}`;
42
+ return { algorithm: name, family: "SHA-2", primitive: "hash", functions: ["digest"], keySize: bits, ...level(bits) };
43
+ }
44
+ if (/^blake2[bs]/.test(w))
45
+ return { algorithm: w.startsWith("blake2b") ? "BLAKE2b" : "BLAKE2s", family: "BLAKE2", primitive: "hash", functions: ["digest"] };
46
+ if (w === "blake3")
47
+ return { algorithm: "BLAKE3", family: "BLAKE3", primitive: "hash", functions: ["digest"] };
48
+ return null;
49
+ }
50
+ /** NIST defines categories 2 and 4 by SHA-256 and SHA-384 collision search. */
51
+ function level(bits) {
52
+ return bits === 256 ? { nistQuantumLevel: 2 } : bits === 384 ? { nistQuantumLevel: 4 } : {};
53
+ }
54
+ /** "SHA-256" -> "SHA256" as HMAC and PBKDF2 names spell it; "SHA3-256" stays. */
55
+ const short = (alg) => alg.replace(/^SHA-/, "SHA");
56
+ function hmac(hashWord) {
57
+ const h = sha(hashWord);
58
+ if (!h)
59
+ return null; // HMAC-MD5 and HMAC-SHA1 are findings already
60
+ return { algorithm: `HMAC-${short(h.algorithm)}`, family: "HMAC", primitive: "mac", functions: ["tag"] };
61
+ }
62
+ function kdf(name, hashWord) {
63
+ const h = hashWord ? sha(hashWord) : null;
64
+ return { algorithm: h ? `${name}-${short(h.algorithm)}` : name, family: name, primitive: "kdf", functions: ["keyderive"] };
65
+ }
66
+ const CHACHA = { algorithm: "ChaCha20-Poly1305", family: "ChaCha20", primitive: "ae", functions: CIPHER_FNS, keySize: 256 };
67
+ /** "aes-256-gcm", "aes256", "aes-128-cbc", "id-aes256-GCM" */
68
+ function aesName(s) {
69
+ const m = s.toLowerCase().match(/aes[-_]?(128|192|256)?(?:[-_/](gcm-siv|gcm|cbc|ctr|ccm|cfb|ofb|ecb|siv|ocb|wrap))?/);
70
+ if (!m)
71
+ return null;
72
+ return aes(m[1] ? Number(m[1]) : undefined, m[2]);
73
+ }
74
+ const NUM = (s) => (s ? Number(s) : undefined);
75
+ // ---------- Stateful hash-based signatures (LMS/HSS and XMSS/XMSS^MT, NIST SP 800-208) ----------
76
+ const STATEFUL_NOTE = "Stateful: each one-time key signs once. Never restore the signing state from a backup or share it between machines.";
77
+ const SHA2_MARGIN = "The SHA-256 parameter sets have a thinner margin than their nominal level against multi-target attacks, as discussed on the IETF CFRG and NIST pqc-forum lists. Experts there call this certificational, not a practical break. Prefer the SHAKE256 sets in new designs; existing ones need no rush.";
78
+ const PREHASH = "For long messages, sign a fixed-length hash of the message (such as SHA-512), not the message itself.";
79
+ function hashSet(h) {
80
+ const w = h.toUpperCase();
81
+ if (w.startsWith("SHA"))
82
+ return w.startsWith("SHAKE") ? (w === "SHAKE256" ? "shake256" : "shake128") : "sha2";
83
+ return "sha2";
84
+ }
85
+ /** LMS_SHA256_M32_H10, lms_shake256_n24_h15 (Bouncy Castle), LMS-SHAKE-M24-H20. */
86
+ function lms(hash, n, h) {
87
+ const shake = /shake/i.test(hash);
88
+ return {
89
+ algorithm: `LMS-${shake ? "SHAKE" : "SHA256"}-M${n}-H${h}`,
90
+ family: "LMS",
91
+ primitive: "signature",
92
+ functions: ["sign", "verify"],
93
+ note: `${STATEFUL_NOTE} Up to 2^${h} signatures per key.`,
94
+ ...(shake ? { risk: "quantum-safe" } : { risk: "check", caution: SHA2_MARGIN }),
95
+ };
96
+ }
97
+ function lmots(hash, n, w) {
98
+ const shake = /shake/i.test(hash);
99
+ return {
100
+ algorithm: `LM-OTS-${shake ? "SHAKE" : "SHA256"}-N${n}-W${w}`,
101
+ family: "LMS",
102
+ primitive: "signature",
103
+ functions: ["sign", "verify"],
104
+ note: STATEFUL_NOTE,
105
+ ...(shake ? { risk: "quantum-safe" } : { risk: "check", caution: SHA2_MARGIN }),
106
+ };
107
+ }
108
+ /** XMSS-SHA2_10_256, XMSSMT-SHA2_20/2_256, XMSS-SHAKE256_16_192 (SP 800-208), XMSS-SHAKE_10_256 (RFC 8391, SHAKE128). */
109
+ function xmss(mt, hash, height, layers, n) {
110
+ const set = hashSet(hash);
111
+ const name = `XMSS${mt ? "MT" : ""}-${set === "sha2" ? "SHA2" : set === "shake256" ? "SHAKE256" : "SHAKE"}_${height}${layers ? `/${layers}` : ""}_${n}`;
112
+ const base = { algorithm: name, family: mt ? "XMSS^MT" : "XMSS", primitive: "signature", functions: ["sign", "verify"], note: `${STATEFUL_NOTE} Up to 2^${height} signatures per key.` };
113
+ if (n === "512" || set === "shake128") {
114
+ const why = set === "shake128" ? "uses SHAKE128 and" : "uses 64-byte hashes and";
115
+ return { ...base, risk: "check", caution: `${name} is defined in RFC 8391 but ${why} is not one of the parameter sets NIST SP 800-208 approves. Move to an approved set such as XMSS${mt ? "MT" : ""}-SHAKE256_${height}${layers ? `/${layers}` : ""}_256.` };
116
+ }
117
+ if (set === "sha2")
118
+ return { ...base, risk: "check", caution: `${SHA2_MARGIN} ${PREHASH}` };
119
+ return { ...base, risk: "quantum-safe" };
120
+ }
121
+ export const INVENTORY_RULES = [
122
+ // ---------- Python ----------
123
+ { id: "py-hash", langs: ["python"], pattern: /\bhashlib\.(sha224|sha256|sha384|sha512|sha3_\d{3}|blake2[bs])\s*\(|hashlib\.new\s*\(\s*['"](sha\d{3}|sha3_\d{3}|sha512_\d{3})['"]|\bhashes\.(SHA224|SHA256|SHA384|SHA512|SHA3_\d{3}|BLAKE2[bs])\s*\(/, item: (m) => sha(m[1] ?? m[2] ?? m[3]) },
124
+ { id: "py-hmac", langs: ["python"], pattern: /\bhmac\.(?:new|digest)\s*\([^)]*(?:hashlib\.|['"])(sha\d{3}|sha3_\d{3})/, item: (m) => hmac(m[1]) },
125
+ { id: "py-aesgcm", langs: ["python"], pattern: /\bAESGCM\s*\(|\bAESCCM\s*\(|\bAESGCMSIV\s*\(|\bAESSIV\s*\(|\bAESOCB3\s*\(/, item: (m) => aes(undefined, m[0].match(/AES(GCMSIV|GCM|CCM|SIV|OCB3)/)[1].replace("GCMSIV", "gcm-siv").replace("OCB3", "ocb")) },
126
+ { id: "py-aes-modes", langs: ["python"], pattern: /\balgorithms\.AES(?:128|256)?\s*\(.*\bmodes\.(GCM|CBC|CTR|CFB|OFB)\s*\(|\bAES\.new\s*\(.*\bAES\.MODE_(GCM|CBC|CTR|CCM|EAX|SIV|OCB|CFB|OFB)\b/, item: (m, line) => aes(NUM(line.match(/AES(128|256)\s*\(/)?.[1]), (m[1] ?? m[2]).toLowerCase()) },
127
+ { id: "py-chacha", langs: ["python"], pattern: /\bChaCha20Poly1305\s*\(|\bChaCha20_Poly1305\.new\s*\(/, item: () => CHACHA },
128
+ { id: "py-kdf", langs: ["python"], pattern: /\bPBKDF2HMAC\s*\(|\bhashlib\.pbkdf2_hmac\s*\(\s*['"](sha\d{3})['"]|\bScrypt\s*\(|\bhashlib\.scrypt\s*\(|\bHKDF\s*\(|\bargon2\.|\bPasswordHasher\s*\(|\bbcrypt\.(?:hashpw|gensalt|kdf)\s*\(/, item: (m, line) => {
129
+ const t = m[0];
130
+ if (/PBKDF2HMAC|pbkdf2_hmac/.test(t))
131
+ return kdf("PBKDF2", m[1] ?? line.match(/hashes\.(SHA\d{3})\s*\(/)?.[1]);
132
+ if (/[Ss]crypt/.test(t))
133
+ return kdf("scrypt");
134
+ if (/HKDF/.test(t))
135
+ return kdf("HKDF", line.match(/hashes\.(SHA\d{3})\s*\(/)?.[1]);
136
+ if (/bcrypt/.test(t))
137
+ return kdf("bcrypt");
138
+ return kdf("Argon2");
139
+ } },
140
+ // ---------- JavaScript / TypeScript ----------
141
+ { id: "js-hash", langs: ["js"], pattern: /\bcreateHash\s*\(\s*['"`](sha224|sha256|sha384|sha512|sha3-\d{3}|sha512-\d{3}|blake2[bs]\d*)['"`]/i, item: (m) => sha(m[1]) },
142
+ { id: "js-hmac", langs: ["js"], pattern: /\bcreateHmac\s*\(\s*['"`](sha\d{3}|sha3-\d{3})['"`]/i, item: (m) => hmac(m[1]) },
143
+ { id: "js-cipher", langs: ["js"], pattern: /\bcreate(?:Cipher|Decipher)iv\s*\(\s*['"`](aes[-_a-z0-9]*|chacha20-poly1305)['"`]/i, item: (m) => (/chacha/i.test(m[1]) ? CHACHA : aesName(m[1])) },
144
+ { id: "js-subtle-digest", langs: ["js"], pattern: /\bdigest\s*\(\s*['"`](SHA-256|SHA-384|SHA-512)['"`]/, item: (m) => sha(m[1]) },
145
+ { id: "js-webcrypto-aes", langs: ["js"], pattern: /name\s*:\s*['"`](AES-GCM|AES-CBC|AES-CTR|AES-KW)['"`]/, item: (m, line) => aes(NUM(line.match(/length\s*:\s*(128|192|256)\b/)?.[1]), m[1].slice(4).toLowerCase().replace("kw", "wrap")) },
146
+ { id: "js-webcrypto-hmac", langs: ["js"], pattern: /name\s*:\s*['"`]HMAC['"`].*hash\s*:\s*(?:\{\s*name\s*:\s*)?['"`](SHA-256|SHA-384|SHA-512)['"`]/, item: (m) => hmac(m[1]) },
147
+ { id: "js-kdf", langs: ["js"], pattern: /\bpbkdf2(?:Sync)?\s*\([^)]*['"`](sha\d{3})['"`]|\bscrypt(?:Sync)?\s*\(|\bhkdf(?:Sync)?\s*\(\s*['"`](sha\d{3})['"`]|\bargon2\.hash\s*\(|\bbcrypt\.(?:hash|genSalt)(?:Sync)?\s*\(|name\s*:\s*['"`](PBKDF2|HKDF)['"`]/, item: (m) => {
148
+ const t = m[0];
149
+ if (/pbkdf2|PBKDF2/.test(t))
150
+ return kdf("PBKDF2", m[1]);
151
+ if (/hkdf|HKDF/.test(t))
152
+ return kdf("HKDF", m[2]);
153
+ if (/scrypt/.test(t))
154
+ return kdf("scrypt");
155
+ if (/bcrypt/.test(t))
156
+ return kdf("bcrypt");
157
+ return kdf("Argon2");
158
+ } },
159
+ // ---------- Go ----------
160
+ { id: "go-hash", langs: ["go"], pattern: /\b(sha256|sha512|sha3)\.(New|New224|New384|New512_224|New512_256|Sum256|Sum224|Sum384|Sum512|Sum512_256|New256)\s*\(/, item: (m) => {
161
+ if (m[1] === "sha3")
162
+ return sha(`sha3${m[2].match(/\d{3}/)?.[0] ?? "256"}`);
163
+ const d = m[2].match(/\d{3}(?:_\d{3})?/)?.[0];
164
+ if (m[1] === "sha256")
165
+ return sha(d === "224" ? "sha224" : "sha256");
166
+ return sha(d ? `sha${d.replace("_", "")}` : "sha512");
167
+ } },
168
+ { id: "go-hmac", langs: ["go"], pattern: /\bhmac\.New\s*\(\s*(sha256|sha512|sha3)\.(New\w*)/, item: (m) => hmac(m[1] === "sha3" ? "sha3256" : m[1] === "sha512" && /384/.test(m[2]) ? "sha384" : m[1]) },
169
+ { id: "go-aes", langs: ["go"], pattern: /\baes\.NewCipher\s*\(/, item: () => aes(undefined, undefined) },
170
+ { id: "go-gcm", langs: ["go"], pattern: /\bcipher\.NewGCM(?:WithNonceSize|WithTagSize|WithRandomNonce)?\s*\(/, item: () => aes(undefined, "gcm") },
171
+ { id: "go-chacha", langs: ["go"], pattern: /\bchacha20poly1305\.NewX?\s*\(/, item: () => CHACHA },
172
+ { id: "go-kdf", langs: ["go"], pattern: /\bpbkdf2\.Key\s*\([^)]*\b(sha256|sha512)\.New|\bscrypt\.Key\s*\(|\bargon2\.I?D?Key\s*\(|\bbcrypt\.GenerateFromPassword\s*\(|\bhkdf\.(?:New|Key|Extract)\s*\(\s*(sha256|sha512)\.New/, item: (m) => {
173
+ const t = m[0];
174
+ if (t.startsWith("pbkdf2"))
175
+ return kdf("PBKDF2", m[1]);
176
+ if (t.startsWith("hkdf"))
177
+ return kdf("HKDF", m[2]);
178
+ if (t.startsWith("scrypt"))
179
+ return kdf("scrypt");
180
+ if (t.startsWith("bcrypt"))
181
+ return kdf("bcrypt");
182
+ return kdf("Argon2");
183
+ } },
184
+ // ---------- Java / Kotlin ----------
185
+ { id: "java-hash", langs: ["java"], pattern: /MessageDigest\.getInstance\s*\(\s*"(SHA-?224|SHA-?256|SHA-?384|SHA-?512|SHA3-\d{3})"/, item: (m) => sha(m[1]) },
186
+ { id: "java-hmac", langs: ["java"], pattern: /Mac\.getInstance\s*\(\s*"Hmac(SHA\d{3}|SHA3-\d{3})"/, item: (m) => hmac(m[1]) },
187
+ { id: "java-cipher", langs: ["java"], pattern: /Cipher\.getInstance\s*\(\s*"(AES(?:_(?:128|256))?\/(?:GCM|CBC|CTR|CCM)[^"]*|ChaCha20-Poly1305)"/, item: (m) => (/ChaCha/.test(m[1]) ? CHACHA : aes(NUM(m[1].match(/AES_(128|256)/)?.[1]), m[1].split("/")[1].toLowerCase())) },
188
+ { id: "java-kdf", langs: ["java"], pattern: /SecretKeyFactory\.getInstance\s*\(\s*"PBKDF2WithHmac(SHA\d{3})"|\bBCrypt\.(?:hashpw|gensalt)\s*\(|\bArgon2PasswordEncoder\b|\bSCryptPasswordEncoder\b|\bBCryptPasswordEncoder\b/, item: (m) => (m[1] ? kdf("PBKDF2", m[1]) : /Argon2/.test(m[0]) ? kdf("Argon2") : /SCrypt/.test(m[0]) ? kdf("scrypt") : kdf("bcrypt")) },
189
+ { id: "java-aes-keygen", langs: ["java"], pattern: /KeyGenerator\.getInstance\s*\(\s*"AES"/, item: () => aes(undefined, undefined) },
190
+ { id: "java-aes-keysize", langs: ["java"], pattern: /\b\w*(?:keyGen|KeyGen|generator|Generator)\w*\.init\s*\(\s*(128|192|256)\s*\)/, item: (m) => aes(Number(m[1]), undefined) },
191
+ // ---------- Post-quantum (any of the languages above, and config) ----------
192
+ { id: "pqc-mlkem", langs: ["python", "js", "go", "java", "config"], pattern: /\b(?:ML[-_]?KEM|MLKEM)[-_]?(512|768|1024)\b|\bKyber(512|768|1024)\b/i, item: (m, line) => (/(?:X25519|SecP256r1|SecP384r1)[-_]?MLKEM/i.test(line) ? null : { algorithm: `ML-KEM-${m[1] ?? m[2]}`, family: "ML-KEM", primitive: "kem", functions: ["keygen", "encapsulate", "decapsulate"], nistQuantumLevel: { 512: 1, 768: 3, 1024: 5 }[Number(m[1] ?? m[2])], ...latticeLevelCaution(`ML-KEM-${m[1] ?? m[2]}`) }) },
193
+ { id: "pqc-hybrid", langs: ["python", "js", "go", "java", "config"], pattern: /\b(X25519|SecP256r1|SecP384r1)[-_]?MLKEM[-_]?(768|1024)\b/i, item: (m) => ({ algorithm: `${m[1]}MLKEM${m[2]}`, family: "ML-KEM", primitive: "kem", functions: ["keygen", "encapsulate", "decapsulate"], nistQuantumLevel: m[2] === "1024" ? 5 : 3, note: "Hybrid: classical and ML-KEM together." }) },
194
+ { id: "pqc-mldsa", langs: ["python", "js", "go", "java", "config"], pattern: /\b(?:ML[-_]?DSA|MLDSA)[-_]?(44|65|87)\b|\bDilithium([235])\b/i, item: (m) => {
195
+ const p = m[1] ?? { "2": "44", "3": "65", "5": "87" }[m[2]];
196
+ return { algorithm: `ML-DSA-${p}`, family: "ML-DSA", primitive: "signature", functions: ["sign", "verify"], nistQuantumLevel: { "44": 2, "65": 3, "87": 5 }[p], ...latticeLevelCaution(`ML-DSA-${p}`) };
197
+ } },
198
+ { id: "pqc-slhdsa", langs: ["python", "js", "go", "java", "config"], pattern: /\bSLH[-_]?DSA(?:[-_](SHA2|SHAKE)[-_](128|192|256)[sf])?\b|\bSPHINCS\+/i, item: (m) => ({ algorithm: m[2] ? `SLH-DSA-${m[1].toUpperCase()}-${m[2]}` : "SLH-DSA", family: "SLH-DSA", primitive: "signature", functions: ["sign", "verify"], ...(m[2] ? { nistQuantumLevel: { 128: 1, 192: 3, 256: 5 }[Number(m[2])] } : {}) }) },
199
+ { id: "eth-address", langs: ["python", "js", "go", "java", "config"], native: true, pattern: /(?<![0-9A-Za-z])0x([0-9a-fA-F]{40})(?![0-9A-Za-z])/, item: (m, line) => ethAddress(m[1], line) },
200
+ { id: "pqc-lms", langs: ["python", "js", "go", "java", "config"], native: true, pattern: /(?<![A-Za-z0-9])LMS[-_]?(SHA256|SHAKE(?:256)?)[-_]?[MN](32|24)[-_]?H(5|10|15|20|25)(?![0-9])/i, item: (m) => lms(m[1], m[2], m[3]) },
201
+ { id: "pqc-lmots", langs: ["python", "js", "go", "java", "config"], native: true, pattern: /(?<![A-Za-z0-9])LM[-_]?OTS[-_]?(SHA256|SHAKE(?:256)?)[-_]?N(32|24)[-_]?W(1|2|4|8)(?![0-9])/i, item: (m) => lmots(m[1], m[2], m[3]) },
202
+ { id: "pqc-xmss", langs: ["python", "js", "go", "java", "config"], native: true, pattern: /(?<![A-Za-z0-9])XMSS(MT)?[-_](SHA2|SHAKE256|SHAKE)_(\d{1,2})(?:\/(\d{1,2}))?_(192|256|512)(?![0-9])/i, item: (m) => xmss(m[1], m[2], m[3], m[4], m[5]) },
203
+ ];
204
+ const CODE_OR_CONFIG_LANGS = new Set(["python", "js", "go", "java", "config"]);
205
+ const OTHER_CODE = /\.(c|cc|cpp|cxx|h|hh|hpp|rs|cs|swift|m|mm|rb|php|ex|exs|zig|sol|vy)$/i;
206
+ // An account address in code or settings: a wallet, signer, owner or treasury.
207
+ const ADDRESS_CONTEXT = /address|wallet|account|signer|owner|treasury|recipient|admin|operator|deployer|multisig|beneficiary|payee|payout/i;
208
+ const NOT_ADDRESS_CONTEXT = /hash|\btx|commit|topic|selector|salt|nonce|checksum|sha1|digest/i;
209
+ const ADDRESS_NOTE = "If this is an account someone holds a key for (not a contract), a secp256k1 key controls it. A quantum computer could work out that key from the public key, which an account reveals the first time it signs a transaction. Contract addresses aren't controlled by a key.";
210
+ function ethAddress(hex, line) {
211
+ if (!ADDRESS_CONTEXT.test(line) || NOT_ADDRESS_CONTEXT.test(line))
212
+ return null;
213
+ // The zero address and burn addresses belong to no one.
214
+ if (/^0{40}$/.test(hex) || /^0+dead$/i.test(hex) || /^dead0*$/i.test(hex))
215
+ return null;
216
+ return { algorithm: "Ethereum address (secp256k1)", family: "ECDSA", primitive: "signature", functions: ["sign", "verify"], nistQuantumLevel: 0, risk: "check", caution: ADDRESS_NOTE };
217
+ }
218
+ /** Every non-weak algorithm used in one file. Comments and documentation are ignored. */
219
+ export function findInventory(path, content) {
220
+ const lang = langFor(path);
221
+ const native = !lang && OTHER_CODE.test(path);
222
+ if ((!native && (!lang || !CODE_OR_CONFIG_LANGS.has(lang))) || content.includes("\u0000"))
223
+ return [];
224
+ const rules = INVENTORY_RULES.filter((r) => (native ? r.native : r.langs.includes(lang)));
225
+ const out = [];
226
+ const lines = content.split(/\r?\n/);
227
+ // Translation catalogs and detection tables name algorithms; they don't use them.
228
+ if (isTranslationFile(path, lines))
229
+ return [];
230
+ for (let i = 0; i < lines.length; i++) {
231
+ if (lines[i].length > 2000 || COMMENT_LINE.test(lines[i]))
232
+ continue;
233
+ if (inDetectionTable(lines, i))
234
+ continue;
235
+ const text = stripTrailingComment(lines[i], path);
236
+ const seen = new Set();
237
+ for (const r of rules) {
238
+ const m = text.match(r.pattern);
239
+ if (!m)
240
+ continue;
241
+ if (inProse(text, m.index ?? 0, (m.index ?? 0) + m[0].length, path))
242
+ continue;
243
+ const item = r.item(m, text);
244
+ if (!item || seen.has(item.algorithm))
245
+ continue;
246
+ // A rule that only knows the family (AES with no size) adds nothing next to a fuller one on the same line.
247
+ if ([...seen].some((s) => s.startsWith(item.algorithm + "-")))
248
+ continue;
249
+ seen.add(item.algorithm);
250
+ out.push({ ...item, file: path, line: i + 1 });
251
+ }
252
+ }
253
+ // Drop a bare "AES" or "AES-GCM" when the same line also named the full one.
254
+ // Likewise a bare hash that is part of an HMAC or key derivation named on the same line.
255
+ return out.filter((x) => !out.some((y) => y !== x &&
256
+ y.line === x.line &&
257
+ (y.algorithm.startsWith(x.algorithm + "-") || (x.primitive === "hash" && (y.primitive === "mac" || y.primitive === "kdf") && y.algorithm.endsWith("-" + short(x.algorithm))))));
258
+ }
259
+ /** One line per algorithm that has a caution, for the text summary. */
260
+ export function inventoryCautions(items) {
261
+ // Grouped by what the caution says, so LMS and its LM-OTS setting on one line read as one note.
262
+ const by = new Map();
263
+ for (const i of items)
264
+ if (i.caution)
265
+ by.set(i.caution, [...(by.get(i.caution) ?? []), i]);
266
+ return [...by.values()].map((list) => {
267
+ const names = [...new Set(list.map((i) => i.algorithm))];
268
+ return { algorithm: names.slice(0, 3).join(", ") + (names.length > 3 ? ` and ${names.length - 3} more` : ""), at: `${list[0].file}:${list[0].line}`, caution: list[0].caution, more: list.length - 1 };
269
+ });
270
+ }
271
+ /** Counts by algorithm, for the text summary. */
272
+ export function inventoryCounts(items) {
273
+ const c = new Map();
274
+ for (const i of items)
275
+ c.set(i.algorithm, (c.get(i.algorithm) ?? 0) + 1);
276
+ return [...c.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
277
+ }
@@ -0,0 +1,24 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Activity log: every connection and every file the encryption map reads, with time, target and reason.
4
+ // Written next to the report, so a customer can hand it to their security team.
5
+ import { appendFileSync } from "node:fs";
6
+ export class ActivityLog {
7
+ entries = [];
8
+ file;
9
+ constructor(file) {
10
+ this.file = file;
11
+ }
12
+ record(area, target, what) {
13
+ const line = `${new Date().toISOString()} ${area.padEnd(5)} ${target} ${what}`;
14
+ this.entries.push(line);
15
+ if (this.file) {
16
+ try {
17
+ appendFileSync(this.file, line + "\n");
18
+ }
19
+ catch {
20
+ // the log in memory still goes into the report
21
+ }
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,60 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // The permission card for each area: what it touches, what it reads, what it never does.
4
+ // Shown before an area runs. The answer is no unless the person says yes.
5
+ const list = (t) => (t.length <= 4 ? t.join(", ") : `${t.slice(0, 3).join(", ")} and ${t.length - 3} more`);
6
+ export const CARDS = {
7
+ code: {
8
+ area: "code",
9
+ title: "Code and config",
10
+ touch: (t) => `the files in ${list(t)}.`,
11
+ read: "source code and infrastructure config, in memory, to find encryption, leaked keys and exposed settings.",
12
+ never: "change a file, run any code, or send code anywhere.",
13
+ cost: "Reads files only. No network connections.",
14
+ },
15
+ web: {
16
+ area: "web",
17
+ title: "Websites and public services",
18
+ touch: (t) => `${t.length} address${t.length === 1 ? "" : "es"} (${list(t)}), each under a domain you proved you own with a DNS record.`,
19
+ read: "the encryption each one offers when connecting, the same handshake a browser makes, and its certificate. For SSH addresses, the settings the server announces before any login.",
20
+ never: "log in, test for vulnerabilities, send attack traffic, or touch any address you haven't proved.",
21
+ cost: "About 6 connections per address, one at a time.",
22
+ },
23
+ network: {
24
+ area: "network",
25
+ title: "Network and connected equipment",
26
+ touch: (t) => `the addresses in ${list(t)}: private ranges on your own network only, at most 1,024 addresses.`,
27
+ read: "which of about 30 common ports answer on each device, the title of any web page they serve, the certificate on secure admin pages, and the router's list of automatic port forwards (UPnP), if it publishes one.",
28
+ never: "log in, try a password, send commands to equipment, change a setting, or touch any address outside these ranges.",
29
+ cost: "One connection at a time per device, a few a second. Usually a few minutes.",
30
+ warning: "Some older industrial, medical or building controllers can misbehave even when gently connected to. List any under exclude in the scope file, or answer no and skip this area.",
31
+ },
32
+ host: {
33
+ area: "host",
34
+ title: "This machine",
35
+ touch: () => "this computer only.",
36
+ read: "SSH and TLS settings, Windows encryption settings, the machine's own certificates, and the type and size of public key files.",
37
+ never: "change a setting, read a private key, or connect to anything.",
38
+ cost: "Reads local settings only. No network connections.",
39
+ },
40
+ cloud: {
41
+ area: "cloud",
42
+ title: "Cloud accounts",
43
+ touch: (t) => `${list(t)}, through ${t.length === 1 ? "its" : "their"} own command-line tool${t.length === 1 ? "" : "s"} (aws, az, gcloud) and the sign-in already on this machine.`,
44
+ read: "the type and size of each key in the provider's key service (AWS KMS, Azure Key Vault, Google Cloud KMS), the key type of each certificate and certificate authority, the TLS settings of load balancers, CDNs, APIs, apps and file transfer servers, and whether databases, caches, storage and file systems require encryption in transit and at rest.",
45
+ never: "create, change or delete anything, use a key, read a secret or a private key, or ask for, store or send your credentials. Every call is a list, describe, get or show call.",
46
+ cost: "A few dozen read-only calls per region, subscription or project. A whole AWS account usually takes a few minutes.",
47
+ },
48
+ };
49
+ export function cardText(card, targets) {
50
+ const lines = [
51
+ card.title,
52
+ ` What I'll touch: ${card.touch(targets)}`,
53
+ ` What I read: ${card.read}`,
54
+ ` What I never do: ${card.never}`,
55
+ ` ${card.cost}`,
56
+ ];
57
+ if (card.warning)
58
+ lines.push(` ${card.warning}`);
59
+ return lines.join("\n");
60
+ }
@@ -0,0 +1,110 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Who holds the keys to your cloud data. Reads Terraform/OpenTofu and CloudFormation for storage,
4
+ // databases and backups, and notes where the cloud provider holds the encryption keys.
5
+ // Provider-held keys protect against a stolen disk, not against the provider, an insider there,
6
+ // or a legal demand made to them. For data no third party should be able to read, encrypt it
7
+ // before it leaves your hands, or keep the keys yourself.
8
+ // Advice only: it is listed in the map report and does not change the readiness score.
9
+ export const CUSTODY_FIX = {
10
+ provider: "The provider holds the keys, so it can read this data. Encrypt sensitive data before it's uploaded (client-side encryption), or use keys you hold: an external key store such as AWS KMS External Key Store, Google Cloud External Key Manager or Azure Key Vault Managed HSM with your own keys.",
11
+ "provider-kms": "You manage the key, but it lives in the provider's key service, so the provider could still use it. For data no third party should read, encrypt it before upload or move the key to an external key store you hold.",
12
+ };
13
+ /** Resource types we know, what they hold, and which keys name a key you chose. */
14
+ const TF = {
15
+ aws_s3_bucket_server_side_encryption_configuration: { kind: "storage", keyAttr: /kms_master_key_id\s*=/, defaultOn: true },
16
+ aws_db_instance: { kind: "database", keyAttr: /kms_key_id\s*=/, needsOn: /storage_encrypted\s*=\s*true/ },
17
+ aws_rds_cluster: { kind: "database", keyAttr: /kms_key_id\s*=/, needsOn: /storage_encrypted\s*=\s*true/ },
18
+ aws_docdb_cluster: { kind: "database", keyAttr: /kms_key_id\s*=/, needsOn: /storage_encrypted\s*=\s*true/ },
19
+ aws_neptune_cluster: { kind: "database", keyAttr: /kms_key_arn\s*=/, needsOn: /storage_encrypted\s*=\s*true/ },
20
+ aws_redshift_cluster: { kind: "database", keyAttr: /kms_key_id\s*=/, needsOn: /encrypted\s*=\s*true/ },
21
+ aws_dynamodb_table: { kind: "database", keyAttr: /kms_key_arn\s*=/, defaultOn: true },
22
+ aws_ebs_volume: { kind: "disk", keyAttr: /kms_key_id\s*=/, needsOn: /encrypted\s*=\s*true/ },
23
+ aws_efs_file_system: { kind: "storage", keyAttr: /kms_key_id\s*=/, needsOn: /encrypted\s*=\s*true/ },
24
+ aws_backup_vault: { kind: "backup", keyAttr: /kms_key_arn\s*=/, defaultOn: true },
25
+ aws_sqs_queue: { kind: "storage", keyAttr: /kms_master_key_id\s*=/, needsOn: /sqs_managed_sse_enabled\s*=\s*true|kms_master_key_id/ },
26
+ google_storage_bucket: { kind: "storage", keyAttr: /default_kms_key_name\s*=/, defaultOn: true },
27
+ google_sql_database_instance: { kind: "database", keyAttr: /encryption_key_name\s*=/, defaultOn: true },
28
+ google_bigquery_dataset: { kind: "database", keyAttr: /kms_key_name\s*=/, defaultOn: true },
29
+ google_compute_disk: { kind: "disk", keyAttr: /kms_key_self_link\s*=|raw_key\s*=|rsa_encrypted_key\s*=/, defaultOn: true },
30
+ azurerm_storage_account: { kind: "storage", keyAttr: /customer_managed_key\s*\{/, defaultOn: true },
31
+ azurerm_mssql_database: { kind: "database", keyAttr: /transparent_data_encryption_key_vault_key_id\s*=/, defaultOn: true },
32
+ azurerm_postgresql_flexible_server: { kind: "database", keyAttr: /customer_managed_key\s*\{/, defaultOn: true },
33
+ azurerm_cosmosdb_account: { kind: "database", keyAttr: /key_vault_key_id\s*=/, defaultOn: true },
34
+ };
35
+ const KIND_WORD = { storage: "Cloud storage", database: "Cloud database", backup: "Cloud backups", disk: "Cloud disk" };
36
+ function title(kind, c) {
37
+ return c === "provider" ? `${KIND_WORD[kind]} encrypted with keys the provider holds` : `${KIND_WORD[kind]} keys live in the provider's key service`;
38
+ }
39
+ function advice(path, line, resource, kind, custody) {
40
+ return { target: `${path}:${line}`, resource, kind, custody, ruleId: custody === "provider" ? "cloud-provider-held-keys" : "cloud-keys-in-provider-kms", title: title(kind, custody), fix: CUSTODY_FIX[custody] };
41
+ }
42
+ const strip = (s) => s.replace(/"(?:[^"\\]|\\.)*"/g, '""').replace(/#.*$|\/\/.*$/, "");
43
+ /** Terraform resource blocks: type, name, first line (1-based) and body text. */
44
+ export function tfResources(text) {
45
+ const lines = text.split("\n");
46
+ const out = [];
47
+ for (let i = 0; i < lines.length; i++) {
48
+ const m = lines[i].match(/^\s*resource\s+"([a-z0-9_]+)"\s+"([A-Za-z0-9_-]+)"\s*\{/);
49
+ if (!m)
50
+ continue;
51
+ let depth = 0;
52
+ let j = i;
53
+ for (; j < lines.length; j++) {
54
+ for (const ch of strip(lines[j])) {
55
+ if (ch === "{")
56
+ depth++;
57
+ else if (ch === "}")
58
+ depth--;
59
+ }
60
+ if (depth <= 0)
61
+ break;
62
+ }
63
+ out.push({ type: m[1], name: m[2], line: i + 1, body: lines.slice(i + 1, j).map((l) => l.replace(/^\s*(#|\/\/).*$/, "")).join("\n") });
64
+ i = j;
65
+ }
66
+ return out;
67
+ }
68
+ export function cloudKeyAdvice(path, text) {
69
+ const p = path.toLowerCase();
70
+ const out = [];
71
+ if (/\.(tf|hcl)$/.test(p)) {
72
+ const res = tfResources(text);
73
+ // An Azure storage account can get its key from a separate resource in the same file.
74
+ const separateAzureKey = res.some((r) => r.type === "azurerm_storage_account_customer_managed_key");
75
+ for (const r of res) {
76
+ const spec = TF[r.type];
77
+ if (!spec)
78
+ continue;
79
+ if (spec.needsOn && !spec.needsOn.test(r.body))
80
+ continue; // encryption off is already a finding of its own
81
+ const id = `${r.type}.${r.name}`;
82
+ if (r.type === "aws_s3_bucket_server_side_encryption_configuration") {
83
+ const own = !/sse_algorithm\s*=\s*"AES256"/.test(r.body) && spec.keyAttr.test(r.body);
84
+ out.push(advice(path, r.line, id, spec.kind, own ? "provider-kms" : "provider"));
85
+ continue;
86
+ }
87
+ // A customer-supplied key (raw_key or rsa_encrypted_key) is one you hold: Google keeps only a hash of it.
88
+ if (r.type === "google_compute_disk" && /raw_key\s*=|rsa_encrypted_key\s*=/.test(r.body))
89
+ continue;
90
+ if (r.type === "azurerm_storage_account" && separateAzureKey) {
91
+ out.push(advice(path, r.line, id, spec.kind, "provider-kms"));
92
+ continue;
93
+ }
94
+ out.push(advice(path, r.line, id, spec.kind, spec.keyAttr.test(r.body) ? "provider-kms" : "provider"));
95
+ }
96
+ }
97
+ else if (/\.(ya?ml|json|template)$/.test(p) && /AWSTemplateFormatVersion|AWS::/.test(text)) {
98
+ const lines = text.split("\n");
99
+ lines.forEach((l, i) => {
100
+ const m = l.match(/["']?SSEAlgorithm["']?\s*:\s*["']?(AES256|aws:kms)["']?/);
101
+ if (!m)
102
+ return;
103
+ // The key can sit just before or just after (JSON tools often sort keys, putting KMSMasterKeyID first).
104
+ const near = lines.slice(Math.max(0, i - 3), i + 4).join("\n");
105
+ const custody = m[1] === "AES256" || !/KMSMasterKeyID/.test(near) ? "provider" : "provider-kms";
106
+ out.push(advice(path, i + 1, "S3 bucket encryption", "storage", custody));
107
+ });
108
+ }
109
+ return out;
110
+ }
@@ -0,0 +1,34 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Live cloud accounts: reads key, certificate and TLS settings from AWS, Azure and Google Cloud.
4
+ // Runs the provider's own command-line tool (aws, az, gcloud), so it uses the sign-in that tool
5
+ // already has on this machine. This code never reads, stores or sends credentials or keys.
6
+ // Every call is a list, describe, get or show call, checked against a fixed list before it runs.
7
+ // Account ids, names and ARNs stay in the local report; the anonymized summary never sees them.
8
+ import { runAws } from "./cloud-aws.js";
9
+ import { runAzure } from "./cloud-azure.js";
10
+ import { runGcp } from "./cloud-gcp.js";
11
+ import { emptyCloud, realRunner } from "./cloud-common.js";
12
+ export * from "./cloud-common.js";
13
+ /** Checks each provider in the scope, one after another. Each provider records what it reads in the activity log. */
14
+ export async function runCloud(scope, log, o = {}) {
15
+ const runner = o.runner ?? realRunner;
16
+ const all = emptyCloud();
17
+ const merge = (r) => {
18
+ all.result.findings.push(...r.result.findings);
19
+ all.result.strengths.push(...r.result.strengths);
20
+ all.result.errors.push(...r.result.errors);
21
+ all.result.checked.push(...r.result.checked);
22
+ all.result.skipped.push(...r.result.skipped);
23
+ all.inventory.push(...r.inventory);
24
+ all.notes.push(...r.notes);
25
+ };
26
+ const opts = { runner, concurrency: o.concurrency ?? 4, now: o.now ?? new Date() };
27
+ if (scope.aws)
28
+ merge(await runAws(scope.aws, log, opts));
29
+ if (scope.azure)
30
+ merge(await runAzure(scope.azure, log, opts));
31
+ if (scope.gcp)
32
+ merge(await runGcp(scope.gcp, log, opts));
33
+ return all;
34
+ }
package/dist/map-ct.js ADDED
@@ -0,0 +1,107 @@
1
+ // SPDX-License-Identifier: PolyForm-Shield-1.0.0
2
+ // Copyright 2026 Hard Keel (https://hardkeel.com)
3
+ // Hostnames under a domain, from public Certificate Transparency logs (via crt.sh).
4
+ // Every public certificate is logged, so this finds names people forget: old APIs, staging
5
+ // sites, a vendor's portal on your domain. It reads a public log only. It never contacts any
6
+ // of the hosts it finds; checking them still needs the domain proved and benthic map.
7
+ import { MAX_WEB_TARGETS } from "./map-web.js";
8
+ const HOST = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
9
+ const YEAR_MS = 365 * 86_400_000;
10
+ /** A bare domain from what someone typed: "https://Example.com/x" -> "example.com". Null if it isn't one. */
11
+ export function ctDomain(raw) {
12
+ const d = raw.trim().toLowerCase().replace(/^[a-z]+:\/\//, "").replace(/[/:?#].*$/, "").replace(/^\*\./, "").replace(/\.$/, "");
13
+ if (!HOST.test(d) || /^\d+(\.\d+){3}$/.test(d))
14
+ return null;
15
+ return d;
16
+ }
17
+ /** Sorts hostnames so a domain's own name comes first, then by name read from the right (api.example.com near app.example.com). */
18
+ function byName(a, b) {
19
+ const ka = a.split(".").reverse().join(".");
20
+ const kb = b.split(".").reverse().join(".");
21
+ return ka < kb ? -1 : ka > kb ? 1 : 0;
22
+ }
23
+ /** Turns crt.sh rows into hostnames under the domain. Wildcards become the name they cover; emails and other names are dropped. */
24
+ export function hostsFromCt(domain, rows, now = Date.now()) {
25
+ const current = new Set();
26
+ const expired = new Set();
27
+ for (const r of rows) {
28
+ const end = r.not_after ? Date.parse(r.not_after.endsWith("Z") ? r.not_after : r.not_after + "Z") : NaN;
29
+ const live = Number.isNaN(end) || end >= now;
30
+ if (!live && now - end > YEAR_MS)
31
+ continue;
32
+ for (const raw of String(r.name_value ?? "").split(/\s+/)) {
33
+ const n = raw.trim().toLowerCase().replace(/^\*\./, "").replace(/\.$/, "");
34
+ if (!HOST.test(n))
35
+ continue;
36
+ if (n !== domain && !n.endsWith("." + domain))
37
+ continue;
38
+ (live ? current : expired).add(n);
39
+ }
40
+ }
41
+ for (const n of current)
42
+ expired.delete(n);
43
+ return { domain, current: [...current].sort(byName), recentlyExpired: [...expired].sort(byName) };
44
+ }
45
+ /** The one request this makes: crt.sh's search for the domain and everything under it. */
46
+ export function ctUrl(domain) {
47
+ return `https://crt.sh/?q=${encodeURIComponent("%." + domain)}&output=json`;
48
+ }
49
+ /** Looks the domain up on crt.sh. One request, with a plain user agent and nothing about the person running it. */
50
+ export async function lookupCt(domain, version, fetchFn = fetch, timeoutMs = 45_000) {
51
+ const ctl = new AbortController();
52
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
53
+ try {
54
+ const res = await fetchFn(ctUrl(domain), { headers: { accept: "application/json", "user-agent": `hardkeel-benthic/${version}` }, signal: ctl.signal });
55
+ if (!res.ok)
56
+ return { error: `crt.sh answered ${res.status}. It's often busy; try again in a minute.` };
57
+ const body = (await res.text()).trim();
58
+ let rows;
59
+ try {
60
+ rows = body ? JSON.parse(body) : [];
61
+ }
62
+ catch {
63
+ return { error: "crt.sh sent something that isn't a list of certificates. It's often busy; try again in a minute." };
64
+ }
65
+ if (!Array.isArray(rows))
66
+ return { error: "crt.sh sent something that isn't a list of certificates." };
67
+ const hosts = hostsFromCt(domain, rows);
68
+ if (!hosts.current.includes(domain) && !hosts.recentlyExpired.includes(domain))
69
+ hosts.current.unshift(domain);
70
+ return hosts;
71
+ }
72
+ catch (e) {
73
+ return { error: ctl.signal.aborted ? "crt.sh didn't answer in time. It's often busy; try again in a minute." : `couldn't reach crt.sh (${reason(e)})` };
74
+ }
75
+ finally {
76
+ clearTimeout(timer);
77
+ }
78
+ }
79
+ /** Node's fetch says only "fetch failed"; the cause has the useful part, like ENOTFOUND. */
80
+ function reason(e) {
81
+ const c = e?.cause;
82
+ return c?.code ?? c?.message ?? (e instanceof Error ? e.message : String(e));
83
+ }
84
+ /** What the hosts command prints. */
85
+ export function hostsText(h, showExpired) {
86
+ const lines = [];
87
+ const n = h.current.length;
88
+ lines.push(`Hostnames under ${h.domain} in public certificate logs (crt.sh): ${n} with a current certificate.`, "");
89
+ for (const x of h.current)
90
+ lines.push(` ${x}`);
91
+ if (h.recentlyExpired.length) {
92
+ lines.push("");
93
+ if (showExpired) {
94
+ lines.push(`Only on certificates that expired in the last year (often gone, sometimes forgotten):`, "");
95
+ for (const x of h.recentlyExpired)
96
+ lines.push(` ${x}`);
97
+ }
98
+ else {
99
+ lines.push(`${h.recentlyExpired.length} more appear only on certificates that expired in the last year. Add --all to list them.`);
100
+ }
101
+ }
102
+ const list = showExpired ? [...h.current, ...h.recentlyExpired] : h.current;
103
+ lines.push("", "This read a public log only. None of these hosts were contacted.", `To check them: prove ${h.domain} (benthic prove ${h.domain}), then run benthic map and paste this list when it asks for websites:`, "", ` ${list.slice(0, MAX_WEB_TARGETS).join(" ")}`);
104
+ if (list.length > MAX_WEB_TARGETS)
105
+ lines.push("", `That's the first ${MAX_WEB_TARGETS}; a map run checks at most ${MAX_WEB_TARGETS} addresses.`);
106
+ return lines.join("\n") + "\n";
107
+ }