tinyzoo 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +99 -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 +392 -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/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 +197 -0
- package/server/utils/cmsWebhooks.ts +101 -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 { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/login — email + password. One generic answer for every
|
|
5
|
+
// failure (unknown email, wrong password, not yet accepted, disabled), equal work
|
|
6
|
+
// either way, and rate limits per address and per IP (counting failed attempts only).
|
|
7
|
+
const body = z.object({ email: z.string().trim().toLowerCase().max(320), password: z.string().max(200) })
|
|
8
|
+
const WINDOW = 15 * 60_000
|
|
9
|
+
|
|
10
|
+
export default defineEventHandler(async (event) => {
|
|
11
|
+
assertBuiltinAuth()
|
|
12
|
+
const { email, password } = parseOr422(body, await readBody(event))
|
|
13
|
+
const ip = clientIp(event)
|
|
14
|
+
if (!(await rateLimit(`login:ip:${ip}`, 30, WINDOW)) || !(await rateLimit(`login:email:${email}`, 10, WINDOW))) {
|
|
15
|
+
throw tooManyRequests(event, 'Too many sign-in attempts; wait a few minutes and try again', WINDOW)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
await ensureDemoAccount(email, password) // the public demo account (cms.demo), if these are its details
|
|
19
|
+
const { db, reg } = useCms()
|
|
20
|
+
const [user] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.email, email))
|
|
21
|
+
const ok = user?.passwordHash
|
|
22
|
+
? await verifyPassword(user.passwordHash, password)
|
|
23
|
+
: (await verifyPassword(await dummyPasswordHash(), password), false)
|
|
24
|
+
|
|
25
|
+
if (!user || !ok || user.status !== 'active') {
|
|
26
|
+
await audit(event, 'auth.login_failed', { userId: user?.id ?? null, meta: { email, ip } })
|
|
27
|
+
throw createError({ statusCode: 401, statusMessage: 'Wrong email or password' })
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const updates: Record<string, unknown> = { lastLoginAt: new Date() }
|
|
31
|
+
if (passwordNeedsReHash(user.passwordHash!)) updates.passwordHash = await hashPassword(password)
|
|
32
|
+
const [updated] = await db.update(reg.cmsUsers).set(updates).where(eq(reg.cmsUsers.id, user.id)).returning()
|
|
33
|
+
const current = updated ?? user
|
|
34
|
+
|
|
35
|
+
await startCmsSession(event, current)
|
|
36
|
+
// A sign-in that worked is not a guess: only failures count towards the limits (a whole
|
|
37
|
+
// office behind one address, or someone who signs in and out all day, must not lock itself out).
|
|
38
|
+
await rateLimitRefund(`login:ip:${ip}`, WINDOW)
|
|
39
|
+
await rateLimitRefund(`login:email:${email}`, WINDOW)
|
|
40
|
+
await audit(event, 'auth.login', { userId: user.id })
|
|
41
|
+
return { user: sessionUser(current) }
|
|
42
|
+
})
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// POST /api/cms/_auth/logout — end this browser's session.
|
|
2
|
+
export default defineEventHandler(async (event) => {
|
|
3
|
+
const user = getCmsSession(event)
|
|
4
|
+
await clearUserSession(event)
|
|
5
|
+
if (user) await audit(event, 'auth.logout', { userId: user.id })
|
|
6
|
+
return { ok: true }
|
|
7
|
+
})
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { and, eq } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// PATCH /api/cms/_auth/me — change your own name and interface language.
|
|
5
|
+
//
|
|
6
|
+
// The update only applies if the session version is still the one this request was
|
|
7
|
+
// authorised with. Otherwise a stolen session could keep itself alive across the
|
|
8
|
+
// owner's password change by re-signing its cookie with the new version.
|
|
9
|
+
const body = z.object({
|
|
10
|
+
name: z.string().trim().min(1).max(120).optional(),
|
|
11
|
+
locale: z.string().max(10).nullable().optional(),
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
export default defineEventHandler(async (event) => {
|
|
15
|
+
assertBuiltinAuth()
|
|
16
|
+
const me = requireCmsUser(event)
|
|
17
|
+
if (!(await rateLimit(`me:${me.id}`, 60, 60_000))) throw tooManyRequests(event, 'Too many requests', 60_000)
|
|
18
|
+
const data = parseOr422(body, await readBody(event))
|
|
19
|
+
// The shared demo account keeps its name (everyone signs in as it); the language may change.
|
|
20
|
+
if (data.name !== undefined && isDemoAccount(me.email)) throw createError({ statusCode: 403, statusMessage: 'The demo account keeps its name', data: { code: 'demo_account' } })
|
|
21
|
+
const { db, reg } = useCms()
|
|
22
|
+
const [u] = await db.update(reg.cmsUsers).set({ ...data, updatedAt: new Date() })
|
|
23
|
+
.where(and(eq(reg.cmsUsers.id, me.id), eq(reg.cmsUsers.sessionVersion, event.context.cmsSessionVersion)))
|
|
24
|
+
.returning()
|
|
25
|
+
if (!u) {
|
|
26
|
+
await clearUserSession(event)
|
|
27
|
+
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
|
28
|
+
}
|
|
29
|
+
await startCmsSession(event, u)
|
|
30
|
+
await audit(event, 'account.update', { meta: { fields: Object.keys(data) } })
|
|
31
|
+
return { user: sessionUser(u) }
|
|
32
|
+
})
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { and, eq, sql } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/password — change your own password (the current one is
|
|
5
|
+
// required). Other browsers are signed out; this one stays signed in.
|
|
6
|
+
const body = z.object({ current: z.string().max(200), password: passwordSchema })
|
|
7
|
+
|
|
8
|
+
export default defineEventHandler(async (event) => {
|
|
9
|
+
assertBuiltinAuth()
|
|
10
|
+
const me = requireCmsUser(event)
|
|
11
|
+
if (isDemoAccount(me.email)) throw createError({ statusCode: 403, statusMessage: 'The demo account keeps its password', data: { code: 'demo_account' } })
|
|
12
|
+
if (!(await rateLimit(`password:${me.id}`, 10, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
13
|
+
const data = parseOr422(body, await readBody(event))
|
|
14
|
+
const { db, reg } = useCms()
|
|
15
|
+
const [u] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.id, me.id))
|
|
16
|
+
if (!u?.passwordHash || !(await verifyPassword(u.passwordHash, data.current))) {
|
|
17
|
+
throw createError({ statusCode: 422, statusMessage: 'Validation failed', data: [{ path: ['current'], message: 'Wrong password' }] })
|
|
18
|
+
}
|
|
19
|
+
const [updated] = await db.update(reg.cmsUsers)
|
|
20
|
+
.set({ passwordHash: await hashPassword(data.password), sessionVersion: sql`${reg.cmsUsers.sessionVersion} + 1`, updatedAt: new Date() })
|
|
21
|
+
.where(and(eq(reg.cmsUsers.id, me.id), eq(reg.cmsUsers.sessionVersion, event.context.cmsSessionVersion))).returning()
|
|
22
|
+
if (!updated) {
|
|
23
|
+
await clearUserSession(event)
|
|
24
|
+
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
|
|
25
|
+
}
|
|
26
|
+
await startCmsSession(event, updated)
|
|
27
|
+
await audit(event, 'account.password')
|
|
28
|
+
return { ok: true }
|
|
29
|
+
})
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { and, eq, isNull, sql } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/reset — set a new password with a reset link. Every other
|
|
5
|
+
// session of the account is signed out (session version bump); this browser is
|
|
6
|
+
// signed in with the new one.
|
|
7
|
+
const body = z.object({ token: z.string().min(1).max(200), password: passwordSchema })
|
|
8
|
+
|
|
9
|
+
export default defineEventHandler(async (event) => {
|
|
10
|
+
assertBuiltinAuth()
|
|
11
|
+
if (!(await rateLimit(`reset:ip:${clientIp(event)}`, 20, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
12
|
+
const data = parseOr422(body, await readBody(event))
|
|
13
|
+
const { db, reg } = useCms()
|
|
14
|
+
const found = await findToken(db, reg, data.token, 'reset')
|
|
15
|
+
if (!found || found.user.status !== 'active') {
|
|
16
|
+
throw createError({ statusCode: 410, statusMessage: 'This link has expired or was already used; ask for a new one' })
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const passwordHash = await hashPassword(data.password)
|
|
20
|
+
const user = await db.transaction(async (tx: any) => {
|
|
21
|
+
// Claim the link atomically: of two simultaneous requests only one gets the row.
|
|
22
|
+
const [claimed] = await tx.update(reg.cmsTokens).set({ usedAt: new Date() })
|
|
23
|
+
.where(and(eq(reg.cmsTokens.id, found.token.id), isNull(reg.cmsTokens.usedAt))).returning({ id: reg.cmsTokens.id })
|
|
24
|
+
if (!claimed) throw createError({ statusCode: 410, statusMessage: 'This link has expired or was already used' })
|
|
25
|
+
const [u] = await tx.update(reg.cmsUsers)
|
|
26
|
+
.set({ passwordHash, sessionVersion: sql`${reg.cmsUsers.sessionVersion} + 1`, updatedAt: new Date(), lastLoginAt: new Date() })
|
|
27
|
+
.where(eq(reg.cmsUsers.id, found.user.id)).returning()
|
|
28
|
+
return u
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
await startCmsSession(event, user)
|
|
32
|
+
await audit(event, 'auth.reset', { userId: user.id })
|
|
33
|
+
return { user: sessionUser(user) }
|
|
34
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { eq, sql } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_auth/setup — create the first administrator on a fresh install and
|
|
5
|
+
// sign them in. Refused (409) as soon as any account exists. The check and the
|
|
6
|
+
// insert run under a transaction-scoped advisory lock, so two simultaneous setups
|
|
7
|
+
// cannot both win.
|
|
8
|
+
//
|
|
9
|
+
// Setup also needs a code, so a fresh deploy cannot be claimed by whoever opens the
|
|
10
|
+
// page first: NUXT_CMS_AUTH_SETUP_TOKEN when it is set, otherwise (in production) a
|
|
11
|
+
// one-time code the server prints in its log (cmsSetupCode.ts). Development needs none.
|
|
12
|
+
const body = z.object({ name: z.string().trim().min(1).max(120), email: emailSchema, password: passwordSchema, token: z.string().max(200).optional() })
|
|
13
|
+
const SETUP_LOCK = 72_011_001
|
|
14
|
+
|
|
15
|
+
export default defineEventHandler(async (event) => {
|
|
16
|
+
assertBuiltinAuth()
|
|
17
|
+
if (!(await rateLimit(`setup:${clientIp(event)}`, 10, 15 * 60_000))) throw tooManyRequests(event, 'Too many attempts; try again later', 15 * 60_000)
|
|
18
|
+
const data = parseOr422(body, await readBody(event))
|
|
19
|
+
const required = setupToken()
|
|
20
|
+
const codeOk = required
|
|
21
|
+
? constantTimeEqual(data.token ?? '', required)
|
|
22
|
+
: setupCodeApplies() ? await setupCodeAccepts(data.token) : true
|
|
23
|
+
if (!codeOk) {
|
|
24
|
+
await audit(event, 'auth.setup_failed', { userId: null })
|
|
25
|
+
throw createError({ statusCode: 403, statusMessage: 'The setup code is missing or wrong', data: { code: 'setup_token' } })
|
|
26
|
+
}
|
|
27
|
+
const { db, reg } = useCms()
|
|
28
|
+
const passwordHash = await hashPassword(data.password)
|
|
29
|
+
|
|
30
|
+
const user = await db.transaction(async (tx: any) => {
|
|
31
|
+
await tx.execute(sql`select pg_advisory_xact_lock(${SETUP_LOCK})`)
|
|
32
|
+
const [row] = await tx.select({ n: sql<number>`count(*)::int` }).from(reg.cmsUsers)
|
|
33
|
+
if ((row?.n ?? 0) > 0) throw createError({ statusCode: 409, statusMessage: 'Already set up; sign in instead' })
|
|
34
|
+
const [created] = await tx.insert(reg.cmsUsers).values({
|
|
35
|
+
email: data.email, name: data.name, role: 'admin', status: 'active', passwordHash, lastLoginAt: new Date(),
|
|
36
|
+
}).returning()
|
|
37
|
+
// The code has done its job; it must not outlive the first account.
|
|
38
|
+
await tx.delete(reg.cmsState).where(eq(reg.cmsState.key, SETUP_CODE_KEY))
|
|
39
|
+
return created
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
await startCmsSession(event, user)
|
|
43
|
+
await audit(event, 'auth.setup', { userId: user.id })
|
|
44
|
+
setResponseStatus(event, 201)
|
|
45
|
+
return { user: sessionUser(user) }
|
|
46
|
+
})
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_auth/status — what the sign-in page needs to know: whether the CMS
|
|
4
|
+
// still needs its first administrator. Public.
|
|
5
|
+
export default defineEventHandler(async () => {
|
|
6
|
+
if (cmsAuthMode() !== 'builtin') return { mode: 'external', needsSetup: false }
|
|
7
|
+
const { db, reg } = useCms()
|
|
8
|
+
const [row] = await db.select({ n: sql<number>`count(*)::int` }).from(reg.cmsUsers)
|
|
9
|
+
const needsSetup = (row?.n ?? 0) === 0
|
|
10
|
+
// Whether first-run setup asks for a setup code, and where to find it (never the code
|
|
11
|
+
// itself): 'config' = the deploy's NUXT_CMS_AUTH_SETUP_TOKEN, 'log' = printed by the server.
|
|
12
|
+
const configured = !!setupToken()
|
|
13
|
+
const generated = needsSetup && setupCodeApplies()
|
|
14
|
+
// The start-up step may have missed (database not ready); make sure there is a code.
|
|
15
|
+
if (generated) await ensureSetupCode().catch((err) => console.error('[cms] could not prepare the setup code', safeErrorMessage(err)))
|
|
16
|
+
const codeIn = configured ? 'config' : generated ? 'log' : null
|
|
17
|
+
return { mode: 'builtin', needsSetup, needsToken: needsSetup && (configured || generated), ...(needsSetup && codeIn ? { codeIn } : {}) }
|
|
18
|
+
})
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_collab/session?entity=&id=&locale= — the shared document for one entry
|
|
4
|
+
// (or one translation): its name, the epoch to present when connecting, the fields
|
|
5
|
+
// edited together, whether this person may write or only watch, and text left behind
|
|
6
|
+
// unsaved by a tab that closed (`unsaved`). See cmsCollab.ts.
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const user = requireCmsUser(event)
|
|
9
|
+
if (cmsAuthMode() !== 'builtin') throw createError({ statusCode: 404, statusMessage: 'Shared editing needs the built-in sign-in' })
|
|
10
|
+
const { reg } = useCms()
|
|
11
|
+
const q = getQuery(event)
|
|
12
|
+
const locale = requestedLocale(event, reg)
|
|
13
|
+
const translation = isTranslationLocale(reg, locale) ? locale : null
|
|
14
|
+
const target = parseCollabName(collabName(String(q.entity ?? ''), String(q.id ?? ''), translation))
|
|
15
|
+
if (!target) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
16
|
+
if (!(await rateLimit(`collab:${user.id}`, 120, 60_000))) throw tooManyRequests(event, 'Too many requests; try again shortly', 60_000)
|
|
17
|
+
const access = await collabAccess(user, target)
|
|
18
|
+
if (!access) throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
19
|
+
const { epoch } = await ensureCollabDocument(target)
|
|
20
|
+
// Stored text the editor cannot hold is edited alone, so it is never replaced.
|
|
21
|
+
const saved = await savedContent(target)
|
|
22
|
+
// Text a closed tab left behind unsaved: offered to people who may write, never in the document.
|
|
23
|
+
const unsaved = access === 'write' ? await unsavedText(target, saved?.version ?? null) : null
|
|
24
|
+
const fields = collabFields(target.entity, target.locale).filter((k) => fitsEditor(saved?.values[k]))
|
|
25
|
+
// The name on this person's cursor, exactly as the server will check it.
|
|
26
|
+
const { db } = useCms()
|
|
27
|
+
const [me] = await db.select({ name: reg.cmsUsers.name, email: reg.cmsUsers.email }).from(reg.cmsUsers).where(eq(reg.cmsUsers.id, user.id))
|
|
28
|
+
setResponseHeader(event, 'Cache-Control', 'no-store')
|
|
29
|
+
return { name: target.name, epoch, fields, access, you: displayName(me?.name, me?.email ?? user.email), unsaved }
|
|
30
|
+
})
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// GET /api/cms/_collab/socket — the shared-editing socket (Hocuspocus), on the app's
|
|
2
|
+
// own port. Admitted like the realtime socket (same origin, valid session); which
|
|
3
|
+
// documents it may open is decided per document (cmsCollabServer.onAuthenticate).
|
|
4
|
+
//
|
|
5
|
+
// Hocuspocus needs the real `ws` socket and Node request behind the crossws peer
|
|
6
|
+
// (it listens for pongs, pings, replays its own queue). They sit at
|
|
7
|
+
// `peer._internal`, which is crossws-private: checked here, and a miss closes the
|
|
8
|
+
// connection with a logged error instead of failing quietly.
|
|
9
|
+
const MAX_SOCKETS_PER_USER = 10
|
|
10
|
+
// Shared-editing messages are small; the `ws` default (100 MiB) is not.
|
|
11
|
+
const MAX_PAYLOAD_BYTES = 2 * 1024 * 1024
|
|
12
|
+
const socketsByUser = new Map<string, Set<any>>()
|
|
13
|
+
|
|
14
|
+
export default defineWebSocketHandler({
|
|
15
|
+
upgrade(request: any) {
|
|
16
|
+
return admitAdminSocket(request)
|
|
17
|
+
},
|
|
18
|
+
async open(peer: any) {
|
|
19
|
+
const user = peer.context?.cmsUser
|
|
20
|
+
if (!user) return peer.close(4401, 'Unauthorized')
|
|
21
|
+
const ws = peer._internal?.ws
|
|
22
|
+
const req = peer._internal?.nodeReq
|
|
23
|
+
if (!ws || typeof ws.on !== 'function' || !req?.headers) {
|
|
24
|
+
console.error('[cms] collab: no raw socket behind the crossws peer — has crossws changed? Refusing.')
|
|
25
|
+
return peer.close(1011, 'Shared editing unavailable')
|
|
26
|
+
}
|
|
27
|
+
if (ws._receiver && typeof ws._receiver._maxPayload === 'number') ws._receiver._maxPayload = MAX_PAYLOAD_BYTES
|
|
28
|
+
// Too many tabs: the oldest gives way (as on the realtime socket).
|
|
29
|
+
const mine = socketsByUser.get(user.id) ?? new Set()
|
|
30
|
+
if (mine.size >= MAX_SOCKETS_PER_USER) {
|
|
31
|
+
const oldest = mine.values().next().value
|
|
32
|
+
mine.delete(oldest)
|
|
33
|
+
oldest?.close?.(4429, 'Too many open tabs')
|
|
34
|
+
}
|
|
35
|
+
mine.add(ws)
|
|
36
|
+
socketsByUser.set(user.id, mine)
|
|
37
|
+
ws.on('close', () => {
|
|
38
|
+
mine.delete(ws)
|
|
39
|
+
if (!mine.size) socketsByUser.delete(user.id)
|
|
40
|
+
})
|
|
41
|
+
// One socket carries every document the page has open.
|
|
42
|
+
ws.setMaxListeners?.(Number.POSITIVE_INFINITY)
|
|
43
|
+
ws.on('error', (err: unknown) => console.error('[cms] collab socket error', (err as Error)?.message ?? err))
|
|
44
|
+
const server = await useCollabServer()
|
|
45
|
+
server.handleConnection(ws, req, { user, sv: peer.context.cmsSessionVersion })
|
|
46
|
+
},
|
|
47
|
+
// Hocuspocus owns the socket from `open` on; these stay deliberately inert.
|
|
48
|
+
message() {},
|
|
49
|
+
close() {},
|
|
50
|
+
error() {},
|
|
51
|
+
})
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// DELETE /api/cms/_collab/unsaved?entity=&id=&locale= — the text a closed tab left
|
|
2
|
+
// behind unsaved is dealt with (kept in the form, or discarded): forget it. Only for
|
|
3
|
+
// people who may edit the entry. See cmsCollab.ts.
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
const user = requireCmsUser(event)
|
|
6
|
+
if (cmsAuthMode() !== 'builtin') throw createError({ statusCode: 404, statusMessage: 'Shared editing needs the built-in sign-in' })
|
|
7
|
+
const { reg } = useCms()
|
|
8
|
+
const q = getQuery(event)
|
|
9
|
+
const locale = requestedLocale(event, reg)
|
|
10
|
+
const translation = isTranslationLocale(reg, locale) ? locale : null
|
|
11
|
+
const target = parseCollabName(collabName(String(q.entity ?? ''), String(q.id ?? ''), translation))
|
|
12
|
+
if (!target) throw createError({ statusCode: 404, statusMessage: 'Not found' })
|
|
13
|
+
if ((await collabAccess(user, target)) !== 'write') throw createError({ statusCode: 404, statusMessage: 'Not found or not permitted' })
|
|
14
|
+
await dropUnsavedText(target)
|
|
15
|
+
return { ok: true }
|
|
16
|
+
})
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Serializable schema graph that drives /admin. Auth-gated and annotated with
|
|
2
|
+
// per-entity permissions so the dashboard can hide what the user can't touch.
|
|
3
|
+
export default defineEventHandler((event) => {
|
|
4
|
+
const { reg } = useCms()
|
|
5
|
+
const user = requireCmsUser(event)
|
|
6
|
+
return reg.graph
|
|
7
|
+
.filter((g) => accessWhere(reg.byName.get(g.name)!, 'read', user).allowed)
|
|
8
|
+
.map((g) => {
|
|
9
|
+
const e = reg.byName.get(g.name)!
|
|
10
|
+
return {
|
|
11
|
+
...g,
|
|
12
|
+
can: {
|
|
13
|
+
create: accessWhere(e, 'create', user).allowed,
|
|
14
|
+
update: accessWhere(e, 'update', user).allowed,
|
|
15
|
+
delete: accessWhere(e, 'delete', user).allowed,
|
|
16
|
+
publish: canPublish(user),
|
|
17
|
+
},
|
|
18
|
+
}
|
|
19
|
+
})
|
|
20
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { parseLinkRef } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// POST /api/cms/_links/resolve { refs: ['cms:page/…'], locale } — what the admin shows
|
|
4
|
+
// beside a stored link: the target's title, its address in the language being edited
|
|
5
|
+
// and whether it is live, a draft, gone or not readable by this person. Feeds the link
|
|
6
|
+
// fields, the rich-text link popover and the lists. Only what the signed-in user may read.
|
|
7
|
+
const MAX_REFS = 100
|
|
8
|
+
|
|
9
|
+
export default defineEventHandler(async (event) => {
|
|
10
|
+
const { db, reg } = useCms()
|
|
11
|
+
const user = requireCmsUser(event)
|
|
12
|
+
const body = await readBody<{ refs?: unknown; locale?: unknown }>(event)
|
|
13
|
+
const refs = [...new Set((Array.isArray(body?.refs) ? body.refs : []).filter((r): r is string => typeof r === 'string' && !!parseLinkRef(r)))].slice(0, MAX_REFS)
|
|
14
|
+
const wanted = typeof body?.locale === 'string' ? body.locale : null
|
|
15
|
+
const locale = reg.locales ? (wanted && reg.locales.locales.includes(wanted) ? wanted : reg.locales.default) : null
|
|
16
|
+
return { locale, items: await describeLinkRefs(db, reg, user, refs, locale) }
|
|
17
|
+
})
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { and, desc, eq, indexTree, inArray, linkRef, or, sitePath, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_links?q=&locale= — what an editor can link to: entries of every
|
|
4
|
+
// collection that has an address on the website (`content.path`), by title, with
|
|
5
|
+
// that address in the language being edited. Feeds the link picker (rich text,
|
|
6
|
+
// menus, link fields), so editors pick a page instead of typing its address.
|
|
7
|
+
// Only what the signed-in user may read; drafts are included and marked, because
|
|
8
|
+
// a menu is often prepared before the page goes live. Only collections a link can
|
|
9
|
+
// follow (public, with an address) are offered. Each item carries `ref`, what a link
|
|
10
|
+
// stores (`cms:<entity>/<id>`): the link then follows the entry when its address changes.
|
|
11
|
+
const PER_COLLECTION = 8
|
|
12
|
+
const TOTAL = 24
|
|
13
|
+
|
|
14
|
+
export default defineEventHandler(async (event) => {
|
|
15
|
+
const { db, reg } = useCms()
|
|
16
|
+
const user = requireCmsUser(event)
|
|
17
|
+
const query = getQuery(event)
|
|
18
|
+
const search = String(query.q ?? '').trim().slice(0, 100)
|
|
19
|
+
const wanted = typeof query.locale === 'string' ? query.locale : null
|
|
20
|
+
const locale = reg.locales ? (wanted && reg.locales.locales.includes(wanted) ? wanted : reg.locales.default) : null
|
|
21
|
+
const isDefault = !reg.locales || locale === reg.locales.default
|
|
22
|
+
|
|
23
|
+
type Link = { entity: string; id: string; ref: string; title: string; path: string; published: boolean }
|
|
24
|
+
const out: Link[] = []
|
|
25
|
+
for (const e of reg.entities) {
|
|
26
|
+
if (out.length >= TOTAL) break
|
|
27
|
+
if (!isLinkable(e)) continue
|
|
28
|
+
const { allowed, where } = accessWhere(e, 'read', user)
|
|
29
|
+
if (!allowed) continue
|
|
30
|
+
const keys = pathKeys(e.content!.path).filter((k: string) => e.table[k])
|
|
31
|
+
const titleCol = e.table[e.titleField]
|
|
32
|
+
const liveCond = publishedCond(e)
|
|
33
|
+
const cols: Record<string, any> = { id: e.table.id, title: titleCol, live: liveCond ? sql<boolean>`${liveCond}` : sql<boolean>`true` }
|
|
34
|
+
for (const k of keys) cols[k] = e.table[k]
|
|
35
|
+
const conds: any[] = []
|
|
36
|
+
if (where) conds.push(where)
|
|
37
|
+
if (search) {
|
|
38
|
+
// By title or by address, in the language being edited as well as the default one
|
|
39
|
+
// (an editor may remember either): a translated title or address is searched too.
|
|
40
|
+
const like = '%' + foldAccents(search.replace(/^\/+/, '')).replace(/[\\%_]/g, (c) => '\\' + c) + '%'
|
|
41
|
+
const t = !isDefault ? e.localesTable : null
|
|
42
|
+
const inLocale = t
|
|
43
|
+
? [e.titleField, ...keys].filter((k, i, all) => all.indexOf(k) === i && e.localized.includes(k) && t[k]).map((k) => sql`${foldedColumn(t[k])} like ${like}`)
|
|
44
|
+
: []
|
|
45
|
+
const matches = [
|
|
46
|
+
sql`${foldedColumn(titleCol)} like ${like}`,
|
|
47
|
+
...keys.map((k: string) => sql`${foldedColumn(e.table[k])} like ${like}`),
|
|
48
|
+
...(t && inLocale.length ? [sql`exists (select 1 from ${t} where ${t.parentId} = ${e.table.id} and ${t.locale} = ${locale} and (${sql.join(inLocale, sql` or `)}))`] : []),
|
|
49
|
+
]
|
|
50
|
+
conds.push(or(...matches))
|
|
51
|
+
}
|
|
52
|
+
// The title that is exactly what was typed first, then one that starts with it, then the newest.
|
|
53
|
+
const typed = foldAccents(search)
|
|
54
|
+
const best = search ? sql`case when ${foldedColumn(titleCol)} = ${typed} then 0 when ${foldedColumn(titleCol)} like ${typed.replace(/[\\%_]/g, (c) => '\\' + c) + '%'} then 1 else 2 end` : null
|
|
55
|
+
const rows: any[] = await db.select(cols).from(e.table).where(conds.length ? and(...conds) : undefined)
|
|
56
|
+
.orderBy(...(best ? [best] : []), desc(e.table.updatedAt)).limit(PER_COLLECTION)
|
|
57
|
+
if (!rows.length) continue
|
|
58
|
+
|
|
59
|
+
// A translated address (or title) comes from the translation; untranslated parts
|
|
60
|
+
// fall back to the default language, as on the website.
|
|
61
|
+
const tr = new Map<string, any>()
|
|
62
|
+
if (!isDefault && e.localesTable) {
|
|
63
|
+
const t = e.localesTable
|
|
64
|
+
const tcols: Record<string, any> = { parentId: t.parentId }
|
|
65
|
+
for (const k of [...keys, e.titleField]) if (e.localized.includes(k) && t[k]) tcols[k] = t[k]
|
|
66
|
+
const trs: any[] = await db.select(tcols).from(t).where(and(inArray(t.parentId, rows.map((r) => r.id)), eq(t.locale, locale!)))
|
|
67
|
+
for (const r of trs) tr.set(r.parentId, r)
|
|
68
|
+
}
|
|
69
|
+
// A page tree: the address runs through the ancestors.
|
|
70
|
+
const treeIndex = e.tree ? indexTree(await loadTreeNodes(db, reg, e)) : null
|
|
71
|
+
for (const row of rows) {
|
|
72
|
+
const merged = { ...row }
|
|
73
|
+
const t = tr.get(row.id)
|
|
74
|
+
if (t) for (const [k, v] of Object.entries(t)) if (k !== 'parentId' && v !== null && v !== undefined && v !== '') merged[k] = v
|
|
75
|
+
const path = treeIndex ? treePathIn(reg, e, treeIndex, row.id, locale) : sitePath(reg.locales, e.content!.path, locale, merged)
|
|
76
|
+
if (!path) continue
|
|
77
|
+
out.push({ entity: e.name, id: row.id, ref: linkRef(e.name, row.id), title: String(merged[e.titleField] ?? ''), path, published: !!row.live })
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { locale, items: out.slice(0, TOTAL) }
|
|
81
|
+
})
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// GET /api/cms/_live — the admin's realtime socket (see utils/cmsLive.ts).
|
|
2
|
+
//
|
|
3
|
+
// The upgrade is refused unless it comes from this site's own pages (Origin) and
|
|
4
|
+
// carries a valid built-in session for an active account. Realtime needs the
|
|
5
|
+
// built-in sign-in: with external auth the host owns identity and there is no
|
|
6
|
+
// request event here to read it from.
|
|
7
|
+
|
|
8
|
+
export default defineWebSocketHandler({
|
|
9
|
+
upgrade(request: any) {
|
|
10
|
+
return admitAdminSocket(request)
|
|
11
|
+
},
|
|
12
|
+
open(peer: any) {
|
|
13
|
+
const user = peer.context?.cmsUser
|
|
14
|
+
if (!user) return peer.close(4401, 'Unauthorized')
|
|
15
|
+
// Realtime messages are tiny; refuse big frames before they are buffered whole
|
|
16
|
+
// (the `ws` default is 100 MiB). crossws-private, so only when it is there.
|
|
17
|
+
const ws = peer._internal?.ws
|
|
18
|
+
if (ws?._receiver && typeof ws._receiver._maxPayload === 'number') ws._receiver._maxPayload = 16 * 1024
|
|
19
|
+
liveOpen(peer, user, peer.context.cmsSessionVersion)
|
|
20
|
+
},
|
|
21
|
+
message(peer: any, message: any) {
|
|
22
|
+
return liveMessage(peer, message.text())
|
|
23
|
+
},
|
|
24
|
+
close(peer: any) {
|
|
25
|
+
liveClose(peer)
|
|
26
|
+
},
|
|
27
|
+
error(peer: any) {
|
|
28
|
+
liveClose(peer)
|
|
29
|
+
},
|
|
30
|
+
})
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_media/:id/usage — where this file is used (entries this person may
|
|
4
|
+
// read): media fields, rich text and blocks, translations included.
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
const user = requireCmsUser(event)
|
|
7
|
+
const { db, reg } = useCms()
|
|
8
|
+
const id = getIdParam(event)
|
|
9
|
+
// Finding uses reads every rich-text column: keep it to a human pace.
|
|
10
|
+
if (!(await rateLimit(`media-usage:${user.id}`, 60, 60_000))) throw tooManyRequests(event, 'Too many requests; try again shortly', 60_000)
|
|
11
|
+
const [media] = await db.select().from(reg.cmsMedia).where(eq(reg.cmsMedia.id, id))
|
|
12
|
+
if (!media) throw createError({ statusCode: 404, statusMessage: 'Media not found' })
|
|
13
|
+
return { usage: await mediaUsage(db, reg, user, id, media.key) }
|
|
14
|
+
})
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
import { deleteImageVariants } from '../../../utils/cmsImageSizes'
|
|
3
|
+
|
|
4
|
+
// DELETE /api/cms/_media/:id — remove a media record and its blob. Lets orphaned
|
|
5
|
+
// uploads be reclaimed (full auto-GC on hero replace / entity delete is a follow-up).
|
|
6
|
+
// If a required FK still references it, the DB's ON DELETE restrict surfaces an error.
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const user = requireCmsUser(event)
|
|
9
|
+
const { db, reg } = useCms()
|
|
10
|
+
const id = getIdParam(event)
|
|
11
|
+
|
|
12
|
+
const [media] = await db.select().from(reg.cmsMedia).where(eq(reg.cmsMedia.id, id))
|
|
13
|
+
if (!media) throw createError({ statusCode: 404, statusMessage: 'Media not found' })
|
|
14
|
+
assertMediaOwner(user, media)
|
|
15
|
+
|
|
16
|
+
// Refuse rather than orphan a live reference (entity GC handles auto-cleanup).
|
|
17
|
+
if (await isMediaReferenced(db, reg, id, media.key)) {
|
|
18
|
+
throw createError({ statusCode: 409, statusMessage: 'Media is in use and cannot be deleted.' })
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Remove the blob first; if that fails we keep the row so the delete stays retryable.
|
|
22
|
+
await useCmsStorage().delete(media.key)
|
|
23
|
+
await deleteImageVariants(media.key)
|
|
24
|
+
await db.delete(reg.cmsMedia).where(eq(reg.cmsMedia.id, id))
|
|
25
|
+
forgetServedMedia(media.key)
|
|
26
|
+
|
|
27
|
+
await audit(event, 'media.delete', { recordId: id })
|
|
28
|
+
return { ok: true }
|
|
29
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// GET /api/cms/_media/:id — resolve a media id to its record (used by the
|
|
4
|
+
// media field widget to render the existing preview when editing).
|
|
5
|
+
export default defineEventHandler(async (event) => {
|
|
6
|
+
requireCmsUser(event)
|
|
7
|
+
const { db, reg } = useCms()
|
|
8
|
+
const id = getIdParam(event)
|
|
9
|
+
|
|
10
|
+
const [media] = await db.select().from(reg.cmsMedia).where(eq(reg.cmsMedia.id, id))
|
|
11
|
+
if (!media) throw createError({ statusCode: 404, statusMessage: 'Media not found' })
|
|
12
|
+
return media
|
|
13
|
+
})
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { eq } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// PATCH /api/cms/_media/:id — update a file's editable details: alt text (and per
|
|
4
|
+
// content language: altLocales { en: '…' }), its library folder, and its focal point
|
|
5
|
+
// ({ x, y } in percent; null clears it). Only the fields sent change. Authors may
|
|
6
|
+
// change only files they uploaded.
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
const user = requireCmsUser(event)
|
|
9
|
+
const { db, reg } = useCms()
|
|
10
|
+
const id = getIdParam(event)
|
|
11
|
+
|
|
12
|
+
const raw = await readBody(event).catch(() => null)
|
|
13
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw createError({ statusCode: 422, statusMessage: 'Expected an object' })
|
|
14
|
+
const body = raw as Record<string, unknown>
|
|
15
|
+
const text = (v: unknown) => {
|
|
16
|
+
const raw = typeof v === 'string' ? v.trim().slice(0, 1000) : ''
|
|
17
|
+
return raw.length ? raw : null
|
|
18
|
+
}
|
|
19
|
+
const set: Record<string, unknown> = {}
|
|
20
|
+
if ('alt' in body) set.alt = text(body.alt)
|
|
21
|
+
if ('altLocales' in body) {
|
|
22
|
+
const langs = new Set(reg.locales?.locales ?? [])
|
|
23
|
+
const given = body.altLocales && typeof body.altLocales === 'object' ? body.altLocales as Record<string, unknown> : {}
|
|
24
|
+
const clean = Object.fromEntries(Object.entries(given).filter(([k]) => langs.has(k) && k !== reg.locales?.default).map(([k, v]) => [k, text(v)]).filter(([, v]) => v))
|
|
25
|
+
set.altLocales = Object.keys(clean).length ? clean : null
|
|
26
|
+
}
|
|
27
|
+
if ('folder' in body) set.folder = cleanFolder(body.folder)
|
|
28
|
+
// Edited on the library page (`keep`): someone cares about it, so it stays.
|
|
29
|
+
if (body.keep === true) set.inLibrary = true
|
|
30
|
+
if ('focal' in body) {
|
|
31
|
+
const f = body.focal as { x?: unknown; y?: unknown } | null
|
|
32
|
+
const pct = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(100, Math.max(0, Math.round(v))) : null)
|
|
33
|
+
const x = f ? pct(f.x) : null
|
|
34
|
+
const y = f ? pct(f.y) : null
|
|
35
|
+
if (f && (x === null || y === null)) throw createError({ statusCode: 422, statusMessage: 'Focal point needs x and y between 0 and 100' })
|
|
36
|
+
set.focalX = x
|
|
37
|
+
set.focalY = y
|
|
38
|
+
}
|
|
39
|
+
if (!Object.keys(set).length) throw createError({ statusCode: 422, statusMessage: 'Nothing to change' })
|
|
40
|
+
|
|
41
|
+
const [existing] = await db.select().from(reg.cmsMedia).where(eq(reg.cmsMedia.id, id))
|
|
42
|
+
if (!existing) throw createError({ statusCode: 404, statusMessage: 'Media not found' })
|
|
43
|
+
assertMediaOwner(user, existing)
|
|
44
|
+
// What visitors see of a file (description, focal point) is live content: people who
|
|
45
|
+
// may not publish cannot change it while the website shows the file.
|
|
46
|
+
const publicChange = 'alt' in set || 'altLocales' in set || 'focalX' in set
|
|
47
|
+
if (publicChange && !canPublish(user) && await isMediaLive(db, reg, id, existing.key)) {
|
|
48
|
+
throw createError({ statusCode: 403, statusMessage: 'This file is on the website; your role cannot change what visitors see' })
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const [media] = await db.update(reg.cmsMedia).set(set).where(eq(reg.cmsMedia.id, id)).returning()
|
|
52
|
+
if (!media) throw createError({ statusCode: 404, statusMessage: 'Media not found' })
|
|
53
|
+
await audit(event, 'media.update', { recordId: id, meta: { fields: Object.keys(set) } })
|
|
54
|
+
// Entries showing the file changed for visitors: tell the website (webhooks, caches).
|
|
55
|
+
if (publicChange) {
|
|
56
|
+
for (const u of await mediaUsage(db, reg, { id: 'system', role: 'admin' }, id, existing.key, 50)) {
|
|
57
|
+
const e = reg.byName.get(u.entity)
|
|
58
|
+
if (!e || u.locale) continue
|
|
59
|
+
const seen = await changeSnapshot(e, u.id)
|
|
60
|
+
if (seen.live) await reportChange(event, { type: 'entry.updated', entity: e, id: u.id, before: seen, noRevision: true })
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return media
|
|
64
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { inArray } from 'tinyzoo'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
// POST /api/cms/_media/exists { ids } — which of these files still exist. Restoring
|
|
5
|
+
// an older version uses it to leave out files deleted since.
|
|
6
|
+
const body = z.object({ ids: z.array(z.string().uuid()).max(500) })
|
|
7
|
+
|
|
8
|
+
export default defineEventHandler(async (event) => {
|
|
9
|
+
requireCmsUser(event)
|
|
10
|
+
const { ids } = parseOr422(body, await readBody(event))
|
|
11
|
+
if (!ids.length) return { ids: [] }
|
|
12
|
+
const { db, reg } = useCms()
|
|
13
|
+
const rows: any[] = await db.select({ id: reg.cmsMedia.id }).from(reg.cmsMedia).where(inArray(reg.cmsMedia.id, ids))
|
|
14
|
+
return { ids: rows.map((r) => r.id) }
|
|
15
|
+
})
|