@crediolabs/policy-synth 0.1.4 → 0.1.6

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 (154) hide show
  1. package/LICENSE +21 -0
  2. package/dist/codegen/template.js +3 -3
  3. package/dist/record/decode.d.ts +6 -3
  4. package/dist/record/decode.js +56 -3
  5. package/dist/record/freshness.d.ts +14 -1
  6. package/dist/record/freshness.js +32 -2
  7. package/dist/record/index.d.ts +11 -0
  8. package/dist/record/index.js +25 -0
  9. package/dist/record/movements.d.ts +15 -3
  10. package/dist/record/movements.js +42 -7
  11. package/dist/run/index.d.ts +43 -0
  12. package/dist/run/index.js +222 -0
  13. package/dist/run/schemas.d.ts +2016 -0
  14. package/dist/run/schemas.js +223 -0
  15. package/dist/synth/address.d.ts +7 -0
  16. package/dist/synth/address.js +12 -0
  17. package/dist/synth/compose-from-recording.d.ts +4 -3
  18. package/dist/synth/compose-from-recording.js +16 -6
  19. package/dist/synth/deny-cases.d.ts +12 -2
  20. package/dist/synth/deny-cases.js +76 -4
  21. package/dist/synth/evaluate.js +2 -2
  22. package/dist/synth/index.d.ts +1 -0
  23. package/dist/synth/index.js +4 -0
  24. package/dist/synth/minimize.d.ts +1 -1
  25. package/dist/synth/minimize.js +3 -3
  26. package/dist/synth/synthesize-from-recording.d.ts +5 -2
  27. package/dist/synth/synthesize-from-recording.js +175 -69
  28. package/dist/types.d.ts +41 -1
  29. package/dist/types.js +17 -0
  30. package/dist/verify/simulate.js +18 -2
  31. package/dist/verify/verify.js +18 -2
  32. package/dist-cjs/adapters/interpreter/adapter.d.ts +38 -0
  33. package/dist-cjs/adapters/interpreter/adapter.js +527 -0
  34. package/dist-cjs/adapters/interpreter/index.d.ts +1 -0
  35. package/dist-cjs/adapters/interpreter/index.js +8 -0
  36. package/dist-cjs/adapters/oz/adapter.d.ts +20 -0
  37. package/dist-cjs/adapters/oz/adapter.js +289 -0
  38. package/dist-cjs/adapters/oz/index.d.ts +1 -0
  39. package/dist-cjs/adapters/oz/index.js +8 -0
  40. package/dist-cjs/codegen/compile-gate.d.ts +33 -0
  41. package/dist-cjs/codegen/compile-gate.js +123 -0
  42. package/dist-cjs/codegen/index.d.ts +2 -0
  43. package/dist-cjs/codegen/index.js +14 -0
  44. package/dist-cjs/codegen/template.d.ts +18 -0
  45. package/dist-cjs/codegen/template.js +134 -0
  46. package/dist-cjs/errors.d.ts +37 -0
  47. package/dist-cjs/errors.js +3 -0
  48. package/dist-cjs/index.d.ts +11 -0
  49. package/dist-cjs/index.js +27 -0
  50. package/dist-cjs/ir/index.d.ts +1 -0
  51. package/dist-cjs/ir/index.js +3 -0
  52. package/dist-cjs/ir/types.d.ts +108 -0
  53. package/dist-cjs/ir/types.js +12 -0
  54. package/dist-cjs/mandate/index.d.ts +2 -0
  55. package/dist-cjs/mandate/index.js +6 -0
  56. package/dist-cjs/mandate/to-ir.d.ts +3 -0
  57. package/dist-cjs/mandate/to-ir.js +63 -0
  58. package/dist-cjs/mandate/types.d.ts +20 -0
  59. package/dist-cjs/mandate/types.js +9 -0
  60. package/dist-cjs/package.json +3 -0
  61. package/dist-cjs/predicate/encode.d.ts +10 -0
  62. package/dist-cjs/predicate/encode.js +252 -0
  63. package/dist-cjs/predicate/index.d.ts +1 -0
  64. package/dist-cjs/predicate/index.js +6 -0
  65. package/dist-cjs/record/decode.d.ts +79 -0
  66. package/dist-cjs/record/decode.js +441 -0
  67. package/dist-cjs/record/freshness.d.ts +30 -0
  68. package/dist-cjs/record/freshness.js +85 -0
  69. package/dist-cjs/record/index.d.ts +32 -0
  70. package/dist-cjs/record/index.js +191 -0
  71. package/dist-cjs/record/movements.d.ts +32 -0
  72. package/dist-cjs/record/movements.js +227 -0
  73. package/dist-cjs/record/rpc.d.ts +22 -0
  74. package/dist-cjs/record/rpc.js +74 -0
  75. package/dist-cjs/record/validate.d.ts +22 -0
  76. package/dist-cjs/record/validate.js +63 -0
  77. package/dist-cjs/registry/identify.d.ts +11 -0
  78. package/dist-cjs/registry/identify.js +87 -0
  79. package/dist-cjs/registry/index.d.ts +3 -0
  80. package/dist-cjs/registry/index.js +15 -0
  81. package/dist-cjs/registry/known-addresses.d.ts +16 -0
  82. package/dist-cjs/registry/known-addresses.js +53 -0
  83. package/dist-cjs/registry/protocols.d.ts +38 -0
  84. package/dist-cjs/registry/protocols.js +153 -0
  85. package/dist-cjs/review-card/builder.d.ts +14 -0
  86. package/dist-cjs/review-card/builder.js +264 -0
  87. package/dist-cjs/review-card/conflict.d.ts +40 -0
  88. package/dist-cjs/review-card/conflict.js +114 -0
  89. package/dist-cjs/review-card/cross-check.d.ts +11 -0
  90. package/dist-cjs/review-card/cross-check.js +151 -0
  91. package/dist-cjs/review-card/index.d.ts +3 -0
  92. package/dist-cjs/review-card/index.js +10 -0
  93. package/dist-cjs/run/index.d.ts +43 -0
  94. package/dist-cjs/run/index.js +237 -0
  95. package/dist-cjs/run/schemas.d.ts +2016 -0
  96. package/dist-cjs/run/schemas.js +226 -0
  97. package/dist-cjs/seams/index.d.ts +1 -0
  98. package/dist-cjs/seams/index.js +3 -0
  99. package/dist-cjs/seams/types.d.ts +66 -0
  100. package/dist-cjs/seams/types.js +12 -0
  101. package/dist-cjs/synth/address.d.ts +7 -0
  102. package/dist-cjs/synth/address.js +15 -0
  103. package/dist-cjs/synth/compose-from-recording.d.ts +65 -0
  104. package/dist-cjs/synth/compose-from-recording.js +366 -0
  105. package/dist-cjs/synth/deny-cases.d.ts +22 -0
  106. package/dist-cjs/synth/deny-cases.js +438 -0
  107. package/dist-cjs/synth/evaluate.d.ts +39 -0
  108. package/dist-cjs/synth/evaluate.js +428 -0
  109. package/dist-cjs/synth/harness.d.ts +16 -0
  110. package/dist-cjs/synth/harness.js +29 -0
  111. package/dist-cjs/synth/index.d.ts +10 -0
  112. package/dist-cjs/synth/index.js +28 -0
  113. package/dist-cjs/synth/lower.d.ts +23 -0
  114. package/dist-cjs/synth/lower.js +119 -0
  115. package/dist-cjs/synth/minimize.d.ts +4 -0
  116. package/dist-cjs/synth/minimize.js +41 -0
  117. package/dist-cjs/synth/predicate-literals.d.ts +5 -0
  118. package/dist-cjs/synth/predicate-literals.js +28 -0
  119. package/dist-cjs/synth/scope.d.ts +26 -0
  120. package/dist-cjs/synth/scope.js +81 -0
  121. package/dist-cjs/synth/synthesize-from-mandate.d.ts +5 -0
  122. package/dist-cjs/synth/synthesize-from-mandate.js +37 -0
  123. package/dist-cjs/synth/synthesize-from-recording.d.ts +49 -0
  124. package/dist-cjs/synth/synthesize-from-recording.js +759 -0
  125. package/dist-cjs/types.d.ts +311 -0
  126. package/dist-cjs/types.js +55 -0
  127. package/dist-cjs/verify/envelope.d.ts +15 -0
  128. package/dist-cjs/verify/envelope.js +23 -0
  129. package/dist-cjs/verify/index.d.ts +3 -0
  130. package/dist-cjs/verify/index.js +8 -0
  131. package/dist-cjs/verify/simulate.d.ts +31 -0
  132. package/dist-cjs/verify/simulate.js +261 -0
  133. package/dist-cjs/verify/verify.d.ts +21 -0
  134. package/dist-cjs/verify/verify.js +192 -0
  135. package/package.json +43 -3
  136. package/src/codegen/template.ts +3 -3
  137. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +171 -0
  138. package/src/record/corpus-fixtures.json +532 -0
  139. package/src/record/decode.ts +63 -10
  140. package/src/record/freshness.ts +34 -2
  141. package/src/record/index.ts +40 -0
  142. package/src/record/movements.ts +40 -7
  143. package/src/run/index.ts +277 -0
  144. package/src/run/schemas.ts +250 -0
  145. package/src/synth/address.ts +14 -0
  146. package/src/synth/compose-from-recording.ts +20 -9
  147. package/src/synth/deny-cases.ts +87 -4
  148. package/src/synth/evaluate.ts +2 -2
  149. package/src/synth/index.ts +4 -0
  150. package/src/synth/minimize.ts +7 -3
  151. package/src/synth/synthesize-from-recording.ts +200 -68
  152. package/src/types.ts +37 -1
  153. package/src/verify/simulate.ts +21 -2
  154. package/src/verify/verify.ts +21 -2
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ // src/verify/simulate.ts - the post-simulation verdict for `simulate_policy`.
3
+ //
4
+ // `simulatePolicy` replays a recorded transaction against a proposed
5
+ // `PredicateNode` and emits the `SimulationResult` envelope the review-card
6
+ // builder + the verification pipeline consume.
7
+ //
8
+ // Boundary (pinned, must not drift):
9
+ // - `SIMULATION_ERROR` = RUNTIME evaluation failed. Surfaced by
10
+ // `simulatePolicy`. Reasons: malformed `permitTx` input (no top-level
11
+ // invocation to build an EvalContext from), a referenced oracle asset
12
+ // without a satisfying price fixture, or a non-runtime propagation (a
13
+ // throw that is not an oracle error or a controlled deny). A
14
+ // runtime evaluation failure is NOT a policy-minimality problem; the
15
+ // policy may still be minimal. Re-running with a complete fixture MAY
16
+ // succeed.
17
+ // - `VERIFICATION_FAILED` = STATIC minimality check failed. Surfaced
18
+ // by `verifyPolicy`. The minimiser identified a load-bearing-free
19
+ // constraint; the policy is structurally over-broad regardless of how
20
+ // any concrete call evaluates. Re-running with a different fixture
21
+ // will NOT fix it; the policy must be trimmed.
22
+ //
23
+ // Determinism: same `(predicate, permitTx, opts)` -> byte-identical
24
+ // envelope, no clock, no randomness.
25
+ //
26
+ // The permit EvalContext is built locally (mirror of the helper used in
27
+ // `synthesize-from-recording.ts`) so this module does not couple to the
28
+ // orchestrator's private build helpers. The shape is pinned by the test
29
+ // suite to stay in lockstep.
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.simulatePolicy = simulatePolicy;
32
+ const deny_cases_ts_1 = require("../synth/deny-cases.js");
33
+ const evaluate_ts_1 = require("../synth/evaluate.js");
34
+ const types_ts_1 = require("../types.js");
35
+ const SIMULATOR_VERSION = 'ts-model-1.0.0';
36
+ /** Replay a recorded transaction against a proposed predicate and emit the
37
+ * `SimulationResult` envelope. The simulator returns the SAME permit
38
+ * verdict `runHarness` expects: the intended recorded call must permit; every
39
+ * generated deny dimension must deny. A runtime evaluation failure
40
+ * (malformed input, missing oracle fixture, etc.) returns a `SIMULATION_ERROR`
41
+ * `ToolError` - NOT a deny verdict, NOT `VERIFICATION_FAILED`. The boundary
42
+ * is pinned: minimality is a verify-time concern, runtime evaluation is a
43
+ * simulate-time concern. */
44
+ function simulatePolicy(predicate, permitTx, opts = {}) {
45
+ // The permit EvalContext requires a top-level invocation. A recorded tx
46
+ // with no invocations is structurally malformed input - we surface a
47
+ // runtime `SIMULATION_ERROR` rather than fabricating a permit verdict.
48
+ const topLevel = permitTx.invocations[0];
49
+ if (!topLevel) {
50
+ return {
51
+ ok: false,
52
+ error: simulationError('recorded transaction has no top-level invocation to simulate'),
53
+ };
54
+ }
55
+ let permitCtx;
56
+ try {
57
+ permitCtx = buildPermitContext(predicate, permitTx, topLevel, opts);
58
+ }
59
+ catch (e) {
60
+ return {
61
+ ok: false,
62
+ error: simulationError(`could not build permit evaluation context: ${e.message}`),
63
+ };
64
+ }
65
+ // `predicate === null` means the policy is OZ-only (no interpreter
66
+ // predicate). We still emit the envelope so the review card + verifier
67
+ // can consume it: the permit verdict evaluates an always-permit empty
68
+ // tree, and the deny battery is empty (nothing to verify at the
69
+ // interpreter layer).
70
+ const evaluatePredicate = predicate ?? { op: 'and', children: [] };
71
+ const evaluatedCases = [];
72
+ let permitVerdict;
73
+ try {
74
+ permitVerdict = (0, evaluate_ts_1.evaluate)(evaluatePredicate, permitCtx);
75
+ }
76
+ catch (e) {
77
+ return {
78
+ ok: false,
79
+ error: simulationError(`permit evaluation threw at runtime: ${e.message}`, e),
80
+ };
81
+ }
82
+ evaluatedCases.push({
83
+ dimension: 'permit',
84
+ outcome: permitVerdict.permit ? 'permit' : 'deny',
85
+ reason: permitVerdict.permit ? 'matches recorded call' : permitVerdict.reason,
86
+ });
87
+ // The deny battery is generated against the SAME permit context. A
88
+ // runtime evaluation failure on ANY deny case is a `SIMULATION_ERROR` -
89
+ // not a deny verdict (an evaluate-throws is not a deny) and not a
90
+ // minimality problem.
91
+ const cases = (0, deny_cases_ts_1.generateCases)(evaluatePredicate, permitCtx);
92
+ for (const deny of cases.denies) {
93
+ let result;
94
+ try {
95
+ result = (0, evaluate_ts_1.evaluate)(evaluatePredicate, deny.ctx);
96
+ }
97
+ catch (e) {
98
+ return {
99
+ ok: false,
100
+ error: simulationError(`deny case "${deny.dimension}" threw at runtime: ${e.message}`, e),
101
+ };
102
+ }
103
+ evaluatedCases.push({
104
+ dimension: deny.dimension,
105
+ outcome: result.permit ? 'permit' : 'deny',
106
+ reason: result.permit ? 'no matching deny' : result.reason,
107
+ });
108
+ }
109
+ const envelope = {
110
+ permit: permitVerdict.permit ? { tx: 'permit' } : { tx: 'deny', reason: permitVerdict.reason },
111
+ evaluatedCases,
112
+ backend: 'ts-model',
113
+ simulatorVersion: SIMULATOR_VERSION,
114
+ };
115
+ return { ok: true, data: envelope };
116
+ }
117
+ /** Build the permit `EvalContext` the simulator drives. Mirrors the
118
+ * helper in `synthesize-from-recording.ts` so the simulator sees the same
119
+ * shape the orchestrator's self-verify pipeline sees; we mirror here
120
+ * rather than import to keep `src/verify/` decoupled from the
121
+ * orchestrator's private helpers. The shape is pinned by tests so the
122
+ * two implementations stay in lockstep. */
123
+ function buildPermitContext(predicate, tx, topLevel, opts) {
124
+ const amountByToken = {};
125
+ const totals = new Map();
126
+ for (const m of tx.tokenMovements) {
127
+ const current = totals.get(m.token) ?? 0n;
128
+ totals.set(m.token, current + BigInt(m.amount));
129
+ }
130
+ for (const [token, total] of totals) {
131
+ amountByToken[token] = total.toString();
132
+ }
133
+ // Oracle prices: when the caller supplies a fixture, use it; otherwise
134
+ // derive a satisfying entry per `oracle_price` leaf in the predicate so
135
+ // the permit call permits. Negatives are clamped at 0 (Stellar oracle
136
+ // prices are non-negative).
137
+ const oraclePriceByAsset = {};
138
+ if (opts.oraclePricesByAsset) {
139
+ for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
140
+ oraclePriceByAsset[asset] = entry;
141
+ }
142
+ }
143
+ if (predicate !== null) {
144
+ visitOracleLeaves(predicate, (asset, op, bound) => {
145
+ // A caller-supplied fixture entry always wins; we only fill gaps.
146
+ if (oraclePriceByAsset[asset] !== undefined)
147
+ return;
148
+ let price;
149
+ switch (op) {
150
+ case 'lt':
151
+ case 'gt':
152
+ price = op === 'lt' ? bound - 1n : bound + 1n;
153
+ break;
154
+ case 'lte':
155
+ case 'gte':
156
+ case 'eq':
157
+ price = bound;
158
+ break;
159
+ }
160
+ if (price < 0n)
161
+ price = 0n;
162
+ oraclePriceByAsset[asset] = {
163
+ price: price.toString(),
164
+ timestampSeconds: tx.fetchedAt,
165
+ };
166
+ });
167
+ }
168
+ const ctx = {
169
+ contract: topLevel.contract,
170
+ fn: topLevel.fn,
171
+ args: topLevel.args.map(cloneScVal),
172
+ atLedger: tx.ledgerSequence,
173
+ nowSeconds: tx.fetchedAt,
174
+ amountByToken,
175
+ windowSpentByToken: {},
176
+ invocationCountByWindow: {},
177
+ oraclePriceByAsset,
178
+ };
179
+ if (opts.validUntilLedger !== undefined) {
180
+ ctx.validUntilLedger = opts.validUntilLedger;
181
+ }
182
+ return ctx;
183
+ }
184
+ function cloneScVal(value, depth = 0) {
185
+ // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
186
+ // payload cannot RangeError the JS stack during context building. Over-depth
187
+ // throws a ToolError-shaped error that the simulator's existing try/catch
188
+ // converts to a structured `{ok:false, error}` (not a thrown RangeError).
189
+ if (value.type === 'vec') {
190
+ if (depth >= types_ts_1.MAX_SCVAL_CLONE_DEPTH) {
191
+ throw cloneDepthError(value);
192
+ }
193
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
194
+ }
195
+ return { ...value };
196
+ }
197
+ function cloneDepthError(value) {
198
+ const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${types_ts_1.MAX_SCVAL_CLONE_DEPTH})`);
199
+ err.code = 'SIMULATION_ERROR';
200
+ err.severity = 'error';
201
+ err.retryable = false;
202
+ err.depthContext = value.type;
203
+ throw err;
204
+ }
205
+ function visitOracleLeaves(node, visit) {
206
+ switch (node.op) {
207
+ case 'and':
208
+ case 'or':
209
+ for (const child of node.children)
210
+ visitOracleLeaves(child, visit);
211
+ return;
212
+ case 'not':
213
+ visitOracleLeaves(node.child, visit);
214
+ return;
215
+ case 'eq':
216
+ case 'lt':
217
+ case 'lte':
218
+ case 'gt':
219
+ case 'gte': {
220
+ const leftLeaf = node.left;
221
+ const rightLeaf = node.right;
222
+ let oracleAsset;
223
+ let literal;
224
+ if (leftLeaf.kind === 'oracle_price') {
225
+ oracleAsset = leftLeaf.asset;
226
+ literal = oracleLiteralFromLeaf(rightLeaf);
227
+ }
228
+ else if (rightLeaf.kind === 'oracle_price') {
229
+ oracleAsset = rightLeaf.asset;
230
+ literal = oracleLiteralFromLeaf(leftLeaf);
231
+ }
232
+ if (oracleAsset === undefined || literal === undefined)
233
+ return;
234
+ visit(oracleAsset, node.op, literal);
235
+ return;
236
+ }
237
+ case 'in':
238
+ return;
239
+ }
240
+ }
241
+ function oracleLiteralFromLeaf(leaf) {
242
+ if (leaf.kind !== 'literal_i128')
243
+ return undefined;
244
+ try {
245
+ return BigInt(leaf.value);
246
+ }
247
+ catch {
248
+ return undefined;
249
+ }
250
+ }
251
+ function simulationError(message, cause) {
252
+ const error = {
253
+ code: 'SIMULATION_ERROR',
254
+ message,
255
+ severity: 'error',
256
+ retryable: false,
257
+ };
258
+ if (cause !== undefined)
259
+ error.details = { cause: String(cause) };
260
+ return error;
261
+ }
@@ -0,0 +1,21 @@
1
+ import type { ToolResponse } from '../errors.ts';
2
+ import type { PredicateNode, RecordedTransaction } from '../types.ts';
3
+ /** Options for `verifyPolicy`. Mirrors the orchestrator's permit-context
4
+ * knobs (expiry; oracle fixture) so verify sees the same shape
5
+ * `simulatePolicy` sees. */
6
+ export interface VerifyOptions {
7
+ validUntilLedger?: number;
8
+ oraclePricesByAsset?: Record<string, {
9
+ price: string;
10
+ timestampSeconds: number;
11
+ } | {
12
+ error: 'stale' | 'missing' | 'deviation' | 'paused' | 'decimals' | 'fingerprint';
13
+ }>;
14
+ }
15
+ /** Run the static minimality check on a proposed predicate + recorded tx.
16
+ * Returns `{ ok: true }` when the predicate is minimal (every top-level
17
+ * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
18
+ * be dropped without losing a deny-case. The dropped conjuncts are
19
+ * reported in `details.droppedConstraints` so the caller can render a
20
+ * review-card warning. */
21
+ export declare function verifyPolicy(predicate: PredicateNode, permitTx: RecordedTransaction, opts?: VerifyOptions): ToolResponse<true>;
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ // src/verify/verify.ts - the static minimality check for `verify_policy`.
3
+ //
4
+ // `verifyPolicy` proves the policy is MINIMAL: no top-level conjunct is
5
+ // load-bearing-free. It is the static sibling of `simulatePolicy` and emits
6
+ // `VERIFICATION_FAILED` (not `SIMULATION_ERROR`) on failure. The boundary is
7
+ // pinned:
8
+ //
9
+ // - `VERIFICATION_FAILED` = STATIC minimality check failed. The policy is
10
+ // structurally over-broad: a constraint could be dropped without losing
11
+ // a deny-case. Surfaced by `verifyPolicy`. Runtime evaluation is not
12
+ // part of this check; the policy may evaluate to a permit/deny just
13
+ // fine, the failure is shape-only.
14
+ //
15
+ // - `SIMULATION_ERROR` = RUNTIME evaluation failed (see simulate.ts).
16
+ // This module never emits SIMULATION_ERROR. A minimality failure is
17
+ // never a simulation error and vice-versa.
18
+ //
19
+ // Algorithm:
20
+ // 1. Build the permit EvalContext from `permitTx` (mirror of the
21
+ // orchestrator's helper so verify is self-contained).
22
+ // 2. Run `minimize(predicate, permitCtx)` to strip load-bearing-free
23
+ // top-level conjuncts (only `and` predicates are minimisable; other
24
+ // shapes are returned unchanged by `minimize`).
25
+ // 3. If the minimised tree has fewer top-level conjuncts than the input,
26
+ // return `VERIFICATION_FAILED` listing the dropped conjuncts by their
27
+ // structural fingerprint.
28
+ // 4. Otherwise `{ ok: true }`.
29
+ //
30
+ // Determinism: same `(predicate, permitTx)` -> byte-identical verdict.
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.verifyPolicy = verifyPolicy;
33
+ const minimize_ts_1 = require("../synth/minimize.js");
34
+ const types_ts_1 = require("../types.js");
35
+ /** Run the static minimality check on a proposed predicate + recorded tx.
36
+ * Returns `{ ok: true }` when the predicate is minimal (every top-level
37
+ * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
38
+ * be dropped without losing a deny-case. The dropped conjuncts are
39
+ * reported in `details.droppedConstraints` so the caller can render a
40
+ * review-card warning. */
41
+ function verifyPolicy(predicate, permitTx, opts = {}) {
42
+ const topLevel = permitTx.invocations[0];
43
+ if (!topLevel) {
44
+ return {
45
+ ok: false,
46
+ error: verificationFailed('recorded transaction has no top-level invocation to verify against', { droppedConstraints: [] }),
47
+ };
48
+ }
49
+ let permitCtx;
50
+ try {
51
+ permitCtx = buildPermitContextForVerify(permitTx, topLevel, opts);
52
+ }
53
+ catch (e) {
54
+ return {
55
+ ok: false,
56
+ error: verificationFailed(`could not build permit evaluation context: ${e.message}`, { droppedConstraints: [] }),
57
+ };
58
+ }
59
+ // `minimize` only reduces `and` predicates; other shapes are returned
60
+ // unchanged. A non-`and` predicate therefore trivially passes the static
61
+ // minimality check (its top-level structure carries no removable
62
+ // conjuncts). The runtime harness in `simulatePolicy` covers the
63
+ // OR / NOT / comparison shapes.
64
+ const minimised = (0, minimize_ts_1.minimize)(predicate, permitCtx);
65
+ // Drop count: only meaningful for `and`. For other shapes we already
66
+ // returned the input unchanged; report ok.
67
+ if (predicate.op !== 'and' || minimised.op !== 'and') {
68
+ if (!structuralEqual(predicate, minimised)) {
69
+ return {
70
+ ok: false,
71
+ error: verificationFailed('minimizer returned a structurally different tree for a non-and predicate', { droppedConstraints: [fingerprint(minimised)] }),
72
+ };
73
+ }
74
+ return { ok: true, data: true };
75
+ }
76
+ const inputChildren = predicate.children;
77
+ const minimisedChildren = minimised.children;
78
+ if (minimisedChildren.length >= inputChildren.length) {
79
+ return { ok: true, data: true };
80
+ }
81
+ // Over-broad: identify the dropped conjuncts by structural fingerprint
82
+ // (so the review card can quote exactly which constraint was redundant).
83
+ // We use a multiset comparison because two structurally identical
84
+ // conjuncts (e.g. a duplicate `call_fn == transfer`) collapse to the
85
+ // same fingerprint - the dropped item is the one whose fingerprint
86
+ // count drops between input and minimised.
87
+ const inputCounts = fingerprintCounts(inputChildren);
88
+ const minimisedCounts = fingerprintCounts(minimisedChildren);
89
+ const dropped = [];
90
+ for (const [fp, count] of inputCounts) {
91
+ const kept = minimisedCounts.get(fp) ?? 0;
92
+ for (let i = 0; i < count - kept; i++)
93
+ dropped.push(fp);
94
+ }
95
+ return {
96
+ ok: false,
97
+ error: verificationFailed(`policy is structurally over-broad: ${dropped.length} redundant conjunct(s) can be dropped without losing a deny case`, { droppedConstraints: dropped }),
98
+ };
99
+ }
100
+ function buildPermitContextForVerify(tx, topLevel, opts) {
101
+ const amountByToken = {};
102
+ const totals = new Map();
103
+ for (const m of tx.tokenMovements) {
104
+ const current = totals.get(m.token) ?? 0n;
105
+ totals.set(m.token, current + BigInt(m.amount));
106
+ }
107
+ for (const [token, total] of totals) {
108
+ amountByToken[token] = total.toString();
109
+ }
110
+ const oraclePriceByAsset = {};
111
+ if (opts.oraclePricesByAsset) {
112
+ for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
113
+ oraclePriceByAsset[asset] = entry;
114
+ }
115
+ }
116
+ const ctx = {
117
+ contract: topLevel.contract,
118
+ fn: topLevel.fn,
119
+ args: topLevel.args.map(cloneScVal),
120
+ atLedger: tx.ledgerSequence,
121
+ nowSeconds: tx.fetchedAt,
122
+ amountByToken,
123
+ windowSpentByToken: {},
124
+ invocationCountByWindow: {},
125
+ oraclePriceByAsset,
126
+ };
127
+ if (opts.validUntilLedger !== undefined) {
128
+ ctx.validUntilLedger = opts.validUntilLedger;
129
+ }
130
+ return ctx;
131
+ }
132
+ function cloneScVal(value, depth = 0) {
133
+ // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
134
+ // payload cannot RangeError the JS stack during context building. Over-depth
135
+ // throws a ToolError-shaped error that the verifier's existing try/catch
136
+ // converts to a structured `{ok:false, error}` (not a thrown RangeError).
137
+ if (value.type === 'vec') {
138
+ if (depth >= types_ts_1.MAX_SCVAL_CLONE_DEPTH) {
139
+ throw cloneDepthError(value);
140
+ }
141
+ return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
142
+ }
143
+ return { ...value };
144
+ }
145
+ function cloneDepthError(value) {
146
+ const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${types_ts_1.MAX_SCVAL_CLONE_DEPTH})`);
147
+ err.code = 'VERIFICATION_FAILED';
148
+ err.severity = 'error';
149
+ err.retryable = false;
150
+ err.depthContext = value.type;
151
+ throw err;
152
+ }
153
+ function fingerprint(node) {
154
+ return JSON.stringify(node, replacer);
155
+ }
156
+ /** Multiset fingerprint counts for a list of conjuncts. Two structurally
157
+ * identical conjuncts (e.g. a duplicate `call_fn == transfer`) each
158
+ * contribute their own count. The minimiser may drop one of them; we
159
+ * surface exactly the surplus via the count difference. */
160
+ function fingerprintCounts(children) {
161
+ const counts = new Map();
162
+ for (const child of children) {
163
+ const fp = fingerprint(child);
164
+ counts.set(fp, (counts.get(fp) ?? 0) + 1);
165
+ }
166
+ return counts;
167
+ }
168
+ /** Deterministic JSON key order for fingerprinting. Object keys are sorted
169
+ * recursively so the same shape produces the same string. */
170
+ function replacer(_key, value) {
171
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
172
+ const obj = value;
173
+ const sorted = {};
174
+ for (const k of Object.keys(obj).sort()) {
175
+ sorted[k] = obj[k];
176
+ }
177
+ return sorted;
178
+ }
179
+ return value;
180
+ }
181
+ function structuralEqual(a, b) {
182
+ return fingerprint(a) === fingerprint(b);
183
+ }
184
+ function verificationFailed(message, details) {
185
+ return {
186
+ code: 'VERIFICATION_FAILED',
187
+ message,
188
+ severity: 'error',
189
+ retryable: false,
190
+ details,
191
+ };
192
+ }
package/package.json CHANGED
@@ -1,22 +1,57 @@
1
1
  {
2
2
  "name": "@crediolabs/policy-synth",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "license": "MIT",
5
5
  "description": "Off-chain TypeScript synthesis core for the OZ Accounts Policy Builder. Records Soroban transactions, synthesises the minimal policy that permits exactly that flow, verifies it, and returns an unsigned install transaction.",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
8
8
  "types": "./dist/index.d.ts",
9
+ "engines": {
10
+ "node": ">=22.12",
11
+ "bun": ">=1.3.0"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/untangledfinance/oz-policy-builder.git",
16
+ "directory": "packages/policy-synth"
17
+ },
18
+ "homepage": "https://github.com/untangledfinance/oz-policy-builder#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/untangledfinance/oz-policy-builder/issues"
21
+ },
22
+ "keywords": [
23
+ "stellar",
24
+ "soroban",
25
+ "openzeppelin",
26
+ "policy",
27
+ "smart-account",
28
+ "authorization"
29
+ ],
30
+ "sideEffects": false,
31
+ "author": {
32
+ "name": "Untangled Finance Limited",
33
+ "url": "https://untangled.finance"
34
+ },
9
35
  "exports": {
10
36
  ".": {
11
37
  "types": "./dist/index.d.ts",
12
38
  "bun": "./src/index.ts",
13
39
  "import": "./dist/index.js",
40
+ "require": "./dist-cjs/index.js",
14
41
  "default": "./dist/index.js"
15
42
  },
43
+ "./run": {
44
+ "types": "./dist/run/index.d.ts",
45
+ "bun": "./src/run/index.ts",
46
+ "import": "./dist/run/index.js",
47
+ "require": "./dist-cjs/run/index.js",
48
+ "default": "./dist/run/index.js"
49
+ },
16
50
  "./package.json": "./package.json"
17
51
  },
