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