midnight-shield 0.0.0-stage → 0.4.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.
Files changed (53) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/LICENSE +21 -0
  3. package/README.md +384 -2
  4. package/action.yml +56 -0
  5. package/dist/src/analyzer.d.ts +97 -0
  6. package/dist/src/analyzer.js +895 -0
  7. package/dist/src/ast.d.ts +211 -0
  8. package/dist/src/ast.js +2 -0
  9. package/dist/src/browser.d.ts +3 -0
  10. package/dist/src/browser.js +5 -0
  11. package/dist/src/cli.d.ts +2 -0
  12. package/dist/src/cli.js +336 -0
  13. package/dist/src/config.d.ts +26 -0
  14. package/dist/src/config.js +87 -0
  15. package/dist/src/fixes.d.ts +10 -0
  16. package/dist/src/fixes.js +45 -0
  17. package/dist/src/index.d.ts +10 -0
  18. package/dist/src/index.js +10 -0
  19. package/dist/src/lexer.d.ts +18 -0
  20. package/dist/src/lexer.js +135 -0
  21. package/dist/src/linter.d.ts +67 -0
  22. package/dist/src/linter.js +137 -0
  23. package/dist/src/node.d.ts +13 -0
  24. package/dist/src/node.js +98 -0
  25. package/dist/src/parser.d.ts +2 -0
  26. package/dist/src/parser.js +791 -0
  27. package/dist/src/plugin-loader.d.ts +3 -0
  28. package/dist/src/plugin-loader.js +31 -0
  29. package/dist/src/plugins.d.ts +34 -0
  30. package/dist/src/plugins.js +59 -0
  31. package/dist/src/reporters.d.ts +22 -0
  32. package/dist/src/reporters.js +286 -0
  33. package/dist/src/rules.d.ts +23 -0
  34. package/dist/src/rules.js +104 -0
  35. package/dist/src/sdk.d.ts +6 -0
  36. package/dist/src/sdk.js +130 -0
  37. package/dist/src/walk.d.ts +28 -0
  38. package/dist/src/walk.js +110 -0
  39. package/docs/rules/MS000.md +7 -0
  40. package/docs/rules/MS001.md +46 -0
  41. package/docs/rules/MS002.md +42 -0
  42. package/docs/rules/MS003.md +41 -0
  43. package/docs/rules/MS004.md +41 -0
  44. package/docs/rules/MS005.md +32 -0
  45. package/docs/rules/MS006.md +17 -0
  46. package/docs/rules/MS007.md +44 -0
  47. package/docs/rules/MS008.md +59 -0
  48. package/docs/rules/MS009.md +45 -0
  49. package/docs/rules/MS010.md +46 -0
  50. package/docs/rules/MS101.md +32 -0
  51. package/docs/rules/MS102.md +31 -0
  52. package/package.json +67 -4
  53. package/skills/midnight-shield/SKILL.md +67 -0
