@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,167 +0,0 @@
1
- // src/codegen/compile-gate.ts - toolchain-gated `cargo check` for the
2
- // codegen escape hatch.
3
- //
4
- // The escape hatch ships as the `policy-builder escape-hatch` CLI subcommand
5
- // (a later phase). This gate is its safety net, NOT the happy path. Property:
6
- // generated Rust compiles against the pinned OZ crate; broken source returns
7
- // `COMPILE_GATE_FAILED` with `stderr`; an absent toolchain returns `SKIPPED`
8
- // (does NOT fail - we cannot make build tools a hard runtime requirement for
9
- // a TypeScript package).
10
-
11
- import { spawn } from 'node:child_process'
12
- import { mkdtemp, rm, writeFile } from 'node:fs/promises'
13
- import { tmpdir } from 'node:os'
14
- import { join } from 'node:path'
15
-
16
- export type CompileGateResult =
17
- | { code: 'COMPILE_OK' }
18
- | { code: 'COMPILE_GATE_FAILED'; stderr: string }
19
- | { code: 'SKIPPED'; reason: string }
20
-
21
- export interface CompileGateOpts {
22
- /** Caller-controlled abort signal; aborting before toolchain probe resolves
23
- * the gate to `SKIPPED` rather than starting a cargo invocation. */
24
- signal?: AbortSignal
25
- /** Override the `cargo` binary (mostly for tests). */
26
- cargoBin?: string
27
- /** Override the target directory (mostly for tests). */
28
- tempDir?: string
29
- }
30
-
31
- interface ToolchainProbe {
32
- present: boolean
33
- reason: string
34
- }
35
-
36
- /** Probe the host for the Rust toolchain the gate requires. We require BOTH
37
- * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
38
- * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
39
- export async function hasRustToolchain(): Promise<boolean> {
40
- const probe = await probeToolchain()
41
- return probe.present
42
- }
43
-
44
- async function probeToolchain(): Promise<ToolchainProbe> {
45
- const cargo = await which('cargo')
46
- if (!cargo) return { present: false, reason: 'cargo not found on PATH' }
47
- const stellar = await which('stellar')
48
- if (!stellar) return { present: false, reason: 'stellar not found on PATH' }
49
- return { present: true, reason: `${cargo} + ${stellar}` }
50
- }
51
-
52
- async function which(bin: string): Promise<string | null> {
53
- try {
54
- const out = await runProcess('sh', ['-c', `command -v ${bin}`], { capture: true })
55
- const path = out.stdout.trim()
56
- return path.length > 0 ? path : null
57
- } catch {
58
- return null
59
- }
60
- }
61
-
62
- interface RunOpts {
63
- capture?: boolean
64
- signal?: AbortSignal
65
- }
66
-
67
- function runProcess(
68
- cmd: string,
69
- args: string[],
70
- opts: RunOpts
71
- ): Promise<{ stdout: string; stderr: string; code: number }> {
72
- return new Promise((resolve, reject) => {
73
- if (opts.signal?.aborted) {
74
- reject(new Error('aborted'))
75
- return
76
- }
77
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] })
78
- let stdout = ''
79
- let stderr = ''
80
- child.stdout.on('data', (b: Buffer) => {
81
- stdout += b.toString('utf8')
82
- })
83
- child.stderr.on('data', (b: Buffer) => {
84
- stderr += b.toString('utf8')
85
- })
86
- const onAbort = () => {
87
- child.kill('SIGTERM')
88
- reject(new Error('aborted'))
89
- }
90
- opts.signal?.addEventListener('abort', onAbort, { once: true })
91
- child.on('error', (e) => {
92
- opts.signal?.removeEventListener('abort', onAbort)
93
- reject(e)
94
- })
95
- child.on('close', (code) => {
96
- opts.signal?.removeEventListener('abort', onAbort)
97
- resolve({ stdout, stderr, code: code ?? -1 })
98
- })
99
- })
100
- }
101
-
102
- const CARGO_MANIFEST = `[package]
103
- name = "escape-hatch-gate"
104
- version = "0.0.0"
105
- edition = "2021"
106
- publish = false
107
-
108
- [lib]
109
- crate-type = ["cdylib"]
110
- # The gate writes the source beside the manifest rather than under src/, so
111
- # the path is stated. Without it cargo looks for src/lib.rs and fails to
112
- # parse the manifest before it ever compiles anything, which reads as a
113
- # broken generator rather than a broken scaffold.
114
- path = "lib.rs"
115
-
116
- [dependencies]
117
- soroban-sdk = "22"
118
-
119
- [workspace]
120
- `
121
-
122
- /** Compile-check a Rust source string against the pinned Soroban SDK.
123
- *
124
- * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
125
- * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
126
- * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
127
- *
128
- * The gate writes the source to a temporary crate and runs `cargo check`
129
- * against it; the crate is cleaned up whether or not compilation succeeds.
130
- * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
131
- * user (the LLM agent) so the user can iterate. */
132
- export async function compileCheck(
133
- rustSource: string,
134
- opts: CompileGateOpts = {}
135
- ): Promise<CompileGateResult> {
136
- if (opts.signal?.aborted) {
137
- return { code: 'SKIPPED', reason: 'aborted before probe' }
138
- }
139
-
140
- const probe = await probeToolchain()
141
- if (!probe.present) {
142
- return { code: 'SKIPPED', reason: probe.reason }
143
- }
144
-
145
- let dir: string | null = null
146
- try {
147
- dir = await mkdtemp(join(opts.tempDir ?? tmpdir(), 'codegen-gate-'))
148
- await writeFile(join(dir, 'Cargo.toml'), CARGO_MANIFEST)
149
- await writeFile(join(dir, 'lib.rs'), rustSource)
150
-
151
- const runOpts: RunOpts = opts.signal ? { signal: opts.signal } : {}
152
- const result = await runProcess(
153
- opts.cargoBin ?? 'cargo',
154
- ['check', '--quiet', '--offline', '--manifest-path', join(dir, 'Cargo.toml')],
155
- runOpts
156
- ).catch((e: Error) => ({ stdout: '', stderr: e.message, code: -1 }))
157
-
158
- if (result.code === 0) {
159
- return { code: 'COMPILE_OK' }
160
- }
161
- return { code: 'COMPILE_GATE_FAILED', stderr: result.stderr || result.stdout }
162
- } finally {
163
- if (dir) {
164
- await rm(dir, { recursive: true, force: true }).catch(() => {})
165
- }
166
- }
167
- }
@@ -1,17 +0,0 @@
1
- // src/codegen/index.ts - re-export the codegen escape-hatch surface.
2
- //
3
- // The escape hatch is OUT of the audited happy path: the synthesiser never
4
- // calls `generateRust` itself; the CLI subcommand (a later phase) is the only
5
- // entry point. Keeping the surface in one file makes that boundary visible
6
- // in import statements.
7
-
8
- export {
9
- type CompileGateOpts,
10
- type CompileGateResult,
11
- compileCheck,
12
- hasRustToolchain,
13
- } from './compile-gate.ts'
14
- export {
15
- type EscapeHatchSpec,
16
- generateRust,
17
- } from './template.ts'
@@ -1,165 +0,0 @@
1
- // src/codegen/template.ts - deterministic Rust source generator for the OZ
2
- // `Policy` escape-hatch skeleton.
3
- //
4
- // SUPERSEDED. The architecture this belongs to no longer exists. A deployed
5
- // policy involves exactly two contracts, the OZ smart account and one
6
- // immutable interpreter, and the synthesiser emits policy DATA rather than
7
- // code. Nothing on the synthesis path reaches this module, and no install can
8
- // produce a contract from it. When a constraint falls outside the grammar the
9
- // answer is to version the synthesiser and the interpreter together, not to
10
- // put unaudited Rust on chain per policy.
11
- //
12
- // Deleting it is a decision nobody has taken yet, not a dependency question.
13
- // `compile-gate.ts` takes a Rust string and knows nothing about this module,
14
- // and its tests compile a hardcoded fixture, so the gate keeps working either
15
- // way. What deleting this would remove is the only in-repo producer of policy
16
- // Rust for the gate to check. Do not read its presence as the product
17
- // generating contracts, and do not wire it into the synthesis path.
18
- //
19
- // What follows describes the abandoned design.
20
- //
21
- // This is the LAST-RESORT tool for constraints the v1 DSL cannot express. It
22
- // lives OUT of the audited happy-path surface; the synthesiser never emits it
23
- // automatically. It mirrors Zodiac Roles' `Custom` operator: a hand-written
24
- // (here: scaffolded) policy the operator assumes responsibility for.
25
- //
26
- // The skeleton carries five storage invariants the user MUST preserve when
27
- // filling in the predicate logic:
28
- // 1. `smart_account.require_auth()` is invoked INSIDE `enforce`.
29
- // 2. Storage is keyed by the composite `(smart_account, rule_id)`.
30
- // 3. Chain reads use `unwrap_or_default()` so a missing key is a permitted
31
- // default, not a panic.
32
- // 4. Storage is `persistent()` (NOT `instance()`) so the policy survives
33
- // contract instance lifecycle changes.
34
- // 5. `uninstall` removes the stored state.
35
- //
36
- // Determinism: same `(spec, name)` -> byte-identical output. No clock, no RNG,
37
- // no environment reads.
38
-
39
- /** A small typed description of one uncovered constraint the v1 DSL refused
40
- * to express. The synthesiser surfaces these from `CompileResult.uncovered`
41
- * and the codegen escape hatch wraps them into a hand-auditable skeleton. */
42
- export interface EscapeHatchSpec {
43
- /** Address of the policy contract the skeleton is generated for. */
44
- contract: string
45
- /** The trait method the predicate lives inside (default: 'enforce'). */
46
- fnName?: string
47
- /** Human-readable description of each construct the DSL could not cover. */
48
- uncovered: string[]
49
- }
50
-
51
- /** Format a name for use as a Rust identifier. The input is constrained by
52
- * the caller (a kebab-case policy name + alphanumeric addresses); this is a
53
- * belt-and-braces sanitiser that maps anything non-identifier to '_'. */
54
- function asRustIdent(s: string): string {
55
- let out = ''
56
- for (let i = 0; i < s.length; i++) {
57
- const ch = s.charCodeAt(i)
58
- const ok =
59
- (ch >= 48 && ch <= 57) || // 0-9
60
- (ch >= 65 && ch <= 90) || // A-Z
61
- (ch >= 97 && ch <= 122) || // a-z
62
- ch === 95 // _
63
- out += ok ? s[i] : '_'
64
- }
65
- // Identifiers may not start with a digit.
66
- if (out.length > 0 && out.charCodeAt(0) >= 48 && out.charCodeAt(0) <= 57) {
67
- out = `_${out}`
68
- }
69
- return out || 'policy'
70
- }
71
-
72
- /** Render the `uncovered` list as a `//` comment block (one line per item). */
73
- function renderUncovered(uncovered: string[]): string {
74
- if (uncovered.length === 0) {
75
- return ' // (no specific uncovered constructs reported)'
76
- }
77
- return uncovered.map((line) => ` // - ${line}`).join('\n')
78
- }
79
-
80
- /** Generate a deterministic OZ `Policy` skeleton for an uncovered constraint.
81
- *
82
- * The skeleton is NOT a finished policy; the user fills in the predicate
83
- * logic in the marked TODO(user) holes and audits the result themselves.
84
- *
85
- * Same `(spec, name)` always produces byte-identical output. */
86
- export function generateRust(spec: EscapeHatchSpec, name: string): string {
87
- const _contract = spec.contract
88
- const _fnName = spec.fnName ?? 'enforce'
89
- const structName = asRustIdent(name)
90
- const _dataKeyName = `${asRustIdent(name)}_data`
91
- const uncoveredBlock = renderUncovered(spec.uncovered)
92
-
93
- return `// Auto-generated by the OZ Policy Builder codegen escape hatch.
94
- // THIS OUTPUT IS THE USER'S TO COMPLETE AND AUDIT.
95
- // The synthesiser never emits it on the happy path; reach for it only when
96
- // a constraint cannot be expressed in the v1 DSL grammar (same shape as
97
- // Zodiac Roles' \`Custom\` operator).
98
-
99
- #![no_std]
100
-
101
- use soroban_sdk::{contract, contractimpl, contracttype, Address, Env, Vec};
102
-
103
- #[contracttype]
104
- pub enum DataKey {
105
- /// Composite key \`(smart_account, rule_id)\` so multiple policies on
106
- /// one smart account coexist without collision.
107
- State(Address, u32),
108
- }
109
-
110
- #[contract]
111
- pub struct ${structName};
112
-
113
- #[contractimpl]
114
- impl ${structName} {
115
- pub fn install(e: &Env, smart_account: Address, rule_id: u32) {
116
- // TODO(user): initialise policy state for this (smart_account, rule_id).
117
- // The skeleton leaves the stored value empty; the predicate body
118
- // (in \`enforce\`) decides what to read.
119
- e.storage().persistent().set(
120
- &DataKey::State(smart_account.clone(), rule_id),
121
- &(),
122
- );
123
- }
124
-
125
- pub fn enforce(
126
- e: &Env,
127
- smart_account: Address,
128
- rule_id: u32,
129
- _signers: Vec<Address>,
130
- ) {
131
- // Invariant 1: authorise the smart account BEFORE any state read or
132
- // predicate evaluation. Removing this call opens the policy to
133
- // impersonation by any caller with a valid rule_id.
134
- smart_account.require_auth();
135
-
136
- // Invariant 2 + 4: read stored state through the composite key on
137
- // \`persistent()\` storage. \`unwrap_or_default()\` (invariant 3)
138
- // makes an empty key a permitted default rather than a panic.
139
- let _state: () = e
140
- .storage()
141
- .persistent()
142
- .get(&DataKey::State(smart_account.clone(), rule_id))
143
- .unwrap_or_default();
144
-
145
- // --- uncovered constraints the v1 DSL refused to express ---
146
- ${uncoveredBlock}
147
-
148
- // TODO(user): replace the placeholder below with the real predicate
149
- // body. The recorded flow's \`(contract, fn_name, args)\` is the
150
- // single authorised call \`Policy::enforce\` receives; match against
151
- // \`e\` here.
152
- let _ = (_state, &e);
153
- }
154
-
155
- pub fn uninstall(e: &Env, smart_account: Address, rule_id: u32) {
156
- // Invariant 5: \`uninstall\` removes the stored state so a subsequent
157
- // install starts from a clean slate (and the nonce returns to its
158
- // post-uninstall value).
159
- e.storage()
160
- .persistent()
161
- .remove(&DataKey::State(smart_account, rule_id));
162
- }
163
- }
164
- `
165
- }
Binary file
@@ -1,219 +0,0 @@
1
- //! Transactions for the merge remedy.
2
- //!
3
- //! `plan-merge-policy.ts` decides WHAT should happen; this builds the XDR for
4
- //! the step the caller asked for. Two calls, in order, because OZ refuses to
5
- //! attach a policy that is already on the rule:
6
- //!
7
- //! step 1 `detach` -> `account.remove_policy(rule_id, policy_id)`
8
- //! step 2 `reinstall` -> `account.add_policy(rule_id, interpreter, param)`
9
- //!
10
- //! The two cannot be emitted together. Simulating step 2 while the old
11
- //! attachment is still there hits `DuplicatePolicy`, so the second transaction
12
- //! is only buildable once the first has confirmed.
13
- //!
14
- //! Both calls route through the smart account and are authorised the same way
15
- //! as `revoke_policy`: against the deploy-time admin rule, with the recorded
16
- //! `rootInvocation` binding the auth payload to this exact rule and policy.
17
- //! Detaching runs our `uninstall`, which is master-gated, so the signer has to
18
- //! be a master of the rule either way.
19
-
20
- import {
21
- Account,
22
- Address,
23
- BASE_FEE,
24
- Operation,
25
- rpc,
26
- TransactionBuilder,
27
- xdr,
28
- } from '@stellar/stellar-sdk'
29
- import { DEFAULT_GRAMMAR_VERSION, encodePolicyInstallParams } from './build-add-context-rule.ts'
30
- import type { InstallRpcClient } from './build-install-policy.ts'
31
- import {
32
- accountEntry,
33
- authDigest,
34
- authPayload,
35
- delegatedSignerEntry,
36
- signaturePayload,
37
- } from './oz-auth.ts'
38
- import type { MergeStep } from './plan-merge-policy.ts'
39
-
40
- /** Matches the window the install and revoke builders use. */
41
- const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 100
42
-
43
- /**
44
- * The context rule the merge authorises AGAINST, which is not the rule being
45
- * merged.
46
- *
47
- * Both calls mutate the smart account itself, so they need the account's own
48
- * authorisation, and this builder asks rule 0 for it - the same assumption the
49
- * install and revoke builders make. OpenZeppelin does NOT enforce any
50
- * admin semantic for rule 0: it is simply the first rule the account's
51
- * constructor created, and OZ's reference account creates it as `Default`
52
- * covering every context.
53
- *
54
- * The assumption is therefore load-bearing and unverified at build time. If
55
- * rule 0 does not exist, does not cover `CallContract(<smart account>)`, or
56
- * does not list the source account as a signer, the transaction is built and
57
- * then fails when submitted, and the operator pays the fee for a transaction
58
- * that was never signable. Changing it is a wire-visible change: the id is
59
- * hashed into the auth digest.
60
- */
61
- export const ADMIN_CONTEXT_RULE_ID = 0
62
-
63
- export interface BuildMergePolicyArgs {
64
- smartAccount: string
65
- sourceAccount: string
66
- networkPassphrase: string
67
- ruleId: number
68
- /** OZ registry id of the interpreter policy on this rule, from the plan. */
69
- policyId: number
70
- interpreterAddress: string
71
- step: MergeStep
72
- /** Only needed for `reinstall`: the merged predicate, already encoded. */
73
- encodedPredicate?: string
74
- predicateHash?: string
75
- /** Nonce for the reinstall. Read from chain rather than assumed: a detach
76
- * whose uninstall panicked leaves the old nonce in place. */
77
- installNonce?: number
78
- /** Oracle bounds to carry over from the document being replaced. */
79
- oracleParams?: {
80
- maxStalenessSeconds?: number
81
- maxDeviationBps?: number
82
- maxCrossFeedDeviationBps?: number
83
- }
84
- rpc: InstallRpcClient
85
- baseFee?: number
86
- authValidUntilLedgers?: number
87
- }
88
-
89
- export interface BuildMergePolicyResult {
90
- unsignedXdr: string
91
- smartAccount: string
92
- sourceAccount: string
93
- step: MergeStep
94
- call: { contract: string; fn: 'remove_policy' | 'add_policy'; ruleId: number }
95
- authNonce: string
96
- authValidUntilLedger: number
97
- rootInvocationXdr: string
98
- }
99
-
100
- function hostFunctionFor(args: BuildMergePolicyArgs): xdr.HostFunction {
101
- if (args.step === 'detach') {
102
- return xdr.HostFunction.hostFunctionTypeInvokeContract(
103
- new xdr.InvokeContractArgs({
104
- contractAddress: new Address(args.smartAccount).toScAddress(),
105
- functionName: 'remove_policy',
106
- args: [xdr.ScVal.scvU32(args.ruleId), xdr.ScVal.scvU32(args.policyId)],
107
- })
108
- )
109
- }
110
-
111
- if (!args.encodedPredicate || !args.predicateHash) {
112
- throw new Error('merge_policy: reinstall needs the merged predicate and its hash')
113
- }
114
- return xdr.HostFunction.hostFunctionTypeInvokeContract(
115
- new xdr.InvokeContractArgs({
116
- contractAddress: new Address(args.smartAccount).toScAddress(),
117
- functionName: 'add_policy',
118
- args: [
119
- xdr.ScVal.scvU32(args.ruleId),
120
- new Address(args.interpreterAddress).toScVal(),
121
- // Same encoder as a fresh install: the field order is ABI-significant
122
- // and it re-hashes the predicate to confirm the supplied hash.
123
- encodePolicyInstallParams({
124
- encodedPredicate: args.encodedPredicate,
125
- predicateHash: args.predicateHash,
126
- installNonce: args.installNonce ?? 1,
127
- grammarVersion: DEFAULT_GRAMMAR_VERSION,
128
- ...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
129
- }),
130
- ],
131
- })
132
- )
133
- }
134
-
135
- /**
136
- * Build the unsigned transaction for one step of the merge.
137
- *
138
- * The auth dance mirrors `buildRevokePolicyXdr`: simulate once to record the
139
- * account's auth entry, rebuild with the payload bound to that recorded
140
- * `rootInvocation`, then assemble. Binding to the recorded invocation rather
141
- * than to the input arguments is what makes the signature commit to the exact
142
- * rule and policy being changed.
143
- */
144
- export async function buildMergePolicyXdr(
145
- args: BuildMergePolicyArgs
146
- ): Promise<BuildMergePolicyResult> {
147
- const fn = args.step === 'detach' ? 'remove_policy' : 'add_policy'
148
- const source = await args.rpc.getAccount(args.sourceAccount)
149
- const hostFunction = hostFunctionFor(args)
150
- const makeOperation = (auth: xdr.SorobanAuthorizationEntry[] = []) =>
151
- Operation.invokeHostFunction({ func: hostFunction, auth })
152
- const baseFee = args.baseFee !== undefined ? String(args.baseFee) : BASE_FEE
153
-
154
- const buildTx = (op: xdr.Operation) =>
155
- new TransactionBuilder(new Account(args.sourceAccount, source.sequenceNumber()), {
156
- fee: baseFee,
157
- networkPassphrase: args.networkPassphrase,
158
- })
159
- .addOperation(op)
160
- .setTimeout(0)
161
- .build()
162
-
163
- const recorded = await args.rpc.simulateTransaction(buildTx(makeOperation()))
164
- if (rpc.Api.isSimulationError(recorded)) {
165
- // Short and stable, like the other builders: the SDK's full error carries
166
- // host and URL detail that has no business in a user-facing message.
167
- throw new Error(`merge_policy: ${fn} simulateTransaction failed`)
168
- }
169
- const original = (recorded.result?.auth ?? []).find(
170
- (entry) =>
171
- entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
172
- Address.fromScAddress(entry.credentials().address().address()).toString() ===
173
- args.smartAccount
174
- )
175
- if (!original) {
176
- throw new Error(
177
- `merge_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`
178
- )
179
- }
180
-
181
- const validUntilLedger =
182
- (await args.rpc.getLatestLedger()).sequence +
183
- (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS)
184
- const contextRuleIds = [ADMIN_CONTEXT_RULE_ID]
185
- const digest = authDigest(
186
- signaturePayload(
187
- args.networkPassphrase,
188
- original.credentials().address().nonce(),
189
- validUntilLedger,
190
- original.rootInvocation()
191
- ),
192
- contextRuleIds
193
- )
194
- const authEntries = [
195
- accountEntry(
196
- original,
197
- validUntilLedger,
198
- authPayload([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))
199
- ),
200
- ...contextRuleIds.map(() => delegatedSignerEntry(args.smartAccount, digest)),
201
- ]
202
- const txWithAuth = buildTx(makeOperation(authEntries))
203
- const enforcing = await args.rpc.simulateTransaction(txWithAuth)
204
- if (rpc.Api.isSimulationError(enforcing)) {
205
- throw new Error(`merge_policy: ${fn} auth simulateTransaction failed`)
206
- }
207
- const finalTx = rpc.assembleTransaction(txWithAuth, enforcing).build()
208
-
209
- return {
210
- unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
211
- smartAccount: args.smartAccount,
212
- sourceAccount: args.sourceAccount,
213
- step: args.step,
214
- call: { contract: args.smartAccount, fn, ruleId: args.ruleId },
215
- authNonce: original.credentials().address().nonce().toString(),
216
- authValidUntilLedger: validUntilLedger,
217
- rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
218
- }
219
- }