18
52
  "files": [
19
53
  "dist",
54
+ "dist-cjs",
20
55
  "src",
21
56
  "!src/**/*.test.ts"
22
57
  ],
@@ -25,10 +60,15 @@
25
60
  },
26
61
  "scripts": {
27
62
  "test": "bun test",
28
- "build": "tsc -p tsconfig.build.json"
63
+ "build": "tsc -p tsconfig.build.json && tsc -p tsconfig.build.cjs.json && node scripts/write-cjs-package-json.cjs",
64
+ "build:esm": "tsc -p tsconfig.build.json",
65
+ "build:cjs": "tsc -p tsconfig.build.cjs.json && node scripts/write-cjs-package-json.cjs",
66
+ "prepublishOnly": "bun run build && bun test",
67
+ "prepack": "bun run build"
29
68
  },
30
69
  "dependencies": {
31
- "@stellar/stellar-sdk": "14.4.0"
70
+ "@stellar/stellar-sdk": "14.4.0",
71
+ "zod": "3.25.76"
32
72
  },
33
73
  "devDependencies": {
34
74
  "@biomejs/biome": "2.5.5",
@@ -67,10 +67,10 @@ function renderUncovered(uncovered: string[]): string {
67
67
  *
68
68
  * Same `(spec, name)` always produces byte-identical output. */
69
69
  export function generateRust(spec: EscapeHatchSpec, name: string): string {
70
- const contract = spec.contract
71
- const fnName = spec.fnName ?? 'enforce'
70
+ const _contract = spec.contract
71
+ const _fnName = spec.fnName ?? 'enforce'
72
72
  const structName = asRustIdent(name)
73
- const dataKeyName = `${asRustIdent(name)}_data`
73
+ const _dataKeyName = `${asRustIdent(name)}_data`
74
74
  const uncoveredBlock = renderUncovered(spec.uncovered)
75
75
 
76
76
  return `// Auto-generated by the OZ Policy Builder codegen escape hatch.