@crediolabs/policy-synth 0.2.0 → 0.3.1

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 (249) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/errors.d.ts +1 -1
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +1 -4
  7. package/dist/install/build-add-context-rule.d.ts +3 -19
  8. package/dist/install/build-add-context-rule.js +3 -98
  9. package/dist/install/build-install-policy.d.ts +4 -53
  10. package/dist/install/build-install-policy.js +44 -123
  11. package/dist/install/index.d.ts +0 -2
  12. package/dist/install/index.js +0 -7
  13. package/dist/predicate/decode.d.ts +1 -1
  14. package/dist/predicate/decode.js +2 -70
  15. package/dist/predicate/encode.js +45 -229
  16. package/dist/predicate/from-json.js +1 -42
  17. package/dist/record/decode.js +3 -8
  18. package/dist/record/freshness.d.ts +17 -11
  19. package/dist/record/freshness.js +28 -18
  20. package/dist/review-card/builder.d.ts +4 -3
  21. package/dist/review-card/builder.js +18 -162
  22. package/dist/review-card/cross-check.js +2 -105
  23. package/dist/review-card/render-leaf.d.ts +4 -0
  24. package/dist/review-card/render-leaf.js +47 -0
  25. package/dist/run/index.d.ts +36 -139
  26. package/dist/run/index.js +125 -437
  27. package/dist/run/schemas.d.ts +168 -1929
  28. package/dist/run/schemas.js +40 -269
  29. package/dist/{synth → simulate}/deny-cases.d.ts +4 -8
  30. package/dist/simulate/deny-cases.js +282 -0
  31. package/dist/simulate/evaluate.d.ts +18 -0
  32. package/dist/simulate/evaluate.js +271 -0
  33. package/dist/simulate/index.d.ts +4 -0
  34. package/dist/simulate/index.js +8 -0
  35. package/dist/synth/compose-from-recording.d.ts +24 -51
  36. package/dist/synth/compose-from-recording.js +120 -282
  37. package/dist/synth/index.d.ts +0 -5
  38. package/dist/synth/index.js +0 -5
  39. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  40. package/dist/synth/synthesize-from-recording.js +41 -356
  41. package/dist/types.d.ts +8 -60
  42. package/dist/types.js +5 -2
  43. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  44. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  45. package/dist-cjs/errors.d.ts +1 -1
  46. package/dist-cjs/index.d.ts +1 -4
  47. package/dist-cjs/index.js +1 -4
  48. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  49. package/dist-cjs/install/build-add-context-rule.js +1 -97
  50. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  51. package/dist-cjs/install/build-install-policy.js +44 -122
  52. package/dist-cjs/install/index.d.ts +0 -2
  53. package/dist-cjs/install/index.js +2 -23
  54. package/dist-cjs/predicate/decode.d.ts +1 -1
  55. package/dist-cjs/predicate/decode.js +2 -70
  56. package/dist-cjs/predicate/encode.js +45 -229
  57. package/dist-cjs/predicate/from-json.js +1 -42
  58. package/dist-cjs/record/decode.js +3 -8
  59. package/dist-cjs/record/freshness.d.ts +17 -11
  60. package/dist-cjs/record/freshness.js +28 -18
  61. package/dist-cjs/review-card/builder.d.ts +4 -3
  62. package/dist-cjs/review-card/builder.js +23 -167
  63. package/dist-cjs/review-card/cross-check.js +7 -110
  64. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  65. package/dist-cjs/review-card/render-leaf.js +52 -0
  66. package/dist-cjs/run/index.d.ts +36 -139
  67. package/dist-cjs/run/index.js +125 -444
  68. package/dist-cjs/run/schemas.d.ts +168 -1929
  69. package/dist-cjs/run/schemas.js +41 -270
  70. package/dist-cjs/{synth → simulate}/deny-cases.d.ts +4 -8
  71. package/dist-cjs/simulate/deny-cases.js +286 -0
  72. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  73. package/dist-cjs/simulate/evaluate.js +274 -0
  74. package/dist-cjs/simulate/index.d.ts +4 -0
  75. package/dist-cjs/simulate/index.js +13 -0
  76. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  77. package/dist-cjs/synth/compose-from-recording.js +120 -282
  78. package/dist-cjs/synth/index.d.ts +0 -5
  79. package/dist-cjs/synth/index.js +1 -11
  80. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  81. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  82. package/dist-cjs/types.d.ts +8 -60
  83. package/dist-cjs/types.js +6 -3
  84. package/package.json +5 -5
  85. package/src/adapters/interpreter/adapter.ts +76 -572
  86. package/src/errors.ts +0 -19
  87. package/src/index.ts +1 -4
  88. package/src/install/build-add-context-rule.ts +5 -139
  89. package/src/install/build-install-policy.ts +93 -214
  90. package/src/install/index.ts +0 -34
  91. package/src/predicate/decode.ts +2 -70
  92. package/src/predicate/encode.ts +49 -261
  93. package/src/predicate/from-json.ts +1 -43
  94. package/src/record/decode.ts +3 -8
  95. package/src/record/freshness.ts +29 -18
  96. package/src/review-card/builder.ts +19 -168
  97. package/src/review-card/cross-check.ts +3 -105
  98. package/src/review-card/render-leaf.ts +48 -0
  99. package/src/run/index.ts +144 -572
  100. package/src/run/schemas.ts +42 -291
  101. package/src/simulate/deny-cases.ts +334 -0
  102. package/src/simulate/evaluate.ts +284 -0
  103. package/src/simulate/index.ts +11 -0
  104. package/src/synth/compose-from-recording.ts +148 -347
  105. package/src/synth/index.ts +0 -13
  106. package/src/synth/synthesize-from-recording.ts +43 -456
  107. package/src/types.ts +13 -49
  108. package/dist/adapters/interpreter/index.d.ts +0 -1
  109. package/dist/adapters/interpreter/index.js +0 -2
  110. package/dist/adapters/oz/adapter.d.ts +0 -20
  111. package/dist/adapters/oz/adapter.js +0 -295
  112. package/dist/adapters/oz/index.d.ts +0 -1
  113. package/dist/adapters/oz/index.js +0 -2
  114. package/dist/codegen/compile-gate.d.ts +0 -33
  115. package/dist/codegen/compile-gate.js +0 -124
  116. package/dist/codegen/index.d.ts +0 -2
  117. package/dist/codegen/index.js +0 -8
  118. package/dist/codegen/template.d.ts +0 -18
  119. package/dist/codegen/template.js +0 -148
  120. package/dist/install/authority-overlap.d.ts +0 -134
  121. package/dist/install/authority-overlap.js +0 -0
  122. package/dist/install/build-install-predicate.d.ts +0 -96
  123. package/dist/install/build-install-predicate.js +0 -444
  124. package/dist/install/build-merge-policy.d.ts +0 -70
  125. package/dist/install/build-merge-policy.js +0 -130
  126. package/dist/install/plan-merge-policy.d.ts +0 -49
  127. package/dist/install/plan-merge-policy.js +0 -86
  128. package/dist/install/read-account-rules.d.ts +0 -100
  129. package/dist/install/read-account-rules.js +0 -283
  130. package/dist/ir/index.d.ts +0 -1
  131. package/dist/ir/index.js +0 -2
  132. package/dist/ir/types.d.ts +0 -140
  133. package/dist/ir/types.js +0 -11
  134. package/dist/mandate/index.d.ts +0 -2
  135. package/dist/mandate/index.js +0 -2
  136. package/dist/mandate/to-ir.d.ts +0 -3
  137. package/dist/mandate/to-ir.js +0 -60
  138. package/dist/mandate/types.d.ts +0 -20
  139. package/dist/mandate/types.js +0 -8
  140. package/dist/seams/index.d.ts +0 -1
  141. package/dist/seams/index.js +0 -2
  142. package/dist/seams/types.d.ts +0 -66
  143. package/dist/seams/types.js +0 -11
  144. package/dist/synth/deny-cases.js +0 -562
  145. package/dist/synth/evaluate.d.ts +0 -39
  146. package/dist/synth/evaluate.js +0 -551
  147. package/dist/synth/harness.d.ts +0 -28
  148. package/dist/synth/harness.js +0 -47
  149. package/dist/synth/minimize.d.ts +0 -4
  150. package/dist/synth/minimize.js +0 -38
  151. package/dist/synth/permit-context.d.ts +0 -15
  152. package/dist/synth/permit-context.js +0 -116
  153. package/dist/synth/predicate-literals.d.ts +0 -5
  154. package/dist/synth/predicate-literals.js +0 -25
  155. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  156. package/dist/synth/synthesize-from-mandate.js +0 -59
  157. package/dist/verify/envelope.d.ts +0 -15
  158. package/dist/verify/envelope.js +0 -22
  159. package/dist/verify/index.d.ts +0 -3
  160. package/dist/verify/index.js +0 -3
  161. package/dist/verify/simulate.d.ts +0 -31
  162. package/dist/verify/simulate.js +0 -258
  163. package/dist/verify/verify.d.ts +0 -21
  164. package/dist/verify/verify.js +0 -189
  165. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  166. package/dist-cjs/adapters/interpreter/index.js +0 -8
  167. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  168. package/dist-cjs/adapters/oz/adapter.js +0 -300
  169. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  170. package/dist-cjs/adapters/oz/index.js +0 -8
  171. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  172. package/dist-cjs/codegen/compile-gate.js +0 -128
  173. package/dist-cjs/codegen/index.d.ts +0 -2
  174. package/dist-cjs/codegen/index.js +0 -14
  175. package/dist-cjs/codegen/template.d.ts +0 -18
  176. package/dist-cjs/codegen/template.js +0 -151
  177. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  178. package/dist-cjs/install/authority-overlap.js +0 -0
  179. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  180. package/dist-cjs/install/build-install-predicate.js +0 -479
  181. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  182. package/dist-cjs/install/build-merge-policy.js +0 -134
  183. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  184. package/dist-cjs/install/plan-merge-policy.js +0 -90
  185. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  186. package/dist-cjs/install/read-account-rules.js +0 -296
  187. package/dist-cjs/ir/index.d.ts +0 -1
  188. package/dist-cjs/ir/index.js +0 -3
  189. package/dist-cjs/ir/types.d.ts +0 -140
  190. package/dist-cjs/ir/types.js +0 -12
  191. package/dist-cjs/mandate/index.d.ts +0 -2
  192. package/dist-cjs/mandate/index.js +0 -6
  193. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  194. package/dist-cjs/mandate/to-ir.js +0 -63
  195. package/dist-cjs/mandate/types.d.ts +0 -20
  196. package/dist-cjs/mandate/types.js +0 -9
  197. package/dist-cjs/seams/index.d.ts +0 -1
  198. package/dist-cjs/seams/index.js +0 -3
  199. package/dist-cjs/seams/types.d.ts +0 -66
  200. package/dist-cjs/seams/types.js +0 -12
  201. package/dist-cjs/synth/deny-cases.js +0 -568
  202. package/dist-cjs/synth/evaluate.d.ts +0 -39
  203. package/dist-cjs/synth/evaluate.js +0 -554
  204. package/dist-cjs/synth/harness.d.ts +0 -28
  205. package/dist-cjs/synth/harness.js +0 -50
  206. package/dist-cjs/synth/minimize.d.ts +0 -4
  207. package/dist-cjs/synth/minimize.js +0 -41
  208. package/dist-cjs/synth/permit-context.d.ts +0 -15
  209. package/dist-cjs/synth/permit-context.js +0 -119
  210. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  211. package/dist-cjs/synth/predicate-literals.js +0 -28
  212. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  213. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  214. package/dist-cjs/verify/envelope.d.ts +0 -15
  215. package/dist-cjs/verify/envelope.js +0 -23
  216. package/dist-cjs/verify/index.d.ts +0 -3
  217. package/dist-cjs/verify/index.js +0 -8
  218. package/dist-cjs/verify/simulate.d.ts +0 -31
  219. package/dist-cjs/verify/simulate.js +0 -261
  220. package/dist-cjs/verify/verify.d.ts +0 -21
  221. package/dist-cjs/verify/verify.js +0 -192
  222. package/src/adapters/interpreter/index.ts +0 -8
  223. package/src/adapters/oz/adapter.ts +0 -376
  224. package/src/adapters/oz/index.ts +0 -9
  225. package/src/codegen/compile-gate.ts +0 -167
  226. package/src/codegen/index.ts +0 -17
  227. package/src/codegen/template.ts +0 -165
  228. package/src/install/authority-overlap.ts +0 -0
  229. package/src/install/build-merge-policy.ts +0 -219
  230. package/src/install/plan-merge-policy.ts +0 -133
  231. package/src/install/read-account-rules.ts +0 -376
  232. package/src/ir/index.ts +0 -13
  233. package/src/ir/types.ts +0 -132
  234. package/src/mandate/index.ts +0 -4
  235. package/src/mandate/to-ir.ts +0 -71
  236. package/src/mandate/types.ts +0 -21
  237. package/src/seams/index.ts +0 -11
  238. package/src/seams/types.ts +0 -81
  239. package/src/synth/deny-cases.ts +0 -663
  240. package/src/synth/evaluate.ts +0 -613
  241. package/src/synth/harness.ts +0 -68
  242. package/src/synth/minimize.ts +0 -48
  243. package/src/synth/permit-context.ts +0 -136
  244. package/src/synth/predicate-literals.ts +0 -27
  245. package/src/synth/synthesize-from-mandate.ts +0 -82
  246. package/src/verify/envelope.ts +0 -28
  247. package/src/verify/index.ts +0 -5
  248. package/src/verify/simulate.ts +0 -311
  249. package/src/verify/verify.ts +0 -243
