@crediolabs/policy-synth 0.1.17 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +44 -246
  2. package/dist/adapters/interpreter/adapter.d.ts +6 -7
  3. package/dist/adapters/interpreter/adapter.js +28 -48
  4. package/dist/adapters/oz/adapter.js +12 -13
  5. package/dist/codegen/compile-gate.js +5 -0
  6. package/dist/codegen/template.js +17 -0
  7. package/dist/install/authority-overlap.d.ts +134 -0
  8. package/dist/install/authority-overlap.js +0 -0
  9. package/dist/install/build-add-context-rule.d.ts +8 -0
  10. package/dist/install/build-add-context-rule.js +17 -46
  11. package/dist/install/build-install-policy.d.ts +12 -5
  12. package/dist/install/build-install-policy.js +32 -23
  13. package/dist/install/build-merge-policy.d.ts +70 -0
  14. package/dist/install/build-merge-policy.js +130 -0
  15. package/dist/install/get-interpreter-info.js +2 -2
  16. package/dist/install/index.d.ts +3 -1
  17. package/dist/install/index.js +8 -1
  18. package/dist/install/oz-auth.js +5 -3
  19. package/dist/install/plan-merge-policy.d.ts +49 -0
  20. package/dist/install/plan-merge-policy.js +86 -0
  21. package/dist/install/read-account-rules.d.ts +100 -0
  22. package/dist/install/read-account-rules.js +283 -0
  23. package/dist/predicate/decode.js +1 -1
  24. package/dist/predicate/encode.js +171 -10
  25. package/dist/record/decode.js +5 -6
  26. package/dist/registry/protocols.d.ts +1 -1
  27. package/dist/registry/protocols.js +1 -1
  28. package/dist/review-card/builder.d.ts +6 -0
  29. package/dist/review-card/builder.js +9 -1
  30. package/dist/run/index.d.ts +104 -18
  31. package/dist/run/index.js +359 -75
  32. package/dist/run/schemas.d.ts +479 -18
  33. package/dist/run/schemas.js +132 -24
  34. package/dist/synth/compose-from-recording.d.ts +10 -15
  35. package/dist/synth/compose-from-recording.js +79 -124
  36. package/dist/synth/deny-cases.d.ts +5 -0
  37. package/dist/synth/deny-cases.js +52 -13
  38. package/dist/synth/evaluate.js +69 -119
  39. package/dist/synth/harness.d.ts +13 -1
  40. package/dist/synth/harness.js +22 -1
  41. package/dist/synth/index.d.ts +1 -1
  42. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  43. package/dist/synth/synthesize-from-recording.js +129 -155
  44. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  45. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  46. package/dist-cjs/adapters/oz/adapter.js +12 -13
  47. package/dist-cjs/codegen/compile-gate.js +5 -0
  48. package/dist-cjs/codegen/template.js +17 -0
  49. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  50. package/dist-cjs/install/authority-overlap.js +0 -0
  51. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  52. package/dist-cjs/install/build-add-context-rule.js +17 -45
  53. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  54. package/dist-cjs/install/build-install-policy.js +32 -23
  55. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  56. package/dist-cjs/install/build-merge-policy.js +134 -0
  57. package/dist-cjs/install/get-interpreter-info.js +2 -2
  58. package/dist-cjs/install/index.d.ts +3 -1
  59. package/dist-cjs/install/index.js +24 -3
  60. package/dist-cjs/install/oz-auth.js +5 -3
  61. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  62. package/dist-cjs/install/plan-merge-policy.js +90 -0
  63. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  64. package/dist-cjs/install/read-account-rules.js +296 -0
  65. package/dist-cjs/predicate/decode.js +1 -1
  66. package/dist-cjs/predicate/encode.js +171 -10
  67. package/dist-cjs/record/decode.js +5 -6
  68. package/dist-cjs/registry/protocols.d.ts +1 -1
  69. package/dist-cjs/registry/protocols.js +1 -1
  70. package/dist-cjs/review-card/builder.d.ts +6 -0
  71. package/dist-cjs/review-card/builder.js +9 -1
  72. package/dist-cjs/run/index.d.ts +104 -18
  73. package/dist-cjs/run/index.js +360 -74
  74. package/dist-cjs/run/schemas.d.ts +479 -18
  75. package/dist-cjs/run/schemas.js +133 -25
  76. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  77. package/dist-cjs/synth/compose-from-recording.js +79 -124
  78. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  79. package/dist-cjs/synth/deny-cases.js +52 -13
  80. package/dist-cjs/synth/evaluate.js +69 -119
  81. package/dist-cjs/synth/harness.d.ts +13 -1
  82. package/dist-cjs/synth/harness.js +22 -1
  83. package/dist-cjs/synth/index.d.ts +1 -1
  84. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  85. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  86. package/package.json +1 -1
  87. package/src/adapters/interpreter/adapter.ts +28 -48
  88. package/src/adapters/oz/adapter.ts +12 -13
  89. package/src/codegen/compile-gate.ts +5 -0
  90. package/src/codegen/template.ts +17 -0
  91. package/src/install/authority-overlap.ts +0 -0
  92. package/src/install/build-add-context-rule.ts +29 -56
  93. package/src/install/build-install-policy.ts +41 -23
  94. package/src/install/build-merge-policy.ts +219 -0
  95. package/src/install/get-interpreter-info.ts +2 -2
  96. package/src/install/index.ts +36 -2
  97. package/src/install/oz-auth.ts +5 -3
  98. package/src/install/plan-merge-policy.ts +133 -0
  99. package/src/install/read-account-rules.ts +376 -0
  100. package/src/predicate/decode.ts +1 -1
  101. package/src/predicate/encode.ts +176 -10
  102. package/src/record/decode.ts +5 -6
  103. package/src/registry/protocols.ts +1 -1
  104. package/src/review-card/builder.ts +17 -1
  105. package/src/run/index.ts +500 -102
  106. package/src/run/schemas.ts +145 -24
  107. package/src/synth/compose-from-recording.ts +87 -132
  108. package/src/synth/deny-cases.ts +59 -13
  109. package/src/synth/evaluate.ts +70 -118
  110. package/src/synth/harness.ts +29 -1
  111. package/src/synth/index.ts +1 -0
  112. package/src/synth/synthesize-from-recording.ts +209 -192
  113. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -0,0 +1,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,134 @@
