@blundergoat/gruff-ts 0.1.1 → 0.3.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/CHANGELOG.md +55 -19
- package/README.md +103 -35
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +60 -3
- package/docs/dashboard.md +7 -0
- package/docs/output-formats.md +11 -1
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +12 -11
- package/docs/reports-and-ci.md +5 -2
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +20 -4
- package/scripts/preflight-checks.sh +4 -41
- package/src/analyser.ts +47 -34
- package/src/blocks.ts +82 -75
- 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 +209 -51
- package/src/comment-rules.ts +4 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +311 -428
- package/src/constants.ts +10 -2
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +8 -5
- package/src/dead-code-rules.ts +60 -14
- package/src/discovery.ts +88 -32
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +58 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +94 -31
- package/src/line-rules.ts +58 -4
- package/src/naming-pushers.ts +42 -7
- package/src/pillar-summary.ts +129 -0
- package/src/profiles.ts +232 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +2 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -397
- package/src/rule-list.ts +85 -1
- package/src/rules.ts +28 -27
- package/src/safety-rules.ts +22 -7
- package/src/scoring.ts +78 -8
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +140 -7
- package/src/test-fixtures.ts +59 -13
- package/src/types.ts +108 -5
package/src/constants.ts
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
// Shared release constants that keep CLI, reports, and rule catalogue output in sync.
|
|
2
|
-
const VERSION = "0.
|
|
2
|
+
const VERSION = "0.3.0";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
/*
|
|
5
|
+
* Threshold at which the `analyse` text renderer appends a one-line pointer to `gruff-ts summary`.
|
|
6
|
+
* Below 50 a flat list is still browsable; above 50 the operator hits scroll fatigue and needs the
|
|
7
|
+
* per-rule digest. Calibrated against the gruff-ts self-scan (~8 findings) and the goat-flow scan
|
|
8
|
+
* in 2026-05-25 feedback (1643 findings) - the threshold earns its keep at the cross-over.
|
|
9
|
+
*/
|
|
10
|
+
const OUTPUT_VOLUME_HINT_THRESHOLD = 50;
|
|
11
|
+
|
|
12
|
+
export { OUTPUT_VOLUME_HINT_THRESHOLD, VERSION };
|
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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Loopback dashboard HTTP surface that renders live analyzer reports without exposing remote scans.
|
|
2
2
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
3
3
|
import { chdir, cwd, stdout } from "node:process";
|
|
4
|
-
import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-
|
|
4
|
+
import { dashboardErrorHtml, dashboardHomeHtml, renderHtml } from "./report-html.ts";
|
|
5
5
|
import type { AnalysisOptions, AnalysisReport } from "./types.ts";
|
|
6
6
|
|
|
7
7
|
type DashboardAnalyse = (options: AnalysisOptions) => AnalysisReport;
|
|
@@ -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/dead-code-rules.ts
CHANGED
|
@@ -31,29 +31,75 @@ export function analyseDeadCode(file: SourceFile, source: string, findings: Find
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
/*
|
|
35
|
+
* Line-by-line walker that resets the terminator flag at every `case:` / `default:` because
|
|
36
|
+
* dead-code detection must respect control-flow boundaries. Each line is walked once in source
|
|
37
|
+
* order; the per-line state-machine update is extracted into `advanceUnreachableState` to keep
|
|
38
|
+
* this loop's branching low. Reports `waste.unreachable-code` with stable, deterministic
|
|
39
|
+
* fingerprint anchors so baselines and report snapshots round-trip without churn.
|
|
40
|
+
*/
|
|
37
41
|
export function analyseUnreachable(file: SourceFile, source: string, findings: Finding[]): void {
|
|
38
|
-
let
|
|
39
|
-
let isInConditionalBranch = false;
|
|
42
|
+
let state: UnreachableScanState = { didPreviousTerminate: false, conditionalParenDepth: 0, isConsequentPending: false };
|
|
40
43
|
source.split(/\r?\n/).forEach((line, index) => {
|
|
41
44
|
const trimmed = line.trim();
|
|
42
45
|
const branchLabel = isBranchLabel(trimmed);
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
if (isUnreachableStatement(trimmed, didPreviousTerminate, branchLabel)) {
|
|
46
|
+
const didPriorTerminate = branchLabel ? false : state.didPreviousTerminate;
|
|
47
|
+
if (isUnreachableStatement(trimmed, didPriorTerminate, branchLabel)) {
|
|
47
48
|
findings.push(finding({ ruleId: "waste.unreachable-code", message: "Statement appears after a terminating statement.", file, line: index + 1, severity: "warning", pillar: "maintainability" }));
|
|
48
49
|
}
|
|
49
|
-
|
|
50
|
-
// `if (x)\n return y;\nnextLine` - `nextLine` runs when `x` is falsy. Tracking the prior line's
|
|
51
|
-
// conditional-opener shape suppresses the false positive on compact guard clauses.
|
|
52
|
-
didPreviousTerminate = isTerminatingStatement(trimmed) && !isInConditionalBranch;
|
|
53
|
-
isInConditionalBranch = isBracelessConditionalOpener(trimmed);
|
|
50
|
+
state = advanceUnreachableState(trimmed, { ...state, didPreviousTerminate: didPriorTerminate });
|
|
54
51
|
});
|
|
55
52
|
}
|
|
56
53
|
|
|
54
|
+
// Working state for the unreachable walker. Tracking these three fields together keeps the
|
|
55
|
+
// state-machine transitions explicit and lets the per-line update return a fresh value rather
|
|
56
|
+
// than mutating shared scope.
|
|
57
|
+
interface UnreachableScanState {
|
|
58
|
+
didPreviousTerminate: boolean;
|
|
59
|
+
conditionalParenDepth: number;
|
|
60
|
+
isConsequentPending: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/*
|
|
64
|
+
* Computes the next walker state from the current line. The conditional-context check (inside the
|
|
65
|
+
* predicate parens, or on the consequent line) drives whether a terminator on this line counts as
|
|
66
|
+
* unconditional. Branching is intentional here because the multi-line predicate has three discrete
|
|
67
|
+
* cases: opener line, inside-predicate continuation, and "no longer in a predicate." Splitting
|
|
68
|
+
* them inline would invariably reintroduce the npath the wrapper was trying to avoid.
|
|
69
|
+
*/
|
|
70
|
+
function advanceUnreachableState(trimmed: string, state: UnreachableScanState): UnreachableScanState {
|
|
71
|
+
const isInConditionalBranch = state.conditionalParenDepth > 0 || state.isConsequentPending;
|
|
72
|
+
const didPreviousTerminate = isTerminatingStatement(trimmed) && !isInConditionalBranch;
|
|
73
|
+
if (isBracelessConditionalOpener(trimmed)) {
|
|
74
|
+
const balance = parenBalance(trimmed);
|
|
75
|
+
const conditionalParenDepth = balance > 0 ? balance : 0;
|
|
76
|
+
return { didPreviousTerminate, conditionalParenDepth, isConsequentPending: conditionalParenDepth === 0 };
|
|
77
|
+
}
|
|
78
|
+
if (state.conditionalParenDepth > 0) {
|
|
79
|
+
const conditionalParenDepth = Math.max(0, state.conditionalParenDepth + parenBalance(trimmed));
|
|
80
|
+
return { didPreviousTerminate, conditionalParenDepth, isConsequentPending: conditionalParenDepth === 0 };
|
|
81
|
+
}
|
|
82
|
+
return { didPreviousTerminate, conditionalParenDepth: 0, isConsequentPending: false };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Net paren balance for one line of masked code (opens minus closes). String-literal parens are
|
|
86
|
+
// already blanked upstream by the masker, so the count is reliable for predicate-depth tracking.
|
|
87
|
+
function parenBalance(text: string): number {
|
|
88
|
+
return countChar(text, "(") - countChar(text, ")");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Counts a single character's occurrences without allocating a match array. Used to balance parens
|
|
92
|
+
// across the lines of a multi-line conditional predicate in `analyseUnreachable`.
|
|
93
|
+
function countChar(text: string, character: string): number {
|
|
94
|
+
let count = 0;
|
|
95
|
+
for (const char of text) {
|
|
96
|
+
if (char === character) {
|
|
97
|
+
count += 1;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return count;
|
|
101
|
+
}
|
|
102
|
+
|
|
57
103
|
// Detects single-line conditional/loop openers that begin a one-statement body (no `{`). The next
|
|
58
104
|
// line is the conditional body, so any terminator there is conditional rather than unconditional.
|
|
59
105
|
function isBracelessConditionalOpener(trimmed: string): boolean {
|
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/doc-rules.ts
CHANGED
|
@@ -50,9 +50,9 @@ export function exportedDeclarations(source: string, codeSource: string): Export
|
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
/*
|
|
53
|
-
* Skips functions and interfaces - those have dedicated rules (`docs.missing-function-doc`,
|
|
54
|
-
* `docs.missing-
|
|
55
|
-
* classes/types/enums without a leading JSDoc-style block comment.
|
|
53
|
+
* Skips functions and interfaces - those have dedicated rules (`docs.missing-exported-function-doc`,
|
|
54
|
+
* `docs.missing-internal-function-doc`, `docs.missing-interface-doc`). Reports the stable
|
|
55
|
+
* `docs.missing-public-doc` finding for classes/types/enums without a leading JSDoc-style block comment.
|
|
56
56
|
*/
|
|
57
57
|
export function pushMissingPublicDocFinding(file: SourceFile, source: string, declaration: ExportedDeclaration, findings: Finding[]): void {
|
|
58
58
|
if (declaration.kind === "function" || declaration.kind === "interface") {
|
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
|
|
|
@@ -106,3 +142,20 @@ export function isGenericName(name: string, bannedNames: Set<string>): boolean {
|
|
|
106
142
|
export function escapeRegex(source: string): string {
|
|
107
143
|
return source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
108
144
|
}
|
|
145
|
+
|
|
146
|
+
/*
|
|
147
|
+
* Per-rule severity tally for the `summary` Top-N rules block. Walks the findings once and returns
|
|
148
|
+
* a deterministic Map keyed by ruleId carrying total / error / warning / advisory counts. Lets the
|
|
149
|
+
* renderer surface "412 (0 err / 0 warn / 412 adv)" rows without re-scanning findings per row. The
|
|
150
|
+
* count shape mirrors the `summary` schema invariant - total must equal err + warn + adv.
|
|
151
|
+
*/
|
|
152
|
+
export function countRuleSeverities(findings: Finding[]): Map<string, { total: number; error: number; warning: number; advisory: number }> {
|
|
153
|
+
const counts = new Map<string, { total: number; error: number; warning: number; advisory: number }>();
|
|
154
|
+
for (const finding of findings) {
|
|
155
|
+
const entry = counts.get(finding.ruleId) ?? { total: 0, error: 0, warning: 0, advisory: 0 };
|
|
156
|
+
entry.total += 1;
|
|
157
|
+
entry[finding.severity] += 1;
|
|
158
|
+
counts.set(finding.ruleId, entry);
|
|
159
|
+
}
|
|
160
|
+
return counts;
|
|
161
|
+
}
|
|
@@ -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;
|