@crediolabs/policy-synth 0.2.0 → 0.3.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 (249) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/errors.d.ts +1 -1
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +1 -4
  7. package/dist/install/build-add-context-rule.d.ts +3 -19
  8. package/dist/install/build-add-context-rule.js +3 -98
  9. package/dist/install/build-install-policy.d.ts +4 -53
  10. package/dist/install/build-install-policy.js +44 -123
  11. package/dist/install/index.d.ts +0 -2
  12. package/dist/install/index.js +0 -7
  13. package/dist/predicate/decode.d.ts +1 -1
  14. package/dist/predicate/decode.js +2 -70
  15. package/dist/predicate/encode.js +45 -229
  16. package/dist/predicate/from-json.js +1 -42
  17. package/dist/record/decode.js +3 -8
  18. package/dist/record/freshness.d.ts +17 -11
  19. package/dist/record/freshness.js +28 -18
  20. package/dist/review-card/builder.d.ts +4 -3
  21. package/dist/review-card/builder.js +18 -162
  22. package/dist/review-card/cross-check.js +2 -105
  23. package/dist/review-card/render-leaf.d.ts +4 -0
  24. package/dist/review-card/render-leaf.js +47 -0
  25. package/dist/run/index.d.ts +36 -139
  26. package/dist/run/index.js +125 -437
  27. package/dist/run/schemas.d.ts +168 -1929
  28. package/dist/run/schemas.js +40 -269
  29. package/dist/{synth → simulate}/deny-cases.d.ts +4 -8
  30. package/dist/simulate/deny-cases.js +282 -0
  31. package/dist/simulate/evaluate.d.ts +18 -0
  32. package/dist/simulate/evaluate.js +271 -0
  33. package/dist/simulate/index.d.ts +4 -0
  34. package/dist/simulate/index.js +8 -0
  35. package/dist/synth/compose-from-recording.d.ts +24 -51
  36. package/dist/synth/compose-from-recording.js +120 -282
  37. package/dist/synth/index.d.ts +0 -5
  38. package/dist/synth/index.js +0 -5
  39. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  40. package/dist/synth/synthesize-from-recording.js +41 -356
  41. package/dist/types.d.ts +8 -60
  42. package/dist/types.js +5 -2
  43. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  44. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  45. package/dist-cjs/errors.d.ts +1 -1
  46. package/dist-cjs/index.d.ts +1 -4
  47. package/dist-cjs/index.js +1 -4
  48. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  49. package/dist-cjs/install/build-add-context-rule.js +1 -97
  50. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  51. package/dist-cjs/install/build-install-policy.js +44 -122
  52. package/dist-cjs/install/index.d.ts +0 -2
  53. package/dist-cjs/install/index.js +2 -23
  54. package/dist-cjs/predicate/decode.d.ts +1 -1
  55. package/dist-cjs/predicate/decode.js +2 -70
  56. package/dist-cjs/predicate/encode.js +45 -229
  57. package/dist-cjs/predicate/from-json.js +1 -42
  58. package/dist-cjs/record/decode.js +3 -8
  59. package/dist-cjs/record/freshness.d.ts +17 -11
  60. package/dist-cjs/record/freshness.js +28 -18
  61. package/dist-cjs/review-card/builder.d.ts +4 -3
  62. package/dist-cjs/review-card/builder.js +23 -167
  63. package/dist-cjs/review-card/cross-check.js +7 -110
  64. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  65. package/dist-cjs/review-card/render-leaf.js +52 -0
  66. package/dist-cjs/run/index.d.ts +36 -139
  67. package/dist-cjs/run/index.js +125 -444
  68. package/dist-cjs/run/schemas.d.ts +168 -1929
  69. package/dist-cjs/run/schemas.js +41 -270
  70. package/dist-cjs/{synth → simulate}/deny-cases.d.ts +4 -8
  71. package/dist-cjs/simulate/deny-cases.js +286 -0
  72. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  73. package/dist-cjs/simulate/evaluate.js +274 -0
  74. package/dist-cjs/simulate/index.d.ts +4 -0
  75. package/dist-cjs/simulate/index.js +13 -0
  76. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  77. package/dist-cjs/synth/compose-from-recording.js +120 -282
  78. package/dist-cjs/synth/index.d.ts +0 -5
  79. package/dist-cjs/synth/index.js +1 -11
  80. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  81. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  82. package/dist-cjs/types.d.ts +8 -60
  83. package/dist-cjs/types.js +6 -3
  84. package/package.json +5 -5
  85. package/src/adapters/interpreter/adapter.ts +76 -572
  86. package/src/errors.ts +0 -19
  87. package/src/index.ts +1 -4
  88. package/src/install/build-add-context-rule.ts +5 -139
  89. package/src/install/build-install-policy.ts +93 -214
  90. package/src/install/index.ts +0 -34
  91. package/src/predicate/decode.ts +2 -70
  92. package/src/predicate/encode.ts +49 -261
  93. package/src/predicate/from-json.ts +1 -43
  94. package/src/record/decode.ts +3 -8
  95. package/src/record/freshness.ts +29 -18
  96. package/src/review-card/builder.ts +19 -168
  97. package/src/review-card/cross-check.ts +3 -105
  98. package/src/review-card/render-leaf.ts +48 -0
  99. package/src/run/index.ts +144 -572
  100. package/src/run/schemas.ts +42 -291
  101. package/src/simulate/deny-cases.ts +334 -0
  102. package/src/simulate/evaluate.ts +284 -0
  103. package/src/simulate/index.ts +11 -0
  104. package/src/synth/compose-from-recording.ts +148 -347
  105. package/src/synth/index.ts +0 -13
  106. package/src/synth/synthesize-from-recording.ts +43 -456
  107. package/src/types.ts +13 -49
  108. package/dist/adapters/interpreter/index.d.ts +0 -1
  109. package/dist/adapters/interpreter/index.js +0 -2
  110. package/dist/adapters/oz/adapter.d.ts +0 -20
  111. package/dist/adapters/oz/adapter.js +0 -295
  112. package/dist/adapters/oz/index.d.ts +0 -1
  113. package/dist/adapters/oz/index.js +0 -2
  114. package/dist/codegen/compile-gate.d.ts +0 -33
  115. package/dist/codegen/compile-gate.js +0 -124
  116. package/dist/codegen/index.d.ts +0 -2
  117. package/dist/codegen/index.js +0 -8
  118. package/dist/codegen/template.d.ts +0 -18
  119. package/dist/codegen/template.js +0 -148
  120. package/dist/install/authority-overlap.d.ts +0 -134
  121. package/dist/install/authority-overlap.js +0 -0
  122. package/dist/install/build-install-predicate.d.ts +0 -96
  123. package/dist/install/build-install-predicate.js +0 -444
  124. package/dist/install/build-merge-policy.d.ts +0 -70
  125. package/dist/install/build-merge-policy.js +0 -130
  126. package/dist/install/plan-merge-policy.d.ts +0 -49
  127. package/dist/install/plan-merge-policy.js +0 -86
  128. package/dist/install/read-account-rules.d.ts +0 -100
  129. package/dist/install/read-account-rules.js +0 -283
  130. package/dist/ir/index.d.ts +0 -1
  131. package/dist/ir/index.js +0 -2
  132. package/dist/ir/types.d.ts +0 -140
  133. package/dist/ir/types.js +0 -11
  134. package/dist/mandate/index.d.ts +0 -2
  135. package/dist/mandate/index.js +0 -2
  136. package/dist/mandate/to-ir.d.ts +0 -3
  137. package/dist/mandate/to-ir.js +0 -60
  138. package/dist/mandate/types.d.ts +0 -20
  139. package/dist/mandate/types.js +0 -8
  140. package/dist/seams/index.d.ts +0 -1
  141. package/dist/seams/index.js +0 -2
  142. package/dist/seams/types.d.ts +0 -66
  143. package/dist/seams/types.js +0 -11
  144. package/dist/synth/deny-cases.js +0 -562
  145. package/dist/synth/evaluate.d.ts +0 -39
  146. package/dist/synth/evaluate.js +0 -551
  147. package/dist/synth/harness.d.ts +0 -28
  148. package/dist/synth/harness.js +0 -47
  149. package/dist/synth/minimize.d.ts +0 -4
  150. package/dist/synth/minimize.js +0 -38
  151. package/dist/synth/permit-context.d.ts +0 -15
  152. package/dist/synth/permit-context.js +0 -116
  153. package/dist/synth/predicate-literals.d.ts +0 -5
  154. package/dist/synth/predicate-literals.js +0 -25
  155. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  156. package/dist/synth/synthesize-from-mandate.js +0 -59
  157. package/dist/verify/envelope.d.ts +0 -15
  158. package/dist/verify/envelope.js +0 -22
  159. package/dist/verify/index.d.ts +0 -3
  160. package/dist/verify/index.js +0 -3
  161. package/dist/verify/simulate.d.ts +0 -31
  162. package/dist/verify/simulate.js +0 -258
  163. package/dist/verify/verify.d.ts +0 -21
  164. package/dist/verify/verify.js +0 -189
  165. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  166. package/dist-cjs/adapters/interpreter/index.js +0 -8
  167. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  168. package/dist-cjs/adapters/oz/adapter.js +0 -300
  169. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  170. package/dist-cjs/adapters/oz/index.js +0 -8
  171. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  172. package/dist-cjs/codegen/compile-gate.js +0 -128
  173. package/dist-cjs/codegen/index.d.ts +0 -2
  174. package/dist-cjs/codegen/index.js +0 -14
  175. package/dist-cjs/codegen/template.d.ts +0 -18
  176. package/dist-cjs/codegen/template.js +0 -151
  177. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  178. package/dist-cjs/install/authority-overlap.js +0 -0
  179. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  180. package/dist-cjs/install/build-install-predicate.js +0 -479
  181. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  182. package/dist-cjs/install/build-merge-policy.js +0 -134
  183. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  184. package/dist-cjs/install/plan-merge-policy.js +0 -90
  185. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  186. package/dist-cjs/install/read-account-rules.js +0 -296
  187. package/dist-cjs/ir/index.d.ts +0 -1
  188. package/dist-cjs/ir/index.js +0 -3
  189. package/dist-cjs/ir/types.d.ts +0 -140
  190. package/dist-cjs/ir/types.js +0 -12
  191. package/dist-cjs/mandate/index.d.ts +0 -2
  192. package/dist-cjs/mandate/index.js +0 -6
  193. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  194. package/dist-cjs/mandate/to-ir.js +0 -63
  195. package/dist-cjs/mandate/types.d.ts +0 -20
  196. package/dist-cjs/mandate/types.js +0 -9
  197. package/dist-cjs/seams/index.d.ts +0 -1
  198. package/dist-cjs/seams/index.js +0 -3
  199. package/dist-cjs/seams/types.d.ts +0 -66
  200. package/dist-cjs/seams/types.js +0 -12
  201. package/dist-cjs/synth/deny-cases.js +0 -568
  202. package/dist-cjs/synth/evaluate.d.ts +0 -39
  203. package/dist-cjs/synth/evaluate.js +0 -554
  204. package/dist-cjs/synth/harness.d.ts +0 -28
  205. package/dist-cjs/synth/harness.js +0 -50
  206. package/dist-cjs/synth/minimize.d.ts +0 -4
  207. package/dist-cjs/synth/minimize.js +0 -41
  208. package/dist-cjs/synth/permit-context.d.ts +0 -15
  209. package/dist-cjs/synth/permit-context.js +0 -119
  210. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  211. package/dist-cjs/synth/predicate-literals.js +0 -28
  212. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  213. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  214. package/dist-cjs/verify/envelope.d.ts +0 -15
  215. package/dist-cjs/verify/envelope.js +0 -23
  216. package/dist-cjs/verify/index.d.ts +0 -3
  217. package/dist-cjs/verify/index.js +0 -8
  218. package/dist-cjs/verify/simulate.d.ts +0 -31
  219. package/dist-cjs/verify/simulate.js +0 -261
  220. package/dist-cjs/verify/verify.d.ts +0 -21
  221. package/dist-cjs/verify/verify.js +0 -192
  222. package/src/adapters/interpreter/index.ts +0 -8
  223. package/src/adapters/oz/adapter.ts +0 -376
  224. package/src/adapters/oz/index.ts +0 -9
  225. package/src/codegen/compile-gate.ts +0 -167
  226. package/src/codegen/index.ts +0 -17
  227. package/src/codegen/template.ts +0 -165
  228. package/src/install/authority-overlap.ts +0 -0
  229. package/src/install/build-merge-policy.ts +0 -219
  230. package/src/install/plan-merge-policy.ts +0 -133
  231. package/src/install/read-account-rules.ts +0 -376
  232. package/src/ir/index.ts +0 -13
  233. package/src/ir/types.ts +0 -132
  234. package/src/mandate/index.ts +0 -4
  235. package/src/mandate/to-ir.ts +0 -71
  236. package/src/mandate/types.ts +0 -21
  237. package/src/seams/index.ts +0 -11
  238. package/src/seams/types.ts +0 -81
  239. package/src/synth/deny-cases.ts +0 -663
  240. package/src/synth/evaluate.ts +0 -613
  241. package/src/synth/harness.ts +0 -68
  242. package/src/synth/minimize.ts +0 -48
  243. package/src/synth/permit-context.ts +0 -136
  244. package/src/synth/predicate-literals.ts +0 -27
  245. package/src/synth/synthesize-from-mandate.ts +0 -82
  246. package/src/verify/envelope.ts +0 -28
  247. package/src/verify/index.ts +0 -5
  248. package/src/verify/simulate.ts +0 -311
  249. package/src/verify/verify.ts +0 -243
