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