@eloxiv/kernel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,1652 @@
1
+ /**
2
+ * Files (docs/contracts/files.md): file records owned by modules and attached to their records by reference. The
3
+ * bytes are in the deployment's StorageBackend under keys only the kernel makes; the metadata, attachment,
4
+ * lifecycle and every authorisation are here, in the kernel's tables.
5
+ *
6
+ * beginUpload limits (deployment, entity, declared type), the record's `attach` policy, and the quota
7
+ * reserved under the organisation's lock; the file row (`uploading`) and signed part URLs
8
+ * PUT part the kernel's route checks the URL's signature and the exact length, streams the part to the
9
+ * backend (a multipart upload, or one object for a single part) and records it: resumable
10
+ * completeUpload every part present at its size: the backend assembles them, the file is `processing`, and
11
+ * `files.uploaded` (same transaction) starts `eloxiv.file-finalize`
12
+ * finalize inspect (exact size, SHA-256, type sniffed from the bytes against the declared type and the
13
+ * entity's types), scan (the deployment's `FileScanner`), settle: `available` (its name indexed
14
+ * for Search, ingested when its entity asks), or `rejected` / `quarantined` with the bytes deleted
15
+ * read a file attached to a record is readable exactly when its record is (the entity's read policy,
16
+ * for the caller, now); a staged one by its uploader only
17
+ * delete by whoever may `attach` to its record (a staged one by its uploader); refused under a retention
18
+ * hold; the quota is released at once and the bytes purged after the retention period
19
+ * sweep abandoned uploads, staged files never attached, and deleted files' bytes
20
+ */
21
+ import {
22
+ ATTACH_ACTION,
23
+ FILES_ACTIONS,
24
+ FILES_MANAGE,
25
+ Forbidden,
26
+ InvalidInput,
27
+ StorageQuotaExceeded,
28
+ WorkflowFailed,
29
+ type Actor,
30
+ type AnyEntity,
31
+ type AuthorityRecord,
32
+ type BeginUpload,
33
+ type DownloadUrl,
34
+ type FileRecord,
35
+ type PartUrl,
36
+ type RecordRef,
37
+ type ScanResult,
38
+ type StorageUsage,
39
+ type TextPage,
40
+ type UploadPlan,
41
+ } from "@eloxiv/contracts"
42
+ import { Context, Duration, Effect, Layer, Option, Redacted, Schedule, Schema } from "effect"
43
+ import { SqlClient } from "effect/sql"
44
+ import { createHash } from "node:crypto"
45
+ import { fromBase64url, toBase64url } from "../Base64url.ts"
46
+ import { filesConfig, KernelConfig, type FilesConfig } from "../Config.ts"
47
+ import { Authority } from "../Authority.ts"
48
+ import { defineKernelWorkflow } from "../durable/Trust.ts"
49
+ import { Identity, type HeldCredential } from "../Identity.ts"
50
+ import { asSystem } from "../inbox/System.ts"
51
+ import { scopeAllows } from "../machine/Tokens.ts"
52
+ import { Ingestion, type IngestionShape } from "../ingestion/Ingestion.ts"
53
+ import { Outbox, type ReactionEvent } from "../Outbox.ts"
54
+ import { Policy } from "../policy/Policy.ts"
55
+ import { recordAccess } from "../records/Access.ts"
56
+ import { Registry, type RegistryShape } from "../Registry.ts"
57
+ import { scrubIngested } from "../ingestion/Scrub.ts"
58
+ import { lockRecord, recordLockKey } from "../search/RecordLock.ts"
59
+ import type { WorkflowsShape } from "../Workflows.ts"
60
+ import { accepts, baseType, decideType, INLINE_TYPES, isActive, sniff, SNIFF_BYTES } from "./Sniff.ts"
61
+ import { getBytes, readAll, StorageBackend, type StorageBackendShape } from "./Storage.ts"
62
+ import { fileKeyOf, PROVIDER_KEYS, StorageProviders } from "./Providers.ts"
63
+
64
+ export { FILES_MODULE } from "./FileTable.ts"
65
+ import { FILES_MODULE } from "./FileTable.ts"
66
+ export const FILE_FINALIZE_WORKFLOW = "eloxiv.file-finalize"
67
+ export const FILE_UPLOAD_PATH = "/files/upload"
68
+ export const FILE_DOWNLOAD_PATH = "/files/download"
69
+
70
+ /** The virus-scan hook (the contract's `scan`): a deployment's scanner, called once per completed upload. */
71
+ export interface FileScanner {
72
+ readonly scan: (file: {
73
+ readonly fileId: string
74
+ readonly orgId: string
75
+ readonly contentType: string
76
+ readonly size: number
77
+ /** The file's bytes, as a stream to read (or cancel). */
78
+ readonly read: () => Effect.Effect<ReadableStream<Uint8Array>, unknown>
79
+ }) => Effect.Effect<ScanResult, unknown>
80
+ }
81
+
82
+ /** The deployment's scanner, if it has one (`KernelOptions.fileScanner`). */
83
+ export class FileScanners extends Context.Service<FileScanners, { readonly scanner: FileScanner | undefined }>()(
84
+ "@eloxiv/kernel/FileScanners",
85
+ ) {}
86
+
87
+ /** What a handler sees (`ctx.files`): its caller's view of files, in its transaction. */
88
+ export interface FilesApi {
89
+ /** Attach a staged file the caller uploaded to a record of this module the caller may `attach` to. */
90
+ readonly attach: (fileId: string, to: RecordRef) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
91
+ /** The files of a record the caller may read. */
92
+ readonly list: (record: RecordRef) => Effect.Effect<ReadonlyArray<FileRecord>, Forbidden | InvalidInput>
93
+ }
94
+
95
+ export interface FilesShape {
96
+ readonly beginUpload: (actor: Actor, input: BeginUpload) => Effect.Effect<UploadPlan, Forbidden | InvalidInput>
97
+ readonly resumeUpload: (actor: Actor, fileId: string) => Effect.Effect<UploadPlan, Forbidden | InvalidInput>
98
+ /**
99
+ * Complete an upload as `actor`; `authority` is the call's, bound for the finalisation that follows
100
+ * (`bindDeferred(ctx.authority, "once")`), which asserts it again before it makes the file visible.
101
+ */
102
+ readonly completeUpload: (
103
+ actor: Actor,
104
+ fileId: string,
105
+ invocationId: string,
106
+ authority: AuthorityRecord,
107
+ ) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
108
+ readonly abortUpload: (actor: Actor, fileId: string) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
109
+ readonly attach: (
110
+ actor: Actor,
111
+ fileId: string,
112
+ to: RecordRef,
113
+ invocationId: string,
114
+ ) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
115
+ readonly get: (actor: Actor, fileId: string) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
116
+ readonly list: (
117
+ actor: Actor,
118
+ record: RecordRef,
119
+ ) => Effect.Effect<{ readonly files: ReadonlyArray<FileRecord> }, Forbidden | InvalidInput>
120
+ readonly download: (
121
+ actor: Actor,
122
+ input: { readonly fileId: string; readonly disposition?: "attachment" | "inline" | undefined },
123
+ /** The credential of the call (when there was one): the URL works only while it does, within its scope. */
124
+ held?: HeldCredential,
125
+ ) => Effect.Effect<DownloadUrl, Forbidden | InvalidInput>
126
+ readonly read: (
127
+ actor: Actor,
128
+ input: { readonly fileId: string; readonly offset?: number | undefined; readonly limit?: number | undefined },
129
+ ) => Effect.Effect<TextPage, Forbidden | InvalidInput>
130
+ readonly delete: (
131
+ actor: Actor,
132
+ fileId: string,
133
+ invocationId: string,
134
+ ) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
135
+ readonly retain: (
136
+ actor: Actor,
137
+ fileId: string,
138
+ until: string | null,
139
+ ) => Effect.Effect<FileRecord, Forbidden | InvalidInput>
140
+ readonly usage: (actor: Actor) => Effect.Effect<StorageUsage>
141
+ readonly setQuota: (actor: Actor, limitBytes: number | null) => Effect.Effect<StorageUsage, Forbidden>
142
+ /** Metering's storage part: admit `bytes` more in the organisation, under its lock (in the caller's transaction). */
143
+ readonly reserve: (orgId: string, bytes: number) => Effect.Effect<StorageUsage, StorageQuotaExceeded>
144
+ /** The upload route: a part's bytes for a signed part URL. */
145
+ readonly receivePart: (
146
+ token: string,
147
+ declaredLength: number | undefined,
148
+ read: (maxBytes: number) => Effect.Effect<Uint8Array | { readonly refused: number; readonly message: string }>,
149
+ ) => Effect.Effect<{ readonly status: number; readonly body: Record<string, unknown> }>
150
+ /** The download route: the bytes for a signed download URL, with the headers they are served with. */
151
+ readonly openDownload: (
152
+ token: string,
153
+ ) => Effect.Effect<
154
+ | { readonly status: 200; readonly headers: Record<string, string>; readonly body: ReadableStream<Uint8Array> }
155
+ | { readonly status: number; readonly body: Record<string, unknown> }
156
+ >
157
+ /** `ctx.files` for a handler of `module` running as `role`. */
158
+ readonly forHandler: (actor: Actor, module: string, role: string | undefined, invocationId: string) => FilesApi
159
+ /**
160
+ * Finalisation's check, in its transaction under the record's lock: the uploader may still `attach` to the record,
161
+ * with their membership and permissions read now. The record's sharing grants are locked (`FOR SHARE`) first, so a
162
+ * revocation either committed before the check (and is seen) or waits until the file is settled.
163
+ */
164
+ readonly mayStillAttach: (userId: string, orgId: string, record: RecordRef) => Effect.Effect<boolean>
165
+ /** Expire abandoned uploads and staged files, purge deleted and refused files' bytes. */
166
+ readonly sweep: Effect.Effect<{ readonly expired: number; readonly purged: number }>
167
+ }
168
+
169
+ export class Files extends Context.Service<Files, FilesShape>()("@eloxiv/kernel/Files") {}
170
+
171
+ interface FileRow {
172
+ readonly id: string
173
+ readonly orgId: string
174
+ readonly ownerType: string | null
175
+ readonly ownerId: string | null
176
+ readonly name: string
177
+ readonly declaredType: string
178
+ readonly contentType: string | null
179
+ readonly size: string | number
180
+ readonly sha256: string | null
181
+ readonly state: FileRecord["state"]
182
+ readonly stateReason: string | null
183
+ readonly scan: FileRecord["scan"]
184
+ readonly storageKey: string
185
+ readonly uploadId: string | null
186
+ readonly partSize: number
187
+ readonly parts: number
188
+ readonly uploadedBy: string
189
+ readonly createdAt: Date
190
+ readonly completedAt: Date | null
191
+ readonly expiresAt: Date | null
192
+ readonly deletedAt: Date | null
193
+ readonly retainUntil: Date | null
194
+ /** The generation of the record it was attached to when the upload began (null: attached otherwise). */
195
+ readonly recordGeneration?: string | null
196
+ }
197
+
198
+ const COLUMNS = `id, org_id AS "orgId", owner_type AS "ownerType", owner_id AS "ownerId", name, declared_type AS "declaredType",
199
+ content_type AS "contentType", size, sha256, state, state_reason AS "stateReason", scan, storage_key AS "storageKey",
200
+ upload_id AS "uploadId", part_size AS "partSize", parts, uploaded_by AS "uploadedBy", created_at AS "createdAt",
201
+ completed_at AS "completedAt", expires_at AS "expiresAt", deleted_at AS "deletedAt", retain_until AS "retainUntil"`
202
+
203
+ const iso = (date: Date | string | null) => (date === null ? null : new Date(date).toISOString())
204
+
205
+ export const recordOf = (row: FileRow): FileRecord => ({
206
+ id: row.id,
207
+ orgId: row.orgId,
208
+ name: row.name,
209
+ declaredType: row.declaredType,
210
+ contentType: row.contentType,
211
+ size: Number(row.size),
212
+ sha256: row.sha256,
213
+ state: row.state,
214
+ stateReason: row.stateReason,
215
+ scan: row.scan,
216
+ attachedTo: row.ownerType === null || row.ownerId === null ? null : { entity: row.ownerType, id: row.ownerId },
217
+ uploadedBy: row.uploadedBy,
218
+ createdAt: iso(row.createdAt)!,
219
+ completedAt: iso(row.completedAt),
220
+ deletedAt: iso(row.deletedAt),
221
+ retainUntil: iso(row.retainUntil),
222
+ })
223
+
224
+ /** The storage key of a file: `files/<organisation, hex>/<file id>`, never anything a caller chose. */
225
+ const storageKeyOf = (orgId: string, fileId: string) =>
226
+ `files/${[...new TextEncoder().encode(orgId)].map((b) => b.toString(16).padStart(2, "0")).join("")}/${fileId}`
227
+
228
+ /** A file name as stored: no path, no control characters, at most 255 characters. */
229
+ const cleanName = (name: string) =>
230
+ name
231
+ .replace(/\p{Cc}/gu, "")
232
+ .split(/[/\\]/u)
233
+ .pop()!
234
+ .trim()
235
+ .slice(0, 255)
236
+
237
+ const MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/u
238
+
239
+ /** `Content-Disposition` with an ASCII fallback and the UTF-8 name (RFC 6266, RFC 5987). */
240
+ const dispositionOf = (kind: "attachment" | "inline", name: string) => {
241
+ const fallback = name.replace(/[^\x20-\x7e]|["\\]/gu, "_")
242
+ return `${kind}; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name)}`
243
+ }
244
+
245
+ /** The organisation's lock for quota reservations (an advisory transaction lock). */
246
+ const quotaLock = (orgId: string) => `eloxiv.storage:${orgId}`
247
+
248
+ /** A part URL: one part of one upload, of one size, used once (its nonce is claimed before any byte is stored). */
249
+ interface UploadToken {
250
+ readonly k: "up"
251
+ readonly f: string
252
+ readonly p: number
253
+ readonly s: number
254
+ readonly e: number
255
+ readonly n: string
256
+ }
257
+ /**
258
+ * A download URL: one file, for the person it was issued to and the credential they used (its kind, id and
259
+ * session), both checked again when it is used.
260
+ */
261
+ interface DownloadToken {
262
+ readonly k: "down"
263
+ readonly f: string
264
+ readonly d: "attachment" | "inline"
265
+ readonly e: number
266
+ readonly u: string
267
+ readonly o: string
268
+ readonly c: readonly [HeldCredential["kind"], string | null, string | null]
269
+ }
270
+
271
+ export const FilesLayer = Layer.effect(
272
+ Files,
273
+ Effect.gen(function* () {
274
+ const sql = yield* SqlClient.SqlClient
275
+ const registry = yield* Registry
276
+ const policy = yield* Policy
277
+ const outbox = yield* Outbox
278
+ const storage = yield* StorageBackend
279
+ const providers = yield* Effect.serviceOption(StorageProviders)
280
+ const ingestion = yield* Ingestion
281
+ const kernelConfig = yield* KernelConfig
282
+ const identity = yield* Identity
283
+ const config: FilesConfig = filesConfig(kernelConfig)
284
+ const baseUrl = kernelConfig.baseUrl.replace(/\/$/u, "")
285
+ const signingKey = yield* Effect.promise(async () => {
286
+ const secret = await crypto.subtle.importKey(
287
+ "raw",
288
+ new TextEncoder().encode(Redacted.value(kernelConfig.authSecret)),
289
+ { name: "HMAC", hash: "SHA-256" },
290
+ false,
291
+ ["sign"],
292
+ )
293
+ const derived = await crypto.subtle.sign("HMAC", secret, new TextEncoder().encode("eloxiv.files.urls.v1"))
294
+ return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"])
295
+ })
296
+
297
+ const sign = (payload: UploadToken | DownloadToken) =>
298
+ Effect.promise(async () => {
299
+ const body = toBase64url(new TextEncoder().encode(JSON.stringify(payload)))
300
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", signingKey, new TextEncoder().encode(body)))
301
+ return `${body}.${toBase64url(mac)}`
302
+ })
303
+
304
+ /** A token is its exact text: both halves decode strictly (one spelling only), then the signature verifies. */
305
+ const verify = <T extends UploadToken | DownloadToken>(token: string, kind: T["k"]) =>
306
+ Effect.promise(async (): Promise<T | undefined> => {
307
+ const [body, mac] = token.split(".")
308
+ if (body === undefined || mac === undefined || token.split(".").length !== 2) return undefined
309
+ const macBytes = fromBase64url(mac)
310
+ const bodyBytes = fromBase64url(body)
311
+ if (macBytes === undefined || bodyBytes === undefined) return undefined
312
+ let ok = false
313
+ try {
314
+ ok = await crypto.subtle.verify("HMAC", signingKey, macBytes, new TextEncoder().encode(body))
315
+ } catch {
316
+ return undefined
317
+ }
318
+ if (!ok) return undefined
319
+ try {
320
+ const payload = JSON.parse(new TextDecoder().decode(bodyBytes)) as T
321
+ if (payload.k !== kind || typeof payload.e !== "number" || payload.e * 1000 < Date.now()) return undefined
322
+ return payload
323
+ } catch {
324
+ return undefined
325
+ }
326
+ })
327
+
328
+ const forbidden = (action: string, message: string) => new Forbidden({ action, message })
329
+ const notReadable = (action: string) => forbidden(action, "No such file, or you may not read it")
330
+
331
+ const row = (fileId: string, orgId: string, lock = false) =>
332
+ sql
333
+ .unsafe<FileRow>(
334
+ `SELECT ${COLUMNS} FROM eloxiv.file WHERE id = $1 AND org_id = $2${lock ? " FOR UPDATE" : ""}`,
335
+ [fileId, orgId],
336
+ )
337
+ .pipe(
338
+ Effect.map((rows) => rows[0]),
339
+ Effect.orDie,
340
+ )
341
+
342
+ /**
343
+ * A file's row locked for a change, in the order every index writer takes its locks (`RecordLock.ts`): the
344
+ * record it is attached to (and `extra`, a record it is being attached to) first, then the row.
345
+ */
346
+ const lockedRow = (fileId: string, orgId: string, extra?: { readonly type: string; readonly id: string }) =>
347
+ lockRecordsThenRow(sql, (forUpdate) => row(fileId, orgId, forUpdate), extra === undefined ? [] : [extra])
348
+
349
+ const access = recordAccess(sql, registry, policy)
350
+
351
+ /** The entity a file may be attached to: registered, and declaring `files`. */
352
+ const filesEntity = (cedarType: string) => {
353
+ const registered = registry.entities.get(cedarType)
354
+ return registered?.entity.files === undefined
355
+ ? Effect.fail(new InvalidInput({ message: `${cedarType} is not an entity that accepts files` }))
356
+ : Effect.succeed(
357
+ registered as {
358
+ readonly entity: AnyEntity & { readonly files: NonNullable<AnyEntity["files"]> }
359
+ readonly module: typeof registered.module
360
+ },
361
+ )
362
+ }
363
+
364
+ /** May the actor read this file, now? Its record's read policy; a staged file, its uploader. */
365
+ const mayRead = (actor: Actor, file: FileRow) =>
366
+ file.ownerType === null || file.ownerId === null
367
+ ? Effect.succeed(file.uploadedBy === actor.userId)
368
+ : access
369
+ .permitted(actor, file.ownerType, [file.ownerId], "read")
370
+ .pipe(Effect.map((ids) => ids.has(file.ownerId!)))
371
+
372
+ const readable = (actor: Actor, fileId: string, action: string) =>
373
+ Effect.gen(function* () {
374
+ const file = yield* row(fileId, actor.orgId)
375
+ if (file === undefined || !(yield* mayRead(actor, file))) return yield* notReadable(action)
376
+ return file
377
+ })
378
+
379
+ const usageOf = (orgId: string) =>
380
+ Effect.gen(function* () {
381
+ const [used] = yield* sql<{ used: string }>`
382
+ SELECT coalesce(sum(size), 0)::text AS used FROM eloxiv.file
383
+ WHERE org_id = ${orgId} AND state IN ('uploading', 'processing', 'available')`
384
+ const [quota] = yield* sql<{ limit: string | null }>`
385
+ SELECT limit_bytes::text AS "limit" FROM eloxiv.storage_quota WHERE org_id = ${orgId}`
386
+ const limit = quota?.limit ?? null
387
+ return {
388
+ orgId,
389
+ usedBytes: Number(used?.used ?? 0),
390
+ limitBytes: limit === null ? config.defaultQuotaBytes : Number(limit),
391
+ } satisfies StorageUsage
392
+ }).pipe(Effect.orDie)
393
+
394
+ const reserve: FilesShape["reserve"] = (orgId, bytes) =>
395
+ Effect.gen(function* () {
396
+ // Concurrent reservations of one organisation queue here, so each sees the others' files.
397
+ yield* sql`SELECT pg_advisory_xact_lock(hashtextextended(${quotaLock(orgId)}, 0))`.pipe(Effect.orDie)
398
+ const usage = yield* usageOf(orgId)
399
+ if (usage.limitBytes !== null && usage.usedBytes + bytes > usage.limitBytes) {
400
+ return yield* new StorageQuotaExceeded({
401
+ message: `The organisation's storage quota is ${usage.limitBytes} bytes; ${usage.usedBytes} are used and this needs ${bytes} more`,
402
+ orgId,
403
+ limitBytes: usage.limitBytes,
404
+ usedBytes: usage.usedBytes,
405
+ requestedBytes: bytes,
406
+ })
407
+ }
408
+ return usage
409
+ })
410
+
411
+ /**
412
+ * An upload's recorded parts and its part URLs' claims, once it is no longer open: a claim only has to outlive
413
+ * the upload's `uploading` state (a claim is refused for an upload in any other state).
414
+ */
415
+ const forgetParts = (fileId: string) =>
416
+ Effect.all([
417
+ sql`DELETE FROM eloxiv.file_part WHERE file_id = ${fileId}`,
418
+ sql`DELETE FROM eloxiv.file_part_claim WHERE file_id = ${fileId}`,
419
+ ]).pipe(Effect.asVoid, Effect.orDie)
420
+
421
+ const partSizeOf = (file: Pick<FileRow, "size" | "partSize" | "parts">, part: number) =>
422
+ part < file.parts ? file.partSize : Number(file.size) - (file.parts - 1) * file.partSize
423
+
424
+ const planOf = (file: FileRow) =>
425
+ Effect.gen(function* () {
426
+ const received = (yield* sql<{ part: number }>`
427
+ SELECT part_number AS part FROM eloxiv.file_part WHERE file_id = ${file.id} ORDER BY part_number`.pipe(
428
+ Effect.orDie,
429
+ )).map((r) => r.part)
430
+ const expires = Math.min(
431
+ Math.floor(Date.now() / 1000) + config.uploadUrlTtlS,
432
+ Math.floor(new Date(file.expiresAt ?? Date.now()).getTime() / 1000),
433
+ )
434
+ const parts: Array<PartUrl> = []
435
+ for (let part = 1; part <= file.parts; part++) {
436
+ if (received.includes(part)) continue
437
+ const size = partSizeOf(file, part)
438
+ const token = yield* sign({ k: "up", f: file.id, p: part, s: size, e: expires, n: crypto.randomUUID() })
439
+ parts.push({
440
+ partNumber: part,
441
+ size,
442
+ url: `${baseUrl}${FILE_UPLOAD_PATH}?token=${token}`,
443
+ headers: { "content-length": String(size) },
444
+ })
445
+ }
446
+ return {
447
+ fileId: file.id,
448
+ partSize: file.partSize,
449
+ parts,
450
+ received,
451
+ urlsExpireAt: new Date(expires * 1000).toISOString(),
452
+ uploadExpiresAt: iso(file.expiresAt)!,
453
+ } satisfies UploadPlan
454
+ })
455
+
456
+ const beginUpload: FilesShape["beginUpload"] = (actor, input) =>
457
+ Effect.gen(function* () {
458
+ const action = "files.beginUpload"
459
+ const name = cleanName(input.name)
460
+ if (name === "") return yield* new InvalidInput({ message: "The file needs a name" })
461
+ const declared = baseType(input.contentType)
462
+ if (!MEDIA_TYPE.test(declared))
463
+ return yield* new InvalidInput({ message: `${input.contentType} is not a media type` })
464
+ let limit = config.maxBytes
465
+ let types: ReadonlyArray<string> | undefined
466
+ let generation: string | null = null
467
+ if (input.attachTo !== undefined) {
468
+ const { entity } = yield* filesEntity(input.attachTo.entity)
469
+ limit = Math.min(limit, entity.files.maxBytes ?? limit)
470
+ types = entity.files.types
471
+ // The record's lock before it is looked for (`RecordLock.ts`): a deletion under way finishes first, and the
472
+ // record is then gone, so no file is staged for a record being deleted.
473
+ yield* lockRecord(sql, { type: input.attachTo.entity, id: input.attachTo.id }).pipe(Effect.orDie)
474
+ const org = yield* access.organisationIf(actor, input.attachTo.entity, input.attachTo.id, ATTACH_ACTION)
475
+ if (org === undefined) return yield* forbidden(action, "No such record, or you may not attach files to it")
476
+ // The record's generation now: finalisation makes the file visible only if it has not moved since.
477
+ generation = yield* generationOf(sql, { type: input.attachTo.entity, id: input.attachTo.id })
478
+ }
479
+ if (input.size > limit) {
480
+ return yield* new InvalidInput({
481
+ message: `The file is ${input.size} bytes; at most ${limit} are accepted here`,
482
+ })
483
+ }
484
+ if (!accepts(types, declared)) {
485
+ return yield* new InvalidInput({ message: `Files of type ${declared} are not accepted here` })
486
+ }
487
+ const parts = Math.max(1, Math.ceil(input.size / config.partBytes))
488
+ if (parts > 1 && !storage.capabilities.multipart) {
489
+ return yield* new InvalidInput({
490
+ message: `The storage backend takes files of at most ${config.partBytes} bytes`,
491
+ })
492
+ }
493
+ yield* reserve(actor.orgId, input.size).pipe(
494
+ Effect.catchTag("StorageQuotaExceeded", (e) => Effect.fail(forbidden(action, e.message))),
495
+ )
496
+ const id = crypto.randomUUID()
497
+ // Where its bytes go, for good: the uploader's own store, else their organisation's, else the deployment's.
498
+ // An upload for a record is the organisation's: never in one member's own store.
499
+ const provider = Option.isSome(providers)
500
+ ? yield* providers.value.choose(actor, input.attachTo !== undefined)
501
+ : null
502
+ const key =
503
+ provider === null
504
+ ? storageKeyOf(actor.orgId, id)
505
+ : `${PROVIDER_KEYS}${provider}/${storageKeyOf(actor.orgId, id)}`
506
+ yield* sql`INSERT INTO eloxiv.file (id, org_id, owner_type, owner_id, name, declared_type, size, state, storage_key,
507
+ part_size, parts, uploaded_by, expires_at, record_generation)
508
+ VALUES (${id}, ${actor.orgId}, ${input.attachTo?.entity ?? null}, ${input.attachTo?.id ?? null}, ${name},
509
+ ${declared}, ${input.size}, 'uploading', ${key}, ${config.partBytes}, ${parts},
510
+ ${actor.userId}, now() + make_interval(secs => ${config.uploadTtlMs / 1000}), ${generation}::bigint)`.pipe(
511
+ Effect.orDie,
512
+ )
513
+ return yield* planOf((yield* row(id, actor.orgId))!)
514
+ })
515
+
516
+ /** The actor's own upload in progress (or `forbidden`). */
517
+ const ownUpload = (actor: Actor, fileId: string, action: string, lock: boolean) =>
518
+ Effect.gen(function* () {
519
+ const file = yield* row(fileId, actor.orgId, lock)
520
+ if (file === undefined || file.uploadedBy !== actor.userId)
521
+ return yield* forbidden(action, "No such upload of yours")
522
+ return file
523
+ })
524
+
525
+ const resumeUpload: FilesShape["resumeUpload"] = (actor, fileId) =>
526
+ Effect.gen(function* () {
527
+ const file = yield* ownUpload(actor, fileId, "files.resumeUpload", false)
528
+ if (file.state !== "uploading" || new Date(file.expiresAt ?? 0).getTime() <= Date.now()) {
529
+ return yield* new InvalidInput({
530
+ message: `The upload is ${file.state === "uploading" ? "expired" : file.state}`,
531
+ })
532
+ }
533
+ return yield* planOf(file)
534
+ })
535
+
536
+ const completeUpload: FilesShape["completeUpload"] = (actor, fileId, invocationId, authority) =>
537
+ Effect.gen(function* () {
538
+ const file = yield* ownUpload(actor, fileId, "files.completeUpload", true)
539
+ if (file.state !== "uploading") {
540
+ if (file.state === "deleted") return yield* new InvalidInput({ message: "The upload was abandoned" })
541
+ return recordOf(file)
542
+ }
543
+ if (new Date(file.expiresAt ?? 0).getTime() <= Date.now()) {
544
+ return yield* new InvalidInput({ message: "The upload expired" })
545
+ }
546
+ const parts = yield* sql<{ part: number; size: string; etag: string; staged: string | null }>`
547
+ SELECT part_number AS part, size::text AS size, etag, staged_key AS staged FROM eloxiv.file_part
548
+ WHERE file_id = ${fileId} ORDER BY part_number`.pipe(Effect.orDie)
549
+ const missing: Array<number> = []
550
+ for (let part = 1; part <= file.parts; part++) {
551
+ const got = parts.find((p) => p.part === part)
552
+ if (got === undefined || Number(got.size) !== partSizeOf(file, part)) missing.push(part)
553
+ }
554
+ if (missing.length > 0) {
555
+ return yield* new InvalidInput({ message: `Parts not received yet: ${missing.join(", ")}` })
556
+ }
557
+ // The object the file is from now on: written once, here, under the file's lock, and never again (part
558
+ // URLs write only their own staged keys or the multipart upload, which completing ends).
559
+ if (file.parts === 1) {
560
+ const staged = parts[0]!.staged
561
+ if (staged === null) return yield* new InvalidInput({ message: "Parts not received yet: 1" })
562
+ yield* sql`UPDATE eloxiv.file SET storage_key = ${staged} WHERE id = ${fileId}`.pipe(Effect.orDie)
563
+ } else {
564
+ // The parts the store holds, as it holds them: a part sent twice (over a URL from the plan and one from a
565
+ // resumed plan) is whichever the store kept, whatever order the two were recorded in here. Each must be
566
+ // there, at its exact size; the content is checked whole when the file is finalized.
567
+ const refusedBy = (e: { readonly message: string }) =>
568
+ new InvalidInput({ message: `The storage backend refused the upload: ${e.message}` })
569
+ const held = yield* storage.listParts(file.storageKey, file.uploadId ?? "").pipe(
570
+ Effect.map((list) => new Map(list.map((p) => [p.partNumber, p]))),
571
+ Effect.catchTag("StorageNotFound", () => Effect.succeed(undefined)),
572
+ Effect.mapError(refusedBy),
573
+ )
574
+ if (held === undefined) {
575
+ // Completed already (a retry after the transaction that recorded it failed): the object is there.
576
+ yield* storage.head(file.storageKey).pipe(Effect.mapError(refusedBy))
577
+ } else {
578
+ const absent: Array<number> = []
579
+ for (let part = 1; part <= file.parts; part++) {
580
+ if (held.get(part)?.size !== partSizeOf(file, part)) absent.push(part)
581
+ }
582
+ if (absent.length > 0) {
583
+ return yield* new InvalidInput({ message: `Parts not received yet: ${absent.join(", ")}` })
584
+ }
585
+ yield* storage
586
+ .completeMultipart(
587
+ file.storageKey,
588
+ file.uploadId ?? "",
589
+ Array.from({ length: file.parts }, (_, i) => ({ partNumber: i + 1, etag: held.get(i + 1)!.etag })),
590
+ )
591
+ .pipe(
592
+ Effect.catchTag("StorageNotFound", () => storage.head(file.storageKey)),
593
+ Effect.mapError(refusedBy),
594
+ )
595
+ }
596
+ }
597
+ yield* sql`UPDATE eloxiv.file SET state = 'processing', completed_at = now(), updated_at = now(),
598
+ authority = ${JSON.stringify(authority)}::jsonb
599
+ WHERE id = ${fileId}`.pipe(Effect.orDie)
600
+ yield* forgetParts(fileId)
601
+ // Its finalizing workflow starts from this event, committed with the state change.
602
+ yield* publish(file, "files.uploaded", "processing", invocationId)
603
+ return recordOf((yield* row(fileId, actor.orgId))!)
604
+ })
605
+
606
+ const abortUpload: FilesShape["abortUpload"] = (actor, fileId) =>
607
+ Effect.gen(function* () {
608
+ const file = yield* ownUpload(actor, fileId, "files.abortUpload", true)
609
+ if (file.state !== "uploading") return yield* new InvalidInput({ message: `The file is ${file.state}` })
610
+ yield* sql`UPDATE eloxiv.file SET state = 'deleted', state_reason = 'The upload was abandoned',
611
+ deleted_at = now(), updated_at = now() WHERE id = ${fileId}`.pipe(Effect.orDie)
612
+ yield* forgetParts(fileId)
613
+ return recordOf((yield* row(fileId, actor.orgId))!)
614
+ })
615
+
616
+ const publish = (
617
+ file: Pick<FileRow, "id" | "orgId" | "ownerType" | "ownerId">,
618
+ type: string,
619
+ state: string,
620
+ invocationId: string,
621
+ ) =>
622
+ outbox.publish({
623
+ invocationId,
624
+ type,
625
+ module: FILES_MODULE,
626
+ orgId: file.orgId,
627
+ payload: {
628
+ fileId: file.id,
629
+ attachedTo: file.ownerType === null ? null : { entity: file.ownerType, id: file.ownerId },
630
+ state,
631
+ },
632
+ })
633
+
634
+ const attach: FilesShape["attach"] = (actor, fileId, to, invocationId) =>
635
+ Effect.gen(function* () {
636
+ const action = "files.attachTo"
637
+ const file = yield* lockedRow(fileId, actor.orgId, { type: to.entity, id: to.id })
638
+ if (file === undefined || file.uploadedBy !== actor.userId || file.ownerType !== null) {
639
+ return yield* forbidden(action, "No such staged file of yours")
640
+ }
641
+ if (file.state !== "available") return yield* new InvalidInput({ message: `The file is ${file.state}` })
642
+ const { entity } = yield* filesEntity(to.entity)
643
+ const org = yield* access.organisationIf(actor, to.entity, to.id, ATTACH_ACTION)
644
+ if (org === undefined) return yield* forbidden(action, "No such record, or you may not attach files to it")
645
+ const limit = Math.min(config.maxBytes, entity.files.maxBytes ?? config.maxBytes)
646
+ if (Number(file.size) > limit) {
647
+ return yield* new InvalidInput({
648
+ message: `The file is ${file.size} bytes; at most ${limit} are accepted here`,
649
+ })
650
+ }
651
+ if (!accepts(entity.files.types, file.contentType ?? file.declaredType)) {
652
+ return yield* new InvalidInput({ message: `Files of type ${file.contentType} are not accepted here` })
653
+ }
654
+ // A file staged in the uploader's own store becomes the organisation's: copied to the organisation's store
655
+ // (or the deployment's) and read from there, so the record never depends on that store, or on its owner
656
+ // staying. The copy is in place before the record names it; the uploader's store keeps its own copy. Only the
657
+ // bytes finalize verified are copied: read at most the file's size, then its exact size and SHA-256 checked
658
+ // against what finalize recorded, since the uploader's store may hold other bytes now. Otherwise the attach is
659
+ // refused and the file left as it was.
660
+ if (Option.isSome(providers) && (yield* providers.value.personal(file.storageKey))) {
661
+ const target = yield* providers.value.choose(actor, true)
662
+ const key =
663
+ target === null ? fileKeyOf(file.storageKey) : `${PROVIDER_KEYS}${target}/${fileKeyOf(file.storageKey)}`
664
+ const changed = new InvalidInput({
665
+ message: "The file's bytes in your store are not the ones verified; it was not attached",
666
+ })
667
+ const { bytes } = yield* getBytes(storage, file.storageKey, { max: Number(file.size) }).pipe(
668
+ Effect.mapError(() => changed),
669
+ )
670
+ const digest = createHash("sha256").update(bytes).digest("hex")
671
+ if (bytes.byteLength !== Number(file.size) || file.sha256 === null || digest !== file.sha256) {
672
+ return yield* changed
673
+ }
674
+ const copied = yield* storage.put(key, bytes, { contentType: file.contentType ?? file.declaredType }).pipe(
675
+ Effect.mapError(
676
+ (e) =>
677
+ new InvalidInput({
678
+ message: `The file could not be moved to the organisation's storage: ${e.message}`,
679
+ }),
680
+ ),
681
+ )
682
+ yield* sql`UPDATE eloxiv.file SET storage_key = ${key}, etag = ${copied.etag} WHERE id = ${fileId}`.pipe(
683
+ Effect.orDie,
684
+ )
685
+ }
686
+ yield* sql`UPDATE eloxiv.file SET owner_type = ${to.entity}, owner_id = ${to.id}, updated_at = now()
687
+ WHERE id = ${fileId}`.pipe(Effect.orDie)
688
+ const attached = (yield* row(fileId, actor.orgId))!
689
+ yield* availableHook(sql, registry, ingestion, attached, invocationId).pipe(Effect.orDie)
690
+ return recordOf(attached)
691
+ })
692
+
693
+ const get: FilesShape["get"] = (actor, fileId) => readable(actor, fileId, "files.get").pipe(Effect.map(recordOf))
694
+
695
+ const list: FilesShape["list"] = (actor, record) =>
696
+ Effect.gen(function* () {
697
+ yield* filesEntity(record.entity)
698
+ const ids = yield* access.permitted(actor, record.entity, [record.id], "read")
699
+ if (!ids.has(record.id)) return yield* forbidden("files.list", "No such record, or you may not read it")
700
+ const rows = yield* sql
701
+ .unsafe<FileRow>(
702
+ `SELECT ${COLUMNS} FROM eloxiv.file WHERE org_id = $1 AND owner_type = $2 AND owner_id = $3 AND state <> 'deleted'
703
+ ORDER BY created_at, id`,
704
+ [actor.orgId, record.entity, record.id],
705
+ )
706
+ .pipe(Effect.orDie)
707
+ return { files: rows.map(recordOf) }
708
+ })
709
+
710
+ const download: FilesShape["download"] = (actor, input, held) =>
711
+ Effect.gen(function* () {
712
+ const file = yield* readable(actor, input.fileId, "files.download")
713
+ if (file.state !== "available" || file.contentType === null) {
714
+ return yield* new InvalidInput({ message: `The file is ${file.state}` })
715
+ }
716
+ const disposition =
717
+ input.disposition === "inline" && INLINE_TYPES.has(file.contentType) ? "inline" : "attachment"
718
+ const ttl = Math.max(1, config.downloadUrlTtlS)
719
+ // Always the kernel's own route, never a store's presigned URL: the route checks the holder's access again
720
+ // when the URL is used, serves only the object finalize verified, and sets the headers itself.
721
+ const expires = Math.floor(Date.now() / 1000) + ttl
722
+ const token = yield* sign({
723
+ k: "down",
724
+ f: file.id,
725
+ d: disposition,
726
+ e: expires,
727
+ u: actor.userId,
728
+ o: actor.orgId,
729
+ c: [held?.kind ?? "session", held?.id ?? null, held?.session ?? null],
730
+ })
731
+ return {
732
+ url: `${baseUrl}${FILE_DOWNLOAD_PATH}?token=${token}`,
733
+ expiresAt: new Date(expires * 1000).toISOString(),
734
+ contentType: file.contentType,
735
+ size: Number(file.size),
736
+ }
737
+ })
738
+
739
+ const read: FilesShape["read"] = (actor, input) =>
740
+ Effect.gen(function* () {
741
+ const file = yield* readable(actor, input.fileId, "files.readText")
742
+ if (file.state !== "available") return yield* new InvalidInput({ message: `The file is ${file.state}` })
743
+ const offset = input.offset ?? 0
744
+ const limit = Math.min(input.limit ?? 20_000, 20_000)
745
+ const ingested = yield* ingestion.textOfFile(file.id)
746
+ let text = ingested.state === "done" ? ingested.text : null
747
+ let extraction = ingested.state
748
+ let truncated = ingested.truncated
749
+ if (text === null && (file.contentType ?? "").startsWith("text/") && Number(file.size) <= 1024 * 1024) {
750
+ // A small text file reads as it is, ingested or not.
751
+ const body = yield* storage.get(file.storageKey).pipe(
752
+ Effect.flatMap(({ body }) => Effect.promise(() => readAll(body, 1024 * 1024))),
753
+ Effect.mapError((e) => new InvalidInput({ message: `The file could not be read: ${e.message}` })),
754
+ )
755
+ text = new TextDecoder().decode(body)
756
+ extraction = "done"
757
+ truncated = false
758
+ }
759
+ const all = text ?? ""
760
+ const page = all.slice(offset, offset + limit)
761
+ return {
762
+ fileId: file.id,
763
+ text: page,
764
+ offset,
765
+ total: all.length,
766
+ nextOffset: offset + page.length < all.length ? offset + page.length : null,
767
+ extraction,
768
+ truncated,
769
+ }
770
+ })
771
+
772
+ /**
773
+ * Delete a file's document and every copy of what was ingested from it: its items scrubbed (their original,
774
+ * title, text and chunks) the one way ingested content is removed (`ingestion/Scrub.ts`). In the caller's
775
+ * transaction, which holds the record's lock.
776
+ */
777
+ const forgetFile = (file: Pick<FileRow, "id" | "ownerType" | "ownerId">) =>
778
+ Effect.gen(function* () {
779
+ if (file.ownerType === null || file.ownerId === null) return
780
+ const record = { type: file.ownerType, id: file.ownerId }
781
+ yield* sql`DELETE FROM eloxiv.search_document WHERE record_type = ${record.type} AND record_id = ${record.id}
782
+ AND part = ${`file:${file.id}`}`
783
+ const items = yield* sql<{ id: string }>`
784
+ SELECT id FROM eloxiv.ingestion_item
785
+ WHERE record_type = ${record.type} AND record_id = ${record.id} AND source_key = ${`file:${file.id}`}`
786
+ yield* scrubIngested(
787
+ sql,
788
+ record,
789
+ items.map((i) => i.id),
790
+ "The file was deleted",
791
+ )
792
+ }).pipe(Effect.orDie)
793
+
794
+ const deleteFile: FilesShape["delete"] = (actor, fileId, invocationId) =>
795
+ Effect.gen(function* () {
796
+ const action = "files.delete"
797
+ const file = yield* lockedRow(fileId, actor.orgId)
798
+ const refused = forbidden(action, "No such file, or you may not delete it")
799
+ if (file === undefined) return yield* refused
800
+ if (file.ownerType === null || file.ownerId === null) {
801
+ if (file.uploadedBy !== actor.userId) return yield* refused
802
+ } else {
803
+ const org = yield* access.organisationIf(actor, file.ownerType, file.ownerId, ATTACH_ACTION)
804
+ if (org === undefined) return yield* refused
805
+ }
806
+ if (file.state === "deleted") return recordOf(file)
807
+ if (file.retainUntil !== null && new Date(file.retainUntil).getTime() > Date.now()) {
808
+ return yield* new InvalidInput({ message: `The file is held until ${iso(file.retainUntil)}` })
809
+ }
810
+ yield* sql`UPDATE eloxiv.file SET state = 'deleted', state_reason = 'Deleted', deleted_at = now(), updated_at = now()
811
+ WHERE id = ${fileId}`.pipe(Effect.orDie)
812
+ yield* forgetParts(fileId)
813
+ yield* forgetFile(file)
814
+ yield* publish(file, "files.deleted", "deleted", invocationId)
815
+ return recordOf((yield* row(fileId, actor.orgId))!)
816
+ })
817
+
818
+ const retain: FilesShape["retain"] = (actor, fileId, until) =>
819
+ Effect.gen(function* () {
820
+ if (!actor.permissions.includes(FILES_MANAGE)) {
821
+ return yield* forbidden("files.retain", `Retention holds need ${FILES_MANAGE}`)
822
+ }
823
+ const at = until === null ? null : new Date(until)
824
+ if (at !== null && Number.isNaN(at.getTime()))
825
+ return yield* new InvalidInput({ message: "until is not an instant" })
826
+ // Only on files the administrator may read (their record's read policy): a hold reveals nothing else.
827
+ const file = yield* lockedRow(fileId, actor.orgId)
828
+ if (file === undefined || !(yield* mayRead(actor, file))) return yield* notReadable("files.retain")
829
+ yield* sql`UPDATE eloxiv.file SET retain_until = ${at}, updated_at = now() WHERE id = ${fileId}`.pipe(
830
+ Effect.orDie,
831
+ )
832
+ return recordOf((yield* row(fileId, actor.orgId))!)
833
+ })
834
+
835
+ const usage: FilesShape["usage"] = (actor) => usageOf(actor.orgId)
836
+
837
+ const setQuota: FilesShape["setQuota"] = (actor, limitBytes) =>
838
+ Effect.gen(function* () {
839
+ if (!actor.permissions.includes(FILES_MANAGE)) {
840
+ return yield* forbidden("files.setQuota", `Storage quotas need ${FILES_MANAGE}`)
841
+ }
842
+ if (limitBytes === null) {
843
+ yield* sql`DELETE FROM eloxiv.storage_quota WHERE org_id = ${actor.orgId}`.pipe(Effect.orDie)
844
+ } else {
845
+ yield* sql`INSERT INTO eloxiv.storage_quota (org_id, limit_bytes, updated_by) VALUES (${actor.orgId}, ${limitBytes}, ${actor.userId})
846
+ ON CONFLICT (org_id) DO UPDATE SET limit_bytes = EXCLUDED.limit_bytes, updated_by = EXCLUDED.updated_by,
847
+ updated_at = now()`.pipe(Effect.orDie)
848
+ }
849
+ return yield* usageOf(actor.orgId)
850
+ })
851
+
852
+ const receivePart: FilesShape["receivePart"] = (token, declaredLength, readBody) =>
853
+ Effect.gen(function* () {
854
+ const refuse = (status: number, tag: string, message: string) => ({ status, body: { _tag: tag, message } })
855
+ const claim = yield* verify<UploadToken>(token, "up")
856
+ if (claim === undefined) return refuse(403, "Forbidden", "This upload URL is not valid, or it expired")
857
+ if (declaredLength !== claim.s) {
858
+ return refuse(400, "InvalidInput", `This part must be sent with Content-Length ${claim.s}`)
859
+ }
860
+ // The URL is single-use: its nonce is claimed, while the upload is open, before a byte is read or stored.
861
+ const claimed = yield* sql<{ nonce: string }>`
862
+ INSERT INTO eloxiv.file_part_claim (nonce, file_id, part_number)
863
+ SELECT ${claim.n}, ${claim.f}, ${claim.p}
864
+ WHERE EXISTS (SELECT 1 FROM eloxiv.file WHERE id = ${claim.f} AND state = 'uploading' AND expires_at > now())
865
+ ON CONFLICT (nonce) DO NOTHING
866
+ RETURNING nonce`.pipe(Effect.orDie)
867
+ if (claimed.length === 0) {
868
+ return refuse(409, "Conflict", "This part URL was used already, or the upload is no longer in progress")
869
+ }
870
+ const [file] = yield* sql<FileRow>`
871
+ SELECT id, org_id AS "orgId", state, storage_key AS "storageKey", upload_id AS "uploadId", declared_type AS "declaredType",
872
+ parts
873
+ FROM eloxiv.file WHERE id = ${claim.f}`.pipe(Effect.orDie)
874
+ if (file === undefined) return refuse(409, "Conflict", "The upload is no longer in progress")
875
+ const bytes = yield* readBody(claim.s)
876
+ if (!(bytes instanceof Uint8Array)) return refuse(bytes.refused, "InvalidInput", bytes.message)
877
+ if (bytes.byteLength !== claim.s) {
878
+ return refuse(400, "InvalidInput", `This part is ${claim.s} bytes, not ${bytes.byteLength}`)
879
+ }
880
+ // A single part goes to a key of its own attempt (never the file's object, which completion chooses); parts
881
+ // of several go into the multipart upload, which completing ends.
882
+ const staged = file.parts === 1 ? `${file.storageKey}/staged/${claim.n}` : null
883
+ const stored =
884
+ staged !== null
885
+ ? yield* storage
886
+ .put(staged, bytes, { contentType: file.declaredType })
887
+ .pipe(Effect.map((o) => ({ etag: o.etag })))
888
+ : yield* Effect.gen(function* () {
889
+ let uploadId = file.uploadId
890
+ if (uploadId === null) {
891
+ const started = yield* storage.createMultipart(file.storageKey, { contentType: file.declaredType })
892
+ const [won] = yield* sql<{ uploadId: string }>`
893
+ UPDATE eloxiv.file SET upload_id = ${started.uploadId}
894
+ WHERE id = ${file.id} AND upload_id IS NULL AND state = 'uploading'
895
+ RETURNING upload_id AS "uploadId"`.pipe(Effect.orDie)
896
+ if (won === undefined) {
897
+ // Another part started the upload first (or it closed meanwhile): use its, abandon ours.
898
+ yield* storage.abortMultipart(file.storageKey, started.uploadId).pipe(Effect.ignore)
899
+ const [current] = yield* sql<{ uploadId: string | null }>`
900
+ SELECT upload_id AS "uploadId" FROM eloxiv.file WHERE id = ${file.id} AND state = 'uploading'`.pipe(
901
+ Effect.orDie,
902
+ )
903
+ if (current?.uploadId == null) return undefined
904
+ uploadId = current.uploadId
905
+ } else uploadId = won.uploadId
906
+ }
907
+ return yield* storage.uploadPart(file.storageKey, uploadId, claim.p, bytes)
908
+ })
909
+ if (stored === undefined) return refuse(409, "Conflict", "The upload is no longer in progress")
910
+ // Recorded under the file's lock, only while it is still uploading: a part that arrives after the upload
911
+ // completed, was abandoned or purged is refused, and its staged bytes deleted.
912
+ const recorded = yield* sql
913
+ .withTransaction(
914
+ Effect.gen(function* () {
915
+ const [current] = yield* sql<{
916
+ state: string
917
+ }>`SELECT state FROM eloxiv.file WHERE id = ${file.id} FOR UPDATE`
918
+ if (current?.state !== "uploading") return { ok: false as const, replaced: null }
919
+ const [previous] = yield* sql<{ staged: string | null }>`
920
+ SELECT staged_key AS staged FROM eloxiv.file_part WHERE file_id = ${file.id} AND part_number = ${claim.p}`
921
+ yield* sql`INSERT INTO eloxiv.file_part (file_id, part_number, size, etag, staged_key)
922
+ VALUES (${file.id}, ${claim.p}, ${bytes.byteLength}, ${stored.etag}, ${staged})
923
+ ON CONFLICT (file_id, part_number) DO UPDATE SET size = EXCLUDED.size, etag = EXCLUDED.etag,
924
+ staged_key = EXCLUDED.staged_key, received_at = now()`
925
+ return { ok: true as const, replaced: previous?.staged ?? null }
926
+ }),
927
+ )
928
+ .pipe(Effect.orDie)
929
+ if (!recorded.ok) {
930
+ if (staged !== null) yield* storage.delete(staged).pipe(Effect.ignore)
931
+ return refuse(409, "Conflict", "The upload is no longer in progress")
932
+ }
933
+ if (recorded.replaced !== null && recorded.replaced !== staged) {
934
+ yield* storage.delete(recorded.replaced).pipe(Effect.ignore)
935
+ }
936
+ return { status: 200, body: { partNumber: claim.p, size: bytes.byteLength } }
937
+ }).pipe(
938
+ Effect.catchTags({
939
+ StorageNotFound: (e) => Effect.succeed({ status: 409, body: { _tag: "Conflict", message: e.message } }),
940
+ StorageConflict: (e) => Effect.succeed({ status: 409, body: { _tag: "Conflict", message: e.message } }),
941
+ StorageInvalid: (e) => Effect.succeed({ status: 400, body: { _tag: "InvalidInput", message: e.message } }),
942
+ StorageUnavailable: (e) =>
943
+ Effect.logWarning(`Storage refused a part: ${e.message}`).pipe(
944
+ Effect.as({
945
+ status: 503,
946
+ body: { _tag: "Unavailable", message: "Storage is unavailable; resume the upload for a new part URL" },
947
+ }),
948
+ ),
949
+ }),
950
+ )
951
+
952
+ /**
953
+ * May the person a download URL was issued to still read the file, now, with the credential they used? The
954
+ * credential not revoked, expired or signed out, and its scope (an agent's or a token's, narrower than the
955
+ * person's) still covering `files.download`; their membership; and the record's read policy, evaluated in a
956
+ * transaction of its own (the invocation context names them while it runs).
957
+ */
958
+ const stillReadable = (claim: DownloadToken) =>
959
+ sql
960
+ .withTransaction(
961
+ Effect.gen(function* () {
962
+ const { u: userId, o: orgId, f: fileId } = claim
963
+ const [kind, id, session] = Array.isArray(claim.c) ? claim.c : []
964
+ if (kind === undefined) return false
965
+ const credential = yield* identity.recheck(
966
+ { kind, id: id ?? null, session: session ?? null },
967
+ userId,
968
+ orgId,
969
+ )
970
+ if (credential === undefined) return false
971
+ const permissionActions = (permission: string) => registry.permissions.get(permission)?.actions
972
+ if (!scopeAllows(credential.scope, FILES_ACTIONS.download, permissionActions)) return false
973
+ const actor = yield* identity.resolve({ kind: "user", userId, orgId }).pipe(Effect.option)
974
+ if (Option.isNone(actor)) return false
975
+ yield* sql`INSERT INTO eloxiv.invocation_context (actor, org, action)
976
+ VALUES (${userId}, ${orgId}, ${"files.download"})
977
+ ON CONFLICT (xid) DO UPDATE SET actor = EXCLUDED.actor, org = EXCLUDED.org, action = EXCLUDED.action`
978
+ const file = yield* row(fileId, orgId)
979
+ const may = file !== undefined && (yield* mayRead(actor.value, file))
980
+ yield* sql`DELETE FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id()`
981
+ return may
982
+ }),
983
+ )
984
+ .pipe(Effect.orDie)
985
+
986
+ const openDownload: FilesShape["openDownload"] = (token) =>
987
+ Effect.gen(function* () {
988
+ const claim = yield* verify<DownloadToken>(token, "down")
989
+ const gone = {
990
+ status: 404,
991
+ body: { _tag: "NotFound", message: "This download URL is not valid, or it expired" },
992
+ }
993
+ if (claim === undefined) return gone
994
+ const [file] = yield* sql<{
995
+ key: string
996
+ state: string
997
+ contentType: string | null
998
+ name: string
999
+ size: string
1000
+ etag: string | null
1001
+ }>`
1002
+ SELECT storage_key AS key, state, content_type AS "contentType", name, size::text AS size, etag
1003
+ FROM eloxiv.file WHERE id = ${claim.f}`.pipe(Effect.orDie)
1004
+ // A file deleted since the URL was issued is gone at once; so is one its holder may no longer read.
1005
+ if (file === undefined || file.state !== "available" || file.contentType === null) return gone
1006
+ if (!(yield* stillReadable(claim))) return gone
1007
+ const opened = yield* storage.get(file.key).pipe(Effect.option)
1008
+ if (Option.isNone(opened)) return gone
1009
+ // The object must be the one finalize verified (its etag and size), or nothing is served.
1010
+ if (opened.value.object.etag !== file.etag || opened.value.object.size !== Number(file.size)) {
1011
+ yield* Effect.promise(() => opened.value.body.cancel())
1012
+ yield* Effect.logError(
1013
+ `File ${claim.f}'s stored object is not the one that was verified; refusing to serve it`,
1014
+ )
1015
+ return { status: 409, body: { _tag: "Conflict", message: "The file's content changed after it was checked" } }
1016
+ }
1017
+ // Opening the object may have waited (a remote store): the credential is checked again before the first byte,
1018
+ // so nothing is served to a session signed out (or a credential revoked) since the check above. A stream
1019
+ // already open finishes: it was authorised when it opened, and it is bounded by the file's size.
1020
+ if (!(yield* stillReadable(claim))) {
1021
+ yield* Effect.promise(() => opened.value.body.cancel())
1022
+ return gone
1023
+ }
1024
+ const active = isActive(file.contentType)
1025
+ return {
1026
+ status: 200 as const,
1027
+ headers: {
1028
+ "content-type": active ? "application/octet-stream" : file.contentType,
1029
+ "content-length": String(opened.value.object.size),
1030
+ "content-disposition": dispositionOf(active ? "attachment" : claim.d, file.name),
1031
+ "x-content-type-options": "nosniff",
1032
+ "content-security-policy": "default-src 'none'; sandbox",
1033
+ "cache-control": "private, no-store",
1034
+ "cross-origin-resource-policy": "same-origin",
1035
+ },
1036
+ body: opened.value.body,
1037
+ }
1038
+ })
1039
+
1040
+ const forHandler: FilesShape["forHandler"] = (actor, module, role, invocationId) => {
1041
+ /** Kernel tables as the kernel; the handler's role again after. */
1042
+ const asKernel = <A, E>(effect: Effect.Effect<A, E>) =>
1043
+ Effect.gen(function* () {
1044
+ yield* sql.unsafe(`RESET ROLE`).pipe(Effect.orDie)
1045
+ return yield* effect
1046
+ }).pipe(
1047
+ Effect.ensuring(
1048
+ (role === undefined
1049
+ ? sql.unsafe(`RESET ROLE`)
1050
+ : sql.unsafe(`SET LOCAL ROLE "${role.replaceAll('"', '""')}"`)
1051
+ ).pipe(Effect.orDie),
1052
+ ),
1053
+ )
1054
+ const ownEntity = (cedarType: string) =>
1055
+ registry.entities.get(cedarType)?.module.contract.name === module
1056
+ ? Effect.void
1057
+ : Effect.fail(
1058
+ new Forbidden({ action: "files.attachTo", message: `${cedarType} is not an entity of module ${module}` }),
1059
+ )
1060
+ return {
1061
+ attach: (fileId, to) => Effect.andThen(ownEntity(to.entity), asKernel(attach(actor, fileId, to, invocationId))),
1062
+ // A module lists the files of its own records only.
1063
+ list: (record) =>
1064
+ Effect.andThen(ownEntity(record.entity), asKernel(list(actor, record).pipe(Effect.map((l) => l.files)))),
1065
+ }
1066
+ }
1067
+
1068
+ const mayStillAttach: FilesShape["mayStillAttach"] = (userId, orgId, record) =>
1069
+ Effect.gen(function* () {
1070
+ const actor = yield* identity.resolve({ kind: "user", userId, orgId }).pipe(Effect.option)
1071
+ if (actor._tag === "None") return false
1072
+ yield* sql`SELECT 1 FROM eloxiv.share_grant
1073
+ WHERE resource_type = ${record.entity} AND resource_id = ${record.id} FOR SHARE`.pipe(Effect.orDie)
1074
+ // The record is read under its module's row-level security as the uploader completing the upload (the
1075
+ // invocation context that call had), then the context is cleared again.
1076
+ yield* sql`INSERT INTO eloxiv.invocation_context (actor, org, action)
1077
+ VALUES (${userId}, ${orgId}, 'files.completeUpload')
1078
+ ON CONFLICT (xid) DO UPDATE SET actor = EXCLUDED.actor, org = EXCLUDED.org, action = EXCLUDED.action,
1079
+ subscriber = NULL`.pipe(Effect.orDie)
1080
+ const org = yield* access.organisationIf(actor.value, record.entity, record.id, ATTACH_ACTION)
1081
+ yield* sql`DELETE FROM eloxiv.invocation_context WHERE xid = pg_current_xact_id()`.pipe(Effect.orDie)
1082
+ return org !== undefined
1083
+ })
1084
+
1085
+ const sweep: FilesShape["sweep"] = Effect.gen(function* () {
1086
+ // Uploads past their time, and staged files never attached: deleted (their bytes purged below).
1087
+ const expired = yield* sql<{ id: string }>`
1088
+ UPDATE eloxiv.file SET state = 'deleted', updated_at = now(), deleted_at = now(),
1089
+ state_reason = CASE WHEN state = 'uploading' THEN 'The upload expired' ELSE 'It was never attached' END
1090
+ WHERE (state = 'uploading' AND expires_at <= now())
1091
+ OR (owner_type IS NULL AND state IN ('available', 'processing', 'rejected', 'quarantined')
1092
+ AND completed_at <= now() - make_interval(secs => ${config.stagedTtlMs / 1000}))
1093
+ RETURNING id`
1094
+ for (const file of expired) yield* forgetParts(file.id)
1095
+ // Deleted files' bytes, once retention allows; refused and quarantined files' bytes, which finalisation deletes
1096
+ // (`purge`), whenever it did not (its run ended between the settle and the purge, or replayed past them).
1097
+ const due = yield* sql<{ id: string; orgId: string; key: string; uploadId: string | null }>`
1098
+ SELECT id, org_id AS "orgId", storage_key AS key, upload_id AS "uploadId" FROM eloxiv.file
1099
+ WHERE purged_at IS NULL AND (retain_until IS NULL OR retain_until <= now())
1100
+ AND ((state = 'deleted' AND deleted_at <= now() - make_interval(secs => ${config.deletedRetentionMs / 1000}))
1101
+ OR state IN ('rejected', 'quarantined'))
1102
+ ORDER BY coalesce(deleted_at, updated_at) LIMIT 500`
1103
+ let purged = 0
1104
+ for (const file of due) {
1105
+ const done = yield* Effect.gen(function* () {
1106
+ if (file.uploadId !== null) yield* storage.abortMultipart(file.key, file.uploadId)
1107
+ yield* storage.delete(file.key)
1108
+ // And every staged part the upload left (a part that lands after this is deleted by its own request).
1109
+ let cursor: string | null = null
1110
+ do {
1111
+ const page: { objects: ReadonlyArray<{ key: string }>; nextCursor: string | null } = yield* storage.list({
1112
+ prefix: `${file.key}/`,
1113
+ cursor,
1114
+ })
1115
+ for (const object of page.objects) yield* storage.delete(object.key)
1116
+ cursor = page.nextCursor
1117
+ } while (cursor !== null)
1118
+ return true
1119
+ }).pipe(
1120
+ Effect.catch((e) =>
1121
+ Effect.logWarning(`Purging file ${file.id} failed; it is retried`, e).pipe(Effect.as(false)),
1122
+ ),
1123
+ )
1124
+ if (!done) continue
1125
+ yield* sql`UPDATE eloxiv.file SET purged_at = now(), updated_at = now() WHERE id = ${file.id}`
1126
+ purged++
1127
+ }
1128
+ return { expired: expired.length, purged }
1129
+ }).pipe(Effect.orDie)
1130
+
1131
+ return Files.of({
1132
+ beginUpload,
1133
+ resumeUpload,
1134
+ completeUpload,
1135
+ abortUpload,
1136
+ attach,
1137
+ get,
1138
+ list,
1139
+ download,
1140
+ read,
1141
+ delete: deleteFile,
1142
+ retain,
1143
+ usage,
1144
+ setQuota,
1145
+ reserve,
1146
+ receivePart,
1147
+ openDownload,
1148
+ forHandler,
1149
+ mayStillAttach,
1150
+ sweep,
1151
+ })
1152
+ }),
1153
+ )
1154
+
1155
+ /** The deployment's scanner; a deployment that requires scanning (`files.requireScan`) refuses to start without one. */
1156
+ export const FileScannersLayer = (scanner: FileScanner | undefined) =>
1157
+ Layer.effect(
1158
+ FileScanners,
1159
+ Effect.gen(function* () {
1160
+ if (scanner === undefined && filesConfig(yield* KernelConfig).requireScan) {
1161
+ return yield* Effect.die(new Error("Files requires a virus scanner (files.requireScan) but none is configured"))
1162
+ }
1163
+ return FileScanners.of({ scanner })
1164
+ }),
1165
+ )
1166
+
1167
+ /** Sweep every `sweepMs` (config) for the life of the scope (runners only). */
1168
+ export const FilesSweeper = Layer.effectDiscard(
1169
+ Effect.gen(function* () {
1170
+ const files = yield* Files
1171
+ const config = filesConfig(yield* KernelConfig)
1172
+ yield* files.sweep.pipe(
1173
+ Effect.catchCause((cause) => Effect.logWarning("Files sweep failed", cause)),
1174
+ Effect.repeat(Schedule.spaced(Duration.millis(config.sweepMs))),
1175
+ Effect.forkScoped,
1176
+ )
1177
+ }),
1178
+ )
1179
+
1180
+ // --- Finalizing an upload (the durable workflow) -----------------------------------------------------------------
1181
+
1182
+ const Inspected = Schema.Struct({
1183
+ skip: Schema.Boolean,
1184
+ size: Schema.Number,
1185
+ sha256: Schema.NullOr(Schema.String),
1186
+ /** The verified object's etag: what downloads check the stored object against. */
1187
+ etag: Schema.NullOr(Schema.String),
1188
+ contentType: Schema.NullOr(Schema.String),
1189
+ problem: Schema.NullOr(Schema.String),
1190
+ })
1191
+ const Scanned = Schema.Struct({
1192
+ verdict: Schema.Literals(["clean", "infected", "skipped", "error"]),
1193
+ detail: Schema.NullOr(Schema.String),
1194
+ })
1195
+ const Settled = Schema.Struct({ state: Schema.String, purge: Schema.Boolean })
1196
+ /** The states whose bytes finalisation deletes. */
1197
+ const REFUSED: ReadonlySet<string> = new Set(["rejected", "quarantined"])
1198
+
1199
+ const failStep = (cause: unknown) =>
1200
+ new WorkflowFailed({
1201
+ message: `File step failed: ${String(cause instanceof Error ? cause.message : cause).slice(0, 500)}`,
1202
+ })
1203
+
1204
+ const fileFor = (sql: SqlClient.SqlClient, fileId: string) =>
1205
+ sql<FileRow>`SELECT id, org_id AS "orgId", owner_type AS "ownerType", owner_id AS "ownerId", name, size, state,
1206
+ declared_type AS "declaredType", storage_key AS "storageKey", uploaded_by AS "uploadedBy"
1207
+ FROM eloxiv.file WHERE id = ${fileId}`.pipe(Effect.map(([file]) => file))
1208
+
1209
+ /** Read the whole object once: its size, SHA-256 and first bytes. */
1210
+ const inspectBytes = (storage: StorageBackendShape, key: string) =>
1211
+ Effect.gen(function* () {
1212
+ const { body, object } = yield* storage.get(key)
1213
+ return yield* Effect.promise(async () => {
1214
+ const hash = createHash("sha256")
1215
+ const head = new Uint8Array(SNIFF_BYTES)
1216
+ let headLength = 0
1217
+ let size = 0
1218
+ const reader = body.getReader()
1219
+ for (;;) {
1220
+ const { done, value } = await reader.read()
1221
+ if (done) break
1222
+ hash.update(value)
1223
+ if (headLength < SNIFF_BYTES) {
1224
+ const take = Math.min(SNIFF_BYTES - headLength, value.byteLength)
1225
+ head.set(value.subarray(0, take), headLength)
1226
+ headLength += take
1227
+ }
1228
+ size += value.byteLength
1229
+ }
1230
+ return { size, sha256: hash.digest("hex"), head: head.subarray(0, headLength), etag: object.etag }
1231
+ })
1232
+ })
1233
+
1234
+ export const fileFinalizeWorkflow = defineKernelWorkflow({
1235
+ name: FILE_FINALIZE_WORKFLOW,
1236
+ input: Schema.Struct({ fileId: Schema.String }),
1237
+ output: Schema.Struct({ state: Schema.String }),
1238
+ run: ({ fileId }, ctx) =>
1239
+ Effect.gen(function* () {
1240
+ const services = yield* Effect.context<
1241
+ SqlClient.SqlClient | StorageBackend | Registry | Outbox | Ingestion | FileScanners | Files | Authority
1242
+ >()
1243
+ const provided = <A, E>(effect: Effect.Effect<A, E, any>) =>
1244
+ effect.pipe(Effect.provide(services), Effect.mapError(failStep)) as Effect.Effect<A, WorkflowFailed>
1245
+
1246
+ // 1. Inspect: the exact size, the hash, and the type the bytes are, against what was declared and accepted.
1247
+ const inspected = yield* ctx.step("inspect", Inspected, () =>
1248
+ provided(
1249
+ Effect.gen(function* () {
1250
+ const sql = yield* SqlClient.SqlClient
1251
+ const storage = yield* StorageBackend
1252
+ const registry = yield* Registry
1253
+ const file = yield* fileFor(sql, fileId)
1254
+ if (file === undefined || file.state !== "processing") {
1255
+ return { skip: true, size: 0, sha256: null, etag: null, contentType: null, problem: null }
1256
+ }
1257
+ const bytes = yield* inspectBytes(storage, file.storageKey)
1258
+ const decided = decideType(sniff(bytes.head), file.declaredType)
1259
+ const entity = file.ownerType === null ? undefined : registry.entities.get(file.ownerType)?.entity
1260
+ const problem =
1261
+ bytes.size !== Number(file.size)
1262
+ ? `The file is ${bytes.size} bytes, not the ${file.size} declared`
1263
+ : !decided.ok
1264
+ ? decided.reason
1265
+ : !accepts(entity?.files?.types, decided.type)
1266
+ ? `Files of type ${decided.type} are not accepted here`
1267
+ : null
1268
+ return {
1269
+ skip: false,
1270
+ size: bytes.size,
1271
+ sha256: bytes.sha256,
1272
+ etag: bytes.etag,
1273
+ contentType: decided.ok ? decided.type : null,
1274
+ problem,
1275
+ }
1276
+ }),
1277
+ ),
1278
+ )
1279
+ if (inspected.skip) return { state: "skipped" }
1280
+
1281
+ // 2. Scan (the deployment's scanner, if any), unless the inspection already refused it.
1282
+ const scanned = yield* ctx.step("scan", Scanned, () =>
1283
+ provided(
1284
+ Effect.gen(function* () {
1285
+ if (inspected.problem !== null) return { verdict: "skipped" as const, detail: null }
1286
+ const { scanner } = yield* FileScanners
1287
+ if (scanner === undefined) return { verdict: "skipped" as const, detail: null }
1288
+ const sql = yield* SqlClient.SqlClient
1289
+ const storage = yield* StorageBackend
1290
+ const file = (yield* fileFor(sql, fileId))!
1291
+ const result = yield* scanner
1292
+ .scan({
1293
+ fileId,
1294
+ orgId: file.orgId,
1295
+ contentType: inspected.contentType ?? file.declaredType,
1296
+ size: inspected.size,
1297
+ read: () => storage.get(file.storageKey).pipe(Effect.map((o) => o.body)),
1298
+ })
1299
+ .pipe(Effect.catch((e) => Effect.succeed({ verdict: "error" as const, detail: String(e).slice(0, 500) })))
1300
+ return { verdict: result.verdict, detail: result.detail }
1301
+ }),
1302
+ ),
1303
+ )
1304
+
1305
+ // 3. Settle, in one transaction: available (indexed, ingested), or rejected / quarantined.
1306
+ const settled = yield* ctx.step("settle", Settled, () =>
1307
+ provided(
1308
+ Effect.gen(function* () {
1309
+ const sql = yield* SqlClient.SqlClient
1310
+ const outbox = yield* Outbox
1311
+ const authority = yield* Authority
1312
+ return yield* sql.withTransaction(
1313
+ Effect.gen(function* () {
1314
+ // The authority the upload was completed under, asserted before any lock it protects (the lock
1315
+ // order: authority links first, then the record, then the row): the uploader's credential, session
1316
+ // and membership still hold, or the file is refused and nothing of it is made visible.
1317
+ const [recorded] = yield* sql<{
1318
+ orgId: string
1319
+ uploadedBy: string
1320
+ state: string
1321
+ authority: AuthorityRecord | null
1322
+ purged: boolean
1323
+ }>`SELECT org_id AS "orgId", uploaded_by AS "uploadedBy", state, authority, purged_at IS NOT NULL AS purged
1324
+ FROM eloxiv.file WHERE id = ${fileId}`.pipe(Effect.orDie)
1325
+ // Settled already (this step ran and committed, but its result was not kept): bytes it refused and
1326
+ // did not delete yet are still deleted.
1327
+ if (recorded === undefined || recorded.state !== "processing")
1328
+ return {
1329
+ state: recorded?.state ?? "gone",
1330
+ purge: recorded !== undefined && REFUSED.has(recorded.state) && !recorded.purged,
1331
+ }
1332
+ // Bound to a name and confirmed at commit (`authority.confirm(asserted)` below), or refused here.
1333
+ const asserted = yield* authority
1334
+ .assert({
1335
+ chain: recorded.authority === null ? "unrecorded" : recorded.authority.chain,
1336
+ who: { userId: recorded.uploadedBy, orgId: recorded.orgId },
1337
+ scope: recorded.authority?.scope ?? null,
1338
+ })
1339
+ .pipe(Effect.catch((refusal) => Effect.succeed({ refused: refusal.message })))
1340
+ if ("refused" in asserted) {
1341
+ const [refused] = yield* sql<{ ownerType: string | null; ownerId: string | null }>`
1342
+ UPDATE eloxiv.file SET state = 'rejected', updated_at = now(),
1343
+ state_reason = ${`The authority it was uploaded under no longer holds: ${asserted.refused}`.slice(0, 2000)}
1344
+ WHERE id = ${fileId} AND state = 'processing'
1345
+ RETURNING owner_type AS "ownerType", owner_id AS "ownerId"`.pipe(Effect.orDie)
1346
+ if (refused === undefined) return { state: "gone", purge: false }
1347
+ yield* outbox.publish({
1348
+ invocationId: fileId,
1349
+ type: "files.rejected",
1350
+ module: FILES_MODULE,
1351
+ orgId: recorded.orgId,
1352
+ payload: {
1353
+ fileId,
1354
+ attachedTo:
1355
+ refused.ownerType === null ? null : { entity: refused.ownerType, id: refused.ownerId },
1356
+ state: "rejected",
1357
+ },
1358
+ })
1359
+ return { state: "rejected", purge: true }
1360
+ }
1361
+ // The record's lock before the row (`RecordLock.ts`): its deletion may be under way.
1362
+ const file = yield* lockRecordsThenRow(
1363
+ sql,
1364
+ (forUpdate) =>
1365
+ sql
1366
+ .unsafe<FileRow>(
1367
+ `SELECT id, org_id AS "orgId", owner_type AS "ownerType", owner_id AS "ownerId", name, state,
1368
+ uploaded_by AS "uploadedBy", record_generation::text AS "recordGeneration"
1369
+ FROM eloxiv.file WHERE id = $1${forUpdate ? " FOR UPDATE" : ""}`,
1370
+ [fileId],
1371
+ )
1372
+ .pipe(
1373
+ Effect.map((rows) => rows[0]),
1374
+ Effect.orDie,
1375
+ ),
1376
+ [],
1377
+ )
1378
+ if (file === undefined || file.state !== "processing")
1379
+ return { state: file?.state ?? "gone", purge: false }
1380
+ // Checked again under the record's lock, in the transaction that makes the file visible: a record
1381
+ // deleted while the file was uploaded or inspected takes the file with it, and nothing of it is
1382
+ // indexed or ingested.
1383
+ const owner = ownerOf(file)
1384
+ // The uploader may still attach to the record (their permissions read now, its grants held): a grant
1385
+ // revoked while the file was inspected or scanned refuses it, as it refuses a new upload.
1386
+ if (
1387
+ owner !== undefined &&
1388
+ !(yield* (yield* Files).mayStillAttach(file.uploadedBy, file.orgId, {
1389
+ entity: owner.type,
1390
+ id: owner.id,
1391
+ }))
1392
+ ) {
1393
+ yield* sql`UPDATE eloxiv.file SET state = 'rejected', updated_at = now(),
1394
+ state_reason = 'Its uploader may no longer attach files to its record'
1395
+ WHERE id = ${fileId}`
1396
+ yield* outbox.publish({
1397
+ invocationId: fileId,
1398
+ type: "files.rejected",
1399
+ module: FILES_MODULE,
1400
+ orgId: file.orgId,
1401
+ payload: { fileId, attachedTo: { entity: owner.type, id: owner.id }, state: "rejected" },
1402
+ })
1403
+ return { state: "rejected", purge: true }
1404
+ }
1405
+ // The record changed since the upload began (its generation moved: a write, a scrub of its personal
1406
+ // data): the file is refused, so nothing derived from it (its name, its content) is made visible
1407
+ // after a change it was prepared before. Uploaded again, it is attached to the record as it is now.
1408
+ // An upload attached at its start without a recorded generation (begun before kernel migration
1409
+ // `0041`) is stale too: it fails closed, and is uploaded again.
1410
+ const captured = file.recordGeneration ?? null
1411
+ if (owner !== undefined) {
1412
+ const now = yield* generationOf(sql, owner)
1413
+ if (captured === null || now !== captured) {
1414
+ const reason = "Its record changed while the file was being uploaded: upload it again"
1415
+ yield* sql`UPDATE eloxiv.file SET state = 'rejected', state_reason = ${reason}, updated_at = now()
1416
+ WHERE id = ${fileId}`
1417
+ yield* outbox.publish({
1418
+ invocationId: fileId,
1419
+ type: "files.rejected",
1420
+ module: FILES_MODULE,
1421
+ orgId: file.orgId,
1422
+ payload: { fileId, attachedTo: { entity: owner.type, id: owner.id }, state: "rejected" },
1423
+ })
1424
+ return { state: "rejected", purge: true }
1425
+ }
1426
+ }
1427
+ if (owner !== undefined && !(yield* recordExists(sql, yield* Registry, file.orgId, owner))) {
1428
+ yield* sql`UPDATE eloxiv.file SET state = 'deleted', state_reason = 'Its record was deleted',
1429
+ deleted_at = coalesce(deleted_at, now()), updated_at = now()
1430
+ WHERE id = ${fileId}`
1431
+ yield* outbox.publish({
1432
+ invocationId: fileId,
1433
+ type: "files.deleted",
1434
+ module: FILES_MODULE,
1435
+ orgId: file.orgId,
1436
+ payload: { fileId, attachedTo: { entity: owner.type, id: owner.id }, state: "deleted" },
1437
+ })
1438
+ return { state: "deleted", purge: false }
1439
+ }
1440
+ const state =
1441
+ inspected.problem !== null
1442
+ ? "rejected"
1443
+ : scanned.verdict === "infected"
1444
+ ? "quarantined"
1445
+ : scanned.verdict === "error"
1446
+ ? "rejected"
1447
+ : "available"
1448
+ const reason =
1449
+ inspected.problem ??
1450
+ (scanned.verdict === "infected"
1451
+ ? `The virus scan found ${scanned.detail ?? "something"}`
1452
+ : scanned.verdict === "error"
1453
+ ? `The virus scan failed: ${scanned.detail ?? "no reason given"}`
1454
+ : null)
1455
+ yield* sql`UPDATE eloxiv.file SET state = ${state}, state_reason = ${reason}, sha256 = ${inspected.sha256},
1456
+ content_type = ${inspected.contentType}, etag = ${inspected.etag}, scan = ${inspected.problem === null ? scanned.verdict : null},
1457
+ updated_at = now()
1458
+ WHERE id = ${fileId}`
1459
+ if (state === "available" && file.ownerType !== null && file.ownerId !== null) {
1460
+ yield* availableHook(sql, yield* Registry, yield* Ingestion, file, fileId)
1461
+ }
1462
+ yield* outbox.publish({
1463
+ invocationId: fileId,
1464
+ type: state === "available" ? "files.available" : "files.rejected",
1465
+ module: FILES_MODULE,
1466
+ orgId: file.orgId,
1467
+ payload: {
1468
+ fileId,
1469
+ attachedTo: file.ownerType === null ? null : { entity: file.ownerType, id: file.ownerId },
1470
+ state,
1471
+ },
1472
+ })
1473
+ // The check at commit, the last statement of the transaction that makes the file visible: a session or
1474
+ // token that expired, or a session revoked, while the file was settled commits none of it (the step
1475
+ // runs again, and is refused). The refusals above commit without it: they make nothing visible.
1476
+ yield* authority.confirm(asserted)
1477
+ return { state, purge: state !== "available" }
1478
+ }),
1479
+ )
1480
+ }),
1481
+ ),
1482
+ )
1483
+
1484
+ // 4. Bytes the kernel refused or quarantined are deleted.
1485
+ if (settled.purge) {
1486
+ yield* ctx.step("purge", Schema.Boolean, () =>
1487
+ provided(
1488
+ Effect.gen(function* () {
1489
+ const sql = yield* SqlClient.SqlClient
1490
+ const storage = yield* StorageBackend
1491
+ const [file] = yield* sql<{
1492
+ key: string
1493
+ }>`SELECT storage_key AS key FROM eloxiv.file WHERE id = ${fileId}`
1494
+ if (file !== undefined) yield* storage.delete(file.key)
1495
+ yield* sql`UPDATE eloxiv.file SET purged_at = now() WHERE id = ${fileId}`
1496
+ return true
1497
+ }),
1498
+ ),
1499
+ )
1500
+ }
1501
+ return { state: settled.state }
1502
+ }),
1503
+ })
1504
+
1505
+ /** The record a file is attached to, if any. */
1506
+ const ownerOf = (file: Pick<FileRow, "ownerType" | "ownerId"> | undefined) =>
1507
+ file?.ownerType != null && file.ownerId != null ? { type: file.ownerType, id: file.ownerId } : undefined
1508
+
1509
+ /** A record's generation now (moved by every write to it and every scrub of it). */
1510
+ const generationOf = (sql: SqlClient.SqlClient, record: { readonly type: string; readonly id: string }) =>
1511
+ sql<{ generation: string }>`SELECT generation::text AS generation FROM eloxiv.record_generation
1512
+ WHERE record_type = ${record.type} AND record_id = ${record.id}`.pipe(
1513
+ Effect.map((rows) => rows[0]?.generation ?? "0"),
1514
+ Effect.orDie,
1515
+ )
1516
+
1517
+ /** Does the record exist (read as its module's system actor, in the file's organisation)? */
1518
+ const recordExists = (
1519
+ sql: SqlClient.SqlClient,
1520
+ registry: RegistryShape,
1521
+ orgId: string,
1522
+ record: { readonly type: string; readonly id: string },
1523
+ ) =>
1524
+ Effect.gen(function* () {
1525
+ const registered = registry.entities.get(record.type)
1526
+ if (registered === undefined) return false
1527
+ const entity = registered.entity
1528
+ const ident = (name: string) => `"${name.replaceAll('"', '""')}"`
1529
+ const pk = ident((entity.columns as Record<string, string>)[entity.primaryKey]!)
1530
+ const rows = yield* asSystem(
1531
+ sql,
1532
+ registered.module.contract.name,
1533
+ orgId,
1534
+ sql.unsafe<{ n: number }>(
1535
+ `SELECT 1 AS n FROM ${ident(entity.table.schema)}.${ident(entity.table.name)} WHERE ${pk}::text = $1`,
1536
+ [record.id],
1537
+ ),
1538
+ ).pipe(Effect.orDie)
1539
+ return rows.length > 0
1540
+ })
1541
+
1542
+ /** The row was found attached to a record whose lock is not held: let go of it, take that lock, read it again. */
1543
+ class Relock {
1544
+ readonly _tag = "Relock"
1545
+ readonly record: { readonly type: string; readonly id: string }
1546
+ constructor(record: { readonly type: string; readonly id: string }) {
1547
+ this.record = record
1548
+ }
1549
+ }
1550
+
1551
+ /**
1552
+ * A file's row, locked only after the locks of the records it is attached to (`RecordLock.ts`: records before
1553
+ * rows, always), with `extra` records locked first too. Each read under the row's lock is in a savepoint: found
1554
+ * attached to a record whose lock is not held (attached meanwhile), the savepoint is rolled back (letting go of the
1555
+ * row), that record's lock is taken, and the row read again. Never a record's lock waited for while holding a row.
1556
+ * Once the row is locked under its record's lock, the record it is attached to can change no more.
1557
+ */
1558
+ const lockRecordsThenRow = <R extends Pick<FileRow, "ownerType" | "ownerId">>(
1559
+ sql: SqlClient.SqlClient,
1560
+ read: (forUpdate: boolean) => Effect.Effect<R | undefined>,
1561
+ extra: ReadonlyArray<{ readonly type: string; readonly id: string }>,
1562
+ ) =>
1563
+ Effect.gen(function* () {
1564
+ const locked = new Set<string>()
1565
+ const lock = (records: ReadonlyArray<{ readonly type: string; readonly id: string } | undefined>) =>
1566
+ Effect.gen(function* () {
1567
+ const wanted = records.filter((r) => r !== undefined && !locked.has(recordLockKey(r.type, r.id))) as Array<{
1568
+ readonly type: string
1569
+ readonly id: string
1570
+ }>
1571
+ wanted.sort((a, b) => (a.type === b.type ? (a.id < b.id ? -1 : 1) : a.type < b.type ? -1 : 1))
1572
+ for (const record of wanted) {
1573
+ yield* lockRecord(sql, record).pipe(Effect.orDie)
1574
+ locked.add(recordLockKey(record.type, record.id))
1575
+ }
1576
+ })
1577
+ yield* lock([ownerOf(yield* read(false)), ...extra])
1578
+ for (;;) {
1579
+ const attempt = yield* sql
1580
+ .withTransaction(
1581
+ Effect.gen(function* () {
1582
+ const current = yield* read(true)
1583
+ const owner = ownerOf(current)
1584
+ if (owner !== undefined && !locked.has(recordLockKey(owner.type, owner.id))) {
1585
+ return yield* Effect.fail(new Relock(owner))
1586
+ }
1587
+ return current
1588
+ }),
1589
+ )
1590
+ .pipe(
1591
+ Effect.catchTag("SqlError", (e) => Effect.die(e)),
1592
+ Effect.result,
1593
+ )
1594
+ if (attempt._tag === "Success") return attempt.success
1595
+ yield* lock([attempt.failure.record])
1596
+ }
1597
+ })
1598
+
1599
+ /**
1600
+ * A file attached to a record became available: its name indexed under the record, and its content ingested when
1601
+ * the record's entity asks (`files.ingest`). In the caller's transaction.
1602
+ */
1603
+ const availableHook = (
1604
+ sql: SqlClient.SqlClient,
1605
+ registry: RegistryShape,
1606
+ ingestion: IngestionShape,
1607
+ file: Pick<FileRow, "id" | "orgId" | "ownerType" | "ownerId" | "name" | "uploadedBy">,
1608
+ invocationId: string,
1609
+ ) =>
1610
+ Effect.gen(function* () {
1611
+ const record = { type: file.ownerType!, id: file.ownerId! }
1612
+ yield* sql`INSERT INTO eloxiv.search_document (record_type, record_id, part, org_id, title, body, config, tsv)
1613
+ VALUES (${record.type}, ${record.id}, ${`file:${file.id}`}, ${file.orgId}, ${file.name}, ${file.name},
1614
+ 'simple', to_tsvector('simple', ${file.name.replace(/[._-]+/gu, " ")}))
1615
+ ON CONFLICT (record_type, record_id, part) DO UPDATE SET title = EXCLUDED.title, body = EXCLUDED.body,
1616
+ tsv = EXCLUDED.tsv, updated_at = now()`
1617
+ const registered = registry.entities.get(record.type)
1618
+ if (registered?.entity.files?.ingest === true) {
1619
+ yield* ingestion
1620
+ .enqueue({
1621
+ orgId: file.orgId,
1622
+ record,
1623
+ module: registered.module.contract.name,
1624
+ source: { kind: "file", fileId: file.id },
1625
+ submittedBy: file.uploadedBy,
1626
+ invocationId,
1627
+ })
1628
+ .pipe(
1629
+ Effect.catchTag("InvalidInput", (e) => Effect.logWarning(`File ${file.id} was not ingested: ${e.message}`)),
1630
+ )
1631
+ }
1632
+ })
1633
+
1634
+ const UploadedPayload = Schema.Struct({ fileId: Schema.String })
1635
+
1636
+ /** The kernel reaction that starts a completed upload's finalizing workflow (once per file). */
1637
+ export const filesReactions = (workflows: WorkflowsShape) => [
1638
+ {
1639
+ id: "files.finalize",
1640
+ event: "files.uploaded",
1641
+ handle: (event: ReactionEvent) =>
1642
+ Effect.gen(function* () {
1643
+ const payload = yield* Schema.decodeUnknownEffect(UploadedPayload)(event.payload)
1644
+ yield* workflows.start({
1645
+ workflow: FILE_FINALIZE_WORKFLOW,
1646
+ key: payload.fileId,
1647
+ identity: { kind: "system", orgId: event.orgId },
1648
+ input: { fileId: payload.fileId },
1649
+ })
1650
+ }),
1651
+ },
1652
+ ]