@hardkeel/quantum-scan 0.2.0 → 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/score.js CHANGED
@@ -1,122 +1,122 @@
1
- // Hard Keel quantum readiness score, method version 1.
2
- // Turns a full-repository scan into a 0-100 score and a grade from A+ to F.
3
- // The method is public: docs/readiness-score.md and hardkeel.com/learn/quantum-readiness-score/.
4
- // Change a weight, cap or threshold only by bumping METHOD_VERSION and the docs together.
5
- export const METHOD_VERSION = "1";
6
- const GRADES = ["A+", "A", "B", "C", "D", "F"];
7
- /** Points taken off for one kind of problem (one algorithm or setting), before the use multiplier. */
8
- const BASE = {
9
- secret: () => 25,
10
- weak: (s) => (s === "critical" || s === "high" ? 10 : 6),
11
- exposed: (s) => ({ critical: 12, high: 8, medium: 5, low: 2 })[s],
12
- "quantum-key-exchange": () => 5,
13
- "quantum-signature": () => 2,
14
- };
15
- /** Most a category can take off in total, so one area can't hide every other. */
16
- const CAP = {
17
- secret: 50,
18
- weak: 30,
19
- exposed: 30,
20
- "quantum-key-exchange": 20,
21
- "quantum-signature": 8,
22
- };
23
- /** Best grade a repository can get while it has any problem in this category. */
24
- const GRADE_CAP = {
25
- secret: "D",
26
- weak: "C",
27
- exposed: "C",
28
- "quantum-key-exchange": "B",
29
- "quantum-signature": "A",
30
- };
31
- const THRESHOLDS = [
32
- [90, "A"],
33
- [75, "B"],
34
- [60, "C"],
35
- [40, "D"],
36
- [0, "F"],
37
- ];
38
- export function categoryOf(f) {
39
- if (f.risk === "secret")
40
- return "secret";
41
- if (f.risk === "weak-now")
42
- return "weak";
43
- if (f.risk === "exposed")
44
- return "exposed";
45
- return f.primitive === "signature" ? "quantum-signature" : "quantum-key-exchange";
46
- }
47
- /** 1 use counts once; more uses count more, up to double (16 or more uses). */
48
- export function useMultiplier(uses) {
49
- return Math.min(2, 1 + 0.25 * Math.log2(Math.max(1, uses)));
50
- }
51
- function worse(a, b) {
52
- return GRADES[Math.max(GRADES.indexOf(a), GRADES.indexOf(b))];
53
- }
54
- export function readinessScore(findings, pqc = []) {
55
- const pqcKex = pqc.some((p) => p.use === "key-establishment");
56
- const pqcSig = pqc.some((p) => p.use === "signature");
57
- // One deduction per category and algorithm (or setting), however many files use it.
58
- const groups = new Map();
59
- for (const f of findings) {
60
- const k = `${categoryOf(f)}|${f.algorithm}`;
61
- groups.set(k, [...(groups.get(k) ?? []), f]);
62
- }
63
- const deductions = [];
64
- for (const g of groups.values()) {
65
- const category = categoryOf(g[0]);
66
- // A group is as serious as its most serious use.
67
- const sev = g.map((f) => f.severity).sort((a, b) => sevRank(a) - sevRank(b))[0];
68
- let points = BASE[category](sev) * useMultiplier(g.length);
69
- // Credit for migration under way: half off where post-quantum methods are already in use.
70
- if ((category === "quantum-key-exchange" && pqcKex) || (category === "quantum-signature" && pqcSig))
71
- points /= 2;
72
- deductions.push({ category, algorithm: g[0].algorithm, uses: g.length, points: round1(points) });
73
- }
74
- const counts = { secret: 0, weak: 0, exposed: 0, "quantum-key-exchange": 0, "quantum-signature": 0 };
75
- const byCategory = { ...counts };
76
- for (const d of deductions) {
77
- counts[d.category] += d.uses;
78
- byCategory[d.category] += d.points;
79
- }
80
- let total = 0;
81
- for (const c of Object.keys(CAP))
82
- total += Math.min(CAP[c], byCategory[c]);
83
- const score = Math.max(0, Math.round(100 - total));
84
- let grade = THRESHOLDS.find(([min]) => score >= min)[1];
85
- for (const c of Object.keys(GRADE_CAP))
86
- if (counts[c])
87
- grade = worse(grade, GRADE_CAP[c]);
88
- // A+ is for repositories with nothing left to fix that already use post-quantum methods.
89
- if (grade === "A" && !findings.length && (pqcKex || pqcSig))
90
- grade = "A+";
91
- const due = counts.secret || counts.weak || counts.exposed ? "now" : counts["quantum-key-exchange"] ? "2030" : counts["quantum-signature"] ? "2035" : null;
92
- return {
93
- method: METHOD_VERSION,
94
- score,
95
- grade,
96
- counts,
97
- pqc: { keyExchange: pqcKex, signatures: pqcSig, algorithms: [...new Set(pqc.map((p) => p.algorithm))] },
98
- due,
99
- deductions: deductions.sort((a, b) => b.points - a.points),
100
- };
101
- }
102
- function sevRank(s) {
103
- return { critical: 0, high: 1, medium: 2, low: 3 }[s];
104
- }
105
- function round1(n) {
106
- return Math.round(n * 10) / 10;
107
- }
108
- /** One plain sentence about the grade, for reports and the command line. */
109
- export function gradeSentence(s) {
110
- const lead = `Quantum readiness: ${s.grade} (${s.score}/100, Hard Keel method v${s.method}).`;
111
- if (s.grade === "A+")
112
- return `${lead} Nothing to fix, and post-quantum encryption is already in use.`;
113
- if (s.due === null)
114
- return `${lead} Nothing to fix.`;
115
- if (s.counts.secret)
116
- return `${lead} A leaked key or password holds the grade at D or lower until it is revoked and removed.`;
117
- if (s.due === "now")
118
- return `${lead} Weak encryption or exposed settings hold the grade at C or lower until they are fixed.`;
119
- if (s.due === "2030")
120
- return `${lead} Key exchange or RSA keys that quantum computers will break hold the grade at B until they move to post-quantum methods.`;
121
- return `${lead} Only signatures are left to move to post-quantum methods, before 2035.`;
122
- }
1
+ // Hard Keel quantum readiness score, method version 1.
2
+ // Turns a full-repository scan into a 0-100 score and a grade from A+ to F.
3
+ // The method is public: docs/readiness-score.md and hardkeel.com/learn/quantum-readiness-score/.
4
+ // Change a weight, cap or threshold only by bumping METHOD_VERSION and the docs together.
5
+ export const METHOD_VERSION = "1";
6
+ const GRADES = ["A+", "A", "B", "C", "D", "F"];
7
+ /** Points taken off for one kind of problem (one algorithm or setting), before the use multiplier. */
8
+ const BASE = {
9
+ secret: () => 25,
10
+ weak: (s) => (s === "critical" || s === "high" ? 10 : 6),
11
+ exposed: (s) => ({ critical: 12, high: 8, medium: 5, low: 2 })[s],
12
+ "quantum-key-exchange": () => 5,
13
+ "quantum-signature": () => 2,
14
+ };
15
+ /** Most a category can take off in total, so one area can't hide every other. */
16
+ const CAP = {
17
+ secret: 50,
18
+ weak: 30,
19
+ exposed: 30,
20
+ "quantum-key-exchange": 20,
21
+ "quantum-signature": 8,
22
+ };
23
+ /** Best grade a repository can get while it has any problem in this category. */
24
+ const GRADE_CAP = {
25
+ secret: "D",
26
+ weak: "C",
27
+ exposed: "C",
28
+ "quantum-key-exchange": "B",
29
+ "quantum-signature": "A",
30
+ };
31
+ const THRESHOLDS = [
32
+ [90, "A"],
33
+ [75, "B"],
34
+ [60, "C"],
35
+ [40, "D"],
36
+ [0, "F"],
37
+ ];
38
+ export function categoryOf(f) {
39
+ if (f.risk === "secret")
40
+ return "secret";
41
+ if (f.risk === "weak-now")
42
+ return "weak";
43
+ if (f.risk === "exposed")
44
+ return "exposed";
45
+ return f.primitive === "signature" ? "quantum-signature" : "quantum-key-exchange";
46
+ }
47
+ /** 1 use counts once; more uses count more, up to double (16 or more uses). */
48
+ export function useMultiplier(uses) {
49
+ return Math.min(2, 1 + 0.25 * Math.log2(Math.max(1, uses)));
50
+ }
51
+ function worse(a, b) {
52
+ return GRADES[Math.max(GRADES.indexOf(a), GRADES.indexOf(b))];
53
+ }
54
+ export function readinessScore(findings, pqc = []) {
55
+ const pqcKex = pqc.some((p) => p.use === "key-establishment");
56
+ const pqcSig = pqc.some((p) => p.use === "signature");
57
+ // One deduction per category and algorithm (or setting), however many files use it.
58
+ const groups = new Map();
59
+ for (const f of findings) {
60
+ const k = `${categoryOf(f)}|${f.algorithm}`;
61
+ groups.set(k, [...(groups.get(k) ?? []), f]);
62
+ }
63
+ const deductions = [];
64
+ for (const g of groups.values()) {
65
+ const category = categoryOf(g[0]);
66
+ // A group is as serious as its most serious use.
67
+ const sev = g.map((f) => f.severity).sort((a, b) => sevRank(a) - sevRank(b))[0];
68
+ let points = BASE[category](sev) * useMultiplier(g.length);
69
+ // Credit for migration under way: half off where post-quantum methods are already in use.
70
+ if ((category === "quantum-key-exchange" && pqcKex) || (category === "quantum-signature" && pqcSig))
71
+ points /= 2;
72
+ deductions.push({ category, algorithm: g[0].algorithm, uses: g.length, points: round1(points) });
73
+ }
74
+ const counts = { secret: 0, weak: 0, exposed: 0, "quantum-key-exchange": 0, "quantum-signature": 0 };
75
+ const byCategory = { ...counts };
76
+ for (const d of deductions) {
77
+ counts[d.category] += d.uses;
78
+ byCategory[d.category] += d.points;
79
+ }
80
+ let total = 0;
81
+ for (const c of Object.keys(CAP))
82
+ total += Math.min(CAP[c], byCategory[c]);
83
+ const score = Math.max(0, Math.round(100 - total));
84
+ let grade = THRESHOLDS.find(([min]) => score >= min)[1];
85
+ for (const c of Object.keys(GRADE_CAP))
86
+ if (counts[c])
87
+ grade = worse(grade, GRADE_CAP[c]);
88
+ // A+ is for repositories with nothing left to fix that already use post-quantum methods.
89
+ if (grade === "A" && !findings.length && (pqcKex || pqcSig))
90
+ grade = "A+";
91
+ const due = counts.secret || counts.weak || counts.exposed ? "now" : counts["quantum-key-exchange"] ? "2030" : counts["quantum-signature"] ? "2035" : null;
92
+ return {
93
+ method: METHOD_VERSION,
94
+ score,
95
+ grade,
96
+ counts,
97
+ pqc: { keyExchange: pqcKex, signatures: pqcSig, algorithms: [...new Set(pqc.map((p) => p.algorithm))] },
98
+ due,
99
+ deductions: deductions.sort((a, b) => b.points - a.points),
100
+ };
101
+ }
102
+ function sevRank(s) {
103
+ return { critical: 0, high: 1, medium: 2, low: 3 }[s];
104
+ }
105
+ function round1(n) {
106
+ return Math.round(n * 10) / 10;
107
+ }
108
+ /** One plain sentence about the grade, for reports and the command line. */
109
+ export function gradeSentence(s) {
110
+ const lead = `Quantum readiness: ${s.grade} (${s.score}/100, Hard Keel method v${s.method}).`;
111
+ if (s.grade === "A+")
112
+ return `${lead} Nothing to fix, and post-quantum encryption is already in use.`;
113
+ if (s.due === null)
114
+ return `${lead} Nothing to fix.`;
115
+ if (s.counts.secret)
116
+ return `${lead} A leaked key or password holds the grade at D or lower until it is revoked and removed.`;
117
+ if (s.due === "now")
118
+ return `${lead} Weak encryption or exposed settings hold the grade at C or lower until they are fixed.`;
119
+ if (s.due === "2030")
120
+ return `${lead} Key exchange or RSA keys that quantum computers will break hold the grade at B until they move to post-quantum methods.`;
121
+ return `${lead} Only signatures are left to move to post-quantum methods, before 2035.`;
122
+ }
package/dist/secrets.js CHANGED
@@ -1,97 +1,108 @@
1
- // Leaked-credential detection. A bonus check that rides along with the crypto scan.
2
- export const SECRET_RULES = [
3
- { id: "private-key", name: "Private key", pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY(?: BLOCK)?-----/ },
4
- { id: "aws-access-key-id", name: "AWS access key", pattern: /\b((?:AKIA|ASIA|AGPA|AIDA|AROA)[0-9A-Z]{16})\b/, group: 1 },
5
- { id: "github-token", name: "GitHub token", pattern: /\b(gh[pousr]_[A-Za-z0-9]{36,255})\b/, group: 1 },
6
- { id: "github-fine-grained-pat", name: "GitHub token", pattern: /\b(github_pat_[A-Za-z0-9_]{60,255})\b/, group: 1 },
7
- { id: "gitlab-pat", name: "GitLab token", pattern: /\b(glpat-[A-Za-z0-9_-]{20,})\b/, group: 1 },
8
- { id: "slack-token", name: "Slack token", pattern: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/, group: 1 },
9
- { id: "slack-webhook", name: "Slack webhook", pattern: /(https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+)/, group: 1 },
10
- { id: "stripe-secret", name: "Stripe secret key", pattern: /\b((?:sk|rk)_live_[A-Za-z0-9]{20,})\b/, group: 1 },
11
- { id: "google-api-key", name: "Google API key", pattern: /\b(AIza[0-9A-Za-z_-]{35})\b/, group: 1 },
12
- { id: "anthropic-key", name: "Anthropic API key", pattern: /\b(sk-ant-[A-Za-z0-9_-]{32,})\b/, group: 1 },
13
- { id: "openai-key", name: "OpenAI API key", pattern: /\b(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{32,})\b/, group: 1 },
14
- { id: "sendgrid-key", name: "SendGrid key", pattern: /\b(SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})\b/, group: 1 },
15
- { id: "npm-token", name: "npm token", pattern: /\b(npm_[A-Za-z0-9]{36})\b/, group: 1 },
16
- { id: "db-url-password", name: "Database password in URL", pattern: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/'"]+:([^@\s'"]{6,})@/, group: 1, minEntropy: 2.5 },
17
- {
18
- id: "generic-assignment",
19
- name: "Hardcoded secret",
20
- pattern: /\b[A-Za-z0-9_]*(?:api[_-]?key|secret|token|passwd|password|private[_-]?key)[A-Za-z0-9_]*["']?\s*[:=]\s*["']([^"'\s]{16,})["']/i,
21
- group: 1,
22
- minEntropy: 3.5,
23
- },
24
- ];
25
- const PLACEHOLDER = /(example|sample|dummy|changeme|change_me|placeholder|your[_-]|^your|xxxx|\*\*\*\*|<[^>]+>|\$\{|\{\{|process\.env|os\.environ|getenv|redacted|test)/i;
26
- // Documentation tokens like "xoxb-1234567890-abcdefghij".
27
- const FAKE_SEQUENCE = /1234567890|0123456789|abcdefghij/;
28
- // Names that hold something about a secret, not the secret itself (SECRET_KEY_PREFIX, password_template).
29
- const NOT_A_SECRET_NAME = /(template|prefix|suffix|header|_name|name_|field|path|url|label|message|_msg|_type|type_|format|pattern|regex)/i;
30
- /** The generic "name = value" rule is noisy; drop the shapes that are almost never real secrets. */
31
- function looksLikeSecretAssignment(match, value, line) {
32
- const name = match.split(/["']?\s*[:=]/)[0];
33
- if (NOT_A_SECRET_NAME.test(name))
34
- return false;
35
- if (/^\s*(>>>|\.\.\.)\s/.test(line))
36
- return false; // doctest example
37
- if (/^[a-z_-]+$/.test(value))
38
- return false; // an identifier, like "userauth-gssapi-token"
39
- if (/^\$?[a-z0-9_]+\$/.test(value))
40
- return false; // a stored password hash, like "pbkdf2_sha256$..." or "$argon2id$..."
41
- if (/\$\{?[A-Za-z_]/.test(value))
42
- return false; // string interpolation, like "$user:$password"
43
- if (/^[([^]/.test(value))
44
- return false; // a regular expression
45
- if (/\\(x[0-9a-f]{2}|u[0-9a-f]{4}|0)/i.test(value))
46
- return false; // a binary magic string, like "openssh-key-v1\x00"
47
- if (/^[a-z]+(?:[A-Z][a-z]*)+$/.test(value))
48
- return false; // a camelCase identifier, like "challengePassword"
49
- if (/\{\{/.test(line))
50
- return false; // a Helm or Go template line
51
- if (/^[a-z][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)+$/.test(value))
52
- return false; // a settings key, like "webhook.github.secret"
53
- if (/^[A-Z][A-Z0-9_]{5,}$/.test(value))
54
- return false; // the name of an environment variable, like "ARGOCD_AUTH_TOKEN"
55
- if (/^(\/|\.{1,2}\/|~\/|[A-Za-z]:\\)/.test(value))
56
- return false; // a file path, like "/var/run/secrets/token"
57
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value))
58
- return false; // a URL, like "https://oauth2.googleapis.com/token"
59
- return true;
60
- }
61
- export function entropy(s) {
62
- const counts = new Map();
63
- for (const ch of s)
64
- counts.set(ch, (counts.get(ch) ?? 0) + 1);
65
- let h = 0;
66
- for (const c of counts.values()) {
67
- const p = c / s.length;
68
- h -= p * Math.log2(p);
69
- }
70
- return h;
71
- }
72
- export function mask(value) {
73
- if (value.length <= 8)
74
- return "****";
75
- return `${value.slice(0, 4)}${"*".repeat(Math.min(12, value.length - 4))}`;
76
- }
77
- export function findSecrets(line) {
78
- const hits = [];
79
- for (const rule of SECRET_RULES) {
80
- const m = line.match(rule.pattern);
81
- if (!m)
82
- continue;
83
- const value = m[rule.group ?? 0] ?? m[0];
84
- if (rule.id !== "private-key" && (PLACEHOLDER.test(value) || FAKE_SEQUENCE.test(value)))
85
- continue;
86
- if (rule.minEntropy !== undefined && entropy(value) < rule.minEntropy)
87
- continue;
88
- if (rule.id === "generic-assignment" && !looksLikeSecretAssignment(m[0], value, line))
89
- continue;
90
- if (rule.id === "db-url-password" && /^(pass(word)?|passwd|pwd|secret)$/i.test(value))
91
- continue;
92
- hits.push({ rule, value });
93
- }
94
- // The generic rule only counts when nothing specific matched the line.
95
- const specific = hits.filter((h) => h.rule.id !== "generic-assignment");
96
- return specific.length ? specific : hits;
97
- }
1
+ // Leaked-credential detection. A bonus check that rides along with the crypto scan.
2
+ export const SECRET_RULES = [
3
+ { id: "private-key", name: "Private key", pattern: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED |PGP )?PRIVATE KEY(?: BLOCK)?-----/ },
4
+ { id: "aws-access-key-id", name: "AWS access key", pattern: /\b((?:AKIA|ASIA|AGPA|AIDA|AROA)[0-9A-Z]{16})\b/, group: 1 },
5
+ { id: "github-token", name: "GitHub token", pattern: /\b(gh[pousr]_[A-Za-z0-9]{36,255})\b/, group: 1 },
6
+ { id: "github-fine-grained-pat", name: "GitHub token", pattern: /\b(github_pat_[A-Za-z0-9_]{60,255})\b/, group: 1 },
7
+ { id: "gitlab-pat", name: "GitLab token", pattern: /\b(glpat-[A-Za-z0-9_-]{20,})\b/, group: 1 },
8
+ { id: "slack-token", name: "Slack token", pattern: /\b(xox[baprs]-[A-Za-z0-9-]{10,})\b/, group: 1 },
9
+ { id: "slack-webhook", name: "Slack webhook", pattern: /(https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]+)/, group: 1 },
10
+ { id: "stripe-secret", name: "Stripe secret key", pattern: /\b((?:sk|rk)_live_[A-Za-z0-9]{20,})\b/, group: 1 },
11
+ { id: "google-api-key", name: "Google API key", pattern: /\b(AIza[0-9A-Za-z_-]{35})\b/, group: 1 },
12
+ { id: "anthropic-key", name: "Anthropic API key", pattern: /\b(sk-ant-[A-Za-z0-9_-]{32,})\b/, group: 1 },
13
+ { id: "openai-key", name: "OpenAI API key", pattern: /\b(sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{32,})\b/, group: 1 },
14
+ { id: "sendgrid-key", name: "SendGrid key", pattern: /\b(SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})\b/, group: 1 },
15
+ { id: "npm-token", name: "npm token", pattern: /\b(npm_[A-Za-z0-9]{36})\b/, group: 1 },
16
+ { id: "db-url-password", name: "Database password in URL", pattern: /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/'"]+:([^@\s'"]{6,})@/, group: 1, minEntropy: 2.5 },
17
+ {
18
+ id: "generic-assignment",
19
+ name: "Hardcoded secret",
20
+ pattern: /\b[A-Za-z0-9_]*(?:api[_-]?key|secret|token|passwd|password|private[_-]?key)[A-Za-z0-9_]*["']?\s*[:=]\s*["']([^"'\s]{16,})["']/i,
21
+ group: 1,
22
+ minEntropy: 3.5,
23
+ },
24
+ ];
25
+ const PLACEHOLDER = /(example|sample|dummy|changeme|change_me|placeholder|your[_-]|^your|xxxx|\*\*\*\*|<[^>]+>|\$\{|\{\{|process\.env|os\.environ|getenv|redacted|test)/i;
26
+ // Documentation tokens like "xoxb-1234567890-abcdefghij".
27
+ const FAKE_SEQUENCE = /1234567890|0123456789|abcdefghij/;
28
+ // Names that hold something about a secret, not the secret itself (SECRET_KEY_PREFIX, password_template).
29
+ const NOT_A_SECRET_NAME = /(template|prefix|suffix|header|_name|name_|field|path|url|label|message|_msg|_type|type_|format|pattern|regex|tokeniz|hashed|token_?(?:roles_?)?key|_uid|invalid|not_?found|expir|permission|^\W*has_|repo|class|checksum|params?\b|req_?(?:query|body))/i;
30
+ /** The generic "name = value" rule is noisy; drop the shapes that are almost never real secrets. */
31
+ function looksLikeSecretAssignment(match, value, line) {
32
+ const name = match.split(/["']?\s*[:=]/)[0];
33
+ if (NOT_A_SECRET_NAME.test(name))
34
+ return false;
35
+ if (/^\s*(>>>|\.\.\.)\s/.test(line))
36
+ return false; // doctest example
37
+ if (/^[a-z_-]+$/.test(value))
38
+ return false; // an identifier, like "userauth-gssapi-token"
39
+ if (!/^[\x21-\x7e]+$/.test(value))
40
+ return false; // text in another script, like a translated "Password" label
41
+ if (!/\d/.test(value) && value.length < 32)
42
+ return false; // words, like "excludedRequestDomains:", not a random value
43
+ if (/^\$?[a-z0-9_]+\$/.test(value))
44
+ return false; // a stored password hash, like "pbkdf2_sha256$..." or "$argon2id$..."
45
+ if (/\$\{?[A-Za-z_]|\$\(|\{\}|%[sd]|^var\(/.test(value))
46
+ return false; // interpolation or a format string, like "$user:$password" or "$(Build.Secret)"
47
+ if (/^(bao|vault|secret|op|sm|ref\+[a-z]+|arn):/i.test(value))
48
+ return false; // a reference to a secret store, not the secret
49
+ if (/^(phc_|pk_(live|test)_)/.test(value))
50
+ return false; // a public client key (PostHog, Stripe publishable), safe to ship
51
+ if (/^[([^]/.test(value))
52
+ return false; // a regular expression
53
+ if (/\\(x[0-9a-f]{2}|u[0-9a-f]{4}|0)/i.test(value))
54
+ return false; // a binary magic string, like "openssh-key-v1\x00"
55
+ if (/^[a-z]+(?:[A-Z][a-z]*)+$/.test(value))
56
+ return false; // a camelCase identifier, like "challengePassword"
57
+ if (/\{\{/.test(line))
58
+ return false; // a Helm or Go template line
59
+ if (/^[a-z][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)+$/.test(value))
60
+ return false; // a settings key, like "webhook.github.secret"
61
+ if (/^[A-Z][A-Z0-9_]{5,}$/.test(value))
62
+ return false; // the name of an environment variable, like "ARGOCD_AUTH_TOKEN"
63
+ if (/^(\/|\.{1,2}\/|~\/|[A-Za-z]:\\)/.test(value))
64
+ return false; // a file path, like "/var/run/secrets/token"
65
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value))
66
+ return false; // a URL, like "https://oauth2.googleapis.com/token"
67
+ return true;
68
+ }
69
+ export function entropy(s) {
70
+ const counts = new Map();
71
+ for (const ch of s)
72
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
73
+ let h = 0;
74
+ for (const c of counts.values()) {
75
+ const p = c / s.length;
76
+ h -= p * Math.log2(p);
77
+ }
78
+ return h;
79
+ }
80
+ export function mask(value) {
81
+ if (value.length <= 8)
82
+ return "****";
83
+ return `${value.slice(0, 4)}${"*".repeat(Math.min(12, value.length - 4))}`;
84
+ }
85
+ export function findSecrets(line) {
86
+ const hits = [];
87
+ for (const rule of SECRET_RULES) {
88
+ const m = line.match(rule.pattern);
89
+ if (!m)
90
+ continue;
91
+ const value = m[rule.group ?? 0] ?? m[0];
92
+ if (rule.id !== "private-key" && (PLACEHOLDER.test(value) || FAKE_SEQUENCE.test(value)))
93
+ continue;
94
+ if (rule.minEntropy !== undefined && entropy(value) < rule.minEntropy)
95
+ continue;
96
+ if (rule.id === "generic-assignment" && !looksLikeSecretAssignment(m[0], value, line))
97
+ continue;
98
+ if (rule.id === "db-url-password" && /^(pass(word)?|passwd|pwd|secret)$/i.test(value))
99
+ continue;
100
+ // A database on this machine (CI services, local dev) has a throwaway password.
101
+ if (rule.id === "db-url-password" && /@(localhost|127\.0\.0\.1|\[::1\])[:/]/.test(m[0] + line.slice((m.index ?? 0) + m[0].length, (m.index ?? 0) + m[0].length + 12)))
102
+ continue;
103
+ hits.push({ rule, value });
104
+ }
105
+ // The generic rule only counts when nothing specific matched the line.
106
+ const specific = hits.filter((h) => h.rule.id !== "generic-assignment");
107
+ return specific.length ? specific : hits;
108
+ }