tinyzoo 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (391) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +99 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +392 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTooMany.ts +9 -0
  312. package/server/utils/cmsTranslationWrite.ts +186 -0
  313. package/server/utils/cmsTree.ts +251 -0
  314. package/server/utils/cmsTreeAddress.ts +65 -0
  315. package/server/utils/cmsUpload.ts +197 -0
  316. package/server/utils/cmsWebhooks.ts +101 -0
  317. package/shared/json.ts +11 -0
  318. package/shared/richtext-editor.ts +56 -0
  319. package/shared/richtext-normalize.ts +33 -0
  320. package/shared/richtext-paste.ts +151 -0
  321. package/shared/storage-delivery.ts +53 -0
  322. package/src/blocks.ts +624 -0
  323. package/src/changes.ts +54 -0
  324. package/src/content-shape.ts +340 -0
  325. package/src/deprecate.ts +64 -0
  326. package/src/descriptor.ts +149 -0
  327. package/src/docs.ts +27 -0
  328. package/src/emitter.ts +94 -0
  329. package/src/entity.ts +624 -0
  330. package/src/errorReport.ts +41 -0
  331. package/src/fields.ts +465 -0
  332. package/src/i18n.ts +26 -0
  333. package/src/index.ts +54 -0
  334. package/src/linkref.ts +31 -0
  335. package/src/links.ts +179 -0
  336. package/src/locales.ts +39 -0
  337. package/src/media.ts +48 -0
  338. package/src/migrate.ts +236 -0
  339. package/src/openapi.ts +377 -0
  340. package/src/paths.ts +88 -0
  341. package/src/plugin.ts +505 -0
  342. package/src/presets.ts +230 -0
  343. package/src/richtext.ts +88 -0
  344. package/src/sdk.ts +181 -0
  345. package/src/search.ts +312 -0
  346. package/src/seed.ts +225 -0
  347. package/src/setupCode.ts +30 -0
  348. package/src/system.ts +219 -0
  349. package/src/tree.ts +421 -0
  350. package/src/upgrades.ts +137 -0
  351. package/starter/.env.example +10 -0
  352. package/starter/README.md +65 -0
  353. package/starter/app/app.config.ts +10 -0
  354. package/starter/app/app.vue +12 -0
  355. package/starter/app/assets/css/main.css +15 -0
  356. package/starter/app/components/global/BlockContact.vue +15 -0
  357. package/starter/app/components/global/BlockCta.vue +15 -0
  358. package/starter/app/components/global/BlockHero.vue +23 -0
  359. package/starter/app/components/global/BlockImage.vue +13 -0
  360. package/starter/app/components/global/BlockText.vue +12 -0
  361. package/starter/app/composables/useSite.ts +77 -0
  362. package/starter/app/error.vue +28 -0
  363. package/starter/app/layouts/default.vue +106 -0
  364. package/starter/app/lib/cms-content.ts +152 -0
  365. package/starter/app/pages/[...slug].vue +66 -0
  366. package/starter/app/pages/hledat.vue +59 -0
  367. package/starter/app/pages/index.vue +20 -0
  368. package/starter/cms.config.ts +137 -0
  369. package/starter/compose.yaml +15 -0
  370. package/starter/drizzle.config.ts +8 -0
  371. package/starter/gitignore.txt +8 -0
  372. package/starter/nuxt.config.ts +13 -0
  373. package/starter/package.json +38 -0
  374. package/starter/scripts/typecheck.mjs +38 -0
  375. package/starter/seed/index.ts +297 -0
  376. package/starter/seed/media/about.jpg +0 -0
  377. package/starter/seed/media/hero.jpg +0 -0
  378. package/starter/seed/media/logo.png +0 -0
  379. package/starter/seed/media/news-bread.jpg +0 -0
  380. package/starter/seed/media/news-morning.jpg +0 -0
  381. package/starter/server/db/migrations/0000_init.sql +269 -0
  382. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  383. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  384. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  385. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  386. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  387. package/starter/server/db/migrations/meta/_journal.json +27 -0
  388. package/starter/server/db/schema.ts +253 -0
  389. package/starter/server/plugins/sitemap.ts +11 -0
  390. package/starter/server/routes/robots.txt.get.ts +12 -0
  391. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,14 @@
