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/diff.js ADDED
@@ -0,0 +1,72 @@
1
+ // Parses unified diff text (as produced by `git diff`) into files and hunks.
2
+
3
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/;
4
+
5
+ export function parseDiff(text) {
6
+ const files = [];
7
+ let file = null;
8
+ let hunk = null;
9
+ let newLine = 0;
10
+
11
+ const startFile = (oldPath, newPath) => {
12
+ file = { oldPath, newPath, path: newPath, status: 'modified', binary: false, hunks: [] };
13
+ files.push(file);
14
+ hunk = null;
15
+ };
16
+
17
+ for (const raw of text.split(/\r?\n/)) {
18
+ if (raw.startsWith('diff --git ')) {
19
+ const m = raw.match(/^diff --git a\/(.+) b\/(.+)$/);
20
+ startFile(m ? m[1] : null, m ? m[2] : null);
21
+ continue;
22
+ }
23
+ if (!file) continue;
24
+
25
+ if (!hunk) {
26
+ if (raw.startsWith('new file mode')) file.status = 'added';
27
+ else if (raw.startsWith('deleted file mode')) file.status = 'deleted';
28
+ else if (raw.startsWith('rename from ')) { file.oldPath = raw.slice(12); file.status = 'renamed'; }
29
+ else if (raw.startsWith('rename to ')) file.newPath = raw.slice(10);
30
+ else if (raw.startsWith('Binary files ')) file.binary = true;
31
+ else if (raw.startsWith('--- ')) file.oldPath = stripPrefix(raw.slice(4)) ?? file.oldPath;
32
+ else if (raw.startsWith('+++ ')) file.newPath = stripPrefix(raw.slice(4)) ?? file.newPath;
33
+ file.path = file.status === 'deleted' ? file.oldPath : file.newPath;
34
+ }
35
+
36
+ const header = raw.match(HUNK_HEADER);
37
+ if (header) {
38
+ newLine = Number(header[3]);
39
+ hunk = {
40
+ header: raw,
41
+ context: header[5].trim(),
42
+ oldStart: Number(header[1]),
43
+ newStart: newLine,
44
+ line: null,
45
+ added: [],
46
+ removed: [],
47
+ };
48
+ file.hunks.push(hunk);
49
+ continue;
50
+ }
51
+ if (!hunk) continue;
52
+
53
+ if (raw.startsWith('+')) {
54
+ hunk.added.push(raw.slice(1));
55
+ hunk.line ??= newLine;
56
+ newLine++;
57
+ } else if (raw.startsWith('-')) {
58
+ hunk.removed.push(raw.slice(1));
59
+ hunk.line ??= newLine;
60
+ } else if (raw.startsWith(' ')) {
61
+ newLine++;
62
+ }
63
+ }
64
+
65
+ for (const f of files) for (const h of f.hunks) h.line ??= h.newStart;
66
+ return files;
67
+ }
68
+
69
+ function stripPrefix(p) {
70
+ if (p === '/dev/null') return null;
71
+ return p.replace(/^[ab]\//, '');
72
+ }
package/src/git.js ADDED
@@ -0,0 +1,90 @@
1
+ // Everything that talks to git: building the diff text and reading the new side of files.
2
+ import { execFileSync } from 'node:child_process';
3
+ import { readFileSync, statSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+
6
+ const MAX_UNTRACKED_BYTES = 1024 * 1024;
7
+
8
+ export function git(args, cwd) {
9
+ try {
10
+ return execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
11
+ } catch (err) {
12
+ const msg = err.stderr?.toString().trim() || err.message;
13
+ throw new Error(`git ${args.join(' ')} failed: ${msg}`);
14
+ }
15
+ }
16
+
17
+ export function repoRoot(cwd) {
18
+ try {
19
+ return git(['rev-parse', '--show-toplevel'], cwd).trim();
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ // mode: 'worktree' (vs HEAD, plus untracked files), 'staged', or 'range' (git diff args).
26
+ export function readGitDiff({ mode, args = [], untracked = true, cwd }) {
27
+ const base = ['diff', '--no-color', '--no-ext-diff', '-M'];
28
+ if (mode === 'staged') return git([...base, '--cached', ...args], cwd);
29
+ if (mode === 'range') return git([...base, ...args], cwd);
30
+
31
+ let text;
32
+ try {
33
+ text = git([...base, 'HEAD'], cwd);
34
+ } catch {
35
+ // No commits yet: fall back to staged + unstaged.
36
+ text = git([...base, '--cached'], cwd) + git(base, cwd);
37
+ }
38
+ return untracked ? text + untrackedDiff(cwd) : text;
39
+ }
40
+
41
+ // Builds "new file" diffs for untracked files, skipping ignored, binary, and huge files.
42
+ export function untrackedDiff(cwd) {
43
+ const root = repoRoot(cwd);
44
+ if (!root) return '';
45
+ const paths = git(['ls-files', '--others', '--exclude-standard', '-z'], root).split('\0').filter(Boolean);
46
+ let out = '';
47
+ for (const path of paths) {
48
+ const full = join(root, path);
49
+ let buf;
50
+ try {
51
+ if (statSync(full).size > MAX_UNTRACKED_BYTES) continue;
52
+ buf = readFileSync(full);
53
+ } catch {
54
+ continue;
55
+ }
56
+ if (buf.includes(0)) continue;
57
+ const lines = buf.toString('utf8').split(/\r?\n/);
58
+ if (lines.at(-1) === '') lines.pop();
59
+ out += `diff --git a/${path} b/${path}\nnew file mode 100644\n--- /dev/null\n+++ b/${path}\n`;
60
+ if (lines.length) out += `@@ -0,0 +1,${lines.length} @@\n` + lines.map((l) => '+' + l).join('\n') + '\n';
61
+ }
62
+ return out;
63
+ }
64
+
65
+ // Returns (path) => content of the file on the "new" side of the diff, or null.
66
+ export function newSideReader({ mode, args = [], cwd }) {
67
+ const root = repoRoot(cwd);
68
+ if (!root) return () => null;
69
+ let rev = null; // null means the working tree
70
+ if (mode === 'staged') rev = '';
71
+ else if (mode === 'range') rev = rightSide(args);
72
+
73
+ return (path) => {
74
+ try {
75
+ if (rev === null) return readFileSync(join(root, path), 'utf8');
76
+ return git(['show', `${rev}:${path}`], root);
77
+ } catch {
78
+ return null;
79
+ }
80
+ };
81
+ }
82
+
83
+ // The revision on the right of a diff range, or null when it is the working tree.
84
+ function rightSide(args) {
85
+ const sep = args.indexOf('--');
86
+ const list = (sep === -1 ? args : args.slice(0, sep)).filter((a) => !a.startsWith('-'));
87
+ if (list.length === 1 && list[0].includes('..')) return list[0].split(/\.\.\.?/)[1] || 'HEAD';
88
+ if (list.length >= 2) return list[1];
89
+ return null;
90
+ }
package/src/hook.js ADDED
@@ -0,0 +1,43 @@
1
+ // Claude Code PostToolUse hook: after Claude edits a file, scan that file's uncommitted
2
+ // changes and hand any medium or high risk hunks back to Claude as extra context.
3
+ import { realpathSync } from 'node:fs';
4
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { analyze } from './analyze.js';
6
+ import { formatText } from './report.js';
7
+ import { repoRoot } from './git.js';
8
+
9
+ const MAX_CONTEXT = 9000; // Claude Code caps additionalContext at 10k characters
10
+
11
+ // Takes the hook's stdin JSON; returns the JSON to print, or null to stay silent.
12
+ export async function runHook(input) {
13
+ const filePath = input?.tool_input?.file_path;
14
+ if (typeof filePath !== 'string' || !filePath) return null;
15
+ const cwd = input.cwd || process.cwd();
16
+ const root = repoRoot(cwd);
17
+ if (!root) return null;
18
+
19
+ // realpath on both sides: on Windows the hook's path may be a short 8.3 name while git
20
+ // reports the long one, and symlinked directories differ the same way elsewhere.
21
+ const abs = isAbsolute(filePath) ? filePath : resolve(cwd, filePath);
22
+ const rel = relative(real(root), real(abs)).split(sep).join('/');
23
+ if (!rel || rel.startsWith('../')) return null;
24
+
25
+ const { results } = await analyze({ mode: 'worktree', cwd: root });
26
+ const risky = results.filter((r) => r.file === rel && (r.level === 'high' || r.level === 'medium'));
27
+ if (!risky.length) return null;
28
+
29
+ let text =
30
+ `riskdiff flagged the uncommitted changes in ${rel}. ` +
31
+ 'Check each finding below: fix it if it is a real problem, or tell the user why it is safe.\n\n' +
32
+ formatText(risky, { code: true });
33
+ if (text.length > MAX_CONTEXT) text = text.slice(0, MAX_CONTEXT) + '\n… (truncated; run riskdiff for the full report)';
34
+ return { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: text } };
35
+ }
36
+
37
+ function real(path) {
38
+ try {
39
+ return realpathSync.native(path);
40
+ } catch {
41
+ return resolve(path);
42
+ }
43
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,99 @@
1
+ // Minimal MCP server over stdio (newline-delimited JSON-RPC 2.0). Logs go to stderr.
2
+ import { createInterface } from 'node:readline';
3
+ import { analyze } from './analyze.js';
4
+ import { atOrAbove, summarize } from './report.js';
5
+
6
+ const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
7
+
8
+ const TOOLS = [
9
+ {
10
+ name: 'riskdiff_scan',
11
+ description:
12
+ 'Score every hunk of a git diff by merge risk (secrets, removed auth checks, dangerous exec, SQL, ' +
13
+ 'weakened tests, risky dependencies, sensitive paths) and return them riskiest first as JSON. ' +
14
+ 'With no range it scans uncommitted changes, including untracked files.',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ cwd: { type: 'string', description: 'Directory inside the git repository to scan. Defaults to the server working directory.' },
19
+ range: { type: 'string', description: 'git diff arguments, e.g. "main...HEAD" or "HEAD~3 -- src". Omit for uncommitted changes.' },
20
+ staged: { type: 'boolean', description: 'Scan staged changes only.' },
21
+ checkPackages: { type: 'boolean', description: 'Look new npm/PyPI dependencies up in their registries (sends package names only).' },
22
+ minLevel: { type: 'string', enum: ['low', 'medium', 'high'], description: 'Only return hunks at or above this level. Default: low.' },
23
+ },
24
+ additionalProperties: false,
25
+ },
26
+ },
27
+ ];
28
+
29
+ export async function callTool(name, args = {}) {
30
+ if (name !== 'riskdiff_scan') throw Object.assign(new Error(`unknown tool: ${name}`), { code: -32602 });
31
+ const range = typeof args.range === 'string' ? args.range.trim().split(/\s+/).filter(Boolean) : [];
32
+ const { results, packageCheck } = await analyze({
33
+ cwd: args.cwd || process.cwd(),
34
+ mode: args.staged ? 'staged' : range.length ? 'range' : 'worktree',
35
+ args: range,
36
+ packages: args.checkPackages,
37
+ });
38
+ const min = args.minLevel || 'low';
39
+ const report = {
40
+ summary: summarize(results),
41
+ hunks: results.filter((r) => r.score > 0 && atOrAbove(r.level, min)).map(({ hunk, ...rest }) => rest),
42
+ };
43
+ if (packageCheck?.failed) report.warning = `could not reach the registry for ${packageCheck.failed} package(s)`;
44
+ return JSON.stringify(report, null, 2);
45
+ }
46
+
47
+ export async function handle(msg, serverInfo) {
48
+ const { id, method, params } = msg;
49
+ if (id === undefined || id === null) return null; // notifications get no reply
50
+ const reply = (result) => ({ jsonrpc: '2.0', id, result });
51
+ const error = (code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
52
+
53
+ switch (method) {
54
+ case 'initialize': {
55
+ const asked = params?.protocolVersion;
56
+ return reply({
57
+ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
58
+ capabilities: { tools: {} },
59
+ serverInfo,
60
+ });
61
+ }
62
+ case 'ping':
63
+ return reply({});
64
+ case 'tools/list':
65
+ return reply({ tools: TOOLS });
66
+ case 'tools/call':
67
+ try {
68
+ const text = await callTool(params?.name, params?.arguments);
69
+ return reply({ content: [{ type: 'text', text }], isError: false });
70
+ } catch (err) {
71
+ if (err.code === -32602) return error(-32602, err.message);
72
+ return reply({ content: [{ type: 'text', text: `riskdiff: ${err.message}` }], isError: true });
73
+ }
74
+ default:
75
+ return error(-32601, `method not found: ${method}`);
76
+ }
77
+ }
78
+
79
+ export function serve({ version, input = process.stdin, output = process.stdout } = {}) {
80
+ const serverInfo = { name: 'riskdiff', version };
81
+ const rl = createInterface({ input, crlfDelay: Infinity });
82
+ rl.on('line', async (line) => {
83
+ if (!line.trim()) return;
84
+ let msg;
85
+ try {
86
+ msg = JSON.parse(line);
87
+ } catch {
88
+ output.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }) + '\n');
89
+ return;
90
+ }
91
+ try {
92
+ const res = await handle(msg, serverInfo);
93
+ if (res) output.write(JSON.stringify(res) + '\n');
94
+ } catch (err) {
95
+ console.error(`riskdiff mcp: ${err.stack || err.message}`);
96
+ }
97
+ });
98
+ return new Promise((done) => rl.on('close', done));
99
+ }
@@ -0,0 +1,153 @@
1
+ // Checks for new dependencies: look-alike names and duplicate libraries (offline),
2
+ // plus an opt-in registry lookup for packages that don't exist, are brand new, or are barely used.
3
+ import { POPULAR, SAME_JOB } from './popular.js';
4
+ import { finalize, sortResults } from './score.js';
5
+
6
+ const DAY = 24 * 60 * 60 * 1000;
7
+ const NEW_PACKAGE_DAYS = 30;
8
+ const LOW_WEEKLY_DOWNLOADS = 500;
9
+ const POPULAR_WEEKLY_DOWNLOADS = 50_000;
10
+
11
+ export const normalize = (name, ecosystem) =>
12
+ ecosystem === 'pypi' ? name.toLowerCase().replace(/[-_.]+/g, '-') : name.toLowerCase();
13
+
14
+ const popularSets = Object.fromEntries(
15
+ Object.entries(POPULAR).map(([eco, names]) => [eco, new Set(names.map((n) => normalize(n, eco)))]),
16
+ );
17
+
18
+ // The popular package this name looks like, or null. Popular names never match themselves.
19
+ export function lookalike({ name, ecosystem }) {
20
+ const popular = popularSets[ecosystem];
21
+ if (!popular) return null;
22
+ const n = normalize(name, ecosystem);
23
+ if (popular.has(n) || n.length < 5) return null;
24
+ const limit = n.length >= 8 ? 2 : 1;
25
+ for (const p of POPULAR[ecosystem]) {
26
+ const target = normalize(p, ecosystem);
27
+ if (Math.abs(target.length - n.length) <= limit && editDistance(n, target) <= limit) return p;
28
+ }
29
+ return null;
30
+ }
31
+
32
+ // Other libraries already in the project that do the same job as `dep`, or null.
33
+ export function sameJob(dep, projectDeps) {
34
+ const n = normalize(dep.name, dep.ecosystem);
35
+ for (const group of SAME_JOB) {
36
+ const members = (group[dep.ecosystem] ?? []).map((m) => normalize(m, dep.ecosystem));
37
+ if (!members.includes(n)) continue;
38
+ const others = projectDeps
39
+ .filter((d) => d.ecosystem === dep.ecosystem)
40
+ .map((d) => normalize(d.name, d.ecosystem))
41
+ .filter((d) => d !== n && members.includes(d));
42
+ if (others.length) return { job: group.job, others: [...new Set(others)] };
43
+ }
44
+ return null;
45
+ }
46
+
47
+ // Optimal string alignment distance (Levenshtein plus adjacent swaps).
48
+ export function editDistance(a, b) {
49
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
50
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
51
+ for (let i = 1; i <= a.length; i++) {
52
+ for (let j = 1; j <= b.length; j++) {
53
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
54
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
55
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
56
+ }
57
+ }
58
+ return d[a.length][b.length];
59
+ }
60
+
61
+ // Looks up every npm and PyPI dependency in the results, adds findings, and re-sorts.
62
+ // Returns { checked, failed } so callers can warn when the network was unavailable.
63
+ export async function checkPackages(results, { fetch = globalThis.fetch, now = Date.now(), timeoutMs = 8000, rules } = {}) {
64
+ const enabled = (id) => !rules || rules.some((r) => r.id === id);
65
+ const weightOf = (id, fallback) => rules?.find((r) => r.id === id)?.weight ?? fallback;
66
+ const unique = new Map();
67
+ for (const r of results) for (const d of r.deps ?? []) if (d.ecosystem === 'npm' || d.ecosystem === 'pypi') unique.set(`${d.ecosystem}:${d.name}`, d);
68
+
69
+ const lookups = new Map();
70
+ let failed = 0;
71
+ await pool([...unique.entries()], 8, async ([key, dep]) => {
72
+ try {
73
+ lookups.set(key, dep.ecosystem === 'npm' ? await npmInfo(dep.name, fetch, timeoutMs) : await pypiInfo(dep.name, fetch, timeoutMs));
74
+ } catch {
75
+ failed++;
76
+ }
77
+ });
78
+
79
+ for (const r of results) {
80
+ if (r.ignored === 'all') continue;
81
+ const skip = new Set(Array.isArray(r.ignored) ? r.ignored : []);
82
+ const add = (id, fallback, reason) => {
83
+ if (!enabled(id) || skip.has(id) || r.findings.some((f) => f.id === id && f.reason === reason)) return;
84
+ r.findings.push({ id, weight: weightOf(id, fallback), reason });
85
+ };
86
+ for (const d of r.deps ?? []) {
87
+ const info = lookups.get(`${d.ecosystem}:${d.name}`);
88
+ if (!info) continue;
89
+ const registry = d.ecosystem === 'npm' ? 'npm' : 'PyPI';
90
+ if (!info.exists) {
91
+ add('package-not-found', 50, `${d.name} does not exist on ${registry}${d.name.startsWith('@') ? ' (or is private)' : ''}; possibly a hallucinated name`);
92
+ continue;
93
+ }
94
+ if (info.created && now - info.created < NEW_PACKAGE_DAYS * DAY) {
95
+ const days = Math.max(0, Math.floor((now - info.created) / DAY));
96
+ add('package-new', 30, `${d.name} was first published ${days === 0 ? 'today' : `${days} day${days === 1 ? '' : 's'} ago`}`);
97
+ }
98
+ if (info.weeklyDownloads !== undefined && info.weeklyDownloads < LOW_WEEKLY_DOWNLOADS) {
99
+ add('package-low-downloads', 15, `${d.name} had only ${info.weeklyDownloads} downloads last week`);
100
+ }
101
+ if (info.deprecated) add('package-deprecated', 15, `${d.name} is deprecated: ${String(info.deprecated).slice(0, 120)}`);
102
+ }
103
+ finalize(r);
104
+ }
105
+ sortResults(results);
106
+ return { checked: unique.size - failed, failed };
107
+ }
108
+
109
+ async function getJson(url, fetch, timeoutMs) {
110
+ const res = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
111
+ if (res.status === 404) return null;
112
+ if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
113
+ return res.json();
114
+ }
115
+
116
+ async function npmInfo(name, fetch, timeoutMs) {
117
+ const encoded = name.startsWith('@') ? `@${encodeURIComponent(name.slice(1))}` : encodeURIComponent(name);
118
+ const downloads = await getJson(`https://api.npmjs.org/downloads/point/last-week/${encoded}`, fetch, timeoutMs).catch(() => undefined);
119
+ const weeklyDownloads = typeof downloads?.downloads === 'number' ? downloads.downloads : undefined;
120
+ // Popular packages have huge registry documents; their age and existence aren't in question.
121
+ if (weeklyDownloads >= POPULAR_WEEKLY_DOWNLOADS) return { exists: true, weeklyDownloads };
122
+
123
+ const doc = await getJson(`https://registry.npmjs.org/${encoded}`, fetch, timeoutMs);
124
+ if (!doc) return { exists: false };
125
+ const latest = doc['dist-tags']?.latest;
126
+ return {
127
+ exists: true,
128
+ created: Date.parse(doc.time?.created) || undefined,
129
+ weeklyDownloads,
130
+ deprecated: latest ? doc.versions?.[latest]?.deprecated : undefined,
131
+ };
132
+ }
133
+
134
+ async function pypiInfo(name, fetch, timeoutMs) {
135
+ const doc = await getJson(`https://pypi.org/pypi/${encodeURIComponent(name)}/json`, fetch, timeoutMs);
136
+ if (!doc) return { exists: false };
137
+ let created;
138
+ for (const files of Object.values(doc.releases ?? {})) {
139
+ for (const f of files) {
140
+ const t = Date.parse(f.upload_time_iso_8601 ?? f.upload_time);
141
+ if (t && (!created || t < created)) created = t;
142
+ }
143
+ }
144
+ return { exists: true, created, deprecated: doc.info?.yanked ? doc.info.yanked_reason || 'yanked' : undefined };
145
+ }
146
+
147
+ async function pool(items, size, fn) {
148
+ let next = 0;
149
+ const workers = Array.from({ length: Math.min(size, items.length) }, async () => {
150
+ while (next < items.length) await fn(items[next++]);
151
+ });
152
+ await Promise.all(workers);
153
+ }
package/src/popular.js ADDED
@@ -0,0 +1,60 @@
1
+ // Widely used package names, for spotting look-alike (typosquat or hallucinated) names
2
+ // and for knowing which libraries do the same job.
3
+
4
+ export const POPULAR = {
5
+ npm: [
6
+ 'react', 'react-dom', 'next', 'vue', 'svelte', 'angular', 'preact', 'solid-js', 'express', 'koa', 'fastify', 'hono',
7
+ 'axios', 'node-fetch', 'got', 'superagent', 'undici', 'ky', 'request', 'lodash', 'underscore', 'ramda', 'moment',
8
+ 'dayjs', 'date-fns', 'luxon', 'uuid', 'nanoid', 'chalk', 'commander', 'yargs', 'inquirer', 'debug', 'dotenv',
9
+ 'cors', 'helmet', 'body-parser', 'cookie-parser', 'jsonwebtoken', 'bcrypt', 'bcryptjs', 'passport', 'mongoose',
10
+ 'sequelize', 'typeorm', 'prisma', '@prisma/client', 'knex', 'pg', 'mysql2', 'sqlite3', 'redis', 'ioredis',
11
+ 'socket.io', 'ws', 'zod', 'joi', 'yup', 'ajv', 'typescript', 'eslint', 'prettier', 'jest', 'mocha', 'chai',
12
+ 'vitest', 'ava', 'sinon', 'supertest', 'webpack', 'vite', 'rollup', 'esbuild', 'parcel', 'babel-loader',
13
+ '@babel/core', 'tailwindcss', 'postcss', 'autoprefixer', 'sass', 'styled-components', 'classnames', 'clsx',
14
+ 'redux', '@reduxjs/toolkit', 'zustand', 'mobx', 'jotai', 'immer', 'rxjs', 'graphql', 'apollo-server',
15
+ '@apollo/client', 'react-router', 'react-router-dom', 'react-query', '@tanstack/react-query', 'swr', 'formik',
16
+ 'react-hook-form', 'framer-motion', 'three', 'd3', 'chart.js', 'recharts', 'puppeteer', 'playwright', 'cheerio',
17
+ 'jsdom', 'sharp', 'multer', 'nodemailer', 'winston', 'pino', 'morgan', 'glob', 'minimist', 'semver', 'rimraf',
18
+ 'mkdirp', 'fs-extra', 'chokidar', 'cross-env', 'concurrently', 'nodemon', 'ts-node', 'tsx', 'husky',
19
+ 'lint-staged', 'jquery', 'bootstrap', 'marked', 'markdown-it', 'highlight.js', 'prismjs', 'openai',
20
+ '@anthropic-ai/sdk', 'langchain', 'stripe', 'aws-sdk', 'firebase', 'firebase-admin', 'mongodb', 'bluebird',
21
+ 'async', 'qs', 'yaml', 'js-yaml', 'xml2js', 'csv-parse', 'papaparse', 'validator', 'sanitize-html',
22
+ 'dompurify', 'crypto-js', 'jscodeshift', 'react-codemod', 'execa', 'ora', 'boxen', 'prompts', 'zx',
23
+ ],
24
+ pypi: [
25
+ 'requests', 'httpx', 'aiohttp', 'urllib3', 'flask', 'django', 'fastapi', 'starlette', 'uvicorn', 'gunicorn',
26
+ 'numpy', 'pandas', 'scipy', 'matplotlib', 'seaborn', 'plotly', 'scikit-learn', 'tensorflow', 'torch',
27
+ 'torchvision', 'keras', 'transformers', 'openai', 'anthropic', 'langchain', 'pydantic', 'sqlalchemy',
28
+ 'psycopg2', 'psycopg2-binary', 'psycopg', 'pymysql', 'redis', 'celery', 'boto3', 'botocore', 'pytest',
29
+ 'pytest-cov', 'nose', 'tox', 'black', 'ruff', 'flake8', 'pylint', 'mypy', 'isort', 'click', 'typer',
30
+ 'rich', 'tqdm', 'pyyaml', 'toml', 'tomli', 'python-dotenv', 'jinja2', 'markupsafe', 'werkzeug', 'pillow',
31
+ 'opencv-python', 'beautifulsoup4', 'lxml', 'scrapy', 'selenium', 'playwright', 'pyjwt', 'cryptography',
32
+ 'bcrypt', 'passlib', 'paramiko', 'arrow', 'pendulum', 'python-dateutil', 'pytz', 'six', 'attrs', 'marshmallow',
33
+ 'alembic', 'pymongo', 'motor', 'grpcio', 'protobuf', 'setuptools', 'wheel', 'pip', 'poetry', 'virtualenv',
34
+ 'jupyter', 'notebook', 'ipython', 'streamlit', 'gradio', 'networkx', 'sympy', 'nltk', 'spacy', 'xgboost',
35
+ 'lightgbm', 'loguru', 'structlog', 'orjson', 'ujson', 'simplejson', 'docker', 'kubernetes', 'colorama',
36
+ ],
37
+ };
38
+
39
+ // Libraries that do the same job. Adding a second one is usually an agent not noticing the first.
40
+ export const SAME_JOB = [
41
+ { job: 'HTTP client', npm: ['axios', 'node-fetch', 'got', 'superagent', 'request', 'ky', 'undici', 'cross-fetch'], pypi: ['requests', 'httpx', 'aiohttp', 'urllib3'] },
42
+ { job: 'date library', npm: ['moment', 'dayjs', 'date-fns', 'luxon'], pypi: ['arrow', 'pendulum'] },
43
+ { job: 'utility library', npm: ['lodash', 'underscore', 'ramda'] },
44
+ { job: 'ID generator', npm: ['uuid', 'nanoid', 'cuid', 'shortid'] },
45
+ { job: 'test runner', npm: ['jest', 'mocha', 'vitest', 'ava', 'jasmine', 'tap'], pypi: ['pytest', 'nose'] },
46
+ { job: 'schema validator', npm: ['zod', 'joi', 'yup', 'ajv', 'superstruct', 'valibot'], pypi: ['pydantic', 'marshmallow'] },
47
+ { job: 'CLI parser', npm: ['commander', 'yargs', 'minimist', 'meow', 'cac'], pypi: ['click', 'typer'] },
48
+ { job: 'logger', npm: ['winston', 'pino', 'bunyan', 'log4js'], pypi: ['loguru', 'structlog'] },
49
+ { job: 'password hashing', npm: ['bcrypt', 'bcryptjs', 'argon2'], pypi: ['bcrypt', 'passlib', 'argon2-cffi'] },
50
+ { job: 'state manager', npm: ['@reduxjs/toolkit', 'zustand', 'mobx', 'jotai', 'recoil', 'valtio'] },
51
+ { job: 'ORM', npm: ['sequelize', 'typeorm', 'prisma', 'mikro-orm', 'drizzle-orm', 'objection'] },
52
+ { job: 'Postgres driver', pypi: ['psycopg2', 'psycopg2-binary', 'psycopg', 'asyncpg'] },
53
+ { job: 'YAML parser', npm: ['yaml', 'js-yaml'], pypi: ['pyyaml', 'ruamel.yaml'] },
54
+ { job: 'JSON library', pypi: ['orjson', 'ujson', 'simplejson'] },
55
+ { job: 'build tool', npm: ['webpack', 'vite', 'rollup', 'parcel', 'esbuild'] },
56
+ { job: 'Redis client', npm: ['redis', 'ioredis'] },
57
+ { job: 'class name helper', npm: ['classnames', 'clsx'] },
58
+ { job: 'data fetching hook', npm: ['react-query', '@tanstack/react-query', 'swr'] },
59
+ { job: 'markdown parser', npm: ['marked', 'markdown-it', 'remark'] },
60
+ ];
package/src/report.js ADDED
@@ -0,0 +1,141 @@
1
+ import { LEVELS, testTamper } from './score.js';
2
+
3
+ const AI_LABEL = { real: 'likely real', 'false-positive': 'likely false positive', unsure: 'unsure' };
4
+
5
+ const COLORS = { high: '\x1b[31m', medium: '\x1b[33m', low: '\x1b[36m', none: '\x1b[90m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' };
6
+
7
+ export function summarize(results) {
8
+ const counts = { high: 0, medium: 0, low: 0, none: 0 };
9
+ for (const r of results) counts[r.level]++;
10
+ return { files: new Set(results.map((r) => r.file)).size, hunks: results.length, ...counts, testTamper: testTamper(results) };
11
+ }
12
+
13
+ // "2 tests skipped, 1 assertion removed", or null when the tests were not weakened.
14
+ export function tamperLine({ testTamper: t }) {
15
+ if (!t.total) return null;
16
+ const parts = [
17
+ [t.skipped, 'test skipped or focused', 'tests skipped or focused'],
18
+ [t.assertionsRemoved, 'hunk removed assertions', 'hunks removed assertions'],
19
+ [t.filesDeleted, 'test file deleted', 'test files deleted'],
20
+ ].filter(([n]) => n).map(([n, one, many]) => `${n} ${n === 1 ? one : many}`);
21
+ return `Tests weakened: ${parts.join(', ')}`;
22
+ }
23
+
24
+ export function formatText(results, { color = false, code = false } = {}) {
25
+ const c = (name, s) => (color ? COLORS[name] + s + COLORS.reset : s);
26
+ const s = summarize(results);
27
+ const out = [
28
+ c('bold', 'riskdiff') +
29
+ ` · ${s.files} file${s.files === 1 ? '' : 's'}, ${s.hunks} hunk${s.hunks === 1 ? '' : 's'} · ` +
30
+ [c('high', `${s.high} high`), c('medium', `${s.medium} medium`), c('low', `${s.low} low`)].join(' · '),
31
+ '',
32
+ ];
33
+ const tamper = tamperLine(s);
34
+ if (tamper) out.push(c('medium', `⚠ ${tamper}`), '');
35
+
36
+ const shown = results.filter((r) => r.score > 0);
37
+ if (!shown.length) out.push(c('dim', 'No risky changes found.'));
38
+
39
+ for (const r of shown) {
40
+ const tag = r.level.toUpperCase().padEnd(6);
41
+ const where = `${r.file}:${r.line}`;
42
+ const ctx = r.context ? c('dim', ` ${r.context}`) : '';
43
+ out.push(`${c(r.level, tag)} ${String(r.score).padStart(3)} ${c('bold', where)}${ctx}`);
44
+ out.push(c('dim', ` +${r.added} −${r.removed}${r.status !== 'modified' ? ` (${r.status})` : ''}`));
45
+ for (const f of r.findings) out.push(` ${c(r.level, '•')} ${f.reason} ${c('dim', `[${f.id} +${f.weight}]`)}`);
46
+ if (r.ai) out.push(` ${c('bold', 'AI:')} ${AI_LABEL[r.ai.verdict]}${r.ai.note ? ` — ${r.ai.note}` : ''}`);
47
+ if (code) {
48
+ for (const l of r.hunk.removed.slice(0, 20)) out.push(c('high', ` - ${l}`));
49
+ for (const l of r.hunk.added.slice(0, 20)) out.push(c('low', ` + ${l}`));
50
+ }
51
+ out.push('');
52
+ }
53
+ return out.join('\n');
54
+ }
55
+
56
+ export function formatMarkdown(results) {
57
+ const s = summarize(results);
58
+ const out = [
59
+ // Lets the GitHub Action find and update its own PR comment.
60
+ '<!-- riskdiff -->',
61
+ '## riskdiff report',
62
+ '',
63
+ `**${s.files}** files · **${s.hunks}** hunks · 🔴 ${s.high} high · 🟠 ${s.medium} medium · 🔵 ${s.low} low`,
64
+ '',
65
+ ];
66
+ const tamper = tamperLine(s);
67
+ if (tamper) out.push(`> [!WARNING]
68
+ > ${tamper}`, '');
69
+ const shown = results.filter((r) => r.score > 0);
70
+ if (!shown.length) return [...out, 'No risky changes found.', ''].join('\n');
71
+
72
+ out.push('| Risk | Score | Location | Why |', '|---|---:|---|---|');
73
+ const icon = { high: '🔴 High', medium: '🟠 Medium', low: '🔵 Low' };
74
+ for (const r of shown) {
75
+ let why = r.findings.map((f) => f.reason).join('<br>');
76
+ if (r.ai) why += `<br>🤖 _${AI_LABEL[r.ai.verdict]}${r.ai.note ? ` — ${r.ai.note.replace(/\|/g, '\\|')}` : ''}_`;
77
+ out.push(`| ${icon[r.level]} | ${r.score} | \`${r.file}:${r.line}\` | ${why} |`);
78
+ }
79
+ return out.join('\n') + '\n';
80
+ }
81
+
82
+ export function formatJson(results) {
83
+ return JSON.stringify(
84
+ { summary: summarize(results), hunks: results.map(({ hunk, ...rest }) => rest) },
85
+ null,
86
+ 2,
87
+ );
88
+ }
89
+
90
+ const SARIF_LEVEL = { high: 'error', medium: 'warning', low: 'note' };
91
+
92
+ // SARIF 2.1.0, for GitHub code scanning and other SARIF viewers. One result per finding.
93
+ // Deleted files are left out: there is no line left to annotate.
94
+ export function formatSarif(results, { version, rules = [] } = {}) {
95
+ const used = new Map();
96
+ const sarifResults = [];
97
+ for (const r of results) {
98
+ if (r.score === 0 || r.status === 'deleted') continue;
99
+ for (const f of r.findings) {
100
+ const rule = rules.find((x) => x.id === f.id);
101
+ if (!used.has(f.id)) used.set(f.id, rule?.reason ?? f.reason);
102
+ sarifResults.push({
103
+ ruleId: f.id,
104
+ level: SARIF_LEVEL[r.level],
105
+ message: { text: `${f.reason} (hunk score ${r.score}, ${r.level} risk)` },
106
+ locations: [{ physicalLocation: { artifactLocation: { uri: r.file }, region: { startLine: Math.max(1, r.line) } } }],
107
+ partialFingerprints: { riskdiffHunk: `${r.file}:${f.id}:${r.context || r.line}` },
108
+ properties: { score: r.score, weight: f.weight, level: r.level },
109
+ });
110
+ }
111
+ }
112
+ return JSON.stringify(
113
+ {
114
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
115
+ version: '2.1.0',
116
+ runs: [
117
+ {
118
+ tool: {
119
+ driver: {
120
+ name: 'riskdiff',
121
+ version,
122
+ informationUri: 'https://github.com/zeitgeistz/riskdiff',
123
+ rules: [...used].map(([id, text]) => ({
124
+ id,
125
+ shortDescription: { text },
126
+ helpUri: 'https://github.com/zeitgeistz/riskdiff#-what-it-catches',
127
+ })),
128
+ },
129
+ },
130
+ results: sarifResults,
131
+ },
132
+ ],
133
+ },
134
+ null,
135
+ 2,
136
+ );
137
+ }
138
+
139
+ export function atOrAbove(level, threshold) {
140
+ return LEVELS.indexOf(level) >= LEVELS.indexOf(threshold);
141
+ }