@eloxiv/kernel 0.0.0-stage → 0.1.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 (1167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/AccountMail.d.ts +40 -0
  4. package/dist/AccountMail.d.ts.map +1 -0
  5. package/dist/AccountMail.js +169 -0
  6. package/dist/AccountMail.js.map +1 -0
  7. package/dist/AppConfig.d.ts +72 -0
  8. package/dist/AppConfig.d.ts.map +1 -0
  9. package/dist/AppConfig.js +87 -0
  10. package/dist/AppConfig.js.map +1 -0
  11. package/dist/Approvals.d.ts +132 -0
  12. package/dist/Approvals.d.ts.map +1 -0
  13. package/dist/Approvals.js +342 -0
  14. package/dist/Approvals.js.map +1 -0
  15. package/dist/Audit.d.ts +93 -0
  16. package/dist/Audit.d.ts.map +1 -0
  17. package/dist/Audit.js +275 -0
  18. package/dist/Audit.js.map +1 -0
  19. package/dist/AuthSeam.d.ts +58 -0
  20. package/dist/AuthSeam.d.ts.map +1 -0
  21. package/dist/AuthSeam.js +101 -0
  22. package/dist/AuthSeam.js.map +1 -0
  23. package/dist/Authority.d.ts +160 -0
  24. package/dist/Authority.d.ts.map +1 -0
  25. package/dist/Authority.js +325 -0
  26. package/dist/Authority.js.map +1 -0
  27. package/dist/Avatars.d.ts +26 -0
  28. package/dist/Avatars.d.ts.map +1 -0
  29. package/dist/Avatars.js +140 -0
  30. package/dist/Avatars.js.map +1 -0
  31. package/dist/Base64url.d.ts +9 -0
  32. package/dist/Base64url.d.ts.map +1 -0
  33. package/dist/Base64url.js +26 -0
  34. package/dist/Base64url.js.map +1 -0
  35. package/dist/BasePath.d.ts +39 -0
  36. package/dist/BasePath.d.ts.map +1 -0
  37. package/dist/BasePath.js +70 -0
  38. package/dist/BasePath.js.map +1 -0
  39. package/dist/CallActed.d.ts +10 -0
  40. package/dist/CallActed.d.ts.map +1 -0
  41. package/dist/CallActed.js +10 -0
  42. package/dist/CallActed.js.map +1 -0
  43. package/dist/Config.d.ts +459 -0
  44. package/dist/Config.d.ts.map +1 -0
  45. package/dist/Config.js +415 -0
  46. package/dist/Config.js.map +1 -0
  47. package/dist/DeliveryPolicy.d.ts +20 -0
  48. package/dist/DeliveryPolicy.d.ts.map +1 -0
  49. package/dist/DeliveryPolicy.js +35 -0
  50. package/dist/DeliveryPolicy.js.map +1 -0
  51. package/dist/DesktopSignIn.d.ts +24 -0
  52. package/dist/DesktopSignIn.d.ts.map +1 -0
  53. package/dist/DesktopSignIn.js +148 -0
  54. package/dist/DesktopSignIn.js.map +1 -0
  55. package/dist/Directory.d.ts +179 -0
  56. package/dist/Directory.d.ts.map +1 -0
  57. package/dist/Directory.js +1184 -0
  58. package/dist/Directory.js.map +1 -0
  59. package/dist/Flags.d.ts +59 -0
  60. package/dist/Flags.d.ts.map +1 -0
  61. package/dist/Flags.js +195 -0
  62. package/dist/Flags.js.map +1 -0
  63. package/dist/Gate.d.ts +42 -0
  64. package/dist/Gate.d.ts.map +1 -0
  65. package/dist/Gate.js +132 -0
  66. package/dist/Gate.js.map +1 -0
  67. package/dist/Hash.d.ts +4 -0
  68. package/dist/Hash.d.ts.map +1 -0
  69. package/dist/Hash.js +16 -0
  70. package/dist/Hash.js.map +1 -0
  71. package/dist/Identity.d.ts +327 -0
  72. package/dist/Identity.d.ts.map +1 -0
  73. package/dist/Identity.js +1232 -0
  74. package/dist/Identity.js.map +1 -0
  75. package/dist/IntervalJob.d.ts +40 -0
  76. package/dist/IntervalJob.d.ts.map +1 -0
  77. package/dist/IntervalJob.js +76 -0
  78. package/dist/IntervalJob.js.map +1 -0
  79. package/dist/Invocation.d.ts +210 -0
  80. package/dist/Invocation.d.ts.map +1 -0
  81. package/dist/Invocation.js +1680 -0
  82. package/dist/Invocation.js.map +1 -0
  83. package/dist/KernelHandlers.d.ts +19 -0
  84. package/dist/KernelHandlers.d.ts.map +1 -0
  85. package/dist/KernelHandlers.js +15 -0
  86. package/dist/KernelHandlers.js.map +1 -0
  87. package/dist/KernelModule.d.ts +65 -0
  88. package/dist/KernelModule.d.ts.map +1 -0
  89. package/dist/KernelModule.js +116 -0
  90. package/dist/KernelModule.js.map +1 -0
  91. package/dist/MemberRoutes.d.ts +6 -0
  92. package/dist/MemberRoutes.d.ts.map +1 -0
  93. package/dist/MemberRoutes.js +107 -0
  94. package/dist/MemberRoutes.js.map +1 -0
  95. package/dist/Module.d.ts +479 -0
  96. package/dist/Module.d.ts.map +1 -0
  97. package/dist/Module.js +30 -0
  98. package/dist/Module.js.map +1 -0
  99. package/dist/ModuleIdentity.d.ts +17 -0
  100. package/dist/ModuleIdentity.d.ts.map +1 -0
  101. package/dist/ModuleIdentity.js +106 -0
  102. package/dist/ModuleIdentity.js.map +1 -0
  103. package/dist/Notifications.d.ts +107 -0
  104. package/dist/Notifications.d.ts.map +1 -0
  105. package/dist/Notifications.js +475 -0
  106. package/dist/Notifications.js.map +1 -0
  107. package/dist/Outbox.d.ts +146 -0
  108. package/dist/Outbox.d.ts.map +1 -0
  109. package/dist/Outbox.js +518 -0
  110. package/dist/Outbox.js.map +1 -0
  111. package/dist/Privacy.d.ts +50 -0
  112. package/dist/Privacy.d.ts.map +1 -0
  113. package/dist/Privacy.js +167 -0
  114. package/dist/Privacy.js.map +1 -0
  115. package/dist/Progress.d.ts +42 -0
  116. package/dist/Progress.d.ts.map +1 -0
  117. package/dist/Progress.js +215 -0
  118. package/dist/Progress.js.map +1 -0
  119. package/dist/QuerySurface.d.ts +73 -0
  120. package/dist/QuerySurface.d.ts.map +1 -0
  121. package/dist/QuerySurface.js +440 -0
  122. package/dist/QuerySurface.js.map +1 -0
  123. package/dist/QueryViews.d.ts +70 -0
  124. package/dist/QueryViews.d.ts.map +1 -0
  125. package/dist/QueryViews.js +94 -0
  126. package/dist/QueryViews.js.map +1 -0
  127. package/dist/Readiness.d.ts +40 -0
  128. package/dist/Readiness.d.ts.map +1 -0
  129. package/dist/Readiness.js +203 -0
  130. package/dist/Readiness.js.map +1 -0
  131. package/dist/Redact.d.ts +11 -0
  132. package/dist/Redact.d.ts.map +1 -0
  133. package/dist/Redact.js +21 -0
  134. package/dist/Redact.js.map +1 -0
  135. package/dist/Registry.d.ts +117 -0
  136. package/dist/Registry.d.ts.map +1 -0
  137. package/dist/Registry.js +297 -0
  138. package/dist/Registry.js.map +1 -0
  139. package/dist/Release.d.ts +205 -0
  140. package/dist/Release.d.ts.map +1 -0
  141. package/dist/Release.js +880 -0
  142. package/dist/Release.js.map +1 -0
  143. package/dist/Retention.d.ts +43 -0
  144. package/dist/Retention.d.ts.map +1 -0
  145. package/dist/Retention.js +124 -0
  146. package/dist/Retention.js.map +1 -0
  147. package/dist/Scheduler.d.ts +56 -0
  148. package/dist/Scheduler.d.ts.map +1 -0
  149. package/dist/Scheduler.js +470 -0
  150. package/dist/Scheduler.js.map +1 -0
  151. package/dist/Server.d.ts +341 -0
  152. package/dist/Server.d.ts.map +1 -0
  153. package/dist/Server.js +1106 -0
  154. package/dist/Server.js.map +1 -0
  155. package/dist/Sessions.d.ts +38 -0
  156. package/dist/Sessions.d.ts.map +1 -0
  157. package/dist/Sessions.js +45 -0
  158. package/dist/Sessions.js.map +1 -0
  159. package/dist/Settings.d.ts +63 -0
  160. package/dist/Settings.d.ts.map +1 -0
  161. package/dist/Settings.js +219 -0
  162. package/dist/Settings.js.map +1 -0
  163. package/dist/Sharing.d.ts +99 -0
  164. package/dist/Sharing.d.ts.map +1 -0
  165. package/dist/Sharing.js +315 -0
  166. package/dist/Sharing.js.map +1 -0
  167. package/dist/Sync.d.ts +188 -0
  168. package/dist/Sync.d.ts.map +1 -0
  169. package/dist/Sync.js +1100 -0
  170. package/dist/Sync.js.map +1 -0
  171. package/dist/Telemetry.d.ts +154 -0
  172. package/dist/Telemetry.d.ts.map +1 -0
  173. package/dist/Telemetry.js +536 -0
  174. package/dist/Telemetry.js.map +1 -0
  175. package/dist/Versioning.d.ts +98 -0
  176. package/dist/Versioning.d.ts.map +1 -0
  177. package/dist/Versioning.js +387 -0
  178. package/dist/Versioning.js.map +1 -0
  179. package/dist/WorkItems.d.ts +67 -0
  180. package/dist/WorkItems.d.ts.map +1 -0
  181. package/dist/WorkItems.js +211 -0
  182. package/dist/WorkItems.js.map +1 -0
  183. package/dist/Workflows.d.ts +78 -0
  184. package/dist/Workflows.d.ts.map +1 -0
  185. package/dist/Workflows.js +478 -0
  186. package/dist/Workflows.js.map +1 -0
  187. package/dist/agent/Admission.d.ts +22 -0
  188. package/dist/agent/Admission.d.ts.map +1 -0
  189. package/dist/agent/Admission.js +34 -0
  190. package/dist/agent/Admission.js.map +1 -0
  191. package/dist/agent/Channels.d.ts +15 -0
  192. package/dist/agent/Channels.d.ts.map +1 -0
  193. package/dist/agent/Channels.js +50 -0
  194. package/dist/agent/Channels.js.map +1 -0
  195. package/dist/agent/Context.d.ts +73 -0
  196. package/dist/agent/Context.d.ts.map +1 -0
  197. package/dist/agent/Context.js +338 -0
  198. package/dist/agent/Context.js.map +1 -0
  199. package/dist/agent/Http.d.ts +18 -0
  200. package/dist/agent/Http.d.ts.map +1 -0
  201. package/dist/agent/Http.js +410 -0
  202. package/dist/agent/Http.js.map +1 -0
  203. package/dist/agent/Metering.d.ts +162 -0
  204. package/dist/agent/Metering.d.ts.map +1 -0
  205. package/dist/agent/Metering.js +315 -0
  206. package/dist/agent/Metering.js.map +1 -0
  207. package/dist/agent/ModelSetup.d.ts +10 -0
  208. package/dist/agent/ModelSetup.d.ts.map +1 -0
  209. package/dist/agent/ModelSetup.js +331 -0
  210. package/dist/agent/ModelSetup.js.map +1 -0
  211. package/dist/agent/Models.d.ts +197 -0
  212. package/dist/agent/Models.d.ts.map +1 -0
  213. package/dist/agent/Models.js +489 -0
  214. package/dist/agent/Models.js.map +1 -0
  215. package/dist/agent/Processors.d.ts +102 -0
  216. package/dist/agent/Processors.d.ts.map +1 -0
  217. package/dist/agent/Processors.js +80 -0
  218. package/dist/agent/Processors.js.map +1 -0
  219. package/dist/agent/Queue.d.ts +21 -0
  220. package/dist/agent/Queue.d.ts.map +1 -0
  221. package/dist/agent/Queue.js +64 -0
  222. package/dist/agent/Queue.js.map +1 -0
  223. package/dist/agent/Receipts.d.ts +41 -0
  224. package/dist/agent/Receipts.d.ts.map +1 -0
  225. package/dist/agent/Receipts.js +142 -0
  226. package/dist/agent/Receipts.js.map +1 -0
  227. package/dist/agent/Resources.d.ts +68 -0
  228. package/dist/agent/Resources.d.ts.map +1 -0
  229. package/dist/agent/Resources.js +207 -0
  230. package/dist/agent/Resources.js.map +1 -0
  231. package/dist/agent/Run.d.ts +178 -0
  232. package/dist/agent/Run.d.ts.map +1 -0
  233. package/dist/agent/Run.js +2896 -0
  234. package/dist/agent/Run.js.map +1 -0
  235. package/dist/agent/Runtime.d.ts +79 -0
  236. package/dist/agent/Runtime.d.ts.map +1 -0
  237. package/dist/agent/Runtime.js +366 -0
  238. package/dist/agent/Runtime.js.map +1 -0
  239. package/dist/agent/Settings.d.ts +126 -0
  240. package/dist/agent/Settings.d.ts.map +1 -0
  241. package/dist/agent/Settings.js +44 -0
  242. package/dist/agent/Settings.js.map +1 -0
  243. package/dist/agent/Skills.d.ts +73 -0
  244. package/dist/agent/Skills.d.ts.map +1 -0
  245. package/dist/agent/Skills.js +95 -0
  246. package/dist/agent/Skills.js.map +1 -0
  247. package/dist/agent/Store.d.ts +37 -0
  248. package/dist/agent/Store.d.ts.map +1 -0
  249. package/dist/agent/Store.js +50 -0
  250. package/dist/agent/Store.js.map +1 -0
  251. package/dist/agent/ToolSearch.d.ts +37 -0
  252. package/dist/agent/ToolSearch.d.ts.map +1 -0
  253. package/dist/agent/ToolSearch.js +119 -0
  254. package/dist/agent/ToolSearch.js.map +1 -0
  255. package/dist/agent/index.d.ts +37 -0
  256. package/dist/agent/index.d.ts.map +1 -0
  257. package/dist/agent/index.js +44 -0
  258. package/dist/agent/index.js.map +1 -0
  259. package/dist/agent/module.d.ts +12889 -0
  260. package/dist/agent/module.d.ts.map +1 -0
  261. package/dist/agent/module.js +1550 -0
  262. package/dist/agent/module.js.map +1 -0
  263. package/dist/appState/Sweep.d.ts +21 -0
  264. package/dist/appState/Sweep.d.ts.map +1 -0
  265. package/dist/appState/Sweep.js +46 -0
  266. package/dist/appState/Sweep.js.map +1 -0
  267. package/dist/appState/module.d.ts +1710 -0
  268. package/dist/appState/module.d.ts.map +1 -0
  269. package/dist/appState/module.js +344 -0
  270. package/dist/appState/module.js.map +1 -0
  271. package/dist/audit/module.d.ts +158 -0
  272. package/dist/audit/module.d.ts.map +1 -0
  273. package/dist/audit/module.js +72 -0
  274. package/dist/audit/module.js.map +1 -0
  275. package/dist/auth/AuthProvider.d.ts +224 -0
  276. package/dist/auth/AuthProvider.d.ts.map +1 -0
  277. package/dist/auth/AuthProvider.js +104 -0
  278. package/dist/auth/AuthProvider.js.map +1 -0
  279. package/dist/auth/BetterAuthProvider.d.ts +40 -0
  280. package/dist/auth/BetterAuthProvider.d.ts.map +1 -0
  281. package/dist/auth/BetterAuthProvider.js +458 -0
  282. package/dist/auth/BetterAuthProvider.js.map +1 -0
  283. package/dist/auth/Methods.d.ts +7 -0
  284. package/dist/auth/Methods.d.ts.map +1 -0
  285. package/dist/auth/Methods.js +7 -0
  286. package/dist/auth/Methods.js.map +1 -0
  287. package/dist/auth/SessionTokens.d.ts +23 -0
  288. package/dist/auth/SessionTokens.d.ts.map +1 -0
  289. package/dist/auth/SessionTokens.js +150 -0
  290. package/dist/auth/SessionTokens.js.map +1 -0
  291. package/dist/collab/Collab.d.ts +105 -0
  292. package/dist/collab/Collab.d.ts.map +1 -0
  293. package/dist/collab/Collab.js +475 -0
  294. package/dist/collab/Collab.js.map +1 -0
  295. package/dist/collab/Housekeeping.d.ts +38 -0
  296. package/dist/collab/Housekeeping.d.ts.map +1 -0
  297. package/dist/collab/Housekeeping.js +146 -0
  298. package/dist/collab/Housekeeping.js.map +1 -0
  299. package/dist/collab/LiveCopy.d.ts +7 -0
  300. package/dist/collab/LiveCopy.d.ts.map +1 -0
  301. package/dist/collab/LiveCopy.js +79 -0
  302. package/dist/collab/LiveCopy.js.map +1 -0
  303. package/dist/collab/Socket.d.ts +19 -0
  304. package/dist/collab/Socket.d.ts.map +1 -0
  305. package/dist/collab/Socket.js +323 -0
  306. package/dist/collab/Socket.js.map +1 -0
  307. package/dist/collab/Store.d.ts +42 -0
  308. package/dist/collab/Store.d.ts.map +1 -0
  309. package/dist/collab/Store.js +59 -0
  310. package/dist/collab/Store.js.map +1 -0
  311. package/dist/collab/Ydoc.d.ts +88 -0
  312. package/dist/collab/Ydoc.d.ts.map +1 -0
  313. package/dist/collab/Ydoc.js +314 -0
  314. package/dist/collab/Ydoc.js.map +1 -0
  315. package/dist/collab/derive/bundle.gen.d.ts +2 -0
  316. package/dist/collab/derive/bundle.gen.d.ts.map +1 -0
  317. package/dist/collab/derive/bundle.gen.js +3 -0
  318. package/dist/collab/derive/bundle.gen.js.map +1 -0
  319. package/dist/collab/derive/entry.d.ts +3 -0
  320. package/dist/collab/derive/entry.d.ts.map +1 -0
  321. package/dist/collab/derive/entry.js +35 -0
  322. package/dist/collab/derive/entry.js.map +1 -0
  323. package/dist/collab/derive/polyfill.d.ts +3 -0
  324. package/dist/collab/derive/polyfill.d.ts.map +1 -0
  325. package/dist/collab/derive/polyfill.js +17 -0
  326. package/dist/collab/derive/polyfill.js.map +1 -0
  327. package/dist/collab/module.d.ts +305 -0
  328. package/dist/collab/module.d.ts.map +1 -0
  329. package/dist/collab/module.js +161 -0
  330. package/dist/collab/module.js.map +1 -0
  331. package/dist/connections/Connections.d.ts +199 -0
  332. package/dist/connections/Connections.d.ts.map +1 -0
  333. package/dist/connections/Connections.js +1633 -0
  334. package/dist/connections/Connections.js.map +1 -0
  335. package/dist/connections/Connector.d.ts +213 -0
  336. package/dist/connections/Connector.d.ts.map +1 -0
  337. package/dist/connections/Connector.js +55 -0
  338. package/dist/connections/Connector.js.map +1 -0
  339. package/dist/connections/Crypto.d.ts +55 -0
  340. package/dist/connections/Crypto.d.ts.map +1 -0
  341. package/dist/connections/Crypto.js +100 -0
  342. package/dist/connections/Crypto.js.map +1 -0
  343. package/dist/connections/Destinations.d.ts +63 -0
  344. package/dist/connections/Destinations.d.ts.map +1 -0
  345. package/dist/connections/Destinations.js +338 -0
  346. package/dist/connections/Destinations.js.map +1 -0
  347. package/dist/connections/Discovery.d.ts +53 -0
  348. package/dist/connections/Discovery.d.ts.map +1 -0
  349. package/dist/connections/Discovery.js +209 -0
  350. package/dist/connections/Discovery.js.map +1 -0
  351. package/dist/connections/EffectKinds.d.ts +17 -0
  352. package/dist/connections/EffectKinds.d.ts.map +1 -0
  353. package/dist/connections/EffectKinds.js +26 -0
  354. package/dist/connections/EffectKinds.js.map +1 -0
  355. package/dist/connections/Effects.d.ts +49 -0
  356. package/dist/connections/Effects.d.ts.map +1 -0
  357. package/dist/connections/Effects.js +347 -0
  358. package/dist/connections/Effects.js.map +1 -0
  359. package/dist/connections/Metering.d.ts +40 -0
  360. package/dist/connections/Metering.d.ts.map +1 -0
  361. package/dist/connections/Metering.js +142 -0
  362. package/dist/connections/Metering.js.map +1 -0
  363. package/dist/connections/ProviderApi.d.ts +47 -0
  364. package/dist/connections/ProviderApi.d.ts.map +1 -0
  365. package/dist/connections/ProviderApi.js +103 -0
  366. package/dist/connections/ProviderApi.js.map +1 -0
  367. package/dist/connections/Secrets.d.ts +78 -0
  368. package/dist/connections/Secrets.d.ts.map +1 -0
  369. package/dist/connections/Secrets.js +342 -0
  370. package/dist/connections/Secrets.js.map +1 -0
  371. package/dist/connections/Sync.d.ts +85 -0
  372. package/dist/connections/Sync.d.ts.map +1 -0
  373. package/dist/connections/Sync.js +201 -0
  374. package/dist/connections/Sync.js.map +1 -0
  375. package/dist/connections/module.d.ts +1061 -0
  376. package/dist/connections/module.d.ts.map +1 -0
  377. package/dist/connections/module.js +485 -0
  378. package/dist/connections/module.js.map +1 -0
  379. package/dist/data/Corpus.d.ts +79 -0
  380. package/dist/data/Corpus.d.ts.map +1 -0
  381. package/dist/data/Corpus.js +343 -0
  382. package/dist/data/Corpus.js.map +1 -0
  383. package/dist/data/Datasets.d.ts +88 -0
  384. package/dist/data/Datasets.d.ts.map +1 -0
  385. package/dist/data/Datasets.js +375 -0
  386. package/dist/data/Datasets.js.map +1 -0
  387. package/dist/data/Programs.d.ts +58 -0
  388. package/dist/data/Programs.d.ts.map +1 -0
  389. package/dist/data/Programs.js +197 -0
  390. package/dist/data/Programs.js.map +1 -0
  391. package/dist/data/module.d.ts +210 -0
  392. package/dist/data/module.d.ts.map +1 -0
  393. package/dist/data/module.js +140 -0
  394. package/dist/data/module.js.map +1 -0
  395. package/dist/db/Bootstrap.d.ts +508 -0
  396. package/dist/db/Bootstrap.d.ts.map +1 -0
  397. package/dist/db/Bootstrap.js +2368 -0
  398. package/dist/db/Bootstrap.js.map +1 -0
  399. package/dist/db/Catalog.d.ts +10 -0
  400. package/dist/db/Catalog.d.ts.map +1 -0
  401. package/dist/db/Catalog.js +9 -0
  402. package/dist/db/Catalog.js.map +1 -0
  403. package/dist/db/Conflicts.d.ts +18 -0
  404. package/dist/db/Conflicts.d.ts.map +1 -0
  405. package/dist/db/Conflicts.js +29 -0
  406. package/dist/db/Conflicts.js.map +1 -0
  407. package/dist/db/DirectoryLock.d.ts +16 -0
  408. package/dist/db/DirectoryLock.d.ts.map +1 -0
  409. package/dist/db/DirectoryLock.js +15 -0
  410. package/dist/db/DirectoryLock.js.map +1 -0
  411. package/dist/db/HandlerGate.d.ts +28 -0
  412. package/dist/db/HandlerGate.d.ts.map +1 -0
  413. package/dist/db/HandlerGate.js +76 -0
  414. package/dist/db/HandlerGate.js.map +1 -0
  415. package/dist/db/Host.d.ts +94 -0
  416. package/dist/db/Host.d.ts.map +1 -0
  417. package/dist/db/Host.js +189 -0
  418. package/dist/db/Host.js.map +1 -0
  419. package/dist/db/KernelSchema.d.ts +52 -0
  420. package/dist/db/KernelSchema.d.ts.map +1 -0
  421. package/dist/db/KernelSchema.js +4313 -0
  422. package/dist/db/KernelSchema.js.map +1 -0
  423. package/dist/db/MigrationCheck.d.ts +38 -0
  424. package/dist/db/MigrationCheck.d.ts.map +1 -0
  425. package/dist/db/MigrationCheck.js +180 -0
  426. package/dist/db/MigrationCheck.js.map +1 -0
  427. package/dist/db/QueryViewCheck.d.ts +172 -0
  428. package/dist/db/QueryViewCheck.d.ts.map +1 -0
  429. package/dist/db/QueryViewCheck.js +967 -0
  430. package/dist/db/QueryViewCheck.js.map +1 -0
  431. package/dist/db/ReadOnly.d.ts +13 -0
  432. package/dist/db/ReadOnly.d.ts.map +1 -0
  433. package/dist/db/ReadOnly.js +16 -0
  434. package/dist/db/ReadOnly.js.map +1 -0
  435. package/dist/db/Scram.d.ts +5 -0
  436. package/dist/db/Scram.d.ts.map +1 -0
  437. package/dist/db/Scram.js +17 -0
  438. package/dist/db/Scram.js.map +1 -0
  439. package/dist/db/SqlState.d.ts +36 -0
  440. package/dist/db/SqlState.d.ts.map +1 -0
  441. package/dist/db/SqlState.js +64 -0
  442. package/dist/db/SqlState.js.map +1 -0
  443. package/dist/db/Startup.d.ts +18 -0
  444. package/dist/db/Startup.d.ts.map +1 -0
  445. package/dist/db/Startup.js +22 -0
  446. package/dist/db/Startup.js.map +1 -0
  447. package/dist/db/ZeroDdl.d.ts +85 -0
  448. package/dist/db/ZeroDdl.d.ts.map +1 -0
  449. package/dist/db/ZeroDdl.js +240 -0
  450. package/dist/db/ZeroDdl.js.map +1 -0
  451. package/dist/db/ZeroPush.d.ts +7 -0
  452. package/dist/db/ZeroPush.d.ts.map +1 -0
  453. package/dist/db/ZeroPush.js +126 -0
  454. package/dist/db/ZeroPush.js.map +1 -0
  455. package/dist/devices/Devices.d.ts +130 -0
  456. package/dist/devices/Devices.d.ts.map +1 -0
  457. package/dist/devices/Devices.js +769 -0
  458. package/dist/devices/Devices.js.map +1 -0
  459. package/dist/devices/Flow.d.ts +47 -0
  460. package/dist/devices/Flow.d.ts.map +1 -0
  461. package/dist/devices/Flow.js +131 -0
  462. package/dist/devices/Flow.js.map +1 -0
  463. package/dist/devices/Http.d.ts +6 -0
  464. package/dist/devices/Http.d.ts.map +1 -0
  465. package/dist/devices/Http.js +103 -0
  466. package/dist/devices/Http.js.map +1 -0
  467. package/dist/devices/module.d.ts +1313 -0
  468. package/dist/devices/module.d.ts.map +1 -0
  469. package/dist/devices/module.js +266 -0
  470. package/dist/devices/module.js.map +1 -0
  471. package/dist/durable/Cluster.d.ts +13 -0
  472. package/dist/durable/Cluster.d.ts.map +1 -0
  473. package/dist/durable/Cluster.js +57 -0
  474. package/dist/durable/Cluster.js.map +1 -0
  475. package/dist/durable/Definition.d.ts +215 -0
  476. package/dist/durable/Definition.d.ts.map +1 -0
  477. package/dist/durable/Definition.js +18 -0
  478. package/dist/durable/Definition.js.map +1 -0
  479. package/dist/durable/Schedule.d.ts +46 -0
  480. package/dist/durable/Schedule.d.ts.map +1 -0
  481. package/dist/durable/Schedule.js +120 -0
  482. package/dist/durable/Schedule.js.map +1 -0
  483. package/dist/durable/Trust.d.ts +90 -0
  484. package/dist/durable/Trust.d.ts.map +1 -0
  485. package/dist/durable/Trust.js +61 -0
  486. package/dist/durable/Trust.js.map +1 -0
  487. package/dist/enterprise/Routes.d.ts +32 -0
  488. package/dist/enterprise/Routes.d.ts.map +1 -0
  489. package/dist/enterprise/Routes.js +448 -0
  490. package/dist/enterprise/Routes.js.map +1 -0
  491. package/dist/enterprise/WorkOs.d.ts +42 -0
  492. package/dist/enterprise/WorkOs.d.ts.map +1 -0
  493. package/dist/enterprise/WorkOs.js +109 -0
  494. package/dist/enterprise/WorkOs.js.map +1 -0
  495. package/dist/files/FileTable.d.ts +937 -0
  496. package/dist/files/FileTable.d.ts.map +1 -0
  497. package/dist/files/FileTable.js +79 -0
  498. package/dist/files/FileTable.js.map +1 -0
  499. package/dist/files/Files.d.ts +169 -0
  500. package/dist/files/Files.d.ts.map +1 -0
  501. package/dist/files/Files.js +1232 -0
  502. package/dist/files/Files.js.map +1 -0
  503. package/dist/files/Http.d.ts +13 -0
  504. package/dist/files/Http.d.ts.map +1 -0
  505. package/dist/files/Http.js +30 -0
  506. package/dist/files/Http.js.map +1 -0
  507. package/dist/files/LocalStorage.d.ts +7 -0
  508. package/dist/files/LocalStorage.d.ts.map +1 -0
  509. package/dist/files/LocalStorage.js +284 -0
  510. package/dist/files/LocalStorage.js.map +1 -0
  511. package/dist/files/Providers.d.ts +64 -0
  512. package/dist/files/Providers.d.ts.map +1 -0
  513. package/dist/files/Providers.js +245 -0
  514. package/dist/files/Providers.js.map +1 -0
  515. package/dist/files/S3Storage.d.ts +27 -0
  516. package/dist/files/S3Storage.d.ts.map +1 -0
  517. package/dist/files/S3Storage.js +301 -0
  518. package/dist/files/S3Storage.js.map +1 -0
  519. package/dist/files/SigV4.d.ts +65 -0
  520. package/dist/files/SigV4.d.ts.map +1 -0
  521. package/dist/files/SigV4.js +152 -0
  522. package/dist/files/SigV4.js.map +1 -0
  523. package/dist/files/Sniff.d.ts +50 -0
  524. package/dist/files/Sniff.d.ts.map +1 -0
  525. package/dist/files/Sniff.js +223 -0
  526. package/dist/files/Sniff.js.map +1 -0
  527. package/dist/files/Storage.d.ts +75 -0
  528. package/dist/files/Storage.d.ts.map +1 -0
  529. package/dist/files/Storage.js +70 -0
  530. package/dist/files/Storage.js.map +1 -0
  531. package/dist/files/module.d.ts +666 -0
  532. package/dist/files/module.d.ts.map +1 -0
  533. package/dist/files/module.js +217 -0
  534. package/dist/files/module.js.map +1 -0
  535. package/dist/flags/module.d.ts +966 -0
  536. package/dist/flags/module.d.ts.map +1 -0
  537. package/dist/flags/module.js +146 -0
  538. package/dist/flags/module.js.map +1 -0
  539. package/dist/inbox/Flow.d.ts +49 -0
  540. package/dist/inbox/Flow.d.ts.map +1 -0
  541. package/dist/inbox/Flow.js +425 -0
  542. package/dist/inbox/Flow.js.map +1 -0
  543. package/dist/inbox/System.d.ts +11 -0
  544. package/dist/inbox/System.d.ts.map +1 -0
  545. package/dist/inbox/System.js +26 -0
  546. package/dist/inbox/System.js.map +1 -0
  547. package/dist/inbox/approvals.d.ts +1548 -0
  548. package/dist/inbox/approvals.d.ts.map +1 -0
  549. package/dist/inbox/approvals.js +268 -0
  550. package/dist/inbox/approvals.js.map +1 -0
  551. package/dist/inbox/consent.d.ts +1213 -0
  552. package/dist/inbox/consent.d.ts.map +1 -0
  553. package/dist/inbox/consent.js +281 -0
  554. package/dist/inbox/consent.js.map +1 -0
  555. package/dist/inbox/index.d.ts +2231 -0
  556. package/dist/inbox/index.d.ts.map +1 -0
  557. package/dist/inbox/index.js +22 -0
  558. package/dist/inbox/index.js.map +1 -0
  559. package/dist/inbox/notifications.d.ts +2743 -0
  560. package/dist/inbox/notifications.d.ts.map +1 -0
  561. package/dist/inbox/notifications.js +362 -0
  562. package/dist/inbox/notifications.js.map +1 -0
  563. package/dist/inbox/tables.d.ts +1992 -0
  564. package/dist/inbox/tables.d.ts.map +1 -0
  565. package/dist/inbox/tables.js +149 -0
  566. package/dist/inbox/tables.js.map +1 -0
  567. package/dist/inbox/workItems.d.ts +1188 -0
  568. package/dist/inbox/workItems.d.ts.map +1 -0
  569. package/dist/inbox/workItems.js +158 -0
  570. package/dist/inbox/workItems.js.map +1 -0
  571. package/dist/index.d.ts +152 -0
  572. package/dist/index.d.ts.map +1 -0
  573. package/dist/index.js +154 -0
  574. package/dist/index.js.map +1 -0
  575. package/dist/ingestion/Chunk.d.ts +15 -0
  576. package/dist/ingestion/Chunk.d.ts.map +1 -0
  577. package/dist/ingestion/Chunk.js +49 -0
  578. package/dist/ingestion/Chunk.js.map +1 -0
  579. package/dist/ingestion/Extract.d.ts +69 -0
  580. package/dist/ingestion/Extract.d.ts.map +1 -0
  581. package/dist/ingestion/Extract.js +376 -0
  582. package/dist/ingestion/Extract.js.map +1 -0
  583. package/dist/ingestion/ExtractChild.d.ts +2 -0
  584. package/dist/ingestion/ExtractChild.d.ts.map +1 -0
  585. package/dist/ingestion/ExtractChild.js +54 -0
  586. package/dist/ingestion/ExtractChild.js.map +1 -0
  587. package/dist/ingestion/ExtractPool.d.ts +38 -0
  588. package/dist/ingestion/ExtractPool.d.ts.map +1 -0
  589. package/dist/ingestion/ExtractPool.js +203 -0
  590. package/dist/ingestion/ExtractPool.js.map +1 -0
  591. package/dist/ingestion/Ingestion.d.ts +183 -0
  592. package/dist/ingestion/Ingestion.d.ts.map +1 -0
  593. package/dist/ingestion/Ingestion.js +650 -0
  594. package/dist/ingestion/Ingestion.js.map +1 -0
  595. package/dist/ingestion/Isolated.d.ts +18 -0
  596. package/dist/ingestion/Isolated.d.ts.map +1 -0
  597. package/dist/ingestion/Isolated.js +15 -0
  598. package/dist/ingestion/Isolated.js.map +1 -0
  599. package/dist/ingestion/Markup.d.ts +29 -0
  600. package/dist/ingestion/Markup.d.ts.map +1 -0
  601. package/dist/ingestion/Markup.js +111 -0
  602. package/dist/ingestion/Markup.js.map +1 -0
  603. package/dist/ingestion/Pdf.d.ts +6 -0
  604. package/dist/ingestion/Pdf.d.ts.map +1 -0
  605. package/dist/ingestion/Pdf.js +192 -0
  606. package/dist/ingestion/Pdf.js.map +1 -0
  607. package/dist/ingestion/Runs.d.ts +59 -0
  608. package/dist/ingestion/Runs.d.ts.map +1 -0
  609. package/dist/ingestion/Runs.js +128 -0
  610. package/dist/ingestion/Runs.js.map +1 -0
  611. package/dist/ingestion/Scrub.d.ts +16 -0
  612. package/dist/ingestion/Scrub.d.ts.map +1 -0
  613. package/dist/ingestion/Scrub.js +15 -0
  614. package/dist/ingestion/Scrub.js.map +1 -0
  615. package/dist/ingestion/Zip.d.ts +19 -0
  616. package/dist/ingestion/Zip.d.ts.map +1 -0
  617. package/dist/ingestion/Zip.js +85 -0
  618. package/dist/ingestion/Zip.js.map +1 -0
  619. package/dist/ingestion/module.d.ts +111 -0
  620. package/dist/ingestion/module.d.ts.map +1 -0
  621. package/dist/ingestion/module.js +51 -0
  622. package/dist/ingestion/module.js.map +1 -0
  623. package/dist/ingress/Definition.d.ts +146 -0
  624. package/dist/ingress/Definition.d.ts.map +1 -0
  625. package/dist/ingress/Definition.js +12 -0
  626. package/dist/ingress/Definition.js.map +1 -0
  627. package/dist/ingress/Ingress.d.ts +61 -0
  628. package/dist/ingress/Ingress.d.ts.map +1 -0
  629. package/dist/ingress/Ingress.js +929 -0
  630. package/dist/ingress/Ingress.js.map +1 -0
  631. package/dist/ingress/Verifiers.d.ts +43 -0
  632. package/dist/ingress/Verifiers.d.ts.map +1 -0
  633. package/dist/ingress/Verifiers.js +137 -0
  634. package/dist/ingress/Verifiers.js.map +1 -0
  635. package/dist/machine/MachineIdentity.d.ts +34 -0
  636. package/dist/machine/MachineIdentity.d.ts.map +1 -0
  637. package/dist/machine/MachineIdentity.js +200 -0
  638. package/dist/machine/MachineIdentity.js.map +1 -0
  639. package/dist/machine/Managed.d.ts +40 -0
  640. package/dist/machine/Managed.d.ts.map +1 -0
  641. package/dist/machine/Managed.js +163 -0
  642. package/dist/machine/Managed.js.map +1 -0
  643. package/dist/machine/OAuth.d.ts +11 -0
  644. package/dist/machine/OAuth.d.ts.map +1 -0
  645. package/dist/machine/OAuth.js +913 -0
  646. package/dist/machine/OAuth.js.map +1 -0
  647. package/dist/machine/Pages.d.ts +64 -0
  648. package/dist/machine/Pages.d.ts.map +1 -0
  649. package/dist/machine/Pages.js +54 -0
  650. package/dist/machine/Pages.js.map +1 -0
  651. package/dist/machine/Tokens.d.ts +25 -0
  652. package/dist/machine/Tokens.d.ts.map +1 -0
  653. package/dist/machine/Tokens.js +62 -0
  654. package/dist/machine/Tokens.js.map +1 -0
  655. package/dist/make/Credentials.d.ts +8 -0
  656. package/dist/make/Credentials.d.ts.map +1 -0
  657. package/dist/make/Credentials.js +29 -0
  658. package/dist/make/Credentials.js.map +1 -0
  659. package/dist/make/Example.d.ts +159 -0
  660. package/dist/make/Example.d.ts.map +1 -0
  661. package/dist/make/Example.js +94 -0
  662. package/dist/make/Example.js.map +1 -0
  663. package/dist/make/Execute.d.ts +151 -0
  664. package/dist/make/Execute.d.ts.map +1 -0
  665. package/dist/make/Execute.js +316 -0
  666. package/dist/make/Execute.js.map +1 -0
  667. package/dist/make/Http.d.ts +17 -0
  668. package/dist/make/Http.d.ts.map +1 -0
  669. package/dist/make/Http.js +63 -0
  670. package/dist/make/Http.js.map +1 -0
  671. package/dist/make/Lifecycle.d.ts +167 -0
  672. package/dist/make/Lifecycle.d.ts.map +1 -0
  673. package/dist/make/Lifecycle.js +580 -0
  674. package/dist/make/Lifecycle.js.map +1 -0
  675. package/dist/make/Manifest.d.ts +61 -0
  676. package/dist/make/Manifest.d.ts.map +1 -0
  677. package/dist/make/Manifest.js +792 -0
  678. package/dist/make/Manifest.js.map +1 -0
  679. package/dist/make/Repair.d.ts +111 -0
  680. package/dist/make/Repair.d.ts.map +1 -0
  681. package/dist/make/Repair.js +236 -0
  682. package/dist/make/Repair.js.map +1 -0
  683. package/dist/make/Runtime.d.ts +144 -0
  684. package/dist/make/Runtime.d.ts.map +1 -0
  685. package/dist/make/Runtime.js +309 -0
  686. package/dist/make/Runtime.js.map +1 -0
  687. package/dist/make/Session.d.ts +19 -0
  688. package/dist/make/Session.d.ts.map +1 -0
  689. package/dist/make/Session.js +27 -0
  690. package/dist/make/Session.js.map +1 -0
  691. package/dist/make/SqlGuard.d.ts +48 -0
  692. package/dist/make/SqlGuard.d.ts.map +1 -0
  693. package/dist/make/SqlGuard.js +333 -0
  694. package/dist/make/SqlGuard.js.map +1 -0
  695. package/dist/make/Subscribe.d.ts +18 -0
  696. package/dist/make/Subscribe.d.ts.map +1 -0
  697. package/dist/make/Subscribe.js +175 -0
  698. package/dist/make/Subscribe.js.map +1 -0
  699. package/dist/make/Validate.d.ts +47 -0
  700. package/dist/make/Validate.d.ts.map +1 -0
  701. package/dist/make/Validate.js +222 -0
  702. package/dist/make/Validate.js.map +1 -0
  703. package/dist/make/ViewStep.d.ts +27 -0
  704. package/dist/make/ViewStep.d.ts.map +1 -0
  705. package/dist/make/ViewStep.js +43 -0
  706. package/dist/make/ViewStep.js.map +1 -0
  707. package/dist/make/module.d.ts +808 -0
  708. package/dist/make/module.d.ts.map +1 -0
  709. package/dist/make/module.js +232 -0
  710. package/dist/make/module.js.map +1 -0
  711. package/dist/notifications/Decide.d.ts +29 -0
  712. package/dist/notifications/Decide.d.ts.map +1 -0
  713. package/dist/notifications/Decide.js +395 -0
  714. package/dist/notifications/Decide.js.map +1 -0
  715. package/dist/notifications/Providers.d.ts +110 -0
  716. package/dist/notifications/Providers.d.ts.map +1 -0
  717. package/dist/notifications/Providers.js +404 -0
  718. package/dist/notifications/Providers.js.map +1 -0
  719. package/dist/notifications/Push.d.ts +189 -0
  720. package/dist/notifications/Push.d.ts.map +1 -0
  721. package/dist/notifications/Push.js +457 -0
  722. package/dist/notifications/Push.js.map +1 -0
  723. package/dist/notifications/Smtp.d.ts +74 -0
  724. package/dist/notifications/Smtp.d.ts.map +1 -0
  725. package/dist/notifications/Smtp.js +344 -0
  726. package/dist/notifications/Smtp.js.map +1 -0
  727. package/dist/policy/CedarSchema.d.ts +47 -0
  728. package/dist/policy/CedarSchema.d.ts.map +1 -0
  729. package/dist/policy/CedarSchema.js +115 -0
  730. package/dist/policy/CedarSchema.js.map +1 -0
  731. package/dist/policy/Compiler.d.ts +364 -0
  732. package/dist/policy/Compiler.d.ts.map +1 -0
  733. package/dist/policy/Compiler.js +1311 -0
  734. package/dist/policy/Compiler.js.map +1 -0
  735. package/dist/policy/Policy.d.ts +70 -0
  736. package/dist/policy/Policy.d.ts.map +1 -0
  737. package/dist/policy/Policy.js +114 -0
  738. package/dist/policy/Policy.js.map +1 -0
  739. package/dist/policy/Rls.d.ts +110 -0
  740. package/dist/policy/Rls.d.ts.map +1 -0
  741. package/dist/policy/Rls.js +314 -0
  742. package/dist/policy/Rls.js.map +1 -0
  743. package/dist/policy/Row.d.ts +17 -0
  744. package/dist/policy/Row.d.ts.map +1 -0
  745. package/dist/policy/Row.js +3 -0
  746. package/dist/policy/Row.js.map +1 -0
  747. package/dist/privacy/Flow.d.ts +20 -0
  748. package/dist/privacy/Flow.d.ts.map +1 -0
  749. package/dist/privacy/Flow.js +193 -0
  750. package/dist/privacy/Flow.js.map +1 -0
  751. package/dist/privacy/Inventory.d.ts +110 -0
  752. package/dist/privacy/Inventory.d.ts.map +1 -0
  753. package/dist/privacy/Inventory.js +1704 -0
  754. package/dist/privacy/Inventory.js.map +1 -0
  755. package/dist/privacy/Sources.d.ts +86 -0
  756. package/dist/privacy/Sources.d.ts.map +1 -0
  757. package/dist/privacy/Sources.js +598 -0
  758. package/dist/privacy/Sources.js.map +1 -0
  759. package/dist/privacy/Visits.d.ts +21 -0
  760. package/dist/privacy/Visits.d.ts.map +1 -0
  761. package/dist/privacy/Visits.js +279 -0
  762. package/dist/privacy/Visits.js.map +1 -0
  763. package/dist/privacy/ZeroCvr.d.ts +15 -0
  764. package/dist/privacy/ZeroCvr.d.ts.map +1 -0
  765. package/dist/privacy/ZeroCvr.js +63 -0
  766. package/dist/privacy/ZeroCvr.js.map +1 -0
  767. package/dist/privacy/module.d.ts +2505 -0
  768. package/dist/privacy/module.d.ts.map +1 -0
  769. package/dist/privacy/module.js +228 -0
  770. package/dist/privacy/module.js.map +1 -0
  771. package/dist/progress/module.d.ts +1572 -0
  772. package/dist/progress/module.d.ts.map +1 -0
  773. package/dist/progress/module.js +139 -0
  774. package/dist/progress/module.js.map +1 -0
  775. package/dist/proposals/module.d.ts +275 -0
  776. package/dist/proposals/module.d.ts.map +1 -0
  777. package/dist/proposals/module.js +269 -0
  778. package/dist/proposals/module.js.map +1 -0
  779. package/dist/query/module.d.ts +91 -0
  780. package/dist/query/module.d.ts.map +1 -0
  781. package/dist/query/module.js +50 -0
  782. package/dist/query/module.js.map +1 -0
  783. package/dist/records/Access.d.ts +26 -0
  784. package/dist/records/Access.d.ts.map +1 -0
  785. package/dist/records/Access.js +43 -0
  786. package/dist/records/Access.js.map +1 -0
  787. package/dist/records/References.d.ts +18 -0
  788. package/dist/records/References.d.ts.map +1 -0
  789. package/dist/records/References.js +47 -0
  790. package/dist/records/References.js.map +1 -0
  791. package/dist/runtime/bun.d.ts +29 -0
  792. package/dist/runtime/bun.d.ts.map +1 -0
  793. package/dist/runtime/bun.js +71 -0
  794. package/dist/runtime/bun.js.map +1 -0
  795. package/dist/runtime/idle.d.ts +5 -0
  796. package/dist/runtime/idle.d.ts.map +1 -0
  797. package/dist/runtime/idle.js +61 -0
  798. package/dist/runtime/idle.js.map +1 -0
  799. package/dist/runtime/node.d.ts +36 -0
  800. package/dist/runtime/node.d.ts.map +1 -0
  801. package/dist/runtime/node.js +86 -0
  802. package/dist/runtime/node.js.map +1 -0
  803. package/dist/runtime/resolve.d.ts +8 -0
  804. package/dist/runtime/resolve.d.ts.map +1 -0
  805. package/dist/runtime/resolve.js +136 -0
  806. package/dist/runtime/resolve.js.map +1 -0
  807. package/dist/sandbox/Sandbox.d.ts +86 -0
  808. package/dist/sandbox/Sandbox.d.ts.map +1 -0
  809. package/dist/sandbox/Sandbox.js +246 -0
  810. package/dist/sandbox/Sandbox.js.map +1 -0
  811. package/dist/sandbox/worker.d.ts +93 -0
  812. package/dist/sandbox/worker.d.ts.map +1 -0
  813. package/dist/sandbox/worker.js +503 -0
  814. package/dist/sandbox/worker.js.map +1 -0
  815. package/dist/scheduler/Automations.d.ts +99 -0
  816. package/dist/scheduler/Automations.d.ts.map +1 -0
  817. package/dist/scheduler/Automations.js +247 -0
  818. package/dist/scheduler/Automations.js.map +1 -0
  819. package/dist/scheduler/History.d.ts +61 -0
  820. package/dist/scheduler/History.d.ts.map +1 -0
  821. package/dist/scheduler/History.js +154 -0
  822. package/dist/scheduler/History.js.map +1 -0
  823. package/dist/scheduler/module.d.ts +2365 -0
  824. package/dist/scheduler/module.d.ts.map +1 -0
  825. package/dist/scheduler/module.js +370 -0
  826. package/dist/scheduler/module.js.map +1 -0
  827. package/dist/search/RecordLock.d.ts +22 -0
  828. package/dist/search/RecordLock.d.ts.map +1 -0
  829. package/dist/search/RecordLock.js +21 -0
  830. package/dist/search/RecordLock.js.map +1 -0
  831. package/dist/search/Search.d.ts +63 -0
  832. package/dist/search/Search.d.ts.map +1 -0
  833. package/dist/search/Search.js +424 -0
  834. package/dist/search/Search.js.map +1 -0
  835. package/dist/search/Sources.d.ts +56 -0
  836. package/dist/search/Sources.d.ts.map +1 -0
  837. package/dist/search/Sources.js +121 -0
  838. package/dist/search/Sources.js.map +1 -0
  839. package/dist/search/module.d.ts +72 -0
  840. package/dist/search/module.d.ts.map +1 -0
  841. package/dist/search/module.js +44 -0
  842. package/dist/search/module.js.map +1 -0
  843. package/dist/settings/module.d.ts +677 -0
  844. package/dist/settings/module.d.ts.map +1 -0
  845. package/dist/settings/module.js +103 -0
  846. package/dist/settings/module.js.map +1 -0
  847. package/dist/sharing/module.d.ts +1105 -0
  848. package/dist/sharing/module.d.ts.map +1 -0
  849. package/dist/sharing/module.js +295 -0
  850. package/dist/sharing/module.js.map +1 -0
  851. package/dist/spaces/module.d.ts +1787 -0
  852. package/dist/spaces/module.d.ts.map +1 -0
  853. package/dist/spaces/module.js +248 -0
  854. package/dist/spaces/module.js.map +1 -0
  855. package/dist/surfaces/Agent.d.ts +89 -0
  856. package/dist/surfaces/Agent.d.ts.map +1 -0
  857. package/dist/surfaces/Agent.js +112 -0
  858. package/dist/surfaces/Agent.js.map +1 -0
  859. package/dist/surfaces/CookieGuard.d.ts +77 -0
  860. package/dist/surfaces/CookieGuard.d.ts.map +1 -0
  861. package/dist/surfaces/CookieGuard.js +373 -0
  862. package/dist/surfaces/CookieGuard.js.map +1 -0
  863. package/dist/surfaces/Http.d.ts +15 -0
  864. package/dist/surfaces/Http.d.ts.map +1 -0
  865. package/dist/surfaces/Http.js +250 -0
  866. package/dist/surfaces/Http.js.map +1 -0
  867. package/dist/surfaces/Mcp.d.ts +90 -0
  868. package/dist/surfaces/Mcp.d.ts.map +1 -0
  869. package/dist/surfaces/Mcp.js +443 -0
  870. package/dist/surfaces/Mcp.js.map +1 -0
  871. package/dist/surfaces/Rpc.d.ts +15 -0
  872. package/dist/surfaces/Rpc.d.ts.map +1 -0
  873. package/dist/surfaces/Rpc.js +68 -0
  874. package/dist/surfaces/Rpc.js.map +1 -0
  875. package/dist/surfaces/headers.d.ts +9 -0
  876. package/dist/surfaces/headers.d.ts.map +1 -0
  877. package/dist/surfaces/headers.js +15 -0
  878. package/dist/surfaces/headers.js.map +1 -0
  879. package/dist/surfaces/request.d.ts +68 -0
  880. package/dist/surfaces/request.d.ts.map +1 -0
  881. package/dist/surfaces/request.js +130 -0
  882. package/dist/surfaces/request.js.map +1 -0
  883. package/dist/telemetry/module.d.ts +74 -0
  884. package/dist/telemetry/module.d.ts.map +1 -0
  885. package/dist/telemetry/module.js +77 -0
  886. package/dist/telemetry/module.js.map +1 -0
  887. package/dist/versioning/module.d.ts +231 -0
  888. package/dist/versioning/module.d.ts.map +1 -0
  889. package/dist/versioning/module.js +151 -0
  890. package/dist/versioning/module.js.map +1 -0
  891. package/package.json +71 -3
  892. package/src/AccountMail.ts +218 -0
  893. package/src/AppConfig.ts +148 -0
  894. package/src/Approvals.ts +555 -0
  895. package/src/Audit.ts +381 -0
  896. package/src/AuthSeam.ts +136 -0
  897. package/src/Authority.ts +577 -0
  898. package/src/Avatars.ts +172 -0
  899. package/src/Base64url.ts +23 -0
  900. package/src/BasePath.ts +80 -0
  901. package/src/CallActed.ts +10 -0
  902. package/src/Config.ts +857 -0
  903. package/src/DeliveryPolicy.ts +52 -0
  904. package/src/DesktopSignIn.ts +181 -0
  905. package/src/Directory.ts +1792 -0
  906. package/src/Flags.ts +281 -0
  907. package/src/Gate.ts +159 -0
  908. package/src/Hash.ts +14 -0
  909. package/src/Identity.ts +1811 -0
  910. package/src/IntervalJob.ts +96 -0
  911. package/src/Invocation.ts +2387 -0
  912. package/src/KernelHandlers.ts +29 -0
  913. package/src/KernelModule.ts +165 -0
  914. package/src/MemberRoutes.ts +146 -0
  915. package/src/Module.ts +573 -0
  916. package/src/ModuleIdentity.ts +134 -0
  917. package/src/Notifications.ts +665 -0
  918. package/src/Outbox.ts +761 -0
  919. package/src/Privacy.ts +265 -0
  920. package/src/Progress.ts +360 -0
  921. package/src/QuerySurface.ts +559 -0
  922. package/src/QueryViews.ts +165 -0
  923. package/src/Readiness.ts +284 -0
  924. package/src/Redact.ts +22 -0
  925. package/src/Registry.ts +399 -0
  926. package/src/Release.ts +1197 -0
  927. package/src/Retention.ts +167 -0
  928. package/src/Scheduler.ts +657 -0
  929. package/src/Server.ts +1838 -0
  930. package/src/Sessions.ts +56 -0
  931. package/src/Settings.ts +312 -0
  932. package/src/Sharing.ts +525 -0
  933. package/src/Sync.ts +1478 -0
  934. package/src/Telemetry.ts +754 -0
  935. package/src/Versioning.ts +588 -0
  936. package/src/WorkItems.ts +367 -0
  937. package/src/Workflows.ts +746 -0
  938. package/src/agent/Admission.ts +37 -0
  939. package/src/agent/Channels.ts +58 -0
  940. package/src/agent/Context.ts +430 -0
  941. package/src/agent/Http.ts +523 -0
  942. package/src/agent/Metering.ts +625 -0
  943. package/src/agent/ModelSetup.ts +414 -0
  944. package/src/agent/Models.ts +850 -0
  945. package/src/agent/Processors.ts +156 -0
  946. package/src/agent/Queue.ts +97 -0
  947. package/src/agent/Receipts.ts +192 -0
  948. package/src/agent/Resources.ts +376 -0
  949. package/src/agent/Run.ts +3762 -0
  950. package/src/agent/Runtime.ts +635 -0
  951. package/src/agent/Settings.ts +171 -0
  952. package/src/agent/Skills.ts +118 -0
  953. package/src/agent/Store.ts +73 -0
  954. package/src/agent/ToolSearch.ts +152 -0
  955. package/src/agent/index.ts +68 -0
  956. package/src/agent/migrations/agent/0000_agent.sql +162 -0
  957. package/src/agent/migrations/agent/0001_model_call.sql +33 -0
  958. package/src/agent/migrations/agent/0002_device.sql +2 -0
  959. package/src/agent/migrations/agent/0003_authority.sql +1 -0
  960. package/src/agent/migrations/agent/0004_budget_alert.sql +2 -0
  961. package/src/agent/migrations/agent/0005_feedback.sql +13 -0
  962. package/src/agent/migrations/agent/0095_run_options.sql +3 -0
  963. package/src/agent/migrations/agent/0096_conversation_meta.sql +7 -0
  964. package/src/agent/migrations/agent/0097_submission.sql +26 -0
  965. package/src/agent/migrations/agent/0098_threads.sql +21 -0
  966. package/src/agent/migrations/agent/0099_submission_refused.sql +4 -0
  967. package/src/agent/migrations/agent/0142_teams.sql +19 -0
  968. package/src/agent/module.ts +1793 -0
  969. package/src/appState/Sweep.ts +66 -0
  970. package/src/appState/migrations/0000_app_state.sql +35 -0
  971. package/src/appState/module.ts +418 -0
  972. package/src/audit/migrations/README.md +1 -0
  973. package/src/audit/module.ts +95 -0
  974. package/src/auth/AuthProvider.ts +293 -0
  975. package/src/auth/BetterAuthProvider.ts +476 -0
  976. package/src/auth/Methods.ts +7 -0
  977. package/src/auth/SessionTokens.ts +156 -0
  978. package/src/collab/Collab.ts +708 -0
  979. package/src/collab/Housekeeping.ts +193 -0
  980. package/src/collab/LiveCopy.ts +98 -0
  981. package/src/collab/Socket.ts +380 -0
  982. package/src/collab/Store.ts +105 -0
  983. package/src/collab/Ydoc.ts +337 -0
  984. package/src/collab/derive/bundle.gen.ts +2 -0
  985. package/src/collab/derive/entry.ts +34 -0
  986. package/src/collab/derive/polyfill.ts +15 -0
  987. package/src/collab/migrations/.gitkeep +0 -0
  988. package/src/collab/module.ts +237 -0
  989. package/src/connections/Connections.ts +2315 -0
  990. package/src/connections/Connector.ts +304 -0
  991. package/src/connections/Crypto.ts +134 -0
  992. package/src/connections/Destinations.ts +351 -0
  993. package/src/connections/Discovery.ts +251 -0
  994. package/src/connections/EffectKinds.ts +30 -0
  995. package/src/connections/Effects.ts +541 -0
  996. package/src/connections/Metering.ts +205 -0
  997. package/src/connections/ProviderApi.ts +137 -0
  998. package/src/connections/Secrets.ts +581 -0
  999. package/src/connections/Sync.ts +318 -0
  1000. package/src/connections/migrations/.gitkeep +0 -0
  1001. package/src/connections/module.ts +584 -0
  1002. package/src/data/Corpus.ts +434 -0
  1003. package/src/data/Datasets.ts +479 -0
  1004. package/src/data/Programs.ts +285 -0
  1005. package/src/data/migrations/README.md +1 -0
  1006. package/src/data/module.ts +177 -0
  1007. package/src/db/Bootstrap.ts +2832 -0
  1008. package/src/db/Catalog.ts +10 -0
  1009. package/src/db/Conflicts.ts +42 -0
  1010. package/src/db/DirectoryLock.ts +19 -0
  1011. package/src/db/HandlerGate.ts +107 -0
  1012. package/src/db/Host.ts +250 -0
  1013. package/src/db/KernelSchema.ts +4422 -0
  1014. package/src/db/MigrationCheck.ts +221 -0
  1015. package/src/db/QueryViewCheck.ts +1035 -0
  1016. package/src/db/ReadOnly.ts +23 -0
  1017. package/src/db/Scram.ts +20 -0
  1018. package/src/db/SqlState.ts +77 -0
  1019. package/src/db/Startup.ts +25 -0
  1020. package/src/db/ZeroDdl.ts +272 -0
  1021. package/src/db/ZeroPush.ts +128 -0
  1022. package/src/db/schema.snapshot.json +13831 -0
  1023. package/src/devices/Devices.ts +1219 -0
  1024. package/src/devices/Flow.ts +198 -0
  1025. package/src/devices/Http.ts +212 -0
  1026. package/src/devices/migrations/0000_devices.sql +53 -0
  1027. package/src/devices/migrations/0001_parent_run.sql +2 -0
  1028. package/src/devices/migrations/0002_authority.sql +1 -0
  1029. package/src/devices/migrations/0003_follow_up.sql +4 -0
  1030. package/src/devices/migrations/0004_commands.sql +30 -0
  1031. package/src/devices/migrations/0005_command_cancel.sql +7 -0
  1032. package/src/devices/module.ts +313 -0
  1033. package/src/durable/Cluster.ts +90 -0
  1034. package/src/durable/Definition.ts +244 -0
  1035. package/src/durable/Schedule.ts +155 -0
  1036. package/src/durable/Trust.ts +149 -0
  1037. package/src/enterprise/Routes.ts +501 -0
  1038. package/src/enterprise/WorkOs.ts +133 -0
  1039. package/src/files/FileTable.ts +84 -0
  1040. package/src/files/Files.ts +1652 -0
  1041. package/src/files/Http.ts +46 -0
  1042. package/src/files/LocalStorage.ts +348 -0
  1043. package/src/files/Providers.ts +356 -0
  1044. package/src/files/S3Storage.ts +403 -0
  1045. package/src/files/SigV4.ts +222 -0
  1046. package/src/files/Sniff.ts +218 -0
  1047. package/src/files/Storage.ts +143 -0
  1048. package/src/files/migrations/README.md +1 -0
  1049. package/src/files/module.ts +282 -0
  1050. package/src/flags/migrations/0000_flags.sql +20 -0
  1051. package/src/flags/module.ts +178 -0
  1052. package/src/inbox/Flow.ts +548 -0
  1053. package/src/inbox/System.ts +33 -0
  1054. package/src/inbox/approvals.ts +335 -0
  1055. package/src/inbox/consent.ts +331 -0
  1056. package/src/inbox/index.ts +24 -0
  1057. package/src/inbox/migrations/approvals/0000_approvals.sql +36 -0
  1058. package/src/inbox/migrations/approvals/0001_provenance.sql +1 -0
  1059. package/src/inbox/migrations/approvals/0002_withdrawn.sql +3 -0
  1060. package/src/inbox/migrations/approvals/0003_title.sql +11 -0
  1061. package/src/inbox/migrations/consent/0000_consent.sql +31 -0
  1062. package/src/inbox/migrations/consent/0001_consent_revoked.sql +3 -0
  1063. package/src/inbox/migrations/consent/0002_permission_request.sql +1 -0
  1064. package/src/inbox/migrations/consent/0003_title.sql +11 -0
  1065. package/src/inbox/migrations/inbox/0000_work_items.sql +31 -0
  1066. package/src/inbox/migrations/notifications/0000_notifications.sql +66 -0
  1067. package/src/inbox/notifications.ts +471 -0
  1068. package/src/inbox/tables.ts +163 -0
  1069. package/src/inbox/workItems.ts +199 -0
  1070. package/src/index.ts +229 -0
  1071. package/src/ingestion/Chunk.ts +49 -0
  1072. package/src/ingestion/Extract.ts +387 -0
  1073. package/src/ingestion/ExtractChild.ts +67 -0
  1074. package/src/ingestion/ExtractPool.ts +270 -0
  1075. package/src/ingestion/Ingestion.ts +929 -0
  1076. package/src/ingestion/Isolated.ts +26 -0
  1077. package/src/ingestion/Markup.ts +117 -0
  1078. package/src/ingestion/Pdf.ts +167 -0
  1079. package/src/ingestion/Runs.ts +192 -0
  1080. package/src/ingestion/Scrub.ts +22 -0
  1081. package/src/ingestion/Zip.ts +87 -0
  1082. package/src/ingestion/migrations/README.md +1 -0
  1083. package/src/ingestion/module.ts +65 -0
  1084. package/src/ingress/Definition.ts +158 -0
  1085. package/src/ingress/Ingress.ts +1220 -0
  1086. package/src/ingress/Verifiers.ts +166 -0
  1087. package/src/machine/MachineIdentity.ts +310 -0
  1088. package/src/machine/Managed.ts +228 -0
  1089. package/src/machine/OAuth.ts +1140 -0
  1090. package/src/machine/Pages.ts +139 -0
  1091. package/src/machine/Tokens.ts +75 -0
  1092. package/src/make/Credentials.ts +36 -0
  1093. package/src/make/Example.ts +104 -0
  1094. package/src/make/Execute.ts +534 -0
  1095. package/src/make/Http.ts +71 -0
  1096. package/src/make/Lifecycle.ts +911 -0
  1097. package/src/make/Manifest.ts +884 -0
  1098. package/src/make/Repair.ts +262 -0
  1099. package/src/make/Runtime.ts +494 -0
  1100. package/src/make/Session.ts +33 -0
  1101. package/src/make/SqlGuard.ts +362 -0
  1102. package/src/make/Subscribe.ts +282 -0
  1103. package/src/make/Validate.ts +247 -0
  1104. package/src/make/ViewStep.ts +64 -0
  1105. package/src/make/migrations/README.md +1 -0
  1106. package/src/make/module.ts +261 -0
  1107. package/src/notifications/Decide.ts +483 -0
  1108. package/src/notifications/Providers.ts +532 -0
  1109. package/src/notifications/Push.ts +594 -0
  1110. package/src/notifications/Smtp.ts +379 -0
  1111. package/src/policy/CedarSchema.ts +156 -0
  1112. package/src/policy/Compiler.ts +1627 -0
  1113. package/src/policy/Policy.ts +178 -0
  1114. package/src/policy/Rls.ts +460 -0
  1115. package/src/policy/Row.ts +15 -0
  1116. package/src/privacy/Flow.ts +283 -0
  1117. package/src/privacy/Inventory.ts +2414 -0
  1118. package/src/privacy/Sources.ts +831 -0
  1119. package/src/privacy/Visits.ts +339 -0
  1120. package/src/privacy/ZeroCvr.ts +66 -0
  1121. package/src/privacy/migrations/0000_privacy.sql +48 -0
  1122. package/src/privacy/module.ts +280 -0
  1123. package/src/progress/migrations/0000_progress.sql +27 -0
  1124. package/src/progress/migrations/0001_notify.sql +1 -0
  1125. package/src/progress/module.ts +161 -0
  1126. package/src/proposals/migrations/README.md +1 -0
  1127. package/src/proposals/module.ts +338 -0
  1128. package/src/query/migrations/README.md +1 -0
  1129. package/src/query/module.ts +66 -0
  1130. package/src/records/Access.ts +97 -0
  1131. package/src/records/References.ts +65 -0
  1132. package/src/runtime/bun.ts +131 -0
  1133. package/src/runtime/idle.ts +88 -0
  1134. package/src/runtime/node.ts +140 -0
  1135. package/src/runtime/resolve.ts +141 -0
  1136. package/src/sandbox/Sandbox.ts +330 -0
  1137. package/src/sandbox/worker.ts +577 -0
  1138. package/src/scheduler/Automations.ts +319 -0
  1139. package/src/scheduler/History.ts +231 -0
  1140. package/src/scheduler/migrations/0000_schedules.sql +11 -0
  1141. package/src/scheduler/migrations/0001_resumed_at.sql +1 -0
  1142. package/src/scheduler/migrations/0002_origin.sql +3 -0
  1143. package/src/scheduler/migrations/0003_authority.sql +1 -0
  1144. package/src/scheduler/migrations/0004_operate.sql +18 -0
  1145. package/src/scheduler/module.ts +445 -0
  1146. package/src/search/RecordLock.ts +25 -0
  1147. package/src/search/Search.ts +563 -0
  1148. package/src/search/Sources.ts +157 -0
  1149. package/src/search/migrations/README.md +1 -0
  1150. package/src/search/module.ts +49 -0
  1151. package/src/settings/migrations/0000_settings.sql +15 -0
  1152. package/src/settings/module.ts +126 -0
  1153. package/src/sharing/migrations/0000_access_requests.sql +17 -0
  1154. package/src/sharing/module.ts +351 -0
  1155. package/src/spaces/migrations/0000_spaces.sql +35 -0
  1156. package/src/spaces/module.ts +287 -0
  1157. package/src/surfaces/Agent.ts +224 -0
  1158. package/src/surfaces/CookieGuard.ts +433 -0
  1159. package/src/surfaces/Http.ts +341 -0
  1160. package/src/surfaces/Mcp.ts +585 -0
  1161. package/src/surfaces/Rpc.ts +101 -0
  1162. package/src/surfaces/headers.ts +16 -0
  1163. package/src/surfaces/request.ts +173 -0
  1164. package/src/telemetry/migrations/.gitkeep +0 -0
  1165. package/src/telemetry/module.ts +94 -0
  1166. package/src/versioning/migrations/.gitkeep +0 -0
  1167. package/src/versioning/module.ts +194 -0
@@ -0,0 +1,2832 @@
1
+ /**
2
+ * Database bootstrap and migrations.
3
+ *
4
+ * Bootstrap runs once per database as a superuser: it creates the kernel role,
5
+ * two NOLOGIN roles and one schema per module, and the sync publication. A
6
+ * module's owner role owns its schema and is used only by its migrations, on a
7
+ * session that logs in as it (`connectOwner`); its runtime role uses only its
8
+ * own schema, and the kernel role is a member of it (without inheriting) so it
9
+ * can `SET ROLE` into it for handlers (decision: module isolation is enforced by
10
+ * the database).
11
+ */
12
+ import { PgClient } from "@effect/sql-pg"
13
+ import { Cause, Effect, FileSystem, Layer, Path, Redacted, Scope } from "effect"
14
+ import * as Reactivity from "effect/reactivity/Reactivity"
15
+ import { SqlClient } from "effect/sql"
16
+ import type { AnyEntity, EntityField, QueryViewDeclaration } from "@eloxiv/contracts"
17
+ import { MigrationFailed, QUERY_SURFACE_SCHEMA, queryRelationName, queryViewName } from "@eloxiv/contracts"
18
+ import type { AnyKernelModule } from "../Module.ts"
19
+ import { isKernelProvided } from "../KernelModule.ts"
20
+ import { canonicalJson, sha256 } from "../Hash.ts"
21
+ import { optionalField } from "../policy/Compiler.ts"
22
+ import { SUBSCRIBER_ACTION, tablePolicies, uniqueKeyProblems } from "../policy/Rls.ts"
23
+ import { pinCatalogPath } from "./Catalog.ts"
24
+ import { scramVerifier } from "./Scram.ts"
25
+ import { AUTHENTICATION_FAILURES, retryConcurrentCatalogUpdate, sqlStateOf } from "./SqlState.ts"
26
+ import type { HostProfile } from "./Host.ts"
27
+ import { queryViewCallProblems } from "./QueryViewCheck.ts"
28
+ import { SqlMessageStorage, SqlRunnerStorage } from "effect/cluster"
29
+ import * as Migrator from "effect/sql/Migrator"
30
+ import { CLUSTER_PREFIX, CLUSTER_SCHEMA, type Migration, recordMigrationStatements } from "./KernelSchema.ts"
31
+ import { ANNOUNCE_TRIGGER, announceSchemaStatements, SETUP_HELPERS_VERSION, TRUSTED_OWNER } from "./ZeroDdl.ts"
32
+ import { ZERO_CLEANUP_FUNCTION, ZERO_PUSH_FUNCTION, ZERO_PUSH_STATUS_FUNCTION, zeroPushStatements } from "./ZeroPush.ts"
33
+ import { trackedDeclarations, trackedTables } from "../search/Sources.ts"
34
+
35
+ export const SYNC_PUBLICATION = "eloxiv_sync"
36
+
37
+ /**
38
+ * Kernel tables zero-cache replicates besides the module schemas: sharing grants, and the live directory
39
+ * facts the sync read filter tests (see migration 0011_sync_directory).
40
+ */
41
+ export const SYNC_KERNEL_TABLES = [
42
+ "eloxiv.share_grant",
43
+ "eloxiv.share_redemption",
44
+ "eloxiv.sync_fact",
45
+ "eloxiv.sync_org",
46
+ // File metadata (the Files contract): the sync endpoint filters it by each file's record's read policy.
47
+ "eloxiv.file",
48
+ ] as const
49
+
50
+ /**
51
+ * The query surface's read role (QuerySurface): it can use only the surface's schema and read only its views,
52
+ * each owned by the module's runtime role, so row-level security filters every row by its entity's read policy.
53
+ * The kernel may switch into it (SET) but inherits nothing from it.
54
+ */
55
+ export const QUERY_ROLE = "eloxiv_query"
56
+
57
+ /**
58
+ * The owner of the platform read functions (`publishPlatformReads`): the SECURITY DEFINER functions through which
59
+ * handlers read deployment settings, their settings values and the flag rules that apply to them, without
60
+ * switching the role of the handler's connection. NOLOGIN, no members: nothing but those functions acts as it,
61
+ * and it can read only the columns and rows they select.
62
+ */
63
+ export const PLATFORM_READ_ROLE = "eloxiv_platform_read"
64
+ /** The schema of the platform read functions: owned by the superuser that runs setup, no access for `PUBLIC`. */
65
+ export const PLATFORM_READ_SCHEMA = "eloxiv_platform"
66
+ /** The schemas of the kernel-provided `settings` and `flags` modules (their functions exist when they are installed). */
67
+ const SETTINGS_SCHEMA = "eloxiv_settings"
68
+ const FLAGS_SCHEMA = "eloxiv_flags"
69
+
70
+ /** Advisory lock key serialising role changes across concurrent setups. */
71
+ const ROLE_LOCK = 4_242_001
72
+
73
+ const ident = (name: string): string => {
74
+ if (!/^[a-z_][a-z0-9_]*$/.test(name)) throw new Error(`Unsafe SQL identifier: ${name}`)
75
+ return `"${name}"`
76
+ }
77
+ const literal = (value: string): string => `'${value.replaceAll("'", "''")}'`
78
+ /** Any identifier, quoted. */
79
+ const quote = (name: string): string => `"${name.replaceAll('"', '""')}"`
80
+
81
+ /**
82
+ * What `ALTER ROLE ... PASSWORD` is given for `password`: a SCRAM verifier computed here, so the password never
83
+ * reaches the server, or, on a host that accepts only plaintext passwords (db/Host.ts), the password itself.
84
+ */
85
+ export const rolePassword = (host: HostProfile, password: string): string =>
86
+ host.scramVerifiers ? scramVerifier(password) : password
87
+
88
+ export interface DatabaseTarget {
89
+ readonly database: string
90
+ readonly role: string
91
+ readonly password: string
92
+ }
93
+
94
+ export const parseDatabaseUrl = (url: Redacted.Redacted): DatabaseTarget => {
95
+ const parsed = new URL(Redacted.value(url))
96
+ return {
97
+ database: decodeURIComponent(parsed.pathname.slice(1)),
98
+ role: decodeURIComponent(parsed.username),
99
+ password: decodeURIComponent(parsed.password),
100
+ }
101
+ }
102
+
103
+ /** Run `f` with a short-lived client for `url`. */
104
+ export const withClient = <A, E, R>(url: Redacted.Redacted, f: (sql: SqlClient.SqlClient) => Effect.Effect<A, E, R>) =>
105
+ Effect.scoped(
106
+ Effect.gen(function* () {
107
+ const client = yield* PgClient.make({ url, maxConnections: 1 })
108
+ return yield* f(client)
109
+ }),
110
+ ).pipe(Effect.provide(Reactivity.layer))
111
+
112
+ export const adminUrlFor = (adminUrl: Redacted.Redacted, database: string): Redacted.Redacted => {
113
+ const parsed = new URL(Redacted.value(adminUrl))
114
+ parsed.pathname = `/${encodeURIComponent(database)}`
115
+ return Redacted.make(parsed.toString())
116
+ }
117
+
118
+ /** Serialises `CREATE DATABASE` across concurrent setups (on the admin database). */
119
+ const DATABASE_LOCK = 4_242_003
120
+
121
+ /**
122
+ * How a login as `role` to `database` (at the admin URL's host) with `password` goes now: `admitted`, `refused` (the
123
+ * server refused the password: SQLSTATE 28P01 or 28000), or `unknown` (anything else: a reset connection, a missing
124
+ * database, a timeout), which answers nothing.
125
+ */
126
+ const loginOutcome = (adminUrl: Redacted.Redacted, database: string, role: string, password: string) =>
127
+ Effect.scoped(
128
+ Effect.gen(function* () {
129
+ const url = new URL(Redacted.value(adminUrlFor(adminUrl, database)))
130
+ url.username = role
131
+ url.password = password
132
+ const client = yield* PgClient.makeClient({ url: Redacted.make(url.toString()) })
133
+ yield* client`SELECT 1`
134
+ }),
135
+ ).pipe(
136
+ Effect.as<"admitted" | "refused" | "unknown">("admitted"),
137
+ Effect.catchCause((cause) =>
138
+ Effect.succeed(authenticationFailure(Cause.squash(cause)) === undefined ? "unknown" : "refused"),
139
+ ),
140
+ Effect.provide(Reactivity.layer),
141
+ )
142
+
143
+ /**
144
+ * On a host where the setup role is no superuser (db/Host.ts): the setup role holds `role`'s privileges (INHERIT)
145
+ * and may act as it (SET), as a superuser would without either. Setup then owns, through the roles it created, what
146
+ * they own: it hardens a module's tables as their owner, creates the database owned by the kernel role, and gives
147
+ * views and functions to the runtime and platform roles. The membership goes one way only: `role` gains nothing,
148
+ * and no role setup creates is a member of the setup role (`clusterTrustProblems`). (PostgreSQL also makes the
149
+ * creator of a role a member with `ADMIN OPTION` and nothing else, a grant its creator cannot revoke.) Nothing for a
150
+ * superuser.
151
+ */
152
+ const ensureSetupMembership = (sql: SqlClient.SqlClient, host: HostProfile, role: string) =>
153
+ Effect.gen(function* () {
154
+ if (host.superuser) return
155
+ const [held] = yield* sql<{ inherit: boolean; set: boolean }>`
156
+ SELECT coalesce(bool_or(m.inherit_option), false) AS inherit, coalesce(bool_or(m.set_option), false) AS "set"
157
+ FROM pg_catalog.pg_auth_members m
158
+ WHERE m.roleid = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = ${role})
159
+ AND m.member = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = session_user)`
160
+ if (held?.inherit === true && held.set) return
161
+ yield* sql.unsafe(`GRANT ${ident(role)} TO SESSION_USER WITH INHERIT TRUE, SET TRUE`)
162
+ })
163
+
164
+ /**
165
+ * The trust setup's design rests on, checked on the cluster's admin connection under the role lock, before setup
166
+ * changes any role: the setup role (`session_user`) is the kernel's trusted owner besides superusers, so it must be
167
+ * a role nothing setup creates can reach, and the kernel role must hold nothing privileged.
168
+ *
169
+ * - The kernel role is not the setup role (setup would strip and repair it).
170
+ * - None of the kernel role, the query and platform roles and the modules' roles (`roles`) is a member of the setup
171
+ * role, directly or not: code acting as any of them never acts as the role that owns setup's functions and the
172
+ * kernel's recorded security state.
173
+ * - The kernel role is no superuser and has no `CREATEROLE`, `CREATEDB` or `REPLICATION`, and is a member of no role
174
+ * that is one or has them or `BYPASSRLS`, of no predefined `pg_*` role (`pg_read_all_data`, `pg_write_all_data`,
175
+ * ...) and not of the setup role, directly or through another role: on a managed host the console's roles are
176
+ * such members (Neon's `neon_superuser`). Create the kernel role through SQL, or let setup create it. Its
177
+ * memberships in the query role and the modules' runtime roles (`roles`, and other apps' runtime roles on a
178
+ * shared cluster, where it can only `SET ROLE`) are setup's own, and setup holds those roles plain itself
179
+ * (`enforceModuleRoles`, the kernel's recorded state), repairing what changed them.
180
+ */
181
+ export const clusterTrustProblems = (sql: SqlClient.SqlClient, kernelRole: string, roles: ReadonlyArray<string>) =>
182
+ Effect.gen(function* () {
183
+ const [setup] = yield* sql<{ role: string }>`SELECT session_user::text AS role`
184
+ if (setup?.role === kernelRole) {
185
+ return [
186
+ `the kernel role ${kernelRole} is the role setup runs as (ELOXIV_ADMIN_DATABASE_URL); give the kernel a role of its own`,
187
+ ]
188
+ }
189
+ const reaching = yield* sql<{ role: string }>`
190
+ SELECT r.rolname AS role FROM pg_catalog.pg_roles r
191
+ WHERE r.rolname = ANY(${[kernelRole, ...roles]}) AND pg_catalog.pg_has_role(r.oid, session_user, 'MEMBER')
192
+ ORDER BY 1`
193
+ const [kernel] = yield* sql<{ attributes: ReadonlyArray<string> | null; memberOf: ReadonlyArray<string> | null }>`
194
+ SELECT array_remove(ARRAY[CASE WHEN k.rolsuper THEN 'SUPERUSER' END, CASE WHEN k.rolcreaterole THEN 'CREATEROLE' END,
195
+ CASE WHEN k.rolcreatedb THEN 'CREATEDB' END, CASE WHEN k.rolreplication THEN 'REPLICATION' END], NULL) AS attributes,
196
+ (SELECT array_agg(DISTINCT r.rolname ORDER BY r.rolname) FROM pg_catalog.pg_auth_members m
197
+ JOIN pg_catalog.pg_roles d ON d.oid = m.roleid
198
+ JOIN pg_catalog.pg_roles r ON pg_catalog.pg_has_role(d.oid, r.oid, 'MEMBER')
199
+ WHERE m.member = k.oid AND NOT d.rolname = ANY(${roles})
200
+ -- Modules' runtime roles, also other apps' on a shared cluster: each app's setup holds them plain.
201
+ AND NOT (d.rolname LIKE 'eloxiv\\_mod\\_%' AND NOT m.inherit_option AND NOT m.admin_option)
202
+ AND (r.rolsuper OR r.rolcreaterole OR r.rolcreatedb OR r.rolreplication OR r.rolbypassrls
203
+ OR r.rolname LIKE 'pg\\_%' OR r.rolname = session_user)) AS "memberOf"
204
+ FROM pg_catalog.pg_roles k WHERE k.rolname = ${kernelRole}`
205
+ return [
206
+ ...reaching.map(
207
+ (r) => `${r.role} is a member of ${setup?.role}, the role setup runs as: code acting as it could act as setup`,
208
+ ),
209
+ ...(kernel?.attributes ?? []).map((a) => `the kernel role ${kernelRole} has ${a}`),
210
+ ...(kernel?.memberOf ?? []).map(
211
+ (r) =>
212
+ `the kernel role ${kernelRole} is a member of ${r}, a privileged role: create it through SQL, or let setup create it`,
213
+ ),
214
+ ]
215
+ })
216
+
217
+ /**
218
+ * Setup, cluster-wide: the kernel role and every module's roles, then the database. Idempotent, and safe to run
219
+ * concurrently: role changes and database creation are each serialised by an advisory lock. Returns the modules
220
+ * whose existing roles had been changed and were restored (`enforceModuleRoles`). Runs as the setup role: a
221
+ * superuser, or on a managed host its most privileged role (`host`, db/Host.ts).
222
+ */
223
+ export const bootstrapCluster = Effect.fn("Bootstrap.bootstrapCluster")(function* (options: {
224
+ readonly adminUrl: Redacted.Redacted
225
+ readonly target: DatabaseTarget
226
+ readonly modules: ReadonlyArray<AnyKernelModule>
227
+ /** What the host allows (`detectHost`). */
228
+ readonly host: HostProfile
229
+ /** Recorded on the database if this creates it. */
230
+ readonly comment?: string | undefined
231
+ /** The password a MAKE module's runtime role logs in with (`makeRolePassword`); needed when `modules` has one. */
232
+ readonly makePassword?: ((role: string) => string) | undefined
233
+ }) {
234
+ const { target, host } = options
235
+ const rolesRepaired: Array<string> = []
236
+ yield* withClient(options.adminUrl, (sql) =>
237
+ Effect.gen(function* () {
238
+ // Roles are cluster-wide: serialise concurrent setups (for example parallel test databases).
239
+ yield* sql`SELECT pg_advisory_xact_lock(${ROLE_LOCK})`
240
+ const moduleRoles = options.modules.flatMap((m) => [m.role, m.owner])
241
+ // Before any role is changed: the setup role is one nothing setup creates can reach, and the kernel role is
242
+ // plain (an existing kernel role that is not would otherwise be changed, or trusted).
243
+ const untrusted = yield* clusterTrustProblems(sql, target.role, [QUERY_ROLE, PLATFORM_READ_ROLE, ...moduleRoles])
244
+ if (untrusted.length > 0) {
245
+ return yield* Effect.die(new Error(`Setup refuses to run: ${untrusted.join("; ")}`))
246
+ }
247
+ const role = yield* sql<{
248
+ n: number
249
+ }>`SELECT count(*)::int AS n FROM pg_catalog.pg_roles WHERE rolname = ${target.role}`
250
+ if (role[0]?.n === 0) {
251
+ // As every password setup sets: a verifier where the host takes one, and in no traced statement.
252
+ yield* sql
253
+ .unsafe(`CREATE ROLE ${ident(target.role)} LOGIN PASSWORD ${literal(rolePassword(host, target.password))}`)
254
+ .pipe(Effect.withTracerEnabled(false))
255
+ }
256
+ // The kernel role may not bypass row-level security.
257
+ yield* sql.unsafe(`ALTER ROLE ${ident(target.role)} NOBYPASSRLS`)
258
+ yield* ensureSetupMembership(sql, host, target.role)
259
+ const queryRole = yield* sql<{ n: number }>`SELECT count(*)::int AS n FROM pg_roles WHERE rolname = ${QUERY_ROLE}`
260
+ if (queryRole[0]?.n === 0) yield* sql.unsafe(`CREATE ROLE ${ident(QUERY_ROLE)} NOLOGIN NOBYPASSRLS`)
261
+ yield* sql.unsafe(`ALTER ROLE ${ident(QUERY_ROLE)} NOLOGIN NOBYPASSRLS NOINHERIT`)
262
+ yield* sql.unsafe(`GRANT ${ident(QUERY_ROLE)} TO ${ident(target.role)} WITH INHERIT FALSE, SET TRUE`)
263
+ // The kernel bounds each surface query's temporary files (a superuser-only setting it may then set). A
264
+ // managed Postgres whose administrator is no true superuser may refuse the grant: the surface then runs
265
+ // without that one limit (it checks the privilege) rather than setup failing.
266
+ yield* sql
267
+ .withTransaction(sql.unsafe(`GRANT SET ON PARAMETER temp_file_limit TO ${ident(target.role)}`))
268
+ .pipe(
269
+ Effect.catch((e) =>
270
+ Effect.logWarning(
271
+ `The kernel role may not set temp_file_limit; query surface reads go without it: ${e.message}`,
272
+ ),
273
+ ),
274
+ )
275
+ const platformRole = yield* sql<{
276
+ n: number
277
+ }>`SELECT count(*)::int AS n FROM pg_roles WHERE rolname = ${PLATFORM_READ_ROLE}`
278
+ if (platformRole[0]?.n === 0) yield* sql.unsafe(`CREATE ROLE ${ident(PLATFORM_READ_ROLE)} NOLOGIN NOBYPASSRLS`)
279
+ yield* sql.unsafe(`ALTER ROLE ${ident(PLATFORM_READ_ROLE)} NOLOGIN NOBYPASSRLS NOINHERIT`)
280
+ yield* ensureSetupMembership(sql, host, PLATFORM_READ_ROLE)
281
+ for (const module of options.modules) {
282
+ let existed = true
283
+ for (const role of [module.role, module.owner]) {
284
+ const [found] = yield* sql<{ n: number }>`
285
+ SELECT count(*)::int AS n FROM pg_catalog.pg_roles WHERE rolname = ${role}`
286
+ if (found?.n === 0) {
287
+ existed = false
288
+ yield* sql.unsafe(`CREATE ROLE ${ident(role)} NOLOGIN NOBYPASSRLS`)
289
+ }
290
+ yield* ensureSetupMembership(sql, host, role)
291
+ }
292
+ // A module's roles hold no privileged attribute, no password, no LOGIN (the owner role logs in only while
293
+ // setup connects it, `connectOwner`, under this lock) and no membership but the kernel role's in the
294
+ // runtime role, whatever changed them. Repairs of roles that existed already are reported.
295
+ if ((yield* enforceModuleRoles(sql, module, target.role, "cluster", existed)) && existed) {
296
+ rolesRepaired.push(module.contract.name)
297
+ }
298
+ // A MAKE module's runtime role logs in with its derived password, set again by every setup (the verifier
299
+ // is computed here, so the password never reaches the server; the statement is not traced). On a host that
300
+ // takes only plaintext passwords, chosen by the operator (`scramVerifiers`, db/Host.ts), the password itself
301
+ // goes over this connection and stays in the host's statement statistics and logs, so it is sent only when
302
+ // the role does not already log in with it (a first install, a new MAKE role key): docs/contracts/release.md,
303
+ // "Database hosts", says how to rotate it.
304
+ if (module.make !== undefined) {
305
+ if (options.makePassword === undefined) {
306
+ return yield* Effect.die(
307
+ new Error(`Module ${module.contract.name} is a MAKE module: setup needs its password`),
308
+ )
309
+ }
310
+ const password = options.makePassword(module.role)
311
+ // Kept only on proof that it is already set: a login with it admitted, and one with a wrong password
312
+ // refused for its password. Anything else (a refusal, a reset connection, a timeout) sends it again.
313
+ if (
314
+ !host.scramVerifiers &&
315
+ existed &&
316
+ (yield* loginOutcome(options.adminUrl, target.database, module.role, password)) === "admitted" &&
317
+ (yield* loginOutcome(options.adminUrl, target.database, module.role, crypto.randomUUID())) === "refused"
318
+ ) {
319
+ continue
320
+ }
321
+ yield* sql
322
+ .unsafe(`ALTER ROLE ${ident(module.role)} LOGIN PASSWORD ${literal(rolePassword(host, password))}`)
323
+ .pipe(Effect.withTracerEnabled(false))
324
+ }
325
+ }
326
+ }).pipe(sql.withTransaction),
327
+ )
328
+ yield* withClient(options.adminUrl, (sql) =>
329
+ Effect.gen(function* () {
330
+ // A session lock (CREATE DATABASE cannot run in a transaction); the client has one connection.
331
+ yield* sql`SELECT pg_advisory_lock(${DATABASE_LOCK})`
332
+ const db = yield* sql<{
333
+ n: number
334
+ }>`SELECT count(*)::int AS n FROM pg_catalog.pg_database WHERE datname = ${target.database}`
335
+ if (db[0]?.n === 0) {
336
+ yield* sql.unsafe(`CREATE DATABASE ${ident(target.database)} OWNER ${ident(target.role)}`)
337
+ if (options.comment !== undefined) {
338
+ yield* sql.unsafe(`COMMENT ON DATABASE ${ident(target.database)} IS ${literal(options.comment)}`)
339
+ }
340
+ }
341
+ }).pipe(Effect.ensuring(sql`SELECT pg_advisory_unlock(${DATABASE_LOCK})`.pipe(Effect.ignore))),
342
+ )
343
+ return { rolesRepaired } as const
344
+ })
345
+
346
+ /**
347
+ * Setup inside the app's database, as the setup role, under the migration lease: the kernel's and Better Auth's
348
+ * schemas and the kernel's release bookkeeping (applied migrations, the lease, setup history, schema
349
+ * snapshots, and `eloxiv_setup.record_migration`, which owner sessions record their migrations with), all owned
350
+ * by the kernel role. Idempotent; DDL only for what is missing. What the host does not allow (`host`) is left out
351
+ * and recorded as such in the kernel's state: the catalogue functions' revocation, setup's own event trigger.
352
+ */
353
+ export const bootstrapDatabase = (sql: SqlClient.SqlClient, target: DatabaseTarget, host: HostProfile) =>
354
+ Effect.gen(function* () {
355
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA public FROM PUBLIC`)
356
+ yield* sql.unsafe(`REVOKE CREATE ON DATABASE ${ident(target.database)} FROM PUBLIC`)
357
+ // No temporary objects for module roles (the kernel role owns the database and keeps them): a temporary
358
+ // relation or type shadows the catalogue for unqualified names in its session.
359
+ yield* sql.unsafe(`REVOKE TEMPORARY ON DATABASE ${ident(target.database)} FROM PUBLIC`)
360
+ // Catalogue functions every role may run by default that no module needs (`REVOKED_CATALOG_FUNCTIONS`), where
361
+ // the host lets setup revoke them (db/Host.ts: elsewhere MAKE's guard admits no call of them, and registry
362
+ // modules are trusted code). Where it does, the revocation must have taken: PostgreSQL only warns when a
363
+ // REVOKE revokes nothing.
364
+ if (host.catalogRevoke) {
365
+ const publicCatalog = sql<{ fn: string }>`
366
+ SELECT p.oid::pg_catalog.regprocedure::text AS fn FROM pg_catalog.pg_proc p
367
+ WHERE p.oid::pg_catalog.regprocedure::text = ANY(${[...REVOKED_CATALOG_FUNCTIONS]})
368
+ AND pg_catalog.has_function_privilege('public', p.oid, 'EXECUTE')`
369
+ for (const { fn } of yield* publicCatalog) yield* sql.unsafe(`REVOKE EXECUTE ON FUNCTION ${fn} FROM PUBLIC`)
370
+ const left = yield* publicCatalog
371
+ if (left.length > 0) {
372
+ return yield* Effect.die(
373
+ new Error(
374
+ `Setup revoked ${left.map((f) => f.fn).join(", ")} from PUBLIC, but PUBLIC may still run them; setup refuses to continue`,
375
+ ),
376
+ )
377
+ }
378
+ }
379
+ yield* sql.unsafe(`CREATE SCHEMA IF NOT EXISTS eloxiv AUTHORIZATION ${ident(target.role)}`)
380
+ yield* ensureSchemaOwner(sql, "eloxiv", target.role)
381
+ yield* sql.unsafe(`CREATE SCHEMA IF NOT EXISTS auth AUTHORIZATION ${ident(target.role)}`)
382
+ const owners = yield* tableOwners(sql, "eloxiv", Object.keys(releaseBookkeeping))
383
+ for (const [table, statement] of Object.entries(releaseBookkeeping)) {
384
+ const owner = owners.get(table)
385
+ if (owner === undefined) yield* sql.unsafe(statement)
386
+ if (owner !== target.role) yield* sql.unsafe(`ALTER TABLE eloxiv.${ident(table)} OWNER TO ${ident(target.role)}`)
387
+ }
388
+ // Module migrations record themselves while the kernel's migrations (which also define it, 0025) are still
389
+ // uncommitted in setup's transaction, so a fresh database needs it first, and an older database its current
390
+ // form (the plan arrived with the setup review). Owned by the kernel role.
391
+ // Setup's helper functions are current when each exists with this version's body (`SETUP_HELPERS_VERSION`).
392
+ const current = (functions: ReadonlyArray<string>) =>
393
+ sql<{ current: boolean }>`SELECT count(*) = ${functions.length} AS current FROM pg_catalog.pg_proc p
394
+ WHERE p.oid::pg_catalog.regprocedure::text = ANY(${functions.map((f) => f.replaceAll(" ", ""))}::text[])
395
+ AND pg_catalog.strpos(p.prosrc, ${SETUP_HELPERS_VERSION}) > 0`.pipe(Effect.map(([r]) => r?.current === true))
396
+ const announcersCurrent = yield* current(["eloxiv_setup.announce_schema(text)", "eloxiv_setup.announce_ddl()"])
397
+ const pushersCurrent = yield* current([ZERO_PUSH_FUNCTION, ZERO_CLEANUP_FUNCTION, ZERO_PUSH_STATUS_FUNCTION])
398
+ const [present] = yield* sql<{ recorder: boolean; announcer: boolean; pusher: boolean; state: boolean }>`
399
+ SELECT pg_catalog.to_regprocedure('eloxiv_setup.record_migration(text)') IS NOT NULL
400
+ AND EXISTS (SELECT 1 FROM pg_catalog.pg_attribute
401
+ WHERE attrelid = pg_catalog.to_regclass('eloxiv_setup.migration_plan') AND attname = 'current') AS recorder,
402
+ ${announcersCurrent}::boolean
403
+ AND (EXISTS (SELECT 1 FROM pg_catalog.pg_event_trigger WHERE evtname = ${ANNOUNCE_TRIGGER})
404
+ OR NOT ${host.eventTriggers}) AS announcer,
405
+ ${pushersCurrent}::boolean AS pusher,
406
+ pg_catalog.to_regclass('eloxiv_release.kernel_state') IS NOT NULL AS state`
407
+ if (present?.recorder !== true) {
408
+ yield* sql.withTransaction(
409
+ Effect.gen(function* () {
410
+ yield* sql.unsafe(`SET LOCAL ROLE ${ident(target.role)}`)
411
+ for (const statement of recordMigrationStatements) yield* sql.unsafe(statement)
412
+ }),
413
+ )
414
+ }
415
+ // Owned by the setup role (they call zero-cache's functions, see ZeroDdl.ts); the event trigger only where the
416
+ // host allows event triggers. Creating it can collide with another transaction creating an event trigger as the
417
+ // setup role (on Neon, `concurrentCatalogUpdate`): the transaction, which replaces what it creates, runs again.
418
+ if (present?.announcer !== true) {
419
+ yield* retryConcurrentCatalogUpdate(
420
+ sql.withTransaction(
421
+ Effect.gen(function* () {
422
+ for (const statement of announceSchemaStatements(host.eventTriggers)) yield* sql.unsafe(statement)
423
+ }),
424
+ ),
425
+ )
426
+ }
427
+ // Owned by the setup role too: sync's push bookkeeping in zero-cache's shard schema (ZeroPush.ts).
428
+ if (present?.pusher !== true) {
429
+ yield* sql.withTransaction(
430
+ Effect.gen(function* () {
431
+ for (const statement of zeroPushStatements(target.role)) yield* sql.unsafe(statement)
432
+ }),
433
+ )
434
+ }
435
+ // The kernel's recorded security state, where only setup's superuser writes: the kernel role reads it.
436
+ if (present?.state !== true) {
437
+ yield* sql.withTransaction(
438
+ Effect.gen(function* () {
439
+ yield* sql.unsafe(`CREATE SCHEMA IF NOT EXISTS eloxiv_release`)
440
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA eloxiv_release FROM PUBLIC`)
441
+ yield* sql.unsafe(`CREATE TABLE IF NOT EXISTS eloxiv_release.kernel_state (
442
+ singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
443
+ state jsonb NOT NULL,
444
+ recorded_at timestamptz NOT NULL DEFAULT now()
445
+ )`)
446
+ yield* sql.unsafe(`REVOKE ALL ON eloxiv_release.kernel_state FROM PUBLIC`)
447
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA eloxiv_release TO ${ident(target.role)}`)
448
+ yield* sql.unsafe(`GRANT SELECT ON eloxiv_release.kernel_state TO ${ident(target.role)}`)
449
+ }),
450
+ )
451
+ }
452
+ })
453
+
454
+ /**
455
+ * Catalogue functions PostgreSQL lets every role run that no module needs, revoked from PUBLIC in the app's
456
+ * database (and held there as the kernel's security state): logical decoding messages (a forged
457
+ * `<app>/<shard>/ddl` message makes zero-cache apply a schema change that never happened, such as dropping a
458
+ * kernel table from every replica), and creating large objects (data a module stores outside its schema escapes
459
+ * its row-level security, hardening and snapshot). The kernel needs none of them; zero-cache runs as a superuser.
460
+ */
461
+ export const REVOKED_CATALOG_FUNCTIONS = [
462
+ "pg_logical_emit_message(boolean,text,text,boolean)",
463
+ "pg_logical_emit_message(boolean,text,bytea,boolean)",
464
+ "lo_create(oid)",
465
+ "lo_creat(integer)",
466
+ "lo_from_bytea(oid,bytea)",
467
+ ] as const
468
+
469
+ /** The format of the kernel's recorded security state; a record in another format is refused (re-baseline). */
470
+ export const KERNEL_STATE_FORMAT = 2
471
+
472
+ /**
473
+ * The schemas whose security state is the kernel's: its own (`eloxiv`, `eloxiv_ctx`, `eloxiv_setup`,
474
+ * `eloxiv_cluster`), the query surface's views (`eloxiv_surface`), the platform read functions
475
+ * (`eloxiv_platform`), and Better Auth's (`auth`).
476
+ */
477
+ export const KERNEL_STATE_SCHEMAS: ReadonlyArray<string> = [
478
+ "eloxiv",
479
+ "eloxiv_ctx",
480
+ "eloxiv_setup",
481
+ "eloxiv_cluster",
482
+ QUERY_SURFACE_SCHEMA,
483
+ PLATFORM_READ_SCHEMA,
484
+ "auth",
485
+ ]
486
+ const KERNEL_STATE_SCHEMA_ARRAY = `ARRAY[${KERNEL_STATE_SCHEMAS.map((n) => `'${n}'`).join(", ")}]`
487
+
488
+ /** The kernel's own fixed roles besides its login role: the query surface's reader and the platform reads' owner. */
489
+ export const KERNEL_FIXED_ROLES: ReadonlyArray<string> = [QUERY_ROLE, PLATFORM_READ_ROLE]
490
+
491
+ /*
492
+ * DDL only when something changes. zero-cache installs event triggers on every DDL command in the databases it
493
+ * replicates, and each one, even a no-op such as `CREATE TABLE IF NOT EXISTS` on an existing table or
494
+ * `ALTER ... OWNER TO` the current owner, runs its schema introspection (20 to 50 ms each on a fast machine). A
495
+ * setup of an already set-up database should send none.
496
+ */
497
+
498
+ /** The owners of the tables of `schema` named in `tables` that exist. */
499
+ const tableOwners = (sql: SqlClient.SqlClient, schema: string, tables: ReadonlyArray<string>) =>
500
+ sql<{ table: string; owner: string }>`
501
+ SELECT c.relname AS "table", pg_get_userbyid(c.relowner) AS owner
502
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
503
+ WHERE n.nspname = ${schema} AND c.relname = ANY(${tables as Array<string>}) AND c.relkind IN ('r', 'p')`.pipe(
504
+ Effect.map((rows) => new Map(rows.map((row) => [row.table, row.owner]))),
505
+ )
506
+
507
+ /** `CREATE SCHEMA` unless it exists, then `ALTER SCHEMA ... OWNER TO CURRENT_USER` unless that user owns it. */
508
+ const ensureOwnSchema = (sql: SqlClient.SqlClient, schema: string) =>
509
+ Effect.gen(function* () {
510
+ const [current] = yield* sql<{ owner: string; me: string }>`
511
+ SELECT pg_catalog.pg_get_userbyid(nspowner) AS owner, current_user AS me FROM pg_catalog.pg_namespace
512
+ WHERE nspname = ${schema}`
513
+ if (current === undefined) yield* sql.unsafe(`CREATE SCHEMA ${ident(schema)}`)
514
+ else if (current.owner !== current.me) yield* sql.unsafe(`ALTER SCHEMA ${ident(schema)} OWNER TO CURRENT_USER`)
515
+ })
516
+
517
+ /** `ALTER SCHEMA ... OWNER TO role` unless `role` already owns it. */
518
+ const ensureSchemaOwner = (sql: SqlClient.SqlClient, schema: string, role: string) =>
519
+ Effect.gen(function* () {
520
+ const [current] = yield* sql<{ owner: string }>`
521
+ SELECT pg_get_userbyid(nspowner) AS owner FROM pg_catalog.pg_namespace WHERE nspname = ${schema}`
522
+ if (current?.owner !== role) yield* sql.unsafe(`ALTER SCHEMA ${ident(schema)} OWNER TO ${ident(role)}`)
523
+ })
524
+
525
+ /** The kernel's release bookkeeping by table, created by `bootstrapDatabase` before any migration runs. */
526
+ export const releaseBookkeeping: Readonly<Record<string, string>> = {
527
+ module_migration: `CREATE TABLE IF NOT EXISTS eloxiv.module_migration (
528
+ module text NOT NULL,
529
+ name text NOT NULL,
530
+ applied_at timestamptz NOT NULL DEFAULT now(),
531
+ PRIMARY KEY (module, name)
532
+ )`,
533
+ // The migration lease's holder (at most one row); the advisory lock is what excludes other setups.
534
+ release_lease: `CREATE TABLE IF NOT EXISTS eloxiv.release_lease (
535
+ singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
536
+ owner text NOT NULL,
537
+ pid integer NOT NULL,
538
+ acquired_at timestamptz NOT NULL,
539
+ expires_at timestamptz NOT NULL
540
+ )`,
541
+ release_history: `CREATE TABLE IF NOT EXISTS eloxiv.release_history (
542
+ id bigserial PRIMARY KEY,
543
+ owner text NOT NULL,
544
+ started_at timestamptz NOT NULL,
545
+ finished_at timestamptz NOT NULL DEFAULT clock_timestamp(),
546
+ outcome text NOT NULL,
547
+ error text,
548
+ applied jsonb NOT NULL DEFAULT '{}'::jsonb
549
+ )`,
550
+ schema_snapshot: `CREATE TABLE IF NOT EXISTS eloxiv.schema_snapshot (
551
+ module text PRIMARY KEY,
552
+ fingerprint text NOT NULL,
553
+ snapshot jsonb NOT NULL,
554
+ migrations text[] NOT NULL,
555
+ recorded_at timestamptz NOT NULL DEFAULT now()
556
+ )`,
557
+ }
558
+
559
+ /**
560
+ * Before the module's migrations, on setup's session, in a transaction of its own that commits before any owner
561
+ * session connects (they must see it): each module's schema, owned by its owner role and closed to everyone else,
562
+ * and the owner role's right to record its migrations. An empty schema exposes nothing, so a failed setup may
563
+ * leave a new one behind.
564
+ */
565
+ export const bootstrapModules = (sql: SqlClient.SqlClient, modules: ReadonlyArray<AnyKernelModule>) =>
566
+ Effect.gen(function* () {
567
+ /** Whether a module's query-surface views were dropped (the kernel's security state changed). */
568
+ let surfaceDropped = false
569
+ for (const module of modules) {
570
+ // A schema that exists already is the module's only if its roles own it (earlier skeleton versions let the
571
+ // runtime role own the module's objects): setup never hands anyone else's schema to a module.
572
+ const [existing] = yield* sql<{ owner: string }>`
573
+ SELECT pg_catalog.pg_get_userbyid(nspowner) AS owner FROM pg_catalog.pg_namespace WHERE nspname = ${module.schema}`
574
+ if (existing !== undefined && existing.owner !== module.owner && existing.owner !== module.role) {
575
+ return yield* new MigrationFailed({
576
+ module: module.contract.name,
577
+ migration: null,
578
+ message:
579
+ `Module ${module.contract.name}: schema ${module.schema} already exists, owned by ${existing.owner}, ` +
580
+ `not by the module's roles; setup does not take it over. Give the module a schema of its own.`,
581
+ })
582
+ }
583
+ // Earlier skeleton versions let the runtime role own the module's objects: given to the owner role. Only
584
+ // then, since it would also hand over the module's query-surface views (owned by the runtime role, so they
585
+ // read under its row-level security): those are dropped first, and step 2 creates them again.
586
+ const [legacy] = yield* sql<{ owned: boolean }>`
587
+ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
588
+ WHERE n.nspname = ${module.schema} AND c.relowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = ${module.role}))
589
+ OR EXISTS (SELECT 1 FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
590
+ WHERE n.nspname = ${module.schema} AND p.proowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = ${module.role}))
591
+ OR EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
592
+ WHERE n.nspname = ${module.schema} AND t.typowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = ${module.role}))
593
+ OR EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n
594
+ WHERE n.nspname = ${module.schema} AND n.nspowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = ${module.role})) AS owned`
595
+ if (legacy?.owned === true) {
596
+ if (yield* dropSurfaceViews(sql, module)) surfaceDropped = true
597
+ yield* sql.unsafe(`REASSIGN OWNED BY ${ident(module.role)} TO ${ident(module.owner)}`)
598
+ }
599
+ yield* sql.unsafe(`CREATE SCHEMA IF NOT EXISTS ${ident(module.schema)} AUTHORIZATION ${ident(module.owner)}`)
600
+ yield* ensureSchemaOwner(sql, module.schema, module.owner)
601
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA ${ident(module.schema)} FROM PUBLIC`)
602
+ // The owner's migration session records what it applies (kernel migration 0025), and tells zero-cache of
603
+ // the schema changes it makes (ZeroDdl.ts).
604
+ const [granted] = yield* sql<{ ok: boolean }>`
605
+ SELECT pg_catalog.has_function_privilege(${module.owner}, 'eloxiv_setup.record_migration(text)', 'EXECUTE')
606
+ AND pg_catalog.has_schema_privilege(${module.owner}, 'eloxiv_setup', 'USAGE') AS ok`
607
+ if (granted?.ok !== true) {
608
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA eloxiv_setup TO ${ident(module.owner)}`)
609
+ yield* sql.unsafe(`GRANT EXECUTE ON FUNCTION eloxiv_setup.record_migration(text) TO ${ident(module.owner)}`)
610
+ }
611
+ }
612
+ return { surfaceDropped }
613
+ })
614
+
615
+ /**
616
+ * Before any owner session connects, under the lease: list each module's pending migrations as the only names
617
+ * its owner session may record (`eloxiv_setup.record_migration`).
618
+ */
619
+ /**
620
+ * On setup's session, before an owner session applies `name` of `module`: the one name it may record now. (The
621
+ * previous migration's row is gone with its recording, in the owner's still open transaction, so this never
622
+ * waits on it.)
623
+ */
624
+ export const markCurrentMigration = (sql: SqlClient.SqlClient, module: string, name: string) =>
625
+ sql`UPDATE eloxiv_setup.migration_plan SET current = true WHERE module = ${module} AND name = ${name}`
626
+
627
+ export const planMigrations = (
628
+ sql: SqlClient.SqlClient,
629
+ plans: ReadonlyArray<{ readonly module: string; readonly names: ReadonlyArray<string> }>,
630
+ ) =>
631
+ Effect.gen(function* () {
632
+ yield* sql`DELETE FROM eloxiv_setup.migration_plan`
633
+ for (const plan of plans) {
634
+ for (const name of plan.names) {
635
+ yield* sql`INSERT INTO eloxiv_setup.migration_plan (module, name) VALUES (${plan.module}, ${name})`
636
+ }
637
+ }
638
+ })
639
+
640
+ /**
641
+ * The advisory lock (first key; the second is `hashtext(<owner role>)`) a setup holds, on the cluster's admin
642
+ * database, while an owner role can log in (`connectOwner`): `status` tells that window from a LOGIN left behind.
643
+ */
644
+ export const OWNER_LOGIN_LOCK = 4_242_004
645
+
646
+ /** The application name of every owner session (informational: a migration can change it). */
647
+ export const OWNER_SESSION_APPLICATION = "eloxiv-setup-migrations"
648
+
649
+ /**
650
+ * The `pg_hba.conf` rules that may apply when `owner` logs in to `database`, with their method, each as
651
+ * `<line>: <type> <databases> <users> <method>` (judged by `ownerLoginMethodVerdict`). Read on the cluster's
652
+ * superuser connection.
653
+ */
654
+ export const passwordlessOwnerRules = (sql: SqlClient.SqlClient, database: string, owner: string) =>
655
+ sql<{ rule: string; method: string }>`
656
+ SELECT r.line_number || ': ' || r.type || ' ' || array_to_string(r.database, ',') || ' '
657
+ || array_to_string(r.user_name, ',') || ' ' || r.auth_method AS rule, r.auth_method AS method
658
+ FROM pg_catalog.pg_hba_file_rules r
659
+ WHERE r.error IS NULL AND NOT (r.database = ARRAY['replication']::text[])
660
+ AND r.database && ARRAY['all', 'sameuser', 'samerole', ${database}]::text[]
661
+ AND (r.user_name && ARRAY['all', ${owner}]::text[]
662
+ OR EXISTS (SELECT 1 FROM unnest(r.user_name) u WHERE u LIKE '/%' AND ${owner} ~ substr(u, 2)))
663
+ ORDER BY r.line_number`
664
+
665
+ /** The SQLSTATE of a refused login found anywhere in an error and its causes, or undefined. */
666
+ export const authenticationFailure = (error: unknown): string | undefined => sqlStateOf(error, AUTHENTICATION_FAILURES)
667
+
668
+ /** The innermost message of an error, for an operator. */
669
+ const failureText = (error: unknown): string => {
670
+ let message = String(error)
671
+ for (let e = error as { message?: unknown; cause?: unknown; reason?: unknown } | undefined, i = 0; e && i < 8; i++) {
672
+ if (typeof e.message === "string" && e.message.length > 0) message = e.message
673
+ e = (e.reason ?? e.cause) as typeof e
674
+ }
675
+ return message
676
+ }
677
+
678
+ /**
679
+ * A connection that logs in as `owner`, a module's owner role, in the caller's scope: the session a module's
680
+ * migrations run on. It has no more privileged role to return to (`RESET ROLE`, `set_config('role', ...)` and
681
+ * `SET SESSION AUTHORIZATION` all end at the owner), and the owner role holds no privileged attribute or
682
+ * membership (`bootstrapCluster`, checked again here).
683
+ *
684
+ * The owner role can log in only while this connects it: holding the cluster-wide advisory lock that serialises
685
+ * role changes (on the cluster's superuser connection `adminUrl`, as `bootstrapCluster` does), setup checks the
686
+ * role is still plain, gives it LOGIN and a password known only to this process (sent as a SCRAM-SHA-256
687
+ * verifier computed here, in a statement that is not traced, so the password reaches neither the server nor a
688
+ * trace), connects, and takes both away again before releasing the lock; a failure to take them away fails the
689
+ * connection (and the next setup removes them before anything logs in, under the same lock). An open session
690
+ * stays open; nothing else can log in as the owner with a password, and no credential is stored anywhere.
691
+ * `pg_hba.conf` must let the owner role in only with it (`passwordlessOwnerRules`, `ownerLoginMethodVerdict`).
692
+ *
693
+ * On a host where the setup role is no superuser (`host`, db/Host.ts) the setup role's own membership in the owner
694
+ * role (`ensureSetupMembership`) is the one the owner role may have. Where the host takes no SCRAM verifier, the
695
+ * one-time password itself is sent; it is dead once this returns. Where setup cannot read `pg_hba.conf`'s rules,
696
+ * the window is tested instead (`hbaProbe`): while the owner role can log in, a login with a wrong password must be
697
+ * refused, from where setup runs; one that is not is refused (`refuse`, production) or warned about (`warn`).
698
+ */
699
+ export const connectOwner = (
700
+ adminUrl: Redacted.Redacted,
701
+ database: string,
702
+ owner: string,
703
+ options: { readonly host: HostProfile; readonly hbaProbe: "refuse" | "warn" },
704
+ ) =>
705
+ Effect.gen(function* () {
706
+ const outer = yield* Effect.scope
707
+ const password = `${crypto.randomUUID()}${crypto.randomUUID()}`.replaceAll("-", "")
708
+ const url = new URL(Redacted.value(adminUrlFor(adminUrl, database)))
709
+ url.username = owner
710
+ url.password = password
711
+ return yield* Effect.scoped(
712
+ Effect.gen(function* () {
713
+ const admin = yield* PgClient.makeClient({ url: adminUrl })
714
+ yield* admin`SELECT pg_catalog.pg_advisory_lock(${ROLE_LOCK})`
715
+ yield* Effect.addFinalizer(() => admin`SELECT pg_catalog.pg_advisory_unlock(${ROLE_LOCK})`.pipe(Effect.ignore))
716
+ const [role] = yield* admin<{ plain: boolean }>`
717
+ SELECT NOT (a.rolsuper OR a.rolcreaterole OR a.rolcreatedb OR a.rolreplication OR a.rolbypassrls
718
+ OR a.rolcanlogin OR a.rolpassword IS NOT NULL)
719
+ AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members m WHERE m.member = a.oid
720
+ OR (m.roleid = a.oid AND m.member <> (SELECT s.oid FROM pg_catalog.pg_roles s WHERE s.rolname = session_user))) AS plain
721
+ FROM pg_catalog.pg_authid a WHERE a.rolname = ${owner}`
722
+ if (role?.plain !== true) {
723
+ return yield* Effect.fail(
724
+ new Error(`The owner role ${owner} changed since setup checked it; its migrations were not run`),
725
+ )
726
+ }
727
+ yield* admin`SELECT pg_catalog.pg_advisory_lock(${OWNER_LOGIN_LOCK}, pg_catalog.hashtext(${owner}))`
728
+ yield* Effect.addFinalizer(() =>
729
+ admin`SELECT pg_catalog.pg_advisory_unlock(${OWNER_LOGIN_LOCK}, pg_catalog.hashtext(${owner}))`.pipe(
730
+ Effect.ignore,
731
+ ),
732
+ )
733
+ const close = admin.unsafe(`ALTER ROLE ${ident(owner)} NOLOGIN PASSWORD NULL`)
734
+ // Should connecting fail: the login goes before the lock is released (finalizers run last first), and a
735
+ // failure is reported, not ignored.
736
+ yield* Effect.addFinalizer(() =>
737
+ close.pipe(
738
+ Effect.catchCause((cause) =>
739
+ Effect.logError(`Could not remove the login of ${owner}; the next setup removes it`, cause),
740
+ ),
741
+ ),
742
+ )
743
+ yield* admin
744
+ .unsafe(`ALTER ROLE ${ident(owner)} LOGIN PASSWORD ${literal(rolePassword(options.host, password))}`)
745
+ .pipe(Effect.withTracerEnabled(false))
746
+ if (!options.host.hbaRules) {
747
+ const wrong = new URL(url)
748
+ wrong.password = crypto.randomUUID().replaceAll("-", "")
749
+ // Only a refusal of the password itself passes (SQLSTATE 28P01 or 28000): a connection the network, a
750
+ // proxy or the server ended for any other reason proves nothing about how the owner role is admitted.
751
+ const outcome = yield* Effect.scoped(
752
+ Effect.gen(function* () {
753
+ const probe = yield* PgClient.makeClient({ url: Redacted.make(wrong.toString()) })
754
+ yield* probe`SELECT 1`
755
+ }),
756
+ ).pipe(
757
+ Effect.as<{ admitted: boolean; failure: unknown }>({ admitted: true, failure: undefined }),
758
+ Effect.catchCause((cause) => Effect.succeed({ admitted: false, failure: Cause.squash(cause) })),
759
+ )
760
+ if (!outcome.admitted && authenticationFailure(outcome.failure) === undefined) {
761
+ return yield* Effect.fail(
762
+ new Error(
763
+ `Setup could not test how ${owner} (a module's owner role) is admitted to ${database}: a login with a ` +
764
+ `wrong password failed for another reason than its password (${failureText(outcome.failure)}), so ` +
765
+ `it proves nothing; setup refuses to run. Check the connection to the database, then run setup again`,
766
+ ),
767
+ )
768
+ }
769
+ const admitted = outcome.admitted
770
+ if (admitted) {
771
+ const message =
772
+ `The database admitted ${owner} (a module's owner role) to ${database} with a wrong password while setup ` +
773
+ `let it log in: any process that can connect from here could log in as it. Make owner roles ` +
774
+ `authenticate by password (scram-sha-256)`
775
+ if (options.hbaProbe === "refuse") {
776
+ return yield* Effect.fail(new Error(`${message}; setup refuses to run otherwise`))
777
+ }
778
+ yield* Effect.logWarning(`${message} (allowed outside production, ELOXIV_ENV)`)
779
+ }
780
+ }
781
+ const session = yield* PgClient.makeClient({
782
+ url: Redacted.make(url.toString()),
783
+ applicationName: OWNER_SESSION_APPLICATION,
784
+ }).pipe(Scope.provide(outer))
785
+ yield* close
786
+ return session
787
+ }),
788
+ )
789
+ }).pipe(Effect.provide(Reactivity.layer))
790
+
791
+ /**
792
+ * On a module's owner session, at the end of its migrations' transaction: leave nothing reachable until setup
793
+ * hardens the module (on its own session, after this commits). Every table has row-level security enabled and
794
+ * forced with no policy, so even the runtime role sees and writes nothing; no one but the owner holds a
795
+ * privilege on the schema itself (not even USAGE) or on its tables, views, sequences, functions and procedures;
796
+ * every trigger is enabled. If setup fails after this commits, the module stays closed rather than
797
+ * open.
798
+ */
799
+ export const closeModule = (sql: SqlClient.SqlClient, module: AnyKernelModule) =>
800
+ Effect.gen(function* () {
801
+ yield* pinCatalogPath(sql)
802
+ const schema = ident(module.schema)
803
+ const tables = yield* sql<{ name: string }>`
804
+ SELECT c.relname AS name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
805
+ WHERE n.nspname = ${module.schema} AND c.relkind IN ('r', 'p') ORDER BY 1`
806
+ for (const { name } of tables) {
807
+ const qualified = `${schema}.${ident(name)}`
808
+ const policies = yield* sql<{ name: string }>`
809
+ SELECT policyname AS name FROM pg_catalog.pg_policies WHERE schemaname = ${module.schema} AND tablename = ${name}`
810
+ for (const policy of policies) yield* sql.unsafe(`DROP POLICY ${ident(policy.name)} ON ${qualified}`)
811
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE ROW LEVEL SECURITY`)
812
+ yield* sql.unsafe(`ALTER TABLE ${qualified} FORCE ROW LEVEL SECURITY`)
813
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE TRIGGER USER`)
814
+ }
815
+ const others = `PUBLIC, ${ident(module.role)}`
816
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA ${schema} FROM ${others}`)
817
+ yield* sql.unsafe(`REVOKE ALL ON ALL TABLES IN SCHEMA ${schema} FROM ${others}`)
818
+ yield* sql.unsafe(`REVOKE ALL ON ALL SEQUENCES IN SCHEMA ${schema} FROM ${others}`)
819
+ yield* sql.unsafe(`REVOKE ALL ON ALL ROUTINES IN SCHEMA ${schema} FROM ${others}`)
820
+ // And from any other role a migration granted something to: the schema, its relations, columns, sequences,
821
+ // functions and procedures belong to the owner alone until hardening opens them.
822
+ yield* revokeOthers(sql, module.schema, [])
823
+ })
824
+
825
+ /**
826
+ * In the setup's transaction, after hardening: (re)create the publication Zero replicates from (the modules'
827
+ * schemas and the kernel's sync tables). An unchanged publication is left alone: zero-cache treats a
828
+ * publication change as a schema change.
829
+ *
830
+ * Where the host allows no schema-wide publication (`schemaPublications`, db/Host.ts: PostgreSQL requires a
831
+ * superuser for one), the publication lists every table of the synced modules' schemas instead, as this setup
832
+ * leaves them (it runs after every migration of the setup): a table a migration creates is published by the setup
833
+ * that creates it, and zero-cache copies its rows when it first sees it.
834
+ */
835
+ export const ensurePublication = (
836
+ sql: SqlClient.SqlClient,
837
+ modules: ReadonlyArray<AnyKernelModule>,
838
+ host: Pick<HostProfile, "schemaPublications">,
839
+ ) =>
840
+ Effect.gen(function* () {
841
+ // MAKE modules are not synced: their data is read through their actions and views.
842
+ const synced = modules.filter((m) => m.make === undefined)
843
+ const wantedSchemas = host.schemaPublications ? synced.map((m) => m.schema).sort() : []
844
+ const moduleTables = host.schemaPublications
845
+ ? []
846
+ : (yield* sql<{ name: string }>`
847
+ SELECT n.nspname || '.' || c.relname AS name FROM pg_catalog.pg_class c
848
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
849
+ WHERE n.nspname = ANY(${synced.map((m) => m.schema)}) AND c.relkind IN ('r', 'p') AND NOT c.relispartition
850
+ ORDER BY 1`).map((r) => r.name)
851
+ const wantedTables = [...SYNC_KERNEL_TABLES, ...moduleTables].sort()
852
+ const qualified = (name: string) =>
853
+ name
854
+ .split(".")
855
+ .map((part) => quote(part))
856
+ .join(".")
857
+ // (A MAKE preview's database has no synced module.)
858
+ const spec =
859
+ wantedSchemas.length === 0
860
+ ? `TABLE ${wantedTables.map(qualified).join(", ")}`
861
+ : `TABLES IN SCHEMA ${wantedSchemas.map(ident).join(", ")}, TABLE ${SYNC_KERNEL_TABLES.join(", ")}`
862
+ const existing = yield* sql<{
863
+ n: number
864
+ }>`SELECT count(*)::int AS n FROM pg_catalog.pg_publication WHERE pubname = ${SYNC_PUBLICATION}`
865
+ if (existing[0]?.n === 0) {
866
+ yield* sql.unsafe(`CREATE PUBLICATION ${SYNC_PUBLICATION} FOR ${spec}`)
867
+ return
868
+ }
869
+ const schemasNow = yield* sql<{ schema: string }>`
870
+ SELECT n.nspname AS schema FROM pg_catalog.pg_publication_namespace pn
871
+ JOIN pg_catalog.pg_publication p ON p.oid = pn.pnpubid JOIN pg_catalog.pg_namespace n ON n.oid = pn.pnnspid
872
+ WHERE p.pubname = ${SYNC_PUBLICATION} ORDER BY 1`
873
+ const tablesNow = yield* sql<{ name: string }>`
874
+ SELECT n.nspname || '.' || c.relname AS name FROM pg_catalog.pg_publication_rel pr
875
+ JOIN pg_catalog.pg_publication p ON p.oid = pr.prpubid JOIN pg_catalog.pg_class c ON c.oid = pr.prrelid
876
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
877
+ WHERE p.pubname = ${SYNC_PUBLICATION} ORDER BY 1`
878
+ const expectedTables = host.schemaPublications ? [...SYNC_KERNEL_TABLES].sort() : wantedTables
879
+ // Compared as sets, each sorted here (a database's collation may order names otherwise than JavaScript).
880
+ if (
881
+ JSON.stringify(schemasNow.map((r) => r.schema).sort()) !== JSON.stringify(wantedSchemas) ||
882
+ JSON.stringify(tablesNow.map((r) => r.name).sort()) !== JSON.stringify(expectedTables)
883
+ ) {
884
+ yield* sql.unsafe(`ALTER PUBLICATION ${SYNC_PUBLICATION} SET ${spec}`)
885
+ }
886
+ })
887
+
888
+ /** drizzle-kit separates statements with this marker. */
889
+ const STATEMENT_BREAKPOINT = "--> statement-breakpoint"
890
+
891
+ /**
892
+ * The first line of a migration that cannot run in a transaction (the Release contract). Setup runs it
893
+ * outside the setup's transaction, after the migrations before it have committed with their hardening. Such a
894
+ * migration may hold only statements that need it: `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`
895
+ * and `REINDEX ... CONCURRENTLY`.
896
+ */
897
+ export const NO_TRANSACTION_MARKER = "-- eloxiv:no-transaction"
898
+
899
+ /** Read a module's drizzle-kit migrations (`*.sql`, file-name order). */
900
+ export const readModuleMigrations = Effect.fn("Bootstrap.readModuleMigrations")(function* (module: AnyKernelModule) {
901
+ // A MAKE module's migrations come from its stored source, not from files.
902
+ if (module.migrations !== undefined) return module.migrations
903
+ const fs = yield* FileSystem.FileSystem
904
+ const path = yield* Path.Path
905
+ const dir = yield* path.fromFileUrl(module.migrationsDir)
906
+ const files = (yield* fs.readDirectory(dir)).filter((f) => f.endsWith(".sql")).sort()
907
+ const migrations: Array<Migration> = []
908
+ for (const file of files) {
909
+ const text = yield* fs.readFileString(path.join(dir, file))
910
+ const outside = text.trimStart().startsWith(NO_TRANSACTION_MARKER)
911
+ const statements = (outside ? text.trimStart().slice(NO_TRANSACTION_MARKER.length) : text)
912
+ .split(STATEMENT_BREAKPOINT)
913
+ .map((s) => s.trim())
914
+ // The kernel creates each module's schema with the right owner during setup.
915
+ .filter((s) => s.length > 0 && !/^CREATE SCHEMA\b/i.test(s))
916
+ migrations.push({ name: file.replace(/\.sql$/, ""), statements, ...(outside ? { transactional: false } : {}) })
917
+ }
918
+ return migrations
919
+ })
920
+
921
+ /**
922
+ * Effect cluster's message and runner storage migrations, inside the kernel-owned `eloxiv_cluster` schema
923
+ * (created by kernel migration 0009_durable_work). They are Effect's own, versioned in their own history tables
924
+ * (`cluster_migrations`, `cluster_runner_migrations`). Setup runs them in its transaction, as the kernel role,
925
+ * with the schema as the search path, so the kernel's runtime never needs DDL for them.
926
+ */
927
+ export const migrateCluster = Effect.gen(function* () {
928
+ const sql = yield* SqlClient.SqlClient
929
+ yield* sql.withTransaction(
930
+ Effect.gen(function* () {
931
+ yield* sql.unsafe(`SET LOCAL search_path TO ${CLUSTER_SCHEMA}`)
932
+ yield* Migrator.make({})({
933
+ loader: SqlMessageStorage.migrations({ prefix: CLUSTER_PREFIX }),
934
+ table: `${CLUSTER_PREFIX}_migrations`,
935
+ })
936
+ yield* Migrator.make({})({
937
+ loader: SqlRunnerStorage.migrations({ prefix: CLUSTER_PREFIX }),
938
+ table: `${CLUSTER_PREFIX}_runner_migrations`,
939
+ })
940
+ }),
941
+ )
942
+ }).pipe(Effect.orDie, Effect.withSpan("Bootstrap.migrateCluster"))
943
+
944
+ export class UnsafeModuleSchema extends Error {
945
+ override readonly name = "UnsafeModuleSchema"
946
+ /** The module whose schema was refused. */
947
+ readonly module: string
948
+ constructor(module: string, message: string) {
949
+ super(message)
950
+ this.module = module
951
+ }
952
+ }
953
+
954
+ /**
955
+ * Objects a migration may not leave in a module schema, because they would run
956
+ * outside the runtime role's row-level security: deferred or constraint
957
+ * triggers (they fire at commit, after authorisation), foreign keys whose
958
+ * referential actions rewrite child rows (Postgres runs them as the table
959
+ * owner, bypassing row-level security), SECURITY DEFINER
960
+ * functions (they run as the owner), rules (their actions run as the owner),
961
+ * materialised views, views that are not `security_invoker`, and BEFORE UPDATE
962
+ * row triggers other than the kernel's key and reference guards (one could
963
+ * change a primary key after the key guard ran, so the kernel's guards, which
964
+ * never change the row, must be the only ones and so terminal).
965
+ * Also foreign tables, and any cast to or from a type of the module's schema or
966
+ * through one of its functions: Postgres runs a cast wherever it converts such
967
+ * a value, including where the module's code was never called (`to_json` and
968
+ * `to_jsonb` use a cast to `json`; the kernel's write log runs `to_jsonb` on
969
+ * every written row in a SECURITY DEFINER trigger), and base types with their
970
+ * own input and output functions (only a superuser can create them). Beyond the
971
+ * schema: event triggers that call a function in the module's schema or owned
972
+ * by one of its `roles` (they would run module code on every DDL command,
973
+ * migrations included), and default privileges in the module's schema or for
974
+ * the schema's owner or its `roles` (they would grant on objects a later
975
+ * migration creates). None are expected; event triggers of other software
976
+ * (zero-cache's) are not affected. Every catalogue relation is named
977
+ * qualified, with `pg_temp` last on the search path, so nothing in the session
978
+ * can shadow what this reads.
979
+ */
980
+ export const unsafeModuleObjects = (sql: SqlClient.SqlClient, schema: string, roles: ReadonlyArray<string> = []) =>
981
+ Effect.gen(function* () {
982
+ yield* pinCatalogPath(sql)
983
+ const roleList = [...roles]
984
+ const found = yield* sql<{ what: string }>`
985
+ SELECT 'deferred or constraint trigger ' || t.tgname || ' on ' || c.relname AS what
986
+ FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
987
+ WHERE n.nspname = ${schema} AND NOT t.tgisinternal AND (t.tgdeferrable OR t.tgconstraint <> 0)
988
+ UNION ALL
989
+ SELECT 'BEFORE UPDATE trigger ' || t.tgname || ' on ' || c.relname || ' (it could change a primary key)'
990
+ FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
991
+ WHERE n.nspname = ${schema} AND NOT t.tgisinternal
992
+ AND (t.tgtype::int & 1) <> 0 AND (t.tgtype::int & 2) <> 0 AND (t.tgtype::int & 16) <> 0
993
+ AND t.tgfoid NOT IN (SELECT g.oid FROM pg_catalog.pg_proc g JOIN pg_catalog.pg_namespace gn ON gn.oid = g.pronamespace
994
+ WHERE gn.nspname = 'eloxiv' AND g.proname IN ('guard_key', 'guard_reference'))
995
+ UNION ALL
996
+ SELECT 'SECURITY DEFINER function ' || p.proname FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
997
+ WHERE n.nspname = ${schema} AND p.prosecdef
998
+ UNION ALL
999
+ SELECT 'foreign key ' || c.conname || ' on ' || c.conrelid::regclass::text
1000
+ || ' with a referential action that rewrites rows (CASCADE, SET NULL or SET DEFAULT)'
1001
+ FROM pg_catalog.pg_constraint c JOIN pg_catalog.pg_namespace n ON n.oid = c.connamespace
1002
+ WHERE n.nspname = ${schema} AND c.contype = 'f'
1003
+ AND (c.confupdtype IN ('c', 'n', 'd') OR c.confdeltype IN ('c', 'n', 'd'))
1004
+ UNION ALL
1005
+ SELECT 'rule ' || r.rulename || ' on ' || r.tablename FROM pg_catalog.pg_rules r WHERE r.schemaname = ${schema}
1006
+ UNION ALL
1007
+ SELECT 'materialised view ' || c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1008
+ WHERE n.nspname = ${schema} AND c.relkind = 'm'
1009
+ UNION ALL
1010
+ SELECT 'view without security_invoker ' || c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1011
+ WHERE n.nspname = ${schema} AND c.relkind = 'v' AND NOT coalesce('security_invoker=true' = ANY (c.reloptions), false)
1012
+ UNION ALL
1013
+ SELECT 'foreign table ' || c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1014
+ WHERE n.nspname = ${schema} AND c.relkind = 'f'
1015
+ UNION ALL
1016
+ SELECT 'cast from ' || format_type(k.castsource, NULL) || ' to ' || format_type(k.casttarget, NULL)
1017
+ || ' (Postgres runs it wherever it converts the value, including inside kernel functions)'
1018
+ FROM pg_catalog.pg_cast k
1019
+ LEFT JOIN pg_catalog.pg_type s ON s.oid = k.castsource LEFT JOIN pg_catalog.pg_namespace sn ON sn.oid = s.typnamespace
1020
+ LEFT JOIN pg_catalog.pg_type t ON t.oid = k.casttarget LEFT JOIN pg_catalog.pg_namespace tn ON tn.oid = t.typnamespace
1021
+ LEFT JOIN pg_catalog.pg_proc p ON p.oid = k.castfunc LEFT JOIN pg_catalog.pg_namespace pn ON pn.oid = p.pronamespace
1022
+ WHERE sn.nspname = ${schema} OR tn.nspname = ${schema} OR pn.nspname = ${schema}
1023
+ UNION ALL
1024
+ SELECT 'base type ' || t.typname || ' with its own input and output functions'
1025
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
1026
+ WHERE n.nspname = ${schema} AND t.typtype = 'b' AND t.typcategory <> 'A'
1027
+ UNION ALL
1028
+ SELECT 'event trigger ' || e.evtname || ' (it calls ' || n.nspname || '.' || p.proname || ')'
1029
+ FROM pg_catalog.pg_event_trigger e JOIN pg_catalog.pg_proc p ON p.oid = e.evtfoid
1030
+ JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
1031
+ WHERE n.nspname = ${schema} OR pg_catalog.pg_get_userbyid(p.proowner) = ANY(${roleList})
1032
+ OR pg_catalog.pg_get_userbyid(e.evtowner) = ANY(${roleList})
1033
+ UNION ALL
1034
+ SELECT 'default privileges for ' || pg_catalog.pg_get_userbyid(d.defaclrole) || coalesce(' in schema ' || n.nspname, '')
1035
+ || ' (' || d.defaclacl::pg_catalog.text || '; objects created later would be reachable before hardening)'
1036
+ FROM pg_catalog.pg_default_acl d LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.defaclnamespace
1037
+ WHERE n.nspname = ${schema} OR pg_catalog.pg_get_userbyid(d.defaclrole) = ANY(${roleList})
1038
+ OR d.defaclrole = (SELECT s.nspowner FROM pg_catalog.pg_namespace s WHERE s.nspname = ${schema})`
1039
+ return found.map((f) => f.what)
1040
+ })
1041
+
1042
+ /** Postgres types whose every value is a Cedar Long, compared exactly in SQL. */
1043
+ const LONG_COLUMN_TYPES: ReadonlySet<string> = new Set(["int8", "int4", "int2"])
1044
+
1045
+ /**
1046
+ * Policy columns that do not hold what the compiler assumes of them: a Long attribute stored in anything but an
1047
+ * integer type (a `numeric`, `float` or text column could hold a value Cedar's Long cannot, or compare it
1048
+ * inexactly), and a nullable column behind a field the contract says every record has (the compiler reads such
1049
+ * an attribute as always present, so a NULL would be read as a value instead of the error Cedar raises for a
1050
+ * missing attribute). Declare the field optional (`Schema.optionalKey`, `Schema.NullOr`) or the column NOT NULL.
1051
+ */
1052
+ export const policyColumnProblems = (sql: SqlClient.SqlClient, module: AnyKernelModule) =>
1053
+ Effect.gen(function* () {
1054
+ const problems: Array<string> = []
1055
+ for (const entity of Object.values(module.contract.entities) as ReadonlyArray<AnyEntity>) {
1056
+ const columns = yield* sql<{ name: string; type: string; notNull: boolean }>`
1057
+ SELECT a.attname AS name, t.typname AS type, a.attnotnull AS "notNull"
1058
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
1059
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
1060
+ WHERE n.nspname = ${entity.table.schema} AND c.relname = ${entity.table.name} AND a.attnum > 0
1061
+ AND NOT a.attisdropped`
1062
+ if (columns.length === 0) continue
1063
+ const byName = new Map(columns.map((c) => [c.name, c]))
1064
+ for (const [name, attribute] of Object.entries(entity.policyAttributes)) {
1065
+ if (attribute.kind !== "column") continue
1066
+ const columnName = (entity.columns as Record<string, string>)[attribute.field]
1067
+ const column = columnName === undefined ? undefined : byName.get(columnName)
1068
+ if (column === undefined) {
1069
+ problems.push(
1070
+ `${entity.cedarType}.${name} is stored in ${columnName ?? attribute.field}, which the table has not`,
1071
+ )
1072
+ continue
1073
+ }
1074
+ if (attribute.type === "Long" && !LONG_COLUMN_TYPES.has(column.type)) {
1075
+ problems.push(
1076
+ `${entity.cedarType}.${name} is a Long stored in a ${column.type} column (it must be an integer type)`,
1077
+ )
1078
+ }
1079
+ if (!column.notNull && !optionalField(entity, attribute.field)) {
1080
+ problems.push(
1081
+ `${entity.cedarType}.${name} is stored in the nullable column ${column.name}, but its field ${attribute.field} is not optional`,
1082
+ )
1083
+ }
1084
+ }
1085
+ }
1086
+ return problems
1087
+ })
1088
+
1089
+ /**
1090
+ * The CHECK each sync guard installs (`@eloxiv/contracts/drizzle`'s allowlist, proven on both of zero-cache's
1091
+ * paths by `packages/testing/test/sync-types.test.ts`): sync carries the column's type exactly only inside this
1092
+ * window, so a value outside it can never be written (NULL always can). Bounds are epoch seconds, not timestamp or
1093
+ * date literals: Postgres prints a literal in the session's time zone and date style, so the definition (and the
1094
+ * schema fingerprint over it) would vary with the session.
1095
+ */
1096
+ const SYNC_GUARDS: Readonly<Record<NonNullable<EntityField["guard"]>, (column: string) => string>> = {
1097
+ "safe-integer": (c) => `${c} BETWEEN -9007199254740991 AND 9007199254740991`,
1098
+ "finite-double": (c) => `${c}::text NOT IN ('NaN', 'Infinity', '-Infinity', '-0')`,
1099
+ // Microseconds: 1970-01-01 to 2037-12-31.
1100
+ instant: (c) =>
1101
+ `pg_catalog.isfinite(${c}) AND EXTRACT(epoch FROM ${c}) >= 0 AND EXTRACT(epoch FROM ${c}) < 2145916800`,
1102
+ // Milliseconds: 1970-01-01 to 9999-12-31.
1103
+ "instant-ms": (c) =>
1104
+ `pg_catalog.isfinite(${c}) AND EXTRACT(epoch FROM ${c}) >= 0 AND EXTRACT(epoch FROM ${c}) < 253402300800`,
1105
+ // 1902-01-01 to 9999-12-31.
1106
+ date: (c) =>
1107
+ `pg_catalog.isfinite(${c}) AND EXTRACT(epoch FROM ${c}) >= -2145916800 AND EXTRACT(epoch FROM ${c}) <= 253402214400`,
1108
+ "json-doubles": (c) => `eloxiv_guard.json_doubles(${c})`,
1109
+ // One dimension, from index 1, no NULL element (CASE keeps array_position from a multidimensional array).
1110
+ "plain-array": (c) =>
1111
+ `CASE WHEN ${c} IS NULL OR pg_catalog.cardinality(${c}) = 0 THEN true ` +
1112
+ `WHEN pg_catalog.array_ndims(${c}) = 1 AND pg_catalog.array_lower(${c}, 1) = 1 ` +
1113
+ `THEN pg_catalog.array_position(${c}, NULL) IS NULL ELSE false END`,
1114
+ }
1115
+
1116
+ /** A guard's CHECK, and its name: a hash of the column, the guard and the CHECK, so no two names collide. */
1117
+ export const syncGuardOf = (column: string, guard: NonNullable<EntityField["guard"]>) =>
1118
+ Effect.promise(async () => {
1119
+ const check = SYNC_GUARDS[guard](quote(column))
1120
+ const hash = await sha256(JSON.stringify([column, guard, check]))
1121
+ return { name: `eloxiv_sync_v1_${hash.slice(0, 20)}`, check }
1122
+ })
1123
+
1124
+ /** The sync guards a module's security state records: each one's table, name, definition and validity. */
1125
+ const syncGuardsState = (schema: string) =>
1126
+ `(SELECT coalesce(jsonb_agg(jsonb_build_object('table', t.relname, 'name', c.conname,
1127
+ 'definition', pg_get_constraintdef(c.oid), 'validated', c.convalidated) ORDER BY t.relname, c.conname), '[]')
1128
+ FROM pg_catalog.pg_constraint c JOIN pg_catalog.pg_class t ON t.oid = c.conrelid
1129
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
1130
+ WHERE n.nspname = ${literal(schema)} AND c.contype = 'c' AND c.conname LIKE 'eloxiv\\_sync\\_%')`
1131
+
1132
+ interface RecordedGuard {
1133
+ readonly table: string
1134
+ readonly name: string
1135
+ readonly definition: string
1136
+ readonly validated: boolean
1137
+ }
1138
+
1139
+ /**
1140
+ * Install (and keep) the sync guards of a module's synced columns as CHECK constraints, and drop guards of columns
1141
+ * that no longer sync. A guard is kept only if its definition (`pg_get_constraintdef`) is the one setup recorded
1142
+ * when it installed it (`recorded`, from the module's last security state); any other constraint under its name
1143
+ * (an edited guard, a `CHECK (true)` in its place, one `NOT VALID`) is replaced. Returns the guards it replaced
1144
+ * that setup had recorded otherwise (security drift), and the names of every guard it keeps. A row already outside a guard's window makes setup fail: it
1145
+ * could not sync.
1146
+ */
1147
+ export const installSyncGuards = (
1148
+ sql: SqlClient.SqlClient,
1149
+ module: AnyKernelModule,
1150
+ recorded: ReadonlyArray<RecordedGuard> | undefined,
1151
+ ) =>
1152
+ Effect.gen(function* () {
1153
+ const replaced: Array<string> = []
1154
+ const names: Array<string> = []
1155
+ for (const entity of Object.values(module.contract.entities) as ReadonlyArray<AnyEntity>) {
1156
+ const table = `${quote(entity.table.schema)}.${quote(entity.table.name)}`
1157
+ const wanted = new Map<string, { readonly column: string; readonly guard: string; readonly check: string }>()
1158
+ if (entity.sync !== false) {
1159
+ const storage = entity.storage as Readonly<Record<string, EntityField>>
1160
+ for (const field of entity.sync.fields) {
1161
+ const declared = storage[field]
1162
+ if (declared?.guard === undefined) continue
1163
+ const { name, check } = yield* syncGuardOf(declared.column, declared.guard)
1164
+ wanted.set(name, { column: declared.column, guard: declared.guard, check })
1165
+ names.push(`${entity.table.name}.${name}`)
1166
+ }
1167
+ }
1168
+ const existing = yield* sql<{ name: string; definition: string; validated: boolean }>`
1169
+ SELECT c.conname AS name, pg_catalog.pg_get_constraintdef(c.oid) AS definition, c.convalidated AS validated
1170
+ FROM pg_catalog.pg_constraint c
1171
+ JOIN pg_catalog.pg_class t ON t.oid = c.conrelid JOIN pg_catalog.pg_namespace n ON n.oid = t.relnamespace
1172
+ WHERE n.nspname = ${entity.table.schema} AND t.relname = ${entity.table.name} AND c.contype = 'c'
1173
+ AND c.conname LIKE 'eloxiv\\_sync\\_%'`
1174
+ const present = new Map(existing.map((e) => [e.name, e]))
1175
+ const known = new Map(
1176
+ (recorded ?? []).filter((r) => r.table === entity.table.name).map((r) => [r.name, r] as const),
1177
+ )
1178
+ for (const name of present.keys()) {
1179
+ if (!wanted.has(name)) yield* sql.unsafe(`ALTER TABLE ${table} DROP CONSTRAINT ${quote(name)}`)
1180
+ }
1181
+ for (const [name, { column, guard, check }] of wanted) {
1182
+ const live = present.get(name)
1183
+ const record = known.get(name)
1184
+ if (live !== undefined && record !== undefined && live.validated && record.validated) {
1185
+ if (live.definition === record.definition) continue
1186
+ }
1187
+ if (live !== undefined) {
1188
+ // Not the guard setup installed: replaced, and drift if setup had recorded the guard itself.
1189
+ if (record !== undefined) replaced.push(`${entity.table.name}.${name} (${column})`)
1190
+ yield* sql.unsafe(`ALTER TABLE ${table} DROP CONSTRAINT ${quote(name)}`)
1191
+ }
1192
+ yield* sql.unsafe(`ALTER TABLE ${table} ADD CONSTRAINT ${quote(name)} CHECK (${check})`).pipe(
1193
+ Effect.catch((error) => {
1194
+ const cause = (error as { cause?: unknown }).cause ?? error
1195
+ const reason = cause instanceof Error ? cause.message : JSON.stringify(cause)
1196
+ return Effect.die(
1197
+ new UnsafeModuleSchema(
1198
+ module.contract.name,
1199
+ `Module ${module.contract.name}'s ${entity.cedarType} holds values sync cannot carry exactly (${name}, column ${column}: ${reason})`,
1200
+ ),
1201
+ )
1202
+ }),
1203
+ )
1204
+ yield* sql.unsafe(
1205
+ `COMMENT ON CONSTRAINT ${quote(name)} ON ${table} IS ${literal(`Eloxiv sync guard ${guard} on column ${column}`)}`,
1206
+ )
1207
+ }
1208
+ }
1209
+ return { replaced, names }
1210
+ })
1211
+
1212
+ /**
1213
+ * Where an entity's Drizzle table (the only declaration of its fields, decision 9; a MAKE module's are its
1214
+ * manifest's JSON column declarations) and the database its migrations built disagree: the table missing, another primary key, a field whose column is missing, has
1215
+ * another Postgres type than the table declares (an integer for a timestamp, `jsonb` for a `text[]`, a timestamp
1216
+ * without a time zone for one with), admits NULL where the table declares `notNull`, or is a Postgres enum with a
1217
+ * value the table does not declare. Sync and the published row would otherwise promise what the database does
1218
+ * not hold. The database may have more columns than the table declares; they are invisible to Eloxiv.
1219
+ */
1220
+ export const entityColumnProblems = (sql: SqlClient.SqlClient, module: AnyKernelModule) =>
1221
+ Effect.gen(function* () {
1222
+ const problems: Array<string> = []
1223
+ // A MAKE module's fields are declared by its manifest's JSON column declarations, held to the same rules.
1224
+ const declaredBy = module.make !== undefined ? "its manifest" : "its Drizzle table"
1225
+ const entities = Object.values(module.contract.entities) as ReadonlyArray<AnyEntity>
1226
+ // Every type the module's fields declare, resolved by Postgres once (its OID, so a domain is not its base type,
1227
+ // and its modifier): one query per module, not one per field (setup runs this at every start).
1228
+ const declaredTypes = [
1229
+ ...new Set(
1230
+ entities.flatMap((entity) =>
1231
+ Object.values(entity.storage as Readonly<Record<string, EntityField>>).map((field) => field.sqlType),
1232
+ ),
1233
+ ),
1234
+ ]
1235
+ const resolvedTypes = new Map(
1236
+ declaredTypes.length === 0
1237
+ ? []
1238
+ : (yield* sql<{ name: string; oid: number | null; mod: number | null }>`
1239
+ SELECT t.name, pg_catalog.to_regtype(t.name)::pg_catalog.oid::pg_catalog.int4 AS oid,
1240
+ pg_catalog.to_regtypemod(t.name) AS mod
1241
+ FROM pg_catalog.jsonb_array_elements_text(${JSON.stringify(declaredTypes)}::pg_catalog.jsonb) AS t(name)`).map(
1242
+ (row) => [row.name, row] as const,
1243
+ ),
1244
+ )
1245
+ for (const entity of entities) {
1246
+ const located = `${entity.table.schema}.${entity.table.name}`
1247
+ const columns = yield* sql<{
1248
+ name: string
1249
+ type: string
1250
+ oid: number
1251
+ mod: number
1252
+ enumType: number | null
1253
+ notNull: boolean
1254
+ collation: string | null
1255
+ }>`
1256
+ SELECT a.attname AS name, pg_catalog.format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS "notNull",
1257
+ a.atttypid::pg_catalog.int4 AS oid, a.atttypmod AS mod,
1258
+ CASE WHEN t.typtype = 'e' THEN t.oid WHEN e.typtype = 'e' THEN e.oid END::pg_catalog.int4 AS "enumType",
1259
+ CASE WHEN NOT co.collisdeterministic THEN co.collname::pg_catalog.text END AS collation
1260
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1261
+ JOIN pg_catalog.pg_type t ON t.oid = a.atttypid LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem AND t.typelem <> 0
1262
+ LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation
1263
+ WHERE n.nspname = ${entity.table.schema} AND c.relname = ${entity.table.name} AND c.relkind IN ('r', 'p')
1264
+ AND a.attnum > 0 AND NOT a.attisdropped`
1265
+ if (columns.length === 0) {
1266
+ problems.push(`${entity.cedarType}'s table ${located} does not exist (its migrations do not create it)`)
1267
+ continue
1268
+ }
1269
+ const key = yield* sql<{ name: string }>`
1270
+ SELECT a.attname AS name
1271
+ FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class c ON c.oid = i.indrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1272
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey)
1273
+ WHERE n.nspname = ${entity.table.schema} AND c.relname = ${entity.table.name} AND i.indisprimary
1274
+ ORDER BY a.attnum`
1275
+ const expectedKey = (entity.columns as Record<string, string>)[entity.primaryKey]!
1276
+ if (key.length !== 1 || key[0]!.name !== expectedKey) {
1277
+ problems.push(
1278
+ `${entity.cedarType}'s table ${located} has primary key ${key.map((k) => k.name).join(", ") || "none"}, but the entity's is ${expectedKey}`,
1279
+ )
1280
+ }
1281
+ const byName = new Map(columns.map((c) => [c.name, c]))
1282
+ const policyFields = new Set(
1283
+ Object.values(entity.policyAttributes).flatMap((a) => (a.kind === "column" ? [a.field] : [])),
1284
+ )
1285
+ for (const [field, declared] of Object.entries(entity.storage as Readonly<Record<string, EntityField>>)) {
1286
+ const column = byName.get(declared.column)
1287
+ if (column === undefined) {
1288
+ problems.push(
1289
+ `${entity.cedarType}.${field} is declared in column ${declared.column}, which the table has not`,
1290
+ )
1291
+ continue
1292
+ }
1293
+ // Cedar and sync compare strings exactly; a non-deterministic collation would make SQL and row-level
1294
+ // security call different strings equal (backlog 25).
1295
+ if (column.collation !== null && policyFields.has(field)) {
1296
+ problems.push(
1297
+ `${entity.cedarType}.${field} is a policy attribute, but column ${column.name} has the non-deterministic collation ${column.collation}, under which PostgreSQL compares otherwise than Cedar's exact strings`,
1298
+ )
1299
+ }
1300
+ if (!column.notNull && !declared.nullable) {
1301
+ problems.push(
1302
+ `${entity.cedarType}.${field} is notNull in ${declaredBy}, but column ${column.name} admits NULL`,
1303
+ )
1304
+ }
1305
+ // The same type, resolved by Postgres (its OID: a domain is not its base type) with the same modifier.
1306
+ const want = resolvedTypes.get(declared.sqlType)
1307
+ if (want?.oid !== column.oid || (want.mod ?? -1) !== column.mod) {
1308
+ problems.push(
1309
+ `${entity.cedarType}.${field} is ${declared.sqlType} in ${declaredBy}, but column ${column.name} is ${column.type}`,
1310
+ )
1311
+ continue
1312
+ }
1313
+ if (column.enumType !== null) {
1314
+ const labels = (yield* sql<{ label: string }>`
1315
+ SELECT enumlabel AS label FROM pg_catalog.pg_enum WHERE enumtypid = ${column.enumType}::pg_catalog.oid ORDER BY enumsortorder`).map(
1316
+ (l) => l.label,
1317
+ )
1318
+ const allowed = new Set(declared.enum ?? [])
1319
+ for (const label of labels) {
1320
+ if (!allowed.has(label)) {
1321
+ problems.push(
1322
+ `${entity.cedarType}.${field}'s enum ${column.type.replace(/\[\]$/, "")} holds ${label}, which ${declaredBy} does not declare`,
1323
+ )
1324
+ }
1325
+ }
1326
+ }
1327
+ }
1328
+ }
1329
+ return problems
1330
+ })
1331
+
1332
+ /**
1333
+ * The security-relevant state of a module's schema, as hardening leaves it: the schema's and every relation's
1334
+ * owner and privileges (column privileges included), row-level security enabled and forced, every policy
1335
+ * (roles, command, expressions), every trigger and whether it is enabled, every function's owner, privileges,
1336
+ * `SECURITY DEFINER`, body (hashed) and settings, what the runtime role may use of `eloxiv_ctx`, the module
1337
+ * roles' attributes and memberships in both directions, and the event triggers and default privileges that
1338
+ * touch the module's schema or roles. Setup records it with the
1339
+ * hardening; a later setup, and the Release status, compare the live state with it (security drift). Policy
1340
+ * expressions are printed with `pg_catalog` as the search path, so they read the same in every session.
1341
+ */
1342
+ export const securityState = (sql: SqlClient.SqlClient, module: Pick<AnyKernelModule, "schema" | "role" | "owner">) =>
1343
+ Effect.gen(function* () {
1344
+ const schema = module.schema
1345
+ const roles = [module.role, module.owner]
1346
+ const acl = (column: string) => `(SELECT coalesce(jsonb_agg(a ORDER BY a), '[]') FROM unnest(${column}::text[]) a)`
1347
+ const [saved] = yield* sql<{ path: string }>`SELECT pg_catalog.current_setting('search_path') AS path`
1348
+ yield* sql`SELECT pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true)`
1349
+ const [row] = yield* sql<{ state: unknown }>`
1350
+ SELECT jsonb_build_object(
1351
+ 'format', ${SECURITY_STATE_FORMAT}::int,
1352
+ 'schema', (SELECT jsonb_build_object('owner', pg_get_userbyid(n.nspowner), 'acl', ${sql.literal(acl("n.nspacl"))})
1353
+ FROM pg_catalog.pg_namespace n WHERE n.nspname = ${schema}),
1354
+ 'relations', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', c.relname, 'kind', c.relkind,
1355
+ 'owner', pg_get_userbyid(c.relowner), 'rls', c.relrowsecurity, 'forced', c.relforcerowsecurity,
1356
+ 'acl', ${sql.literal(acl("c.relacl"))},
1357
+ 'columns', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', a.attname, 'acl', ${sql.literal(acl("a.attacl"))})
1358
+ ORDER BY a.attname), '[]')
1359
+ FROM pg_catalog.pg_attribute a WHERE a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped AND a.attacl IS NOT NULL))
1360
+ ORDER BY c.relname), '[]')
1361
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1362
+ WHERE n.nspname = ${schema} AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')),
1363
+ 'policies', (SELECT coalesce(jsonb_agg(jsonb_build_object('table', c.relname, 'name', p.polname,
1364
+ 'permissive', p.polpermissive, 'command', p.polcmd,
1365
+ 'roles', (SELECT jsonb_agg(CASE WHEN r = 0 THEN 'public' ELSE pg_get_userbyid(r) END ORDER BY 1) FROM unnest(p.polroles) r),
1366
+ 'using', pg_get_expr(p.polqual, p.polrelid), 'check', pg_get_expr(p.polwithcheck, p.polrelid))
1367
+ ORDER BY c.relname, p.polname), '[]')
1368
+ FROM pg_catalog.pg_policy p JOIN pg_catalog.pg_class c ON c.oid = p.polrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1369
+ WHERE n.nspname = ${schema}),
1370
+ 'triggers', (SELECT coalesce(jsonb_agg(jsonb_build_object('table', c.relname, 'name', t.tgname,
1371
+ 'definition', pg_get_triggerdef(t.oid), 'enabled', t.tgenabled) ORDER BY c.relname, t.tgname), '[]')
1372
+ FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1373
+ WHERE n.nspname = ${schema} AND NOT t.tgisinternal),
1374
+ 'functions', (SELECT coalesce(jsonb_agg(jsonb_build_object(
1375
+ 'name', p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')',
1376
+ 'owner', pg_get_userbyid(p.proowner), 'securityDefiner', p.prosecdef, 'acl', ${sql.literal(acl("p.proacl"))},
1377
+ 'source', md5(coalesce(p.prosrc, '') || coalesce(p.probin, '')), 'config', p.proconfig,
1378
+ 'returns', pg_get_function_result(p.oid), 'volatility', p.provolatile, 'language', (SELECT l.lanname FROM pg_catalog.pg_language l WHERE l.oid = p.prolang))
1379
+ ORDER BY p.proname, pg_get_function_identity_arguments(p.oid)), '[]')
1380
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${schema}),
1381
+ 'roles', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', r.rolname, 'super', r.rolsuper,
1382
+ 'bypassrls', r.rolbypassrls, 'createrole', r.rolcreaterole, 'createdb', r.rolcreatedb,
1383
+ 'replication', r.rolreplication,
1384
+ -- The owner role logs in for a moment while setup connects it (any setup on the cluster, under the
1385
+ -- role lock), so its LOGIN is not state: every setup removes it under that lock.
1386
+ 'login', CASE WHEN r.rolname = ${module.owner} THEN NULL ELSE r.rolcanlogin END) ORDER BY r.rolname), '[]')
1387
+ FROM pg_catalog.pg_roles r WHERE r.rolname = ANY(${roles})),
1388
+ 'memberships', (SELECT coalesce(jsonb_agg(jsonb_build_object('role', pg_get_userbyid(m.roleid),
1389
+ 'member', pg_get_userbyid(m.member), 'inherit', m.inherit_option, 'set', m.set_option, 'admin', m.admin_option)
1390
+ ORDER BY pg_get_userbyid(m.roleid), pg_get_userbyid(m.member), pg_get_userbyid(m.grantor)), '[]')
1391
+ FROM pg_catalog.pg_auth_members m
1392
+ WHERE pg_get_userbyid(m.roleid) = ANY(${roles}) OR pg_get_userbyid(m.member) = ANY(${roles})),
1393
+ 'eventTriggers', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', e.evtname, 'event', e.evtevent,
1394
+ 'function', n.nspname || '.' || p.proname, 'enabled', e.evtenabled) ORDER BY e.evtname), '[]')
1395
+ FROM pg_catalog.pg_event_trigger e JOIN pg_catalog.pg_proc p ON p.oid = e.evtfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
1396
+ WHERE n.nspname = ${schema} OR pg_get_userbyid(p.proowner) = ANY(${roles})
1397
+ OR pg_get_userbyid(e.evtowner) = ANY(${roles})),
1398
+ 'defaultPrivileges', (SELECT coalesce(jsonb_agg(jsonb_build_object('role', pg_get_userbyid(d.defaclrole),
1399
+ 'schema', n.nspname, 'type', d.defaclobjtype, 'acl', ${sql.literal(acl("d.defaclacl"))})
1400
+ ORDER BY pg_get_userbyid(d.defaclrole), n.nspname, d.defaclobjtype), '[]')
1401
+ FROM pg_catalog.pg_default_acl d LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.defaclnamespace
1402
+ WHERE n.nspname = ${schema} OR pg_get_userbyid(d.defaclrole) = ANY(${roles})),
1403
+ 'context', jsonb_build_object(
1404
+ 'usage', has_schema_privilege(${module.role}, 'eloxiv_ctx', 'USAGE'),
1405
+ 'notExecutable', (SELECT coalesce(jsonb_agg(p.proname ORDER BY p.proname), '[]')
1406
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
1407
+ WHERE n.nspname = 'eloxiv_ctx' AND NOT has_function_privilege(${module.role}, p.oid, 'EXECUTE'))),
1408
+ 'database', (SELECT jsonb_agg(jsonb_build_object('role', r,
1409
+ 'create', pg_catalog.has_database_privilege(r, pg_catalog.current_database(), 'CREATE'),
1410
+ 'temporary', pg_catalog.has_database_privilege(r, pg_catalog.current_database(), 'TEMPORARY')) ORDER BY r)
1411
+ FROM unnest(${roles}::text[]) r),
1412
+ 'settings', (SELECT coalesce(jsonb_agg(jsonb_build_object('role', pg_get_userbyid(s.setrole),
1413
+ 'database', s.setdatabase <> 0, 'config', s.setconfig) ORDER BY pg_get_userbyid(s.setrole), s.setdatabase), '[]')
1414
+ FROM pg_catalog.pg_db_role_setting s
1415
+ WHERE pg_get_userbyid(s.setrole) = ANY(${roles})
1416
+ AND s.setdatabase IN (0, (SELECT oid FROM pg_catalog.pg_database WHERE datname = pg_catalog.current_database()))),
1417
+ 'kernelGrants', ${sql.literal(kernelGrants(roles))},
1418
+ 'syncGuards', ${sql.literal(syncGuardsState(schema))}
1419
+ ) AS state`
1420
+ yield* sql`SELECT pg_catalog.set_config('search_path', ${saved!.path}, true)`
1421
+ return row!.state as Record<string, unknown>
1422
+ })
1423
+
1424
+ /** The format of a recorded security state: one recorded in another format is not compared (setup re-hardens). */
1425
+ export const SECURITY_STATE_FORMAT = 5
1426
+
1427
+ /**
1428
+ * Every privilege the module's two roles (`roles`, an SQL array of their names) hold in the kernel's and Better Auth's schemas
1429
+ * (`KERNEL_STATE_SCHEMAS`), beyond what setup gives them: the runtime role uses `eloxiv_ctx` and `eloxiv_platform`
1430
+ * and executes their functions; the owner role uses `eloxiv_setup` and executes `record_migration` and
1431
+ * `announce_schema`. As `<kind> <object> <role> <privilege>`.
1432
+ */
1433
+ const kernelGrantRows = (roles: string) => `
1434
+ SELECT g.what || ' ' || g.object || ' ' || pg_catalog.pg_get_userbyid(g.grantee) || ' ' || g.privilege AS grant,
1435
+ g.what, g.object, pg_catalog.pg_get_userbyid(g.grantee) AS grantee
1436
+ FROM (
1437
+ SELECT 'schema' AS what, pg_catalog.quote_ident(n.nspname) AS object, n.nspname AS schema, NULL::text AS fn,
1438
+ (pg_catalog.aclexplode(n.nspacl)).grantee, (pg_catalog.aclexplode(n.nspacl)).privilege_type AS privilege
1439
+ FROM pg_catalog.pg_namespace n WHERE n.nspname = ANY(${KERNEL_STATE_SCHEMA_ARRAY})
1440
+ UNION ALL
1441
+ SELECT CASE WHEN c.relkind = 'S' THEN 'sequence' ELSE 'table' END,
1442
+ pg_catalog.quote_ident(n.nspname) || '.' || pg_catalog.quote_ident(c.relname), n.nspname, NULL,
1443
+ (pg_catalog.aclexplode(c.relacl)).grantee, (pg_catalog.aclexplode(c.relacl)).privilege_type
1444
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1445
+ WHERE n.nspname = ANY(${KERNEL_STATE_SCHEMA_ARRAY})
1446
+ UNION ALL
1447
+ SELECT 'column', pg_catalog.quote_ident(n.nspname) || '.' || pg_catalog.quote_ident(c.relname) || '('
1448
+ || pg_catalog.quote_ident(a.attname) || ')', n.nspname, NULL,
1449
+ (pg_catalog.aclexplode(a.attacl)).grantee, (pg_catalog.aclexplode(a.attacl)).privilege_type
1450
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
1451
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1452
+ WHERE n.nspname = ANY(${KERNEL_STATE_SCHEMA_ARRAY}) AND a.attacl IS NOT NULL
1453
+ UNION ALL
1454
+ SELECT 'routine', p.oid::pg_catalog.regprocedure::text, n.nspname, p.proname,
1455
+ (pg_catalog.aclexplode(p.proacl)).grantee, (pg_catalog.aclexplode(p.proacl)).privilege_type
1456
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
1457
+ WHERE n.nspname = ANY(${KERNEL_STATE_SCHEMA_ARRAY})
1458
+ ) g
1459
+ WHERE g.grantee <> 0 AND pg_catalog.pg_get_userbyid(g.grantee) = ANY(${roles})
1460
+ AND NOT (g.what = 'schema' AND g.privilege = 'USAGE' AND (
1461
+ (g.schema IN ('eloxiv_ctx', '${PLATFORM_READ_SCHEMA}') AND pg_catalog.pg_get_userbyid(g.grantee) LIKE 'eloxiv\\_mod\\_%')
1462
+ OR (g.schema = 'eloxiv_setup' AND pg_catalog.pg_get_userbyid(g.grantee) LIKE 'eloxiv\\_own\\_%')))
1463
+ AND NOT (g.what = 'routine' AND g.privilege = 'EXECUTE' AND (
1464
+ (g.schema IN ('eloxiv_ctx', '${PLATFORM_READ_SCHEMA}') AND pg_catalog.pg_get_userbyid(g.grantee) LIKE 'eloxiv\\_mod\\_%')
1465
+ OR (g.schema = 'eloxiv_setup' AND g.fn = 'record_migration'
1466
+ AND pg_catalog.pg_get_userbyid(g.grantee) LIKE 'eloxiv\\_own\\_%')))`
1467
+
1468
+ /** The unexpected privileges of `roles` (safe identifiers) in kernel schemas, sorted, for the security state. */
1469
+ const kernelGrants = (roles: ReadonlyArray<string>) =>
1470
+ `(SELECT coalesce(jsonb_agg(k.grant ORDER BY k.grant), '[]') FROM (${kernelGrantRows(
1471
+ `ARRAY[${roles.map((r) => `'${ident(r).slice(1, -1)}'`).join(", ")}]::text[]`,
1472
+ )}) k)`
1473
+
1474
+ /**
1475
+ * Before any owner session connects, under the lease, on setup's session: what a module's two roles may do in
1476
+ * the app's database beyond their own schema is held to nothing. Privileges in the kernel's and Better Auth's
1477
+ * schemas (a `GRANT SELECT ON eloxiv.membership`, on `auth."user"`, on a kernel function) are revoked, but those
1478
+ * setup gives (`kernelGrantRows`); `CREATE` and `TEMPORARY` on the database are revoked (a temporary object would
1479
+ * shadow the catalogue in the owner's session); per-role settings (`ALTER ROLE ... SET`, for every database or
1480
+ * this one) are reset. Returns whether anything was repaired; fails if anything is left.
1481
+ */
1482
+ export const moduleSessionHygiene = (sql: SqlClient.SqlClient, module: AnyKernelModule, database: string) =>
1483
+ Effect.gen(function* () {
1484
+ const roles = [module.role, module.owner]
1485
+ const inspect = Effect.gen(function* () {
1486
+ const grants = yield* sql.unsafe<{ grant: string; what: string; object: string; grantee: string }>(
1487
+ kernelGrantRows("$1"),
1488
+ [roles],
1489
+ )
1490
+ const database_ = yield* sql<{ role: string; create: boolean; temporary: boolean }>`
1491
+ SELECT r AS role, pg_catalog.has_database_privilege(r, pg_catalog.current_database(), 'CREATE') AS "create",
1492
+ pg_catalog.has_database_privilege(r, pg_catalog.current_database(), 'TEMPORARY') AS temporary
1493
+ FROM unnest(${roles}::text[]) r`
1494
+ const settings = yield* sql<{ role: string; inDatabase: boolean }>`
1495
+ SELECT pg_catalog.pg_get_userbyid(s.setrole) AS role, s.setdatabase <> 0 AS "inDatabase"
1496
+ FROM pg_catalog.pg_db_role_setting s
1497
+ WHERE pg_catalog.pg_get_userbyid(s.setrole) = ANY(${roles})
1498
+ AND s.setdatabase IN (0, (SELECT oid FROM pg_catalog.pg_database WHERE datname = pg_catalog.current_database()))`
1499
+ return { grants, database: database_.filter((d) => d.create || d.temporary), settings }
1500
+ })
1501
+ const describe = (found: Effect.Success<typeof inspect>) => [
1502
+ ...found.grants.map((g) => g.grant),
1503
+ ...found.database.map(
1504
+ (d) => `${d.role} may create ${d.create ? "schemas" : "temporary objects"} in the database`,
1505
+ ),
1506
+ ...found.settings.map((s) => `${s.role} has settings${s.inDatabase ? " in this database" : ""}`),
1507
+ ]
1508
+ const found = yield* inspect
1509
+ if (describe(found).length === 0) return false
1510
+ yield* Effect.logWarning(
1511
+ `Module ${module.contract.name}: its roles were given more outside setup (${describe(found).join("; ")}); revoking it`,
1512
+ )
1513
+ for (const g of found.grants) {
1514
+ const on =
1515
+ g.what === "column"
1516
+ ? `(${g.object.slice(g.object.indexOf("(") + 1, -1)}) ON TABLE ${g.object.slice(0, g.object.indexOf("("))}`
1517
+ : `ON ${g.what === "routine" ? "ROUTINE" : g.what.toUpperCase()} ${g.object}`
1518
+ yield* sql.unsafe(`REVOKE ALL ${on} FROM ${ident(g.grantee)}`)
1519
+ }
1520
+ for (const d of found.database)
1521
+ yield* sql.unsafe(`REVOKE CREATE, TEMPORARY ON DATABASE ${ident(database)} FROM ${ident(d.role)}`)
1522
+ for (const s of found.settings) {
1523
+ yield* sql.unsafe(
1524
+ s.inDatabase
1525
+ ? `ALTER ROLE ${ident(s.role)} IN DATABASE ${ident(database)} RESET ALL`
1526
+ : `ALTER ROLE ${ident(s.role)} RESET ALL`,
1527
+ )
1528
+ }
1529
+ const left = describe(yield* inspect)
1530
+ if (left.length > 0) {
1531
+ return yield* new MigrationFailed({
1532
+ module: module.contract.name,
1533
+ migration: null,
1534
+ message: `Module ${module.contract.name}: setup could not take back what its roles were given: ${left.join("; ")}`,
1535
+ })
1536
+ }
1537
+ return true
1538
+ })
1539
+
1540
+ /**
1541
+ * Whether each module role may log in outside setup's connect window: neither. The runtime role never logs in.
1542
+ * The owner role logs in only while setup connects a module's migration session (`connectOwner`): under the
1543
+ * cluster's role lock it gets LOGIN and a one-time password, setup connects, and both are removed before the
1544
+ * lock is released, so the open session keeps working and nothing else can log in. Every other role attribute is
1545
+ * fixed: no SUPERUSER, BYPASSRLS, CREATEROLE, CREATEDB or REPLICATION, and no password, for either.
1546
+ */
1547
+ export const MODULE_ROLE_LOGIN: { readonly runtime: boolean; readonly owner: boolean } = {
1548
+ runtime: false,
1549
+ owner: false,
1550
+ }
1551
+
1552
+ /**
1553
+ * Whether a module's runtime role logs in: only a MAKE module's. Its sandboxed code's statements run on sessions
1554
+ * that log in as that role (never on the kernel's connection), so there is no more privileged role a statement
1555
+ * could return to; setup gives it LOGIN and the password derived for it (`makeRolePassword`), as a SCRAM verifier.
1556
+ */
1557
+ export const runtimeLogin = (module: Pick<AnyKernelModule, "make">): boolean =>
1558
+ module.make !== undefined || MODULE_ROLE_LOGIN.runtime
1559
+
1560
+ interface RoleRow {
1561
+ readonly name: string
1562
+ readonly super: boolean
1563
+ readonly bypassrls: boolean
1564
+ readonly createrole: boolean
1565
+ readonly createdb: boolean
1566
+ readonly replication: boolean
1567
+ readonly login: boolean
1568
+ readonly password: boolean
1569
+ }
1570
+
1571
+ interface MembershipRow {
1572
+ readonly role: string
1573
+ readonly member: string
1574
+ readonly grantor: string
1575
+ readonly inherit: boolean
1576
+ readonly set: boolean
1577
+ readonly admin: boolean
1578
+ }
1579
+
1580
+ /**
1581
+ * Hold a module's two roles to what bootstrap gives them: the attributes above, and exactly one membership, the
1582
+ * kernel role's in the runtime role (`INHERIT FALSE, SET TRUE`, no `ADMIN`); neither role is a member of any
1583
+ * role, and nothing else is a member of either. Deviations are repaired (`ALTER ROLE`, `REVOKE`, `GRANT`),
1584
+ * whoever made them (an operator, or anything else with the rights); if any remains, setup fails. Returns
1585
+ * whether anything was repaired. A module role serves one kernel role per cluster.
1586
+ *
1587
+ * - `"cluster"`: in `bootstrapCluster`, under the cluster's role lock, before anything runs as the owner role:
1588
+ * also the owner role's LOGIN and both roles' passwords (setup is the only one that gives them, under the same
1589
+ * lock, `connectOwner`).
1590
+ * - `"setup"`: in setup's transaction, with the hardening: everything but the owner's LOGIN and the passwords
1591
+ * (another database's setup may be connecting the same owner role right now). `kernelRole` null: the owner of
1592
+ * schema `eloxiv`.
1593
+ */
1594
+ const enforceModuleRoles = (
1595
+ sql: SqlClient.SqlClient,
1596
+ module: AnyKernelModule,
1597
+ kernelRole: string | null,
1598
+ scope: "cluster" | "setup",
1599
+ existed = true,
1600
+ ) =>
1601
+ Effect.gen(function* () {
1602
+ const roles = [module.role, module.owner]
1603
+ if (kernelRole === null) {
1604
+ const [kernel] = yield* sql<{ role: string | null }>`
1605
+ SELECT pg_catalog.pg_get_userbyid(nspowner) AS role FROM pg_catalog.pg_namespace WHERE nspname = 'eloxiv'`
1606
+ kernelRole = kernel?.role ?? null
1607
+ }
1608
+ // The setup role's own membership in either role (a setup role that is no superuser holds it, and PostgreSQL
1609
+ // makes a role's creator a member with ADMIN OPTION): the setup role is trusted, and the module's roles gain
1610
+ // nothing from it (`ensureSetupMembership`).
1611
+ const [setup] = yield* sql<{ role: string }>`SELECT session_user::text AS role`
1612
+ const kernelMembership = (m: MembershipRow) =>
1613
+ m.role === module.role && m.member === kernelRole && !m.inherit && m.set && !m.admin
1614
+ const expectedMembership = (m: MembershipRow) =>
1615
+ kernelMembership(m) || ((m.role === module.role || m.role === module.owner) && m.member === setup?.role)
1616
+ const inspect = Effect.gen(function* () {
1617
+ const attributes = yield* scope === "cluster"
1618
+ ? sql<RoleRow>`
1619
+ SELECT rolname AS name, rolsuper AS super, rolbypassrls AS bypassrls, rolcreaterole AS createrole,
1620
+ rolcreatedb AS createdb, rolreplication AS replication, rolcanlogin AS login,
1621
+ rolpassword IS NOT NULL AS password
1622
+ FROM pg_catalog.pg_authid WHERE rolname = ANY(${roles}) ORDER BY rolname`
1623
+ : sql<RoleRow>`
1624
+ SELECT rolname AS name, rolsuper AS super, rolbypassrls AS bypassrls, rolcreaterole AS createrole,
1625
+ rolcreatedb AS createdb, rolreplication AS replication, rolcanlogin AS login, false AS password
1626
+ FROM pg_catalog.pg_roles WHERE rolname = ANY(${roles}) ORDER BY rolname`
1627
+ const memberships = yield* sql<MembershipRow>`
1628
+ SELECT pg_get_userbyid(roleid) AS role, pg_get_userbyid(member) AS member, pg_get_userbyid(grantor) AS grantor,
1629
+ inherit_option AS inherit, set_option AS "set", admin_option AS admin
1630
+ FROM pg_catalog.pg_auth_members WHERE pg_get_userbyid(roleid) = ANY(${roles}) OR pg_get_userbyid(member) = ANY(${roles})
1631
+ ORDER BY 1, 2, 3`
1632
+ const alter = attributes.flatMap((a) => {
1633
+ const login = a.name === module.owner ? MODULE_ROLE_LOGIN.owner : runtimeLogin(module)
1634
+ const fixes = [
1635
+ ...(a.super ? ["NOSUPERUSER"] : []),
1636
+ ...(a.bypassrls ? ["NOBYPASSRLS"] : []),
1637
+ ...(a.createrole ? ["NOCREATEROLE"] : []),
1638
+ ...(a.createdb ? ["NOCREATEDB"] : []),
1639
+ ...(a.replication ? ["NOREPLICATION"] : []),
1640
+ ...(a.login !== login && (scope === "cluster" || a.name !== module.owner)
1641
+ ? [login ? "LOGIN" : "NOLOGIN"]
1642
+ : []),
1643
+ // A MAKE module's runtime role logs in with the password setup derives for it (`makeRolePassword`).
1644
+ ...(a.password && !(module.make !== undefined && a.name === module.role) ? ["PASSWORD NULL"] : []),
1645
+ ]
1646
+ return fixes.length === 0 ? [] : [{ role: a.name, fixes }]
1647
+ })
1648
+ const unexpected = memberships.filter((m) => !expectedMembership(m))
1649
+ const missing = kernelRole !== null && !memberships.some(kernelMembership)
1650
+ return { alter, unexpected, missing }
1651
+ })
1652
+ const describe = (found: Effect.Success<typeof inspect>) => [
1653
+ ...found.alter.map((a) => `${a.role} needs ${a.fixes.join(" ")}`),
1654
+ ...found.unexpected.map((m) => `${m.member} is a member of ${m.role} (granted by ${m.grantor})`),
1655
+ ...(found.missing ? [`${kernelRole} is not a member of ${module.role} (INHERIT FALSE, SET TRUE)`] : []),
1656
+ ]
1657
+ const found = yield* inspect
1658
+ if (describe(found).length === 0) return false
1659
+ // (Roles just created only need their kernel membership: nothing changed them.)
1660
+ if (existed) {
1661
+ yield* Effect.logWarning(
1662
+ `Module ${module.contract.name}: its roles were changed outside setup (${describe(found).join("; ")}); restoring them`,
1663
+ )
1664
+ }
1665
+ for (const a of found.alter) yield* sql.unsafe(`ALTER ROLE ${ident(a.role)} ${a.fixes.join(" ")}`)
1666
+ for (const m of found.unexpected) {
1667
+ yield* sql.unsafe(`REVOKE ${ident(m.role)} FROM ${ident(m.member)} GRANTED BY ${ident(m.grantor)}`)
1668
+ }
1669
+ if (found.missing || found.unexpected.some((m) => m.role === module.role && m.member === kernelRole)) {
1670
+ yield* sql.unsafe(`GRANT ${ident(module.role)} TO ${ident(kernelRole!)} WITH INHERIT FALSE, SET TRUE`)
1671
+ }
1672
+ const left = describe(yield* inspect)
1673
+ if (left.length > 0) {
1674
+ return yield* Effect.die(
1675
+ new UnsafeModuleSchema(
1676
+ module.contract.name,
1677
+ `Module ${module.contract.name}: its roles could not be restored: ${left.join("; ")}`,
1678
+ ),
1679
+ )
1680
+ }
1681
+ return true
1682
+ })
1683
+
1684
+ /** The parts of two security states that differ (their top-level keys), for an operator's message. */
1685
+ export const securityDifferences = (expected: unknown, live: Record<string, unknown>): ReadonlyArray<string> => {
1686
+ const before = (expected ?? {}) as Record<string, unknown>
1687
+ return Object.keys(live).filter((key) => canonicalJson(before[key]) !== canonicalJson(live[key]))
1688
+ }
1689
+
1690
+ /**
1691
+ * After migrations, on setup's own superuser session: refuse unsafe objects, reset
1692
+ * privileges (runtime role: SELECT, INSERT, UPDATE, DELETE only; no TRUNCATE,
1693
+ * DDL, triggers or ownership; no other grantee at all), install the generated
1694
+ * row-level security policies (replacing any a migration created), and the
1695
+ * write-log triggers, then record the security state it left.
1696
+ *
1697
+ * A module whose migrations, tables and policies are unchanged since its last
1698
+ * hardening is left alone (no DDL), but only once its live security state is
1699
+ * checked against the one recorded: if it drifted (row-level security disabled,
1700
+ * a policy dropped or added, a privilege granted, a trigger disabled), the
1701
+ * module is hardened again and returned among the repaired; if hardening cannot
1702
+ * restore the recorded state (an object it does not manage changed), setup
1703
+ * fails instead of recording the drift.
1704
+ */
1705
+ /**
1706
+ * The work-item sources of a module whose titles copy a record field (`workItemSources.<source>.title`), by table:
1707
+ * what is kept in step (the source, the field's column; WorkItems' `followRecords`), with the table's primary key.
1708
+ */
1709
+ export const workItemTitleSources = (module: AnyKernelModule) => {
1710
+ const byTable = new Map<
1711
+ string,
1712
+ { pk: string; cedarType: string; tombstone: string | undefined; sources: Array<{ source: string; column: string }> }
1713
+ >()
1714
+ const entities = module.contract.entities as Record<string, AnyEntity>
1715
+ const declared = (module.contract.workItemSources ?? {}) as Readonly<
1716
+ Record<string, { readonly entity: string; readonly title: string }>
1717
+ >
1718
+ for (const [source, declaration] of Object.entries(declared).sort(([a], [b]) => (a < b ? -1 : 1))) {
1719
+ const entity = entities[declaration.entity]
1720
+ if (entity === undefined || entity.table.schema !== module.schema) continue
1721
+ const columns = entity.columns as Record<string, string>
1722
+ const column = columns[declaration.title]
1723
+ const pk = columns[entity.primaryKey]
1724
+ if (column === undefined || pk === undefined) continue
1725
+ const tombstoneField = (module.tombstones ?? {})[declaration.entity]
1726
+ const entry = byTable.get(entity.table.name) ?? {
1727
+ pk,
1728
+ cedarType: entity.cedarType,
1729
+ tombstone: tombstoneField === undefined ? undefined : columns[tombstoneField],
1730
+ sources: [],
1731
+ }
1732
+ entry.sources.push({ source, column })
1733
+ byTable.set(entity.table.name, entry)
1734
+ }
1735
+ return byTable
1736
+ }
1737
+
1738
+ /**
1739
+ * Clear the titles of work items whose source record is gone, or a tombstone (`KernelModule.tombstones`), closed
1740
+ * items included: titles copy record text, and an item must not outlive what it copied. Where the module words a
1741
+ * source's titles in the kernel (`KernelModule.workItemTitles`), retitle every item of a live record from it. As
1742
+ * setup's superuser.
1743
+ */
1744
+ const repairWorkItemTitles = (sql: SqlClient.SqlClient, module: AnyKernelModule) =>
1745
+ Effect.gen(function* () {
1746
+ const sources = workItemTitleSources(module)
1747
+ if (sources.size === 0) return
1748
+ const [inbox] = yield* sql<{ present: boolean }>`
1749
+ SELECT to_regclass('eloxiv_inbox.work_item') IS NOT NULL AS present`
1750
+ if (inbox?.present !== true) return
1751
+ for (const [table, titled] of sources) {
1752
+ const qualified = `${ident(module.schema)}.${ident(table)}`
1753
+ const [exists] = yield* sql<{ present: boolean }>`SELECT to_regclass(${qualified}) IS NOT NULL AS present`
1754
+ if (exists?.present !== true) continue
1755
+ for (const { source, column } of titled.sources) {
1756
+ yield* sql.unsafe(
1757
+ `UPDATE eloxiv_inbox.work_item w SET title = '', updated_at = now()
1758
+ WHERE w.module = $1 AND w.source = $2 AND w.title <> ''
1759
+ AND NOT EXISTS (SELECT 1 FROM ${qualified} r WHERE r.${ident(titled.pk)}::text = w.source_id
1760
+ ${titled.tombstone === undefined ? "" : `AND NOT r.${ident(titled.tombstone)}`})`,
1761
+ [module.contract.name, source],
1762
+ )
1763
+ // A source the module words in the kernel: live records' items take the title the record gives now (an
1764
+ // item titled before titles followed their records, or by a write that did not retitle it).
1765
+ const wording = (module.workItemTitles ?? {})[source]
1766
+ if (wording === undefined) continue
1767
+ const items = yield* sql.unsafe<{ id: string; title: string; value: string | null }>(
1768
+ `SELECT w.id, w.title, r.${ident(column)}::text AS value
1769
+ FROM eloxiv_inbox.work_item w JOIN ${qualified} r ON r.${ident(titled.pk)}::text = w.source_id
1770
+ WHERE w.module = $1 AND w.source = $2
1771
+ ${titled.tombstone === undefined ? "" : `AND NOT r.${ident(titled.tombstone)}`}`,
1772
+ [module.contract.name, source],
1773
+ )
1774
+ const stale = items.flatMap((item) => {
1775
+ const title = wording(item.value ?? "")
1776
+ return title === item.title ? [] : [{ id: item.id, title }]
1777
+ })
1778
+ if (stale.length === 0) continue
1779
+ yield* sql`UPDATE eloxiv_inbox.work_item w SET title = v.title, updated_at = now()
1780
+ FROM unnest(${stale.map((s) => s.id)}::text[], ${stale.map((s) => s.title)}::text[]) AS v(id, title)
1781
+ WHERE w.id = v.id`
1782
+ }
1783
+ }
1784
+ })
1785
+
1786
+ /** A foreign key of a module table: the referencing columns and the record they name. */
1787
+ export interface ModuleReference {
1788
+ readonly name: string
1789
+ readonly table: string
1790
+ readonly columns: ReadonlyArray<string>
1791
+ readonly parentSchema: string
1792
+ readonly parentTable: string
1793
+ readonly parentColumns: ReadonlyArray<string>
1794
+ }
1795
+
1796
+ /** The trigger guarding a foreign key (`eloxiv.guard_reference`): its name, within Postgres's 63 bytes. */
1797
+ const referenceTrigger = (constraint: string): string => {
1798
+ const name = `eloxiv_guard_ref_${constraint}`
1799
+ if (new TextEncoder().encode(name).length <= 63) return name
1800
+ let hash = 0x811c9dc5
1801
+ for (const unit of constraint) hash = Math.imul(hash ^ unit.codePointAt(0)!, 0x01000193) >>> 0
1802
+ return `eloxiv_guard_ref_${constraint.replace(/[^A-Za-z0-9_]/g, "").slice(0, 36)}_${hash.toString(16)}`
1803
+ }
1804
+
1805
+ /**
1806
+ * A module schema's constraints whose outcome can depend on rows the caller cannot read: its foreign keys, its
1807
+ * unique keys other than primary keys (unique constraints and indexes, columns `null` for one over expressions) and
1808
+ * its exclusion constraints.
1809
+ */
1810
+ const moduleConstraints = (sql: SqlClient.SqlClient, schema: string) =>
1811
+ Effect.gen(function* () {
1812
+ const references = yield* sql<{
1813
+ name: string
1814
+ table: string
1815
+ columns: Array<string>
1816
+ parentSchema: string
1817
+ parentTable: string
1818
+ parentColumns: Array<string>
1819
+ }>`
1820
+ SELECT c.conname AS name, cl.relname AS "table",
1821
+ ARRAY(SELECT a.attname::text FROM unnest(c.conkey) WITH ORDINALITY k(attnum, i)
1822
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum ORDER BY k.i) AS columns,
1823
+ pn.nspname AS "parentSchema", pc.relname AS "parentTable",
1824
+ ARRAY(SELECT a.attname::text FROM unnest(c.confkey) WITH ORDINALITY k(attnum, i)
1825
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = c.confrelid AND a.attnum = k.attnum ORDER BY k.i) AS "parentColumns"
1826
+ FROM pg_catalog.pg_constraint c
1827
+ JOIN pg_catalog.pg_class cl ON cl.oid = c.conrelid JOIN pg_catalog.pg_namespace n ON n.oid = cl.relnamespace
1828
+ JOIN pg_catalog.pg_class pc ON pc.oid = c.confrelid JOIN pg_catalog.pg_namespace pn ON pn.oid = pc.relnamespace
1829
+ WHERE n.nspname = ${schema} AND c.contype = 'f' ORDER BY cl.relname, c.conname`
1830
+ // Foreign keys that reference anything but their parent's single-column primary key, the one key the key guard
1831
+ // makes immutable: changing another referenced key fails with a referencing record and succeeds without one.
1832
+ const mutableReferences = yield* sql<{ name: string; table: string }>`
1833
+ SELECT c.conname AS name, cl.relname AS "table"
1834
+ FROM pg_catalog.pg_constraint c
1835
+ JOIN pg_catalog.pg_class cl ON cl.oid = c.conrelid JOIN pg_catalog.pg_namespace n ON n.oid = cl.relnamespace
1836
+ WHERE n.nspname = ${schema} AND c.contype = 'f' AND NOT EXISTS (
1837
+ SELECT 1 FROM pg_catalog.pg_index i
1838
+ WHERE i.indrelid = c.confrelid AND i.indisprimary AND i.indnatts = 1 AND c.confkey = ARRAY[i.indkey[0]])
1839
+ ORDER BY 2, 1`
1840
+ // Only the key attributes (the first `indnkeyatts`; INCLUDE columns play no part in uniqueness). A column anchors
1841
+ // a key to the actor or organisation only where the index compares it as policies do: its type's default operator
1842
+ // class and a deterministic collation (a case-insensitive one would make two organisations' ids collide).
1843
+ const unique = yield* sql<{
1844
+ table: string
1845
+ name: string
1846
+ columns: Array<string> | null
1847
+ anchors: Array<string> | null
1848
+ kind: string
1849
+ }>`
1850
+ SELECT cl.relname AS "table", ic.relname AS name, 'unique' AS kind,
1851
+ CASE WHEN 0 = ANY ((i.indkey::int2[])[0:i.indnkeyatts - 1]) OR i.indexprs IS NOT NULL THEN NULL ELSE
1852
+ ARRAY(SELECT a.attname::text FROM generate_series(0, i.indnkeyatts - 1) AS k(o)
1853
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[k.o] ORDER BY k.o) END AS columns,
1854
+ CASE WHEN 0 = ANY ((i.indkey::int2[])[0:i.indnkeyatts - 1]) OR i.indexprs IS NOT NULL THEN NULL ELSE
1855
+ ARRAY(SELECT a.attname::text FROM generate_series(0, i.indnkeyatts - 1) AS k(o)
1856
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[k.o]
1857
+ JOIN pg_catalog.pg_opclass oc ON oc.oid = i.indclass[k.o] AND oc.opcdefault
1858
+ LEFT JOIN pg_catalog.pg_collation co ON co.oid = i.indcollation[k.o]
1859
+ WHERE i.indcollation[k.o] = 0 OR co.collisdeterministic ORDER BY k.o) END AS anchors
1860
+ FROM pg_catalog.pg_index i
1861
+ JOIN pg_catalog.pg_class cl ON cl.oid = i.indrelid JOIN pg_catalog.pg_namespace n ON n.oid = cl.relnamespace
1862
+ JOIN pg_catalog.pg_class ic ON ic.oid = i.indexrelid
1863
+ WHERE n.nspname = ${schema} AND i.indisunique AND NOT i.indisprimary
1864
+ UNION ALL
1865
+ SELECT cl.relname, c.conname, 'exclusion', NULL, NULL
1866
+ FROM pg_catalog.pg_constraint c
1867
+ JOIN pg_catalog.pg_class cl ON cl.oid = c.conrelid JOIN pg_catalog.pg_namespace n ON n.oid = cl.relnamespace
1868
+ WHERE n.nspname = ${schema} AND c.contype = 'x'
1869
+ ORDER BY 1, 2`
1870
+ return {
1871
+ references: references satisfies ReadonlyArray<ModuleReference>,
1872
+ mutableReferences,
1873
+ unique: unique.map((u) => ({
1874
+ table: `${schema}.${u.table}`,
1875
+ name: u.name,
1876
+ columns: u.columns,
1877
+ anchors: u.anchors,
1878
+ kind: u.kind as "unique" | "exclusion",
1879
+ })),
1880
+ }
1881
+ })
1882
+
1883
+ export const hardenModules = <E, R>(
1884
+ sql: SqlClient.SqlClient,
1885
+ modules: ReadonlyArray<AnyKernelModule>,
1886
+ /** The Cedar policies row-level security is generated from: every module's, or each module's own (MAKE). */
1887
+ policies: string | ((module: AnyKernelModule) => string),
1888
+ /** Publish the module's query views (`publishModuleViews`): after its hardening, before its state is recorded. */
1889
+ views: (module: AnyKernelModule) => Effect.Effect<void, E, R>,
1890
+ ) =>
1891
+ Effect.gen(function* () {
1892
+ yield* pinCatalogPath(sql)
1893
+ const repaired: Array<string> = []
1894
+ for (const module of modules) {
1895
+ const schema = module.schema
1896
+ const unsafe = yield* unsafeModuleObjects(sql, schema, [module.role, module.owner])
1897
+ if (unsafe.length > 0) {
1898
+ return yield* Effect.die(
1899
+ new UnsafeModuleSchema(
1900
+ module.contract.name,
1901
+ `Module ${module.contract.name} left objects that escape row-level security: ${unsafe.join("; ")}`,
1902
+ ),
1903
+ )
1904
+ }
1905
+ const columns = yield* policyColumnProblems(sql, module)
1906
+ if (columns.length > 0) {
1907
+ return yield* Effect.die(
1908
+ new UnsafeModuleSchema(
1909
+ module.contract.name,
1910
+ `Module ${module.contract.name} stores policy attributes the compiler cannot read exactly: ${columns.join("; ")}`,
1911
+ ),
1912
+ )
1913
+ }
1914
+ const fields = yield* entityColumnProblems(sql, module)
1915
+ if (fields.length > 0) {
1916
+ return yield* Effect.die(
1917
+ new UnsafeModuleSchema(
1918
+ module.contract.name,
1919
+ `Module ${module.contract.name}'s ${module.make !== undefined ? "entities" : "Drizzle tables"} do not match its database: ${fields.join("; ")}`,
1920
+ ),
1921
+ )
1922
+ }
1923
+ // Every setup: work-item titles of records that are gone or tombstoned keep nothing of them (closed items
1924
+ // too), and those of live records the kernel words say what the record says now, whatever ran before.
1925
+ yield* repairWorkItemTitles(sql, module)
1926
+ const [stored] = yield* sql<{ fingerprint: string; security: unknown }>`
1927
+ SELECT fingerprint, security FROM eloxiv.module_hardening WHERE module = ${module.contract.name}`
1928
+ // (A state recorded before this format, or none, is simply hardened again.)
1929
+ const recorded = (stored?.security as { format?: unknown } | null | undefined)?.format === SECURITY_STATE_FORMAT
1930
+ // Every setup: synced columns of a type sync carries exactly only within a window are held to it, by the
1931
+ // guards setup recorded (a guard changed since is replaced: drift).
1932
+ const guards = yield* installSyncGuards(
1933
+ sql,
1934
+ module,
1935
+ recorded ? (stored!.security as { syncGuards?: ReadonlyArray<RecordedGuard> }).syncGuards : undefined,
1936
+ )
1937
+ if (guards.replaced.length > 0) {
1938
+ yield* Effect.logWarning(
1939
+ `Module ${module.contract.name}: its sync guards (${guards.replaced.join(", ")}) changed outside setup; replaced them`,
1940
+ )
1941
+ }
1942
+ // Roles are checked and restored every time, also when the module itself is unchanged: bootstrap restored
1943
+ // them under the role lock, and this catches anything changed since (the owner's LOGIN excepted, which only
1944
+ // the role lock may change).
1945
+ const rolesRepaired = yield* enforceModuleRoles(sql, module, null, "setup")
1946
+ const modulePolicies = typeof policies === "string" ? policies : policies(module)
1947
+ // Constraints whose outcome could depend on records the caller cannot read (backlog 1): unique keys must be
1948
+ // ones a writer can only conflict on with records it can read; references are guarded (below).
1949
+ const constraints = yield* moduleConstraints(sql, schema)
1950
+ // The kernel's own modules are exempt: kernel code, whose handlers check the record a key names (an agent's
1951
+ // conversation) before writing.
1952
+ const uniqueProblems = isKernelProvided(module)
1953
+ ? []
1954
+ : uniqueKeyProblems(module.contract, modulePolicies, constraints.unique)
1955
+ if (constraints.mutableReferences.length > 0) {
1956
+ return yield* Effect.die(
1957
+ new UnsafeModuleSchema(
1958
+ module.contract.name,
1959
+ `Module ${module.contract.name} has foreign keys that reference a key other than their table's primary key, whose changes would disclose referencing records a writer cannot read: ${constraints.mutableReferences.map((r) => `${r.name} on ${schema}.${r.table}`).join("; ")}. Reference the primary key`,
1960
+ ),
1961
+ )
1962
+ }
1963
+ if (uniqueProblems.length > 0) {
1964
+ return yield* Effect.die(
1965
+ new UnsafeModuleSchema(
1966
+ module.contract.name,
1967
+ `Module ${module.contract.name} has unique keys whose conflicts would disclose records a writer cannot read: ${uniqueProblems.join("; ")}`,
1968
+ ),
1969
+ )
1970
+ }
1971
+ const generatedList = tablePolicies(
1972
+ module.contract,
1973
+ { runtime: module.role, owner: module.owner },
1974
+ modulePolicies,
1975
+ )
1976
+ // Tables of entities that keep a record history (Versioning), in this module's schema.
1977
+ const historyTables = new Set(
1978
+ (Object.values(module.contract.entities) as ReadonlyArray<AnyEntity>)
1979
+ .filter((entity) => entity.history === true && entity.table.schema === schema)
1980
+ .map((entity) => entity.table.name),
1981
+ )
1982
+ const tableList = yield* sql<{ table: string; pk: string | null }>`
1983
+ SELECT c.relname AS "table",
1984
+ (SELECT a.attname FROM pg_catalog.pg_index i JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0]
1985
+ WHERE i.indrelid = c.oid AND i.indisprimary AND i.indnatts = 1) AS pk
1986
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1987
+ WHERE n.nspname = ${schema} AND c.relkind IN ('r', 'p') ORDER BY 1`
1988
+ const applied = yield* sql<{ name: string }>`
1989
+ SELECT name FROM eloxiv.module_migration WHERE module = ${module.contract.name} ORDER BY name`
1990
+ const kernelApplied = (yield* sql<{ name: string }>`
1991
+ SELECT name FROM eloxiv.module_migration WHERE module = 'eloxiv' ORDER BY name`).map((m) => m.name)
1992
+ const fingerprint = yield* Effect.promise(() =>
1993
+ sha256(
1994
+ JSON.stringify([
1995
+ // Kernel migrations can change what hardening installs (functions, triggers): re-harden after them.
1996
+ kernelApplied,
1997
+ module.role,
1998
+ module.owner,
1999
+ tableList,
2000
+ applied,
2001
+ generatedList.map((t) => t.statements),
2002
+ // The foreign keys the reference guards follow.
2003
+ constraints.references,
2004
+ // What Search and Files track (the trigger and what setup indexes).
2005
+ trackedDeclarations(module),
2006
+ // Tables whose write log keeps rows for record history (Versioning): their triggers differ.
2007
+ [...historyTables].sort(),
2008
+ // Work-item titles copied from record fields: brought into step when this changes.
2009
+ [...workItemTitleSources(module)].sort(([a], [b]) => (a < b ? -1 : 1)),
2010
+ // A new set of guards (a column synced, a guard's window changed) is a change, not drift.
2011
+ guards.names,
2012
+ ]),
2013
+ ),
2014
+ )
2015
+ // Nothing changed since the last setup (migrations, tables, policies, guards): leave privileges and RLS as
2016
+ // they are, provided nothing changed them since either.
2017
+ let drifted: ReadonlyArray<string> = []
2018
+ if (stored?.fingerprint === fingerprint && recorded) {
2019
+ drifted = securityDifferences(stored.security, yield* securityState(sql, module))
2020
+ if (drifted.length === 0) {
2021
+ if (rolesRepaired || guards.replaced.length > 0) repaired.push(module.contract.name)
2022
+ yield* views(module)
2023
+ continue
2024
+ }
2025
+ yield* Effect.logWarning(
2026
+ `Module ${module.contract.name}: its security state (${drifted.join(", ")}) changed outside setup; hardening it again`,
2027
+ )
2028
+ }
2029
+
2030
+ const runtime = ident(module.role)
2031
+ const owner = ident(module.owner)
2032
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA ${ident(schema)} FROM PUBLIC, ${runtime}`)
2033
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA ${ident(schema)} TO ${runtime}`)
2034
+ yield* sql.unsafe(`REVOKE ALL ON ALL TABLES IN SCHEMA ${ident(schema)} FROM PUBLIC, ${runtime}`)
2035
+ yield* sql.unsafe(`GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ${ident(schema)} TO ${runtime}`)
2036
+ yield* sql.unsafe(`REVOKE ALL ON ALL SEQUENCES IN SCHEMA ${ident(schema)} FROM PUBLIC, ${runtime}`)
2037
+ yield* sql.unsafe(`GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA ${ident(schema)} TO ${runtime}`)
2038
+ yield* sql.unsafe(`REVOKE ALL ON ALL ROUTINES IN SCHEMA ${ident(schema)} FROM PUBLIC, ${runtime}`)
2039
+ yield* sql.unsafe(`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA ${ident(schema)} TO ${runtime}`)
2040
+ // Nobody but the owner and the runtime role holds a privilege in the schema, whoever granted it.
2041
+ yield* revokeOthers(sql, schema, [module.role])
2042
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA eloxiv_ctx TO ${runtime}`)
2043
+ yield* sql.unsafe(`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA eloxiv_ctx TO ${runtime}`)
2044
+ // The MAKE call functions are for MAKE modules' sessions only (each also checks the call's own ticket).
2045
+ if (module.make === undefined) {
2046
+ yield* sql.unsafe(
2047
+ `REVOKE EXECUTE ON FUNCTION eloxiv_ctx.make_call_of(text), eloxiv_ctx.make_claim(text, text, text),
2048
+ eloxiv_ctx.make_finish(text, jsonb), eloxiv_ctx.make_consume(text), eloxiv_ctx.make_deliver(text)
2049
+ FROM ${runtime}`,
2050
+ )
2051
+ }
2052
+
2053
+ const generated = new Map(generatedList.map((t) => [t.table, t]))
2054
+ const tracked = trackedTables(module)
2055
+ for (const t of generated.values()) {
2056
+ for (const d of t.denied) yield* Effect.logWarning(`${d.action} is denied on ${t.table}: ${d.reason}`)
2057
+ }
2058
+ for (const { table, pk } of tableList) {
2059
+ const qualified = `${ident(schema)}.${ident(table)}`
2060
+ const existing = yield* sql<{ name: string }>`
2061
+ SELECT policyname AS name FROM pg_catalog.pg_policies WHERE schemaname = ${schema} AND tablename = ${table}`
2062
+ for (const { name } of existing) yield* sql.unsafe(`DROP POLICY ${ident(name)} ON ${qualified}`)
2063
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE ROW LEVEL SECURITY`)
2064
+ yield* sql.unsafe(`ALTER TABLE ${qualified} FORCE ROW LEVEL SECURITY`)
2065
+ // Migrations run as the owner, which the runtime and the kernel cannot reach.
2066
+ yield* sql.unsafe(
2067
+ `CREATE POLICY eloxiv_migrate ON ${qualified} FOR ALL TO ${owner} USING (true) WITH CHECK (true)`,
2068
+ )
2069
+ // Tables without an entity contract get no runtime policy: the runtime role is denied (fail closed).
2070
+ for (const statement of generated.get(`${schema}.${table}`)?.statements ?? []) yield* sql.unsafe(statement)
2071
+ yield* sql.unsafe(
2072
+ `CREATE OR REPLACE TRIGGER eloxiv_track_write AFTER INSERT OR UPDATE OR DELETE ON ${qualified}
2073
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.track_write(${literal(pk ?? "")}${historyTables.has(table) && pk !== null ? ", 'history'" : ""})`,
2074
+ )
2075
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE TRIGGER eloxiv_track_write`)
2076
+ // Search and Files (entities declaring `search` or `files`): the index and record deletion follow every
2077
+ // write, in its transaction.
2078
+ if (tracked.has(table)) {
2079
+ yield* sql.unsafe(
2080
+ `CREATE OR REPLACE TRIGGER eloxiv_track_record AFTER INSERT OR UPDATE OR DELETE ON ${qualified}
2081
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.track_record()`,
2082
+ )
2083
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE TRIGGER eloxiv_track_record`)
2084
+ } else {
2085
+ yield* sql.unsafe(`DROP TRIGGER IF EXISTS eloxiv_track_record ON ${qualified}`)
2086
+ }
2087
+ // Records whose work items copy their text get a generation even when Search and Files do not track them
2088
+ // (every write moves it, under the record's lock), so a title prepared before a change is never applied
2089
+ // after it (WorkItems' fence).
2090
+ const titled = workItemTitleSources(module).get(table)
2091
+ if (titled !== undefined && !tracked.has(table)) {
2092
+ yield* sql.unsafe(
2093
+ `CREATE OR REPLACE TRIGGER eloxiv_track_generation AFTER INSERT OR UPDATE OR DELETE ON ${qualified}
2094
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.track_generation(${literal(titled.cedarType)}, ${literal(titled.pk)})`,
2095
+ )
2096
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE TRIGGER eloxiv_track_generation`)
2097
+ } else {
2098
+ yield* sql.unsafe(`DROP TRIGGER IF EXISTS eloxiv_track_generation ON ${qualified}`)
2099
+ }
2100
+ // Identities are immutable outside migrations (the write log and every check key on them). The guard
2101
+ // runs before the update, so referential checks never run on a key change (their outcome would reveal
2102
+ // unreadable children), and setup refuses every other BEFORE UPDATE trigger, so nothing changes the
2103
+ // key after it.
2104
+ yield* sql.unsafe(`DROP TRIGGER IF EXISTS eloxiv_guard_key_final ON ${qualified}`)
2105
+ if (pk !== null) {
2106
+ yield* sql.unsafe(
2107
+ `CREATE OR REPLACE TRIGGER eloxiv_guard_key BEFORE UPDATE ON ${qualified}
2108
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.guard_key(${literal(pk)}, ${literal(module.owner)})`,
2109
+ )
2110
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE TRIGGER eloxiv_guard_key`)
2111
+ }
2112
+ // A new or changed reference must name a record the writer can read: a missing record and an unreadable
2113
+ // one are refused alike, before the referential check (whose outcome would tell them apart).
2114
+ const references = constraints.references.filter((r) => r.table === table)
2115
+ const wanted = new Set(references.map((r) => referenceTrigger(r.name)))
2116
+ const present = yield* sql<{ name: string }>`
2117
+ SELECT t.tgname AS name FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
2118
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2119
+ WHERE n.nspname = ${schema} AND c.relname = ${table} AND NOT t.tgisinternal AND t.tgname LIKE 'eloxiv\\_guard\\_ref\\_%'`
2120
+ for (const { name } of present) {
2121
+ if (!wanted.has(name)) yield* sql.unsafe(`DROP TRIGGER ${ident(name)} ON ${qualified}`)
2122
+ }
2123
+ for (const reference of references) {
2124
+ const trigger = ident(referenceTrigger(reference.name))
2125
+ const args = [
2126
+ module.owner,
2127
+ reference.parentSchema,
2128
+ reference.parentTable,
2129
+ ...reference.columns,
2130
+ ...reference.parentColumns,
2131
+ ]
2132
+ yield* sql.unsafe(
2133
+ `CREATE OR REPLACE TRIGGER ${trigger} BEFORE INSERT OR UPDATE ON ${qualified}
2134
+ FOR EACH ROW EXECUTE FUNCTION eloxiv.guard_reference(${args.map(literal).join(", ")})`,
2135
+ )
2136
+ yield* sql.unsafe(`ALTER TABLE ${qualified} ENABLE TRIGGER ${trigger}`)
2137
+ }
2138
+ }
2139
+ // The views are part of what is recorded: their privileges are the module's state too.
2140
+ yield* views(module)
2141
+ const security = yield* securityState(sql, module)
2142
+ if (drifted.length > 0) {
2143
+ // A repair: hardening must have restored exactly the state it recorded last time.
2144
+ const left = securityDifferences(stored!.security, security)
2145
+ if (left.length > 0) {
2146
+ return yield* Effect.die(
2147
+ new UnsafeModuleSchema(
2148
+ module.contract.name,
2149
+ `Module ${module.contract.name}: its security state (${left.join(", ")}) was changed outside setup, ` +
2150
+ `and hardening cannot restore it (an object it does not manage was changed: an owner, a trigger, ` +
2151
+ `a function's body or settings). Undo the change, then run setup again.`,
2152
+ ),
2153
+ )
2154
+ }
2155
+ }
2156
+ if (drifted.length > 0 || rolesRepaired || guards.replaced.length > 0) repaired.push(module.contract.name)
2157
+ yield* sql`INSERT INTO eloxiv.module_hardening (module, fingerprint, security)
2158
+ VALUES (${module.contract.name}, ${fingerprint}, ${JSON.stringify(security)}::jsonb)
2159
+ ON CONFLICT (module) DO UPDATE SET fingerprint = EXCLUDED.fingerprint, security = EXCLUDED.security,
2160
+ hardened_at = now()`
2161
+ }
2162
+ return repaired
2163
+ })
2164
+
2165
+ /**
2166
+ * Revoke every privilege in `schema` (on it, and on its relations, columns, sequences and functions) from every
2167
+ * role holding one but the objects' owners and `keep`, whoever granted it.
2168
+ */
2169
+ const revokeOthers = (sql: SqlClient.SqlClient, schema: string, keep: ReadonlyArray<string>) =>
2170
+ Effect.gen(function* () {
2171
+ const others = yield* sql<{ grantee: string }>`
2172
+ SELECT DISTINCT pg_catalog.pg_get_userbyid(a.grantee) AS grantee FROM (
2173
+ SELECT (pg_catalog.aclexplode(c.relacl)).grantee, c.relowner AS owner FROM pg_catalog.pg_class c
2174
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${schema} AND c.relacl IS NOT NULL
2175
+ UNION ALL
2176
+ SELECT (pg_catalog.aclexplode(at.attacl)).grantee, c.relowner FROM pg_catalog.pg_attribute at
2177
+ JOIN pg_catalog.pg_class c ON c.oid = at.attrelid
2178
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${schema} AND at.attacl IS NOT NULL
2179
+ UNION ALL
2180
+ SELECT (pg_catalog.aclexplode(p.proacl)).grantee, p.proowner FROM pg_catalog.pg_proc p
2181
+ JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${schema} AND p.proacl IS NOT NULL
2182
+ UNION ALL
2183
+ SELECT (pg_catalog.aclexplode(n.nspacl)).grantee, n.nspowner FROM pg_catalog.pg_namespace n
2184
+ WHERE n.nspname = ${schema} AND n.nspacl IS NOT NULL
2185
+ ) a WHERE a.grantee <> 0 AND a.grantee <> a.owner AND NOT (pg_catalog.pg_get_userbyid(a.grantee) = ANY(${[...keep]}))
2186
+ ORDER BY 1`
2187
+ for (const { grantee } of others) {
2188
+ const who = ident(grantee)
2189
+ yield* sql.unsafe(`REVOKE ALL ON ALL TABLES IN SCHEMA ${ident(schema)} FROM ${who}`)
2190
+ yield* sql.unsafe(`REVOKE ALL ON ALL SEQUENCES IN SCHEMA ${ident(schema)} FROM ${who}`)
2191
+ yield* sql.unsafe(`REVOKE ALL ON ALL ROUTINES IN SCHEMA ${ident(schema)} FROM ${who}`)
2192
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA ${ident(schema)} FROM ${who}`)
2193
+ }
2194
+ })
2195
+
2196
+ /**
2197
+ * The kernel's security state: in its schemas (`KERNEL_STATE_SCHEMAS`: `eloxiv`, `eloxiv_ctx`, `eloxiv_setup`,
2198
+ * `eloxiv_cluster`, the query surface's `eloxiv_surface`, the platform reads' `eloxiv_platform`) and Better Auth's
2199
+ * (`auth`), each schema's, relation's, column's and routine's owner and privileges, row-level security, every
2200
+ * view's definition, every routine's `SECURITY DEFINER`, settings and body (hashed), every trigger on their
2201
+ * tables and whether it is enabled, the default privileges in those schemas or of the kernel role, which of
2202
+ * `REVOKED_CATALOG_FUNCTIONS` PUBLIC may run, and the attributes and memberships of the kernel's fixed roles
2203
+ * (`KERNEL_FIXED_ROLES`: `eloxiv_query`, `eloxiv_platform_read`, which owns the SECURITY DEFINER platform reads;
2204
+ * a kernel role's `SET`-only membership in `eloxiv_query` is expected, one per app on the cluster). Privileges of module roles are left out: setup
2205
+ * holds them to fixed values itself (`moduleSessionHygiene`, `hardenModules`). Setup records it at the end of
2206
+ * every setup in `eloxiv_release.kernel_state`, which only setup's superuser can write; the next setup, before
2207
+ * anything runs, and `status` compare the live state with it. Nothing changes these schemas but setup, so a
2208
+ * difference is security drift: setup refuses it, never records it.
2209
+ */
2210
+ export const kernelSecurityState = (sql: SqlClient.SqlClient) =>
2211
+ Effect.gen(function* () {
2212
+ // A privilege list as granted, the default one (a NULL acl) written out, so granting and revoking back leaves
2213
+ // it equal; without the module roles' entries.
2214
+ const acl = (column: string, kind: string, owner: string) =>
2215
+ `(SELECT coalesce(jsonb_agg(a ORDER BY a), '[]')
2216
+ FROM unnest(coalesce(${column}, pg_catalog.acldefault(${kind}, ${owner}))::text[]) a
2217
+ WHERE a !~ '^"?eloxiv_(mod|own)_')`
2218
+ const plainAcl = (column: string) =>
2219
+ `(SELECT coalesce(jsonb_agg(a ORDER BY a), '[]') FROM unnest(${column}::text[]) a WHERE a !~ '^"?eloxiv_(mod|own)_')`
2220
+ const schemas = KERNEL_STATE_SCHEMA_ARRAY
2221
+ const [row] = yield* sql<{ state: Record<string, unknown> }>`
2222
+ SELECT jsonb_build_object(
2223
+ 'format', ${KERNEL_STATE_FORMAT}::int,
2224
+ 'schemas', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', n.nspname,
2225
+ 'owner', pg_catalog.pg_get_userbyid(n.nspowner), 'acl', ${sql.literal(acl("n.nspacl", "'n'", "n.nspowner"))}) ORDER BY n.nspname), '[]')
2226
+ FROM pg_catalog.pg_namespace n WHERE n.nspname = ANY(${sql.literal(schemas)})),
2227
+ 'relations', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', n.nspname || '.' || c.relname, 'kind', c.relkind,
2228
+ 'owner', pg_catalog.pg_get_userbyid(c.relowner), 'rls', c.relrowsecurity, 'forced', c.relforcerowsecurity,
2229
+ 'definition', CASE WHEN c.relkind IN ('v', 'm') THEN pg_catalog.pg_get_viewdef(c.oid) END,
2230
+ 'acl', ${sql.literal(acl("c.relacl", "CASE WHEN c.relkind = 'S' THEN 's' ELSE 'r' END::\"char\"", "c.relowner"))}) ORDER BY n.nspname, c.relname), '[]')
2231
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2232
+ WHERE n.nspname = ANY(${sql.literal(schemas)}) AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')),
2233
+ 'columns', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', n.nspname || '.' || c.relname || '(' || a.attname || ')',
2234
+ 'acl', ${sql.literal(plainAcl("a.attacl"))}) ORDER BY n.nspname, c.relname, a.attname), '[]')
2235
+ FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
2236
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2237
+ WHERE n.nspname = ANY(${sql.literal(schemas)}) AND a.attnum > 0 AND NOT a.attisdropped AND a.attacl IS NOT NULL
2238
+ AND ${sql.literal(plainAcl("a.attacl"))} <> '[]'::jsonb),
2239
+ 'routines', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', p.oid::pg_catalog.regprocedure::text,
2240
+ 'owner', pg_catalog.pg_get_userbyid(p.proowner), 'securityDefiner', p.prosecdef, 'config', p.proconfig,
2241
+ 'source', pg_catalog.md5(coalesce(p.prosrc, '') || coalesce(p.probin, '')),
2242
+ 'acl', ${sql.literal(acl("p.proacl", "'f'", "p.proowner"))})
2243
+ ORDER BY p.oid::pg_catalog.regprocedure::text), '[]')
2244
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2245
+ WHERE n.nspname = ANY(${sql.literal(schemas)})),
2246
+ 'triggers', (SELECT coalesce(jsonb_agg(jsonb_build_object('on', n.nspname || '.' || c.relname, 'name', t.tgname,
2247
+ 'definition', pg_catalog.pg_get_triggerdef(t.oid), 'enabled', t.tgenabled)
2248
+ ORDER BY n.nspname, c.relname, t.tgname), '[]')
2249
+ FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid
2250
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2251
+ WHERE n.nspname = ANY(${sql.literal(schemas)}) AND NOT t.tgisinternal),
2252
+ 'defaultPrivileges', (SELECT coalesce(jsonb_agg(jsonb_build_object(
2253
+ 'name', pg_catalog.pg_get_userbyid(d.defaclrole) || ' in ' || coalesce(n.nspname, 'every schema') || ' on ' || d.defaclobjtype::text,
2254
+ 'acl', ${sql.literal(plainAcl("d.defaclacl"))})
2255
+ ORDER BY pg_catalog.pg_get_userbyid(d.defaclrole), n.nspname, d.defaclobjtype), '[]')
2256
+ FROM pg_catalog.pg_default_acl d LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.defaclnamespace
2257
+ WHERE n.nspname = ANY(${sql.literal(schemas)})
2258
+ OR d.defaclrole = (SELECT k.nspowner FROM pg_catalog.pg_namespace k WHERE k.nspname = 'eloxiv')),
2259
+ 'eventTriggers', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', e.evtname, 'event', e.evtevent,
2260
+ 'function', p.oid::pg_catalog.regprocedure::text, 'owner', pg_catalog.pg_get_userbyid(e.evtowner),
2261
+ 'tags', e.evttags) ORDER BY e.evtname), '[]')
2262
+ FROM pg_catalog.pg_event_trigger e JOIN pg_catalog.pg_proc p ON p.oid = e.evtfoid
2263
+ JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2264
+ WHERE n.nspname = ANY(${sql.literal(schemas)})),
2265
+ 'catalog', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', f,
2266
+ 'public', pg_catalog.has_function_privilege('public', f::pg_catalog.regprocedure, 'EXECUTE')) ORDER BY f), '[]')
2267
+ FROM unnest(${[...REVOKED_CATALOG_FUNCTIONS]}::text[]) f
2268
+ WHERE pg_catalog.to_regprocedure(f) IS NOT NULL),
2269
+ 'roles', (SELECT coalesce(jsonb_agg(jsonb_build_object('name', r.rolname, 'super', r.rolsuper,
2270
+ 'bypassrls', r.rolbypassrls, 'createrole', r.rolcreaterole, 'createdb', r.rolcreatedb,
2271
+ 'replication', r.rolreplication, 'login', r.rolcanlogin, 'inherit', r.rolinherit,
2272
+ 'memberships', (SELECT coalesce(jsonb_agg(jsonb_build_object('role', pg_catalog.pg_get_userbyid(m.roleid),
2273
+ 'member', pg_catalog.pg_get_userbyid(m.member), 'inherit', m.inherit_option, 'set', m.set_option,
2274
+ 'admin', m.admin_option)
2275
+ ORDER BY pg_catalog.pg_get_userbyid(m.roleid), pg_catalog.pg_get_userbyid(m.member)), '[]')
2276
+ FROM pg_catalog.pg_auth_members m WHERE m.member = r.oid OR (m.roleid = r.oid
2277
+ -- A kernel role's membership in the query role (bootstrapCluster), one per app on the cluster.
2278
+ AND NOT (r.rolname = ${QUERY_ROLE} AND NOT m.inherit_option AND m.set_option AND NOT m.admin_option))))
2279
+ ORDER BY r.rolname), '[]')
2280
+ FROM pg_catalog.pg_roles r WHERE r.rolname = ANY(${[...KERNEL_FIXED_ROLES]}::text[]))
2281
+ ) AS state`
2282
+ return row!.state
2283
+ })
2284
+
2285
+ /**
2286
+ * Parts of the kernel's recorded state added within its format (`KERNEL_STATE_FORMAT`): a record written before one
2287
+ * existed lacks it, and is compared without it until the next setup records it. Nothing else may be missing.
2288
+ */
2289
+ export const KERNEL_STATE_NEW_PARTS: ReadonlySet<string> = new Set(["eventTriggers"])
2290
+
2291
+ /** What differs between two kernel security states: each object, by name, for an operator's message. */
2292
+ export const kernelStateDifferences = (expected: unknown, live: Record<string, unknown>): ReadonlyArray<string> => {
2293
+ const before = (expected ?? {}) as Record<string, unknown>
2294
+ const differences: Array<string> = []
2295
+ const label: Record<string, string> = {
2296
+ schemas: "schema",
2297
+ relations: "relation",
2298
+ columns: "column privileges of",
2299
+ routines: "routine",
2300
+ triggers: "trigger",
2301
+ eventTriggers: "event trigger",
2302
+ defaultPrivileges: "default privileges for",
2303
+ catalog: "catalogue function",
2304
+ roles: "role",
2305
+ }
2306
+ for (const key of Object.keys(label)) {
2307
+ // A part added after records of this format were written (`KERNEL_STATE_NEW_PARTS`) is not compared while a
2308
+ // record lacks it: this setup records it. A record that lacks any other part is malformed, and refused.
2309
+ if (!(key in before)) {
2310
+ if (!KERNEL_STATE_NEW_PARTS.has(key)) differences.push(`the recorded state has no ${key}`)
2311
+ continue
2312
+ }
2313
+ const name = (item: unknown) => {
2314
+ const o = item as Record<string, unknown>
2315
+ return key === "triggers"
2316
+ ? `trigger ${String(o["name"])} on ${String(o["on"])}`
2317
+ : `${label[key]} ${String(o["name"])}`
2318
+ }
2319
+ const was = new Map(
2320
+ ((before[key] ?? []) as ReadonlyArray<unknown>).map((item) => [name(item), canonicalJson(item)]),
2321
+ )
2322
+ const now = new Map(((live[key] ?? []) as ReadonlyArray<unknown>).map((item) => [name(item), canonicalJson(item)]))
2323
+ for (const [n, v] of now) if (was.get(n) !== v) differences.push(was.has(n) ? `${n} changed` : `${n} added`)
2324
+ for (const n of was.keys()) if (!now.has(n)) differences.push(`${n} removed`)
2325
+ }
2326
+ return differences
2327
+ }
2328
+
2329
+ /**
2330
+ * The kernel's recorded security state: `none` (no setup recorded one), `foreign` (in another format), or the
2331
+ * state. Readable by the kernel role; written only by setup's superuser.
2332
+ */
2333
+ export const recordedKernelState = (sql: SqlClient.SqlClient) =>
2334
+ Effect.gen(function* () {
2335
+ const [table] = yield* sql<{ present: boolean }>`
2336
+ SELECT pg_catalog.to_regclass('eloxiv_release.kernel_state') IS NOT NULL AS present`
2337
+ if (table?.present !== true) return { kind: "none" } as const
2338
+ const [row] = yield* sql<{ state: { format?: unknown; host?: HostProfile } }>`
2339
+ SELECT state FROM eloxiv_release.kernel_state`
2340
+ if (row === undefined) return { kind: "none" } as const
2341
+ if (row.state?.format !== KERNEL_STATE_FORMAT) return { kind: "foreign" } as const
2342
+ return { kind: "recorded", state: row.state, host: row.state.host } as const
2343
+ })
2344
+
2345
+ /**
2346
+ * Record the kernel's security state as setup leaves it (in setup's transaction, as the setup role), with the host's
2347
+ * profile (`host`): which of setup's protections it applied there. The next setup compares the host with it
2348
+ * (`hostDifferences`); `status`, which runs as the kernel role and cannot probe the host, compares the rest.
2349
+ */
2350
+ export const recordKernelState = (sql: SqlClient.SqlClient, host: HostProfile) =>
2351
+ Effect.gen(function* () {
2352
+ const state = { ...(yield* kernelSecurityState(sql)), host }
2353
+ yield* sql`INSERT INTO eloxiv_release.kernel_state (singleton, state, recorded_at)
2354
+ VALUES (true, ${JSON.stringify(state)}::jsonb, now())
2355
+ ON CONFLICT (singleton) DO UPDATE SET state = EXCLUDED.state, recorded_at = EXCLUDED.recorded_at`
2356
+ })
2357
+
2358
+ /**
2359
+ * The objects setup creates as the setup role and that act with its privileges or hold what only it may write: the
2360
+ * `SECURITY DEFINER` functions of `eloxiv_setup` that call zero-cache's (`announce_schema`, `announce_ddl`,
2361
+ * `zero_push`, `zero_push_status`, `zero_cleanup`), the event triggers on the kernel's functions, and the kernel's
2362
+ * recorded security state (`eloxiv_release` and its `kernel_state`). Each must be owned by a trusted owner
2363
+ * (`TRUSTED_OWNER`: a superuser or the setup role, `session_user` here); this returns those that are not, on
2364
+ * setup's session in the app's database, before setup changes anything. The kernel's recorded state then holds
2365
+ * their owners, so a later change is drift (`kernelSecurityState`).
2366
+ */
2367
+ export const untrustedSetupObjects = (sql: SqlClient.SqlClient) =>
2368
+ Effect.gen(function* () {
2369
+ const rows = yield* sql.unsafe<{ what: string; owner: string }>(`
2370
+ SELECT o.what, pg_catalog.pg_get_userbyid(o.owner) AS owner FROM (
2371
+ SELECT 'function ' || p.oid::pg_catalog.regprocedure::text AS what, p.proowner AS owner
2372
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2373
+ WHERE n.nspname = 'eloxiv_setup'
2374
+ AND p.proname IN ('announce_schema', 'announce_ddl', 'zero_push', 'zero_push_status', 'zero_cleanup')
2375
+ UNION ALL
2376
+ SELECT 'event trigger ' || e.evtname, e.evtowner
2377
+ FROM pg_catalog.pg_event_trigger e JOIN pg_catalog.pg_proc p ON p.oid = e.evtfoid
2378
+ JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ANY(${KERNEL_STATE_SCHEMA_ARRAY})
2379
+ UNION ALL
2380
+ SELECT 'schema eloxiv_release', n.nspowner FROM pg_catalog.pg_namespace n WHERE n.nspname = 'eloxiv_release'
2381
+ UNION ALL
2382
+ SELECT 'table eloxiv_release.kernel_state', c.relowner FROM pg_catalog.pg_class c
2383
+ WHERE c.oid = pg_catalog.to_regclass('eloxiv_release.kernel_state')
2384
+ ) o WHERE ${TRUSTED_OWNER("o.owner", "session_user")} IS NOT TRUE
2385
+ ORDER BY 1`)
2386
+ return rows.map((r) => `${r.what} is owned by ${r.owner}`)
2387
+ })
2388
+
2389
+ /** The kernel-managed published query views (`qv_*`) in a module schema. */
2390
+ export const dropQueryViews = (sql: SqlClient.SqlClient, schema: string) =>
2391
+ Effect.gen(function* () {
2392
+ const views = yield* sql<{ name: string }>`
2393
+ SELECT c.relname AS name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2394
+ WHERE n.nspname = ${schema} AND c.relkind = 'v' AND c.relname LIKE 'qv\\_%'`
2395
+ for (const { name } of views) yield* sql.unsafe(`DROP VIEW IF EXISTS ${ident(schema)}.${ident(name)}`)
2396
+ })
2397
+
2398
+ /**
2399
+ * A module's published query views (decision 6): `security_invoker` views owned by the module's owner role,
2400
+ * readable (SELECT only) by its runtime role, so the tables' row-level security applies to whoever reads them.
2401
+ * Registry checks have already refused SQL that is not a plain SELECT over the module's schema; here Postgres's
2402
+ * own record of what each view reads is checked as well: only tables of the module's schema, including the
2403
+ * entity whose policy filters its rows, only allowlisted side-effect-free built-in functions, operators,
2404
+ * coercions and types, resolved from the view's stored query tree (see `QueryViewCheck.ts`), and exactly the
2405
+ * declared columns. A view that fails stops setup.
2406
+ *
2407
+ * `mode` says what to do on `sql`:
2408
+ * - `"publish"` (setup's session, a module with no pending migration): create each view as the owner (`SET
2409
+ * LOCAL ROLE`; a view's text is one prepared statement, which only defines the view), check it, grant it;
2410
+ * - `"create"` (the module's owner session, after its migrations, in their transaction): create and check, so a
2411
+ * refused view fails the migrations' transaction; nothing is granted there;
2412
+ * - `"grant"` (setup's session, after the owner session committed): check again, on a connection no migration
2413
+ * touched, and grant.
2414
+ */
2415
+ export const publishModuleViews = (
2416
+ sql: SqlClient.SqlClient,
2417
+ module: AnyKernelModule,
2418
+ mode: "publish" | "create" | "grant",
2419
+ ) =>
2420
+ Effect.gen(function* () {
2421
+ const schema = module.schema
2422
+ yield* pinCatalogPath(sql)
2423
+ if (mode !== "grant") yield* dropQueryViews(sql, schema)
2424
+ for (const [id, declared] of Object.entries(module.contract.queryViews ?? {})) {
2425
+ const view = declared as QueryViewDeclaration
2426
+ const entity = (module.contract.entities as Record<string, AnyEntity>)[view.entity]!
2427
+ const name = queryViewName(id)
2428
+ const qualified = `${ident(schema)}.${ident(name)}`
2429
+ const refuse = (why: string) =>
2430
+ Effect.die(
2431
+ new UnsafeModuleSchema(module.contract.name, `Module ${module.contract.name}: query view ${id} ${why}`),
2432
+ )
2433
+ if (mode !== "grant") {
2434
+ // In a savepoint (as the owner): a failed CREATE rolls back to it (and out of the owner role).
2435
+ const created = yield* Effect.exit(
2436
+ sql.withTransaction(
2437
+ Effect.gen(function* () {
2438
+ if (mode === "publish") yield* sql.unsafe(`SET LOCAL ROLE ${ident(module.owner)}`)
2439
+ yield* sql.unsafe(
2440
+ `CREATE VIEW ${qualified} WITH (security_invoker = true) AS ${view.sql.trim().replace(/;\s*$/, "")}`,
2441
+ )
2442
+ if (mode === "publish") yield* sql.unsafe(`RESET ROLE`)
2443
+ }),
2444
+ ),
2445
+ )
2446
+ if (created._tag === "Failure") return yield* refuse(`cannot be created: ${Cause.pretty(created.cause)}`)
2447
+ }
2448
+ const [exists] = yield* sql<{ present: boolean }>`
2449
+ SELECT pg_catalog.to_regclass(${`${schema}.${name}`}) IS NOT NULL AS present`
2450
+ if (exists?.present !== true) return yield* refuse("was not created")
2451
+ const relations = yield* sql<{ schema: string; name: string }>`
2452
+ SELECT DISTINCT n.nspname AS schema, c.relname AS name
2453
+ FROM pg_catalog.pg_rewrite r
2454
+ JOIN pg_catalog.pg_depend d ON d.objid = r.oid AND d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.refclassid = 'pg_catalog.pg_class'::regclass
2455
+ JOIN pg_catalog.pg_class c ON c.oid = d.refobjid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2456
+ WHERE r.ev_class = ${`${schema}.${name}`}::regclass AND d.refobjid <> r.ev_class`
2457
+ const outside = relations.filter((r) => r.schema !== schema)
2458
+ if (outside.length > 0) {
2459
+ return yield* refuse(
2460
+ `reads ${outside.map((r) => `${r.schema}.${r.name}`).join(", ")}, outside schema ${schema}`,
2461
+ )
2462
+ }
2463
+ if (!relations.some((r) => r.name === entity.table.name)) {
2464
+ return yield* refuse(`does not read ${entity.table.schema}.${entity.table.name}, the table of ${entity.name}`)
2465
+ }
2466
+ // Dependencies on built-in catalog objects are not recorded; any recorded function is outside it.
2467
+ const functions = yield* sql<{ name: string }>`
2468
+ SELECT DISTINCT n.nspname || '.' || p.proname AS name
2469
+ FROM pg_catalog.pg_rewrite r
2470
+ JOIN pg_catalog.pg_depend d ON d.objid = r.oid AND d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.refclassid = 'pg_catalog.pg_proc'::regclass
2471
+ JOIN pg_catalog.pg_proc p ON p.oid = d.refobjid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
2472
+ WHERE r.ev_class = ${`${schema}.${name}`}::regclass`
2473
+ if (functions.length > 0) return yield* refuse(`calls ${functions.map((f) => f.name).join(", ")}`)
2474
+ // Built-in callables have no recorded dependency: resolve every function, operator, coercion and type from
2475
+ // the view's own query tree and accept only the allowlisted side-effect-free built-ins.
2476
+ const calls = yield* queryViewCallProblems(sql, `${schema}.${name}`, schema)
2477
+ if (calls.length > 0) return yield* refuse(calls.join("; "))
2478
+ const columns = (yield* sql<{ name: string }>`
2479
+ SELECT attname AS name FROM pg_catalog.pg_attribute
2480
+ WHERE attrelid = ${`${schema}.${name}`}::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`).map(
2481
+ (c) => c.name,
2482
+ )
2483
+ const fields = Object.keys(view.row.fields).sort()
2484
+ if (JSON.stringify([...columns].sort()) !== JSON.stringify(fields)) {
2485
+ return yield* refuse(`returns columns ${columns.join(", ")} but declares ${fields.join(", ")}`)
2486
+ }
2487
+ if (mode !== "create") {
2488
+ yield* sql.unsafe(`REVOKE ALL ON ${qualified} FROM PUBLIC, ${ident(module.role)}`)
2489
+ yield* sql.unsafe(`GRANT SELECT ON ${qualified} TO ${ident(module.role)}`)
2490
+ }
2491
+ }
2492
+ })
2493
+
2494
+ /**
2495
+ * The query surface's views of `module` (owned by its runtime role, reading its tables), dropped, so its
2496
+ * migrations can change those tables: on setup's session, before the module's owner session migrates it.
2497
+ * `publishSurfaceViews` creates them again in step 2. Returns whether any was dropped.
2498
+ */
2499
+ export const dropSurfaceViews = (sql: SqlClient.SqlClient, module: AnyKernelModule) =>
2500
+ Effect.gen(function* () {
2501
+ const views = yield* sql<{ name: string }>`
2502
+ SELECT c.relname AS name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2503
+ WHERE n.nspname = ${QUERY_SURFACE_SCHEMA} AND c.relkind = 'v'
2504
+ AND c.relowner = (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = ${module.role})`
2505
+ for (const { name } of views) yield* sql.unsafe(`DROP VIEW IF EXISTS ${ident(QUERY_SURFACE_SCHEMA)}.${ident(name)}`)
2506
+ return views.length > 0
2507
+ })
2508
+
2509
+ /**
2510
+ * In step 2's transaction, after the hardening: the query surface (QuerySurface). Schema `eloxiv_surface`, owned
2511
+ * by the superuser that runs setup, holds one view per published query view, named `<module>_<view>`, with the
2512
+ * view's own SQL. Each is owned by the module's runtime role and is not `security_invoker`, so reading it reads
2513
+ * the module's tables as the runtime role, under the row-level security that applies the entity's read policy
2514
+ * for the caller recorded in the transaction's invocation context; it is a security barrier, so a caller's
2515
+ * predicates cannot run before that filter. The read role `eloxiv_query` may use the schema and read these
2516
+ * views, and nothing else of the app: no module schema, no kernel table. Each view is checked like the module's
2517
+ * own (the same allowlist, its own schema's tables only). All of it is the kernel's security state
2518
+ * (`kernelSecurityState`), recorded after this.
2519
+ */
2520
+ export const publishSurfaceViews = (sql: SqlClient.SqlClient, modules: ReadonlyArray<AnyKernelModule>) =>
2521
+ Effect.gen(function* () {
2522
+ const [{ database } = { database: "" }] = yield* sql<{ database: string }>`
2523
+ SELECT pg_catalog.current_database() AS database`
2524
+ const surface = ident(QUERY_SURFACE_SCHEMA)
2525
+ yield* ensureOwnSchema(sql, QUERY_SURFACE_SCHEMA)
2526
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA ${surface} FROM PUBLIC`)
2527
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA ${surface} TO ${ident(QUERY_ROLE)}`)
2528
+ // Row-level security on the tables behind the views calls the invocation-context functions as the reader.
2529
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA eloxiv_ctx TO ${ident(QUERY_ROLE)}`)
2530
+ yield* sql.unsafe(`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA eloxiv_ctx TO ${ident(QUERY_ROLE)}`)
2531
+ yield* sql.unsafe(
2532
+ `REVOKE EXECUTE ON FUNCTION eloxiv_ctx.make_call_of(text), eloxiv_ctx.make_claim(text, text, text),
2533
+ eloxiv_ctx.make_finish(text, jsonb), eloxiv_ctx.make_consume(text), eloxiv_ctx.make_deliver(text)
2534
+ FROM ${ident(QUERY_ROLE)}`,
2535
+ )
2536
+ // Checking a query creates a temporary view of it (in a rolled-back transaction) to read Postgres's own tree.
2537
+ yield* sql.unsafe(`GRANT TEMPORARY ON DATABASE ${ident(database)} TO ${ident(QUERY_ROLE)}`)
2538
+ const existing = yield* sql<{ name: string }>`
2539
+ SELECT c.relname AS name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
2540
+ WHERE n.nspname = ${QUERY_SURFACE_SCHEMA} AND c.relkind = 'v'`
2541
+ for (const { name } of existing) yield* sql.unsafe(`DROP VIEW IF EXISTS ${surface}.${ident(name)}`)
2542
+ for (const module of modules) {
2543
+ for (const [id, declared] of Object.entries(module.contract.queryViews ?? {})) {
2544
+ const view = declared as QueryViewDeclaration
2545
+ const name = queryRelationName(id)
2546
+ const qualified = `${surface}.${ident(name)}`
2547
+ yield* sql.unsafe(
2548
+ `CREATE VIEW ${qualified} WITH (security_barrier = true) AS ${view.sql.trim().replace(/;\s*$/, "")}`,
2549
+ )
2550
+ const problems = yield* queryViewCallProblems(sql, `${QUERY_SURFACE_SCHEMA}.${name}`, module.schema)
2551
+ if (problems.length > 0) {
2552
+ return yield* Effect.die(
2553
+ new UnsafeModuleSchema(
2554
+ module.contract.name,
2555
+ `Module ${module.contract.name}: query view ${id} on the query surface ${problems.join("; ")}`,
2556
+ ),
2557
+ )
2558
+ }
2559
+ yield* giveTo(sql, QUERY_SURFACE_SCHEMA, module.role, `ALTER VIEW ${qualified} OWNER TO ${ident(module.role)}`)
2560
+ yield* sql.unsafe(`REVOKE ALL ON ${qualified} FROM PUBLIC, ${ident(module.role)}`)
2561
+ yield* sql.unsafe(`GRANT SELECT ON ${qualified} TO ${ident(QUERY_ROLE)}`)
2562
+ }
2563
+ }
2564
+ })
2565
+
2566
+ /**
2567
+ * Run `statement`, which gives an object in `schema` to `role` (`ALTER ... OWNER TO`). PostgreSQL lets anyone but a
2568
+ * superuser do that only while the new owner may create in the schema, so a setup role that is no superuser
2569
+ * (db/Host.ts) grants `role` CREATE there for the statement and revokes it after, in the same transaction: the
2570
+ * schema's privileges end as a superuser's setup leaves them.
2571
+ */
2572
+ const giveTo = (sql: SqlClient.SqlClient, schema: string, role: string, statement: string) =>
2573
+ Effect.gen(function* () {
2574
+ const [me] = yield* sql<{ super: boolean; creates: boolean }>`
2575
+ SELECT (SELECT rolsuper FROM pg_catalog.pg_roles WHERE rolname = current_user) AS super,
2576
+ pg_catalog.has_schema_privilege(${role}, ${schema}, 'CREATE') AS creates`
2577
+ if (me?.super === true || me?.creates === true) {
2578
+ yield* sql.unsafe(statement)
2579
+ return
2580
+ }
2581
+ yield* sql.unsafe(`GRANT CREATE ON SCHEMA ${ident(schema)} TO ${ident(role)}`)
2582
+ yield* sql.unsafe(statement)
2583
+ yield* sql.unsafe(`REVOKE CREATE ON SCHEMA ${ident(schema)} FROM ${ident(role)}`)
2584
+ })
2585
+
2586
+ /** The module tables the platform read functions read (`publishPlatformReads`), by the module's schema. */
2587
+ const PLATFORM_TABLES: Readonly<Record<string, string>> = {
2588
+ [SETTINGS_SCHEMA]: "value",
2589
+ [FLAGS_SCHEMA]: "rule",
2590
+ }
2591
+
2592
+ /**
2593
+ * Within a module's hardening (its views callback), before its security state is recorded: what the platform
2594
+ * read role may read of the `settings` and `flags` modules' tables (USAGE on the schema, SELECT on the table, and
2595
+ * a row-level security policy confined to the caller's organisation). It is part of the module's recorded state,
2596
+ * so a later setup holds it to exactly this. Nothing for other modules; no DDL when it is all in place.
2597
+ */
2598
+ export const platformTableAccess = (sql: SqlClient.SqlClient, module: AnyKernelModule) =>
2599
+ Effect.gen(function* () {
2600
+ const tableName = PLATFORM_TABLES[module.schema]
2601
+ if (tableName === undefined) return
2602
+ const role = ident(PLATFORM_READ_ROLE)
2603
+ const table = `${ident(module.schema)}.${ident(tableName)}`
2604
+ const [present] = yield* sql<{ usage: boolean; select: boolean; policy: boolean }>`
2605
+ SELECT pg_catalog.has_schema_privilege(${PLATFORM_READ_ROLE}, ${module.schema}, 'USAGE') AS usage,
2606
+ pg_catalog.has_table_privilege(${PLATFORM_READ_ROLE}, ${`${module.schema}.${tableName}`}, 'SELECT') AS "select",
2607
+ EXISTS (SELECT 1 FROM pg_catalog.pg_policies WHERE schemaname = ${module.schema} AND tablename = ${tableName}
2608
+ AND policyname = 'eloxiv_platform_read') AS policy`
2609
+ if (present?.usage !== true) yield* sql.unsafe(`GRANT USAGE ON SCHEMA ${ident(module.schema)} TO ${role}`)
2610
+ if (present?.select !== true) yield* sql.unsafe(`GRANT SELECT ON ${table} TO ${role}`)
2611
+ if (present?.policy !== true) {
2612
+ yield* sql.unsafe(
2613
+ `CREATE POLICY eloxiv_platform_read ON ${table} FOR SELECT TO ${role} USING (org_id = eloxiv_ctx.current_org())`,
2614
+ )
2615
+ }
2616
+ })
2617
+
2618
+ /**
2619
+ * In step 2's transaction, after the query surface: the platform read functions, in schema `eloxiv_platform`,
2620
+ * through which a handler (`ctx.settings`, `ctx.flags`) and the `settings` and `flags` modules' own actions read
2621
+ * what the caller's runtime role cannot, on the handler's own connection and transaction, without switching its
2622
+ * role (a role switch would also apply to the handler's concurrent statements). Each is SECURITY DEFINER, owned
2623
+ * by the dedicated role `eloxiv_platform_read`, with a fixed search path; it takes only the key it reads, refuses
2624
+ * a transaction with no invocation context, and returns only that key's values for the caller recorded in that
2625
+ * context (their organisation, them, their groups):
2626
+ *
2627
+ * - `deployment_setting(key)`: the `app` and `module` values a deployment administrator set;
2628
+ * - `stored_setting(key)`: the caller's own `user` value and their organisation's `org` value (with `settings`);
2629
+ * - `flag_rules(flag)`: the flag's rules that can apply to the caller, exactly those the `flags` read policy
2630
+ * admits (with `flags`).
2631
+ *
2632
+ * EXECUTE goes to the modules' runtime roles only (`kernelGrantRows` expects it). The owner role may read
2633
+ * `eloxiv.deployment_setting`, and the two module tables through `platformTableAccess`. The functions and their
2634
+ * privileges are the kernel's security state (`kernelSecurityState`), recorded after this.
2635
+ */
2636
+ export const publishPlatformReads = (sql: SqlClient.SqlClient, modules: ReadonlyArray<AnyKernelModule>) =>
2637
+ Effect.gen(function* () {
2638
+ const role = ident(PLATFORM_READ_ROLE)
2639
+ const schema = ident(PLATFORM_READ_SCHEMA)
2640
+ yield* ensureOwnSchema(sql, PLATFORM_READ_SCHEMA)
2641
+ yield* sql.unsafe(`REVOKE ALL ON SCHEMA ${schema} FROM PUBLIC`)
2642
+ // Recreated from scratch every setup, so no grant to a module that is no longer installed survives.
2643
+ for (const fn of [
2644
+ "deployment_setting",
2645
+ "stored_setting",
2646
+ "flag_rules",
2647
+ "record_version",
2648
+ "record_agent_versions",
2649
+ "revert_delete_write",
2650
+ "collab_state",
2651
+ ]) {
2652
+ yield* sql.unsafe(`DROP FUNCTION IF EXISTS ${schema}.${ident(fn)}(text)`)
2653
+ }
2654
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA eloxiv_ctx TO ${role}`)
2655
+ yield* sql.unsafe(
2656
+ `GRANT EXECUTE ON FUNCTION eloxiv_ctx.current_actor(), eloxiv_ctx.current_org(), eloxiv_ctx.current_action(), eloxiv_ctx.in_group(text) TO ${role}`,
2657
+ )
2658
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA eloxiv TO ${role}`)
2659
+ yield* sql.unsafe(`GRANT SELECT (key, level, value) ON eloxiv.deployment_setting TO ${role}`)
2660
+ const context = `
2661
+ v_org text := eloxiv_ctx.current_org();
2662
+ v_actor text := eloxiv_ctx.current_actor();
2663
+ BEGIN
2664
+ IF v_org IS NULL OR v_actor IS NULL THEN
2665
+ RAISE EXCEPTION 'eloxiv_platform: no invocation context' USING ERRCODE = 'insufficient_privilege';
2666
+ END IF;`
2667
+ const create = (name: string, returns: string, body: string) =>
2668
+ Effect.gen(function* () {
2669
+ yield* sql.unsafe(
2670
+ `CREATE FUNCTION ${schema}.${ident(name)}(p_key text) RETURNS TABLE (${returns})
2671
+ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $fn$
2672
+ #variable_conflict use_column
2673
+ DECLARE ${context}
2674
+ ${body}
2675
+ END $fn$`,
2676
+ )
2677
+ yield* giveTo(
2678
+ sql,
2679
+ PLATFORM_READ_SCHEMA,
2680
+ PLATFORM_READ_ROLE,
2681
+ `ALTER FUNCTION ${schema}.${ident(name)}(text) OWNER TO ${role}`,
2682
+ )
2683
+ yield* sql.unsafe(`REVOKE ALL ON FUNCTION ${schema}.${ident(name)}(text) FROM PUBLIC`)
2684
+ })
2685
+ const created = ["deployment_setting"]
2686
+ yield* create(
2687
+ "deployment_setting",
2688
+ "level text, value jsonb",
2689
+ `RETURN QUERY SELECT d.level, d.value FROM eloxiv.deployment_setting d WHERE d.key = p_key;`,
2690
+ )
2691
+ // A recorded version of one of the calling action's own module's records (the Versioning contract's
2692
+ // ctx.history.restore): `p_key` is `{"entity", "id", "version"}` (version 0: the latest), the entity must be
2693
+ // the acting module's (`<module>.<entity>`, from the invocation context's action), in the caller's organisation.
2694
+ yield* sql.unsafe(
2695
+ `GRANT SELECT (org_id, entity, record_id, version, op, snapshot) ON eloxiv.record_history TO ${role}`,
2696
+ )
2697
+ yield* create(
2698
+ "record_version",
2699
+ "snapshot jsonb, latest_op text",
2700
+ `IF split_part(p_key::jsonb ->> 'entity', '.', 1) <> split_part(eloxiv_ctx.current_action(), '.', 1) THEN
2701
+ RAISE EXCEPTION 'eloxiv_platform: another module''s history' USING ERRCODE = 'insufficient_privilege';
2702
+ END IF;
2703
+ RETURN QUERY SELECT
2704
+ (SELECT h.snapshot FROM eloxiv.record_history h
2705
+ WHERE h.org_id = v_org AND h.entity = p_key::jsonb ->> 'entity' AND h.record_id = p_key::jsonb ->> 'id'
2706
+ AND (h.version = (p_key::jsonb ->> 'version')::int OR ((p_key::jsonb ->> 'version')::int = 0 AND h.version = (
2707
+ SELECT max(l.version) FROM eloxiv.record_history l WHERE l.org_id = v_org
2708
+ AND l.entity = p_key::jsonb ->> 'entity' AND l.record_id = p_key::jsonb ->> 'id')))),
2709
+ (SELECT h.op FROM eloxiv.record_history h
2710
+ WHERE h.org_id = v_org AND h.entity = p_key::jsonb ->> 'entity' AND h.record_id = p_key::jsonb ->> 'id'
2711
+ ORDER BY h.version DESC LIMIT 1);`,
2712
+ )
2713
+ created.push("record_version")
2714
+ // Every recorded version of one of the calling action's own module's records, with who made it and the agent edit
2715
+ // group it belongs to (the Versioning contract's ctx.history.revert), and whether the record's collaborative
2716
+ // document has changes from outside the caller's group `{conversationId, messageId}` (updates the group's runs did
2717
+ // not make, other than reverts of the group): `p_key` is `{"entity", "id", "cedar", "conversationId", "messageId"}`,
2718
+ // under the same rule as record_version (the acting module's entity, the caller's organisation), and the Cedar type
2719
+ // must be of the acting module's namespace (which the invocation path records in the context).
2720
+ yield* sql.unsafe(
2721
+ `GRANT SELECT (actor_user_id, agent_conversation_id, agent_message_id, revert_conversation_id, revert_message_id)
2722
+ ON eloxiv.record_history TO ${role}`,
2723
+ )
2724
+ yield* sql.unsafe(
2725
+ `GRANT SELECT (document_id, reason, actor_user_id, agent_conversation_id, agent_message_id, updates, reverted_seq)
2726
+ ON eloxiv.collab_version TO ${role}`,
2727
+ )
2728
+ yield* create(
2729
+ "record_agent_versions",
2730
+ `version integer, op text, snapshot jsonb, actor_user_id text, agent_conversation_id text, agent_message_id text,
2731
+ revert_conversation_id text, revert_message_id text, document_outside boolean`,
2732
+ `IF split_part(p_key::jsonb ->> 'entity', '.', 1) <> split_part(eloxiv_ctx.current_action(), '.', 1)
2733
+ OR split_part(p_key::jsonb ->> 'cedar', '::', 1) IS DISTINCT FROM
2734
+ (SELECT c.namespace FROM eloxiv.invocation_context c WHERE c.xid = pg_current_xact_id()) THEN
2735
+ RAISE EXCEPTION 'eloxiv_platform: another module''s history' USING ERRCODE = 'insufficient_privilege';
2736
+ END IF;
2737
+ RETURN QUERY SELECT h.version, h.op, h.snapshot, h.actor_user_id, h.agent_conversation_id, h.agent_message_id,
2738
+ h.revert_conversation_id, h.revert_message_id,
2739
+ coalesce((SELECT d.head_seq - coalesce((SELECT sum(v.updates) + count(DISTINCT v.reverted_seq)
2740
+ FROM eloxiv.collab_version v
2741
+ WHERE v.document_id = d.id AND v.reason = 'agent' AND v.actor_user_id = v_actor
2742
+ AND v.agent_conversation_id = p_key::jsonb ->> 'conversationId'
2743
+ AND (p_key::jsonb ->> 'messageId' IS NULL OR v.agent_message_id = p_key::jsonb ->> 'messageId')), 0) > 0
2744
+ FROM eloxiv.collab_document d
2745
+ WHERE d.entity = p_key::jsonb ->> 'cedar' AND d.record_id = p_key::jsonb ->> 'id' AND d.org_id = v_org),
2746
+ false)
2747
+ FROM eloxiv.record_history h
2748
+ WHERE h.org_id = v_org AND h.entity = p_key::jsonb ->> 'entity' AND h.record_id = p_key::jsonb ->> 'id'
2749
+ ORDER BY h.version;`,
2750
+ )
2751
+ created.push("record_agent_versions")
2752
+ // The write-log entry of the latest DELETE of a row in the calling transaction (`p_key`: `{"schema", "table",
2753
+ // "pk"}`): what `ctx.history.revert` records of its own delete, so the invocation path accepts exactly that entry.
2754
+ // It reveals nothing but the caller's own transaction's writes (as `eloxiv_ctx.transaction_writes` does).
2755
+ yield* sql.unsafe(`GRANT SELECT (id, xid, table_schema, table_name, pk, op) ON eloxiv.invocation_write TO ${role}`)
2756
+ yield* create(
2757
+ "revert_delete_write",
2758
+ "id bigint",
2759
+ `RETURN QUERY SELECT max(w.id) FROM eloxiv.invocation_write w
2760
+ WHERE w.xid = pg_current_xact_id() AND w.op = 'DELETE' AND w.table_schema = p_key::jsonb ->> 'schema'
2761
+ AND w.table_name = p_key::jsonb ->> 'table' AND w.pk = p_key::jsonb ->> 'pk';`,
2762
+ )
2763
+ created.push("revert_delete_write")
2764
+ // A collaborative document's stored state for a live copy (CollabDocument, `ctx.collab.text`): only while a
2765
+ // module's subscriber is delivered (the context's action is the subscriber action), only for that module's own
2766
+ // entities (the Cedar namespace the dispatcher recorded), only in the context's organisation. STABLE, so it reads
2767
+ // the calling statement's snapshot: the caller checks the owning record in the same statement.
2768
+ yield* sql.unsafe(`GRANT SELECT (xid, action, subscriber, namespace) ON eloxiv.invocation_context TO ${role}`)
2769
+ yield* sql.unsafe(
2770
+ `GRANT SELECT (id, org_id, entity, record_id, snapshot, snapshot_seq, head_seq) ON eloxiv.collab_document TO ${role}`,
2771
+ )
2772
+ yield* sql.unsafe(`GRANT SELECT (document_id, seq, update) ON eloxiv.collab_update TO ${role}`)
2773
+ yield* create(
2774
+ "collab_state",
2775
+ "org_id text, snapshot bytea, snapshot_seq bigint, head_seq bigint, tail bytea[]",
2776
+ `IF eloxiv_ctx.current_action() IS DISTINCT FROM '${SUBSCRIBER_ACTION}'
2777
+ OR split_part(p_key::jsonb ->> 'entity', '::', 1) IS DISTINCT FROM
2778
+ (SELECT c.subscriber FROM eloxiv.invocation_context c WHERE c.xid = pg_current_xact_id()) THEN
2779
+ RAISE EXCEPTION 'eloxiv_platform: another module''s document' USING ERRCODE = 'insufficient_privilege';
2780
+ END IF;
2781
+ RETURN QUERY SELECT d.org_id, d.snapshot, d.snapshot_seq, d.head_seq,
2782
+ coalesce((SELECT array_agg(u.update ORDER BY u.seq) FROM eloxiv.collab_update u
2783
+ WHERE u.document_id = d.id AND u.seq > d.snapshot_seq AND u.seq <= d.head_seq), '{}')
2784
+ FROM eloxiv.collab_document d
2785
+ WHERE d.entity = p_key::jsonb ->> 'entity' AND d.record_id = p_key::jsonb ->> 'id' AND d.org_id = v_org;`,
2786
+ )
2787
+ created.push("collab_state")
2788
+ const installed = new Set(modules.map((m) => m.schema))
2789
+ if (installed.has(SETTINGS_SCHEMA)) {
2790
+ yield* create(
2791
+ "stored_setting",
2792
+ "level text, value jsonb",
2793
+ `RETURN QUERY SELECT s.level, s.value FROM ${ident(SETTINGS_SCHEMA)}."value" s
2794
+ WHERE s.key = p_key AND s.org_id = v_org AND s.value IS NOT NULL
2795
+ AND (s.level = 'org' OR (s.level = 'user' AND s.user_id = v_actor));`,
2796
+ )
2797
+ created.push("stored_setting")
2798
+ }
2799
+ if (installed.has(FLAGS_SCHEMA)) {
2800
+ // The flags module's read policy (flags.read), for the caller in the organisation they act in.
2801
+ yield* create(
2802
+ "flag_rules",
2803
+ `id text, org_id text, flag text, kind text, subject text, enabled boolean, percentage double precision,
2804
+ updated_by text, updated_at timestamptz`,
2805
+ `RETURN QUERY SELECT r.id, r.org_id, r.flag, r.kind, r.subject, r.enabled, r.percentage, r.updated_by,
2806
+ r.updated_at
2807
+ FROM ${ident(FLAGS_SCHEMA)}."rule" r
2808
+ WHERE r.flag = p_key AND r.org_id = v_org
2809
+ AND (r.kind IN ('org', 'rollout', 'role')
2810
+ OR (r.kind = 'user' AND r.user_id = v_actor)
2811
+ OR (r.kind = 'group' AND eloxiv_ctx.in_group(r.group_id)));`,
2812
+ )
2813
+ created.push("flag_rules")
2814
+ }
2815
+ if (modules.length === 0) return
2816
+ const runtimes = modules.map((m) => ident(m.role)).join(", ")
2817
+ yield* sql.unsafe(`GRANT USAGE ON SCHEMA ${schema} TO ${runtimes}`)
2818
+ for (const name of created) {
2819
+ yield* sql.unsafe(`GRANT EXECUTE ON FUNCTION ${schema}.${ident(name)}(text) TO ${runtimes}`)
2820
+ }
2821
+ })
2822
+
2823
+ /**
2824
+ * How long a statement or transaction of the kernel waits for one of its pool's connections before it fails: no
2825
+ * call waits forever behind others (MAKE calls never hold one while they wait for anything else).
2826
+ */
2827
+ export const KERNEL_POOL_WAIT_MS = 30_000
2828
+
2829
+ export const PgLayer = (url: Redacted.Redacted) =>
2830
+ PgClient.layer({ url, maxConnections: 16, acquireTimeout: `${KERNEL_POOL_WAIT_MS} millis` }).pipe(
2831
+ Layer.provide(Reactivity.layer),
2832
+ )