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,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP byte ranges and entity tags for serving stored files. Pure functions with no
|
|
3
|
+
* Nitro globals, so the unit tests can load them.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** `bytes=a-b`, `bytes=a-` or `bytes=-n`: one range only. Anything else (several ranges, other units) is not one. */
|
|
7
|
+
const SINGLE_RANGE = /^bytes=(\d*)-(\d*)$/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The `Range` header when it asks for one range (it is passed on to the object store as
|
|
11
|
+
* it is), otherwise `undefined`: the whole file is served, as the HTTP rules allow.
|
|
12
|
+
*/
|
|
13
|
+
export function singleRange(header: unknown): string | undefined {
|
|
14
|
+
const value = String(header ?? '').trim()
|
|
15
|
+
const m = SINGLE_RANGE.exec(value)
|
|
16
|
+
return m && (m[1] || m[2]) ? value : undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The bytes (both ends included) a `Range` header selects in a file of `size` bytes; `'unsatisfiable'` when none of them exist. */
|
|
20
|
+
export function byteRange(header: unknown, size: number): { start: number; end: number } | 'unsatisfiable' | null {
|
|
21
|
+
const value = singleRange(header)
|
|
22
|
+
if (!value) return null
|
|
23
|
+
const m = SINGLE_RANGE.exec(value)!
|
|
24
|
+
const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]))
|
|
25
|
+
const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1
|
|
26
|
+
if (start >= size || start > end) return 'unsatisfiable'
|
|
27
|
+
return { start, end }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Does an `If-None-Match` header (a list, `*`, weak tags) name this entity tag? */
|
|
31
|
+
export function etagMatches(header: unknown, etag: string | undefined): boolean {
|
|
32
|
+
const value = String(header ?? '').trim()
|
|
33
|
+
if (!value || !etag) return false
|
|
34
|
+
if (value === '*') return true
|
|
35
|
+
const bare = (tag: string) => tag.trim().replace(/^W\//, '')
|
|
36
|
+
const wanted = bare(etag)
|
|
37
|
+
return value.split(',').some((tag) => bare(tag) === wanted)
|
|
38
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Sliding-window rate limiter keyed by an arbitrary string.
|
|
2
|
+
//
|
|
3
|
+
// Per-process, in-memory state: the fallback when Redis is not configured or cannot
|
|
4
|
+
// answer (see rateLimit in cmsStore.ts, which shares counts between replicas).
|
|
5
|
+
//
|
|
6
|
+
// Memory is bounded: keys are capped in length, and once the map grows past
|
|
7
|
+
// MAX_KEYS, expired entries are swept and, if still too many, the oldest dropped —
|
|
8
|
+
// so a flood of distinct keys cannot grow the heap without limit.
|
|
9
|
+
const hits = new Map<string, number[]>()
|
|
10
|
+
const MAX_KEYS = 10_000
|
|
11
|
+
const MAX_KEY_LENGTH = 200
|
|
12
|
+
|
|
13
|
+
function sweep(now: number, windowMs: number) {
|
|
14
|
+
for (const [k, times] of hits) {
|
|
15
|
+
if (!times.length || times[times.length - 1]! <= now - windowMs) hits.delete(k)
|
|
16
|
+
}
|
|
17
|
+
// Still too many live keys: drop the oldest (Map keeps insertion order).
|
|
18
|
+
for (const k of hits.keys()) {
|
|
19
|
+
if (hits.size <= MAX_KEYS * 0.9) break
|
|
20
|
+
hits.delete(k)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Returns true if the action is allowed and records it; false if `key` has
|
|
26
|
+
* already used `max` slots within `windowMs`. `max <= 0` means unlimited.
|
|
27
|
+
*/
|
|
28
|
+
export function rateLimitOk(key: string, max: number, windowMs: number): boolean {
|
|
29
|
+
if (max <= 0) return true
|
|
30
|
+
const k = key.length > MAX_KEY_LENGTH ? key.slice(0, MAX_KEY_LENGTH) : key
|
|
31
|
+
const now = Date.now()
|
|
32
|
+
const cutoff = now - windowMs
|
|
33
|
+
const recent = (hits.get(k) ?? []).filter((t) => t > cutoff)
|
|
34
|
+
if (recent.length >= max) {
|
|
35
|
+
hits.set(k, recent)
|
|
36
|
+
return false
|
|
37
|
+
}
|
|
38
|
+
recent.push(now)
|
|
39
|
+
hits.delete(k) // re-insert so the most recently used key is the newest
|
|
40
|
+
hits.set(k, recent)
|
|
41
|
+
if (hits.size > MAX_KEYS) sweep(now, windowMs)
|
|
42
|
+
return true
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Number of tracked keys (for tests and diagnostics). */
|
|
46
|
+
export function rateLimitKeyCount(): number {
|
|
47
|
+
return hits.size
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The client's IP from `X-Forwarded-For`, trusting exactly `trustedHops` proxies in
|
|
52
|
+
* front of the app. Each proxy appends the address it saw, so the client is the
|
|
53
|
+
* entry `trustedHops` places from the end — never the first entry, which the client
|
|
54
|
+
* can write itself. With no trusted proxies, the socket address is used.
|
|
55
|
+
*/
|
|
56
|
+
export function pickClientIp(xff: string | undefined, socketIp: string | undefined, trustedHops: number): string {
|
|
57
|
+
if (trustedHops <= 0 || !xff) return socketIp || 'unknown'
|
|
58
|
+
const chain = xff.split(',').map((s) => s.trim()).filter(Boolean)
|
|
59
|
+
const ip = chain[chain.length - trustedHops]
|
|
60
|
+
return (ip || chain[0] || socketIp || 'unknown').slice(0, 64)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Hits for `key` in the last `windowMs`, counting this one (memory store). */
|
|
64
|
+
export function rateLimitCount(key: string, windowMs: number): number {
|
|
65
|
+
const k = key.length > MAX_KEY_LENGTH ? key.slice(0, MAX_KEY_LENGTH) : key
|
|
66
|
+
const now = Date.now()
|
|
67
|
+
const recent = (hits.get(k) ?? []).filter((t) => t > now - windowMs)
|
|
68
|
+
recent.push(now)
|
|
69
|
+
hits.delete(k)
|
|
70
|
+
hits.set(k, recent)
|
|
71
|
+
if (hits.size > MAX_KEYS) sweep(now, windowMs)
|
|
72
|
+
return recent.length
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Take back one hit of `key` (memory store): a sign-in that succeeded is not an attempt to guess. */
|
|
76
|
+
export function rateLimitRefundMemory(key: string, windowMs: number): void {
|
|
77
|
+
const k = key.length > MAX_KEY_LENGTH ? key.slice(0, MAX_KEY_LENGTH) : key
|
|
78
|
+
const recent = (hits.get(k) ?? []).filter((t) => t > Date.now() - windowMs)
|
|
79
|
+
recent.pop()
|
|
80
|
+
if (recent.length) hits.set(k, recent)
|
|
81
|
+
else hits.delete(k)
|
|
82
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { inArray, looksLikeLinkRef, sitePrefix } from 'tinyzoo'
|
|
2
|
+
import type { CmsEntity, CmsRegistry } from 'tinyzoo'
|
|
3
|
+
|
|
4
|
+
// Redirects defined with defineRedirects(), served by the cms-redirects middleware.
|
|
5
|
+
// Loaded into memory and refreshed every 30 s (other replicas) or right after a
|
|
6
|
+
// redirect is created, changed or deleted on this instance.
|
|
7
|
+
type Target = { to: string; status: 301 | 302 }
|
|
8
|
+
let cache: { at: number; map: Map<string, Target> } | null = null
|
|
9
|
+
const TTL_MS = 30_000
|
|
10
|
+
|
|
11
|
+
export function redirectEntity(reg: CmsRegistry) {
|
|
12
|
+
return reg.entities.find((e) => (e as any).preset === 'redirects')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function invalidateRedirects(): void {
|
|
16
|
+
cache = null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Normalise a path for lookup: decoded (browsers send /star%C3%A1, editors type
|
|
21
|
+
* /stará), no query or fragment, no repeated or trailing slash (except "/").
|
|
22
|
+
*/
|
|
23
|
+
export function normalizePath(path: string): string {
|
|
24
|
+
let p = (path.split(/[?#]/)[0] || '/').replace(/\/{2,}/g, '/')
|
|
25
|
+
try {
|
|
26
|
+
p = decodeURI(p)
|
|
27
|
+
}
|
|
28
|
+
catch { /* malformed escape: compare as sent */ }
|
|
29
|
+
return p.length > 1 && p.endsWith('/') ? p.slice(0, -1) : p
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A Location header value: non-ASCII percent-encoded (headers are ASCII), existing escapes kept. */
|
|
33
|
+
export function locationHeader(to: string): string {
|
|
34
|
+
try {
|
|
35
|
+
return encodeURI(decodeURI(to))
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return encodeURI(to)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The language a redirect's old address is in, by the site's prefix rule
|
|
44
|
+
* (`defineLocales({ prefix })`): '/en/old' is English, '/old' the default language. A site
|
|
45
|
+
* with no prefix for its languages cannot tell, and gets the default language.
|
|
46
|
+
*/
|
|
47
|
+
export function redirectLocale(reg: CmsRegistry, from: string): string | null {
|
|
48
|
+
const locales = reg.locales
|
|
49
|
+
if (!locales) return null
|
|
50
|
+
const path = normalizePath(from)
|
|
51
|
+
for (const l of locales.locales) {
|
|
52
|
+
const prefix = sitePrefix(locales, l)
|
|
53
|
+
if (prefix && (path === prefix || path.startsWith(`${prefix}/`))) return l
|
|
54
|
+
}
|
|
55
|
+
return locales.default
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Where each redirect leads, as a visitor would be sent: a target stored as a reference
|
|
60
|
+
* to a page is that page's current address in the language of the old address (`/en/old`
|
|
61
|
+
* leads to the English page); one whose page is gone or not published leads nowhere (null).
|
|
62
|
+
* Addresses are returned as stored. Aligned with `rows`.
|
|
63
|
+
*/
|
|
64
|
+
async function redirectTargets(db: any, reg: CmsRegistry, rows: { from: string; to: unknown }[]): Promise<(string | null)[]> {
|
|
65
|
+
const wanted = new Map<string | null, Set<string>>()
|
|
66
|
+
for (const r of rows) {
|
|
67
|
+
if (typeof r.to !== 'string' || !looksLikeLinkRef(r.to)) continue
|
|
68
|
+
const locale = redirectLocale(reg, r.from)
|
|
69
|
+
wanted.set(locale, (wanted.get(locale) ?? new Set()).add(r.to))
|
|
70
|
+
}
|
|
71
|
+
const resolved = new Map<string | null, Map<string, string | null>>()
|
|
72
|
+
for (const [locale, refs] of wanted) resolved.set(locale, await resolveLinkRefs(db, reg, refs, { locale }))
|
|
73
|
+
return rows.map((r) => {
|
|
74
|
+
if (typeof r.to !== 'string' || !r.to) return null
|
|
75
|
+
return looksLikeLinkRef(r.to) ? resolved.get(redirectLocale(reg, r.from))?.get(r.to) ?? null : r.to
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function findRedirect(path: string): Promise<Target | null> {
|
|
80
|
+
const { db, reg } = useCms()
|
|
81
|
+
const e = redirectEntity(reg)
|
|
82
|
+
if (!e) return null
|
|
83
|
+
if (!cache || Date.now() - cache.at > TTL_MS) {
|
|
84
|
+
const rows: any[] = await db.select({ from: e.table.from, to: e.table.to, permanent: e.table.permanent }).from(e.table)
|
|
85
|
+
// A target picked from the site's pages is stored as a reference and follows the page
|
|
86
|
+
// (in the language of the old address); one whose page is gone or not published sends nobody anywhere.
|
|
87
|
+
const targets = await redirectTargets(db, reg, rows)
|
|
88
|
+
const map = new Map<string, Target>()
|
|
89
|
+
rows.forEach((r, i) => {
|
|
90
|
+
const to = targets[i]
|
|
91
|
+
// A page that has taken over the old address answers there itself: a redirect that
|
|
92
|
+
// leads to its own address would only send the visitor round and round.
|
|
93
|
+
if (!to || normalizePath(to) === normalizePath(r.from)) return
|
|
94
|
+
map.set(normalizePath(r.from), { to, status: r.permanent === false ? 302 : 301 })
|
|
95
|
+
})
|
|
96
|
+
cache = { at: Date.now(), map }
|
|
97
|
+
}
|
|
98
|
+
return cache.map.get(normalizePath(path)) ?? null
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* An entry went live at (or moved to) these addresses: redirects away from them are
|
|
103
|
+
* removed, or they would hide the entry. Run in the transaction of the write (`tx`),
|
|
104
|
+
* so the entry and the removal land together. Returns the redirects removed.
|
|
105
|
+
*/
|
|
106
|
+
export async function dropRedirectsFrom(tx: any, reg: CmsRegistry, addresses: string[]): Promise<number> {
|
|
107
|
+
const re = redirectEntity(reg)
|
|
108
|
+
const from = [...new Set(addresses.filter(Boolean))]
|
|
109
|
+
if (!re || !from.length) return 0
|
|
110
|
+
const gone: any[] = await tx.delete(re.table).where(inArray(re.table.from, from)).returning({ id: re.table.id })
|
|
111
|
+
if (gone.length) invalidateRedirects()
|
|
112
|
+
return gone.length
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* After a write to a linkable entry (any collection with an address, not only a page
|
|
117
|
+
* tree): drop the redirects away from the addresses it is live at now, in every language.
|
|
118
|
+
* `redirects.from` is unique, so a page that takes over an old address answers there.
|
|
119
|
+
*/
|
|
120
|
+
export async function dropRedirectsFromLiveAddresses(tx: any, reg: CmsRegistry, e: CmsEntity, id: string): Promise<number> {
|
|
121
|
+
if (!redirectEntity(reg) || e.singleton || !e.content?.path) return 0
|
|
122
|
+
const now = await changeSnapshot(e, id, tx)
|
|
123
|
+
return now.live ? dropRedirectsFrom(tx, reg, now.paths.map((p) => p.path)) : 0
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Refuse a redirect that would send visitors in a circle: to its own address, or
|
|
128
|
+
* through other redirects back to where it started (A → B → A). Such a page never
|
|
129
|
+
* loads, so the save answers 422 on `to`, like any other wrong value.
|
|
130
|
+
*/
|
|
131
|
+
export async function assertNoRedirectLoop(e: any, values: Record<string, any>, old?: Record<string, any> | null): Promise<void> {
|
|
132
|
+
if (e?.preset !== 'redirects') return
|
|
133
|
+
const from = values.from ?? old?.from
|
|
134
|
+
let to = values.to ?? old?.to
|
|
135
|
+
if (typeof from !== 'string' || typeof to !== 'string') return
|
|
136
|
+
const start = normalizePath(from)
|
|
137
|
+
const sitePath = (v: string) => (v.startsWith('/') && !v.startsWith('//') ? normalizePath(v) : null)
|
|
138
|
+
const { db, reg } = useCms()
|
|
139
|
+
// Targets that are references to pages count as the pages' addresses (as served, in the language of each old address).
|
|
140
|
+
const rows: any[] = await db.select({ id: e.table.id, from: e.table.from, to: e.table.to }).from(e.table)
|
|
141
|
+
const others = rows.filter((r) => r.id !== old?.id)
|
|
142
|
+
const targets = await redirectTargets(db, reg, [{ from, to }, ...others])
|
|
143
|
+
to = targets[0] ?? ''
|
|
144
|
+
let next = sitePath(to)
|
|
145
|
+
if (next === null) return
|
|
146
|
+
const map = new Map<string, string>()
|
|
147
|
+
others.forEach((r, i) => map.set(normalizePath(r.from), targets[i + 1] ?? ''))
|
|
148
|
+
for (let hops = 0; next !== null && hops < 20; hops++) {
|
|
149
|
+
if (next === start) {
|
|
150
|
+
// Straight back to itself, or round through other redirects (A → B → A).
|
|
151
|
+
const self = hops === 0
|
|
152
|
+
throw createError({
|
|
153
|
+
statusCode: 422, statusMessage: 'Validation failed',
|
|
154
|
+
data: [{ code: self ? 'redirect_loop' : 'redirect_circle', path: ['to'], message: self ? 'This redirect would lead back to its own address' : 'This redirect would make a circle with other redirects' }],
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
const hop = map.get(next)
|
|
158
|
+
next = hop === undefined ? null : sitePath(hop)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { inArray, lt, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Retention (GDPR): personal data is not kept forever.
|
|
5
|
+
*
|
|
6
|
+
* - Plugin data: each plugin's `retention` hook (the forms plugin deletes submissions
|
|
7
|
+
* past their form's `retentionDays`; none = kept).
|
|
8
|
+
* - The audit log: `cms.retention.auditDays` (default 365; 0 = kept) — it holds who
|
|
9
|
+
* did what and, for failed sign-ins, the email and address tried.
|
|
10
|
+
*
|
|
11
|
+
* A daily task (`cms:retention`) deletes what is past its time, in batches, one
|
|
12
|
+
* instance at a time (an advisory lock), and writes one audit entry with the counts
|
|
13
|
+
* (never what was in the rows).
|
|
14
|
+
*/
|
|
15
|
+
const LOCK = 72_011_040
|
|
16
|
+
const BATCH = 500
|
|
17
|
+
|
|
18
|
+
export interface RetentionResult {
|
|
19
|
+
/** What the forms plugin deleted, per form (also in `plugins.forms`). */
|
|
20
|
+
forms: Record<string, number>
|
|
21
|
+
/** What each plugin's retention hook deleted, by plugin name. */
|
|
22
|
+
plugins: Record<string, Record<string, number>>
|
|
23
|
+
audit: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Delete what is past its retention. Returns null when another instance holds the lock. */
|
|
27
|
+
export async function runRetention(): Promise<RetentionResult | null> {
|
|
28
|
+
const { db, reg } = useCms()
|
|
29
|
+
const auditDays = Math.max(0, Math.floor(Number((useRuntimeConfig().cms as any)?.retention?.auditDays ?? 365)) || 0)
|
|
30
|
+
const result: RetentionResult = { forms: {}, plugins: {}, audit: 0 }
|
|
31
|
+
const ran = await db.transaction(async (tx: any) => {
|
|
32
|
+
const [{ locked }] = (await tx.execute(sql`select pg_try_advisory_xact_lock(${LOCK}) as locked`)).rows
|
|
33
|
+
if (!locked) return false
|
|
34
|
+
for (const p of reg.plugins) {
|
|
35
|
+
if (!p.hooks?.retention) continue
|
|
36
|
+
const counts = (await p.hooks.retention({ tx, reg, batch: BATCH })) || {}
|
|
37
|
+
if (Object.values(counts).some((n) => n > 0)) result.plugins[p.name] = counts
|
|
38
|
+
}
|
|
39
|
+
result.forms = result.plugins.forms ?? {}
|
|
40
|
+
if (auditDays >= 1) {
|
|
41
|
+
const a = reg.cmsAudit
|
|
42
|
+
for (;;) {
|
|
43
|
+
const old: any[] = await tx.select({ id: a.id }).from(a).where(lt(a.createdAt, sql`now() - make_interval(days => ${auditDays})`)).limit(BATCH * 2)
|
|
44
|
+
if (!old.length) break
|
|
45
|
+
await tx.delete(a).where(inArray(a.id, old.map((r) => r.id)))
|
|
46
|
+
result.audit += old.length
|
|
47
|
+
if (old.length < BATCH * 2) break
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return true
|
|
51
|
+
})
|
|
52
|
+
if (!ran) return null
|
|
53
|
+
const forms = Object.values(result.forms).reduce((a, b) => a + b, 0)
|
|
54
|
+
const others = Object.entries(result.plugins).filter(([name]) => name !== 'forms')
|
|
55
|
+
if (forms || others.length || result.audit) {
|
|
56
|
+
const more = others.map(([name, counts]) => `, ${Object.values(counts).reduce((a, b) => a + b, 0)} item(s) of the ${name} plugin`).join('')
|
|
57
|
+
console.info(`[cms] retention: deleted ${forms} form submission(s)${more} and ${result.audit} audit entr${result.audit === 1 ? 'y' : 'ies'}`)
|
|
58
|
+
await audit(null, 'retention.purge', { meta: { forms: result.forms, audit: result.audit, ...(others.length ? { plugins: Object.fromEntries(others) } : {}) } })
|
|
59
|
+
}
|
|
60
|
+
return result
|
|
61
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { and, desc, eq, inArray, isNull, notInArray, type CmsEntity } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Revisions: after every save, a snapshot of what was saved — the entry's field values
|
|
5
|
+
* (or one translation's) exactly as the editor loads them — so the history panel can
|
|
6
|
+
* list, compare and restore. Restoring loads a snapshot into the editor; saving it
|
|
7
|
+
* then goes through the normal write path (access, publishing rules, version check).
|
|
8
|
+
*
|
|
9
|
+
* The newest `cms.revisions.keep` per entry and language are kept (default 50;
|
|
10
|
+
* 0 turns revisions off). Deleting an entry deletes its revisions.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** The values a snapshot holds: the editable fields (+ media records for previews). */
|
|
14
|
+
function snapshotOf(e: CmsEntity, row: Record<string, any>, locale: string | null): Record<string, any> {
|
|
15
|
+
const keys = Object.entries(e.fields)
|
|
16
|
+
.filter(([key, f]) => (f as any).relation?.kind !== 'one-to-many' && (!locale || e.localized.includes(key)))
|
|
17
|
+
.map(([key]) => key)
|
|
18
|
+
const out: Record<string, any> = {}
|
|
19
|
+
for (const k of keys) {
|
|
20
|
+
out[k] = row[k] ?? null
|
|
21
|
+
if (row[`${k}__media`] !== undefined) out[`${k}__media`] = row[`${k}__media`]
|
|
22
|
+
}
|
|
23
|
+
return out
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const keepCount = () => {
|
|
27
|
+
const n = Number((useRuntimeConfig().cms as any)?.revisions?.keep ?? 50)
|
|
28
|
+
return Number.isFinite(n) ? n : 50
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Record what a save stored. Never fails the save. */
|
|
32
|
+
export async function recordRevision(event: any, e: CmsEntity, id: string, locale: string | null, action: string): Promise<void> {
|
|
33
|
+
const keep = keepCount()
|
|
34
|
+
if (keep <= 0) return
|
|
35
|
+
try {
|
|
36
|
+
const { db, reg } = useCms()
|
|
37
|
+
const r = reg.cmsRevisions
|
|
38
|
+
const [row] = await db.select().from(e.table).where(eq(e.table.id, id))
|
|
39
|
+
if (!row) return
|
|
40
|
+
await hydrateRowForForm(db, reg, e, row, { markFailed: false })
|
|
41
|
+
let version = row.updatedAt ?? null
|
|
42
|
+
if (locale) {
|
|
43
|
+
const found = (await translationRows(db, e, [id], locale)).get(id)
|
|
44
|
+
const tr = found ? upgradedCopy(e, found, { recordId: id }) : found
|
|
45
|
+
for (const k of e.localized) row[k] = tr?.[k] ?? null
|
|
46
|
+
version = tr?.updatedAt ?? null
|
|
47
|
+
}
|
|
48
|
+
const data = snapshotOf(e, row, locale)
|
|
49
|
+
const sameLocale = locale ? eq(r.locale, locale) : isNull(r.locale)
|
|
50
|
+
const [prev]: any[] = await db.select({ data: r.data }).from(r)
|
|
51
|
+
.where(and(eq(r.entity, e.name), eq(r.recordId, id), sameLocale)).orderBy(desc(r.createdAt)).limit(1)
|
|
52
|
+
// The first one has nothing to compare with: it changed nothing in particular.
|
|
53
|
+
// An older snapshot is compared in the current shape: an upgrade alone is not a change.
|
|
54
|
+
if (prev?.data && typeof prev.data === 'object') upgradeStoredJson(e, prev.data, { recordId: id })
|
|
55
|
+
const changed = prev ? Object.keys(data).filter((k) => !k.endsWith('__media') && stableJson(data[k]) !== stableJson(prev.data?.[k])) : []
|
|
56
|
+
await db.insert(r).values({ entity: e.name, recordId: id, locale, action, version, data, changed, userId: event?.context?.cmsUser ? actorId(event.context.cmsUser) : null })
|
|
57
|
+
// Keep the newest `keep`.
|
|
58
|
+
const newest: any[] = await db.select({ id: r.id }).from(r)
|
|
59
|
+
.where(and(eq(r.entity, e.name), eq(r.recordId, id), sameLocale)).orderBy(desc(r.createdAt)).limit(keep)
|
|
60
|
+
if (newest.length === keep) {
|
|
61
|
+
await db.delete(r).where(and(eq(r.entity, e.name), eq(r.recordId, id), sameLocale, notInArray(r.id, newest.map((x) => x.id))))
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
console.error('[cms] could not record a revision', safeErrorMessage(err))
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Forget an entry's revisions (it was deleted). */
|
|
70
|
+
export async function dropRevisions(e: CmsEntity, id: string): Promise<void> {
|
|
71
|
+
try {
|
|
72
|
+
const { db, reg } = useCms()
|
|
73
|
+
await db.delete(reg.cmsRevisions).where(and(eq(reg.cmsRevisions.entity, e.name), eq(reg.cmsRevisions.recordId, id)))
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
console.error('[cms] could not drop revisions', safeErrorMessage(err))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The history of one entry (or translation), newest first, with who saved each. */
|
|
81
|
+
export async function listRevisions(e: CmsEntity, id: string, locale: string | null) {
|
|
82
|
+
const { db, reg } = useCms()
|
|
83
|
+
const r = reg.cmsRevisions
|
|
84
|
+
const rows: any[] = await db.select({ id: r.id, action: r.action, version: r.version, changed: r.changed, userId: r.userId, createdAt: r.createdAt })
|
|
85
|
+
.from(r).where(and(eq(r.entity, e.name), eq(r.recordId, id), locale ? eq(r.locale, locale) : isNull(r.locale)))
|
|
86
|
+
.orderBy(desc(r.createdAt)).limit(200)
|
|
87
|
+
const ids = [...new Set(rows.map((x) => x.userId).filter(Boolean))] as string[]
|
|
88
|
+
const users: any[] = ids.length ? await db.select({ id: reg.cmsUsers.id, name: reg.cmsUsers.name, email: reg.cmsUsers.email }).from(reg.cmsUsers).where(inArray(reg.cmsUsers.id, ids)) : []
|
|
89
|
+
const names = new Map(users.map((u) => [u.id, displayName(u.name, u.email)]))
|
|
90
|
+
return rows.map((x) => ({ ...x, byName: x.userId ? names.get(x.userId) ?? null : null }))
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Forget one translation's revisions (it was removed). */
|
|
94
|
+
export async function dropTranslationRevisions(e: CmsEntity, id: string, locale: string): Promise<void> {
|
|
95
|
+
try {
|
|
96
|
+
const { db, reg } = useCms()
|
|
97
|
+
const r = reg.cmsRevisions
|
|
98
|
+
await db.delete(r).where(and(eq(r.entity, e.name), eq(r.recordId, id), eq(r.locale, locale)))
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
console.error('[cms] could not drop revisions', safeErrorMessage(err))
|
|
102
|
+
}
|
|
103
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { and, eq, gt, lte, propOf, sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
const LOCK = 72_011_004
|
|
4
|
+
const KEY = 'scheduler.lastRun'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Report every scheduled entry whose publish date passed since the last run. One
|
|
8
|
+
* replica at a time (a Postgres advisory lock); the last run is kept in cms_state,
|
|
9
|
+
* so a restart or a missed minute catches up instead of skipping. The very first
|
|
10
|
+
* run starts from now.
|
|
11
|
+
*/
|
|
12
|
+
export async function announceScheduled(): Promise<number> {
|
|
13
|
+
const { db, reg } = useCms()
|
|
14
|
+
const due: { e: any; id: string; row: any }[] = []
|
|
15
|
+
const ran = await db.transaction(async (tx: any) => {
|
|
16
|
+
const [{ locked }] = (await tx.execute(sql`select pg_try_advisory_xact_lock(${LOCK}) as locked`)).rows
|
|
17
|
+
if (!locked) return false
|
|
18
|
+
const s = reg.cmsState
|
|
19
|
+
const [state] = await tx.select().from(s).where(eq(s.key, KEY))
|
|
20
|
+
const [{ now }] = (await tx.execute(sql`select now() as now`)).rows
|
|
21
|
+
// The very first run looks back ten minutes (an entry going live during a deploy).
|
|
22
|
+
const since = state?.value?.at ? new Date(state.value.at) : new Date(new Date(now).getTime() - 10 * 60_000)
|
|
23
|
+
for (const e of reg.entities) {
|
|
24
|
+
const p = e.publish
|
|
25
|
+
if (!p?.dateField || p.schedule === false) continue
|
|
26
|
+
const date = e.table[propOf(p.dateField, e.fields[p.dateField]!)]
|
|
27
|
+
const status = e.table[propOf(p.field, e.fields[p.field]!)]
|
|
28
|
+
// Only entries saved before their date (scheduled): "publish now" was announced
|
|
29
|
+
// when it was saved — the server stamps that date itself (stampPublishDate),
|
|
30
|
+
// so it never lies after the save. At worst a borderline case is announced twice.
|
|
31
|
+
const rows: any[] = await tx.select().from(e.table)
|
|
32
|
+
.where(and(eq(status, p.publishedValue), gt(date, since), lte(date, new Date(now)), sql`${date} > ${e.table.updatedAt}`))
|
|
33
|
+
for (const row of rows) due.push({ e, id: row.id, row })
|
|
34
|
+
}
|
|
35
|
+
await tx.insert(s).values({ key: KEY, value: { at: new Date(now).toISOString() } })
|
|
36
|
+
.onConflictDoUpdate({ target: s.key, set: { value: { at: new Date(now).toISOString() }, updatedAt: sql`now()` } })
|
|
37
|
+
return true
|
|
38
|
+
})
|
|
39
|
+
if (!ran) return 0
|
|
40
|
+
if (due.length) console.info(`[cms] scheduled: ${due.length} entries went live`)
|
|
41
|
+
for (const { e, id, row } of due) {
|
|
42
|
+
await reportChange(null, { type: 'entry.published', entity: e, id, before: { live: false, paths: [] }, after: row, noRevision: true })
|
|
43
|
+
}
|
|
44
|
+
return due.length
|
|
45
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What may be logged or sent to an error tracker: messages without query values, error
|
|
5
|
+
* copies without their payload, and webhook addresses without their secret. Pure
|
|
6
|
+
* functions with no Nitro globals, so the unit tests can load them.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The message without query parameters: drizzle's "Failed query: … params: …" would
|
|
11
|
+
* put emails, password hashes or draft text in the log. The driver's own error (the
|
|
12
|
+
* innermost cause) says what went wrong without them. h3 copies the message of the
|
|
13
|
+
* error it wraps, so the chain can hold several "Failed query" layers.
|
|
14
|
+
*/
|
|
15
|
+
export function safeErrorMessage(err: any): string {
|
|
16
|
+
const msg = String(err?.message || err?.statusMessage || 'unknown')
|
|
17
|
+
if (!msg.startsWith('Failed query')) return msg
|
|
18
|
+
let inner = err?.cause
|
|
19
|
+
for (let depth = 0; depth < 8 && inner && String(inner.message ?? '').startsWith('Failed query'); depth++) inner = inner.cause
|
|
20
|
+
if (!inner?.message) return 'Query failed'
|
|
21
|
+
return 'Query failed: ' + inner.message + (inner.code ? ' (' + inner.code + ')' : '')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A one-line hint when a query failed because a table does not exist (Postgres 42P01):
|
|
26
|
+
* the database has not got the migrations yet, as happens for a moment when `cms.config.ts`
|
|
27
|
+
* changes before `pnpm db:migrate` has run. Null for any other error.
|
|
28
|
+
*/
|
|
29
|
+
export function missingTableHint(err: unknown): string | null {
|
|
30
|
+
for (let e: any = err, depth = 0; e && typeof e === 'object' && depth < 8; e = e.cause, depth++) {
|
|
31
|
+
if (e.code === '42P01') return 'a table is missing: apply the migrations (`pnpm db:migrate`, or start with NUXT_CMS_MIGRATIONS_ON_START=true) and restart the server'
|
|
32
|
+
}
|
|
33
|
+
return null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A copy of the error that is safe to send away: the message is `safeErrorMessage`, the
|
|
38
|
+
* stack keeps its frames (file names and line numbers, no values), and the causes are
|
|
39
|
+
* copied the same way (to a depth of 5). Everything else on the original — `data`, a
|
|
40
|
+
* driver's `detail`, query parameters — is left behind.
|
|
41
|
+
*/
|
|
42
|
+
export function scrubError(err: unknown, depth = 0): Error {
|
|
43
|
+
if (!err || typeof err !== 'object') return new Error(typeof err === 'string' ? err : 'unknown')
|
|
44
|
+
const src = err as any
|
|
45
|
+
const copy = new Error(safeErrorMessage(src), depth < 5 && src.cause ? { cause: scrubError(src.cause, depth + 1) } : undefined)
|
|
46
|
+
if (typeof src.name === 'string') copy.name = src.name
|
|
47
|
+
const frames = typeof src.stack === 'string' ? src.stack.split('\n').filter((l: string) => /^\s+at\s/.test(l)) : []
|
|
48
|
+
copy.stack = [`${copy.name}: ${copy.message}`, ...frames].join('\n')
|
|
49
|
+
return copy
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A mail server's refusal often names the address ("550 5.1.1 <jana@example.com>: Recipient
|
|
54
|
+
* address rejected"): for the logs, anything that looks like an email becomes `<email>`.
|
|
55
|
+
*/
|
|
56
|
+
export function redactEmails(text: string): string {
|
|
57
|
+
return text.replace(/[^\s<>"'(),;:@]+@[^\s<>"'(),;:@]+\.[^\s<>"'(),;:@]+/g, '<email>')
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A copy of an error with everything it has (message, stack, causes, payload), taken before `hushError` changes the original. */
|
|
61
|
+
export function snapshotError<T>(err: T): T {
|
|
62
|
+
if (!err || typeof err !== 'object') return err
|
|
63
|
+
return Object.create(Object.getPrototypeOf(err), Object.getOwnPropertyDescriptors(err))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Make an unhandled error safe for what prints it without us: Nitro writes
|
|
68
|
+
* "[request error] [unhandled] [GET] <url>" and then the error itself (message, stack,
|
|
69
|
+
* `cause` with a failed query's `params`) to stderr, and h3 has copied the failed query's
|
|
70
|
+
* text, values included, into the message.
|
|
71
|
+
*
|
|
72
|
+
* Changed on the error itself, because that object is what gets printed (and what other
|
|
73
|
+
* `error` hooks see afterwards): the message is the fixed "Server Error" — the same words
|
|
74
|
+
* the client already gets for an unhandled error, so responses do not change —, the
|
|
75
|
+
* causes are scrubbed copies (`scrubError`: driver message and frames, no values), `data`
|
|
76
|
+
* is dropped, and the error is no longer marked `unhandled`/`fatal`, which is the only
|
|
77
|
+
* thing that makes Nitro and h3 print it. The one line that is written is tinyzoo's own
|
|
78
|
+
* JSON line (`cms-errors.ts`). Take a `snapshotError` first if the original is needed.
|
|
79
|
+
*/
|
|
80
|
+
export function hushError(err: any): void {
|
|
81
|
+
if (!err || typeof err !== 'object') return
|
|
82
|
+
const safe = scrubError(err)
|
|
83
|
+
const set = (key: string, value: unknown) => { try { err[key] = value } catch { /* frozen: nothing more to do */ } }
|
|
84
|
+
set('message', 'Server Error')
|
|
85
|
+
set('stack', safe.stack?.replace(/^[^\n]*/, `${safe.name}: Server Error`))
|
|
86
|
+
set('cause', safe.cause)
|
|
87
|
+
set('data', undefined)
|
|
88
|
+
set('unhandled', false)
|
|
89
|
+
set('fatal', false)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A webhook address for logs and the `cms:error` hook: the origin and a short hash of the
|
|
94
|
+
* path — no credentials, no query, and no path, because Slack, Discord and similar
|
|
95
|
+
* services keep their secret in it (`/services/T000/B000/XXXX`). The hash still tells two
|
|
96
|
+
* webhooks on the same host apart.
|
|
97
|
+
*/
|
|
98
|
+
export function safeUrl(url: string): string {
|
|
99
|
+
try {
|
|
100
|
+
const u = new URL(url)
|
|
101
|
+
const path = u.pathname === '/' ? '' : `/…#${createHash('sha256').update(u.pathname).digest('hex').slice(0, 8)}`
|
|
102
|
+
return u.origin + path
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return '(invalid url)'
|
|
106
|
+
}
|
|
107
|
+
}
|