@crediolabs/policy-synth 0.1.18 → 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 (42) hide show
  1. package/README.md +3 -2
  2. package/dist/install/authority-overlap.d.ts +134 -0
  3. package/dist/install/authority-overlap.js +0 -0
  4. package/dist/install/build-add-context-rule.d.ts +8 -0
  5. package/dist/install/build-add-context-rule.js +1 -1
  6. package/dist/install/build-merge-policy.d.ts +70 -0
  7. package/dist/install/build-merge-policy.js +130 -0
  8. package/dist/install/index.d.ts +2 -0
  9. package/dist/install/index.js +7 -0
  10. package/dist/install/plan-merge-policy.d.ts +49 -0
  11. package/dist/install/plan-merge-policy.js +86 -0
  12. package/dist/install/read-account-rules.d.ts +100 -0
  13. package/dist/install/read-account-rules.js +283 -0
  14. package/dist/run/index.d.ts +93 -8
  15. package/dist/run/index.js +282 -11
  16. package/dist/run/schemas.d.ts +290 -11
  17. package/dist/run/schemas.js +77 -11
  18. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  19. package/dist-cjs/install/authority-overlap.js +0 -0
  20. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  21. package/dist-cjs/install/build-add-context-rule.js +1 -0
  22. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  23. package/dist-cjs/install/build-merge-policy.js +134 -0
  24. package/dist-cjs/install/index.d.ts +2 -0
  25. package/dist-cjs/install/index.js +23 -2
  26. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  27. package/dist-cjs/install/plan-merge-policy.js +90 -0
  28. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  29. package/dist-cjs/install/read-account-rules.js +296 -0
  30. package/dist-cjs/run/index.d.ts +93 -8
  31. package/dist-cjs/run/index.js +283 -10
  32. package/dist-cjs/run/schemas.d.ts +290 -11
  33. package/dist-cjs/run/schemas.js +78 -12
  34. package/package.json +1 -1
  35. package/src/install/authority-overlap.ts +0 -0
  36. package/src/install/build-add-context-rule.ts +12 -1
  37. package/src/install/build-merge-policy.ts +219 -0
  38. package/src/install/index.ts +34 -0
  39. package/src/install/plan-merge-policy.ts +133 -0
  40. package/src/install/read-account-rules.ts +376 -0
  41. package/src/run/index.ts +386 -14
  42. package/src/run/schemas.ts +84 -11