@@ -0,0 +1,211 @@
1
+ export interface Loc {
2
+ line: number;
3
+ col: number;
4
+ }
5
+ export interface TypeRef {
6
+ name: string;
7
+ args: TypeArg[];
8
+ text: string;
9
+ }
10
+ export type TypeArg = {
11
+ kind: "type";
12
+ type: TypeRef;
13
+ } | {
14
+ kind: "number";
15
+ value: number;
16
+ } | {
17
+ kind: "range";
18
+ from: number;
19
+ to: number;
20
+ } | {
21
+ kind: "string";
22
+ value: string;
23
+ } | {
24
+ kind: "param";
25
+ name: string;
26
+ };
27
+ export type Expr = {
28
+ kind: "ident";
29
+ name: string;
30
+ typeArgs?: TypeRef[];
31
+ loc: Loc;
32
+ } | {
33
+ kind: "number";
34
+ value: string;
35
+ loc: Loc;
36
+ } | {
37
+ kind: "string";
38
+ value: string;
39
+ loc: Loc;
40
+ } | {
41
+ kind: "call";
42
+ callee: Expr;
43
+ typeArgs?: TypeRef[];
44
+ args: Expr[];
45
+ loc: Loc;
46
+ } | {
47
+ kind: "member";
48
+ object: Expr;
49
+ property: string;
50
+ loc: Loc;
51
+ } | {
52
+ kind: "index";
53
+ object: Expr;
54
+ index: Expr;
55
+ loc: Loc;
56
+ } | {
57
+ kind: "vector";
58
+ elements: Expr[];
59
+ loc: Loc;
60
+ } | {
61
+ kind: "struct";
62
+ type: TypeRef;
63
+ fields: {
64
+ name: string;
65
+ value: Expr;
66
+ }[];
67
+ loc: Loc;
68
+ } | {
69
+ kind: "binary";
70
+ op: string;
71
+ left: Expr;
72
+ right: Expr;
73
+ loc: Loc;
74
+ } | {
75
+ kind: "unary";
76
+ op: string;
77
+ arg: Expr;
78
+ loc: Loc;
79
+ } | {
80
+ kind: "cast";
81
+ expr: Expr;
82
+ type: TypeRef;
83
+ loc: Loc;
84
+ } | {
85
+ kind: "cond";
86
+ test: Expr;
87
+ then: Expr;
88
+ else: Expr;
89
+ loc: Loc;
90
+ } | {
91
+ kind: "lambda";
92
+ params: Param[];
93
+ body: Expr | Stmt[];
94
+ loc: Loc;
95
+ } | {
96
+ kind: "spread";
97
+ arg: Expr;
98
+ loc: Loc;
99
+ };
100
+ export interface Param {
101
+ name: string;
102
+ type?: TypeRef;
103
+ loc: Loc;
104
+ }
105
+ export type Stmt = {
106
+ kind: "const";
107
+ names: string[];
108
+ type?: TypeRef;
109
+ init: Expr;
110
+ loc: Loc;
111
+ } | {
112
+ kind: "assign";
113
+ target: Expr;
114
+ op: string;
115
+ value: Expr;
116
+ loc: Loc;
117
+ } | {
118
+ kind: "if";
119
+ test: Expr;
120
+ then: Stmt[];
121
+ else?: Stmt[];
122
+ loc: Loc;
123
+ } | {
124
+ kind: "for";
125
+ name: string;
126
+ iter: Expr;
127
+ body: Stmt[];
128
+ loc: Loc;
129
+ } | {
130
+ kind: "return";
131
+ value?: Expr;
132
+ loc: Loc;
133
+ } | {
134
+ kind: "expr";
135
+ expr: Expr;
136
+ loc: Loc;
137
+ } | {
138
+ kind: "block";
139
+ body: Stmt[];
140
+ loc: Loc;
141
+ };
142
+ export type Decl = {
143
+ kind: "pragma";
144
+ text: string;
145
+ loc: Loc;
146
+ } | {
147
+ kind: "ledger";
148
+ name: string;
149
+ type: TypeRef;
150
+ exported: boolean;
151
+ sealed: boolean;
152
+ loc: Loc;
153
+ } | {
154
+ kind: "witness";
155
+ name: string;
156
+ params: Param[];
157
+ returnType?: TypeRef;
158
+ loc: Loc;
159
+ } | {
160
+ kind: "circuit";
161
+ name: string;
162
+ params: Param[];
163
+ returnType?: TypeRef;
164
+ body?: Stmt[];
165
+ exported: boolean;
166
+ pure: boolean;
167
+ loc: Loc;
168
+ } | {
169
+ kind: "constructor";
170
+ params: Param[];
171
+ body: Stmt[];
172
+ loc: Loc;
173
+ } | {
174
+ kind: "struct";
175
+ name: string;
176
+ fields: Param[];
177
+ loc: Loc;
178
+ } | {
179
+ kind: "enum";
180
+ name: string;
181
+ members: string[];
182
+ loc: Loc;
183
+ } | {
184
+ kind: "typeAlias";
185
+ name: string;
186
+ type: TypeRef;
187
+ loc: Loc;
188
+ } | {
189
+ kind: "import";
190
+ target: string;
191
+ isPath: boolean;
192
+ prefix: string;
193
+ loc: Loc;
194
+ } | {
195
+ kind: "include";
196
+ path: string;
197
+ loc: Loc;
198
+ } | {
199
+ kind: "module";
200
+ name: string;
201
+ decls: Decl[];
202
+ loc: Loc;
203
+ };
204
+ export interface ParseDiagnostic {
205
+ message: string;
206
+ loc: Loc;
207
+ }
208
+ export interface Program {
209
+ decls: Decl[];
210
+ diagnostics: ParseDiagnostic[];
211
+ }
@@ -0,0 +1,2 @@
1
+ // AST for the subset of Compact that Midnight Shield analyzes.
2
+ export {};
@@ -0,0 +1,3 @@
1
+ export { lintSource, mapDisclosures, type Finding, type DisclosureEntry } from "./linter.js";
2
+ export { RULES, RULES_BY_ID } from "./rules.js";
3
+ export { formatMarkdown, VERSION } from "./reporters.js";
@@ -0,0 +1,5 @@
1
+ // Browser entry point for the web playground. Everything here runs locally in
2
+ // the page: no Node APIs, no network.
3
+ export { lintSource, mapDisclosures } from "./linter.js";
4
+ export { RULES, RULES_BY_ID } from "./rules.js";
5
+ export { formatMarkdown, VERSION } from "./reporters.js";
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,336 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { CONFIG_FILE, ConfigError, DEFAULT_CONFIG, loadConfig } from "./config.js";
6
+ import { applyEdits } from "./fixes.js";
7
+ import { createBaseline } from "./linter.js";
8
+ import { lintFiles, listTargetFiles, mapDisclosuresInFiles, readBaseline } from "./node.js";
9
+ import { loadPlugins } from "./plugin-loader.js";
10
+ import { PluginError } from "./plugins.js";
11
+ import { VERSION, formatDisclosures, formatDisclosuresMarkdown, formatJson, formatMarkdown, formatSarif, formatText } from "./reporters.js";
12
+ import { CONFIDENCE_ORDER, RULES, RULES_BY_ID, SEVERITY_ORDER } from "./rules.js";
13
+ const HELP = `midnight-shield ${VERSION}
14
+ Static analyzer for Midnight Compact contracts and their TypeScript code.
15
+
16
+ Usage:
17
+ midnight-shield [paths...] [options] scan files and folders (default: .)
18
+ midnight-shield explain <RULE> show a rule's documentation
19
+ midnight-shield --init create ${CONFIG_FILE}
20
+
21
+ Output:
22
+ -f, --format <text|json|sarif|markdown> Output format (default: text)
23
+ -o, --output <file> Write the report to a file
24
+ --print disclosures Print the disclosure map: every point where
25
+ data becomes public, and what flows there
26
+ --no-code-frame Do not print source lines
27
+ --no-color Disable colored output
28
+
29
+ Filtering:
30
+ --fail-on <severity> Exit 1 at or above this severity (default: high;
31
+ "none" never fails)
32
+ --min-severity <severity> Hide findings below this severity
33
+ --min-confidence <confidence> Hide findings below this confidence (high, medium, low)
34
+ --disable <MS001,MS005> Skip rules
35
+ --ignore <glob> Skip files matching a glob (repeatable)
36
+ --no-sdk Do not check TypeScript/JavaScript files
37
+ --show-suppressed Also list findings hidden by comments or a baseline
38
+
39
+ Adoption:
40
+ --baseline <file> Accept the findings recorded in this file;
41
+ report only new ones
42
+ --write-baseline <file> Record the current findings as accepted
43
+ --fix Apply safe automatic fixes
44
+ --fix-dry-run Show which files --fix would change
45
+ -c, --config <file> Config file (default: ./${CONFIG_FILE})
46
+ --plugin <module> Load custom rules from a module (repeatable)
47
+
48
+ -v, --version Print the version
49
+ -h, --help Show this help
50
+ --list-rules Print all rules
51
+
52
+ Suppress a finding in code:
53
+ // shield-disable-next-line MS005
54
+ // shield-disable-line MS005
55
+ // shield-disable-file MS006
56
+ `;
57
+ function fail(msg) {
58
+ process.stderr.write(`midnight-shield: ${msg}\n`);
59
+ process.exit(2);
60
+ }
61
+ function parseSeverity(v, flag) {
62
+ if (!v || !SEVERITY_ORDER.includes(v))
63
+ fail(`${flag} must be one of ${SEVERITY_ORDER.join(", ")}`);
64
+ return v;
65
+ }
66
+ function parseConfidence(v, flag) {
67
+ if (!v || !CONFIDENCE_ORDER.includes(v))
68
+ fail(`${flag} must be one of ${CONFIDENCE_ORDER.join(", ")}`);
69
+ return v;
70
+ }
71
+ /** docs/rules lives two levels above dist/src/cli.js in the installed package. */
72
+ function docsDir() {
73
+ return join(dirname(fileURLToPath(import.meta.url)), "..", "..", "docs", "rules");
74
+ }
75
+ function explain(id, plugins) {
76
+ if (!id)
77
+ fail("explain needs a rule ID, e.g. midnight-shield explain MS001");
78
+ const ruleId = id.toUpperCase();
79
+ const builtIn = RULES_BY_ID.get(ruleId);
80
+ const custom = plugins.find((p) => p.id === ruleId);
81
+ const meta = builtIn ?? custom;
82
+ if (!meta)
83
+ fail(`unknown rule ${id}. Run midnight-shield --list-rules`);
84
+ const doc = join(docsDir(), `${ruleId}.md`);
85
+ if (builtIn && existsSync(doc)) {
86
+ process.stdout.write(readFileSync(doc, "utf8").trimEnd() + "\n");
87
+ }
88
+ else {
89
+ process.stdout.write(`${meta.id} ${meta.name}\n\nSeverity: ${meta.severity}\nConfidence: ${meta.confidence}\n\n${meta.summary}\n`);
90
+ if (meta.docUrl)
91
+ process.stdout.write(`\n${meta.docUrl}\n`);
92
+ }
93
+ }
94
+ async function main(argv) {
95
+ const paths = [];
96
+ let format = "text";
97
+ let output;
98
+ let configPath;
99
+ let failOn;
100
+ let minSeverity;
101
+ let minConfidence;
102
+ let disable;
103
+ const ignore = [];
104
+ const pluginPaths = [];
105
+ let codeFrame = true;
106
+ let sdk;
107
+ let showSuppressed = false;
108
+ let baselinePath;
109
+ let writeBaseline;
110
+ let fix = false;
111
+ let fixDryRun = false;
112
+ let print;
113
+ let command;
114
+ let color = (Boolean(process.stdout.isTTY) || Boolean(process.env.FORCE_COLOR)) && !process.env.NO_COLOR;
115
+ for (let i = 0; i < argv.length; i++) {
116
+ const a = argv[i];
117
+ const value = () => {
118
+ const v = argv[++i];
119
+ if (v === undefined)
120
+ fail(`${a} needs a value`);
121
+ return v;
122
+ };
123
+ switch (a) {
124
+ case "-h":
125
+ case "--help":
126
+ process.stdout.write(HELP);
127
+ return;
128
+ case "-v":
129
+ case "--version":
130
+ process.stdout.write(`${VERSION}\n`);
131
+ return;
132
+ case "--list-rules":
133
+ for (const r of RULES)
134
+ process.stdout.write(`${r.id} ${r.severity.padEnd(8)} ${r.confidence.padEnd(6)} ${r.name.padEnd(28)} ${r.summary}\n`);
135
+ return;
136
+ case "--init":
137
+ if (existsSync(CONFIG_FILE))
138
+ fail(`${CONFIG_FILE} already exists`);
139
+ writeFileSync(CONFIG_FILE, JSON.stringify(DEFAULT_CONFIG, null, 2) + "\n");
140
+ process.stdout.write(`Created ${CONFIG_FILE}\n`);
141
+ return;
142
+ case "-f":
143
+ case "--format":
144
+ format = value();
145
+ if (!["text", "json", "sarif", "markdown", "md"].includes(format))
146
+ fail("--format must be text, json, sarif or markdown");
147
+ if (format === "md")
148
+ format = "markdown";
149
+ break;
150
+ case "-o":
151
+ case "--output":
152
+ output = value();
153
+ break;
154
+ case "-c":
155
+ case "--config":
156
+ configPath = value();
157
+ break;
158
+ case "--fail-on": {
159
+ const v = value();
160
+ failOn = v === "none" ? "none" : parseSeverity(v, "--fail-on");
161
+ break;
162
+ }
163
+ case "--min-severity":
164
+ minSeverity = parseSeverity(value(), "--min-severity");
165
+ break;
166
+ case "--min-confidence":
167
+ minConfidence = parseConfidence(value(), "--min-confidence");
168
+ break;
169
+ case "--disable":
170
+ disable = value()
171
+ .split(",")
172
+ .map((s) => s.trim().toUpperCase())
173
+ .filter(Boolean);
174
+ break;
175
+ case "--ignore":
176
+ ignore.push(value());
177
+ break;
178
+ case "--plugin":
179
+ pluginPaths.push(value());
180
+ break;
181
+ case "--baseline":
182
+ baselinePath = value();
183
+ break;
184
+ case "--write-baseline":
185
+ writeBaseline = value();
186
+ break;
187
+ case "--show-suppressed":
188
+ showSuppressed = true;
189
+ break;
190
+ case "--fix":
191
+ fix = true;
192
+ break;
193
+ case "--fix-dry-run":
194
+ fixDryRun = true;
195
+ break;
196
+ case "--print":
197
+ print = value();
198
+ if (print !== "disclosures")
199
+ fail('--print supports "disclosures"');
200
+ break;
201
+ case "--no-code-frame":
202
+ codeFrame = false;
203
+ break;
204
+ case "--no-sdk":
205
+ sdk = false;
206
+ break;
207
+ case "--no-color":
208
+ color = false;
209
+ break;
210
+ default:
211
+ if (a.startsWith("-"))
212
+ fail(`unknown option ${a}`);
213
+ if (!command && paths.length === 0 && a === "explain")
214
+ command = "explain";
215
+ else
216
+ paths.push(a);
217
+ }
218
+ }
219
+ let config;
220
+ try {
221
+ config = loadConfig(configPath) ?? {};
222
+ }
223
+ catch (e) {
224
+ if (e instanceof ConfigError)
225
+ fail(e.message);
226
+ throw e;
227
+ }
228
+ const configDir = configPath ? dirname(resolve(configPath)) : process.cwd();
229
+ let plugins = [];
230
+ try {
231
+ plugins = [
232
+ ...(await loadPlugins(config.plugins ?? [], configDir)),
233
+ ...(await loadPlugins(pluginPaths, process.cwd())),
234
+ ];
235
+ }
236
+ catch (e) {
237
+ if (e instanceof PluginError)
238
+ fail(e.message);
239
+ throw e;
240
+ }
241
+ if (command === "explain")
242
+ return explain(paths[0], plugins);
243
+ const baselineFile = baselinePath ?? (config.baseline ? resolve(configDir, config.baseline) : undefined);
244
+ let baseline;
245
+ if (baselineFile && !writeBaseline) {
246
+ if (!existsSync(baselineFile))
247
+ fail(`baseline not found: ${baselineFile}`);
248
+ try {
249
+ baseline = readBaseline(baselineFile);
250
+ }
251
+ catch (e) {
252
+ fail(e.message);
253
+ }
254
+ }
255
+ const options = {
256
+ disable: disable ?? config.disable,
257
+ minSeverity: minSeverity ?? config.minSeverity,
258
+ minConfidence: minConfidence ?? config.minConfidence,
259
+ ignore: [...(config.ignore ?? []), ...ignore],
260
+ sdk: sdk ?? config.sdk ?? true,
261
+ plugins,
262
+ baseline,
263
+ includeSuppressed: true,
264
+ };
265
+ const failLevel = failOn ?? config.failOn ?? "high";
266
+ if (paths.length === 0)
267
+ paths.push(".");
268
+ let fileCount;
269
+ let findings;
270
+ try {
271
+ fileCount = listTargetFiles(paths, options.ignore, process.cwd(), options.sdk).length;
272
+ if (print === "disclosures") {
273
+ const entries = mapDisclosuresInFiles(paths, options);
274
+ const out = format === "json" ? JSON.stringify({ tool: "midnight-shield", version: VERSION, disclosures: entries }, null, 2) : format === "markdown" ? formatDisclosuresMarkdown(entries) : formatDisclosures(entries, { color: color && !output });
275
+ if (output)
276
+ writeFileSync(output, out + "\n");
277
+ else
278
+ process.stdout.write(out + "\n");
279
+ return;
280
+ }
281
+ findings = lintFiles(paths, options);
282
+ }
283
+ catch (e) {
284
+ fail(e.message);
285
+ }
286
+ if (fix || fixDryRun) {
287
+ const byFile = new Map();
288
+ for (const f of findings)
289
+ if (f.fix && !f.suppressed)
290
+ byFile.set(f.file, [...(byFile.get(f.file) ?? []), f]);
291
+ for (const [file, fs] of byFile) {
292
+ const rules = fs.map((f) => f.ruleId).join(", ");
293
+ if (fixDryRun) {
294
+ process.stdout.write(`would fix ${file} (${rules})\n`);
295
+ continue;
296
+ }
297
+ const source = readFileSync(file, "utf8");
298
+ writeFileSync(file, applyEdits(source, fs.map((f) => f.fix)));
299
+ process.stdout.write(`fixed ${file} (${rules})\n`);
300
+ }
301
+ if (!byFile.size)
302
+ process.stdout.write("Nothing to fix automatically.\n");
303
+ if (fixDryRun)
304
+ return;
305
+ findings = lintFiles(paths, options); // re-scan after fixing
306
+ }
307
+ if (writeBaseline) {
308
+ const data = createBaseline(findings);
309
+ writeFileSync(writeBaseline, JSON.stringify(data, null, 2) + "\n");
310
+ process.stdout.write(`Wrote ${data.findings.length} accepted finding(s) to ${writeBaseline}\n`);
311
+ return;
312
+ }
313
+ const visible = showSuppressed ? findings : findings.filter((f) => !f.suppressed);
314
+ const active = findings.filter((f) => !f.suppressed);
315
+ const text = (useColor) => formatText(visible, fileCount, { color: useColor, codeFrame });
316
+ const report = format === "json"
317
+ ? formatJson(visible)
318
+ : format === "sarif"
319
+ ? formatSarif(findings, plugins)
320
+ : format === "markdown"
321
+ ? formatMarkdown(visible, fileCount, { date: new Date().toISOString().slice(0, 10) })
322
+ : text(color && !output);
323
+ if (output) {
324
+ writeFileSync(output, report + "\n");
325
+ process.stdout.write(text(color) + "\n");
326
+ }
327
+ else {
328
+ process.stdout.write(report + "\n");
329
+ }
330
+ if (failLevel !== "none") {
331
+ const limit = SEVERITY_ORDER.indexOf(failLevel);
332
+ if (active.some((f) => SEVERITY_ORDER.indexOf(f.severity) <= limit))
333
+ process.exitCode = 1;
334
+ }
335
+ }
336
+ main(process.argv.slice(2)).catch((e) => fail(e.stack ?? String(e)));
@@ -0,0 +1,26 @@
1
+ import { type Confidence, type Severity } from "./rules.js";
2
+ export declare const CONFIG_FILE = "midnight-shield.config.json";
3
+ export interface Config {
4
+ /** rule IDs to skip, e.g. ["MS005"] */
5
+ disable?: string[];
6
+ /** exit with code 1 at or above this severity ("none" never fails) */
7
+ failOn?: Severity | "none";
8
+ /** hide findings below this severity */
9
+ minSeverity?: Severity;
10
+ /** glob patterns of files to skip, relative to the working directory */
11
+ ignore?: string[];
12
+ /** hide findings below this confidence */
13
+ minConfidence?: Confidence;
14
+ /** baseline file of accepted findings */
15
+ baseline?: string;
16
+ /** custom rule modules, relative to the config file */
17
+ plugins?: string[];
18
+ /** also check TypeScript/JavaScript files (default true) */
19
+ sdk?: boolean;
20
+ }
21
+ export declare const DEFAULT_CONFIG: Config;
22
+ export declare class ConfigError extends Error {
23
+ }
24
+ /** Load and validate a config file. Returns undefined when the default file does not exist. */
25
+ export declare function loadConfig(path?: string, cwd?: string): Config | undefined;
26
+ export declare function validateConfig(raw: unknown, source?: string): Config;
@@ -0,0 +1,87 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { CONFIDENCE_ORDER, RULES_BY_ID, SEVERITY_ORDER } from "./rules.js";
4
+ export const CONFIG_FILE = "midnight-shield.config.json";
5
+ export const DEFAULT_CONFIG = {
6
+ disable: [],
7
+ failOn: "high",
8
+ minSeverity: "info",
9
+ minConfidence: "low",
10
+ ignore: [],
11
+ plugins: [],
12
+ sdk: true,
13
+ };
14
+ export class ConfigError extends Error {
15
+ }
16
+ /** Load and validate a config file. Returns undefined when the default file does not exist. */
17
+ export function loadConfig(path, cwd = process.cwd()) {
18
+ const file = resolve(cwd, path ?? CONFIG_FILE);
19
+ if (!existsSync(file)) {
20
+ if (path)
21
+ throw new ConfigError(`config file not found: ${path}`);
22
+ return undefined;
23
+ }
24
+ let raw;
25
+ try {
26
+ raw = JSON.parse(readFileSync(file, "utf8"));
27
+ }
28
+ catch (e) {
29
+ throw new ConfigError(`${file}: invalid JSON (${e.message})`);
30
+ }
31
+ return validateConfig(raw, file);
32
+ }
33
+ export function validateConfig(raw, source = "config") {
34
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
35
+ throw new ConfigError(`${source}: expected a JSON object`);
36
+ const obj = raw;
37
+ const out = {};
38
+ for (const key of Object.keys(obj)) {
39
+ if (!["disable", "failOn", "minSeverity", "minConfidence", "ignore", "baseline", "plugins", "sdk", "$schema"].includes(key))
40
+ throw new ConfigError(`${source}: unknown key "${key}"`);
41
+ }
42
+ if (obj.disable !== undefined) {
43
+ if (!Array.isArray(obj.disable) || !obj.disable.every((x) => typeof x === "string"))
44
+ throw new ConfigError(`${source}: "disable" must be an array of rule IDs`);
45
+ const ids = obj.disable.map((x) => x.toUpperCase());
46
+ const unknown = ids.filter((id) => !RULES_BY_ID.has(id) && /^MS\d{3}$/.test(id));
47
+ if (unknown.length)
48
+ throw new ConfigError(`${source}: unknown rule ID(s) in "disable": ${unknown.join(", ")}`);
49
+ out.disable = ids;
50
+ }
51
+ if (obj.failOn !== undefined) {
52
+ if (obj.failOn !== "none" && !SEVERITY_ORDER.includes(obj.failOn))
53
+ throw new ConfigError(`${source}: "failOn" must be one of ${SEVERITY_ORDER.join(", ")}, none`);
54
+ out.failOn = obj.failOn;
55
+ }
56
+ if (obj.minSeverity !== undefined) {
57
+ if (!SEVERITY_ORDER.includes(obj.minSeverity))
58
+ throw new ConfigError(`${source}: "minSeverity" must be one of ${SEVERITY_ORDER.join(", ")}`);
59
+ out.minSeverity = obj.minSeverity;
60
+ }
61
+ if (obj.minConfidence !== undefined) {
62
+ if (!CONFIDENCE_ORDER.includes(obj.minConfidence))
63
+ throw new ConfigError(`${source}: "minConfidence" must be one of ${CONFIDENCE_ORDER.join(", ")}`);
64
+ out.minConfidence = obj.minConfidence;
65
+ }
66
+ if (obj.baseline !== undefined) {
67
+ if (typeof obj.baseline !== "string")
68
+ throw new ConfigError(`${source}: "baseline" must be a file path`);
69
+ out.baseline = obj.baseline;
70
+ }
71
+ if (obj.plugins !== undefined) {
72
+ if (!Array.isArray(obj.plugins) || !obj.plugins.every((x) => typeof x === "string"))
73
+ throw new ConfigError(`${source}: "plugins" must be an array of module paths`);
74
+ out.plugins = obj.plugins;
75
+ }
76
+ if (obj.sdk !== undefined) {
77
+ if (typeof obj.sdk !== "boolean")
78
+ throw new ConfigError(`${source}: "sdk" must be true or false`);
79
+ out.sdk = obj.sdk;
80
+ }
81
+ if (obj.ignore !== undefined) {
82
+ if (!Array.isArray(obj.ignore) || !obj.ignore.every((x) => typeof x === "string"))
83
+ throw new ConfigError(`${source}: "ignore" must be an array of glob patterns`);
84
+ out.ignore = obj.ignore;
85
+ }
86
+ return out;
87
+ }
@@ -0,0 +1,10 @@
1
+ export interface TextEdit {
2
+ /** 1-based line to insert before */
3
+ line: number;
4
+ insert: string;
5
+ }
6
+ export declare const DEFAULT_PRAGMA = "pragma language_version >= 0.28.0;";
7
+ /** MS006: insert a pragma after any leading comments and blank lines. */
8
+ export declare function pragmaFix(source: string, pragma?: string): TextEdit;
9
+ /** Apply edits to a source string. Edits are applied bottom-up so line numbers stay valid. */
10
+ export declare function applyEdits(source: string, edits: TextEdit[]): string;