@crediolabs/policy-synth 0.3.0 → 0.4.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 (152) hide show
  1. package/dist/install/authority-overlap.d.ts +101 -0
  2. package/dist/install/authority-overlap.js +227 -0
  3. package/dist/install/index.d.ts +1 -0
  4. package/dist/install/index.js +4 -0
  5. package/dist/record/freshness.d.ts +17 -11
  6. package/dist/record/freshness.js +28 -18
  7. package/dist/record/index.d.ts +10 -0
  8. package/dist/record/index.js +32 -1
  9. package/dist/record/rpc.d.ts +4 -0
  10. package/dist/record/rpc.js +4 -1
  11. package/dist/registry/identify.d.ts +10 -1
  12. package/dist/registry/identify.js +4 -1
  13. package/dist/registry/on-chain-spec.d.ts +37 -0
  14. package/dist/registry/on-chain-spec.js +152 -0
  15. package/dist/run/index.d.ts +25 -4
  16. package/dist/run/index.js +65 -4
  17. package/dist/run/schemas.d.ts +313 -0
  18. package/dist/run/schemas.js +52 -0
  19. package/dist/synth/declare.d.ts +30 -0
  20. package/dist/synth/declare.js +98 -0
  21. package/dist/synth/index.d.ts +1 -0
  22. package/dist/synth/index.js +1 -0
  23. package/dist-cjs/install/authority-overlap.d.ts +101 -0
  24. package/dist-cjs/install/authority-overlap.js +236 -0
  25. package/dist-cjs/install/index.d.ts +1 -0
  26. package/dist-cjs/install/index.js +13 -2
  27. package/dist-cjs/record/freshness.d.ts +17 -11
  28. package/dist-cjs/record/freshness.js +28 -18
  29. package/dist-cjs/record/index.d.ts +10 -0
  30. package/dist-cjs/record/index.js +31 -0
  31. package/dist-cjs/record/rpc.d.ts +4 -0
  32. package/dist-cjs/record/rpc.js +7 -3
  33. package/dist-cjs/registry/identify.d.ts +10 -1
  34. package/dist-cjs/registry/identify.js +4 -0
  35. package/dist-cjs/registry/on-chain-spec.d.ts +37 -0
  36. package/dist-cjs/registry/on-chain-spec.js +159 -0
  37. package/dist-cjs/run/index.d.ts +25 -4
  38. package/dist-cjs/run/index.js +65 -2
  39. package/dist-cjs/run/schemas.d.ts +313 -0
  40. package/dist-cjs/run/schemas.js +53 -1
  41. package/dist-cjs/synth/declare.d.ts +30 -0
  42. package/dist-cjs/synth/declare.js +101 -0
  43. package/dist-cjs/synth/index.d.ts +1 -0
  44. package/dist-cjs/synth/index.js +3 -1
  45. package/package.json +2 -2
  46. package/src/install/authority-overlap.ts +312 -0
  47. package/src/install/index.ts +20 -0
  48. package/src/record/freshness.ts +29 -18
  49. package/src/record/index.ts +59 -2
  50. package/src/record/rpc.ts +4 -1
  51. package/src/registry/identify.ts +4 -1
  52. package/src/registry/on-chain-spec.ts +168 -0
  53. package/src/run/index.ts +79 -2
  54. package/src/run/schemas.ts +57 -0
  55. package/src/synth/declare.ts +157 -0
  56. package/src/synth/index.ts +5 -0
  57. package/dist/adapters/interpreter/index.d.ts +0 -1
  58. package/dist/adapters/interpreter/index.js +0 -2
  59. package/dist/adapters/oz/adapter.d.ts +0 -20
  60. package/dist/adapters/oz/adapter.js +0 -281
  61. package/dist/adapters/oz/index.d.ts +0 -1
  62. package/dist/adapters/oz/index.js +0 -2
  63. package/dist/codegen/compile-gate.d.ts +0 -33
  64. package/dist/codegen/compile-gate.js +0 -124
  65. package/dist/codegen/index.d.ts +0 -2
  66. package/dist/codegen/index.js +0 -8
  67. package/dist/codegen/template.d.ts +0 -18
  68. package/dist/codegen/template.js +0 -148
  69. package/dist/ir/index.d.ts +0 -1
  70. package/dist/ir/index.js +0 -2
  71. package/dist/ir/types.d.ts +0 -71
  72. package/dist/ir/types.js +0 -9
  73. package/dist/mandate/index.d.ts +0 -2
  74. package/dist/mandate/index.js +0 -2
  75. package/dist/mandate/to-ir.d.ts +0 -3
  76. package/dist/mandate/to-ir.js +0 -60
  77. package/dist/mandate/types.d.ts +0 -20
  78. package/dist/mandate/types.js +0 -8
  79. package/dist/seams/index.d.ts +0 -1
  80. package/dist/seams/index.js +0 -2
  81. package/dist/seams/types.d.ts +0 -64
  82. package/dist/seams/types.js +0 -11
  83. package/dist/synth/deny-cases.d.ts +0 -28
  84. package/dist/synth/deny-cases.js +0 -212
  85. package/dist/synth/evaluate.d.ts +0 -18
  86. package/dist/synth/evaluate.js +0 -271
  87. package/dist/synth/harness.d.ts +0 -28
  88. package/dist/synth/harness.js +0 -47
  89. package/dist/synth/minimize.d.ts +0 -4
  90. package/dist/synth/minimize.js +0 -38
  91. package/dist/synth/permit-context.d.ts +0 -8
  92. package/dist/synth/permit-context.js +0 -35
  93. package/dist/synth/predicate-literals.d.ts +0 -5
  94. package/dist/synth/predicate-literals.js +0 -25
  95. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  96. package/dist/synth/synthesize-from-mandate.js +0 -59
  97. package/dist/verify/envelope.d.ts +0 -15
  98. package/dist/verify/envelope.js +0 -22
  99. package/dist/verify/index.d.ts +0 -3
  100. package/dist/verify/index.js +0 -3
  101. package/dist/verify/simulate.d.ts +0 -18
  102. package/dist/verify/simulate.js +0 -172
  103. package/dist/verify/verify.d.ts +0 -15
  104. package/dist/verify/verify.js +0 -181
  105. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  106. package/dist-cjs/adapters/interpreter/index.js +0 -7
  107. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  108. package/dist-cjs/adapters/oz/adapter.js +0 -286
  109. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  110. package/dist-cjs/adapters/oz/index.js +0 -8
  111. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  112. package/dist-cjs/codegen/compile-gate.js +0 -128
  113. package/dist-cjs/codegen/index.d.ts +0 -2
  114. package/dist-cjs/codegen/index.js +0 -14
  115. package/dist-cjs/codegen/template.d.ts +0 -18
  116. package/dist-cjs/codegen/template.js +0 -151
  117. package/dist-cjs/ir/index.d.ts +0 -1
  118. package/dist-cjs/ir/index.js +0 -3
  119. package/dist-cjs/ir/types.d.ts +0 -71
  120. package/dist-cjs/ir/types.js +0 -10
  121. package/dist-cjs/mandate/index.d.ts +0 -2
  122. package/dist-cjs/mandate/index.js +0 -6
  123. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  124. package/dist-cjs/mandate/to-ir.js +0 -63
  125. package/dist-cjs/mandate/types.d.ts +0 -20
  126. package/dist-cjs/mandate/types.js +0 -9
  127. package/dist-cjs/seams/index.d.ts +0 -1
  128. package/dist-cjs/seams/index.js +0 -3
  129. package/dist-cjs/seams/types.d.ts +0 -64
  130. package/dist-cjs/seams/types.js +0 -12
  131. package/dist-cjs/synth/deny-cases.d.ts +0 -28
  132. package/dist-cjs/synth/deny-cases.js +0 -217
  133. package/dist-cjs/synth/evaluate.d.ts +0 -18
  134. package/dist-cjs/synth/evaluate.js +0 -274
  135. package/dist-cjs/synth/harness.d.ts +0 -28
  136. package/dist-cjs/synth/harness.js +0 -50
  137. package/dist-cjs/synth/minimize.d.ts +0 -4
  138. package/dist-cjs/synth/minimize.js +0 -41
  139. package/dist-cjs/synth/permit-context.d.ts +0 -8
  140. package/dist-cjs/synth/permit-context.js +0 -38
  141. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  142. package/dist-cjs/synth/predicate-literals.js +0 -28
  143. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  144. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  145. package/dist-cjs/verify/envelope.d.ts +0 -15
  146. package/dist-cjs/verify/envelope.js +0 -23
  147. package/dist-cjs/verify/index.d.ts +0 -3
  148. package/dist-cjs/verify/index.js +0 -8
  149. package/dist-cjs/verify/simulate.d.ts +0 -18
  150. package/dist-cjs/verify/simulate.js +0 -175
  151. package/dist-cjs/verify/verify.d.ts +0 -15
  152. package/dist-cjs/verify/verify.js +0 -184