@@ -0,0 +1,219 @@
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
+
20
+ import {
21
+ Account,
22
+ Address,
23
+ BASE_FEE,
24
+ Operation,
25
+ rpc,
26
+ TransactionBuilder,
27
+ xdr,
28
+ } from '@stellar/stellar-sdk'
29
+ import { DEFAULT_GRAMMAR_VERSION, encodePolicyInstallParams } from './build-add-context-rule.ts'
30
+ import type { InstallRpcClient } from './build-install-policy.ts'
31
+ import {
32
+ accountEntry,
33
+ authDigest,
34
+ authPayload,
35
+ delegatedSignerEntry,
36
+ signaturePayload,
37
+ } from './oz-auth.ts'
38
+ import type { MergeStep } from './plan-merge-policy.ts'
39
+
40
+ /** Matches the window the install and revoke builders use. */
41
+ const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 100
42
+
43
+ /**
44
+ * The context rule the merge authorises AGAINST, which is not the rule being
45
+ * merged.
46
+ *
47
+ * Both calls mutate the smart account itself, so they need the account's own
48
+ * authorisation, and this builder asks rule 0 for it - the same assumption the
49
+ * install and revoke builders make. OpenZeppelin does NOT enforce any
50
+ * admin semantic for rule 0: it is simply the first rule the account's
51
+ * constructor created, and OZ's reference account creates it as `Default`
52
+ * covering every context.
53
+ *
54
+ * The assumption is therefore load-bearing and unverified at build time. If
55
+ * rule 0 does not exist, does not cover `CallContract(<smart account>)`, or
56
+ * does not list the source account as a signer, the transaction is built and
57
+ * then fails when submitted, and the operator pays the fee for a transaction
58
+ * that was never signable. Changing it is a wire-visible change: the id is
59
+ * hashed into the auth digest.
60
+ */
61
+ export const ADMIN_CONTEXT_RULE_ID = 0
62
+
63
+ export interface BuildMergePolicyArgs {
64
+ smartAccount: string
65
+ sourceAccount: string
66
+ networkPassphrase: string
67
+ ruleId: number
68
+ /** OZ registry id of the interpreter policy on this rule, from the plan. */
69
+ policyId: number
70
+ interpreterAddress: string
71
+ step: MergeStep
72
+ /** Only needed for `reinstall`: the merged predicate, already encoded. */
73
+ encodedPredicate?: string
74
+ predicateHash?: string
75
+ /** Nonce for the reinstall. Read from chain rather than assumed: a detach
76
+ * whose uninstall panicked leaves the old nonce in place. */
77
+ installNonce?: number
78
+ /** Oracle bounds to carry over from the document being replaced. */
79
+ oracleParams?: {
80
+ maxStalenessSeconds?: number
81
+ maxDeviationBps?: number
82
+ maxCrossFeedDeviationBps?: number
83
+ }
84
+ rpc: InstallRpcClient
85
+ baseFee?: number
86
+ authValidUntilLedgers?: number
87
+ }
88
+
89
+ export interface BuildMergePolicyResult {
90
+ unsignedXdr: string
91
+ smartAccount: string
92
+ sourceAccount: string
93
+ step: MergeStep
94
+ call: { contract: string; fn: 'remove_policy' | 'add_policy'; ruleId: number }
95
+ authNonce: string
96
+ authValidUntilLedger: number
97
+ rootInvocationXdr: string
98
+ }
99
+
100
+ function hostFunctionFor(args: BuildMergePolicyArgs): xdr.HostFunction {
101
+ if (args.step === 'detach') {
102
+ return xdr.HostFunction.hostFunctionTypeInvokeContract(
103
+ new xdr.InvokeContractArgs({
104
+ contractAddress: new Address(args.smartAccount).toScAddress(),
105
+ functionName: 'remove_policy',
106
+ args: [xdr.ScVal.scvU32(args.ruleId), xdr.ScVal.scvU32(args.policyId)],
107
+ })
108
+ )
109
+ }
110
+
111
+ if (!args.encodedPredicate || !args.predicateHash) {
112
+ throw new Error('merge_policy: reinstall needs the merged predicate and its hash')
113
+ }
114
+ return xdr.HostFunction.hostFunctionTypeInvokeContract(
115
+ new xdr.InvokeContractArgs({
116
+ contractAddress: new Address(args.smartAccount).toScAddress(),
117
+ functionName: 'add_policy',
118
+ args: [
119
+ xdr.ScVal.scvU32(args.ruleId),
120
+ new Address(args.interpreterAddress).toScVal(),
121
+ // Same encoder as a fresh install: the field order is ABI-significant
122
+ // and it re-hashes the predicate to confirm the supplied hash.
123
+ encodePolicyInstallParams({
124
+ encodedPredicate: args.encodedPredicate,
125
+ predicateHash: args.predicateHash,
126
+ installNonce: args.installNonce ?? 1,
127
+ grammarVersion: DEFAULT_GRAMMAR_VERSION,
128
+ ...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
129
+ }),
130
+ ],
131
+ })
132
+ )
133
+ }
134
+
135
+ /**
136
+ * Build the unsigned transaction for one step of the merge.
137
+ *
138
+ * The auth dance mirrors `buildRevokePolicyXdr`: simulate once to record the
139
+ * account's auth entry, rebuild with the payload bound to that recorded
140
+ * `rootInvocation`, then assemble. Binding to the recorded invocation rather
141
+ * than to the input arguments is what makes the signature commit to the exact
142
+ * rule and policy being changed.
143
+ */
144
+ export async function buildMergePolicyXdr(
145
+ args: BuildMergePolicyArgs
146
+ ): Promise<BuildMergePolicyResult> {
147
+ const fn = args.step === 'detach' ? 'remove_policy' : 'add_policy'
148
+ const source = await args.rpc.getAccount(args.sourceAccount)
149
+ const hostFunction = hostFunctionFor(args)
150
+ const makeOperation = (auth: xdr.SorobanAuthorizationEntry[] = []) =>
151
+ Operation.invokeHostFunction({ func: hostFunction, auth })
152
+ const baseFee = args.baseFee !== undefined ? String(args.baseFee) : BASE_FEE
153
+
154
+ const buildTx = (op: xdr.Operation) =>
155
+ new TransactionBuilder(new Account(args.sourceAccount, source.sequenceNumber()), {
156
+ fee: baseFee,
157
+ networkPassphrase: args.networkPassphrase,
158
+ })
159
+ .addOperation(op)
160
+ .setTimeout(0)
161
+ .build()
162
+
163
+ const recorded = await args.rpc.simulateTransaction(buildTx(makeOperation()))
164
+ if (rpc.Api.isSimulationError(recorded)) {
165
+ // Short and stable, like the other builders: the SDK's full error carries
166
+ // host and URL detail that has no business in a user-facing message.
167
+ throw new Error(`merge_policy: ${fn} simulateTransaction failed`)
168
+ }
169
+ const original = (recorded.result?.auth ?? []).find(
170
+ (entry) =>
171
+ entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
172
+ Address.fromScAddress(entry.credentials().address().address()).toString() ===
173
+ args.smartAccount
174
+ )
175
+ if (!original) {
176
+ throw new Error(
177
+ `merge_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`
178
+ )
179
+ }
180
+
181
+ const validUntilLedger =
182
+ (await args.rpc.getLatestLedger()).sequence +
183
+ (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS)
184
+ const contextRuleIds = [ADMIN_CONTEXT_RULE_ID]
185
+ const digest = authDigest(
186
+ signaturePayload(
187
+ args.networkPassphrase,
188
+ original.credentials().address().nonce(),
189
+ validUntilLedger,
190
+ original.rootInvocation()
191
+ ),
192
+ contextRuleIds
193
+ )
194
+ const authEntries = [
195
+ accountEntry(
196
+ original,
197
+ validUntilLedger,
198
+ authPayload([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))
199
+ ),
200
+ ...contextRuleIds.map(() => delegatedSignerEntry(args.smartAccount, digest)),
201
+ ]
202
+ const txWithAuth = buildTx(makeOperation(authEntries))
203
+ const enforcing = await args.rpc.simulateTransaction(txWithAuth)
204
+ if (rpc.Api.isSimulationError(enforcing)) {
205
+ throw new Error(`merge_policy: ${fn} auth simulateTransaction failed`)
206
+ }
207
+ const finalTx = rpc.assembleTransaction(txWithAuth, enforcing).build()
208
+
209
+ return {
210
+ unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
211
+ smartAccount: args.smartAccount,
212
+ sourceAccount: args.sourceAccount,
213
+ step: args.step,
214
+ call: { contract: args.smartAccount, fn, ruleId: args.ruleId },
215
+ authNonce: original.credentials().address().nonce().toString(),
216
+ authValidUntilLedger: validUntilLedger,
217
+ rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
218
+ }
219
+ }
@@ -12,6 +12,29 @@
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
+
16
+ // Cross-rule authority analysis. A caller installing a policy needs to know
17
+ // whether its signers can already reach the same calls through another context
18
+ // rule, because OZ lets the signer name the rule and enforces only that one's
19
+ // policies. Without this, a second, tighter rule reads as a restriction while
20
+ // restricting nothing.
21
+ export {
22
+ ANY,
23
+ type AuthorityOverlap,
24
+ type ContextType,
25
+ effectiveSelectors,
26
+ findAuthorityOverlaps,
27
+ type IntendedInstall,
28
+ intersectSelectors,
29
+ type MergeResult,
30
+ mergeIntoAnd,
31
+ type ObservedRule,
32
+ type OverlapSeverity,
33
+ permittedSelectors,
34
+ type RuleClass,
35
+ type Selector,
36
+ signerKey,
37
+ } from './authority-overlap.ts'
15
38
  export {
16
39
  ADD_CONTEXT_RULE_SYMBOL,
17
40
  type AddContextRuleArgs,
@@ -19,3 +42,14 @@ export {
19
42
  buildAddContextRuleArgs,
20
43
  DEFAULT_GRAMMAR_VERSION,
21
44
  } from './build-add-context-rule.ts'
45
+ export {
46
+ type AccountRuleReader,
47
+ accountRuleReaderFromServer,
48
+ type CollectedRules,
49
+ collectObservedRules,
50
+ decodeContextRule,
51
+ decodeContextType,
52
+ decodeSigner,
53
+ docLedgerKey,
54
+ MAX_RULE_ID_SCAN,
55
+ } from './read-account-rules.ts'
@@ -0,0 +1,133 @@
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
+
35
+ import type { PredicateNode } from '../types.ts'
36
+ import type { ObservedRule } from './authority-overlap.ts'
37
+ import { type MergeResult, mergeIntoAnd } from './authority-overlap.ts'
38
+
39
+ export type MergeStep = 'detach' | 'reinstall'
40
+
41
+ export interface MergePlanRefused {
42
+ ok: false
43
+ /** Why the merge cannot proceed, in terms the caller can act on. */
44
+ reason: string
45
+ }
46
+
47
+ export interface MergePlanAccepted {
48
+ ok: true
49
+ /** The conjunction to install in step 2. */
50
+ predicate: PredicateNode
51
+ /** OZ registry id of the interpreter policy on this rule, for
52
+ * `remove_policy`. */
53
+ policyId: number
54
+ /** Oracle bounds to re-install with the merged predicate. Carried from the
55
+ * document being replaced: they are tighten-only overrides against the wasm
56
+ * defaults, so omitting them would quietly widen the policy while the
57
+ * operator believed they were tightening it. */
58
+ oracleParams?: {
59
+ maxStalenessSeconds?: number
60
+ maxDeviationBps?: number
61
+ maxCrossFeedDeviationBps?: number
62
+ }
63
+ /** Consequences the caller must see BEFORE signing step 1, because step 1 is
64
+ * the destructive one. */
65
+ warnings: string[]
66
+ /** What the caller should do after the requested step confirms. */
67
+ followUp: string
68
+ }
69
+
70
+ export type MergePlan = MergePlanRefused | MergePlanAccepted
71
+
72
+ /** The interpreter's registry id on a rule, or null when it is not attached
73
+ * or the ids were not readable. */
74
+ export function interpreterPolicyId(rule: ObservedRule, interpreterAddress: string): number | null {
75
+ const index = rule.policyAddresses.indexOf(interpreterAddress)
76
+ if (index < 0) return null
77
+ const id = rule.policyIds?.[index]
78
+ return typeof id === 'number' ? id : null
79
+ }
80
+
81
+ /**
82
+ * Decide whether the merge can proceed, and say what it will cost.
83
+ *
84
+ * Refuses rather than guesses whenever the account is not in the shape the
85
+ * remedy assumes: the rule must be policed by our interpreter, its predicate
86
+ * must have been readable, and the ids needed to detach it must be present. A
87
+ * merge built on a predicate we could not read would silently replace a rule
88
+ * with something narrower or wider than its author wrote.
89
+ */
90
+ export function planMergePolicy(args: {
91
+ rule: ObservedRule
92
+ interpreterAddress: string
93
+ incoming: PredicateNode
94
+ step: MergeStep
95
+ }): MergePlan {
96
+ const policyId = interpreterPolicyId(args.rule, args.interpreterAddress)
97
+ if (policyId === null) {
98
+ return {
99
+ ok: false,
100
+ 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.`,
101
+ }
102
+ }
103
+
104
+ const existing = args.rule.predicate
105
+ if (!existing) {
106
+ return {
107
+ ok: false,
108
+ 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`,
109
+ }
110
+ }
111
+
112
+ const merged: MergeResult = mergeIntoAnd(existing, args.incoming)
113
+ if (!merged.ok || !merged.predicate) {
114
+ return { ok: false, reason: merged.reason ?? 'the two predicates cannot be conjoined' }
115
+ }
116
+
117
+ const warnings = [
118
+ `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`,
119
+ 'the rule is unpoliced between the two transactions, so a signer of it is unconstrained by this policy until step 2 confirms',
120
+ ]
121
+
122
+ return {
123
+ ok: true,
124
+ predicate: merged.predicate,
125
+ policyId,
126
+ ...(args.rule.oracleBounds ? { oracleParams: args.rule.oracleBounds } : {}),
127
+ warnings,
128
+ followUp:
129
+ args.step === 'detach'
130
+ ? "sign and submit this transaction, wait for it to confirm, then call again with step: 'reinstall' to install the merged predicate"
131
+ : 'sign and submit this transaction; the merged predicate is then the only policy governing this rule',
132
+ }
133
+ }