copilotz 1.0.0-rc.20 → 1.0.0-rc.21

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 (340) hide show
  1. package/CHANGELOG.md +417 -0
  2. package/README.md +295 -19
  3. package/hosts/orgs/mod.d.ts +4 -1
  4. package/hosts/orgs/mod.js +2 -2
  5. package/hosts/web/files.d.ts +6 -2
  6. package/hosts/web/files.js +36 -3
  7. package/hosts/web/node/mod.d.ts +1 -1
  8. package/hosts/web/node/mod.js +1 -1
  9. package/hosts/web/node/serve.d.ts +26 -0
  10. package/hosts/web/node/serve.js +23 -1
  11. package/hosts/web/routes.d.ts +28 -1
  12. package/hosts/web/routes.js +65 -10
  13. package/hosts/web/server.d.ts +5 -4
  14. package/hosts/web/server.js +1 -1
  15. package/package.json +2 -2
  16. package/plugins/access/accounts/collections/account.d.ts +2 -2
  17. package/plugins/access/contacts/actions/chat.d.ts +1 -0
  18. package/plugins/access/contacts/actions/chat.js +45 -0
  19. package/plugins/access/contacts/actions/forget.d.ts +1 -0
  20. package/plugins/access/contacts/actions/forget.js +56 -0
  21. package/plugins/access/contacts/actions/start.d.ts +1 -0
  22. package/plugins/access/contacts/actions/start.js +50 -0
  23. package/plugins/access/contacts/collections/contact.d.ts +81 -0
  24. package/plugins/access/contacts/collections/contact.js +58 -0
  25. package/plugins/access/contacts/contract.d.ts +10 -0
  26. package/plugins/access/contacts/contract.js +10 -0
  27. package/plugins/access/contacts/mod.d.ts +27 -0
  28. package/plugins/access/contacts/mod.js +49 -0
  29. package/plugins/access/contacts/views/contact.d.ts +8 -0
  30. package/plugins/access/contacts/views/contact.js +25 -0
  31. package/plugins/access/contacts/web.d.ts +7 -0
  32. package/plugins/access/contacts/web.js +11 -0
  33. package/plugins/access/directory/collections/credit-code.d.ts +1 -1
  34. package/plugins/access/directory/collections/invite.d.ts +1 -1
  35. package/plugins/access/identity/mod.js +8 -6
  36. package/plugins/access/mod.d.ts +7 -1
  37. package/plugins/access/mod.js +7 -2
  38. package/plugins/access/spaces/actions/agents.js +12 -6
  39. package/plugins/access/spaces/actions/create.js +10 -1
  40. package/plugins/access/spaces/actions/invitation.js +5 -2
  41. package/plugins/access/spaces/actions/keep.d.ts +1 -0
  42. package/plugins/access/spaces/actions/keep.js +55 -0
  43. package/plugins/access/spaces/actions/member.js +17 -4
  44. package/plugins/access/spaces/actions/rename.js +4 -0
  45. package/plugins/access/spaces/collections/member.d.ts +1 -1
  46. package/plugins/access/spaces/collections/request.d.ts +1 -1
  47. package/plugins/access/spaces/collections/space.d.ts +9 -0
  48. package/plugins/access/spaces/collections/space.js +2 -0
  49. package/plugins/access/spaces/contract.d.ts +4 -3
  50. package/plugins/access/spaces/contract.js +1 -1
  51. package/plugins/access/spaces/mod.d.ts +7 -1
  52. package/plugins/access/spaces/mod.js +8 -1
  53. package/plugins/access/spaces/resources/tools.d.ts +0 -5
  54. package/plugins/access/spaces/resources/tools.js +11 -1
  55. package/plugins/access/spaces/shared/agents.js +2 -2
  56. package/plugins/access/spaces/shared/can.d.ts +18 -3
  57. package/plugins/access/spaces/shared/can.js +32 -5
  58. package/plugins/access/spaces/shared/declared.d.ts +21 -0
  59. package/plugins/access/spaces/shared/declared.js +8 -0
  60. package/plugins/access/spaces/shared/labels.d.ts +7 -1
  61. package/plugins/access/spaces/shared/labels.js +56 -8
  62. package/plugins/access/spaces/shared/managers.js +2 -2
  63. package/plugins/access/spaces/shared/names.d.ts +9 -5
  64. package/plugins/access/spaces/shared/names.js +36 -19
  65. package/plugins/access/spaces/shared/reach.d.ts +20 -6
  66. package/plugins/access/spaces/shared/reach.js +62 -20
  67. package/plugins/access/spaces/shared/rules.d.ts +10 -5
  68. package/plugins/access/spaces/shared/rules.js +35 -10
  69. package/plugins/access/spaces/shared/seat.d.ts +3 -2
  70. package/plugins/access/spaces/shared/seat.js +9 -2
  71. package/plugins/access/spaces/views/where.d.ts +4 -2
  72. package/plugins/access/spaces/views/where.js +9 -0
  73. package/plugins/access/spaces/web.js +1 -1
  74. package/plugins/access/web.d.ts +1 -0
  75. package/plugins/access/web.js +1 -0
  76. package/plugins/agents/chat/actions/erase.d.ts +1 -0
  77. package/plugins/agents/chat/actions/erase.js +51 -0
  78. package/plugins/agents/chat/actions/open.d.ts +1 -0
  79. package/plugins/agents/chat/actions/open.js +49 -0
  80. package/plugins/agents/chat/actions/quiet.d.ts +1 -0
  81. package/plugins/agents/chat/actions/quiet.js +33 -0
  82. package/plugins/agents/chat/actions/say.d.ts +1 -0
  83. package/plugins/agents/chat/actions/say.js +82 -0
  84. package/plugins/agents/chat/actions/send.js +57 -19
  85. package/plugins/agents/chat/actions/shown.d.ts +1 -0
  86. package/plugins/agents/chat/actions/shown.js +35 -0
  87. package/plugins/agents/chat/collections/intent.d.ts +124 -0
  88. package/plugins/agents/chat/collections/intent.js +52 -0
  89. package/plugins/agents/chat/collections/message.d.ts +74 -1
  90. package/plugins/agents/chat/collections/message.js +23 -1
  91. package/plugins/agents/chat/collections/shown.d.ts +105 -0
  92. package/plugins/agents/chat/collections/shown.js +34 -0
  93. package/plugins/agents/chat/contract.d.ts +15 -7
  94. package/plugins/agents/chat/contract.js +7 -1
  95. package/plugins/agents/chat/mod.d.ts +20 -2
  96. package/plugins/agents/chat/mod.js +43 -4
  97. package/plugins/agents/chat/processors/failed.js +15 -5
  98. package/plugins/agents/chat/processors/turn.d.ts +1 -1
  99. package/plugins/agents/chat/processors/turn.js +95 -35
  100. package/plugins/agents/chat/shared/delivery.d.ts +16 -2
  101. package/plugins/agents/chat/shared/delivery.js +62 -7
  102. package/plugins/agents/chat/shared/send.d.ts +1 -3
  103. package/plugins/agents/chat/shared/send.js +2 -9
  104. package/plugins/agents/chat/shared/tools.d.ts +33 -0
  105. package/plugins/agents/chat/shared/tools.js +28 -0
  106. package/plugins/agents/chat/shared/types.d.ts +59 -1
  107. package/plugins/agents/chat/views/message.d.ts +4 -2
  108. package/plugins/agents/chat/views/message.js +22 -4
  109. package/plugins/agents/chat/views/prompt.js +38 -4
  110. package/plugins/agents/history/collections/outline.d.ts +1 -1
  111. package/plugins/agents/history/collections/summary.d.ts +1 -1
  112. package/plugins/agents/history/mod.js +2 -1
  113. package/plugins/agents/history/processors/erase.d.ts +3 -0
  114. package/plugins/agents/history/processors/erase.js +11 -0
  115. package/plugins/agents/memory/mod.js +2 -1
  116. package/plugins/agents/memory/processors/extract.d.ts +1 -1
  117. package/plugins/agents/memory/processors/extract.js +5 -0
  118. package/plugins/agents/memory/resources/tools.js +1 -1
  119. package/plugins/agents/memory/shared/settings.d.ts +7 -2
  120. package/plugins/agents/memory/shared/settings.js +9 -1
  121. package/plugins/agents/routines/collections/routine.d.ts +1 -1
  122. package/plugins/agents/routines/collections/run.d.ts +1 -1
  123. package/plugins/compute/apps/collections/app.d.ts +2 -2
  124. package/plugins/compute/cloud/resources/tools.js +3 -3
  125. package/plugins/compute/computers/collections/approval.d.ts +2 -2
  126. package/plugins/compute/computers/collections/grant.d.ts +1 -1
  127. package/plugins/compute/computers/collections/preview.d.ts +2 -2
  128. package/plugins/compute/computers/program/version.d.ts +1 -1
  129. package/plugins/compute/computers/program/version.js +1 -1
  130. package/plugins/compute/computers/resources/downloads.js +1 -1
  131. package/plugins/compute/computers/shared/wake.d.ts +1 -1
  132. package/plugins/compute/computers/shared/wake.js +17 -0
  133. package/plugins/interfaces/api/collections/key.d.ts +1 -1
  134. package/plugins/interfaces/api/shared/events.js +5 -4
  135. package/plugins/interfaces/maintenance/actions/read.d.ts +4 -0
  136. package/plugins/interfaces/maintenance/actions/read.js +76 -0
  137. package/plugins/interfaces/maintenance/actions/write.d.ts +4 -0
  138. package/plugins/interfaces/maintenance/actions/write.js +64 -0
  139. package/plugins/interfaces/maintenance/contract.d.ts +60 -0
  140. package/plugins/interfaces/maintenance/contract.js +2 -0
  141. package/plugins/interfaces/maintenance/mod.d.ts +52 -0
  142. package/plugins/interfaces/maintenance/mod.js +66 -0
  143. package/plugins/interfaces/maintenance/resources/routes.d.ts +71 -0
  144. package/plugins/interfaces/maintenance/resources/routes.js +457 -0
  145. package/plugins/interfaces/maintenance/shared/ops.d.ts +4 -0
  146. package/plugins/interfaces/maintenance/shared/ops.js +19 -0
  147. package/plugins/interfaces/mcp/actions/call.d.ts +11 -0
  148. package/plugins/interfaces/mcp/actions/call.js +304 -0
  149. package/plugins/interfaces/mcp/actions/prune.d.ts +1 -0
  150. package/plugins/interfaces/mcp/actions/prune.js +18 -0
  151. package/plugins/interfaces/mcp/collections/closed.d.ts +23 -0
  152. package/plugins/interfaces/mcp/collections/closed.js +17 -0
  153. package/plugins/interfaces/mcp/collections/rate.d.ts +27 -0
  154. package/plugins/interfaces/mcp/collections/rate.js +18 -0
  155. package/plugins/interfaces/mcp/collections/receipt.d.ts +46 -0
  156. package/plugins/interfaces/mcp/collections/receipt.js +46 -0
  157. package/plugins/interfaces/mcp/contract.d.ts +9 -0
  158. package/plugins/interfaces/mcp/contract.js +9 -0
  159. package/plugins/interfaces/mcp/mod.d.ts +84 -0
  160. package/plugins/interfaces/mcp/mod.js +122 -0
  161. package/plugins/interfaces/mcp/processors/closed.d.ts +13 -0
  162. package/plugins/interfaces/mcp/processors/closed.js +16 -0
  163. package/plugins/interfaces/mcp/resources/running.d.ts +21 -0
  164. package/plugins/interfaces/mcp/resources/running.js +36 -0
  165. package/plugins/interfaces/mcp/resources/server.d.ts +54 -0
  166. package/plugins/interfaces/mcp/resources/server.js +423 -0
  167. package/plugins/interfaces/mcp/resources/tools.d.ts +114 -0
  168. package/plugins/interfaces/mcp/resources/tools.js +324 -0
  169. package/plugins/interfaces/mcp/shared/caller.d.ts +45 -0
  170. package/plugins/interfaces/mcp/shared/caller.js +99 -0
  171. package/plugins/interfaces/mcp/shared/keys.d.ts +50 -0
  172. package/plugins/interfaces/mcp/shared/keys.js +53 -0
  173. package/plugins/interfaces/mcp/shared/settings.d.ts +187 -0
  174. package/plugins/interfaces/mcp/shared/settings.js +176 -0
  175. package/plugins/interfaces/mcp/views/offered.d.ts +20 -0
  176. package/plugins/interfaces/mcp/views/offered.js +20 -0
  177. package/plugins/interfaces/mod.d.ts +5 -1
  178. package/plugins/interfaces/mod.js +5 -1
  179. package/plugins/interfaces/terminal/actions/print.js +1 -1
  180. package/plugins/interfaces/terminal/actions/set.js +1 -1
  181. package/plugins/interfaces/terminal/collections/output.d.ts +1 -1
  182. package/plugins/interfaces/terminal/collections/shell.js +1 -1
  183. package/plugins/interfaces/voice/actions/block.d.ts +2 -0
  184. package/plugins/interfaces/voice/actions/block.js +74 -0
  185. package/plugins/interfaces/voice/actions/call.d.ts +19 -0
  186. package/plugins/interfaces/voice/actions/call.js +253 -0
  187. package/plugins/interfaces/voice/actions/hook.d.ts +5 -0
  188. package/plugins/interfaces/voice/actions/hook.js +225 -0
  189. package/plugins/interfaces/voice/actions/prune.d.ts +1 -0
  190. package/plugins/interfaces/voice/actions/prune.js +35 -0
  191. package/plugins/interfaces/voice/collections/blocked.d.ts +87 -0
  192. package/plugins/interfaces/voice/collections/blocked.js +34 -0
  193. package/plugins/interfaces/voice/collections/call.d.ts +279 -0
  194. package/plugins/interfaces/voice/collections/call.js +77 -0
  195. package/plugins/interfaces/voice/collections/phone.d.ts +74 -0
  196. package/plugins/interfaces/voice/collections/phone.js +26 -0
  197. package/plugins/interfaces/voice/contract.d.ts +14 -0
  198. package/plugins/interfaces/voice/contract.js +2 -0
  199. package/plugins/interfaces/voice/mod.d.ts +57 -0
  200. package/plugins/interfaces/voice/mod.js +118 -0
  201. package/plugins/interfaces/voice/processors/forget.d.ts +13 -0
  202. package/plugins/interfaces/voice/processors/forget.js +27 -0
  203. package/plugins/interfaces/voice/resources/relay.d.ts +77 -0
  204. package/plugins/interfaces/voice/resources/relay.js +428 -0
  205. package/plugins/interfaces/voice/resources/tools.d.ts +1 -0
  206. package/plugins/interfaces/voice/resources/tools.js +25 -0
  207. package/plugins/interfaces/voice/shared/caller.d.ts +27 -0
  208. package/plugins/interfaces/voice/shared/caller.js +38 -0
  209. package/plugins/interfaces/voice/shared/settings.d.ts +136 -0
  210. package/plugins/interfaces/voice/shared/settings.js +121 -0
  211. package/plugins/interfaces/voice/shared/signature.d.ts +11 -0
  212. package/plugins/interfaces/voice/shared/signature.js +34 -0
  213. package/plugins/interfaces/voice/views/call.d.ts +41 -0
  214. package/plugins/interfaces/voice/views/call.js +30 -0
  215. package/plugins/interfaces/voice/views/context.d.ts +9 -0
  216. package/plugins/interfaces/voice/views/context.js +14 -0
  217. package/plugins/interfaces/voice/views/message.d.ts +17 -0
  218. package/plugins/interfaces/voice/views/message.js +41 -0
  219. package/plugins/interfaces/whatsapp/actions/connect.js +3 -0
  220. package/plugins/interfaces/whatsapp/actions/disconnect.js +4 -1
  221. package/plugins/interfaces/whatsapp/actions/hook.js +27 -11
  222. package/plugins/interfaces/whatsapp/actions/set.d.ts +8 -0
  223. package/plugins/interfaces/whatsapp/actions/set.js +121 -0
  224. package/plugins/interfaces/whatsapp/collections/blocked.d.ts +29 -0
  225. package/plugins/interfaces/whatsapp/collections/blocked.js +22 -0
  226. package/plugins/interfaces/whatsapp/collections/code.d.ts +1 -1
  227. package/plugins/interfaces/whatsapp/collections/number.d.ts +90 -4
  228. package/plugins/interfaces/whatsapp/collections/number.js +36 -4
  229. package/plugins/interfaces/whatsapp/collections/phone.d.ts +13 -3
  230. package/plugins/interfaces/whatsapp/collections/phone.js +9 -3
  231. package/plugins/interfaces/whatsapp/collections/rate.d.ts +27 -0
  232. package/plugins/interfaces/whatsapp/collections/rate.js +13 -0
  233. package/plugins/interfaces/whatsapp/collections/sent.d.ts +24 -12
  234. package/plugins/interfaces/whatsapp/collections/sent.js +11 -7
  235. package/plugins/interfaces/whatsapp/collections/thread.d.ts +14 -6
  236. package/plugins/interfaces/whatsapp/collections/thread.js +7 -5
  237. package/plugins/interfaces/whatsapp/collections/typing.d.ts +70 -0
  238. package/plugins/interfaces/whatsapp/collections/typing.js +21 -0
  239. package/plugins/interfaces/whatsapp/contract.d.ts +27 -4
  240. package/plugins/interfaces/whatsapp/contract.js +34 -1
  241. package/plugins/interfaces/whatsapp/events/undelivered.d.ts +8 -0
  242. package/plugins/interfaces/whatsapp/events/undelivered.js +17 -0
  243. package/plugins/interfaces/whatsapp/mod.d.ts +28 -2
  244. package/plugins/interfaces/whatsapp/mod.js +65 -6
  245. package/plugins/interfaces/whatsapp/processors/forget.d.ts +6 -0
  246. package/plugins/interfaces/whatsapp/processors/forget.js +11 -0
  247. package/plugins/interfaces/whatsapp/processors/receive.d.ts +17 -3
  248. package/plugins/interfaces/whatsapp/processors/receive.js +264 -81
  249. package/plugins/interfaces/whatsapp/processors/reply.d.ts +25 -5
  250. package/plugins/interfaces/whatsapp/processors/reply.js +216 -20
  251. package/plugins/interfaces/whatsapp/processors/typing.d.ts +8 -0
  252. package/plugins/interfaces/whatsapp/processors/typing.js +25 -0
  253. package/plugins/interfaces/whatsapp/shared/customers.d.ts +13 -0
  254. package/plugins/interfaces/whatsapp/shared/customers.js +16 -0
  255. package/plugins/interfaces/whatsapp/shared/graph.d.ts +31 -6
  256. package/plugins/interfaces/whatsapp/shared/graph.js +117 -10
  257. package/plugins/interfaces/whatsapp/shared/media.d.ts +23 -0
  258. package/plugins/interfaces/whatsapp/shared/media.js +46 -0
  259. package/plugins/interfaces/whatsapp/shared/number.d.ts +19 -8
  260. package/plugins/interfaces/whatsapp/shared/number.js +64 -7
  261. package/plugins/interfaces/whatsapp/shared/parts.d.ts +94 -0
  262. package/plugins/interfaces/whatsapp/shared/parts.js +184 -0
  263. package/plugins/interfaces/whatsapp/shared/payload.d.ts +27 -1
  264. package/plugins/interfaces/whatsapp/shared/payload.js +36 -1
  265. package/plugins/interfaces/whatsapp/shared/settings.d.ts +49 -1
  266. package/plugins/interfaces/whatsapp/shared/settings.js +11 -0
  267. package/plugins/interfaces/whatsapp/views/message.d.ts +13 -0
  268. package/plugins/interfaces/whatsapp/views/message.js +13 -0
  269. package/plugins/interfaces/whatsapp/views/web/line.d.ts +24 -0
  270. package/plugins/interfaces/whatsapp/views/web/line.js +44 -0
  271. package/plugins/interfaces/whatsapp/views/web/space.d.ts +7 -5
  272. package/plugins/interfaces/whatsapp/views/web/space.js +17 -10
  273. package/plugins/interfaces/whatsapp/views/web/style.d.ts +1 -1
  274. package/plugins/interfaces/whatsapp/views/web/style.js +8 -0
  275. package/plugins/models/adapters/llm/anthropic.d.ts +1 -1
  276. package/plugins/models/adapters/llm/anthropic.js +28 -15
  277. package/plugins/models/adapters/llm/gemini.d.ts +1 -1
  278. package/plugins/models/adapters/llm/gemini.js +2 -1
  279. package/plugins/models/adapters/llm/openai-compatible.d.ts +1 -1
  280. package/plugins/models/adapters/llm/openai-compatible.js +2 -1
  281. package/plugins/models/adapters/llm/openai.d.ts +1 -1
  282. package/plugins/models/adapters/llm/openai.js +16 -4
  283. package/plugins/models/shared/types.d.ts +8 -0
  284. package/plugins/models/shared/types.js +10 -0
  285. package/runtime/actor.d.ts +6 -0
  286. package/runtime/actor.js +9 -4
  287. package/runtime/aggregate.js +8 -2
  288. package/runtime/blobs.d.ts +15 -12
  289. package/runtime/blobs.js +58 -11
  290. package/runtime/cache.d.ts +6 -0
  291. package/runtime/cache.js +19 -1
  292. package/runtime/define.d.ts +10 -0
  293. package/runtime/errors.d.ts +20 -2
  294. package/runtime/errors.js +7 -1
  295. package/runtime/executor.js +27 -11
  296. package/runtime/links.d.ts +31 -0
  297. package/runtime/links.js +60 -0
  298. package/runtime/maintain.d.ts +88 -0
  299. package/runtime/maintain.js +120 -0
  300. package/runtime/memory.js +7 -4
  301. package/runtime/mod.d.ts +6 -4
  302. package/runtime/mod.js +5 -2
  303. package/runtime/mongo.d.ts +13 -0
  304. package/runtime/mongo.js +39 -8
  305. package/runtime/observe.d.ts +2 -0
  306. package/runtime/observe.js +14 -10
  307. package/runtime/ops.d.ts +5 -0
  308. package/runtime/ops.js +10 -1
  309. package/runtime/owner.d.ts +18 -1
  310. package/runtime/owner.js +127 -61
  311. package/runtime/presence.d.ts +18 -0
  312. package/runtime/presence.js +25 -0
  313. package/runtime/registry.d.ts +5 -0
  314. package/runtime/registry.js +18 -0
  315. package/runtime/runtime.js +9 -3
  316. package/runtime/store.d.ts +48 -1
  317. package/runtime/wire.d.ts +1 -0
  318. package/runtime/wire.js +3 -1
  319. package/stores/blobs/files/mod.js +4 -2
  320. package/stores/blobs/gcs/mod.d.ts +3 -0
  321. package/stores/blobs/gcs/mod.js +6 -5
  322. package/stores/blobs/http/mod.d.ts +1 -1
  323. package/stores/blobs/http/mod.js +2 -1
  324. package/stores/latency/mod.js +5 -1
  325. package/stores/sql/postgres/maintenance.d.ts +24 -0
  326. package/stores/sql/postgres/maintenance.js +258 -0
  327. package/stores/sql/postgres/mod.d.ts +20 -4
  328. package/stores/sql/postgres/mod.js +363 -96
  329. package/stores/sql/postgres/update.js +3 -1
  330. package/stores/sql/shared/capped.d.ts +2 -0
  331. package/stores/sql/shared/capped.js +22 -0
  332. package/stores/sql/shared/rows.d.ts +14 -0
  333. package/stores/sql/shared/rows.js +29 -0
  334. package/stores/sql/shared/statement.d.ts +12 -0
  335. package/stores/sql/shared/statement.js +244 -0
  336. package/stores/sql/sqlite/apart.d.ts +11 -0
  337. package/stores/sql/sqlite/apart.js +219 -0
  338. package/stores/sql/sqlite/mod.d.ts +16 -2
  339. package/stores/sql/sqlite/mod.js +246 -51
  340. package/testing/mod.js +1 -1
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Maintenance: HTTP endpoints for an app's operators, for when they can't
3
+ * reach its database themselves (a client's network that keeps their
4
+ * database user out). The one place an app runs SQL of its own.
5
+ *
6
+ * - **A key** (the `maintenance` resource's `key`, or several in `keys`
7
+ * while one rotates, from the app's environment): every request shows one
8
+ * (`Authorization: Bearer <key>`), compared in constant time. Without
9
+ * one, every request is unauthorized; a weak one stops the app. An orgs
10
+ * host's orgs don't get the plugin (one key would reach every org).
11
+ * - **A line for each request**, before it runs (`log`): who, what (a
12
+ * statement's hash), which key, when: a record outside the database.
13
+ * - **The maintenance actor** (`{ kind: "maintenance", id: "maintenance",
14
+ * by? }`): who every request acts as. Its Actions let only it call them,
15
+ * and run as the system on the record (`ctx.as()`: events say `via` it),
16
+ * so no rule keeps it from a document, and nothing else can act as it: a
17
+ * host binds actors, and none binds this one but these routes.
18
+ * - **Read SQL**, one read-only statement (`runtime.maintenance.read`, the
19
+ * store's `inspect`): at most `limit` rows and `bytes`, cut off after
20
+ * `timeout`. On a PostgreSQL server, as a role of its own
21
+ * (`postgresStore({ maintenance: { url } })`; the README's Maintenance).
22
+ * - **Writes through the owner**: the collections' operations (insertOne…
23
+ * deleteMany, and find…aggregate), checked against their schemas, recorded
24
+ * as events, cached and heard by Processors like any write; and the
25
+ * collections' named queries (`booking.stats`), read as the system.
26
+ * - **Raw SQL writes, inside the owner** (`runtime.maintenance.write`), for
27
+ * what operations can't do: one statement, in line with the owner's
28
+ * writes, fenced by its epoch, with one `maintenance.sql` audit event in
29
+ * the same commit; the owner then forgets what it derived from documents.
30
+ * It bypasses schemas and per-document events.
31
+ * - **Blobs by id**, as stored (in the store, or the app's Blobs).
32
+ *
33
+ * The endpoints are in `resources/routes.ts`; what raw SQL does to the
34
+ * owner, in `runtime/maintain.ts`.
35
+ *
36
+ * ```ts
37
+ * plugins: [...plugins, maintenance, definePlugin({
38
+ * name: "app",
39
+ * resources: { maintenance: { key: process.env.MAINTENANCE_KEY } },
40
+ * })]
41
+ * ```
42
+ *
43
+ * ```sh
44
+ * curl -s https://app.example.com/maintenance/sql -H "authorization: Bearer $KEY" \
45
+ * -d '{"sql": "SELECT _id, text FROM message WHERE thread = $1", "params": ["t1"]}'
46
+ * ```
47
+ */
48
+ import { type Plugin } from "../../../runtime/mod.js";
49
+ export * from "./contract.js";
50
+ export { serveMaintenance } from "./resources/routes.js";
51
+ export declare const maintenance: Plugin;
52
+ export default maintenance;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Maintenance: HTTP endpoints for an app's operators, for when they can't
3
+ * reach its database themselves (a client's network that keeps their
4
+ * database user out). The one place an app runs SQL of its own.
5
+ *
6
+ * - **A key** (the `maintenance` resource's `key`, or several in `keys`
7
+ * while one rotates, from the app's environment): every request shows one
8
+ * (`Authorization: Bearer <key>`), compared in constant time. Without
9
+ * one, every request is unauthorized; a weak one stops the app. An orgs
10
+ * host's orgs don't get the plugin (one key would reach every org).
11
+ * - **A line for each request**, before it runs (`log`): who, what (a
12
+ * statement's hash), which key, when: a record outside the database.
13
+ * - **The maintenance actor** (`{ kind: "maintenance", id: "maintenance",
14
+ * by? }`): who every request acts as. Its Actions let only it call them,
15
+ * and run as the system on the record (`ctx.as()`: events say `via` it),
16
+ * so no rule keeps it from a document, and nothing else can act as it: a
17
+ * host binds actors, and none binds this one but these routes.
18
+ * - **Read SQL**, one read-only statement (`runtime.maintenance.read`, the
19
+ * store's `inspect`): at most `limit` rows and `bytes`, cut off after
20
+ * `timeout`. On a PostgreSQL server, as a role of its own
21
+ * (`postgresStore({ maintenance: { url } })`; the README's Maintenance).
22
+ * - **Writes through the owner**: the collections' operations (insertOne…
23
+ * deleteMany, and find…aggregate), checked against their schemas, recorded
24
+ * as events, cached and heard by Processors like any write; and the
25
+ * collections' named queries (`booking.stats`), read as the system.
26
+ * - **Raw SQL writes, inside the owner** (`runtime.maintenance.write`), for
27
+ * what operations can't do: one statement, in line with the owner's
28
+ * writes, fenced by its epoch, with one `maintenance.sql` audit event in
29
+ * the same commit; the owner then forgets what it derived from documents.
30
+ * It bypasses schemas and per-document events.
31
+ * - **Blobs by id**, as stored (in the store, or the app's Blobs).
32
+ *
33
+ * The endpoints are in `resources/routes.ts`; what raw SQL does to the
34
+ * owner, in `runtime/maintain.ts`.
35
+ *
36
+ * ```ts
37
+ * plugins: [...plugins, maintenance, definePlugin({
38
+ * name: "app",
39
+ * resources: { maintenance: { key: process.env.MAINTENANCE_KEY } },
40
+ * })]
41
+ * ```
42
+ *
43
+ * ```sh
44
+ * curl -s https://app.example.com/maintenance/sql -H "authorization: Bearer $KEY" \
45
+ * -d '{"sql": "SELECT _id, text FROM message WHERE thread = $1", "params": ["t1"]}'
46
+ * ```
47
+ */
48
+ import { definePlugin } from "../../../runtime/mod.js";
49
+ import { readAction } from "./actions/read.js";
50
+ import { writeAction } from "./actions/write.js";
51
+ import { route, settingsOf } from "./resources/routes.js";
52
+ export * from "./contract.js";
53
+ export { serveMaintenance } from "./resources/routes.js";
54
+ export const maintenance = definePlugin({
55
+ name: "maintenance",
56
+ actions: {
57
+ "maintenance.read": readAction,
58
+ "maintenance.write": writeAction,
59
+ },
60
+ resources: {
61
+ routes: { maintenance: route },
62
+ },
63
+ // A key too short to be safe stops the app from starting.
64
+ check: ({ resources }) => void settingsOf(resources),
65
+ });
66
+ export default maintenance;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The maintenance endpoints, the plugin's `routes` resource, under
3
+ * `/maintenance/`. Every request shows the app's one maintenance key
4
+ * (`Authorization: Bearer <key>`), compared in constant time, and acts as
5
+ * the maintenance actor; `X-Maintenance-By` says who sent it, for the
6
+ * record. JSON in and out, errors as `{ error: { code, message } }` with
7
+ * the status their code says; no CORS, so a page elsewhere can't call it.
8
+ *
9
+ * - `GET /maintenance/`: what's here: whether the store runs SQL, the
10
+ * collections, the limits, the endpoints.
11
+ * - `POST /maintenance/sql` `{ sql, params?, limit?, timeout? }`: one
12
+ * read-only statement on committed state: `{ rows, count, truncated, ms }`.
13
+ * - `POST /maintenance/sql/write` `{ sql, params?, limit?, timeout? }`: one
14
+ * statement that writes, run by the owner in line with its other writes,
15
+ * fenced, with its `maintenance.sql` audit event (runtime/maintain.ts):
16
+ * `{ changed, rows, truncated, event, ms }`. It bypasses schemas and
17
+ * per-document events: use the collections' operations when they can.
18
+ * - `POST /maintenance/collections/<collection>/<op>`: an operation through
19
+ * the owner's write path (the `maintenance.read` and `maintenance.write`
20
+ * Actions): insertOne `{ doc }`, insertMany `{ docs }`, updateOne and
21
+ * updateMany `{ filter, update, upsert? }`, replaceOne `{ filter, doc,
22
+ * upsert? }`, deleteOne and deleteMany `{ filter }` (all of them is
23
+ * `filter: {}`, said so); find `{ filter?, sort?, limit?, skip? }`,
24
+ * findOne `{ filter?, sort? }`, countDocuments `{ filter? }`, aggregate
25
+ * `{ pipeline }`.
26
+ * - `POST /maintenance/queries/<collection>.<name>`: a collection's named
27
+ * query (`booking.stats`), the body its params, read through the owner as
28
+ * the system on the record: `{ result, ms }`. It checks its params itself.
29
+ * - `GET /maintenance/blobs/<sha256-…>`: a blob's bytes and type, as a download.
30
+ *
31
+ * Writes take an `Idempotency-Key`: sent again, one answers what it did the
32
+ * first time, without doing it twice. Reads take at most the settings'
33
+ * `limit` rows and `timeout` ms, and may ask for less.
34
+ */
35
+ import { type Actor, type Resources, type Runtime } from "../../../../runtime/mod.js";
36
+ import type { MaintenanceLog } from "../contract.js";
37
+ type Settings = {
38
+ keys: string[];
39
+ limit: number;
40
+ timeout: number;
41
+ bytes: number;
42
+ log: (line: MaintenanceLog) => void;
43
+ /** An orgs host's org: maintenance doesn't serve one (one key would reach every org). */
44
+ org: boolean;
45
+ };
46
+ /** Why a key isn't one: too short, too few characters, or a short run repeated. */
47
+ export declare function weak(key: string): string | undefined;
48
+ export declare function settingsOf(resources: Resources): Settings;
49
+ /** Whether `given` is `key`, in time that tells nothing about either. */
50
+ export declare function sameKey(given: string, key: string): Promise<boolean>;
51
+ /** What the web host hands a `serve` route: the runtime, and who a session signs in (unused). */
52
+ type Served = {
53
+ runtime: Pick<Runtime, "call" | "describe" | "maintenance">;
54
+ whom?(): Promise<Actor | null>;
55
+ };
56
+ /**
57
+ * Rows within `bytes` of JSON: as many as fit, in order, and whether some
58
+ * were left out. What a read answers never grows past what the settings let.
59
+ */
60
+ export declare function fit<T>(rows: T[], bytes: number): {
61
+ rows: T[];
62
+ cut: boolean;
63
+ };
64
+ /** Answers a request under `/maintenance/`. */
65
+ export declare function serveMaintenance(request: Request, host?: Served): Promise<Response>;
66
+ /** The route the web host serves them at. */
67
+ export declare const route: {
68
+ path: string;
69
+ serve: typeof serveMaintenance;
70
+ };
71
+ export {};
@@ -0,0 +1,457 @@
1
+ /**
2
+ * The maintenance endpoints, the plugin's `routes` resource, under
3
+ * `/maintenance/`. Every request shows the app's one maintenance key
4
+ * (`Authorization: Bearer <key>`), compared in constant time, and acts as
5
+ * the maintenance actor; `X-Maintenance-By` says who sent it, for the
6
+ * record. JSON in and out, errors as `{ error: { code, message } }` with
7
+ * the status their code says; no CORS, so a page elsewhere can't call it.
8
+ *
9
+ * - `GET /maintenance/`: what's here: whether the store runs SQL, the
10
+ * collections, the limits, the endpoints.
11
+ * - `POST /maintenance/sql` `{ sql, params?, limit?, timeout? }`: one
12
+ * read-only statement on committed state: `{ rows, count, truncated, ms }`.
13
+ * - `POST /maintenance/sql/write` `{ sql, params?, limit?, timeout? }`: one
14
+ * statement that writes, run by the owner in line with its other writes,
15
+ * fenced, with its `maintenance.sql` audit event (runtime/maintain.ts):
16
+ * `{ changed, rows, truncated, event, ms }`. It bypasses schemas and
17
+ * per-document events: use the collections' operations when they can.
18
+ * - `POST /maintenance/collections/<collection>/<op>`: an operation through
19
+ * the owner's write path (the `maintenance.read` and `maintenance.write`
20
+ * Actions): insertOne `{ doc }`, insertMany `{ docs }`, updateOne and
21
+ * updateMany `{ filter, update, upsert? }`, replaceOne `{ filter, doc,
22
+ * upsert? }`, deleteOne and deleteMany `{ filter }` (all of them is
23
+ * `filter: {}`, said so); find `{ filter?, sort?, limit?, skip? }`,
24
+ * findOne `{ filter?, sort? }`, countDocuments `{ filter? }`, aggregate
25
+ * `{ pipeline }`.
26
+ * - `POST /maintenance/queries/<collection>.<name>`: a collection's named
27
+ * query (`booking.stats`), the body its params, read through the owner as
28
+ * the system on the record: `{ result, ms }`. It checks its params itself.
29
+ * - `GET /maintenance/blobs/<sha256-…>`: a blob's bytes and type, as a download.
30
+ *
31
+ * Writes take an `Idempotency-Key`: sent again, one answers what it did the
32
+ * first time, without doing it twice. Reads take at most the settings'
33
+ * `limit` rows and `timeout` ms, and may ask for less.
34
+ */
35
+ import { invalid, redacted, } from "../../../../runtime/mod.js";
36
+ import { isRead, READS } from "../actions/read.js";
37
+ import { isWrite, WRITES } from "../actions/write.js";
38
+ // The settings (the `maintenance` resource), with their defaults, checked.
39
+ /** A key shorter than this is refused at start: it would be guessable. */
40
+ const MIN_KEY = 32;
41
+ const positive = (value, name, fallback) => {
42
+ if (value === undefined || value === null)
43
+ return fallback;
44
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
45
+ throw invalid(`maintenance.${name} is a positive number`);
46
+ }
47
+ return Math.floor(value);
48
+ };
49
+ /** Why a key isn't one: too short, too few characters, or a short run repeated. */
50
+ export function weak(key) {
51
+ if (key.length < MIN_KEY)
52
+ return `at least ${MIN_KEY} characters`;
53
+ if (new Set(key).size < 10)
54
+ return "random: it uses too few characters";
55
+ for (let period = 1; period <= key.length / 2; period++) {
56
+ if ([...key].every((c, i) => c === key[i % period]))
57
+ return "random: it repeats itself";
58
+ }
59
+ }
60
+ export function settingsOf(resources) {
61
+ const set = (resources.maintenance ?? {});
62
+ const keys = [set.key, ...(set.keys ?? [])].filter((key) => key !== undefined && key !== "");
63
+ for (const key of keys) {
64
+ const why = typeof key === "string" ? weak(key) : "text";
65
+ if (why)
66
+ throw invalid(`A maintenance key must be ${why}: make one with 32 random bytes`);
67
+ }
68
+ const org = resources.org !== undefined && resources.org !== null;
69
+ if (org && keys.length) {
70
+ throw invalid("Maintenance doesn't serve an orgs host's orgs (one key would reach every org): leave " +
71
+ "it out of their plugins, or its key out of their settings.");
72
+ }
73
+ return {
74
+ keys: keys,
75
+ limit: positive(set.limit, "limit", 1_000),
76
+ timeout: positive(set.timeout, "timeout", 30_000),
77
+ bytes: positive(set.bytes, "bytes", 8 * 1024 * 1024),
78
+ log: typeof set.log === "function" ? set.log : (line) => console.log(JSON.stringify(line)),
79
+ org,
80
+ };
81
+ }
82
+ // The key a request shows, compared in constant time: both are hashed first, so the comparison
83
+ // takes as long whatever their lengths and wherever they differ.
84
+ const digest = async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
85
+ /** Whether `given` is `key`, in time that tells nothing about either. */
86
+ export async function sameKey(given, key) {
87
+ const [a, b] = await Promise.all([digest(given), digest(key)]);
88
+ let differ = 0;
89
+ for (let i = 0; i < a.length; i++)
90
+ differ |= a[i] ^ b[i];
91
+ return differ === 0;
92
+ }
93
+ /** Which of the keys `given` is (its place among them), comparing it with every one. */
94
+ async function keyOf(given, keys) {
95
+ let found;
96
+ for (const [i, key] of keys.entries())
97
+ if (await sameKey(given, key))
98
+ found ??= i;
99
+ return found;
100
+ }
101
+ /** A statement's SHA-256, hex: what the log line keeps of it. */
102
+ const hashOf = async (text) => [...await digest(text)].map((b) => b.toString(16).padStart(2, "0")).join("");
103
+ /** The key a request shows: a Bearer token, or undefined. */
104
+ function bearer(request) {
105
+ const [scheme, token, ...rest] = (request.headers.get("authorization") ?? "").trim().split(/\s+/);
106
+ return scheme?.toLowerCase() === "bearer" && token && !rest.length ? token : undefined;
107
+ }
108
+ // Answers: JSON (bytes as `{ base64 }`, big integers as strings), and bodies read within a limit.
109
+ /** The largest body taken: 16 MB. */
110
+ const MAX_BODY = 16 * 1024 * 1024;
111
+ /** The status each error code answers with. */
112
+ const STATUS = {
113
+ invalid: 400,
114
+ sql: 400,
115
+ read_only: 400,
116
+ unauthorized: 401,
117
+ forbidden: 403,
118
+ not_found: 404,
119
+ method: 405,
120
+ duplicate_key: 409,
121
+ id_conflict: 409,
122
+ too_large: 413,
123
+ unsupported: 501,
124
+ shared_schema: 501,
125
+ unsafe_role: 501,
126
+ busy: 503,
127
+ unavailable: 503,
128
+ fenced: 503,
129
+ timeout: 504,
130
+ };
131
+ const base64 = (bytes) => {
132
+ let binary = "";
133
+ for (let i = 0; i < bytes.length; i += 0x8000) {
134
+ binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
135
+ }
136
+ return btoa(binary);
137
+ };
138
+ /** What JSON can't say as it is: bytes, and integers too big for a number. */
139
+ const plain = (_key, value) => typeof value === "bigint"
140
+ ? value.toString()
141
+ : value instanceof Uint8Array
142
+ ? { base64: base64(value) }
143
+ : value;
144
+ const json = (value, status = 200, headers = {}) => new Response(JSON.stringify(value ?? null, plain), {
145
+ status,
146
+ headers: {
147
+ "content-type": "application/json; charset=utf-8",
148
+ "cache-control": "no-store",
149
+ ...headers,
150
+ },
151
+ });
152
+ /** An error as the endpoints say it. */
153
+ const failure = (status, code, message, headers = {}) => json({ error: { code, message } }, status, headers);
154
+ /** An error with a code: the endpoints' own, the runtime's, the stores'. */
155
+ const fault = (code, message) => Object.assign(new Error(message), { code });
156
+ /** What a thrown error answers: its code's status and its message; anything else, a 500. */
157
+ function answerFor(error) {
158
+ const code = error?.code;
159
+ const message = error instanceof Error ? error.message : String(error);
160
+ if (/^Unknown (action|collection|query)/.test(message)) {
161
+ return failure(404, "not_found", message);
162
+ }
163
+ if (typeof code === "string" && STATUS[code]) {
164
+ const state = error.state;
165
+ return json({ error: { code, message, ...(state !== undefined ? { state } : {}) } }, STATUS[code]);
166
+ }
167
+ console.error("maintenance:", message);
168
+ return failure(500, "internal", "Something went wrong.");
169
+ }
170
+ /** A request's JSON body, an object; none is `{}`. Refused past `MAX_BODY`. */
171
+ async function bodyOf(request) {
172
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_BODY) {
173
+ throw fault("too_large", "The body is too large (16 MB at most).");
174
+ }
175
+ const chunks = [];
176
+ let size = 0;
177
+ if (request.body) {
178
+ const reader = request.body.getReader();
179
+ for (;;) {
180
+ const { done, value } = await reader.read();
181
+ if (done)
182
+ break;
183
+ size += value.length;
184
+ if (size > MAX_BODY) {
185
+ await reader.cancel().catch(() => { });
186
+ throw fault("too_large", "The body is too large (16 MB at most).");
187
+ }
188
+ chunks.push(value);
189
+ }
190
+ }
191
+ const bytes = new Uint8Array(size);
192
+ let at = 0;
193
+ for (const chunk of chunks)
194
+ (bytes.set(chunk, at), at += chunk.length);
195
+ const text = new TextDecoder().decode(bytes);
196
+ if (!text.trim())
197
+ return {};
198
+ let body;
199
+ try {
200
+ body = JSON.parse(text);
201
+ }
202
+ catch {
203
+ throw fault("invalid", "The body isn't JSON.");
204
+ }
205
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
206
+ throw fault("invalid", "The body is a JSON object.");
207
+ }
208
+ return body;
209
+ }
210
+ const BLOB = /^sha256-[0-9a-f]{64}$/;
211
+ const unauthorized = () => failure(401, "unauthorized", "Show the maintenance key: `Authorization: Bearer <key>`.", {
212
+ "www-authenticate": 'Bearer realm="maintenance"',
213
+ });
214
+ /** Who sends it: the key's holder, by the name the request gives (as given). */
215
+ function actorOf(request) {
216
+ const by = request.headers.get("x-maintenance-by");
217
+ if (by === null)
218
+ return { kind: "maintenance", id: "maintenance" };
219
+ if (!/^[\x20-\x7e]{1,100}$/.test(by) || !by.trim()) {
220
+ throw fault("invalid", "X-Maintenance-By is a name: 1 to 100 visible ASCII characters.");
221
+ }
222
+ return { kind: "maintenance", id: "maintenance", by: by.trim() };
223
+ }
224
+ /** A write's id, from the caller's `Idempotency-Key`, apart for each kind of write. */
225
+ function idOf(request, kind) {
226
+ const given = request.headers.get("idempotency-key");
227
+ if (given === null)
228
+ return undefined;
229
+ if (!/^[\x21-\x7e]{1,200}$/.test(given)) {
230
+ throw fault("invalid", "An Idempotency-Key is 1 to 200 visible ASCII characters.");
231
+ }
232
+ return `maintenance:${kind}:${given}`;
233
+ }
234
+ /** Only these fields, so a misspelt one isn't quietly ignored. */
235
+ function only(body, fields) {
236
+ const other = Object.keys(body).find((field) => !fields.includes(field));
237
+ if (other)
238
+ throw fault("invalid", `Unknown field \`${other}\`: this takes ${fields.join(", ")}.`);
239
+ }
240
+ /** A whole number from 1 to `max`, or `max` when not given. */
241
+ function upTo(value, name, max) {
242
+ if (value === undefined)
243
+ return max;
244
+ if (!Number.isInteger(value) || value < 1 || value > max) {
245
+ throw fault("invalid", `\`${name}\` is a whole number from 1 to ${max}.`);
246
+ }
247
+ return value;
248
+ }
249
+ /** A SQL request's statement and options, checked against the settings. */
250
+ function sqlOf(body, settings) {
251
+ only(body, ["sql", "params", "limit", "timeout"]);
252
+ if (typeof body.sql !== "string" || !body.sql.trim()) {
253
+ throw fault("invalid", "`sql` is the statement, as text.");
254
+ }
255
+ if (body.params !== undefined && !Array.isArray(body.params)) {
256
+ throw fault("invalid", "`params` is a list, bound in order ($1, $2… or ?1, ?2…).");
257
+ }
258
+ return {
259
+ sql: body.sql,
260
+ ...(body.params !== undefined ? { params: body.params } : {}),
261
+ limit: upTo(body.limit, "limit", settings.limit),
262
+ timeout: upTo(body.timeout, "timeout", settings.timeout),
263
+ };
264
+ }
265
+ /**
266
+ * Rows within `bytes` of JSON: as many as fit, in order, and whether some
267
+ * were left out. What a read answers never grows past what the settings let.
268
+ */
269
+ export function fit(rows, bytes) {
270
+ const encoder = new TextEncoder();
271
+ let used = 2;
272
+ for (const [i, row] of rows.entries()) {
273
+ used += encoder.encode(JSON.stringify(row ?? null, plain)).length + 1;
274
+ if (used > bytes)
275
+ return { rows: rows.slice(0, i), cut: true };
276
+ }
277
+ return { rows, cut: false };
278
+ }
279
+ /** A single answer within `bytes`, or `too_large`. */
280
+ const within = (value, bytes) => {
281
+ if (new TextEncoder().encode(JSON.stringify(value ?? null, plain)).length > bytes) {
282
+ throw fault("too_large", `The answer is over ${bytes} bytes: ask for less.`);
283
+ }
284
+ return value;
285
+ };
286
+ /** Answers a request under `/maintenance/`. */
287
+ export async function serveMaintenance(request, host) {
288
+ if (!host?.runtime) {
289
+ return failure(501, "unavailable", "The web host doesn't hand this route the runtime.");
290
+ }
291
+ const { runtime } = host;
292
+ try {
293
+ const settings = settingsOf(runtime.describe().resources);
294
+ // No key, or an orgs host's org: as unauthorized as a wrong key, so nothing says it's here.
295
+ const given = bearer(request);
296
+ const key = given && settings.keys.length && !settings.org
297
+ ? await keyOf(given, settings.keys)
298
+ : undefined;
299
+ if (key === undefined)
300
+ return unauthorized();
301
+ const actor = actorOf(request);
302
+ const url = new URL(request.url);
303
+ const path = url.pathname.replace(/^\/maintenance\/?/, "/");
304
+ const method = (want) => {
305
+ if (request.method !== want)
306
+ throw fault("method", `Use ${want} for ${url.pathname}.`);
307
+ };
308
+ /** The request's line, before it runs: who, what, when. */
309
+ const log = (what, more = {}) => settings.log({
310
+ severity: "NOTICE",
311
+ maintenance: what,
312
+ ...(actor.by ? { by: actor.by } : {}),
313
+ ...more,
314
+ key,
315
+ at: new Date().toISOString(),
316
+ });
317
+ const { bytes } = settings;
318
+ if (path === "/") {
319
+ method("GET");
320
+ return json({
321
+ sql: runtime.maintenance.sql,
322
+ collections: Object.keys(runtime.describe().collections).sort(),
323
+ limit: settings.limit,
324
+ timeout: settings.timeout,
325
+ bytes,
326
+ endpoints: {
327
+ "POST /maintenance/sql": "{ sql, params?, limit?, timeout? }: one read-only statement",
328
+ "POST /maintenance/sql/write": "{ sql, params?, limit?, timeout? }: one that writes",
329
+ "POST /maintenance/collections/<collection>/<op>": [...WRITES, ...READS].join(", "),
330
+ "POST /maintenance/queries/<collection>.<name>": "a named query, the body its params",
331
+ "GET /maintenance/blobs/<id>": "a blob's bytes",
332
+ },
333
+ });
334
+ }
335
+ if (path === "/sql" || path === "/sql/write") {
336
+ method("POST");
337
+ const write = path === "/sql/write";
338
+ const { sql, ...options } = sqlOf(await bodyOf(request), settings);
339
+ log(write ? "sql.write" : "sql.read", {
340
+ sql: await hashOf(redacted(sql)),
341
+ params: options.params?.length ?? 0,
342
+ });
343
+ const started = performance.now();
344
+ if (!write) {
345
+ try {
346
+ // The store stops fetching once the rows pass the bytes this answer may take.
347
+ const read = await runtime.maintenance.read(sql, { ...options, bytes });
348
+ const { rows, cut } = fit(read.rows, bytes);
349
+ return json({
350
+ rows,
351
+ count: rows.length,
352
+ truncated: read.truncated || cut,
353
+ ms: elapsed(started),
354
+ // On the store's own connection, one at a time, with no timeout (SQLite).
355
+ ...(read.inline ? { inline: true } : {}),
356
+ });
357
+ }
358
+ catch (error) {
359
+ const code = error.code;
360
+ if (code !== "read_only")
361
+ throw error;
362
+ throw fault(code, `${error.message} (this endpoint reads: /sql/write writes)`);
363
+ }
364
+ }
365
+ const id = idOf(request, "sql");
366
+ const done = await runtime.maintenance.write(sql, {
367
+ ...options,
368
+ actor,
369
+ ...(id ? { id } : {}),
370
+ });
371
+ const { rows, cut } = fit(done.rows, bytes);
372
+ return json({
373
+ changed: done.changed,
374
+ rows,
375
+ truncated: done.truncated || cut,
376
+ event: { id: done.event.id, seq: done.event.seq, at: done.event.at },
377
+ ms: elapsed(started),
378
+ ...(done.repeated ? { repeated: true } : {}),
379
+ });
380
+ }
381
+ const operation = /^\/collections\/([^/]+)\/([^/]+)$/.exec(path);
382
+ if (operation) {
383
+ method("POST");
384
+ const [collection, op] = operation.slice(1).map(decodeURIComponent);
385
+ const body = await bodyOf(request);
386
+ if (isWrite(op)) {
387
+ only(body, ["doc", "docs", "filter", "update", "upsert"]);
388
+ const id = idOf(request, "op");
389
+ log("op", { collection, op });
390
+ return json(await runtime.call("maintenance.write", { ...body, collection, op }, { actor, ...(id ? { id } : {}) }));
391
+ }
392
+ if (isRead(op)) {
393
+ only(body, ["filter", "sort", "limit", "skip", "pipeline"]);
394
+ const limit = upTo(body.limit, "limit", settings.limit);
395
+ log("op", { collection, op });
396
+ const read = await runtime.call("maintenance.read", { ...body, collection, op, limit }, { actor });
397
+ if (!Array.isArray(read.docs))
398
+ return json(within(read, bytes));
399
+ const { rows, cut } = fit(read.docs, bytes);
400
+ return json({ ...read, docs: rows, truncated: Boolean(read.truncated) || cut });
401
+ }
402
+ throw fault("not_found", `No operation "${op}": ${[...WRITES, ...READS].join(", ")}.`);
403
+ }
404
+ const query = /^\/queries\/([^/]+)$/.exec(path);
405
+ if (query) {
406
+ method("POST");
407
+ const named = decodeURIComponent(query[1]);
408
+ const dot = named.lastIndexOf(".");
409
+ if (dot <= 0 || dot === named.length - 1) {
410
+ throw fault("not_found", `No query "${named}": name it <collection>.<query>.`);
411
+ }
412
+ const params = await bodyOf(request);
413
+ log("query", { query: named });
414
+ const started = performance.now();
415
+ const { result } = await runtime.call("maintenance.read", {
416
+ collection: named.slice(0, dot),
417
+ op: "query",
418
+ name: named.slice(dot + 1),
419
+ params,
420
+ }, { actor });
421
+ if (!Array.isArray(result)) {
422
+ return json({ result: within(result, bytes), ms: elapsed(started) });
423
+ }
424
+ const { rows, cut } = fit(result, bytes);
425
+ return json({ result: rows, ...(cut ? { truncated: true } : {}), ms: elapsed(started) });
426
+ }
427
+ const blob = /^\/blobs\/([^/]+)$/.exec(path);
428
+ if (blob) {
429
+ method("GET");
430
+ const id = decodeURIComponent(blob[1]);
431
+ if (!BLOB.test(id))
432
+ throw fault("invalid", "A blob's id is sha256- and 64 hex digits.");
433
+ log("blob", { blob: id });
434
+ const found = await runtime.maintenance.blob(id);
435
+ if (!found)
436
+ throw fault("not_found", `No blob ${id}.`);
437
+ return new Response(found.data, {
438
+ headers: {
439
+ "content-type": found.type || "application/octet-stream",
440
+ "content-length": String(found.data.length),
441
+ // Never shown at the app's address, whatever it holds: saved, as a file.
442
+ "content-disposition": `attachment; filename="${id}"`,
443
+ "x-content-type-options": "nosniff",
444
+ "content-security-policy": "sandbox",
445
+ "cache-control": "no-store",
446
+ },
447
+ });
448
+ }
449
+ throw fault("not_found", `Nothing at ${url.pathname}: see GET /maintenance/ for what's here.`);
450
+ }
451
+ catch (error) {
452
+ return answerFor(error);
453
+ }
454
+ }
455
+ const elapsed = (started) => Math.round((performance.now() - started) * 100) / 100;
456
+ /** The route the web host serves them at. */
457
+ export const route = { path: "/maintenance/", serve: serveMaintenance };
@@ -0,0 +1,4 @@
1
+ /** A collection maintenance may name: a declared one, not the runtime's own. */
2
+ export declare function own(collection: string): string;
3
+ /** A field an operation needs. */
4
+ export declare function needs<T>(value: T | undefined, op: string, field: string): T;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What both maintenance Actions hold to: the collections their operations
3
+ * reach (declared ones, never the runtime's own `sys.*`, which only SQL
4
+ * reaches), and the fields each operation needs.
5
+ */
6
+ import { invalid } from "../../../../runtime/mod.js";
7
+ /** A collection maintenance may name: a declared one, not the runtime's own. */
8
+ export function own(collection) {
9
+ if (collection.startsWith("sys.")) {
10
+ throw invalid(`"${collection}" is the runtime's own: its operations don't reach it.`);
11
+ }
12
+ return collection;
13
+ }
14
+ /** A field an operation needs. */
15
+ export function needs(value, op, field) {
16
+ if (value === undefined)
17
+ throw invalid(`${op} takes \`${field}\`.`);
18
+ return value;
19
+ }