@@ -1,128 +0,0 @@
1
- "use strict";
2
- // src/codegen/compile-gate.ts - toolchain-gated `cargo check` for the
3
- // codegen escape hatch.
4
- //
5
- // The escape hatch ships as the `policy-builder escape-hatch` CLI subcommand
6
- // (a later phase). This gate is its safety net, NOT the happy path. Property:
7
- // generated Rust compiles against the pinned OZ crate; broken source returns
8
- // `COMPILE_GATE_FAILED` with `stderr`; an absent toolchain returns `SKIPPED`
9
- // (does NOT fail - we cannot make build tools a hard runtime requirement for
10
- // a TypeScript package).
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.hasRustToolchain = hasRustToolchain;
13
- exports.compileCheck = compileCheck;
14
- const node_child_process_1 = require("node:child_process");
15
- const promises_1 = require("node:fs/promises");
16
- const node_os_1 = require("node:os");
17
- const node_path_1 = require("node:path");
18
- /** Probe the host for the Rust toolchain the gate requires. We require BOTH
19
- * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
20
- * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
21
- async function hasRustToolchain() {
22
- const probe = await probeToolchain();
23
- return probe.present;
24
- }
25
- async function probeToolchain() {
26
- const cargo = await which('cargo');
27
- if (!cargo)
28
- return { present: false, reason: 'cargo not found on PATH' };
29
- const stellar = await which('stellar');
30
- if (!stellar)
31
- return { present: false, reason: 'stellar not found on PATH' };
32
- return { present: true, reason: `${cargo} + ${stellar}` };
33
- }
34
- async function which(bin) {
35
- try {
36
- const out = await runProcess('sh', ['-c', `command -v ${bin}`], { capture: true });
37
- const path = out.stdout.trim();
38
- return path.length > 0 ? path : null;
39
- }
40
- catch {
41
- return null;
42
- }
43
- }
44
- function runProcess(cmd, args, opts) {
45
- return new Promise((resolve, reject) => {
46
- if (opts.signal?.aborted) {
47
- reject(new Error('aborted'));
48
- return;
49
- }
50
- const child = (0, node_child_process_1.spawn)(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
51
- let stdout = '';
52
- let stderr = '';
53
- child.stdout.on('data', (b) => {
54
- stdout += b.toString('utf8');
55
- });
56
- child.stderr.on('data', (b) => {
57
- stderr += b.toString('utf8');
58
- });
59
- const onAbort = () => {
60
- child.kill('SIGTERM');
61
- reject(new Error('aborted'));
62
- };
63
- opts.signal?.addEventListener('abort', onAbort, { once: true });
64
- child.on('error', (e) => {
65
- opts.signal?.removeEventListener('abort', onAbort);
66
- reject(e);
67
- });
68
- child.on('close', (code) => {
69
- opts.signal?.removeEventListener('abort', onAbort);
70
- resolve({ stdout, stderr, code: code ?? -1 });
71
- });
72
- });
73
- }
74
- const CARGO_MANIFEST = `[package]
75
- name = "escape-hatch-gate"
76
- version = "0.0.0"
77
- edition = "2021"
78
- publish = false
79
-
80
- [lib]
81
- crate-type = ["cdylib"]
82
- # The gate writes the source beside the manifest rather than under src/, so
83
- # the path is stated. Without it cargo looks for src/lib.rs and fails to
84
- # parse the manifest before it ever compiles anything, which reads as a
85
- # broken generator rather than a broken scaffold.
86
- path = "lib.rs"
87
-
88
- [dependencies]
89
- soroban-sdk = "22"
90
-
91
- [workspace]
92
- `;
93
- /** Compile-check a Rust source string against the pinned Soroban SDK.
94
- *
95
- * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
96
- * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
97
- * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
98
- *
99
- * The gate writes the source to a temporary crate and runs `cargo check`
100
- * against it; the crate is cleaned up whether or not compilation succeeds.
101
- * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
102
- * user (the LLM agent) so the user can iterate. */
103
- async function compileCheck(rustSource, opts = {}) {
104
- if (opts.signal?.aborted) {
105
- return { code: 'SKIPPED', reason: 'aborted before probe' };
106
- }
107
- const probe = await probeToolchain();
108
- if (!probe.present) {
109
- return { code: 'SKIPPED', reason: probe.reason };
110
- }
111
- let dir = null;
112
- try {
113
- dir = await (0, promises_1.mkdtemp)((0, node_path_1.join)(opts.tempDir ?? (0, node_os_1.tmpdir)(), 'codegen-gate-'));
114
- await (0, promises_1.writeFile)((0, node_path_1.join)(dir, 'Cargo.toml'), CARGO_MANIFEST);
115
- await (0, promises_1.writeFile)((0, node_path_1.join)(dir, 'lib.rs'), rustSource);
116
- const runOpts = opts.signal ? { signal: opts.signal } : {};
117
- const result = await runProcess(opts.cargoBin ?? 'cargo', ['check', '--quiet', '--offline', '--manifest-path', (0, node_path_1.join)(dir, 'Cargo.toml')], runOpts).catch((e) => ({ stdout: '', stderr: e.message, code: -1 }));
118
- if (result.code === 0) {
119
- return { code: 'COMPILE_OK' };
120
- }
121
- return { code: 'COMPILE_GATE_FAILED', stderr: result.stderr || result.stdout };
122
- }
123
- finally {
124
- if (dir) {
125
- await (0, promises_1.rm)(dir, { recursive: true, force: true }).catch(() => { });
126
- }
127
- }
128
- }
@@ -1,2 +0,0 @@
1
- export { type CompileGateOpts, type CompileGateResult, compileCheck, hasRustToolchain, } from './compile-gate.ts';
2
- export { type EscapeHatchSpec, generateRust, } from './template.ts';
@@ -1,14 +0,0 @@
1
- "use strict";
2
- // src/codegen/index.ts - re-export the codegen escape-hatch surface.
3
- //
4
- // The escape hatch is OUT of the audited happy path: the synthesiser never
5
- // calls `generateRust` itself; the CLI subcommand (a later phase) is the only
6
- // entry point. Keeping the surface in one file makes that boundary visible
7
- // in import statements.
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.generateRust = exports.hasRustToolchain = exports.compileCheck = void 0;
10
- var compile_gate_ts_1 = require("./compile-gate.js");
11
- Object.defineProperty(exports, "compileCheck", { enumerable: true, get: function () { return compile_gate_ts_1.compileCheck; } });
12
- Object.defineProperty(exports, "hasRustToolchain", { enumerable: true, get: function () { return compile_gate_ts_1.hasRustToolchain; } });
13
- var template_ts_1 = require("./template.js");
14
- Object.defineProperty(exports, "generateRust", { enumerable: true, get: function () { return template_ts_1.generateRust; } });
@@ -1,18 +0,0 @@
1
- /** A small typed description of one uncovered constraint the v1 DSL refused
2
- * to express. The synthesiser surfaces these from `CompileResult.uncovered`
3
- * and the codegen escape hatch wraps them into a hand-auditable skeleton. */
4
- export interface EscapeHatchSpec {
5
- /** Address of the policy contract the skeleton is generated for. */
6
- contract: string;
7
- /** The trait method the predicate lives inside (default: 'enforce'). */
8
- fnName?: string;
9
- /** Human-readable description of each construct the DSL could not cover. */
10
- uncovered: string[];
11
- }
12
- /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
13
- *
14
- * The skeleton is NOT a finished policy; the user fills in the predicate
15
- * logic in the marked TODO(user) holes and audits the result themselves.
16
- *
17
- * Same `(spec, name)` always produces byte-identical output. */
18
- export declare function generateRust(spec: EscapeHatchSpec, name: string): string;
@@ -1,151 +0,0 @@
1
- "use strict";
2
- // src/codegen/template.ts - deterministic Rust source generator for the OZ
3
- // `Policy` escape-hatch skeleton.
4
- //
5
- // SUPERSEDED. The architecture this belongs to no longer exists. A deployed
6
- // policy involves exactly two contracts, the OZ smart account and one
7
- // immutable interpreter, and the synthesiser emits policy DATA rather than
8
- // code. Nothing on the synthesis path reaches this module, and no install can
9
- // produce a contract from it. When a constraint falls outside the grammar the
10
- // answer is to version the synthesiser and the interpreter together, not to
11
- // put unaudited Rust on chain per policy.
12
- //
13
- // Deleting it is a decision nobody has taken yet, not a dependency question.
14
- // `compile-gate.ts` takes a Rust string and knows nothing about this module,
15
- // and its tests compile a hardcoded fixture, so the gate keeps working either
16
- // way. What deleting this would remove is the only in-repo producer of policy
17
- // Rust for the gate to check. Do not read its presence as the product
18
- // generating contracts, and do not wire it into the synthesis path.
19
- //
20
- // What follows describes the abandoned design.
21
- //
22
- // This is the LAST-RESORT tool for constraints the v1 DSL cannot express. It
23
- // lives OUT of the audited happy-path surface; the synthesiser never emits it
24
- // automatically. It mirrors Zodiac Roles' `Custom` operator: a hand-written
25
- // (here: scaffolded) policy the operator assumes responsibility for.
26
- //
27
- // The skeleton carries five storage invariants the user MUST preserve when
28
- // filling in the predicate logic:
29
- // 1. `smart_account.require_auth()` is invoked INSIDE `enforce`.
30
- // 2. Storage is keyed by the composite `(smart_account, rule_id)`.
31
- // 3. Chain reads use `unwrap_or_default()` so a missing key is a permitted
32
- // default, not a panic.
33
- // 4. Storage is `persistent()` (NOT `instance()`) so the policy survives
34
- // contract instance lifecycle changes.
35
- // 5. `uninstall` removes the stored state.
36
- //
37
- // Determinism: same `(spec, name)` -> byte-identical output. No clock, no RNG,
38
- // no environment reads.
39
- Object.defineProperty(exports, "__esModule", { value: true });
40
- exports.generateRust = generateRust;
41
- /** Format a name for use as a Rust identifier. The input is constrained by
42
- * the caller (a kebab-case policy name + alphanumeric addresses); this is a
43
- * belt-and-braces sanitiser that maps anything non-identifier to '_'. */
44
- function asRustIdent(s) {
45
- let out = '';
46
- for (let i = 0; i < s.length; i++) {
47
- const ch = s.charCodeAt(i);
48
- const ok = (ch >= 48 && ch <= 57) || // 0-9
49
- (ch >= 65 && ch <= 90) || // A-Z
50
- (ch >= 97 && ch <= 122) || // a-z
51
- ch === 95; // _
52
- out += ok ? s[i] : '_';
53
- }
54
- // Identifiers may not start with a digit.
55
- if (out.length > 0 && out.charCodeAt(0) >= 48 && out.charCodeAt(0) <= 57) {
56
- out = `_${out}`;
57
- }
58
- return out || 'policy';
59
- }
60
- /** Render the `uncovered` list as a `//` comment block (one line per item). */
61
- function renderUncovered(uncovered) {
62
- if (uncovered.length === 0) {
63
- return ' // (no specific uncovered constructs reported)';
64
- }
65
- return uncovered.map((line) => ` // - ${line}`).join('\n');
66
- }
67
- /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
68
- *
69
- * The skeleton is NOT a finished policy; the user fills in the predicate
70
- * logic in the marked TODO(user) holes and audits the result themselves.
71
- *
72
- * Same `(spec, name)` always produces byte-identical output. */
73
- function generateRust(spec, name) {
74
- const _contract = spec.contract;
75
- const _fnName = spec.fnName ?? 'enforce';
76
- const structName = asRustIdent(name);
77
- const _dataKeyName = `${asRustIdent(name)}_data`;
78
- const uncoveredBlock = renderUncovered(spec.uncovered);
79
- return `// Auto-generated by the OZ Policy Builder codegen escape hatch.
80
- // THIS OUTPUT IS THE USER'S TO COMPLETE AND AUDIT.
81
- // The synthesiser never emits it on the happy path; reach for it only when
82
- // a constraint cannot be expressed in the v1 DSL grammar (same shape as
83
- // Zodiac Roles' \`Custom\` operator).
84
-
85
- #![no_std]
86
-
87
- use soroban_sdk::{contract, contractimpl, contracttype, Address, Env, Vec};
88
-
89
- #[contracttype]
90
- pub enum DataKey {
91
- /// Composite key \`(smart_account, rule_id)\` so multiple policies on
92
- /// one smart account coexist without collision.
93
- State(Address, u32),
94
- }
95
-
96
- #[contract]
97
- pub struct ${structName};
98
-
99
- #[contractimpl]
100
- impl ${structName} {
101
- pub fn install(e: &Env, smart_account: Address, rule_id: u32) {
102
- // TODO(user): initialise policy state for this (smart_account, rule_id).
103
- // The skeleton leaves the stored value empty; the predicate body
104
- // (in \`enforce\`) decides what to read.
105
- e.storage().persistent().set(
106
- &DataKey::State(smart_account.clone(), rule_id),
107
- &(),
108
- );
109
- }
110
-
111
- pub fn enforce(
112
- e: &Env,
113
- smart_account: Address,
114
- rule_id: u32,
115
- _signers: Vec<Address>,
116
- ) {
117
- // Invariant 1: authorise the smart account BEFORE any state read or
118
- // predicate evaluation. Removing this call opens the policy to
119
- // impersonation by any caller with a valid rule_id.
120
- smart_account.require_auth();
121
-
122
- // Invariant 2 + 4: read stored state through the composite key on
123
- // \`persistent()\` storage. \`unwrap_or_default()\` (invariant 3)
124
- // makes an empty key a permitted default rather than a panic.
125
- let _state: () = e
126
- .storage()
127
- .persistent()
128
- .get(&DataKey::State(smart_account.clone(), rule_id))
129
- .unwrap_or_default();
130
-
131
- // --- uncovered constraints the v1 DSL refused to express ---
132
- ${uncoveredBlock}
133
-
134
- // TODO(user): replace the placeholder below with the real predicate
135
- // body. The recorded flow's \`(contract, fn_name, args)\` is the
136
- // single authorised call \`Policy::enforce\` receives; match against
137
- // \`e\` here.
138
- let _ = (_state, &e);
139
- }
140
-
141
- pub fn uninstall(e: &Env, smart_account: Address, rule_id: u32) {
142
- // Invariant 5: \`uninstall\` removes the stored state so a subsequent
143
- // install starts from a clean slate (and the nonce returns to its
144
- // post-uninstall value).
145
- e.storage()
146
- .persistent()
147
- .remove(&DataKey::State(smart_account, rule_id));
148
- }
149
- }
150
- `;
151
- }
@@ -1,134 +0,0 @@
1
- import type { PredicateNode, SignerDraft } from '../types.ts';
2
- /** Wildcard component of a `Selector`: the predicate does not pin this half. */
3
- export declare const ANY = "*";
4
- /** A (contract, function) pair a predicate may permit. `ANY` in either half
5
- * means unconstrained, so `{contract: ANY, fn: ANY}` is "any call at all". */
6
- export interface Selector {
7
- contract: string;
8
- fn: string;
9
- }
10
- export type ContextType = {
11
- kind: 'default';
12
- } | {
13
- kind: 'call_contract';
14
- address: string;
15
- } | {
16
- kind: 'create_contract';
17
- wasmHash: string;
18
- };
19
- /** How much we can say about a neighbouring rule.
20
- * - `interpreter`: policed by our interpreter and the predicate was readable,
21
- * so its authority is known exactly and it can be merged.
22
- * - `foreign`: policed by some other contract. The address is visible, the
23
- * semantics are not, so it must be reviewed by hand.
24
- * - `unpoliced`: no policy at all. Whatever the rule's context type allows,
25
- * its signers may do without constraint. */
26
- export type RuleClass = 'interpreter' | 'foreign' | 'unpoliced';
27
- export interface ObservedRule {
28
- id: number;
29
- contextType: ContextType;
30
- signers: SignerDraft[];
31
- /** Policy contract addresses attached to the rule, in OZ's order. */
32
- policyAddresses: string[];
33
- /** OZ's global registry ids for those policies, index-aligned with
34
- * `policyAddresses`. `remove_policy` takes the id, not the address, so
35
- * detaching a policy is impossible without them. */
36
- policyIds?: number[];
37
- /** Per-policy oracle bounds from the stored document, when it was
38
- * readable. A merge must re-install these or it silently widens them. */
39
- oracleBounds?: {
40
- maxStalenessSeconds?: number;
41
- maxDeviationBps?: number;
42
- maxCrossFeedDeviationBps?: number;
43
- };
44
- /** Decoded predicate. Present only when the rule is policed by our
45
- * interpreter AND the stored document was readable. */
46
- predicate?: PredicateNode;
47
- }
48
- export interface IntendedInstall {
49
- /** Rule the predicate is being installed onto. A re-install onto the same
50
- * id is a replacement, not an overlap, so this id is skipped. */
51
- ruleId: number;
52
- contextType: ContextType;
53
- signers: SignerDraft[];
54
- predicate: PredicateNode;
55
- }
56
- export type OverlapSeverity =
57
- /** A neighbouring rule imposes no constraint at all on the shared calls. */
58
- 'bypass'
59
- /** A neighbouring policy exists but we cannot read what it permits. */
60
- | 'unknown'
61
- /** Both rules are ours. The new rule will not restrict the shared calls,
62
- * because the signer can name whichever rule is more permissive. */
63
- | 'not-restricting';
64
- export interface AuthorityOverlap {
65
- ruleId: number;
66
- ruleClass: RuleClass;
67
- severity: OverlapSeverity;
68
- /** Signers present in both rules. Overlap is only reachable by a signer who
69
- * can name both rules, so a rule sharing no signer is not a collision. */
70
- sharedSigners: SignerDraft[];
71
- /** The selectors both rules can serve. Non-empty by construction. */
72
- sharedSelectors: Selector[];
73
- /** True when the neighbour is ours and can therefore be replaced by the
74
- * conjunction of the two predicates. */
75
- mergeable: boolean;
76
- advice: string;
77
- }
78
- /** Canonical key for signer equality. Mirrors OZ's `Signer` enum: a delegated
79
- * signer is its address, an external signer is the verifier plus the key
80
- * bytes, since one verifier may hold many keys. */
81
- export declare function signerKey(s: SignerDraft): string;
82
- /** Intersection of two selector SETS: every compatible pairing survives. */
83
- export declare function intersectSelectors(a: Selector[], b: Selector[]): Selector[];
84
- /**
85
- * The set of `(contract, fn)` selectors a predicate may permit.
86
- *
87
- * This is a deliberate OVER-approximation: every call the predicate actually
88
- * permits is covered by some returned selector, and unrecognised structure
89
- * widens to the wildcard rather than narrowing. That direction is what makes
90
- * the emptiness test below sound. A call carries exactly one `(contract, fn)`,
91
- * so if two predicates' over-approximations do not intersect, no single call
92
- * can be routed to either of them and the rules provably cannot collide.
93
- *
94
- * `not` is treated as unconstrained. Complementing a selector set would need
95
- * the universe of addresses and function names, which is not available and
96
- * would not be sound to guess.
97
- */
98
- export declare function permittedSelectors(node: PredicateNode): Selector[];
99
- /** Selectors a context type admits, before the predicate narrows them. */
100
- export declare function selectorsForContextType(ct: ContextType): Selector[];
101
- /** What a rule can actually authorise: its context type narrowed by its
102
- * predicate. An unpoliced or unreadable rule contributes no narrowing. */
103
- export declare function effectiveSelectors(rule: ObservedRule): Selector[];
104
- /**
105
- * Every existing rule that a signer of the intended install could name instead.
106
- *
107
- * A rule collides when it shares at least one signer AND at least one selector,
108
- * because both conditions are needed for the signer to have a choice. The rule
109
- * being installed onto is skipped: re-installing over it replaces its
110
- * predicate rather than adding a second source of authority.
111
- */
112
- export declare function findAuthorityOverlaps(args: {
113
- intended: IntendedInstall;
114
- existing: ObservedRule[];
115
- }): AuthorityOverlap[];
116
- export interface MergeResult {
117
- ok: boolean;
118
- predicate?: PredicateNode;
119
- /** Set when `ok` is false. */
120
- reason?: string;
121
- }
122
- /**
123
- * Conjunction of an existing predicate with a new one, for the tightening case.
124
- *
125
- * `and` children are flattened so repeated merges do not nest, which keeps the
126
- * encoded form closer to the byte cap.
127
- *
128
- * The guard matters more than the merge. `and` is only correct when the caller
129
- * means to tighten. Applied to two predicates that pin DIFFERENT selectors it
130
- * produces a predicate permitting nothing, which silently disables the policy
131
- * instead of restricting it. That case is refused, because the caller wanted
132
- * two capabilities and two rules already express that correctly.
133
- */
134
- export declare function mergeIntoAnd(existing: PredicateNode, incoming: PredicateNode): MergeResult;
@@ -1,96 +0,0 @@
1
- import { Contract } from '@stellar/stellar-sdk';
2
- import type { InstallRpcClient } from './build-install-policy.ts';
3
- /** Inputs for the install-predicate build. */
4
- export interface BuildInstallPredicateArgs {
5
- /** The smart account contract address (C...). The interpreter hashes
6
- * this rule's `signers` at install; we fetch it via `get_context_rule`
7
- * on this address, not reconstruct it. */
8
- smartAccount: string;
9
- /** The signer that authorises the install (G... wallet). */
10
- sourceAccount: string;
11
- /** The rule id the account assigned in call 1. */
12
- ruleId: number;
13
- /** The interpreter contract address (C...). */
14
- interpreterAddress: string;
15
- /** Network passphrase - pins the hash the auth digest binds. */
16
- networkPassphrase: string;
17
- /** Already-encoded (base64) canonical ScVal of the predicate. */
18
- encodedPredicate: string;
19
- /** Hex sha256 of the canonical predicate XDR bytes. */
20
- predicateHash: string;
21
- /** Grammar version override; defaults to 1. */
22
- grammarVersion?: number;
23
- /** Base fee in stroops; defaults to BASE_FEE (100). */
24
- baseFee?: number;
25
- /** RPC client to use for the simulation pass; injected for tests. */
26
- rpc: InstallRpcClient;
27
- /** Ledger window (in ledgers) for the auth entry's `validUntil`. */
28
- authValidUntilLedgers?: number;
29
- }
30
- /** Human-readable description of the install-predicate call, decoded FROM
31
- * the built XDR (not from the input args). The wallet signature binds
32
- * to bytes; the review card has to bind to the same bytes, so this is
33
- * the only safe source.
34
- *
35
- * `ruleId` is NOT decoded from the XDR - it lives inside
36
- * `raw_context_rule`, which is passed through verbatim. Decoding it
37
- * here would re-introduce the client-side reconstruction the file
38
- * header warns against. The top-level `BuildInstallPredicateResult`
39
- * echoes the caller-supplied rule id instead. */
40
- export interface InstallPredicateCallDescribes {
41
- /** The interpreter that will hold the predicate. */
42
- targetContract: string;
43
- /** The fn name on the target (always `install` today). */
44
- fnName: 'install';
45
- /** Grammar version the interpreter enforces; read off the wire. */
46
- grammarVersion: number;
47
- /** Per-rule install nonce; read off the wire. */
48
- installNonce: number;
49
- /** Hex sha256 of the encoded predicate blob; read off the wire. */
50
- predicateHash: string;
51
- /** Hex sha256 of the predicate bytes embedded in the params map. The
52
- * two values MUST match; a difference is a wire tampering signal. */
53
- predicateSha256OfEmbeddedBytes: string;
54
- /** The smart account address encoded in args[2], read off the wire. */
55
- smartAccountOnWire: string;
56
- }
57
- /** Output of the install-predicate build. The unsigned XDR is the
58
- * wallet's input; the wallet signs it (single envelope signature) and
59
- * submits. The auth tree matches install_policy: account entry
60
- * carrying OZ's AuthPayload + a source-account delegated signer entry.
61
- * Both are covered by the envelope signature. */
62
- export interface BuildInstallPredicateResult {
63
- /** Unsigned Soroban transaction envelope, base64 XDR. */
64
- unsignedXdr: string;
65
- /** Smart account contract address (echo). */
66
- smartAccount: string;
67
- /** Source account (echo) - the address that signs the envelope. */
68
- sourceAccount: string;
69
- /** The interpreter contract address (echo). */
70
- interpreterAddress: string;
71
- /** The rule id the account assigned in call 1 (echo). */
72
- ruleId: number;
73
- /** The host-call target + fn name. */
74
- call: {
75
- contract: string;
76
- fn: 'install';
77
- };
78
- /** The smart-account auth nonce (snapshot). */
79
- authNonce: string;
80
- /** The ledger sequence + window the auth entry expires at. */
81
- authValidUntilLedger: number;
82
- /** The captured rootInvocation for the smart-account entry. */
83
- rootInvocationXdr: string;
84
- /** Human-readable description of the install call, decoded FROM the
85
- * built unsigned XDR (not from the input args). The wallet signature
86
- * binds to bytes; the review card has to bind to the same bytes, so
87
- * this is the only safe source. */
88
- describes: InstallPredicateCallDescribes;
89
- }
90
- /** Build the unsigned transaction envelope for
91
- * `interpreter.install(params, raw_context_rule, smart_account)`. The
92
- * output XDR is signed by the wallet, not by us. */
93
- export declare function buildInstallPredicateXdr(args: BuildInstallPredicateArgs): Promise<BuildInstallPredicateResult>;
94
- /** Re-export `Contract` so the run-layer does not need to import the
95
- * SDK directly. Mirrors the build-install-policy.ts convention. */
96
- export { Contract };