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,354 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { and, desc, eq, indexTree, inArray, or, pathTemplateKeys, propOf, sitePath, sql, entryTexts, foldSearchText, isSearchableField, matchEntry, highlightRanges } from 'tinyzoo'
3
+ import type { CmsEntity, CmsRegistry } from 'tinyzoo'
4
+ import { mergeTranslation } from './cmsLocales'
5
+ // Explicit (not Nitro's auto-import): the CLI's import rebuilds the index outside Nitro.
6
+ import { upgradedCopy } from './cmsBlocks'
7
+
8
+ /**
9
+ * Search, typos included, on Postgres alone (the pg_trgm extension).
10
+ *
11
+ * The index (`cms_search`) holds what each entry says as plain text — one row per
12
+ * entry and language — kept up to date by reportChange and rebuilt when the search
13
+ * configuration changes. A search runs in two steps:
14
+ *
15
+ * 1. Postgres finds candidates: every word is in the entry, exactly or close to a
16
+ * word in it (trigram word similarity, through GIN indexes), so a typo is not missed;
17
+ * 2. each candidate's text is checked word by word (src/search.ts: within one typo
18
+ * for words of 4–7 letters, two for longer ones, a swap counting as one), which
19
+ * drops lookalikes ("bazar" is not "bazén"), ranks the rest and cuts a snippet.
20
+ *
21
+ * Used by the website search (`/api/content/_search`) and the admin's search (`/api/cms/_search`).
22
+ */
23
+
24
+ /** Bump when what goes into the index changes: every site rebuilds it once. */
25
+ const INDEX_VERSION = 1
26
+ const STATE_KEY = 'search.index'
27
+ const LOCK = 72_011_005
28
+ /** Trigram word similarity a candidate needs (lenient: step 2 decides). */
29
+ const THRESHOLD = 0.3
30
+ /** Most candidates read per collection, best first. */
31
+ const CANDIDATES = 100
32
+ const BATCH = 500
33
+
34
+ // ── what goes into the index ──────────────────────────────────────────────────
35
+
36
+ interface SearchDoc { title: string; body: string; extra: string }
37
+
38
+ /**
39
+ * An entry's text: `body` is what visitors may read (no hidden fields; only
40
+ * `content.search.fields` when set); `extra` the rest, for the admin only —
41
+ * hidden or left-out prose and the list's searchable fields (an email address).
42
+ */
43
+ function documentOf(e: CmsEntity, source: Record<string, any>): SearchDoc {
44
+ // Read blocks in their current shape (a renamed field is still found).
45
+ const row = upgradedCopy(e, source)
46
+ const cfg = e.content?.search
47
+ const picked = cfg && typeof cfg === 'object' && Array.isArray(cfg.fields) ? new Set<string>(cfg.fields) : null
48
+ const hidden = new Set<string>(e.content?.hidden ?? [])
49
+ const publicFields: Record<string, any> = {}
50
+ const privateFields: Record<string, any> = {}
51
+ for (const [k, fld] of Object.entries(e.fields)) {
52
+ if (k === e.titleField) continue
53
+ if (hidden.has(k) || (picked && !picked.has(k))) privateFields[k] = fld
54
+ else publicFields[k] = fld
55
+ }
56
+ const extra = entryTexts(privateFields, row)
57
+ for (const k of e.admin?.list?.searchable ?? []) {
58
+ const fld = e.fields[k]
59
+ if (k !== e.titleField && fld && !fld.relation && !isSearchableField(fld) && row[k] != null && row[k] !== '') extra.push(String(row[k]))
60
+ }
61
+ const title = row[e.titleField]
62
+ return { title: typeof title === 'string' ? title : title == null ? '' : String(title), body: entryTexts(publicFields, row).join('\n'), extra: extra.join('\n') }
63
+ }
64
+
65
+ /** Index rows of one entry: one per language it exists in, or one ('') without translations. */
66
+ function indexRows(reg: CmsRegistry, e: CmsEntity, row: Record<string, any>, translations: any[]): any[] {
67
+ const out: any[] = []
68
+ const add = (locale: string, values: Record<string, any>, path: string | null) => {
69
+ const d = documentOf(e, values)
70
+ out.push({
71
+ entity: e.name, recordId: row.id, locale,
72
+ title: d.title, body: d.body, extra: d.extra,
73
+ titleFolded: foldSearchText(d.title), bodyFolded: foldSearchText(d.body), extraFolded: foldSearchText(d.extra),
74
+ path, updatedAt: new Date(),
75
+ })
76
+ }
77
+ // A page tree's address depends on its ancestors, who can change without this entry
78
+ // being saved: it is worked out when searching, not stored.
79
+ const pathOf = (locale: string | null, values: Record<string, any>) => (e.tree ? null : sitePath(reg.locales, e.content?.path, locale, values))
80
+ if (reg.locales && e.localized.length) {
81
+ const def = reg.locales.default
82
+ add(def, row, pathOf(def, row))
83
+ for (const tr of translations) {
84
+ if (tr.locale === def || !reg.locales.locales.includes(tr.locale)) continue
85
+ const merged = mergeTranslation(e, { ...row }, tr)
86
+ add(tr.locale, merged, pathOf(tr.locale, merged))
87
+ }
88
+ }
89
+ else add('', row, null)
90
+ return out
91
+ }
92
+
93
+ async function insertRows(db: any, reg: CmsRegistry, rows: any[]) {
94
+ const s = reg.cmsSearch
95
+ for (let i = 0; i < rows.length; i += BATCH) {
96
+ await db.insert(s).values(rows.slice(i, i + BATCH)).onConflictDoUpdate({
97
+ target: [s.entity, s.recordId, s.locale],
98
+ set: {
99
+ title: sql`excluded.title`, body: sql`excluded.body`, extra: sql`excluded.extra`,
100
+ titleFolded: sql`excluded.title_folded`, bodyFolded: sql`excluded.body_folded`, extraFolded: sql`excluded.extra_folded`,
101
+ path: sql`excluded.path`, updatedAt: sql`excluded.updated_at`,
102
+ },
103
+ })
104
+ }
105
+ }
106
+
107
+ const indexable = (e: CmsEntity) => !e.singleton
108
+
109
+ /** Bring one entry's index rows up to date (all its languages); removes them when it is gone. */
110
+ export async function indexEntry(db: any, reg: CmsRegistry, e: CmsEntity, id: string): Promise<void> {
111
+ if (!indexable(e)) return
112
+ const s = reg.cmsSearch
113
+ await db.transaction(async (tx: any) => {
114
+ const [row] = await tx.select().from(e.table).where(eq(e.table.id, id))
115
+ await tx.delete(s).where(and(eq(s.entity, e.name), eq(s.recordId, id)))
116
+ if (!row) return
117
+ const translations = e.localesTable && e.localized.length
118
+ ? await tx.select().from(e.localesTable).where(eq(e.localesTable.parentId, id))
119
+ : []
120
+ await insertRows(tx, reg, indexRows(reg, e, row, translations))
121
+ })
122
+ }
123
+
124
+ /** Keep the index in step with a reported change (called by reportChange). */
125
+ export async function syncSearchIndex(e: CmsEntity, id: string, type: string): Promise<void> {
126
+ if (!indexable(e)) return
127
+ const { db, reg } = useCms()
128
+ if (type === 'entry.deleted') {
129
+ const s = reg.cmsSearch
130
+ await db.delete(s).where(and(eq(s.entity, e.name), eq(s.recordId, id)))
131
+ }
132
+ else await indexEntry(db, reg, e, id)
133
+ }
134
+
135
+ /** What the index is built from: when it changes, the index is rebuilt. */
136
+ export function searchIndexSignature(reg: CmsRegistry): string {
137
+ const fieldShape = (fields: Record<string, any>): any => Object.entries(fields).map(([k, f]) => [
138
+ k, f.type, f.meta?.format ?? null,
139
+ f.blocks ? Object.fromEntries(Object.entries(f.blocks as Record<string, any>).map(([t, b]) => [t, fieldShape(b.fields)])) : null,
140
+ // Only groups add an element: the signature of a site without one stays what it was.
141
+ ...(f.fields ? [fieldShape(f.fields)] : []),
142
+ ])
143
+ const shape = reg.entities.filter(indexable).map((e) => ({
144
+ name: e.name, title: e.titleField, localized: e.localized, fields: fieldShape(e.fields),
145
+ hidden: e.content?.hidden ?? [], search: e.content?.search ?? null, searchable: e.admin?.list?.searchable ?? [],
146
+ path: e.content?.path ?? null, tree: e.tree ?? null,
147
+ }))
148
+ return createHash('sha256').update(JSON.stringify({ v: INDEX_VERSION, locales: reg.locales, shape })).digest('hex')
149
+ }
150
+
151
+ /**
152
+ * Rebuild the whole index (one replica at a time; the others skip). Readers keep
153
+ * the old index until it is done. Returns the number of index rows, or null when
154
+ * another replica is already at it.
155
+ */
156
+ export async function rebuildSearchIndex(db: any, reg: CmsRegistry): Promise<number | null> {
157
+ const s = reg.cmsSearch
158
+ const signature = searchIndexSignature(reg)
159
+ return db.transaction(async (tx: any) => {
160
+ const [{ locked }] = (await tx.execute(sql`select pg_try_advisory_xact_lock(${LOCK}) as locked`)).rows
161
+ if (!locked) return null
162
+ await tx.delete(s)
163
+ let count = 0
164
+ for (const e of reg.entities.filter(indexable)) {
165
+ for (let offset = 0; ; offset += BATCH) {
166
+ const rows: any[] = await tx.select().from(e.table).orderBy(e.table.id).limit(BATCH).offset(offset)
167
+ if (!rows.length) break
168
+ const byParent = new Map<string, any[]>()
169
+ if (e.localesTable && e.localized.length) {
170
+ const trs: any[] = await tx.select().from(e.localesTable).where(inArray(e.localesTable.parentId, rows.map((r) => r.id)))
171
+ for (const tr of trs) byParent.set(tr.parentId, [...(byParent.get(tr.parentId) ?? []), tr])
172
+ }
173
+ const out = rows.flatMap((row) => indexRows(reg, e, row, byParent.get(row.id) ?? []))
174
+ await insertRows(tx, reg, out)
175
+ count += out.length
176
+ if (rows.length < BATCH) break
177
+ }
178
+ }
179
+ const st = reg.cmsState
180
+ const value = { signature, at: new Date().toISOString(), rows: count }
181
+ await tx.insert(st).values({ key: STATE_KEY, value }).onConflictDoUpdate({ target: st.key, set: { value, updatedAt: sql`now()` } })
182
+ return count
183
+ })
184
+ }
185
+
186
+ /** Rebuild the index when it was built from another configuration (or never). Called on start. */
187
+ export async function ensureSearchIndex(): Promise<void> {
188
+ const { db, reg } = useCms()
189
+ const st = reg.cmsState
190
+ const [state] = await db.select().from(st).where(eq(st.key, STATE_KEY))
191
+ if ((state?.value as any)?.signature === searchIndexSignature(reg)) return
192
+ const started = Date.now()
193
+ const rows = await rebuildSearchIndex(db, reg)
194
+ if (rows !== null) console.info(`[cms] search index built: ${rows} entries and translations in ${Date.now() - started} ms`)
195
+ }
196
+
197
+ // ── searching ─────────────────────────────────────────────────────────────────
198
+
199
+ /**
200
+ * Every word is in one of `cols` exactly (LIKE), or close to a word in it (pg_trgm
201
+ * `<%`, index-assisted); words under three letters only exactly.
202
+ */
203
+ function termsCond(cols: any[], terms: string[]): any {
204
+ return and(...terms.map((term) => {
205
+ const like = '%' + term.replace(/[\\%_]/g, (c) => '\\' + c) + '%'
206
+ const exact = cols.map((c) => sql`${c} like ${like}`)
207
+ const near = term.length >= 3 ? cols.map((c) => sql`${term} <% ${c}`) : []
208
+ return or(...exact, ...near)
209
+ }))
210
+ }
211
+
212
+ /** How close the words are, for picking the best candidates (title weighs double). */
213
+ function closeness(title: any, others: any[], terms: string[]): any {
214
+ const parts = terms.map((t) => sql`greatest(word_similarity(${t}, ${title}) * 2, ${sql.join(others.map((c) => sql`word_similarity(${t}, ${c})`), sql`, `)})`)
215
+ return sql`(${sql.join(parts, sql` + `)})`
216
+ }
217
+
218
+ /** Run `fn` with the lenient similarity threshold, for this transaction only. */
219
+ function withThreshold<T>(db: any, fn: (tx: any) => Promise<T>): Promise<T> {
220
+ return db.transaction(async (tx: any) => {
221
+ await tx.execute(sql`select set_config('pg_trgm.word_similarity_threshold', ${String(THRESHOLD)}, true)`)
222
+ return fn(tx)
223
+ })
224
+ }
225
+
226
+ export interface PublicSearchItem {
227
+ entity: string
228
+ id: string
229
+ title: string
230
+ titleHighlights: [number, number][]
231
+ excerpt: string
232
+ highlights: [number, number][]
233
+ /** The entry's address on the website, in the language searched (null if it has none there). */
234
+ path: string | null
235
+ locale: string | null
236
+ updatedAt: string
237
+ score: number
238
+ }
239
+
240
+ /** Collections the website search covers: public, at an address, not opted out. */
241
+ export function publicSearchEntities(reg: CmsRegistry): CmsEntity[] {
242
+ return reg.entities.filter((e) => e.content?.public && !e.singleton && e.content.path && e.content.search !== false)
243
+ }
244
+
245
+ /**
246
+ * The website search: published entries of public collections with an address, in
247
+ * the visitor's language (an entry not translated into it is left out), never
248
+ * matching fields hidden from the public.
249
+ */
250
+ export async function searchPublic(db: any, reg: CmsRegistry, terms: string[], query: string, locale: string | null, only?: Set<string>): Promise<PublicSearchItem[]> {
251
+ const s = reg.cmsSearch
252
+ const out: PublicSearchItem[] = []
253
+ await withThreshold(db, async (tx) => {
254
+ for (const e of publicSearchEntities(reg)) {
255
+ if (only && !only.has(e.name)) continue
256
+ // A collection with translations has a row per language; one without, a row for all.
257
+ const langs = locale && reg.locales && e.localized.length ? [locale] : ['']
258
+ const pathCols: Record<string, any> = {}
259
+ for (const k of pathTemplateKeys(e.content!.path)) if (e.table[k]) pathCols[k] = e.table[k]
260
+ const score = closeness(s.titleFolded, [s.bodyFolded], terms)
261
+ const conds = [eq(s.entity, e.name), inArray(s.locale, langs), termsCond([s.titleFolded, s.bodyFolded], terms), publishedCond(e)]
262
+ const rows: any[] = await tx.select({ id: s.recordId, title: s.title, body: s.body, path: s.path, updatedAt: e.table.updatedAt, rank: score, ...pathCols })
263
+ .from(s).innerJoin(e.table, eq(e.table.id, s.recordId))
264
+ .where(and(...conds.filter(Boolean))).orderBy(desc(score)).limit(CANDIDATES)
265
+ const treeIndex = e.tree && rows.length ? indexTree(await loadTreeNodes(tx, reg, e)) : null
266
+ for (const r of rows) {
267
+ const match = matchEntry(r.title, [r.body], terms, query)
268
+ if (!match) continue
269
+ out.push({
270
+ entity: e.name,
271
+ id: r.id,
272
+ title: r.title,
273
+ titleHighlights: highlightRanges(r.title, terms),
274
+ excerpt: match.excerpt,
275
+ highlights: match.highlights,
276
+ path: treeIndex ? treePathIn(reg, e, treeIndex, r.id, locale) : r.path ?? sitePath(reg.locales, e.content!.path, locale ?? reg.locales?.default ?? null, r),
277
+ locale,
278
+ updatedAt: new Date(r.updatedAt).toISOString(),
279
+ score: match.score,
280
+ })
281
+ }
282
+ }
283
+ })
284
+ return out.sort(byScore)
285
+ }
286
+
287
+ export interface AdminSearchItem {
288
+ entity: string
289
+ id: string
290
+ title: string
291
+ titleHighlights: [number, number][]
292
+ excerpt: string
293
+ highlights: [number, number][]
294
+ /** 'published' | 'scheduled' | 'draft' for collections with publishing, else null. */
295
+ status: string | null
296
+ updatedAt: string
297
+ score: number
298
+ }
299
+
300
+ /**
301
+ * The admin's search: entries of every collection this person may read (their row
302
+ * rules apply), drafts included, in every language — an editor may remember the
303
+ * English title of a Czech page — and the admin-only text (hidden fields, an email).
304
+ */
305
+ export async function searchAdmin(db: any, reg: CmsRegistry, user: any, terms: string[], query: string, perEntity: number): Promise<AdminSearchItem[]> {
306
+ const s = reg.cmsSearch
307
+ const out: AdminSearchItem[] = []
308
+ await withThreshold(db, async (tx) => {
309
+ for (const e of reg.entities) {
310
+ if (!indexable(e)) continue
311
+ const access = accessWhere(e, 'read', user)
312
+ if (!access.allowed) continue
313
+ const p = e.publish
314
+ const due = scheduleCond(e)
315
+ const score = closeness(s.titleFolded, [s.bodyFolded, s.extraFolded], terms)
316
+ const rows: any[] = await tx.select({
317
+ id: s.recordId, locale: s.locale, title: s.title, body: s.body, extra: s.extra, rank: score,
318
+ ownTitle: e.table[e.titleField], updatedAt: e.table.updatedAt,
319
+ status: p ? e.table[propOf(p.field, e.fields[p.field]!)] : sql`null`,
320
+ due: due ? sql<boolean>`coalesce(${due}, false)` : sql<boolean>`true`,
321
+ }).from(s).innerJoin(e.table, eq(e.table.id, s.recordId))
322
+ .where(both(and(eq(s.entity, e.name), termsCond([s.titleFolded, s.bodyFolded, s.extraFolded], terms)), access.where))
323
+ .orderBy(desc(score)).limit(CANDIDATES)
324
+
325
+ // One result per entry, read across its languages.
326
+ const byId = new Map<string, any[]>()
327
+ for (const r of rows) byId.set(r.id, [...(byId.get(r.id) ?? []), r])
328
+ const found: AdminSearchItem[] = []
329
+ for (const [id, versions] of byId) {
330
+ const first = versions[0]
331
+ const title = String(first.ownTitle ?? first.title ?? '')
332
+ const titles = [...new Set([title, ...versions.map((v) => v.title)])].filter(Boolean).join(' · ')
333
+ const match = matchEntry(titles, versions.flatMap((v) => [v.body, v.extra]).filter(Boolean), terms, query)
334
+ if (!match) continue
335
+ found.push({
336
+ entity: e.name,
337
+ id,
338
+ title,
339
+ titleHighlights: highlightRanges(title, terms),
340
+ excerpt: match.excerpt,
341
+ highlights: match.highlights,
342
+ status: !p ? null : first.status !== p.publishedValue ? 'draft' : first.due ? 'published' : 'scheduled',
343
+ updatedAt: new Date(first.updatedAt).toISOString(),
344
+ score: match.score,
345
+ })
346
+ }
347
+ out.push(...found.sort(byScore).slice(0, perEntity))
348
+ }
349
+ })
350
+ return out.sort(byScore)
351
+ }
352
+
353
+ const byScore = (a: { score: number; updatedAt: string }, b: { score: number; updatedAt: string }) =>
354
+ b.score - a.score || b.updatedAt.localeCompare(a.updatedAt)
@@ -0,0 +1,102 @@
1
+ import { eq } from 'tinyzoo'
2
+
3
+
4
+ export interface CmsUser {
5
+ id: string
6
+ email?: string
7
+ name?: string
8
+ /** 'admin' | 'editor' | 'author' with built-in auth; anything with external auth. */
9
+ role: string
10
+ locale?: string | null
11
+ }
12
+
13
+ /**
14
+ * Current user on `event.context.cmsUser`. With built-in auth the CMS's own
15
+ * middleware (server/middleware/cms-session.ts) sets it from the session after
16
+ * checking the account in the database; with `cms.auth.mode: 'external'` the host does.
17
+ */
18
+ /** The name of the session cookie (nuxt-auth-utils: `nuxt-session`, or `runtimeConfig.session.name`). */
19
+ export function sessionCookieName(): string {
20
+ return String((useRuntimeConfig().session as any)?.name || 'nuxt-session')
21
+ }
22
+
23
+ /**
24
+ * Does the request carry a session cookie at all? Reading a session when it does not
25
+ * *creates* one and sets its cookie on the response — so every anonymous visitor got a
26
+ * cookie (and a CDN refused to cache the page). Only look at the session when there is
27
+ * one to look at.
28
+ */
29
+ export function hasSessionCookie(event: any): boolean {
30
+ const name = sessionCookieName()
31
+ const header = event?.node?.req?.headers?.cookie ?? event?.headers?.get?.('cookie')
32
+ return typeof header === 'string' && header.split(';').some((c) => c.trim().startsWith(name + '='))
33
+ }
34
+
35
+ export function getCmsSession(event: any): CmsUser | null {
36
+ return (event.context?.cmsUser as CmsUser) ?? null
37
+ }
38
+
39
+ export function requireCmsUser(event: any): CmsUser {
40
+ const user = getCmsSession(event)
41
+ if (!user) throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
42
+ return user
43
+ }
44
+
45
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
46
+
47
+ /**
48
+ * The account a sealed session belongs to, if it may still be used: it exists, is
49
+ * active, and the session was issued for its current session version (a password
50
+ * change or "sign out everywhere" bumps it). Null otherwise.
51
+ */
52
+ export async function activeAccountOf(session: any): Promise<any | null> {
53
+ const id = session?.cms?.uid
54
+ if (typeof id !== 'string' || !UUID.test(id)) return null
55
+ const { db, reg } = useCms()
56
+ const [u] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, id))
57
+ if (!u || u.status !== 'active' || u.sessionVersion !== session?.cms?.sv) return null
58
+ return u
59
+ }
60
+
61
+ /**
62
+ * Admit a WebSocket upgrade for the admin (realtime, shared editing): it must come
63
+ * from this site's own pages and carry a valid built-in session for an active
64
+ * account. Puts the account on `request.context` (cmsUser, cmsSessionVersion), which
65
+ * the socket's peer then carries. Throws a Response to refuse.
66
+ */
67
+ export async function admitAdminSocket(request: any): Promise<void> {
68
+ if (cmsAuthMode() !== 'builtin') throw new Response('Needs the built-in sign-in', { status: 404 })
69
+ if (!sameOrigin(request)) throw new Response('Forbidden', { status: 403 })
70
+ const session: any = hasSessionCookie(request) ? await getUserSession(request).catch(() => null) : null
71
+ const u = await activeAccountOf(session)
72
+ if (!u) throw new Response('Unauthorized', { status: 401 })
73
+ request.context.cmsUser = { id: u.id, email: u.email, name: u.name || u.email, role: u.role, locale: u.locale }
74
+ request.context.cmsSessionVersion = u.sessionVersion
75
+ }
76
+
77
+ /**
78
+ * Browsers always send Origin on a WebSocket handshake, and cookies go with it even
79
+ * from other sites, so the origin must be this host (as the browser addressed it,
80
+ * or the configured public address).
81
+ */
82
+ function sameOrigin(request: any): boolean {
83
+ const origin = request.headers?.get?.('origin')
84
+ if (!origin) return false
85
+ let host: string
86
+ try {
87
+ host = new URL(origin).host
88
+ }
89
+ catch {
90
+ return false
91
+ }
92
+ const allowed = new Set<string>()
93
+ for (const h of [request.headers.get('host'), request.headers.get('x-forwarded-host')]) if (h) allowed.add(String(h).split(',')[0]!.trim())
94
+ const pub = (useRuntimeConfig().cms as any)?.publicUrl
95
+ if (pub) {
96
+ try {
97
+ allowed.add(new URL(pub).host)
98
+ }
99
+ catch { /* not a URL */ }
100
+ }
101
+ return allowed.has(host)
102
+ }
@@ -0,0 +1,97 @@
1
+ import { eq, generateSetupCode, normalizeSetupCode, sql } from 'tinyzoo'
2
+
3
+ /**
4
+ * The setup code of a fresh production deploy.
5
+ *
6
+ * `NUXT_CMS_AUTH_SETUP_TOKEN` is optional, so without it anyone opening
7
+ * /admin/setup on a new deploy would become its administrator. In production, with
8
+ * no token configured and no account yet, the app makes a random one-time code
9
+ * instead and prints it in the log: whoever deployed the site can read it, a
10
+ * visitor cannot.
11
+ *
12
+ * Several replicas share one code: it lives in `cms_state` (key `setup_code`), only
13
+ * as a hash. The instance that stores it prints it; the others find it there and
14
+ * print where to look. It is removed when the first account exists (in the same
15
+ * transaction as the account itself, see setup.post.ts).
16
+ */
17
+ export const SETUP_CODE_KEY = 'setup_code'
18
+
19
+ /** A code printed less than this long ago is left alone: its log line is still the one to read. */
20
+ const REISSUE_AFTER = '5 minutes'
21
+
22
+ /**
23
+ * A built server counts as production unless it says otherwise (NODE_ENV=development
24
+ * or test, or `nuxt dev`): an unset NODE_ENV must not leave a deploy open.
25
+ */
26
+ export function isProductionServer(): boolean {
27
+ if (import.meta.dev) return false
28
+ const env = typeof process !== 'undefined' ? process.env?.NODE_ENV : undefined
29
+ return env !== 'development' && env !== 'test'
30
+ }
31
+
32
+ /** True when first-run setup asks for a generated code: production, built-in sign-in, no configured token. */
33
+ export function setupCodeApplies(): boolean {
34
+ return cmsAuthMode() === 'builtin' && !setupToken() && isProductionServer()
35
+ }
36
+
37
+ async function noAccountYet(db: any, reg: any): Promise<boolean> {
38
+ const [row] = await db.select({ n: sql<number>`count(*)::int` }).from(reg.cmsUsers)
39
+ return Number(row?.n ?? 0) === 0
40
+ }
41
+
42
+ /**
43
+ * Make sure a code exists while there is no account, and print it when this call
44
+ * made it. At start (`reissue`) an older code whose plain text is gone is replaced
45
+ * and printed again; later calls (the status endpoint) only fill a gap.
46
+ */
47
+ export async function ensureSetupCode(opts: { reissue?: boolean } = {}): Promise<'issued' | 'exists' | 'not-needed'> {
48
+ if (!setupCodeApplies()) return 'not-needed'
49
+ const { db, reg } = useCms()
50
+ const s = reg.cmsState
51
+ if (!(await noAccountYet(db, reg))) {
52
+ await db.delete(s).where(eq(s.key, SETUP_CODE_KEY)) // a leftover of an earlier run
53
+ return 'not-needed'
54
+ }
55
+ // The status endpoint asks on every visit: when a code exists there is nothing to write.
56
+ if (!opts.reissue && (await db.select({ key: s.key }).from(s).where(eq(s.key, SETUP_CODE_KEY))).length) return 'exists'
57
+ const code = generateSetupCode()
58
+ const value = { hash: await sha256Hex(normalizeSetupCode(code)), at: new Date().toISOString() }
59
+ const insert = db.insert(s).values({ key: SETUP_CODE_KEY, value })
60
+ const rows: any[] = opts.reissue
61
+ ? await insert.onConflictDoUpdate({
62
+ target: s.key,
63
+ set: { value, updatedAt: sql`now()` },
64
+ setWhere: sql`${s.updatedAt} < now() - ${REISSUE_AFTER}::interval`,
65
+ }).returning({ key: s.key })
66
+ : await insert.onConflictDoNothing().returning({ key: s.key })
67
+ if (rows.length) {
68
+ const base = String((useRuntimeConfig().cms as any)?.publicUrl || '').replace(/\/+$/, '')
69
+ console.warn(`[cms] No administrator yet. Setup code: ${code} — open ${base}/admin/setup`)
70
+ return 'issued'
71
+ }
72
+ if (opts.reissue) console.warn('[cms] No administrator yet. A setup code was issued a moment ago (by another instance) — look for "Setup code:" in the log.')
73
+ return 'exists'
74
+ }
75
+
76
+ /**
77
+ * May setup go on with what the person typed? Not asked once an account exists (the
78
+ * setup endpoint then answers "already set up" whatever was typed); until then it must
79
+ * be the current code.
80
+ */
81
+ export async function setupCodeAccepts(input: unknown): Promise<boolean> {
82
+ if (await verifySetupCode(input)) return true
83
+ const { db, reg } = useCms()
84
+ return !(await noAccountYet(db, reg))
85
+ }
86
+
87
+ /** Is `input` the current setup code? Compares hashes in constant time. */
88
+ export async function verifySetupCode(input: unknown): Promise<boolean> {
89
+ const typed = normalizeSetupCode(input)
90
+ const { db, reg } = useCms()
91
+ const [row] = await db.select().from(reg.cmsState).where(eq(reg.cmsState.key, SETUP_CODE_KEY))
92
+ const value = (row?.value ?? {}) as { hash?: unknown }
93
+ const stored = typeof value.hash === 'string' ? value.hash : ''
94
+ // Hash even a missing or empty input, so the time does not tell whether a code exists.
95
+ const given = await sha256Hex(typed)
96
+ return !!stored && !!typed && constantTimeEqual(given, stored)
97
+ }