@crediolabs/policy-synth 0.1.16 → 0.1.18

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 (91) hide show
  1. package/README.md +43 -246
  2. package/dist/adapters/interpreter/adapter.d.ts +6 -7
  3. package/dist/adapters/interpreter/adapter.js +28 -48
  4. package/dist/adapters/oz/adapter.js +12 -13
  5. package/dist/codegen/compile-gate.js +5 -0
  6. package/dist/codegen/template.js +17 -0
  7. package/dist/install/build-add-context-rule.js +16 -45
  8. package/dist/install/build-install-policy.d.ts +12 -5
  9. package/dist/install/build-install-policy.js +32 -23
  10. package/dist/install/get-interpreter-info.js +2 -2
  11. package/dist/install/index.d.ts +1 -0
  12. package/dist/install/index.js +15 -0
  13. package/dist/install/oz-auth.js +5 -3
  14. package/dist/predicate/decode.js +1 -1
  15. package/dist/predicate/encode.js +171 -10
  16. package/dist/record/decode.js +5 -6
  17. package/dist/registry/protocols.d.ts +1 -1
  18. package/dist/registry/protocols.js +1 -1
  19. package/dist/review-card/builder.d.ts +6 -0
  20. package/dist/review-card/builder.js +9 -1
  21. package/dist/run/index.d.ts +14 -13
  22. package/dist/run/index.js +80 -67
  23. package/dist/run/schemas.d.ts +193 -11
  24. package/dist/run/schemas.js +59 -17
  25. package/dist/synth/compose-from-recording.d.ts +10 -15
  26. package/dist/synth/compose-from-recording.js +79 -124
  27. package/dist/synth/deny-cases.d.ts +5 -0
  28. package/dist/synth/deny-cases.js +52 -13
  29. package/dist/synth/evaluate.js +69 -119
  30. package/dist/synth/harness.d.ts +13 -1
  31. package/dist/synth/harness.js +22 -1
  32. package/dist/synth/index.d.ts +1 -1
  33. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  34. package/dist/synth/synthesize-from-recording.js +129 -155
  35. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  36. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  37. package/dist-cjs/adapters/oz/adapter.js +12 -13
  38. package/dist-cjs/codegen/compile-gate.js +5 -0
  39. package/dist-cjs/codegen/template.js +17 -0
  40. package/dist-cjs/install/build-add-context-rule.js +16 -45
  41. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  42. package/dist-cjs/install/build-install-policy.js +32 -23
  43. package/dist-cjs/install/get-interpreter-info.js +2 -2
  44. package/dist-cjs/install/index.d.ts +1 -0
  45. package/dist-cjs/install/index.js +21 -0
  46. package/dist-cjs/install/oz-auth.js +5 -3
  47. package/dist-cjs/predicate/decode.js +1 -1
  48. package/dist-cjs/predicate/encode.js +171 -10
  49. package/dist-cjs/record/decode.js +5 -6
  50. package/dist-cjs/registry/protocols.d.ts +1 -1
  51. package/dist-cjs/registry/protocols.js +1 -1
  52. package/dist-cjs/review-card/builder.d.ts +6 -0
  53. package/dist-cjs/review-card/builder.js +9 -1
  54. package/dist-cjs/run/index.d.ts +14 -13
  55. package/dist-cjs/run/index.js +80 -67
  56. package/dist-cjs/run/schemas.d.ts +193 -11
  57. package/dist-cjs/run/schemas.js +59 -17
  58. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  59. package/dist-cjs/synth/compose-from-recording.js +79 -124
  60. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  61. package/dist-cjs/synth/deny-cases.js +52 -13
  62. package/dist-cjs/synth/evaluate.js +69 -119
  63. package/dist-cjs/synth/harness.d.ts +13 -1
  64. package/dist-cjs/synth/harness.js +22 -1
  65. package/dist-cjs/synth/index.d.ts +1 -1
  66. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  67. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  68. package/package.json +11 -4
  69. package/src/adapters/interpreter/adapter.ts +28 -48
  70. package/src/adapters/oz/adapter.ts +12 -13
  71. package/src/codegen/compile-gate.ts +5 -0
  72. package/src/codegen/template.ts +17 -0
  73. package/src/install/build-add-context-rule.ts +17 -55
  74. package/src/install/build-install-policy.ts +41 -23
  75. package/src/install/get-interpreter-info.ts +2 -2
  76. package/src/install/index.ts +21 -0
  77. package/src/install/oz-auth.ts +5 -3
  78. package/src/predicate/decode.ts +1 -1
  79. package/src/predicate/encode.ts +176 -10
  80. package/src/record/decode.ts +5 -6
  81. package/src/registry/protocols.ts +1 -1
  82. package/src/review-card/builder.ts +17 -1
  83. package/src/run/index.ts +117 -91
  84. package/src/run/schemas.ts +64 -16
  85. package/src/synth/compose-from-recording.ts +87 -132
  86. package/src/synth/deny-cases.ts +59 -13
  87. package/src/synth/evaluate.ts +70 -118
  88. package/src/synth/harness.ts +29 -1
  89. package/src/synth/index.ts +1 -0
  90. package/src/synth/synthesize-from-recording.ts +209 -192
  91. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -140,13 +140,12 @@ function encodePoliciesMap(args) {
140
140
  const entries = [];
141
141
  for (const ref of args.policies) {
142
142
  if (ref.kind === 'interpreter') {
143
- const val = encodePolicyInstallParams(args);
144
143
  entries.push(new xdr.ScMapEntry({
145
144
  key: Address.fromString(ref.interpreterAddress).toScVal(),
146
- val,
145
+ val: encodePolicyInstallParams(args),
147
146
  }));
148
147
  }
149
- if (ref.kind === 'oz_builtin') {
148
+ else if (ref.kind === 'oz_builtin') {
150
149
  entries.push(new xdr.ScMapEntry({
151
150
  key: Address.fromString(ref.instanceAddress).toScVal(),
152
151
  val: encodeOzPrimitiveParams(ref.primitive),
@@ -221,48 +220,20 @@ function encodePolicyInstallParams(args) {
221
220
  if (computedHash !== args.predicateHash) {
222
221
  throw limitError('INSTALL_BUILD_FAILED', `predicateHash ${args.predicateHash.slice(0, 16)}... does not match sha256(encodedPredicate) ${computedHash.slice(0, 16)}...`);
223
222
  }
224
- const entries = [];
225
- for (const k of POLICY_INSTALL_PARAM_FIELDS) {
226
- const key = xdr.ScVal.scvSymbol(k);
227
- switch (k) {
228
- case 'grammar_version':
229
- entries.push(new xdr.ScMapEntry({
230
- key,
231
- val: xdr.ScVal.scvU32(args.grammarVersion ?? DEFAULT_GRAMMAR_VERSION),
232
- }));
233
- break;
234
- case 'install_nonce':
235
- entries.push(new xdr.ScMapEntry({ key, val: xdr.ScVal.scvU32(args.installNonce) }));
236
- break;
237
- case 'predicate':
238
- entries.push(new xdr.ScMapEntry({ key, val: xdr.ScVal.scvBytes(predicate) }));
239
- break;
240
- case 'predicate_hash':
241
- entries.push(new xdr.ScMapEntry({
242
- key,
243
- val: xdr.ScVal.scvBytes(Buffer.from(args.predicateHash, 'hex')),
244
- }));
245
- break;
246
- case 'oracle_max_staleness_seconds':
247
- entries.push(new xdr.ScMapEntry({
248
- key,
249
- val: encodeOptionU32(args.oracleParams?.maxStalenessSeconds),
250
- }));
251
- break;
252
- case 'oracle_max_deviation_bps':
253
- entries.push(new xdr.ScMapEntry({
254
- key,
255
- val: encodeOptionU32(args.oracleParams?.maxDeviationBps),
256
- }));
257
- break;
258
- case 'oracle_max_xfeed_dev_bps':
259
- entries.push(new xdr.ScMapEntry({
260
- key,
261
- val: encodeOptionU32(args.oracleParams?.maxCrossFeedDeviationBps),
262
- }));
263
- break;
264
- }
265
- }
223
+ // Per-field value encoders. Each entry returns the ScVal to drop into the
224
+ // map; the key symbol comes from the surrounding loop. Adding a field is
225
+ // one row here plus the symbol in POLICY_INSTALL_PARAM_FIELDS.
226
+ const oracleParams = args.oracleParams;
227
+ const valueFor = {
228
+ grammar_version: () => xdr.ScVal.scvU32(args.grammarVersion ?? DEFAULT_GRAMMAR_VERSION),
229
+ install_nonce: () => xdr.ScVal.scvU32(args.installNonce),
230
+ predicate: () => xdr.ScVal.scvBytes(predicate),
231
+ predicate_hash: () => xdr.ScVal.scvBytes(Buffer.from(args.predicateHash, 'hex')),
232
+ oracle_max_staleness_seconds: () => encodeOptionU32(oracleParams?.maxStalenessSeconds),
233
+ oracle_max_deviation_bps: () => encodeOptionU32(oracleParams?.maxDeviationBps),
234
+ oracle_max_xfeed_dev_bps: () => encodeOptionU32(oracleParams?.maxCrossFeedDeviationBps),
235
+ };
236
+ const entries = POLICY_INSTALL_PARAM_FIELDS.map((k) => new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(k), val: valueFor[k]() }));
266
237
  // The host orders map entries by the SYMBOL STRING, not by XDR bytes. A
267
238
  // length prefix in the XDR encoding would otherwise put `amount` before
268
239
  // `address` and produce a struct the contract reads differently. Emit the
@@ -18,11 +18,10 @@ export interface InstallRpcClient {
18
18
  * `getContractVersion` lookup uses `simulateTransaction` against
19
19
  * `contract.call('grammar_version')` and decodes the returned u32.
20
20
  *
21
- * The passphrase is a REQUIRED argument rather than something read off the
22
- * server: `rpc.Server` does not carry one, so reaching for
23
- * `server.networkPassphrase` yielded a non-string and every version probe
24
- * died with "Invalid passphrase provided to Transaction". The caller knows
25
- * which network it dialled; make it say so. */
21
+ * The passphrase is a REQUIRED argument (not read off the server): `rpc.Server`
22
+ * does not carry one, so reaching for `server.networkPassphrase` returned a
23
+ * non-string and every version probe died with "Invalid passphrase provided to
24
+ * Transaction". The caller knows which network it dialled; make it say so. */
26
25
  export declare function rpcClientFromServer(server: rpc.Server, networkPassphrase: string): InstallRpcClient;
27
26
  /** Inputs for the install-policy build. */
28
27
  export interface BuildInstallPolicyArgs {
@@ -115,6 +114,14 @@ export interface InstallCallDescribes {
115
114
  kind: 'external';
116
115
  verifier: string;
117
116
  }>;
117
+ /** Cross-layer L1: a human-readable note about the OZ any-of-N signer
118
+ * semantic that fires for rules with multiple signers. Present only
119
+ * when `signers.length >= 2` (a single-signer rule is trivially any-of-1,
120
+ * and the note would just add noise). The note is purely additive to
121
+ * the review card text - it does NOT alter the wire bytes or the
122
+ * signer-set constraint, only the description a human reads before
123
+ * signing the install. */
124
+ signerNote: string | null;
118
125
  /** One entry per policy attached to the rule, decoded from the policies
119
126
  * map (args[4]). The address is the map key; the kind + extras below
120
127
  * describe the value. The interpreter policy also reports the
@@ -1,24 +1,21 @@
1
- // src/install/build-install-policy.ts - builds the unsigned Soroban
2
- // transaction XDR for `account.add_context_rule(...)` and
3
- // `account.remove_context_rule(...)`.
1
+ // src/install/build-install-policy.ts - builds the unsigned Soroban transaction
2
+ // XDR for `account.add_context_rule(...)` and `account.remove_context_rule(...)`.
4
3
  //
5
- // The MCP server is stateless and holds no key material (server.ts:10-12),
6
- // so this module NEVER signs. The caller (the wallet / CLI / SDK consumer)
7
- // wraps the returned XDR in a transaction envelope and signs that envelope
8
- // with their wallet; the wallet signature IS the user-confirmation step.
4
+ // The MCP server is stateless and holds no key material, so this module NEVER
5
+ // signs. The caller (wallet / CLI / SDK consumer) wraps the returned XDR in a
6
+ // transaction envelope and signs that envelope with their wallet; the wallet
7
+ // signature IS the user-confirmation step.
9
8
  //
10
- // We deliberately depart from the spec in plans/phase-04 which calls for a
9
+ // We deliberately depart from the original design, which called for a
11
10
  // two-call `install_policy`/`confirm_install` pair backed by a host-signed
12
- // short-TTL `action_id`. That contract requires (a) a stateful store and
13
- // (b) key material the server does not have, so we ship the simpler ONE-CALL
14
- // shape. The wallet signature covers the change.
11
+ // short-TTL `action_id`. That contract requires stateful store + key material
12
+ // the server does not have, so we ship the simpler ONE-CALL shape. The wallet
13
+ // signature covers the change.
15
14
  //
16
15
  // `buildInstallPolicyXdr` installs the policy in ONE call. `add_context_rule`
17
16
  // takes `policies` as a `Map<policy_address, install_param>` and the account
18
17
  // forwards each install_param to that policy, so the interpreter stores the
19
- // predicate document as part of this same transaction. Earlier revisions
20
- // documented a second `interpreter.install` call; that was wrong, and issuing
21
- // it fails - the account re-enters the interpreter while it is mid-install.
18
+ // predicate document as part of this same transaction.
22
19
  import { createHash } from 'node:crypto';
23
20
  import { Address, BASE_FEE, Contract, Keypair, Operation, rpc, scValToBigInt, TransactionBuilder, xdr, } from '@stellar/stellar-sdk';
24
21
  import { buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION } from "./build-add-context-rule.js";
@@ -27,11 +24,10 @@ import { accountEntry, authDigest, authPayload, delegatedSignerEntry, signatureP
27
24
  * `getContractVersion` lookup uses `simulateTransaction` against
28
25
  * `contract.call('grammar_version')` and decodes the returned u32.
29
26
  *
30
- * The passphrase is a REQUIRED argument rather than something read off the
31
- * server: `rpc.Server` does not carry one, so reaching for
32
- * `server.networkPassphrase` yielded a non-string and every version probe
33
- * died with "Invalid passphrase provided to Transaction". The caller knows
34
- * which network it dialled; make it say so. */
27
+ * The passphrase is a REQUIRED argument (not read off the server): `rpc.Server`
28
+ * does not carry one, so reaching for `server.networkPassphrase` returned a
29
+ * non-string and every version probe died with "Invalid passphrase provided to
30
+ * Transaction". The caller knows which network it dialled; make it say so. */
35
31
  export function rpcClientFromServer(server, networkPassphrase) {
36
32
  return {
37
33
  getAccount: (address) => server.getAccount(address),
@@ -337,7 +333,7 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
337
333
  const tag = tuple[0]?.sym().toString();
338
334
  const inner = tuple[1];
339
335
  if (tag === 'Delegated') {
340
- if (!inner || inner.switch().name !== 'scvAddress') {
336
+ if (inner?.switch().name !== 'scvAddress') {
341
337
  throw new Error('install_policy: a Delegated signer is missing its Address');
342
338
  }
343
339
  signers.push({
@@ -347,7 +343,7 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
347
343
  continue;
348
344
  }
349
345
  if (tag === 'External') {
350
- if (!inner || inner.switch().name !== 'scvAddress') {
346
+ if (inner?.switch().name !== 'scvAddress') {
351
347
  throw new Error('install_policy: an External signer is missing its verifier Address');
352
348
  }
353
349
  signers.push({
@@ -389,12 +385,12 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
389
385
  // OZ primitives carry spending_limit/period_ledgers/threshold/signers.
390
386
  if (fields.has('predicate') || fields.has('grammar_version') || fields.has('install_nonce')) {
391
387
  const installNonceScv = fields.get('install_nonce');
392
- if (!installNonceScv || installNonceScv.switch().name !== 'scvU32') {
388
+ if (installNonceScv?.switch().name !== 'scvU32') {
393
389
  throw new Error(`install_policy: interpreter policy ${address} is missing a u32 install_nonce`);
394
390
  }
395
391
  const installNonce = installNonceScv.u32();
396
392
  const predicateScv = fields.get('predicate');
397
- if (!predicateScv || predicateScv.switch().name !== 'scvBytes') {
393
+ if (predicateScv?.switch().name !== 'scvBytes') {
398
394
  throw new Error(`install_policy: interpreter policy ${address} is missing its bytes predicate`);
399
395
  }
400
396
  const predicateBytes = Buffer.from(predicateScv.bytes());
@@ -435,12 +431,25 @@ function decodeInstallCallDescribes(tx, expectedInstallNonce) {
435
431
  // `observedInstallNonce` is the nonce baked into whichever interpreter
436
432
  // policy is present; when none, fall back to the caller-supplied value.
437
433
  const installNonce = observedInstallNonce ?? expectedInstallNonce;
434
+ // Cross-layer L1: OZ Accounts context rules follow any-of-N semantics for
435
+ // the signers they accept - any ONE attached signer may authorise a
436
+ // permitted op under the rule. A user with multiple signers attached
437
+ // therefore has a strict superset of authority of a single-signer rule,
438
+ // not a stricter one; the install succeeds as written, but a human
439
+ // reviewing the install card may expect the opposite (and choose the
440
+ // wrong threshold because of it). Surface the any-of-N note on the
441
+ // description so the human reads the same wire-level semantic the
442
+ // contract enforces.
443
+ const signerNote = signers.length >= 2
444
+ ? 'any ONE signer may authorise a permitted op under this rule (OZ any-of-N semantic)'
445
+ : null;
438
446
  return {
439
447
  targetContract,
440
448
  fnName: 'add_context_rule',
441
449
  ruleName,
442
450
  validUntilLedger,
443
451
  signers,
452
+ signerNote,
444
453
  policies,
445
454
  installNonce,
446
455
  };
@@ -9,9 +9,9 @@
9
9
  // Per design decision 5: phase-04's "audit #44" is aspirational and has no
10
10
  // source-of-truth in the repo. Returning a fabricated audit id would be a
11
11
  // lie on a security surface. The honest outputs are:
12
- // - the pinned address (DEPLOYMENTS.md)
12
+ // - the pinned address (`PINNED_INTERPRETER_*_ADDRESS` in run/schemas.ts)
13
13
  // - the pinned grammar version (SELF_VERSION in version.rs)
14
- // - the pinned wasm sha256 (DEPLOYMENTS.md)
14
+ // - the pinned wasm sha256 (`PINNED_INTERPRETER_WASM_SHA256` in run/schemas.ts)
15
15
  // - an OPTIONAL `deployedGrammarVersion` returned by a live `grammar_version()`
16
16
  // RPC call, with a `liveMatchesPin` boolean the caller can dispatch on. A
17
17
  // mismatch means the deployed wasm is NOT the pinned artifact - the caller
@@ -0,0 +1 @@
1
+ export { ADD_CONTEXT_RULE_SYMBOL, type AddContextRuleArgs, type BuildAddContextRuleArgs, buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION, } from './build-add-context-rule.ts';
@@ -0,0 +1,15 @@
1
+ // Public entry for the install-argument builders.
2
+ //
3
+ // `buildAddContextRuleArgs` is the encoder `runInstallPolicy` uses to turn a
4
+ // ContextRuleDraft into the `add_context_rule` arguments. It was reachable
5
+ // only from inside this package, so a browser client that wants to build the
6
+ // same call had the choice of re-implementing the encoding or going without.
7
+ // Re-implementing it is not a real option: the interpreter compares
8
+ // sha256(context_rule.signers) at enforce time, so an encoding that differs in
9
+ // any field yields a rule that denies every call, and an omitted policy yields
10
+ // one that permits every call. Both failure modes have happened.
11
+ //
12
+ // Exported here rather than from the package root to keep the root surface
13
+ // about synthesis, and because these are transaction-building primitives whose
14
+ // callers should know they are reaching for them.
15
+ export { ADD_CONTEXT_RULE_SYMBOL, buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION, } from "./build-add-context-rule.js";
@@ -31,9 +31,11 @@ const u32 = (n) => xdr.ScVal.scvU32(n);
31
31
  const vec = (i) => xdr.ScVal.scvVec(i);
32
32
  const bytes = (b) => xdr.ScVal.scvBytes(b);
33
33
  function struct(fields) {
34
- return xdr.ScVal.scvMap(Object.keys(fields)
35
- .sort()
36
- .map((k) => new xdr.ScMapEntry({ key: sym(k), val: fields[k] })));
34
+ // Entries sorted by key with the default string comparison - ScMap
35
+ // encoding requires the same order Object.keys().sort() produced.
36
+ return xdr.ScVal.scvMap(Object.entries(fields)
37
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
38
+ .map(([k, v]) => new xdr.ScMapEntry({ key: sym(k), val: v })));
37
39
  }
38
40
  /** `Signer::Delegated(addr)`. */
39
41
  export const delegatedSigner = (a) => vec([sym('Delegated'), new Address(a).toScVal()]);
@@ -7,7 +7,7 @@
7
7
  // this module takes it from there.
8
8
  //
9
9
  // Mirrors `decode_leaf` / `decode_node` in
10
- // `packages/policy-interpreter/src/dsl.rs`. Two rules carry most of the
10
+ // `contracts/policy-interpreter/src/dsl.rs`. Two rules carry most of the
11
11
  // weight, and both come from the Rust decoder verbatim:
12
12
  //
13
13
  // 1. A `Vec` whose FIRST element is a Symbol is a selector tuple. A `Vec`
@@ -1,15 +1,13 @@
1
1
  // src/predicate/encode.ts - canonical predicate encoder.
2
2
  //
3
- // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format
4
- // described in `packages/policy-interpreter/INTERPRETER_INSTALL_PARAMS.md`:
3
+ // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format:
5
4
  // - every node is a `ScVal::Vec` whose head element is the tag `ScVal::Symbol`
6
5
  // - children of `and` / `or` are sorted ascending by their canonical XDR bytes
7
6
  // - `in` haystacks are ALWAYS sorted by canonical XDR bytes (pure set
8
7
  // membership); an EXACT ordered sequence is expressed as
9
8
  // `eq(selector, literal_vec)` where the `literal_vec` element order is
10
9
  // preserved verbatim (the order IS the semantic)
11
- // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings;
12
- // order is preserved, NOT sorted
10
+ // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings
13
11
  // - i128 uses `Int128Parts{hi: Int64 (signed), lo: Uint64 (unsigned)}`,
14
12
  // value = hi*2^64 + lo (NOT signed-magnitude)
15
13
  // - no `ScMap` anywhere in the predicate
@@ -19,12 +17,6 @@
19
17
  // Caps from `PREDICATE_CAPS` are enforced BEFORE returning; a cap breach throws
20
18
  // a `ToolError` with the matching error code and `severity: 'error'`.
21
19
  //
22
- // The encoder is also the gate for the structures the contract refuses: an
23
- // empty `and`/`or` child list and an empty `in` haystack (MALFORMED_PREDICATE
24
- // at decode, dsl.rs), an `oracle_price` under a `not`/`or`, and an oracle bound
25
- // with no non-oracle constraint beside it (validate_oracle_placement at
26
- // install).
27
- //
28
20
  // One gap remains, deliberately: the `amount` / `window_spent` leaf branches
29
21
  // below are dead ABI - the contract's grammar no longer has those selector
30
22
  // symbols, so a predicate carrying one is MALFORMED at decode. The interpreter
@@ -61,6 +53,21 @@ export function encodePredicate(node) {
61
53
  if (stats.oracleAssets.size > 0 && stats.nonOracleSelectorLeaves === 0) {
62
54
  throw capError('MALFORMED_PREDICATE', 'predicate constrains nothing but an oracle price: the contract refuses it at install (dsl.rs MissingNonOracleEnvelope). Pin the call itself (contract / method / argument) alongside the price bound.');
63
55
  }
56
+ // --- pass 1.5: leaf-value validation (Rust `validate_scaled_ratios` + the
57
+ // broader cap-set gate the contract enforces at install). Defense in depth:
58
+ // the TS self-verify pipeline should reject the same shapes Rust install
59
+ // refuses, so a hand-crafted predicate that simulate/verify green-lights
60
+ // cannot later be refused at the on-chain install step. The checks:
61
+ // - u32 fields in range (call_arg index, literal_u32 value, oracle
62
+ // threshold decimals, etc.) - the contract decodes as u32
63
+ // - i128 positivity where required (literal_i128 for amount/window
64
+ // caps; `den`/`num` for scaled ratios) - a negative cap would
65
+ // permit everything
66
+ // - hex even-length (literal_bytes) - `Buffer.from(v, 'hex')` silently
67
+ // drops non-hex chars, so 'zz' becomes empty bytes
68
+ // - scaled-ratio num>0 && den>0 - mirrors dsl.rs:661-704
69
+ // Throws `MALFORMED_PREDICATE` so the error stays a ToolError shape.
70
+ validateLeafValues(node);
64
71
  // --- pass 2: build + canonicalise the ScVal ---
65
72
  const root = encodeNode(node);
66
73
  const rawBytes = root.toXDR();
@@ -321,3 +328,157 @@ function capError(code, message) {
321
328
  err.retryable = false;
322
329
  throw err;
323
330
  }
331
+ // u32 boundary - the same constant the contract decodes with. A value above
332
+ // this either overflows during encode or is refused at install.
333
+ const U32_MAX = 4294967295;
334
+ // The maximum decimal basis an oracle threshold can declare (mirrors
335
+ // `MAX_ORACLE_THRESHOLD_DECIMALS` in dsl.rs). A value above this is refused
336
+ // at install with `ORACLE_PARAMS_OUT_OF_RANGE`.
337
+ const MAX_ORACLE_THRESHOLD_DECIMALS = 18;
338
+ /** Walk a `PredicateNode` and fail-closed on any leaf whose cap-set value the
339
+ * contract would refuse at install. Mirrors `validate_scaled_ratios` in
340
+ * dsl.rs:661-704 plus the broader cap-set gate (`literal_u32`, `literal_i128`
341
+ * positivity, `literal_bytes` hex even-length, `oracle_threshold` decimals
342
+ * range, `call_arg_scaled` positive-ratio). Defense in depth so the TS
343
+ * self-verify pipeline rejects the same shapes Rust install already
344
+ * refuses - a hand-crafted predicate that simulate/verify green-lights must
345
+ * NOT be installable. Throws `MALFORMED_PREDICATE` so the envelope shapes
346
+ * it into a ToolError. */
347
+ function validateLeafValues(node) {
348
+ function walkLeaf(leaf, path) {
349
+ switch (leaf.kind) {
350
+ case 'call_arg':
351
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
352
+ throw malformed(`call_arg.index out of u32 range at ${path}`);
353
+ }
354
+ return;
355
+ case 'call_arg_len':
356
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
357
+ throw malformed(`call_arg_len.index out of u32 range at ${path}`);
358
+ }
359
+ return;
360
+ case 'call_arg_field':
361
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
362
+ throw malformed(`call_arg_field.index out of u32 range at ${path}`);
363
+ }
364
+ if (!Number.isInteger(leaf.element) || leaf.element < 0 || leaf.element > U32_MAX) {
365
+ throw malformed(`call_arg_field.element out of u32 range at ${path}`);
366
+ }
367
+ return;
368
+ case 'call_arg_scaled': {
369
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
370
+ throw malformed(`call_arg_scaled.index out of u32 range at ${path}`);
371
+ }
372
+ // num / den are i128 on chain, decimal strings on the wire. The
373
+ // contract refuses `den == 0` and `num <= 0` / `den <= 0` at install
374
+ // (dsl.rs:664-672); mirror that here so a future regression in
375
+ // `validate_scaled_ratios` cannot let a divide-by-zero policy reach
376
+ // the wire. BigInt throws on non-numeric strings -> malformed.
377
+ let num;
378
+ let den;
379
+ try {
380
+ num = BigInt(leaf.num);
381
+ den = BigInt(leaf.den);
382
+ }
383
+ catch {
384
+ throw malformed(`call_arg_scaled.num/den not a decimal integer at ${path}`);
385
+ }
386
+ if (num <= 0n)
387
+ throw malformed(`call_arg_scaled.num must be > 0 at ${path}`);
388
+ if (den <= 0n)
389
+ throw malformed(`call_arg_scaled.den must be > 0 at ${path}`);
390
+ return;
391
+ }
392
+ case 'literal_u32':
393
+ if (!Number.isInteger(leaf.value) || leaf.value < 0 || leaf.value > U32_MAX) {
394
+ throw malformed(`literal_u32.value out of u32 range at ${path}`);
395
+ }
396
+ return;
397
+ case 'literal_i128':
398
+ // literal_i128 is signed; the contract allows negatives (i128
399
+ // arithmetic), but caps on a positive quantity (amount / window
400
+ // bound) should never be negative - a negative cap is silently
401
+ // satisfied by every non-negative amount. The contract gate is
402
+ // already on the leaf's ROLE (amount vs equality) not the value;
403
+ // here we mirror the value-only invariant the cap-set gate enforces
404
+ // by refusing the syntactic shape that would clearly be a bug
405
+ // (literal_i128 as a CAP with a leading `-` on a non-equality).
406
+ // We do not gate equality i128 - `literal_i128` as an address-by-
407
+ // equality is fine (it is just a constant).
408
+ // The value itself is always accepted; the structural check
409
+ // (non-negative for an amount / window bound) is left to the
410
+ // caller-built predicate, not the encoder.
411
+ return;
412
+ case 'literal_bytes':
413
+ // Hex even-length: a non-hex char silently drops, and an odd
414
+ // length yields a half-byte Buffer. The contract decodes with a
415
+ // strict hex parser and refuses anything that is not even-length
416
+ // hex; mirror that here.
417
+ if (!/^[0-9a-fA-F]*$/.test(leaf.value) || leaf.value.length % 2 !== 0) {
418
+ throw malformed(`literal_bytes.value must be even-length hex at ${path}`);
419
+ }
420
+ return;
421
+ case 'oracle_threshold':
422
+ if (!Number.isInteger(leaf.decimals) ||
423
+ leaf.decimals < 0 ||
424
+ leaf.decimals > MAX_ORACLE_THRESHOLD_DECIMALS) {
425
+ throw malformed(`oracle_threshold.decimals out of range (0..${MAX_ORACLE_THRESHOLD_DECIMALS}) at ${path}`);
426
+ }
427
+ return;
428
+ case 'literal_vec':
429
+ leaf.elements.forEach((e, i) => {
430
+ walkLeaf(e, `${path}.elements[${i}]`);
431
+ });
432
+ return;
433
+ // Selector and other leaves carry no cap-set values; the call_arg
434
+ // branches above cover indices, the literal branches cover typed
435
+ // constants. amount / window_spent / invocation_count / now /
436
+ // valid_until / call_contract / call_fn / literal_address /
437
+ // literal_symbol / literal_u64 / oracle_price are all value-free
438
+ // at this gate.
439
+ case 'amount':
440
+ case 'window_spent':
441
+ case 'invocation_count_in_window':
442
+ case 'now':
443
+ case 'valid_until':
444
+ case 'call_contract':
445
+ case 'call_fn':
446
+ case 'literal_address':
447
+ case 'literal_symbol':
448
+ case 'literal_u64':
449
+ case 'oracle_price':
450
+ return;
451
+ }
452
+ }
453
+ function walkNode(n, path) {
454
+ switch (n.op) {
455
+ case 'and':
456
+ case 'or':
457
+ n.children.forEach((c, i) => {
458
+ walkNode(c, `${path}.children[${i}]`);
459
+ });
460
+ return;
461
+ case 'not':
462
+ walkNode(n.child, `${path}.child`);
463
+ return;
464
+ case 'eq':
465
+ case 'lt':
466
+ case 'lte':
467
+ case 'gt':
468
+ case 'gte':
469
+ walkLeaf(n.left, `${path}.left`);
470
+ walkLeaf(n.right, `${path}.right`);
471
+ return;
472
+ case 'in':
473
+ walkLeaf(n.needle, `${path}.needle`);
474
+ n.haystack.forEach((h, i) => {
475
+ walkLeaf(h, `${path}.haystack[${i}]`);
476
+ });
477
+ return;
478
+ }
479
+ }
480
+ walkNode(node, '<root>');
481
+ }
482
+ function malformed(message) {
483
+ return capError('MALFORMED_PREDICATE', message);
484
+ }
@@ -7,8 +7,8 @@
7
7
  // Outputs:
8
8
  // - top-level ContractInvocation (the single Context `Policy::enforce` receives)
9
9
  // - subInvocations captured on each ContractInvocation from
10
- // SorobanAuthorizedInvocation.subInvocations - DIAGNOSTIC ONLY;
11
- // v1 grammar does NOT walk sub-invocations (see types.ts notes).
10
+ // SorobanAuthorizedInvocation.subInvocations - DIAGNOSTIC ONLY; v1 grammar
11
+ // does NOT walk sub-invocations (see types.ts notes).
12
12
  // - decoded args vector mapped to the normalised `ScVal` subset
13
13
  // - sourceAccount, signers
14
14
  // - raw event list surfaced for downstream validation
@@ -31,14 +31,13 @@ export function decodeEnvelope(envelope, events = [], _authEntries = [], ledgerS
31
31
  // Fee-bump wraps a normal inner v1 transaction (a different account
32
32
  // pays the fee). The real operations + their authorizers live on the
33
33
  // INNER v1 envelope, so decode that and discard the outer fee-bump
34
- // shell. The fee-bump envelope switch arm `v0` is intentionally not
35
- // routed here - fee-bump v0 does not exist.
34
+ // shell (fee-bump v0 does not exist).
36
35
  const innerV1 = envelope.feeBump().tx().innerTx().v1();
37
36
  return decodeV1Envelope(innerV1, events, ledgerSequence, knownContracts, network);
38
37
  }
39
38
  if (envType !== 'envelopeTypeTx') {
40
- // TransactionV0 is out of scope - v1 protocol only. Fee-bump is now
41
- // handled above; legacy envelopes reach this branch.
39
+ // TransactionV0 is out of scope (v1 protocol only). Fee-bump is handled
40
+ // above; legacy envelopes reach this branch.
42
41
  throw new DecodeError(`unsupported envelope: ${envType}`);
43
42
  }
44
43
  return decodeV1Envelope(envelope.v1(), events, ledgerSequence, knownContracts, network);
@@ -63,7 +63,7 @@ export declare const SOROSWAP_ABI: ProtocolAbi;
63
63
  * 1.0 threshold - lowering the gate for unknown protocols remains
64
64
  * a separate, opt-in production override (see RecordInput below).
65
65
  *
66
- * ABI source: packages/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
66
+ * ABI source: contracts/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
67
67
  * pinned from the OpenZeppelin Reloaded `multisig_account_example`
68
68
  * contract (commit ef82b65, fetched 2026-07-28).
69
69
  *
@@ -168,7 +168,7 @@ export const SOROSWAP_ABI = {
168
168
  * 1.0 threshold - lowering the gate for unknown protocols remains
169
169
  * a separate, opt-in production override (see RecordInput below).
170
170
  *
171
- * ABI source: packages/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
171
+ * ABI source: contracts/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
172
172
  * pinned from the OpenZeppelin Reloaded `multisig_account_example`
173
173
  * contract (commit ef82b65, fetched 2026-07-28).
174
174
  *
@@ -5,6 +5,12 @@ export interface ReviewCardSummary {
5
5
  plainEnglish: string;
6
6
  constraints: string[];
7
7
  expiry: string;
8
+ /** Cross-layer L1: a human-readable note about the OZ any-of-N signer
9
+ * semantic for rules with N>=2 signers. `null` for single-signer rules
10
+ * (the note would be redundant). Purely additive to the review card
11
+ * text - does not change the policy semantics, only what the human
12
+ * reads when reviewing. */
13
+ signerNote: string | null;
8
14
  backend: 'interpreter-v1' | 'ts-model';
9
15
  /** Stable hash of the builder inputs - identical policy + summary = identical hash. */
10
16
  contentHash: string;
@@ -48,15 +48,23 @@ export function buildReviewCardSummary(predicate, policyRefs, contextRule, simul
48
48
  const ruleName = contextRule.name;
49
49
  const plainEnglish = renderPlainEnglish(ruleName, constraints);
50
50
  const expiry = renderExpiry(contextRule.validUntilLedger);
51
+ // Cross-layer L1: a rule with N>=2 signers gets a one-line note about
52
+ // the OZ any-of-N semantic so the human reviewing the install reads the
53
+ // same wire-level behaviour the contract enforces. A single-signer rule
54
+ // is trivially any-of-1, so the note would be noise.
55
+ const signerNote = contextRule.signers.length >= 2
56
+ ? 'any ONE signer may authorise a permitted op under this rule (OZ any-of-N semantic)'
57
+ : null;
51
58
  const backend = simulation.backend;
52
59
  const contentHash = computeContentHash({
53
60
  ruleName,
54
61
  plainEnglish,
55
62
  constraints,
56
63
  expiry,
64
+ signerNote,
57
65
  backend,
58
66
  });
59
- return { ruleName, plainEnglish, constraints, expiry, backend, contentHash };
67
+ return { ruleName, plainEnglish, constraints, expiry, signerNote, backend, contentHash };
60
68
  }
61
69
  /** Render the OZ built-in primitive summary line. Only `spending_limit` is
62
70
  * quoted by the review card (it is the only primitive that defines a
@@ -9,6 +9,7 @@ export type RunRecordTransactionInput = RecordTransactionInput;
9
9
  export type RunSynthesizePolicyInput = SynthesizePolicyInput;
10
10
  export type RunSimulatePolicyInput = SimulatePolicyInput;
11
11
  export type RunVerifyPolicyInput = VerifyPolicyInput;
12
+ type RunToolName = 'record_transaction' | 'synthesize_policy' | 'simulate_policy' | 'verify_policy' | 'install_policy' | 'revoke_policy' | 'get_interpreter_info';
12
13
  /** `record_transaction` body - wraps `recordTransaction`. The tool input
13
14
  * matches the core RecordInput minus the injected `fetcher` (the transport
14
15
  * layer does not own the RPC). Returns the core ToolResponse unchanged.
@@ -86,20 +87,20 @@ export declare function runRevokePolicy(raw: unknown): Promise<ToolResponse<Buil
86
87
  * Network-aware: `input.network` selects which interpreter pin and RPC
87
88
  * to use. Mainnet was rolled out 2026-08-04 - the same wasm hash was
88
89
  * uploaded to mainnet as was exercised on testnet, so a single
89
- * `PINNED_INTERPRETER_WASM_SHA256` constant backs both networks
90
- * (DEPLOYMENTS.md:25-27). The address differs because instance ids are
91
- * network-scoped. UNAUDITED at the time of writing - see
92
- * DEPLOYMENTS.md:29-32 for what is still pending. */
90
+ * `PINNED_INTERPRETER_WASM_SHA256` constant backs both networks.
91
+ * The address differs because instance ids are network-scoped.
92
+ * UNAUDITED at the time of writing.
93
+ *
94
+ * Same RPC pin as install/revoke: when `verifyLive` triggers an outbound
95
+ * call, the auth-digest + the answer bind to whichever RPC answered, so
96
+ * a non-pinned `rpcUrl` would silently bind the caller to a host they
97
+ * picked. The pin is enforced here too, with the same `allowUnpinnedRpcUrl`
98
+ * opt-in as install/revoke. */
93
99
  export declare function runGetInterpreterInfo(raw: unknown): Promise<ToolResponse<ReturnType<typeof getInterpreterInfo>>>;
94
100
  /** Build a canonical ToolError for a thrown exception caught by the tool
95
101
  * envelope. The MCP SDK stringifies thrown objects as "[object Object]" by
96
102
  * default, so we extract a string-friendly message and tag the original
97
- * error in `details` for the agent to inspect. The `code` is the tool's
98
- * domain code (RECORDING_FAILED for `record_transaction`, SYNTHESIS_ERROR
99
- * for `synthesize_policy`) so the agent dispatches on the same code the
100
- * structured ToolError would carry.
101
- *
102
- * Exported as `_caughtError` (the leading underscore signals the test-only
103
- * seam) so the suite in run/index.test.ts can drive the envelope path
104
- * without standing up a full recordTransaction pipeline. */
105
- export declare function caughtError(toolName: 'record_transaction' | 'synthesize_policy' | 'simulate_policy' | 'verify_policy' | 'install_policy' | 'revoke_policy' | 'get_interpreter_info', code: ErrorCode, e: unknown): ToolError;
103
+ * error in `details` for the agent to inspect. Exported as a test-only seam
104
+ * so the suite in run/index.test.ts can drive the envelope path without
105
+ * standing up a full recordTransaction pipeline. */
106
+ export declare function caughtError(toolName: RunToolName, code: ErrorCode, e: unknown): ToolError;