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