@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,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,86 +0,0 @@
1
- //! Planning the merge remedy for a cross-rule authority overlap.
2
- //!
3
- //! When two rules our interpreter polices can serve the same calls, the
4
- //! tightening remedy is to replace one rule's predicate with the conjunction
5
- //! of both (see `authority-overlap.ts`). Carrying that out against an OZ smart
6
- //! account is not one call, and the reasons are worth stating because they
7
- //! shape the whole tool:
8
- //!
9
- //! 1. A Soroban transaction carries exactly ONE operation - "smart contract
10
- //! transactions can only have one operation per transaction" - so the
11
- //! detach and the re-attach cannot be bundled even though the host would
12
- //! run them in order happily. And `add_policy` panics `DuplicatePolicy`
13
- //! while the policy is still attached (`smart_account/storage.rs`
14
- //! `add_policy`), so the second transaction cannot even be simulated
15
- //! until the first has confirmed.
16
- //! 2. `remove_policy` calls `try_uninstall` and DISCARDS the result
17
- //! (`smart_account/storage.rs`: `let _ = ...try_uninstall(...)`), so the
18
- //! policy is detached whether or not our `uninstall` succeeded. When it
19
- //! succeeded the document, nonce, signer hash, master set and counters
20
- //! are gone and the re-install is a fresh install at nonce 1. When it
21
- //! panicked - our `uninstall` panics `MissingState` if the master set has
22
- //! been archived - the nonce SURVIVES, and re-installing at 1 would be
23
- //! refused on chain as a replay, leaving the rule stuck unpoliced. The
24
- //! nonce is therefore READ at reinstall time rather than assumed.
25
- //! 3. Because of (2), any rate-limit or spend window on that rule is reset
26
- //! by the merge. A signer who had consumed most of a window gets a clean
27
- //! one. That is a real cost of tightening this way and the caller has to
28
- //! be told, not discover it.
29
- //! 4. So the caller performs step 1, waits for it to confirm, then asks for
30
- //! step 2.
31
- //!
32
- //! This module is pure. It decides what should happen and why; the XDR is
33
- //! built by `build-merge-policy.ts`.
34
- import { mergeIntoAnd } from "./authority-overlap.js";
35
- /** The interpreter's registry id on a rule, or null when it is not attached
36
- * or the ids were not readable. */
37
- export function interpreterPolicyId(rule, interpreterAddress) {
38
- const index = rule.policyAddresses.indexOf(interpreterAddress);
39
- if (index < 0)
40
- return null;
41
- const id = rule.policyIds?.[index];
42
- return typeof id === 'number' ? id : null;
43
- }
44
- /**
45
- * Decide whether the merge can proceed, and say what it will cost.
46
- *
47
- * Refuses rather than guesses whenever the account is not in the shape the
48
- * remedy assumes: the rule must be policed by our interpreter, its predicate
49
- * must have been readable, and the ids needed to detach it must be present. A
50
- * merge built on a predicate we could not read would silently replace a rule
51
- * with something narrower or wider than its author wrote.
52
- */
53
- export function planMergePolicy(args) {
54
- const policyId = interpreterPolicyId(args.rule, args.interpreterAddress);
55
- if (policyId === null) {
56
- return {
57
- ok: false,
58
- 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.`,
59
- };
60
- }
61
- const existing = args.rule.predicate;
62
- if (!existing) {
63
- return {
64
- ok: false,
65
- 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`,
66
- };
67
- }
68
- const merged = mergeIntoAnd(existing, args.incoming);
69
- if (!merged.ok || !merged.predicate) {
70
- return { ok: false, reason: merged.reason ?? 'the two predicates cannot be conjoined' };
71
- }
72
- const warnings = [
73
- `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`,
74
- 'the rule is unpoliced between the two transactions, so a signer of it is unconstrained by this policy until step 2 confirms',
75
- ];
76
- return {
77
- ok: true,
78
- predicate: merged.predicate,
79
- policyId,
80
- ...(args.rule.oracleBounds ? { oracleParams: args.rule.oracleBounds } : {}),
81
- warnings,
82
- followUp: args.step === 'detach'
83
- ? "sign and submit this transaction, wait for it to confirm, then call again with step: 'reinstall' to install the merged predicate"
84
- : 'sign and submit this transaction; the merged predicate is then the only policy governing this rule',
85
- };
86
- }
@@ -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,283 +0,0 @@
1
- //! Reading an OpenZeppelin smart account's context rules back off chain.
2
- //!
3
- //! `authority-overlap.ts` needs to know what a signer can already do before a
4
- //! new policy is installed. That means every rule on the account: its context
5
- //! type, its signers, its attached policies, and - for rules our interpreter
6
- //! polices - the predicate itself.
7
- //!
8
- //! The predicate is NOT reachable through a contract call. The interpreter
9
- //! exposes no getter for `StoredDoc` (`lib.rs` publishes only `grammar_version`,
10
- //! `install`, `enforce`, the pause pair, `uninstall` and
11
- //! `rotate_master_signer_set`), so it is read as a ledger entry instead. That
12
- //! keeps this a pure client-side capability: adding a getter would change a
13
- //! deployed contract's ABI and force a redeploy plus re-audit to obtain data
14
- //! the ledger already exposes.
15
- //!
16
- //! The decoders here are pure so they can be tested without a network; the
17
- //! caller supplies raw `ScVal`s.
18
- import { Account, Address, BASE_FEE, Contract, Keypair, rpc, TransactionBuilder, xdr, } from '@stellar/stellar-sdk';
19
- import { decodePredicate } from "../predicate/decode.js";
20
- /** `storage.rs:295` - the third element of the persistent doc key tuple. */
21
- export const K_DOC = 1;
22
- /** Persistent-storage key for a rule's stored document:
23
- * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
24
- export function docKeyScVal(smartAccount, ruleId) {
25
- return xdr.ScVal.scvVec([
26
- new Address(smartAccount).toScVal(),
27
- xdr.ScVal.scvU32(ruleId),
28
- xdr.ScVal.scvU32(K_DOC),
29
- ]);
30
- }
31
- /** Ledger key for the interpreter's persistent entry holding that document. */
32
- export function docLedgerKey(interpreter, smartAccount, ruleId) {
33
- return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
34
- contract: new Address(interpreter).toScAddress(),
35
- key: docKeyScVal(smartAccount, ruleId),
36
- durability: xdr.ContractDataDurability.persistent(),
37
- }));
38
- }
39
- // ---- ScVal helpers -----
40
- /** Field of a `#[contracttype]` struct, which the host encodes as a map keyed
41
- * by field-name symbol. Returns undefined when the field is absent so a
42
- * caller can distinguish "not there" from "there and empty". */
43
- function mapField(v, name) {
44
- if (v.switch() !== xdr.ScValType.scvMap())
45
- return undefined;
46
- for (const entry of v.map() ?? []) {
47
- const key = entry.key();
48
- if (key.switch() === xdr.ScValType.scvSymbol() && key.sym().toString() === name) {
49
- return entry.val();
50
- }
51
- }
52
- return undefined;
53
- }
54
- function u32Of(v) {
55
- return v?.switch() === xdr.ScValType.scvU32() ? v.u32() : undefined;
56
- }
57
- function addressOf(v) {
58
- if (!v || v.switch() !== xdr.ScValType.scvAddress())
59
- return undefined;
60
- return Address.fromScAddress(v.address()).toString();
61
- }
62
- /** An enum variant of a `#[contracttype]` enum: `ScVal::Vec([Symbol, ...args])`. */
63
- function enumVariant(v) {
64
- if (!v || v.switch() !== xdr.ScValType.scvVec())
65
- return undefined;
66
- const items = v.vec() ?? [];
67
- const head = items[0];
68
- if (!head || head.switch() !== xdr.ScValType.scvSymbol())
69
- return undefined;
70
- return { tag: head.sym().toString(), args: items.slice(1) };
71
- }
72
- // ---- decoders -----
73
- /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
74
- * is the widest reading and therefore the safe one: it makes the rule look
75
- * like it could serve any call, so overlap is over-reported, never missed. */
76
- export function decodeContextType(v) {
77
- const variant = enumVariant(v);
78
- if (!variant)
79
- return { kind: 'default' };
80
- if (variant.tag === 'CallContract') {
81
- const addr = addressOf(variant.args[0]);
82
- return addr ? { kind: 'call_contract', address: addr } : { kind: 'default' };
83
- }
84
- if (variant.tag === 'CreateContract') {
85
- const arg = variant.args[0];
86
- const hash = arg?.switch() === xdr.ScValType.scvBytes() ? arg.bytes().toString('hex') : '';
87
- return { kind: 'create_contract', wasmHash: hash };
88
- }
89
- return { kind: 'default' };
90
- }
91
- /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
92
- export function decodeSigner(v) {
93
- const variant = enumVariant(v);
94
- if (!variant)
95
- return undefined;
96
- if (variant.tag === 'Delegated') {
97
- const addr = addressOf(variant.args[0]);
98
- return addr ? { kind: 'delegated', address: addr } : undefined;
99
- }
100
- if (variant.tag === 'External') {
101
- const verifier = addressOf(variant.args[0]);
102
- const keyArg = variant.args[1];
103
- const keyBytes = keyArg?.switch() === xdr.ScValType.scvBytes() ? keyArg.bytes().toString('hex') : '';
104
- return verifier ? { kind: 'external', verifier, keyBytes } : undefined;
105
- }
106
- return undefined;
107
- }
108
- /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
109
- * `predicate` is filled in separately from the ledger entry. */
110
- export function decodeContextRule(v) {
111
- const id = u32Of(mapField(v, 'id'));
112
- if (id === undefined)
113
- return undefined;
114
- const signersVal = mapField(v, 'signers');
115
- const signers = [];
116
- if (signersVal?.switch() === xdr.ScValType.scvVec()) {
117
- for (const s of signersVal.vec() ?? []) {
118
- const decoded = decodeSigner(s);
119
- if (decoded)
120
- signers.push(decoded);
121
- }
122
- }
123
- const policiesVal = mapField(v, 'policies');
124
- const policyAddresses = [];
125
- if (policiesVal?.switch() === xdr.ScValType.scvVec()) {
126
- for (const p of policiesVal.vec() ?? []) {
127
- const addr = addressOf(p);
128
- if (addr)
129
- policyAddresses.push(addr);
130
- }
131
- }
132
- // `policy_ids` is index-aligned with `policies` in OZ's ContextRule. Only
133
- // the ids can be passed to `remove_policy`, so a detach is impossible
134
- // without them; they are read here rather than looked up again later.
135
- const policyIdsVal = mapField(v, 'policy_ids');
136
- const policyIds = [];
137
- if (policyIdsVal?.switch() === xdr.ScValType.scvVec()) {
138
- for (const pid of policyIdsVal.vec() ?? []) {
139
- const n = u32Of(pid);
140
- if (n !== undefined)
141
- policyIds.push(n);
142
- }
143
- }
144
- return {
145
- id,
146
- contextType: decodeContextType(mapField(v, 'context_type')),
147
- signers,
148
- policyAddresses,
149
- ...(policyIds.length > 0 ? { policyIds } : {}),
150
- };
151
- }
152
- /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
153
- export const K_NONCE = 2;
154
- /** Ledger key for a rule's stored install nonce. Read directly for the same
155
- * reason as the document: the interpreter publishes no getter. */
156
- export function nonceLedgerKey(interpreter, smartAccount, ruleId) {
157
- return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
158
- contract: new Address(interpreter).toScAddress(),
159
- key: xdr.ScVal.scvVec([
160
- new Address(smartAccount).toScVal(),
161
- xdr.ScVal.scvU32(ruleId),
162
- xdr.ScVal.scvU32(K_NONCE),
163
- ]),
164
- durability: xdr.ContractDataDurability.persistent(),
165
- }));
166
- }
167
- export function decodeStoredOracleBounds(v) {
168
- const read = (name) => u32Of(mapField(v, name));
169
- const staleness = read('oracle_max_staleness_seconds');
170
- const deviation = read('oracle_max_deviation_bps');
171
- const xfeed = read('oracle_max_xfeed_dev_bps');
172
- return {
173
- ...(staleness !== undefined ? { maxStalenessSeconds: staleness } : {}),
174
- ...(deviation !== undefined ? { maxDeviationBps: deviation } : {}),
175
- ...(xfeed !== undefined ? { maxCrossFeedDeviationBps: xfeed } : {}),
176
- };
177
- }
178
- /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
179
- export function decodeStoredPredicateBytes(v) {
180
- const field = mapField(v, 'predicate_bytes');
181
- if (!field || field.switch() !== xdr.ScValType.scvBytes())
182
- return undefined;
183
- return field.bytes();
184
- }
185
- /** How far the id scan will probe before giving up. OZ imposes no per-account
186
- * rule cap, so there is no exact bound to derive; this one is far above any
187
- * realistic account and keeps a malformed `Count` from spinning forever. */
188
- export const MAX_RULE_ID_SCAN = 512;
189
- /**
190
- * Every context rule on the account, with predicates filled in for the rules
191
- * our interpreter polices.
192
- *
193
- * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
194
- * decrements `Count` on removal without ever reusing an id
195
- * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
196
- * `remove_context_rule` only lowers `Count`), so after any removal
197
- * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
198
- * silently skip live rules at higher ids, and a skipped rule is a missed
199
- * overlap - the one error that reports safety which does not exist. Instead
200
- * the scan walks ids upward until it has accounted for `Count` live rules.
201
- *
202
- * A rule whose predicate cannot be read is deliberately left without one. That
203
- * demotes it to the `foreign` class, so the scan reports it as opaque instead
204
- * of assuming it is narrow.
205
- */
206
- export async function collectObservedRules(args) {
207
- const count = await args.reader.getContextRuleCount(args.smartAccount);
208
- const limit = args.maxRuleIdScan ?? MAX_RULE_ID_SCAN;
209
- const rules = [];
210
- const unreadablePredicateRuleIds = [];
211
- let id = 0;
212
- while (rules.length < count && id < limit) {
213
- const raw = await args.reader.getContextRule(args.smartAccount, id);
214
- id++;
215
- if (!raw)
216
- continue;
217
- const rule = decodeContextRule(raw);
218
- if (!rule)
219
- continue;
220
- if (rule.policyAddresses.includes(args.interpreterAddress)) {
221
- const doc = await args.reader.getStoredDoc(args.interpreterAddress, args.smartAccount, rule.id);
222
- const bytes = doc ? decodeStoredPredicateBytes(doc) : undefined;
223
- if (bytes) {
224
- try {
225
- rule.predicate = decodePredicate(bytes);
226
- // Carried so a merge can re-install the SAME bounds. They are
227
- // tighten-only overrides, so losing them widens the policy quietly.
228
- if (doc)
229
- rule.oracleBounds = decodeStoredOracleBounds(doc);
230
- }
231
- catch {
232
- unreadablePredicateRuleIds.push(rule.id);
233
- }
234
- }
235
- else {
236
- unreadablePredicateRuleIds.push(rule.id);
237
- }
238
- }
239
- rules.push(rule);
240
- }
241
- return { rules, unreadablePredicateRuleIds, incomplete: rules.length < count };
242
- }
243
- /**
244
- * An `AccountRuleReader` over a live RPC server.
245
- *
246
- * The two OZ getters are read-only simulations, built the same way as
247
- * `getContractVersion` in `build-install-policy.ts`: the source account is
248
- * constructed locally because a simulation never checks its sequence number,
249
- * and asking the network for a random key would 404.
250
- *
251
- * The stored document is fetched as a ledger entry rather than a contract
252
- * call, because the interpreter publishes no getter for it.
253
- */
254
- export function accountRuleReaderFromServer(server, networkPassphrase) {
255
- async function simulateCall(contract, method, ...args) {
256
- const account = new Account(Keypair.random().publicKey(), '0');
257
- const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase })
258
- .addOperation(new Contract(contract).call(method, ...args))
259
- .setTimeout(30)
260
- .build();
261
- const sim = await server.simulateTransaction(tx);
262
- if (rpc.Api.isSimulationError(sim))
263
- return undefined;
264
- return sim.result?.retval;
265
- }
266
- return {
267
- async getContextRuleCount(smartAccount) {
268
- const val = await simulateCall(smartAccount, 'get_context_rules_count');
269
- return u32Of(val) ?? 0;
270
- },
271
- async getContextRule(smartAccount, ruleId) {
272
- return simulateCall(smartAccount, 'get_context_rule', xdr.ScVal.scvU32(ruleId));
273
- },
274
- async getStoredDoc(interpreter, smartAccount, ruleId) {
275
- const key = docLedgerKey(interpreter, smartAccount, ruleId);
276
- const res = await server.getLedgerEntries(key);
277
- const entry = res.entries?.[0]?.val;
278
- if (!entry || entry.switch() !== xdr.LedgerEntryType.contractData())
279
- return undefined;
280
- return entry.contractData().val();
281
- },
282
- };
283
- }
@@ -1,134 +0,0 @@
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;