tinyzoo 0.0.0-stage → 0.2.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 (392) 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 +98 -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 +393 -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/cmsTiming.ts +14 -0
  312. package/server/utils/cmsTooMany.ts +9 -0
  313. package/server/utils/cmsTranslationWrite.ts +186 -0
  314. package/server/utils/cmsTree.ts +251 -0
  315. package/server/utils/cmsTreeAddress.ts +65 -0
  316. package/server/utils/cmsUpload.ts +228 -0
  317. package/server/utils/cmsWebhooks.ts +104 -0
  318. package/shared/json.ts +11 -0
  319. package/shared/richtext-editor.ts +56 -0
  320. package/shared/richtext-normalize.ts +33 -0
  321. package/shared/richtext-paste.ts +151 -0
  322. package/shared/storage-delivery.ts +53 -0
  323. package/src/blocks.ts +624 -0
  324. package/src/changes.ts +54 -0
  325. package/src/content-shape.ts +340 -0
  326. package/src/deprecate.ts +64 -0
  327. package/src/descriptor.ts +149 -0
  328. package/src/docs.ts +27 -0
  329. package/src/emitter.ts +94 -0
  330. package/src/entity.ts +624 -0
  331. package/src/errorReport.ts +41 -0
  332. package/src/fields.ts +465 -0
  333. package/src/i18n.ts +26 -0
  334. package/src/index.ts +54 -0
  335. package/src/linkref.ts +31 -0
  336. package/src/links.ts +179 -0
  337. package/src/locales.ts +39 -0
  338. package/src/media.ts +48 -0
  339. package/src/migrate.ts +236 -0
  340. package/src/openapi.ts +377 -0
  341. package/src/paths.ts +88 -0
  342. package/src/plugin.ts +505 -0
  343. package/src/presets.ts +230 -0
  344. package/src/richtext.ts +88 -0
  345. package/src/sdk.ts +181 -0
  346. package/src/search.ts +312 -0
  347. package/src/seed.ts +225 -0
  348. package/src/setupCode.ts +30 -0
  349. package/src/system.ts +219 -0
  350. package/src/tree.ts +421 -0
  351. package/src/upgrades.ts +137 -0
  352. package/starter/.env.example +10 -0
  353. package/starter/README.md +65 -0
  354. package/starter/app/app.config.ts +10 -0
  355. package/starter/app/app.vue +12 -0
  356. package/starter/app/assets/css/main.css +15 -0
  357. package/starter/app/components/global/BlockContact.vue +15 -0
  358. package/starter/app/components/global/BlockCta.vue +15 -0
  359. package/starter/app/components/global/BlockHero.vue +23 -0
  360. package/starter/app/components/global/BlockImage.vue +13 -0
  361. package/starter/app/components/global/BlockText.vue +12 -0
  362. package/starter/app/composables/useSite.ts +77 -0
  363. package/starter/app/error.vue +28 -0
  364. package/starter/app/layouts/default.vue +106 -0
  365. package/starter/app/lib/cms-content.ts +152 -0
  366. package/starter/app/pages/[...slug].vue +66 -0
  367. package/starter/app/pages/hledat.vue +59 -0
  368. package/starter/app/pages/index.vue +20 -0
  369. package/starter/cms.config.ts +137 -0
  370. package/starter/compose.yaml +15 -0
  371. package/starter/drizzle.config.ts +8 -0
  372. package/starter/gitignore.txt +8 -0
  373. package/starter/nuxt.config.ts +13 -0
  374. package/starter/package.json +38 -0
  375. package/starter/scripts/typecheck.mjs +38 -0
  376. package/starter/seed/index.ts +297 -0
  377. package/starter/seed/media/about.jpg +0 -0
  378. package/starter/seed/media/hero.jpg +0 -0
  379. package/starter/seed/media/logo.png +0 -0
  380. package/starter/seed/media/news-bread.jpg +0 -0
  381. package/starter/seed/media/news-morning.jpg +0 -0
  382. package/starter/server/db/migrations/0000_init.sql +269 -0
  383. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  384. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  385. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  386. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  387. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  388. package/starter/server/db/migrations/meta/_journal.json +27 -0
  389. package/starter/server/db/schema.ts +253 -0
  390. package/starter/server/plugins/sitemap.ts +11 -0
  391. package/starter/server/routes/robots.txt.get.ts +12 -0
  392. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,188 @@
