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,42 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
import { CMS_IMAGE_WIDTHS, imageVariant, isResizableImage, MAX_IMAGE_PIXELS } from '../../../../../utils/cmsImageSizes'
|
|
3
|
+
|
|
4
|
+
// GET /api/cms/_media/img/<media id>/<width>.webp — a smaller copy of an uploaded
|
|
5
|
+
// picture (see cmsImageSizes). Public like the files themselves, cached for a year.
|
|
6
|
+
//
|
|
7
|
+
// A picture that cannot be resized (more pixels than the limit — files stored before
|
|
8
|
+
// the limit was checked at upload — or a file the decoder cannot read) is sent as the
|
|
9
|
+
// original instead of an error: the page still shows it, and its <img srcset> does not
|
|
10
|
+
// break on one candidate.
|
|
11
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
12
|
+
export default defineEventHandler(async (event) => {
|
|
13
|
+
const id = getRouterParam(event, 'id') ?? ''
|
|
14
|
+
const width = Number(/^(\d+)\.webp$/.exec(getRouterParam(event, 'file') ?? '')?.[1])
|
|
15
|
+
if (!UUID.test(id) || !(CMS_IMAGE_WIDTHS as readonly number[]).includes(width)) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
16
|
+
const { db, reg } = useCms()
|
|
17
|
+
const [m] = await db.select({ key: reg.cmsMedia.key, url: reg.cmsMedia.url, mime: reg.cmsMedia.mime, width: reg.cmsMedia.width, height: reg.cmsMedia.height }).from(reg.cmsMedia).where(eq(reg.cmsMedia.id, id))
|
|
18
|
+
if (!m || !isResizableImage(m.mime)) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
19
|
+
|
|
20
|
+
const original = () => {
|
|
21
|
+
// Not for a year: the picture may be replaced by a smaller one under the same address.
|
|
22
|
+
setResponseHeader(event, 'Cache-Control', 'public, max-age=3600')
|
|
23
|
+
return sendRedirect(event, m.url, 302)
|
|
24
|
+
}
|
|
25
|
+
if (m.width && m.height && m.width * m.height > MAX_IMAGE_PIXELS) return original()
|
|
26
|
+
|
|
27
|
+
let body: Buffer | null
|
|
28
|
+
try {
|
|
29
|
+
body = await imageVariant(m.key, width)
|
|
30
|
+
}
|
|
31
|
+
catch (err: any) {
|
|
32
|
+
if (err?.statusCode) throw err // the store is unavailable (502): say so
|
|
33
|
+
// The decoder refused the file (too many pixels, damaged): the original is all there is.
|
|
34
|
+
console.warn('[cms] a picture could not be resized, sending the original:', String(err?.message ?? err).slice(0, 200))
|
|
35
|
+
return original()
|
|
36
|
+
}
|
|
37
|
+
if (!body) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
38
|
+
setResponseHeader(event, 'Content-Type', 'image/webp')
|
|
39
|
+
setResponseHeader(event, 'X-Content-Type-Options', 'nosniff')
|
|
40
|
+
setResponseHeader(event, 'Cache-Control', 'public, max-age=31536000, immutable')
|
|
41
|
+
return body
|
|
42
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { and, asc, desc, eq, inArray, isNotNull, isNull, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_media — paginated media library (newest first). Optional ?q= search
|
|
4
|
+
// over name/alt (in every language)/key/mime, ?accept= (e.g. "image/*") to filter by MIME so a typed
|
|
5
|
+
// picker's count + items match, and ?folder= (a folder's name, or "none"). Returns
|
|
6
|
+
// the library's folders too. Powers the media page and the picker.
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
requireCmsUser(event)
|
|
9
|
+
const { db, reg } = useCms()
|
|
10
|
+
const m = reg.cmsMedia
|
|
11
|
+
|
|
12
|
+
const query = getQuery(event)
|
|
13
|
+
const page = Math.max(1, Number(query.page) || 1)
|
|
14
|
+
const limit = Math.min(60, Math.max(1, Number(query.limit) || 24))
|
|
15
|
+
const offset = Math.min((page - 1) * limit, 100_000) // bound deep-offset scans
|
|
16
|
+
const q = String(query.q ?? '').trim().slice(0, 100)
|
|
17
|
+
const accept = String(query.accept ?? '').trim()
|
|
18
|
+
|
|
19
|
+
const conds: any[] = []
|
|
20
|
+
if (q) {
|
|
21
|
+
// Escape LIKE wildcards so a literal % / _ in the query can't widen the match.
|
|
22
|
+
const esc = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
|
|
23
|
+
// Descriptions are per content language (alt_locales): a search finds a file by what it says in any of them.
|
|
24
|
+
conds.push(sql`(${m.name} ilike ${esc} or ${m.alt} ilike ${esc} or exists (select 1 from jsonb_each_text(coalesce(${m.altLocales}, '{}'::jsonb)) as alt(lang, text) where alt.text ilike ${esc}) or ${m.key} ilike ${esc} or ${m.mime} ilike ${esc})`)
|
|
25
|
+
}
|
|
26
|
+
if (accept && accept !== '*') {
|
|
27
|
+
const parts = accept.split(',').map((s) => s.trim()).filter(Boolean)
|
|
28
|
+
const mimeConds = parts.map((a) => a.endsWith('/*') ? sql`${m.mime} ilike ${`${a.slice(0, -1)}%`}` : sql`${m.mime} = ${a}`)
|
|
29
|
+
if (mimeConds.length) conds.push(sql`(${sql.join(mimeConds, sql` or `)})`)
|
|
30
|
+
}
|
|
31
|
+
// ?ids=a,b — exactly these files (a gallery loading its thumbnails).
|
|
32
|
+
const ids = String(query.ids ?? '').split(',').filter((id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)).slice(0, 200)
|
|
33
|
+
if (ids.length) conds.push(inArray(m.id, ids))
|
|
34
|
+
const folder = typeof query.folder === 'string' ? query.folder : ''
|
|
35
|
+
if (folder === 'none') conds.push(isNull(m.folder))
|
|
36
|
+
else if (folder) conds.push(eq(m.folder, folder.slice(0, 80)))
|
|
37
|
+
const where = conds.length ? and(...conds) : undefined
|
|
38
|
+
|
|
39
|
+
const rows = await db.select().from(m).where(where).orderBy(desc(m.createdAt)).limit(limit).offset(offset)
|
|
40
|
+
const [counted] = await db.select({ count: sql<number>`count(*)::int` }).from(m).where(where)
|
|
41
|
+
const count = counted?.count ?? 0
|
|
42
|
+
const folders: any[] = await db.selectDistinct({ folder: m.folder }).from(m).where(isNotNull(m.folder)).orderBy(asc(m.folder)).limit(200)
|
|
43
|
+
return { items: rows, total: count, page, limit, folders: folders.map((f) => f.folder) }
|
|
44
|
+
})
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { eq, sql } from 'tinyzoo'
|
|
3
|
+
import { imageSize } from 'image-size'
|
|
4
|
+
|
|
5
|
+
// Allowlist of storable types → canonical extension. Deliberately EXCLUDES
|
|
6
|
+
// svg / html / xml: those execute script when served inline from our own origin
|
|
7
|
+
// (stored-XSS). The stored extension is derived from the validated MIME, never
|
|
8
|
+
// from the attacker-supplied filename, so the served Content-Type stays trusted.
|
|
9
|
+
const ALLOWED: Record<string, string> = {
|
|
10
|
+
'image/png': 'png',
|
|
11
|
+
'image/jpeg': 'jpg',
|
|
12
|
+
'image/gif': 'gif',
|
|
13
|
+
'image/webp': 'webp',
|
|
14
|
+
'image/avif': 'avif',
|
|
15
|
+
'video/mp4': 'mp4',
|
|
16
|
+
'video/webm': 'webm',
|
|
17
|
+
'audio/mpeg': 'mp3',
|
|
18
|
+
'application/pdf': 'pdf',
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** What a type is called in "Not a readable …". */
|
|
22
|
+
const ALLOWED_KIND: Record<string, string> = {
|
|
23
|
+
'application/pdf': 'PDF',
|
|
24
|
+
'video/mp4': 'video',
|
|
25
|
+
'video/webm': 'video',
|
|
26
|
+
'audio/mpeg': 'audio file',
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// POST /api/cms/_media — multipart upload. Stores the blob via the StorageDriver
|
|
30
|
+
// and records metadata in cms_media. Returns the media record.
|
|
31
|
+
export default defineEventHandler(async (event) => {
|
|
32
|
+
const user = requireCmsUser(event)
|
|
33
|
+
const { db, reg } = useCms()
|
|
34
|
+
const storage = useCmsStorage()
|
|
35
|
+
|
|
36
|
+
// Rate-limit per user before doing any work.
|
|
37
|
+
if (!(await rateLimit(`upload:${user.id}`, uploadRatePerMin(), 60_000))) {
|
|
38
|
+
throw tooManyRequests(event, 'Too many uploads; slow down.', 60_000)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const max = maxUploadBytes()
|
|
42
|
+
// Refuse an oversized body from the declared Content-Length before reading any of it
|
|
43
|
+
// (the coarse global guard in cms-limits.ts backs this up). +1MB multipart margin.
|
|
44
|
+
const declared = Number(getHeader(event, 'content-length') || 0)
|
|
45
|
+
if (declared && declared > max + 1024 * 1024) {
|
|
46
|
+
throw createError({ statusCode: 413, statusMessage: 'File too large (max ' + Math.round(max / 1024 / 1024) + 'MB)', data: { code: 'file_too_large', maxMb: Math.round(max / 1024 / 1024) } })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The body is read as it arrives, into a temp file; the cap counts the bytes that
|
|
50
|
+
// really come in (chunked bodies have no Content-Length). See cmsUpload.ts.
|
|
51
|
+
const { file, fields } = await receiveUpload(event, { maxBytes: max, tempDir: storage.tempDir })
|
|
52
|
+
try {
|
|
53
|
+
if (!file) {
|
|
54
|
+
throw createError({ statusCode: 400, statusMessage: 'No file uploaded (expected multipart field "file")' })
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const mime = file.type
|
|
58
|
+
const ext = ALLOWED[mime]
|
|
59
|
+
if (!ext) {
|
|
60
|
+
throw createError({ statusCode: 415, statusMessage: `Unsupported media type: ${mime || 'unknown'}` })
|
|
61
|
+
}
|
|
62
|
+
if (!file.size) throw createError({ statusCode: 400, statusMessage: 'The file is empty' })
|
|
63
|
+
|
|
64
|
+
// The type says what it is; the first bytes must agree (a renamed text file, a
|
|
65
|
+
// download cut off before its header).
|
|
66
|
+
if (!looksLike(mime, file.head)) {
|
|
67
|
+
throw createError({ statusCode: 415, statusMessage: `Not a readable ${ALLOWED_KIND[mime] ?? 'file'}` })
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Dimensions for images (best-effort, pure JS, from the first bytes).
|
|
71
|
+
let width: number | null = null
|
|
72
|
+
let height: number | null = null
|
|
73
|
+
if (mime.startsWith('image/')) {
|
|
74
|
+
try {
|
|
75
|
+
const dim = imageSize(new Uint8Array(file.head))
|
|
76
|
+
width = dim.width ?? null
|
|
77
|
+
height = dim.height ?? null
|
|
78
|
+
} catch {
|
|
79
|
+
// Called a picture but isn't one (a renamed text file, a broken download): it
|
|
80
|
+
// would only show as a broken image everywhere.
|
|
81
|
+
throw createError({ statusCode: 415, statusMessage: 'Not a readable image' })
|
|
82
|
+
}
|
|
83
|
+
// Too many pixels to ever resize (and to decode without eating the server's memory):
|
|
84
|
+
// better refused now, with the limit, than uploaded and broken everywhere.
|
|
85
|
+
if (width && height && width * height > MAX_IMAGE_PIXELS) {
|
|
86
|
+
const mp = Math.round(MAX_IMAGE_PIXELS / 1_000_000)
|
|
87
|
+
throw createError({
|
|
88
|
+
statusCode: 422,
|
|
89
|
+
statusMessage: `The picture has too many pixels (${width} × ${height}); at most ${mp} megapixels are allowed`,
|
|
90
|
+
data: { code: 'image_too_many_pixels', maxMegapixels: mp, width, height },
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Per-user storage quota.
|
|
96
|
+
const quota = maxBytesPerUser()
|
|
97
|
+
if (quota) {
|
|
98
|
+
const [usage] = await db
|
|
99
|
+
.select({ used: sql<string>`coalesce(sum(${reg.cmsMedia.size}), 0)` })
|
|
100
|
+
.from(reg.cmsMedia)
|
|
101
|
+
.where(eq(reg.cmsMedia.uploadedBy, user.id))
|
|
102
|
+
if (Number(usage?.used ?? 0) + file.size > quota) {
|
|
103
|
+
throw createError({ statusCode: 413, statusMessage: 'Storage quota exceeded.' })
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Date-prefixed, uuid-named key: tidy directory tree, collision-free, RFC3986-safe.
|
|
108
|
+
const now = new Date()
|
|
109
|
+
const key = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${randomUUID()}.${ext}`
|
|
110
|
+
|
|
111
|
+
const stored = await storage.putFile(key, file.path, { size: file.size, sha256: file.sha256, contentType: mime })
|
|
112
|
+
|
|
113
|
+
const [media] = await db
|
|
114
|
+
.insert(reg.cmsMedia)
|
|
115
|
+
.values({
|
|
116
|
+
url: stored.url,
|
|
117
|
+
key: stored.key,
|
|
118
|
+
mime,
|
|
119
|
+
size: stored.size,
|
|
120
|
+
width,
|
|
121
|
+
height,
|
|
122
|
+
uploadedBy: user.id,
|
|
123
|
+
name: displayFileName(file.filename),
|
|
124
|
+
folder: cleanFolder(fields.folder),
|
|
125
|
+
// Uploaded in the library (its page or picker): kept there even when no entry uses it.
|
|
126
|
+
inLibrary: fields.library === '1',
|
|
127
|
+
// No default description: a file name ("IMG_2041.jpg") read aloud by a screen
|
|
128
|
+
// reader is worse than none. Editors add it next to the image.
|
|
129
|
+
alt: null,
|
|
130
|
+
})
|
|
131
|
+
.returning()
|
|
132
|
+
|
|
133
|
+
await audit(event, 'media.upload', { recordId: media?.id, meta: { mime, size: stored.size } })
|
|
134
|
+
setResponseStatus(event, 201)
|
|
135
|
+
return media
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
await discardReceived(file) // already moved on success; a no-op then
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
/** The uploaded file's name, for people (no path, no control characters, bounded). */
|
|
143
|
+
function displayFileName(name: string | undefined): string | null {
|
|
144
|
+
const base = String(name ?? '').split(/[\\/]/).pop() ?? ''
|
|
145
|
+
const clean = base.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 200)
|
|
146
|
+
return clean || null
|
|
147
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { Readable } from 'node:stream'
|
|
2
|
+
import { pipeline } from 'node:stream/promises'
|
|
3
|
+
|
|
4
|
+
// GET /api/cms/_media/raw/** — serve an uploaded file. Public on purpose: media behave
|
|
5
|
+
// like CDN assets (the frontend renders them in <img>). But only files the CMS itself
|
|
6
|
+
// stored: a key without a cms_media row (an object some other tool put in a shared
|
|
7
|
+
// bucket, a path that merely exists) is a 404 — see cmsMediaKeys.ts.
|
|
8
|
+
//
|
|
9
|
+
// - local driver: streams the file from disk;
|
|
10
|
+
// - S3 with delivery 'proxy' (the default for a private bucket): streams the object from
|
|
11
|
+
// the bucket — never held in memory, so a video larger than the pod's RAM is fine;
|
|
12
|
+
// - S3 with delivery 'redirect': 302 to a signed address that lives five minutes (made
|
|
13
|
+
// per request, never stored);
|
|
14
|
+
// - S3 with delivery 'public': new files are stored under the bucket's own address and
|
|
15
|
+
// this route is not used for them; it still serves the app paths of rows made before
|
|
16
|
+
// a switch (a site that moved from the local driver).
|
|
17
|
+
export default defineEventHandler(async (event) => {
|
|
18
|
+
const key = getRouterParam(event, 'key')
|
|
19
|
+
if (!key) throw createError({ statusCode: 400, statusMessage: 'Missing key' })
|
|
20
|
+
|
|
21
|
+
const media = await servedMedia(key)
|
|
22
|
+
if (!media) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
23
|
+
// A PDF opened in the browser's viewer and saved from there should carry its name,
|
|
24
|
+
// not the uuid of its key.
|
|
25
|
+
const disposition = contentDispositionFor(media)
|
|
26
|
+
|
|
27
|
+
const storage = useCmsStorage()
|
|
28
|
+
|
|
29
|
+
if (storage.delivery === 'redirect' && storage.presign) {
|
|
30
|
+
let address: string
|
|
31
|
+
try {
|
|
32
|
+
address = await storage.presign(key, PRESIGN_SECONDS, disposition)
|
|
33
|
+
}
|
|
34
|
+
catch (err: any) {
|
|
35
|
+
if (err?.statusCode) throw err
|
|
36
|
+
throw createError({ statusCode: 502, statusMessage: 'Media storage is not available', cause: new Error('Could not sign an address') })
|
|
37
|
+
}
|
|
38
|
+
// The browser may keep the redirect for less time than the address lives.
|
|
39
|
+
setResponseHeader(event, 'Cache-Control', 'private, max-age=' + REDIRECT_CACHE_SECONDS)
|
|
40
|
+
return sendRedirect(event, address, 302)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const obj = await storage.read(key, {
|
|
44
|
+
range: String(getRequestHeader(event, 'range') ?? '') || undefined,
|
|
45
|
+
ifNoneMatch: String(getRequestHeader(event, 'if-none-match') ?? '') || undefined,
|
|
46
|
+
})
|
|
47
|
+
if (!obj) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
48
|
+
|
|
49
|
+
setResponseHeader(event, 'Content-Type', obj.contentType)
|
|
50
|
+
// Defense in depth against a hostile blob that slipped the upload allowlist:
|
|
51
|
+
// never sniff a different type, and neutralize any inline script execution.
|
|
52
|
+
setResponseHeader(event, 'X-Content-Type-Options', 'nosniff')
|
|
53
|
+
setResponseHeader(event, 'Content-Security-Policy', "default-src 'none'; sandbox")
|
|
54
|
+
setResponseHeader(event, 'Content-Disposition', disposition)
|
|
55
|
+
// Byte ranges: Safari will not play a video without them, and every browser seeks
|
|
56
|
+
// and resumes with them. One range only (bytes=a-b, a-, -n); others get the whole file.
|
|
57
|
+
setResponseHeader(event, 'Accept-Ranges', 'bytes')
|
|
58
|
+
if (obj.etag) setResponseHeader(event, 'ETag', obj.etag)
|
|
59
|
+
if (obj.lastModified) setResponseHeader(event, 'Last-Modified', obj.lastModified)
|
|
60
|
+
|
|
61
|
+
if (obj.status === 416) {
|
|
62
|
+
if (obj.contentRange) setResponseHeader(event, 'Content-Range', obj.contentRange)
|
|
63
|
+
throw createError({ statusCode: 416, statusMessage: 'Range not satisfiable' })
|
|
64
|
+
}
|
|
65
|
+
setResponseHeader(event, 'Cache-Control', 'public, max-age=31536000, immutable')
|
|
66
|
+
setResponseStatus(event, obj.status)
|
|
67
|
+
if (obj.status === 304 || !obj.body) return null
|
|
68
|
+
if (obj.status === 206 && obj.contentRange) setResponseHeader(event, 'Content-Range', obj.contentRange)
|
|
69
|
+
if (obj.contentLength !== undefined) setResponseHeader(event, 'Content-Length', obj.contentLength)
|
|
70
|
+
if (event.method === 'HEAD') {
|
|
71
|
+
await obj.body.cancel().catch(() => {})
|
|
72
|
+
return ''
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// A Node pipeline, not h3's stream helper: it waits for the socket to drain (a slow
|
|
76
|
+
// phone does not make the pod buffer the video) and, when the visitor leaves, cancels
|
|
77
|
+
// the read from the bucket or the disk.
|
|
78
|
+
try {
|
|
79
|
+
await pipeline(Readable.fromWeb(obj.body as any), event.node.res)
|
|
80
|
+
}
|
|
81
|
+
catch (err: any) {
|
|
82
|
+
// A visitor who closes the tab ends the pipeline early: not an error.
|
|
83
|
+
if (err?.code !== 'ERR_STREAM_PREMATURE_CLOSE') console.error('[cms] a file could not be streamed', scrubError(err))
|
|
84
|
+
}
|
|
85
|
+
})
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { and, asc, desc, eq, gt, gte, isNull, listLayout, ne, or, propOf, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_overview — what the admin home page shows: how many items each
|
|
4
|
+
// collection holds, the most recently edited items across all of them, this
|
|
5
|
+
// person's own drafts, what is scheduled to go live next and what is coming up in
|
|
6
|
+
// dated collections (events: the next ones by their date). Only what the
|
|
7
|
+
// signed-in user may read (entity- and row-level access applied).
|
|
8
|
+
const RECENT = 8
|
|
9
|
+
|
|
10
|
+
export default defineEventHandler(async (event) => {
|
|
11
|
+
const { db, reg } = useCms()
|
|
12
|
+
const user = requireCmsUser(event)
|
|
13
|
+
|
|
14
|
+
const counts: Record<string, number> = {}
|
|
15
|
+
type Item = { entity: string; id: string; title: string | null; updatedAt: Date; published: boolean | null; publishAt?: Date | null }
|
|
16
|
+
const recent: Item[] = []
|
|
17
|
+
const drafts: Item[] = []
|
|
18
|
+
const scheduled: Item[] = []
|
|
19
|
+
const upcoming: { entity: string; id: string; title: string | null; at: Date }[] = []
|
|
20
|
+
|
|
21
|
+
for (const e of reg.entities) {
|
|
22
|
+
const { allowed, where } = accessWhere(e, 'read', user)
|
|
23
|
+
if (!allowed) continue
|
|
24
|
+
|
|
25
|
+
if (e.singleton) {
|
|
26
|
+
const [row] = await db.select({ updatedAt: e.table.updatedAt }).from(e.table).where(where).limit(1)
|
|
27
|
+
counts[e.name] = row ? 1 : 0
|
|
28
|
+
continue
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const [counted] = await db.select({ count: sql<number>`count(*)::int` }).from(e.table).where(where)
|
|
32
|
+
counts[e.name] = counted?.count ?? 0
|
|
33
|
+
|
|
34
|
+
const titleCol = e.table[e.titleField]
|
|
35
|
+
const statusCol = e.publish ? e.table[propOf(e.publish.field, e.fields[e.publish.field]!)] : undefined
|
|
36
|
+
const dateCol = e.publish?.dateField ? e.table[propOf(e.publish.dateField, e.fields[e.publish.dateField]!)] : undefined
|
|
37
|
+
const rows: any[] = await db
|
|
38
|
+
.select({ id: e.table.id, title: titleCol, updatedAt: e.table.updatedAt, ...(statusCol ? { status: statusCol } : {}), ...(dateCol ? { date: dateCol } : {}) })
|
|
39
|
+
.from(e.table).where(where).orderBy(desc(e.table.updatedAt)).limit(RECENT)
|
|
40
|
+
// My drafts, and what goes live next (collections with a publish workflow).
|
|
41
|
+
const p = e.publish
|
|
42
|
+
if (p && statusCol) {
|
|
43
|
+
const base = { id: e.table.id, title: titleCol, updatedAt: e.table.updatedAt, ...(dateCol ? { date: dateCol } : {}) }
|
|
44
|
+
const me = actorId(user)
|
|
45
|
+
const mine: any[] = me
|
|
46
|
+
? await db.select(base).from(e.table)
|
|
47
|
+
.where(both(where, and(or(isNull(statusCol), ne(statusCol, p.publishedValue)), or(eq(e.table.createdBy, me), eq(e.table.updatedBy, me)))))
|
|
48
|
+
.orderBy(desc(e.table.updatedAt)).limit(RECENT)
|
|
49
|
+
: []
|
|
50
|
+
for (const r of mine) drafts.push({ entity: e.name, id: r.id, title: r.title == null ? null : String(r.title), updatedAt: r.updatedAt, published: false })
|
|
51
|
+
const sched = scheduleCond(e)
|
|
52
|
+
if (sched && dateCol) {
|
|
53
|
+
const next: any[] = await db.select(base).from(e.table)
|
|
54
|
+
.where(both(where, and(eq(statusCol, p.publishedValue), gt(dateCol, sql`now()`))))
|
|
55
|
+
.orderBy(asc(dateCol)).limit(RECENT)
|
|
56
|
+
for (const r of next) scheduled.push({ entity: e.name, id: r.id, title: r.title == null ? null : String(r.title), updatedAt: r.updatedAt, published: true, publishAt: r.date })
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
// Dated collections (no drafts, a date column): the next few by their date.
|
|
60
|
+
if (listLayout(e) === 'dated') {
|
|
61
|
+
const columns = e.admin?.list?.columns ?? Object.keys(e.fields).slice(0, 4)
|
|
62
|
+
const key = columns.find((k) => e.fields[k]?.type === 'datetime')
|
|
63
|
+
const col = key ? e.table[propOf(key, e.fields[key]!)] : undefined
|
|
64
|
+
if (col) {
|
|
65
|
+
const next: any[] = await db.select({ id: e.table.id, title: titleCol, at: col }).from(e.table)
|
|
66
|
+
.where(both(where, gte(col, sql`now()`))).orderBy(asc(col)).limit(RECENT)
|
|
67
|
+
for (const r of next) upcoming.push({ entity: e.name, id: r.id, title: r.title == null ? null : String(r.title), at: r.at })
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const r of rows) {
|
|
71
|
+
recent.push({
|
|
72
|
+
entity: e.name,
|
|
73
|
+
id: r.id,
|
|
74
|
+
title: r.title == null ? null : String(r.title),
|
|
75
|
+
updatedAt: r.updatedAt,
|
|
76
|
+
published: e.publish ? r.status === e.publish.publishedValue : null,
|
|
77
|
+
publishAt: r.date ?? null,
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
recent.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
|
|
83
|
+
drafts.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
|
|
84
|
+
scheduled.sort((a, b) => new Date(a.publishAt!).getTime() - new Date(b.publishAt!).getTime())
|
|
85
|
+
upcoming.sort((a, b) => new Date(a.at).getTime() - new Date(b.at).getTime())
|
|
86
|
+
return { counts, recent: recent.slice(0, RECENT), drafts: drafts.slice(0, RECENT), scheduled: scheduled.slice(0, RECENT), upcoming: upcoming.slice(0, RECENT) }
|
|
87
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// POST /api/cms/_preview — the editor's unsaved values for the live preview beside the
|
|
2
|
+
// form: { entity, id, locale, data }, or { entity, id, locale, clear: true } when the
|
|
3
|
+
// editor closes. Kept only for this editor's own ?preview requests (cmsPreviewDraft).
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const { reg } = useCms()
|
|
6
|
+
const user = requireCmsUser(event)
|
|
7
|
+
const body = await readBody<{ entity?: string; id?: string; locale?: string | null; data?: Record<string, any>; clear?: boolean }>(event)
|
|
8
|
+
const e = getEntity(reg, body?.entity)
|
|
9
|
+
authorize(e, 'read', user)
|
|
10
|
+
const id = String(body?.id ?? '')
|
|
11
|
+
if (!/^[0-9a-f-]{36}$/i.test(id)) throw createError({ statusCode: 400, statusMessage: 'An entry id is required' })
|
|
12
|
+
const locale = body?.locale ? String(body.locale) : null
|
|
13
|
+
if (body?.clear) dropPreviewDraft(reg, e, user.id, id, locale)
|
|
14
|
+
else if (body?.data && typeof body.data === 'object') putPreviewDraft(reg, e, user.id, id, locale, body.data)
|
|
15
|
+
setResponseStatus(event, 204)
|
|
16
|
+
return null
|
|
17
|
+
})
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// POST /api/cms/_privacy/delete { email } — erase one person (GDPR right to erasure):
|
|
2
|
+
// their form submissions are deleted, their account (if any) is disabled and anonymised,
|
|
3
|
+
// and the audit entries about them lose their personal fields. Not your own account,
|
|
4
|
+
// never the last active administrator. Audited with counts only; administrators only,
|
|
5
|
+
// rate limited.
|
|
6
|
+
export default defineEventHandler(async (event) => {
|
|
7
|
+
const me = requireCmsAdmin(event)
|
|
8
|
+
await privacyRateLimit(event, me.id, 'delete')
|
|
9
|
+
const { email } = parseOr422(privacyBody, await readBody(event))
|
|
10
|
+
const { db, reg } = useCms()
|
|
11
|
+
const result = await erasePerson(db, reg, email, me.id)
|
|
12
|
+
await audit(event, 'privacy.delete', { meta: result })
|
|
13
|
+
return { ok: true, ...result }
|
|
14
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// POST /api/cms/_privacy/export { email } — everything stored about one email address,
|
|
2
|
+
// as a JSON file to hand to the person (GDPR right of access). Audited; administrators
|
|
3
|
+
// only, rate limited. Never includes password hashes or sign-in secrets.
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const me = requireCmsAdmin(event)
|
|
6
|
+
await privacyRateLimit(event, me.id, 'read')
|
|
7
|
+
const { email } = parseOr422(privacyBody, await readBody(event))
|
|
8
|
+
const { db, reg } = useCms()
|
|
9
|
+
|
|
10
|
+
const found = await findSubmissions(db, reg, email)
|
|
11
|
+
const account = await findAccount(db, reg, email)
|
|
12
|
+
const entries = await findAuditEntries(db, reg, email, account?.id ?? null)
|
|
13
|
+
const document = {
|
|
14
|
+
exportedAt: new Date().toISOString(),
|
|
15
|
+
email,
|
|
16
|
+
formSubmissions: found.map(({ form, row }) => submissionView(form, row)),
|
|
17
|
+
account: account ? accountView(account) : null,
|
|
18
|
+
auditEntries: entries.map((a) => ({ id: a.id, createdAt: a.createdAt, action: a.action, entity: a.entity, recordId: a.recordId, userId: a.userId, meta: a.meta })),
|
|
19
|
+
}
|
|
20
|
+
// The audit entry records that an export happened and its size, never the address.
|
|
21
|
+
await audit(event, 'privacy.export', { meta: { submissions: found.length, account: !!account, auditEntries: entries.length } })
|
|
22
|
+
setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
|
|
23
|
+
setResponseHeader(event, 'content-disposition', 'attachment; filename="personal-data.json"')
|
|
24
|
+
return JSON.stringify(document, null, 2)
|
|
25
|
+
})
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// POST /api/cms/_privacy/lookup { email } — what is stored about one email address:
|
|
4
|
+
// form submissions whose email fields match, the CMS account with that address and the
|
|
5
|
+
// audit entries about it. Administrators only, rate limited; the address travels in the
|
|
6
|
+
// body (not the URL), so it does not end up in access logs.
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const me = requireCmsAdmin(event)
|
|
9
|
+
await privacyRateLimit(event, me.id, 'read')
|
|
10
|
+
const { email } = parseOr422(privacyBody, await readBody(event))
|
|
11
|
+
const { db, reg } = useCms()
|
|
12
|
+
|
|
13
|
+
const found = await findSubmissions(db, reg, email)
|
|
14
|
+
const account = await findAccount(db, reg, email)
|
|
15
|
+
const entries = await findAuditEntries(db, reg, email, account?.id ?? null, 50)
|
|
16
|
+
return {
|
|
17
|
+
email,
|
|
18
|
+
submissions: found.map(({ form, row }) => ({ ...submissionView(form, row), formLabel: form.label })),
|
|
19
|
+
account: account ? accountView(account) : null,
|
|
20
|
+
audit: { total: entries.length >= 50 ? await countAudit(db, reg, email, account?.id ?? null) : entries.length, latest: entries.slice(0, 20).map((a) => ({ id: a.id, action: a.action, entity: a.entity, createdAt: a.createdAt })) },
|
|
21
|
+
}
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
async function countAudit(db: any, reg: any, email: string, accountId: string | null): Promise<number> {
|
|
25
|
+
const [row] = await db.select({ n: sql<number>`count(*)::int` }).from(reg.cmsAudit).where(auditCondition(reg, email, accountId))
|
|
26
|
+
return row?.n ?? 0
|
|
27
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { SEARCH_MAX_QUERY, searchTerms } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_search?q=… — the admin's search (⌘K): entries of every collection the
|
|
4
|
+
// signed-in person may read, drafts included, matched in any language. A few best
|
|
5
|
+
// matches per collection, best first:
|
|
6
|
+
// { query, items: [{ entity, id, title, titleHighlights, excerpt, highlights, status, updatedAt }] }
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const { db, reg } = useCms()
|
|
9
|
+
const user = requireCmsUser(event)
|
|
10
|
+
const query = getQuery(event)
|
|
11
|
+
const q = String(query.q ?? '').trim().slice(0, SEARCH_MAX_QUERY)
|
|
12
|
+
const perEntity = Math.min(20, Math.max(1, Number(query.limit) || 5))
|
|
13
|
+
const terms = searchTerms(q)
|
|
14
|
+
if (!terms.length) return { query: q, items: [] }
|
|
15
|
+
const found = await searchAdmin(db, reg, user, terms, q, perEntity)
|
|
16
|
+
return { query: q, items: found.map(({ score: _score, ...item }) => item) }
|
|
17
|
+
})
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// GET /api/cms/_singleton/:name — the single row of a global (or null if not yet
|
|
2
|
+
// saved), shaped for the admin form. `_singleton` is underscore-prefixed so it wins
|
|
3
|
+
// static routing over /api/cms/[entity].
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const { db, reg } = useCms()
|
|
6
|
+
const user = requireCmsUser(event)
|
|
7
|
+
const e = getEntity(reg, getRouterParam(event, 'name'))
|
|
8
|
+
if (!e.singleton) throw createError({ statusCode: 404, statusMessage: `Not a global: ${e.name}` })
|
|
9
|
+
const where = authorize(e, 'read', user)
|
|
10
|
+
|
|
11
|
+
const [row] = await db.select().from(e.table).where(where).orderBy(e.table.createdAt).limit(1)
|
|
12
|
+
if (row) {
|
|
13
|
+
await hydrateRowForForm(db, reg, e, row)
|
|
14
|
+
const locale = requestedLocale(event, reg)
|
|
15
|
+
if (isTranslationLocale(reg, locale) && e.localized.length) await translationFormRow(db, reg, e, row, locale)
|
|
16
|
+
if (reg.locales && e.localized.length) row.__locales = (await availableLocales(db, reg, e, [row.id])).get(row.id)
|
|
17
|
+
}
|
|
18
|
+
return { row: row ?? null, can: await updateVerdict(db, e, user, null) }
|
|
19
|
+
})
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { eq, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// PUT /api/cms/_singleton/:name — upsert the single row of a global. Validates the
|
|
4
|
+
// full payload, inserts on first save or updates the existing row, and GCs any media
|
|
5
|
+
// blob replaced/cleared by this write.
|
|
6
|
+
export default defineEventHandler(async (event) => {
|
|
7
|
+
const { db, reg } = useCms()
|
|
8
|
+
const user = requireCmsUser(event)
|
|
9
|
+
const e = getEntity(reg, getRouterParam(event, 'name'))
|
|
10
|
+
if (!e.singleton) throw createError({ statusCode: 404, statusMessage: `Not a global: ${e.name}` })
|
|
11
|
+
const rowFilter = authorize(e, 'update', user)
|
|
12
|
+
|
|
13
|
+
// ?locale=<translation>: translate the (existing) settings row.
|
|
14
|
+
const locale = requestedLocale(event, reg)
|
|
15
|
+
if (isTranslationLocale(reg, locale)) {
|
|
16
|
+
const [existing] = await db.select({ id: e.table.id }).from(e.table).orderBy(e.table.createdAt).limit(1)
|
|
17
|
+
if (!existing) throw createError({ statusCode: 409, statusMessage: 'Save the default language first' })
|
|
18
|
+
return { row: await writeTranslation(event, e, existing.id, locale, user, rowFilter) }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The row as it is now: blocks that are behind or of a type that is gone are only kept when stored already.
|
|
22
|
+
const [prior] = await db.select().from(e.table).orderBy(e.table.createdAt).limit(1)
|
|
23
|
+
const data = parseOr422(writeSchema(e, 'create', prior), await readBody(event))
|
|
24
|
+
await assertMediaAccepted(db, reg, e, data)
|
|
25
|
+
const { values, m2m } = splitPayload(e, data)
|
|
26
|
+
const base = baseVersion(event)
|
|
27
|
+
const seenBefore = prior ? await changeSnapshot(e, prior.id) : null
|
|
28
|
+
|
|
29
|
+
const mediaCols = Object.entries(e.fields)
|
|
30
|
+
.filter(([, f]) => (f as any).type === 'media')
|
|
31
|
+
.map(([k]) => `${k}Id`)
|
|
32
|
+
const oldMedia: Record<string, string | null> = {}
|
|
33
|
+
// Media referenced inside rich text / blocks before this write (cleanup below).
|
|
34
|
+
const jsonCols = Object.entries(e.fields).filter(([, f]) => JSON_MEDIA_TYPES.has((f as any).type)).map(([k]) => k)
|
|
35
|
+
let oldEmbedded: string[] = []
|
|
36
|
+
|
|
37
|
+
const row = await db.transaction(async (tx: any) => {
|
|
38
|
+
// One save of this global at a time (also the very first one, when there is no
|
|
39
|
+
// row to lock yet): a concurrent save waits, then sees this one's version.
|
|
40
|
+
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${'cms-global:' + e.name}))`)
|
|
41
|
+
const [existing] = await tx.select().from(e.table).orderBy(e.table.createdAt).limit(1).for('update')
|
|
42
|
+
await assertCurrentVersion(e, existing, base)
|
|
43
|
+
for (const c of mediaCols) oldMedia[c] = existing?.[c] ?? null
|
|
44
|
+
if (existing) oldEmbedded = jsonCols.flatMap((k) => jsonMediaIds(e.fields[k], existing[k]))
|
|
45
|
+
|
|
46
|
+
let current: any
|
|
47
|
+
values.updatedBy = actorId(user)
|
|
48
|
+
if (existing) {
|
|
49
|
+
values.updatedAt = nextVersion(e.table.updatedAt)
|
|
50
|
+
;[current] = await tx.update(e.table).set(values).where(both(eq(e.table.id, existing.id), rowFilter)).returning()
|
|
51
|
+
if (!current) throw createError({ statusCode: 403, statusMessage: 'Not permitted' })
|
|
52
|
+
} else {
|
|
53
|
+
values.createdBy = actorId(user)
|
|
54
|
+
;[current] = await tx.insert(e.table).values(values).returning()
|
|
55
|
+
}
|
|
56
|
+
await writeM2M(tx, reg, e, current.id, m2m, true)
|
|
57
|
+
return current
|
|
58
|
+
}).catch((err: unknown) => rethrowDbError(err, e, 'write'))
|
|
59
|
+
|
|
60
|
+
// GC each replaced/cleared media blob after commit — fields, and anything dropped
|
|
61
|
+
// from rich text or blocks.
|
|
62
|
+
const storage = useCmsStorage()
|
|
63
|
+
for (const c of mediaCols) {
|
|
64
|
+
if (oldMedia[c] && oldMedia[c] !== row[c]) await gcMediaIfOrphan(db, reg, storage, oldMedia[c], gcScope(user))
|
|
65
|
+
}
|
|
66
|
+
if (oldEmbedded.length) {
|
|
67
|
+
const still = new Set(jsonCols.flatMap((k) => jsonMediaIds(e.fields[k], row[k])))
|
|
68
|
+
for (const mid of new Set(oldEmbedded)) if (!still.has(mid)) await gcMediaIfOrphan(db, reg, storage, mid, gcScope(user))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
await audit(event, 'settings.update', { entity: e.name, recordId: row.id })
|
|
72
|
+
await noteCollabSave(event, { entity: e, id: row.id, locale: null }, row.updatedAt)
|
|
73
|
+
await reportChange(event, { type: 'global.updated', entity: e, id: row.id, before: seenBefore, after: row })
|
|
74
|
+
await hydrateRowForForm(db, reg, e, row)
|
|
75
|
+
return { row }
|
|
76
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// POST /api/cms/_users/:id/resend — send a fresh invitation link (the old one stops
|
|
4
|
+
// working). Returns the link for copying. Administrators only.
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
assertBuiltinAuth()
|
|
7
|
+
const me = requireCmsAdmin(event)
|
|
8
|
+
const id = getIdParam(event)
|
|
9
|
+
const { db, reg } = useCms()
|
|
10
|
+
const [user] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, id))
|
|
11
|
+
if (!user) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
12
|
+
if (user.status !== 'invited') throw createError({ statusCode: 409, statusMessage: 'This person has already accepted' })
|
|
13
|
+
|
|
14
|
+
const secret = await issueToken(db, reg, { userId: user.id, kind: 'invite', ttlMs: INVITE_TTL_MS, createdBy: me.id })
|
|
15
|
+
const inviteUrl = adminLink(event, `/admin/invite/${secret}`)
|
|
16
|
+
let emailed = false
|
|
17
|
+
try {
|
|
18
|
+
emailed = await sendCmsMail(inviteEmail({ to: user.email, inviter: me.name || me.email || 'An administrator', url: inviteUrl, role: user.role, locale: me.locale || requestLocale(event) }))
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
console.error('[cms] could not send the invitation email', redactEmails(safeErrorMessage(err)))
|
|
22
|
+
}
|
|
23
|
+
await audit(event, 'user.resend', { recordId: id, meta: { emailed } })
|
|
24
|
+
return { inviteUrl, emailed }
|
|
25
|
+
})
|