@crediolabs/policy-synth 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/adapters/interpreter/index.d.ts +1 -1
  5. package/dist/adapters/interpreter/index.js +1 -1
  6. package/dist/adapters/oz/adapter.js +1 -15
  7. package/dist/errors.d.ts +1 -1
  8. package/dist/index.d.ts +1 -4
  9. package/dist/index.js +1 -4
  10. package/dist/install/build-add-context-rule.d.ts +3 -19
  11. package/dist/install/build-add-context-rule.js +3 -98
  12. package/dist/install/build-install-policy.d.ts +4 -53
  13. package/dist/install/build-install-policy.js +44 -123
  14. package/dist/install/index.d.ts +0 -2
  15. package/dist/install/index.js +0 -7
  16. package/dist/ir/index.d.ts +1 -1
  17. package/dist/ir/types.d.ts +7 -76
  18. package/dist/ir/types.js +0 -2
  19. package/dist/predicate/decode.d.ts +1 -1
  20. package/dist/predicate/decode.js +2 -70
  21. package/dist/predicate/encode.js +45 -229
  22. package/dist/predicate/from-json.js +1 -42
  23. package/dist/record/decode.js +3 -8
  24. package/dist/review-card/builder.d.ts +4 -3
  25. package/dist/review-card/builder.js +18 -162
  26. package/dist/review-card/cross-check.js +2 -105
  27. package/dist/review-card/render-leaf.d.ts +4 -0
  28. package/dist/review-card/render-leaf.js +47 -0
  29. package/dist/run/index.d.ts +36 -139
  30. package/dist/run/index.js +125 -437
  31. package/dist/run/schemas.d.ts +168 -1929
  32. package/dist/run/schemas.js +40 -269
  33. package/dist/seams/types.d.ts +0 -2
  34. package/dist/simulate/deny-cases.d.ts +26 -0
  35. package/dist/simulate/deny-cases.js +282 -0
  36. package/dist/simulate/evaluate.d.ts +18 -0
  37. package/dist/simulate/evaluate.js +271 -0
  38. package/dist/simulate/index.d.ts +4 -0
  39. package/dist/simulate/index.js +8 -0
  40. package/dist/synth/compose-from-recording.d.ts +24 -51
  41. package/dist/synth/compose-from-recording.js +120 -282
  42. package/dist/synth/deny-cases.d.ts +5 -7
  43. package/dist/synth/deny-cases.js +23 -373
  44. package/dist/synth/evaluate.d.ts +0 -21
  45. package/dist/synth/evaluate.js +56 -336
  46. package/dist/synth/index.d.ts +0 -5
  47. package/dist/synth/index.js +0 -5
  48. package/dist/synth/permit-context.d.ts +2 -9
  49. package/dist/synth/permit-context.js +1 -82
  50. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  51. package/dist/synth/synthesize-from-recording.js +41 -356
  52. package/dist/types.d.ts +8 -60
  53. package/dist/types.js +5 -2
  54. package/dist/verify/simulate.d.ts +1 -14
  55. package/dist/verify/simulate.js +2 -88
  56. package/dist/verify/verify.d.ts +1 -7
  57. package/dist/verify/verify.js +0 -8
  58. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  59. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  60. package/dist-cjs/adapters/interpreter/index.d.ts +1 -1
  61. package/dist-cjs/adapters/interpreter/index.js +1 -2
  62. package/dist-cjs/adapters/oz/adapter.js +1 -15
  63. package/dist-cjs/errors.d.ts +1 -1
  64. package/dist-cjs/index.d.ts +1 -4
  65. package/dist-cjs/index.js +1 -4
  66. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  67. package/dist-cjs/install/build-add-context-rule.js +1 -97
  68. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  69. package/dist-cjs/install/build-install-policy.js +44 -122
  70. package/dist-cjs/install/index.d.ts +0 -2
  71. package/dist-cjs/install/index.js +2 -23
  72. package/dist-cjs/ir/index.d.ts +1 -1
  73. package/dist-cjs/ir/types.d.ts +7 -76
  74. package/dist-cjs/ir/types.js +0 -2
  75. package/dist-cjs/predicate/decode.d.ts +1 -1
  76. package/dist-cjs/predicate/decode.js +2 -70
  77. package/dist-cjs/predicate/encode.js +45 -229
  78. package/dist-cjs/predicate/from-json.js +1 -42
  79. package/dist-cjs/record/decode.js +3 -8
  80. package/dist-cjs/review-card/builder.d.ts +4 -3
  81. package/dist-cjs/review-card/builder.js +23 -167
  82. package/dist-cjs/review-card/cross-check.js +7 -110
  83. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  84. package/dist-cjs/review-card/render-leaf.js +52 -0
  85. package/dist-cjs/run/index.d.ts +36 -139
  86. package/dist-cjs/run/index.js +125 -444
  87. package/dist-cjs/run/schemas.d.ts +168 -1929
  88. package/dist-cjs/run/schemas.js +41 -270
  89. package/dist-cjs/seams/types.d.ts +0 -2
  90. package/dist-cjs/simulate/deny-cases.d.ts +26 -0
  91. package/dist-cjs/simulate/deny-cases.js +286 -0
  92. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  93. package/dist-cjs/simulate/evaluate.js +274 -0
  94. package/dist-cjs/simulate/index.d.ts +4 -0
  95. package/dist-cjs/simulate/index.js +13 -0
  96. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  97. package/dist-cjs/synth/compose-from-recording.js +120 -282
  98. package/dist-cjs/synth/deny-cases.d.ts +5 -7
  99. package/dist-cjs/synth/deny-cases.js +23 -374
  100. package/dist-cjs/synth/evaluate.d.ts +0 -21
  101. package/dist-cjs/synth/evaluate.js +57 -337
  102. package/dist-cjs/synth/index.d.ts +0 -5
  103. package/dist-cjs/synth/index.js +1 -11
  104. package/dist-cjs/synth/permit-context.d.ts +2 -9
  105. package/dist-cjs/synth/permit-context.js +1 -82
  106. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  107. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  108. package/dist-cjs/types.d.ts +8 -60
  109. package/dist-cjs/types.js +6 -3
  110. package/dist-cjs/verify/simulate.d.ts +1 -14
  111. package/dist-cjs/verify/simulate.js +2 -88
  112. package/dist-cjs/verify/verify.d.ts +1 -7
  113. package/dist-cjs/verify/verify.js +0 -8
  114. package/package.json +4 -4
  115. package/src/adapters/interpreter/adapter.ts +76 -572
  116. package/src/errors.ts +0 -19
  117. package/src/index.ts +1 -4
  118. package/src/install/build-add-context-rule.ts +5 -139
  119. package/src/install/build-install-policy.ts +93 -214
  120. package/src/install/index.ts +0 -34
  121. package/src/predicate/decode.ts +2 -70
  122. package/src/predicate/encode.ts +49 -261
  123. package/src/predicate/from-json.ts +1 -43
  124. package/src/record/decode.ts +3 -8
  125. package/src/review-card/builder.ts +19 -168
  126. package/src/review-card/cross-check.ts +3 -105
  127. package/src/review-card/render-leaf.ts +48 -0
  128. package/src/run/index.ts +144 -572
  129. package/src/run/schemas.ts +42 -291
  130. package/src/simulate/deny-cases.ts +334 -0
  131. package/src/simulate/evaluate.ts +284 -0
  132. package/src/simulate/index.ts +11 -0
  133. package/src/synth/compose-from-recording.ts +148 -347
  134. package/src/synth/index.ts +0 -13
  135. package/src/synth/synthesize-from-recording.ts +43 -456
  136. package/src/types.ts +13 -49
  137. package/dist/install/authority-overlap.d.ts +0 -134
  138. package/dist/install/authority-overlap.js +0 -0
  139. package/dist/install/build-install-predicate.d.ts +0 -96
  140. package/dist/install/build-install-predicate.js +0 -444
  141. package/dist/install/build-merge-policy.d.ts +0 -70
  142. package/dist/install/build-merge-policy.js +0 -130
  143. package/dist/install/plan-merge-policy.d.ts +0 -49
  144. package/dist/install/plan-merge-policy.js +0 -86
  145. package/dist/install/read-account-rules.d.ts +0 -100
  146. package/dist/install/read-account-rules.js +0 -283
  147. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  148. package/dist-cjs/install/authority-overlap.js +0 -0
  149. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  150. package/dist-cjs/install/build-install-predicate.js +0 -479
  151. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  152. package/dist-cjs/install/build-merge-policy.js +0 -134
  153. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  154. package/dist-cjs/install/plan-merge-policy.js +0 -90
  155. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  156. package/dist-cjs/install/read-account-rules.js +0 -296
  157. package/src/adapters/interpreter/index.ts +0 -8
  158. package/src/adapters/oz/adapter.ts +0 -376
  159. package/src/adapters/oz/index.ts +0 -9
  160. package/src/codegen/compile-gate.ts +0 -167
  161. package/src/codegen/index.ts +0 -17
  162. package/src/codegen/template.ts +0 -165
  163. package/src/install/authority-overlap.ts +0 -0
  164. package/src/install/build-merge-policy.ts +0 -219
  165. package/src/install/plan-merge-policy.ts +0 -133
  166. package/src/install/read-account-rules.ts +0 -376
  167. package/src/ir/index.ts +0 -13
  168. package/src/ir/types.ts +0 -132
  169. package/src/mandate/index.ts +0 -4
  170. package/src/mandate/to-ir.ts +0 -71
  171. package/src/mandate/types.ts +0 -21
  172. package/src/seams/index.ts +0 -11
  173. package/src/seams/types.ts +0 -81
  174. package/src/synth/deny-cases.ts +0 -663
  175. package/src/synth/evaluate.ts +0 -613
  176. package/src/synth/harness.ts +0 -68
  177. package/src/synth/minimize.ts +0 -48
  178. package/src/synth/permit-context.ts +0 -136
  179. package/src/synth/predicate-literals.ts +0 -27
  180. package/src/synth/synthesize-from-mandate.ts +0 -82
  181. package/src/verify/envelope.ts +0 -28
  182. package/src/verify/index.ts +0 -5
  183. package/src/verify/simulate.ts +0 -311
  184. package/src/verify/verify.ts +0 -243
