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,130 @@
1
+ // Checks for the TypeScript/JavaScript side of a Midnight DApp: the code that
2
+ // talks to the proof server and holds wallet secrets. These are token-level
3
+ // heuristics (no type information), so they report medium confidence.
4
+ import { isSecretName } from "./analyzer.js";
5
+ import { lex } from "./lexer.js";
6
+ export const SDK_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
7
+ export function isSdkFile(file) {
8
+ return SDK_EXTENSIONS.some((ext) => file.endsWith(ext)) && !file.endsWith(".d.ts");
9
+ }
10
+ /** Test files use fake secrets and fake remote servers on purpose, so SDK checks skip them. */
11
+ export function isTestFile(file) {
12
+ const f = file.split("\\").join("/");
13
+ return /(^|\/)(test|tests|__tests__|__mocks__)\//.test(f) || /\.(test|spec)\.[cm]?[jt]sx?$/.test(f);
14
+ }
15
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]", "host.docker.internal", "proof-server"]);
16
+ const LOG_OBJECTS = new Set(["console", "logger", "log"]);
17
+ const LOG_METHODS = new Set(["log", "info", "debug", "warn", "error", "trace"]);
18
+ function urlHost(literal) {
19
+ const m = literal.slice(1, -1).match(/^(?:https?|wss?):\/\/(\[[^\]]+\]|[^/:?#]+)(?::(\d+))?/i);
20
+ return m ? { host: m[1].toLowerCase(), port: m[2] } : undefined;
21
+ }
22
+ /** Identifiers used inside the ${...} parts of a template literal token. */
23
+ function templateExpressionTokens(t) {
24
+ if (!t.value.startsWith("`"))
25
+ return [];
26
+ const out = [];
27
+ const re = /\$\{([^}]*)\}/g;
28
+ let m;
29
+ while ((m = re.exec(t.value))) {
30
+ for (const inner of lex(m[1]).tokens)
31
+ if (inner.kind !== "eof")
32
+ out.push({ ...inner, line: t.line, col: t.col });
33
+ }
34
+ return out;
35
+ }
36
+ const SAFE_PROPERTIES = new Set(["kind", "type", "length", "size", "name", "id", "label", "source", "constructor", "network", "networkId"]);
37
+ const BOUNDARY = new Set([",", ";", "{", "}"]);
38
+ export function lintSdkSource(source) {
39
+ const { tokens } = lex(source);
40
+ const out = [];
41
+ const loc = (t) => ({ line: t.line, col: t.col });
42
+ for (let i = 0; i < tokens.length; i++) {
43
+ const t = tokens[i];
44
+ // MS101: a proof-server URL that is not local
45
+ if (t.kind === "string" && !t.value.startsWith("`")) {
46
+ const u = urlHost(t.value);
47
+ if (u && !LOCAL_HOSTS.has(u.host)) {
48
+ // the property, variable or call this string belongs to (back to the previous , ; { })
49
+ let mentionsProof = false;
50
+ for (let j = i - 1, depth = 0; j >= 0 && j >= i - 16; j--) {
51
+ const v = tokens[j].value;
52
+ if (v === ")" || v === "]")
53
+ depth++;
54
+ else if (v === "(" || v === "[") {
55
+ if (depth === 0) {
56
+ // a call like httpClientProofProvider('...')
57
+ if (/proof/i.test(tokens[j - 1]?.value ?? ""))
58
+ mentionsProof = true;
59
+ continue;
60
+ }
61
+ depth--;
62
+ }
63
+ else if (depth === 0 && BOUNDARY.has(v))
64
+ break;
65
+ if (depth === 0 && (tokens[j].kind === "ident" || tokens[j].kind === "string") && /proof/i.test(v))
66
+ mentionsProof = true;
67
+ }
68
+ if (u.port === "6300" || mentionsProof) {
69
+ out.push({
70
+ ruleId: "MS101",
71
+ severity: "critical",
72
+ confidence: "medium",
73
+ loc: loc(t),
74
+ message: `The proof server points to a remote host (${u.host}). The proof server receives every user's private inputs in plain form, so a remote one sees all of them. Run it locally (http://localhost:6300) or on a machine the user controls.`,
75
+ });
76
+ }
77
+ }
78
+ }
79
+ // MS102: a secret passed to a log call
80
+ if (t.kind === "ident" && LOG_OBJECTS.has(t.value) && tokens[i + 1]?.value === "." && LOG_METHODS.has(tokens[i + 2]?.value ?? "") && tokens[i + 3]?.value === "(") {
81
+ // tokens of the call's arguments, with template ${...} expressions expanded
82
+ let depth = 0;
83
+ const inner = [];
84
+ for (let j = i + 3; j < tokens.length; j++) {
85
+ const v = tokens[j].value;
86
+ if (v === "(")
87
+ depth++;
88
+ else if (v === ")" && --depth === 0)
89
+ break;
90
+ if (j === i + 3)
91
+ continue;
92
+ if (tokens[j].kind === "string")
93
+ inner.push(...templateExpressionTokens(tokens[j]));
94
+ else
95
+ inner.push(tokens[j]);
96
+ }
97
+ // only values passed directly count: `log(secret)` or `${secret}`; a secret passed
98
+ // through another call first (`log(publicKeyOf(secret))`) is a derived value
99
+ const secrets = [];
100
+ let d = 0;
101
+ for (let k = 0; k < inner.length; k++) {
102
+ const tok = inner[k];
103
+ if (tok.value === "(" || tok.value === "[")
104
+ d++;
105
+ else if ((tok.value === ")" || tok.value === "]") && d > 0)
106
+ d--;
107
+ if (d > 0 || tok.kind !== "ident" || !isSecretName(tok.value))
108
+ continue;
109
+ const next = inner[k + 1]?.value;
110
+ const after = inner[k + 2]?.value ?? "";
111
+ if (next === "." && SAFE_PROPERTIES.has(after))
112
+ continue; // secret.kind, seed.length: metadata only
113
+ if (next === "(")
114
+ continue; // isSecret(...): a function, not the value
115
+ if (!secrets.includes(tok.value))
116
+ secrets.push(tok.value);
117
+ }
118
+ if (secrets.length) {
119
+ out.push({
120
+ ruleId: "MS102",
121
+ severity: "high",
122
+ confidence: "medium",
123
+ loc: loc(t),
124
+ message: `'${secrets.join("', '")}' looks like a secret and is passed to ${t.value}.${tokens[i + 2].value}(). Logs are stored and shared (CI output, crash reports, browser consoles). Remove it or log a non-reversible identifier instead.`,
125
+ });
126
+ }
127
+ }
128
+ }
129
+ return out;
130
+ }
@@ -0,0 +1,28 @@
1
+ import type { Decl, Expr, Program, Stmt } from "./ast.js";
2
+ type CircuitDecl = Extract<Decl, {
3
+ kind: "circuit";
4
+ }>;
5
+ type ConstructorDecl = Extract<Decl, {
6
+ kind: "constructor";
7
+ }>;
8
+ export interface WalkContext {
9
+ /** name of the circuit (or "constructor") the node is in */
10
+ circuit: string;
11
+ /** the enclosing circuit is exported */
12
+ exported: boolean;
13
+ /** the node is inside the first argument of an assert(...) */
14
+ inAssert: boolean;
15
+ }
16
+ export interface Visitor {
17
+ decl?(decl: Decl): void;
18
+ circuit?(decl: CircuitDecl | ConstructorDecl, ctx: WalkContext): void;
19
+ statement?(stmt: Stmt, ctx: WalkContext): void;
20
+ expression?(expr: Expr, ctx: WalkContext): void;
21
+ /** a call expression; `callee` is the called name, e.g. "persistentHash" or "balances.insert" */
22
+ call?(expr: Extract<Expr, {
23
+ kind: "call";
24
+ }>, callee: string, ctx: WalkContext): void;
25
+ }
26
+ export declare function calleeName(e: Expr): string;
27
+ export declare function walkProgram(program: Program, visitor: Visitor): void;
28
+ export {};
@@ -0,0 +1,110 @@
1
+ // Generic AST walker, used by custom rules (plugins).
2
+ export function calleeName(e) {
3
+ if (e.kind === "ident")
4
+ return e.name;
5
+ if (e.kind === "member")
6
+ return `${calleeName(e.object)}.${e.property}`;
7
+ return "";
8
+ }
9
+ export function walkProgram(program, visitor) {
10
+ const walkDecls = (decls) => {
11
+ for (const d of decls) {
12
+ visitor.decl?.(d);
13
+ if (d.kind === "module")
14
+ walkDecls(d.decls);
15
+ if (d.kind === "circuit" && d.body) {
16
+ const ctx = { circuit: d.name, exported: d.exported, inAssert: false };
17
+ visitor.circuit?.(d, ctx);
18
+ walkStmts(d.body, ctx, visitor);
19
+ }
20
+ if (d.kind === "constructor") {
21
+ const ctx = { circuit: "constructor", exported: false, inAssert: false };
22
+ visitor.circuit?.(d, ctx);
23
+ walkStmts(d.body, ctx, visitor);
24
+ }
25
+ }
26
+ };
27
+ walkDecls(program.decls);
28
+ }
29
+ function walkStmts(stmts, ctx, v) {
30
+ for (const s of stmts) {
31
+ v.statement?.(s, ctx);
32
+ switch (s.kind) {
33
+ case "const":
34
+ walkExpr(s.init, ctx, v);
35
+ break;
36
+ case "assign":
37
+ walkExpr(s.target, ctx, v);
38
+ walkExpr(s.value, ctx, v);
39
+ break;
40
+ case "if":
41
+ walkExpr(s.test, ctx, v);
42
+ walkStmts(s.then, ctx, v);
43
+ if (s.else)
44
+ walkStmts(s.else, ctx, v);
45
+ break;
46
+ case "for":
47
+ walkExpr(s.iter, ctx, v);
48
+ walkStmts(s.body, ctx, v);
49
+ break;
50
+ case "return":
51
+ if (s.value)
52
+ walkExpr(s.value, ctx, v);
53
+ break;
54
+ case "expr":
55
+ walkExpr(s.expr, ctx, v);
56
+ break;
57
+ case "block":
58
+ walkStmts(s.body, ctx, v);
59
+ break;
60
+ }
61
+ }
62
+ }
63
+ function walkExpr(e, ctx, v) {
64
+ v.expression?.(e, ctx);
65
+ switch (e.kind) {
66
+ case "call": {
67
+ const name = calleeName(e.callee);
68
+ v.call?.(e, name, ctx);
69
+ if (e.callee.kind !== "ident")
70
+ walkExpr(e.callee, ctx, v);
71
+ e.args.forEach((a, i) => walkExpr(a, name === "assert" && i === 0 ? { ...ctx, inAssert: true } : ctx, v));
72
+ break;
73
+ }
74
+ case "member":
75
+ walkExpr(e.object, ctx, v);
76
+ break;
77
+ case "index":
78
+ walkExpr(e.object, ctx, v);
79
+ walkExpr(e.index, ctx, v);
80
+ break;
81
+ case "vector":
82
+ e.elements.forEach((x) => walkExpr(x, ctx, v));
83
+ break;
84
+ case "struct":
85
+ e.fields.forEach((f) => walkExpr(f.value, ctx, v));
86
+ break;
87
+ case "binary":
88
+ walkExpr(e.left, ctx, v);
89
+ walkExpr(e.right, ctx, v);
90
+ break;
91
+ case "unary":
92
+ case "spread":
93
+ walkExpr(e.arg, ctx, v);
94
+ break;
95
+ case "cast":
96
+ walkExpr(e.expr, ctx, v);
97
+ break;
98
+ case "cond":
99
+ walkExpr(e.test, ctx, v);
100
+ walkExpr(e.then, ctx, v);
101
+ walkExpr(e.else, ctx, v);
102
+ break;
103
+ case "lambda":
104
+ if (Array.isArray(e.body))
105
+ walkStmts(e.body, ctx, v);
106
+ else
107
+ walkExpr(e.body, ctx, v);
108
+ break;
109
+ }
110
+ }
@@ -0,0 +1,7 @@
1
+ # MS000 parse-error
2
+
3
+ **Severity:** info
4
+
5
+ Midnight Shield could not parse part of the file, so that part was skipped. The rest of the file is still analyzed.
6
+
7
+ This usually means the file uses syntax the parser does not support yet. Please open an issue with a minimal example: https://github.com/efforthye/midnight-shield/issues
@@ -0,0 +1,46 @@
1
+ # MS001 own-public-key-auth
2
+
3
+ **Severity:** critical
4
+
5
+ ## What it finds
6
+
7
+ `ownPublicKey()` used to decide who may call a circuit: compared with `==` / `!=` to a stored or supplied key, or checked with `.member()` on a ledger set. This includes cases where the value is passed into a helper circuit that does the comparison.
8
+
9
+ ## Why it matters
10
+
11
+ `ownPublicKey()` is not like `msg.sender`. It is supplied by the prover when the proof is built, and nothing in the proof binds it to the caller's wallet. The owner's key is usually public on the ledger, so anyone can supply it and pass the check.
12
+
13
+ The [Midnight security best practices](https://docs.midnight.network/guides/security-best-practices) say the same: "Never authenticate with ownPublicKey()".
14
+
15
+ ## Example
16
+
17
+ ```compact
18
+ export ledger owner: ZswapCoinPublicKey;
19
+
20
+ export circuit withdraw(): [] {
21
+ assert(ownPublicKey() == owner, "not the owner"); // MS001
22
+ }
23
+ ```
24
+
25
+ ## Fix
26
+
27
+ Authorize by proving knowledge of a secret. Store a domain-separated hash of the secret, and recompute it from a witness:
28
+
29
+ ```compact
30
+ witness secretKey(): Bytes<32>;
31
+ export ledger ownerId: Bytes<32>;
32
+
33
+ circuit deriveId(sk: Bytes<32>): Bytes<32> {
34
+ return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:owner:"), sk]);
35
+ }
36
+
37
+ export circuit withdraw(): [] {
38
+ assert(deriveId(secretKey()) == ownerId, "not the owner");
39
+ }
40
+ ```
41
+
42
+ ## Not flagged
43
+
44
+ - `ownPublicKey()` as a payment destination, e.g. `left<ZswapCoinPublicKey, ContractAddress>(ownPublicKey())`.
45
+ - Comparisons with a constant, such as checking for the zero key.
46
+ - `ownPublicKey()` hashed together with a secret before the comparison.
@@ -0,0 +1,42 @@
1
+ # MS002 unconstrained-witness
2
+
3
+ **Severity:** medium
4
+
5
+ ## What it finds
6
+
7
+ A witness whose result reaches public state (through `disclose()` or a ledger write) while no `assert` or `if` anywhere in the file checks its value.
8
+
9
+ ## Why it matters
10
+
11
+ Witnesses run on the user's machine, and the prover can return any value. A circuit that publishes a witness value without checking it lets the user write whatever they want to the ledger: a fake balance, a fake score, a fake state.
12
+
13
+ ## Example
14
+
15
+ ```compact
16
+ witness myBalance(): Uint<64>;
17
+ export ledger balance: Uint<64>;
18
+
19
+ export circuit syncBalance(): [] {
20
+ balance = disclose(myBalance()); // MS002
21
+ }
22
+ ```
23
+
24
+ ## Fix
25
+
26
+ Constrain the value before trusting it: bound its range, check membership in a ledger set or Merkle tree, or check its relation to existing ledger state.
27
+
28
+ ```compact
29
+ export circuit syncBalance(): [] {
30
+ const b = myBalance();
31
+ assert(b <= 1000000, "balance out of range");
32
+ balance = disclose(b);
33
+ }
34
+ ```
35
+
36
+ ## Not flagged
37
+
38
+ To keep noise low, the rule only checks witnesses that report facts: `Boolean`, `Uint`, `Field`, enums, and structs or tuples that contain them. It skips:
39
+
40
+ - free-form data such as `Bytes<n>` and `Opaque` (names, messages, keys),
41
+ - witnesses whose name suggests randomness (`rand`, `salt`, `nonce`, `seed`, `entropy`, `blind`),
42
+ - values that pass through a hash or commitment before becoming public.
@@ -0,0 +1,41 @@
1
+ # MS003 low-entropy-hash
2
+
3
+ **Severity:** high
4
+
5
+ ## What it finds
6
+
7
+ A `persistentHash` / `transientHash` whose private inputs have little entropy (32 bits or less in total), and whose result is made public. Constant inputs (such as a `pad(...)` tag) and public ledger values add no entropy.
8
+
9
+ ## Why it matters
10
+
11
+ A hash hides nothing if the input has few possible values. For a vote (`YES` / `NO`), an age (`Uint<8>`) or a PIN (`Uint<16>`), anyone can hash every candidate and compare with the public hash. Declaring the disclosure with `disclose()` does not make the value secret.
12
+
13
+ ## Example
14
+
15
+ ```compact
16
+ witness myVote(): Vote;
17
+ export ledger ballots: Set<Bytes<32>>;
18
+
19
+ export circuit castVote(): [] {
20
+ const h = persistentHash<Vector<2, Bytes<32>>>([pad(32, "vote:"), myVote() as Field as Bytes<32>]);
21
+ ballots.insert(disclose(h)); // MS003
22
+ }
23
+ ```
24
+
25
+ ## Fix
26
+
27
+ Use a commitment with fresh secret randomness:
28
+
29
+ ```compact
30
+ witness randomness(): Bytes<32>;
31
+
32
+ export circuit castVote(): [] {
33
+ ballots.insert(persistentCommit<Vote>(myVote(), randomness()));
34
+ }
35
+ ```
36
+
37
+ Or include a high-entropy secret (such as a 32-byte secret key) in the hash.
38
+
39
+ ## How entropy is estimated
40
+
41
+ `Boolean` = 1 bit, `Uint<n>` = n bits, `Uint<a..b>` = log2(b - a), enums = log2(member count), `Bytes<n>` = 8n bits, `Field` = 254 bits. Casts keep the smaller of the value's and the target type's entropy. Values of unknown type are treated as high-entropy, so the rule does not guess.
@@ -0,0 +1,41 @@
1
+ # MS004 weak-commitment-randomness
2
+
3
+ **Severity:** high (reuse: medium)
4
+
5
+ ## What it finds
6
+
7
+ A `persistentCommit` / `transientCommit` whose randomness (second argument) is:
8
+
9
+ - constant, such as `pad(32, "salt")` or `default<Bytes<32>>`,
10
+ - read from public ledger state,
11
+ - short (less than 128 bits of entropy), or
12
+ - the same expression used by another commitment of a different value in the same circuit.
13
+
14
+ ## Why it matters
15
+
16
+ A commitment only hides the value if the randomness is secret and unpredictable. With known randomness, anyone can recompute the commitment for every candidate value. Reused randomness lets observers link commitments to each other.
17
+
18
+ ## Example
19
+
20
+ ```compact
21
+ export ledger salt: Bytes<32>;
22
+ export ledger committed: Bytes<32>;
23
+
24
+ export circuit commitAmount(amount: Uint<64>): [] {
25
+ committed = persistentCommit<Uint<64>>(amount, salt); // MS004: public randomness
26
+ }
27
+ ```
28
+
29
+ ## Fix
30
+
31
+ Take fresh 32-byte randomness from a witness for every commitment:
32
+
33
+ ```compact
34
+ witness randomness(): Bytes<32>;
35
+
36
+ export circuit commitAmount(amount: Uint<64>): [] {
37
+ committed = persistentCommit<Uint<64>>(amount, randomness());
38
+ }
39
+ ```
40
+
41
+ If you need several commitments from one seed, derive separate randomness per use, e.g. `persistentHash([pad(32, "myapp:commit:a"), seed])`.
@@ -0,0 +1,32 @@
1
+ # MS005 missing-domain-separation
2
+
3
+ **Severity:** low
4
+
5
+ ## What it finds
6
+
7
+ A `persistentHash` / `transientHash` over private data where none of the inputs is a constant domain tag. When a helper circuit receives the tag as a parameter, the rule checks the callers in the same file before reporting.
8
+
9
+ ## Why it matters
10
+
11
+ If the same secret is hashed for different purposes (a public key, a nullifier, a commitment) without a tag, the outputs can collide or be linked across uses and across contracts. A distinct tag per purpose keeps them independent.
12
+
13
+ ## Example
14
+
15
+ ```compact
16
+ witness secretKey(): Bytes<32>;
17
+ export ledger publicKey: Bytes<32>;
18
+
19
+ export circuit register(): [] {
20
+ publicKey = disclose(persistentHash<Bytes<32>>(secretKey())); // MS005
21
+ }
22
+ ```
23
+
24
+ ## Fix
25
+
26
+ ```compact
27
+ publicKey = disclose(persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:pk:"), secretKey()]));
28
+ ```
29
+
30
+ ## Known limits
31
+
32
+ Library helpers that receive their tag from another file cannot be checked, because Midnight Shield analyzes one file at a time. Suppress with `// shield-disable-next-line MS005` if the tag is supplied by the caller.
@@ -0,0 +1,17 @@
1
+ # MS006 missing-pragma
2
+
3
+ **Severity:** info
4
+
5
+ ## What it finds
6
+
7
+ A file with no `pragma language_version` declaration.
8
+
9
+ ## Why it matters
10
+
11
+ Compact changes between versions. Without a pragma, a contract may compile with a newer compiler whose semantics differ from what it was written and tested for.
12
+
13
+ ## Fix
14
+
15
+ ```compact
16
+ pragma language_version >= 0.28.0;
17
+ ```
@@ -0,0 +1,44 @@
1
+ # MS007 disclosed-secret
2
+
3
+ **Severity:** high · **Confidence:** low (the rule relies on names)
4
+
5
+ ## What it finds
6
+
7
+ The raw value of a witness or circuit parameter whose name says it is a secret (`secretKey`, `localSk`, `_secret`, `seed`, `mnemonic`, `password`, `privateKey`) reaching `disclose()` or a ledger write.
8
+
9
+ ## Why it matters
10
+
11
+ Everything disclosed is visible to anyone who reads the chain. A secret key that is published once can be used by anyone, forever.
12
+
13
+ This often happens when `disclose()` is added only to make a compiler error go away, which is a common pattern in AI-generated code.
14
+
15
+ ## Example
16
+
17
+ ```compact
18
+ witness secretKey(): Bytes<32>;
19
+ export ledger owner: Bytes<32>;
20
+
21
+ constructor() {
22
+ owner = disclose(secretKey()); // MS007
23
+ }
24
+ ```
25
+
26
+ ## Fix
27
+
28
+ Publish a domain-separated hash of the secret (a public identifier), and keep the secret itself private:
29
+
30
+ ```compact
31
+ circuit deriveId(sk: Bytes<32>): Bytes<32> {
32
+ return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:owner:"), sk]);
33
+ }
34
+
35
+ constructor() {
36
+ owner = disclose(deriveId(secretKey()));
37
+ }
38
+ ```
39
+
40
+ ## Not flagged
41
+
42
+ - Hashes, commitments, and other values derived from the secret (for example a public key computed with a standard-library function).
43
+ - Comparisons that involve the secret, such as `assert(deriveId(sk) == owner)`: they reveal one bit, not the secret.
44
+ - Witnesses and parameters whose names do not look secret. Name your secrets clearly so the rule can protect them.
@@ -0,0 +1,59 @@
1
+ # MS008 missing-nullifier
2
+
3
+ **Severity:** medium
4
+
5
+ ## What it finds
6
+
7
+ An exported circuit that authorizes the caller with an anonymous Merkle membership proof (`tree.checkRoot(...)` over private data) and then changes ledger state, without ever asserting that some value is **not** yet in a set (a nullifier check).
8
+
9
+ ## Why it matters
10
+
11
+ A Merkle membership proof says "I am one of the members" without saying which one. That is the point, but it also means the contract cannot tell whether the same member already acted. Without a nullifier, one member can vote, claim, or withdraw as many times as they like.
12
+
13
+ ## Example
14
+
15
+ ```compact
16
+ export ledger voters: MerkleTree<10, Bytes<32>>;
17
+ export ledger yes: Counter;
18
+ witness secretKey(): Bytes<32>;
19
+ witness voterPath(): MerkleTreePath<10, Bytes<32>>;
20
+
21
+ circuit voterLeaf(sk: Bytes<32>): Bytes<32> {
22
+ return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:voter:"), sk]);
23
+ }
24
+
25
+ export circuit voteYes(): [] {
26
+ const path = voterPath();
27
+ assert(disclose(path.leaf == voterLeaf(secretKey())), "not your path");
28
+ assert(voters.checkRoot(disclose(merkleTreePathRoot<10, Bytes<32>>(path))), "not a voter"); // MS008
29
+ yes.increment(1);
30
+ }
31
+ ```
32
+
33
+ ## Fix
34
+
35
+ Derive a nullifier that is unique per member (and per action), check it, and record it:
36
+
37
+ ```compact
38
+ export ledger used: Set<Bytes<32>>;
39
+
40
+ export circuit voteYes(): [] {
41
+ const path = voterPath();
42
+ assert(disclose(path.leaf == voterLeaf(secretKey())), "not your path");
43
+ assert(voters.checkRoot(disclose(merkleTreePathRoot<10, Bytes<32>>(path))), "not a voter");
44
+ const n = disclose(persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:vote:"), secretKey()]));
45
+ assert(!used.member(n), "already voted");
46
+ used.insert(n);
47
+ yes.increment(1);
48
+ }
49
+ ```
50
+
51
+ This follows the nullifier pattern in the [Midnight security best practices](https://docs.midnight.network/guides/security-best-practices): store used nullifiers in a `Set`.
52
+
53
+ ## Not flagged
54
+
55
+ - Circuits that check a nullifier (`assert(!set.member(...))`) anywhere in the circuit or its helpers.
56
+ - Membership checks with `Set.member(...)`: these are usually role or allowlist checks where repeating is intended.
57
+ - Circuits that do not change ledger state.
58
+
59
+ If repeating the action is intended, suppress with `// shield-disable-next-line MS008`.
@@ -0,0 +1,45 @@
1
+ # MS009 unbound-merkle-path
2
+
3
+ **Severity:** high
4
+
5
+ ## What it finds
6
+
7
+ A circuit that checks the root of a Merkle path (`tree.checkRoot(merkleTreePathRoot<n, T>(path))`) but never asserts what the path's leaf is (`path.leaf == ...`).
8
+
9
+ ## Why it matters
10
+
11
+ A Merkle path only proves that *some* leaf is in the tree. Paths are built from public ledger data, so anyone can construct a valid path for someone else's leaf. Unless the circuit checks that the leaf is derived from the caller's own secret, any non-member can pass the membership check with a member's path.
12
+
13
+ ## Example
14
+
15
+ ```compact
16
+ export circuit claim(): [] {
17
+ const path = memberPath();
18
+ assert(members.checkRoot(disclose(merkleTreePathRoot<10, Bytes<32>>(path))), "not a member"); // MS009
19
+ // ...
20
+ }
21
+ ```
22
+
23
+ ## Fix
24
+
25
+ Bind the leaf to a value only the caller can produce:
26
+
27
+ ```compact
28
+ circuit memberLeaf(sk: Bytes<32>): Bytes<32> {
29
+ return persistentHash<Vector<2, Bytes<32>>>([pad(32, "myapp:member:"), sk]);
30
+ }
31
+
32
+ export circuit claim(): [] {
33
+ const path = memberPath();
34
+ assert(disclose(path.leaf == memberLeaf(secretKey())), "not your path");
35
+ assert(members.checkRoot(disclose(merkleTreePathRoot<10, Bytes<32>>(path))), "not a member");
36
+ // ...
37
+ }
38
+ ```
39
+
40
+ The [Midnight security best practices](https://docs.midnight.network/guides/security-best-practices) pair Merkle membership with this kind of path-binding assert.
41
+
42
+ ## Not flagged
43
+
44
+ - Any assert in the same circuit (or a helper it calls) that compares `path.leaf`, before or after the root check, including inside an `if`.
45
+ - Roots stored in a variable first (`const root = merkleTreePathRoot(path); tree.checkRoot(root)`) are followed.