1
+ import { eq, mediaIdsInBlocks, mediaIdsInFields, sql } from 'tinyzoo'
2
+ import { deleteImageVariants } from './cmsImageSizes'
3
+ import type { CmsRegistry } from 'tinyzoo'
4
+ import type { StorageDriver } from './cmsStorage'
5
+
6
+ /** Field types storing JSON that can hold media ids (rich text images, blocks, galleries). */
7
+ export const JSON_MEDIA_TYPES = new Set(['richtext', 'blocks', 'gallery', 'group'])
8
+
9
+ /** Every (table, column) pair that holds a media FK, across all entities. */
10
+ function mediaColumns(reg: CmsRegistry): { table: any; col: any }[] {
11
+ const cols: { table: any; col: any }[] = []
12
+ for (const e of reg.entities) {
13
+ for (const [key, fld] of Object.entries(e.fields)) {
14
+ if ((fld as any).type === 'media') cols.push({ table: e.table, col: (e.table as any)[`${key}Id`] })
15
+ }
16
+ }
17
+ return cols
18
+ }
19
+
20
+ /**
21
+ * Every (table, column) pair holding jsonb that can reference media: rich text
22
+ * (embedded images) and blocks (media fields and rich text inside blocks).
23
+ */
24
+ function richTextColumns(reg: CmsRegistry): { table: any; col: any }[] {
25
+ const cols: { table: any; col: any }[] = []
26
+ for (const e of reg.entities) {
27
+ for (const [key, fld] of Object.entries(e.fields)) {
28
+ if (JSON_MEDIA_TYPES.has((fld as any).type)) {
29
+ cols.push({ table: e.table, col: (e.table as any)[key] })
30
+ // …and the same field in every translation.
31
+ if ((fld as any).isLocalized && e.localesTable) cols.push({ table: e.localesTable, col: e.localesTable[key] })
32
+ }
33
+ }
34
+ }
35
+ return cols
36
+ }
37
+
38
+ /** Media ids referenced by one jsonb value of a field (rich text or blocks). */
39
+ export function jsonMediaIds(fld: any, value: unknown): string[] {
40
+ if (fld?.type === 'blocks') return mediaIdsInBlocks(value, fld.blocks ?? {})
41
+ if (fld?.type === 'group') return value && typeof value === 'object' ? mediaIdsInFields(fld.fields ?? {}, value as Record<string, any>) : []
42
+ if (fld?.type === 'gallery') return Array.isArray(value) ? value.map((x: any) => x?.mediaId).filter((id: unknown): id is string => typeof id === 'string') : []
43
+ return embeddedMediaIds(value)
44
+ }
45
+
46
+ /** Collect cms_media ids embedded in a rich-text doc (image nodes carry `mediaId`). */
47
+ export function embeddedMediaIds(doc: any, out: string[] = []): string[] {
48
+ if (!doc || typeof doc !== 'object') return out
49
+ if (typeof doc.attrs?.mediaId === 'string') out.push(doc.attrs.mediaId)
50
+ if (Array.isArray(doc.content)) for (const child of doc.content) embeddedMediaIds(child, out)
51
+ return out
52
+ }
53
+
54
+ /**
55
+ * True if any entity row still references this media — as a FK, or embedded in rich
56
+ * text. The rich-text scan matches BOTH the cms_media id (our images carry it as
57
+ * `mediaId`) AND the storage key (always present in the image `src`), so an embedded
58
+ * image whose `mediaId` was lost (paste/import/legacy) is still protected from GC.
59
+ */
60
+ export async function isMediaReferenced(db: any, reg: CmsRegistry, mediaId: string, mediaKey?: string): Promise<boolean> {
61
+ for (const { table, col } of mediaColumns(reg)) {
62
+ const [hit] = await db.select({ id: table.id }).from(table).where(eq(col, mediaId)).limit(1)
63
+ if (hit) return true
64
+ }
65
+ // A uuid (and the uuid-named storage key) can't contain LIKE wildcards, so these
66
+ // substring matches are exact in practice.
67
+ for (const { table, col } of richTextColumns(reg)) {
68
+ const cond = mediaKey
69
+ ? sql`cast(${col} as text) ilike ${`%${mediaId}%`} or cast(${col} as text) ilike ${`%${mediaKey}%`}`
70
+ : sql`cast(${col} as text) ilike ${`%${mediaId}%`}`
71
+ const [hit] = await db.select({ id: table.id }).from(table).where(cond).limit(1)
72
+ if (hit) return true
73
+ }
74
+ return false
75
+ }
76
+
77
+ /** Media ids referenced by a single row — media FKs AND images embedded in its rich text. */
78
+ export function mediaIdsOf(reg: CmsRegistry, e: any, row: Record<string, any>): string[] {
79
+ const ids: string[] = []
80
+ for (const [key, fld] of Object.entries(e.fields)) {
81
+ if ((fld as any).type === 'media' && row[`${key}Id`]) ids.push(row[`${key}Id`])
82
+ else if ((fld as any).type === 'richtext' && row[key]) embeddedMediaIds(row[key], ids)
83
+ else if (((fld as any).type === 'blocks' || (fld as any).type === 'gallery' || (fld as any).type === 'group') && row[key]) ids.push(...jsonMediaIds(fld, row[key]))
84
+ }
85
+ return ids
86
+ }
87
+
88
+ /**
89
+ * Delete a media row + its blob IFF nothing references it anymore. Call AFTER the
90
+ * referencing write has committed. A no-op for null or still-referenced ids.
91
+ */
92
+ export async function gcMediaIfOrphan(
93
+ db: any,
94
+ reg: CmsRegistry,
95
+ storage: StorageDriver,
96
+ mediaId: string | null | undefined,
97
+ scope: { onlyUploadedBy?: string } = {},
98
+ ): Promise<void> {
99
+ if (!mediaId) return
100
+ // Load the row first so we can check references by storage key too (see above).
101
+ const [m] = await db.select().from(reg.cmsMedia).where(eq(reg.cmsMedia.id, mediaId))
102
+ if (!m) return
103
+ // Cleanup triggered by someone who may only delete their own files (authors) must
104
+ // not remove anyone else's — pointing a draft at a file and clearing it would
105
+ // otherwise be a way around that rule.
106
+ if (scope.onlyUploadedBy !== undefined && m.uploadedBy !== scope.onlyUploadedBy) return
107
+ // A library file stays until someone deletes it there (other pages may use it later,
108
+ // and older versions in History still point at it).
109
+ if (m.inLibrary) return
110
+ if (await isMediaReferenced(db, reg, mediaId, m.key)) return
111
+ await storage.delete(m.key)
112
+ await deleteImageVariants(m.key)
113
+ await db.delete(reg.cmsMedia).where(eq(reg.cmsMedia.id, mediaId))
114
+ }
115
+
116
+ /** Whose files a write by `user` may clean up: authors only their own, everyone else any. */
117
+ export function gcScope(user: { id: string; role: string }): { onlyUploadedBy?: string } {
118
+ return user.role === 'author' ? { onlyUploadedBy: user.id } : {}
119
+ }
120
+
121
+ /**
122
+ * Where a file is used: the entries (and globals) holding it in a media field, in rich
123
+ * text or in blocks — also in translations. Only entries this person may read are
124
+ * listed. At most `limit`.
125
+ */
126
+ export async function mediaUsage(db: any, reg: CmsRegistry, user: any, mediaId: string, mediaKey: string | undefined, limit = 50) {
127
+ const found = new Map<string, { entity: string; id: string; title: string | null; locale: string | null }>()
128
+ const like = (col: any) => (mediaKey
129
+ ? sql`(cast(${col} as text) ilike ${'%' + mediaId + '%'} or cast(${col} as text) ilike ${'%' + mediaKey + '%'})`
130
+ : sql`cast(${col} as text) ilike ${'%' + mediaId + '%'}`)
131
+ for (const e of reg.entities) {
132
+ if (found.size >= limit) break
133
+ const { allowed, where } = accessWhere(e, 'read', user)
134
+ if (!allowed) continue
135
+ const title = (e.table as any)[e.titleField]
136
+ const add = (rows: any[], locale: string | null = null) => {
137
+ for (const r of rows) found.set(`${e.name}:${r.id}:${locale ?? ''}`, { entity: e.name, id: r.id, title: r.title == null ? null : String(r.title), locale })
138
+ }
139
+ for (const [key, fld] of Object.entries(e.fields)) {
140
+ const type = (fld as any).type
141
+ if (type === 'media') {
142
+ add(await db.select({ id: e.table.id, title }).from(e.table).where(both(eq((e.table as any)[`${key}Id`], mediaId), where)).limit(limit))
143
+ }
144
+ else if (JSON_MEDIA_TYPES.has(type)) {
145
+ add(await db.select({ id: e.table.id, title }).from(e.table).where(both(like((e.table as any)[key]), where)).limit(limit))
146
+ const t = e.localesTable
147
+ if ((fld as any).isLocalized && t) {
148
+ const hits: any[] = await db.select({ parentId: t.parentId, locale: t.locale }).from(t).where(like(t[key])).limit(limit)
149
+ for (const h of hits) {
150
+ const [parent] = await db.select({ id: e.table.id, title }).from(e.table).where(both(eq(e.table.id, h.parentId), where))
151
+ if (parent) add([parent], h.locale)
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ return [...found.values()].slice(0, limit)
158
+ }
159
+
160
+ /**
161
+ * Is this file on the website right now: used by an entry visitors can see (live,
162
+ * per its collection's rule) — in a media field, rich text or blocks, translations
163
+ * included? Authors may not change such a file's public details.
164
+ */
165
+ export async function isMediaLive(db: any, reg: CmsRegistry, mediaId: string, mediaKey?: string): Promise<boolean> {
166
+ const like = (col: any) => (mediaKey
167
+ ? sql`(cast(${col} as text) ilike ${'%' + mediaId + '%'} or cast(${col} as text) ilike ${'%' + mediaKey + '%'})`
168
+ : sql`cast(${col} as text) ilike ${'%' + mediaId + '%'}`)
169
+ for (const e of reg.entities) {
170
+ const live = publishedCond(e)
171
+ for (const [key, fld] of Object.entries(e.fields)) {
172
+ const type = (fld as any).type
173
+ let cond: any = null
174
+ if (type === 'media') cond = eq((e.table as any)[`${key}Id`], mediaId)
175
+ else if (JSON_MEDIA_TYPES.has(type)) {
176
+ cond = like((e.table as any)[key])
177
+ const t = e.localesTable
178
+ if ((fld as any).isLocalized && t) {
179
+ cond = sql`(${cond} or exists (select 1 from ${t} where ${t.parentId} = ${e.table.id} and ${like(t[key])}))`
180
+ }
181
+ }
182
+ if (!cond) continue
183
+ const [hit] = await db.select({ id: e.table.id }).from(e.table).where(both(cond, live)).limit(1)
184
+ if (hit) return true
185
+ }
186
+ }
187
+ return false
188
+ }
@@ -0,0 +1,62 @@
1
+ import { eq } from 'tinyzoo'
2
+ import { CMS_IMAGE_WIDTHS } from './cmsImageSizes'
3
+
4
+ // Which stored objects may the raw media route serve? Only those that belong to a
5
+ // cms_media row (or are the resized copy of one). A bucket is often shared with other
6
+ // tools; without this, anyone could read every object in it through /_media/raw/<key>.
7
+ //
8
+ // The answer is cached for a minute in memory (a page shows many pictures, each asked
9
+ // for again by every visitor), the misses for half a minute (probes for keys that do
10
+ // not exist should not each cost a query). A key is a random uuid made at upload, so
11
+ // nobody asks for one before its row exists; a deleted file simply loses its object.
12
+
13
+ export interface ServedMedia {
14
+ name: string | null
15
+ mime: string
16
+ }
17
+
18
+ const POSITIVE_MS = 60_000
19
+ const NEGATIVE_MS = 30_000
20
+ const MAX_ENTRIES = 5000
21
+ const cache = new Map<string, { value: ServedMedia | null; until: number }>()
22
+
23
+ /** `_w/640/2026/01/<uuid>.png.webp` → `2026/01/<uuid>.png` (a resized copy's original), else the key itself. */
24
+ export function originalKeyOf(key: string): string | null {
25
+ if (!key.startsWith('_w/')) return key
26
+ const m = /^_w\/(\d+)\/(.+)\.webp$/.exec(key)
27
+ if (!m || !(CMS_IMAGE_WIDTHS as readonly number[]).includes(Number(m[1]))) return null
28
+ return m[2]!
29
+ }
30
+
31
+ /** The media row a stored key belongs to (its name and type), or null when the key is not one of ours. */
32
+ export async function servedMedia(key: string): Promise<ServedMedia | null> {
33
+ const original = originalKeyOf(key)
34
+ if (!original) return null
35
+ const hit = cache.get(original)
36
+ if (hit && hit.until > Date.now()) return hit.value
37
+ const { db, reg } = useCms()
38
+ const [row] = await db.select({ name: reg.cmsMedia.name, mime: reg.cmsMedia.mime }).from(reg.cmsMedia).where(eq(reg.cmsMedia.key, original)).limit(1)
39
+ const value = row ? { name: row.name ?? null, mime: row.mime } : null
40
+ if (cache.size >= MAX_ENTRIES) cache.clear()
41
+ cache.set(original, { value, until: Date.now() + (value ? POSITIVE_MS : NEGATIVE_MS) })
42
+ return value
43
+ }
44
+
45
+ /** Forget a key (its file was just deleted). Other instances' copies expire by themselves. */
46
+ export function forgetServedMedia(key: string): void {
47
+ cache.delete(key)
48
+ }
49
+
50
+ /**
51
+ * The Content-Disposition of a served file: `inline`, and for a PDF the file's own name
52
+ * (`filename` for old clients, `filename*` with the real characters), so "Save as" does
53
+ * not offer a uuid. Never an attachment: the pages embed these.
54
+ */
55
+ export function contentDispositionFor(media: ServedMedia): string {
56
+ if (media.mime !== 'application/pdf') return 'inline'
57
+ const base = (media.name ?? '').replace(/[\u0000-\u001f\u007f"\\/]/g, '').trim().replace(/\.pdf$/i, '').slice(0, 150) || 'document'
58
+ const name = base + '.pdf'
59
+ const ascii = name.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\x20-\x7e]/g, '_').replace(/[%;]/g, '_')
60
+ const encoded = encodeURIComponent(name).replace(/['()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
61
+ return 'inline; filename="' + ascii + '"; filename*=UTF-8\'\'' + encoded
62
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Migrations at start. Pushbase (and most container platforms) ship only the build
3
+ * output, so the database must be migrated by the app itself when it boots.
4
+ *
5
+ * The host's drizzle-kit migrations folder is bundled into the server build as
6
+ * server assets (see module.ts), and applied here with drizzle's own bookkeeping —
7
+ * the same `drizzle.__drizzle_migrations` table, hashes and ordering as
8
+ * `drizzle-kit migrate` — so either tool can take over from the other — plus the
9
+ * package's upgrade steps (the data work a migration cannot express, see
10
+ * src/upgrades.ts) in the same transaction. A Postgres advisory lock makes concurrent
11
+ * replicas take turns; the second one finds nothing left to do. A migration older than
12
+ * the newest applied one that was never applied stops the start with an error. Node only: a Worker may not do I/O while it starts (see the plugin).
13
+ *
14
+ * The database may not accept connections yet when the app boots (a freshly
15
+ * provisioned one, a restart during maintenance): connection errors are retried for
16
+ * about a minute and a half. If migrating still fails, the instance reports itself
17
+ * dead (/api/health/live) and, in production, exits so the platform restarts it —
18
+ * rather than staying up and answering 503 forever.
19
+ */
20
+
21
+ import { allUpgradeSteps, isConnectionError, runUpgrade, sqlWithParams, type MigrationJournal, type MigrationSource } from 'tinyzoo'
22
+ import { scrubError } from './cmsScrub'
23
+
24
+ let ready: Promise<void> = Promise.resolve()
25
+ let state: 'idle' | 'running' | 'done' | 'failed' = 'idle'
26
+
27
+ /** Resolves once start-up migrations have finished (immediately when disabled). */
28
+ export function cmsMigrationsReady(): Promise<void> {
29
+ return ready
30
+ }
31
+ export function cmsMigrationState() {
32
+ return state
33
+ }
34
+
35
+ /** Start migrating from the bundled assets (called once by the Nitro plugin). */
36
+ const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 15_000, 15_000, 15_000, 15_000]
37
+ export function startCmsMigrations(): void {
38
+ state = 'running'
39
+ ready = (async () => {
40
+ for (let attempt = 0; ; attempt++) {
41
+ try {
42
+ return await migrateOnce()
43
+ }
44
+ catch (err) {
45
+ if (!isConnectionError(err) || attempt >= RETRY_DELAYS_MS.length) throw err
46
+ const delayMs = RETRY_DELAYS_MS[attempt]!
47
+ console.warn('[cms] database not reachable yet, retrying migrations in', delayMs, 'ms')
48
+ await new Promise((r) => setTimeout(r, delayMs))
49
+ }
50
+ }
51
+ })().catch((err) => {
52
+ state = 'failed'
53
+ console.error('[cms] migrations failed — the app will not serve API requests', scrubError(err))
54
+ if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production' && typeof process.exit === 'function') {
55
+ // Let the platform restart the instance (after the log line is written).
56
+ setTimeout(() => process.exit(1), 100)
57
+ }
58
+ throw err
59
+ })
60
+ ready.catch(() => {}) // the failure is reported through health and API requests
61
+ }
62
+
63
+ async function migrateOnce(): Promise<void> {
64
+ const assets = useStorage('assets:cms-migrations')
65
+ const journal = await assets.getItem<MigrationJournal>('meta/_journal.json')
66
+ if (!journal?.entries) throw new Error('No bundled migrations (meta/_journal.json) — is cms.migrations.dir right?')
67
+ const source: MigrationSource = {
68
+ journal,
69
+ readSql: async (tag) => {
70
+ const raw = await assets.getItemRaw(`${tag}.sql`)
71
+ if (raw == null) throw new Error(`Bundled migration ${tag}.sql is missing`)
72
+ return typeof raw === 'string' ? raw : new TextDecoder().decode(raw as Uint8Array)
73
+ },
74
+ }
75
+ const { db, reg } = useCms()
76
+ // Upgrade steps (tinyzoo's and the plugins') run in the same transaction and lock.
77
+ const result = await runUpgrade(source, (fn) => (db as any).transaction((tx: any) =>
78
+ fn(async (text, params = []) => {
79
+ const res: any = await tx.execute(sqlWithParams(text, params))
80
+ return res.rows ?? res
81
+ })), allUpgradeSteps(reg.plugins))
82
+ const ranSteps = result.steps.filter((s) => s.ran).map((s) => s.id)
83
+ if (ranSteps.length) console.info(`[cms] ran upgrade steps: ${ranSteps.join(', ')}`)
84
+ console.info(result.migrations.length ? `[cms] applied migrations: ${result.migrations.join(', ')}` : '[cms] database is up to date')
85
+ state = 'done'
86
+ }
@@ -0,0 +1,72 @@
1
+ // Live preview: what an editor has typed but not saved, shown on the website preview
2
+ // as they type.
3
+ //
4
+ // The editor's preview panel sends the form's values here (POST /api/cms/_preview)
5
+ // and the preview page refetches its content. The content API then lays those values
6
+ // over the saved entry — only for that same signed-in editor, only with ?preview, and
7
+ // never cached. Nobody else, and no published page, ever sees them.
8
+ //
9
+ // Kept in this server's memory for a while (one server process; a draft is gone after
10
+ // a restart, and the preview simply shows the saved version again).
11
+ import type { CmsEntity, CmsRegistry } from 'tinyzoo'
12
+ import { splitPayload } from './cmsCrud'
13
+ import { isTranslationLocale } from './cmsLocales'
14
+ import { isPreviewAuthorized } from './cmsContent'
15
+
16
+ const TTL = 30 * 60_000
17
+ const MAX = 500
18
+ const drafts = new Map<string, { values: Record<string, any>; at: number }>()
19
+
20
+ const keyOf = (userId: string, entity: string, id: string, locale: string | null) => `${userId}\u0000${entity}\u0000${id}\u0000${locale ?? ''}`
21
+ // The default language and "no languages" are the same draft.
22
+ const draftLocale = (reg: CmsRegistry, locale: string | null | undefined) => (isTranslationLocale(reg, locale) ? locale : null)
23
+
24
+ /**
25
+ * Keep an editor's unsaved values for the preview. Each value is checked against its
26
+ * field (a half-typed one that is not valid yet keeps the saved value) and turned into
27
+ * the entry's columns, as a save would. Lists of related entries are not previewed.
28
+ */
29
+ export function putPreviewDraft(reg: CmsRegistry, e: CmsEntity, userId: string, id: string, locale: string | null, data: Record<string, any>) {
30
+ const loc = draftLocale(reg, locale)
31
+ const valid: Record<string, any> = {}
32
+ for (const [key, value] of Object.entries(data ?? {})) {
33
+ const fld = e.fields[key]
34
+ if (!fld || (loc && !e.localized.includes(key))) continue
35
+ const parsed = fld.zod('update').safeParse(value)
36
+ if (parsed.success) valid[key] = parsed.data
37
+ }
38
+ const { values } = splitPayload(e, valid)
39
+ const now = Date.now()
40
+ if (drafts.size >= MAX) {
41
+ for (const [k, d] of drafts) if (now - d.at > TTL) drafts.delete(k)
42
+ if (drafts.size >= MAX) drafts.delete(drafts.keys().next().value!)
43
+ }
44
+ drafts.set(keyOf(userId, e.name, id, loc), { values, at: now })
45
+ }
46
+
47
+ export function dropPreviewDraft(reg: CmsRegistry, e: CmsEntity, userId: string, id: string, locale: string | null) {
48
+ drafts.delete(keyOf(userId, e.name, id, draftLocale(reg, locale)))
49
+ }
50
+
51
+ /**
52
+ * Lay the signed-in editor's unsaved values over the rows a ?preview request reads
53
+ * (after translations are merged, before related entries are filled in). Returns
54
+ * whether anything was laid over, so the caller can keep the answer out of caches.
55
+ */
56
+ export function applyPreviewDrafts(event: any, reg: CmsRegistry, e: CmsEntity, rows: any[], locale: string | null): boolean {
57
+ const user = event.context?.cmsUser
58
+ if (!user || !drafts.size || !isPreviewAuthorized(event)) return false
59
+ const loc = draftLocale(reg, locale)
60
+ let applied = false
61
+ for (const row of rows) {
62
+ const draft = drafts.get(keyOf(user.id, e.name, row.id, loc))
63
+ if (!draft) continue
64
+ if (Date.now() - draft.at > TTL) {
65
+ drafts.delete(keyOf(user.id, e.name, row.id, loc))
66
+ continue
67
+ }
68
+ Object.assign(row, draft.values)
69
+ applied = true
70
+ }
71
+ return applied
72
+ }
@@ -0,0 +1,176 @@
1
+ import { and, eq, or, propOf, sql } from 'tinyzoo'
2
+ import type { CmsEntity, CmsRegistry } from 'tinyzoo'
3
+ import { z } from 'zod'
4
+ import { formEntities, purgeSubmissions } from '../../forms/retention'
5
+
6
+ /**
7
+ * Everything stored about one email address (GDPR access and erasure), for the
8
+ * admin's Privacy screen: form submissions whose email fields match, the CMS account
9
+ * with that address, and the audit entries about it.
10
+ *
11
+ * What counts as stored about a person:
12
+ * - form submissions: rows of a form (defineForm) whose `format: 'email'` text
13
+ * fields equal the address (case-insensitive, whitespace trimmed) — and their saved
14
+ * versions and search rows, which hold the same text;
15
+ * - the account: email, name, role, status, language, sign-in times;
16
+ * - audit entries: those the account made, those about it (invitation, role change)
17
+ * and failed sign-ins that tried the address.
18
+ * Not covered: what an editor wrote under their own name in entries or media (that is
19
+ * the site's content, not personal data about a visitor), and copies in backups.
20
+ */
21
+
22
+ // The same rules as emailSchema (cmsAuth.ts), written out: this runs while the module loads, and the
23
+ // server utils are bundled in an order that does not promise cmsAuth is ready by then.
24
+ export const privacyBody = z.object({ email: z.string().trim().toLowerCase().pipe(z.email()).pipe(z.string().max(254)) })
25
+
26
+ /** Rate limit per signed-in administrator (and per address of the client), so a stolen session cannot scrape quickly. */
27
+ export async function privacyRateLimit(event: any, userId: string, kind: 'read' | 'delete'): Promise<void> {
28
+ const [max, windowMs] = kind === 'delete' ? [10, 10 * 60_000] : [60, 10 * 60_000]
29
+ const ok = (await rateLimit(`privacy:${kind}:${userId}`, max, windowMs)) && (await rateLimit(`privacy-ip:${kind}:${clientIp(event)}`, max * 2, windowMs))
30
+ if (!ok) throw tooManyRequests(event, 'Too many requests; try again in a few minutes', windowMs)
31
+ }
32
+
33
+ /** The text fields of a form that hold an email address. */
34
+ function emailFields(e: CmsEntity): string[] {
35
+ const form = (e as any).form as { fields: string[] }
36
+ return form.fields.filter((k) => (e.fields[k] as any)?.type === 'text' && (e.fields[k] as any)?.meta?.format === 'email')
37
+ }
38
+
39
+ const emailMatches = (e: CmsEntity, email: string) => {
40
+ const keys = emailFields(e)
41
+ if (!keys.length) return null
42
+ return or(...keys.map((k) => sql`lower(btrim(${e.table[propOf(k, e.fields[k]!)]})) = ${email}`))
43
+ }
44
+
45
+ export interface FoundSubmission { form: CmsEntity; row: Record<string, any> }
46
+
47
+ export async function findSubmissions(db: any, reg: CmsRegistry, email: string): Promise<FoundSubmission[]> {
48
+ const out: FoundSubmission[] = []
49
+ for (const e of formEntities(reg)) {
50
+ const where = emailMatches(e, email)
51
+ if (!where) continue
52
+ const rows: any[] = await db.select().from(e.table).where(where).orderBy(sql`${e.table.createdAt} desc`)
53
+ for (const row of rows) out.push({ form: e, row })
54
+ }
55
+ return out
56
+ }
57
+
58
+ /** The condition that picks the audit entries touching a person: theirs, about them, or naming their address. */
59
+ export function auditCondition(reg: CmsRegistry, email: string, accountId: string | null) {
60
+ const a = reg.cmsAudit
61
+ const parts = [sql`lower(${a.meta}->>'email') = ${email}`]
62
+ if (accountId) parts.push(eq(a.userId, accountId), and(eq(a.recordId, accountId), sql`${a.action} like 'user.%'`)!)
63
+ return or(...parts)!
64
+ }
65
+
66
+ export async function findAccount(db: any, reg: CmsRegistry, email: string) {
67
+ if (cmsAuthMode() !== 'builtin') return null
68
+ const [row] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.email, email))
69
+ return row ?? null
70
+ }
71
+
72
+ /** The submission as shown to the administrator: the form's own fields, when it arrived, its state. */
73
+ export function submissionView(e: CmsEntity, row: Record<string, any>) {
74
+ const form = (e as any).form as { fields: string[] }
75
+ const data: Record<string, unknown> = {}
76
+ for (const k of form.fields) data[k] = row[propOf(k, e.fields[k]!)] ?? null
77
+ return { form: e.name, id: row.id as string, createdAt: row.createdAt as Date, status: (row.status as string | null) ?? null, data }
78
+ }
79
+
80
+ /** The account without secrets (no password hash, no session counter). */
81
+ export function accountView(u: any) {
82
+ return { id: u.id as string, email: u.email as string, name: u.name as string, role: u.role as string, status: u.status as string, language: (u.locale as string | null) ?? null, lastLoginAt: u.lastLoginAt as Date | null, createdAt: u.createdAt as Date }
83
+ }
84
+
85
+ export async function findAuditEntries(db: any, reg: CmsRegistry, email: string, accountId: string | null, limit?: number) {
86
+ const a = reg.cmsAudit
87
+ const q = db.select().from(a).where(auditCondition(reg, email, accountId)).orderBy(sql`${a.createdAt} desc`)
88
+ return (limit ? await q.limit(limit) : await q) as any[]
89
+ }
90
+
91
+ /**
92
+ * Erase one person: their form submissions go (with the saved versions and search
93
+ * rows), the account is disabled and anonymised, and the audit entries about them lose
94
+ * their personal fields (email, address, name) but keep who-did-what: the account id
95
+ * stays on them, now pointing at an account with no name or address. Only the erased
96
+ * person's own details go: an administrator's `user.invite` entries keep the invitees'
97
+ * addresses (see `scrubAudit`).
98
+ *
99
+ * Why anonymise instead of delete the account: the history of the site ("saved by …",
100
+ * entries' authors, uploaded files) refers to the account by id; deleting it would
101
+ * leave that history pointing at nobody and break the "who changed this" trail the
102
+ * audit log is for, while anonymising removes every personal detail.
103
+ */
104
+ export async function erasePerson(db: any, reg: CmsRegistry, email: string, actorId: string): Promise<{ submissions: number; account: boolean; auditEntries: number }> {
105
+ return db.transaction(async (tx: any) => {
106
+ await tx.execute(sql`select pg_advisory_xact_lock(${ADMIN_GUARD_LOCK})`)
107
+ const account = await findAccount(tx, reg, email)
108
+ if (account) {
109
+ if (account.id === actorId) throw createError({ statusCode: 409, statusMessage: 'You cannot erase your own account; ask another administrator' })
110
+ if (account.role === 'admin' && account.status === 'active') await assertAnotherActiveAdmin(tx, reg, account.id)
111
+ }
112
+
113
+ let submissions = 0
114
+ for (const { form, ids } of groupByForm(await findSubmissions(tx, reg, email))) submissions += await purgeSubmissions(tx, reg, form, ids)
115
+
116
+ // The audit entries lose what identifies the person — and only that; computed before the
117
+ // account's email changes.
118
+ const auditEntries = await scrubAudit(tx, reg, email, account)
119
+
120
+ if (account) {
121
+ const u = reg.cmsUsers
122
+ await tx.update(u).set({
123
+ email: `deleted-${account.id}@anonymised.invalid`,
124
+ name: '', status: 'disabled', role: 'author', passwordHash: null, locale: null, lastLoginAt: null,
125
+ sessionVersion: sql`${u.sessionVersion} + 1`, updatedAt: new Date(),
126
+ }).where(eq(u.id, account.id))
127
+ await tx.delete(reg.cmsTokens).where(eq(reg.cmsTokens.userId, account.id))
128
+ }
129
+ return { submissions, account: !!account, auditEntries }
130
+ })
131
+ }
132
+
133
+ /**
134
+ * Take the erased person's own details out of the audit log, and nobody else's:
135
+ * - entries that name their address (`meta.email`, any case, whitespace trimmed: a failed
136
+ * sign-in with it, their invitation, their deletion) and entries about their account
137
+ * (`user.*` on their id) lose email, IP address and name;
138
+ * - entries they made themselves lose their IP address and their name — but not an
139
+ * `email` that is someone else's: the `user.invite` entries of an administrator hold
140
+ * the invitees' addresses, which belong to the invitees.
141
+ * Returns how many entries were changed.
142
+ */
143
+ async function scrubAudit(tx: any, reg: CmsRegistry, email: string, account: { id: string; name: string } | null): Promise<number> {
144
+ const a = reg.cmsAudit
145
+ const isObject = sql`${a.meta} is not null and jsonb_typeof(${a.meta}) = 'object'`
146
+ const touched = new Set<string>()
147
+ const run = async (set: ReturnType<typeof sql>, where: ReturnType<typeof sql>) => {
148
+ const res: any = await tx.execute(sql`update ${a} set meta = nullif(${set}, '{}'::jsonb) where ${isObject} and (${where}) returning ${a.id}`)
149
+ for (const row of res?.rows ?? []) touched.add(String(row.id))
150
+ }
151
+ const strip = sql`${a.meta} - 'email' - 'ip' - 'name'`
152
+ // Naming the address: a sign-in attempt (its IP address went with the attempt) or an entry by somebody
153
+ // else about this person (the actor's own details are not ours to take).
154
+ await run(sql`case when ${a.action} like 'auth.%' then ${strip} else ${a.meta} - 'email' end`, sql`lower(btrim(${a.meta}->>'email')) = ${email}`)
155
+ if (account) {
156
+ await run(strip, sql`${a.recordId} = ${account.id} and ${a.action} like 'user.%' and ${a.meta} ?| array['email', 'ip', 'name']`)
157
+ // Their own entries: their client address, and their name if it is the one on the entry.
158
+ const name = (account.name ?? '').trim().toLowerCase()
159
+ await run(
160
+ sql`case when ${name}::text <> '' and lower(btrim(${a.meta}->>'name')) = ${name} then ${a.meta} - 'ip' - 'name' else ${a.meta} - 'ip' end`,
161
+ sql`${a.userId} = ${account.id} and (${a.meta} ? 'ip' or (${name}::text <> '' and lower(btrim(${a.meta}->>'name')) = ${name}))`,
162
+ )
163
+ }
164
+ return touched.size
165
+ }
166
+
167
+ function groupByForm(found: FoundSubmission[]): { form: CmsEntity; ids: string[] }[] {
168
+ const by = new Map<string, { form: CmsEntity; ids: string[] }>()
169
+ for (const { form, row } of found) {
170
+ const g = by.get(form.name) ?? { form, ids: [] }
171
+ g.ids.push(row.id)
172
+ by.set(form.name, g)
173
+ }
174
+ return [...by.values()]
175
+ }
176
+
@@ -0,0 +1,57 @@
1
+ import { alias, and, eq, isNull, lte, or, propOf, snake, sql } from 'tinyzoo'
2
+ import type { CmsEntity } from 'tinyzoo'
3
+
4
+ // What is live, as a Drizzle condition. With explicit imports only (no Nitro auto-imports):
5
+ // `tinyzoo links:convert` uses it too, outside Nitro. (Drizzle's `and` leaves out a condition
6
+ // that is undefined, so "no condition" needs no special case.)
7
+
8
+ /**
9
+ * The "is live" Drizzle condition for an entity (undefined = everything is public):
10
+ * `content.published` — or, without one, the publish workflow's status — and, for
11
+ * scheduled entries, a publish date that has come. In a page tree every ancestor must
12
+ * be live too: a page under a draft is not on the website. Everything that decides what
13
+ * visitors see goes through here: the content API, populated references, the sitemap,
14
+ * webhooks.
15
+ */
16
+ export function publishedCond(e: CmsEntity): any {
17
+ return and(ownPublishedCond(e), ancestorsLiveCond(e))
18
+ }
19
+
20
+ /** The entry's own "is live" condition, against `t` (its table, or an alias of it). */
21
+ export function ownPublishedCond(e: CmsEntity, t: any = e.table): any {
22
+ const p = e.publish
23
+ const status = p ? eq(t[propOf(p.field, e.fields[p.field]!)], p.publishedValue) : undefined
24
+ const base: any = e.content?.published ? e.content.published(t) : status
25
+ return and(base, scheduleCond(e, t))
26
+ }
27
+
28
+ /** "Its publish date has come" (or it has none), for entities whose publishing is scheduled. */
29
+ export function scheduleCond(e: CmsEntity, t: any = e.table): any {
30
+ const p = e.publish
31
+ if (!p?.dateField || p.schedule === false) return undefined
32
+ const col = t[propOf(p.dateField, e.fields[p.dateField]!)]
33
+ return or(isNull(col), lte(col, sql`now()`))
34
+ }
35
+
36
+ /**
37
+ * Page tree: every ancestor is live too. The whole chain up to the top is walked (a
38
+ * recursive query, so a page that sits deeper than `tree.maxDepth` allows today — the
39
+ * limit was lowered after it was made — is judged by all of its ancestors, not only by the
40
+ * nearest ones). Stops at a top-level page; a page without a parent pays nothing.
41
+ */
42
+ export function ancestorsLiveCond(e: CmsEntity): any {
43
+ if (!e.tree) return undefined
44
+ const parentProp = `${e.tree.parent}Id`
45
+ const base = snake(e.name)
46
+ const first: any = alias(e.table, `${base}_up`)
47
+ const step: any = alias(e.table, `${base}_upn`)
48
+ const live = (t: any) => sql`coalesce(${ownPublishedCond(e, t) ?? sql`true`}, false)`
49
+ // `union` (not `union all`) drops a row it has seen, so a loop in stored data ends the walk.
50
+ return or(isNull(e.table[parentProp]), sql`not exists (
51
+ with recursive up(id, parent_id, live) as (
52
+ select ${first.id}, ${first[parentProp]}, ${live(first)} from ${e.table} ${first} where ${first.id} = ${e.table[parentProp]}
53
+ union
54
+ select ${step.id}, ${step[parentProp]}, ${live(step)} from ${e.table} ${step} join up on ${step.id} = up.parent_id
55
+ ) select 1 from up where not up.live
56
+ )`)
57
+ }