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.
Files changed (53) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +382 -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
package/CHANGELOG.md ADDED
@@ -0,0 +1,68 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [0.4.1] - 2026-11-20
6
+
7
+ ### Changed
8
+
9
+ - Releases are published from GitHub Actions with npm Trusted Publishing (OIDC) and provenance. No npm token is stored in the repository.
10
+ - Playground: cleaner finding cards, Pretendard for text and JetBrains Mono (without ligatures) for code.
11
+ - README: install options and a web playground section with screenshots.
12
+
13
+ ## [0.4.0] - 2026-11-20
14
+
15
+ ### Added
16
+
17
+ - **Disclosure map** (`--print disclosures`): every point where data becomes public (`disclose()`, ledger writes, exported return values), the private inputs that flow there, and whether they are raw, hashed or committed.
18
+ - **Confidence** for every finding (high, medium, low), separate from severity. `--min-confidence` filters by it. Name-based rules report low confidence.
19
+ - **Baselines**: `--write-baseline` records current findings; `--baseline` reports only new ones. Fingerprints survive code moving to other lines.
20
+ - `--show-suppressed`, and SARIF `suppressions` for findings hidden by comments or a baseline.
21
+ - `--format markdown` report for audits and pull requests.
22
+ - `midnight-shield explain <RULE>`.
23
+ - `--fix` / `--fix-dry-run` for fixes that cannot change contract behavior (MS006).
24
+ - **Custom rules** via plugins (`--plugin`, `"plugins"` in config) with an AST visitor API. See `docs/custom-rules.md`.
25
+ - MS010 `linkable-ledger-update`: in contracts with anonymous Merkle membership, the same secret-derived identifier is published by several circuits.
26
+ - **TypeScript/JavaScript checks**: MS101 `remote-proof-server`, MS102 `secret-in-log`. Test files are skipped. `--no-sdk` turns them off.
27
+ - **Web playground** (`playground/`, published with GitHub Pages): paste a contract and see findings and the disclosure map in the browser.
28
+ - **VS Code extension** (`vscode/`): diagnostics as you type, rule links, workspace scan, disclosure map command.
29
+ - **npm package** ready to publish (`npx midnight-shield`), with a release workflow.
30
+ - Corpus verification now also scans the TypeScript/JavaScript files of both corpora (1,052 files).
31
+
32
+ ### Changed
33
+
34
+ - The analysis core no longer depends on Node.js, so it runs in the browser. File-system helpers moved to `node.ts`.
35
+ - `pin` is no longer treated as a secret name (it was mostly version pins).
36
+
37
+ ## [0.3.0] - 2026-11-20
38
+
39
+ ### Added
40
+
41
+ - MS007 `disclosed-secret`: the raw value of a secret-named witness or parameter is made public.
42
+ - MS008 `missing-nullifier`: Merkle-authorized state change without a nullifier check.
43
+ - MS009 `unbound-merkle-path`: Merkle root checked without tying the path's leaf to the caller.
44
+ - Corpus verification (`npm run verify`): scans midnight-examples and OpenZeppelin Contracts for Compact at pinned commits and compares with a reviewed baseline.
45
+ - CI compiles the example contracts with the real Compact compiler.
46
+ - Test suite split into lexer, parser, rules, reporters, CLI, examples and fuzz tests (89 tests, about 97% line coverage). `npm run coverage` prints a coverage report.
47
+
48
+ ### Changed
49
+
50
+ - Circuits are followed up to 8 calls deep (was 4).
51
+
52
+ ## [0.2.0] - 2026-11-20
53
+
54
+ ### Added
55
+
56
+ - Follows `import "path" prefix X_;` into other files.
57
+ - Code frames and rule links in text output.
58
+ - `midnight-shield.config.json` (`--init`, `--config`), `--ignore`, `--no-code-frame`.
59
+ - Claude Code skill in `skills/midnight-shield`.
60
+
61
+ ## [0.1.0] - 2026-11-20
62
+
63
+ ### Added
64
+
65
+ - Compact lexer and parser with error recovery.
66
+ - Data-flow analyzer and rules MS000 to MS006.
67
+ - CLI with text, JSON and SARIF output.
68
+ - GitHub Action with SARIF upload.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 efforthye
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,383 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # 🛡️ Midnight Shield
4
+
5
+ **Static analyzer for Midnight Compact contracts and the TypeScript code around them.**
6
+ Catch security and privacy bugs before you deploy: in your terminal, your editor, your browser, CI, and AI coding agents.
7
+
8
+ [![CI](https://github.com/efforthye/midnight-shield/actions/workflows/ci.yml/badge.svg)](https://github.com/efforthye/midnight-shield/actions/workflows/ci.yml)
9
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
10
+ ![Node](https://img.shields.io/badge/node-%3E%3D20-brightgreen)
11
+ ![Rules](https://img.shields.io/badge/rules-12-purple)
12
+ ![Tests](https://img.shields.io/badge/tests-120%20passing-brightgreen)
13
+ ![Coverage](https://img.shields.io/badge/coverage%20(src)-96%25-brightgreen)
14
+ [![npm](https://img.shields.io/npm/v/midnight-shield?color=orange)](https://www.npmjs.com/package/midnight-shield)
15
+
16
+ [Quick start](#quick-start) · [Web playground](#web-playground) · [Rules](#rules) · [Disclosure map](#disclosure-map) · [Editor](#vs-code) · [CI](#github-action) · [AI agents](#use-with-ai-coding-agents) · [Verification](#testing-and-verification)
17
+
18
+ <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/demo.png" alt="Midnight Shield scanning a vulnerable Compact contract" width="820">
19
+
20
+ **[▶ Try it in your browser](https://efforthye.github.io/midnight-shield/)** · no install, your code never leaves the page
21
+
22
+ <sub>Community project for the Midnight ecosystem. Not an official Midnight Foundation product.</sub>
23
+
24
+ </div>
25
+
26
+ ---
27
+
28
+ ## Why Midnight Shield?
29
+
30
+ The Compact compiler already stops you from disclosing witness data by accident. But a contract can **compile cleanly and still leak or be exploitable**:
31
+
32
+ | Bug | What goes wrong | Rule |
33
+ | --- | --- | --- |
34
+ | "Owner" check with `ownPublicKey()` | The prover supplies that value, so anyone can pass the check | [MS001](docs/rules/MS001.md) |
35
+ | Unchecked witness | The user can write any balance, score, or state to the ledger | [MS002](docs/rules/MS002.md) |
36
+ | Public hash of a vote, age, or PIN | Few possible inputs, so the hash can be brute-forced | [MS003](docs/rules/MS003.md) |
37
+ | Commitment with public or reused randomness | The commitment hides nothing, or links users together | [MS004](docs/rules/MS004.md) |
38
+ | `disclose(secretKey())` | The secret key is published for everyone to read | [MS007](docs/rules/MS007.md) |
39
+ | Merkle membership with no nullifier | One member can vote or claim again and again | [MS008](docs/rules/MS008.md) |
40
+ | Merkle root checked, leaf never checked | Anyone can reuse another member's public path | [MS009](docs/rules/MS009.md) |
41
+ | Same member tag in every circuit | Anonymous members' actions can be linked together | [MS010](docs/rules/MS010.md) |
42
+ | Remote proof server in the DApp | A third party sees every user's private inputs | [MS101](docs/rules/MS101.md) |
43
+ | Wallet seed in a log | The seed ends up in CI logs and crash reports | [MS102](docs/rules/MS102.md) |
44
+
45
+ Midnight Shield is to Midnight what **Slither** is to Solidity and **aztec-lint** is to Noir: a static analyzer that catches issues before deploy, with rules built around Midnight's privacy model.
46
+
47
+ ## Highlights
48
+
49
+ - 🔍 **Real parser and data-flow analysis.** Tracks every value back to witnesses, private inputs, public ledger state, or constants, across helper circuits and imported files.
50
+ - 🗺️ **Disclosure map.** One table of everything your contract makes public, and whether it is raw, hashed or committed. Unique to Midnight.
51
+ - 🎲 **Entropy-aware.** Knows a `Boolean` vote has 1 bit of secret entropy and a `Bytes<32>` key has 256, so it flags brute-forceable hashes without crying wolf.
52
+ - 🎯 **Honest about certainty.** Every finding has a severity *and* a confidence. Rules that rely on names or guess intent say so.
53
+ - 🧪 **Verified on real code, in CI.** 1,052 files of the official examples and OpenZeppelin Contracts for Compact (Compact and TypeScript) at pinned commits: zero parse errors, zero medium-or-worse findings. Examples are compiled with the real Compact compiler.
54
+ - 🧰 **Everywhere you work.** CLI, web playground, VS Code, GitHub Action with SARIF, Markdown reports, Claude Code skill, plugin API.
55
+ - 🏗️ **Easy to adopt.** Baselines accept existing findings so CI only fails on new ones. Zero runtime dependencies.
56
+
57
+ ## Quick start
58
+
59
+ Requires Node.js 20 or later.
60
+
61
+ ```bash
62
+ # run once, no install
63
+ npx midnight-shield contracts/
64
+
65
+ # or add it to your project
66
+ npm install --save-dev midnight-shield
67
+ npx midnight-shield contracts/
68
+
69
+ # or install globally
70
+ npm install -g midnight-shield
71
+ midnight-shield contracts/
72
+ ```
73
+
74
+ Not ready to install anything? Paste a contract into the **[web playground](#web-playground)**.
75
+
76
+ The repository has examples: [`examples/vulnerable.compact`](examples/vulnerable.compact) triggers every Compact rule, [`examples/dapp/vulnerable.ts`](examples/dapp/vulnerable.ts) every TypeScript rule, and the `safe` versions show the fixes (0 findings).
77
+
78
+ ## Web playground
79
+
80
+ **[efforthye.github.io/midnight-shield](https://efforthye.github.io/midnight-shield/)**
81
+
82
+ The full analyzer, compiled to run in the browser. Paste a Compact contract or DApp TypeScript and see findings as you type. Nothing is uploaded: there is no server, so private contract code stays on your machine.
83
+
84
+ | Findings with fixes | Disclosure map |
85
+ | --- | --- |
86
+ | <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/playground.png" alt="Playground findings" width="400"> | <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/playground-disclosures.png" alt="Playground disclosure map" width="400"> |
87
+
88
+ - **Live analysis** of `.compact` and `.ts` code, with problem lines marked in the editor gutter
89
+ - **Disclosure map** tab: every value that becomes public, and whether it is raw, hashed or committed
90
+ - **Examples** to start from: a vulnerable contract, its safe version, and vulnerable DApp code
91
+ - **Share link**: the code is stored in the URL hash, so you can send a finding to a teammate or reviewer
92
+ - **Download report** as Markdown for an audit note or a PR comment
93
+ - Severity filter, light and dark themes, and a mobile layout
94
+
95
+ <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/playground-light.png" alt="Playground checking TypeScript DApp code in light theme" width="820">
96
+
97
+ To run it locally: `npm run playground` builds a single file at `playground/dist/index.html` that you can open directly.
98
+
99
+ ## Usage guide
100
+
101
+ ### 1. Scan
102
+
103
+ ```bash
104
+ npx midnight-shield contracts/ # .compact files and the DApp's .ts/.js files
105
+ npx midnight-shield contracts/ --no-sdk # only .compact files
106
+ ```
107
+
108
+ Midnight Shield skips `node_modules`, `dist`, `build`, compiler output and, for TypeScript checks, test files. It follows `import "..."` into other Compact files.
109
+
110
+ ### 2. Read a finding
111
+
112
+ Each finding shows its **severity**, **rule**, **location** (clickable in most terminals), **confidence** when it is not high, the **message** with the fix, a **code frame**, and a link to the rule page.
113
+
114
+ ```bash
115
+ npx midnight-shield explain MS009 # read a rule's documentation in the terminal
116
+ ```
117
+
118
+ ### 3. Fix and scan again
119
+
120
+ Every rule page shows a vulnerable and a fixed example. Safe fixes can be applied automatically:
121
+
122
+ ```bash
123
+ npx midnight-shield contracts/ --fix-dry-run # see what would change
124
+ npx midnight-shield contracts/ --fix # apply
125
+ ```
126
+
127
+ Only fixes that cannot change what a contract does are automatic (today: adding a missing `pragma`). Fixes that change hashes or commitments would change on-chain values, so they are left to you or to the [AI skill](#use-with-ai-coding-agents).
128
+
129
+ <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/safe.png" alt="No findings" width="820">
130
+
131
+ ### 4. Adopt it in an existing project
132
+
133
+ Accept today's findings and fail CI only on new ones:
134
+
135
+ ```bash
136
+ npx midnight-shield contracts/ --write-baseline .midnight-shield-baseline.json
137
+ npx midnight-shield contracts/ --baseline .midnight-shield-baseline.json
138
+ ```
139
+
140
+ Baseline entries are matched by a fingerprint of the rule and the code line, so moving code around does not break them. `--show-suppressed` lists everything that is hidden by a baseline or an inline comment, for audits.
141
+
142
+ ### 5. Configure
143
+
144
+ ```bash
145
+ npx midnight-shield --init # creates midnight-shield.config.json
146
+ ```
147
+
148
+ ```json
149
+ {
150
+ "disable": [],
151
+ "failOn": "high",
152
+ "minSeverity": "info",
153
+ "minConfidence": "low",
154
+ "ignore": ["**/test/**"],
155
+ "baseline": ".midnight-shield-baseline.json",
156
+ "plugins": ["./tools/our-rules.mjs"],
157
+ "sdk": true
158
+ }
159
+ ```
160
+
161
+ To silence one finding in code, say why next to it:
162
+
163
+ ```compact
164
+ // shield-disable-next-line MS005 -- the tag is supplied by every caller
165
+ const h = persistentHash<Vector<2, Bytes<32>>>([tag, sk]);
166
+ ```
167
+
168
+ `shield-disable-line` and `shield-disable-file` work the same way. Leave out the rule ID to suppress every rule.
169
+
170
+ ### 6. Report
171
+
172
+ ```bash
173
+ npx midnight-shield contracts/ --format markdown -o report.md # audit or PR report
174
+ npx midnight-shield contracts/ --format sarif -o results.sarif # GitHub code scanning
175
+ npx midnight-shield contracts/ --format json # scripts and AI agents
176
+ ```
177
+
178
+ ## Rules
179
+
180
+ <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/rules.png" alt="midnight-shield --list-rules" width="820">
181
+
182
+ **Compact contracts**
183
+
184
+ | ID | Name | Severity | Confidence | Finds |
185
+ | --- | --- | --- | --- | --- |
186
+ | [MS001](docs/rules/MS001.md) | `own-public-key-auth` | 🟣 Critical | high | `ownPublicKey()` compared to a key to authorize the caller, including through helper circuits |
187
+ | [MS002](docs/rules/MS002.md) | `unconstrained-witness` | 🟡 Medium | medium | A witness value reaches public state with no `assert` that checks it |
188
+ | [MS003](docs/rules/MS003.md) | `low-entropy-hash` | 🔴 High | medium | A hash of only low-entropy private values (vote, age, PIN) made public |
189
+ | [MS004](docs/rules/MS004.md) | `weak-commitment-randomness` | 🔴 High | high | A commitment with constant, public, short, or reused randomness |
190
+ | [MS005](docs/rules/MS005.md) | `missing-domain-separation` | 🔵 Low | medium | A hash of private data with no constant domain tag |
191
+ | [MS006](docs/rules/MS006.md) | `missing-pragma` | ⚪ Info | high | No `pragma language_version` (auto-fixable) |
192
+ | [MS007](docs/rules/MS007.md) | `disclosed-secret` | 🔴 High | low | The raw value of a secret key, seed, or password is made public |
193
+ | [MS008](docs/rules/MS008.md) | `missing-nullifier` | 🟡 Medium | low | Merkle-authorized state change with no nullifier, so it can be repeated |
194
+ | [MS009](docs/rules/MS009.md) | `unbound-merkle-path` | 🔴 High | high | Merkle root checked, but the path's leaf is never tied to the caller |
195
+ | [MS010](docs/rules/MS010.md) | `linkable-ledger-update` | 🟡 Medium | medium | In an anonymous-membership contract, the same secret-derived tag is published by several circuits |
196
+
197
+ **DApp code (TypeScript / JavaScript)**
198
+
199
+ | ID | Name | Severity | Confidence | Finds |
200
+ | --- | --- | --- | --- | --- |
201
+ | [MS101](docs/rules/MS101.md) | `remote-proof-server` | 🟣 Critical | medium | The proof server URL points to a remote host |
202
+ | [MS102](docs/rules/MS102.md) | `secret-in-log` | 🔴 High | medium | A seed, secret key or password passed to a log call |
203
+
204
+ Need a rule for your own conventions? [Write a plugin](docs/custom-rules.md).
205
+
206
+ ## Disclosure map
207
+
208
+ On Midnight, everything that becomes public is explicit. The disclosure map lists all of it in one place, so a reviewer can check the privacy of a contract in minutes:
209
+
210
+ ```bash
211
+ npx midnight-shield contracts/ --print disclosures
212
+ ```
213
+
214
+ <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/disclosures.png" alt="Disclosure map" width="820">
215
+
216
+ `RAW` means private data is published as is. That is sometimes intended (a public balance), but every `RAW` row deserves a second look. The map is also available as JSON and Markdown (`--format json|markdown`), in the playground, and in VS Code.
217
+
218
+ ## How it works
219
+
220
+ ```mermaid
221
+ flowchart LR
222
+ A[".compact files"] --> B["Lexer"]
223
+ B --> C["Parser<br/>(syntax tree)"]
224
+ I["Imported modules"] --> D
225
+ C --> D["Data-flow analyzer"]
226
+ D --> E["Rules MS001-MS010<br/>+ plugins"]
227
+ T[".ts / .js files"] --> S["SDK checks<br/>MS101-MS102"]
228
+ E --> F["Config, baseline,<br/>suppressions"]
229
+ S --> F
230
+ D --> M["Disclosure map"]
231
+ F --> G["Text / JSON / SARIF / Markdown<br/>VS Code / Playground"]
232
+ ```
233
+
234
+ For every circuit, the analyzer evaluates each expression to a summary of where its value came from:
235
+
236
+ | Source | Example | Treated as |
237
+ | --- | --- | --- |
238
+ | Witness | `secretKey()` | Private, prover-controlled |
239
+ | Circuit parameter | `amount: Uint<64>` | Private |
240
+ | Ledger state | `owner`, `balances.lookup(k)` | Public |
241
+ | Constant | `pad(32, "app:")`, `default<Bytes<32>>`, enum members | Public, zero entropy |
242
+ | `disclose(x)` | | Public from this point on |
243
+
244
+ Secret entropy is estimated from types (`Boolean` = 1 bit, `Uint<16>` = 16, `Bytes<32>` = 256). Calls to circuits in the same file or in imported modules are evaluated with the caller's arguments, so a check hidden in a helper is still found.
245
+
246
+ The rules follow the [Midnight security best practices](https://docs.midnight.network/guides/security-best-practices) and the [explicit disclosure](https://docs.midnight.network/compact/explicit_disclosure) rules.
247
+
248
+ ## VS Code
249
+
250
+ The extension in [`vscode/`](vscode) shows findings as you type, with links to each rule, a **Scan workspace** command and a **Show disclosure map** command. It reads `midnight-shield.config.json` and inline suppressions. See [`vscode/README.md`](vscode/README.md) to build and install it.
251
+
252
+ ## GitHub Action
253
+
254
+ ```yaml
255
+ # .github/workflows/midnight-shield.yml
256
+ name: Midnight Shield
257
+ on: [push, pull_request]
258
+
259
+ jobs:
260
+ scan:
261
+ runs-on: ubuntu-latest
262
+ permissions:
263
+ contents: read
264
+ security-events: write # show results in the Security tab
265
+ steps:
266
+ - uses: actions/checkout@v4
267
+ - uses: efforthye/midnight-shield@main
268
+ with:
269
+ path: contracts
270
+ fail-on: high
271
+ ```
272
+
273
+ Findings appear in **Security → Code scanning** and as annotations on pull requests.
274
+
275
+ | Input | Default | Description |
276
+ | --- | --- | --- |
277
+ | `path` | `.` | Files or folders to scan |
278
+ | `fail-on` | `high` | Fail the job at or above this severity (`none` to never fail) |
279
+ | `upload-sarif` | `true` | Upload results to GitHub code scanning |
280
+
281
+ ## Use with AI coding agents
282
+
283
+ ### Claude Code skill
284
+
285
+ [`skills/midnight-shield`](skills/midnight-shield/SKILL.md) teaches Claude Code to scan, fix findings in order of severity, check the disclosure map, and re-scan until the contract is clean:
286
+
287
+ ```bash
288
+ mkdir -p .claude/skills
289
+ cp -r node_modules/midnight-shield/skills/midnight-shield .claude/skills/
290
+ ```
291
+
292
+ ### JSON and the library API
293
+
294
+ ```bash
295
+ npx midnight-shield contracts/ --format json --fail-on none
296
+ ```
297
+
298
+ ```ts
299
+ import { lintSource, mapDisclosures } from "midnight-shield";
300
+
301
+ const findings = lintSource(source, "counter.compact");
302
+ const publicData = mapDisclosures(source, "counter.compact");
303
+ ```
304
+
305
+ ## CLI reference
306
+
307
+ ```text
308
+ midnight-shield [paths...] [options]
309
+ midnight-shield explain <RULE>
310
+ midnight-shield --init
311
+
312
+ Output: -f, --format text|json|sarif|markdown -o, --output <file>
313
+ --print disclosures --no-code-frame --no-color
314
+ Filtering: --fail-on <severity> --min-severity <severity> --min-confidence <confidence>
315
+ --disable <IDs> --ignore <glob> --no-sdk --show-suppressed
316
+ Adoption: --baseline <file> --write-baseline <file> --fix --fix-dry-run
317
+ -c, --config <file> --plugin <module>
318
+ Other: --list-rules -v, --version -h, --help
319
+ ```
320
+
321
+ Exit codes: `0` no blocking findings, `1` findings at or above `--fail-on`, `2` usage or config error.
322
+
323
+ ## How it compares
324
+
325
+ | | Compact compiler | [Night Check](https://github.com/CjDabrow/night-check) | **Midnight Shield** |
326
+ | --- | --- | --- | --- |
327
+ | Blocks undeclared witness disclosure | ✅ | | (left to the compiler) |
328
+ | Analysis method | Type checker | Line-by-line patterns | Syntax tree + data flow |
329
+ | Follows values across helper circuits and imports | | | ✅ |
330
+ | Entropy-aware hash and commitment checks | | | ✅ |
331
+ | Disclosure map | | | ✅ |
332
+ | TypeScript/DApp checks | | ✅ | ✅ |
333
+ | Severity + confidence | | Severity | ✅ |
334
+ | Baselines, suppressions, config | | | ✅ |
335
+ | CLI · GitHub Action + SARIF · VS Code | ✅ · · | Demo script | ✅ · ✅ · ✅ |
336
+ | Web UI | | ✅ (with on-chain review receipt) | ✅ (local only) |
337
+ | AI agent skill · plugin API | | | ✅ · ✅ |
338
+ | Verified against real Midnight code in CI | n/a | | ✅ |
339
+
340
+ ## Testing and verification
341
+
342
+ | Check | What it proves | Command |
343
+ | --- | --- | --- |
344
+ | **Unit and integration tests** (120 tests, 96% line coverage of `src/`) | Lexer, parser, every rule (flagged and not-flagged cases), reporters, CLI, baselines, plugins, fixes | `npm test`, `npm run coverage` |
345
+ | **Fuzz tests** | Random token edits, truncations, random bytes, deep nesting and recursive circuits never crash the analyzer | part of `npm test` |
346
+ | **Corpus verification** | 1,052 real files (Compact and TypeScript) at pinned commits: zero parse errors, no medium-or-worse findings, results match a reviewed baseline | `npm run verify` |
347
+ | **Real compiler** | The example contracts compile with the official `compact` toolchain | CI job `compile-examples` |
348
+ | **Package** | The npm tarball installs and the CLI runs | CI job `package` |
349
+
350
+ <img src="https://raw.githubusercontent.com/efforthye/midnight-shield/main/docs/assets/verify.png" alt="Corpus verification output" width="720">
351
+
352
+ ## Roadmap
353
+
354
+ - [x] **v0.1** Parser, data-flow analysis, CLI, GitHub Action, SARIF
355
+ - [x] **v0.2** Imported modules, code frames, config file, Claude Code skill
356
+ - [x] **v0.3** Merkle and secret rules, corpus verification, real-compiler CI
357
+ - [x] **v0.4** Disclosure map, confidence, baselines, Markdown, plugins, autofix, TypeScript checks, playground, VS Code extension, npm package
358
+ - [ ] VS Code Marketplace release
359
+ - [ ] Data-flow facts for plugins
360
+ - [ ] More rules from community feedback
361
+
362
+ Ideas and false-positive reports are welcome in [Issues](https://github.com/efforthye/midnight-shield/issues).
363
+
364
+ ## Development
365
+
366
+ ```bash
367
+ npm install
368
+ npm test # build + tests
369
+ npm run coverage # tests with coverage
370
+ npm run verify # scan real Midnight code and compare with the baseline
371
+ npm run playground # build the web playground into playground/dist
372
+ npm run demo # scan examples/
373
+ ```
374
+
375
+ See [CONTRIBUTING.md](CONTRIBUTING.md), [SECURITY.md](SECURITY.md) and [CHANGELOG.md](CHANGELOG.md).
376
+
377
+ ## Acknowledgements
378
+
379
+ Several initial rule ideas come from [Night Check](https://github.com/CjDabrow/night-check) (MIT). Feature ideas from [Slither](https://github.com/crytic/slither), [Aderyn](https://github.com/Cyfrin/aderyn), [Circomspect](https://github.com/trailofbits/circomspect) and aztec-lint. Built as part of **KR NightForce Cohort 2** (Builder track).
380
+
381
+ ## License
382
+
383
+ [MIT](LICENSE)
package/action.yml ADDED
@@ -0,0 +1,56 @@
1
+ name: Midnight Shield
2
+ description: Static analysis for Midnight Compact contracts. Finds security and privacy issues before deploy.
3
+ author: efforthye
4
+ branding:
5
+ icon: shield
6
+ color: purple
7
+
8
+ inputs:
9
+ path:
10
+ description: Files or directories to scan (space-separated)
11
+ default: "."
12
+ fail-on:
13
+ description: Fail the step if a finding is at or above this severity (critical, high, medium, low, info, none)
14
+ default: "high"
15
+ upload-sarif:
16
+ description: Upload results to GitHub code scanning (requires security-events write permission)
17
+ default: "true"
18
+
19
+ runs:
20
+ using: composite
21
+ steps:
22
+ - uses: actions/setup-node@v4
23
+ with:
24
+ node-version: 20
25
+
26
+ - name: Build Midnight Shield
27
+ shell: bash
28
+ working-directory: ${{ github.action_path }}
29
+ run: |
30
+ npm ci --no-audit --no-fund
31
+ npm run build
32
+
33
+ - name: Scan Compact contracts
34
+ id: scan
35
+ shell: bash
36
+ env:
37
+ SCAN_PATH: ${{ inputs.path }}
38
+ FAIL_ON: ${{ inputs.fail-on }}
39
+ run: |
40
+ set +e
41
+ # shellcheck disable=SC2086
42
+ node "$GITHUB_ACTION_PATH/dist/src/cli.js" $SCAN_PATH --format sarif --output midnight-shield.sarif --fail-on "$FAIL_ON"
43
+ echo "exit-code=$?" >> "$GITHUB_OUTPUT"
44
+
45
+ - name: Upload SARIF
46
+ if: inputs.upload-sarif == 'true'
47
+ uses: github/codeql-action/upload-sarif@v3
48
+ with:
49
+ sarif_file: midnight-shield.sarif
50
+ category: midnight-shield
51
+
52
+ - name: Check result
53
+ shell: bash
54
+ env:
55
+ EXIT_CODE: ${{ steps.scan.outputs.exit-code }}
56
+ run: exit "$EXIT_CODE"
@@ -0,0 +1,97 @@
1
+ import type { Expr, Loc, Program } from "./ast.js";
2
+ import { type Confidence, type Severity } from "./rules.js";
3
+ export interface RawFinding {
4
+ ruleId: string;
5
+ severity: Severity;
6
+ confidence: Confidence;
7
+ message: string;
8
+ loc: Loc;
9
+ }
10
+ export type Protection = "raw" | "hash" | "commit" | "public" | "constant";
11
+ /** A point where data becomes public: disclose(), a ledger write, or an exported circuit's return value. */
12
+ export interface DisclosureEvent {
13
+ circuit: string;
14
+ loc: Loc;
15
+ via: "disclose" | "ledger write" | "return";
16
+ /** ledger field written, when known */
17
+ target?: string;
18
+ /** private inputs that flow into the public value: "witness:sk", "param:amount" */
19
+ sources: string[];
20
+ protection: Protection;
21
+ /** estimated secret entropy in bits (undefined = unknown or high) */
22
+ secretBits?: number;
23
+ }
24
+ /** Does an identifier look like it names a secret? (`secretKey`, `localSk`, `_secret`, `privateKey`) */
25
+ export declare function isSecretName(name: string): boolean;
26
+ /** Resolves an `import "path"` or `include "path"` to a parsed program. */
27
+ export type ImportResolver = (fromFile: string | undefined, target: string) => {
28
+ file: string;
29
+ program: Program;
30
+ } | undefined;
31
+ export declare class Analyzer {
32
+ private program;
33
+ private resolver?;
34
+ private file?;
35
+ private ledgers;
36
+ private witnesses;
37
+ private circuits;
38
+ private visitedFiles;
39
+ private enums;
40
+ private structs;
41
+ private aliases;
42
+ private findings;
43
+ private seen;
44
+ private constrainedWitnesses;
45
+ private witnessSinks;
46
+ private hashSites;
47
+ /** MS010: identity key -> circuits that publish it (first location per circuit) */
48
+ private identityUses;
49
+ /** exported circuits that authorize with anonymous Merkle membership */
50
+ private anonymousCircuits;
51
+ constructor(program: Program, resolver?: ImportResolver | undefined, file?: string | undefined);
52
+ /**
53
+ * Register declarations. Imported modules are registered under their import
54
+ * prefix (e.g. `Utils_hash`) so calls from the analyzed file resolve, and
55
+ * marked external: they are followed when called, but not reported on.
56
+ */
57
+ private collect;
58
+ /** Resolve a name used inside code of the module with `frame.prefix`. */
59
+ private resolveName;
60
+ run(): RawFinding[];
61
+ /**
62
+ * MS002 targets witnesses that report facts (amounts, flags, states, records).
63
+ * Free-form user input (Bytes, Opaque) and randomness are expected to be
64
+ * unconstrained, so they are skipped to avoid noise.
65
+ */
66
+ private isFactualWitness;
67
+ private isFactualType;
68
+ private analyzeDecls;
69
+ private analyzeFunction;
70
+ private paramInfo;
71
+ private report;
72
+ private disclosures;
73
+ getDisclosures(): DisclosureEvent[];
74
+ private recordDisclosure;
75
+ private typeBits;
76
+ private lookup;
77
+ private execBlock;
78
+ private execStmt;
79
+ private markConstrained;
80
+ /** A value becomes public here (disclose() or a ledger write). */
81
+ private sink;
82
+ private evalExpr;
83
+ private evalIdent;
84
+ private ownpkCompare;
85
+ private evalCall;
86
+ /** MS008: look for Merkle membership proofs and nullifier checks inside an assert condition. */
87
+ private scanAuthorization;
88
+ /** Paths are tracked by name within one top-level circuit; helper frames get their own namespace. */
89
+ private pathKey;
90
+ private evalLambda;
91
+ /** Flatten the inputs of a hash: vector literals and struct literals become their elements. */
92
+ private hashInputs;
93
+ private evalHash;
94
+ private evalCommit;
95
+ private inlineCircuit;
96
+ }
97
+ export declare function exprText(e: Expr): string;