@voidh4x0r/slopgate 0.0.0-stage → 0.1.1
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/CHANGELOG.md +82 -0
- package/LICENSE +21 -0
- package/README.md +304 -2
- package/dist/ast.d.ts +29 -0
- package/dist/ast.js +3 -0
- package/dist/baseline.d.ts +33 -0
- package/dist/baseline.js +104 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +487 -0
- package/dist/config.d.ts +25 -0
- package/dist/config.js +91 -0
- package/dist/data/python-stdlib.d.ts +21 -0
- package/dist/data/python-stdlib.js +92 -0
- package/dist/deps.d.ts +8 -0
- package/dist/deps.js +491 -0
- package/dist/diff.d.ts +30 -0
- package/dist/diff.js +217 -0
- package/dist/engine.d.ts +15 -0
- package/dist/engine.js +169 -0
- package/dist/files.d.ts +33 -0
- package/dist/files.js +214 -0
- package/dist/mcp.d.ts +41 -0
- package/dist/mcp.js +226 -0
- package/dist/parser.d.ts +3 -0
- package/dist/parser.js +45 -0
- package/dist/reporters/github.d.ts +2 -0
- package/dist/reporters/github.js +44 -0
- package/dist/reporters/json.d.ts +10 -0
- package/dist/reporters/json.js +36 -0
- package/dist/reporters/pretty.d.ts +12 -0
- package/dist/reporters/pretty.js +103 -0
- package/dist/reporters/sarif.d.ts +2 -0
- package/dist/reporters/sarif.js +75 -0
- package/dist/rules/helpers.d.ts +53 -0
- package/dist/rules/helpers.js +178 -0
- package/dist/rules/index.d.ts +3 -0
- package/dist/rules/index.js +4 -0
- package/dist/rules/python.d.ts +2 -0
- package/dist/rules/python.js +632 -0
- package/dist/rules/typescript.d.ts +2 -0
- package/dist/rules/typescript.js +563 -0
- package/dist/suppress.d.ts +12 -0
- package/dist/suppress.js +52 -0
- package/dist/types.d.ts +95 -0
- package/dist/types.js +1 -0
- package/grammars/README.md +28 -0
- package/grammars/tree-sitter-python.wasm +0 -0
- package/grammars/tree-sitter-tsx.wasm +0 -0
- package/grammars/tree-sitter-typescript.wasm +0 -0
- package/package.json +61 -4
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import { loadBaseline, partitionByBaseline } from "./baseline.js";
|
|
6
|
+
import { loadConfig, meetsConfidence } from "./config.js";
|
|
7
|
+
import { diffSince, isInDiff } from "./diff.js";
|
|
8
|
+
import { scanProject } from "./engine.js";
|
|
9
|
+
import { ALL_RULES } from "./rules/index.js";
|
|
10
|
+
const PROTOCOL_FALLBACK = '2024-11-05';
|
|
11
|
+
const MAX_FINDINGS = 50;
|
|
12
|
+
const TOOLS = [
|
|
13
|
+
{
|
|
14
|
+
name: 'scan_diff',
|
|
15
|
+
description: 'Run slopgate on the lines changed since a git ref (default HEAD). Use this before finishing a task to check that the new code does not contain hallucinated imports, empty stubs, tests that cannot fail, swallowed errors or dead code.',
|
|
16
|
+
inputSchema: {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
base: { type: 'string', description: 'Git ref to compare against (default: HEAD)' },
|
|
20
|
+
confidence: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
enum: ['high', 'medium', 'low'],
|
|
23
|
+
description: 'Minimum confidence to report (default: high)',
|
|
24
|
+
},
|
|
25
|
+
maxFindings: { type: 'integer', description: 'Maximum findings to print (default: 50)' },
|
|
26
|
+
},
|
|
27
|
+
additionalProperties: false,
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: 'scan_path',
|
|
32
|
+
description: 'Run slopgate over a directory or file. Returns findings with rule id, confidence and evidence.',
|
|
33
|
+
inputSchema: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
path: { type: 'string', description: 'File or directory, relative to the repository root' },
|
|
37
|
+
confidence: {
|
|
38
|
+
type: 'string',
|
|
39
|
+
enum: ['high', 'medium', 'low'],
|
|
40
|
+
description: 'Minimum confidence to report (default: high)',
|
|
41
|
+
},
|
|
42
|
+
maxFindings: { type: 'integer', description: 'Maximum findings to print (default: 50)' },
|
|
43
|
+
},
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: 'list_rules',
|
|
49
|
+
description: 'List the rules slopgate can report, with their default severity and confidence.',
|
|
50
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
51
|
+
},
|
|
52
|
+
];
|
|
53
|
+
function ok(id, result) {
|
|
54
|
+
return { jsonrpc: '2.0', id, result };
|
|
55
|
+
}
|
|
56
|
+
function fail(id, code, message) {
|
|
57
|
+
return { jsonrpc: '2.0', id, error: { code, message } };
|
|
58
|
+
}
|
|
59
|
+
/** True when `candidate` is `root` itself or lives below it. */
|
|
60
|
+
export function isInsideRoot(realRoot, candidate) {
|
|
61
|
+
const relative = path.relative(realRoot, candidate);
|
|
62
|
+
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
63
|
+
}
|
|
64
|
+
function textResult(text, isError = false) {
|
|
65
|
+
return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) };
|
|
66
|
+
}
|
|
67
|
+
function coerceConfidence(value, fallback) {
|
|
68
|
+
if (value === 'high' || value === 'medium' || value === 'low')
|
|
69
|
+
return value;
|
|
70
|
+
return fallback;
|
|
71
|
+
}
|
|
72
|
+
function coerceNumber(value, fallback) {
|
|
73
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
74
|
+
? Math.min(Math.floor(value), MAX_FINDINGS)
|
|
75
|
+
: fallback;
|
|
76
|
+
}
|
|
77
|
+
function formatFindings(findings, result, version, max, preamble) {
|
|
78
|
+
const shown = findings.slice(0, max);
|
|
79
|
+
const errors = findings.filter((finding) => finding.severity === 'error').length;
|
|
80
|
+
const lines = [];
|
|
81
|
+
if (preamble)
|
|
82
|
+
lines.push(preamble);
|
|
83
|
+
lines.push(`slopgate ${version} · ${findings.length} finding(s) (${errors} error) · ${result.stats.files} files scanned in ${result.stats.durationMs}ms`);
|
|
84
|
+
if (findings.length === 0) {
|
|
85
|
+
lines.push('No findings above the confidence threshold.');
|
|
86
|
+
return lines.join('\n');
|
|
87
|
+
}
|
|
88
|
+
if (findings.length > shown.length) {
|
|
89
|
+
lines.push(`Showing the first ${shown.length} of ${findings.length}.`);
|
|
90
|
+
}
|
|
91
|
+
for (const finding of shown) {
|
|
92
|
+
lines.push(`${finding.file}:${finding.start.line}:${finding.start.column} ${finding.severity} ${finding.confidence} ${finding.ruleId} ${finding.message}`);
|
|
93
|
+
if (finding.snippet)
|
|
94
|
+
lines.push(` ${finding.snippet}`);
|
|
95
|
+
for (const item of finding.evidence.slice(0, 2))
|
|
96
|
+
lines.push(` - ${item}`);
|
|
97
|
+
}
|
|
98
|
+
return lines.join('\n');
|
|
99
|
+
}
|
|
100
|
+
export function createMcpServer(deps) {
|
|
101
|
+
async function callTool(name, params) {
|
|
102
|
+
if (name === 'list_rules') {
|
|
103
|
+
const lines = ['id\tseverity\tconfidence\tlanguages\ttitle'];
|
|
104
|
+
for (const rule of ALL_RULES) {
|
|
105
|
+
lines.push(`${rule.meta.id}\t${rule.meta.severity}\t${rule.meta.confidence}\t${rule.meta.languages.join(',')}\t${rule.meta.title}`);
|
|
106
|
+
}
|
|
107
|
+
return textResult(lines.join('\n'));
|
|
108
|
+
}
|
|
109
|
+
const confidence = coerceConfidence(params.confidence, deps.config.confidence);
|
|
110
|
+
const max = coerceNumber(params.maxFindings, MAX_FINDINGS);
|
|
111
|
+
if (name === 'scan_path') {
|
|
112
|
+
const target = path.resolve(deps.root, typeof params.path === 'string' ? params.path : '.');
|
|
113
|
+
if (!isInsideRoot(deps.root, target)) {
|
|
114
|
+
return textResult(`Refusing to scan outside the repository root: ${target}`, true);
|
|
115
|
+
}
|
|
116
|
+
// `path.resolve` does not follow symlinks: a link inside the root could
|
|
117
|
+
// still point outside it, so compare real paths as well.
|
|
118
|
+
const realRoot = await realpath(deps.root).catch(() => deps.root);
|
|
119
|
+
const realTarget = await realpath(target).catch(() => target);
|
|
120
|
+
if (!isInsideRoot(realRoot, realTarget)) {
|
|
121
|
+
return textResult(`Refusing to scan outside the repository root: ${target}`, true);
|
|
122
|
+
}
|
|
123
|
+
const result = await deps.scan(target);
|
|
124
|
+
const visible = result.findings.filter((finding) => meetsConfidence(finding.confidence, confidence));
|
|
125
|
+
return textResult(formatFindings(visible, result, deps.version, max));
|
|
126
|
+
}
|
|
127
|
+
if (name === 'scan_diff') {
|
|
128
|
+
const base = typeof params.base === 'string' && params.base.length > 0 ? params.base : 'HEAD';
|
|
129
|
+
const result = await deps.scan(deps.root);
|
|
130
|
+
const set = await deps.diff(deps.root, base);
|
|
131
|
+
const inDiff = result.findings.filter((finding) => isInDiff(finding, set) && meetsConfidence(finding.confidence, confidence));
|
|
132
|
+
const preamble = `Diff since ${base}: ${inDiff.length} finding(s) on changed lines.`;
|
|
133
|
+
return textResult(formatFindings(inDiff, result, deps.version, max, preamble));
|
|
134
|
+
}
|
|
135
|
+
return textResult(`Unknown tool: ${name}`, true);
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
async handle(line) {
|
|
139
|
+
let request;
|
|
140
|
+
try {
|
|
141
|
+
request = JSON.parse(line);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return fail(null, -32700, 'Parse error');
|
|
145
|
+
}
|
|
146
|
+
if (request === null || typeof request !== 'object' || typeof request.method !== 'string') {
|
|
147
|
+
return fail(null, -32600, 'Invalid request');
|
|
148
|
+
}
|
|
149
|
+
const isNotification = request.id === undefined || request.id === null;
|
|
150
|
+
const id = request.id ?? null;
|
|
151
|
+
try {
|
|
152
|
+
switch (request.method) {
|
|
153
|
+
case 'initialize': {
|
|
154
|
+
const requested = request.params?.protocolVersion;
|
|
155
|
+
return ok(id, {
|
|
156
|
+
protocolVersion: typeof requested === 'string' ? requested : PROTOCOL_FALLBACK,
|
|
157
|
+
capabilities: { tools: {} },
|
|
158
|
+
serverInfo: { name: 'slopgate', version: deps.version },
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
case 'notifications/initialized':
|
|
162
|
+
return null;
|
|
163
|
+
case 'ping':
|
|
164
|
+
return ok(id, {});
|
|
165
|
+
case 'tools/list':
|
|
166
|
+
return ok(id, { tools: TOOLS });
|
|
167
|
+
case 'tools/call': {
|
|
168
|
+
const params = (request.params ?? {});
|
|
169
|
+
if (typeof params.name !== 'string')
|
|
170
|
+
return fail(id, -32602, 'tools/call requires a tool name');
|
|
171
|
+
const args = params.arguments !== null && typeof params.arguments === 'object'
|
|
172
|
+
? params.arguments
|
|
173
|
+
: {};
|
|
174
|
+
const result = await callTool(params.name, args);
|
|
175
|
+
return ok(id, result);
|
|
176
|
+
}
|
|
177
|
+
default:
|
|
178
|
+
return isNotification ? null : fail(id, -32601, `Method not found: ${request.method}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
const message = error.message;
|
|
183
|
+
if (request.method === 'tools/call') {
|
|
184
|
+
return ok(id, textResult(`slopgate error: ${message}`, true));
|
|
185
|
+
}
|
|
186
|
+
return fail(id, -32603, message);
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export function defaultMcpDeps(root, version) {
|
|
192
|
+
let configPromise;
|
|
193
|
+
const getConfig = async () => {
|
|
194
|
+
configPromise ??= loadConfig(root).then((loaded) => loaded.config);
|
|
195
|
+
return configPromise;
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
root,
|
|
199
|
+
version,
|
|
200
|
+
async scan(scanRoot) {
|
|
201
|
+
const config = await getConfig();
|
|
202
|
+
const result = await scanProject({ root: scanRoot, config });
|
|
203
|
+
// Respect a baseline if one exists, so agents do not re-report known debt.
|
|
204
|
+
const baseline = await loadBaseline(path.join(root, '.slopgate-baseline.json'));
|
|
205
|
+
if (baseline)
|
|
206
|
+
return { ...result, findings: partitionByBaseline(result.findings, baseline).fresh };
|
|
207
|
+
return result;
|
|
208
|
+
},
|
|
209
|
+
diff: diffSince,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/** Runs the stdio loop. Resolves when stdin closes. */
|
|
213
|
+
export async function serveMcp(root, version) {
|
|
214
|
+
const config = (await loadConfig(root)).config;
|
|
215
|
+
const base = defaultMcpDeps(root, version);
|
|
216
|
+
const server = createMcpServer({ ...base, config });
|
|
217
|
+
process.stderr.write(`slopgate mcp ${version} ready (root: ${root})\n`);
|
|
218
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
219
|
+
for await (const line of rl) {
|
|
220
|
+
if (line.trim().length === 0)
|
|
221
|
+
continue;
|
|
222
|
+
const response = await server.handle(line);
|
|
223
|
+
if (response !== null)
|
|
224
|
+
process.stdout.write(JSON.stringify(response) + '\n');
|
|
225
|
+
}
|
|
226
|
+
}
|
package/dist/parser.d.ts
ADDED
package/dist/parser.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { Language, Parser } from 'web-tree-sitter';
|
|
4
|
+
const PACKAGE_ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
5
|
+
const GRAMMARS = {
|
|
6
|
+
python: 'tree-sitter-python.wasm',
|
|
7
|
+
typescript: 'tree-sitter-typescript.wasm',
|
|
8
|
+
tsx: 'tree-sitter-tsx.wasm',
|
|
9
|
+
};
|
|
10
|
+
let initPromise;
|
|
11
|
+
const parserCache = new Map();
|
|
12
|
+
async function ensureRuntime() {
|
|
13
|
+
initPromise ??= Parser.init();
|
|
14
|
+
await initPromise;
|
|
15
|
+
}
|
|
16
|
+
function grammarPath(language) {
|
|
17
|
+
return path.join(PACKAGE_ROOT, 'grammars', GRAMMARS[language]);
|
|
18
|
+
}
|
|
19
|
+
export async function getParser(language) {
|
|
20
|
+
const cached = parserCache.get(language);
|
|
21
|
+
if (cached)
|
|
22
|
+
return cached;
|
|
23
|
+
const created = (async () => {
|
|
24
|
+
await ensureRuntime();
|
|
25
|
+
const wasm = grammarPath(language);
|
|
26
|
+
let lang;
|
|
27
|
+
try {
|
|
28
|
+
lang = await Language.load(wasm);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
throw new Error(`could not load grammar for ${language} (${wasm}). ` +
|
|
32
|
+
'If you installed from source, run `npm install` first. ' +
|
|
33
|
+
`Underlying error: ${error.message}`);
|
|
34
|
+
}
|
|
35
|
+
const parser = new Parser();
|
|
36
|
+
parser.setLanguage(lang);
|
|
37
|
+
return parser;
|
|
38
|
+
})();
|
|
39
|
+
parserCache.set(language, created);
|
|
40
|
+
// A failed grammar load must not be cached forever: the next call retries.
|
|
41
|
+
created.catch(() => {
|
|
42
|
+
parserCache.delete(language);
|
|
43
|
+
});
|
|
44
|
+
return created;
|
|
45
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub Actions workflow commands: annotations show up inline on the pull
|
|
3
|
+
* request diff without any extra setup (unlike SARIF, which needs code scanning).
|
|
4
|
+
*
|
|
5
|
+
* Escaping rules:
|
|
6
|
+
* property values: % \r \n : ,
|
|
7
|
+
* message data: % \r \n
|
|
8
|
+
*/
|
|
9
|
+
function escapeProperty(value) {
|
|
10
|
+
return value
|
|
11
|
+
.replace(/%/g, '%25')
|
|
12
|
+
.replace(/\r/g, '%0D')
|
|
13
|
+
.replace(/\n/g, '%0A')
|
|
14
|
+
.replace(/:/g, '%3A')
|
|
15
|
+
.replace(/,/g, '%2C');
|
|
16
|
+
}
|
|
17
|
+
function escapeData(value) {
|
|
18
|
+
return value.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
|
19
|
+
}
|
|
20
|
+
const ANNOTATION_LEVEL = {
|
|
21
|
+
error: 'error',
|
|
22
|
+
warning: 'warning',
|
|
23
|
+
info: 'notice',
|
|
24
|
+
};
|
|
25
|
+
export function renderGithub(findings, stats) {
|
|
26
|
+
const lines = [];
|
|
27
|
+
for (const finding of findings) {
|
|
28
|
+
const properties = [
|
|
29
|
+
`file=${escapeProperty(finding.file)}`,
|
|
30
|
+
`line=${finding.start.line}`,
|
|
31
|
+
`col=${finding.start.column}`,
|
|
32
|
+
`endLine=${finding.end.line}`,
|
|
33
|
+
`endColumn=${finding.end.column}`,
|
|
34
|
+
`title=${escapeProperty(finding.ruleId)}`,
|
|
35
|
+
].join(',');
|
|
36
|
+
// The message is shown as the annotation body; keep it to one line.
|
|
37
|
+
const message = finding.help ? `${finding.message} — ${finding.help}` : finding.message;
|
|
38
|
+
lines.push(`::${ANNOTATION_LEVEL[finding.severity]} ${properties}::${escapeData(message)}`);
|
|
39
|
+
}
|
|
40
|
+
const errors = findings.filter((finding) => finding.severity === 'error').length;
|
|
41
|
+
const warnings = findings.filter((finding) => finding.severity === 'warning').length;
|
|
42
|
+
lines.push(`::notice title=slopgate::${findings.length} finding(s) (${errors} error, ${warnings} warning) · ${stats.files} files scanned in ${stats.durationMs}ms`);
|
|
43
|
+
return lines.join('\n') + '\n';
|
|
44
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Finding, ScanStats } from '../types.ts';
|
|
2
|
+
export interface JsonInput {
|
|
3
|
+
findings: readonly Finding[];
|
|
4
|
+
stats: ScanStats;
|
|
5
|
+
version: string;
|
|
6
|
+
suppressedByComment: number;
|
|
7
|
+
baselined: number;
|
|
8
|
+
hiddenByConfidence: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function renderJson(input: JsonInput): string;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { findingFingerprint } from "../baseline.js";
|
|
2
|
+
export function renderJson(input) {
|
|
3
|
+
const bySeverity = { error: 0, warning: 0, info: 0 };
|
|
4
|
+
const byConfidence = { high: 0, medium: 0, low: 0 };
|
|
5
|
+
for (const finding of input.findings) {
|
|
6
|
+
bySeverity[finding.severity] += 1;
|
|
7
|
+
byConfidence[finding.confidence] += 1;
|
|
8
|
+
}
|
|
9
|
+
const payload = {
|
|
10
|
+
tool: 'slopgate',
|
|
11
|
+
version: input.version,
|
|
12
|
+
stats: input.stats,
|
|
13
|
+
summary: {
|
|
14
|
+
findings: input.findings.length,
|
|
15
|
+
bySeverity,
|
|
16
|
+
byConfidence,
|
|
17
|
+
suppressedByComment: input.suppressedByComment,
|
|
18
|
+
baselined: input.baselined,
|
|
19
|
+
hiddenByConfidence: input.hiddenByConfidence,
|
|
20
|
+
},
|
|
21
|
+
findings: input.findings.map((finding) => ({
|
|
22
|
+
ruleId: finding.ruleId,
|
|
23
|
+
severity: finding.severity,
|
|
24
|
+
confidence: finding.confidence,
|
|
25
|
+
file: finding.file,
|
|
26
|
+
start: finding.start,
|
|
27
|
+
end: finding.end,
|
|
28
|
+
message: finding.message,
|
|
29
|
+
snippet: finding.snippet,
|
|
30
|
+
evidence: finding.evidence,
|
|
31
|
+
...(finding.help ? { help: finding.help } : {}),
|
|
32
|
+
fingerprint: findingFingerprint(finding),
|
|
33
|
+
})),
|
|
34
|
+
};
|
|
35
|
+
return JSON.stringify(payload, null, 2) + '\n';
|
|
36
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Finding, ScanStats } from '../types.ts';
|
|
2
|
+
export interface PrettyInput {
|
|
3
|
+
findings: readonly Finding[];
|
|
4
|
+
stats: ScanStats;
|
|
5
|
+
suppressedByComment: number;
|
|
6
|
+
baselined: number;
|
|
7
|
+
hiddenByConfidence: number;
|
|
8
|
+
version: string;
|
|
9
|
+
color: boolean;
|
|
10
|
+
quiet?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare function renderPretty(input: PrettyInput): string;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
function ansi(enabled, code) {
|
|
2
|
+
return (text) => (enabled ? `\u001b[${code}m${text}\u001b[0m` : text);
|
|
3
|
+
}
|
|
4
|
+
function wrap(text, width) {
|
|
5
|
+
const words = text.split(/\s+/).filter((word) => word.length > 0);
|
|
6
|
+
const lines = [];
|
|
7
|
+
let current = '';
|
|
8
|
+
for (const word of words) {
|
|
9
|
+
if (current.length === 0) {
|
|
10
|
+
current = word;
|
|
11
|
+
}
|
|
12
|
+
else if (current.length + 1 + word.length <= width) {
|
|
13
|
+
current += ' ' + word;
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
lines.push(current);
|
|
17
|
+
current = word;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (current.length > 0)
|
|
21
|
+
lines.push(current);
|
|
22
|
+
return lines.length > 0 ? lines : [''];
|
|
23
|
+
}
|
|
24
|
+
const LOC_WIDTH = 8;
|
|
25
|
+
const SEV_WIDTH = 7;
|
|
26
|
+
const CONF_WIDTH = 6;
|
|
27
|
+
const RULE_WIDTH = 23;
|
|
28
|
+
const GUTTER = ' '.repeat(LOC_WIDTH + 2);
|
|
29
|
+
export function renderPretty(input) {
|
|
30
|
+
const { findings, stats, version, color } = input;
|
|
31
|
+
const bold = ansi(color, '1');
|
|
32
|
+
const dim = ansi(color, '2');
|
|
33
|
+
const red = ansi(color, '31');
|
|
34
|
+
const yellow = ansi(color, '33');
|
|
35
|
+
const cyan = ansi(color, '36');
|
|
36
|
+
const green = ansi(color, '32');
|
|
37
|
+
const out = [];
|
|
38
|
+
out.push('');
|
|
39
|
+
out.push(`${bold('slopgate')} ${dim(version)} ${dim('·')} ${stats.files} files ${dim('·')} ${stats.durationMs}ms`);
|
|
40
|
+
out.push('');
|
|
41
|
+
if (findings.length === 0) {
|
|
42
|
+
out.push(` ${green('✓')} no findings above the confidence threshold`);
|
|
43
|
+
out.push('');
|
|
44
|
+
}
|
|
45
|
+
let currentFile;
|
|
46
|
+
if (!input.quiet) {
|
|
47
|
+
for (const finding of findings) {
|
|
48
|
+
if (finding.file !== currentFile) {
|
|
49
|
+
if (currentFile !== undefined)
|
|
50
|
+
out.push('');
|
|
51
|
+
out.push(cyan(finding.file));
|
|
52
|
+
currentFile = finding.file;
|
|
53
|
+
}
|
|
54
|
+
const location = `${finding.start.line}:${finding.start.column}`.padStart(LOC_WIDTH);
|
|
55
|
+
const severity = finding.severity === 'error'
|
|
56
|
+
? red(finding.severity.padEnd(SEV_WIDTH))
|
|
57
|
+
: finding.severity === 'warning'
|
|
58
|
+
? yellow(finding.severity.padEnd(SEV_WIDTH))
|
|
59
|
+
: dim(finding.severity.padEnd(SEV_WIDTH));
|
|
60
|
+
const confidence = dim(finding.confidence.padEnd(CONF_WIDTH));
|
|
61
|
+
const rule = dim(finding.ruleId.padEnd(RULE_WIDTH));
|
|
62
|
+
out.push(` ${location} ${severity} ${confidence} ${rule} ${finding.message}`);
|
|
63
|
+
if (finding.snippet) {
|
|
64
|
+
out.push(`${GUTTER} ${dim('│ ' + finding.snippet)}`);
|
|
65
|
+
}
|
|
66
|
+
for (const item of finding.evidence.slice(0, 2)) {
|
|
67
|
+
out.push(`${GUTTER} ${dim('· ' + item)}`);
|
|
68
|
+
}
|
|
69
|
+
if (finding.help) {
|
|
70
|
+
const lines = wrap(finding.help, 92);
|
|
71
|
+
lines.forEach((line, index) => {
|
|
72
|
+
const marker = index === 0 ? '↳ ' : ' ';
|
|
73
|
+
out.push(dim(`${GUTTER} ${marker}${line}`));
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (findings.length > 0 && !input.quiet)
|
|
79
|
+
out.push('');
|
|
80
|
+
const bySeverity = { error: 0, warning: 0, info: 0 };
|
|
81
|
+
const byConfidence = { high: 0, medium: 0, low: 0 };
|
|
82
|
+
for (const finding of findings) {
|
|
83
|
+
bySeverity[finding.severity] += 1;
|
|
84
|
+
byConfidence[finding.confidence] += 1;
|
|
85
|
+
}
|
|
86
|
+
const fileCount = new Set(findings.map((finding) => finding.file)).size;
|
|
87
|
+
out.push(` ${bold(String(findings.length))} ${findings.length === 1 ? 'finding' : 'findings'} in ${fileCount} ${fileCount === 1 ? 'file' : 'files'} ${dim('·')} ${stats.files} files scanned in ${stats.durationMs}ms`);
|
|
88
|
+
out.push(dim(` ${bySeverity.error} error · ${bySeverity.warning} warning · ${bySeverity.info} info (${byConfidence.high} high · ${byConfidence.medium} medium · ${byConfidence.low} low confidence)`));
|
|
89
|
+
const extras = [];
|
|
90
|
+
if (input.hiddenByConfidence > 0)
|
|
91
|
+
extras.push(`${input.hiddenByConfidence} below confidence threshold`);
|
|
92
|
+
if (input.suppressedByComment > 0)
|
|
93
|
+
extras.push(`${input.suppressedByComment} suppressed by comment`);
|
|
94
|
+
if (input.baselined > 0)
|
|
95
|
+
extras.push(`${input.baselined} in baseline`);
|
|
96
|
+
if (extras.length > 0)
|
|
97
|
+
out.push(dim(` hidden: ${extras.join(' · ')}`));
|
|
98
|
+
if (stats.parseErrors > 0) {
|
|
99
|
+
out.push(yellow(` ${stats.parseErrors} file(s) had syntax errors and may be partially analysed`));
|
|
100
|
+
}
|
|
101
|
+
out.push('');
|
|
102
|
+
return out.join('\n');
|
|
103
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { findingFingerprint } from "../baseline.js";
|
|
2
|
+
import { RULE_BY_ID } from "../rules/index.js";
|
|
3
|
+
const SARIF_LEVEL = {
|
|
4
|
+
error: 'error',
|
|
5
|
+
warning: 'warning',
|
|
6
|
+
info: 'note',
|
|
7
|
+
};
|
|
8
|
+
function encodeUriPath(file) {
|
|
9
|
+
// Each segment is encoded separately so `/` stays a path separator while
|
|
10
|
+
// spaces, `#`, `?` and non-ASCII characters become valid URI references.
|
|
11
|
+
return file.split('/').map(encodeURIComponent).join('/');
|
|
12
|
+
}
|
|
13
|
+
export function renderSarif(findings, version) {
|
|
14
|
+
const usedRules = new Map();
|
|
15
|
+
for (const finding of findings) {
|
|
16
|
+
if (!usedRules.has(finding.ruleId))
|
|
17
|
+
usedRules.set(finding.ruleId, finding);
|
|
18
|
+
}
|
|
19
|
+
const rules = [...usedRules.entries()].map(([ruleId, finding]) => {
|
|
20
|
+
const meta = RULE_BY_ID.get(ruleId)?.meta;
|
|
21
|
+
return {
|
|
22
|
+
id: ruleId,
|
|
23
|
+
name: meta?.title ?? ruleId,
|
|
24
|
+
shortDescription: { text: meta?.title ?? ruleId },
|
|
25
|
+
fullDescription: { text: meta?.summary ?? '' },
|
|
26
|
+
defaultConfiguration: { level: SARIF_LEVEL[finding.severity] },
|
|
27
|
+
properties: {
|
|
28
|
+
confidence: meta?.confidence ?? finding.confidence,
|
|
29
|
+
tags: meta?.tags ?? [],
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
});
|
|
33
|
+
const payload = {
|
|
34
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
35
|
+
version: '2.1.0',
|
|
36
|
+
runs: [
|
|
37
|
+
{
|
|
38
|
+
tool: {
|
|
39
|
+
driver: {
|
|
40
|
+
name: 'slopgate',
|
|
41
|
+
version,
|
|
42
|
+
informationUri: 'https://github.com/VoidH4x0r/slopgate',
|
|
43
|
+
rules,
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
results: findings.map((finding) => ({
|
|
47
|
+
ruleId: finding.ruleId,
|
|
48
|
+
level: SARIF_LEVEL[finding.severity],
|
|
49
|
+
message: { text: finding.message },
|
|
50
|
+
locations: [
|
|
51
|
+
{
|
|
52
|
+
physicalLocation: {
|
|
53
|
+
artifactLocation: { uri: encodeUriPath(finding.file) },
|
|
54
|
+
region: {
|
|
55
|
+
startLine: finding.start.line,
|
|
56
|
+
startColumn: finding.start.column,
|
|
57
|
+
endLine: finding.end.line,
|
|
58
|
+
endColumn: finding.end.column,
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
partialFingerprints: {
|
|
64
|
+
primaryLocationLineHash: findingFingerprint(finding),
|
|
65
|
+
},
|
|
66
|
+
properties: {
|
|
67
|
+
confidence: finding.confidence,
|
|
68
|
+
evidence: finding.evidence,
|
|
69
|
+
},
|
|
70
|
+
})),
|
|
71
|
+
},
|
|
72
|
+
],
|
|
73
|
+
};
|
|
74
|
+
return JSON.stringify(payload, null, 2) + '\n';
|
|
75
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { AstNode } from '../ast.ts';
|
|
2
|
+
import type { CommentRange, Position, RuleContext } from '../types.ts';
|
|
3
|
+
export declare function startOf(node: AstNode): Position;
|
|
4
|
+
export declare function endOf(node: AstNode): Position;
|
|
5
|
+
/** Trimmed first line of a node, capped for display. */
|
|
6
|
+
export declare function snippetOf(_ctx: RuleContext, node: AstNode): string;
|
|
7
|
+
export declare function isComment(node: AstNode): boolean;
|
|
8
|
+
/** Named children that are actual statements (comments excluded). */
|
|
9
|
+
export declare function statementsOf(block: AstNode): AstNode[];
|
|
10
|
+
/** Depth-limited, allocation-light walk over named children. */
|
|
11
|
+
export declare function walk(node: AstNode, visit: (node: AstNode, depth: number) => boolean | void, maxDepth?: number): void;
|
|
12
|
+
export declare function descendantsOfType(root: AstNode, types: readonly string[]): AstNode[];
|
|
13
|
+
/** Nearest ancestor whose type is in `types` (excluding the node itself). */
|
|
14
|
+
export declare function ancestorOfType(node: AstNode, types: readonly string[]): AstNode | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Real comment nodes in the tree. A `//` inside a string or a `#` inside a URL
|
|
17
|
+
* is not a comment, so rules must not scan raw source text for these markers.
|
|
18
|
+
*/
|
|
19
|
+
export declare function collectCommentRanges(root: AstNode): CommentRange[];
|
|
20
|
+
/**
|
|
21
|
+
* True when a real comment overlaps the given line range. Comments before the
|
|
22
|
+
* first statement of a block are often attached to the parent node, so callers
|
|
23
|
+
* pass the enclosing statement's range (for example the whole `try`, not just
|
|
24
|
+
* the `except` clause).
|
|
25
|
+
*/
|
|
26
|
+
export declare function hasCommentBetween(ctx: RuleContext, fromLine: number, toLine: number): boolean;
|
|
27
|
+
export declare function collapseWhitespace(value: string): string;
|
|
28
|
+
export declare function truncate(value: string, max: number): string;
|
|
29
|
+
/**
|
|
30
|
+
* Test files and fixtures are full of intentional stubs, dead branches and
|
|
31
|
+
* swallowed errors (they are testing those behaviours). Rules that are not
|
|
32
|
+
* test-specific skip them; `py/noop-test` and `ts/noop-test` are the rules
|
|
33
|
+
* that look at tests themselves.
|
|
34
|
+
*/
|
|
35
|
+
export declare function isTestPath(file: string): boolean;
|
|
36
|
+
/** Type stubs declare every function with `...`; stub rules must not fire. */
|
|
37
|
+
export declare function isStubFile(file: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Modules whose whole purpose is to provide no-op stand-ins (CPython's
|
|
40
|
+
* `multiprocessing/dummy`, single-threaded shims). Their empty bodies are the
|
|
41
|
+
* implementation, not an unfinished one.
|
|
42
|
+
*/
|
|
43
|
+
export declare function isNoopModulePath(file: string): boolean;
|
|
44
|
+
/** True when the file name follows a test-module convention. */
|
|
45
|
+
export declare function looksLikeTestModule(file: string): boolean;
|
|
46
|
+
/** Text of the function's leading docstring, if it has one. */
|
|
47
|
+
export declare function docstringOf(fn: AstNode): string | undefined;
|
|
48
|
+
/** True when the function's body starts with a docstring. */
|
|
49
|
+
export declare function hasDocstring(fn: AstNode): boolean;
|
|
50
|
+
/** True when the node sits inside `if __name__ == "__main__":`. */
|
|
51
|
+
export declare function insideMainGuard(node: AstNode): boolean;
|
|
52
|
+
/** Cleanup/finaliser code swallows errors on purpose; treat it as medium. */
|
|
53
|
+
export declare function insideCleanupFunction(node: AstNode): boolean;
|