@cossackframework/cms 0.0.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (427) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/agent-docs.json +259 -0
  4. package/app/README.md +78 -0
  5. package/app/cossack-recipe.json +43 -0
  6. package/app/src/auth-bot-check.ts +32 -0
  7. package/app/src/auth-bot-token.ts +11 -0
  8. package/app/src/auth-input.ts +35 -0
  9. package/app/src/auth-options.ts +18 -0
  10. package/app/src/auth-providers.ts +16 -0
  11. package/app/src/auth.ts +1082 -0
  12. package/app/src/brand.ts +68 -0
  13. package/app/src/cms/ai.ts +54 -0
  14. package/app/src/cms/analytics.ts +33 -0
  15. package/app/src/cms/block-errors.ts +55 -0
  16. package/app/src/cms/block-inserter.ts +111 -0
  17. package/app/src/cms/block-panel.ts +68 -0
  18. package/app/src/cms/block-rows.ts +44 -0
  19. package/app/src/cms/block-tree.ts +585 -0
  20. package/app/src/cms/blocks.css +708 -0
  21. package/app/src/cms/builder.ts +126 -0
  22. package/app/src/cms/cache.ts +44 -0
  23. package/app/src/cms/carousel.client.ts +52 -0
  24. package/app/src/cms/collab/presence.ts +69 -0
  25. package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
  26. package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
  27. package/app/src/cms/collab/room.ts +881 -0
  28. package/app/src/cms/compare.client.ts +47 -0
  29. package/app/src/cms/condition-control.ts +109 -0
  30. package/app/src/cms/content-api.ts +143 -0
  31. package/app/src/cms/content.ts +524 -0
  32. package/app/src/cms/countdown.client.ts +37 -0
  33. package/app/src/cms/editor-layout-editor.ts +260 -0
  34. package/app/src/cms/editor-layout-view.ts +37 -0
  35. package/app/src/cms/editor.ts +381 -0
  36. package/app/src/cms/entry.ts +26 -0
  37. package/app/src/cms/feeds.ts +145 -0
  38. package/app/src/cms/field-controls.ts +222 -0
  39. package/app/src/cms/field-group-editor.ts +105 -0
  40. package/app/src/cms/field-group-view.ts +211 -0
  41. package/app/src/cms/form-view.ts +203 -0
  42. package/app/src/cms/form.client.ts +203 -0
  43. package/app/src/cms/guards.ts +27 -0
  44. package/app/src/cms/handoff.ts +202 -0
  45. package/app/src/cms/headings.ts +51 -0
  46. package/app/src/cms/icons.ts +80 -0
  47. package/app/src/cms/import.client.ts +16 -0
  48. package/app/src/cms/index.ts +191 -0
  49. package/app/src/cms/lightbox.client.ts +109 -0
  50. package/app/src/cms/machine.ts +118 -0
  51. package/app/src/cms/maintenance.ts +97 -0
  52. package/app/src/cms/manage.ts +1236 -0
  53. package/app/src/cms/mcp-tools.ts +388 -0
  54. package/app/src/cms/mcp.ts +242 -0
  55. package/app/src/cms/media-chooser.ts +123 -0
  56. package/app/src/cms/media-usage.ts +57 -0
  57. package/app/src/cms/middleware.ts +199 -0
  58. package/app/src/cms/middlewares.ts +13 -0
  59. package/app/src/cms/network-ui.ts +36 -0
  60. package/app/src/cms/network-view.ts +38 -0
  61. package/app/src/cms/notes-announce.ts +65 -0
  62. package/app/src/cms/notes-rail.ts +207 -0
  63. package/app/src/cms/notification-rules.ts +66 -0
  64. package/app/src/cms/recovery.ts +82 -0
  65. package/app/src/cms/replace.ts +63 -0
  66. package/app/src/cms/reserved-paths.ts +19 -0
  67. package/app/src/cms/rich-text-field.ts +325 -0
  68. package/app/src/cms/rich-text-schema.ts +91 -0
  69. package/app/src/cms/rich-text.client.ts +255 -0
  70. package/app/src/cms/search.client.ts +116 -0
  71. package/app/src/cms/seo-head.ts +78 -0
  72. package/app/src/cms/seo.ts +241 -0
  73. package/app/src/cms/settings-draft.ts +218 -0
  74. package/app/src/cms/settings-file.ts +127 -0
  75. package/app/src/cms/settings-form.ts +180 -0
  76. package/app/src/cms/settings-languages.ts +125 -0
  77. package/app/src/cms/settings-nav.ts +102 -0
  78. package/app/src/cms/settings-network.ts +151 -0
  79. package/app/src/cms/settings-permalinks.ts +114 -0
  80. package/app/src/cms/settings-scroll.ts +10 -0
  81. package/app/src/cms/settings-search.ts +77 -0
  82. package/app/src/cms/settings-section.ts +38 -0
  83. package/app/src/cms/share.client.ts +27 -0
  84. package/app/src/cms/site-editing.ts +219 -0
  85. package/app/src/cms/site-editor.client.ts +1008 -0
  86. package/app/src/cms/site-editor.ts +99 -0
  87. package/app/src/cms/site-export.ts +60 -0
  88. package/app/src/cms/site-forms.ts +143 -0
  89. package/app/src/cms/site-import.ts +28 -0
  90. package/app/src/cms/site-session.ts +36 -0
  91. package/app/src/cms/site-taskbar.ts +77 -0
  92. package/app/src/cms/site-view.ts +1014 -0
  93. package/app/src/cms/site.ts +1322 -0
  94. package/app/src/cms/sitemaps.ts +131 -0
  95. package/app/src/cms/stat.client.ts +56 -0
  96. package/app/src/cms/style-controls.ts +252 -0
  97. package/app/src/cms/tabs.client.ts +36 -0
  98. package/app/src/cms/taskbar.ts +134 -0
  99. package/app/src/cms/term-icons.ts +10 -0
  100. package/app/src/cms/traffic.ts +26 -0
  101. package/app/src/cms/ui.ts +170 -0
  102. package/app/src/cms/updates.ts +124 -0
  103. package/app/src/cms/uploads.ts +26 -0
  104. package/app/src/cms/worker.ts +13 -0
  105. package/app/src/config/auth.ts +30 -0
  106. package/app/src/config/cms.ts +18 -0
  107. package/app/src/dashboard/access.ts +344 -0
  108. package/app/src/dashboard/agent-icons.ts +44 -0
  109. package/app/src/dashboard/app-passwords.ts +74 -0
  110. package/app/src/dashboard/avatar-field.ts +58 -0
  111. package/app/src/dashboard/bulk.ts +53 -0
  112. package/app/src/dashboard/head.ts +29 -0
  113. package/app/src/dashboard/icons.ts +15 -0
  114. package/app/src/dashboard/list-table.ts +120 -0
  115. package/app/src/dashboard/modules/roles.ts +15 -0
  116. package/app/src/dashboard/modules/sessions.ts +15 -0
  117. package/app/src/dashboard/modules/settings.ts +15 -0
  118. package/app/src/dashboard/modules/users.ts +18 -0
  119. package/app/src/dashboard/page.ts +67 -0
  120. package/app/src/dashboard/registry.ts +13 -0
  121. package/app/src/dashboard/session-list.ts +98 -0
  122. package/app/src/dashboard/tabs.ts +26 -0
  123. package/app/src/dashboard/time-ago.ts +16 -0
  124. package/app/src/dashboard/types.ts +40 -0
  125. package/app/src/dashboard/user-sections.ts +172 -0
  126. package/app/src/lib/permissions.ts +84 -0
  127. package/app/src/middlewares/auth.ts +117 -0
  128. package/app/src/pages/(site)/[...path]/index.ts +609 -0
  129. package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
  130. package/app/src/pages/(site)/feed/index.ts +12 -0
  131. package/app/src/pages/(site)/index.ts +11 -0
  132. package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
  133. package/app/src/pages/(site)/layout.ts +219 -0
  134. package/app/src/pages/(site)/llms.txt/index.ts +23 -0
  135. package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
  136. package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
  137. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
  138. package/app/src/pages/(site)/robots.txt/index.ts +29 -0
  139. package/app/src/pages/(site)/search/index.ts +36 -0
  140. package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
  141. package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
  142. package/app/src/pages/api/auth/session.ts +48 -0
  143. package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
  144. package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
  145. package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
  146. package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
  147. package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
  148. package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
  149. package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
  150. package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
  151. package/app/src/pages/api/cms/cache/purge.ts +6 -0
  152. package/app/src/pages/api/cms/collections/index.ts +6 -0
  153. package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
  154. package/app/src/pages/api/cms/comments/[id].ts +9 -0
  155. package/app/src/pages/api/cms/comments/index.ts +126 -0
  156. package/app/src/pages/api/cms/comments/queue.ts +6 -0
  157. package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
  158. package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
  159. package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
  160. package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
  161. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
  162. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
  163. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
  164. package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
  165. package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
  166. package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
  167. package/app/src/pages/api/cms/export/[collection].ts +37 -0
  168. package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
  169. package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
  170. package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
  171. package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
  172. package/app/src/pages/api/cms/import/[collection].ts +23 -0
  173. package/app/src/pages/api/cms/mcp.ts +29 -0
  174. package/app/src/pages/api/cms/me/index.ts +6 -0
  175. package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
  176. package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
  177. package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
  178. package/app/src/pages/api/cms/media/[id].ts +6 -0
  179. package/app/src/pages/api/cms/media.ts +26 -0
  180. package/app/src/pages/api/cms/menus/[location].ts +14 -0
  181. package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
  182. package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
  183. package/app/src/pages/api/cms/network/sites/index.ts +14 -0
  184. package/app/src/pages/api/cms/notes/[id].ts +13 -0
  185. package/app/src/pages/api/cms/notes/index.ts +6 -0
  186. package/app/src/pages/api/cms/payments/webhook.ts +28 -0
  187. package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
  188. package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
  189. package/app/src/pages/api/cms/plugins/index.ts +6 -0
  190. package/app/src/pages/api/cms/recovery.ts +29 -0
  191. package/app/src/pages/api/cms/redirects/index.ts +9 -0
  192. package/app/src/pages/api/cms/roles/index.ts +6 -0
  193. package/app/src/pages/api/cms/schema/[collection].ts +13 -0
  194. package/app/src/pages/api/cms/search.ts +16 -0
  195. package/app/src/pages/api/cms/settings/[group].ts +9 -0
  196. package/app/src/pages/api/cms/settings/index.ts +9 -0
  197. package/app/src/pages/api/cms/site-export.ts +34 -0
  198. package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
  199. package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
  200. package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
  201. package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
  202. package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
  203. package/app/src/pages/api/cms/uploads/index.ts +26 -0
  204. package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
  205. package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
  206. package/app/src/pages/api/cms/users/index.ts +12 -0
  207. package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
  208. package/app/src/pages/api/cms/webhooks/index.ts +9 -0
  209. package/app/src/pages/auth/[provider]/callback.ts +11 -0
  210. package/app/src/pages/auth/[provider]/redirect.ts +9 -0
  211. package/app/src/pages/auth/forgot-password/index.ts +75 -0
  212. package/app/src/pages/auth/layout.ts +32 -0
  213. package/app/src/pages/auth/login/index.ts +198 -0
  214. package/app/src/pages/auth/magic/index.ts +68 -0
  215. package/app/src/pages/auth/register/index.ts +117 -0
  216. package/app/src/pages/auth/reset-password/index.ts +65 -0
  217. package/app/src/pages/auth/setup/index.ts +194 -0
  218. package/app/src/pages/auth/two-factor/index.ts +67 -0
  219. package/app/src/pages/auth/verify/index.ts +62 -0
  220. package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
  221. package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
  222. package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
  223. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
  224. package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
  225. package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
  226. package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
  227. package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
  228. package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
  229. package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
  230. package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
  231. package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
  232. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
  233. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
  234. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
  235. package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
  236. package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
  237. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
  238. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
  239. package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
  240. package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
  241. package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
  242. package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
  243. package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
  244. package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
  245. package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
  246. package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
  247. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
  248. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
  249. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
  250. package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
  251. package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
  252. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
  253. package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
  254. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
  255. package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
  256. package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
  257. package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
  258. package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
  259. package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
  260. package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
  261. package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
  262. package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
  263. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
  264. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
  265. package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
  266. package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
  267. package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
  268. package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
  269. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
  270. package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
  271. package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
  272. package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
  273. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
  274. package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
  275. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
  276. package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
  277. package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +182 -0
  278. package/app/src/pages/dashboard/index.ts +214 -0
  279. package/app/src/pages/dashboard/layout.ts +320 -0
  280. package/app/src/pages/dashboard/profile/index.ts +211 -0
  281. package/app/src/pages/dashboard/profile/security/index.ts +255 -0
  282. package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
  283. package/app/src/pages/dashboard/roles/index.ts +134 -0
  284. package/app/src/pages/dashboard/roles/new/index.ts +95 -0
  285. package/app/src/pages/dashboard/sessions/index.ts +105 -0
  286. package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
  287. package/app/src/pages/dashboard/users/index.ts +299 -0
  288. package/app/src/pages/dashboard/users/new/index.ts +123 -0
  289. package/app/src/passkeys.client.ts +18 -0
  290. package/app/src/plugins/default-theme/assets/cover.svg +31 -0
  291. package/app/src/plugins/default-theme/assets/logo.svg +8 -0
  292. package/app/src/plugins/default-theme/parts/comments.ts +66 -0
  293. package/app/src/plugins/default-theme/parts/list.ts +38 -0
  294. package/app/src/plugins/default-theme/parts/media.ts +15 -0
  295. package/app/src/plugins/default-theme/parts/options.ts +45 -0
  296. package/app/src/plugins/default-theme/plugin.json +275 -0
  297. package/app/src/plugins/default-theme/templates/archive.ts +14 -0
  298. package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
  299. package/app/src/plugins/default-theme/templates/entry.ts +27 -0
  300. package/app/src/plugins/default-theme/templates/home.ts +8 -0
  301. package/app/src/plugins/default-theme/templates/layout.ts +40 -0
  302. package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
  303. package/app/src/plugins/default-theme/templates/search.ts +32 -0
  304. package/app/src/services/rbac.ts +65 -0
  305. package/app/src/services/roles.ts +89 -0
  306. package/app/src/services/users.ts +173 -0
  307. package/package.json +114 -2
  308. package/src/automations.ts +95 -0
  309. package/src/bindings.ts +138 -0
  310. package/src/block-references.ts +239 -0
  311. package/src/block-shape.ts +155 -0
  312. package/src/blocks.ts +1157 -0
  313. package/src/cache.ts +54 -0
  314. package/src/checks.ts +198 -0
  315. package/src/cloudflare-workers.d.ts +13 -0
  316. package/src/cloudflare.ts +61 -0
  317. package/src/collab.ts +372 -0
  318. package/src/collections.ts +421 -0
  319. package/src/comments.ts +46 -0
  320. package/src/cron.ts +95 -0
  321. package/src/dashboard-menu.ts +105 -0
  322. package/src/diff.ts +113 -0
  323. package/src/editor-layout.ts +316 -0
  324. package/src/errors.ts +50 -0
  325. package/src/field-groups.ts +498 -0
  326. package/src/fields.ts +411 -0
  327. package/src/form-builder.ts +1053 -0
  328. package/src/forms.ts +109 -0
  329. package/src/highlight.ts +134 -0
  330. package/src/hooks.ts +510 -0
  331. package/src/icon-catalog.ts +55 -0
  332. package/src/icons.ts +128 -0
  333. package/src/images.ts +149 -0
  334. package/src/index.ts +100 -0
  335. package/src/isolate-core.ts +245 -0
  336. package/src/isolate.ts +19 -0
  337. package/src/isolation.ts +69 -0
  338. package/src/mail.ts +182 -0
  339. package/src/manifest.ts +476 -0
  340. package/src/media.ts +193 -0
  341. package/src/menus.ts +287 -0
  342. package/src/module.ts +32 -0
  343. package/src/modules/content.ts +64 -0
  344. package/src/modules/forms.ts +35 -0
  345. package/src/node.ts +66 -0
  346. package/src/notes.ts +237 -0
  347. package/src/permissions.ts +139 -0
  348. package/src/plugin-settings.ts +114 -0
  349. package/src/records.ts +56 -0
  350. package/src/redirects.ts +59 -0
  351. package/src/resource.ts +245 -0
  352. package/src/richtext.ts +402 -0
  353. package/src/schema-json.ts +112 -0
  354. package/src/search.ts +89 -0
  355. package/src/seo.ts +477 -0
  356. package/src/server/accounts.ts +418 -0
  357. package/src/server/ai.ts +33 -0
  358. package/src/server/api-tokens.ts +91 -0
  359. package/src/server/areas.ts +116 -0
  360. package/src/server/audit.ts +94 -0
  361. package/src/server/auth.ts +89 -0
  362. package/src/server/automations.ts +190 -0
  363. package/src/server/autosaves.ts +69 -0
  364. package/src/server/brand-icons.ts +50 -0
  365. package/src/server/brands.ts +86 -0
  366. package/src/server/budget.ts +97 -0
  367. package/src/server/cache.ts +104 -0
  368. package/src/server/capabilities.ts +333 -0
  369. package/src/server/cloudflare.ts +92 -0
  370. package/src/server/comments.ts +237 -0
  371. package/src/server/drafts.ts +176 -0
  372. package/src/server/field-groups.ts +88 -0
  373. package/src/server/files.ts +780 -0
  374. package/src/server/forms.ts +726 -0
  375. package/src/server/handoffs.ts +107 -0
  376. package/src/server/host-schema.ts +312 -0
  377. package/src/server/host.ts +2892 -0
  378. package/src/server/images.ts +34 -0
  379. package/src/server/index.ts +59 -0
  380. package/src/server/indexnow.ts +91 -0
  381. package/src/server/isolation.ts +183 -0
  382. package/src/server/locked.ts +45 -0
  383. package/src/server/mail.ts +93 -0
  384. package/src/server/markdown.ts +24 -0
  385. package/src/server/menus.ts +286 -0
  386. package/src/server/network-policy.ts +60 -0
  387. package/src/server/network.ts +665 -0
  388. package/src/server/notes.ts +275 -0
  389. package/src/server/outbox.ts +213 -0
  390. package/src/server/path-moves.ts +33 -0
  391. package/src/server/payments.ts +59 -0
  392. package/src/server/previews.ts +62 -0
  393. package/src/server/purge.ts +140 -0
  394. package/src/server/reconcile.ts +38 -0
  395. package/src/server/redirects.ts +183 -0
  396. package/src/server/repository.ts +1107 -0
  397. package/src/server/schedules.ts +105 -0
  398. package/src/server/schema.ts +562 -0
  399. package/src/server/security.ts +391 -0
  400. package/src/server/seed.ts +52 -0
  401. package/src/server/shared-fields.ts +34 -0
  402. package/src/server/site-export.ts +151 -0
  403. package/src/server/site-import.ts +482 -0
  404. package/src/server/site-search.ts +289 -0
  405. package/src/server/site-settings.ts +286 -0
  406. package/src/server/sites.ts +243 -0
  407. package/src/server/stores.ts +314 -0
  408. package/src/server/stripe.ts +173 -0
  409. package/src/server/taxonomies.ts +415 -0
  410. package/src/server/tokens.ts +25 -0
  411. package/src/server/traffic.ts +118 -0
  412. package/src/server/users.ts +653 -0
  413. package/src/server/webhooks.ts +245 -0
  414. package/src/settings-controls.ts +54 -0
  415. package/src/settings-document.ts +111 -0
  416. package/src/settings.ts +426 -0
  417. package/src/storage/cloudflare.ts +94 -0
  418. package/src/storage/index.ts +30 -0
  419. package/src/storage/node.ts +114 -0
  420. package/src/taxonomy.ts +51 -0
  421. package/src/theme.ts +1135 -0
  422. package/src/to-markdown.ts +179 -0
  423. package/src/updates.ts +126 -0
  424. package/src/version.ts +2 -0
  425. package/src/vite.d.ts +25 -0
  426. package/src/vite.js +199 -0
  427. package/src/webhooks.ts +107 -0
