riskdiff-cli 0.0.0-stage → 2.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.
package/src/rules.js ADDED
@@ -0,0 +1,244 @@
1
+ // Risk rules. Each rule matches a hunk by file path, added lines, or removed lines.
2
+ // A rule counts at most once per hunk; the hunk score is the sum of matched weights.
3
+ //
4
+ // Line rules see code with comments stripped (hunk.addedCode / hunk.removedCode),
5
+ // unless the rule sets `raw: true` because what it looks for can live in comments.
6
+ // A `match` function may return a string, which replaces the reason with specifics.
7
+ import { lookalike, sameJob } from './packages.js';
8
+
9
+ export const TEST_PATH = /(^|\/)(tests?|__tests__|spec)\/|\.(test|spec)\.[a-z]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$/i;
10
+ export const MANIFEST = /(^|\/)(package\.json|requirements[^/]*\.txt|pyproject\.toml|Pipfile|go\.mod|Cargo\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/;
11
+ const LOCKFILE = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Pipfile\.lock|go\.sum|Cargo\.lock|Gemfile\.lock|composer\.lock)$/;
12
+
13
+ export const builtinRules = [
14
+ // --- Sensitive areas (by path) ---
15
+ {
16
+ id: 'auth-code',
17
+ weight: 25,
18
+ reason: 'Touches authentication, sessions, or permissions',
19
+ path: /(auth|login|logout|session|passw(or)?d|permission|acl|oauth|jwt|rbac|credential)/i,
20
+ },
21
+ {
22
+ id: 'payment-code',
23
+ weight: 25,
24
+ reason: 'Touches payments or billing',
25
+ path: /(payment|billing|checkout|invoice|stripe|paypal|subscription|refund)/i,
26
+ },
27
+ {
28
+ id: 'crypto-code',
29
+ weight: 20,
30
+ reason: 'Touches cryptography or hashing',
31
+ path: /(crypto|encrypt|decrypt|cipher|hash|signing|signature)/i,
32
+ },
33
+ {
34
+ id: 'migration',
35
+ weight: 20,
36
+ reason: 'Database migration or SQL file',
37
+ path: /(migrations?\/|\.sql$|schema\.prisma$)/i,
38
+ },
39
+ {
40
+ id: 'ci-infra',
41
+ weight: 20,
42
+ reason: 'CI, deployment, or infrastructure config',
43
+ path: /(^\.github\/workflows\/|(^|\/)Dockerfile|docker-compose|\.tf$|(^|\/)(k8s|helm|deploy|infra)\/|\.gitlab-ci\.yml$|Jenkinsfile)/i,
44
+ },
45
+ {
46
+ id: 'env-file',
47
+ weight: 30,
48
+ reason: 'Environment or secrets file',
49
+ path: /(^|\/)\.env(\.|$)(?!example|sample|template)/i,
50
+ },
51
+ {
52
+ id: 'lockfile',
53
+ weight: 3,
54
+ reason: 'Lockfile change (usually follows a manifest change)',
55
+ path: LOCKFILE,
56
+ },
57
+
58
+ // --- Added code ---
59
+ {
60
+ id: 'hardcoded-secret',
61
+ weight: 50,
62
+ reason: 'Looks like a hardcoded secret or API key',
63
+ raw: true,
64
+ added: [
65
+ /(api[_-]?key|secret|passw(or)?d|token|private[_-]?key)["']?\s*[:=]\s*["'][^"'\s]{8,}["']/i,
66
+ /\b(AKIA[0-9A-Z]{16}|sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{36}|xox[baprs]-[A-Za-z0-9-]{10,})\b/,
67
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
68
+ ],
69
+ },
70
+ {
71
+ id: 'dangerous-exec',
72
+ weight: 30,
73
+ reason: 'Runs dynamic code or shell commands',
74
+ added: [
75
+ /\beval\s*\(/,
76
+ /new\s+Function\s*\(/,
77
+ /child_process|\bexecSync\s*\(|\bspawnSync\s*\(/,
78
+ /\bos\.system\s*\(|\bsubprocess\.\w+\(|shell\s*=\s*True/,
79
+ /\b(Runtime\.getRuntime\(\)\.exec|ProcessBuilder)\b/,
80
+ ],
81
+ },
82
+ {
83
+ id: 'destructive-sql',
84
+ weight: 35,
85
+ reason: 'Destructive SQL (DROP, TRUNCATE, or DELETE without WHERE)',
86
+ added: [/\bDROP\s+(TABLE|DATABASE|SCHEMA|COLUMN)\b/i, /\bTRUNCATE\b/i, /\bDELETE\s+FROM\s+[\w."`]+\s*(;|["'`]|$)/i],
87
+ },
88
+ {
89
+ id: 'sql-injection',
90
+ weight: 25,
91
+ reason: 'SQL built from string concatenation or interpolation',
92
+ added: [
93
+ /\b(SELECT|INSERT|UPDATE|DELETE)\b[^;]*["'`]\s*\+\s*\w/i,
94
+ /\b(SELECT|INSERT|UPDATE|DELETE)\b[^;]*\$\{/i,
95
+ /f["'][^"']*\b(SELECT|INSERT|UPDATE|DELETE)\b[^"']*\{/i,
96
+ /\b(SELECT|INSERT|UPDATE|DELETE)\b[^;]*["']\s*%\s*\(?\w/i,
97
+ ],
98
+ },
99
+ {
100
+ id: 'security-disabled',
101
+ weight: 30,
102
+ reason: 'Disables a security check (TLS, CORS, CSRF)',
103
+ added: [
104
+ /verify\s*=\s*False/,
105
+ /rejectUnauthorized\s*:\s*false/,
106
+ /NODE_TLS_REJECT_UNAUTHORIZED\s*=?\s*["']?0/,
107
+ /InsecureSkipVerify\s*:\s*true/,
108
+ /Access-Control-Allow-Origin["']?\s*[:,]\s*["']\*/i,
109
+ /origin\s*:\s*["']\*["']/,
110
+ /csrf[_-]?(exempt|disable)|csrf\(\)\.disable|@csrf_exempt/i,
111
+ ],
112
+ },
113
+ {
114
+ id: 'test-skipped',
115
+ weight: 20,
116
+ reason: 'Skips or focuses tests',
117
+ added: [
118
+ /\b(it|test|describe)\.(skip|only)\s*\(/,
119
+ /\b(xit|xdescribe|xtest|fit|fdescribe)\s*\(/,
120
+ /@pytest\.mark\.(skip|xfail)/,
121
+ /@(Disabled|Ignore)\b/,
122
+ /\bt\.Skip\(/,
123
+ /unittest\.skip/,
124
+ ],
125
+ },
126
+ {
127
+ id: 'swallowed-error',
128
+ weight: 15,
129
+ reason: 'Catches an error and ignores it',
130
+ added: [/catch\s*(\(\s*\w*\s*\))?\s*\{\s*\}/, /except(\s+\w+(\s+as\s+\w+)?)?\s*:\s*pass\b/, /\.catch\(\s*\(\s*\)\s*=>\s*\{?\s*\}?\s*\)/],
131
+ },
132
+ {
133
+ id: 'new-dependency',
134
+ weight: 15,
135
+ reason: 'Adds or changes a dependency',
136
+ match: (file, hunk) => (hunk.deps ?? []).length > 0,
137
+ },
138
+ {
139
+ id: 'package-lookalike',
140
+ weight: 30,
141
+ reason: 'New dependency name looks like a popular package',
142
+ match: (file, hunk) => {
143
+ const hits = (hunk.deps ?? []).map((d) => [d.name, lookalike(d)]).filter(([, p]) => p);
144
+ return hits.length > 0 && hits.map(([n, p]) => `${n} looks like ${p}; check it is the package you meant`).join('; ');
145
+ },
146
+ },
147
+ {
148
+ id: 'duplicate-dependency',
149
+ weight: 15,
150
+ reason: 'Adds a library that does the same job as one already in the project',
151
+ match: (file, hunk) => {
152
+ const byJob = new Map();
153
+ for (const d of hunk.deps ?? []) {
154
+ const hit = sameJob(d, hunk.projectDeps ?? hunk.deps);
155
+ if (!hit) continue;
156
+ const entry = byJob.get(hit.job) ?? { added: new Set(), others: new Set() };
157
+ entry.added.add(d.name);
158
+ for (const o of hit.others) entry.others.add(o);
159
+ byJob.set(hit.job, entry);
160
+ }
161
+ const addedNames = new Set((hunk.deps ?? []).map((d) => d.name.toLowerCase()));
162
+ const messages = [...byJob].map(([job, { added, others }]) => {
163
+ const existing = [...others].filter((o) => !addedNames.has(o));
164
+ return existing.length
165
+ ? `Adds ${[...added].join(' and ')}, but the project already has ${existing.join(', ')} (${job})`
166
+ : `Adds ${[...added].join(' and ')}, which do the same job (${job})`;
167
+ });
168
+ return messages.length > 0 && messages.join('; ');
169
+ },
170
+ },
171
+ // Registry rules: filled in by checkPackages() when --check-packages is on.
172
+ { id: 'package-not-found', weight: 50, reason: 'Dependency does not exist in its registry', online: true, match: () => false },
173
+ { id: 'package-new', weight: 30, reason: 'Dependency was first published in the last 30 days', online: true, match: () => false },
174
+ { id: 'package-low-downloads', weight: 15, reason: 'Dependency has very few downloads', online: true, match: () => false },
175
+ { id: 'package-deprecated', weight: 15, reason: 'Dependency is deprecated or yanked', online: true, match: () => false },
176
+ {
177
+ id: 'todo-added',
178
+ weight: 5,
179
+ reason: 'Adds a TODO, FIXME, or HACK',
180
+ raw: true,
181
+ added: [/\b(TODO|FIXME|HACK|XXX)\b/],
182
+ },
183
+
184
+ // --- Removed code ---
185
+ {
186
+ id: 'auth-check-removed',
187
+ weight: 50,
188
+ reason: 'Removes an authentication or permission check',
189
+ removed: [
190
+ /\b(requireAuth|isAuthenticated|ensureAuth\w*|authorize\w*|checkPermission\w*|hasPermission|verifyToken|requireRole|canAccess)\b/,
191
+ /@(login_required|permission_required|PreAuthorize|Secured|RolesAllowed|UseGuards)\b/,
192
+ ],
193
+ },
194
+ {
195
+ id: 'error-handling-removed',
196
+ weight: 20,
197
+ reason: 'Removes error handling',
198
+ removed: [/\b(try|catch|except|finally|throw|raise|rescue)\b|if\s+err\s*!=\s*nil/],
199
+ },
200
+ {
201
+ id: 'validation-removed',
202
+ weight: 20,
203
+ reason: 'Removes input validation or sanitizing',
204
+ removed: [/\b(validate\w*|sanitiz\w*|escape\w*|assertValid\w*)\s*\(|\.parse\(|zod|Joi\./i],
205
+ },
206
+ {
207
+ id: 'assertion-removed',
208
+ weight: 20,
209
+ reason: 'Removes test assertions',
210
+ testsOnly: true,
211
+ removed: [/\b(expect|assert\w*|should)\b[.(]|^\s*assert\s|\bself\.assert\w+\(/],
212
+ },
213
+ {
214
+ id: 'test-file-deleted',
215
+ weight: 25,
216
+ reason: 'Deletes a test file',
217
+ match: (file) => file.status === 'deleted' && TEST_PATH.test(file.path),
218
+ },
219
+ ];
220
+
221
+ export function matchRule(rule, file, hunk) {
222
+ if (rule.testsOnly && !TEST_PATH.test(file.path ?? '')) return false;
223
+ if (rule.match) return rule.match(file, hunk);
224
+ if (rule.path) return rule.path.test(file.path ?? '');
225
+ if (rule.added) {
226
+ const lines = rule.raw ? hunk.added : hunk.addedCode;
227
+ return lines.some((l) => rule.added.some((p) => p.test(l)));
228
+ }
229
+ if (rule.removed) {
230
+ // Deleted files are covered by their own rules, so they never count here.
231
+ if (file.status === 'deleted') return false;
232
+ const removed = rule.raw ? hunk.removed : hunk.removedCode;
233
+ const added = rule.raw ? hunk.added : hunk.addedCode;
234
+ return rule.removed.some((p) => removedMore(removed, added, p));
235
+ }
236
+ return false;
237
+ }
238
+
239
+ // True when the pattern appears on more removed lines than added lines,
240
+ // so moving or rewording the same code does not count as removal.
241
+ function removedMore(removed, added, pattern) {
242
+ const count = (lines) => lines.filter((l) => pattern.test(l)).length;
243
+ return count(removed) > count(added);
244
+ }
package/src/score.js ADDED
@@ -0,0 +1,90 @@
1
+ import { builtinRules, matchRule, MANIFEST } from './rules.js';
2
+ import { commentStyle, stripComments, ignoredRules } from './source.js';
3
+ import { addedDeps, allDeps } from './deps.js';
4
+
5
+ export const LEVELS = ['none', 'low', 'medium', 'high'];
6
+ const TEST_RULES = new Set(['test-skipped', 'assertion-removed', 'test-file-deleted']);
7
+
8
+ export function levelFor(score) {
9
+ if (score >= 50) return 'high';
10
+ if (score >= 25) return 'medium';
11
+ if (score > 0) return 'low';
12
+ return 'none';
13
+ }
14
+
15
+ // Scores every hunk and returns them sorted riskiest first.
16
+ // rules rule list (built-in rules by default)
17
+ // include (path) => boolean, false to skip a file
18
+ // readNew (path) => new file content or null, used to read manifests
19
+ export function scoreFiles(files, { rules = builtinRules, include = () => true, readNew = () => null } = {}) {
20
+ const knownIds = new Set(rules.map((r) => r.id));
21
+ const results = [];
22
+ for (const file of files) {
23
+ if (file.binary || !include(file.path ?? '')) continue;
24
+ const style = commentStyle(file.path);
25
+ const isManifest = MANIFEST.test(file.path ?? '');
26
+ let manifest, projectDeps;
27
+ // A deleted file with no hunks (e.g. empty) still deserves a row.
28
+ const hunks = file.hunks.length ? file.hunks : [{ header: '', context: '', line: 1, added: [], removed: [] }];
29
+
30
+ for (const hunk of hunks) {
31
+ hunk.addedCode = hunk.added.map((l) => stripComments(l, style));
32
+ hunk.removedCode = hunk.removed.map((l) => stripComments(l, style));
33
+ if (isManifest) {
34
+ if (manifest === undefined) {
35
+ manifest = readNew(file.path);
36
+ projectDeps = allDeps(file.path, manifest);
37
+ }
38
+ hunk.deps = addedDeps(file.path, hunk.added, manifest);
39
+ hunk.projectDeps = projectDeps.length ? projectDeps : hunk.deps;
40
+ }
41
+ const ignored = ignoredRules(hunk.added, knownIds);
42
+
43
+ const findings = [];
44
+ for (const rule of ignored === 'all' ? [] : rules) {
45
+ if (ignored?.has(rule.id)) continue;
46
+ const hit = matchRule(rule, file, hunk);
47
+ if (hit) findings.push({ id: rule.id, weight: rule.weight, reason: typeof hit === 'string' ? hit : rule.reason });
48
+ }
49
+
50
+ const changed = hunk.added.length + hunk.removed.length;
51
+ // Big hunks are harder to review; lockfile churn is not.
52
+ const sizeBonus = findings.some((f) => f.id === 'lockfile') ? 0 : Math.min(10, Math.floor(changed / 25));
53
+ if (sizeBonus && ignored !== 'all') findings.push({ id: 'large-change', weight: sizeBonus, reason: `Large change (${changed} lines)` });
54
+
55
+ results.push(finalize({
56
+ file: file.path,
57
+ status: file.status,
58
+ line: hunk.line,
59
+ context: hunk.context,
60
+ added: hunk.added.length,
61
+ removed: hunk.removed.length,
62
+ ignored: ignored === 'all' ? 'all' : ignored ? [...ignored] : undefined,
63
+ deps: hunk.deps?.length ? hunk.deps : undefined,
64
+ findings,
65
+ hunk,
66
+ }));
67
+ }
68
+ }
69
+ return sortResults(results);
70
+ }
71
+
72
+ // Recomputes score and level from findings. Call again after adding findings.
73
+ export function finalize(result) {
74
+ result.findings.sort((a, b) => b.weight - a.weight);
75
+ result.score = result.findings.reduce((sum, f) => sum + f.weight, 0);
76
+ result.level = levelFor(result.score);
77
+ return result;
78
+ }
79
+
80
+ export function sortResults(results) {
81
+ return results.sort((a, b) => b.score - a.score || a.file.localeCompare(b.file) || a.line - b.line);
82
+ }
83
+
84
+ // Counts the findings that weaken the test suite across the whole diff.
85
+ export function testTamper(results) {
86
+ const counts = { 'test-skipped': 0, 'assertion-removed': 0, 'test-file-deleted': 0 };
87
+ for (const r of results) for (const f of r.findings) if (TEST_RULES.has(f.id)) counts[f.id]++;
88
+ const total = Object.values(counts).reduce((a, b) => a + b, 0);
89
+ return { total, skipped: counts['test-skipped'], assertionsRemoved: counts['assertion-removed'], filesDeleted: counts['test-file-deleted'] };
90
+ }
package/src/source.js ADDED
@@ -0,0 +1,70 @@
1
+ // Language-aware helpers for reading changed lines: comment stripping and ignore directives.
2
+
3
+ const HASH = /\.(py|rb|sh|bash|zsh|ya?ml|toml|r|pl|ps1|cfg|ini|conf)$|(^|\/)(Dockerfile[^/]*|Makefile|Gemfile|Rakefile|requirements[^/]*\.txt|\.env[^/]*)$/i;
4
+ const SLASH = /\.(m?[jt]sx?|cjs|cts|mts|java|kt|kts|go|c|h|cc|cpp|hpp|cs|rs|swift|scala|dart|groovy|gradle|vue|svelte|css|scss|less|jsonc)$/i;
5
+ const BOTH = /\.(php|tf|hcl)$/i;
6
+ const SQL = /\.sql$/i;
7
+
8
+ export function commentStyle(path = '') {
9
+ if (BOTH.test(path)) return { hash: true, slash: true };
10
+ if (SLASH.test(path)) return { slash: true };
11
+ if (HASH.test(path)) return { hash: true };
12
+ if (SQL.test(path)) return { dashes: true };
13
+ return {};
14
+ }
15
+
16
+ // Removes comments from one line of code, leaving string literals intact.
17
+ // Works line by line, so a multi-line block comment is only caught by its leading "*".
18
+ export function stripComments(line, style) {
19
+ if (!style.hash && !style.slash && !style.dashes) return line;
20
+ if (style.slash && /^\s*(\*(\s|\/|$)|\/\*.*\*\/\s*$)/.test(line)) return '';
21
+
22
+ let out = '';
23
+ let quote = null;
24
+ for (let i = 0; i < line.length; i++) {
25
+ const ch = line[i];
26
+ if (quote) {
27
+ out += ch;
28
+ if (ch === '\\') out += line[++i] ?? '';
29
+ else if (ch === quote) quote = null;
30
+ continue;
31
+ }
32
+ if (ch === '"' || ch === "'" || ch === '`') {
33
+ quote = ch;
34
+ out += ch;
35
+ continue;
36
+ }
37
+ if (style.hash && ch === '#') break;
38
+ if (style.dashes && ch === '-' && line[i + 1] === '-') break;
39
+ if (style.slash && ch === '/' && line[i + 1] === '/') break;
40
+ if (style.slash && ch === '/' && line[i + 1] === '*') {
41
+ const end = line.indexOf('*/', i + 2);
42
+ if (end === -1) break;
43
+ i = end + 1;
44
+ continue;
45
+ }
46
+ out += ch;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ const DIRECTIVE = /riskdiff-ignore\b(.*)$/;
52
+
53
+ // Reads `riskdiff-ignore [rule-id, ...]` directives from added lines.
54
+ // Returns 'all', a Set of rule ids, or null when the hunk has no directive.
55
+ export function ignoredRules(addedLines, knownIds) {
56
+ let ids = null;
57
+ for (const line of addedLines) {
58
+ const m = line.match(DIRECTIVE);
59
+ if (!m) continue;
60
+ const named = [];
61
+ for (const token of m[1].split(/[\s,:;]+/).filter(Boolean)) {
62
+ if (!knownIds.has(token)) break;
63
+ named.push(token);
64
+ }
65
+ if (!named.length) return 'all';
66
+ ids ??= new Set();
67
+ for (const id of named) ids.add(id);
68
+ }
69
+ return ids;
70
+ }