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