1
+ "use strict";
2
+ //! Transactions for the merge remedy.
3
+ //!
4
+ //! `plan-merge-policy.ts` decides WHAT should happen; this builds the XDR for
5
+ //! the step the caller asked for. Two calls, in order, because OZ refuses to
6
+ //! attach a policy that is already on the rule:
7
+ //!
8
+ //! step 1 `detach` -> `account.remove_policy(rule_id, policy_id)`
9
+ //! step 2 `reinstall` -> `account.add_policy(rule_id, interpreter, param)`
10
+ //!
11
+ //! The two cannot be emitted together. Simulating step 2 while the old
12
+ //! attachment is still there hits `DuplicatePolicy`, so the second transaction
13
+ //! is only buildable once the first has confirmed.
14
+ //!
15
+ //! Both calls route through the smart account and are authorised the same way
16
+ //! as `revoke_policy`: against the deploy-time admin rule, with the recorded
17
+ //! `rootInvocation` binding the auth payload to this exact rule and policy.
18
+ //! Detaching runs our `uninstall`, which is master-gated, so the signer has to
19
+ //! be a master of the rule either way.
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.ADMIN_CONTEXT_RULE_ID = void 0;
22
+ exports.buildMergePolicyXdr = buildMergePolicyXdr;
23
+ const stellar_sdk_1 = require("@stellar/stellar-sdk");
24
+ const build_add_context_rule_ts_1 = require("./build-add-context-rule.js");
25
+ const oz_auth_ts_1 = require("./oz-auth.js");
26
+ /** Matches the window the install and revoke builders use. */
27
+ const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 100;
28
+ /**
29
+ * The context rule the merge authorises AGAINST, which is not the rule being
30
+ * merged.
31
+ *
32
+ * Both calls mutate the smart account itself, so they need the account's own
33
+ * authorisation, and this builder asks rule 0 for it - the same assumption the
34
+ * install and revoke builders make. OpenZeppelin does NOT enforce any
35
+ * admin semantic for rule 0: it is simply the first rule the account's
36
+ * constructor created, and OZ's reference account creates it as `Default`
37
+ * covering every context.
38
+ *
39
+ * The assumption is therefore load-bearing and unverified at build time. If
40
+ * rule 0 does not exist, does not cover `CallContract(<smart account>)`, or
41
+ * does not list the source account as a signer, the transaction is built and
42
+ * then fails when submitted, and the operator pays the fee for a transaction
43
+ * that was never signable. Changing it is a wire-visible change: the id is
44
+ * hashed into the auth digest.
45
+ */
46
+ exports.ADMIN_CONTEXT_RULE_ID = 0;
47
+ function hostFunctionFor(args) {
48
+ if (args.step === 'detach') {
49
+ return stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
50
+ contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
51
+ functionName: 'remove_policy',
52
+ args: [stellar_sdk_1.xdr.ScVal.scvU32(args.ruleId), stellar_sdk_1.xdr.ScVal.scvU32(args.policyId)],
53
+ }));
54
+ }
55
+ if (!args.encodedPredicate || !args.predicateHash) {
56
+ throw new Error('merge_policy: reinstall needs the merged predicate and its hash');
57
+ }
58
+ return stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
59
+ contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
60
+ functionName: 'add_policy',
61
+ args: [
62
+ stellar_sdk_1.xdr.ScVal.scvU32(args.ruleId),
63
+ new stellar_sdk_1.Address(args.interpreterAddress).toScVal(),
64
+ // Same encoder as a fresh install: the field order is ABI-significant
65
+ // and it re-hashes the predicate to confirm the supplied hash.
66
+ (0, build_add_context_rule_ts_1.encodePolicyInstallParams)({
67
+ encodedPredicate: args.encodedPredicate,
68
+ predicateHash: args.predicateHash,
69
+ installNonce: args.installNonce ?? 1,
70
+ grammarVersion: build_add_context_rule_ts_1.DEFAULT_GRAMMAR_VERSION,
71
+ ...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
72
+ }),
73
+ ],
74
+ }));
75
+ }
76
+ /**
77
+ * Build the unsigned transaction for one step of the merge.
78
+ *
79
+ * The auth dance mirrors `buildRevokePolicyXdr`: simulate once to record the
80
+ * account's auth entry, rebuild with the payload bound to that recorded
81
+ * `rootInvocation`, then assemble. Binding to the recorded invocation rather
82
+ * than to the input arguments is what makes the signature commit to the exact
83
+ * rule and policy being changed.
84
+ */
85
+ async function buildMergePolicyXdr(args) {
86
+ const fn = args.step === 'detach' ? 'remove_policy' : 'add_policy';
87
+ const source = await args.rpc.getAccount(args.sourceAccount);
88
+ const hostFunction = hostFunctionFor(args);
89
+ const makeOperation = (auth = []) => stellar_sdk_1.Operation.invokeHostFunction({ func: hostFunction, auth });
90
+ const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
91
+ const buildTx = (op) => new stellar_sdk_1.TransactionBuilder(new stellar_sdk_1.Account(args.sourceAccount, source.sequenceNumber()), {
92
+ fee: baseFee,
93
+ networkPassphrase: args.networkPassphrase,
94
+ })
95
+ .addOperation(op)
96
+ .setTimeout(0)
97
+ .build();
98
+ const recorded = await args.rpc.simulateTransaction(buildTx(makeOperation()));
99
+ if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
100
+ // Short and stable, like the other builders: the SDK's full error carries
101
+ // host and URL detail that has no business in a user-facing message.
102
+ throw new Error(`merge_policy: ${fn} simulateTransaction failed`);
103
+ }
104
+ const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
105
+ stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
106
+ args.smartAccount);
107
+ if (!original) {
108
+ throw new Error(`merge_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
109
+ }
110
+ const validUntilLedger = (await args.rpc.getLatestLedger()).sequence +
111
+ (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS);
112
+ const contextRuleIds = [exports.ADMIN_CONTEXT_RULE_ID];
113
+ const digest = (0, oz_auth_ts_1.authDigest)((0, oz_auth_ts_1.signaturePayload)(args.networkPassphrase, original.credentials().address().nonce(), validUntilLedger, original.rootInvocation()), contextRuleIds);
114
+ const authEntries = [
115
+ (0, oz_auth_ts_1.accountEntry)(original, validUntilLedger, (0, oz_auth_ts_1.authPayload)([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))),
116
+ ...contextRuleIds.map(() => (0, oz_auth_ts_1.delegatedSignerEntry)(args.smartAccount, digest)),
117
+ ];
118
+ const txWithAuth = buildTx(makeOperation(authEntries));
119
+ const enforcing = await args.rpc.simulateTransaction(txWithAuth);
120
+ if (stellar_sdk_1.rpc.Api.isSimulationError(enforcing)) {
121
+ throw new Error(`merge_policy: ${fn} auth simulateTransaction failed`);
122
+ }
123
+ const finalTx = stellar_sdk_1.rpc.assembleTransaction(txWithAuth, enforcing).build();
124
+ return {
125
+ unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
126
+ smartAccount: args.smartAccount,
127
+ sourceAccount: args.sourceAccount,
128
+ step: args.step,
129
+ call: { contract: args.smartAccount, fn, ruleId: args.ruleId },
130
+ authNonce: original.credentials().address().nonce().toString(),
131
+ authValidUntilLedger: validUntilLedger,
132
+ rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
133
+ };
134
+ }
@@ -10,9 +10,9 @@
10
10
  // Per design decision 5: phase-04's "audit #44" is aspirational and has no
11
11
  // source-of-truth in the repo. Returning a fabricated audit id would be a
12
12
  // lie on a security surface. The honest outputs are:
13
- // - the pinned address (DEPLOYMENTS.md)
13
+ // - the pinned address (`PINNED_INTERPRETER_*_ADDRESS` in run/schemas.ts)
14
14
  // - the pinned grammar version (SELF_VERSION in version.rs)
15
- // - the pinned wasm sha256 (DEPLOYMENTS.md)
15
+ // - the pinned wasm sha256 (`PINNED_INTERPRETER_WASM_SHA256` in run/schemas.ts)
16
16
  // - an OPTIONAL `deployedGrammarVersion` returned by a live `grammar_version()`
17
17
  // RPC call, with a `liveMatchesPin` boolean the caller can dispatch on. A
18
18
  // mismatch means the deployed wasm is NOT the pinned artifact - the caller
@@ -1 +1,3 @@
1
- export { ADD_CONTEXT_RULE_SYMBOL, DEFAULT_GRAMMAR_VERSION, buildAddContextRuleArgs, type AddContextRuleArgs, type BuildAddContextRuleArgs, } from './build-add-context-rule.ts';
1
+ export { ANY, type AuthorityOverlap, type ContextType, effectiveSelectors, findAuthorityOverlaps, type IntendedInstall, intersectSelectors, type MergeResult, mergeIntoAnd, type ObservedRule, type OverlapSeverity, permittedSelectors, type RuleClass, type Selector, signerKey, } from './authority-overlap.ts';
2
+ export { ADD_CONTEXT_RULE_SYMBOL, type AddContextRuleArgs, type BuildAddContextRuleArgs, buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION, } from './build-add-context-rule.ts';
3
+ export { type AccountRuleReader, accountRuleReaderFromServer, type CollectedRules, collectObservedRules, decodeContextRule, decodeContextType, decodeSigner, docLedgerKey, MAX_RULE_ID_SCAN, } from './read-account-rules.ts';
@@ -1,6 +1,4 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildAddContextRuleArgs = exports.DEFAULT_GRAMMAR_VERSION = exports.ADD_CONTEXT_RULE_SYMBOL = void 0;
4
2
  // Public entry for the install-argument builders.
5
3
  //
6
4
  // `buildAddContextRuleArgs` is the encoder `runInstallPolicy` uses to turn a
@@ -15,7 +13,30 @@ exports.buildAddContextRuleArgs = exports.DEFAULT_GRAMMAR_VERSION = exports.ADD_
15
13
  // Exported here rather than from the package root to keep the root surface
16
14
  // about synthesis, and because these are transaction-building primitives whose
17
15
  // callers should know they are reaching for them.
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.MAX_RULE_ID_SCAN = exports.docLedgerKey = exports.decodeSigner = exports.decodeContextType = exports.decodeContextRule = exports.collectObservedRules = exports.accountRuleReaderFromServer = exports.DEFAULT_GRAMMAR_VERSION = exports.buildAddContextRuleArgs = exports.ADD_CONTEXT_RULE_SYMBOL = exports.signerKey = exports.permittedSelectors = exports.mergeIntoAnd = exports.intersectSelectors = exports.findAuthorityOverlaps = exports.effectiveSelectors = exports.ANY = void 0;
18
+ // Cross-rule authority analysis. A caller installing a policy needs to know
19
+ // whether its signers can already reach the same calls through another context
20
+ // rule, because OZ lets the signer name the rule and enforces only that one's
21
+ // policies. Without this, a second, tighter rule reads as a restriction while
22
+ // restricting nothing.
23
+ var authority_overlap_ts_1 = require("./authority-overlap.js");
24
+ Object.defineProperty(exports, "ANY", { enumerable: true, get: function () { return authority_overlap_ts_1.ANY; } });
25
+ Object.defineProperty(exports, "effectiveSelectors", { enumerable: true, get: function () { return authority_overlap_ts_1.effectiveSelectors; } });
26
+ Object.defineProperty(exports, "findAuthorityOverlaps", { enumerable: true, get: function () { return authority_overlap_ts_1.findAuthorityOverlaps; } });
27
+ Object.defineProperty(exports, "intersectSelectors", { enumerable: true, get: function () { return authority_overlap_ts_1.intersectSelectors; } });
28
+ Object.defineProperty(exports, "mergeIntoAnd", { enumerable: true, get: function () { return authority_overlap_ts_1.mergeIntoAnd; } });
29
+ Object.defineProperty(exports, "permittedSelectors", { enumerable: true, get: function () { return authority_overlap_ts_1.permittedSelectors; } });
30
+ Object.defineProperty(exports, "signerKey", { enumerable: true, get: function () { return authority_overlap_ts_1.signerKey; } });
18
31
  var build_add_context_rule_ts_1 = require("./build-add-context-rule.js");
19
32
  Object.defineProperty(exports, "ADD_CONTEXT_RULE_SYMBOL", { enumerable: true, get: function () { return build_add_context_rule_ts_1.ADD_CONTEXT_RULE_SYMBOL; } });
20
- Object.defineProperty(exports, "DEFAULT_GRAMMAR_VERSION", { enumerable: true, get: function () { return build_add_context_rule_ts_1.DEFAULT_GRAMMAR_VERSION; } });
21
33
  Object.defineProperty(exports, "buildAddContextRuleArgs", { enumerable: true, get: function () { return build_add_context_rule_ts_1.buildAddContextRuleArgs; } });
34
+ Object.defineProperty(exports, "DEFAULT_GRAMMAR_VERSION", { enumerable: true, get: function () { return build_add_context_rule_ts_1.DEFAULT_GRAMMAR_VERSION; } });
35
+ var read_account_rules_ts_1 = require("./read-account-rules.js");
36
+ Object.defineProperty(exports, "accountRuleReaderFromServer", { enumerable: true, get: function () { return read_account_rules_ts_1.accountRuleReaderFromServer; } });
37
+ Object.defineProperty(exports, "collectObservedRules", { enumerable: true, get: function () { return read_account_rules_ts_1.collectObservedRules; } });
38
+ Object.defineProperty(exports, "decodeContextRule", { enumerable: true, get: function () { return read_account_rules_ts_1.decodeContextRule; } });
39
+ Object.defineProperty(exports, "decodeContextType", { enumerable: true, get: function () { return read_account_rules_ts_1.decodeContextType; } });
40
+ Object.defineProperty(exports, "decodeSigner", { enumerable: true, get: function () { return read_account_rules_ts_1.decodeSigner; } });
41
+ Object.defineProperty(exports, "docLedgerKey", { enumerable: true, get: function () { return read_account_rules_ts_1.docLedgerKey; } });
42
+ Object.defineProperty(exports, "MAX_RULE_ID_SCAN", { enumerable: true, get: function () { return read_account_rules_ts_1.MAX_RULE_ID_SCAN; } });
@@ -39,9 +39,11 @@ const u32 = (n) => stellar_sdk_1.xdr.ScVal.scvU32(n);
39
39
  const vec = (i) => stellar_sdk_1.xdr.ScVal.scvVec(i);
40
40
  const bytes = (b) => stellar_sdk_1.xdr.ScVal.scvBytes(b);
41
41
  function struct(fields) {
42
- return stellar_sdk_1.xdr.ScVal.scvMap(Object.keys(fields)
43
- .sort()
44
- .map((k) => new stellar_sdk_1.xdr.ScMapEntry({ key: sym(k), val: fields[k] })));
42
+ // Entries sorted by key with the default string comparison - ScMap
43
+ // encoding requires the same order Object.keys().sort() produced.
44
+ return stellar_sdk_1.xdr.ScVal.scvMap(Object.entries(fields)
45
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
46
+ .map(([k, v]) => new stellar_sdk_1.xdr.ScMapEntry({ key: sym(k), val: v })));
45
47
  }
46
48
  /** `Signer::Delegated(addr)`. */
47
49
  const delegatedSigner = (a) => vec([sym('Delegated'), new stellar_sdk_1.Address(a).toScVal()]);
@@ -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,90 @@
1
+ "use strict";
2
+ //! Planning the merge remedy for a cross-rule authority overlap.
3
+ //!
4
+ //! When two rules our interpreter polices can serve the same calls, the
5
+ //! tightening remedy is to replace one rule's predicate with the conjunction
6
+ //! of both (see `authority-overlap.ts`). Carrying that out against an OZ smart
7
+ //! account is not one call, and the reasons are worth stating because they
8
+ //! shape the whole tool:
9
+ //!
10
+ //! 1. A Soroban transaction carries exactly ONE operation - "smart contract
11
+ //! transactions can only have one operation per transaction" - so the
12
+ //! detach and the re-attach cannot be bundled even though the host would
13
+ //! run them in order happily. And `add_policy` panics `DuplicatePolicy`
14
+ //! while the policy is still attached (`smart_account/storage.rs`
15
+ //! `add_policy`), so the second transaction cannot even be simulated
16
+ //! until the first has confirmed.
17
+ //! 2. `remove_policy` calls `try_uninstall` and DISCARDS the result
18
+ //! (`smart_account/storage.rs`: `let _ = ...try_uninstall(...)`), so the
19
+ //! policy is detached whether or not our `uninstall` succeeded. When it
20
+ //! succeeded the document, nonce, signer hash, master set and counters
21
+ //! are gone and the re-install is a fresh install at nonce 1. When it
22
+ //! panicked - our `uninstall` panics `MissingState` if the master set has
23
+ //! been archived - the nonce SURVIVES, and re-installing at 1 would be
24
+ //! refused on chain as a replay, leaving the rule stuck unpoliced. The
25
+ //! nonce is therefore READ at reinstall time rather than assumed.
26
+ //! 3. Because of (2), any rate-limit or spend window on that rule is reset
27
+ //! by the merge. A signer who had consumed most of a window gets a clean
28
+ //! one. That is a real cost of tightening this way and the caller has to
29
+ //! be told, not discover it.
30
+ //! 4. So the caller performs step 1, waits for it to confirm, then asks for
31
+ //! step 2.
32
+ //!
33
+ //! This module is pure. It decides what should happen and why; the XDR is
34
+ //! built by `build-merge-policy.ts`.
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.interpreterPolicyId = interpreterPolicyId;
37
+ exports.planMergePolicy = planMergePolicy;
38
+ const authority_overlap_ts_1 = require("./authority-overlap.js");
39
+ /** The interpreter's registry id on a rule, or null when it is not attached
40
+ * or the ids were not readable. */
41
+ function interpreterPolicyId(rule, interpreterAddress) {
42
+ const index = rule.policyAddresses.indexOf(interpreterAddress);
43
+ if (index < 0)
44
+ return null;
45
+ const id = rule.policyIds?.[index];
46
+ return typeof id === 'number' ? id : null;
47
+ }
48
+ /**
49
+ * Decide whether the merge can proceed, and say what it will cost.
50
+ *
51
+ * Refuses rather than guesses whenever the account is not in the shape the
52
+ * remedy assumes: the rule must be policed by our interpreter, its predicate
53
+ * must have been readable, and the ids needed to detach it must be present. A
54
+ * merge built on a predicate we could not read would silently replace a rule
55
+ * with something narrower or wider than its author wrote.
56
+ */
57
+ function planMergePolicy(args) {
58
+ const policyId = interpreterPolicyId(args.rule, args.interpreterAddress);
59
+ if (policyId === null) {
60
+ return {
61
+ ok: false,
62
+ reason: `rule ${args.rule.id} is not policed by the interpreter at ${args.interpreterAddress}, or its policy ids could not be read, so there is nothing to merge into and no id to detach. The merge hard-pins to that interpreter and has no opt-out: the auth digest it builds binds to the audited deployment. A rule installed against a different interpreter has to be replaced rather than merged.`,
63
+ };
64
+ }
65
+ const existing = args.rule.predicate;
66
+ if (!existing) {
67
+ return {
68
+ ok: false,
69
+ reason: `the predicate installed on rule ${args.rule.id} could not be read, so it cannot be conjoined; merging against an unknown predicate would replace the rule with something other than what its author wrote`,
70
+ };
71
+ }
72
+ const merged = (0, authority_overlap_ts_1.mergeIntoAnd)(existing, args.incoming);
73
+ if (!merged.ok || !merged.predicate) {
74
+ return { ok: false, reason: merged.reason ?? 'the two predicates cannot be conjoined' };
75
+ }
76
+ const warnings = [
77
+ `detaching the policy uninstalls it, which removes every counter on rule ${args.rule.id}: any rate limit or spend window there restarts from zero after the merge`,
78
+ 'the rule is unpoliced between the two transactions, so a signer of it is unconstrained by this policy until step 2 confirms',
79
+ ];
80
+ return {
81
+ ok: true,
82
+ predicate: merged.predicate,
83
+ policyId,
84
+ ...(args.rule.oracleBounds ? { oracleParams: args.rule.oracleBounds } : {}),
85
+ warnings,
86
+ followUp: args.step === 'detach'
87
+ ? "sign and submit this transaction, wait for it to confirm, then call again with step: 'reinstall' to install the merged predicate"
88
+ : 'sign and submit this transaction; the merged predicate is then the only policy governing this rule',
89
+ };
90
+ }
@@ -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;