@@ -0,0 +1,243 @@
1
+ /**
2
+ * The site registry on the network database. Each added site has its own database, named by
3
+ * `database`, and answers on its domains: one primary, the rest aliases that redirect to it.
4
+ * The main site is the network database itself; it has no row, but may own domains.
5
+ */
6
+ import { ClientError, type RomeDB, type Value } from '@cossackframework/romedb';
7
+ import { CmsError } from '../errors';
8
+ import { MAIN_SITE } from '../permissions';
9
+ import { inList } from './users';
10
+
11
+ /** The main site: the network database, with no registry row. */
12
+ export { MAIN_SITE };
13
+
14
+ export type SiteStatus = 'creating' | 'active' | 'archived' | 'deleted';
15
+
16
+ export interface SiteDomain {
17
+ /** A host name without port, lowercase, such as `blog.example.com`. */
18
+ readonly host: string;
19
+ readonly primary: boolean;
20
+ /** When the domain answered its check; null until then. */
21
+ readonly verifiedAt: number | null;
22
+ }
23
+
24
+ export interface SiteRecord {
25
+ readonly id: string;
26
+ readonly name: string;
27
+ /** The site database's ID with its provider (a file name, or a Cloud database ID). */
28
+ readonly database: string;
29
+ readonly status: SiteStatus;
30
+ /** The last finished creation step, while `status` is `creating`. */
31
+ readonly step: string | null;
32
+ readonly domains: readonly SiteDomain[];
33
+ readonly createdAt: number;
34
+ readonly updatedAt: number;
35
+ readonly deletedAt: number | null;
36
+ }
37
+
38
+ const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
39
+ /** IDs no added site takes: the main site's, and `new`, the dashboard's Add site address. */
40
+ export const RESERVED_SITE_IDS: ReadonlySet<string> = new Set([MAIN_SITE, 'new']);
41
+ const DATABASE = /^[A-Za-z0-9_-]{1,80}$/;
42
+ const HOST = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
43
+ const STATUSES: readonly SiteStatus[] = ['creating', 'active', 'archived', 'deleted'];
44
+ const COLUMNS = 'id, name, database, status, step, created_at, updated_at, deleted_at';
45
+ const WRITE = { kind: 'cms.sites', retryConflicts: 5 } as const;
46
+
47
+ /** A host as the registry stores it: lowercase, without port or trailing dot. Empty when invalid. */
48
+ export function siteHost(host: string): string {
49
+ const name = String(host ?? '').trim().toLowerCase().replace(/^\[[^\]]*\]/, '').replace(/:\d+$/, '').replace(/\.$/, '');
50
+ return HOST.test(name) ? name : '';
51
+ }
52
+
53
+ export class CmsSites {
54
+ readonly #db: RomeDB;
55
+ readonly #now: () => number;
56
+
57
+ constructor(db: RomeDB, options: { now?: () => number } = {}) {
58
+ this.#db = db;
59
+ this.#now = options.now ?? Date.now;
60
+ }
61
+
62
+ /** Added sites, deleted ones included: zero while the network is only the main site. */
63
+ async count(): Promise<number> {
64
+ const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_sites' }]);
65
+ return Number(result.results[0]!.rows[0]![0] as bigint);
66
+ }
67
+
68
+ async get(id: string): Promise<SiteRecord | null> {
69
+ if (!ID.test(id) || id === MAIN_SITE) return null;
70
+ return (await this.#many([id]))[0] ?? null;
71
+ }
72
+
73
+ /** The added sites among the IDs, in one read; unknown IDs and the main site are left out. */
74
+ async getMany(ids: readonly string[]): Promise<SiteRecord[]> {
75
+ const wanted = [...new Set(ids.filter(id => ID.test(id) && id !== MAIN_SITE))];
76
+ return wanted.length ? this.#many(wanted) : [];
77
+ }
78
+
79
+ /** Newest first. `search` matches the name or a domain. */
80
+ async list(options: { search?: string; status?: SiteStatus; limit?: number; offset?: number } = {}): Promise<{ items: SiteRecord[]; total: number }> {
81
+ const conditions: string[] = [];
82
+ const params: { [key: string]: Value } = {};
83
+ if (options.search?.trim()) {
84
+ conditions.push("(lower(name) LIKE $q ESCAPE '\\' OR id IN (SELECT site_id FROM cms_site_domains WHERE host LIKE $q ESCAPE '\\'))");
85
+ params.$q = `%${options.search.trim().toLowerCase().slice(0, 100).replace(/[\\%_]/g, character => `\\${character}`)}%`;
86
+ }
87
+ if (options.status) { conditions.push('status = $status'); params.$status = options.status; }
88
+ const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
89
+ const result = await this.#db.read([
90
+ { rql: `SELECT id FROM cms_sites${where} ORDER BY created_at DESC, id LIMIT $limit OFFSET $offset`, params: { ...params, $limit: Math.min(Math.max(options.limit ?? 20, 1), 100), $offset: Math.max(options.offset ?? 0, 0) } },
91
+ { rql: `SELECT count(*) FROM cms_sites${where}`, params },
92
+ ]);
93
+ return { items: await this.#many(result.results[0]!.rows.map(row => row[0] as string)), total: Number(result.results[1]!.rows[0]![0] as bigint) };
94
+ }
95
+
96
+ /** Active and archived sites in ID order, starting after `after` and wrapping around: scheduled work visits them in turn. */
97
+ async inTurn(after: string, limit = 50): Promise<SiteRecord[]> {
98
+ const result = await this.#db.read([{ rql: "SELECT id FROM cms_sites WHERE status IN ('active', 'archived') ORDER BY id <= $after, id LIMIT $limit",
99
+ params: { $after: after, $limit: Math.min(Math.max(limit, 1), 200) } }]);
100
+ return this.#many(result.results[0]!.rows.map(row => row[0] as string));
101
+ }
102
+
103
+ /** The site a host belongs to, `main` for the main site's own domains, or null. */
104
+ async siteOf(host: string): Promise<{ site: string; domain: SiteDomain } | null> {
105
+ const name = siteHost(host);
106
+ if (!name) return null;
107
+ const result = await this.#db.read([{ rql: 'SELECT site_id, host, is_primary, verified_at FROM cms_site_domains WHERE host = $host', params: { $host: name } }]);
108
+ const row = result.results[0]!.rows[0];
109
+ return row ? { site: row[0] as string, domain: domainOf(row.slice(1)) } : null;
110
+ }
111
+
112
+ /**
113
+ * Register a site and its domains in one write. The first domain is primary unless one
114
+ * says otherwise. A domain another site has is a conflict.
115
+ */
116
+ async create(input: { id: string; name: string; database: string; status?: SiteStatus; step?: string | null; domains: readonly { host: string; primary?: boolean; verifiedAt?: number | null }[] }): Promise<SiteRecord> {
117
+ if (!ID.test(input.id) || RESERVED_SITE_IDS.has(input.id)) throw new CmsError('CMS_VALIDATION', 'Site IDs are lowercase letters, digits and hyphens, other than main and new.', { fields: { id: 'is invalid.' } });
118
+ if (!DATABASE.test(input.database)) throw new CmsError('CMS_VALIDATION', 'Invalid database ID.');
119
+ checkName(input.name);
120
+ const status = input.status ?? 'active';
121
+ if (!STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown site status.');
122
+ const domains = checkDomains(input.domains);
123
+ const now = this.#now();
124
+ try {
125
+ await this.#db.write([
126
+ { rql: 'INSERT INTO cms_sites (id, name, database, status, step, created_at, updated_at) VALUES ($id, $name, $database, $status, $step, $now, $now)',
127
+ params: { $id: input.id, $name: input.name.trim(), $database: input.database, $status: status, $step: input.step ?? null, $now: now } },
128
+ ...domains.map(domain => ({ rql: 'INSERT INTO cms_site_domains (host, site_id, is_primary, verified_at, created_at) VALUES ($host, $site, $primary, $verified, $now)',
129
+ params: { $host: domain.host, $site: input.id, $primary: domain.primary ? 1 : 0, $verified: domain.verifiedAt, $now: now } })),
130
+ ], WRITE);
131
+ } catch (error) {
132
+ if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|PRIMARY/i.test(error.message)) {
133
+ throw new CmsError('CMS_CONFLICT', /cms_sites\.database/.test(error.message) ? 'Another site uses this database.' : /cms_sites/.test(error.message) ? 'A site with this ID exists.' : 'Another site answers on this domain.');
134
+ }
135
+ throw error;
136
+ }
137
+ return (await this.get(input.id))!;
138
+ }
139
+
140
+ /** Change the name, database, status or creation step. A deleted site records when it was deleted. */
141
+ async update(id: string, patch: { name?: string; database?: string; status?: SiteStatus; step?: string | null }): Promise<SiteRecord | null> {
142
+ const current = await this.get(id);
143
+ if (!current) return null;
144
+ if (patch.name !== undefined) checkName(patch.name);
145
+ if (patch.database !== undefined && !DATABASE.test(patch.database)) throw new CmsError('CMS_VALIDATION', 'Invalid database ID.');
146
+ const status = patch.status ?? current.status;
147
+ if (!STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown site status.');
148
+ const now = this.#now();
149
+ const deletedAt = status === 'deleted' ? current.deletedAt ?? now : null;
150
+ await this.#db.write([{ rql: 'UPDATE cms_sites SET name = $name, database = $database, status = $status, step = $step, deleted_at = $deleted, updated_at = $now WHERE id = $id',
151
+ params: { $id: id, $name: (patch.name ?? current.name).trim(), $database: patch.database ?? current.database, $status: status, $step: patch.step === undefined ? current.step : patch.step, $deleted: deletedAt, $now: now } }], WRITE);
152
+ return this.get(id);
153
+ }
154
+
155
+ /** Add a domain that is not checked yet; it answers as an alias until a check makes it primary. */
156
+ async addDomain(id: string, host: string): Promise<SiteRecord | null> {
157
+ const name = siteHost(host);
158
+ if (!name) throw new CmsError('CMS_VALIDATION', 'Enter a host name, such as blog.example.com.', { fields: { host: 'is invalid.' } });
159
+ if (id !== MAIN_SITE && !(await this.get(id))) return null;
160
+ try {
161
+ await this.#db.write([{ rql: 'INSERT INTO cms_site_domains (host, site_id, is_primary, verified_at, created_at) VALUES ($host, $site, 0, NULL, $now)', params: { $host: name, $site: id, $now: this.#now() } }], WRITE);
162
+ } catch (error) {
163
+ if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|PRIMARY/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'Another site answers on this domain.', { fields: { host: 'is taken.' } });
164
+ throw error;
165
+ }
166
+ return id === MAIN_SITE ? null : this.get(id);
167
+ }
168
+
169
+ /** Record that the domain answered its check, and make it the site's primary domain when asked. */
170
+ async verifyDomain(id: string, host: string, options: { primary?: boolean } = {}): Promise<boolean> {
171
+ const name = siteHost(host);
172
+ const now = this.#now();
173
+ const result = await this.#db.write([
174
+ { rql: 'UPDATE cms_site_domains SET verified_at = $now WHERE host = $host AND site_id = $site', params: { $host: name, $site: id, $now: now } },
175
+ ...(options.primary ? [
176
+ { rql: 'UPDATE cms_site_domains SET is_primary = 0 WHERE site_id = $site AND host != $host AND EXISTS (SELECT 1 FROM cms_site_domains WHERE host = $host AND site_id = $site)', params: { $host: name, $site: id } },
177
+ { rql: 'UPDATE cms_site_domains SET is_primary = 1 WHERE host = $host AND site_id = $site', params: { $host: name, $site: id } },
178
+ ] : []),
179
+ ], WRITE);
180
+ return result.results[0]!.affected === 1n;
181
+ }
182
+
183
+ /** Remove an alias. The primary domain stays until another one is primary. */
184
+ async removeDomain(id: string, host: string): Promise<boolean> {
185
+ const result = await this.#db.write([{ rql: 'DELETE FROM cms_site_domains WHERE host = $host AND site_id = $site AND is_primary = 0', params: { $host: siteHost(host), $site: id } }], WRITE);
186
+ return result.results[0]!.affected === 1n;
187
+ }
188
+
189
+ /** Sites deleted before this time, oldest first: their 30 days to restore are over. */
190
+ async deletedBefore(at: number, limit = 20): Promise<SiteRecord[]> {
191
+ const result = await this.#db.read([{ rql: "SELECT id FROM cms_sites WHERE status = 'deleted' AND deleted_at < $at ORDER BY deleted_at LIMIT $limit", params: { $at: at, $limit: limit } }]);
192
+ return this.#many(result.results[0]!.rows.map(row => row[0] as string));
193
+ }
194
+
195
+ /** Forget a site, its domains and its members' memberships, once its database and media are gone. */
196
+ async remove(id: string): Promise<void> {
197
+ await this.#db.write([
198
+ { rql: 'DELETE FROM cms_site_domains WHERE site_id = $id', params: { $id: id } },
199
+ { rql: 'DELETE FROM cms_memberships WHERE site_id = $id', params: { $id: id } },
200
+ { rql: 'DELETE FROM cms_session_sites WHERE site_id = $id', params: { $id: id } },
201
+ { rql: 'DELETE FROM cms_handoffs WHERE site_id = $id', params: { $id: id } },
202
+ { rql: 'DELETE FROM cms_sites WHERE id = $id', params: { $id: id } },
203
+ ], WRITE);
204
+ }
205
+
206
+ async #many(ids: readonly string[]): Promise<SiteRecord[]> {
207
+ if (!ids.length) return [];
208
+ const list = inList('s', ids);
209
+ const result = await this.#db.read([
210
+ { rql: `SELECT ${COLUMNS} FROM cms_sites WHERE id IN ${list.rql}`, params: list.params },
211
+ { rql: `SELECT site_id, host, is_primary, verified_at FROM cms_site_domains WHERE site_id IN ${list.rql} ORDER BY is_primary DESC, host`, params: list.params },
212
+ ]);
213
+ const domains = new Map<string, SiteDomain[]>();
214
+ for (const row of result.results[1]!.rows) {
215
+ const entry = domains.get(row[0] as string) ?? [];
216
+ entry.push(domainOf(row.slice(1)));
217
+ domains.set(row[0] as string, entry);
218
+ }
219
+ const sites = new Map(result.results[0]!.rows.map(row => [row[0] as string, Object.freeze({
220
+ id: row[0] as string, name: row[1] as string, database: row[2] as string, status: row[3] as SiteStatus, step: row[4] as string | null,
221
+ domains: Object.freeze(domains.get(row[0] as string) ?? []), createdAt: Number(row[5] as bigint), updatedAt: Number(row[6] as bigint),
222
+ deletedAt: row[7] === null ? null : Number(row[7] as bigint),
223
+ })]));
224
+ return ids.map(id => sites.get(id)).filter((site): site is SiteRecord => site !== undefined);
225
+ }
226
+ }
227
+
228
+ function domainOf(row: readonly Value[]): SiteDomain {
229
+ return Object.freeze({ host: row[0] as string, primary: Number(row[1] as bigint) === 1, verifiedAt: row[2] === null ? null : Number(row[2] as bigint) });
230
+ }
231
+
232
+ function checkName(name: string): void {
233
+ if (typeof name !== 'string' || !name.trim() || name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a site name of at most 120 characters.', { fields: { name: 'is required.' } });
234
+ }
235
+
236
+ function checkDomains(domains: readonly { host: string; primary?: boolean; verifiedAt?: number | null }[]): { host: string; primary: boolean; verifiedAt: number | null }[] {
237
+ if (!domains.length || domains.length > 20) throw new CmsError('CMS_VALIDATION', 'A site needs 1 to 20 domains.', { fields: { domains: 'are required.' } });
238
+ const hosts = domains.map(domain => siteHost(domain.host));
239
+ if (hosts.some(host => !host) || new Set(hosts).size !== hosts.length) throw new CmsError('CMS_VALIDATION', 'Enter each domain once, as a host name such as blog.example.com.', { fields: { domains: 'are invalid.' } });
240
+ const primary = domains.findIndex(domain => domain.primary);
241
+ if (domains.filter(domain => domain.primary).length > 1) throw new CmsError('CMS_VALIDATION', 'A site has one primary domain.', { fields: { domains: 'have two primaries.' } });
242
+ return domains.map((domain, index) => ({ host: hosts[index]!, primary: index === (primary < 0 ? 0 : primary), verifiedAt: domain.verifiedAt ?? null }));
243
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * RomeDB implementations of the auth and framework stores, on relational host tables.
3
+ * Each operation is one atomic request; conditional operations check the affected count.
4
+ * The interfaces are structural copies, so this package does not depend on the framework.
5
+ */
6
+ import { createSqlJobStore, type JobStore } from '@cossackframework/core/jobs';
7
+ import { createSqlNotificationStore, type NotificationStore } from '@cossackframework/core/notifications';
8
+ import { rqlDatabase, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
9
+ import { readPaged } from './budget';
10
+
11
+ const TOKEN = /^[A-Za-z0-9_-]{1,191}$/;
12
+ const n = (value: Value | undefined) => Number(value as bigint);
13
+
14
+ export interface AuthSessionRecord { readonly id: string; readonly userId: string; readonly kind: 'auth'; readonly createdAt: number; readonly expiresAt: number }
15
+
16
+ /**
17
+ * A stored session. On a site other than the main one it is a child session: the network
18
+ * session it came from (`parentId`, that session's public reference) and the account's network
19
+ * role at the handoff, so site requests need not read the network database.
20
+ */
21
+ export interface CmsAuthSession extends AuthSessionRecord {
22
+ readonly parentId: string | null;
23
+ readonly networkRole: string | null;
24
+ /** Whether the sign-in that made it used a second factor; a child session copies its network session's. */
25
+ readonly secondFactor: boolean;
26
+ }
27
+
28
+ /** What a child session takes from its network session's handoff. */
29
+ export interface ChildSession {
30
+ /** The network session's public reference. */
31
+ readonly parentId: string;
32
+ readonly networkRole: string | null;
33
+ /** The network session's expiry. */
34
+ readonly expiresAt: number;
35
+ /** Whether the network session's sign-in used a second factor; missing means it did not. */
36
+ readonly secondFactor?: boolean;
37
+ }
38
+
39
+ /** Network sessions that ended: one by its public reference, or an account's (all but `except`). Their child sessions end with them. */
40
+ export type EndedSessions = { readonly session: string } | { readonly user: string; readonly except?: string };
41
+ /** Structural `AuthSessionStore` from `@cossackframework/auth`. */
42
+ export interface CmsAuthSessionStore {
43
+ create(record: AuthSessionRecord, context?: unknown): Promise<void>;
44
+ read(id: string, context?: unknown): Promise<AuthSessionRecord | null>;
45
+ replace(expected: AuthSessionRecord, replacement: AuthSessionRecord, now: number, context?: unknown): Promise<boolean>;
46
+ revoke(id: string, context?: unknown): Promise<void>;
47
+ }
48
+
49
+ export interface OAuthStateRecord { readonly key: string; readonly provider: string; readonly createdAt: number; readonly expiresAt: number }
50
+ /** Structural `OAuthStateStore` from `@cossackframework/auth`. */
51
+ export interface CmsOAuthStateStore {
52
+ create(record: OAuthStateRecord, context?: unknown): Promise<void>;
53
+ consume(key: string, provider: string, now: number, context?: unknown): Promise<boolean>;
54
+ }
55
+
56
+ /** Structural `SessionStore` from `@cossackframework/framework/session`. */
57
+ export interface CmsSessionStore {
58
+ create(ttlMs?: number): Promise<string>;
59
+ has(sessionId: string): Promise<boolean>;
60
+ load(sessionId: string): Promise<Record<string, unknown>>;
61
+ get<T = unknown>(sessionId: string, key: string): Promise<T | undefined>;
62
+ getAll(sessionId: string): Promise<Record<string, unknown>>;
63
+ set(sessionId: string, key: string, value: unknown, ttlMs?: number): Promise<void>;
64
+ unset(sessionId: string, key: string): Promise<void>;
65
+ destroy(sessionId: string): Promise<void>;
66
+ bindUser(sessionId: string, userId: string): Promise<void>;
67
+ purgeExpired(): Promise<number>;
68
+ }
69
+
70
+ /**
71
+ * Auth sessions keyed by token. Rotation is one conditional update of the key; the public
72
+ * reference survives it, so realtime descriptors detect rotation through the fingerprint.
73
+ */
74
+ export function createAuthSessionStore(db: RomeDB, options: { now?: () => number; request?: (context: unknown) => { ip?: string; userAgent?: string }; sessionsEnded?: (ended: EndedSessions) => Promise<void> } = {}): Omit<CmsAuthSessionStore, 'read' | 'create'> & {
75
+ read(id: string, context?: unknown): Promise<CmsAuthSession | null>;
76
+ /** A session whose sign-in used a second factor (`secondFactor`) or did not; `also` joins the session's write (its sign-in event). */
77
+ create(record: AuthSessionRecord, context?: unknown, options?: { secondFactor?: boolean; also?: readonly Statement[] }): Promise<void>;
78
+ /** Mark a session as having used a second factor: its user just added one in it. */
79
+ markSecondFactor(id: string): Promise<boolean>;
80
+ /** A child session on a site, from a network session's handoff. It expires no later than its parent, and rotation keeps that. */
81
+ createChild(record: AuthSessionRecord, child: ChildSession, context?: unknown, options?: { also?: readonly Statement[] }): Promise<void>;
82
+ /** End the child sessions of these network sessions, or all of an account's (but `except`'s). */
83
+ revokeChildren(ended: EndedSessions): Promise<number>;
84
+ publicReference(id: string): Promise<string | null>;
85
+ findByReference(reference: string): Promise<{ id: string; userId: string; expiresAt: number; secondFactor: boolean } | null>;
86
+ listForUser(userId: string, now: number): Promise<{ reference: string; createdAt: number; expiresAt: number; ip: string | null; userAgent: string | null }[]>;
87
+ /** The newest sessions across users, for the dashboard's sign-in activity. Sessions end at sign-out, so this shows who is signed in. */
88
+ listRecent(now: number, limit?: number): Promise<{ reference: string; userId: string; createdAt: number; ip: string | null; userAgent: string | null }[]>;
89
+ revokeAllForUser(userId: string, except?: string): Promise<number>;
90
+ /** Revoke one of the user's sessions by its public reference, never the `current` token. */
91
+ revokeByReference(userId: string, reference: string, current?: string): Promise<boolean>;
92
+ } {
93
+ const now = options.now ?? Date.now;
94
+ const ended = (scope: EndedSessions) => options.sessionsEnded?.(scope).catch(error => console.error('[cms] could not end child sessions', error));
95
+ const insert = async (record: AuthSessionRecord, child: ChildSession | null, context: unknown, secondFactor: boolean, also: readonly Statement[] = []) => {
96
+ assertRecord(record);
97
+ const expires = child ? Math.min(record.expiresAt, child.expiresAt) : record.expiresAt;
98
+ if (expires <= record.createdAt) throw new Error('The network session has expired.');
99
+ const meta = options.request?.(context) ?? {};
100
+ await db.write([{
101
+ rql: 'INSERT INTO cms_auth_sessions (id, public_id, user_id, created_at, expires_at, ip, user_agent, parent_id, network_role, second_factor) VALUES ($id, $public, $user, $created, $expires, $ip, $agent, $parent, $role, $factor)',
102
+ params: { $id: record.id, $public: crypto.randomUUID(), $user: record.userId, $created: record.createdAt, $expires: expires, $ip: meta.ip?.slice(0, 64) ?? null, $agent: meta.userAgent?.slice(0, 512) ?? null,
103
+ $parent: child?.parentId ?? null, $role: child?.networkRole ?? null, $factor: secondFactor ? 1 : 0 },
104
+ }, {
105
+ // The account keeps the sign-in time after the session ends, and so does its member row on the main site.
106
+ rql: 'UPDATE cms_accounts SET last_sign_in_at = $created WHERE id = $user',
107
+ params: { $user: record.userId, $created: record.createdAt },
108
+ }, {
109
+ rql: 'UPDATE cms_users SET last_sign_in_at = $created WHERE id = $user',
110
+ params: { $user: record.userId, $created: record.createdAt },
111
+ }, ...also], { kind: 'cms.auth.session', retryConflicts: 5 });
112
+ };
113
+ return {
114
+ create: (record, context, extra) => insert(record, null, context, extra?.secondFactor === true, extra?.also),
115
+ createChild: (record, child, context, extra) => insert(record, child, context, child.secondFactor === true, extra?.also),
116
+ async markSecondFactor(id) {
117
+ if (!TOKEN.test(id)) return false;
118
+ const result = await db.write([{ rql: 'UPDATE cms_auth_sessions SET second_factor = 1 WHERE id = $id', params: { $id: id } }], { kind: 'cms.auth.session', retryConflicts: 5 });
119
+ return result.results[0]!.affected === 1n;
120
+ },
121
+ async read(id) {
122
+ if (!TOKEN.test(id)) return null;
123
+ const result = await db.read([{ rql: 'SELECT id, user_id, created_at, expires_at, parent_id, network_role, second_factor FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }]);
124
+ const row = result.results[0]!.rows[0];
125
+ return row ? Object.freeze({ id: row[0] as string, userId: row[1] as string, kind: 'auth' as const, createdAt: n(row[2]), expiresAt: n(row[3]), parentId: row[4] as string | null, networkRole: row[5] as string | null,
126
+ secondFactor: row[6] !== null && n(row[6]) === 1 }) : null;
127
+ },
128
+ async replace(expected, replacement, at) {
129
+ assertRecord(expected);
130
+ assertRecord(replacement);
131
+ if (replacement.userId !== expected.userId) return false;
132
+ const guard = 'WHERE id = $id AND user_id = $user AND created_at = $oldCreated AND expires_at = $oldExpires AND expires_at > $now';
133
+ const params = { $next: replacement.id, $created: replacement.createdAt, $id: expected.id, $user: expected.userId,
134
+ $oldCreated: expected.createdAt, $oldExpires: expected.expiresAt, $now: Math.max(at, now()) };
135
+ // A child session keeps its expiry, so it never outlives the network session it came from.
136
+ const result = await db.write([
137
+ { rql: `UPDATE cms_auth_sessions SET id = $next, created_at = $created, expires_at = $expires ${guard} AND parent_id IS NULL`, params: { ...params, $expires: replacement.expiresAt } },
138
+ { rql: `UPDATE cms_auth_sessions SET id = $next, created_at = $created ${guard} AND parent_id IS NOT NULL`, params },
139
+ ], { kind: 'cms.auth.session', retryConflicts: 5 });
140
+ return result.results[0]!.affected + result.results[1]!.affected === 1n;
141
+ },
142
+ async revoke(id) {
143
+ if (!TOKEN.test(id)) return;
144
+ const found = await db.read([{ rql: 'SELECT public_id, parent_id FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }]);
145
+ await db.write([{ rql: 'DELETE FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }], { kind: 'cms.auth.session', retryConflicts: 5 });
146
+ const row = found.results[0]!.rows[0];
147
+ if (row && row[1] === null) await ended({ session: row[0] as string });
148
+ },
149
+ async publicReference(id) {
150
+ if (!TOKEN.test(id)) return null;
151
+ const result = await db.read([{ rql: 'SELECT public_id FROM cms_auth_sessions WHERE id = $id', params: { $id: id } }]);
152
+ return (result.results[0]!.rows[0]?.[0] as string | undefined) ?? null;
153
+ },
154
+ async findByReference(reference) {
155
+ if (!/^[0-9a-f-]{36}$/.test(reference)) return null;
156
+ const result = await db.read([{ rql: 'SELECT id, user_id, expires_at, second_factor FROM cms_auth_sessions WHERE public_id = $ref', params: { $ref: reference } }]);
157
+ const row = result.results[0]!.rows[0];
158
+ return row ? { id: row[0] as string, userId: row[1] as string, expiresAt: n(row[2]), secondFactor: row[3] !== null && n(row[3]) === 1 } : null;
159
+ },
160
+ async listForUser(userId, at) {
161
+ const result = await db.read([{
162
+ rql: 'SELECT public_id, created_at, expires_at, ip, user_agent FROM cms_auth_sessions WHERE user_id = $user AND expires_at > $now ORDER BY created_at DESC LIMIT 100',
163
+ params: { $user: userId, $now: at },
164
+ }]);
165
+ return result.results[0]!.rows.map(row => ({ reference: row[0] as string, createdAt: n(row[1]), expiresAt: n(row[2]), ip: row[3] as string | null, userAgent: row[4] as string | null }));
166
+ },
167
+ async listRecent(at, limit = 10) {
168
+ const result = await db.read([{
169
+ rql: 'SELECT public_id, user_id, created_at, ip, user_agent FROM cms_auth_sessions WHERE expires_at > $now ORDER BY created_at DESC LIMIT $limit',
170
+ params: { $now: at, $limit: Math.min(Math.max(limit, 1), 100) },
171
+ }]);
172
+ return result.results[0]!.rows.map(row => ({ reference: row[0] as string, userId: row[1] as string, createdAt: n(row[2]), ip: row[3] as string | null, userAgent: row[4] as string | null }));
173
+ },
174
+ async revokeByReference(userId, reference, current) {
175
+ if (!/^[0-9a-f-]{36}$/.test(reference)) return false;
176
+ const result = await db.write([{
177
+ rql: `DELETE FROM cms_auth_sessions WHERE public_id = $ref AND user_id = $user${current ? ' AND id != $current' : ''}`,
178
+ params: { $ref: reference, $user: userId, ...(current ? { $current: current } : {}) },
179
+ }], { kind: 'cms.auth.session', retryConflicts: 5 });
180
+ if (result.results[0]!.affected !== 1n) return false;
181
+ await ended({ session: reference });
182
+ return true;
183
+ },
184
+ async revokeAllForUser(userId, except) {
185
+ const kept = except && TOKEN.test(except) ? (await db.read([{ rql: 'SELECT public_id FROM cms_auth_sessions WHERE id = $id', params: { $id: except } }])).results[0]!.rows[0]?.[0] as string | undefined : undefined;
186
+ const result = await db.write([{
187
+ rql: `DELETE FROM cms_auth_sessions WHERE user_id = $user${except ? ' AND id != $except' : ''}`,
188
+ params: { $user: userId, ...(except ? { $except: except } : {}) },
189
+ }], { kind: 'cms.auth.session', retryConflicts: 5 });
190
+ await ended({ user: userId, ...(kept ? { except: kept } : {}) });
191
+ return Number(result.results[0]!.affected);
192
+ },
193
+ async revokeChildren(scope) {
194
+ const result = await db.write(['session' in scope
195
+ ? { rql: 'DELETE FROM cms_auth_sessions WHERE parent_id = $parent', params: { $parent: scope.session } }
196
+ : { rql: `DELETE FROM cms_auth_sessions WHERE user_id = $user AND parent_id IS NOT NULL${scope.except ? ' AND parent_id != $except' : ''}`, params: { $user: scope.user, ...(scope.except ? { $except: scope.except } : {}) } },
197
+ ], { kind: 'cms.auth.session', retryConflicts: 5 });
198
+ return Number(result.results[0]!.affected);
199
+ },
200
+ };
201
+ }
202
+
203
+ /** OAuth state consumed by one conditional delete: exactly one callback can win. */
204
+ export function createOAuthStateStore(db: RomeDB): CmsOAuthStateStore & { purgeExpired(now: number): Promise<number> } {
205
+ return {
206
+ async create(record) {
207
+ if (!/^[a-f0-9]{64}$/.test(record.key) || !/^[a-z0-9_-]{1,64}$/.test(record.provider)) throw new TypeError('Invalid OAuth state record.');
208
+ await db.write([{ rql: 'INSERT INTO cms_oauth_states (key, provider, created_at, expires_at) VALUES ($key, $provider, $created, $expires)',
209
+ params: { $key: record.key, $provider: record.provider, $created: record.createdAt, $expires: record.expiresAt } }], { kind: 'cms.auth.oauth', retryConflicts: 5 });
210
+ },
211
+ async consume(key, provider, now) {
212
+ if (!/^[a-f0-9]{64}$/.test(key)) return false;
213
+ const result = await db.write([{ rql: 'DELETE FROM cms_oauth_states WHERE key = $key AND provider = $provider AND expires_at > $now',
214
+ params: { $key: key, $provider: provider, $now: Math.max(now, Date.now()) } }], { kind: 'cms.auth.oauth', retryConflicts: 5 });
215
+ return result.results[0]!.affected === 1n;
216
+ },
217
+ async purgeExpired(now) {
218
+ const expired = await db.read([{ rql: 'SELECT 1 FROM cms_oauth_states WHERE expires_at <= $now LIMIT 1', params: { $now: now } }]);
219
+ if (!expired.results[0]!.rows.length) return 0;
220
+ const result = await db.write([{ rql: 'DELETE FROM cms_oauth_states WHERE key IN (SELECT key FROM cms_oauth_states WHERE expires_at <= $now LIMIT 1000)', params: { $now: now } }], { kind: 'cms.auth.oauth', retryConflicts: 5 });
221
+ return Number(result.results[0]!.affected);
222
+ },
223
+ };
224
+ }
225
+
226
+ /**
227
+ * The framework session bag. Each key is its own row, so a write to one key never
228
+ * replaces a concurrent write to another; writes slide the expiry.
229
+ */
230
+ export function createSessionStore(db: RomeDB, options: { ttlMs?: number; now?: () => number } = {}): CmsSessionStore {
231
+ const now = options.now ?? Date.now;
232
+ const defaultTtl = options.ttlMs ?? 30 * 24 * 60 * 60 * 1000;
233
+ const live = 'EXISTS (SELECT 1 FROM cms_sessions WHERE id = $id AND expires_at > $now)';
234
+ const read = async (sessionId: string): Promise<Record<string, unknown>> => {
235
+ if (!TOKEN.test(sessionId)) return {};
236
+ const at = now();
237
+ const rows = await readPaged(db, (size, offset) => ({ rql: `SELECT key, value FROM cms_session_values WHERE session_id = $id AND ${live} ORDER BY key LIMIT $limit OFFSET $offset`, params: { $id: sessionId, $now: at, $limit: size, $offset: offset } }), 1000, 0);
238
+ return Object.fromEntries(rows.map(([key, value]) => [key as string, JSON.parse(value as string)]));
239
+ };
240
+ return {
241
+ async create(ttlMs = defaultTtl) {
242
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
243
+ const id = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');
244
+ const at = now();
245
+ await db.write([{ rql: 'INSERT INTO cms_sessions (id, user_id, created_at, expires_at) VALUES ($id, NULL, $at, $expires)', params: { $id: id, $at: at, $expires: at + ttlMs } }], { kind: 'cms.session', retryConflicts: 5 });
246
+ return id;
247
+ },
248
+ async has(sessionId) {
249
+ if (!TOKEN.test(sessionId)) return false;
250
+ const result = await db.read([{ rql: 'SELECT 1 FROM cms_sessions WHERE id = $id AND expires_at > $now', params: { $id: sessionId, $now: now() } }]);
251
+ return result.results[0]!.rows.length === 1;
252
+ },
253
+ load: read,
254
+ getAll: read,
255
+ async get<T>(sessionId: string, key: string) {
256
+ if (!TOKEN.test(sessionId)) return undefined;
257
+ const result = await db.read([{ rql: `SELECT value FROM cms_session_values WHERE session_id = $id AND key = $key AND ${live}`, params: { $id: sessionId, $key: key, $now: now() } }]);
258
+ const value = result.results[0]!.rows[0]?.[0];
259
+ return value === undefined ? undefined : JSON.parse(value as string) as T;
260
+ },
261
+ async set(sessionId, key, value, ttlMs = defaultTtl) {
262
+ if (!TOKEN.test(sessionId)) throw new TypeError('Invalid session ID.');
263
+ const encoded = JSON.stringify(value);
264
+ if (encoded === undefined) throw new TypeError('Session values must be JSON.');
265
+ const at = now();
266
+ await db.write([
267
+ { rql: `INSERT INTO cms_session_values (session_id, key, value) SELECT $id, $key, $value WHERE ${live}
268
+ ON CONFLICT (session_id, key) DO UPDATE SET value = excluded.value`, params: { $id: sessionId, $key: key, $value: encoded, $now: at } },
269
+ { rql: 'UPDATE cms_sessions SET expires_at = $expires WHERE id = $id AND expires_at > $now', params: { $id: sessionId, $expires: at + ttlMs, $now: at } },
270
+ ], { kind: 'cms.session', retryConflicts: 5 });
271
+ },
272
+ async unset(sessionId, key) {
273
+ if (!TOKEN.test(sessionId)) return;
274
+ await db.write([{ rql: 'DELETE FROM cms_session_values WHERE session_id = $id AND key = $key', params: { $id: sessionId, $key: key } }], { kind: 'cms.session', retryConflicts: 5 });
275
+ },
276
+ async destroy(sessionId) {
277
+ if (!TOKEN.test(sessionId)) return;
278
+ await db.write([
279
+ { rql: 'DELETE FROM cms_session_values WHERE session_id = $id', params: { $id: sessionId } },
280
+ { rql: 'DELETE FROM cms_sessions WHERE id = $id', params: { $id: sessionId } },
281
+ ], { kind: 'cms.session', retryConflicts: 5 });
282
+ },
283
+ async bindUser(sessionId, userId) {
284
+ if (!TOKEN.test(sessionId)) return;
285
+ await db.write([{ rql: 'UPDATE cms_sessions SET user_id = $user WHERE id = $id', params: { $id: sessionId, $user: userId } }], { kind: 'cms.session', retryConflicts: 5 });
286
+ },
287
+ async purgeExpired() {
288
+ const at = now();
289
+ const expired = await db.read([{ rql: 'SELECT 1 FROM cms_sessions WHERE expires_at <= $now LIMIT 1', params: { $now: at } }]);
290
+ if (!expired.results[0]!.rows.length) return 0;
291
+ const result = await db.write([
292
+ { rql: 'DELETE FROM cms_session_values WHERE session_id IN (SELECT id FROM cms_sessions WHERE expires_at <= $now LIMIT 500)', params: { $now: at } },
293
+ { rql: 'DELETE FROM cms_sessions WHERE id IN (SELECT id FROM cms_sessions WHERE expires_at <= $now LIMIT 500)', params: { $now: at } },
294
+ ], { kind: 'cms.session', retryConflicts: 5 });
295
+ return Number(result.results[1]!.affected);
296
+ },
297
+ };
298
+ }
299
+
300
+ /** Job ledger with the same lease and fencing semantics as the D1 store. */
301
+ export function createJobStore(db: RomeDB): JobStore {
302
+ return createSqlJobStore(rqlDatabase(db, { kind: 'cms.jobs' }));
303
+ }
304
+
305
+ /** Notification ledger with the same fencing semantics as the D1 store. */
306
+ export function createNotificationStore(db: RomeDB): NotificationStore {
307
+ return createSqlNotificationStore(rqlDatabase(db, { kind: 'cms.notifications' }));
308
+ }
309
+
310
+ function assertRecord(record: AuthSessionRecord): void {
311
+ if (!TOKEN.test(record.id) || typeof record.userId !== 'string' || !record.userId || !Number.isSafeInteger(record.createdAt) || !Number.isSafeInteger(record.expiresAt)) {
312
+ throw new TypeError('Invalid auth session record.');
313
+ }
314
+ }