@crediolabs/policy-synth 0.1.17 → 0.2.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 (113) hide show
  1. package/README.md +44 -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/authority-overlap.d.ts +134 -0
  8. package/dist/install/authority-overlap.js +0 -0
  9. package/dist/install/build-add-context-rule.d.ts +8 -0
  10. package/dist/install/build-add-context-rule.js +17 -46
  11. package/dist/install/build-install-policy.d.ts +12 -5
  12. package/dist/install/build-install-policy.js +32 -23
  13. package/dist/install/build-merge-policy.d.ts +70 -0
  14. package/dist/install/build-merge-policy.js +130 -0
  15. package/dist/install/get-interpreter-info.js +2 -2
  16. package/dist/install/index.d.ts +3 -1
  17. package/dist/install/index.js +8 -1
  18. package/dist/install/oz-auth.js +5 -3
  19. package/dist/install/plan-merge-policy.d.ts +49 -0
  20. package/dist/install/plan-merge-policy.js +86 -0
  21. package/dist/install/read-account-rules.d.ts +100 -0
  22. package/dist/install/read-account-rules.js +283 -0
  23. package/dist/predicate/decode.js +1 -1
  24. package/dist/predicate/encode.js +171 -10
  25. package/dist/record/decode.js +5 -6
  26. package/dist/registry/protocols.d.ts +1 -1
  27. package/dist/registry/protocols.js +1 -1
  28. package/dist/review-card/builder.d.ts +6 -0
  29. package/dist/review-card/builder.js +9 -1
  30. package/dist/run/index.d.ts +104 -18
  31. package/dist/run/index.js +359 -75
  32. package/dist/run/schemas.d.ts +479 -18
  33. package/dist/run/schemas.js +132 -24
  34. package/dist/synth/compose-from-recording.d.ts +10 -15
  35. package/dist/synth/compose-from-recording.js +79 -124
  36. package/dist/synth/deny-cases.d.ts +5 -0
  37. package/dist/synth/deny-cases.js +52 -13
  38. package/dist/synth/evaluate.js +69 -119
  39. package/dist/synth/harness.d.ts +13 -1
  40. package/dist/synth/harness.js +22 -1
  41. package/dist/synth/index.d.ts +1 -1
  42. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  43. package/dist/synth/synthesize-from-recording.js +129 -155
  44. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  45. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  46. package/dist-cjs/adapters/oz/adapter.js +12 -13
  47. package/dist-cjs/codegen/compile-gate.js +5 -0
  48. package/dist-cjs/codegen/template.js +17 -0
  49. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  50. package/dist-cjs/install/authority-overlap.js +0 -0
  51. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  52. package/dist-cjs/install/build-add-context-rule.js +17 -45
  53. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  54. package/dist-cjs/install/build-install-policy.js +32 -23
  55. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  56. package/dist-cjs/install/build-merge-policy.js +134 -0
  57. package/dist-cjs/install/get-interpreter-info.js +2 -2
  58. package/dist-cjs/install/index.d.ts +3 -1
  59. package/dist-cjs/install/index.js +24 -3
  60. package/dist-cjs/install/oz-auth.js +5 -3
  61. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  62. package/dist-cjs/install/plan-merge-policy.js +90 -0
  63. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  64. package/dist-cjs/install/read-account-rules.js +296 -0
  65. package/dist-cjs/predicate/decode.js +1 -1
  66. package/dist-cjs/predicate/encode.js +171 -10
  67. package/dist-cjs/record/decode.js +5 -6
  68. package/dist-cjs/registry/protocols.d.ts +1 -1
  69. package/dist-cjs/registry/protocols.js +1 -1
  70. package/dist-cjs/review-card/builder.d.ts +6 -0
  71. package/dist-cjs/review-card/builder.js +9 -1
  72. package/dist-cjs/run/index.d.ts +104 -18
  73. package/dist-cjs/run/index.js +360 -74
  74. package/dist-cjs/run/schemas.d.ts +479 -18
  75. package/dist-cjs/run/schemas.js +133 -25
  76. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  77. package/dist-cjs/synth/compose-from-recording.js +79 -124
  78. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  79. package/dist-cjs/synth/deny-cases.js +52 -13
  80. package/dist-cjs/synth/evaluate.js +69 -119
  81. package/dist-cjs/synth/harness.d.ts +13 -1
  82. package/dist-cjs/synth/harness.js +22 -1
  83. package/dist-cjs/synth/index.d.ts +1 -1
  84. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  85. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  86. package/package.json +1 -1
  87. package/src/adapters/interpreter/adapter.ts +28 -48
  88. package/src/adapters/oz/adapter.ts +12 -13
  89. package/src/codegen/compile-gate.ts +5 -0
  90. package/src/codegen/template.ts +17 -0
  91. package/src/install/authority-overlap.ts +0 -0
  92. package/src/install/build-add-context-rule.ts +29 -56
  93. package/src/install/build-install-policy.ts +41 -23
  94. package/src/install/build-merge-policy.ts +219 -0
  95. package/src/install/get-interpreter-info.ts +2 -2
  96. package/src/install/index.ts +36 -2
  97. package/src/install/oz-auth.ts +5 -3
  98. package/src/install/plan-merge-policy.ts +133 -0
  99. package/src/install/read-account-rules.ts +376 -0
  100. package/src/predicate/decode.ts +1 -1
  101. package/src/predicate/encode.ts +176 -10
  102. package/src/record/decode.ts +5 -6
  103. package/src/registry/protocols.ts +1 -1
  104. package/src/review-card/builder.ts +17 -1
  105. package/src/run/index.ts +500 -102
  106. package/src/run/schemas.ts +145 -24
  107. package/src/synth/compose-from-recording.ts +87 -132
  108. package/src/synth/deny-cases.ts +59 -13
  109. package/src/synth/evaluate.ts +70 -118
  110. package/src/synth/harness.ts +29 -1
  111. package/src/synth/index.ts +1 -0
  112. package/src/synth/synthesize-from-recording.ts +209 -192
  113. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -0,0 +1,134 @@
