@cossackframework/cms 0.0.0-stage → 0.9.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 +21 -0
- package/README.md +147 -2
- package/agent-docs.json +259 -0
- package/app/README.md +78 -0
- package/app/cossack-recipe.json +43 -0
- package/app/src/auth-bot-check.ts +32 -0
- package/app/src/auth-bot-token.ts +11 -0
- package/app/src/auth-input.ts +35 -0
- package/app/src/auth-options.ts +18 -0
- package/app/src/auth-providers.ts +16 -0
- package/app/src/auth.ts +1082 -0
- package/app/src/brand.ts +68 -0
- package/app/src/cms/ai.ts +54 -0
- package/app/src/cms/analytics.ts +33 -0
- package/app/src/cms/block-errors.ts +55 -0
- package/app/src/cms/block-inserter.ts +111 -0
- package/app/src/cms/block-panel.ts +68 -0
- package/app/src/cms/block-rows.ts +44 -0
- package/app/src/cms/block-tree.ts +585 -0
- package/app/src/cms/blocks.css +708 -0
- package/app/src/cms/builder.ts +126 -0
- package/app/src/cms/cache.ts +44 -0
- package/app/src/cms/carousel.client.ts +52 -0
- package/app/src/cms/collab/presence.ts +69 -0
- package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
- package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
- package/app/src/cms/collab/room.ts +881 -0
- package/app/src/cms/compare.client.ts +47 -0
- package/app/src/cms/condition-control.ts +109 -0
- package/app/src/cms/content-api.ts +143 -0
- package/app/src/cms/content.ts +524 -0
- package/app/src/cms/countdown.client.ts +37 -0
- package/app/src/cms/editor-layout-editor.ts +260 -0
- package/app/src/cms/editor-layout-view.ts +37 -0
- package/app/src/cms/editor.ts +381 -0
- package/app/src/cms/entry.ts +26 -0
- package/app/src/cms/feeds.ts +145 -0
- package/app/src/cms/field-controls.ts +222 -0
- package/app/src/cms/field-group-editor.ts +105 -0
- package/app/src/cms/field-group-view.ts +211 -0
- package/app/src/cms/form-view.ts +203 -0
- package/app/src/cms/form.client.ts +203 -0
- package/app/src/cms/guards.ts +27 -0
- package/app/src/cms/handoff.ts +202 -0
- package/app/src/cms/headings.ts +51 -0
- package/app/src/cms/icons.ts +80 -0
- package/app/src/cms/import.client.ts +16 -0
- package/app/src/cms/index.ts +191 -0
- package/app/src/cms/lightbox.client.ts +109 -0
- package/app/src/cms/machine.ts +118 -0
- package/app/src/cms/maintenance.ts +97 -0
- package/app/src/cms/manage.ts +1236 -0
- package/app/src/cms/mcp-tools.ts +388 -0
- package/app/src/cms/mcp.ts +242 -0
- package/app/src/cms/media-chooser.ts +123 -0
- package/app/src/cms/media-usage.ts +57 -0
- package/app/src/cms/middleware.ts +199 -0
- package/app/src/cms/middlewares.ts +13 -0
- package/app/src/cms/network-ui.ts +36 -0
- package/app/src/cms/network-view.ts +38 -0
- package/app/src/cms/notes-announce.ts +65 -0
- package/app/src/cms/notes-rail.ts +207 -0
- package/app/src/cms/notification-rules.ts +66 -0
- package/app/src/cms/recovery.ts +82 -0
- package/app/src/cms/replace.ts +63 -0
- package/app/src/cms/reserved-paths.ts +19 -0
- package/app/src/cms/rich-text-field.ts +325 -0
- package/app/src/cms/rich-text-schema.ts +91 -0
- package/app/src/cms/rich-text.client.ts +255 -0
- package/app/src/cms/search.client.ts +116 -0
- package/app/src/cms/seo-head.ts +78 -0
- package/app/src/cms/seo.ts +241 -0
- package/app/src/cms/settings-draft.ts +218 -0
- package/app/src/cms/settings-file.ts +127 -0
- package/app/src/cms/settings-form.ts +180 -0
- package/app/src/cms/settings-languages.ts +125 -0
- package/app/src/cms/settings-nav.ts +102 -0
- package/app/src/cms/settings-network.ts +151 -0
- package/app/src/cms/settings-permalinks.ts +114 -0
- package/app/src/cms/settings-scroll.ts +10 -0
- package/app/src/cms/settings-search.ts +77 -0
- package/app/src/cms/settings-section.ts +38 -0
- package/app/src/cms/share.client.ts +27 -0
- package/app/src/cms/site-editing.ts +219 -0
- package/app/src/cms/site-editor.client.ts +1008 -0
- package/app/src/cms/site-editor.ts +99 -0
- package/app/src/cms/site-export.ts +60 -0
- package/app/src/cms/site-forms.ts +143 -0
- package/app/src/cms/site-import.ts +28 -0
- package/app/src/cms/site-session.ts +36 -0
- package/app/src/cms/site-taskbar.ts +77 -0
- package/app/src/cms/site-view.ts +1014 -0
- package/app/src/cms/site.ts +1322 -0
- package/app/src/cms/sitemaps.ts +131 -0
- package/app/src/cms/stat.client.ts +56 -0
- package/app/src/cms/style-controls.ts +252 -0
- package/app/src/cms/tabs.client.ts +36 -0
- package/app/src/cms/taskbar.ts +134 -0
- package/app/src/cms/term-icons.ts +10 -0
- package/app/src/cms/traffic.ts +26 -0
- package/app/src/cms/ui.ts +170 -0
- package/app/src/cms/updates.ts +124 -0
- package/app/src/cms/uploads.ts +26 -0
- package/app/src/cms/worker.ts +13 -0
- package/app/src/config/auth.ts +30 -0
- package/app/src/config/cms.ts +18 -0
- package/app/src/dashboard/access.ts +344 -0
- package/app/src/dashboard/agent-icons.ts +44 -0
- package/app/src/dashboard/app-passwords.ts +74 -0
- package/app/src/dashboard/avatar-field.ts +58 -0
- package/app/src/dashboard/bulk.ts +53 -0
- package/app/src/dashboard/head.ts +29 -0
- package/app/src/dashboard/icons.ts +15 -0
- package/app/src/dashboard/list-table.ts +120 -0
- package/app/src/dashboard/modules/roles.ts +15 -0
- package/app/src/dashboard/modules/sessions.ts +15 -0
- package/app/src/dashboard/modules/settings.ts +15 -0
- package/app/src/dashboard/modules/users.ts +18 -0
- package/app/src/dashboard/page.ts +67 -0
- package/app/src/dashboard/registry.ts +13 -0
- package/app/src/dashboard/session-list.ts +98 -0
- package/app/src/dashboard/tabs.ts +26 -0
- package/app/src/dashboard/time-ago.ts +16 -0
- package/app/src/dashboard/types.ts +40 -0
- package/app/src/dashboard/user-sections.ts +172 -0
- package/app/src/lib/permissions.ts +84 -0
- package/app/src/middlewares/auth.ts +117 -0
- package/app/src/pages/(site)/[...path]/index.ts +609 -0
- package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
- package/app/src/pages/(site)/feed/index.ts +12 -0
- package/app/src/pages/(site)/index.ts +11 -0
- package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
- package/app/src/pages/(site)/layout.ts +219 -0
- package/app/src/pages/(site)/llms.txt/index.ts +23 -0
- package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
- package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
- package/app/src/pages/(site)/robots.txt/index.ts +29 -0
- package/app/src/pages/(site)/search/index.ts +36 -0
- package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
- package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
- package/app/src/pages/api/auth/session.ts +48 -0
- package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
- package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
- package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
- package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
- package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
- package/app/src/pages/api/cms/cache/purge.ts +6 -0
- package/app/src/pages/api/cms/collections/index.ts +6 -0
- package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
- package/app/src/pages/api/cms/comments/[id].ts +9 -0
- package/app/src/pages/api/cms/comments/index.ts +126 -0
- package/app/src/pages/api/cms/comments/queue.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
- package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
- package/app/src/pages/api/cms/export/[collection].ts +37 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
- package/app/src/pages/api/cms/import/[collection].ts +23 -0
- package/app/src/pages/api/cms/mcp.ts +29 -0
- package/app/src/pages/api/cms/me/index.ts +6 -0
- package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
- package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
- package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
- package/app/src/pages/api/cms/media/[id].ts +6 -0
- package/app/src/pages/api/cms/media.ts +26 -0
- package/app/src/pages/api/cms/menus/[location].ts +14 -0
- package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
- package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
- package/app/src/pages/api/cms/network/sites/index.ts +14 -0
- package/app/src/pages/api/cms/notes/[id].ts +13 -0
- package/app/src/pages/api/cms/notes/index.ts +6 -0
- package/app/src/pages/api/cms/payments/webhook.ts +28 -0
- package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
- package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
- package/app/src/pages/api/cms/plugins/index.ts +6 -0
- package/app/src/pages/api/cms/recovery.ts +29 -0
- package/app/src/pages/api/cms/redirects/index.ts +9 -0
- package/app/src/pages/api/cms/roles/index.ts +6 -0
- package/app/src/pages/api/cms/schema/[collection].ts +13 -0
- package/app/src/pages/api/cms/search.ts +16 -0
- package/app/src/pages/api/cms/settings/[group].ts +9 -0
- package/app/src/pages/api/cms/settings/index.ts +9 -0
- package/app/src/pages/api/cms/site-export.ts +34 -0
- package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
- package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
- package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
- package/app/src/pages/api/cms/uploads/index.ts +26 -0
- package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
- package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
- package/app/src/pages/api/cms/users/index.ts +12 -0
- package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
- package/app/src/pages/api/cms/webhooks/index.ts +9 -0
- package/app/src/pages/auth/[provider]/callback.ts +11 -0
- package/app/src/pages/auth/[provider]/redirect.ts +9 -0
- package/app/src/pages/auth/forgot-password/index.ts +75 -0
- package/app/src/pages/auth/layout.ts +32 -0
- package/app/src/pages/auth/login/index.ts +198 -0
- package/app/src/pages/auth/magic/index.ts +68 -0
- package/app/src/pages/auth/register/index.ts +117 -0
- package/app/src/pages/auth/reset-password/index.ts +65 -0
- package/app/src/pages/auth/setup/index.ts +194 -0
- package/app/src/pages/auth/two-factor/index.ts +67 -0
- package/app/src/pages/auth/verify/index.ts +62 -0
- package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
- package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
- package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
- package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
- package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
- package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
- package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
- package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
- package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
- package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
- package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
- package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
- package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
- package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
- package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
- package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
- package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
- package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
- package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
- package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
- package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
- package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
- package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
- package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
- package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
- package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
- package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
- package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
- package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
- package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +182 -0
- package/app/src/pages/dashboard/index.ts +214 -0
- package/app/src/pages/dashboard/layout.ts +320 -0
- package/app/src/pages/dashboard/profile/index.ts +211 -0
- package/app/src/pages/dashboard/profile/security/index.ts +255 -0
- package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
- package/app/src/pages/dashboard/roles/index.ts +134 -0
- package/app/src/pages/dashboard/roles/new/index.ts +95 -0
- package/app/src/pages/dashboard/sessions/index.ts +105 -0
- package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
- package/app/src/pages/dashboard/users/index.ts +299 -0
- package/app/src/pages/dashboard/users/new/index.ts +123 -0
- package/app/src/passkeys.client.ts +18 -0
- package/app/src/plugins/default-theme/assets/cover.svg +31 -0
- package/app/src/plugins/default-theme/assets/logo.svg +8 -0
- package/app/src/plugins/default-theme/parts/comments.ts +66 -0
- package/app/src/plugins/default-theme/parts/list.ts +38 -0
- package/app/src/plugins/default-theme/parts/media.ts +15 -0
- package/app/src/plugins/default-theme/parts/options.ts +45 -0
- package/app/src/plugins/default-theme/plugin.json +275 -0
- package/app/src/plugins/default-theme/templates/archive.ts +14 -0
- package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
- package/app/src/plugins/default-theme/templates/entry.ts +27 -0
- package/app/src/plugins/default-theme/templates/home.ts +8 -0
- package/app/src/plugins/default-theme/templates/layout.ts +40 -0
- package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
- package/app/src/plugins/default-theme/templates/search.ts +32 -0
- package/app/src/services/rbac.ts +65 -0
- package/app/src/services/roles.ts +89 -0
- package/app/src/services/users.ts +173 -0
- package/package.json +123 -3
- package/src/automations.ts +95 -0
- package/src/bindings.ts +138 -0
- package/src/block-references.ts +239 -0
- package/src/block-shape.ts +155 -0
- package/src/blocks.ts +1157 -0
- package/src/cache.ts +54 -0
- package/src/checks.ts +198 -0
- package/src/cloudflare-workers.d.ts +13 -0
- package/src/cloudflare.ts +61 -0
- package/src/collab.ts +372 -0
- package/src/collections.ts +421 -0
- package/src/comments.ts +46 -0
- package/src/cron.ts +95 -0
- package/src/dashboard-menu.ts +105 -0
- package/src/diff.ts +113 -0
- package/src/editor-layout.ts +316 -0
- package/src/errors.ts +50 -0
- package/src/field-groups.ts +498 -0
- package/src/fields.ts +411 -0
- package/src/form-builder.ts +1053 -0
- package/src/forms.ts +109 -0
- package/src/highlight.ts +134 -0
- package/src/hooks.ts +510 -0
- package/src/icon-catalog.ts +55 -0
- package/src/icons.ts +128 -0
- package/src/images.ts +149 -0
- package/src/index.ts +100 -0
- package/src/isolate-core.ts +245 -0
- package/src/isolate.ts +19 -0
- package/src/isolation.ts +69 -0
- package/src/mail.ts +182 -0
- package/src/manifest.ts +476 -0
- package/src/media.ts +193 -0
- package/src/menus.ts +287 -0
- package/src/module.ts +32 -0
- package/src/modules/content.ts +64 -0
- package/src/modules/forms.ts +35 -0
- package/src/node.ts +66 -0
- package/src/notes.ts +237 -0
- package/src/permissions.ts +139 -0
- package/src/plugin-settings.ts +114 -0
- package/src/records.ts +56 -0
- package/src/redirects.ts +59 -0
- package/src/resource.ts +245 -0
- package/src/richtext.ts +402 -0
- package/src/schema-json.ts +112 -0
- package/src/search.ts +89 -0
- package/src/seo.ts +477 -0
- package/src/server/accounts.ts +418 -0
- package/src/server/ai.ts +33 -0
- package/src/server/api-tokens.ts +91 -0
- package/src/server/areas.ts +116 -0
- package/src/server/audit.ts +94 -0
- package/src/server/auth.ts +89 -0
- package/src/server/automations.ts +190 -0
- package/src/server/autosaves.ts +69 -0
- package/src/server/brand-icons.ts +50 -0
- package/src/server/brands.ts +86 -0
- package/src/server/budget.ts +97 -0
- package/src/server/cache.ts +104 -0
- package/src/server/capabilities.ts +333 -0
- package/src/server/cloudflare.ts +92 -0
- package/src/server/comments.ts +237 -0
- package/src/server/drafts.ts +176 -0
- package/src/server/field-groups.ts +88 -0
- package/src/server/files.ts +780 -0
- package/src/server/forms.ts +726 -0
- package/src/server/handoffs.ts +107 -0
- package/src/server/host-schema.ts +312 -0
- package/src/server/host.ts +2892 -0
- package/src/server/images.ts +34 -0
- package/src/server/index.ts +59 -0
- package/src/server/indexnow.ts +91 -0
- package/src/server/isolation.ts +183 -0
- package/src/server/locked.ts +45 -0
- package/src/server/mail.ts +93 -0
- package/src/server/markdown.ts +24 -0
- package/src/server/menus.ts +286 -0
- package/src/server/network-policy.ts +60 -0
- package/src/server/network.ts +665 -0
- package/src/server/notes.ts +275 -0
- package/src/server/outbox.ts +213 -0
- package/src/server/path-moves.ts +33 -0
- package/src/server/payments.ts +59 -0
- package/src/server/previews.ts +62 -0
- package/src/server/purge.ts +140 -0
- package/src/server/reconcile.ts +38 -0
- package/src/server/redirects.ts +183 -0
- package/src/server/repository.ts +1107 -0
- package/src/server/schedules.ts +105 -0
- package/src/server/schema.ts +562 -0
- package/src/server/security.ts +391 -0
- package/src/server/seed.ts +52 -0
- package/src/server/shared-fields.ts +34 -0
- package/src/server/site-export.ts +151 -0
- package/src/server/site-import.ts +482 -0
- package/src/server/site-search.ts +289 -0
- package/src/server/site-settings.ts +286 -0
- package/src/server/sites.ts +243 -0
- package/src/server/stores.ts +314 -0
- package/src/server/stripe.ts +173 -0
- package/src/server/taxonomies.ts +415 -0
- package/src/server/tokens.ts +25 -0
- package/src/server/traffic.ts +118 -0
- package/src/server/users.ts +653 -0
- package/src/server/webhooks.ts +245 -0
- package/src/settings-controls.ts +54 -0
- package/src/settings-document.ts +111 -0
- package/src/settings.ts +426 -0
- package/src/storage/cloudflare.ts +94 -0
- package/src/storage/index.ts +30 -0
- package/src/storage/node.ts +114 -0
- package/src/taxonomy.ts +51 -0
- package/src/theme.ts +1135 -0
- package/src/to-markdown.ts +179 -0
- package/src/updates.ts +126 -0
- package/src/version.ts +2 -0
- package/src/vite.d.ts +25 -0
- package/src/vite.js +199 -0
- package/src/webhooks.ts +107 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP (Model Context Protocol) over Streamable HTTP, stateless: each POST carries one JSON-RPC
|
|
3
|
+
* message, or a batch, and gets its answers as JSON. There are no sessions and no
|
|
4
|
+
* server-initiated streams, so GET and DELETE answer 405. The server speaks initialize, ping,
|
|
5
|
+
* tools/list and tools/call, and acknowledges notifications with 202. It is the part of the
|
|
6
|
+
* protocol the CMS needs, written here so applications take no SDK dependency; the official
|
|
7
|
+
* client proves it in the CLI's tests.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export type JsonSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array';
|
|
11
|
+
|
|
12
|
+
export interface JsonSchemaProperty {
|
|
13
|
+
readonly type?: JsonSchemaType | readonly JsonSchemaType[];
|
|
14
|
+
readonly description?: string;
|
|
15
|
+
readonly enum?: readonly string[];
|
|
16
|
+
readonly items?: JsonSchemaProperty;
|
|
17
|
+
readonly properties?: { readonly [name: string]: JsonSchemaProperty };
|
|
18
|
+
readonly additionalProperties?: boolean | JsonSchemaProperty;
|
|
19
|
+
readonly minimum?: number;
|
|
20
|
+
readonly maximum?: number;
|
|
21
|
+
readonly default?: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface JsonSchema extends JsonSchemaProperty {
|
|
25
|
+
readonly type: 'object';
|
|
26
|
+
readonly properties: { readonly [name: string]: JsonSchemaProperty };
|
|
27
|
+
readonly required?: readonly string[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface McpToolAnnotations {
|
|
31
|
+
readonly title?: string;
|
|
32
|
+
readonly readOnlyHint: boolean;
|
|
33
|
+
readonly destructiveHint: boolean;
|
|
34
|
+
readonly idempotentHint: boolean;
|
|
35
|
+
readonly openWorldHint?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface McpTool<C> {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly title?: string;
|
|
41
|
+
readonly description: string;
|
|
42
|
+
readonly inputSchema: JsonSchema;
|
|
43
|
+
readonly annotations: McpToolAnnotations;
|
|
44
|
+
run(input: { readonly [name: string]: unknown }, context: C): Promise<unknown>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface McpServerOptions<C> {
|
|
48
|
+
readonly name: string;
|
|
49
|
+
readonly version: string;
|
|
50
|
+
/** Guidance the client shows its model after initialize. */
|
|
51
|
+
readonly instructions?: string;
|
|
52
|
+
readonly tools: readonly McpTool<C>[];
|
|
53
|
+
readonly context: C;
|
|
54
|
+
/** The caller may only read: writing tools are neither listed nor run. */
|
|
55
|
+
readonly readOnly?: boolean;
|
|
56
|
+
/** Turns a tool's thrown error into the text and data of an `isError` result; others become "The tool failed." */
|
|
57
|
+
readonly toolError?: (error: unknown) => { message: string; data?: unknown } | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Protocol revisions this server answers; a client's known revision is echoed, anything else gets the newest. */
|
|
61
|
+
export const MCP_PROTOCOL_VERSIONS: readonly string[] = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
62
|
+
|
|
63
|
+
type Id = string | number | null;
|
|
64
|
+
interface Message { jsonrpc?: unknown; id?: Id; method?: unknown; params?: unknown; result?: unknown; error?: unknown }
|
|
65
|
+
|
|
66
|
+
const PARSE_ERROR = -32700;
|
|
67
|
+
const INVALID_REQUEST = -32600;
|
|
68
|
+
const METHOD_NOT_FOUND = -32601;
|
|
69
|
+
const INVALID_PARAMS = -32602;
|
|
70
|
+
const INTERNAL_ERROR = -32603;
|
|
71
|
+
|
|
72
|
+
function failure(id: Id, code: number, message: string, data?: unknown) {
|
|
73
|
+
return { jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
|
|
77
|
+
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers } });
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The largest request body read, and the most messages one batch may carry (each runs in turn). */
|
|
81
|
+
export const MCP_MAX_BYTES = 1024 * 1024;
|
|
82
|
+
export const MCP_MAX_BATCH = 20;
|
|
83
|
+
|
|
84
|
+
/** The body as text, read up to `MCP_MAX_BYTES`: null past it, declared or not. */
|
|
85
|
+
async function boundedText(request: Request): Promise<string | null> {
|
|
86
|
+
const declared = Number(request.headers.get('content-length'));
|
|
87
|
+
if (Number.isFinite(declared) && declared > MCP_MAX_BYTES) return null;
|
|
88
|
+
if (!request.body) return '';
|
|
89
|
+
const reader = request.body.getReader();
|
|
90
|
+
const chunks: Uint8Array[] = [];
|
|
91
|
+
let size = 0;
|
|
92
|
+
for (;;) {
|
|
93
|
+
const { done, value } = await reader.read();
|
|
94
|
+
if (done) break;
|
|
95
|
+
size += value.byteLength;
|
|
96
|
+
if (size > MCP_MAX_BYTES) { await reader.cancel().catch(() => undefined); return null; }
|
|
97
|
+
chunks.push(value);
|
|
98
|
+
}
|
|
99
|
+
const body = new Uint8Array(size);
|
|
100
|
+
let at = 0;
|
|
101
|
+
for (const chunk of chunks) { body.set(chunk, at); at += chunk.byteLength; }
|
|
102
|
+
return new TextDecoder().decode(body);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export async function handleMcp<C>(request: Request, options: McpServerOptions<C>): Promise<Response> {
|
|
106
|
+
if (request.method !== 'POST') {
|
|
107
|
+
return json(failure(null, INVALID_REQUEST, request.method === 'GET' ? 'This server opens no streams: send JSON-RPC requests with POST.' : 'This server keeps no sessions.'), 405, { allow: 'POST' });
|
|
108
|
+
}
|
|
109
|
+
const text = await boundedText(request);
|
|
110
|
+
if (text === null) return json(failure(null, INVALID_REQUEST, `The request is larger than ${MCP_MAX_BYTES / 1024 / 1024} MiB.`), 413);
|
|
111
|
+
let parsed: unknown;
|
|
112
|
+
try { parsed = JSON.parse(text); }
|
|
113
|
+
catch { return json(failure(null, PARSE_ERROR, 'The body is not JSON.'), 400); }
|
|
114
|
+
const batch = Array.isArray(parsed);
|
|
115
|
+
const messages = (batch ? parsed : [parsed]) as unknown[];
|
|
116
|
+
if (!messages.length) return json(failure(null, INVALID_REQUEST, 'An empty batch.'), 400);
|
|
117
|
+
if (messages.length > MCP_MAX_BATCH) return json(failure(null, INVALID_REQUEST, `A batch carries at most ${MCP_MAX_BATCH} messages.`), 400);
|
|
118
|
+
const answers: unknown[] = [];
|
|
119
|
+
for (const message of messages) {
|
|
120
|
+
const reply = await handleMessage(message, options);
|
|
121
|
+
if (reply !== undefined) answers.push(reply);
|
|
122
|
+
}
|
|
123
|
+
if (!answers.length) return new Response(null, { status: 202 });
|
|
124
|
+
return json(batch ? answers : answers[0]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function handleMessage<C>(raw: unknown, options: McpServerOptions<C>): Promise<unknown> {
|
|
128
|
+
const message = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Message : null;
|
|
129
|
+
if (!message || message.jsonrpc !== '2.0') return failure(idOf(message), INVALID_REQUEST, 'Send JSON-RPC 2.0 messages.');
|
|
130
|
+
// A client's response to a server request: this server sends none.
|
|
131
|
+
if (message.method === undefined) return undefined;
|
|
132
|
+
if (typeof message.method !== 'string') return failure(idOf(message), INVALID_REQUEST, 'method is a string.');
|
|
133
|
+
const notification = message.id === undefined;
|
|
134
|
+
const id = idOf(message);
|
|
135
|
+
const params = message.params && typeof message.params === 'object' && !Array.isArray(message.params) ? message.params as { [name: string]: unknown } : {};
|
|
136
|
+
if (notification) return undefined;
|
|
137
|
+
switch (message.method) {
|
|
138
|
+
case 'initialize': {
|
|
139
|
+
const requested = typeof params.protocolVersion === 'string' ? params.protocolVersion : '';
|
|
140
|
+
return {
|
|
141
|
+
jsonrpc: '2.0', id, result: {
|
|
142
|
+
protocolVersion: MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : MCP_PROTOCOL_VERSIONS[0],
|
|
143
|
+
capabilities: { tools: { listChanged: false } },
|
|
144
|
+
serverInfo: { name: options.name, version: options.version },
|
|
145
|
+
...(options.instructions ? { instructions: options.instructions } : {}),
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
case 'ping': return { jsonrpc: '2.0', id, result: {} };
|
|
150
|
+
case 'tools/list': return { jsonrpc: '2.0', id, result: { tools: listedTools(options).map(tool => ({
|
|
151
|
+
name: tool.name, ...(tool.title ? { title: tool.title } : {}), description: tool.description, inputSchema: tool.inputSchema, annotations: tool.annotations,
|
|
152
|
+
})) } };
|
|
153
|
+
case 'tools/call': return callTool(id, params, options);
|
|
154
|
+
default: return failure(id, METHOD_NOT_FOUND, `Unknown method ${message.method}.`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function idOf(message: Message | null): Id {
|
|
159
|
+
return message && (typeof message.id === 'string' || typeof message.id === 'number') ? message.id : null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function listedTools<C>(options: McpServerOptions<C>): readonly McpTool<C>[] {
|
|
163
|
+
return options.readOnly ? options.tools.filter(tool => tool.annotations.readOnlyHint) : options.tools;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function callTool<C>(id: Id, params: { [name: string]: unknown }, options: McpServerOptions<C>): Promise<unknown> {
|
|
167
|
+
const name = typeof params.name === 'string' ? params.name : '';
|
|
168
|
+
const tool = options.tools.find(entry => entry.name === name);
|
|
169
|
+
if (!tool) return failure(id, INVALID_PARAMS, `Unknown tool ${name || '(none)'}.`);
|
|
170
|
+
if (options.readOnly && !tool.annotations.readOnlyHint) return failure(id, INVALID_PARAMS, 'This application password can only read.');
|
|
171
|
+
const input = params.arguments === undefined ? {} : params.arguments;
|
|
172
|
+
const problem = validateInput(tool.inputSchema, input);
|
|
173
|
+
if (problem) return failure(id, INVALID_PARAMS, `Invalid arguments for ${name}: ${problem}`);
|
|
174
|
+
try {
|
|
175
|
+
const result = await tool.run(input as { [name: string]: unknown }, options.context);
|
|
176
|
+
const structured = result === undefined ? { ok: true } : result;
|
|
177
|
+
return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(structured) }], ...(structured && typeof structured === 'object' && !Array.isArray(structured) ? { structuredContent: structured } : {}), isError: false } };
|
|
178
|
+
} catch (error) {
|
|
179
|
+
const known = options.toolError?.(error) ?? null;
|
|
180
|
+
if (!known) {
|
|
181
|
+
console.error('[cms] an MCP tool failed', error);
|
|
182
|
+
return failure(id, INTERNAL_ERROR, 'The tool failed.');
|
|
183
|
+
}
|
|
184
|
+
return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: known.message }], ...(known.data === undefined ? {} : { structuredContent: known.data }), isError: true } };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Why the input does not fit the schema, or null. Checks presence, primitive types, enums and declared nested objects; the operations check values. */
|
|
189
|
+
export function validateInput(schema: JsonSchemaProperty, input: unknown, path = 'arguments'): string | null {
|
|
190
|
+
if (schema.type === 'object' || schema.properties) {
|
|
191
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) return `${path} is an object.`;
|
|
192
|
+
const record = input as { [name: string]: unknown };
|
|
193
|
+
const properties = schema.properties ?? {};
|
|
194
|
+
for (const name of (schema as JsonSchema).required ?? []) {
|
|
195
|
+
if (record[name] === undefined) return `${name} is required.`;
|
|
196
|
+
}
|
|
197
|
+
for (const [name, value] of Object.entries(record)) {
|
|
198
|
+
if (value === undefined) continue;
|
|
199
|
+
const property = properties[name];
|
|
200
|
+
if (!property) {
|
|
201
|
+
if (schema.additionalProperties === false) return `${name} is not an argument.`;
|
|
202
|
+
if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
|
|
203
|
+
const problem = validateInput(schema.additionalProperties, value, `${path}.${name}`);
|
|
204
|
+
if (problem) return problem;
|
|
205
|
+
}
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const problem = validateInput(property, value, name);
|
|
209
|
+
if (problem) return problem;
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
const types = schema.type === undefined ? [] : Array.isArray(schema.type) ? schema.type : [schema.type];
|
|
214
|
+
if (types.length && !types.some(type => matches(type, input))) return `${path} is ${types.map(article).join(' or ')}.`;
|
|
215
|
+
if (schema.enum && !schema.enum.includes(input as string)) return `${path} is one of ${schema.enum.join(', ')}.`;
|
|
216
|
+
if (typeof input === 'number') {
|
|
217
|
+
if (schema.minimum !== undefined && input < schema.minimum) return `${path} is at least ${schema.minimum}.`;
|
|
218
|
+
if (schema.maximum !== undefined && input > schema.maximum) return `${path} is at most ${schema.maximum}.`;
|
|
219
|
+
}
|
|
220
|
+
if (Array.isArray(input) && schema.items) {
|
|
221
|
+
for (const [index, item] of input.entries()) {
|
|
222
|
+
const problem = validateInput(schema.items, item, `${path}[${index}]`);
|
|
223
|
+
if (problem) return problem;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function matches(type: JsonSchemaType, value: unknown): boolean {
|
|
230
|
+
switch (type) {
|
|
231
|
+
case 'string': return typeof value === 'string';
|
|
232
|
+
case 'number': return typeof value === 'number' && Number.isFinite(value);
|
|
233
|
+
case 'integer': return typeof value === 'number' && Number.isInteger(value);
|
|
234
|
+
case 'boolean': return typeof value === 'boolean';
|
|
235
|
+
case 'array': return Array.isArray(value);
|
|
236
|
+
case 'object': return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function article(type: JsonSchemaType): string {
|
|
241
|
+
return type === 'integer' || type === 'object' || type === 'array' ? `an ${type}` : `a ${type}`;
|
|
242
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A media chooser for screens that edit blocks outside the entry editor: Appearance → Widgets
|
|
3
|
+
* and the editor on the public site. Client-safe. The screen keeps the state and finds files
|
|
4
|
+
* on the server; uploads go through `uploadFile`.
|
|
5
|
+
*/
|
|
6
|
+
import { component, html, type TemplateResult } from '@cossackframework/renderer';
|
|
7
|
+
import { Button, Modal, Input, NativeSelect } from '@cossackframework/ui';
|
|
8
|
+
import { mediaKind } from '@cossackframework/cms';
|
|
9
|
+
import type { MediaPreview } from './field-controls';
|
|
10
|
+
import { notice } from './ui';
|
|
11
|
+
|
|
12
|
+
export interface MediaChooserState {
|
|
13
|
+
open: boolean;
|
|
14
|
+
/** The field the chosen file goes to. */
|
|
15
|
+
field: string;
|
|
16
|
+
multiple: boolean;
|
|
17
|
+
search: string;
|
|
18
|
+
/** The kind of file listed (`image`, `video`, …), empty for every kind; a field's first kind when it opens. */
|
|
19
|
+
kind: string;
|
|
20
|
+
items: MediaPreview[];
|
|
21
|
+
/** The file input's accept list; media files by default. */
|
|
22
|
+
accept?: string;
|
|
23
|
+
/** Why an upload failed, shown in the chooser; cleared when it opens. */
|
|
24
|
+
error?: string;
|
|
25
|
+
canUpload?: boolean;
|
|
26
|
+
/** The chooser normally accepts several uploads; scalar file settings use one. */
|
|
27
|
+
uploadMultiple?: boolean;
|
|
28
|
+
busy?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The kinds of file the chooser can list, in its menu's order. */
|
|
32
|
+
export const MEDIA_KIND_CHOICES: readonly { value: string; label: string }[] = [
|
|
33
|
+
{ value: '', label: 'All files' }, { value: 'image', label: 'Images' }, { value: 'video', label: 'Video' }, { value: 'audio', label: 'Audio' },
|
|
34
|
+
{ value: 'document', label: 'Documents' }, { value: 'archive', label: 'Archives' },
|
|
35
|
+
];
|
|
36
|
+
|
|
37
|
+
/** The kind a chooser opens on for a field: the first it declares, images when it declares none. */
|
|
38
|
+
export function chooserKind(field: { readonly kinds: readonly string[] } | null | undefined): string {
|
|
39
|
+
return field?.kinds[0] ?? 'image';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Images, video and audio: what a media field takes. The library's own uploader takes any file. */
|
|
43
|
+
export const MEDIA_ACCEPT = 'image/*,video/*,audio/*';
|
|
44
|
+
|
|
45
|
+
export const closedChooser = (): MediaChooserState => ({ open: false, field: '', multiple: false, search: '', kind: 'image', items: [] });
|
|
46
|
+
|
|
47
|
+
export interface MediaChooserHandlers {
|
|
48
|
+
search(text: string): void;
|
|
49
|
+
/** List another kind of file; the screen sets `kind` and searches again. */
|
|
50
|
+
filter(kind: string): void;
|
|
51
|
+
choose(file: MediaPreview): void;
|
|
52
|
+
/** Upload files from the file input; the chooser lists them afterwards. */
|
|
53
|
+
upload(event: Event): void;
|
|
54
|
+
close(): void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function mediaChooser(state: MediaChooserState, handlers: MediaChooserHandlers): TemplateResult {
|
|
58
|
+
return component(Modal, { open: state.open, size: 'max-w-3xl', 'aria-label': __('Choose media'), onOpenChange: (open: boolean) => { if (!open) handlers.close(); } }, html`
|
|
59
|
+
<div class="space-y-4">
|
|
60
|
+
<div class="flex items-center justify-between gap-3">
|
|
61
|
+
<div role="heading" aria-level="2" class="text-lg font-semibold text-foreground">${__('Choose media')}</div>
|
|
62
|
+
${component(Button, { type: 'button', variant: 'ghost', size: 'sm', '@click': () => handlers.close() }, state.multiple ? __('Done') : __('Close'))}
|
|
63
|
+
</div>
|
|
64
|
+
<div class="flex flex-wrap items-center gap-2">
|
|
65
|
+
${component(Input, { type: 'search', class: 'max-w-xs', placeholder: __('Search media'), 'aria-label': __('Search media'), '.value': state.search,
|
|
66
|
+
'@change': (event: Event) => handlers.search((event.target as HTMLInputElement).value) })}
|
|
67
|
+
${component(NativeSelect, { inline: true, 'aria-label': __('Media type'), '@change': (event: Event) => handlers.filter((event.target as HTMLSelectElement).value) }, html`
|
|
68
|
+
${MEDIA_KIND_CHOICES.map(choice => html`<option value=${choice.value} ?selected=${choice.value === state.kind}>${__(choice.label)}</option>`)}`)}
|
|
69
|
+
${state.canUpload === false ? null : html`<label class="inline-flex cursor-pointer items-center rounded-md border border-border px-3 py-2 text-sm text-foreground hover:bg-muted">
|
|
70
|
+
${state.busy ? __('Uploading…') : state.uploadMultiple === false ? __('Upload file') : __('Upload files')}<input type="file" ?multiple=${state.uploadMultiple !== false} accept=${state.accept ?? MEDIA_ACCEPT} class="sr-only" ?disabled=${!!state.busy} @change=${(event: Event) => handlers.upload(event)}>
|
|
71
|
+
</label>`}
|
|
72
|
+
</div>
|
|
73
|
+
${state.error ? notice(state.error, 'error') : null}
|
|
74
|
+
<ul class="grid max-h-[60vh] grid-cols-2 gap-3 overflow-y-auto sm:grid-cols-4">
|
|
75
|
+
${state.items.map(file => html`<li>
|
|
76
|
+
<button type="button" class="w-full overflow-hidden rounded-md border border-border bg-muted p-0 text-left hover:ring-2 hover:ring-ring cursor-pointer" @click=${() => handlers.choose(file)}>
|
|
77
|
+
${mediaKind(file.contentType) === 'image' ? html`<img src=${file.url} alt=${file.alt} class="aspect-square w-full object-cover" loading="lazy">`
|
|
78
|
+
: html`<span class="flex aspect-square items-center justify-center p-2 text-xs text-muted-foreground">${file.title}</span>`}
|
|
79
|
+
<span class="block truncate bg-card px-2 py-1 text-xs text-foreground">${file.title}</span>
|
|
80
|
+
</button>
|
|
81
|
+
</li>`)}
|
|
82
|
+
</ul>
|
|
83
|
+
${state.items.length ? null : html`<p class="text-sm text-muted-foreground">${__('No media found. Upload files to add them.')}</p>`}
|
|
84
|
+
</div>`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Upload one file from the browser, of any size: begin the upload, PUT the bytes where the
|
|
89
|
+
* server says (the bucket itself, or this application), then complete it. Throws with a
|
|
90
|
+
* message people can read.
|
|
91
|
+
*/
|
|
92
|
+
export async function uploadFile(file: File, signal?: AbortSignal): Promise<MediaPreview> {
|
|
93
|
+
const failed = async (response: Response, fallback: string) => {
|
|
94
|
+
const result = await response.json().catch(() => ({})) as { error?: string };
|
|
95
|
+
return new Error(`${file.name}: ${result.error ?? fallback}`);
|
|
96
|
+
};
|
|
97
|
+
const began = await fetch('/api/cms/uploads', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: file.name, type: file.type, size: file.size }), signal });
|
|
98
|
+
if (!began.ok) throw await failed(began, __('the upload could not start.'));
|
|
99
|
+
const target = await began.json() as { id: string; url: string; method: string; headers: Record<string, string>; direct: boolean };
|
|
100
|
+
const sent = await fetch(target.url, { method: target.method, headers: target.headers, body: file, credentials: target.direct ? 'omit' : 'same-origin', signal });
|
|
101
|
+
if (!sent.ok) throw target.direct ? new Error(`${file.name}: ${__('the storage service refused the upload.')}`) : await failed(sent, __('the upload failed.'));
|
|
102
|
+
const completed = await fetch(`/api/cms/uploads/${target.id}/complete`, { method: 'POST', signal });
|
|
103
|
+
if (!completed.ok) throw await failed(completed, __('the upload failed.'));
|
|
104
|
+
return (await completed.json() as { file: MediaPreview }).file;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Upload the files of a file input to the library; returns the new files' previews and an error, if any. */
|
|
108
|
+
export async function uploadMedia(input: HTMLInputElement): Promise<{ files: MediaPreview[]; error: string }> {
|
|
109
|
+
const files: MediaPreview[] = [];
|
|
110
|
+
let error = '';
|
|
111
|
+
for (const file of [...(input.files ?? [])]) {
|
|
112
|
+
try { files.push(await uploadFile(file)); }
|
|
113
|
+
catch (failure) { error = (failure as Error).message || __('The upload failed.'); }
|
|
114
|
+
}
|
|
115
|
+
input.value = '';
|
|
116
|
+
return { files, error };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A chosen file added to a media value: replaced for one file, appended once for a list. */
|
|
120
|
+
export function withFile(value: unknown, id: string, multiple: boolean): unknown {
|
|
121
|
+
if (!multiple) return id;
|
|
122
|
+
return [...new Set([...(Array.isArray(value) ? value as string[] : []), id])];
|
|
123
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a media file is used: entries whose fields, rich text or blocks reference it, the
|
|
3
|
+
* themes' widget areas, and users whose profile picture or fields it is. Collections are document tables without an index on file IDs, so the
|
|
4
|
+
* newest entries of each are read and checked here; very large sites see the newest matches.
|
|
5
|
+
*/
|
|
6
|
+
import { blockMedia, hasPermission, PERMISSIONS, richTextMedia, type Block, type FieldDeclaration, type Principal, type RichTextDoc } from '@cossackframework/cms';
|
|
7
|
+
import type { CmsHost } from '@cossackframework/cms/server';
|
|
8
|
+
import { recordTitle } from '@cossackframework/cms';
|
|
9
|
+
|
|
10
|
+
export interface MediaUse { title: string; href: string; kind: string; status: string }
|
|
11
|
+
|
|
12
|
+
/** Entries read per collection. */
|
|
13
|
+
const SCAN = 400;
|
|
14
|
+
|
|
15
|
+
/** Whether a record's fields reference the file. */
|
|
16
|
+
function uses(record: { readonly [field: string]: unknown }, fields: { readonly [name: string]: FieldDeclaration }, id: string, types: CmsHost['blockTypes']): boolean {
|
|
17
|
+
for (const [name, declaration] of Object.entries(fields)) {
|
|
18
|
+
const value = record[name];
|
|
19
|
+
if (value === undefined || value === null) continue;
|
|
20
|
+
if (declaration.media && (value === id || (Array.isArray(value) && value.includes(id)))) return true;
|
|
21
|
+
if (declaration.kind === 'richtext' && richTextMedia(value as RichTextDoc).includes(id)) return true;
|
|
22
|
+
if (declaration.kind === 'blocks' && Array.isArray(value) && blocksUse(value as Block[], id, types)) return true;
|
|
23
|
+
if (declaration.kind === 'json' && name === 'seo' && (value as { image?: unknown }).image === id) return true;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Blocks reference the file through their media fields or the rich text inside them. */
|
|
29
|
+
function blocksUse(blocks: readonly Block[], id: string, types: CmsHost['blockTypes']): boolean {
|
|
30
|
+
if (blockMedia(blocks, types).includes(id)) return true;
|
|
31
|
+
const visit = (list: readonly Block[]): boolean => list.some(block => Object.entries(types.get(block.type)?.fields ?? {})
|
|
32
|
+
.some(([name, declaration]) => declaration.kind === 'richtext' && richTextMedia(block.data[name] as RichTextDoc).includes(id)) || visit(block.children ?? []));
|
|
33
|
+
return visit(blocks);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function mediaUsage(cms: CmsHost, id: string, principal: Principal): Promise<MediaUse[]> {
|
|
37
|
+
const found: MediaUse[] = [];
|
|
38
|
+
for (const collection of cms.collections()) {
|
|
39
|
+
const resource = cms.resourceById(`cms/${collection.name}`);
|
|
40
|
+
const page = await cms.resource(resource.id).list({ limit: SCAN, ...(collection.publishable === false ? {} : { where: { status: { ne: 'trash' } } }) }, { principal }).catch(() => ({ records: [] }));
|
|
41
|
+
for (const record of page.records) {
|
|
42
|
+
if (!uses(record, resource.fields, id, cms.blockTypes)) continue;
|
|
43
|
+
found.push({ title: recordTitle(record, resource.titleField), href: `/dashboard/content/${collection.name}/${record.id}`, kind: collection.singular, status: typeof record.status === 'string' ? record.status : '' });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
for (const [name, area] of await cms.areas.all().catch(() => new Map())) {
|
|
47
|
+
if (blocksUse(area.blocks as Block[], id, cms.blockTypes)) found.push({ title: name, href: '/dashboard/appearance/widgets', kind: __('Widget area'), status: '' });
|
|
48
|
+
}
|
|
49
|
+
// Profile pictures and user fields, for people who manage users.
|
|
50
|
+
if (hasPermission(principal, PERMISSIONS.manageUsers)) {
|
|
51
|
+
for (const user of await cms.users.usingFile(id).catch(() => [])) {
|
|
52
|
+
const avatar = user.avatar?.startsWith(`/media/${id}/`) === true;
|
|
53
|
+
found.push({ title: user.name || user.email, href: `/dashboard/users/${user.id}`, kind: avatar ? __('Profile picture') : __('User'), status: '' });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return found;
|
|
57
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import { getCookie } from 'hono/cookie';
|
|
3
|
+
import { enforceRateLimit, getClientIp, getSupportedLocales, LOCALE_COOKIE_NAME, setRequestLocale } from '@cossackframework/core';
|
|
4
|
+
import { ANONYMOUS, escapeHtml, hasPermission, PERMISSIONS, type Principal, DEFAULT_ICON_STYLE, isIconStyle } from '@cossackframework/cms';
|
|
5
|
+
import { MAIN, MAIN_SITE, networkSite, type SiteResolution } from '@cossackframework/cms/server';
|
|
6
|
+
import { cmsFor, networkFor, type CmsBindings } from './index';
|
|
7
|
+
import { handoff } from './handoff';
|
|
8
|
+
import { dashboardPalette } from '../dashboard/head';
|
|
9
|
+
import { runMaintenance } from './maintenance';
|
|
10
|
+
import { accountNeedsSecondFactor, secondFactorRequired, type PublicUser } from '../auth';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* For `createApp({ isPluginActive })`: a rendered plugin's pages, layouts and HTTP handlers
|
|
14
|
+
* answer only while the plugin is active (migrated and granted); otherwise they are not found,
|
|
15
|
+
* like an unknown URL. Before setup, or while the CMS is unavailable, no plugin route answers.
|
|
16
|
+
*/
|
|
17
|
+
export async function pluginRouteActive(plugin: string, c: Context): Promise<boolean> {
|
|
18
|
+
try { return await (c.get('cms') ?? cmsFor(c.env as CmsBindings)).pluginActive(plugin); }
|
|
19
|
+
catch { return false; }
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** When each site's maintenance last ran in this isolate, by database. */
|
|
23
|
+
const lastMaintenance = new Map<string, number>();
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Finds the site the request's host names and puts its CMS host on the context with current
|
|
27
|
+
* collection definitions, then delivers outbox events and webhooks after requests that wrote.
|
|
28
|
+
* Maintenance also runs at most once a minute for each site. A host no site claims gets a 404,
|
|
29
|
+
* an alias redirects to its site's primary domain, and an archived site shows only its dashboard.
|
|
30
|
+
*/
|
|
31
|
+
export const cmsMiddleware: MiddlewareHandler = async (c, next) => {
|
|
32
|
+
const network = networkFor(c.env as CmsBindings);
|
|
33
|
+
const url = new URL(c.req.url);
|
|
34
|
+
// Before setup the registry does not exist yet: the main site answers.
|
|
35
|
+
let found: SiteResolution = await network.resolve(url.host).catch(() => ({ kind: 'site', site: MAIN }));
|
|
36
|
+
// API clients name a site on the network host: `X-Cossack-Site: blog` (or `?site=blog` on the MCP
|
|
37
|
+
// endpoint) serves that site, so a tool need not reach the site's own address.
|
|
38
|
+
const requested = requestedSite(c, url);
|
|
39
|
+
if (requested && requested !== MAIN_SITE && found.kind === 'site' && found.site.id === MAIN_SITE) {
|
|
40
|
+
if (!(await network.enabled().catch(() => false))) return c.json({ error: 'The network is off: only the main site answers.', code: 'CMS_NOT_FOUND' }, 404);
|
|
41
|
+
const record = await network.sites.get(requested).catch(() => null);
|
|
42
|
+
if (!record || record.status === 'deleted' || record.status === 'creating') return c.json({ error: `No site with the ID ${requested}.`, code: 'CMS_NOT_FOUND' }, 404);
|
|
43
|
+
found = record.status === 'archived' ? { kind: 'archived', site: networkSite(record) } : { kind: 'site', site: networkSite(record) };
|
|
44
|
+
}
|
|
45
|
+
// Which site a domain serves, for the network's domain check; aliases answer before they redirect.
|
|
46
|
+
if (url.pathname === '/.well-known/cossack-site' && found.kind !== 'missing') {
|
|
47
|
+
return c.text(found.kind === 'redirect' ? found.site : found.site.id, 200, { 'cache-control': 'no-store' });
|
|
48
|
+
}
|
|
49
|
+
if (found.kind === 'missing') return c.text('No site at this address.', 404);
|
|
50
|
+
if (found.kind === 'redirect') {
|
|
51
|
+
url.hostname = found.host;
|
|
52
|
+
return c.redirect(url.toString(), 301);
|
|
53
|
+
}
|
|
54
|
+
if (found.kind === 'archived' && !/^\/(?:dashboard|auth)(?:\/|$)/.test(c.req.path)) {
|
|
55
|
+
return c.req.path.startsWith('/api/') ? c.json({ error: 'This site is archived.', code: 'CMS_UNAVAILABLE' }, 503) : c.text('This site is archived.', 503);
|
|
56
|
+
}
|
|
57
|
+
const cms = network.hostOf(found.site);
|
|
58
|
+
c.set('cms', cms);
|
|
59
|
+
c.set('site', found.site);
|
|
60
|
+
c.set('network', network);
|
|
61
|
+
c.set('principal', ANONYMOUS);
|
|
62
|
+
// Sign-in happens on the network host; other sites get their sessions through a handoff.
|
|
63
|
+
const routed = await handoff(c, network, found.site);
|
|
64
|
+
if (routed) return routed;
|
|
65
|
+
// Before setup the definition tables do not exist yet; built-in collections apply.
|
|
66
|
+
await cms.ready().catch(error => console.error('[cms] could not load collections', error));
|
|
67
|
+
// Settings → Interface: the style every icon of this request is drawn in (`iconStyle()` in
|
|
68
|
+
// cms/icons.ts reads it) and the dashboard's palettes (`dashboardHead()` in dashboard/head.ts).
|
|
69
|
+
const [style, palette, accent] = await Promise.all((['interface.iconStyle', 'interface.palette', 'interface.accent'] as const).map(key => cms.settings.get(key).catch(() => undefined)));
|
|
70
|
+
c.set('cms.iconStyle', isIconStyle(style) ? style : DEFAULT_ICON_STYLE);
|
|
71
|
+
c.set('cms.palette', dashboardPalette(palette, accent));
|
|
72
|
+
// Until a user picks a language (Profile → Dashboard language), the dashboard speaks the
|
|
73
|
+
// site's default one when a catalog has it. Site pages then switch to their content's language.
|
|
74
|
+
const supported = getSupportedLocales();
|
|
75
|
+
if (supported.length > 1 && !getCookie(c, LOCALE_COOKIE_NAME)) {
|
|
76
|
+
const main = (await cms.languages()).default;
|
|
77
|
+
if (supported.some(code => code.toLowerCase() === main.toLowerCase())) setRequestLocale(main);
|
|
78
|
+
}
|
|
79
|
+
const writes = cms.outboxWrites;
|
|
80
|
+
await next();
|
|
81
|
+
securityHeaders(c, url);
|
|
82
|
+
// The API answers for the site `X-Cossack-Site` names: a shared cache keeps one answer per site.
|
|
83
|
+
if (url.pathname.startsWith('/api/') && !/(^|,)\s*x-cossack-site\s*(,|$)/i.test(c.res.headers.get('vary') ?? '')) c.header('vary', 'X-Cossack-Site', { append: true });
|
|
84
|
+
const now = Date.now();
|
|
85
|
+
if (cms.outboxWrites !== writes) later(c, cms.outbox.dispatch({ limit: 10 }).then(() => cms.webhooks.dispatch({ limit: 10 })));
|
|
86
|
+
if (now - (lastMaintenance.get(found.site.database) ?? 0) > 60_000) {
|
|
87
|
+
lastMaintenance.set(found.site.database, now);
|
|
88
|
+
later(c, runMaintenance(cms, { warm: false }));
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Headers every response carries unless the route set its own: no MIME sniffing, a tight
|
|
94
|
+
* referrer, no framing by other sites (Live Edit frames the site from its own origin), and HSTS
|
|
95
|
+
* over https. A Content-Security-Policy is left to the deployment: pages inline their hydration
|
|
96
|
+
* state, so a policy needs the deployment's nonces or hashes.
|
|
97
|
+
*/
|
|
98
|
+
function securityHeaders(c: Context, url: URL): void {
|
|
99
|
+
const headers = c.res.headers;
|
|
100
|
+
if (!headers.has('x-content-type-options')) c.header('x-content-type-options', 'nosniff');
|
|
101
|
+
if (!headers.has('referrer-policy')) c.header('referrer-policy', 'strict-origin-when-cross-origin');
|
|
102
|
+
if (!headers.has('x-frame-options') && !headers.has('content-security-policy')) c.header('x-frame-options', 'SAMEORIGIN');
|
|
103
|
+
if (url.protocol === 'https:' && !headers.has('strict-transport-security')) c.header('strict-transport-security', 'max-age=31536000');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* After auth: the request principal is the signed-in user's, or anonymous. Under /api/, an
|
|
108
|
+
* application password (`Authorization: Bearer cms_…`) signs the request in instead; read-only
|
|
109
|
+
* passwords may only read, and token requests skip the session's same-origin checks.
|
|
110
|
+
*/
|
|
111
|
+
export const cmsPrincipal: MiddlewareHandler = async (c, next) => {
|
|
112
|
+
const user = c.get('user') as PublicUser | undefined;
|
|
113
|
+
let session = user?.principal as Principal | undefined;
|
|
114
|
+
// Staff that General settings require to use two-step sign-in act with their session only
|
|
115
|
+
// once they have a second factor. Until then the session is anonymous everywhere (the site,
|
|
116
|
+
// Live Edit, previews, server methods), so no page has to repeat the check; signing in and
|
|
117
|
+
// out stays open, the rest of the API refuses, and the dashboard guards send them to set one up.
|
|
118
|
+
if (session && !c.req.path.startsWith('/api/auth/') && await secondFactorRequired(user!, c).catch(() => true)) {
|
|
119
|
+
if (API_PATH.test(c.req.path) && !VISITOR_API.test(c.req.path)) return secondFactorRefusal(c);
|
|
120
|
+
session = undefined;
|
|
121
|
+
}
|
|
122
|
+
c.set('principal', session ?? ANONYMOUS);
|
|
123
|
+
const header = c.req.header('authorization') ?? '';
|
|
124
|
+
if (!user && /^Bearer cms_/i.test(header) && API_PATH.test(c.req.path)) {
|
|
125
|
+
const token = await c.get('cms').tokenPrincipal(header.slice(7).trim()).catch(() => null);
|
|
126
|
+
if (!token) return c.json({ error: 'The application password is not valid.', code: 'CMS_UNAUTHENTICATED' }, 401, { 'www-authenticate': 'Bearer' });
|
|
127
|
+
// An application password made before the requirement was turned on stops working too.
|
|
128
|
+
if (token.principal.kind === 'user' && await accountNeedsSecondFactor({ id: token.principal.id, principal: token.principal }).catch(() => true)) return secondFactorRefusal(c);
|
|
129
|
+
if (token.scope === 'read' && c.req.path !== MCP_PATH && !['GET', 'HEAD', 'OPTIONS'].includes(c.req.method)) return c.json({ error: 'This application password can only read.', code: 'CMS_FORBIDDEN' }, 403);
|
|
130
|
+
c.set('principal', token.principal);
|
|
131
|
+
c.set('cms.token', true);
|
|
132
|
+
c.set('cms.tokenScope', token.scope);
|
|
133
|
+
}
|
|
134
|
+
// Maintenance or coming-soon mode: visitors without dashboard access get a holding page with status 503; the dashboard, sign-in, the API and assets keep answering.
|
|
135
|
+
if (!HOLDING_EXEMPT.test(c.req.path) && !hasPermission(c.get('principal'), PERMISSIONS.dashboard)) {
|
|
136
|
+
const mode = await c.get('cms').settings.get('general.maintenance').catch(() => 'off') as 'off' | 'maintenance' | 'soon';
|
|
137
|
+
if (mode !== 'off') {
|
|
138
|
+
const settings = await c.get('cms').settings.all();
|
|
139
|
+
return c.html(holdingPage(mode, settings['general.siteTitle'], settings['general.maintenanceMessage']), 503, { 'retry-after': '3600', 'cache-control': 'private, no-store' });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (c.req.path === '/api' || c.req.path.startsWith('/api/')) {
|
|
143
|
+
// One budget per caller for the whole API, counted in the framework's rate-limit store (per isolate unless a shared store is configured).
|
|
144
|
+
const principal = c.get('principal');
|
|
145
|
+
const limited = await enforceRateLimit(c, 'cms-api', { window: 60_000, max: principal.kind === 'anonymous' ? API_LIMITS.anonymous : API_LIMITS.signedIn,
|
|
146
|
+
key: () => principal.kind === 'user' ? `user:${principal.id}` : `ip:${getClientIp(c)}`, message: 'Too many requests. Slow down and try again in a minute.' });
|
|
147
|
+
if (limited) return limited;
|
|
148
|
+
}
|
|
149
|
+
await next();
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const API_PATH = /^\/api(?:\/|$)/;
|
|
153
|
+
|
|
154
|
+
/** The API endpoints visitors use from the site (comments, forms, search, menus): staff still waiting to add a second factor use them as anyone does. */
|
|
155
|
+
const VISITOR_API = /^\/api\/cms\/(?:comments|search|recovery|payments\/webhook|menus\/[^/]+|forms\/[^/]+)\/?$/;
|
|
156
|
+
|
|
157
|
+
function secondFactorRefusal(c: Context) {
|
|
158
|
+
return c.json({ error: 'This site requires two-step sign-in: set it up under Profile → Security first.', code: 'CMS_SECOND_FACTOR_REQUIRED' }, 403);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Paths the holding page never covers: the dashboard, sign-in, the API, the framework's own routes, assets and media. */
|
|
162
|
+
const HOLDING_EXEMPT = /^\/(?:dashboard|auth|api|crpc|sse|assets|media|_cossack|\.well-known|favicon\.ico|manifest\.webmanifest|robots\.txt)(?:\/|$)/;
|
|
163
|
+
|
|
164
|
+
/** The holding page of maintenance and coming-soon mode: the site's title, the message, no script, no theme (the theme may be what is being worked on). */
|
|
165
|
+
export function holdingPage(mode: 'maintenance' | 'soon', title: string, message: string): string {
|
|
166
|
+
const esc = escapeHtml;
|
|
167
|
+
const heading = mode === 'soon' ? 'Coming soon' : 'Down for maintenance';
|
|
168
|
+
const text = message.trim() || (mode === 'soon' ? 'This site has not launched yet. Check back soon.' : 'This site is being worked on and will be back shortly.');
|
|
169
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${esc(heading)} · ${esc(title)}</title>`
|
|
170
|
+
+ '<style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;background:#f8fafc;color:#0f172a}main{max-width:36rem;padding:2rem;text-align:center}h1{font-size:1.75rem;margin:0 0 .5rem}p{margin:.5rem 0;white-space:pre-line;color:#475569}.site{font-size:.875rem;letter-spacing:.05em;text-transform:uppercase;color:#64748b}@media(prefers-color-scheme:dark){body{background:#0b1220;color:#e2e8f0}p{color:#94a3b8}}</style></head>'
|
|
171
|
+
+ `<body><main><p class="site">${esc(title)}</p><h1>${esc(heading)}</h1><p>${esc(text)}</p></main></body></html>`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** API requests per minute per caller: a signed-in user or application password, or an anonymous address. */
|
|
175
|
+
export const API_LIMITS = Object.freeze({ anonymous: 120, signedIn: 600 });
|
|
176
|
+
|
|
177
|
+
/** The site an API request names, if any: the `X-Cossack-Site` header, or `?site=` on the MCP endpoint, whose clients set a URL. */
|
|
178
|
+
function requestedSite(c: Context, url: URL): string | null {
|
|
179
|
+
if (!url.pathname.startsWith('/api/')) return null;
|
|
180
|
+
const named = c.req.header('x-cossack-site') ?? (url.pathname === MCP_PATH ? url.searchParams.get('site') : null);
|
|
181
|
+
return named && /^[a-z0-9][a-z0-9-]{0,62}$/.test(named) ? named : null;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The MCP endpoint checks read-only application passwords itself, per tool. */
|
|
185
|
+
export const MCP_PATH = '/api/cms/mcp';
|
|
186
|
+
|
|
187
|
+
declare module 'hono' {
|
|
188
|
+
interface ContextVariableMap {
|
|
189
|
+
/** The request signed in with an application password. */
|
|
190
|
+
'cms.token': boolean;
|
|
191
|
+
/** What that application password may do. */
|
|
192
|
+
'cms.tokenScope': 'read' | 'write';
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function later(c: Parameters<MiddlewareHandler>[0], work: Promise<unknown>): void {
|
|
197
|
+
const settled = work.catch(error => console.error('[cms] background work failed', error));
|
|
198
|
+
try { c.executionCtx.waitUntil(settled); } catch { /* Node keeps running the promise. */ }
|
|
199
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
// First, and before ../auth: this loads the CMS host and, through it, the page registry, whose
|
|
3
|
+
// API routes use `auth` when they load. Loading ../auth first would reach them half-way through it.
|
|
4
|
+
import { cmsMiddleware, cmsPrincipal } from './middleware';
|
|
5
|
+
import { auth } from '../auth';
|
|
6
|
+
import { authGuard } from '../middlewares/auth';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The CMS's global middleware, in the order it must run: the CMS host goes on the context
|
|
10
|
+
* before auth reads users from it, then the session, the principal and the sign-in guard.
|
|
11
|
+
* A project lists it in src/bootstrap/middlewares.ts and adds its own after it.
|
|
12
|
+
*/
|
|
13
|
+
export const cmsMiddlewares: MiddlewareHandler[] = [cmsMiddleware, auth.middleware, cmsPrincipal, authGuard];
|