1
+ // While start-up migrations run, API requests wait for them (a fresh pod can accept
2
+ // connections before the schema is ready); if they failed, the API answers 503
3
+ // instead of running against a half-migrated database. Health checks pass through.
4
+ export default defineEventHandler(async (event) => {
5
+ const path = event.path || ''
6
+ // Health checks and framework endpoints (/api/_nuxt_icon, /api/_auth/session) pass.
7
+ if (!path.startsWith('/api/') || path.startsWith('/api/health/') || path.startsWith('/api/_')) return
8
+ try {
9
+ await cmsMigrationsReady()
10
+ }
11
+ catch {
12
+ throw createError({ statusCode: 503, statusMessage: 'Database migrations failed; see the server log' })
13
+ }
14
+ })
@@ -0,0 +1,28 @@
1
+ // Cross-site request forgery guard for the cookie-authenticated admin API.
2
+ //
3
+ // SameSite=Lax cookies stop other *sites*, but not a page on a sibling subdomain or
4
+ // any page of the host app itself (the admin shares its origin), and h3 parses
5
+ // classic HTML form posts (urlencoded / multipart) into objects the handlers accept.
6
+ // So every state-changing /api/cms/** request must:
7
+ // 1. carry a JSON body (or none) — a plain HTML form cannot send application/json;
8
+ // multipart is accepted only for the media upload endpoint, and
9
+ // 2. when the browser says where it comes from (Sec-Fetch-Site), come from the same
10
+ // origin (or be typed by the user: 'none').
11
+ const SAFE = new Set(['GET', 'HEAD', 'OPTIONS'])
12
+
13
+ export default defineEventHandler((event) => {
14
+ const path = (event.path || '').split('?')[0]!
15
+ if (!path.startsWith('/api/cms/') || SAFE.has(event.method)) return
16
+
17
+ const site = getRequestHeader(event, 'sec-fetch-site')
18
+ if (site && site !== 'same-origin' && site !== 'none') {
19
+ throw createError({ statusCode: 403, statusMessage: 'Cross-site request refused' })
20
+ }
21
+
22
+ const type = (getRequestHeader(event, 'content-type') || '').split(';')[0]!.trim().toLowerCase()
23
+ const hasBody = Number(getRequestHeader(event, 'content-length') || 0) > 0 || !!getRequestHeader(event, 'transfer-encoding')
24
+ if (!hasBody && !type) return
25
+ if (type === 'application/json') return
26
+ if (type === 'multipart/form-data' && event.method === 'POST' && path === '/api/cms/_media') return
27
+ throw createError({ statusCode: 415, statusMessage: 'Send JSON (application/json)' })
28
+ })
@@ -0,0 +1,20 @@
1
+ // Coarse Content-Length ceiling for CMS API routes — a defense-in-depth bound
2
+ // enforced before any handler reads the body. The media upload route gets the
3
+ // configured media cap; every other JSON route gets a small cap. A chunked request
4
+ // has no Content-Length, so this cannot see it: the upload route counts the bytes
5
+ // that actually arrive (cmsUpload.ts) and h3's JSON reader does the same for the rest.
6
+ const JSON_MAX = 4 * 1024 * 1024 // 4MB
7
+
8
+ export default defineEventHandler((event) => {
9
+ const path = event.path || ''
10
+ if (!path.startsWith('/api/cms/')) return
11
+
12
+ const len = Number(getHeader(event, 'content-length') || 0)
13
+ if (!len) return
14
+
15
+ const isUpload = event.method === 'POST' && path.startsWith('/api/cms/_media')
16
+ const max = isUpload ? maxUploadBytes() + 1024 * 1024 : JSON_MAX
17
+ if (len > max) {
18
+ throw createError({ statusCode: 413, statusMessage: 'Request body too large' })
19
+ }
20
+ })
@@ -0,0 +1,21 @@
1
+ // Apply redirects (defineRedirects) to page requests: GET/HEAD for anything that is
2
+ // not the API, the admin or a build asset. Query strings are carried over.
3
+ const SKIP = ['/api/', '/admin', '/_nuxt/', '/__nuxt', '/_ipx/', '/favicon']
4
+
5
+ export default defineEventHandler(async (event) => {
6
+ if (event.method !== 'GET' && event.method !== 'HEAD') return
7
+ const path = event.path || '/'
8
+ if (SKIP.some((p) => path.startsWith(p))) return
9
+ let target
10
+ try {
11
+ target = await findRedirect(path)
12
+ }
13
+ catch (err) {
14
+ console.error('[cms] redirect lookup failed', scrubError(err))
15
+ return
16
+ }
17
+ if (!target) return
18
+ const query = path.includes('?') ? path.slice(path.indexOf('?')) : ''
19
+ const dest = target.to.includes('?') || !query ? target.to : target.to + query
20
+ return sendRedirect(event, locationHeader(dest), target.status)
21
+ })
@@ -0,0 +1,41 @@
1
+ // Built-in auth: turn the sealed session cookie into `event.context.cmsUser` for API
2
+ // requests. The account is re-read from the database every time, so a changed role,
3
+ // a disabled account or a password change (session version bump) takes effect on
4
+ // the very next request — a still-valid cookie is not enough.
5
+ //
6
+ // The CMS identity lives under its own key (session.cms.uid), so a host app that
7
+ // also signs people in with nuxt-auth-utils (site members, OAuth ids…) never trips
8
+ // over it: a session without a CMS identity is simply not a CMS user.
9
+
10
+ export default defineEventHandler(async (event) => {
11
+ if (cmsAuthMode() !== 'builtin') return
12
+ const path = event.path || ''
13
+ const page = path === '/admin' || path.startsWith('/admin/') || path.startsWith('/admin?')
14
+ if (!path.startsWith('/api/') && !page) return
15
+ if (event.context.cmsUser) return
16
+
17
+ // No session cookie: nobody to look up. Reading the session anyway would create one and
18
+ // put a cookie on the response of every anonymous visitor (public content, pages, media).
19
+ if (!hasSessionCookie(event)) {
20
+ // nuxt-auth-utils' own route, which the website's server rendering calls on every page:
21
+ // an anonymous answer without opening a session either.
22
+ if (path.split('?')[0] === '/api/_auth/session' && event.method === 'GET') return {}
23
+ return
24
+ }
25
+
26
+ const session: any = await getUserSession(event)
27
+ // An admin page with no CMS identity in the cookie: nothing to check.
28
+ if (page && !session?.cms) return
29
+ const u = await activeAccountOf(session)
30
+ if (!u) {
31
+ // The cookie no longer opens the admin (role or password changed, account
32
+ // disabled): drop it on this very response — for an admin page too, so the
33
+ // browser lands on sign-in instead of bouncing between sign-in and the admin.
34
+ if (session?.cms) await clearUserSession(event)
35
+ return
36
+ }
37
+ event.context.cmsUser = { id: u.id, email: u.email, name: u.name || u.email, role: u.role, locale: u.locale }
38
+ // The version this request was authorised with; writes that re-sign the session
39
+ // must not upgrade a session past a concurrent password change (see me.patch).
40
+ event.context.cmsSessionVersion = u.sessionVersion
41
+ })
@@ -0,0 +1,15 @@
1
+ import { pluginRouteAccess } from 'tinyzoo'
2
+
3
+ // Plugin routes (/api/cms/_p/<plugin>/…) are closed unless the plugin says otherwise:
4
+ // a signed-in person by default, an administrator or anyone when the handler declares
5
+ // `access: 'admin'` / `'public'`. Checked here, before the handler runs, so a plugin
6
+ // cannot forget it. Runs after cms-session (which says who is signed in): Nitro orders middleware by file name, hence the "z".
7
+ // Plugin routes on the content API (`contentPath`) are open, like the content API itself.
8
+ export default defineEventHandler((event) => {
9
+ const path = event.path || ''
10
+ if (!path.startsWith('/api/cms/_p/')) return
11
+ const access = pluginRouteAccess(useCms().reg.plugins, event.method, path)
12
+ if (access === 'public' || access === null) return
13
+ const user = requireCmsUser(event)
14
+ if (access === 'admin' && user.role !== 'admin') throw createError({ statusCode: 403, statusMessage: 'Administrators only' })
15
+ })
@@ -0,0 +1,35 @@
1
+ // Check the settings a production server cannot work without, when it starts: the platform
2
+ // then shows a start that failed with the variable's name, instead of a server that
3
+ // answers "ready" and fails the first sign-in (or the first request) with a bare 500.
4
+ // - NUXT_SESSION_PASSWORD: at least 32 characters (it seals the session cookie);
5
+ // - a database address: NUXT_CMS_DATABASE_URL or DATABASE_URL;
6
+ // - NUXT_CMS_PUBLIC_URL: not fatal, but the sitemap and the links in emails need it — one warning.
7
+ // Development keeps its defaults (nuxt-auth-utils makes a password, the dev database is
8
+ // in .env); a prerender during the build has no runtime settings either.
9
+ export default defineNitroPlugin(() => {
10
+ if (process.env.NODE_ENV !== 'production' || import.meta.prerender) return
11
+ const config = useRuntimeConfig()
12
+ const cms = (config.cms ?? {}) as any
13
+
14
+ const problems: string[] = []
15
+ if (cmsAuthMode() === 'builtin') {
16
+ const password = String(process.env.NUXT_SESSION_PASSWORD || (config.session as any)?.password || '')
17
+ if (password.length < 32) {
18
+ problems.push(`NUXT_SESSION_PASSWORD is ${password ? 'only ' + password.length + ' characters long' : 'not set'}; it must be at least 32 characters `
19
+ + '(it seals the session cookie). Make one with: openssl rand -base64 32')
20
+ }
21
+ }
22
+ if (!(process.env.NUXT_CMS_DATABASE_URL || process.env.DATABASE_URL || cms.databaseUrl)) {
23
+ problems.push('No database address: set DATABASE_URL (or NUXT_CMS_DATABASE_URL) to a Postgres connection string, e.g. postgres://user:password@host:5432/dbname')
24
+ }
25
+ if (problems.length) {
26
+ const message = '[tinyzoo] the server cannot start:\n - ' + problems.join('\n - ')
27
+ console.error(message)
28
+ throw new Error(message)
29
+ }
30
+
31
+ if (!String(cms.publicUrl || '').trim()) {
32
+ console.warn('[cms] NUXT_CMS_PUBLIC_URL is not set: /sitemap.xml and the links in invitation and password-reset emails need the site\'s public address '
33
+ + '(e.g. https://cms.example.com). Set it in the environment.')
34
+ }
35
+ })
@@ -0,0 +1,53 @@
1
+ import type { CmsChange } from 'tinyzoo'
2
+
3
+ // Listen for content changes saved on the OTHER replicas (shared store, `changes`
4
+ // channel) and clear this instance's caches built from that content. Changes saved
5
+ // here were applied when they were reported.
6
+ export default defineNitroPlugin((nitroApp) => {
7
+ // The shared-editing engine starts with the server, so a first connection after a
8
+ // boot finds it ready (its messages would otherwise arrive before it listens).
9
+ useCollabServer().catch((err) => console.error('[cms] collab could not start', scrubError(err)))
10
+ nitroApp.hooks.hook('close', async () => {
11
+ stopLive()
12
+ await stopCollabServer()
13
+ await closeCmsStore()
14
+ })
15
+ void (async () => {
16
+ try {
17
+ const store = await useCmsStore()
18
+ await store.subscribe(CHANGES_CHANNEL, (raw) => {
19
+ try {
20
+ const msg = JSON.parse(raw)
21
+ if (msg?.origin === instanceId()) return
22
+ const change = validChange(msg?.change)
23
+ if (!change) return
24
+ applyChangeLocally(change)
25
+ notifyChangeListeners(change)
26
+ }
27
+ catch { /* not ours */ }
28
+ })
29
+ }
30
+ catch (err) {
31
+ console.error('[cms] could not listen for changes from other instances', scrubError(err))
32
+ }
33
+ })()
34
+ })
35
+
36
+ const TYPES = new Set(['entry.created', 'entry.updated', 'entry.deleted', 'entry.published', 'entry.unpublished', 'translation.updated', 'translation.deleted', 'global.updated'])
37
+ const str = (v: unknown, max = 200) => (typeof v === 'string' && v.length <= max ? v : null)
38
+
39
+ /** A change as another replica sent it, rebuilt field by field (it may reach browsers). */
40
+ function validChange(c: any): CmsChange | null {
41
+ if (!c || !TYPES.has(c.type) || !str(c.entity, 64) || !str(c.id, 64)) return null
42
+ return {
43
+ type: c.type,
44
+ entity: c.entity,
45
+ id: c.id,
46
+ locale: str(c.locale, 20),
47
+ public: c.public === true,
48
+ paths: Array.isArray(c.paths) ? c.paths.filter((p: unknown) => str(p, 2000)).slice(0, 50) : [],
49
+ by: str(c.by, 64),
50
+ version: str(c.version, 40),
51
+ at: str(c.at, 40) ?? new Date().toISOString(),
52
+ }
53
+ }
@@ -0,0 +1,21 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ // Public content answers (marked by setContentCache) carry an ETag: a fingerprint of
4
+ // the answer. Browsers check back on every request (max-age=0) and send it as
5
+ // If-None-Match; when the content has not changed they get "304 Not Modified" with no
6
+ // body, so checking every time stays cheap and a published change shows at once.
7
+ export default defineNitroPlugin((nitroApp) => {
8
+ nitroApp.hooks.hook('beforeResponse', (event: any, response: { body?: unknown }) => {
9
+ if (!event.context?.cmsContentEtag) return
10
+ if (event.method !== 'GET' && event.method !== 'HEAD') return
11
+ if (getResponseStatus(event) !== 200 || response.body === null || response.body === undefined) return
12
+ const text = typeof response.body === 'string' ? response.body : JSON.stringify(response.body)
13
+ const etag = `W/"${createHash('sha1').update(text).digest('base64url')}"`
14
+ setResponseHeader(event, 'ETag', etag)
15
+ const sent = getRequestHeader(event, 'if-none-match')
16
+ if (sent && sent.split(',').some((t) => t.trim() === etag || t.trim() === '*')) {
17
+ setResponseStatus(event, 304)
18
+ response.body = null
19
+ }
20
+ })
21
+ })
@@ -0,0 +1,45 @@
1
+ // Server errors as one JSON line each on stderr (Pushbase collects both streams), with the request id
2
+ // the user saw in X-Request-Id. Expected errors (4xx) are not logged, nor 503s (the
3
+ // API refusing work while migrations run or after they failed — logged once at start).
4
+ // The same errors run the `cms:error` hook for the host's error tracker (cmsErrors.ts).
5
+ //
6
+ // Nitro would also print an unhandled error itself, with a failed query's parameters (emails,
7
+ // form text, password hashes) and the request URL: this hook runs first and, in production,
8
+ // hushes the error (cmsScrub.ts `hushError`) so that only the JSON line below is written.
9
+ // The original is kept as `rawError` of the `cms:error` report. In development Nitro's own
10
+ // output stays: a developer wants the full message and a terminal is not a log store.
11
+ export default defineNitroPlugin((nitroApp) => {
12
+ nitroApp.hooks.hook('error', (thrown: any, ctx: any) => {
13
+ const quiet = !import.meta.dev && !!thrown && typeof thrown === 'object' && (thrown.unhandled === true || thrown.fatal === true)
14
+ const error = quiet ? snapshotError(thrown) : thrown
15
+ if (quiet) hushError(thrown)
16
+ const status = error?.statusCode ?? error?.status ?? 500
17
+ // Expected errors stay out of the log — except as one short info line when Nitro's own
18
+ // (error-looking, stack-printing) line for an unhandled one was just silenced: a 404 for
19
+ // a mistyped address or a probe for a route that does not exist is not an error of ours.
20
+ const expected = status < 500 || status === 503
21
+ if (expected && !quiet) return
22
+ const event = ctx?.event
23
+ const cause = error?.cause instanceof Error ? error.cause : error
24
+ const requestId: string | null = event?.context?.requestId ?? null
25
+ const method: string | null = event?.method ?? null
26
+ const path: string | null = event?.path ? String(event.path).split('?')[0] ?? null : null
27
+ const userId: string | null = event?.context?.cmsUser?.id ?? null
28
+ if (expected) {
29
+ console.info(JSON.stringify({ level: 'info', msg: error?.statusMessage || 'Request refused', status, requestId, method, path, user: userId }))
30
+ return
31
+ }
32
+ console.error(JSON.stringify({
33
+ level: 'error',
34
+ msg: error?.statusMessage || (error?.message ? safeErrorMessage(error) : 'Server error'),
35
+ status,
36
+ requestId,
37
+ method,
38
+ path,
39
+ user: userId,
40
+ error: safeErrorMessage(cause),
41
+ stack: scrubError(cause).stack?.split('\n').slice(0, 8).join('\n'),
42
+ }))
43
+ if (!expected) reportCmsError({ source: 'request', error, status, requestId, method, path, userId }, event)
44
+ })
45
+ })
@@ -0,0 +1,5 @@
1
+ // Migrate the database when the server starts, if enabled (cms.migrations.onStart /
2
+ // NUXT_CMS_MIGRATIONS_ON_START=true). API requests wait for it (cms-migrate-gate).
3
+ export default defineNitroPlugin(() => {
4
+ if ((useRuntimeConfig().cms as any)?.migrations?.onStart) startCmsMigrations()
5
+ })
@@ -0,0 +1,17 @@
1
+ // Check the content model and the plugins when the server starts: a plugin registered
2
+ // twice, a taken name, an entity that needs a plugin that is not registered. The
3
+ // registry is otherwise built by the first request, which would then answer 500 to
4
+ // everything. In production a failure stops the start with the message (the platform
5
+ // restarts or rolls back); in development it is logged and shown again on every request.
6
+ import { buildRegistry } from 'tinyzoo'
7
+ import * as cmsConfig from '#cms/config'
8
+
9
+ export default defineNitroPlugin(() => {
10
+ try {
11
+ buildRegistry(cmsConfig as Record<string, any>)
12
+ }
13
+ catch (err: any) {
14
+ console.error(`[cms] the content model or a plugin is misconfigured: ${err?.message ?? err}`)
15
+ if (process.env.NODE_ENV === 'production') throw err
16
+ }
17
+ })
@@ -0,0 +1,12 @@
1
+ // The search index: once the database is migrated, rebuild it if it was built from
2
+ // another configuration (a new site, an upgrade, a changed cms.config.ts). In the
3
+ // background — the server answers meanwhile, searching the old index.
4
+ export default defineNitroPlugin(() => {
5
+ if (import.meta.prerender) return
6
+ cmsMigrationsReady()
7
+ .then(() => ensureSearchIndex())
8
+ .catch((err) => {
9
+ const hint = missingTableHint(err)
10
+ console.error(`[cms] could not build the search index${hint ? ` — ${hint}` : ''}`, scrubError(err))
11
+ })
12
+ })
@@ -0,0 +1,15 @@
1
+ // Production, no setup token, no account yet: make (or find) the one-time setup code
2
+ // and print it. Waits for the start-up migrations, which create the tables it uses.
3
+ export default defineNitroPlugin(() => {
4
+ if (!setupCodeApplies()) return
5
+ void (async () => {
6
+ try {
7
+ await cmsMigrationsReady()
8
+ await ensureSetupCode({ reissue: true })
9
+ }
10
+ catch (err) {
11
+ // Not fatal: the status endpoint tries again when someone opens /admin/setup.
12
+ console.error('[cms] could not prepare the setup code', safeErrorMessage(err))
13
+ }
14
+ })()
15
+ })
@@ -0,0 +1,25 @@
1
+ // GET /sitemap.xml — every published page and post with a website address
2
+ // (`content.path`), with hreflang alternates per language. Absolute URLs use
3
+ // cms.publicUrl. A host app can replace it with its own server/routes/sitemap.xml.
4
+ const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&apos;' }[c]!))
5
+
6
+ export default defineEventHandler(async (event) => {
7
+ // A private content API (content token) means a private site map too.
8
+ if ((useRuntimeConfig().cms as any)?.content?.token) throw createError({ statusCode: 404, statusMessage: 'Not found' })
9
+ const base = siteBase(event)
10
+ if (!base) {
11
+ console.error('[cms] /sitemap.xml needs cms.publicUrl (NUXT_CMS_PUBLIC_URL) in production')
12
+ throw createError({ statusCode: 404, statusMessage: 'Not found' })
13
+ }
14
+ const { db, reg } = useCms()
15
+ const entries = await sitemapEntries(db, reg)
16
+ const urls = entries.map((e) => {
17
+ const alt = e.alternates.length > 1
18
+ ? e.alternates.map((a) => `\n <xhtml:link rel="alternate" hreflang="${esc(a.locale)}" href="${esc(base + a.loc)}"/>`).join('')
19
+ : ''
20
+ return ` <url>\n <loc>${esc(base + e.loc)}</loc>${e.lastmod ? `\n <lastmod>${e.lastmod}</lastmod>` : ''}${alt}\n </url>`
21
+ })
22
+ setResponseHeader(event, 'content-type', 'application/xml; charset=utf-8')
23
+ setResponseHeader(event, 'cache-control', 'public, max-age=3600')
24
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${urls.join('\n')}\n</urlset>\n`
25
+ })
@@ -0,0 +1,95 @@
1
+ import type { CmsStoreConfig, SharedStore } from './types'
2
+
3
+ // Shared store: Redis (ioredis) when a URL is configured, else nothing (the caller
4
+ // falls back to per-process memory).
5
+ //
6
+ // Commands never wait on a Redis that is down: no offline queue, a short timeout,
7
+ // and the caller falls back (rate limits count in memory, publishes are dropped).
8
+ // The subscriber connection is the opposite — it waits and re-subscribes after
9
+ // every reconnect, so an instance that booted before Redis was up still hears the
10
+ // other replicas once it is.
11
+ export async function createRedisStore(cfg: CmsStoreConfig): Promise<SharedStore | null> {
12
+ if (!cfg.redisUrl) return null
13
+ const { default: Redis } = await import('ioredis')
14
+ const prefix = cfg.prefix || 'cms'
15
+ const client = new Redis(cfg.redisUrl, {
16
+ maxRetriesPerRequest: 1,
17
+ enableOfflineQueue: false,
18
+ commandTimeout: 500,
19
+ connectTimeout: 2_000,
20
+ })
21
+ client.on('error', (err) => console.error('[cms] redis', err.message))
22
+ // Give the first connection a moment, so the first commands do not fall back for
23
+ // nothing; a Redis that is down does not hold up the start for longer.
24
+ if (client.status !== 'ready') {
25
+ await new Promise<void>((resolve) => {
26
+ const done = () => {
27
+ clearTimeout(timer)
28
+ client.off('ready', done)
29
+ resolve()
30
+ }
31
+ const timer = setTimeout(done, 2_000)
32
+ client.once('ready', done)
33
+ })
34
+ }
35
+ let subscriber: InstanceType<typeof Redis> | undefined
36
+ const handlers = new Map<string, Set<(message: string) => void>>()
37
+
38
+ return {
39
+ kind: 'redis',
40
+ async hit(key, windowMs) {
41
+ // Fixed window: one counter per key and window, expiring with the window. Keys
42
+ // are hashed: they hold emails and IPs.
43
+ const bucket = `${prefix}:rl:${await sha256Hex(key)}:${Math.floor(Date.now() / windowMs)}`
44
+ const res = await client.multi().incr(bucket).pexpire(bucket, windowMs).exec()
45
+ const [err, count] = res?.[0] ?? [new Error('empty transaction result'), null]
46
+ if (err || typeof count !== 'number') throw err ?? new Error('rate limit counter missing')
47
+ return count
48
+ },
49
+ async unhit(key, windowMs) {
50
+ const bucket = `${prefix}:rl:${await sha256Hex(key)}:${Math.floor(Date.now() / windowMs)}`
51
+ // Never below zero (the window may have turned over since the hit).
52
+ const left = await client.decr(bucket)
53
+ if (left < 0) await client.incr(bucket)
54
+ },
55
+ async publish(channel, message) {
56
+ await client.publish(`${prefix}:${channel}`, message)
57
+ },
58
+ async subscribe(channel, handler) {
59
+ if (!subscriber) {
60
+ subscriber = new Redis(cfg.redisUrl, { maxRetriesPerRequest: null, enableOfflineQueue: true, connectTimeout: 2_000 })
61
+ subscriber.on('error', (err) => console.error('[cms] redis subscriber', err.message))
62
+ subscriber.on('message', (ch: string, msg: string) => {
63
+ for (const h of handlers.get(ch) ?? []) h(msg)
64
+ })
65
+ }
66
+ const ch = `${prefix}:${channel}`
67
+ if (!handlers.has(ch)) {
68
+ handlers.set(ch, new Set())
69
+ try {
70
+ await subscriber.subscribe(ch)
71
+ }
72
+ catch (err) {
73
+ handlers.delete(ch)
74
+ throw err
75
+ }
76
+ }
77
+ handlers.get(ch)!.add(handler)
78
+ return async () => {
79
+ handlers.get(ch)?.delete(handler)
80
+ if (!handlers.get(ch)?.size) {
81
+ handlers.delete(ch)
82
+ await subscriber?.unsubscribe(ch)
83
+ }
84
+ }
85
+ },
86
+ async close() {
87
+ await Promise.allSettled([client.quit(), subscriber?.quit()])
88
+ },
89
+ }
90
+ }
91
+
92
+ async function sha256Hex(text: string): Promise<string> {
93
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
94
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('').slice(0, 32)
95
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * State shared by every instance of the app: rate-limit counters and pub/sub
3
+ * messages (realtime, cache invalidation). See utils/cmsStore.ts.
4
+ */
5
+ export interface SharedStore {
6
+ kind: 'redis' | 'memory'
7
+ /** Count one hit for `key` in the current window; returns the hits so far in it. */
8
+ hit: (key: string, windowMs: number) => Promise<number>
9
+ /** Take back the last hit of `key` (a sign-in that worked is not a failed attempt). */
10
+ unhit: (key: string, windowMs: number) => Promise<void>
11
+ publish: (channel: string, message: string) => Promise<void>
12
+ /** Subscribe to a channel; returns an unsubscribe function. */
13
+ subscribe: (channel: string, handler: (message: string) => void) => Promise<() => Promise<void>>
14
+ /** Close connections (server shutdown). */
15
+ close?: () => Promise<void>
16
+ }
17
+ export interface CmsStoreConfig {
18
+ redisUrl: string
19
+ /** Namespace for keys and channels, so environments sharing one Redis stay apart. */
20
+ prefix?: string
21
+ }
@@ -0,0 +1,10 @@
1
+ // Retention (GDPR): delete form submissions and audit entries past their time
2
+ // (defineForm `retentionDays`, `cms.retention.auditDays`). Runs daily; one instance at
3
+ // a time. `npx nitro task run cms:retention` runs it by hand.
4
+ export default defineTask({
5
+ meta: { name: 'cms:retention', description: 'Delete form submissions and audit entries past their retention' },
6
+ async run() {
7
+ const result = await runReportedTask('cms:retention', () => runRetention())
8
+ return { result: result ?? { skipped: 'another instance is running it' } }
9
+ },
10
+ })
@@ -0,0 +1,10 @@
1
+ // Scheduled publishing: entries whose publish date has just come are live already
2
+ // (every visibility check compares the date). This task tells the world: it reports
3
+ // them as published — webhooks (site cache), live updates, the cms:change hook.
4
+ export default defineTask({
5
+ meta: { name: 'cms:scheduled', description: 'Announce scheduled entries that went live' },
6
+ async run() {
7
+ const announced = await runReportedTask('cms:scheduled', () => announceScheduled())
8
+ return { result: { announced } }
9
+ },
10
+ })
@@ -0,0 +1,12 @@
1
+ // Rebuild the search index from scratch (normally automatic: on start, when the
2
+ // configuration changed, and on every save). `npx nitro task run cms:search-reindex`.
3
+ export default defineTask({
4
+ meta: { name: 'cms:search-reindex', description: 'Rebuild the search index' },
5
+ async run() {
6
+ const rows = await runReportedTask('cms:search-reindex', async () => {
7
+ const { db, reg } = useCms()
8
+ return rebuildSearchIndex(db, reg)
9
+ })
10
+ return { result: { rows } }
11
+ },
12
+ })
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Audit log: who did what, when. Best effort — a failed audit write is logged and
3
+ * never fails the request that triggered it.
4
+ *
5
+ * Actions: auth.setup, auth.setup_failed, auth.login, auth.login_failed, auth.logout, auth.reset_request,
6
+ * auth.reset, auth.invite_accept, account.update, account.password, user.invite,
7
+ * user.resend, user.role, user.disable, user.enable, user.delete, entry.create,
8
+ * entry.update, entry.delete, entry.publish, entry.unpublish, settings.update,
9
+ * media.upload, media.delete, retention.purge, privacy.export, privacy.delete.
10
+ */
11
+ export async function audit(
12
+ event: any,
13
+ action: string,
14
+ data: { entity?: string | null; recordId?: string | null; meta?: Record<string, unknown> | null; userId?: string | null } = {},
15
+ ): Promise<void> {
16
+ try {
17
+ const { db, reg } = useCms()
18
+ await db.insert(reg.cmsAudit).values({
19
+ userId: data.userId !== undefined ? data.userId : (event?.context?.cmsUser?.id ?? null),
20
+ action,
21
+ entity: data.entity ?? null,
22
+ recordId: data.recordId ?? null,
23
+ meta: data.meta ?? null,
24
+ })
25
+ }
26
+ catch (err) {
27
+ console.error('[cms] audit write failed', action, scrubError(err))
28
+ }
29
+ }