@@ -0,0 +1,101 @@
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
+ contract: string;
15
+ } | {
16
+ kind: 'create_contract';
17
+ wasmHash: string;
18
+ };
19
+ /** How much can be said about a neighbouring rule.
20
+ * - `interpreter`: policed by our interpreter and the predicate was readable,
21
+ * so its authority is known exactly.
22
+ * - `foreign`: policed by some other contract. The address is visible, the
23
+ * semantics are not, so it needs review by hand.
24
+ * - `unpoliced`: no policy at all. Whatever its context type allows, its
25
+ * 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
+ /** Decoded predicate. Present only when the rule is policed by OUR
34
+ * interpreter and the stored document was readable. */
35
+ predicate?: PredicateNode;
36
+ }
37
+ export interface IntendedInstall {
38
+ /** Rule the predicate is being installed onto. A re-install onto the same
39
+ * id REPLACES its predicate rather than adding a second source of
40
+ * authority, so that id is skipped. */
41
+ ruleId: number;
42
+ contextType: ContextType;
43
+ signers: SignerDraft[];
44
+ predicate: PredicateNode;
45
+ }
46
+ export type OverlapSeverity =
47
+ /** A neighbouring rule imposes no constraint at all on the shared calls. */
48
+ 'bypass'
49
+ /** A neighbouring policy exists but what it permits cannot be read. */
50
+ | 'unknown'
51
+ /** Both rules are ours. The new rule will not restrict the shared calls,
52
+ * because the signer names whichever is more permissive. */
53
+ | 'not-restricting';
54
+ export interface AuthorityOverlap {
55
+ ruleId: number;
56
+ ruleClass: RuleClass;
57
+ severity: OverlapSeverity;
58
+ /** Signers present in BOTH rules. An overlap is only reachable by a signer
59
+ * who can name both, so a rule sharing no signer is not a collision. */
60
+ sharedSigners: SignerDraft[];
61
+ /** The selectors both rules can serve. Non-empty by construction. */
62
+ sharedSelectors: Selector[];
63
+ advice: string;
64
+ }
65
+ /** Canonical key for signer equality. Mirrors OZ's `Signer` enum: a delegated
66
+ * signer is its address, an external signer is the verifier plus the key
67
+ * bytes, since one verifier may hold many keys. */
68
+ export declare function signerKey(s: SignerDraft): string;
69
+ /** Intersection of two selector SETS: every compatible pairing survives. */
70
+ export declare function intersectSelectors(a: Selector[], b: Selector[]): Selector[];
71
+ /**
72
+ * The set of `(contract, fn)` selectors a predicate may permit.
73
+ *
74
+ * A deliberate OVER-approximation: every call the predicate actually permits is
75
+ * covered by some returned selector, and unrecognised structure widens to the
76
+ * wildcard rather than narrowing. That direction is what makes the emptiness
77
+ * test sound. A call carries exactly one `(contract, fn)`, so if two
78
+ * predicates' over-approximations do not intersect, no single call can be
79
+ * routed to either and the rules provably cannot collide.
80
+ *
81
+ * Narrowing instead would be the fail-OPEN direction: it would let this report
82
+ * "no overlap" for rules that do collide.
83
+ */
84
+ export declare function permittedSelectors(node: PredicateNode): Selector[];
85
+ /** Selectors a context type admits, before the predicate narrows them. */
86
+ export declare function selectorsForContextType(ct: ContextType): Selector[];
87
+ /** What a rule can actually authorise: its context type narrowed by its
88
+ * predicate. An unpoliced or unreadable rule contributes no narrowing. */
89
+ export declare function effectiveSelectors(rule: ObservedRule): Selector[];
90
+ /**
91
+ * Every existing rule a signer of the intended install could name instead.
92
+ *
93
+ * A rule collides when it shares at least one signer AND at least one selector.
94
+ * Both are needed for the signer to have a choice: same signer but disjoint
95
+ * calls means no call can be rerouted, and same calls but no shared signer
96
+ * means nobody can reroute them.
97
+ */
98
+ export declare function findAuthorityOverlaps(args: {
99
+ intended: IntendedInstall;
100
+ existing: ObservedRule[];
101
+ }): AuthorityOverlap[];
@@ -0,0 +1,227 @@
1
+ // src/install/authority-overlap.ts - cross-rule authority analysis.
2
+ //
3
+ // An OZ smart account selects a context rule by CALLER DECLARATION and enforces
4
+ // only the policies of the rule that was named. A signer belonging to several
5
+ // rules therefore picks which one applies, so for any given call their
6
+ // authority is the MAXIMUM over the matching rules, never the intersection.
7
+ //
8
+ // The consequence is the one that catches people: installing a second, tighter
9
+ // rule restricts nothing. A key that also sits on an unpoliced rule is not
10
+ // constrained at all - it names that rule and the predicate never runs. This
11
+ // module detects that at install time, before the caller acts on a policy that
12
+ // looks binding and is not.
13
+ //
14
+ // Not theoretical. Proven on chain 2026-08-22: the same key, the same account
15
+ // and the same forbidden call was denied `#100` naming the policed rule and
16
+ // PERMITTED naming an unpoliced one. It happened in this project's own end-to-
17
+ // end harness, written by the author of the grammar, and was caught by review
18
+ // rather than by tooling - which is why the tooling now exists.
19
+ //
20
+ // Adapted to grammar 3 from the version published in `@crediolabs/policy-synth`
21
+ // 0.2.0, which came from the `octogate` repository and was lost when the npm
22
+ // lineage moved here. `or` and `not` are gone from the grammar, so the cases
23
+ // handling them are gone too; oracle bounds are gone from the stored document.
24
+ //
25
+ // Pure: no network. The caller supplies the account's rules.
26
+ /** Wildcard component of a `Selector`: the predicate does not pin this half. */
27
+ export const ANY = '*';
28
+ // ---- signer identity ----
29
+ /** Canonical key for signer equality. Mirrors OZ's `Signer` enum: a delegated
30
+ * signer is its address, an external signer is the verifier plus the key
31
+ * bytes, since one verifier may hold many keys. */
32
+ export function signerKey(s) {
33
+ return s.kind === 'delegated' ? `delegated:${s.address}` : `external:${s.verifier}:${s.keyBytes}`;
34
+ }
35
+ function sharedSigners(a, b) {
36
+ const bKeys = new Set(b.map(signerKey));
37
+ return a.filter((s) => bKeys.has(signerKey(s)));
38
+ }
39
+ // ---- selector extraction ----
40
+ const WILDCARD = { contract: ANY, fn: ANY };
41
+ function selectorKey(s) {
42
+ return `${s.contract} ${s.fn}`;
43
+ }
44
+ function dedupe(sels) {
45
+ const seen = new Map();
46
+ for (const s of sels)
47
+ seen.set(selectorKey(s), s);
48
+ return [...seen.values()];
49
+ }
50
+ /** Intersect one pair. `ANY` absorbs, equal literals survive, and two
51
+ * different literals cannot both hold for a single call. */
52
+ function intersectOne(a, b) {
53
+ const contract = a.contract === ANY
54
+ ? b.contract
55
+ : b.contract === ANY
56
+ ? a.contract
57
+ : a.contract === b.contract
58
+ ? a.contract
59
+ : null;
60
+ if (contract === null)
61
+ return null;
62
+ const fn = a.fn === ANY ? b.fn : b.fn === ANY ? a.fn : a.fn === b.fn ? a.fn : null;
63
+ if (fn === null)
64
+ return null;
65
+ return { contract, fn };
66
+ }
67
+ /** Intersection of two selector SETS: every compatible pairing survives. */
68
+ export function intersectSelectors(a, b) {
69
+ const out = [];
70
+ for (const x of a) {
71
+ for (const y of b) {
72
+ const hit = intersectOne(x, y);
73
+ if (hit)
74
+ out.push(hit);
75
+ }
76
+ }
77
+ return dedupe(out);
78
+ }
79
+ function literalAddress(leaf) {
80
+ return leaf.kind === 'literal_address' ? leaf.value : null;
81
+ }
82
+ function literalSymbol(leaf) {
83
+ return leaf.kind === 'literal_symbol' ? leaf.value : null;
84
+ }
85
+ /** Selector pinned by a single `eq`, whichever side the literal sits on. */
86
+ function selectorFromEq(left, right) {
87
+ if (left.kind === 'call_contract') {
88
+ const addr = literalAddress(right);
89
+ return addr === null ? null : { contract: addr, fn: ANY };
90
+ }
91
+ if (right.kind === 'call_contract') {
92
+ const addr = literalAddress(left);
93
+ return addr === null ? null : { contract: addr, fn: ANY };
94
+ }
95
+ if (left.kind === 'call_fn') {
96
+ const sym = literalSymbol(right);
97
+ return sym === null ? null : { contract: ANY, fn: sym };
98
+ }
99
+ if (right.kind === 'call_fn') {
100
+ const sym = literalSymbol(left);
101
+ return sym === null ? null : { contract: ANY, fn: sym };
102
+ }
103
+ return null;
104
+ }
105
+ /**
106
+ * The set of `(contract, fn)` selectors a predicate may permit.
107
+ *
108
+ * A deliberate OVER-approximation: every call the predicate actually permits is
109
+ * covered by some returned selector, and unrecognised structure widens to the
110
+ * wildcard rather than narrowing. That direction is what makes the emptiness
111
+ * test sound. A call carries exactly one `(contract, fn)`, so if two
112
+ * predicates' over-approximations do not intersect, no single call can be
113
+ * routed to either and the rules provably cannot collide.
114
+ *
115
+ * Narrowing instead would be the fail-OPEN direction: it would let this report
116
+ * "no overlap" for rules that do collide.
117
+ */
118
+ export function permittedSelectors(node) {
119
+ switch (node.op) {
120
+ case 'and': {
121
+ // Every conjunct must hold at once, so the permitted set is the
122
+ // intersection. Intersecting over-approximations stays one.
123
+ let acc = [WILDCARD];
124
+ for (const child of node.children)
125
+ acc = intersectSelectors(acc, permittedSelectors(child));
126
+ return acc;
127
+ }
128
+ case 'eq': {
129
+ const sel = selectorFromEq(node.left, node.right);
130
+ return sel === null ? [WILDCARD] : [sel];
131
+ }
132
+ case 'in': {
133
+ // Set membership over the selector halves: `call_fn in {a, b}` permits
134
+ // both. A haystack element that is not the matching literal kind makes
135
+ // the node uninformative rather than narrower.
136
+ if (node.needle.kind === 'call_contract') {
137
+ const addrs = node.haystack.map(literalAddress);
138
+ if (addrs.some((a) => a === null))
139
+ return [WILDCARD];
140
+ return dedupe(addrs.map((a) => ({ contract: a, fn: ANY })));
141
+ }
142
+ if (node.needle.kind === 'call_fn') {
143
+ const syms = node.haystack.map(literalSymbol);
144
+ if (syms.some((s) => s === null))
145
+ return [WILDCARD];
146
+ return dedupe(syms.map((s) => ({ contract: ANY, fn: s })));
147
+ }
148
+ return [WILDCARD];
149
+ }
150
+ default:
151
+ // `lte` binds an amount, never the selector.
152
+ return [WILDCARD];
153
+ }
154
+ }
155
+ /** Selectors a context type admits, before the predicate narrows them. */
156
+ export function selectorsForContextType(ct) {
157
+ switch (ct.kind) {
158
+ case 'default':
159
+ return [WILDCARD];
160
+ case 'call_contract':
161
+ return [{ contract: ct.contract, fn: ANY }];
162
+ case 'create_contract':
163
+ // A contract-creation context is a different `Context` shape. The
164
+ // interpreter refuses anything that is not `Context::Contract`, and a
165
+ // creation rule can never serve a call, so it shares no selector.
166
+ return [];
167
+ }
168
+ }
169
+ /** What a rule can actually authorise: its context type narrowed by its
170
+ * predicate. An unpoliced or unreadable rule contributes no narrowing. */
171
+ export function effectiveSelectors(rule) {
172
+ const fromType = selectorsForContextType(rule.contextType);
173
+ if (!rule.predicate)
174
+ return fromType;
175
+ return intersectSelectors(fromType, permittedSelectors(rule.predicate));
176
+ }
177
+ function classifyRule(rule) {
178
+ if (rule.policyAddresses.length === 0)
179
+ return 'unpoliced';
180
+ return rule.predicate ? 'interpreter' : 'foreign';
181
+ }
182
+ function adviceFor(cls, ruleId) {
183
+ switch (cls) {
184
+ case 'unpoliced':
185
+ return `rule ${ruleId} has no policy attached, so a shared signer may make these calls with no constraint at all - the predicate you are installing will never run for them. Remove the shared signer from rule ${ruleId}, or attach a policy to it.`;
186
+ case 'foreign':
187
+ return `rule ${ruleId} is policed by a contract this tool cannot decode, so its authority over these calls is unknown. Review it by hand before relying on the new rule.`;
188
+ case 'interpreter':
189
+ return `a shared signer may name rule ${ruleId} instead, so the new rule will not restrict these calls. To TIGHTEN, edit rule ${ruleId} itself rather than adding a second rule. To ADD a separate capability, keep both and expect neither to constrain the other.`;
190
+ }
191
+ }
192
+ /**
193
+ * Every existing rule a signer of the intended install could name instead.
194
+ *
195
+ * A rule collides when it shares at least one signer AND at least one selector.
196
+ * Both are needed for the signer to have a choice: same signer but disjoint
197
+ * calls means no call can be rerouted, and same calls but no shared signer
198
+ * means nobody can reroute them.
199
+ */
200
+ export function findAuthorityOverlaps(args) {
201
+ const intendedSelectors = intersectSelectors(selectorsForContextType(args.intended.contextType), permittedSelectors(args.intended.predicate));
202
+ const out = [];
203
+ for (const rule of args.existing) {
204
+ if (rule.id === args.intended.ruleId)
205
+ continue;
206
+ const shared = sharedSigners(args.intended.signers, rule.signers);
207
+ if (shared.length === 0)
208
+ continue;
209
+ const sharedSelectors = intersectSelectors(intendedSelectors, effectiveSelectors(rule));
210
+ if (sharedSelectors.length === 0)
211
+ continue;
212
+ const ruleClass = classifyRule(rule);
213
+ out.push({
214
+ ruleId: rule.id,
215
+ ruleClass,
216
+ severity: ruleClass === 'unpoliced'
217
+ ? 'bypass'
218
+ : ruleClass === 'foreign'
219
+ ? 'unknown'
220
+ : 'not-restricting',
221
+ sharedSigners: shared,
222
+ sharedSelectors,
223
+ advice: adviceFor(ruleClass, rule.id),
224
+ });
225
+ }
226
+ return out;
227
+ }
@@ -1 +1,2 @@
1
+ export { ANY, type AuthorityOverlap, type ContextType, effectiveSelectors, findAuthorityOverlaps, type IntendedInstall, intersectSelectors, type ObservedRule, type OverlapSeverity, permittedSelectors, type RuleClass, type Selector, selectorsForContextType, 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';
@@ -12,4 +12,8 @@
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. Exported because the check has to happen
16
+ // wherever an install is BUILT, and a client that assembles its own
17
+ // `add_context_rule` call never reaches `runInstallPolicy`.
18
+ export { ANY, effectiveSelectors, findAuthorityOverlaps, intersectSelectors, permittedSelectors, selectorsForContextType, signerKey, } from "./authority-overlap.js";
15
19
  export { ADD_CONTEXT_RULE_SYMBOL, buildAddContextRuleArgs, DEFAULT_GRAMMAR_VERSION, } from "./build-add-context-rule.js";
@@ -16,15 +16,21 @@ export declare function isBelowThreshold(c: ParseConfidence): boolean;
16
16
  * under-confidence recording.
17
17
  *
18
18
  * The remediation text branches on which diagnostic bucket is non-empty:
19
- * - unknownContracts only -> user MUST supply an ABI (or re-capture
20
- * against a known protocol version). The contract is real, the
21
- * recorder just cannot decode it.
22
- * - opaqueScVals only -> the recorder encountered a value shape it
23
- * should support but did not decode. The user cannot supply an ABI
24
- * to fix a decoder bug; the guidance explicitly says so and points at
25
- * re-running after a tool upgrade / reporting the path.
26
- * - both -> list both diagnostics AND chain the right remediation for
27
- * each (the user supplies an ABI AND reports the decoder gap).
28
- * - neither (the "denom === 0" path) -> unchanged from the pre-fix
29
- * text; the user did not actually hit a code-level barrier. */
19
+ * - unknownContracts only -> the contract is not in the compiled-in
20
+ * registry. NOT "the contract has no interface": most Soroban
21
+ * contracts publish a typed spec on chain, this package just never
22
+ * reads one. The reason code stays `no-abi` because it is a published
23
+ * enum value, so the TEXT has to carry the correction.
24
+ * - opaqueScVals only -> the recorder met a value shape it should
25
+ * support but did not decode. That is a decoder bug, and the guidance
26
+ * says so rather than implying the caller can fix it.
27
+ * - both -> list both diagnostics and chain the right remediation.
28
+ * - neither (the "denom === 0" path) -> the caller did not actually hit
29
+ * a code-level barrier.
30
+ *
31
+ * Do NOT tell the caller to supply an ABI. There is no input for one:
32
+ * recognition runs off the compiled-in registry plus a known-contract set
33
+ * that no public tool boundary exposes. The old text named an action
34
+ * nobody could take and sent users looking for a file they do not have and
35
+ * would not need. */
30
36
  export declare function buildLowConfidenceQuestion(c: ParseConfidence): string;
@@ -39,17 +39,23 @@ export function isBelowThreshold(c) {
39
39
  * under-confidence recording.
40
40
  *
41
41
  * The remediation text branches on which diagnostic bucket is non-empty:
42
- * - unknownContracts only -> user MUST supply an ABI (or re-capture
43
- * against a known protocol version). The contract is real, the
44
- * recorder just cannot decode it.
45
- * - opaqueScVals only -> the recorder encountered a value shape it
46
- * should support but did not decode. The user cannot supply an ABI
47
- * to fix a decoder bug; the guidance explicitly says so and points at
48
- * re-running after a tool upgrade / reporting the path.
49
- * - both -> list both diagnostics AND chain the right remediation for
50
- * each (the user supplies an ABI AND reports the decoder gap).
51
- * - neither (the "denom === 0" path) -> unchanged from the pre-fix
52
- * text; the user did not actually hit a code-level barrier. */
42
+ * - unknownContracts only -> the contract is not in the compiled-in
43
+ * registry. NOT "the contract has no interface": most Soroban
44
+ * contracts publish a typed spec on chain, this package just never
45
+ * reads one. The reason code stays `no-abi` because it is a published
46
+ * enum value, so the TEXT has to carry the correction.
47
+ * - opaqueScVals only -> the recorder met a value shape it should
48
+ * support but did not decode. That is a decoder bug, and the guidance
49
+ * says so rather than implying the caller can fix it.
50
+ * - both -> list both diagnostics and chain the right remediation.
51
+ * - neither (the "denom === 0" path) -> the caller did not actually hit
52
+ * a code-level barrier.
53
+ *
54
+ * Do NOT tell the caller to supply an ABI. There is no input for one:
55
+ * recognition runs off the compiled-in registry plus a known-contract set
56
+ * that no public tool boundary exposes. The old text named an action
57
+ * nobody could take and sent users looking for a file they do not have and
58
+ * would not need. */
53
59
  export function buildLowConfidenceQuestion(c) {
54
60
  const hasUnknown = c.unknownContracts.length > 0;
55
61
  const hasOpaque = c.opaqueScVals.length > 0;
@@ -62,16 +68,20 @@ export function buildLowConfidenceQuestion(c) {
62
68
  }
63
69
  const why = reasons.length === 0 ? 'no diagnostic reason available' : reasons.join('; ');
64
70
  const header = `Recording refused: parseConfidence ${c.overall.toFixed(3)} is below the threshold ${c.thresholdUsed.toFixed(3)}. Diagnostic: ${why}.`;
65
- // The two remediation branches are explicit so the user (or the agent)
66
- // can dispatch on the verb. The "unknown contract" branch is the only
67
- // one that asks for an ABI; the "opaque ScVal" branch asks the user to
68
- // report the path and re-run after a tool upgrade.
71
+ // The remediation branches are explicit so the user (or the agent) can
72
+ // dispatch on the verb. Neither branch asks for an ABI: there is no input
73
+ // that accepts one, and for the unknown-contract branch the contract's
74
+ // own spec is usually on chain already - it is this package that does not
75
+ // read it.
76
+ const unknownAdvice = `The contract is not in this package's built-in registry - "no-abi" means unrecognised here, not that the contract lacks an interface. ` +
77
+ `You cannot supply one: the registry is compiled in. Either build the policy without deriving it from this transaction, or re-capture against a protocol the registry covers. ` +
78
+ `Passing confidenceOverride accepts the recording as it stands, including the arguments this tool could not attribute - do that only if you have checked them yourself.`;
69
79
  if (hasUnknown && hasOpaque) {
70
- return (`${header} Supply an ABI for the unknown contract(s) or re-capture the transaction against a known protocol version; ` +
71
- `also file the opaque ScVal path against the recorder (decoder limitation) and re-run record_transaction after a tool upgrade.`);
80
+ return (`${header} ${unknownAdvice} Separately, file the opaque ScVal path against the recorder (a decoder limitation) ` +
81
+ `and re-run record_transaction after a tool upgrade.`);
72
82
  }
73
83
  if (hasUnknown) {
74
- return `${header} Supply an ABI for the unknown contract(s) or re-capture the transaction against a known protocol version, then re-run record_transaction.`;
84
+ return `${header} ${unknownAdvice}`;
75
85
  }
76
86
  if (hasOpaque) {
77
87
  return `${header} This is a recorder decoder limitation (the value shape is supported in principle but not yet decoded) - the agent cannot fix it by supplying an ABI. Report the opaque ScVal path above against the recorder and re-run record_transaction after a tool upgrade.`;
@@ -1,4 +1,5 @@
1
1
  import type { ToolResponse } from '../errors.ts';
2
+ import { type SpecFetcher } from '../registry/on-chain-spec.ts';
2
3
  import type { Network, RecordedTransaction } from '../types.ts';
3
4
  import { type RpcFetcher } from './rpc.ts';
4
5
  /** Public input shape. The brief pins:
@@ -27,6 +28,15 @@ export interface RecordInput {
27
28
  * automatically; tests can pass a deterministic stub. */
28
29
  crossNetworkFetcher?: RpcFetcher;
29
30
  confidenceOverride?: number;
31
+ /** Read a contract's own interface off chain when the compiled-in registry
32
+ * does not recognise it. Default ON: the registry covers the protocols we
33
+ * pinned by hand, and refusing everything else reported `no-abi` for
34
+ * contracts that publish a full typed spec. Set false to record against
35
+ * the registry alone (no extra RPC). */
36
+ resolveContractSpecs?: boolean;
37
+ /** Test seam for the spec lookup. Unset in production, where it is built
38
+ * from the network's pinned RPC URL. */
39
+ specFetcher?: SpecFetcher;
30
40
  }
31
41
  export type RecordResult = ToolResponse<RecordedTransaction>;
32
42
  export declare function recordTransaction(input: RecordInput): Promise<RecordResult>;
@@ -16,11 +16,40 @@
16
16
  //
17
17
  // Returns ToolResponse<RecordedTransaction> per the canonical envelope
18
18
  // defined in src/errors.ts.
19
+ import { Networks } from '@stellar/stellar-sdk';
20
+ import { resolveContractsByOnChainSpec, specFetcherFromRpc, } from "../registry/on-chain-spec.js";
19
21
  import { contractEventsToOnChainEvents, DecodeError, decodeEnvelope, decodeEnvelopeXdr, transactionEventsToOnChainEvents, } from "./decode.js";
20
22
  import { buildLowConfidenceQuestion, computeParseConfidence, isBelowThreshold, } from "./freshness.js";
21
23
  import { extractTokenMovements } from "./movements.js";
22
- import { createRpcServer } from "./rpc.js";
24
+ import { createRpcServer, PUBLIC_RPC_URLS } from "./rpc.js";
23
25
  import { validateAgainstEvents } from "./validate.js";
26
+ /** Second pass over the contracts the compiled-in registry did not recognise.
27
+ *
28
+ * Each candidate's own interface is read off chain and every call it received
29
+ * is checked against it; the ones that verify are fed back through the decoder
30
+ * as known. Re-decoding rather than patching the first result keeps ONE code
31
+ * path computing parseConfidence - a hand-adjusted count here would be a
32
+ * second implementation of the gate, free to drift from the real one.
33
+ *
34
+ * Only ever ADDS recognition. A missing spec, an unreachable RPC or a call the
35
+ * interface does not describe all leave the recording exactly as it was. */
36
+ async function resolveByOnChainSpec(input, decoded, redecode) {
37
+ if (input.resolveContractSpecs === false)
38
+ return decoded;
39
+ if (decoded.unknownContracts.length === 0)
40
+ return decoded;
41
+ const fetcher = input.specFetcher ??
42
+ specFetcherFromRpc(PUBLIC_RPC_URLS[input.network], input.network === 'mainnet' ? Networks.PUBLIC : Networks.TESTNET);
43
+ let resolved;
44
+ try {
45
+ resolved = await resolveContractsByOnChainSpec(decoded.invocations, decoded.unknownContracts.map((u) => u.contract), fetcher);
46
+ }
47
+ catch {
48
+ // A lookup failure must not fail the recording that already succeeded.
49
+ return decoded;
50
+ }
51
+ return resolved.size === 0 ? decoded : redecode(resolved);
52
+ }
24
53
  export async function recordTransaction(input) {
25
54
  if (!input.network) {
26
55
  return err('RECORDING_FAILED', 'network required', false);
@@ -76,6 +105,7 @@ export async function recordTransaction(input) {
76
105
  return err('RECORDING_FAILED', e.message, false);
77
106
  throw e;
78
107
  }
108
+ decoded = await resolveByOnChainSpec(input, decoded, (known) => decodeEnvelope(fetched.envelopeXdr, events, [], fetched.ledger, known, input.network));
79
109
  return finish(input.network, decoded, input.confidenceOverride);
80
110
  }
81
111
  // XDR mode has no raw on-chain events, so the events-based cross-check is
@@ -93,6 +123,7 @@ export async function recordTransaction(input) {
93
123
  return err('RECORDING_FAILED', e.message, false);
94
124
  return err('RECORDING_FAILED', `failed to decode base64 envelope XDR: ${e.message}`, false);
95
125
  }
126
+ decoded = await resolveByOnChainSpec(input, decoded, (known) => decodeEnvelopeXdr(xdrStr, [], [], 0, known, input.network));
96
127
  return finish(input.network, decoded, input.confidenceOverride);
97
128
  }
98
129
  function combineEvents(raw) {
@@ -14,6 +14,10 @@ export interface SorobanTxResponse {
14
14
  events: rpc.Api.TransactionEvents;
15
15
  }
16
16
  export type RpcFetcher = (hash: string) => Promise<SorobanTxResponse | null>;
17
+ /** Exported so the on-chain spec lookup reads from the SAME endpoint the
18
+ * recorder fetched the transaction from. Two different endpoints could
19
+ * disagree about what a contract is. */
20
+ export declare const PUBLIC_RPC_URLS: Record<Network, string>;
17
21
  /** Build a fetcher backed by the public Soroban RPC for the given network.
18
22
  * Injectable by tests via the `fetcher` parameter to `recordTransaction`. */
19
23
  export declare function createRpcServer(network: Network): RpcFetcher;
@@ -4,7 +4,10 @@
4
4
  // Unit tests inject a fetcher so they never hit the network; the integration test
5
5
  // uses the real Soroban RPC through `createRpcServer`.
6
6
  import { rpc } from '@stellar/stellar-sdk';
7
- const PUBLIC_RPC_URLS = {
7
+ /** Exported so the on-chain spec lookup reads from the SAME endpoint the
8
+ * recorder fetched the transaction from. Two different endpoints could
9
+ * disagree about what a contract is. */
10
+ export const PUBLIC_RPC_URLS = {
8
11
  testnet: 'https://soroban-testnet.stellar.org',
9
12
  // The brief pins testnet; mainnet is left to the caller via injection. We keep
10
13
  // a public default that matches the brief's note ("e.g. https://mainnet.sorobanrpc.com").
@@ -1,5 +1,5 @@
1
1
  import type { ScVal } from '../types.ts';
2
- import type { ProtocolId } from './protocols.ts';
2
+ import type { AbiArg, ProtocolId } from './protocols.ts';
3
3
  export interface IdentifiedProtocol {
4
4
  protocol: ProtocolId;
5
5
  fn: string;
@@ -9,3 +9,12 @@ export interface IdentifiedProtocol {
9
9
  * off, or unknown method on a pinned address). The caller MUST keep the
10
10
  * null path fail-closed. */
11
11
  export declare function identifyProtocol(contract: string, method: string, args: ScVal[], network?: 'mainnet' | 'testnet'): IdentifiedProtocol | null;
12
+ /** Compare the decoded args against the ABI signature. Returns true only when
13
+ * the arg count matches AND every arg's ScVal subset type matches the ABI's
14
+ * declared type. `other` is intentionally NOT a valid ABI match - it means
15
+ * the decoder couldn't classify the value, which is exactly the signal
16
+ * fail-closed should refuse. */
17
+ /** Exported so the on-chain-spec path checks a call the SAME way a pinned
18
+ * protocol does. Reimplementing it there would let the two drift, and a
19
+ * looser copy would be the fail-OPEN direction. */
20
+ export declare function argsMatchAbi(expected: AbiArg[], actual: ScVal[]): boolean;
@@ -88,7 +88,10 @@ export function identifyProtocol(contract, method, args, network) {
88
88
  * declared type. `other` is intentionally NOT a valid ABI match - it means
89
89
  * the decoder couldn't classify the value, which is exactly the signal
90
90
  * fail-closed should refuse. */
91
- function argsMatchAbi(expected, actual) {
91
+ /** Exported so the on-chain-spec path checks a call the SAME way a pinned
92
+ * protocol does. Reimplementing it there would let the two drift, and a
93
+ * looser copy would be the fail-OPEN direction. */
94
+ export function argsMatchAbi(expected, actual) {
92
95
  if (expected.length !== actual.length)
93
96
  return false;
94
97
  for (let i = 0; i < expected.length; i += 1) {
@@ -0,0 +1,37 @@
1
+ import { contract as sdkContract } from '@stellar/stellar-sdk';
2
+ import type { ContractInvocation } from '../types.ts';
3
+ import type { AbiArgType, ProtocolAbi } from './protocols.ts';
4
+ /** Map an XDR spec type to the ScVal subset vocabulary the matcher uses.
5
+ *
6
+ * Returns null for a type the recorder's ScVal subset cannot represent. That
7
+ * is deliberate: an argument we cannot type is an argument we cannot check,
8
+ * and claiming a match on it would be the fail-OPEN direction. A function
9
+ * with any such argument is dropped from the derived ABI, so a call to it
10
+ * stays unrecognised rather than being waved through. */
11
+ export declare function abiTypeFromSpecType(specTypeName: string): AbiArgType | null;
12
+ /** The RPC surface this module needs. Narrowed to one method so a test can
13
+ * supply a stub without standing up a server, and so the recorder's existing
14
+ * RPC client can be passed straight in. */
15
+ export interface SpecFetcher {
16
+ contractSpec(contractId: string): Promise<sdkContract.Spec | null>;
17
+ }
18
+ /** Build a `SpecFetcher` over the SDK's contract client. */
19
+ export declare function specFetcherFromRpc(rpcUrl: string, networkPassphrase: string): SpecFetcher;
20
+ /** Convert a fetched spec into the ABI shape `identifyProtocol` already
21
+ * matches against. Functions with an argument outside the ScVal subset are
22
+ * OMITTED rather than partially typed. */
23
+ export declare function abiFromSpec(spec: sdkContract.Spec): ProtocolAbi;
24
+ /** Fetch and convert in one step. Returns null when no usable interface was
25
+ * obtained, which the caller must treat as "unrecognised". */
26
+ export declare function fetchContractAbi(contractId: string, fetcher: SpecFetcher): Promise<ProtocolAbi | null>;
27
+ /** Contracts whose EVERY recorded call matches their own published interface.
28
+ *
29
+ * All-or-nothing per contract, deliberately. A contract where one call
30
+ * verifies and another does not is a contract we do not understand, and
31
+ * marking it recognised would raise confidence on the strength of the call
32
+ * we happened to check. The unverified call is the one that matters.
33
+ *
34
+ * A contract with no fetchable spec, or a call naming a function absent from
35
+ * it, simply stays unknown - this only ever ADDS recognition, so a failure
36
+ * here degrades to today's behaviour rather than to a wrong answer. */
37
+ export declare function resolveContractsByOnChainSpec(invocations: ReadonlyArray<ContractInvocation>, candidates: ReadonlyArray<string>, fetcher: SpecFetcher): Promise<Set<string>>;