@@ -0,0 +1,282 @@
1
+ import { Address } from '@stellar/stellar-sdk';
2
+ import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
3
+ /** A contract address that is not the pinned one. It must be a REAL strkey:
4
+ * the host rejects a malformed one with `Error(Value, InvalidInput)` before
5
+ * the predicate is ever evaluated, which would make the deny case pass for
6
+ * the wrong reason. */
7
+ const OTHER_CONTRACT = Address.contract(Buffer.alloc(32, 0x5a)).toString();
8
+ /** Build deterministic model-evaluated alternatives without mutating the intended call.
9
+ *
10
+ * @param predicate - the synthesized predicate
11
+ * @param permitCtx - EvalContext for the intended (permitted) call
12
+ * @param dimensions - optional whitelist of dimension names to emit; when omitted
13
+ * all known dimensions (including over-permissiveness mutations)
14
+ * are emitted. */
15
+ export function generateCases(predicate, permitCtx, dimensions) {
16
+ const facts = inspectPredicate(predicate);
17
+ const denies = [];
18
+ // contract_scope: the same call sent to a different contract. The predicate
19
+ // pins `call_contract`, so this is the most direct bypass attempt there is -
20
+ // point the agent's authorised call at another contract entirely.
21
+ if (facts.comparisons.some((c) => c.op === 'eq' && c.left.kind === 'call_contract')) {
22
+ denies.push({
23
+ dimension: 'contract_scope',
24
+ ctx: { ...permitCtx, contract: OTHER_CONTRACT },
25
+ expectedReason: 'CONTRACT_SCOPE',
26
+ });
27
+ }
28
+ // function_scope: the same arguments sent to a different method on the
29
+ // pinned contract. `transfer` and `burn` take the same shape; only the
30
+ // `call_fn` pin separates them.
31
+ if (facts.comparisons.some((c) => c.op === 'eq' && c.left.kind === 'call_fn')) {
32
+ denies.push({
33
+ dimension: 'function_scope',
34
+ ctx: { ...permitCtx, fn: `${permitCtx.fn}_not` },
35
+ expectedReason: 'ARG_MISMATCH',
36
+ });
37
+ }
38
+ // arg_bound: set a constrained arg to an opaque ScVal.
39
+ // The reason depends on the predicate shape:
40
+ // - an `eq(call_arg[i], literal)` denies with ARG_MISMATCH
41
+ // - an `in(call_arg[i], [literals])` denies with NOT_IN_ALLOWLIST
42
+ // Both are correct in the TS evaluator; the reason is predicate-dependent
43
+ // so we cannot pin a single canonical reason here.
44
+ const argumentConstraints = [];
45
+ for (const comparison of facts.comparisons) {
46
+ if (comparison.op === 'eq' &&
47
+ comparison.left.kind === 'call_arg' &&
48
+ comparison.right.kind !== 'literal_vec') {
49
+ argumentConstraints.push({ index: comparison.left.index });
50
+ }
51
+ }
52
+ for (const membership of facts.memberships) {
53
+ if (membership.needle.kind === 'call_arg') {
54
+ argumentConstraints.push({ index: membership.needle.index });
55
+ }
56
+ }
57
+ for (const constraint of argumentConstraints) {
58
+ const ctx = cloneContext(permitCtx);
59
+ ctx.args[constraint.index] = { type: 'other', value: 'deny-case-opaque-argument' };
60
+ denies.push({ dimension: 'arg_bound', ctx });
61
+ }
62
+ // soroswap_allowed_path: replace a bound vec arg with a different vector.
63
+ // Still valid for eq comparisons on literal_vec leaves.
64
+ for (const comparison of facts.comparisons) {
65
+ if (comparison.op !== 'eq' ||
66
+ comparison.left.kind !== 'call_arg' ||
67
+ comparison.right.kind !== 'literal_vec') {
68
+ continue;
69
+ }
70
+ const ctx = cloneContext(permitCtx);
71
+ ctx.args[comparison.left.index] = differentVector(ctx.args[comparison.left.index]);
72
+ denies.push({ dimension: 'soroswap_allowed_path', ctx });
73
+ }
74
+ // argument_reorder: swap first two address args.
75
+ // Skipped when dimensions filter is active so the synth pipeline can emit a policy;
76
+ // the over-permissiveness harness then tests this mutation as a FINDING.
77
+ const constrainedArgIndices = new Set();
78
+ for (const comparison of facts.comparisons) {
79
+ if (comparison.left.kind === 'call_arg')
80
+ constrainedArgIndices.add(comparison.left.index);
81
+ }
82
+ for (const membership of facts.memberships) {
83
+ if (membership.needle.kind === 'call_arg')
84
+ constrainedArgIndices.add(membership.needle.index);
85
+ }
86
+ const hasConstrainedArg = constrainedArgIndices.size > 0;
87
+ if ((!dimensions || dimensions.includes('argument_reorder')) &&
88
+ hasConstrainedArg &&
89
+ permitCtx.args.length >= 2 &&
90
+ permitCtx.args[0]?.type === 'address' &&
91
+ permitCtx.args[1]?.type === 'address' &&
92
+ permitCtx.args[0].value !==
93
+ permitCtx.args[1].value) {
94
+ const ctx = cloneContext(permitCtx);
95
+ // Guard above guarantees args[0] and args[1] exist and are address-typed.
96
+ const a0 = ctx.args[0];
97
+ const a1 = ctx.args[1];
98
+ ctx.args[0] = a1;
99
+ ctx.args[1] = a0;
100
+ denies.push({ dimension: 'argument_reorder', ctx });
101
+ }
102
+ // map_field_flip: flip a bound map field to a different valid value of
103
+ // the same type. OPT-IN only, never ORIGINAL.
104
+ // Targets each `call_arg_field` leaf and produces a ctx whose vec element
105
+ // has a different value of the recorded field. ---
106
+ if (!dimensions || dimensions.includes('map_field_flip')) {
107
+ for (const comparison of facts.comparisons) {
108
+ const sel = comparison.left;
109
+ if (sel.kind !== 'call_arg_field')
110
+ continue;
111
+ const arg = permitCtx.args[sel.index];
112
+ if (arg?.type !== 'vec')
113
+ continue;
114
+ const element = arg.value[sel.element];
115
+ if (element?.type !== 'map' || !Array.isArray(element.value))
116
+ continue;
117
+ const entry = element.value.find((e) => e.key === sel.field);
118
+ if (!entry)
119
+ continue;
120
+ const flipped = flipFieldValue(entry.val);
121
+ if (flipped === null)
122
+ continue;
123
+ const ctx = cloneContext(permitCtx);
124
+ const clonedVec = arg.value.map(cloneScVal);
125
+ const clonedElement = clonedVec[sel.element];
126
+ if (clonedElement?.type !== 'map' || !Array.isArray(clonedElement.value))
127
+ continue;
128
+ clonedElement.value = clonedElement.value.map((e) => e.key === sel.field ? { key: e.key, val: flipped } : e);
129
+ clonedVec[sel.element] = clonedElement;
130
+ ctx.args[sel.index] = { type: 'vec', value: clonedVec };
131
+ denies.push({ dimension: 'map_field_flip', ctx });
132
+ }
133
+ }
134
+ // amount_over_cap: push a capped value one unit past its cap.
135
+ //
136
+ // Every value bound is an `lte`, and `arg_bound` only targets `eq`, so
137
+ // without this the headline guarantee - "never more than this much per
138
+ // call" - had nothing exercising it. One over the cap is the smallest
139
+ // mutation that must be refused; if the cap held only for larger overshoots
140
+ // it would not be a cap.
141
+ if (!dimensions || dimensions.includes('amount_over_cap')) {
142
+ for (const comparison of facts.comparisons) {
143
+ if (comparison.op !== 'lte')
144
+ continue;
145
+ const cap = literalInteger(comparison.right);
146
+ if (cap === null)
147
+ continue;
148
+ const over = { type: 'i128', value: (cap + 1n).toString() };
149
+ const sel = comparison.left;
150
+ if (sel.kind === 'call_arg') {
151
+ const ctx = cloneContext(permitCtx);
152
+ ctx.args[sel.index] = over;
153
+ denies.push({ dimension: 'amount_over_cap', ctx, expectedReason: 'ARG_MISMATCH' });
154
+ continue;
155
+ }
156
+ if (sel.kind !== 'call_arg_field')
157
+ continue;
158
+ const arg = permitCtx.args[sel.index];
159
+ if (arg?.type !== 'vec')
160
+ continue;
161
+ const ctx = cloneContext(permitCtx);
162
+ const clonedVec = arg.value.map(cloneScVal);
163
+ const clonedElement = clonedVec[sel.element];
164
+ if (clonedElement?.type !== 'map' || !Array.isArray(clonedElement.value))
165
+ continue;
166
+ clonedElement.value = clonedElement.value.map((e) => e.key === sel.field ? { key: e.key, val: over } : e);
167
+ clonedVec[sel.element] = clonedElement;
168
+ ctx.args[sel.index] = { type: 'vec', value: clonedVec };
169
+ denies.push({ dimension: 'amount_over_cap', ctx, expectedReason: 'ARG_MISMATCH' });
170
+ }
171
+ }
172
+ // vec_append: append a new element to a bound vec. OPT-IN only, never ORIGINAL.
173
+ // Targets every `call_arg_len` leaf; without the length pin a caller can
174
+ // append an extra element to defeat per-element binds. ---
175
+ if (!dimensions || dimensions.includes('vec_append')) {
176
+ for (const comparison of facts.comparisons) {
177
+ const sel = comparison.left;
178
+ if (sel.kind !== 'call_arg_len')
179
+ continue;
180
+ const arg = permitCtx.args[sel.index];
181
+ if (arg?.type !== 'vec')
182
+ continue;
183
+ const ctx = cloneContext(permitCtx);
184
+ ctx.args[sel.index] = {
185
+ type: 'vec',
186
+ value: [...arg.value, { type: 'other', value: 'deny-case-vec-append' }],
187
+ };
188
+ denies.push({ dimension: 'vec_append', ctx });
189
+ }
190
+ }
191
+ return { permit: cloneContext(permitCtx), denies };
192
+ }
193
+ function inspectPredicate(predicate) {
194
+ const facts = { comparisons: [], memberships: [] };
195
+ visit(predicate, facts);
196
+ return facts;
197
+ }
198
+ function visit(node, facts) {
199
+ switch (node.op) {
200
+ case 'and':
201
+ for (const child of node.children)
202
+ visit(child, facts);
203
+ return;
204
+ case 'in':
205
+ facts.memberships.push(node);
206
+ return;
207
+ case 'eq':
208
+ case 'lte':
209
+ facts.comparisons.push(node);
210
+ }
211
+ }
212
+ /** The integer a numeric literal leaf carries, or null when the leaf is not
213
+ * numeric (an address or a vector has no cap to exceed). */
214
+ function literalInteger(leaf) {
215
+ if (leaf.kind === 'literal_i128')
216
+ return BigInt(leaf.value);
217
+ if (leaf.kind === 'literal_u32')
218
+ return BigInt(leaf.value);
219
+ return null;
220
+ }
221
+ function differentVector(actual) {
222
+ if (actual?.type !== 'vec')
223
+ return { type: 'vec', value: [] };
224
+ if (actual.value.length === 0) {
225
+ return { type: 'vec', value: [{ type: 'other', value: 'deny-case-extra-hop' }] };
226
+ }
227
+ if (actual.value.length > 1) {
228
+ const reversed = actual.value.map(cloneScVal).reverse();
229
+ if (JSON.stringify(reversed) !== JSON.stringify(actual.value)) {
230
+ return { type: 'vec', value: reversed };
231
+ }
232
+ }
233
+ const value = actual.value.map(cloneScVal);
234
+ value[0] = { type: 'other', value: 'deny-case-different-hop' };
235
+ return { type: 'vec', value };
236
+ }
237
+ function cloneContext(ctx) {
238
+ return {
239
+ contract: ctx.contract,
240
+ fn: ctx.fn,
241
+ args: ctx.args.map(cloneScVal),
242
+ };
243
+ }
244
+ /** Deep-copy an ScVal so a mutation cannot alias the recorded call.
245
+ * Exported so the permit-context builder shares this one implementation. */
246
+ export function cloneScVal(value, depth = 0) {
247
+ if (value.type === 'vec') {
248
+ if (depth >= MAX_SCVAL_CLONE_DEPTH) {
249
+ throw cloneDepthError(value);
250
+ }
251
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
252
+ }
253
+ return { ...value };
254
+ }
255
+ function cloneDepthError(value) {
256
+ const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
257
+ err.code = 'SYNTHESIS_ERROR';
258
+ err.severity = 'error';
259
+ err.retryable = false;
260
+ err.depthContext = value.type;
261
+ throw err;
262
+ }
263
+ /** Build a value of the SAME ScVal type that differs from the recorded one,
264
+ * used by the `map_field_flip` mutation to defeat a per-element pin without
265
+ * changing the wire type. Returns null when the ScVal type has no obvious
266
+ * different value (e.g. opaque/other). */
267
+ function flipFieldValue(val) {
268
+ switch (val.type) {
269
+ case 'address': {
270
+ const a = 'GBFKRGJYZXLTDEI36ZCQEIM225NMOCR2VDBOIHJTXJ54FEFFVL2FKALE';
271
+ const b = 'GD6XSMQJ47EHHJOWXQOND5YDVZC37JWZJHYHBKE6QJFSLLJ5KQXM5QS5';
272
+ return { type: 'address', value: val.value === a ? b : a };
273
+ }
274
+ case 'i128':
275
+ case 'u32':
276
+ return { type: val.type, value: String(BigInt(val.value) + 1n) };
277
+ case 'symbol':
278
+ return { type: 'symbol', value: `${val.value}x` };
279
+ default:
280
+ return null;
281
+ }
282
+ }
@@ -0,0 +1,18 @@
1
+ import type { PredicateNode, ScVal } from '../types.ts';
2
+ export interface EvalContext {
3
+ /** Contract the interpreter is asked to enforce against. */
4
+ contract: string;
5
+ /** Function name on that contract. */
6
+ fn: string;
7
+ /** Decoded `ScVal[]` of the top-level authorized call. */
8
+ args: ScVal[];
9
+ }
10
+ export type EvalResult = {
11
+ permit: true;
12
+ } | {
13
+ permit: false;
14
+ reason: string;
15
+ };
16
+ /** Evaluate a `PredicateNode` against the candidate call described by `ctx`.
17
+ * Pure function. Returns `{ permit: true }` or `{ permit: false; reason }`. */
18
+ export declare function evaluate(predicate: PredicateNode, ctx: EvalContext): EvalResult;
@@ -0,0 +1,271 @@
1
+ // src/simulate/evaluate.ts - TypeScript reference evaluator for grammar version 3.
2
+ //
3
+ // Pure function. Determinism: same `(predicate, ctx)` -> byte-identical result,
4
+ // no clock, no randomness. Deny order (deny on FIRST violation, stable reason):
5
+ // 1. contract mismatch -> 'CONTRACT_SCOPE'
6
+ // 2. per-ScVal equality on fn/args; EXACT ordered vector
7
+ // equality; fail-closed on opaque args -> 'ARG_MISMATCH'
8
+ // 3. `in` membership; empty haystack ALWAYS denies -> 'NOT_IN_ALLOWLIST'
9
+ // 4. otherwise permit.
10
+ //
11
+ // Grammar version 3 nodes: and, eq, lte
12
+ // Grammar version 3 leaves: call_contract, call_fn, call_arg(i),
13
+ // call_arg_len(i), call_arg_field(i, element, field),
14
+ // literal_address, literal_i128, literal_symbol, literal_u32, literal_vec
15
+ // Grammar version 3 deny reasons: ARG_MISMATCH, CONTRACT_SCOPE,
16
+ // UNSUPPORTED_NODE, NOT_IN_ALLOWLIST
17
+ /** Evaluate a `PredicateNode` against the candidate call described by `ctx`.
18
+ * Pure function. Returns `{ permit: true }` or `{ permit: false; reason }`. */
19
+ export function evaluate(predicate, ctx) {
20
+ return walk(predicate, ctx);
21
+ }
22
+ /** Walk the predicate tree. Returns the FIRST deny reason encountered on
23
+ * the active branch (so `and` fails-fast). */
24
+ function walk(node, ctx) {
25
+ switch (node.op) {
26
+ case 'and': {
27
+ let lastDeny = null;
28
+ for (const child of node.children) {
29
+ const r = walk(child, ctx);
30
+ if (!r.permit)
31
+ return r;
32
+ lastDeny = r;
33
+ }
34
+ return lastDeny ?? { permit: true };
35
+ }
36
+ case 'eq':
37
+ case 'lte':
38
+ return evalCompare(node.op, node.left, node.right, ctx);
39
+ case 'in':
40
+ return evalIn(node.needle, node.haystack, ctx);
41
+ }
42
+ }
43
+ /** Comparison leaf evaluation. */
44
+ function evalCompare(op, left, right, ctx) {
45
+ // CONTRACT_SCOPE on call_contract eq
46
+ if (left.kind === 'call_contract' && op === 'eq') {
47
+ if (right.kind !== 'literal_address')
48
+ return { permit: false, reason: 'CONTRACT_SCOPE' };
49
+ return right.value === ctx.contract
50
+ ? { permit: true }
51
+ : { permit: false, reason: 'CONTRACT_SCOPE' };
52
+ }
53
+ // call_fn equality
54
+ if (left.kind === 'call_fn' && op === 'eq') {
55
+ if (right.kind !== 'literal_symbol')
56
+ return { permit: false, reason: 'ARG_MISMATCH' };
57
+ return right.value === ctx.fn ? { permit: true } : { permit: false, reason: 'ARG_MISMATCH' };
58
+ }
59
+ // call_arg comparison (eq / exact-vec, or lte ordered numeric bound)
60
+ if (left.kind === 'call_arg') {
61
+ const actual = ctx.args[left.index];
62
+ if (op !== 'eq')
63
+ return evalArgOrderedCompare(op, actual, right);
64
+ return evalArgEq(op, actual, right);
65
+ }
66
+ // call_arg_len: length of a vec-typed argument as u32.
67
+ // Fails closed on a non-vec / absent arg or a non-u32 literal.
68
+ if (left.kind === 'call_arg_len') {
69
+ const actual = ctx.args[left.index];
70
+ if (actual?.type !== 'vec')
71
+ return { permit: false, reason: 'ARG_MISMATCH' };
72
+ if (right.kind !== 'literal_u32')
73
+ return { permit: false, reason: 'ARG_MISMATCH' };
74
+ return actual.value.length === right.value
75
+ ? { permit: true }
76
+ : { permit: false, reason: 'ARG_MISMATCH' };
77
+ }
78
+ // call_arg_field: value of a field in the map at element i of
79
+ // the vec at argument index. Fails closed on shape / type / range issues.
80
+ if (left.kind === 'call_arg_field') {
81
+ const actual = ctx.args[left.index];
82
+ if (actual?.type !== 'vec')
83
+ return { permit: false, reason: 'ARG_MISMATCH' };
84
+ const element = actual.value[left.element];
85
+ if (element?.type !== 'map')
86
+ return { permit: false, reason: 'ARG_MISMATCH' };
87
+ if (!Array.isArray(element.value))
88
+ return { permit: false, reason: 'ARG_MISMATCH' };
89
+ const entry = element.value.find((e) => e.key === left.field);
90
+ if (!entry)
91
+ return { permit: false, reason: 'ARG_MISMATCH' };
92
+ if (op === 'eq')
93
+ return evalArgEq(op, entry.val, right);
94
+ return evalArgOrderedCompare(op, entry.val, right);
95
+ }
96
+ // Unknown leaf/op combination - structural fail-closed.
97
+ return { permit: false, reason: 'UNSUPPORTED_NODE' };
98
+ }
99
+ /** Per-ScVal equality. Handles literal_vec as an EXACT ordered sequence:
100
+ * compare element-by-element in order; deny if length or any element differs.
101
+ * Opaque args (`type: 'other'`) fail closed. */
102
+ function evalArgEq(op, actual, right) {
103
+ // eq(call_arg[i], literal_vec) -> EXACT ordered vector equality.
104
+ if (op === 'eq' && right.kind === 'literal_vec') {
105
+ if (actual?.type !== 'vec')
106
+ return { permit: false, reason: 'ARG_MISMATCH' };
107
+ return compareVecExact(actual.value, right.elements)
108
+ ? { permit: true }
109
+ : { permit: false, reason: 'ARG_MISMATCH' };
110
+ }
111
+ if (op === 'eq' && right.kind === 'literal_address') {
112
+ if (!actual)
113
+ return { permit: false, reason: 'ARG_MISMATCH' };
114
+ if (actual.type === 'other')
115
+ return { permit: false, reason: 'ARG_MISMATCH' };
116
+ return actual.type === 'address' && actual.value === right.value
117
+ ? { permit: true }
118
+ : { permit: false, reason: 'ARG_MISMATCH' };
119
+ }
120
+ if (op === 'eq' && right.kind === 'literal_i128') {
121
+ if (actual?.type !== 'i128')
122
+ return { permit: false, reason: 'ARG_MISMATCH' };
123
+ return BigInt(actual.value) === BigInt(right.value)
124
+ ? { permit: true }
125
+ : { permit: false, reason: 'ARG_MISMATCH' };
126
+ }
127
+ if (op === 'eq' && right.kind === 'literal_symbol') {
128
+ if (!actual)
129
+ return { permit: false, reason: 'ARG_MISMATCH' };
130
+ return actual.type === 'symbol' && actual.value === right.value
131
+ ? { permit: true }
132
+ : { permit: false, reason: 'ARG_MISMATCH' };
133
+ }
134
+ if (op === 'eq' && right.kind === 'literal_u32') {
135
+ if (!actual)
136
+ return { permit: false, reason: 'ARG_MISMATCH' };
137
+ return actual.type === 'u32' && actual.value === String(right.value)
138
+ ? { permit: true }
139
+ : { permit: false, reason: 'ARG_MISMATCH' };
140
+ }
141
+ // Anything else: fail closed on opacity (cannot decode the arg reliably).
142
+ if (!actual || actual.type === 'other')
143
+ return { permit: false, reason: 'ARG_MISMATCH' };
144
+ return { permit: false, reason: 'ARG_MISMATCH' };
145
+ }
146
+ /** Ordered numeric comparison (lte) on a `call_arg`. The interpreter reads the
147
+ * arg as an integer (i128 on the recorder's ScVal surface) and compares it
148
+ * to a numeric literal via BigInt. A non-numeric arg or a non-numeric literal
149
+ * fails closed (ARG_MISMATCH) rather than permitting an undecidable bound. */
150
+ function evalArgOrderedCompare(op, actual, right) {
151
+ const actualInt = argNumericBigInt(actual);
152
+ const literalInt = literalNumericBigInt(right);
153
+ if (actualInt === null || literalInt === null) {
154
+ return { permit: false, reason: 'ARG_MISMATCH' };
155
+ }
156
+ return bigintCmp(op, actualInt.toString(), literalInt.toString())
157
+ ? { permit: true }
158
+ : { permit: false, reason: 'ARG_MISMATCH' };
159
+ }
160
+ /** BigInt value of a numeric-integer ScVal arg (i128 / u32), or null when
161
+ * the arg is absent, opaque, or a non-numeric type. */
162
+ function argNumericBigInt(actual) {
163
+ if (!actual)
164
+ return null;
165
+ if (actual.type === 'i128' || actual.type === 'u32') {
166
+ try {
167
+ return BigInt(actual.value);
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ }
173
+ return null;
174
+ }
175
+ /** BigInt value of a numeric-integer literal leaf (`literal_i128` / `literal_u32`),
176
+ * or null for a non-numeric literal. Callers fail closed on null. */
177
+ function literalNumericBigInt(leaf) {
178
+ switch (leaf.kind) {
179
+ case 'literal_i128':
180
+ try {
181
+ return BigInt(leaf.value);
182
+ }
183
+ catch {
184
+ return null;
185
+ }
186
+ case 'literal_u32':
187
+ return BigInt(leaf.value);
188
+ default:
189
+ return null;
190
+ }
191
+ }
192
+ /** Element-by-element ordered comparison of an `ScVal[]` against a
193
+ * `PredicateLeaf[]`. Equal-length and equal at every index => permit.
194
+ * Length mismatch OR any element mismatch => deny ARG_MISMATCH. */
195
+ function compareVecExact(actual, expected) {
196
+ if (actual.length !== expected.length)
197
+ return false;
198
+ for (let i = 0; i < expected.length; i++) {
199
+ const e = expected[i];
200
+ const a = actual[i];
201
+ if (!e || !a)
202
+ return false;
203
+ const r = evalArgEq('eq', a, e);
204
+ if (!r.permit)
205
+ return false;
206
+ }
207
+ return true;
208
+ }
209
+ /** `in` membership. Empty haystack ALWAYS denies. Opaque needle fails closed. */
210
+ function evalIn(needle, haystack, ctx) {
211
+ if (haystack.length === 0)
212
+ return { permit: false, reason: 'NOT_IN_ALLOWLIST' };
213
+ const actual = resolveLeaf(needle, ctx);
214
+ if (!actual || actual.type === 'other')
215
+ return { permit: false, reason: 'NOT_IN_ALLOWLIST' };
216
+ for (const h of haystack) {
217
+ const r = evalArgEq('eq', actual, h);
218
+ if (r.permit)
219
+ return { permit: true };
220
+ }
221
+ return { permit: false, reason: 'NOT_IN_ALLOWLIST' };
222
+ }
223
+ /** Resolve a selector leaf to its current ScVal against the candidate call. */
224
+ function resolveLeaf(leaf, ctx) {
225
+ switch (leaf.kind) {
226
+ case 'call_contract':
227
+ return { type: 'address', value: ctx.contract };
228
+ case 'call_fn':
229
+ return { type: 'symbol', value: ctx.fn };
230
+ case 'call_arg':
231
+ return ctx.args[leaf.index];
232
+ case 'call_arg_len':
233
+ // No direct ScVal projection: the length is an integer the comparator
234
+ // resolves against the right-hand literal. Returning undefined keeps
235
+ // the `in` membership path structurally informed (no haystack match).
236
+ return undefined;
237
+ case 'call_arg_field': {
238
+ const actual = ctx.args[leaf.index];
239
+ if (actual?.type !== 'vec')
240
+ return undefined;
241
+ const element = actual.value[leaf.element];
242
+ if (element?.type !== 'map')
243
+ return undefined;
244
+ if (!Array.isArray(element.value))
245
+ return undefined;
246
+ const entry = element.value.find((e) => e.key === leaf.field);
247
+ return entry ? entry.val : undefined;
248
+ }
249
+ case 'literal_address':
250
+ return { type: 'address', value: leaf.value };
251
+ case 'literal_i128':
252
+ return { type: 'i128', value: leaf.value };
253
+ case 'literal_symbol':
254
+ return { type: 'symbol', value: leaf.value };
255
+ case 'literal_u32':
256
+ return { type: 'u32', value: String(leaf.value) };
257
+ case 'literal_vec':
258
+ return undefined;
259
+ }
260
+ }
261
+ /** BigInt compare helper. */
262
+ function bigintCmp(op, aStr, bStr) {
263
+ const a = BigInt(aStr);
264
+ const b = BigInt(bStr);
265
+ switch (op) {
266
+ case 'eq':
267
+ return a === b;
268
+ case 'lte':
269
+ return a <= b;
270
+ }
271
+ }
@@ -0,0 +1,4 @@
1
+ export type { DenyCase, GeneratedCases } from './deny-cases.ts';
2
+ export { generateCases } from './deny-cases.ts';
3
+ export type { EvalContext, EvalResult } from './evaluate.ts';
4
+ export { evaluate } from './evaluate.ts';
@@ -0,0 +1,8 @@
1
+ // src/simulate/index.ts - the off-chain evaluation engine.
2
+ //
3
+ // `evaluate` is a second implementation of the on-chain predicate semantics.
4
+ // The conformance harness runs it and the Rust interpreter against the same
5
+ // predicate and asserts the verdicts match, so a divergence between the two
6
+ // fails CI rather than reaching a user as a wrong simulation.
7
+ export { generateCases } from "./deny-cases.js";
8
+ export { evaluate } from "./evaluate.js";