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/LICENSE +21 -0
- package/README.md +526 -2
- package/bin/riskdiff.js +148 -0
- package/package.json +32 -4
- package/schema/riskdiff.schema.json +43 -0
- package/src/ai.js +124 -0
- package/src/analyze.js +27 -0
- package/src/config.js +122 -0
- package/src/deps.js +127 -0
- package/src/diff.js +72 -0
- package/src/git.js +90 -0
- package/src/hook.js +43 -0
- package/src/mcp.js +99 -0
- package/src/packages.js +153 -0
- package/src/popular.js +60 -0
- package/src/report.js +141 -0
- package/src/rules.js +244 -0
- package/src/score.js +90 -0
- package/src/source.js +70 -0
package/bin/riskdiff.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { fstatSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { analyze } from '../src/analyze.js';
|
|
5
|
+
import { formatText, formatMarkdown, formatJson, formatSarif, atOrAbove } from '../src/report.js';
|
|
6
|
+
import { buildRules } from '../src/config.js';
|
|
7
|
+
import { aiReview } from '../src/ai.js';
|
|
8
|
+
import { runHook } from '../src/hook.js';
|
|
9
|
+
import { serve } from '../src/mcp.js';
|
|
10
|
+
|
|
11
|
+
const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
12
|
+
|
|
13
|
+
const HELP = `riskdiff ${VERSION} — rank the hunks of a diff by how risky they are to merge
|
|
14
|
+
|
|
15
|
+
Usage
|
|
16
|
+
riskdiff Working tree, staged, and untracked changes vs HEAD
|
|
17
|
+
riskdiff --staged Staged changes only
|
|
18
|
+
riskdiff <git-diff-args> Any git diff range, e.g. main...HEAD
|
|
19
|
+
git diff | riskdiff Read a diff from stdin (or pass "-")
|
|
20
|
+
riskdiff hook Claude Code PostToolUse hook (reads hook JSON on stdin)
|
|
21
|
+
riskdiff mcp Run as an MCP server over stdio
|
|
22
|
+
|
|
23
|
+
Options
|
|
24
|
+
--json Machine-readable output
|
|
25
|
+
--md Markdown table (for PR comments)
|
|
26
|
+
--sarif SARIF 2.1.0 (for GitHub code scanning)
|
|
27
|
+
-o, --output <file> Write the report to a file instead of stdout
|
|
28
|
+
--code Show the changed lines under each hunk
|
|
29
|
+
--fail-on <level> Exit 1 if any hunk is at or above low|medium|high
|
|
30
|
+
--check-packages Look new npm/PyPI dependencies up in their registries
|
|
31
|
+
--ai Ask Claude for a second opinion on the riskiest hunks
|
|
32
|
+
(sends their changed lines to the Anthropic API;
|
|
33
|
+
needs ANTHROPIC_API_KEY, model via RISKDIFF_AI_MODEL)
|
|
34
|
+
--config <path> Config file (default: .riskdiff.json in the repo root)
|
|
35
|
+
--no-untracked Leave out untracked files
|
|
36
|
+
--no-color Disable colors
|
|
37
|
+
-h, --help Show help
|
|
38
|
+
-v, --version Show version`;
|
|
39
|
+
|
|
40
|
+
async function main() {
|
|
41
|
+
const sub = process.argv[2];
|
|
42
|
+
if (sub === 'hook') return hook();
|
|
43
|
+
if (sub === 'mcp') return serve({ version: VERSION });
|
|
44
|
+
|
|
45
|
+
let args;
|
|
46
|
+
try {
|
|
47
|
+
args = parseArgs({
|
|
48
|
+
allowPositionals: true,
|
|
49
|
+
options: {
|
|
50
|
+
staged: { type: 'boolean' },
|
|
51
|
+
json: { type: 'boolean' },
|
|
52
|
+
md: { type: 'boolean' },
|
|
53
|
+
sarif: { type: 'boolean' },
|
|
54
|
+
output: { type: 'string', short: 'o' },
|
|
55
|
+
code: { type: 'boolean' },
|
|
56
|
+
'fail-on': { type: 'string' },
|
|
57
|
+
config: { type: 'string' },
|
|
58
|
+
'check-packages': { type: 'boolean' },
|
|
59
|
+
ai: { type: 'boolean' },
|
|
60
|
+
'no-untracked': { type: 'boolean' },
|
|
61
|
+
'no-color': { type: 'boolean' },
|
|
62
|
+
help: { type: 'boolean', short: 'h' },
|
|
63
|
+
version: { type: 'boolean', short: 'v' },
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
} catch (err) {
|
|
67
|
+
return fail(`${err.message}\n\n${HELP}`);
|
|
68
|
+
}
|
|
69
|
+
const { values: opts, positionals } = args;
|
|
70
|
+
|
|
71
|
+
if (opts.help) return console.log(HELP);
|
|
72
|
+
if (opts.version) return console.log(VERSION);
|
|
73
|
+
if ([opts.json, opts.md, opts.sarif].filter(Boolean).length > 1) return fail('use only one of --json, --md, --sarif');
|
|
74
|
+
if (opts['fail-on'] && !['low', 'medium', 'high'].includes(opts['fail-on'])) {
|
|
75
|
+
return fail(`--fail-on must be low, medium, or high (got "${opts['fail-on']}")`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const fromStdin = positionals[0] === '-' || (!positionals.length && !opts.staged && stdinIsPiped());
|
|
79
|
+
let results, config, packageCheck;
|
|
80
|
+
try {
|
|
81
|
+
({ results, config, packageCheck } = await analyze({
|
|
82
|
+
diffText: fromStdin ? readFileSync(0, 'utf8') : undefined,
|
|
83
|
+
mode: opts.staged ? 'staged' : positionals.length ? 'range' : 'worktree',
|
|
84
|
+
args: positionals,
|
|
85
|
+
configPath: opts.config,
|
|
86
|
+
untracked: !opts['no-untracked'],
|
|
87
|
+
packages: opts['check-packages'],
|
|
88
|
+
}));
|
|
89
|
+
} catch (err) {
|
|
90
|
+
return fail(err.message);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (packageCheck?.failed) {
|
|
94
|
+
console.error(`riskdiff: could not reach the registry for ${packageCheck.failed} package${packageCheck.failed === 1 ? '' : 's'}; they were not checked`);
|
|
95
|
+
}
|
|
96
|
+
if (opts.ai) {
|
|
97
|
+
try {
|
|
98
|
+
await aiReview(results);
|
|
99
|
+
} catch (err) {
|
|
100
|
+
console.error(`riskdiff: AI review skipped: ${err.message}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const failOn = opts['fail-on'] ?? config.failOn;
|
|
104
|
+
const color = !opts.output && !opts['no-color'] && !process.env.NO_COLOR && process.stdout.isTTY;
|
|
105
|
+
let report;
|
|
106
|
+
if (opts.json) report = formatJson(results);
|
|
107
|
+
else if (opts.sarif) report = formatSarif(results, { version: VERSION, rules: buildRules(config) });
|
|
108
|
+
else if (opts.md) report = formatMarkdown(results);
|
|
109
|
+
else report = formatText(results, { color, code: opts.code });
|
|
110
|
+
|
|
111
|
+
if (opts.output) {
|
|
112
|
+
try {
|
|
113
|
+
writeFileSync(opts.output, `${report}\n`);
|
|
114
|
+
} catch (err) {
|
|
115
|
+
return fail(`cannot write ${opts.output}: ${err.message}`);
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
console.log(report);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (failOn && results.some((r) => r.score > 0 && atOrAbove(r.level, failOn))) process.exitCode = 1;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Never blocks or fails the edit: any problem is logged to stderr and the hook exits 0.
|
|
125
|
+
async function hook() {
|
|
126
|
+
try {
|
|
127
|
+
const out = await runHook(JSON.parse(readFileSync(0, 'utf8')));
|
|
128
|
+
if (out) console.log(JSON.stringify(out));
|
|
129
|
+
} catch (err) {
|
|
130
|
+
console.error(`riskdiff hook: ${err.message}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function stdinIsPiped() {
|
|
135
|
+
try {
|
|
136
|
+
const stat = fstatSync(0);
|
|
137
|
+
return stat.isFIFO() || stat.isFile();
|
|
138
|
+
} catch {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function fail(message) {
|
|
144
|
+
console.error(`riskdiff: ${message}`);
|
|
145
|
+
process.exitCode = 2;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
main();
|
package/package.json
CHANGED
|
@@ -1,6 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "riskdiff-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Rank the hunks of a git diff by how risky they are, so you review AI-written changes in the right order.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"riskdiff": "bin/riskdiff.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"schema"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "node --test"
|
|
16
|
+
},
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=18.11"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"git",
|
|
22
|
+
"diff",
|
|
23
|
+
"code-review",
|
|
24
|
+
"security",
|
|
25
|
+
"ai",
|
|
26
|
+
"claude-code",
|
|
27
|
+
"cli"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/zeitgeistz/riskdiff.git"
|
|
32
|
+
},
|
|
33
|
+
"license": "MIT"
|
|
34
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://raw.githubusercontent.com/zeitgeistz/riskdiff/main/schema/riskdiff.schema.json",
|
|
4
|
+
"title": "riskdiff config (.riskdiff.json)",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"properties": {
|
|
8
|
+
"$schema": { "type": "string" },
|
|
9
|
+
"ignore": {
|
|
10
|
+
"description": "Glob patterns for files to skip. A pattern without \"/\" matches the file name in any directory.",
|
|
11
|
+
"type": "array",
|
|
12
|
+
"items": { "type": "string" }
|
|
13
|
+
},
|
|
14
|
+
"rules": {
|
|
15
|
+
"description": "Disable a rule with false, or set its weight with a number.",
|
|
16
|
+
"type": "object",
|
|
17
|
+
"additionalProperties": {
|
|
18
|
+
"oneOf": [{ "const": false }, { "type": "integer", "minimum": 0 }]
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"customRules": {
|
|
22
|
+
"type": "array",
|
|
23
|
+
"items": {
|
|
24
|
+
"type": "object",
|
|
25
|
+
"additionalProperties": false,
|
|
26
|
+
"required": ["id", "weight", "reason"],
|
|
27
|
+
"properties": {
|
|
28
|
+
"id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9-]*$" },
|
|
29
|
+
"weight": { "type": "integer", "minimum": 0 },
|
|
30
|
+
"reason": { "type": "string", "minLength": 1 },
|
|
31
|
+
"path": { "type": "string", "description": "Regex matched against the file path" },
|
|
32
|
+
"added": { "type": "array", "items": { "type": "string" }, "description": "Regexes matched against added lines" },
|
|
33
|
+
"removed": { "type": "array", "items": { "type": "string" }, "description": "Regexes matched against removed lines" },
|
|
34
|
+
"flags": { "type": "string", "description": "Regex flags, e.g. \"i\"" },
|
|
35
|
+
"raw": { "type": "boolean", "description": "Match comments too (default: comments are stripped)" }
|
|
36
|
+
},
|
|
37
|
+
"oneOf": [{ "required": ["path"] }, { "required": ["added"] }, { "required": ["removed"] }]
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"failOn": { "enum": ["low", "medium", "high"] },
|
|
41
|
+
"checkPackages": { "type": "boolean", "description": "Look up new npm and PyPI dependencies in their registries" }
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/ai.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Optional second opinion from Claude on the riskiest hunks. Opt-in only (--ai): it sends
|
|
2
|
+
// the changed lines of up to MAX_HUNKS hunks to the Anthropic API. Plain fetch, no SDK,
|
|
3
|
+
// so riskdiff stays dependency-free.
|
|
4
|
+
const API_URL = 'https://api.anthropic.com/v1/messages';
|
|
5
|
+
export const DEFAULT_MODEL = 'claude-opus-5-5';
|
|
6
|
+
const MAX_HUNKS = 15;
|
|
7
|
+
const MAX_LINES = 40;
|
|
8
|
+
const VERDICTS = ['real', 'false-positive', 'unsure'];
|
|
9
|
+
|
|
10
|
+
const SYSTEM =
|
|
11
|
+
'You review code changes that a static risk scanner flagged. For each hunk, decide whether the ' +
|
|
12
|
+
'flagged risk is real, a false positive, or unclear from the lines shown. "real" means a reviewer ' +
|
|
13
|
+
'should look at it before merging. Give one short sentence explaining why, naming the specific line ' +
|
|
14
|
+
'or construct. Judge only what is shown; say "unsure" rather than guessing about code you cannot see.';
|
|
15
|
+
|
|
16
|
+
const SCHEMA = {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
verdicts: {
|
|
20
|
+
type: 'array',
|
|
21
|
+
items: {
|
|
22
|
+
type: 'object',
|
|
23
|
+
properties: {
|
|
24
|
+
hunk: { type: 'integer' },
|
|
25
|
+
verdict: { type: 'string', enum: VERDICTS },
|
|
26
|
+
note: { type: 'string' },
|
|
27
|
+
},
|
|
28
|
+
required: ['hunk', 'verdict', 'note'],
|
|
29
|
+
additionalProperties: false,
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
required: ['verdicts'],
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export function buildPrompt(hunks) {
|
|
38
|
+
const parts = hunks.map((r, i) => {
|
|
39
|
+
const lines = [
|
|
40
|
+
`<hunk id="${i + 1}" file="${r.file}" line="${r.line}" status="${r.status}" score="${r.score}">`,
|
|
41
|
+
'Findings:',
|
|
42
|
+
...r.findings.map((f) => `- [${f.id}] ${f.reason}`),
|
|
43
|
+
];
|
|
44
|
+
const removed = r.hunk.removed.slice(0, MAX_LINES);
|
|
45
|
+
const added = r.hunk.added.slice(0, MAX_LINES);
|
|
46
|
+
if (removed.length) lines.push('Removed lines:', ...removed.map((l) => `- ${l}`));
|
|
47
|
+
if (added.length) lines.push('Added lines:', ...added.map((l) => `+ ${l}`));
|
|
48
|
+
if (r.hunk.removed.length > MAX_LINES || r.hunk.added.length > MAX_LINES) lines.push('(hunk truncated)');
|
|
49
|
+
lines.push('</hunk>');
|
|
50
|
+
return lines.join('\n');
|
|
51
|
+
});
|
|
52
|
+
return `Review these ${hunks.length} flagged hunks and return one verdict per hunk id.\n\n${parts.join('\n\n')}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Adds `ai: {verdict, note}` to the riskiest results. Returns {reviewed, model}.
|
|
56
|
+
// Throws with a readable message on any API problem; callers treat that as a warning.
|
|
57
|
+
export async function aiReview(results, { apiKey = process.env.ANTHROPIC_API_KEY, model, fetch = globalThis.fetch, timeoutMs = 120000 } = {}) {
|
|
58
|
+
if (!apiKey) throw new Error('--ai needs ANTHROPIC_API_KEY to be set');
|
|
59
|
+
model ||= process.env.RISKDIFF_AI_MODEL || DEFAULT_MODEL;
|
|
60
|
+
const hunks = results.filter((r) => r.score > 0 && r.hunk).slice(0, MAX_HUNKS);
|
|
61
|
+
if (!hunks.length) return { reviewed: 0, model };
|
|
62
|
+
|
|
63
|
+
const body = {
|
|
64
|
+
model,
|
|
65
|
+
max_tokens: 16000,
|
|
66
|
+
system: SYSTEM,
|
|
67
|
+
messages: [{ role: 'user', content: buildPrompt(hunks) }],
|
|
68
|
+
output_config: { effort: 'low', format: { type: 'json_schema', schema: SCHEMA } },
|
|
69
|
+
fallbacks: 'default',
|
|
70
|
+
};
|
|
71
|
+
const res = await send(fetch, body, apiKey, timeoutMs);
|
|
72
|
+
|
|
73
|
+
if (res.stop_reason === 'refusal') throw new Error('the model declined to review this diff');
|
|
74
|
+
if (res.stop_reason === 'max_tokens') throw new Error('the AI review was cut off (max_tokens)');
|
|
75
|
+
const text = res.content?.find((b) => b.type === 'text')?.text;
|
|
76
|
+
let parsed;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(text);
|
|
79
|
+
} catch {
|
|
80
|
+
throw new Error('the AI review returned invalid JSON');
|
|
81
|
+
}
|
|
82
|
+
for (const v of parsed.verdicts ?? []) {
|
|
83
|
+
const r = hunks[v.hunk - 1];
|
|
84
|
+
if (r && VERDICTS.includes(v.verdict)) r.ai = { verdict: v.verdict, note: String(v.note ?? '').trim() };
|
|
85
|
+
}
|
|
86
|
+
return { reviewed: hunks.filter((r) => r.ai).length, model: res.model ?? model };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// POST with up to two retries on rate limits, overload, and server errors.
|
|
90
|
+
async function send(fetch, body, apiKey, timeoutMs) {
|
|
91
|
+
for (let attempt = 0; ; attempt++) {
|
|
92
|
+
let res;
|
|
93
|
+
try {
|
|
94
|
+
res = await fetch(API_URL, {
|
|
95
|
+
method: 'POST',
|
|
96
|
+
headers: {
|
|
97
|
+
'content-type': 'application/json',
|
|
98
|
+
'x-api-key': apiKey,
|
|
99
|
+
'anthropic-version': '2023-06-01',
|
|
100
|
+
'anthropic-beta': 'server-side-fallback-2026-07-01',
|
|
101
|
+
},
|
|
102
|
+
body: JSON.stringify(body),
|
|
103
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
104
|
+
});
|
|
105
|
+
} catch (err) {
|
|
106
|
+
if (attempt < 2) continue;
|
|
107
|
+
throw new Error(`could not reach the Anthropic API: ${err.message}`);
|
|
108
|
+
}
|
|
109
|
+
if (res.ok) return res.json();
|
|
110
|
+
|
|
111
|
+
const retryable = res.status === 429 || res.status >= 500;
|
|
112
|
+
if (retryable && attempt < 2) {
|
|
113
|
+
const wait = Number(res.headers.get('retry-after'));
|
|
114
|
+
await new Promise((r) => setTimeout(r, Number.isFinite(wait) && wait > 0 ? Math.min(wait, 30) * 1000 : 1000 * 2 ** attempt));
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
let detail = '';
|
|
118
|
+
try {
|
|
119
|
+
detail = (await res.json())?.error?.message ?? '';
|
|
120
|
+
} catch {}
|
|
121
|
+
const hint = res.status === 401 ? ' (check ANTHROPIC_API_KEY)' : '';
|
|
122
|
+
throw new Error(`Anthropic API error ${res.status}${hint}${detail ? `: ${detail}` : ''}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
package/src/analyze.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// The full pipeline shared by the CLI, the Claude Code hook, and the MCP server.
|
|
2
|
+
import { parseDiff } from './diff.js';
|
|
3
|
+
import { scoreFiles } from './score.js';
|
|
4
|
+
import { findConfig, loadConfig, buildRules, pathFilter } from './config.js';
|
|
5
|
+
import { readGitDiff, newSideReader, repoRoot } from './git.js';
|
|
6
|
+
import { checkPackages } from './packages.js';
|
|
7
|
+
|
|
8
|
+
// Options:
|
|
9
|
+
// diffText diff to analyze; when omitted it is read from git using mode/args
|
|
10
|
+
// mode 'worktree' | 'staged' | 'range'
|
|
11
|
+
// args git diff arguments for 'range' (and extra args for 'staged')
|
|
12
|
+
// cwd directory to run git in
|
|
13
|
+
// configPath explicit config file; otherwise .riskdiff.json in the repo root or cwd
|
|
14
|
+
// untracked include untracked files in 'worktree' mode (default true)
|
|
15
|
+
// packages look new npm/PyPI dependencies up in their registries (default: config.checkPackages)
|
|
16
|
+
// fetch fetch implementation for the registry lookups (tests pass a fake)
|
|
17
|
+
export async function analyze({ diffText, mode = 'worktree', args = [], cwd = process.cwd(), configPath, untracked = true, packages, fetch } = {}) {
|
|
18
|
+
const root = repoRoot(cwd);
|
|
19
|
+
const config = loadConfig(configPath ?? findConfig([root, cwd]));
|
|
20
|
+
const text = diffText ?? readGitDiff({ mode, args, untracked, cwd });
|
|
21
|
+
const readNew = diffText === undefined ? newSideReader({ mode, args, cwd }) : () => null;
|
|
22
|
+
|
|
23
|
+
const rules = buildRules(config);
|
|
24
|
+
const results = scoreFiles(parseDiff(text), { rules, include: pathFilter(config.ignore), readNew });
|
|
25
|
+
const packageCheck = (packages ?? config.checkPackages) ? await checkPackages(results, { rules, fetch }) : null;
|
|
26
|
+
return { results, config, packageCheck };
|
|
27
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Loads .riskdiff.json and turns it into the rule list and path filter used for scoring.
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { builtinRules } from './rules.js';
|
|
5
|
+
|
|
6
|
+
export const CONFIG_FILE = '.riskdiff.json';
|
|
7
|
+
const KEYS = new Set(['$schema', 'ignore', 'rules', 'customRules', 'failOn', 'checkPackages']);
|
|
8
|
+
const RULE_KEYS = new Set(['id', 'weight', 'reason', 'path', 'added', 'removed', 'flags', 'raw']);
|
|
9
|
+
const LEVELS = ['low', 'medium', 'high'];
|
|
10
|
+
|
|
11
|
+
export function findConfig(dirs) {
|
|
12
|
+
for (const dir of dirs) {
|
|
13
|
+
if (!dir) continue;
|
|
14
|
+
const path = join(dir, CONFIG_FILE);
|
|
15
|
+
if (existsSync(path)) return path;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function loadConfig(path) {
|
|
21
|
+
if (!path) return {};
|
|
22
|
+
let data;
|
|
23
|
+
try {
|
|
24
|
+
data = JSON.parse(readFileSync(path, 'utf8'));
|
|
25
|
+
} catch (err) {
|
|
26
|
+
throw new Error(`cannot read config ${path}: ${err.message}`);
|
|
27
|
+
}
|
|
28
|
+
return validateConfig(data, path);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function validateConfig(data, source = 'config') {
|
|
32
|
+
const bad = (msg) => {
|
|
33
|
+
throw new Error(`${source}: ${msg}`);
|
|
34
|
+
};
|
|
35
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) bad('must be a JSON object');
|
|
36
|
+
for (const key of Object.keys(data)) if (!KEYS.has(key)) bad(`unknown key "${key}"`);
|
|
37
|
+
|
|
38
|
+
if (data.ignore !== undefined && !isStringArray(data.ignore)) bad('"ignore" must be an array of glob strings');
|
|
39
|
+
if (data.failOn !== undefined && !LEVELS.includes(data.failOn)) bad('"failOn" must be low, medium, or high');
|
|
40
|
+
if (data.checkPackages !== undefined && typeof data.checkPackages !== 'boolean') bad('"checkPackages" must be true or false');
|
|
41
|
+
|
|
42
|
+
const customIds = new Set();
|
|
43
|
+
for (const [i, rule] of (data.customRules ?? []).entries()) {
|
|
44
|
+
const where = `customRules[${i}]`;
|
|
45
|
+
if (!rule || typeof rule !== 'object') bad(`${where} must be an object`);
|
|
46
|
+
for (const key of Object.keys(rule)) if (!RULE_KEYS.has(key)) bad(`${where} has unknown key "${key}"`);
|
|
47
|
+
if (typeof rule.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(rule.id)) bad(`${where}.id must be lowercase letters, digits, and dashes`);
|
|
48
|
+
if (builtinRules.some((r) => r.id === rule.id) || customIds.has(rule.id)) bad(`${where}.id "${rule.id}" is already used`);
|
|
49
|
+
customIds.add(rule.id);
|
|
50
|
+
if (!Number.isInteger(rule.weight) || rule.weight < 0) bad(`${where}.weight must be a non-negative integer`);
|
|
51
|
+
if (typeof rule.reason !== 'string' || !rule.reason) bad(`${where}.reason is required`);
|
|
52
|
+
const kinds = ['path', 'added', 'removed'].filter((k) => rule[k] !== undefined);
|
|
53
|
+
if (kinds.length !== 1) bad(`${where} needs exactly one of "path", "added", or "removed"`);
|
|
54
|
+
if (rule.path !== undefined && typeof rule.path !== 'string') bad(`${where}.path must be a regex string`);
|
|
55
|
+
for (const k of ['added', 'removed']) {
|
|
56
|
+
if (rule[k] !== undefined && !isStringArray(rule[k])) bad(`${where}.${k} must be an array of regex strings`);
|
|
57
|
+
}
|
|
58
|
+
for (const pattern of [rule.path, ...(rule.added ?? []), ...(rule.removed ?? [])].filter(Boolean)) {
|
|
59
|
+
try {
|
|
60
|
+
new RegExp(pattern, rule.flags ?? '');
|
|
61
|
+
} catch (err) {
|
|
62
|
+
bad(`${where}: invalid regex ${JSON.stringify(pattern)}: ${err.message}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const known = new Set([...builtinRules.map((r) => r.id), ...customIds]);
|
|
68
|
+
if (data.rules !== undefined) {
|
|
69
|
+
if (!data.rules || typeof data.rules !== 'object' || Array.isArray(data.rules)) bad('"rules" must be an object');
|
|
70
|
+
for (const [id, value] of Object.entries(data.rules)) {
|
|
71
|
+
if (!known.has(id)) bad(`"rules" has unknown rule id "${id}"`);
|
|
72
|
+
if (value !== false && !(Number.isInteger(value) && value >= 0)) bad(`"rules.${id}" must be false or a non-negative integer weight`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return data;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Built-in rules plus custom rules, with weights overridden and disabled rules removed.
|
|
79
|
+
export function buildRules(config = {}) {
|
|
80
|
+
const custom = (config.customRules ?? []).map((r) => ({
|
|
81
|
+
id: r.id,
|
|
82
|
+
weight: r.weight,
|
|
83
|
+
reason: r.reason,
|
|
84
|
+
raw: Boolean(r.raw),
|
|
85
|
+
path: r.path ? new RegExp(r.path, r.flags ?? '') : undefined,
|
|
86
|
+
added: r.added?.map((p) => new RegExp(p, r.flags ?? '')),
|
|
87
|
+
removed: r.removed?.map((p) => new RegExp(p, r.flags ?? '')),
|
|
88
|
+
}));
|
|
89
|
+
const overrides = config.rules ?? {};
|
|
90
|
+
return [...builtinRules, ...custom]
|
|
91
|
+
.filter((r) => overrides[r.id] !== false)
|
|
92
|
+
.map((r) => (Number.isInteger(overrides[r.id]) ? { ...r, weight: overrides[r.id] } : r));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function pathFilter(globs = []) {
|
|
96
|
+
const regexes = globs.map(globToRegExp);
|
|
97
|
+
return (path) => !regexes.some((re) => re.test(path));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Glob syntax: `**` any number of directories, `*` anything but "/", `?` one character.
|
|
101
|
+
// A pattern with no "/" matches the file name in any directory, like .gitignore.
|
|
102
|
+
export function globToRegExp(glob) {
|
|
103
|
+
let pattern = glob.replace(/^\.\//, '');
|
|
104
|
+
if (!pattern.includes('/')) pattern = `**/${pattern}`;
|
|
105
|
+
if (pattern.endsWith('/')) pattern += '**';
|
|
106
|
+
let re = '';
|
|
107
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
108
|
+
const ch = pattern[i];
|
|
109
|
+
if (ch === '*' && pattern[i + 1] === '*') {
|
|
110
|
+
const slash = pattern[i + 2] === '/';
|
|
111
|
+
re += slash ? '(?:.*/)?' : '.*';
|
|
112
|
+
i += slash ? 2 : 1;
|
|
113
|
+
} else if (ch === '*') re += '[^/]*';
|
|
114
|
+
else if (ch === '?') re += '[^/]';
|
|
115
|
+
else re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
116
|
+
}
|
|
117
|
+
return new RegExp(`^${re}$`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isStringArray(v) {
|
|
121
|
+
return Array.isArray(v) && v.every((s) => typeof s === 'string');
|
|
122
|
+
}
|
package/src/deps.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// Finds the dependencies a manifest hunk adds or changes.
|
|
2
|
+
// Returns [{ name, ecosystem }]; ecosystem is 'npm', 'pypi', or another registry name.
|
|
3
|
+
|
|
4
|
+
const NPM_META = new Set([
|
|
5
|
+
'name', 'version', 'description', 'main', 'module', 'browser', 'types', 'typings', 'type', 'license',
|
|
6
|
+
'author', 'homepage', 'private', 'packageManager', 'node', 'npm', 'yarn', 'pnpm', 'url', 'email',
|
|
7
|
+
]);
|
|
8
|
+
const TOML_META = new Set([
|
|
9
|
+
'name', 'version', 'description', 'readme', 'license', 'authors', 'maintainers', 'keywords', 'homepage',
|
|
10
|
+
'repository', 'documentation', 'edition', 'rust-version', 'python', 'requires-python', 'build-backend',
|
|
11
|
+
'requires', 'packages', 'include', 'exclude', 'url', 'verify_ssl', 'python_version', 'publish', 'resolver',
|
|
12
|
+
]);
|
|
13
|
+
const NPM_DEP_SECTIONS = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
|
|
14
|
+
|
|
15
|
+
export function addedDeps(path, addedLines, newContent) {
|
|
16
|
+
const base = path.split('/').pop();
|
|
17
|
+
if (base === 'package.json') return npmDeps(addedLines, newContent);
|
|
18
|
+
if (base === 'composer.json') return jsonKeyDeps(addedLines, 'packagist', (n) => n.includes('/'));
|
|
19
|
+
if (/^requirements[^/]*\.txt$/.test(base)) return requirementsDeps(addedLines);
|
|
20
|
+
if (base === 'pyproject.toml' || base === 'Pipfile') return pythonTomlDeps(addedLines);
|
|
21
|
+
if (base === 'Cargo.toml') return tomlKeyDeps(addedLines, 'crates');
|
|
22
|
+
if (base === 'go.mod') return goDeps(addedLines);
|
|
23
|
+
if (base === 'Gemfile') return gemDeps(addedLines);
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Every dependency declared in a manifest's full content.
|
|
28
|
+
export function allDeps(path, content) {
|
|
29
|
+
if (!content) return [];
|
|
30
|
+
if (path.split('/').pop() === 'package.json') {
|
|
31
|
+
try {
|
|
32
|
+
const pkg = JSON.parse(content);
|
|
33
|
+
return [...new Set(NPM_DEP_SECTIONS.flatMap((s) => Object.keys(pkg[s] ?? {})))].map((name) => ({ name, ecosystem: 'npm' }));
|
|
34
|
+
} catch {
|
|
35
|
+
// Fall through to the line-based reading.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return addedDeps(path, content.split(/\r?\n/), content);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function npmDeps(lines, content) {
|
|
42
|
+
let declared = null;
|
|
43
|
+
if (content) {
|
|
44
|
+
try {
|
|
45
|
+
const pkg = JSON.parse(content);
|
|
46
|
+
declared = new Set(NPM_DEP_SECTIONS.flatMap((s) => Object.keys(pkg[s] ?? {})));
|
|
47
|
+
} catch {
|
|
48
|
+
// Unparseable package.json: fall back to the line heuristic.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return jsonKeyDeps(lines, 'npm', (name, spec) =>
|
|
52
|
+
declared ? declared.has(name) : !NPM_META.has(name) && looksLikeNpmSpec(spec),
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function jsonKeyDeps(lines, ecosystem, accept) {
|
|
57
|
+
const out = [];
|
|
58
|
+
for (const line of lines) {
|
|
59
|
+
const m = line.trim().match(/^"([^"]+)"\s*:\s*"([^"]*)",?$/);
|
|
60
|
+
if (m && accept(m[1], m[2])) out.push({ name: m[1], ecosystem });
|
|
61
|
+
}
|
|
62
|
+
return unique(out);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function looksLikeNpmSpec(spec) {
|
|
66
|
+
return /^([~^<>=]*\s*\d|\*$|latest$|next$|npm:|git|https?:|file:|link:|workspace:|[\w-]+\/[\w.-]+(#.*)?$)/.test(spec) && !/\s{2,}|\s(?![<>=|\d])/.test(spec);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function requirementsDeps(lines) {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const line of lines) {
|
|
72
|
+
const t = line.trim();
|
|
73
|
+
if (!t || t.startsWith('#') || t.startsWith('-')) continue;
|
|
74
|
+
const m = t.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\])?\s*(==|>=|<=|~=|!=|===|>|<|;|@|$)/);
|
|
75
|
+
if (m) out.push({ name: m[1], ecosystem: 'pypi' });
|
|
76
|
+
}
|
|
77
|
+
return unique(out);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function pythonTomlDeps(lines) {
|
|
81
|
+
const out = [];
|
|
82
|
+
for (const line of lines) {
|
|
83
|
+
const t = line.trim();
|
|
84
|
+
// PEP 621: "requests>=2.0",
|
|
85
|
+
const pep = t.match(/^["']([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\])?\s*([<>=!~;@][^"']*)?["'],?$/);
|
|
86
|
+
if (pep) {
|
|
87
|
+
out.push({ name: pep[1], ecosystem: 'pypi' });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
// Poetry / Pipfile: requests = "^2.0" or requests = { version = "^2.0" }
|
|
91
|
+
const kv = t.match(/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*=\s*(["{])/);
|
|
92
|
+
if (kv && !TOML_META.has(kv[1])) out.push({ name: kv[1], ecosystem: 'pypi' });
|
|
93
|
+
}
|
|
94
|
+
return unique(out);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function tomlKeyDeps(lines, ecosystem) {
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const line of lines) {
|
|
100
|
+
const m = line.trim().match(/^([A-Za-z0-9][A-Za-z0-9_-]*)\s*=\s*(["{])/);
|
|
101
|
+
if (m && !TOML_META.has(m[1])) out.push({ name: m[1], ecosystem });
|
|
102
|
+
}
|
|
103
|
+
return unique(out);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function goDeps(lines) {
|
|
107
|
+
const out = [];
|
|
108
|
+
for (const line of lines) {
|
|
109
|
+
const m = line.trim().match(/^(?:require\s+)?([\w.-]+\.[a-z]{2,}\/\S+)\s+v\d/);
|
|
110
|
+
if (m) out.push({ name: m[1], ecosystem: 'go' });
|
|
111
|
+
}
|
|
112
|
+
return unique(out);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function gemDeps(lines) {
|
|
116
|
+
const out = [];
|
|
117
|
+
for (const line of lines) {
|
|
118
|
+
const m = line.trim().match(/^gem\s+["']([^"']+)["']/);
|
|
119
|
+
if (m) out.push({ name: m[1], ecosystem: 'rubygems' });
|
|
120
|
+
}
|
|
121
|
+
return unique(out);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function unique(deps) {
|
|
125
|
+
const seen = new Set();
|
|
126
|
+
return deps.filter((d) => !seen.has(d.name) && seen.add(d.name));
|
|
127
|
+
}
|