1
+ import type { PredicateNode, SignerDraft } from '../types.ts';
2
+ /** Wildcard component of a `Selector`: the predicate does not pin this half. */
3
+ export declare const ANY = "*";
4
+ /** A (contract, function) pair a predicate may permit. `ANY` in either half
5
+ * means unconstrained, so `{contract: ANY, fn: ANY}` is "any call at all". */
6
+ export interface Selector {
7
+ contract: string;
8
+ fn: string;
9
+ }
10
+ export type ContextType = {
11
+ kind: 'default';
12
+ } | {
13
+ kind: 'call_contract';
14
+ address: string;
15
+ } | {
16
+ kind: 'create_contract';
17
+ wasmHash: string;
18
+ };
19
+ /** How much we can say about a neighbouring rule.
20
+ * - `interpreter`: policed by our interpreter and the predicate was readable,
21
+ * so its authority is known exactly and it can be merged.
22
+ * - `foreign`: policed by some other contract. The address is visible, the
23
+ * semantics are not, so it must be reviewed by hand.
24
+ * - `unpoliced`: no policy at all. Whatever the rule's context type allows,
25
+ * its signers may do without constraint. */
26
+ export type RuleClass = 'interpreter' | 'foreign' | 'unpoliced';
27
+ export interface ObservedRule {
28
+ id: number;
29
+ contextType: ContextType;
30
+ signers: SignerDraft[];
31
+ /** Policy contract addresses attached to the rule, in OZ's order. */
32
+ policyAddresses: string[];
33
+ /** OZ's global registry ids for those policies, index-aligned with
34
+ * `policyAddresses`. `remove_policy` takes the id, not the address, so
35
+ * detaching a policy is impossible without them. */
36
+ policyIds?: number[];
37
+ /** Per-policy oracle bounds from the stored document, when it was
38
+ * readable. A merge must re-install these or it silently widens them. */
39
+ oracleBounds?: {
40
+ maxStalenessSeconds?: number;
41
+ maxDeviationBps?: number;
42
+ maxCrossFeedDeviationBps?: number;
43
+ };
44
+ /** Decoded predicate. Present only when the rule is policed by our
45
+ * interpreter AND the stored document was readable. */
46
+ predicate?: PredicateNode;
47
+ }
48
+ export interface IntendedInstall {
49
+ /** Rule the predicate is being installed onto. A re-install onto the same
50
+ * id is a replacement, not an overlap, so this id is skipped. */
51
+ ruleId: number;
52
+ contextType: ContextType;
53
+ signers: SignerDraft[];
54
+ predicate: PredicateNode;
55
+ }
56
+ export type OverlapSeverity =
57
+ /** A neighbouring rule imposes no constraint at all on the shared calls. */
58
+ 'bypass'
59
+ /** A neighbouring policy exists but we cannot read what it permits. */
60
+ | 'unknown'
61
+ /** Both rules are ours. The new rule will not restrict the shared calls,
62
+ * because the signer can name whichever rule is more permissive. */
63
+ | 'not-restricting';
64
+ export interface AuthorityOverlap {
65
+ ruleId: number;
66
+ ruleClass: RuleClass;
67
+ severity: OverlapSeverity;
68
+ /** Signers present in both rules. Overlap is only reachable by a signer who
69
+ * can name both rules, so a rule sharing no signer is not a collision. */
70
+ sharedSigners: SignerDraft[];
71
+ /** The selectors both rules can serve. Non-empty by construction. */
72
+ sharedSelectors: Selector[];
73
+ /** True when the neighbour is ours and can therefore be replaced by the
74
+ * conjunction of the two predicates. */
75
+ mergeable: boolean;
76
+ advice: string;
77
+ }
78
+ /** Canonical key for signer equality. Mirrors OZ's `Signer` enum: a delegated
79
+ * signer is its address, an external signer is the verifier plus the key
80
+ * bytes, since one verifier may hold many keys. */
81
+ export declare function signerKey(s: SignerDraft): string;
82
+ /** Intersection of two selector SETS: every compatible pairing survives. */
83
+ export declare function intersectSelectors(a: Selector[], b: Selector[]): Selector[];
84
+ /**
85
+ * The set of `(contract, fn)` selectors a predicate may permit.
86
+ *
87
+ * This is a deliberate OVER-approximation: every call the predicate actually
88
+ * permits is covered by some returned selector, and unrecognised structure
89
+ * widens to the wildcard rather than narrowing. That direction is what makes
90
+ * the emptiness test below sound. A call carries exactly one `(contract, fn)`,
91
+ * so if two predicates' over-approximations do not intersect, no single call
92
+ * can be routed to either of them and the rules provably cannot collide.
93
+ *
94
+ * `not` is treated as unconstrained. Complementing a selector set would need
95
+ * the universe of addresses and function names, which is not available and
96
+ * would not be sound to guess.
97
+ */
98
+ export declare function permittedSelectors(node: PredicateNode): Selector[];
99
+ /** Selectors a context type admits, before the predicate narrows them. */
100
+ export declare function selectorsForContextType(ct: ContextType): Selector[];
101
+ /** What a rule can actually authorise: its context type narrowed by its
102
+ * predicate. An unpoliced or unreadable rule contributes no narrowing. */
103
+ export declare function effectiveSelectors(rule: ObservedRule): Selector[];
104
+ /**
105
+ * Every existing rule that a signer of the intended install could name instead.
106
+ *
107
+ * A rule collides when it shares at least one signer AND at least one selector,
108
+ * because both conditions are needed for the signer to have a choice. The rule
109
+ * being installed onto is skipped: re-installing over it replaces its
110
+ * predicate rather than adding a second source of authority.
111
+ */
112
+ export declare function findAuthorityOverlaps(args: {
113
+ intended: IntendedInstall;
114
+ existing: ObservedRule[];
115
+ }): AuthorityOverlap[];
116
+ export interface MergeResult {
117
+ ok: boolean;
118
+ predicate?: PredicateNode;
119
+ /** Set when `ok` is false. */
120
+ reason?: string;
121
+ }
122
+ /**
123
+ * Conjunction of an existing predicate with a new one, for the tightening case.
124
+ *
125
+ * `and` children are flattened so repeated merges do not nest, which keeps the
126
+ * encoded form closer to the byte cap.
127
+ *
128
+ * The guard matters more than the merge. `and` is only correct when the caller
129
+ * means to tighten. Applied to two predicates that pin DIFFERENT selectors it
130
+ * produces a predicate permitting nothing, which silently disables the policy
131
+ * instead of restricting it. That case is refused, because the caller wanted
132
+ * two capabilities and two rules already express that correctly.
133
+ */
134
+ export declare function mergeIntoAnd(existing: PredicateNode, incoming: PredicateNode): MergeResult;
@@ -46,3 +46,11 @@ export type AddContextRuleArgs = readonly [
46
46
  /** Build the `add_context_rule` invocation args. Throws a `ToolError`-shaped
47
47
  * error on limit breaches or malformed input. */
48
48
  export declare function buildAddContextRuleArgs(draft: ContextRuleDraft, args: BuildAddContextRuleArgs): AddContextRuleArgs;
49
+ /** The `PolicyInstallParams` ScVal an interpreter policy receives.
50
+ *
51
+ * Exported so the merge remedy can re-install a policy through `add_policy`
52
+ * using the SAME encoder as a fresh install. Re-implementing it would risk
53
+ * exactly the drift this file warns about: the field order is ABI-significant
54
+ * and a differing encoding yields a rule that denies every call. */
55
+ export type PolicyInstallParamArgs = Pick<BuildAddContextRuleArgs, 'encodedPredicate' | 'predicateHash' | 'installNonce' | 'oracleParams' | 'grammarVersion'>;
56
+ export declare function encodePolicyInstallParams(args: PolicyInstallParamArgs): xdr.ScVal;
@@ -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),
@@ -215,54 +214,26 @@ function encodeI128(value) {
215
214
  lo: new xdr.Uint64(BigInt.asUintN(64, v)),
216
215
  }));
