@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,391 @@
1
+ /**
2
+ * Second factors of CMS users: an authenticator app's secret, recovery codes, passkeys, and
3
+ * the short-lived challenges of pending sign-ins and passkey ceremonies.
4
+ */
5
+ import { generateRecoveryCodes, generateTotpSecret, hashRecoveryCode, verifyTotp } from '@cossackframework/auth';
6
+ import type { RomeDB, Value } from '@cossackframework/romedb';
7
+ import { CmsError } from '../errors';
8
+ import { randomToken, sha256Hex } from './tokens';
9
+
10
+ export interface PasskeyInfo {
11
+ readonly id: string;
12
+ readonly name: string;
13
+ readonly deviceType: string | null;
14
+ readonly backedUp: boolean;
15
+ readonly createdAt: number;
16
+ readonly lastUsedAt: number | null;
17
+ }
18
+
19
+ export interface StoredPasskeyRow extends PasskeyInfo {
20
+ readonly userId: string;
21
+ readonly publicKey: string;
22
+ readonly counter: number;
23
+ readonly transports: readonly string[] | null;
24
+ }
25
+
26
+ export interface SecurityStatus {
27
+ /** An authenticator app is set up and confirmed. */
28
+ readonly totp: boolean;
29
+ /** Unused recovery codes. */
30
+ readonly recoveryCodes: number;
31
+ readonly passkeys: readonly PasskeyInfo[];
32
+ }
33
+
34
+ export type ChallengeKind = 'signin' | 'passkey-register' | 'passkey-signin';
35
+
36
+ const WRITE = { kind: 'cms.security', retryConflicts: 5 } as const;
37
+ /** Attempt counters: one row takes every attempt of a burst, so they retry longer. */
38
+ const COUNT = { kind: 'cms.security', retryConflicts: 20 } as const;
39
+ const PASSKEY_COLUMNS = 'id, user_id, name, public_key, counter, transports, device_type, backed_up, created_at, last_used_at';
40
+ /** Wrong codes a pending sign-in allows. */
41
+ export const SIGN_IN_ATTEMPTS = 5;
42
+ /**
43
+ * Second-factor codes counted per account for a window, across every pending sign-in: a right
44
+ * password does not give them back, so knowing the password does not buy more guesses.
45
+ */
46
+ export const SECOND_FACTOR_LOCK = Object.freeze({ windowMs: 15 * 60_000, perAccount: 10 });
47
+ /**
48
+ * Password sign-ins are counted per email and per client address for a window, a right password
49
+ * giving its attempt back; past the limit the sign-in is refused until the window ends, whether
50
+ * or not the account exists.
51
+ */
52
+ export const SIGN_IN_LOCK = Object.freeze({ windowMs: 15 * 60_000, perEmail: 5, perAddress: 20 });
53
+ /** Password reset requests per email and per address in an hour; beyond them nothing is sent. */
54
+ export const RESET_REQUESTS = Object.freeze({ windowMs: 60 * 60_000, perEmail: 3, perAddress: 10 });
55
+
56
+ export class CmsSecurity {
57
+ readonly #db: RomeDB;
58
+ readonly #now: () => number;
59
+
60
+ constructor(db: RomeDB, options: { now?: () => number } = {}) {
61
+ this.#db = db;
62
+ this.#now = options.now ?? Date.now;
63
+ }
64
+
65
+ /**
66
+ * Start a password sign-in: one attempt is counted for the email and for the address before
67
+ * the password is checked, in conditional writes, so attempts sent at once are held to the
68
+ * limits as well as one after another. Refused while either is at its limit for the window.
69
+ * A right password gives the attempt back (`signInSucceeded`); a wrong one leaves it counted.
70
+ */
71
+ async signInBegin(email: string, address: string): Promise<{ ok: true } | { ok: false; retryAfterMs: number }> {
72
+ const [emailId, addressId] = [await emailKey(email), addressKey(address)];
73
+ const byEmail = await this.#count(emailId, SIGN_IN_LOCK.windowMs, SIGN_IN_LOCK.perEmail);
74
+ const byAddress = byEmail && await this.#count(addressId, SIGN_IN_LOCK.windowMs, SIGN_IN_LOCK.perAddress);
75
+ if (byEmail && byAddress) return { ok: true };
76
+ // The email's attempt does not stand when the address refused it.
77
+ if (byEmail) await this.#giveBack(emailId);
78
+ const result = await this.#db.read([{ rql: 'SELECT until FROM cms_attempts WHERE key = $key', params: { $key: byEmail ? addressId : emailId } }]);
79
+ const until = Number((result.results[0]!.rows[0]?.[0] as bigint | undefined) ?? 0n);
80
+ return { ok: false, retryAfterMs: Math.max(1, until - this.#now()) };
81
+ }
82
+
83
+ /** A right password: the email's failures are forgotten, and the address gets this attempt back. */
84
+ async signInSucceeded(email: string, address: string): Promise<void> {
85
+ await this.#bestEffort('DELETE FROM cms_attempts WHERE key = $key', await emailKey(email));
86
+ await this.#giveBack(addressKey(address));
87
+ }
88
+
89
+ async #giveBack(key: string): Promise<void> {
90
+ await this.#bestEffort('UPDATE cms_attempts SET count = count - 1 WHERE key = $key AND count > 0', key);
91
+ }
92
+
93
+ /**
94
+ * A write that gives attempts back. Under a burst on the same key it can keep conflicting past
95
+ * the retries: the attempt then stays counted (the limit errs shut), and the request goes on.
96
+ */
97
+ async #bestEffort(rql: string, key: string): Promise<void> {
98
+ try { await this.#db.write([{ rql, params: { $key: key } }], COUNT); }
99
+ catch (error) {
100
+ if ((error as { code?: string }).code !== 'RDB_WRITE_CONFLICT') throw error;
101
+ console.warn('[cms] a sign-in attempt could not be given back: the key is busy');
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Count an attempt of `kind` (such as `reset`) for a key within a window; false past `max`.
107
+ * A refused attempt keeps the gate shut until the window ends.
108
+ */
109
+ async attempt(kind: string, key: string, max: number, windowMs: number): Promise<boolean> {
110
+ return this.#count(attemptKey(kind, key), windowMs, max);
111
+ }
112
+
113
+ /** Give back an attempt `attempt()` counted, for one that did not go ahead after all. */
114
+ async release(kind: string, key: string): Promise<void> {
115
+ await this.#giveBack(attemptKey(kind, key));
116
+ }
117
+
118
+ /**
119
+ * One more attempt for the key, unless it already has `max` in its window: true when this
120
+ * one was counted. The database does the counting in one write (an ended window starts
121
+ * again, then a conditional increment), so concurrent attempts are each counted once and
122
+ * no more than `max` are let through.
123
+ */
124
+ async #count(key: string, windowMs: number, max: number): Promise<boolean> {
125
+ const now = this.#now();
126
+ try {
127
+ const result = await this.#db.write([
128
+ { rql: 'DELETE FROM cms_attempts WHERE key = $key AND until <= $now', params: { $key: key, $now: now } },
129
+ { rql: 'INSERT INTO cms_attempts (key, count, until) VALUES ($key, 0, $until) ON CONFLICT (key) DO NOTHING', params: { $key: key, $until: now + windowMs } },
130
+ { rql: 'UPDATE cms_attempts SET count = count + 1 WHERE key = $key AND count < $max', params: { $key: key, $max: max } },
131
+ ], COUNT);
132
+ return result.results[2]!.affected === 1n;
133
+ } catch (error) {
134
+ // A key under a burst of attempts can keep conflicting past the retries: refuse this
135
+ // attempt, as the limit would, rather than fail the request.
136
+ if ((error as { code?: string }).code === 'RDB_WRITE_CONFLICT') return false;
137
+ throw error;
138
+ }
139
+ }
140
+
141
+ async status(userId: string): Promise<SecurityStatus> {
142
+ const result = await this.#db.read([
143
+ { rql: 'SELECT totp_confirmed_at, recovery FROM cms_user_security WHERE user_id = $user', params: { $user: userId } },
144
+ { rql: `SELECT ${PASSKEY_COLUMNS} FROM cms_passkeys WHERE user_id = $user ORDER BY created_at LIMIT 50`, params: { $user: userId } },
145
+ ]);
146
+ const row = result.results[0]!.rows[0];
147
+ const recovery = row?.[1] ? (JSON.parse(row[1] as string) as string[]) : [];
148
+ return { totp: Boolean(row?.[0]), recoveryCodes: row?.[0] ? recovery.length : 0, passkeys: result.results[1]!.rows.map(passkeyOf).map(({ userId: _u, publicKey: _p, counter: _c, transports: _t, ...info }) => info) };
149
+ }
150
+
151
+ /** Whether the user has an authenticator app or a passkey. */
152
+ async hasSecondFactor(userId: string): Promise<boolean> {
153
+ const status = await this.status(userId);
154
+ return status.totp || status.passkeys.length > 0;
155
+ }
156
+
157
+ /** Whether a code from the authenticator app is required at sign-in (passkeys sign in on their own). */
158
+ async requiresCode(userId: string): Promise<boolean> {
159
+ return (await this.status(userId)).totp;
160
+ }
161
+
162
+ /**
163
+ * A new, unconfirmed authenticator secret. It takes effect once confirmed with a code. A
164
+ * confirmed authenticator stays as it is: replacing it means turning it off first, which
165
+ * asks for one of its codes, so starting a setup never removes the factor in use.
166
+ */
167
+ async startTotp(userId: string): Promise<string> {
168
+ const secret = generateTotpSecret();
169
+ const now = this.#now();
170
+ const result = await this.#db.write([
171
+ { rql: 'INSERT INTO cms_user_security (user_id, totp_secret, totp_confirmed_at, totp_last_step, recovery, updated_at) VALUES ($user, $secret, NULL, NULL, NULL, $now) ON CONFLICT (user_id) DO NOTHING',
172
+ params: { $user: userId, $secret: secret, $now: now } },
173
+ { rql: 'UPDATE cms_user_security SET totp_secret = $secret, totp_last_step = NULL, updated_at = $now WHERE user_id = $user AND totp_confirmed_at IS NULL',
174
+ params: { $user: userId, $secret: secret, $now: now } },
175
+ ], WRITE);
176
+ if (result.results[1]!.affected !== 1n) throw new CmsError('CMS_VALIDATION', 'An authenticator app is already on. Turn it off with one of its codes before setting up another.');
177
+ return secret;
178
+ }
179
+
180
+ /** The pending or confirmed secret, for showing the QR code again while setting up. */
181
+ async pendingSecret(userId: string): Promise<string | null> {
182
+ const result = await this.#db.read([{ rql: 'SELECT totp_secret, totp_confirmed_at FROM cms_user_security WHERE user_id = $user', params: { $user: userId } }]);
183
+ const row = result.results[0]!.rows[0];
184
+ return row && row[0] && !row[1] ? row[0] as string : null;
185
+ }
186
+
187
+ /** Confirm the authenticator with a current code. Returns new recovery codes, shown once. */
188
+ async confirmTotp(userId: string, code: string): Promise<string[]> {
189
+ const secret = await this.pendingSecret(userId);
190
+ if (!secret) throw new CmsError('CMS_VALIDATION', 'Start the authenticator setup again.');
191
+ const step = await verifyTotp(secret, code, { now: this.#now() });
192
+ if (step === null) throw new CmsError('CMS_VALIDATION', 'That code is not right. Check the time on your device and try again.', { fields: { code: 'is not right.' } });
193
+ const codes = generateRecoveryCodes();
194
+ const hashes = await Promise.all(codes.map(hashRecoveryCode));
195
+ await this.#db.write([{
196
+ rql: 'UPDATE cms_user_security SET totp_confirmed_at = $now, totp_last_step = $step, recovery = $recovery, updated_at = $now WHERE user_id = $user AND totp_secret = $secret',
197
+ params: { $now: this.#now(), $step: step, $recovery: JSON.stringify(hashes), $user: userId, $secret: secret },
198
+ }], WRITE);
199
+ return codes;
200
+ }
201
+
202
+ /** New recovery codes, replacing the old ones. Needs a confirmed authenticator. */
203
+ async regenerateRecoveryCodes(userId: string): Promise<string[]> {
204
+ if (!(await this.status(userId)).totp) throw new CmsError('CMS_VALIDATION', 'Set up an authenticator app first.');
205
+ const codes = generateRecoveryCodes();
206
+ await this.#db.write([{ rql: 'UPDATE cms_user_security SET recovery = $recovery, updated_at = $now WHERE user_id = $user',
207
+ params: { $recovery: JSON.stringify(await Promise.all(codes.map(hashRecoveryCode))), $now: this.#now(), $user: userId } }], WRITE);
208
+ return codes;
209
+ }
210
+
211
+ async disableTotp(userId: string): Promise<void> {
212
+ await this.#db.write([{ rql: 'DELETE FROM cms_user_security WHERE user_id = $user', params: { $user: userId } }], WRITE);
213
+ }
214
+
215
+ /**
216
+ * Check a second-factor code: the authenticator's current code (each step once) or an
217
+ * unused recovery code, which is used up.
218
+ */
219
+ async verifyCode(userId: string, code: string): Promise<'totp' | 'recovery' | null> {
220
+ const result = await this.#db.read([{ rql: 'SELECT totp_secret, totp_confirmed_at, totp_last_step, recovery FROM cms_user_security WHERE user_id = $user', params: { $user: userId } }]);
221
+ const row = result.results[0]!.rows[0];
222
+ if (!row || !row[1]) return null;
223
+ const last = row[2] === null ? null : Number(row[2] as bigint);
224
+ const step = await verifyTotp(row[0] as string, code, { now: this.#now(), afterStep: last });
225
+ if (step !== null) {
226
+ // The step is recorded only if no other sign-in used it first.
227
+ const update = await this.#db.write([{
228
+ rql: 'UPDATE cms_user_security SET totp_last_step = $step WHERE user_id = $user AND (totp_last_step IS NULL OR totp_last_step < $step)',
229
+ params: { $step: step, $user: userId },
230
+ }], WRITE);
231
+ return update.results[0]!.affected === 1n ? 'totp' : null;
232
+ }
233
+ const hashes = row[3] ? JSON.parse(row[3] as string) as string[] : [];
234
+ const hash = await hashRecoveryCode(code);
235
+ if (!hashes.includes(hash)) return null;
236
+ const update = await this.#db.write([{ rql: 'UPDATE cms_user_security SET recovery = $next, updated_at = $now WHERE user_id = $user AND recovery = $current',
237
+ params: { $next: JSON.stringify(hashes.filter(entry => entry !== hash)), $now: this.#now(), $user: userId, $current: row[3] as string } }], WRITE);
238
+ return update.results[0]!.affected === 1n ? 'recovery' : null;
239
+ }
240
+
241
+ async passkeys(userId: string): Promise<StoredPasskeyRow[]> {
242
+ const result = await this.#db.read([{ rql: `SELECT ${PASSKEY_COLUMNS} FROM cms_passkeys WHERE user_id = $user ORDER BY created_at LIMIT 50`, params: { $user: userId } }]);
243
+ return result.results[0]!.rows.map(passkeyOf);
244
+ }
245
+
246
+ async passkey(id: string): Promise<StoredPasskeyRow | null> {
247
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,1024}$/.test(id)) return null;
248
+ const result = await this.#db.read([{ rql: `SELECT ${PASSKEY_COLUMNS} FROM cms_passkeys WHERE id = $id`, params: { $id: id } }]);
249
+ const row = result.results[0]!.rows[0];
250
+ return row ? passkeyOf(row) : null;
251
+ }
252
+
253
+ async addPasskey(userId: string, passkey: { id: string; publicKey: string; counter: number; transports?: readonly string[]; deviceType?: string; backedUp?: boolean }, name: string): Promise<void> {
254
+ const label = name.trim().slice(0, 80) || 'Passkey';
255
+ if ((await this.passkeys(userId)).length >= 20) throw new CmsError('CMS_LIMIT', 'A user can have at most 20 passkeys.');
256
+ try {
257
+ await this.#db.write([{
258
+ rql: `INSERT INTO cms_passkeys (id, user_id, name, public_key, counter, transports, device_type, backed_up, created_at) VALUES ($id, $user, $name, $key, $counter, $transports, $device, $backed, $now)`,
259
+ params: { $id: passkey.id, $user: userId, $name: label, $key: passkey.publicKey, $counter: passkey.counter, $transports: passkey.transports ? JSON.stringify(passkey.transports) : null,
260
+ $device: passkey.deviceType ?? null, $backed: passkey.backedUp ? 1 : 0, $now: this.#now() },
261
+ }], WRITE);
262
+ } catch (error) {
263
+ if ((error as { code?: string }).code === 'RDB_CONSTRAINT') throw new CmsError('CMS_CONFLICT', 'This passkey is already registered.', { cause: error });
264
+ throw error;
265
+ }
266
+ }
267
+
268
+ async renamePasskey(userId: string, id: string, name: string): Promise<void> {
269
+ await this.#db.write([{ rql: 'UPDATE cms_passkeys SET name = $name WHERE id = $id AND user_id = $user', params: { $name: name.trim().slice(0, 80) || 'Passkey', $id: id, $user: userId } }], WRITE);
270
+ }
271
+
272
+ async removePasskey(userId: string, id: string): Promise<void> {
273
+ await this.#db.write([{ rql: 'DELETE FROM cms_passkeys WHERE id = $id AND user_id = $user', params: { $id: id, $user: userId } }], WRITE);
274
+ }
275
+
276
+ /** Record a passkey sign-in; the counter only moves forward. */
277
+ async usePasskey(id: string, counter: number): Promise<void> {
278
+ await this.#db.write([{ rql: 'UPDATE cms_passkeys SET counter = $counter, last_used_at = $now WHERE id = $id', params: { $counter: counter, $now: this.#now(), $id: id } }], WRITE);
279
+ }
280
+
281
+ /** Remove every second factor, for a user who lost their device. */
282
+ async reset(userId: string): Promise<void> {
283
+ await this.#db.write([
284
+ { rql: 'DELETE FROM cms_user_security WHERE user_id = $user', params: { $user: userId } },
285
+ { rql: 'DELETE FROM cms_passkeys WHERE user_id = $user', params: { $user: userId } },
286
+ ], WRITE);
287
+ }
288
+
289
+ /** A challenge kept for `ttlMs`; its random ID goes into a cookie or form. */
290
+ async createChallenge(kind: ChallengeKind, userId: string | null, challenge: string, ttlMs = 5 * 60_000): Promise<string> {
291
+ const id = randomToken(24);
292
+ await this.#db.write([{ rql: 'INSERT INTO cms_auth_challenges (id, kind, user_id, challenge, attempts, expires_at) VALUES ($id, $kind, $user, $challenge, 0, $expires)',
293
+ params: { $id: id, $kind: kind, $user: userId, $challenge: challenge, $expires: this.#now() + ttlMs } }], WRITE);
294
+ return id;
295
+ }
296
+
297
+ /** A live challenge of the kind, without using it up. */
298
+ async challenge(id: string, kind: ChallengeKind): Promise<{ userId: string | null; challenge: string; attempts: number } | null> {
299
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{20,64}$/.test(id)) return null;
300
+ const result = await this.#db.read([{ rql: 'SELECT user_id, challenge, attempts, expires_at FROM cms_auth_challenges WHERE id = $id AND kind = $kind', params: { $id: id, $kind: kind } }]);
301
+ const row = result.results[0]!.rows[0];
302
+ if (!row || Number(row[3] as bigint) <= this.#now()) return null;
303
+ return { userId: row[0] as string | null, challenge: row[1] as string, attempts: Number(row[2] as bigint) };
304
+ }
305
+
306
+ /** Use up a challenge: true only for the first caller while it is live. */
307
+ async takeChallenge(id: string, kind: ChallengeKind): Promise<boolean> {
308
+ const result = await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id = $id AND kind = $kind AND expires_at > $now', params: { $id: id, $kind: kind, $now: this.#now() } }], WRITE);
309
+ return result.results[0]!.affected === 1n;
310
+ }
311
+
312
+ /**
313
+ * Spend one try of a pending sign-in before its code is checked: counted on the challenge
314
+ * (in a conditional write, so codes sent at once each take a try and no more than
315
+ * `SIGN_IN_ATTEMPTS` are checked) and on the account (`SECOND_FACTOR_LOCK`). `expired` when
316
+ * the challenge has no tries left or ended, `locked` when the account has used its codes.
317
+ */
318
+ async secondFactorAttempt(id: string, userId: string): Promise<{ left: number } | 'expired' | 'locked'> {
319
+ const now = this.#now();
320
+ const counted = await this.#db.write([{ rql: 'UPDATE cms_auth_challenges SET attempts = attempts + 1 WHERE id = $id AND kind = $kind AND user_id = $user AND attempts < $max AND expires_at > $now',
321
+ params: { $id: id, $kind: 'signin', $user: userId, $max: SIGN_IN_ATTEMPTS, $now: now } }], WRITE);
322
+ if (counted.results[0]!.affected !== 1n) return 'expired';
323
+ if (!(await this.#count(secondFactorKey(userId), SECOND_FACTOR_LOCK.windowMs, SECOND_FACTOR_LOCK.perAccount))) {
324
+ await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id = $id', params: { $id: id } }], WRITE);
325
+ return 'locked';
326
+ }
327
+ const live = await this.#db.read([{ rql: 'SELECT attempts FROM cms_auth_challenges WHERE id = $id', params: { $id: id } }]);
328
+ const row = live.results[0]!.rows[0];
329
+ return { left: row ? SIGN_IN_ATTEMPTS - Number(row[0] as bigint) : 0 };
330
+ }
331
+
332
+ /**
333
+ * Spend one of the account's code tries outside a sign-in (turning the authenticator off,
334
+ * new recovery codes): the same per-account count as `secondFactorAttempt`, so codes cannot
335
+ * be guessed faster on the security page than at sign-in. False when the account is locked.
336
+ */
337
+ async codeAttempt(userId: string): Promise<boolean> {
338
+ return this.#count(secondFactorKey(userId), SECOND_FACTOR_LOCK.windowMs, SECOND_FACTOR_LOCK.perAccount);
339
+ }
340
+
341
+ /** A wrong code: the challenge ends once it has no tries left. */
342
+ async failChallenge(id: string): Promise<void> {
343
+ await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id = $id AND attempts >= $max', params: { $id: id, $max: SIGN_IN_ATTEMPTS } }], WRITE);
344
+ }
345
+
346
+ /** A right code: the account's second-factor count starts again. */
347
+ async secondFactorSucceeded(userId: string): Promise<void> {
348
+ await this.#db.write([{ rql: 'DELETE FROM cms_attempts WHERE key = $key', params: { $key: secondFactorKey(userId) } }], WRITE);
349
+ }
350
+
351
+ async purgeExpired(): Promise<void> {
352
+ const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_auth_challenges WHERE expires_at <= $now LIMIT 1', params: { $now: this.#now() } }]);
353
+ if (!expired.results[0]!.rows.length) return;
354
+ await this.#db.write([{ rql: 'DELETE FROM cms_auth_challenges WHERE id IN (SELECT id FROM cms_auth_challenges WHERE expires_at <= $now LIMIT 500)', params: { $now: this.#now() } }], WRITE);
355
+ }
356
+
357
+ /** Remove attempt counts whose window ended (500 at a time), which nothing else would. */
358
+ async purgeAttempts(): Promise<void> {
359
+ const now = this.#now();
360
+ const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_attempts WHERE until <= $now LIMIT 1', params: { $now: now } }]);
361
+ if (!expired.results[0]!.rows.length) return;
362
+ await this.#db.write([{ rql: 'DELETE FROM cms_attempts WHERE key IN (SELECT key FROM cms_attempts WHERE until <= $now LIMIT 500)', params: { $now: now } }], WRITE);
363
+ }
364
+ }
365
+
366
+ function passkeyOf(row: readonly Value[]): StoredPasskeyRow {
367
+ return Object.freeze({
368
+ id: row[0] as string, userId: row[1] as string, name: row[2] as string, publicKey: row[3] as string, counter: Number(row[4] as bigint),
369
+ transports: row[5] ? JSON.parse(row[5] as string) as string[] : null, deviceType: row[6] as string | null, backedUp: Number(row[7] as bigint) === 1,
370
+ createdAt: Number(row[8] as bigint), lastUsedAt: row[9] === null ? null : Number(row[9] as bigint),
371
+ });
372
+ }
373
+
374
+ /** The sign-in counter of an email: hashed, lower-cased. */
375
+ async function emailKey(email: string): Promise<string> {
376
+ return `signin:e:${await sha256Hex(email.trim().toLowerCase())}`;
377
+ }
378
+
379
+ /** The second-factor counter of an account. */
380
+ function secondFactorKey(userId: string): string {
381
+ return `signin:2fa:${userId.replace(/[^\x21-\x7e]/g, '-').slice(0, 100)}`;
382
+ }
383
+
384
+ /** The sign-in counter of a client address. */
385
+ function addressKey(address: string): string {
386
+ return `signin:a:${(address || 'unknown').replace(/[^\x21-\x7e]/g, '-').slice(0, 100)}`;
387
+ }
388
+
389
+ function attemptKey(kind: string, key: string): string {
390
+ return `attempt:${kind}:${key.replace(/[^\x21-\x7e]/g, '-').slice(0, 120)}`;
391
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Starter content for a new site, as WordPress ships a first post and page: a "Hello World!"
3
+ * post in an "Uncategorized" category, a "Contact Form" form and a "Contact" page that places
4
+ * it. Seeded once at setup; a site that already has entries is left alone.
5
+ */
6
+ import type { Block } from '../blocks';
7
+ import { richTextFromPlain } from '../richtext';
8
+ import type { Principal } from '../permissions';
9
+ import type { CmsHost } from './host';
10
+
11
+ export interface SeedReport {
12
+ /** Whether anything was created; false when the site already had content. */
13
+ readonly seeded: boolean;
14
+ }
15
+
16
+ const input = (id: string, kind: string, data: { [key: string]: unknown }): Block => ({ _id: id, type: `form/${kind}`, data });
17
+
18
+ /** Create the starter content when the site has no posts, pages or forms. */
19
+ export async function seedStarterContent(cms: CmsHost, context: { principal: Principal }): Promise<SeedReport> {
20
+ const { principal } = context;
21
+ const has = async (resource: string) => cms.resourceById(resource) ? (await cms.resource(resource).list({ limit: 1 }, { principal })).records.length > 0 : true;
22
+ if (await has('cms/posts') || await has('cms/pages') || await has('cms/forms')) return { seeded: false };
23
+
24
+ const category = await cms.taxonomies.create('categories', { name: 'Uncategorized', slug: 'uncategorized' }, { principal });
25
+ await cms.settings.update('writing', { defaultCategory: category.id }, { principal });
26
+
27
+ const form = await cms.resource('cms/forms').create({
28
+ title: 'Contact Form', slug: 'contact-form', status: 'published',
29
+ body: [
30
+ input('name', 'text', { name: 'name', label: 'Your name', required: true }),
31
+ input('email', 'email', { name: 'email', label: 'Email', required: true }),
32
+ input('message', 'textarea', { name: 'message', label: 'Message', required: true }),
33
+ ],
34
+ settings: { submitLabel: 'Send', message: 'Thanks! We received your message and will reply soon.' },
35
+ notifications: { rules: [{ id: 'admin', label: 'Admin notification', to: '{admin_email}', subject: 'New message from {field:name}', body: '{all_fields}\n\n{submission:url}', replyTo: '{field:email}' }] },
36
+ }, { principal });
37
+
38
+ await cms.resource('cms/pages').create({
39
+ title: 'Contact', slug: 'contact', status: 'published',
40
+ content: [
41
+ { _id: 'intro', type: 'core/richtext', data: { text: richTextFromPlain('Have a question? Send us a message and we will get back to you.') } },
42
+ { _id: 'form', type: 'core/form', data: { form: String(form.slug) } },
43
+ ],
44
+ }, { principal });
45
+
46
+ await cms.resource('cms/posts').create({
47
+ title: 'Hello World!', slug: 'hello-world', status: 'published', categories: [category.id],
48
+ excerpt: 'Welcome to your new site. This is your first post: edit or delete it, then start writing.',
49
+ content: [{ _id: 'intro', type: 'core/richtext', data: { text: richTextFromPlain('Welcome to your new site. This is your first post. Edit or delete it, then start writing!') } }],
50
+ }, { principal });
51
+ return { seeded: true };
52
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Fields that are the same in every language reach an entry's other translations in the entry's
3
+ * own update; their revision, audit, search and outbox rows follow from this outbox job, queued in
4
+ * that update, so a crash, an abort or an unconfirmed write after the update still writes them.
5
+ */
6
+ import { defineAction } from '@cossackframework/core/hooks';
7
+ import type { WriteActor } from '../hooks';
8
+
9
+ export interface SharedFieldsEvent {
10
+ readonly eventId: string;
11
+ readonly topic: 'resource.shared';
12
+ readonly at: number;
13
+ readonly resource: string;
14
+ /** The entry the editor saved, its translation group and the update's operation ID. */
15
+ readonly id: string;
16
+ readonly group: string;
17
+ readonly op: string;
18
+ readonly actor: WriteActor;
19
+ }
20
+
21
+ /** Runs from the outbox; the host handles it, plugins cannot hook it. */
22
+ export const sharedFields = defineAction<SharedFieldsEvent>('cms.resource.shared', { version: 1, timeoutMs: 60_000 });
23
+
24
+ /**
25
+ * The operation ID of one translation's rows from one shared update: the same on every retry, so
26
+ * rows a retry finds already written are not written again. A UUID of version 8 from SHA-256.
27
+ */
28
+ export async function sharedOp(op: string, id: string): Promise<string> {
29
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${op}:${id}`)));
30
+ digest[6] = (digest[6]! & 0x0f) | 0x80;
31
+ digest[8] = (digest[8]! & 0x3f) | 0x80;
32
+ const hex = [...digest.subarray(0, 16)].map(byte => byte.toString(16).padStart(2, '0')).join('');
33
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
34
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * A site's database as one JSON document, streamed table by table, for the site to keep or
3
+ * move. Values use RomeDB's portable encoding (`encodeValue`), so integers, record IDs and
4
+ * binary values come back exactly with `decodeValue`. Media files are not included: `cms_files`
5
+ * rows name their storage keys.
6
+ */
7
+ import { ClientError, encodeValue, type DatabaseFile, type RecordId, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
8
+ import { HOST_TABLES } from './host-schema';
9
+
10
+ /**
11
+ * Tables left out: credentials and sign-in state (sessions, second factors, passkeys, reset
12
+ * tokens, application passwords, preview links, handoffs), the cache, and the network's own
13
+ * tables, which hold accounts and the site registry on the main site.
14
+ */
15
+ export const EXPORT_SKIPPED_TABLES: ReadonlySet<string> = new Set([
16
+ 'cms_auth_sessions', 'cms_sessions', 'cms_session_values', 'cms_session_sites', 'cms_oauth_states', 'cms_password_resets', 'cms_auth_challenges',
17
+ 'cms_user_security', 'cms_passkeys', 'cms_api_tokens', 'cms_preview_tokens', 'cms_handoffs', 'cms_cache', 'cms_attempts', 'cms_schedules',
18
+ 'cms_accounts', 'cms_sites', 'cms_site_domains', 'cms_memberships', 'cms_network',
19
+ // The search index is built from the entries; an import rebuilds it.
20
+ 'cms_search',
21
+ // Resized copies are made again on request; an imported row could name any stored object.
22
+ 'cms_file_variants',
23
+ // Each database counts its own schema changes.
24
+ 'cms_schema_generations',
25
+ ]);
26
+
27
+ /** Columns exported as null: webhook signing secrets. */
28
+ export const EXPORT_REDACTED_COLUMNS: Readonly<Record<string, readonly string[]>> = Object.freeze({ cms_webhooks: ['secret'] });
29
+
30
+ /**
31
+ * Tables a `.romedb` file leaves empty: sign-in state (sessions are keyed by their tokens, so a
32
+ * copy would sign in on the live site), authenticator apps and recovery codes (the secrets are
33
+ * stored as they are, so a copy would make valid codes), the cache, pending work, which would
34
+ * run again where the file is opened, webhooks, whose secrets are the live site's, and
35
+ * application passwords, which would sign scripts in to the copy. Accounts stay with their
36
+ * password hashes and passkeys (public keys), so a site's own accounts keep signing in; they
37
+ * set up an authenticator app and application passwords again.
38
+ */
39
+ export const FILE_EXPORT_EMPTIED_TABLES: readonly string[] = [
40
+ 'cms_user_security', 'cms_api_tokens',
41
+ 'cms_auth_sessions', 'cms_sessions', 'cms_session_values', 'cms_session_sites', 'cms_oauth_states', 'cms_password_resets', 'cms_auth_challenges',
42
+ 'cms_preview_tokens', 'cms_handoffs', 'cms_cache', 'cms_attempts', 'cms_outbox', 'cms_webhooks', 'cms_webhook_deliveries', 'cossack_jobs', 'cms_schedules',
43
+ 'cms_file_variants',
44
+ ];
45
+
46
+ /** RomeDB's longest wait for a copy to start arriving. On Cloud a job builds it first. */
47
+ const FILE_EXPORT_TIMEOUT = 120_000;
48
+
49
+ /**
50
+ * A site's database as a `.romedb` file, which a new install opens directly: one snapshot while
51
+ * the site keeps running, on every runtime. RomeDB never reads the tables above into the copy,
52
+ * so no part of the file holds their rows, and the file is a new database.
53
+ */
54
+ export async function siteFile(db: RomeDB, options: { signal?: AbortSignal } = {}): Promise<DatabaseFile> {
55
+ const signal = options.signal ? { signal: options.signal } : {};
56
+ // Every site's database has every host table, so each named table exists.
57
+ return db.exportFile({ ...signal, timeoutMs: FILE_EXPORT_TIMEOUT, emptyTables: [...FILE_EXPORT_EMPTIED_TABLES] });
58
+ }
59
+
60
+ /** A new webhook secret, for one that comes from a copy or an export. */
61
+ export function newSecret(): string {
62
+ return [...crypto.getRandomValues(new Uint8Array(32))].map(byte => byte.toString(16).padStart(2, '0')).join('');
63
+ }
64
+
65
+ export interface SiteExportOptions {
66
+ /** What the document says it is: the site's ID, name and address. */
67
+ readonly site: { readonly id: string; readonly name: string; readonly host: string | null };
68
+ readonly now?: () => number;
69
+ /** Rows per read. Default 200. */
70
+ readonly pageSize?: number;
71
+ readonly signal?: AbortSignal;
72
+ }
73
+
74
+ /**
75
+ * The export as text chunks: `{ format: 'cossack-site-export', version: 1, exportedAt, site,
76
+ * skipped, redacted, tables: [{ name, model, columns?, rows }] }`. Relational rows are arrays in
77
+ * `columns` order; document rows are whole documents. The CMS's own tables come first, by name,
78
+ * so an import has the collections' definitions before their records; then the rest, by name.
79
+ * Each table is read in key order, a page at a time, at least as fresh as the first read.
80
+ */
81
+ export async function* siteExport(db: RomeDB, options: SiteExportOptions): AsyncGenerator<string> {
82
+ const read = (statements: Statement[], after?: number) => db.read(statements, { ...(after === undefined ? {} : { afterSequence: after }), ...(options.signal ? { signal: options.signal } : {}) });
83
+ const first = await read([{ rql: 'INFO FOR DB' }]);
84
+ const sequence = first.sequence;
85
+ const info = first.results[0]!.rows[0]![0] as unknown as { tables?: { name: string; model: string }[] };
86
+ const tables = (info.tables ?? []).filter(table => !EXPORT_SKIPPED_TABLES.has(table.name) && (table.model === 'relational' || table.model === 'document'))
87
+ .sort((a, b) => Number(!HOST.has(a.name)) - Number(!HOST.has(b.name)) || a.name.localeCompare(b.name));
88
+ const json = (value: unknown) => JSON.stringify(value);
89
+ const pageSize = Math.min(Math.max(options.pageSize ?? 200, 1), 1000);
90
+ yield `{"format":"cossack-site-export","version":1,"exportedAt":${json(new Date((options.now ?? Date.now)()).toISOString())},"site":${json(options.site)},`
91
+ + `"skipped":${json([...EXPORT_SKIPPED_TABLES].sort())},"redacted":${json(EXPORT_REDACTED_COLUMNS)},"tables":[`;
92
+ for (const [index, table] of tables.entries()) {
93
+ const name = quote(table.name);
94
+ let columns: string[] = [];
95
+ // Pages follow the key, each read after the last row's key, so a row a write moves or
96
+ // removes meanwhile neither repeats nor pushes another row past a page boundary.
97
+ let keys: string[] = [];
98
+ if (table.model === 'relational') {
99
+ const described = (await read([{ rql: `INFO FOR TABLE ${name}` }], sequence)).results[0]!.rows[0]![0] as unknown as { columns: { name: string; pk: bigint | number }[] };
100
+ columns = described.columns.map(column => column.name);
101
+ keys = described.columns.filter(column => Number(column.pk) > 0).sort((a, b) => Number(a.pk) - Number(b.pk)).map(column => column.name);
102
+ }
103
+ const redacted = new Set(EXPORT_REDACTED_COLUMNS[table.name] ?? []);
104
+ yield `${index ? ',' : ''}{"name":${json(table.name)},"model":${json(table.model)},${table.model === 'relational' ? `"columns":${json(columns)},` : ''}"rows":[`;
105
+ let count = 0;
106
+ let size = pageSize;
107
+ const rowid = table.model === 'relational' && !keys.length;
108
+ const order = table.model === 'document' ? 'id' : rowid ? 'rowid' : keys.map(quote).join(', ');
109
+ let last: Value[] | null = null;
110
+ for (;;) {
111
+ const select = table.model === 'relational' ? [...columns.map(quote), ...(rowid ? ['rowid'] : [])].join(', ') : '*';
112
+ const params: { [key: string]: Value } = { $limit: size };
113
+ let after = '';
114
+ if (last) {
115
+ if (table.model === 'document') after = `WHERE id > type::record('${table.name.replaceAll("'", "''")}', $k0)`;
116
+ else if (rowid) after = 'WHERE rowid > $k0';
117
+ // (a > $k0) OR (a = $k0 AND b > $k1) …: after the last row in key order.
118
+ else after = `WHERE ${keys.map((_, i) => `(${[...keys.slice(0, i).map((key, j) => `${quote(key)} = $k${j}`), `${quote(keys[i]!)} > $k${i}`].join(' AND ')})`).join(' OR ')}`;
119
+ last.forEach((value, i) => { params[`$k${i}`] = value; });
120
+ }
121
+ let page;
122
+ try { page = (await read([{ rql: `SELECT ${select} FROM ${name} ${after} ORDER BY ${order} LIMIT $limit`, params }], sequence)).results[0]!; }
123
+ catch (error) {
124
+ // A page of large rows can pass the limit on one response: read fewer.
125
+ if (error instanceof ClientError && (error.code === 'RDB_LIMIT' || error.code === 'RDB_RESULT_TOO_LARGE') && size > 1) { size = Math.max(1, Math.floor(size / 2)); continue; }
126
+ throw error;
127
+ }
128
+ const rows = page.rows.map(row => table.model === 'relational'
129
+ ? json(row.slice(0, columns.length).map((value, column) => encodeValue(redacted.has(columns[column]!) ? null : value as Value)))
130
+ : json(encodeValue(row[0] as Value)));
131
+ if (rows.length) yield `${count ? ',' : ''}${rows.join(',')}`;
132
+ count += rows.length;
133
+ const end = page.rows.at(-1);
134
+ if (end) {
135
+ if (table.model === 'document') last = [((end[0] as { id: RecordId }).id).key as Value];
136
+ else if (rowid) last = [end[columns.length] as Value];
137
+ else last = keys.map(key => end[columns.indexOf(key)] as Value);
138
+ }
139
+ if (page.rows.length < size) break;
140
+ }
141
+ yield ']}';
142
+ }
143
+ yield ']}\n';
144
+ }
145
+
146
+ const HOST: ReadonlySet<string> = new Set(HOST_TABLES);
147
+
148
+ /** A RomeQL identifier, quoted when it is not a plain lowercase name. */
149
+ export function quote(name: string): string {
150
+ return /^[a-z_][a-z0-9_]*$/.test(name) ? name : `"${name.replaceAll('"', '""')}"`;
151
+ }