@@ -1,134 +0,0 @@
1
- "use strict";
2
- //! Transactions for the merge remedy.
3
- //!
4
- //! `plan-merge-policy.ts` decides WHAT should happen; this builds the XDR for
5
- //! the step the caller asked for. Two calls, in order, because OZ refuses to
6
- //! attach a policy that is already on the rule:
7
- //!
8
- //! step 1 `detach` -> `account.remove_policy(rule_id, policy_id)`
9
- //! step 2 `reinstall` -> `account.add_policy(rule_id, interpreter, param)`
10
- //!
11
- //! The two cannot be emitted together. Simulating step 2 while the old
12
- //! attachment is still there hits `DuplicatePolicy`, so the second transaction
13
- //! is only buildable once the first has confirmed.
14
- //!
15
- //! Both calls route through the smart account and are authorised the same way
16
- //! as `revoke_policy`: against the deploy-time admin rule, with the recorded
17
- //! `rootInvocation` binding the auth payload to this exact rule and policy.
18
- //! Detaching runs our `uninstall`, which is master-gated, so the signer has to
19
- //! be a master of the rule either way.
20
- Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.ADMIN_CONTEXT_RULE_ID = void 0;
22
- exports.buildMergePolicyXdr = buildMergePolicyXdr;
23
- const stellar_sdk_1 = require("@stellar/stellar-sdk");
24
- const build_add_context_rule_ts_1 = require("./build-add-context-rule.js");
25
- const oz_auth_ts_1 = require("./oz-auth.js");
26
- /** Matches the window the install and revoke builders use. */
27
- const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 100;
28
- /**
29
- * The context rule the merge authorises AGAINST, which is not the rule being
30
- * merged.
31
- *
32
- * Both calls mutate the smart account itself, so they need the account's own
33
- * authorisation, and this builder asks rule 0 for it - the same assumption the
34
- * install and revoke builders make. OpenZeppelin does NOT enforce any
35
- * admin semantic for rule 0: it is simply the first rule the account's
36
- * constructor created, and OZ's reference account creates it as `Default`
37
- * covering every context.
38
- *
39
- * The assumption is therefore load-bearing and unverified at build time. If
40
- * rule 0 does not exist, does not cover `CallContract(<smart account>)`, or
41
- * does not list the source account as a signer, the transaction is built and
42
- * then fails when submitted, and the operator pays the fee for a transaction
43
- * that was never signable. Changing it is a wire-visible change: the id is
44
- * hashed into the auth digest.
45
- */
46
- exports.ADMIN_CONTEXT_RULE_ID = 0;
47
- function hostFunctionFor(args) {
48
- if (args.step === 'detach') {
49
- return stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
50
- contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
51
- functionName: 'remove_policy',
52
- args: [stellar_sdk_1.xdr.ScVal.scvU32(args.ruleId), stellar_sdk_1.xdr.ScVal.scvU32(args.policyId)],
53
- }));
54
- }
55
- if (!args.encodedPredicate || !args.predicateHash) {
56
- throw new Error('merge_policy: reinstall needs the merged predicate and its hash');
57
- }
58
- return stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
59
- contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
60
- functionName: 'add_policy',
61
- args: [
62
- stellar_sdk_1.xdr.ScVal.scvU32(args.ruleId),
63
- new stellar_sdk_1.Address(args.interpreterAddress).toScVal(),
64
- // Same encoder as a fresh install: the field order is ABI-significant
65
- // and it re-hashes the predicate to confirm the supplied hash.
66
- (0, build_add_context_rule_ts_1.encodePolicyInstallParams)({
67
- encodedPredicate: args.encodedPredicate,
68
- predicateHash: args.predicateHash,
69
- installNonce: args.installNonce ?? 1,
70
- grammarVersion: build_add_context_rule_ts_1.DEFAULT_GRAMMAR_VERSION,
71
- ...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
72
- }),
73
- ],
74
- }));
75
- }
76
- /**
77
- * Build the unsigned transaction for one step of the merge.
78
- *
79
- * The auth dance mirrors `buildRevokePolicyXdr`: simulate once to record the
80
- * account's auth entry, rebuild with the payload bound to that recorded
81
- * `rootInvocation`, then assemble. Binding to the recorded invocation rather
82
- * than to the input arguments is what makes the signature commit to the exact
83
- * rule and policy being changed.
84
- */
85
- async function buildMergePolicyXdr(args) {
86
- const fn = args.step === 'detach' ? 'remove_policy' : 'add_policy';
87
- const source = await args.rpc.getAccount(args.sourceAccount);
88
- const hostFunction = hostFunctionFor(args);
89
- const makeOperation = (auth = []) => stellar_sdk_1.Operation.invokeHostFunction({ func: hostFunction, auth });
90
- const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
91
- const buildTx = (op) => new stellar_sdk_1.TransactionBuilder(new stellar_sdk_1.Account(args.sourceAccount, source.sequenceNumber()), {
92
- fee: baseFee,
93
- networkPassphrase: args.networkPassphrase,
94
- })
95
- .addOperation(op)
96
- .setTimeout(0)
97
- .build();
98
- const recorded = await args.rpc.simulateTransaction(buildTx(makeOperation()));
99
- if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
100
- // Short and stable, like the other builders: the SDK's full error carries
101
- // host and URL detail that has no business in a user-facing message.
102
- throw new Error(`merge_policy: ${fn} simulateTransaction failed`);
103
- }
104
- const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
105
- stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
106
- args.smartAccount);
107
- if (!original) {
108
- throw new Error(`merge_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
109
- }
110
- const validUntilLedger = (await args.rpc.getLatestLedger()).sequence +
111
- (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS);
112
- const contextRuleIds = [exports.ADMIN_CONTEXT_RULE_ID];
113
- const digest = (0, oz_auth_ts_1.authDigest)((0, oz_auth_ts_1.signaturePayload)(args.networkPassphrase, original.credentials().address().nonce(), validUntilLedger, original.rootInvocation()), contextRuleIds);
114
- const authEntries = [
115
- (0, oz_auth_ts_1.accountEntry)(original, validUntilLedger, (0, oz_auth_ts_1.authPayload)([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))),
116
- ...contextRuleIds.map(() => (0, oz_auth_ts_1.delegatedSignerEntry)(args.smartAccount, digest)),
117
- ];
118
- const txWithAuth = buildTx(makeOperation(authEntries));
119
- const enforcing = await args.rpc.simulateTransaction(txWithAuth);
120
- if (stellar_sdk_1.rpc.Api.isSimulationError(enforcing)) {
121
- throw new Error(`merge_policy: ${fn} auth simulateTransaction failed`);
122
- }
123
- const finalTx = stellar_sdk_1.rpc.assembleTransaction(txWithAuth, enforcing).build();
124
- return {
125
- unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
126
- smartAccount: args.smartAccount,
127
- sourceAccount: args.sourceAccount,
128
- step: args.step,
129
- call: { contract: args.smartAccount, fn, ruleId: args.ruleId },
130
- authNonce: original.credentials().address().nonce().toString(),
131
- authValidUntilLedger: validUntilLedger,
132
- rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
133
- };
134
- }
@@ -1,49 +0,0 @@
1
- import type { PredicateNode } from '../types.ts';
2
- import type { ObservedRule } from './authority-overlap.ts';
3
- export type MergeStep = 'detach' | 'reinstall';
4
- export interface MergePlanRefused {
5
- ok: false;
6
- /** Why the merge cannot proceed, in terms the caller can act on. */
7
- reason: string;
8
- }
9
- export interface MergePlanAccepted {
10
- ok: true;
11
- /** The conjunction to install in step 2. */
12
- predicate: PredicateNode;
13
- /** OZ registry id of the interpreter policy on this rule, for
14
- * `remove_policy`. */
15
- policyId: number;
16
- /** Oracle bounds to re-install with the merged predicate. Carried from the
17
- * document being replaced: they are tighten-only overrides against the wasm
18
- * defaults, so omitting them would quietly widen the policy while the
19
- * operator believed they were tightening it. */
20
- oracleParams?: {
21
- maxStalenessSeconds?: number;
22
- maxDeviationBps?: number;
23
- maxCrossFeedDeviationBps?: number;
24
- };
25
- /** Consequences the caller must see BEFORE signing step 1, because step 1 is
26
- * the destructive one. */
27
- warnings: string[];
28
- /** What the caller should do after the requested step confirms. */
29
- followUp: string;
30
- }
31
- export type MergePlan = MergePlanRefused | MergePlanAccepted;
32
- /** The interpreter's registry id on a rule, or null when it is not attached
33
- * or the ids were not readable. */
34
- export declare function interpreterPolicyId(rule: ObservedRule, interpreterAddress: string): number | null;
35
- /**
36
- * Decide whether the merge can proceed, and say what it will cost.
37
- *
38
- * Refuses rather than guesses whenever the account is not in the shape the
39
- * remedy assumes: the rule must be policed by our interpreter, its predicate
40
- * must have been readable, and the ids needed to detach it must be present. A
41
- * merge built on a predicate we could not read would silently replace a rule
42
- * with something narrower or wider than its author wrote.
43
- */
44
- export declare function planMergePolicy(args: {
45
- rule: ObservedRule;
46
- interpreterAddress: string;
47
- incoming: PredicateNode;
48
- step: MergeStep;
49
- }): MergePlan;
@@ -1,90 +0,0 @@
1
- "use strict";
2
- //! Planning the merge remedy for a cross-rule authority overlap.
3
- //!
4
- //! When two rules our interpreter polices can serve the same calls, the
5
- //! tightening remedy is to replace one rule's predicate with the conjunction
6
- //! of both (see `authority-overlap.ts`). Carrying that out against an OZ smart
7
- //! account is not one call, and the reasons are worth stating because they
8
- //! shape the whole tool:
9
- //!
10
- //! 1. A Soroban transaction carries exactly ONE operation - "smart contract
11
- //! transactions can only have one operation per transaction" - so the
12
- //! detach and the re-attach cannot be bundled even though the host would
13
- //! run them in order happily. And `add_policy` panics `DuplicatePolicy`
14
- //! while the policy is still attached (`smart_account/storage.rs`
15
- //! `add_policy`), so the second transaction cannot even be simulated
16
- //! until the first has confirmed.
17
- //! 2. `remove_policy` calls `try_uninstall` and DISCARDS the result
18
- //! (`smart_account/storage.rs`: `let _ = ...try_uninstall(...)`), so the
19
- //! policy is detached whether or not our `uninstall` succeeded. When it
20
- //! succeeded the document, nonce, signer hash, master set and counters
21
- //! are gone and the re-install is a fresh install at nonce 1. When it
22
- //! panicked - our `uninstall` panics `MissingState` if the master set has
23
- //! been archived - the nonce SURVIVES, and re-installing at 1 would be
24
- //! refused on chain as a replay, leaving the rule stuck unpoliced. The
25
- //! nonce is therefore READ at reinstall time rather than assumed.
26
- //! 3. Because of (2), any rate-limit or spend window on that rule is reset
27
- //! by the merge. A signer who had consumed most of a window gets a clean
28
- //! one. That is a real cost of tightening this way and the caller has to
29
- //! be told, not discover it.
30
- //! 4. So the caller performs step 1, waits for it to confirm, then asks for
31
- //! step 2.
32
- //!
33
- //! This module is pure. It decides what should happen and why; the XDR is
34
- //! built by `build-merge-policy.ts`.
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.interpreterPolicyId = interpreterPolicyId;
37
- exports.planMergePolicy = planMergePolicy;
38
- const authority_overlap_ts_1 = require("./authority-overlap.js");
39
- /** The interpreter's registry id on a rule, or null when it is not attached
40
- * or the ids were not readable. */
41
- function interpreterPolicyId(rule, interpreterAddress) {
42
- const index = rule.policyAddresses.indexOf(interpreterAddress);
43
- if (index < 0)
44
- return null;
45
- const id = rule.policyIds?.[index];
46
- return typeof id === 'number' ? id : null;
47
- }
48
- /**
49
- * Decide whether the merge can proceed, and say what it will cost.
50
- *
51
- * Refuses rather than guesses whenever the account is not in the shape the
52
- * remedy assumes: the rule must be policed by our interpreter, its predicate
53
- * must have been readable, and the ids needed to detach it must be present. A
54
- * merge built on a predicate we could not read would silently replace a rule
55
- * with something narrower or wider than its author wrote.
56
- */
57
- function planMergePolicy(args) {
58
- const policyId = interpreterPolicyId(args.rule, args.interpreterAddress);
59
- if (policyId === null) {
60
- return {
61
- ok: false,
62
- reason: `rule ${args.rule.id} is not policed by the interpreter at ${args.interpreterAddress}, or its policy ids could not be read, so there is nothing to merge into and no id to detach. The merge hard-pins to that interpreter and has no opt-out: the auth digest it builds binds to the audited deployment. A rule installed against a different interpreter has to be replaced rather than merged.`,
63
- };
64
- }
65
- const existing = args.rule.predicate;
66
- if (!existing) {
67
- return {
68
- ok: false,
69
- reason: `the predicate installed on rule ${args.rule.id} could not be read, so it cannot be conjoined; merging against an unknown predicate would replace the rule with something other than what its author wrote`,
70
- };
71
- }
72
- const merged = (0, authority_overlap_ts_1.mergeIntoAnd)(existing, args.incoming);
73
- if (!merged.ok || !merged.predicate) {
74
- return { ok: false, reason: merged.reason ?? 'the two predicates cannot be conjoined' };
75
- }
76
- const warnings = [
77
- `detaching the policy uninstalls it, which removes every counter on rule ${args.rule.id}: any rate limit or spend window there restarts from zero after the merge`,
78
- 'the rule is unpoliced between the two transactions, so a signer of it is unconstrained by this policy until step 2 confirms',
79
- ];
80
- return {
81
- ok: true,
82
- predicate: merged.predicate,
83
- policyId,
84
- ...(args.rule.oracleBounds ? { oracleParams: args.rule.oracleBounds } : {}),
85
- warnings,
86
- followUp: args.step === 'detach'
87
- ? "sign and submit this transaction, wait for it to confirm, then call again with step: 'reinstall' to install the merged predicate"
88
- : 'sign and submit this transaction; the merged predicate is then the only policy governing this rule',
89
- };
90
- }
@@ -1,100 +0,0 @@
1
- import { rpc, xdr } from '@stellar/stellar-sdk';
2
- import type { SignerDraft } from '../types.ts';
3
- import type { ContextType, ObservedRule } from './authority-overlap.ts';
4
- /** `storage.rs:295` - the third element of the persistent doc key tuple. */
5
- export declare const K_DOC = 1;
6
- /** Persistent-storage key for a rule's stored document:
7
- * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
8
- export declare function docKeyScVal(smartAccount: string, ruleId: number): xdr.ScVal;
9
- /** Ledger key for the interpreter's persistent entry holding that document. */
10
- export declare function docLedgerKey(interpreter: string, smartAccount: string, ruleId: number): xdr.LedgerKey;
11
- /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
12
- * is the widest reading and therefore the safe one: it makes the rule look
13
- * like it could serve any call, so overlap is over-reported, never missed. */
14
- export declare function decodeContextType(v: xdr.ScVal | undefined): ContextType;
15
- /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
16
- export declare function decodeSigner(v: xdr.ScVal): SignerDraft | undefined;
17
- /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
18
- * `predicate` is filled in separately from the ledger entry. */
19
- export declare function decodeContextRule(v: xdr.ScVal): ObservedRule | undefined;
20
- /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
21
- export declare const K_NONCE = 2;
22
- /** Ledger key for a rule's stored install nonce. Read directly for the same
23
- * reason as the document: the interpreter publishes no getter. */
24
- export declare function nonceLedgerKey(interpreter: string, smartAccount: string, ruleId: number): xdr.LedgerKey;
25
- /** Per-policy oracle bounds carried on a `StoredDoc`.
26
- *
27
- * These must survive a merge. They are tighten-only overrides against the
28
- * wasm defaults, so dropping them does not fail loudly: the rule keeps
29
- * working and silently tolerates staler prices and wider deviation than its
30
- * author chose. */
31
- export interface StoredOracleBounds {
32
- maxStalenessSeconds?: number;
33
- maxDeviationBps?: number;
34
- maxCrossFeedDeviationBps?: number;
35
- }
36
- export declare function decodeStoredOracleBounds(v: xdr.ScVal): StoredOracleBounds;
37
- /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
38
- export declare function decodeStoredPredicateBytes(v: xdr.ScVal): Buffer | undefined;
39
- /** The three reads the scan needs. Kept as an interface so the collection
40
- * below is testable without a network, matching the `InstallRpcClient`
41
- * pattern in `build-install-policy.ts`. */
42
- export interface AccountRuleReader {
43
- /** OZ `get_context_rules_count()`. */
44
- getContextRuleCount(smartAccount: string): Promise<number>;
45
- /** OZ `get_context_rule(id)`. Undefined when the id is absent. */
46
- getContextRule(smartAccount: string, ruleId: number): Promise<xdr.ScVal | undefined>;
47
- /** The interpreter's persistent `StoredDoc` entry, read as a ledger entry.
48
- * Undefined when no document is stored for that rule. */
49
- getStoredDoc(interpreter: string, smartAccount: string, ruleId: number): Promise<xdr.ScVal | undefined>;
50
- }
51
- /** How far the id scan will probe before giving up. OZ imposes no per-account
52
- * rule cap, so there is no exact bound to derive; this one is far above any
53
- * realistic account and keeps a malformed `Count` from spinning forever. */
54
- export declare const MAX_RULE_ID_SCAN = 512;
55
- export interface CollectedRules {
56
- rules: ObservedRule[];
57
- /** Rule ids whose stored predicate could not be read even though the
58
- * interpreter is attached. Such a rule is reported without a predicate,
59
- * which classifies it as opaque rather than as safely narrow. */
60
- unreadablePredicateRuleIds: number[];
61
- /** True when the scan stopped before accounting for every live rule. The
62
- * result is then a SUBSET of the account's rules, so an empty overlap list
63
- * proves nothing and the caller must not present it as safety. */
64
- incomplete: boolean;
65
- }
66
- /**
67
- * Every context rule on the account, with predicates filled in for the rules
68
- * our interpreter polices.
69
- *
70
- * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
71
- * decrements `Count` on removal without ever reusing an id
72
- * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
73
- * `remove_context_rule` only lowers `Count`), so after any removal
74
- * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
75
- * silently skip live rules at higher ids, and a skipped rule is a missed
76
- * overlap - the one error that reports safety which does not exist. Instead
77
- * the scan walks ids upward until it has accounted for `Count` live rules.
78
- *
79
- * A rule whose predicate cannot be read is deliberately left without one. That
80
- * demotes it to the `foreign` class, so the scan reports it as opaque instead
81
- * of assuming it is narrow.
82
- */
83
- export declare function collectObservedRules(args: {
84
- reader: AccountRuleReader;
85
- smartAccount: string;
86
- interpreterAddress: string;
87
- maxRuleIdScan?: number;
88
- }): Promise<CollectedRules>;
89
- /**
90
- * An `AccountRuleReader` over a live RPC server.
91
- *
92
- * The two OZ getters are read-only simulations, built the same way as
93
- * `getContractVersion` in `build-install-policy.ts`: the source account is
94
- * constructed locally because a simulation never checks its sequence number,
95
- * and asking the network for a random key would 404.
96
- *
97
- * The stored document is fetched as a ledger entry rather than a contract
98
- * call, because the interpreter publishes no getter for it.
99
- */
100
- export declare function accountRuleReaderFromServer(server: rpc.Server, networkPassphrase: string): AccountRuleReader;
@@ -1,296 +0,0 @@
1
- "use strict";
2
- //! Reading an OpenZeppelin smart account's context rules back off chain.
3
- //!
4
- //! `authority-overlap.ts` needs to know what a signer can already do before a
5
- //! new policy is installed. That means every rule on the account: its context
6
- //! type, its signers, its attached policies, and - for rules our interpreter
7
- //! polices - the predicate itself.
8
- //!
9
- //! The predicate is NOT reachable through a contract call. The interpreter
10
- //! exposes no getter for `StoredDoc` (`lib.rs` publishes only `grammar_version`,
11
- //! `install`, `enforce`, the pause pair, `uninstall` and
12
- //! `rotate_master_signer_set`), so it is read as a ledger entry instead. That
13
- //! keeps this a pure client-side capability: adding a getter would change a
14
- //! deployed contract's ABI and force a redeploy plus re-audit to obtain data
15
- //! the ledger already exposes.
16
- //!
17
- //! The decoders here are pure so they can be tested without a network; the
18
- //! caller supplies raw `ScVal`s.
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.MAX_RULE_ID_SCAN = exports.K_NONCE = exports.K_DOC = void 0;
21
- exports.docKeyScVal = docKeyScVal;
22
- exports.docLedgerKey = docLedgerKey;
23
- exports.decodeContextType = decodeContextType;
24
- exports.decodeSigner = decodeSigner;
25
- exports.decodeContextRule = decodeContextRule;
26
- exports.nonceLedgerKey = nonceLedgerKey;
27
- exports.decodeStoredOracleBounds = decodeStoredOracleBounds;
28
- exports.decodeStoredPredicateBytes = decodeStoredPredicateBytes;
29
- exports.collectObservedRules = collectObservedRules;
30
- exports.accountRuleReaderFromServer = accountRuleReaderFromServer;
31
- const stellar_sdk_1 = require("@stellar/stellar-sdk");
32
- const decode_ts_1 = require("../predicate/decode.js");
33
- /** `storage.rs:295` - the third element of the persistent doc key tuple. */
34
- exports.K_DOC = 1;
35
- /** Persistent-storage key for a rule's stored document:
36
- * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
37
- function docKeyScVal(smartAccount, ruleId) {
38
- return stellar_sdk_1.xdr.ScVal.scvVec([
39
- new stellar_sdk_1.Address(smartAccount).toScVal(),
40
- stellar_sdk_1.xdr.ScVal.scvU32(ruleId),
41
- stellar_sdk_1.xdr.ScVal.scvU32(exports.K_DOC),
42
- ]);
43
- }
44
- /** Ledger key for the interpreter's persistent entry holding that document. */
45
- function docLedgerKey(interpreter, smartAccount, ruleId) {
46
- return stellar_sdk_1.xdr.LedgerKey.contractData(new stellar_sdk_1.xdr.LedgerKeyContractData({
47
- contract: new stellar_sdk_1.Address(interpreter).toScAddress(),
48
- key: docKeyScVal(smartAccount, ruleId),
49
- durability: stellar_sdk_1.xdr.ContractDataDurability.persistent(),
50
- }));
51
- }
52
- // ---- ScVal helpers -----
53
- /** Field of a `#[contracttype]` struct, which the host encodes as a map keyed
54
- * by field-name symbol. Returns undefined when the field is absent so a
55
- * caller can distinguish "not there" from "there and empty". */
56
- function mapField(v, name) {
57
- if (v.switch() !== stellar_sdk_1.xdr.ScValType.scvMap())
58
- return undefined;
59
- for (const entry of v.map() ?? []) {
60
- const key = entry.key();
61
- if (key.switch() === stellar_sdk_1.xdr.ScValType.scvSymbol() && key.sym().toString() === name) {
62
- return entry.val();
63
- }
64
- }
65
- return undefined;
66
- }
67
- function u32Of(v) {
68
- return v?.switch() === stellar_sdk_1.xdr.ScValType.scvU32() ? v.u32() : undefined;
69
- }
70
- function addressOf(v) {
71
- if (!v || v.switch() !== stellar_sdk_1.xdr.ScValType.scvAddress())
72
- return undefined;
73
- return stellar_sdk_1.Address.fromScAddress(v.address()).toString();
74
- }
75
- /** An enum variant of a `#[contracttype]` enum: `ScVal::Vec([Symbol, ...args])`. */
76
- function enumVariant(v) {
77
- if (!v || v.switch() !== stellar_sdk_1.xdr.ScValType.scvVec())
78
- return undefined;
79
- const items = v.vec() ?? [];
80
- const head = items[0];
81
- if (!head || head.switch() !== stellar_sdk_1.xdr.ScValType.scvSymbol())
82
- return undefined;
83
- return { tag: head.sym().toString(), args: items.slice(1) };
84
- }
85
- // ---- decoders -----
86
- /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
87
- * is the widest reading and therefore the safe one: it makes the rule look
88
- * like it could serve any call, so overlap is over-reported, never missed. */
89
- function decodeContextType(v) {
90
- const variant = enumVariant(v);
91
- if (!variant)
92
- return { kind: 'default' };
93
- if (variant.tag === 'CallContract') {
94
- const addr = addressOf(variant.args[0]);
95
- return addr ? { kind: 'call_contract', address: addr } : { kind: 'default' };
96
- }
97
- if (variant.tag === 'CreateContract') {
98
- const arg = variant.args[0];
99
- const hash = arg?.switch() === stellar_sdk_1.xdr.ScValType.scvBytes() ? arg.bytes().toString('hex') : '';
100
- return { kind: 'create_contract', wasmHash: hash };
101
- }
102
- return { kind: 'default' };
103
- }
104
- /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
105
- function decodeSigner(v) {
106
- const variant = enumVariant(v);
107
- if (!variant)
108
- return undefined;
109
- if (variant.tag === 'Delegated') {
110
- const addr = addressOf(variant.args[0]);
111
- return addr ? { kind: 'delegated', address: addr } : undefined;
112
- }
113
- if (variant.tag === 'External') {
114
- const verifier = addressOf(variant.args[0]);
115
- const keyArg = variant.args[1];
116
- const keyBytes = keyArg?.switch() === stellar_sdk_1.xdr.ScValType.scvBytes() ? keyArg.bytes().toString('hex') : '';
117
- return verifier ? { kind: 'external', verifier, keyBytes } : undefined;
118
- }
119
- return undefined;
120
- }
121
- /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
122
- * `predicate` is filled in separately from the ledger entry. */
123
- function decodeContextRule(v) {
124
- const id = u32Of(mapField(v, 'id'));
125
- if (id === undefined)
126
- return undefined;
127
- const signersVal = mapField(v, 'signers');
128
- const signers = [];
129
- if (signersVal?.switch() === stellar_sdk_1.xdr.ScValType.scvVec()) {
130
- for (const s of signersVal.vec() ?? []) {
131
- const decoded = decodeSigner(s);
132
- if (decoded)
133
- signers.push(decoded);
134
- }
135
- }
136
- const policiesVal = mapField(v, 'policies');
137
- const policyAddresses = [];
138
- if (policiesVal?.switch() === stellar_sdk_1.xdr.ScValType.scvVec()) {
139
- for (const p of policiesVal.vec() ?? []) {
140
- const addr = addressOf(p);
141
- if (addr)
142
- policyAddresses.push(addr);
143
- }
144
- }
145
- // `policy_ids` is index-aligned with `policies` in OZ's ContextRule. Only
146
- // the ids can be passed to `remove_policy`, so a detach is impossible
147
- // without them; they are read here rather than looked up again later.
148
- const policyIdsVal = mapField(v, 'policy_ids');
149
- const policyIds = [];
150
- if (policyIdsVal?.switch() === stellar_sdk_1.xdr.ScValType.scvVec()) {
151
- for (const pid of policyIdsVal.vec() ?? []) {
152
- const n = u32Of(pid);
153
- if (n !== undefined)
154
- policyIds.push(n);
155
- }
156
- }
157
- return {
158
- id,
159
- contextType: decodeContextType(mapField(v, 'context_type')),
160
- signers,
161
- policyAddresses,
162
- ...(policyIds.length > 0 ? { policyIds } : {}),
163
- };
164
- }
165
- /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
166
- exports.K_NONCE = 2;
167
- /** Ledger key for a rule's stored install nonce. Read directly for the same
168
- * reason as the document: the interpreter publishes no getter. */
169
- function nonceLedgerKey(interpreter, smartAccount, ruleId) {
170
- return stellar_sdk_1.xdr.LedgerKey.contractData(new stellar_sdk_1.xdr.LedgerKeyContractData({
171
- contract: new stellar_sdk_1.Address(interpreter).toScAddress(),
172
- key: stellar_sdk_1.xdr.ScVal.scvVec([
173
- new stellar_sdk_1.Address(smartAccount).toScVal(),
174
- stellar_sdk_1.xdr.ScVal.scvU32(ruleId),
175
- stellar_sdk_1.xdr.ScVal.scvU32(exports.K_NONCE),
176
- ]),
177
- durability: stellar_sdk_1.xdr.ContractDataDurability.persistent(),
178
- }));
179
- }
180
- function decodeStoredOracleBounds(v) {
181
- const read = (name) => u32Of(mapField(v, name));
182
- const staleness = read('oracle_max_staleness_seconds');
183
- const deviation = read('oracle_max_deviation_bps');
184
- const xfeed = read('oracle_max_xfeed_dev_bps');
185
- return {
186
- ...(staleness !== undefined ? { maxStalenessSeconds: staleness } : {}),
187
- ...(deviation !== undefined ? { maxDeviationBps: deviation } : {}),
188
- ...(xfeed !== undefined ? { maxCrossFeedDeviationBps: xfeed } : {}),
189
- };
190
- }
191
- /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
192
- function decodeStoredPredicateBytes(v) {
193
- const field = mapField(v, 'predicate_bytes');
194
- if (!field || field.switch() !== stellar_sdk_1.xdr.ScValType.scvBytes())
195
- return undefined;
196
- return field.bytes();
197
- }
198
- /** How far the id scan will probe before giving up. OZ imposes no per-account
199
- * rule cap, so there is no exact bound to derive; this one is far above any
200
- * realistic account and keeps a malformed `Count` from spinning forever. */
201
- exports.MAX_RULE_ID_SCAN = 512;
202
- /**
203
- * Every context rule on the account, with predicates filled in for the rules
204
- * our interpreter polices.
205
- *
206
- * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
207
- * decrements `Count` on removal without ever reusing an id
208
- * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
209
- * `remove_context_rule` only lowers `Count`), so after any removal
210
- * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
211
- * silently skip live rules at higher ids, and a skipped rule is a missed
212
- * overlap - the one error that reports safety which does not exist. Instead
213
- * the scan walks ids upward until it has accounted for `Count` live rules.
214
- *
215
- * A rule whose predicate cannot be read is deliberately left without one. That
216
- * demotes it to the `foreign` class, so the scan reports it as opaque instead
217
- * of assuming it is narrow.
218
- */
219
- async function collectObservedRules(args) {
220
- const count = await args.reader.getContextRuleCount(args.smartAccount);
221
- const limit = args.maxRuleIdScan ?? exports.MAX_RULE_ID_SCAN;
222
- const rules = [];
223
- const unreadablePredicateRuleIds = [];
224
- let id = 0;
225
- while (rules.length < count && id < limit) {
226
- const raw = await args.reader.getContextRule(args.smartAccount, id);
227
- id++;
228
- if (!raw)
229
- continue;
230
- const rule = decodeContextRule(raw);
231
- if (!rule)
232
- continue;
233
- if (rule.policyAddresses.includes(args.interpreterAddress)) {
234
- const doc = await args.reader.getStoredDoc(args.interpreterAddress, args.smartAccount, rule.id);
235
- const bytes = doc ? decodeStoredPredicateBytes(doc) : undefined;
236
- if (bytes) {
237
- try {
238
- rule.predicate = (0, decode_ts_1.decodePredicate)(bytes);
239
- // Carried so a merge can re-install the SAME bounds. They are
240
- // tighten-only overrides, so losing them widens the policy quietly.
241
- if (doc)
242
- rule.oracleBounds = decodeStoredOracleBounds(doc);
243
- }
244
- catch {
245
- unreadablePredicateRuleIds.push(rule.id);
246
- }
247
- }
248
- else {
249
- unreadablePredicateRuleIds.push(rule.id);
250
- }
251
- }
252
- rules.push(rule);
253
- }
254
- return { rules, unreadablePredicateRuleIds, incomplete: rules.length < count };
255
- }
256
- /**
257
- * An `AccountRuleReader` over a live RPC server.
258
- *
259
- * The two OZ getters are read-only simulations, built the same way as
260
- * `getContractVersion` in `build-install-policy.ts`: the source account is
261
- * constructed locally because a simulation never checks its sequence number,
262
- * and asking the network for a random key would 404.
263
- *
264
- * The stored document is fetched as a ledger entry rather than a contract
265
- * call, because the interpreter publishes no getter for it.
266
- */
267
- function accountRuleReaderFromServer(server, networkPassphrase) {
268
- async function simulateCall(contract, method, ...args) {
269
- const account = new stellar_sdk_1.Account(stellar_sdk_1.Keypair.random().publicKey(), '0');
270
- const tx = new stellar_sdk_1.TransactionBuilder(account, { fee: stellar_sdk_1.BASE_FEE, networkPassphrase })
271
- .addOperation(new stellar_sdk_1.Contract(contract).call(method, ...args))
272
- .setTimeout(30)
273
- .build();
274
- const sim = await server.simulateTransaction(tx);
275
- if (stellar_sdk_1.rpc.Api.isSimulationError(sim))
276
- return undefined;
277
- return sim.result?.retval;
278
- }
279
- return {
280
- async getContextRuleCount(smartAccount) {
281
- const val = await simulateCall(smartAccount, 'get_context_rules_count');
282
- return u32Of(val) ?? 0;
283
- },
284
- async getContextRule(smartAccount, ruleId) {
285
- return simulateCall(smartAccount, 'get_context_rule', stellar_sdk_1.xdr.ScVal.scvU32(ruleId));
286
- },
287
- async getStoredDoc(interpreter, smartAccount, ruleId) {
288
- const key = docLedgerKey(interpreter, smartAccount, ruleId);
289
- const res = await server.getLedgerEntries(key);
290
- const entry = res.entries?.[0]?.val;
291
- if (!entry || entry.switch() !== stellar_sdk_1.xdr.LedgerEntryType.contractData())
292
- return undefined;
293
- return entry.contractData().val();
294
- },
295
- };
296
- }