midnight-shield 0.0.0-stage → 0.4.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 +68 -0
- package/LICENSE +21 -0
- package/README.md +382 -2
- package/action.yml +56 -0
- package/dist/src/analyzer.d.ts +97 -0
- package/dist/src/analyzer.js +895 -0
- package/dist/src/ast.d.ts +211 -0
- package/dist/src/ast.js +2 -0
- package/dist/src/browser.d.ts +3 -0
- package/dist/src/browser.js +5 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +336 -0
- package/dist/src/config.d.ts +26 -0
- package/dist/src/config.js +87 -0
- package/dist/src/fixes.d.ts +10 -0
- package/dist/src/fixes.js +45 -0
- package/dist/src/index.d.ts +10 -0
- package/dist/src/index.js +10 -0
- package/dist/src/lexer.d.ts +18 -0
- package/dist/src/lexer.js +135 -0
- package/dist/src/linter.d.ts +67 -0
- package/dist/src/linter.js +137 -0
- package/dist/src/node.d.ts +13 -0
- package/dist/src/node.js +98 -0
- package/dist/src/parser.d.ts +2 -0
- package/dist/src/parser.js +791 -0
- package/dist/src/plugin-loader.d.ts +3 -0
- package/dist/src/plugin-loader.js +31 -0
- package/dist/src/plugins.d.ts +34 -0
- package/dist/src/plugins.js +59 -0
- package/dist/src/reporters.d.ts +22 -0
- package/dist/src/reporters.js +286 -0
- package/dist/src/rules.d.ts +23 -0
- package/dist/src/rules.js +104 -0
- package/dist/src/sdk.d.ts +6 -0
- package/dist/src/sdk.js +130 -0
- package/dist/src/walk.d.ts +28 -0
- package/dist/src/walk.js +110 -0
- package/docs/rules/MS000.md +7 -0
- package/docs/rules/MS001.md +46 -0
- package/docs/rules/MS002.md +42 -0
- package/docs/rules/MS003.md +41 -0
- package/docs/rules/MS004.md +41 -0
- package/docs/rules/MS005.md +32 -0
- package/docs/rules/MS006.md +17 -0
- package/docs/rules/MS007.md +44 -0
- package/docs/rules/MS008.md +59 -0
- package/docs/rules/MS009.md +45 -0
- package/docs/rules/MS010.md +46 -0
- package/docs/rules/MS101.md +32 -0
- package/docs/rules/MS102.md +31 -0
- package/package.json +67 -4
- package/skills/midnight-shield/SKILL.md +67 -0
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Safe automatic fixes. Only fixes that cannot change what a contract does, or
|
|
2
|
+
// the values it stores, are offered. Fixes that change hashes or commitments
|
|
3
|
+
// (for example adding a domain tag) would change on-chain values and break
|
|
4
|
+
// existing deployments, so they are left to the developer (or the AI skill).
|
|
5
|
+
export const DEFAULT_PRAGMA = "pragma language_version >= 0.28.0;";
|
|
6
|
+
/** MS006: insert a pragma after any leading comments and blank lines. */
|
|
7
|
+
export function pragmaFix(source, pragma = DEFAULT_PRAGMA) {
|
|
8
|
+
const lines = source.split(/\r?\n/);
|
|
9
|
+
let i = 0;
|
|
10
|
+
let inBlock = false;
|
|
11
|
+
for (; i < lines.length; i++) {
|
|
12
|
+
const t = lines[i].trim();
|
|
13
|
+
if (inBlock) {
|
|
14
|
+
if (t.includes("*/"))
|
|
15
|
+
inBlock = false;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (t === "" || t.startsWith("//"))
|
|
19
|
+
continue;
|
|
20
|
+
if (t.startsWith("/*")) {
|
|
21
|
+
if (!t.includes("*/"))
|
|
22
|
+
inBlock = true;
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
// put it right after the leading comment block (skip trailing blank lines back)
|
|
28
|
+
let at = i;
|
|
29
|
+
while (at > 0 && lines[at - 1].trim() === "")
|
|
30
|
+
at--;
|
|
31
|
+
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
|
32
|
+
return { line: at + 1, insert: pragma + eol };
|
|
33
|
+
}
|
|
34
|
+
/** Apply edits to a source string. Edits are applied bottom-up so line numbers stay valid. */
|
|
35
|
+
export function applyEdits(source, edits) {
|
|
36
|
+
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
|
37
|
+
const lines = source.split(/\r?\n/);
|
|
38
|
+
const sorted = [...edits].sort((a, b) => b.line - a.line);
|
|
39
|
+
for (const e of sorted) {
|
|
40
|
+
const idx = Math.max(0, Math.min(lines.length, e.line - 1));
|
|
41
|
+
const text = e.insert.endsWith(eol) ? e.insert.slice(0, -eol.length) : e.insert;
|
|
42
|
+
lines.splice(idx, 0, ...text.split(/\r?\n/));
|
|
43
|
+
}
|
|
44
|
+
return lines.join(eol);
|
|
45
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { lintSource, mapDisclosures, createBaseline, type Finding, type LintOptions, type DisclosureEntry, type BaselineFile } from "./linter.js";
|
|
2
|
+
export { lintFiles, mapDisclosuresInFiles, listTargetFiles, findCompactFiles, fileImportResolver, readBaseline, globToRegExp } from "./node.js";
|
|
3
|
+
export { loadConfig, validateConfig, DEFAULT_CONFIG, type Config } from "./config.js";
|
|
4
|
+
export { loadPlugins } from "./plugin-loader.js";
|
|
5
|
+
export { type CustomRule, type RuleContext, type PluginReport } from "./plugins.js";
|
|
6
|
+
export { walkProgram, calleeName, type Visitor, type WalkContext } from "./walk.js";
|
|
7
|
+
export { applyEdits, pragmaFix, type TextEdit } from "./fixes.js";
|
|
8
|
+
export { parse } from "./parser.js";
|
|
9
|
+
export { RULES, RULES_BY_ID, type RuleMeta, type Severity, type Confidence } from "./rules.js";
|
|
10
|
+
export { formatJson, formatSarif, formatText, formatMarkdown, formatDisclosures, VERSION, type TextOptions } from "./reporters.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Library entry point (Node.js). The browser playground uses src/browser.ts.
|
|
2
|
+
export { lintSource, mapDisclosures, createBaseline } from "./linter.js";
|
|
3
|
+
export { lintFiles, mapDisclosuresInFiles, listTargetFiles, findCompactFiles, fileImportResolver, readBaseline, globToRegExp } from "./node.js";
|
|
4
|
+
export { loadConfig, validateConfig, DEFAULT_CONFIG } from "./config.js";
|
|
5
|
+
export { loadPlugins } from "./plugin-loader.js";
|
|
6
|
+
export { walkProgram, calleeName } from "./walk.js";
|
|
7
|
+
export { applyEdits, pragmaFix } from "./fixes.js";
|
|
8
|
+
export { parse } from "./parser.js";
|
|
9
|
+
export { RULES, RULES_BY_ID } from "./rules.js";
|
|
10
|
+
export { formatJson, formatSarif, formatText, formatMarkdown, formatDisclosures, VERSION } from "./reporters.js";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type TokenKind = "ident" | "number" | "string" | "punct" | "eof";
|
|
2
|
+
export interface Token {
|
|
3
|
+
kind: TokenKind;
|
|
4
|
+
value: string;
|
|
5
|
+
line: number;
|
|
6
|
+
col: number;
|
|
7
|
+
offset: number;
|
|
8
|
+
}
|
|
9
|
+
export interface Comment {
|
|
10
|
+
text: string;
|
|
11
|
+
line: number;
|
|
12
|
+
endLine: number;
|
|
13
|
+
}
|
|
14
|
+
export interface LexResult {
|
|
15
|
+
tokens: Token[];
|
|
16
|
+
comments: Comment[];
|
|
17
|
+
}
|
|
18
|
+
export declare function lex(source: string): LexResult;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Tokenizer for the Compact language.
|
|
2
|
+
// It keeps line/column for every token and collects comments separately so the
|
|
3
|
+
// suppression logic can read `shield-disable` directives.
|
|
4
|
+
// Longest first. `>` is always emitted alone so nested generics such as
|
|
5
|
+
// `Vector<2, Bytes<32>>` close correctly; the parser joins `>` `=` when needed.
|
|
6
|
+
const PUNCTUATORS = [
|
|
7
|
+
"...", "..", "=>", "::", "??", "&&", "||", "<=", "==", "!=", "+=", "-=", "*=",
|
|
8
|
+
"{", "}", "(", ")", "[", "]", "<", ">", ";", ",", ".", ":", "?", "=", "+",
|
|
9
|
+
"-", "*", "/", "%", "!", "#", "&", "|", "^", "@",
|
|
10
|
+
];
|
|
11
|
+
export function lex(source) {
|
|
12
|
+
const tokens = [];
|
|
13
|
+
const comments = [];
|
|
14
|
+
let i = 0;
|
|
15
|
+
let line = 1;
|
|
16
|
+
let col = 1;
|
|
17
|
+
const advance = (n) => {
|
|
18
|
+
for (let k = 0; k < n; k++) {
|
|
19
|
+
if (source[i] === "\n") {
|
|
20
|
+
line++;
|
|
21
|
+
col = 1;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
col++;
|
|
25
|
+
}
|
|
26
|
+
i++;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
while (i < source.length) {
|
|
30
|
+
const ch = source[i];
|
|
31
|
+
if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") {
|
|
32
|
+
advance(1);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
// line comment
|
|
36
|
+
if (ch === "/" && source[i + 1] === "/") {
|
|
37
|
+
const start = i;
|
|
38
|
+
const startLine = line;
|
|
39
|
+
while (i < source.length && source[i] !== "\n")
|
|
40
|
+
advance(1);
|
|
41
|
+
comments.push({ text: source.slice(start + 2, i), line: startLine, endLine: startLine });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
// block comment
|
|
45
|
+
if (ch === "/" && source[i + 1] === "*") {
|
|
46
|
+
const start = i;
|
|
47
|
+
const startLine = line;
|
|
48
|
+
advance(2);
|
|
49
|
+
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/"))
|
|
50
|
+
advance(1);
|
|
51
|
+
advance(2);
|
|
52
|
+
comments.push({ text: source.slice(start + 2, Math.max(start + 2, i - 2)), line: startLine, endLine: line });
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
const tokLine = line;
|
|
56
|
+
const tokCol = col;
|
|
57
|
+
const tokOffset = i;
|
|
58
|
+
if (ch === "`") {
|
|
59
|
+
// template literal (TypeScript/JavaScript): one string token; ${...} is kept inside
|
|
60
|
+
let j = i + 1;
|
|
61
|
+
let depth = 0;
|
|
62
|
+
while (j < source.length) {
|
|
63
|
+
const c = source[j];
|
|
64
|
+
if (c === "\\") {
|
|
65
|
+
j += 2;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (depth === 0 && c === "`")
|
|
69
|
+
break;
|
|
70
|
+
if (c === "$" && source[j + 1] === "{") {
|
|
71
|
+
depth++;
|
|
72
|
+
j += 2;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (depth > 0 && c === "}")
|
|
76
|
+
depth--;
|
|
77
|
+
j++;
|
|
78
|
+
}
|
|
79
|
+
const raw = source.slice(i, j + 1);
|
|
80
|
+
advance(j + 1 - i);
|
|
81
|
+
tokens.push({ kind: "string", value: raw, line: tokLine, col: tokCol, offset: tokOffset });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (ch === '"' || ch === "'") {
|
|
85
|
+
const quote = ch;
|
|
86
|
+
let j = i + 1;
|
|
87
|
+
while (j < source.length && source[j] !== quote) {
|
|
88
|
+
if (source[j] === "\\")
|
|
89
|
+
j++;
|
|
90
|
+
j++;
|
|
91
|
+
}
|
|
92
|
+
const raw = source.slice(i, j + 1);
|
|
93
|
+
advance(j + 1 - i);
|
|
94
|
+
tokens.push({ kind: "string", value: raw, line: tokLine, col: tokCol, offset: tokOffset });
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (/[0-9]/.test(ch)) {
|
|
98
|
+
let j = i;
|
|
99
|
+
if (ch === "0" && /[xXbBoO]/.test(source[i + 1] ?? "")) {
|
|
100
|
+
j += 2;
|
|
101
|
+
while (j < source.length && /[0-9a-fA-F_]/.test(source[j]))
|
|
102
|
+
j++;
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
// stop before `..` so `0..10` lexes as 0 .. 10
|
|
106
|
+
while (j < source.length && /[0-9_]/.test(source[j]))
|
|
107
|
+
j++;
|
|
108
|
+
}
|
|
109
|
+
const raw = source.slice(i, j);
|
|
110
|
+
advance(j - i);
|
|
111
|
+
tokens.push({ kind: "number", value: raw, line: tokLine, col: tokCol, offset: tokOffset });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (/[A-Za-z_$]/.test(ch)) {
|
|
115
|
+
let j = i;
|
|
116
|
+
while (j < source.length && /[A-Za-z0-9_$]/.test(source[j]))
|
|
117
|
+
j++;
|
|
118
|
+
const raw = source.slice(i, j);
|
|
119
|
+
advance(j - i);
|
|
120
|
+
tokens.push({ kind: "ident", value: raw, line: tokLine, col: tokCol, offset: tokOffset });
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const p = PUNCTUATORS.find((op) => source.startsWith(op, i));
|
|
124
|
+
if (p) {
|
|
125
|
+
advance(p.length);
|
|
126
|
+
tokens.push({ kind: "punct", value: p, line: tokLine, col: tokCol, offset: tokOffset });
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
// Unknown character: emit it so the parser can report a precise error.
|
|
130
|
+
advance(1);
|
|
131
|
+
tokens.push({ kind: "punct", value: ch, line: tokLine, col: tokCol, offset: tokOffset });
|
|
132
|
+
}
|
|
133
|
+
tokens.push({ kind: "eof", value: "", line, col, offset: i });
|
|
134
|
+
return { tokens, comments };
|
|
135
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type DisclosureEvent, type ImportResolver } from "./analyzer.js";
|
|
2
|
+
import { type TextEdit } from "./fixes.js";
|
|
3
|
+
import { type CustomRule } from "./plugins.js";
|
|
4
|
+
import { type Confidence, type Severity } from "./rules.js";
|
|
5
|
+
export interface Finding {
|
|
6
|
+
ruleId: string;
|
|
7
|
+
ruleName: string;
|
|
8
|
+
severity: Severity;
|
|
9
|
+
/** how sure the rule is that this is a real problem */
|
|
10
|
+
confidence: Confidence;
|
|
11
|
+
message: string;
|
|
12
|
+
file: string;
|
|
13
|
+
line: number;
|
|
14
|
+
col: number;
|
|
15
|
+
docUrl: string;
|
|
16
|
+
/** the source line the finding points at */
|
|
17
|
+
snippet: string;
|
|
18
|
+
/** stable ID that survives unrelated edits (used by baselines) */
|
|
19
|
+
fingerprint: string;
|
|
20
|
+
/** set when the finding is hidden by an inline comment or a baseline */
|
|
21
|
+
suppressed?: "inline" | "baseline";
|
|
22
|
+
/** a safe automatic fix, when one exists */
|
|
23
|
+
fix?: TextEdit;
|
|
24
|
+
}
|
|
25
|
+
export interface LintOptions {
|
|
26
|
+
/** rule IDs to skip */
|
|
27
|
+
disable?: string[];
|
|
28
|
+
/** only report findings at or above this severity */
|
|
29
|
+
minSeverity?: Severity;
|
|
30
|
+
/** only report findings at or above this confidence */
|
|
31
|
+
minConfidence?: Confidence;
|
|
32
|
+
/** glob patterns of files to skip, e.g. "**\/test/**" */
|
|
33
|
+
ignore?: string[];
|
|
34
|
+
/** resolves `import "path"` so imported circuits are followed */
|
|
35
|
+
resolver?: ImportResolver;
|
|
36
|
+
/** absolute path of the file, used to resolve relative imports */
|
|
37
|
+
absolutePath?: string;
|
|
38
|
+
/** custom rules loaded from plugins */
|
|
39
|
+
plugins?: CustomRule[];
|
|
40
|
+
/** fingerprints of accepted findings (from a baseline file) */
|
|
41
|
+
baseline?: Set<string>;
|
|
42
|
+
/** also return suppressed findings, marked with `suppressed` */
|
|
43
|
+
includeSuppressed?: boolean;
|
|
44
|
+
/** also check TypeScript/JavaScript files (MS101, MS102); default true */
|
|
45
|
+
sdk?: boolean;
|
|
46
|
+
}
|
|
47
|
+
export declare function lintSource(source: string, file?: string, options?: LintOptions): Finding[];
|
|
48
|
+
export interface DisclosureEntry extends DisclosureEvent {
|
|
49
|
+
file: string;
|
|
50
|
+
snippet: string;
|
|
51
|
+
/** rule IDs reported on the same line */
|
|
52
|
+
findings: string[];
|
|
53
|
+
}
|
|
54
|
+
/** List every point where data becomes public in a file (the disclosure map). */
|
|
55
|
+
export declare function mapDisclosures(source: string, file?: string, options?: LintOptions): DisclosureEntry[];
|
|
56
|
+
export interface BaselineFile {
|
|
57
|
+
tool: "midnight-shield";
|
|
58
|
+
version: 1;
|
|
59
|
+
findings: {
|
|
60
|
+
fingerprint: string;
|
|
61
|
+
ruleId: string;
|
|
62
|
+
file: string;
|
|
63
|
+
line: number;
|
|
64
|
+
message: string;
|
|
65
|
+
}[];
|
|
66
|
+
}
|
|
67
|
+
export declare function createBaseline(findings: Finding[]): BaselineFile;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Analyzer } from "./analyzer.js";
|
|
2
|
+
import { pragmaFix } from "./fixes.js";
|
|
3
|
+
import { lex } from "./lexer.js";
|
|
4
|
+
import { parse } from "./parser.js";
|
|
5
|
+
import { runCustomRule } from "./plugins.js";
|
|
6
|
+
import { isSdkFile, isTestFile, lintSdkSource } from "./sdk.js";
|
|
7
|
+
import { CONFIDENCE_ORDER, RULES_BY_ID, SEVERITY_ORDER, ruleDocUrl } from "./rules.js";
|
|
8
|
+
const DIRECTIVE = /shield-disable(-next-line|-line|-file)?\b([^\n]*)/;
|
|
9
|
+
function parseIds(rest) {
|
|
10
|
+
const ids = rest.match(/\b[A-Z][A-Z0-9]*\d{3}\b/g);
|
|
11
|
+
return ids && ids.length ? new Set(ids) : "all";
|
|
12
|
+
}
|
|
13
|
+
function collectSuppressions(source) {
|
|
14
|
+
const { comments } = lex(source);
|
|
15
|
+
const out = { file: undefined, lines: new Map() };
|
|
16
|
+
const addLine = (line, ids) => {
|
|
17
|
+
const prev = out.lines.get(line);
|
|
18
|
+
if (prev === "all" || ids === "all")
|
|
19
|
+
out.lines.set(line, "all");
|
|
20
|
+
else
|
|
21
|
+
out.lines.set(line, new Set([...(prev ?? []), ...ids]));
|
|
22
|
+
};
|
|
23
|
+
for (const c of comments) {
|
|
24
|
+
const m = c.text.match(DIRECTIVE);
|
|
25
|
+
if (!m)
|
|
26
|
+
continue;
|
|
27
|
+
const ids = parseIds(m[2]);
|
|
28
|
+
if (m[1] === "-file")
|
|
29
|
+
out.file = ids;
|
|
30
|
+
else if (m[1] === "-next-line")
|
|
31
|
+
addLine(c.endLine + 1, ids);
|
|
32
|
+
else
|
|
33
|
+
addLine(c.line, ids);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
function isSuppressed(s, ruleId, line) {
|
|
38
|
+
const match = (v) => v === "all" || (v instanceof Set && v.has(ruleId));
|
|
39
|
+
return match(s.file) || match(s.lines.get(line));
|
|
40
|
+
}
|
|
41
|
+
/** Fingerprint = rule + file + the trimmed source line + occurrence index, so moving code up or down keeps it stable. */
|
|
42
|
+
function fingerprint(ruleId, file, snippet, occurrence) {
|
|
43
|
+
return hash53(`${ruleId}|${file}|${snippet.trim()}|${occurrence}`);
|
|
44
|
+
}
|
|
45
|
+
/** cyrb53: a small, fast, well-distributed 53-bit string hash (no Node APIs, so it also runs in the browser). */
|
|
46
|
+
function hash53(str) {
|
|
47
|
+
let h1 = 0xdeadbeef;
|
|
48
|
+
let h2 = 0x41c6ce57;
|
|
49
|
+
for (let i = 0; i < str.length; i++) {
|
|
50
|
+
const ch = str.charCodeAt(i);
|
|
51
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
52
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
53
|
+
}
|
|
54
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
55
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
56
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0");
|
|
57
|
+
}
|
|
58
|
+
function metaFor(ruleId, plugins = []) {
|
|
59
|
+
return RULES_BY_ID.get(ruleId) ?? plugins.find((p) => p.id === ruleId);
|
|
60
|
+
}
|
|
61
|
+
function analyze(source, file, options) {
|
|
62
|
+
if (isSdkFile(file))
|
|
63
|
+
return { raw: isTestFile(file) ? [] : lintSdkSource(source) };
|
|
64
|
+
const program = parse(source);
|
|
65
|
+
const analyzer = new Analyzer(program, options.resolver, options.absolutePath);
|
|
66
|
+
const raw = analyzer.run();
|
|
67
|
+
for (const rule of options.plugins ?? [])
|
|
68
|
+
raw.push(...runCustomRule(rule, file, source, program));
|
|
69
|
+
return { program, analyzer, raw };
|
|
70
|
+
}
|
|
71
|
+
export function lintSource(source, file = "contract.compact", options = {}) {
|
|
72
|
+
const { raw } = analyze(source, file, options);
|
|
73
|
+
return toFindings(raw, source, file, options);
|
|
74
|
+
}
|
|
75
|
+
function toFindings(raw, source, file, options) {
|
|
76
|
+
const lines = source.split(/\r?\n/);
|
|
77
|
+
const suppressions = collectSuppressions(source);
|
|
78
|
+
const disabled = new Set(options.disable ?? []);
|
|
79
|
+
const minRank = SEVERITY_ORDER.indexOf(options.minSeverity ?? "info");
|
|
80
|
+
const minConf = CONFIDENCE_ORDER.indexOf(options.minConfidence ?? "low");
|
|
81
|
+
const occurrences = new Map();
|
|
82
|
+
const all = raw
|
|
83
|
+
.filter((f) => !disabled.has(f.ruleId))
|
|
84
|
+
.filter((f) => SEVERITY_ORDER.indexOf(f.severity) <= minRank)
|
|
85
|
+
.filter((f) => CONFIDENCE_ORDER.indexOf(f.confidence) <= minConf)
|
|
86
|
+
.sort((a, b) => a.loc.line - b.loc.line || a.loc.col - b.loc.col)
|
|
87
|
+
.map((f) => {
|
|
88
|
+
const meta = metaFor(f.ruleId, options.plugins);
|
|
89
|
+
const snippet = lines[f.loc.line - 1] ?? "";
|
|
90
|
+
const key = `${f.ruleId}|${snippet.trim()}`;
|
|
91
|
+
const n = occurrences.get(key) ?? 0;
|
|
92
|
+
occurrences.set(key, n + 1);
|
|
93
|
+
const finding = {
|
|
94
|
+
ruleId: f.ruleId,
|
|
95
|
+
ruleName: meta.name,
|
|
96
|
+
severity: f.severity,
|
|
97
|
+
confidence: f.confidence,
|
|
98
|
+
message: f.message,
|
|
99
|
+
file,
|
|
100
|
+
line: f.loc.line,
|
|
101
|
+
col: f.loc.col,
|
|
102
|
+
docUrl: ruleDocUrl(f.ruleId, meta),
|
|
103
|
+
snippet,
|
|
104
|
+
fingerprint: fingerprint(f.ruleId, file, snippet, n),
|
|
105
|
+
};
|
|
106
|
+
if (f.ruleId === "MS006")
|
|
107
|
+
finding.fix = pragmaFix(source);
|
|
108
|
+
if (isSuppressed(suppressions, f.ruleId, f.loc.line))
|
|
109
|
+
finding.suppressed = "inline";
|
|
110
|
+
else if (options.baseline?.has(finding.fingerprint))
|
|
111
|
+
finding.suppressed = "baseline";
|
|
112
|
+
return finding;
|
|
113
|
+
});
|
|
114
|
+
return options.includeSuppressed ? all : all.filter((f) => !f.suppressed);
|
|
115
|
+
}
|
|
116
|
+
/** List every point where data becomes public in a file (the disclosure map). */
|
|
117
|
+
export function mapDisclosures(source, file = "contract.compact", options = {}) {
|
|
118
|
+
const { analyzer, raw } = analyze(source, file, options);
|
|
119
|
+
if (!analyzer)
|
|
120
|
+
return [];
|
|
121
|
+
const lines = source.split(/\r?\n/);
|
|
122
|
+
return analyzer.getDisclosures().map((d) => ({
|
|
123
|
+
...d,
|
|
124
|
+
file,
|
|
125
|
+
snippet: lines[d.loc.line - 1] ?? "",
|
|
126
|
+
findings: [...new Set(raw.filter((f) => f.loc.line === d.loc.line && f.ruleId !== "MS000").map((f) => f.ruleId))].sort(),
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
export function createBaseline(findings) {
|
|
130
|
+
return {
|
|
131
|
+
tool: "midnight-shield",
|
|
132
|
+
version: 1,
|
|
133
|
+
findings: findings
|
|
134
|
+
.filter((f) => f.suppressed !== "inline")
|
|
135
|
+
.map((f) => ({ fingerprint: f.fingerprint, ruleId: f.ruleId, file: f.file, line: f.line, message: f.message })),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ImportResolver } from "./analyzer.js";
|
|
2
|
+
import { type DisclosureEntry, type Finding, type LintOptions } from "./linter.js";
|
|
3
|
+
/** Find .compact files (and, with `sdk`, TypeScript/JavaScript files) under the given paths. */
|
|
4
|
+
export declare function findCompactFiles(paths: string[], sdk?: boolean): string[];
|
|
5
|
+
/** Resolve imports from disk, relative to the importing file. Parsed files are cached. */
|
|
6
|
+
export declare function fileImportResolver(): ImportResolver;
|
|
7
|
+
/** Convert a glob (`*`, `**`, `?`) to a RegExp matched against forward-slash paths. */
|
|
8
|
+
export declare function globToRegExp(glob: string): RegExp;
|
|
9
|
+
/** The .compact files that will be scanned: found under `paths`, minus `ignore` globs. */
|
|
10
|
+
export declare function listTargetFiles(paths: string[], ignore?: string[], cwd?: string, sdk?: boolean): string[];
|
|
11
|
+
export declare function lintFiles(paths: string[], options?: LintOptions, cwd?: string): Finding[];
|
|
12
|
+
export declare function mapDisclosuresInFiles(paths: string[], options?: LintOptions, cwd?: string): DisclosureEntry[];
|
|
13
|
+
export declare function readBaseline(path: string): Set<string>;
|
package/dist/src/node.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// File-system helpers (Node.js only). The analysis itself lives in linter.ts
|
|
2
|
+
// and has no Node dependencies, so it also runs in the browser playground.
|
|
3
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
5
|
+
import { lintSource, mapDisclosures } from "./linter.js";
|
|
6
|
+
import { parse } from "./parser.js";
|
|
7
|
+
import { isSdkFile } from "./sdk.js";
|
|
8
|
+
const IGNORED_DIRS = new Set(["node_modules", ".git", "dist", "build", "managed", "coverage", ".cache"]);
|
|
9
|
+
/** Find .compact files (and, with `sdk`, TypeScript/JavaScript files) under the given paths. */
|
|
10
|
+
export function findCompactFiles(paths, sdk = false) {
|
|
11
|
+
const out = [];
|
|
12
|
+
const wanted = (p) => p.endsWith(".compact") || (sdk && isSdkFile(p) && !p.endsWith(".min.js"));
|
|
13
|
+
const walk = (p, explicit) => {
|
|
14
|
+
const st = statSync(p);
|
|
15
|
+
if (st.isDirectory()) {
|
|
16
|
+
for (const name of readdirSync(p).sort()) {
|
|
17
|
+
if (IGNORED_DIRS.has(name) || name.startsWith("."))
|
|
18
|
+
continue;
|
|
19
|
+
walk(join(p, name), false);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
else if (wanted(p) || (explicit && (p.endsWith(".compact") || isSdkFile(p)))) {
|
|
23
|
+
out.push(p);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
for (const p of paths)
|
|
27
|
+
walk(p, true);
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
/** Resolve imports from disk, relative to the importing file. Parsed files are cached. */
|
|
31
|
+
export function fileImportResolver() {
|
|
32
|
+
const cache = new Map();
|
|
33
|
+
return (fromFile, target) => {
|
|
34
|
+
const base = fromFile ? dirname(fromFile) : process.cwd();
|
|
35
|
+
for (const candidate of [`${target}.compact`, target]) {
|
|
36
|
+
const abs = resolve(base, candidate);
|
|
37
|
+
if (!cache.has(abs)) {
|
|
38
|
+
cache.set(abs, existsSync(abs) && statSync(abs).isFile() ? parse(readFileSync(abs, "utf8")) : null);
|
|
39
|
+
}
|
|
40
|
+
const program = cache.get(abs);
|
|
41
|
+
if (program)
|
|
42
|
+
return { file: abs, program };
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Convert a glob (`*`, `**`, `?`) to a RegExp matched against forward-slash paths. */
|
|
48
|
+
export function globToRegExp(glob) {
|
|
49
|
+
let re = "";
|
|
50
|
+
for (let i = 0; i < glob.length; i++) {
|
|
51
|
+
const c = glob[i];
|
|
52
|
+
if (c === "*") {
|
|
53
|
+
if (glob[i + 1] === "*") {
|
|
54
|
+
re += ".*";
|
|
55
|
+
i++;
|
|
56
|
+
if (glob[i + 1] === "/")
|
|
57
|
+
i++;
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
re += "[^/]*";
|
|
61
|
+
}
|
|
62
|
+
else if (c === "?")
|
|
63
|
+
re += "[^/]";
|
|
64
|
+
else
|
|
65
|
+
re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
66
|
+
}
|
|
67
|
+
return new RegExp(`^${re}$`);
|
|
68
|
+
}
|
|
69
|
+
/** The .compact files that will be scanned: found under `paths`, minus `ignore` globs. */
|
|
70
|
+
export function listTargetFiles(paths, ignore = [], cwd = process.cwd(), sdk = true) {
|
|
71
|
+
const res = ignore.map(globToRegExp);
|
|
72
|
+
return findCompactFiles(paths, sdk).filter((file) => {
|
|
73
|
+
const rel = relative(cwd, file).split("\\").join("/");
|
|
74
|
+
return !res.some((re) => re.test(rel));
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function eachFile(paths, options, cwd, fn) {
|
|
78
|
+
const out = [];
|
|
79
|
+
const resolver = options.resolver ?? fileImportResolver();
|
|
80
|
+
for (const file of listTargetFiles(paths, options.ignore, cwd, options.sdk ?? true)) {
|
|
81
|
+
const rel = relative(cwd, file).split("\\").join("/");
|
|
82
|
+
const source = readFileSync(file, "utf8");
|
|
83
|
+
out.push(...fn(source, rel, { ...options, resolver, absolutePath: resolve(file) }));
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
export function lintFiles(paths, options = {}, cwd = process.cwd()) {
|
|
88
|
+
return eachFile(paths, options, cwd, (src, rel, opts) => lintSource(src, rel, opts));
|
|
89
|
+
}
|
|
90
|
+
export function mapDisclosuresInFiles(paths, options = {}, cwd = process.cwd()) {
|
|
91
|
+
return eachFile(paths, options, cwd, (src, rel, opts) => mapDisclosures(src, rel, opts));
|
|
92
|
+
}
|
|
93
|
+
export function readBaseline(path) {
|
|
94
|
+
const data = JSON.parse(readFileSync(path, "utf8"));
|
|
95
|
+
if (data.tool !== "midnight-shield" || !Array.isArray(data.findings))
|
|
96
|
+
throw new Error(`${path} is not a Midnight Shield baseline`);
|
|
97
|
+
return new Set(data.findings.map((f) => f.fingerprint));
|
|
98
|
+
}
|