217
216
  }
218
- function encodePolicyInstallParams(args) {
217
+ export function encodePolicyInstallParams(args) {
219
218
  const predicate = Buffer.from(args.encodedPredicate, 'base64');
220
219
  const computedHash = createHash('sha256').update(predicate).digest('hex');
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
  };
@@ -0,0 +1,70 @@
1
+ import type { InstallRpcClient } from './build-install-policy.ts';
2
+ import type { MergeStep } from './plan-merge-policy.ts';
3
+ /**
4
+ * The context rule the merge authorises AGAINST, which is not the rule being
5
+ * merged.
6
+ *
7
+ * Both calls mutate the smart account itself, so they need the account's own
8
+ * authorisation, and this builder asks rule 0 for it - the same assumption the
9
+ * install and revoke builders make. OpenZeppelin does NOT enforce any
10
+ * admin semantic for rule 0: it is simply the first rule the account's
11
+ * constructor created, and OZ's reference account creates it as `Default`
12
+ * covering every context.
13
+ *
14
+ * The assumption is therefore load-bearing and unverified at build time. If
15
+ * rule 0 does not exist, does not cover `CallContract(<smart account>)`, or
16
+ * does not list the source account as a signer, the transaction is built and
17
+ * then fails when submitted, and the operator pays the fee for a transaction
18
+ * that was never signable. Changing it is a wire-visible change: the id is
19
+ * hashed into the auth digest.
20
+ */
21
+ export declare const ADMIN_CONTEXT_RULE_ID = 0;
22
+ export interface BuildMergePolicyArgs {
23
+ smartAccount: string;
24
+ sourceAccount: string;
25
+ networkPassphrase: string;
26
+ ruleId: number;
27
+ /** OZ registry id of the interpreter policy on this rule, from the plan. */
28
+ policyId: number;
29
+ interpreterAddress: string;
30
+ step: MergeStep;
31
+ /** Only needed for `reinstall`: the merged predicate, already encoded. */
32
+ encodedPredicate?: string;
33
+ predicateHash?: string;
34
+ /** Nonce for the reinstall. Read from chain rather than assumed: a detach
35
+ * whose uninstall panicked leaves the old nonce in place. */
36
+ installNonce?: number;
37
+ /** Oracle bounds to carry over from the document being replaced. */
38
+ oracleParams?: {
39
+ maxStalenessSeconds?: number;
40
+ maxDeviationBps?: number;
41
+ maxCrossFeedDeviationBps?: number;
42
+ };
43
+ rpc: InstallRpcClient;
44
+ baseFee?: number;
45
+ authValidUntilLedgers?: number;
46
+ }
47
+ export interface BuildMergePolicyResult {
48
+ unsignedXdr: string;
49
+ smartAccount: string;
50
+ sourceAccount: string;
51
+ step: MergeStep;
52
+ call: {
53
+ contract: string;
54
+ fn: 'remove_policy' | 'add_policy';
55
+ ruleId: number;
56
+ };
57
+ authNonce: string;
58
+ authValidUntilLedger: number;
59
+ rootInvocationXdr: string;
60
+ }
61
+ /**
62
+ * Build the unsigned transaction for one step of the merge.
63
+ *
64
+ * The auth dance mirrors `buildRevokePolicyXdr`: simulate once to record the
65
+ * account's auth entry, rebuild with the payload bound to that recorded
66
+ * `rootInvocation`, then assemble. Binding to the recorded invocation rather
67
+ * than to the input arguments is what makes the signature commit to the exact
68
+ * rule and policy being changed.
69
+ */
70
+ export declare function buildMergePolicyXdr(args: BuildMergePolicyArgs): Promise<BuildMergePolicyResult>;
@@ -0,0 +1,130 @@
1
+ //! Transactions for the merge remedy.
2
+ //!
3
+ //! `plan-merge-policy.ts` decides WHAT should happen; this builds the XDR for
4
+ //! the step the caller asked for. Two calls, in order, because OZ refuses to
5
+ //! attach a policy that is already on the rule:
6
+ //!
7
+ //! step 1 `detach` -> `account.remove_policy(rule_id, policy_id)`
8
+ //! step 2 `reinstall` -> `account.add_policy(rule_id, interpreter, param)`
9
+ //!
10
+ //! The two cannot be emitted together. Simulating step 2 while the old
11
+ //! attachment is still there hits `DuplicatePolicy`, so the second transaction
12
+ //! is only buildable once the first has confirmed.
13
+ //!
14
+ //! Both calls route through the smart account and are authorised the same way
15
+ //! as `revoke_policy`: against the deploy-time admin rule, with the recorded
16
+ //! `rootInvocation` binding the auth payload to this exact rule and policy.
17
+ //! Detaching runs our `uninstall`, which is master-gated, so the signer has to
18
+ //! be a master of the rule either way.
19
+ import { Account, Address, BASE_FEE, Operation, rpc, TransactionBuilder, xdr, } from '@stellar/stellar-sdk';
20
+ import { DEFAULT_GRAMMAR_VERSION, encodePolicyInstallParams } from "./build-add-context-rule.js";
21
+ import { accountEntry, authDigest, authPayload, delegatedSignerEntry, signaturePayload, } from "./oz-auth.js";
22
+ /** Matches the window the install and revoke builders use. */
23
+ const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 100;
24
+ /**
25
+ * The context rule the merge authorises AGAINST, which is not the rule being
26
+ * merged.
27
+ *
28
+ * Both calls mutate the smart account itself, so they need the account's own
29
+ * authorisation, and this builder asks rule 0 for it - the same assumption the
30
+ * install and revoke builders make. OpenZeppelin does NOT enforce any
31
+ * admin semantic for rule 0: it is simply the first rule the account's
32
+ * constructor created, and OZ's reference account creates it as `Default`
33
+ * covering every context.
34
+ *
35
+ * The assumption is therefore load-bearing and unverified at build time. If
36
+ * rule 0 does not exist, does not cover `CallContract(<smart account>)`, or
37
+ * does not list the source account as a signer, the transaction is built and
38
+ * then fails when submitted, and the operator pays the fee for a transaction
39
+ * that was never signable. Changing it is a wire-visible change: the id is
40
+ * hashed into the auth digest.
41
+ */
42
+ export const ADMIN_CONTEXT_RULE_ID = 0;
43
+ function hostFunctionFor(args) {
44
+ if (args.step === 'detach') {
45
+ return xdr.HostFunction.hostFunctionTypeInvokeContract(new xdr.InvokeContractArgs({
46
+ contractAddress: new Address(args.smartAccount).toScAddress(),
47
+ functionName: 'remove_policy',
48
+ args: [xdr.ScVal.scvU32(args.ruleId), xdr.ScVal.scvU32(args.policyId)],
49
+ }));
50
+ }
51
+ if (!args.encodedPredicate || !args.predicateHash) {
52
+ throw new Error('merge_policy: reinstall needs the merged predicate and its hash');
53
+ }
54
+ return xdr.HostFunction.hostFunctionTypeInvokeContract(new xdr.InvokeContractArgs({
55
+ contractAddress: new Address(args.smartAccount).toScAddress(),
56
+ functionName: 'add_policy',
57
+ args: [
58
+ xdr.ScVal.scvU32(args.ruleId),
59
+ new Address(args.interpreterAddress).toScVal(),
60
+ // Same encoder as a fresh install: the field order is ABI-significant
61
+ // and it re-hashes the predicate to confirm the supplied hash.
62
+ encodePolicyInstallParams({
63
+ encodedPredicate: args.encodedPredicate,
64
+ predicateHash: args.predicateHash,
65
+ installNonce: args.installNonce ?? 1,
66
+ grammarVersion: DEFAULT_GRAMMAR_VERSION,
67
+ ...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
68
+ }),
69
+ ],
70
+ }));
71
+ }
72
+ /**
73
+ * Build the unsigned transaction for one step of the merge.
74
+ *
75
+ * The auth dance mirrors `buildRevokePolicyXdr`: simulate once to record the
76
+ * account's auth entry, rebuild with the payload bound to that recorded
77
+ * `rootInvocation`, then assemble. Binding to the recorded invocation rather
78
+ * than to the input arguments is what makes the signature commit to the exact
79
+ * rule and policy being changed.
80
+ */
81
+ export async function buildMergePolicyXdr(args) {
82
+ const fn = args.step === 'detach' ? 'remove_policy' : 'add_policy';
83
+ const source = await args.rpc.getAccount(args.sourceAccount);
84
+ const hostFunction = hostFunctionFor(args);
85
+ const makeOperation = (auth = []) => Operation.invokeHostFunction({ func: hostFunction, auth });
86
+ const baseFee = args.baseFee !== undefined ? String(args.baseFee) : BASE_FEE;
87
+ const buildTx = (op) => new TransactionBuilder(new Account(args.sourceAccount, source.sequenceNumber()), {
88
+ fee: baseFee,
89
+ networkPassphrase: args.networkPassphrase,
90
+ })
91
+ .addOperation(op)
92
+ .setTimeout(0)
93
+ .build();
94
+ const recorded = await args.rpc.simulateTransaction(buildTx(makeOperation()));
95
+ if (rpc.Api.isSimulationError(recorded)) {
96
+ // Short and stable, like the other builders: the SDK's full error carries
97
+ // host and URL detail that has no business in a user-facing message.
98
+ throw new Error(`merge_policy: ${fn} simulateTransaction failed`);
99
+ }
100
+ const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
101
+ Address.fromScAddress(entry.credentials().address().address()).toString() ===
102
+ args.smartAccount);
103
+ if (!original) {
104
+ throw new Error(`merge_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
105
+ }
106
+ const validUntilLedger = (await args.rpc.getLatestLedger()).sequence +
107
+ (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS);
108
+ const contextRuleIds = [ADMIN_CONTEXT_RULE_ID];
109
+ const digest = authDigest(signaturePayload(args.networkPassphrase, original.credentials().address().nonce(), validUntilLedger, original.rootInvocation()), contextRuleIds);
110
+ const authEntries = [
111
+ accountEntry(original, validUntilLedger, authPayload([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))),
112
+ ...contextRuleIds.map(() => delegatedSignerEntry(args.smartAccount, digest)),
113
+ ];
114
+ const txWithAuth = buildTx(makeOperation(authEntries));
115
+ const enforcing = await args.rpc.simulateTransaction(txWithAuth);
116
+ if (rpc.Api.isSimulationError(enforcing)) {
117
+ throw new Error(`merge_policy: ${fn} auth simulateTransaction failed`);
118
+ }
119
+ const finalTx = rpc.assembleTransaction(txWithAuth, enforcing).build();
120
+ return {
121
+ unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
122
+ smartAccount: args.smartAccount,
123
+ sourceAccount: args.sourceAccount,
124
+ step: args.step,
125
+ call: { contract: args.smartAccount, fn, ruleId: args.ruleId },
126
+ authNonce: original.credentials().address().nonce().toString(),
127
+ authValidUntilLedger: validUntilLedger,
128
+ rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
129
+ };
130
+ }
@@ -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
@@ -1 +1,3 @@
1
- export { ADD_CONTEXT_RULE_SYMBOL, DEFAULT_GRAMMAR_VERSION, buildAddContextRuleArgs, type AddContextRuleArgs, type BuildAddContextRuleArgs, } from './build-add-context-rule.ts';
1
+ export { ANY, type AuthorityOverlap, type ContextType, effectiveSelectors, findAuthorityOverlaps, type IntendedInstall, intersectSelectors, type MergeResult, mergeIntoAnd, type ObservedRule, type OverlapSeverity, permittedSelectors, type RuleClass, type Selector, signerKey, } from './authority-overlap.ts';
2
+ export { ADD_CONTEXT_RULE_SYMBOL, type AddContextRuleArgs, type BuildAddContextRuleArgs, buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION, } from './build-add-context-rule.ts';
3
+ export { type AccountRuleReader, accountRuleReaderFromServer, type CollectedRules, collectObservedRules, decodeContextRule, decodeContextType, decodeSigner, docLedgerKey, MAX_RULE_ID_SCAN, } from './read-account-rules.ts';
@@ -12,4 +12,11 @@
12
12
  // Exported here rather than from the package root to keep the root surface
13
13
  // about synthesis, and because these are transaction-building primitives whose
14
14
  // callers should know they are reaching for them.
15
- export { ADD_CONTEXT_RULE_SYMBOL, DEFAULT_GRAMMAR_VERSION, buildAddContextRuleArgs, } from "./build-add-context-rule.js";
15
+ // Cross-rule authority analysis. A caller installing a policy needs to know
16
+ // whether its signers can already reach the same calls through another context
17
+ // rule, because OZ lets the signer name the rule and enforces only that one's
18
+ // policies. Without this, a second, tighter rule reads as a restriction while
19
+ // restricting nothing.
20
+ export { ANY, effectiveSelectors, findAuthorityOverlaps, intersectSelectors, mergeIntoAnd, permittedSelectors, signerKey, } from "./authority-overlap.js";
21
+ export { ADD_CONTEXT_RULE_SYMBOL, buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION, } from "./build-add-context-rule.js";
22
+ export { accountRuleReaderFromServer, collectObservedRules, decodeContextRule, decodeContextType, decodeSigner, docLedgerKey, MAX_RULE_ID_SCAN, } from "./read-account-rules.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()]);