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