@hardkeel/quantum-scan 0.0.0-stage → 0.3.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.
package/dist/report.js ADDED
@@ -0,0 +1,179 @@
1
+ // Human-readable output: pull request comment, check-run annotations, migration report.
2
+ import { gradeSentence } from "./score.js";
3
+ export const COMMENT_MARKER = "<!-- hardkeel-quantum-scan -->";
4
+ const SEV_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };
5
+ export function sortFindings(fs) {
6
+ return [...fs].sort((a, b) => SEV_ORDER[a.severity] - SEV_ORDER[b.severity] || a.file.localeCompare(b.file) || a.line - b.line);
7
+ }
8
+ function counts(fs) {
9
+ return {
10
+ secrets: fs.filter((f) => f.risk === "secret").length,
11
+ weak: fs.filter((f) => f.risk === "weak-now").length,
12
+ quantum: fs.filter((f) => f.risk === "quantum-vulnerable").length,
13
+ exposed: fs.filter((f) => f.risk === "exposed").length,
14
+ };
15
+ }
16
+ function riskLabel(f) {
17
+ if (f.risk === "secret")
18
+ return "Leaked key or password";
19
+ if (f.risk === "weak-now")
20
+ return "Weak today";
21
+ if (f.risk === "exposed")
22
+ return "Exposed setting";
23
+ return "Quantum-vulnerable";
24
+ }
25
+ function esc(s) {
26
+ return s.replace(/\|/g, "\\|").replace(/`/g, "'");
27
+ }
28
+ /** Conclusion for the GitHub check run. Secrets and weak crypto fail; quantum-only is neutral. */
29
+ export function checkConclusion(fs, blockOnQuantum = false) {
30
+ const c = counts(fs);
31
+ if (c.secrets || c.weak || c.exposed)
32
+ return "failure";
33
+ if (c.quantum)
34
+ return blockOnQuantum ? "failure" : "neutral";
35
+ return "success";
36
+ }
37
+ export function prSummaryLine(fs) {
38
+ const c = counts(fs);
39
+ if (!fs.length)
40
+ return "No leaked keys or passwords, weak encryption, exposed infrastructure settings, or encryption quantum computers will break in this change.";
41
+ const parts = [];
42
+ if (c.secrets)
43
+ parts.push(`${c.secrets} leaked key${c.secrets > 1 ? "s or passwords" : " or password"}`);
44
+ if (c.weak)
45
+ parts.push(`${c.weak} use${c.weak > 1 ? "s" : ""} of weak encryption`);
46
+ if (c.exposed)
47
+ parts.push(`${c.exposed} exposed infrastructure setting${c.exposed > 1 ? "s" : ""}`);
48
+ if (c.quantum)
49
+ parts.push(`${c.quantum} use${c.quantum > 1 ? "s" : ""} of encryption quantum computers will break`);
50
+ return `This change adds ${parts.length > 1 ? parts.slice(0, -1).join(", ") + " and " + parts[parts.length - 1] : parts[0]}.`;
51
+ }
52
+ const LOGO = "https://avatars.githubusercontent.com/in/5838578?s=64";
53
+ /** Short name for a finding, like "MD5 hash" or "RSA-1024 key". */
54
+ export function shortLabel(f) {
55
+ const a = f.algorithm;
56
+ if (f.kind === "config" && a === "Open to the internet")
57
+ return f.title; // names the ports, like "SSH (22) open to the whole internet"
58
+ if (f.risk === "secret" || f.kind === "config")
59
+ return a;
60
+ if (a.startsWith("RSA") && f.keySize !== undefined && f.keySize < 2048)
61
+ return `RSA-${f.keySize} key`;
62
+ if (a === "RSA")
63
+ return "RSA key";
64
+ if (a === "EC")
65
+ return "Elliptic-curve key";
66
+ if (/(mode|signature|encryption)$/.test(a) || a.startsWith("TLS"))
67
+ return a;
68
+ const noun = {
69
+ hash: "hash",
70
+ "block-cipher": "cipher",
71
+ "stream-cipher": "cipher",
72
+ signature: "signature",
73
+ "key-agreement": "key exchange",
74
+ "public-key-encryption": "encryption",
75
+ };
76
+ return noun[f.primitive] ? `${a} ${noun[f.primitive]}` : a;
77
+ }
78
+ function plural(n, one, many) {
79
+ return `${n} ${n === 1 ? one : many}`;
80
+ }
81
+ /** The comment's bold first line. */
82
+ export function prHeadline(fs) {
83
+ const now = fs.filter((f) => f.risk !== "quantum-vulnerable").length;
84
+ const later = fs.length - now;
85
+ if (!fs.length)
86
+ return "**Nothing to fix.** No leaked keys, weak or quantum-breakable encryption, or exposed infrastructure settings in this change.";
87
+ if (!now)
88
+ return `**Nothing blocks this merge.** ${plural(later, "item", "items")} to plan for, below.`;
89
+ return `**${plural(now, "problem", "problems")} to fix before merging.**` + (later ? ` ${plural(later, "more item", "more items")} to plan for.` : "");
90
+ }
91
+ export function prComment(fs, opts = {}) {
92
+ const max = opts.maxRows ?? 25;
93
+ const sorted = sortFindings(fs).slice(0, max);
94
+ const where = (f) => {
95
+ const label = `\`${esc(f.file)}:${f.line}\``;
96
+ return opts.repo && opts.sha ? `[${label}](https://github.com/${opts.repo}/blob/${opts.sha}/${encodeURI(f.file)}#L${f.line})` : label;
97
+ };
98
+ const table = (rows) => [
99
+ "| Where | Issue | Fix |",
100
+ "| --- | --- | --- |",
101
+ ...rows.map((f) => `| ${where(f)} | ${esc(shortLabel(f))} | ${esc(f.fix)} |`),
102
+ ];
103
+ const now = sorted.filter((f) => f.risk !== "quantum-vulnerable");
104
+ const later = sorted.filter((f) => f.risk === "quantum-vulnerable");
105
+ const lines = [
106
+ COMMENT_MARKER,
107
+ `### <img src="${LOGO}" width="20" height="20" alt=""> Hard Keel Quantum Scan`,
108
+ "",
109
+ prHeadline(fs),
110
+ ];
111
+ if (now.length)
112
+ lines.push("", "#### Fix before merging", "", ...table(now));
113
+ if (later.length) {
114
+ lines.push("", "#### Plan for later", "", "Safe today, but quantum computers will be able to break these. NIST plans to phase them out between 2030 and 2035.", "", ...table(later));
115
+ }
116
+ if (fs.length > max)
117
+ lines.push("", `${fs.length - max} more are listed in the check results.`);
118
+ if (opts.reportUrl) {
119
+ lines.push("", `**[Open the full report](${opts.reportUrl})** to see every use of encryption in this repository and the order to fix them in.`);
120
+ }
121
+ lines.push("", "<sub>Hard Keel · hardkeel.com · Questions: contact@hardkeel.com</sub>");
122
+ return lines.join("\n");
123
+ }
124
+ export function annotations(fs) {
125
+ return sortFindings(fs).map((f) => ({
126
+ path: f.file,
127
+ start_line: f.line,
128
+ end_line: f.line,
129
+ annotation_level: f.risk === "quantum-vulnerable" ? "warning" : "failure",
130
+ title: `${riskLabel(f)}: ${f.title}`,
131
+ message: f.fix,
132
+ }));
133
+ }
134
+ /** Group a full-repo scan by algorithm and rank by what to migrate first. */
135
+ export function migrationPlan(fs) {
136
+ const map = new Map();
137
+ for (const f of fs)
138
+ map.set(`${f.risk}|${f.algorithm}`, [...(map.get(`${f.risk}|${f.algorithm}`) ?? []), f]);
139
+ const groups = [...map.values()].map((g) => {
140
+ const f = g[0];
141
+ let priority = 4;
142
+ let when = "Before 2035";
143
+ if (f.risk === "secret")
144
+ [priority, when] = [0, "Now"];
145
+ else if (f.risk === "exposed")
146
+ [priority, when] = [1, "Now"];
147
+ else if (f.risk === "weak-now")
148
+ [priority, when] = [1, "Now"];
149
+ else if (f.primitive === "key-agreement" || f.primitive === "public-key-encryption")
150
+ [priority, when] = [2, "By 2030"];
151
+ else
152
+ [priority, when] = [3, "By 2030 to 2035"];
153
+ return { algorithm: f.algorithm, risk: f.risk, count: g.length, files: [...new Set(g.map((x) => x.file))], fix: f.fix, priority, when };
154
+ });
155
+ return groups.sort((a, b) => a.priority - b.priority || b.count - a.count);
156
+ }
157
+ export function migrationReportMarkdown(repo, fs, scannedAt, score) {
158
+ const plan = migrationPlan(fs);
159
+ const c = counts(fs);
160
+ const out = [
161
+ `# Quantum readiness report: ${repo}`,
162
+ "",
163
+ ...(score ? [`**${gradeSentence(score)}** How the score works: https://hardkeel.com/learn/quantum-readiness-score/`, ""] : []),
164
+ `Scanned ${scannedAt}. ${c.quantum} use${c.quantum === 1 ? "" : "s"} of encryption quantum computers will break, ${c.weak} of weak encryption, ${c.exposed} exposed infrastructure setting${c.exposed === 1 ? "" : "s"}, and ${c.secrets} leaked key${c.secrets === 1 ? "" : "s"} or password${c.secrets === 1 ? "" : "s"}.`,
165
+ "",
166
+ "NIST's final transition plan (IR 8547, October 2026) deprecates today's public-key algorithms (RSA, elliptic curve, Diffie-Hellman) after 2030 and disallows them after 2035. Key exchange comes first, because encrypted traffic recorded today can be decrypted once a large quantum computer exists.",
167
+ "",
168
+ "| Order | What | Uses | Files | When | Move to |",
169
+ "| --- | --- | --- | --- | --- | --- |",
170
+ ];
171
+ plan.forEach((g, i) => {
172
+ const files = g.files.slice(0, 3).map((f) => `\`${esc(f)}\``).join(", ") + (g.files.length > 3 ? ` +${g.files.length - 3}` : "");
173
+ out.push(`| ${i + 1} | ${esc(g.algorithm)} | ${g.count} | ${files} | ${g.when} | ${esc(g.fix)} |`);
174
+ });
175
+ if (!plan.length)
176
+ out.push("| | Nothing found | | | | |");
177
+ out.push("", "This report lists what the scanner found in source code and infrastructure config in the repository. It does not cover compiled dependencies, running services or certificates in use. Hard Keel can assess those separately.");
178
+ return out.join("\n");
179
+ }
package/dist/rules.js ADDED
@@ -0,0 +1,135 @@
1
+ // Detection rules for quantum-vulnerable and already-weak cryptography.
2
+ // Each rule is a line-level regex scoped to a set of file languages.
3
+ const KEM_FIX = "Move key exchange to ML-KEM (FIPS 203), or hybrid X25519 + ML-KEM-768 for TLS.";
4
+ const SIG_FIX = "Move to ML-DSA (FIPS 204) or SLH-DSA (FIPS 205) signatures.";
5
+ const HASH_FIX = "Switch to SHA-256 or SHA-3, unless it is only a non-security checksum.";
6
+ const CIPHER_FIX = "Switch to AES-256-GCM.";
7
+ const TLS_FIX = "Require TLS 1.2 or later, ideally TLS 1.3.";
8
+ // Classification of every algorithm the rules can emit.
9
+ export const ALGORITHMS = {
10
+ RSA: { primitive: "public-key-encryption", risk: "quantum-vulnerable", severity: "high", fix: `${KEM_FIX} For signatures, use ML-DSA (FIPS 204).` },
11
+ "RSA signature": { primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: SIG_FIX },
12
+ "RSA encryption": { primitive: "public-key-encryption", risk: "quantum-vulnerable", severity: "high", fix: KEM_FIX },
13
+ ECDSA: { primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: SIG_FIX },
14
+ EC: { primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: `${SIG_FIX} For key exchange, use ML-KEM (FIPS 203).` },
15
+ ECDH: { primitive: "key-agreement", risk: "quantum-vulnerable", severity: "high", fix: KEM_FIX },
16
+ DH: { primitive: "key-agreement", risk: "quantum-vulnerable", severity: "high", fix: KEM_FIX },
17
+ X25519: { primitive: "key-agreement", risk: "quantum-vulnerable", severity: "high", fix: KEM_FIX },
18
+ X448: { primitive: "key-agreement", risk: "quantum-vulnerable", severity: "high", fix: KEM_FIX },
19
+ Ed25519: { primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: SIG_FIX },
20
+ Ed448: { primitive: "signature", risk: "quantum-vulnerable", severity: "medium", fix: SIG_FIX },
21
+ DSA: { primitive: "signature", risk: "weak-now", severity: "high", fix: `DSA is no longer approved. ${SIG_FIX}` },
22
+ MD5: { primitive: "hash", risk: "weak-now", severity: "medium", fix: HASH_FIX },
23
+ "SHA-1": { primitive: "hash", risk: "weak-now", severity: "medium", fix: HASH_FIX },
24
+ DES: { primitive: "block-cipher", risk: "weak-now", severity: "high", fix: CIPHER_FIX },
25
+ "3DES": { primitive: "block-cipher", risk: "weak-now", severity: "high", fix: CIPHER_FIX },
26
+ RC4: { primitive: "stream-cipher", risk: "weak-now", severity: "high", fix: CIPHER_FIX },
27
+ "ECB mode": { primitive: "block-cipher", risk: "weak-now", severity: "high", fix: CIPHER_FIX },
28
+ "TLS 1.0/1.1": { primitive: "protocol", risk: "weak-now", severity: "high", fix: TLS_FIX },
29
+ "Weak TLS ciphers": { primitive: "protocol", risk: "weak-now", severity: "high", fix: "Allow only AES-GCM and ChaCha20 cipher suites." },
30
+ };
31
+ // Maps a key-type word used by many APIs to an algorithm name.
32
+ function keyType(word) {
33
+ const w = word.toLowerCase().replace(/[^a-z0-9]/g, "");
34
+ if (w.startsWith("rsa"))
35
+ return "RSA";
36
+ if (w === "ec" || w === "ecdsa")
37
+ return "ECDSA";
38
+ if (w === "ecdh")
39
+ return "ECDH";
40
+ if (w === "dsa")
41
+ return "DSA";
42
+ if (w === "dh" || w === "diffiehellman")
43
+ return "DH";
44
+ if (w === "ed25519")
45
+ return "Ed25519";
46
+ if (w === "ed448")
47
+ return "Ed448";
48
+ if (w === "x25519")
49
+ return "X25519";
50
+ if (w === "x448")
51
+ return "X448";
52
+ if (w === "xdh")
53
+ return "X25519";
54
+ return null;
55
+ }
56
+ function hashOrCipher(word) {
57
+ const w = word.toLowerCase();
58
+ if (w === "md5")
59
+ return "MD5";
60
+ if (w === "sha1" || w === "sha-1")
61
+ return "SHA-1";
62
+ if (w.startsWith("des-ede") || w === "desede" || w.startsWith("des3") || w === "3des")
63
+ return "3DES";
64
+ if (w.startsWith("des"))
65
+ return "DES";
66
+ if (w.startsWith("rc4") || w === "arc4" || w === "arcfour")
67
+ return "RC4";
68
+ if (/ecb/.test(w))
69
+ return "ECB mode";
70
+ return null;
71
+ }
72
+ export const CRYPTO_RULES = [
73
+ // ---------- Python ----------
74
+ { id: "py-rsa-generate", langs: ["python"], pattern: /\brsa\.generate_private_key\s*\(|\bRSA\.generate\s*\(/, algorithm: "RSA", keySize: /(?:key_size\s*=\s*|RSA\.generate\s*\(\s*)(\d{3,5})/ },
75
+ { id: "py-rsa-padding", langs: ["python"], pattern: /\bPKCS1_OAEP\b|\bpadding\.OAEP\s*\(/, algorithm: "RSA encryption" },
76
+ { id: "py-rsa-sign", langs: ["python"], pattern: /\bpadding\.PSS\s*\(|\bpadding\.PKCS1v15\s*\(|\bpkcs1_15\.new\s*\(/, algorithm: "RSA signature" },
77
+ { id: "py-ec-generate", langs: ["python"], pattern: /\bec\.generate_private_key\s*\(|\bECC\.generate\s*\(|\bSigningKey\.generate\s*\(/, algorithm: "ECDSA" },
78
+ { id: "py-ecdh", langs: ["python"], pattern: /\bec\.ECDH\s*\(/, algorithm: "ECDH" },
79
+ { id: "py-dsa", langs: ["python"], pattern: /\bdsa\.generate_private_key\s*\(|\bDSA\.generate\s*\(/, algorithm: "DSA" },
80
+ { id: "py-dh", langs: ["python"], pattern: /\bdh\.generate_parameters\s*\(/, algorithm: "DH" },
81
+ { id: "py-ed25519", langs: ["python"], pattern: /\bEd25519PrivateKey\b/, algorithm: "Ed25519" },
82
+ { id: "py-x25519", langs: ["python"], pattern: /\bX25519PrivateKey\b/, algorithm: "X25519" },
83
+ { id: "py-weak-hash", langs: ["python"], pattern: /\bhashlib\.(md5|sha1)\s*\(|\bhashes\.(MD5|SHA1)\s*\(|hashlib\.new\s*\(\s*['"](md5|sha1)['"]/, algorithm: (m) => hashOrCipher(m[1] ?? m[2] ?? m[3] ?? "") },
84
+ { id: "py-weak-cipher", langs: ["python"], pattern: /\balgorithms\.(TripleDES|ARC4)\s*\(|\b(DES3|DES|ARC4)\.new\s*\(/, algorithm: (m) => hashOrCipher((m[1] ?? m[2] ?? "").replace("TripleDES", "3des")) },
85
+ { id: "py-ecb", langs: ["python"], pattern: /\bmodes\.ECB\s*\(|\bMODE_ECB\b/, algorithm: "ECB mode" },
86
+ // ---------- JavaScript / TypeScript ----------
87
+ { id: "js-generate-keypair", langs: ["js"], pattern: /\bgenerateKeyPair(?:Sync)?\s*\(\s*['"`]([a-z0-9-]+)['"`]/i, algorithm: (m) => keyType(m[1]), keySize: /modulusLength\s*:\s*(\d{3,5})/ },
88
+ { id: "js-ecdh", langs: ["js"], pattern: /\bcreateECDH\s*\(/, algorithm: "ECDH" },
89
+ { id: "js-dh", langs: ["js"], pattern: /\bcreateDiffieHellman(?:Group)?\s*\(/, algorithm: "DH" },
90
+ { id: "js-webcrypto", langs: ["js"], pattern: /name\s*:\s*['"`](RSA-OAEP|RSASSA-PKCS1-v1_5|RSA-PSS|ECDSA|ECDH|Ed25519|X25519)['"`]/, algorithm: (m) => ({ "RSA-OAEP": "RSA encryption", "RSASSA-PKCS1-v1_5": "RSA signature", "RSA-PSS": "RSA signature" }[m[1]] ?? keyType(m[1])), keySize: /modulusLength\s*:\s*(\d{3,5})/ },
91
+ { id: "js-jwt-alg", langs: ["js"], pattern: /\balgorithms?\s*:\s*\[?\s*['"`]((?:RS|PS|ES)(?:256|384|512)|EdDSA)['"`]/, algorithm: (m) => (m[1].startsWith("ES") ? "ECDSA" : m[1] === "EdDSA" ? "Ed25519" : "RSA signature") },
92
+ { id: "js-forge-rsa", langs: ["js"], pattern: /\bpki\.rsa\.generateKeyPair\s*\(/, algorithm: "RSA", keySize: /generateKeyPair\s*\(\s*(?:\{\s*bits\s*:\s*)?(\d{3,5})/ },
93
+ { id: "js-weak-hash", langs: ["js"], pattern: /\bcreateHash\s*\(\s*['"`](md5|sha1)['"`]|\bcreateHmac\s*\(\s*['"`](md5|sha1)['"`]/i, algorithm: (m) => hashOrCipher(m[1] ?? m[2]) },
94
+ { id: "js-weak-cipher", langs: ["js"], pattern: /\bcreateCipheriv\s*\(\s*['"`]((?:des[a-z0-9-]*)|(?:rc4[a-z0-9-]*)|(?:aes-\d+-ecb))['"`]/i, algorithm: (m) => hashOrCipher(m[1]) },
95
+ // ---------- Go ----------
96
+ { id: "go-rsa", langs: ["go"], pattern: /\brsa\.GenerateKey\s*\(/, algorithm: "RSA", keySize: /GenerateKey\s*\([^,]+,\s*(\d{3,5})/ },
97
+ { id: "go-rsa-encrypt", langs: ["go"], pattern: /\brsa\.Encrypt(?:OAEP|PKCS1v15)\s*\(/, algorithm: "RSA encryption" },
98
+ { id: "go-rsa-sign", langs: ["go"], pattern: /\brsa\.Sign(?:PSS|PKCS1v15)\s*\(/, algorithm: "RSA signature" },
99
+ { id: "go-ecdsa", langs: ["go"], pattern: /\becdsa\.(?:GenerateKey|Sign|SignASN1)\s*\(/, algorithm: "ECDSA" },
100
+ { id: "go-ecdh", langs: ["go"], pattern: /\becdh\.(P256|P384|P521|X25519)\s*\(/, algorithm: (m) => (m[1] === "X25519" ? "X25519" : "ECDH") },
101
+ { id: "go-ed25519", langs: ["go"], pattern: /\bed25519\.(?:GenerateKey|Sign|NewKeyFromSeed)\s*\(/, algorithm: "Ed25519" },
102
+ { id: "go-dsa", langs: ["go"], pattern: /\bdsa\.GenerateKey\s*\(/, algorithm: "DSA" },
103
+ { id: "go-weak-hash", langs: ["go"], pattern: /\b(md5|sha1)\.(?:New|Sum)\s*\(/, algorithm: (m) => hashOrCipher(m[1]) },
104
+ { id: "go-weak-cipher", langs: ["go"], pattern: /\bdes\.(NewCipher|NewTripleDESCipher)\s*\(|\brc4\.NewCipher\s*\(/, algorithm: (m) => (m[1] === "NewTripleDESCipher" ? "3DES" : m[1] ? "DES" : "RC4") },
105
+ // A TLS curve list that leaves out the hybrid ML-KEM group turns off Go's post-quantum default (Go 1.24+).
106
+ { id: "go-tls-curves", langs: ["go"], pattern: /(?<!MLKEM.*)\btls\.(X25519|CurveP256|CurveP384|CurveP521)\b(?!.*MLKEM)/, algorithm: (m) => (m[1] === "X25519" ? "X25519" : "ECDH") },
107
+ { id: "go-tls-old", langs: ["go"], pattern: /\bMinVersion\s*:\s*tls\.VersionTLS1[01]\b/, algorithm: "TLS 1.0/1.1" },
108
+ // ---------- Java / Kotlin ----------
109
+ { id: "java-keypairgen", langs: ["java"], pattern: /KeyPairGenerator\.getInstance\s*\(\s*"([A-Za-z0-9]+)"/, algorithm: (m) => keyType(m[1]) },
110
+ { id: "java-keyagreement", langs: ["java"], pattern: /KeyAgreement\.getInstance\s*\(\s*"([A-Za-z0-9]+)"/, algorithm: (m) => (keyType(m[1]) === "ECDSA" ? "ECDH" : keyType(m[1])) },
111
+ { id: "java-signature", langs: ["java"], pattern: /Signature\.getInstance\s*\(\s*"[A-Za-z0-9]*with(RSA|ECDSA|DSA)[A-Za-z0-9/]*"/, algorithm: (m) => (m[1] === "RSA" ? "RSA signature" : m[1]) },
112
+ { id: "java-signature-ed", langs: ["java"], pattern: /Signature\.getInstance\s*\(\s*"(Ed25519|Ed448|EdDSA)"/, algorithm: (m) => (m[1] === "Ed448" ? "Ed448" : "Ed25519") },
113
+ { id: "java-cipher-rsa", langs: ["java"], pattern: /Cipher\.getInstance\s*\(\s*"RSA[^"]*"/, algorithm: "RSA encryption" },
114
+ { id: "java-weak-cipher", langs: ["java"], pattern: /Cipher\.getInstance\s*\(\s*"((?:DESede|DES|RC4|ARCFOUR)[^"]*|AES\/ECB[^"]*|AES")/, algorithm: (m) => (m[1] === 'AES"' || m[1] === "AES" ? "ECB mode" : hashOrCipher(m[1].split("/")[0]) ?? hashOrCipher(m[1])) },
115
+ { id: "java-weak-hash", langs: ["java"], pattern: /MessageDigest\.getInstance\s*\(\s*"(MD5|SHA-?1)"/, algorithm: (m) => hashOrCipher(m[1]) },
116
+ { id: "java-keysize", langs: ["java"], pattern: /\.initialize\s*\(\s*(\d{3,4})\s*[,)]/, algorithm: (m) => (Number(m[1]) < 2048 && Number(m[1]) >= 512 ? "RSA" : null), keySize: /\.initialize\s*\(\s*(\d{3,4})/ },
117
+ // ---------- Config, keys, certificates (any file) ----------
118
+ { id: "ssh-public-key", langs: ["any"], pattern: /\b(ssh-rsa|ssh-dss|ecdsa-sha2-nistp\d+|ssh-ed25519) AAAA[0-9A-Za-z+/]{20,}/, algorithm: (m) => ({ "ssh-rsa": "RSA signature", "ssh-dss": "DSA", "ssh-ed25519": "Ed25519" }[m[1]] ?? "ECDSA") },
119
+ ];
120
+ export function langFor(path) {
121
+ const p = path.toLowerCase();
122
+ if (/\.(py|pyw)$/.test(p))
123
+ return "python";
124
+ if (/\.(js|mjs|cjs|jsx|ts|mts|cts|tsx)$/.test(p))
125
+ return "js";
126
+ if (/\.go$/.test(p))
127
+ return "go";
128
+ if (/\.(java|kt|kts|scala)$/.test(p))
129
+ return "java";
130
+ if (/(\.conf|\.cfg|\.ini|\.ya?ml|\.toml|\.tf|\.json|\.env|nginx[^/]*|httpd[^/]*|dockerfile[^/]*|containerfile[^/]*|\.hcl|\.tfvars|\.template|\.properties)$/.test(p))
131
+ return "config";
132
+ if (/\.(pem|key|crt|cer|pub|txt|sh|md)$/.test(p) || /(^|\/)(authorized_keys|known_hosts|id_[a-z0-9]+)$/.test(p))
133
+ return "any";
134
+ return null;
135
+ }
package/dist/sarif.js ADDED
@@ -0,0 +1,43 @@
1
+ // SARIF 2.1.0 output, so GitHub code scanning (and other tools) can show findings.
2
+ import { shortLabel } from "./report.js";
3
+ const LEVEL = {
4
+ secret: "error",
5
+ "weak-now": "error",
6
+ "quantum-vulnerable": "warning",
7
+ exposed: "error",
8
+ };
9
+ /** One SARIF rule per kind of problem, like "weak-now/md5" or "secret/aws-access-key". */
10
+ function ruleId(f) {
11
+ const label = shortLabel(f).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
12
+ return `${f.risk}/${label}`;
13
+ }
14
+ export function buildSarif(findings, toolVersion) {
15
+ const rules = new Map();
16
+ for (const f of findings) {
17
+ const id = ruleId(f);
18
+ if (!rules.has(id))
19
+ rules.set(id, { id, name: shortLabel(f), shortDescription: { text: f.title }, help: { text: f.fix } });
20
+ }
21
+ return {
22
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
23
+ version: "2.1.0",
24
+ runs: [
25
+ {
26
+ tool: {
27
+ driver: {
28
+ name: "Hard Keel Quantum Scan",
29
+ version: toolVersion,
30
+ informationUri: "https://hardkeel.com",
31
+ rules: [...rules.values()],
32
+ },
33
+ },
34
+ results: findings.map((f) => ({
35
+ ruleId: ruleId(f),
36
+ level: LEVEL[f.risk],
37
+ message: { text: `${f.title}. ${f.fix}` },
38
+ locations: [{ physicalLocation: { artifactLocation: { uri: f.file }, region: { startLine: f.line } } }],
39
+ })),
40
+ },
41
+ ],
42
+ };
43
+ }
package/dist/scan.js ADDED
@@ -0,0 +1,220 @@
1
+ // Core scanner: runs crypto and secret rules over file contents.
2
+ import { ALGORITHMS, CRYPTO_RULES, langFor } from "./rules.js";
3
+ import { scanInfra } from "./infra.js";
4
+ import { findSecrets, mask } from "./secrets.js";
5
+ import { findPqc } from "./pqc.js";
6
+ import { communityRulesFor } from "./community.js";
7
+ const MAX_LINE = 2000;
8
+ const DOC_FILE = /\.(md|mdx|rst|txt|html?|adoc)$/i;
9
+ // Test code is full of throwaway keys and passwords, including fakes in real token formats, so no secret counts there.
10
+ export const TEST_PATH = /(^|\/)(tests?|__tests__|__snapshots__|testdata|test-data|testing|test[-_]?(?:utils?|helpers?|support|env|suite|fixtures?)|e2e[-_][a-z0-9_-]+|[a-z0-9_-]+[-_]tests?|(?!(?:la|con|at|pro|de)test\/)[a-z0-9]+test|fixtures?|spec|specs|mocks?|e2e|integration(?:[-_]?tests?)?|vectors|test[-_]?vectors|[a-z0-9_]+_vectors)\/|(_test\.go|_test\.py|\.(test|spec)\.[cm]?[jt]sx?)$|(^|\/)test[-_][^/]*$|(^|\/)testing[-_]?utils?\.[a-z]+$|(^|\/)fixtures?\.[cm]?[jt]sx?$/i;
11
+ // Example and tutorial code, which is documentation in code form.
12
+ // Translation files: "password" and "token" there are labels shown to people.
13
+ export const LOCALE_PATH = /(^|\/)(locales?|i18n|l10n|translations?|nls)\/|\.(po|pot|xliff|xlf|ftl|strings)$/i;
14
+ // Example settings files (.env.example), API specs and docs-site configs (public search keys).
15
+ export const EXAMPLE_FILE = /\.(example|sample|template|tmpl|dist)$|(^|\/)\.env\.(example|sample|template)|(^|\/)(openapi|swagger)[^/]*\.(ya?ml|json)$|(^|\/)docusaurus\.config\.[cm]?[jt]s$|\.stories\.[cm]?[jt]sx?$|(^|\/)\.secrets\.baseline$/i;
16
+ export const EXAMPLE_PATH = /(^|\/)(docs?_src|docs?|examples?|samples?|tutorials?)\//i;
17
+ const LOOSE_SECRET_RULES = new Set(["private-key", "generic-assignment", "db-url-password"]);
18
+ const SKIP_PATH = /(^|\/)(node_modules|vendor|dist|build|\.git|__pycache__|\.venv|venv|target)\//;
19
+ const SKIP_FILE = /(\.min\.js|\.map|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|go\.sum|\.lock)$/;
20
+ export function shouldScan(path) {
21
+ if (SKIP_PATH.test(path) || SKIP_FILE.test(path))
22
+ return false;
23
+ return true;
24
+ }
25
+ function trimSnippet(line) {
26
+ const t = line.trim();
27
+ return t.length > 160 ? `${t.slice(0, 157)}...` : t;
28
+ }
29
+ /**
30
+ * Scan one file.
31
+ * @param onlyLines if given, only report findings on these 1-based line numbers
32
+ * (used for pull requests: only what the change added).
33
+ */
34
+ export function scanFile(path, content, onlyLines) {
35
+ if (content.includes("\u0000"))
36
+ return []; // binary
37
+ const lines = content.split(/\r?\n/).map((text, i) => ({ no: i + 1, text }));
38
+ // Scan the whole file so settings see their surrounding block, then keep only the lines asked for.
39
+ const findings = scanLines(path, lines);
40
+ return onlyLines ? findings.filter((f) => onlyLines.has(f.line)) : findings;
41
+ }
42
+ /** Scan the lines a pull request added, straight from GitHub's patch text. No file download needed. */
43
+ export function scanPatch(path, patch) {
44
+ return scanLines(path, patchAddedLines(patch));
45
+ }
46
+ export function scanLines(path, lines) {
47
+ if (!shouldScan(path))
48
+ return [];
49
+ const lang = langFor(path);
50
+ const rules = [...CRYPTO_RULES.filter((r) => r.langs.includes("any") || (lang !== null && r.langs.includes(lang))), ...communityRulesFor(path)];
51
+ const findings = [];
52
+ for (let idx = 0; idx < lines.length; idx++) {
53
+ const { no: lineNo, text: raw } = lines[idx];
54
+ if (raw.length > MAX_LINE)
55
+ continue;
56
+ // Secrets: every text file.
57
+ for (const hit of findSecrets(raw)) {
58
+ // A private-key header only counts when real key material follows it (docs often show "XXXX").
59
+ if (hit.rule.id === "private-key" && !hasKeyMaterial(raw, lines[idx + 1]))
60
+ continue;
61
+ // Docs are full of example passwords; only specific token formats count there.
62
+ if (hit.rule.id === "generic-assignment" && (DOC_FILE.test(path) || LOCALE_PATH.test(path)))
63
+ continue;
64
+ if (hit.rule.id === "db-url-password" && DOC_FILE.test(path))
65
+ continue;
66
+ if (TEST_PATH.test(path))
67
+ continue;
68
+ if (LOOSE_SECRET_RULES.has(hit.rule.id) && (EXAMPLE_PATH.test(path) || EXAMPLE_FILE.test(path) || DOC_FILE.test(path)))
69
+ continue;
70
+ findings.push({
71
+ kind: "secret",
72
+ ruleId: hit.rule.id,
73
+ title: `${hit.rule.name} committed to the repository`,
74
+ algorithm: hit.rule.name,
75
+ primitive: "credential",
76
+ risk: "secret",
77
+ severity: "critical",
78
+ file: path,
79
+ line: lineNo,
80
+ snippet: trimSnippet(raw.split(hit.value).join(mask(hit.value))),
81
+ fix: "Revoke it and issue a new one, then load it from a secret store. Deleting it from the code leaves it in git history.",
82
+ });
83
+ }
84
+ // Crypto: language-scoped rules.
85
+ for (const rule of rules) {
86
+ const m = raw.match(rule.pattern);
87
+ if (!m)
88
+ continue;
89
+ let algorithm = typeof rule.algorithm === "string" ? rule.algorithm : rule.algorithm(m);
90
+ if (!algorithm)
91
+ continue;
92
+ let info = ALGORITHMS[algorithm];
93
+ if (!info)
94
+ continue;
95
+ // Encryption in test code is not what ships, so it stays out of the inventory and the check.
96
+ if (TEST_PATH.test(path))
97
+ continue;
98
+ // Python's usedforsecurity=False marks a hash that is only a checksum.
99
+ if (info.primitive === "hash" && /usedforsecurity\s*=\s*False/.test(raw))
100
+ continue;
101
+ // MD5 and SHA-1 are mostly used for checksums, cache keys and ETags, which are fine.
102
+ // Only flag them where the code around them is about passwords, signing, tokens and the like.
103
+ if ((algorithm === "MD5" || algorithm === "SHA-1") && !weakHashForSecurity(raw, lines, idx))
104
+ continue;
105
+ let keySize;
106
+ if (rule.keySize) {
107
+ const k = raw.match(rule.keySize);
108
+ if (k)
109
+ keySize = Number(k[1]);
110
+ }
111
+ let title = `${algorithm} is ${info.risk === "weak-now" ? "weak today" : "breakable by quantum computers"}`;
112
+ let severity = info.severity;
113
+ let risk = info.risk;
114
+ let fix = info.fix;
115
+ if (keySize !== undefined && algorithm.startsWith("RSA") && keySize < 2048) {
116
+ title = `RSA-${keySize} is weak today and breakable by quantum computers`;
117
+ severity = "high";
118
+ risk = "weak-now";
119
+ fix = "Use 3072-bit keys or larger now, then plan the move to post-quantum methods.";
120
+ }
121
+ findings.push({
122
+ kind: "crypto",
123
+ ruleId: rule.id,
124
+ title,
125
+ algorithm,
126
+ primitive: info.primitive,
127
+ risk,
128
+ severity,
129
+ file: path,
130
+ line: lineNo,
131
+ snippet: trimSnippet(raw),
132
+ fix,
133
+ keySize,
134
+ });
135
+ }
136
+ }
137
+ // Infrastructure config: test fixtures and examples are written to be wrong or to show options.
138
+ if (!TEST_PATH.test(path) && !EXAMPLE_PATH.test(path))
139
+ findings.push(...scanInfra(path, lines));
140
+ return dedupe(findings);
141
+ }
142
+ // Words that say a hash is not protecting anything.
143
+ const HASH_NOT_SECURITY = /nosec|NOSONAR|noqa|usedforsecurity|e-?tag|cache|checksum|\bcrc|dedup|uuid|gravatar|content[-_]?md5|shard|partition|consistent.?hash|file.?hash|hash.?file|filename|file.?name|\bgit\b|identicon|colou?r/i;
144
+ // Words that say it is.
145
+ const HASH_SECURITY = /passw|passwd|\bpwd|signature|\bsign(ed|er|ing)?\b|verif|hmac|authenti|\bauth\b|token|secret|credential|certificat|\bcert\b|salt|nonce|session|encrypt|decrypt|login|\bjwt\b|\botp\b|api.?key|private|\bkdf\b|pbkdf|derive|card|\bssn\b|integrity/i;
146
+ /** Whether an MD5 or SHA-1 call at lines[idx] looks like it protects something. */
147
+ function weakHashForSecurity(raw, lines, idx) {
148
+ if (/hmac/i.test(raw))
149
+ return true;
150
+ if (HASH_NOT_SECURITY.test(raw))
151
+ return false;
152
+ if (HASH_SECURITY.test(raw))
153
+ return true;
154
+ // The function or block around it: a few lines up (often the function name) and a couple down.
155
+ const around = lines.slice(Math.max(0, idx - 6), idx + 3).map((l) => l.text).join("\n");
156
+ if (HASH_NOT_SECURITY.test(around))
157
+ return false;
158
+ return HASH_SECURITY.test(around);
159
+ }
160
+ const KEY_BODY = /^[A-Za-z0-9+/=]{40,}$/;
161
+ function hasKeyMaterial(line, next) {
162
+ const after = line.split(/PRIVATE KEY(?: BLOCK)?-----/)[1] ?? "";
163
+ if (after.split(/\\n|\s+/).some((part) => KEY_BODY.test(part)))
164
+ return true;
165
+ return next !== undefined && KEY_BODY.test(next.text.trim().replace(/^["']|["',]$/g, ""));
166
+ }
167
+ // Two rules can hit the same line for the same algorithm; keep one.
168
+ function dedupe(findings) {
169
+ const seen = new Set();
170
+ return findings.filter((f) => {
171
+ const k = `${f.file}:${f.line}:${f.kind}:${f.algorithm}`;
172
+ if (seen.has(k))
173
+ return false;
174
+ seen.add(k);
175
+ return true;
176
+ });
177
+ }
178
+ export function scanFiles(files) {
179
+ const findings = [];
180
+ const pqc = [];
181
+ let filesScanned = 0;
182
+ for (const f of files) {
183
+ if (!shouldScan(f.path))
184
+ continue;
185
+ filesScanned++;
186
+ findings.push(...scanFile(f.path, f.content, f.onlyLines));
187
+ // Post-quantum use only counts in code that ships, like the problems do.
188
+ if (!TEST_PATH.test(f.path) && !EXAMPLE_PATH.test(f.path))
189
+ pqc.push(...findPqc(f.path, f.content));
190
+ }
191
+ return { findings, filesScanned, pqc };
192
+ }
193
+ /** Parse a unified diff patch (GitHub's `patch` field) into the added lines of the new file. */
194
+ export function patchAddedLines(patch) {
195
+ const out = [];
196
+ if (!patch)
197
+ return out;
198
+ let line = 0;
199
+ for (const l of patch.split("\n")) {
200
+ const h = l.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
201
+ if (h) {
202
+ line = Number(h[1]);
203
+ continue;
204
+ }
205
+ if (l.startsWith("+")) {
206
+ out.push({ no: line, text: l.slice(1) });
207
+ line++;
208
+ }
209
+ else if (l.startsWith("-")) {
210
+ // removed line: new-file counter does not move
211
+ }
212
+ else if (!l.startsWith("\\")) {
213
+ line++;
214
+ }
215
+ }
216
+ return out;
217
+ }
218
+ export function addedLines(patch) {
219
+ return new Set(patchAddedLines(patch).map((l) => l.no));
220
+ }