@blundergoat/gruff-ts 0.2.0 → 0.3.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 +30 -0
- package/README.md +81 -13
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +21 -5
- package/docs/output-formats.md +10 -0
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +5 -5
- package/docs/rules.md +26 -18
- package/package.json +5 -5
- package/scripts/bump-version.sh +1 -1
- package/src/analyser.ts +48 -37
- package/src/blocks.ts +23 -70
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +106 -12
- package/src/comment-rules.ts +5 -1
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +1 -1
- package/src/config.ts +215 -460
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +7 -4
- package/src/discovery.ts +88 -32
- package/src/findings-helpers.ts +41 -5
- package/src/findings.ts +10 -0
- package/src/fixture-purpose-rules.ts +7 -9
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +3 -0
- package/src/line-rules.ts +7 -5
- package/src/naming-pushers.ts +35 -6
- package/src/profiles.ts +231 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +6 -117
- package/src/report-html.ts +1 -1
- package/src/report-renderers.ts +98 -7
- package/src/rule-list.ts +23 -2
- package/src/rules.ts +11 -12
- package/src/safety-rules.ts +16 -6
- package/src/scoring.ts +43 -5
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/static-analysis-redundant-rules.ts +411 -0
- package/src/test-block-rules.ts +115 -53
- package/src/test-fixtures.ts +50 -9
- package/src/types.ts +79 -2
package/src/constants.ts
CHANGED
package/src/context-doc-rules.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Context-doc rules: emit findings when a function or interface comment exists but does not
|
|
2
2
|
// describe the WHY (complex control flow), side effects, error behavior, or public-contract
|
|
3
3
|
// invariants the implementation carries. Each rule reports a stable, deterministic finding.
|
|
4
|
-
import {
|
|
4
|
+
import { type FunctionBlock, maxNestingDepth } from "./blocks.ts";
|
|
5
5
|
import { type CommentRecord } from "./comment-scanner.ts";
|
|
6
6
|
import { threshold } from "./config.ts";
|
|
7
7
|
import { type SourceFile } from "./discovery.ts";
|
|
@@ -147,17 +147,15 @@ function contextDocFinding(input: ContextDocFindingInput): Finding {
|
|
|
147
147
|
});
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
// Composite gate: any one of size, cyclomatic, cognitive,
|
|
150
|
+
// Composite gate: any one of size, cyclomatic, cognitive, or nesting depth crossing the
|
|
151
151
|
// configured stable threshold qualifies a callable as "complex enough to need WHY context".
|
|
152
152
|
function isComplexContextCandidate(block: FunctionBlock, config: Config): boolean {
|
|
153
153
|
const cyclomatic = countMatches(block.codeBody, /\b(if|else if|switch|case|for|while|catch)\b|\?|&&|\|\|/g) + 1;
|
|
154
154
|
const cognitive = cyclomatic + maxNestingDepth(block.codeBody);
|
|
155
|
-
const npath = approximateNpath(functionBodyContent(block.codeBody));
|
|
156
155
|
return (
|
|
157
156
|
block.lineCount > threshold(config, "size.function-length", 200) ||
|
|
158
157
|
cyclomatic > threshold(config, "complexity.cyclomatic", 15) ||
|
|
159
158
|
cognitive > threshold(config, "complexity.cognitive", 15) ||
|
|
160
|
-
npath.value > threshold(config, "complexity.npath", 200) ||
|
|
161
159
|
maxNestingDepth(block.codeBody) > 3
|
|
162
160
|
);
|
|
163
161
|
}
|
package/src/dashboard.ts
CHANGED
|
@@ -12,6 +12,7 @@ interface DashboardContext {
|
|
|
12
12
|
host: string;
|
|
13
13
|
port: number;
|
|
14
14
|
projectRoot: string;
|
|
15
|
+
profile?: string;
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
// Per-request projectRoot + scanPath. Sourced from `?projectRoot` and `?path` query parameters and
|
|
@@ -25,9 +26,9 @@ interface DashboardRouteInput {
|
|
|
25
26
|
// Starts a loopback HTTP server. `analyse` is injected (not imported) to avoid a circular import
|
|
26
27
|
// back into `cli.ts`; see `.goat-flow/lessons/verification.md` on the dashboard import cycle.
|
|
27
28
|
// Side effect: opens a listening socket and writes the URL to stdout unless `shouldWriteOutput` is false.
|
|
28
|
-
function startDashboard(host: string, port: number, projectRoot: string, analyse: DashboardAnalyse, shouldWriteOutput = true): void {
|
|
29
|
+
function startDashboard(host: string, port: number, projectRoot: string, analyse: DashboardAnalyse, shouldWriteOutput = true, profile?: string): void {
|
|
29
30
|
assertLoopbackHost(host);
|
|
30
|
-
const context: DashboardContext = { host, port, projectRoot };
|
|
31
|
+
const context: DashboardContext = { host, port, projectRoot, ...(profile !== undefined ? { profile } : {}) };
|
|
31
32
|
const server = createServer((request, response) => handleDashboardRequest(context, analyse, request, response));
|
|
32
33
|
server.listen(port, host, () => {
|
|
33
34
|
if (shouldWriteOutput) {
|
|
@@ -54,7 +55,7 @@ function handleDashboardRequest(context: DashboardContext, analyse: DashboardAna
|
|
|
54
55
|
return;
|
|
55
56
|
}
|
|
56
57
|
if (url.pathname === "/scan") {
|
|
57
|
-
renderDashboardScan(response, dashboardRouteInput(url, context.projectRoot), analyse);
|
|
58
|
+
renderDashboardScan(response, dashboardRouteInput(url, context.projectRoot), analyse, context.profile);
|
|
58
59
|
return;
|
|
59
60
|
}
|
|
60
61
|
if (url.pathname !== "/") {
|
|
@@ -77,16 +78,18 @@ function dashboardRouteInput(url: URL, projectRoot: string): DashboardRouteInput
|
|
|
77
78
|
// chdirs into the caller-requested project root, runs `analyse`, and always restores the previous
|
|
78
79
|
// cwd in `finally` - leaking the chdir would corrupt subsequent requests. The loopback server must
|
|
79
80
|
// keep serving on analyser failure, so the catch reports the error as a rendered fallback page.
|
|
80
|
-
function renderDashboardScan(response: ServerResponse, input: DashboardRouteInput, analyse: DashboardAnalyse): void {
|
|
81
|
+
function renderDashboardScan(response: ServerResponse, input: DashboardRouteInput, analyse: DashboardAnalyse, profile?: string): void {
|
|
81
82
|
const previous = cwd();
|
|
82
83
|
try {
|
|
83
84
|
chdir(input.root);
|
|
84
85
|
const report = analyse({
|
|
85
86
|
paths: [input.scanPath],
|
|
86
87
|
shouldSkipConfig: false,
|
|
88
|
+
...(profile !== undefined ? { profile } : {}),
|
|
87
89
|
format: "html",
|
|
88
90
|
failOn: "none",
|
|
89
91
|
shouldIncludeIgnored: false,
|
|
92
|
+
changedScope: "symbol",
|
|
90
93
|
shouldSkipBaseline: false,
|
|
91
94
|
});
|
|
92
95
|
writeHtmlResponse(response, 200, renderHtml(report, { projectRoot: input.root, scanPath: input.scanPath }));
|
package/src/discovery.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Filesystem discovery, ignore-policy matching, and display-path normalization for deterministic scans.
|
|
2
2
|
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
3
|
-
import { basename, extname, isAbsolute, join, relative } from "node:path";
|
|
4
|
-
import type { AnalysisOptions, Config } from "./types.ts";
|
|
3
|
+
import { basename, dirname, extname, isAbsolute, join, relative } from "node:path";
|
|
4
|
+
import type { AnalysisOptions, Config, IgnoreSource, SkippedPath } from "./types.ts";
|
|
5
5
|
|
|
6
6
|
// `absolutePath` is what `node:fs` operates on; `displayPath` is the project-relative POSIX form
|
|
7
7
|
// embedded in findings and baselines. They must stay aligned - diverging them breaks fingerprint stability.
|
|
@@ -16,15 +16,18 @@ export interface SourceFile {
|
|
|
16
16
|
interface SourceDiscovery {
|
|
17
17
|
files: SourceFile[];
|
|
18
18
|
missingPaths: string[];
|
|
19
|
-
|
|
19
|
+
skipped: Map<string, SkippedPath>;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
// Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths`
|
|
23
|
-
//
|
|
22
|
+
// Public discovery result. `files` are sorted by display path and deduped; `ignoredPaths` (the
|
|
23
|
+
// back-compatible string[] of excluded paths) and `skipped` (the same paths enriched with ignore
|
|
24
|
+
// source + matched pattern) are sorted so reports stay deterministic even when the underlying
|
|
25
|
+
// filesystem returns directory entries in arbitrary order.
|
|
24
26
|
export interface SourceDiscoveryResult {
|
|
25
27
|
files: SourceFile[];
|
|
26
28
|
missingPaths: string[];
|
|
27
29
|
ignoredPaths: string[];
|
|
30
|
+
skipped: SkippedPath[];
|
|
28
31
|
}
|
|
29
32
|
|
|
30
33
|
// A single line from a `.gitignore`. The combination of `isAnchored`, `isDirectoryOnly`, and `hasSlash`
|
|
@@ -42,7 +45,7 @@ interface GitIgnoreRule {
|
|
|
42
45
|
// result so finding ordering and report-path metadata remain stable across runs - this is part of
|
|
43
46
|
// the schema invariant that makes baseline matching reproducible.
|
|
44
47
|
export function discoverSources(projectRoot: string, options: AnalysisOptions, config: Config): SourceDiscoveryResult {
|
|
45
|
-
const discovery: SourceDiscovery = { files: [], missingPaths: [],
|
|
48
|
+
const discovery: SourceDiscovery = { files: [], missingPaths: [], skipped: new Map<string, SkippedPath>() };
|
|
46
49
|
const inputs = options.paths.length > 0 ? options.paths : ["."];
|
|
47
50
|
|
|
48
51
|
for (const input of inputs) {
|
|
@@ -50,12 +53,15 @@ export function discoverSources(projectRoot: string, options: AnalysisOptions, c
|
|
|
50
53
|
}
|
|
51
54
|
|
|
52
55
|
discovery.files.sort((left, right) => left.displayPath.localeCompare(right.displayPath));
|
|
53
|
-
|
|
56
|
+
const skipped = [...discovery.skipped.values()].sort((left, right) => left.path.localeCompare(right.path));
|
|
57
|
+
return { files: uniqueFiles(discovery.files), missingPaths: discovery.missingPaths, ignoredPaths: skipped.map((entry) => entry.path), skipped };
|
|
54
58
|
}
|
|
55
59
|
|
|
56
60
|
// Resolves the input against `node:fs`. Missing inputs go into `missingPaths` so the CLI can
|
|
57
61
|
// report them as diagnostics rather than silently producing no findings. CI output depends on that
|
|
58
|
-
// distinction
|
|
62
|
+
// distinction. An explicitly supplied file still honours config `paths.ignore` (authoritative in
|
|
63
|
+
// every invocation, per ADR-007); default/gitignore stay directory-walk-only (ADR-003), so passing
|
|
64
|
+
// empty gitignore rules here keeps an explicit file scannable unless config excludes it.
|
|
59
65
|
function discoverSourceInput(projectRoot: string, input: string, options: AnalysisOptions, config: Config, discovery: SourceDiscovery): void {
|
|
60
66
|
const absolute = absolutize(projectRoot, input);
|
|
61
67
|
if (!existsSync(absolute)) {
|
|
@@ -64,11 +70,17 @@ function discoverSourceInput(projectRoot: string, input: string, options: Analys
|
|
|
64
70
|
}
|
|
65
71
|
const stats = statSync(absolute);
|
|
66
72
|
if (stats.isFile()) {
|
|
73
|
+
const display = displayPath(projectRoot, absolute);
|
|
74
|
+
const match = classifyIgnore(display, false, options, config, []);
|
|
75
|
+
if (match) {
|
|
76
|
+
discovery.skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
67
79
|
pushSourceFile(projectRoot, absolute, discovery.files);
|
|
68
80
|
return;
|
|
69
81
|
}
|
|
70
82
|
const gitIgnoreRules = options.shouldIncludeIgnored ? [] : gitIgnoreRulesForDirectory(projectRoot, absolute);
|
|
71
|
-
walk(projectRoot, absolute, options, config, discovery.
|
|
83
|
+
walk(projectRoot, absolute, options, config, discovery.skipped, discovery.files, gitIgnoreRules);
|
|
72
84
|
}
|
|
73
85
|
|
|
74
86
|
function walk(
|
|
@@ -76,7 +88,7 @@ function walk(
|
|
|
76
88
|
directory: string,
|
|
77
89
|
options: AnalysisOptions,
|
|
78
90
|
config: Config,
|
|
79
|
-
|
|
91
|
+
skipped: Map<string, SkippedPath>,
|
|
80
92
|
files: SourceFile[],
|
|
81
93
|
gitIgnoreRules: GitIgnoreRule[],
|
|
82
94
|
): void {
|
|
@@ -84,13 +96,14 @@ function walk(
|
|
|
84
96
|
const absolute = join(directory, entry.name);
|
|
85
97
|
const display = displayPath(projectRoot, absolute);
|
|
86
98
|
if (entry.isDirectory() || entry.isFile()) {
|
|
87
|
-
|
|
88
|
-
|
|
99
|
+
const match = classifyIgnore(display, entry.isDirectory(), options, config, gitIgnoreRules);
|
|
100
|
+
if (match) {
|
|
101
|
+
skipped.set(display, { path: display, source: match.source, pattern: match.pattern });
|
|
89
102
|
continue;
|
|
90
103
|
}
|
|
91
104
|
}
|
|
92
105
|
if (entry.isDirectory()) {
|
|
93
|
-
walk(projectRoot, absolute, options, config,
|
|
106
|
+
walk(projectRoot, absolute, options, config, skipped, files, options.shouldIncludeIgnored ? gitIgnoreRules : appendGitIgnoreRules(projectRoot, absolute, gitIgnoreRules));
|
|
94
107
|
} else if (entry.isFile()) {
|
|
95
108
|
pushSourceFile(projectRoot, absolute, files);
|
|
96
109
|
}
|
|
@@ -104,7 +117,7 @@ function pushSourceFile(projectRoot: string, absolutePath: string, files: Source
|
|
|
104
117
|
const name = basename(absolutePath);
|
|
105
118
|
const isScript = ["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(extension);
|
|
106
119
|
const isText =
|
|
107
|
-
["conf", "config", "
|
|
120
|
+
["conf", "config", "env", "ini", "json", "toml", "xml", "yaml", "yml"].includes(extension) ||
|
|
108
121
|
name.startsWith(".env") ||
|
|
109
122
|
isExactSecretTextFile(name);
|
|
110
123
|
if (isScript || isText) {
|
|
@@ -124,28 +137,68 @@ function isDefaultIgnoredDir(path: string): boolean {
|
|
|
124
137
|
return [".git", ".hg", ".svn", ".idea", ".vscode", "build", "cache", "coverage", "dist", "generated", "node_modules", "target", "tmp", "vendor"].includes(first);
|
|
125
138
|
}
|
|
126
139
|
|
|
127
|
-
//
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
140
|
+
// The matched ignore source and the exact pattern that excluded a path. Returned by `classifyIgnore`.
|
|
141
|
+
interface IgnoreMatch {
|
|
142
|
+
source: IgnoreSource;
|
|
143
|
+
pattern: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Single ignore decision shared by the directory walk, explicit-file handling, and `check-ignore`,
|
|
147
|
+
// so there is exactly one glob/ignore implementation. Returns the first matching source with its
|
|
148
|
+
// pattern, or undefined. Evaluation order is default -> gitignore -> config, but config is the
|
|
149
|
+
// authoritative source: it is checked regardless of `--include-ignored` and applies to explicit file
|
|
150
|
+
// operands (which pass empty gitignore rules so default/gitignore cannot match them, per ADR-003).
|
|
151
|
+
function classifyIgnore(display: string, isDirectory: boolean, options: AnalysisOptions, config: Config, gitIgnoreRules: GitIgnoreRule[]): IgnoreMatch | undefined {
|
|
152
|
+
const defaultMatch = defaultIgnoreMatch(display, isDirectory, options, false);
|
|
153
|
+
if (defaultMatch) {
|
|
154
|
+
return defaultMatch;
|
|
132
155
|
}
|
|
133
|
-
if (
|
|
134
|
-
|
|
156
|
+
if (!options.shouldIncludeIgnored) {
|
|
157
|
+
const rule = matchedGitIgnoreRule(gitIgnoreRules, display, isDirectory);
|
|
158
|
+
if (rule) {
|
|
159
|
+
return { source: "gitignore", pattern: rule.pattern };
|
|
160
|
+
}
|
|
135
161
|
}
|
|
136
|
-
|
|
162
|
+
const configPattern = config.ignoredPaths.find((pattern) => pathMatches(pattern, display));
|
|
163
|
+
if (configPattern !== undefined) {
|
|
164
|
+
return { source: "config", pattern: configPattern };
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
137
167
|
}
|
|
138
168
|
|
|
139
|
-
//
|
|
140
|
-
//
|
|
141
|
-
|
|
142
|
-
|
|
169
|
+
// Ignore classification for a single path, sharing the exact engine discovery uses. Powers
|
|
170
|
+
// `check-ignore`: O(1) per path, no analysis. `options.shouldIncludeIgnored` suppresses
|
|
171
|
+
// default/gitignore matches but never config `paths.ignore`.
|
|
172
|
+
export interface PathIgnoreClassification {
|
|
173
|
+
path: string;
|
|
174
|
+
isIgnored: boolean;
|
|
175
|
+
source?: IgnoreSource;
|
|
176
|
+
pattern?: string;
|
|
143
177
|
}
|
|
144
178
|
|
|
145
|
-
//
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
179
|
+
// Classifies one caller-supplied path without analysing it, preserving the shared ignore contract.
|
|
180
|
+
export function classifyPathIgnore(projectRoot: string, input: string, options: AnalysisOptions, config: Config): PathIgnoreClassification {
|
|
181
|
+
const absolute = absolutize(projectRoot, input);
|
|
182
|
+
const display = displayPath(projectRoot, absolute);
|
|
183
|
+
const isDirectory = existsSync(absolute) && statSync(absolute).isDirectory();
|
|
184
|
+
const defaultMatch = defaultIgnoreMatch(display, isDirectory, options, true);
|
|
185
|
+
if (defaultMatch) {
|
|
186
|
+
return { path: display, isIgnored: true, source: defaultMatch.source, pattern: defaultMatch.pattern };
|
|
187
|
+
}
|
|
188
|
+
const ruleDirectory = isDirectory ? absolute : dirname(absolute);
|
|
189
|
+
const gitIgnoreRules = options.shouldIncludeIgnored || !isDirectory ? [] : gitIgnoreRulesForDirectory(projectRoot, ruleDirectory);
|
|
190
|
+
const match = classifyIgnore(display, isDirectory, options, config, gitIgnoreRules);
|
|
191
|
+
return match ? { path: display, isIgnored: true, source: match.source, pattern: match.pattern } : { path: display, isIgnored: false };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Default ignores are directory-walk policy; `check-ignore` also needs parent-dir answers for
|
|
195
|
+
// changed-file prefilters so generated paths under `dist/` agree with what `analyse .` would scan.
|
|
196
|
+
function defaultIgnoreMatch(display: string, isDirectory: boolean, options: AnalysisOptions, includeParentDir: boolean): IgnoreMatch | undefined {
|
|
197
|
+
if (options.shouldIncludeIgnored) {
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
const defaultIgnored = includeParentDir ? isDefaultIgnoredDir(display) : isDirectory && isDefaultIgnoredDir(display);
|
|
201
|
+
return defaultIgnored ? { source: "default", pattern: `${display.split("/")[0] ?? display}/` } : undefined;
|
|
149
202
|
}
|
|
150
203
|
|
|
151
204
|
// Walks .gitignore files top-down from project root to the target directory so child rules can
|
|
@@ -258,14 +311,17 @@ function normalizedGitIgnorePattern(line: string): string {
|
|
|
258
311
|
|
|
259
312
|
// Sequential evaluation, last match wins. This is the same algorithm git uses and is the reason
|
|
260
313
|
// negations later in a file (or in a child `.gitignore`) can reinstate previously ignored paths.
|
|
261
|
-
|
|
314
|
+
// Returns the deciding rule (for source + pattern reporting) when the path ends up ignored.
|
|
315
|
+
function matchedGitIgnoreRule(rules: GitIgnoreRule[], display: string, isDirectory: boolean): GitIgnoreRule | undefined {
|
|
316
|
+
let matched: GitIgnoreRule | undefined;
|
|
262
317
|
let isIgnored = false;
|
|
263
318
|
for (const rule of rules) {
|
|
264
319
|
if (gitIgnoreRuleMatches(rule, display, isDirectory)) {
|
|
265
320
|
isIgnored = !rule.isNegated;
|
|
321
|
+
matched = rule;
|
|
266
322
|
}
|
|
267
323
|
}
|
|
268
|
-
return isIgnored;
|
|
324
|
+
return isIgnored ? matched : undefined;
|
|
269
325
|
}
|
|
270
326
|
|
|
271
327
|
// First rebases the display path against the rule's basePath (rules don't reach outside their
|
package/src/findings-helpers.ts
CHANGED
|
@@ -79,18 +79,54 @@ export function lineOffset(source: string, index: number): number {
|
|
|
79
79
|
return source.slice(0, Math.max(0, index)).split("\n").length - 1;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
// The keyword list is intentionally conservative to avoid flagging prose that starts with `if`.
|
|
82
|
+
// Detector for `waste.commented-out-code`: require a parseable disabled-code shape rather than a
|
|
83
|
+
// bare keyword so prose such as "import cycle" or section headings don't look executable.
|
|
85
84
|
export function isCommentedOutCode(line: string): boolean {
|
|
86
85
|
const trimmed = line.trim();
|
|
87
86
|
if (!trimmed.startsWith("//")) {
|
|
88
87
|
return false;
|
|
89
88
|
}
|
|
90
89
|
const uncommented = trimmed.replace(/^\/\/+\s?/, "");
|
|
91
|
-
if (
|
|
92
|
-
return
|
|
90
|
+
if (isCommentSeparatorOrAnchor(uncommented)) {
|
|
91
|
+
return false;
|
|
93
92
|
}
|
|
93
|
+
return isDisabledDeclaration(uncommented) || isDisabledControlFlow(uncommented) || isDisabledCall(uncommented);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Skips prose examples, labels, search anchors, and section dividers that often begin with code words.
|
|
97
|
+
function isCommentSeparatorOrAnchor(uncommented: string): boolean {
|
|
98
|
+
const text = uncommented.trim();
|
|
99
|
+
return (
|
|
100
|
+
text === "" ||
|
|
101
|
+
/^[-=*_#]{3,}$/.test(text) ||
|
|
102
|
+
/^[A-Za-z_$][A-Za-z0-9_$]*\s*:\s*['"`[{]/.test(text) ||
|
|
103
|
+
/\b(?:search|grep|anchor|example|for example|e\.g\.)\s*:/.test(text) ||
|
|
104
|
+
/^(?!(?:if|for|while|switch)\b)[A-Za-z_$][A-Za-z0-9_$]*\s+\([^;{}]*[A-Za-z][^;{}]*\)$/.test(text) ||
|
|
105
|
+
/^[A-Z][A-Za-z0-9_$]*(?:\s|\s*\([^)]*\)$)/.test(text)
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Declarations must carry their syntactic partner (`=`, `{`, `from`, etc.) to count as disabled code.
|
|
110
|
+
function isDisabledDeclaration(uncommented: string): boolean {
|
|
111
|
+
return (
|
|
112
|
+
/^(?:const|let|var)\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
|
|
113
|
+
/^(?:async\s+)?function\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\(/.test(uncommented) ||
|
|
114
|
+
/^class\s+[A-Za-z_$][A-Za-z0-9_$]*(?:\s+extends\s+[A-Za-z_$][A-Za-z0-9_$]*)?\s*\{?/.test(uncommented) ||
|
|
115
|
+
/^interface\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
|
|
116
|
+
/^type\s+[A-Za-z_$][A-Za-z0-9_$]*\s*=/.test(uncommented) ||
|
|
117
|
+
/^enum\s+[A-Za-z_$][A-Za-z0-9_$]*\s*\{?/.test(uncommented) ||
|
|
118
|
+
/^import\s+(?:["'][^"']+["']|.+\s+from\s+["'][^"']+["'])/.test(uncommented) ||
|
|
119
|
+
/^export\s+(?:\{|\*|(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\b)/.test(uncommented)
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Control-flow comments need real syntax such as parentheses or an expression after `return`/`throw`.
|
|
124
|
+
function isDisabledControlFlow(uncommented: string): boolean {
|
|
125
|
+
return /^(?:if|for|while|switch)\s*\(/.test(uncommented) || /^(?:return|throw|await)\s+\S/.test(uncommented);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Keep single-line disabled calls; heading/prose guards above filter labels such as `Rules (...)`.
|
|
129
|
+
function isDisabledCall(uncommented: string): boolean {
|
|
94
130
|
return /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)?\s*\([^)]*\);?$/.test(uncommented);
|
|
95
131
|
}
|
|
96
132
|
|
package/src/findings.ts
CHANGED
|
@@ -39,7 +39,17 @@ function makeFinding(input: FindingInput): Finding {
|
|
|
39
39
|
...(input.remediation ? { remediation: input.remediation } : {}),
|
|
40
40
|
metadata: input.metadata ?? {},
|
|
41
41
|
fingerprint,
|
|
42
|
+
stableIdentity: stableIdentityFor(input),
|
|
42
43
|
};
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
// Stable, line-insensitive identity for external diff tooling; fingerprint remains line-sensitive.
|
|
47
|
+
function stableIdentityFor(input: FindingInput): string {
|
|
48
|
+
const symbolOrMessage = input.symbol && input.symbol.length > 0 ? input.symbol : input.message;
|
|
49
|
+
return createHash("sha256")
|
|
50
|
+
.update([input.ruleId, input.filePath, symbolOrMessage].join("\0"))
|
|
51
|
+
.digest("hex")
|
|
52
|
+
.slice(0, 16);
|
|
53
|
+
}
|
|
54
|
+
|
|
45
55
|
export { makeFinding };
|
|
@@ -3,11 +3,10 @@
|
|
|
3
3
|
// reports `docs.fixture-purpose-missing` for each candidate without a nearby explanation comment.
|
|
4
4
|
import { type FunctionBlock, setupLineCount } from "./blocks.ts";
|
|
5
5
|
import { type CommentRecord } from "./comment-scanner.ts";
|
|
6
|
-
import { threshold } from "./config.ts";
|
|
7
6
|
import { type SourceFile } from "./discovery.ts";
|
|
8
7
|
import { makeFinding } from "./findings.ts";
|
|
9
8
|
import { isFixtureLikePath, isTestPath } from "./project-rules.ts";
|
|
10
|
-
import type {
|
|
9
|
+
import type { Finding } from "./types.ts";
|
|
11
10
|
|
|
12
11
|
// Below 12 lines, a fixture is short enough to read at a glance - requiring a purpose header
|
|
13
12
|
// would just be noise; above this threshold, the next reader needs the intent spelled out.
|
|
@@ -34,18 +33,17 @@ export interface FixturePurposeInput {
|
|
|
34
33
|
lines: string[];
|
|
35
34
|
comments: CommentRecord[];
|
|
36
35
|
blocks: FunctionBlock[];
|
|
37
|
-
config: Config;
|
|
38
36
|
findings: Finding[];
|
|
39
37
|
}
|
|
40
38
|
|
|
41
39
|
// Test/fixture paths only - gated up front so production source never reports fixture-purpose
|
|
42
40
|
// findings. Reports the stable `docs.fixture-purpose-missing` finding for each candidate.
|
|
43
41
|
export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
|
|
44
|
-
const { file, source, codeSource, lines, comments, blocks,
|
|
42
|
+
const { file, source, codeSource, lines, comments, blocks, findings } = input;
|
|
45
43
|
if (!isTestPath(file.displayPath) && !isFixtureLikePath(file.displayPath)) {
|
|
46
44
|
return;
|
|
47
45
|
}
|
|
48
|
-
for (const candidate of fixturePurposeCandidates(source, codeSource, blocks
|
|
46
|
+
for (const candidate of fixturePurposeCandidates(source, codeSource, blocks)) {
|
|
49
47
|
if (hasFixturePurposeComment(lines, comments, candidate.line)) {
|
|
50
48
|
continue;
|
|
51
49
|
}
|
|
@@ -71,7 +69,7 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
|
|
|
71
69
|
|
|
72
70
|
// Three candidate kinds collected in one pass: template-literal fixtures, generated array fixtures,
|
|
73
71
|
// and test setup blocks. `occupiedLines` tracks the first two so the third doesn't double-report.
|
|
74
|
-
function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]
|
|
72
|
+
function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]): FixturePurposeCandidate[] {
|
|
75
73
|
if (!hasFixturePurposeCandidateSignal(codeSource, blocks)) {
|
|
76
74
|
return [];
|
|
77
75
|
}
|
|
@@ -96,7 +94,7 @@ function fixturePurposeCandidates(source: string, codeSource: string, blocks: Fu
|
|
|
96
94
|
}
|
|
97
95
|
});
|
|
98
96
|
|
|
99
|
-
for (const candidate of fixtureTestBlockCandidates(blocks,
|
|
97
|
+
for (const candidate of fixtureTestBlockCandidates(blocks, occupiedLines)) {
|
|
100
98
|
pushUniqueFixturePurposeCandidate(candidates, seen, candidate);
|
|
101
99
|
}
|
|
102
100
|
|
|
@@ -178,14 +176,14 @@ function generatedFixtureCandidate(rawLine: string, codeLine: string, lineNumber
|
|
|
178
176
|
|
|
179
177
|
// Test blocks with high setup-line counts AND a fixture-shape signal. Excludes blocks whose setup
|
|
180
178
|
// already produced a template-literal or generated-array candidate at the same line.
|
|
181
|
-
function fixtureTestBlockCandidates(blocks: FunctionBlock[],
|
|
179
|
+
function fixtureTestBlockCandidates(blocks: FunctionBlock[], occupiedLines: Set<number>): FixturePurposeCandidate[] {
|
|
182
180
|
const candidates: FixturePurposeCandidate[] = [];
|
|
183
181
|
for (const block of blocks) {
|
|
184
182
|
if (!block.isTest || fixtureLineInsideBlock(block, occupiedLines)) {
|
|
185
183
|
continue;
|
|
186
184
|
}
|
|
187
185
|
const setupLines = setupLineCount(block.codeBody);
|
|
188
|
-
if (setupLines <=
|
|
186
|
+
if (setupLines <= FIXTURE_PURPOSE_MIN_LINES || !hasFixtureSetupSignal(block.codeBody)) {
|
|
189
187
|
continue;
|
|
190
188
|
}
|
|
191
189
|
candidates.push({
|
|
@@ -9,6 +9,8 @@ export const SECURITY_EXPANSION_RISKY_RULE_IDS = [
|
|
|
9
9
|
"security.open-redirect-candidate",
|
|
10
10
|
"security.path-traversal-candidate",
|
|
11
11
|
"security.ssrf-candidate",
|
|
12
|
+
"security.unsafe-deserialization",
|
|
13
|
+
"security.xxe-candidate",
|
|
12
14
|
] as const;
|
|
13
15
|
|
|
14
16
|
export const SECURITY_EXPANSION_RULE_QUALITY_DOCTRINE = [
|
|
@@ -129,4 +131,30 @@ export const SECURITY_EXPANSION_RULE_QUALITY_DOCTRINE = [
|
|
|
129
131
|
falsePositiveEscapeHatch: "require an external-input token inside the same network request call segment",
|
|
130
132
|
fingerprintStability: "anchor to the request call line with source and sink kinds only in metadata",
|
|
131
133
|
},
|
|
134
|
+
{
|
|
135
|
+
ruleId: "security.unsafe-deserialization",
|
|
136
|
+
signalSource: "syntax-only AST flow scan for external input reaching unsafe deserialization and dynamic code-loading sinks",
|
|
137
|
+
expectedPillar: "security",
|
|
138
|
+
expectedSeverity: "warning",
|
|
139
|
+
expectedConfidence: "medium",
|
|
140
|
+
fixtureCategories: ["valid", "invalid", "noisy-valid", "missing-invalid"],
|
|
141
|
+
invalidFixture: "request body, argv, or environment input passed to unserialize, yaml.load, vm execution, eval, or Function",
|
|
142
|
+
noisyValidFixture: "safe schema-bound YAML loads, fixed literals, and prose strings with deserialization examples",
|
|
143
|
+
missingInvalidFixture: "external serialized data remains reported when safe YAML and fixed literal loads are nearby",
|
|
144
|
+
falsePositiveEscapeHatch: "require local external-input flow and accept explicit safe YAML schema evidence",
|
|
145
|
+
fingerprintStability: "anchor to the unsafe sink line with source and sink kinds only in metadata",
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
ruleId: "security.xxe-candidate",
|
|
149
|
+
signalSource: "syntax-only AST flow scan for external XML reaching parsers with entity expansion enabled",
|
|
150
|
+
expectedPillar: "security",
|
|
151
|
+
expectedSeverity: "warning",
|
|
152
|
+
expectedConfidence: "medium",
|
|
153
|
+
fixtureCategories: ["valid", "invalid", "noisy-valid", "missing-invalid"],
|
|
154
|
+
invalidFixture: "request XML passed to libxmljs or fast-xml-parser calls with entity expansion enabled",
|
|
155
|
+
noisyValidFixture: "XML parser calls with entity expansion disabled and prose strings with XML examples",
|
|
156
|
+
missingInvalidFixture: "entity-expanding XML parse remains reported when non-expanding parser calls are nearby",
|
|
157
|
+
falsePositiveEscapeHatch: "require both external XML flow and local parser options that enable entity expansion",
|
|
158
|
+
fingerprintStability: "anchor to the XML parse line with source and sink kinds only in metadata",
|
|
159
|
+
},
|
|
132
160
|
] as const;
|
package/src/init-config.ts
CHANGED
|
@@ -204,6 +204,9 @@ function renderAllowlistsSection(): string {
|
|
|
204
204
|
" # default when present; an empty list disables that rule's blacklist branch.",
|
|
205
205
|
" # Default: [process, handle, doit, run, execute, manage]",
|
|
206
206
|
" # bannedGenericNames: [process, handle, doit, run, execute, manage]",
|
|
207
|
+
" # Exact public/CLI/DTO boolean names accepted by naming.boolean-prefix.",
|
|
208
|
+
" # Default: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
|
|
209
|
+
" # acceptedBooleanNames: [all, apply, check, dev, enabled, force, fresh, harness, json, ok, verbose, yes]",
|
|
207
210
|
" # Accepted prefixes for boolean identifiers. Names without one of these",
|
|
208
211
|
" # prefixes trigger naming.boolean-prefix.",
|
|
209
212
|
" # Default: [is, has, can, should, does, did, was, will, may, in, scan, supports, requires, allow, check, enable, exclude, include, omit, skip, with, without]",
|
package/src/line-rules.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
|
|
5
5
|
// invoked by the cli orchestrator before/after this module so the stable per-line emission order
|
|
6
6
|
// stays a single contract.
|
|
7
|
+
import { ruleSeverity } from "./config.ts";
|
|
7
8
|
import { type SourceFile } from "./discovery.ts";
|
|
8
9
|
import { makeFinding } from "./findings.ts";
|
|
9
10
|
import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
|
|
@@ -256,13 +257,14 @@ function pushStringTimerFinding(context: LineRuleContext): void {
|
|
|
256
257
|
}
|
|
257
258
|
}
|
|
258
259
|
|
|
259
|
-
// Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks
|
|
260
|
-
//
|
|
261
|
-
//
|
|
260
|
+
// Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks use
|
|
261
|
+
// `rawPatternStartsInCode` to confirm a match starts in real code, not inside a comment. Each finding's
|
|
262
|
+
// severity is resolved through `ruleSeverity`, so a project's per-rule `severity:` override applies.
|
|
263
|
+
// Reports each matching rule's stable, line-anchored finding; the descriptor severity is the default.
|
|
262
264
|
function pushPatternCheckFindings(context: LineRuleContext): void {
|
|
263
265
|
for (const check of context.codeChecks) {
|
|
264
266
|
if (check.pattern.test(context.codeLine)) {
|
|
265
|
-
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: check.severity, pillar: check.pillar }));
|
|
267
|
+
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
|
|
266
268
|
}
|
|
267
269
|
}
|
|
268
270
|
for (const check of context.literalChecks) {
|
|
@@ -270,7 +272,7 @@ function pushPatternCheckFindings(context: LineRuleContext): void {
|
|
|
270
272
|
continue;
|
|
271
273
|
}
|
|
272
274
|
if (rawPatternStartsInCode(context.line, context.codeLine, check.globalPattern ?? check.pattern)) {
|
|
273
|
-
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: check.severity, pillar: check.pillar }));
|
|
275
|
+
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
|
|
274
276
|
}
|
|
275
277
|
}
|
|
276
278
|
}
|
package/src/naming-pushers.ts
CHANGED
|
@@ -46,7 +46,7 @@ export function pushNegativeBooleanAt(file: SourceFile, line: number, name: stri
|
|
|
46
46
|
* `naming.boolean-prefix` finding.
|
|
47
47
|
*/
|
|
48
48
|
export function pushBooleanPrefixAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
|
|
49
|
-
if (hasBooleanPrefix(name, config.booleanPrefixes) || isAcceptedBooleanStateName(name)) {
|
|
49
|
+
if (hasBooleanPrefix(name, config.booleanPrefixes) || isAcceptedBooleanStateName(name) || isAcceptedContractBooleanName(name, config, surface)) {
|
|
50
50
|
return;
|
|
51
51
|
}
|
|
52
52
|
findings.push(
|
|
@@ -67,13 +67,19 @@ export function pushBooleanPrefixAt(file: SourceFile, line: number, name: string
|
|
|
67
67
|
|
|
68
68
|
const ACCEPTED_BOOLEAN_STATE_NAMES = new Set(["acknowledged", "exists", "validated", "detected", "resolved", "selected", "installed"]);
|
|
69
69
|
const ACCEPTED_BOOLEAN_STATE_SUFFIXES = ["Available", "Required", "Validated", "Detected", "Resolved", "Selected", "Installed"];
|
|
70
|
-
|
|
71
70
|
// Some booleans are state adjectives rather than predicate phrases. Keep this list deliberately
|
|
72
|
-
// narrow so vague names such as `ready` or `enabled` still get the maintainability prompt.
|
|
71
|
+
// narrow so vague local names such as `ready` or `enabled` still get the maintainability prompt.
|
|
73
72
|
function isAcceptedBooleanStateName(name: string): boolean {
|
|
74
73
|
return ACCEPTED_BOOLEAN_STATE_NAMES.has(name.toLowerCase()) || ACCEPTED_BOOLEAN_STATE_SUFFIXES.some((suffix) => name.endsWith(suffix));
|
|
75
74
|
}
|
|
76
75
|
|
|
76
|
+
// CLI option bags, DTOs, and schema fields often must expose exact external key names such as
|
|
77
|
+
// `verbose` or `ok`. Limit the exact-name exemption to contract fields so ordinary locals still
|
|
78
|
+
// need predicate-style names.
|
|
79
|
+
function isAcceptedContractBooleanName(name: string, config: Config, surface: NamingSurface): boolean {
|
|
80
|
+
return surface === "interface-field" && config.acceptedBooleanNames.has(name.toLowerCase());
|
|
81
|
+
}
|
|
82
|
+
|
|
77
83
|
/*
|
|
78
84
|
* Allows the standard `i`, `j`, `k` loop counters and anything on `acceptedAbbreviations`. Reports
|
|
79
85
|
* `naming.short-variable` for any other one or two character name as a stable advisory finding.
|
|
@@ -131,18 +137,41 @@ export function pushIdentifierQualityAt(file: SourceFile, line: number, name: st
|
|
|
131
137
|
}
|
|
132
138
|
|
|
133
139
|
// Returns `"generic"` for low-information names from the configured set, `"numbered"` for
|
|
134
|
-
// `foo1` / `
|
|
135
|
-
//
|
|
140
|
+
// numbered placeholder stems such as `foo1` / `mock2`, or undefined when the name is acceptable.
|
|
141
|
+
// Domain tokens with meaningful digits (`adr020`, `step0`, `V110`) are not placeholder names.
|
|
136
142
|
function identifierQualityVariant(name: string, placeholderNames: Set<string>): string | undefined {
|
|
137
143
|
if (placeholderNames.has(name.toLowerCase())) {
|
|
138
144
|
return "generic";
|
|
139
145
|
}
|
|
140
|
-
|
|
146
|
+
const numbered = name.match(/^([A-Za-z_$]+)[0-9]+$/);
|
|
147
|
+
const numberedStem = numbered?.[1]?.toLowerCase() ?? "";
|
|
148
|
+
if (numberedStem && (placeholderNames.has(numberedStem) || NUMBERED_PLACEHOLDER_STEMS.has(numberedStem))) {
|
|
141
149
|
return "numbered";
|
|
142
150
|
}
|
|
143
151
|
return undefined;
|
|
144
152
|
}
|
|
145
153
|
|
|
154
|
+
const NUMBERED_PLACEHOLDER_STEMS = new Set([
|
|
155
|
+
"arg",
|
|
156
|
+
"bar",
|
|
157
|
+
"baz",
|
|
158
|
+
"data",
|
|
159
|
+
"fixture",
|
|
160
|
+
"foo",
|
|
161
|
+
"item",
|
|
162
|
+
"mock",
|
|
163
|
+
"obj",
|
|
164
|
+
"object",
|
|
165
|
+
"param",
|
|
166
|
+
"stub",
|
|
167
|
+
"temp",
|
|
168
|
+
"test",
|
|
169
|
+
"thing",
|
|
170
|
+
"tmp",
|
|
171
|
+
"value",
|
|
172
|
+
"var",
|
|
173
|
+
]);
|
|
174
|
+
|
|
146
175
|
const BOOLEAN_PREFIX_REGEX_CACHE = new WeakMap<Set<string>, RegExp | null>();
|
|
147
176
|
|
|
148
177
|
// Tests the cached prefix regex from `booleanPrefixRegex`. A null regex (empty prefix set) is
|