@cossackframework/cms 0.0.0 → 0.9.2
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 +145 -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 +21 -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 +709 -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 +114 -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 +62 -0
- package/app/src/dashboard/avatar-field.ts +58 -0
- package/app/src/dashboard/bulk.ts +22 -0
- package/app/src/dashboard/head.ts +29 -0
- package/app/src/dashboard/icons.ts +15 -0
- package/app/src/dashboard/list-table.ts +28 -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 +18 -0
- package/app/src/dashboard/session-list.ts +98 -0
- package/app/src/dashboard/tabs.ts +2 -0
- package/app/src/dashboard/time-ago.ts +16 -0
- package/app/src/dashboard/types.ts +43 -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 +82 -0
- package/app/src/pages/auth/layout.ts +32 -0
- package/app/src/pages/auth/login/index.ts +205 -0
- package/app/src/pages/auth/magic/index.ts +68 -0
- package/app/src/pages/auth/register/index.ts +124 -0
- package/app/src/pages/auth/reset-password/index.ts +74 -0
- package/app/src/pages/auth/setup/index.ts +194 -0
- package/app/src/pages/auth/two-factor/index.ts +69 -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 +183 -0
- package/app/src/pages/dashboard/index.ts +214 -0
- package/app/src/pages/dashboard/layout.ts +227 -0
- package/app/src/pages/dashboard/profile/index.ts +211 -0
- package/app/src/pages/dashboard/profile/security/index.ts +249 -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 +114 -2
- 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,653 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A site's users and roles on relational host tables. Each user is a member: an account, with
|
|
3
|
+
* the account's name, email, avatar and status copied in, and the site's own roles, slug and
|
|
4
|
+
* profile fields. Sign-in and passwords are the account's. The account is a network account
|
|
5
|
+
* (see accounts.ts), or on an added site a site account, in the site's own database.
|
|
6
|
+
*/
|
|
7
|
+
import { ClientError, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
|
|
8
|
+
import { CmsError, isCmsError } from '../errors';
|
|
9
|
+
import { SYSTEM_META } from '../field-groups';
|
|
10
|
+
import { slugify } from '../fields';
|
|
11
|
+
import { holdsAll, NETWORK_ADMIN, userPrincipal, type Principal } from '../permissions';
|
|
12
|
+
import { parseMeta, type MetaCheck } from './taxonomies';
|
|
13
|
+
import { ACCOUNT_ID, normalizeEmail, type AccountProfile, type CmsAccount, type CmsAccounts } from './accounts';
|
|
14
|
+
import { MAIN_SITE } from './sites';
|
|
15
|
+
import { readByIds, readPaged } from './budget';
|
|
16
|
+
|
|
17
|
+
export interface CmsUser {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly email: string;
|
|
20
|
+
readonly name: string;
|
|
21
|
+
readonly avatar: string | null;
|
|
22
|
+
readonly status: 'active' | 'disabled';
|
|
23
|
+
/** Role IDs, such as `admin`. */
|
|
24
|
+
readonly roles: readonly string[];
|
|
25
|
+
/** Each role with its name and permissions, in ID order. */
|
|
26
|
+
readonly assignments: readonly { readonly id: string; readonly name: string; readonly permissions: readonly string[] }[];
|
|
27
|
+
/** Permissions of all roles together. */
|
|
28
|
+
readonly permissions: readonly string[];
|
|
29
|
+
readonly createdAt: number;
|
|
30
|
+
/** When the user last started a session on this site, or null when never. */
|
|
31
|
+
readonly lastSignInAt: number | null;
|
|
32
|
+
/** Values of the field groups attached to users, and the author profile (`AUTHOR_FIELDS`). */
|
|
33
|
+
readonly meta: { readonly [field: string]: unknown };
|
|
34
|
+
/** The author page's slug, such as `ada-lovelace`; null until the user is saved or `withSlugs` runs. */
|
|
35
|
+
readonly slug: string | null;
|
|
36
|
+
/** `site`: an account of this site only, in its database. `network`: a network account. */
|
|
37
|
+
readonly account: 'site' | 'network';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface CmsRole {
|
|
41
|
+
readonly id: string;
|
|
42
|
+
readonly name: string;
|
|
43
|
+
readonly permissions: readonly string[];
|
|
44
|
+
readonly createdAt: number;
|
|
45
|
+
/** Users holding the role, when listed. */
|
|
46
|
+
readonly userCount?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface UserPage {
|
|
50
|
+
readonly items: readonly CmsUser[];
|
|
51
|
+
readonly total: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const ID = ACCOUNT_ID;
|
|
55
|
+
const PERMISSION = /^(?:\*|[a-z][a-z0-9:/._*-]{0,127})$/;
|
|
56
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
57
|
+
const WRITE = { kind: 'cms.users', retryConflicts: 5 } as const;
|
|
58
|
+
|
|
59
|
+
/** `($p0, $p1, …)` with its parameters, for a bounded `IN` list. */
|
|
60
|
+
export function inList(prefix: string, values: readonly Value[]): { rql: string; params: { [key: string]: Value } } {
|
|
61
|
+
const params: { [key: string]: Value } = {};
|
|
62
|
+
values.forEach((value, index) => { params[`$${prefix}${index}`] = value; });
|
|
63
|
+
return { rql: `(${values.map((_, index) => `$${prefix}${index}`).join(', ')})`, params };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A LIKE pattern matching `text` anywhere, with `%`, `_` and `\` escaped. Use with `ESCAPE '\\'`. */
|
|
67
|
+
export function containsPattern(text: string): string {
|
|
68
|
+
return `%${text.toLowerCase().replace(/[\\%_]/g, character => `\\${character}`)}%`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The request user: a member whose account is active, with the principal it acts as. */
|
|
72
|
+
export type CmsMember = CmsUser & { readonly principal: Principal };
|
|
73
|
+
|
|
74
|
+
/** The most users one `getMany` reads, and so the page size of `after`. */
|
|
75
|
+
const USERS_PER_READ = 200;
|
|
76
|
+
|
|
77
|
+
export class CmsUsers {
|
|
78
|
+
readonly #db: RomeDB;
|
|
79
|
+
readonly #accounts: CmsAccounts;
|
|
80
|
+
readonly #siteAccounts: CmsAccounts | null;
|
|
81
|
+
readonly #site: string;
|
|
82
|
+
readonly #now: () => number;
|
|
83
|
+
readonly #checkMeta: MetaCheck | undefined;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `accounts` are the network's; `siteAccounts`, on an added site, its own. `site` is this
|
|
87
|
+
* site's ID in the network (default `main`), for the network's record of memberships.
|
|
88
|
+
*/
|
|
89
|
+
constructor(db: RomeDB, options: { accounts: CmsAccounts; siteAccounts?: CmsAccounts; site?: string; now?: () => number; checkMeta?: MetaCheck }) {
|
|
90
|
+
this.#db = db;
|
|
91
|
+
this.#accounts = options.accounts;
|
|
92
|
+
this.#siteAccounts = options.siteAccounts ?? null;
|
|
93
|
+
this.#site = options.site ?? MAIN_SITE;
|
|
94
|
+
this.#now = options.now ?? Date.now;
|
|
95
|
+
this.#checkMeta = options.checkMeta;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A new account that is a member of this site with these roles: a site account on an added
|
|
100
|
+
* site, unless `network` asks for a network account, and a network account on the main site.
|
|
101
|
+
*/
|
|
102
|
+
/**
|
|
103
|
+
* Create an account and its membership. With `approval`, the account starts disabled and waits
|
|
104
|
+
* for approval: its registrations row is written with its member row, so no failure leaves an
|
|
105
|
+
* active account that skipped approval, or a disabled one missing from the queue.
|
|
106
|
+
*/
|
|
107
|
+
async create(input: AccountProfile & { email: string; name: string; password?: string; roles?: readonly string[]; id?: string; meta?: unknown; networkRole?: typeof NETWORK_ADMIN; network?: boolean; status?: 'active' | 'disabled'; approval?: { verified: boolean } }): Promise<CmsUser> {
|
|
108
|
+
const meta = await this.#meta(input.meta, null);
|
|
109
|
+
for (const role of input.roles ?? []) if (!ID.test(role)) throw new CmsError('CMS_VALIDATION', `Invalid role ${role}.`);
|
|
110
|
+
const store = input.network || !this.#siteAccounts ? this.#accounts : this.#siteAccounts;
|
|
111
|
+
if (store === this.#siteAccounts && input.networkRole) throw new CmsError('CMS_VALIDATION', 'Network admins have network accounts.');
|
|
112
|
+
// Members' emails are unique on a site, whichever kind their account is.
|
|
113
|
+
if (await this.findByEmail(input.email).catch(() => null)) throw new CmsError('CMS_CONFLICT', 'An account with this email already exists.', { fields: { email: 'is taken.' } });
|
|
114
|
+
const { network: _network, approval, ...profile } = input;
|
|
115
|
+
const account = await store.create(approval ? { ...profile, status: 'disabled', held: true } : profile);
|
|
116
|
+
try { return await this.#join(account, input.roles ?? [], meta, store === this.#accounts, approval); }
|
|
117
|
+
catch (error) {
|
|
118
|
+
await store.delete(account.id).catch(() => undefined);
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Make an existing account a member of this site, with these roles. */
|
|
124
|
+
async addMember(accountId: string, options: { roles?: readonly string[]; meta?: unknown } = {}): Promise<CmsUser | null> {
|
|
125
|
+
const account = await this.#accounts.get(accountId);
|
|
126
|
+
if (!account) return null;
|
|
127
|
+
const existing = await this.get(accountId);
|
|
128
|
+
if (existing) return existing;
|
|
129
|
+
return this.#join(account, options.roles ?? [], await this.#meta(options.meta, null), true);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Copy the account in as a member with these roles. The network records the memberships of its own accounts. */
|
|
133
|
+
async #join(account: CmsAccount, roles: readonly string[], meta: { readonly [field: string]: unknown }, network: boolean, approval?: { verified: boolean }): Promise<CmsUser> {
|
|
134
|
+
const now = this.#now();
|
|
135
|
+
const slug = await this.#freeSlug(account.name, account.id);
|
|
136
|
+
try {
|
|
137
|
+
await this.#db.write([{
|
|
138
|
+
rql: 'INSERT INTO cms_users (id, email, name, avatar, status, created_at, updated_at, meta, slug) VALUES ($id, $email, $name, $avatar, $status, $now, $now, $meta, $slug)',
|
|
139
|
+
params: { $id: account.id, $email: account.email, $name: account.name, $avatar: account.avatar, $status: approval ? 'disabled' : account.status, $now: now, $meta: JSON.stringify(meta), $slug: slug },
|
|
140
|
+
}, ...roleStatements(account.id, roles),
|
|
141
|
+
...(approval ? [{ rql: 'INSERT INTO cms_registrations (user_id, verified, created_at) VALUES ($id, $verified, $now)', params: { $id: account.id, $verified: approval.verified ? 1 : 0, $now: now } }] : [])], WRITE);
|
|
142
|
+
} catch (error) { throw memberError(error); }
|
|
143
|
+
if (network) {
|
|
144
|
+
// Without the network's record of the membership the member row is an orphan that
|
|
145
|
+
// blocks the email: take it back out.
|
|
146
|
+
try { await this.#accounts.join(account.id, this.#site); }
|
|
147
|
+
catch (error) {
|
|
148
|
+
await this.#db.write([
|
|
149
|
+
{ rql: 'DELETE FROM cms_registrations WHERE user_id = $id', params: { $id: account.id } },
|
|
150
|
+
{ rql: 'DELETE FROM cms_user_roles WHERE user_id = $id', params: { $id: account.id } },
|
|
151
|
+
{ rql: 'DELETE FROM cms_users WHERE id = $id', params: { $id: account.id } },
|
|
152
|
+
], WRITE).catch(() => undefined);
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return (await this.get(account.id))!;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The meta to store: the field groups' check, or the input as given when users have no groups. */
|
|
160
|
+
async #meta(meta: unknown, previous: { readonly [field: string]: unknown } | null, principal?: Principal): Promise<{ readonly [field: string]: unknown }> {
|
|
161
|
+
if (this.#checkMeta) return this.#checkMeta(meta, previous, principal);
|
|
162
|
+
if (meta === undefined) return previous ?? {};
|
|
163
|
+
if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) throw new CmsError('CMS_VALIDATION', 'Meta must be an object of fields.', { fields: { meta: 'must be an object of fields.' } });
|
|
164
|
+
return { ...previous, ...(meta as { [field: string]: unknown }) };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async get(id: string): Promise<CmsUser | null> {
|
|
168
|
+
if (!ID.test(id)) return null;
|
|
169
|
+
return (await this.getMany([id])).get(id) ?? null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Users by ID, in reads that fit the result budget. Missing IDs are absent from the map. */
|
|
173
|
+
async getMany(ids: readonly string[]): Promise<Map<string, CmsUser>> {
|
|
174
|
+
const wanted = [...new Set(ids.filter(id => ID.test(id)))].slice(0, USERS_PER_READ);
|
|
175
|
+
if (!wanted.length) return new Map();
|
|
176
|
+
const list = inList('u', wanted);
|
|
177
|
+
// Profiles hold their meta (bio, links) and roles their permission lists: many may come in smaller reads.
|
|
178
|
+
// The users, which roles they hold, and those roles are read side by side, not one after another.
|
|
179
|
+
const [userRows, result, roleRows] = await Promise.all([
|
|
180
|
+
readByIds(this.#db, wanted, slice => {
|
|
181
|
+
const part = inList('u', slice);
|
|
182
|
+
return { rql: `SELECT id, email, name, avatar, status, created_at, last_sign_in_at, meta, slug FROM cms_users WHERE id IN ${part.rql}`, params: part.params };
|
|
183
|
+
}),
|
|
184
|
+
this.#db.read([
|
|
185
|
+
// network_admin comes from the account alone (resolve): a site role row of that name, as a crafted import could add, grants nothing.
|
|
186
|
+
{ rql: `SELECT user_id, role_id FROM cms_user_roles WHERE user_id IN ${list.rql} AND role_id <> $networkAdmin ORDER BY role_id`, params: { ...list.params, $networkAdmin: NETWORK_ADMIN } },
|
|
187
|
+
// On an added site, accounts in its own database are site accounts.
|
|
188
|
+
...(this.#siteAccounts ? [{ rql: `SELECT id FROM cms_accounts WHERE id IN ${list.rql}`, params: list.params }] : []),
|
|
189
|
+
]),
|
|
190
|
+
// Each role's permissions come once, not once per user who holds it.
|
|
191
|
+
readPaged(this.#db, (size, at) => ({
|
|
192
|
+
rql: `SELECT id, name, permissions FROM cms_roles WHERE id IN (SELECT role_id FROM cms_user_roles WHERE user_id IN ${list.rql} AND role_id <> $networkAdmin) ORDER BY id LIMIT $limit OFFSET $offset`,
|
|
193
|
+
params: { ...list.params, $networkAdmin: NETWORK_ADMIN, $limit: size, $offset: at },
|
|
194
|
+
}), 1000, 0),
|
|
195
|
+
]);
|
|
196
|
+
const local = new Set((result.results[1]?.rows ?? []).map(row => row[0] as string));
|
|
197
|
+
const pairs = result.results[0]!.rows.map(([user, role]) => [user as string, role as string] as const);
|
|
198
|
+
const byId = new Map(roleRows.map(([id, name, permissions]) => [id as string, Object.freeze({ id: id as string, name: name as string, permissions: Object.freeze(JSON.parse(permissions as string) as string[]) })]));
|
|
199
|
+
const roles = new Map<string, CmsUser['assignments'][number][]>();
|
|
200
|
+
for (const [user, role] of pairs) {
|
|
201
|
+
const assignment = byId.get(role);
|
|
202
|
+
if (!assignment) continue;
|
|
203
|
+
const entry = roles.get(user) ?? [];
|
|
204
|
+
entry.push(assignment);
|
|
205
|
+
roles.set(user, entry);
|
|
206
|
+
}
|
|
207
|
+
const users = new Map<string, CmsUser>();
|
|
208
|
+
for (const row of userRows) {
|
|
209
|
+
const assignments = roles.get(row[0] as string) ?? [];
|
|
210
|
+
users.set(row[0] as string, Object.freeze({
|
|
211
|
+
id: row[0] as string, email: row[1] as string, name: row[2] as string, avatar: row[3] as string | null,
|
|
212
|
+
status: row[4] as CmsUser['status'], createdAt: Number(row[5] as bigint), lastSignInAt: row[6] === null ? null : Number(row[6] as bigint), meta: parseMeta(row[7]), slug: (row[8] as string | null) ?? null,
|
|
213
|
+
roles: Object.freeze(assignments.map(role => role.id)), assignments: Object.freeze(assignments),
|
|
214
|
+
permissions: Object.freeze([...new Set(assignments.flatMap(role => role.permissions))].sort()),
|
|
215
|
+
account: local.has(row[0] as string) ? 'site' : 'network',
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
return users;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Users whose avatar is this media file or whose profile fields name it, newest first, 50 at most. */
|
|
222
|
+
async usingFile(fileId: string): Promise<CmsUser[]> {
|
|
223
|
+
if (!ID.test(fileId)) return [];
|
|
224
|
+
const escaped = fileId.replace(/[\\%_]/g, character => `\\${character}`);
|
|
225
|
+
const result = await this.#db.read([{
|
|
226
|
+
rql: "SELECT id FROM cms_users WHERE avatar LIKE $avatar ESCAPE '\\' OR meta LIKE $meta ESCAPE '\\' ORDER BY created_at DESC LIMIT 50",
|
|
227
|
+
params: { $avatar: `/media/${escaped}/%`, $meta: `%"${escaped}"%` },
|
|
228
|
+
}]);
|
|
229
|
+
const ids = result.results[0]!.rows.map(row => row[0] as string);
|
|
230
|
+
const users = await this.getMany(ids);
|
|
231
|
+
return ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async findByEmail(email: string): Promise<CmsUser | null> {
|
|
235
|
+
const result = await this.#db.read([{ rql: 'SELECT id FROM cms_users WHERE email = $email', params: { $email: normalizeEmail(email) } }]);
|
|
236
|
+
const id = result.results[0]!.rows[0]?.[0] as string | undefined;
|
|
237
|
+
return id ? this.get(id) : null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Every user, by ID, a page after the cursor of the one before: for work that goes through them
|
|
242
|
+
* all. `next` is the last ID read (null once there are no more), so a page whose rows don't all
|
|
243
|
+
* resolve to a user still moves on.
|
|
244
|
+
*/
|
|
245
|
+
async after(after: string | null, limit = 100): Promise<{ users: CmsUser[]; next: string | null }> {
|
|
246
|
+
const size = Math.min(Math.max(limit, 1), USERS_PER_READ);
|
|
247
|
+
const result = await this.#db.read([{
|
|
248
|
+
rql: `SELECT id FROM cms_users${after === null ? '' : ' WHERE id > $after'} ORDER BY id LIMIT $limit`,
|
|
249
|
+
params: { ...(after === null ? {} : { $after: after }), $limit: size },
|
|
250
|
+
}]);
|
|
251
|
+
const ids = result.results[0]!.rows.map(row => row[0] as string);
|
|
252
|
+
const users = await this.getMany(ids);
|
|
253
|
+
return {
|
|
254
|
+
users: ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined),
|
|
255
|
+
next: ids.length === size ? ids[ids.length - 1]! : null,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Newest first. `search` matches name or email; `role` limits to one role ID. */
|
|
260
|
+
async list(options: { search?: string; role?: string; limit?: number; offset?: number } = {}): Promise<UserPage> {
|
|
261
|
+
const limit = Math.min(Math.max(options.limit ?? 20, 1), 100);
|
|
262
|
+
const offset = Math.min(Math.max(options.offset ?? 0, 0), 100_000);
|
|
263
|
+
const conditions: string[] = [];
|
|
264
|
+
const params: { [key: string]: Value } = {};
|
|
265
|
+
if (options.search?.trim()) {
|
|
266
|
+
conditions.push("(lower(name) LIKE $q ESCAPE '\\' OR email LIKE $q ESCAPE '\\')");
|
|
267
|
+
params.$q = containsPattern(options.search.trim().slice(0, 100));
|
|
268
|
+
}
|
|
269
|
+
if (options.role) {
|
|
270
|
+
conditions.push('id IN (SELECT user_id FROM cms_user_roles WHERE role_id = $role)');
|
|
271
|
+
params.$role = options.role;
|
|
272
|
+
}
|
|
273
|
+
const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
|
|
274
|
+
const result = await this.#db.read([
|
|
275
|
+
{ rql: `SELECT id FROM cms_users${where} ORDER BY created_at DESC, id DESC LIMIT $limit OFFSET $offset`, params: { ...params, $limit: limit, $offset: offset } },
|
|
276
|
+
conditions.length ? { rql: `SELECT count(*) FROM cms_users${where}`, params } : { rql: 'SELECT count(*) FROM cms_users' },
|
|
277
|
+
]);
|
|
278
|
+
const ids = result.results[0]!.rows.map(row => row[0] as string);
|
|
279
|
+
const users = await this.getMany(ids);
|
|
280
|
+
return { items: ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined), total: Number(result.results[1]!.rows[0]![0] as bigint) };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Change the name, email or avatar (on the account first, then the copy here), the profile
|
|
285
|
+
* meta or the author slug.
|
|
286
|
+
*/
|
|
287
|
+
async update(id: string, patch: AccountProfile & { meta?: unknown; slug?: string }, options: { principal?: Principal } = {}): Promise<boolean> {
|
|
288
|
+
const current = await this.get(id);
|
|
289
|
+
if (!current) return false;
|
|
290
|
+
const meta = patch.meta === undefined ? current.meta : await this.#meta(patch.meta, current.meta, options.principal);
|
|
291
|
+
const profile = patch.name !== undefined || patch.email !== undefined || patch.avatar !== undefined
|
|
292
|
+
? await this.#store(current).update(id, { ...(patch.name === undefined ? {} : { name: patch.name }), ...(patch.email === undefined ? {} : { email: patch.email }), ...(patch.avatar === undefined ? {} : { avatar: patch.avatar }) })
|
|
293
|
+
: current;
|
|
294
|
+
if (!profile) return false;
|
|
295
|
+
// A slug is chosen once, from the name, and kept: author URLs stay stable through renames. A given slug is checked and made unique.
|
|
296
|
+
const slug = patch.slug !== undefined ? await this.#freeSlug(patch.slug, id) : current.slug ?? await this.#freeSlug(profile.name, id);
|
|
297
|
+
try {
|
|
298
|
+
const result = await this.#db.write([{ rql: 'UPDATE cms_users SET name = $name, email = $email, avatar = $avatar, meta = $meta, slug = $slug, updated_at = $now WHERE id = $id',
|
|
299
|
+
params: { $name: profile.name, $email: profile.email, $avatar: profile.avatar, $meta: JSON.stringify(meta), $slug: slug, $now: this.#now(), $id: id } }], WRITE);
|
|
300
|
+
return result.results[0]!.affected === 1n;
|
|
301
|
+
} catch (error) { throw memberError(error); }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Keep a value of the host's own in the user's meta, such as `_recent_blocks`, beside the
|
|
306
|
+
* profile fields and without their checks; null removes it. False when there is no such user.
|
|
307
|
+
*/
|
|
308
|
+
async setSystemMeta(id: string, key: string, value: unknown): Promise<boolean> {
|
|
309
|
+
if (!SYSTEM_META.test(key)) throw new CmsError('CMS_VALIDATION', `${key} is not a system meta key.`);
|
|
310
|
+
const current = await this.get(id);
|
|
311
|
+
if (!current) return false;
|
|
312
|
+
const meta: { [field: string]: unknown } = { ...current.meta, [key]: value };
|
|
313
|
+
if (value === null || value === undefined) delete meta[key];
|
|
314
|
+
const json = JSON.stringify(meta);
|
|
315
|
+
if (json.length > 256 * 1024) throw new CmsError('CMS_LIMIT', 'The user\'s meta is too large.');
|
|
316
|
+
const result = await this.#db.write([{ rql: 'UPDATE cms_users SET meta = $meta WHERE id = $id', params: { $meta: json, $id: id } }], WRITE);
|
|
317
|
+
return result.results[0]!.affected === 1n;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** The user with this author slug, or null. */
|
|
321
|
+
async bySlug(slug: string): Promise<CmsUser | null> {
|
|
322
|
+
if (!SLUG.test(slug)) return null;
|
|
323
|
+
const result = await this.#db.read([{ rql: 'SELECT id FROM cms_users WHERE slug = $slug LIMIT 1', params: { $slug: slug } }]);
|
|
324
|
+
const id = result.results[0]!.rows[0]?.[0] as string | undefined;
|
|
325
|
+
return id ? this.get(id) : null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* These users with slugs: users from before author pages get one from their name, written
|
|
330
|
+
* once. For the site's pages, which link authors; dashboards read `slug` as is.
|
|
331
|
+
*/
|
|
332
|
+
async withSlugs(users: ReadonlyMap<string, CmsUser>): Promise<Map<string, CmsUser>> {
|
|
333
|
+
const result = new Map(users);
|
|
334
|
+
for (const [id, user] of users) {
|
|
335
|
+
if (user.slug) continue;
|
|
336
|
+
const slug = await this.#freeSlug(user.name, id);
|
|
337
|
+
await this.#db.write([{ rql: 'UPDATE cms_users SET slug = $slug WHERE id = $id AND slug IS NULL', params: { $slug: slug, $id: id } }], WRITE).catch(() => undefined);
|
|
338
|
+
result.set(id, Object.freeze({ ...user, slug }));
|
|
339
|
+
}
|
|
340
|
+
return result;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Users who own entries, for author sitemaps and lists: those with a slug, oldest first. */
|
|
344
|
+
async authors(options: { limit?: number; offset?: number } = {}): Promise<CmsUser[]> {
|
|
345
|
+
const limit = Math.min(Math.max(options.limit ?? 200, 1), 1000);
|
|
346
|
+
const result = await this.#db.read([{ rql: 'SELECT id FROM cms_users WHERE slug IS NOT NULL AND status = $active ORDER BY created_at, id LIMIT $limit OFFSET $offset', params: { $active: 'active', $limit: limit, $offset: Math.max(options.offset ?? 0, 0) } }]);
|
|
347
|
+
const ids = result.results[0]!.rows.map(row => row[0] as string);
|
|
348
|
+
const users = await this.getMany(ids);
|
|
349
|
+
return ids.map(id => users.get(id)).filter((user): user is CmsUser => user !== undefined);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** A slug from the text, made unique among users other than `id` by a numeric suffix. */
|
|
353
|
+
async #freeSlug(text: string, id: string): Promise<string> {
|
|
354
|
+
const base = slugify(String(text ?? ''), 60) || 'author';
|
|
355
|
+
const result = await this.#db.read([{ rql: "SELECT slug FROM cms_users WHERE id <> $id AND (slug = $slug OR slug LIKE $prefix ESCAPE '\\') LIMIT 1000", params: { $id: id, $slug: base, $prefix: `${base.replace(/[\\%_]/g, character => `\\${character}`)}-%` } }]);
|
|
356
|
+
const taken = new Set(result.results[0]!.rows.map(row => row[0] as string));
|
|
357
|
+
if (!taken.has(base)) return base;
|
|
358
|
+
for (let n = 2; n < 10_000; n++) if (!taken.has(`${base}-${n}`)) return `${base}-${n}`;
|
|
359
|
+
return `${base}-${crypto.randomUUID().slice(0, 8)}`;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Remove the member and their roles from this site. A network account stays, unless it was
|
|
364
|
+
* made for a registration turned down here; a site account is deleted with what signs it
|
|
365
|
+
* in. Their records keep their owner ID.
|
|
366
|
+
*/
|
|
367
|
+
async delete(id: string): Promise<boolean> {
|
|
368
|
+
if (!ID.test(id)) return false;
|
|
369
|
+
const user = await this.get(id);
|
|
370
|
+
const params = { $id: id };
|
|
371
|
+
const result = await this.#db.write([
|
|
372
|
+
{ rql: 'DELETE FROM cms_user_roles WHERE user_id = $id', params },
|
|
373
|
+
{ rql: 'DELETE FROM cms_users WHERE id = $id', params },
|
|
374
|
+
{ rql: 'DELETE FROM cms_registrations WHERE user_id = $id', params },
|
|
375
|
+
], WRITE);
|
|
376
|
+
if (user?.account === 'site') await this.#siteAccounts!.delete(id);
|
|
377
|
+
else {
|
|
378
|
+
await this.#accounts.leave(id, this.#site);
|
|
379
|
+
// A turned-down registration: the account was made for it, never used, and belongs to
|
|
380
|
+
// no other site, so it goes too, and the email can register again. The delete checks
|
|
381
|
+
// all of that itself, so a site adding the account meanwhile keeps it.
|
|
382
|
+
if (result.results[2]!.affected === 1n) await this.#accounts.deleteUnused(id);
|
|
383
|
+
}
|
|
384
|
+
return result.results[1]!.affected === 1n;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Whether a member waits for approval. */
|
|
388
|
+
async awaitingApproval(id: string): Promise<boolean> {
|
|
389
|
+
const result = await this.#db.read([{ rql: 'SELECT user_id FROM cms_registrations WHERE user_id = $id', params: { $id: id } }]);
|
|
390
|
+
return result.results[0]!.rows.length > 0;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** A held member opened their email link: they still wait for approval. */
|
|
394
|
+
async confirmRegistration(id: string): Promise<boolean> {
|
|
395
|
+
const result = await this.#db.write([{ rql: 'UPDATE cms_registrations SET verified = 1 WHERE user_id = $id', params: { $id: id } }], WRITE);
|
|
396
|
+
return result.results[0]!.affected === 1n;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Members waiting for approval, oldest first, with whether their email is confirmed. */
|
|
400
|
+
async registrations(options: { limit?: number } = {}): Promise<{ user: CmsUser; verified: boolean; createdAt: number }[]> {
|
|
401
|
+
const result = await this.#db.read([{ rql: 'SELECT user_id, verified, created_at FROM cms_registrations ORDER BY created_at, user_id LIMIT $limit', params: { $limit: Math.min(Math.max(options.limit ?? 50, 1), 200) } }]);
|
|
402
|
+
const rows = result.results[0]!.rows;
|
|
403
|
+
const users = await Promise.all(rows.map(([id]) => this.get(String(id))));
|
|
404
|
+
return rows.flatMap(([, verified, createdAt], index) => users[index] ? [{ user: users[index]!, verified: Number(verified as bigint) === 1, createdAt: Number(createdAt as bigint) }] : []);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** How many members wait for approval. */
|
|
408
|
+
async registrationCount(): Promise<number> {
|
|
409
|
+
const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_registrations' }]);
|
|
410
|
+
return Number(result.results[0]!.rows[0]![0] as bigint);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Approve a held member: their account is active, once their email is confirmed. False when
|
|
415
|
+
* they were not waiting; `CMS_VALIDATION` while their email link was not opened yet.
|
|
416
|
+
*/
|
|
417
|
+
async approve(id: string): Promise<boolean> {
|
|
418
|
+
const result = await this.#db.read([{ rql: 'SELECT verified FROM cms_registrations WHERE user_id = $id', params: { $id: id } }]);
|
|
419
|
+
const row = result.results[0]!.rows[0];
|
|
420
|
+
if (!row) return false;
|
|
421
|
+
if (Number(row[0] as bigint) !== 1) throw new CmsError('CMS_VALIDATION', 'This member has not confirmed their email address yet.');
|
|
422
|
+
// Active first, then out of the queue: a failure between the two leaves the member
|
|
423
|
+
// waiting, and approving again finishes it.
|
|
424
|
+
if (!(await this.setStatus(id, 'active'))) return false;
|
|
425
|
+
await this.#db.write([{ rql: 'DELETE FROM cms_registrations WHERE user_id = $id', params: { $id: id } }], WRITE);
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Make a member's site account a network account, or a network account a site account of
|
|
431
|
+
* this site, under the same ID: roles, profile and authorship stay. Only on an added site. A
|
|
432
|
+
* network account must belong to this site alone and not run the network. The account's
|
|
433
|
+
* sessions end, and its passkeys go with the host they were made on.
|
|
434
|
+
*/
|
|
435
|
+
async convert(id: string, to: 'site' | 'network'): Promise<CmsUser> {
|
|
436
|
+
if (!this.#siteAccounts) throw new CmsError('CMS_VALIDATION', 'Only added sites have site accounts.');
|
|
437
|
+
const user = await this.get(id);
|
|
438
|
+
if (!user) throw new CmsError('CMS_NOT_FOUND', 'There is no such member.');
|
|
439
|
+
if (to === 'network') {
|
|
440
|
+
if (user.account === 'site') {
|
|
441
|
+
try { await this.#siteAccounts.moveTo(this.#accounts, id, { site: this.#site }); }
|
|
442
|
+
catch (error) {
|
|
443
|
+
if (isCmsError(error, 'CMS_CONFLICT')) throw new CmsError('CMS_CONFLICT', 'A network account already has this email.', { fields: { email: 'is taken on the network.' } });
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
} else if (to === 'site') {
|
|
448
|
+
// Also finishes a move that copied the account here but did not delete it on the network.
|
|
449
|
+
const account = await this.#accounts.get(id);
|
|
450
|
+
if (account) {
|
|
451
|
+
if (account.networkRole) throw new CmsError('CMS_VALIDATION', 'Network admins keep network accounts.');
|
|
452
|
+
if (((await this.#accounts.memberships([id])).get(id) ?? []).some(site => site !== this.#site)) {
|
|
453
|
+
throw new CmsError('CMS_VALIDATION', 'The account belongs to other sites too. Remove it from them first.');
|
|
454
|
+
}
|
|
455
|
+
await this.#accounts.moveTo(this.#siteAccounts, id);
|
|
456
|
+
}
|
|
457
|
+
} else throw new CmsError('CMS_VALIDATION', 'Choose a site or network account.');
|
|
458
|
+
return (await this.get(id))!;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Replace a user's roles in one atomic batch. */
|
|
462
|
+
async setRoles(id: string, roles: readonly string[]): Promise<void> {
|
|
463
|
+
await this.#db.write([{ rql: 'DELETE FROM cms_user_roles WHERE user_id = $id', params: { $id: id } }, ...roleStatements(id, roles)], WRITE);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** Allow or stop the account's sign-in, and copy the status here. */
|
|
467
|
+
async setStatus(id: string, status: 'active' | 'disabled'): Promise<boolean> {
|
|
468
|
+
const user = await this.get(id);
|
|
469
|
+
if (!user || !(await this.#store(user).setStatus(id, status))) return false;
|
|
470
|
+
const result = await this.#db.write([{ rql: 'UPDATE cms_users SET status = $status, updated_at = $now WHERE id = $id', params: { $status: status, $now: this.#now(), $id: id } }], WRITE);
|
|
471
|
+
return result.results[0]!.affected === 1n;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Set the account's password. */
|
|
475
|
+
async setPassword(id: string, password: string): Promise<boolean> {
|
|
476
|
+
const user = await this.get(id);
|
|
477
|
+
return user !== null && this.#store(user).setPassword(id, password);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** The store of a member's account: this site's for a site account, the network's otherwise. */
|
|
481
|
+
#store(user: CmsUser): CmsAccounts {
|
|
482
|
+
return user.account === 'site' ? this.#siteAccounts! : this.#accounts;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
async count(): Promise<number> {
|
|
486
|
+
const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_users' }]);
|
|
487
|
+
return Number(result.results[0]!.rows[0]![0] as bigint);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* The member as the request user, or null unless their account is active. A network admin
|
|
492
|
+
* also acts with `*` and holds the `network_admin` role. A child session passes the network
|
|
493
|
+
* role it copied, so the account is not read: the network ends child sessions of an account
|
|
494
|
+
* it suspends.
|
|
495
|
+
*/
|
|
496
|
+
async resolve(id: string, session?: { networkRole: string | null }): Promise<CmsMember | null> {
|
|
497
|
+
const [user, account] = await Promise.all([this.get(id), session ? null : (async () => await this.#siteAccounts?.get(id) ?? await this.#accounts.get(id))()]);
|
|
498
|
+
if (!user || (!session && (!account || account.status !== 'active'))) return null;
|
|
499
|
+
const admin = (session ? session.networkRole : account!.networkRole) === NETWORK_ADMIN;
|
|
500
|
+
return Object.freeze({ ...user, principal: userPrincipal(user.id, admin ? [...user.roles, NETWORK_ADMIN] : user.roles, admin ? [...user.permissions, '*'] : user.permissions) });
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** The request principal for an active member, or null. */
|
|
504
|
+
async principal(id: string): Promise<Principal | null> {
|
|
505
|
+
return (await this.resolve(id))?.principal ?? null;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/** Create or replace a role by ID. */
|
|
509
|
+
async defineRole(role: { id: string; name: string; permissions: readonly string[] }): Promise<CmsRole> {
|
|
510
|
+
const permissions = checkRole(role);
|
|
511
|
+
await this.#db.write([{
|
|
512
|
+
rql: 'INSERT INTO cms_roles (id, name, permissions, created_at) VALUES ($id, $name, $permissions, $now) ON CONFLICT (id) DO UPDATE SET name = excluded.name, permissions = excluded.permissions',
|
|
513
|
+
params: { $id: role.id, $name: role.name.trim(), $permissions: JSON.stringify(permissions), $now: this.#now() },
|
|
514
|
+
}], WRITE);
|
|
515
|
+
return (await this.role(role.id))!;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* A new role; its ID is derived from the name when omitted. With an `actor`, the role may
|
|
520
|
+
* hold only permissions the actor holds, so a role manager cannot make a stronger role.
|
|
521
|
+
*/
|
|
522
|
+
async createRole(role: { name: string; permissions: readonly string[]; id?: string }, options: { actor?: Principal } = {}): Promise<CmsRole> {
|
|
523
|
+
const id = role.id ?? (slugify(role.name, 60) || crypto.randomUUID());
|
|
524
|
+
const permissions = checkRole({ ...role, id });
|
|
525
|
+
if (options.actor) checkGrant(options.actor, permissions);
|
|
526
|
+
try {
|
|
527
|
+
await this.#db.write([{ rql: 'INSERT INTO cms_roles (id, name, permissions, created_at) VALUES ($id, $name, $permissions, $now)',
|
|
528
|
+
params: { $id: id, $name: role.name.trim(), $permissions: JSON.stringify(permissions), $now: this.#now() } }], WRITE);
|
|
529
|
+
} catch (error) {
|
|
530
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|PRIMARY|constraint/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'A role with this name already exists.', { fields: { name: 'is taken.' } });
|
|
531
|
+
throw error;
|
|
532
|
+
}
|
|
533
|
+
return (await this.role(id))!;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Change a role's name or permissions. The administrator role stays as it is. With an
|
|
538
|
+
* `actor`, both the role as it is and as it becomes may hold only permissions the actor holds.
|
|
539
|
+
*/
|
|
540
|
+
async updateRole(id: string, patch: { name?: string; permissions?: readonly string[] }, options: { actor?: Principal } = {}): Promise<boolean> {
|
|
541
|
+
if (id === 'admin') throw new CmsError('CMS_FORBIDDEN', 'The administrator role cannot be changed.');
|
|
542
|
+
const read = await this.#storedRole(id);
|
|
543
|
+
if (!read) return false;
|
|
544
|
+
const { role: current, stored } = read;
|
|
545
|
+
const permissions = checkRole({ id, name: patch.name ?? current.name, permissions: patch.permissions ?? current.permissions });
|
|
546
|
+
if (options.actor) {
|
|
547
|
+
if (!holdsAll(options.actor, current.permissions)) throw new CmsError('CMS_FORBIDDEN', 'This role has permissions you do not have, so you cannot change it.');
|
|
548
|
+
checkGrant(options.actor, permissions);
|
|
549
|
+
}
|
|
550
|
+
try {
|
|
551
|
+
// Only over the permissions checked above: a role raised meanwhile is not overwritten.
|
|
552
|
+
const result = await this.#db.write([{ rql: 'UPDATE cms_roles SET name = $name, permissions = $permissions WHERE id = $id AND permissions = $previous',
|
|
553
|
+
params: { $id: id, $name: (patch.name ?? current.name).trim(), $permissions: JSON.stringify(permissions), $previous: stored } }], WRITE);
|
|
554
|
+
if (result.results[0]!.affected === 1n) return true;
|
|
555
|
+
if (await this.role(id)) throw new CmsError('CMS_CONFLICT', 'The role changed since it was read. Reload and try again.');
|
|
556
|
+
return false;
|
|
557
|
+
} catch (error) {
|
|
558
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|constraint/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'A role with this name already exists.', { fields: { name: 'is taken.' } });
|
|
559
|
+
throw error;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Remove a role and its assignments. The administrator role stays, and an actor deletes only roles within their own permissions. */
|
|
564
|
+
async deleteRole(id: string, options: { actor?: Principal } = {}): Promise<boolean> {
|
|
565
|
+
if (id === 'admin') throw new CmsError('CMS_FORBIDDEN', 'The administrator role cannot be deleted.');
|
|
566
|
+
let guard = '';
|
|
567
|
+
let params: { [key: string]: Value } = { $id: id };
|
|
568
|
+
if (options.actor) {
|
|
569
|
+
const read = await this.#storedRole(id);
|
|
570
|
+
if (!read) return false;
|
|
571
|
+
if (!holdsAll(options.actor, read.role.permissions)) throw new CmsError('CMS_FORBIDDEN', 'This role has permissions you do not have, so you cannot delete it.');
|
|
572
|
+
// Only the role as checked: one raised meanwhile stays.
|
|
573
|
+
guard = ' AND EXISTS (SELECT 1 FROM cms_roles WHERE id = $id AND permissions = $previous)';
|
|
574
|
+
params = { $id: id, $previous: read.stored };
|
|
575
|
+
}
|
|
576
|
+
const result = await this.#db.write([
|
|
577
|
+
{ rql: `DELETE FROM cms_user_roles WHERE role_id = $id${guard}`, params },
|
|
578
|
+
{ rql: `DELETE FROM cms_roles WHERE id = $id${guard ? ' AND permissions = $previous' : ''}`, params },
|
|
579
|
+
], WRITE);
|
|
580
|
+
if (result.results[1]!.affected === 1n) return true;
|
|
581
|
+
if (guard && await this.role(id)) throw new CmsError('CMS_CONFLICT', 'The role changed since it was read. Reload and try again.');
|
|
582
|
+
return false;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** The role and its permissions as stored, for a write guarded on them. */
|
|
586
|
+
async #storedRole(id: string): Promise<{ role: CmsRole; stored: string } | null> {
|
|
587
|
+
if (!ID.test(id)) return null;
|
|
588
|
+
const result = await this.#db.read([{ rql: 'SELECT id, name, permissions, created_at FROM cms_roles WHERE id = $id', params: { $id: id } }]);
|
|
589
|
+
const row = result.results[0]!.rows[0];
|
|
590
|
+
return row ? { role: roleOf(row), stored: row[2] as string } : null;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async role(id: string): Promise<CmsRole | null> {
|
|
594
|
+
if (!ID.test(id)) return null;
|
|
595
|
+
const result = await this.#db.read([{ rql: 'SELECT id, name, permissions, created_at FROM cms_roles WHERE id = $id', params: { $id: id } }]);
|
|
596
|
+
const row = result.results[0]!.rows[0];
|
|
597
|
+
return row ? roleOf(row) : null;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Roles in creation order, each with its user count. */
|
|
601
|
+
async roles(options: { search?: string; limit?: number; offset?: number } = {}): Promise<CmsRole[]> {
|
|
602
|
+
const params: { [key: string]: Value } = {};
|
|
603
|
+
let where = '';
|
|
604
|
+
if (options.search?.trim()) { where = " WHERE lower(r.name) LIKE $q ESCAPE '\\'"; params.$q = containsPattern(options.search.trim().slice(0, 100)); }
|
|
605
|
+
// Roles hold their permission lists: many roles may come in smaller reads.
|
|
606
|
+
const rows = await readPaged(this.#db, (limit, offset) => ({
|
|
607
|
+
rql: `SELECT r.id, r.name, r.permissions, r.created_at, (SELECT count(*) FROM cms_user_roles ur WHERE ur.role_id = r.id) FROM cms_roles r${where} ORDER BY r.created_at, r.id LIMIT $limit OFFSET $offset`,
|
|
608
|
+
params: { ...params, $limit: limit, $offset: offset },
|
|
609
|
+
}), Math.min(Math.max(options.limit ?? 200, 1), 200), Math.max(options.offset ?? 0, 0));
|
|
610
|
+
return rows.map(row => ({ ...roleOf(row), userCount: Number(row[4] as bigint) }));
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
async countRoles(options: { search?: string } = {}): Promise<number> {
|
|
614
|
+
const result = await this.#db.read([options.search?.trim()
|
|
615
|
+
? { rql: "SELECT count(*) FROM cms_roles WHERE lower(name) LIKE $q ESCAPE '\\'", params: { $q: containsPattern(options.search.trim().slice(0, 100)) } }
|
|
616
|
+
: { rql: 'SELECT count(*) FROM cms_roles' }]);
|
|
617
|
+
return Number(result.results[0]!.rows[0]![0] as bigint);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function roleOf(row: readonly Value[]): CmsRole {
|
|
622
|
+
return { id: row[0] as string, name: row[1] as string, permissions: JSON.parse(row[2] as string) as string[], createdAt: Number(row[3] as bigint) };
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function roleStatements(userId: string, roles: readonly string[]): Statement[] {
|
|
626
|
+
return [...new Set(roles)].map(role => {
|
|
627
|
+
if (!ID.test(role)) throw new CmsError('CMS_VALIDATION', `Invalid role ${role}.`);
|
|
628
|
+
// Insert only roles that exist; the caller checks the outcome through get().
|
|
629
|
+
return { rql: 'INSERT INTO cms_user_roles (user_id, role_id) SELECT $user, id FROM cms_roles WHERE id = $role', params: { $user: userId, $role: role } as { [key: string]: Value } };
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** A role manager gives only permissions they hold. */
|
|
634
|
+
function checkGrant(actor: Principal, permissions: readonly string[]): void {
|
|
635
|
+
const missing = permissions.filter(permission => !holdsAll(actor, [permission]));
|
|
636
|
+
if (missing.length) throw new CmsError('CMS_FORBIDDEN', `You cannot give a role permissions you do not have: ${missing.join(', ')}.`, { fields: { permissions: 'include permissions you do not have.' } });
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function checkRole(role: { id: string; name: string; permissions: readonly string[] }): string[] {
|
|
640
|
+
if (!ID.test(role.id) || typeof role.name !== 'string' || !role.name.trim() || role.name.length > 80) throw new CmsError('CMS_VALIDATION', 'Enter a role name of at most 80 characters.', { fields: { name: 'is required.' } });
|
|
641
|
+
if (role.id === NETWORK_ADMIN) throw new CmsError('CMS_VALIDATION', 'network_admin is the network\'s role; choose another name.', { fields: { name: 'is reserved.' } });
|
|
642
|
+
const invalid = role.permissions.filter(permission => !PERMISSION.test(permission));
|
|
643
|
+
if (invalid.length) throw new CmsError('CMS_VALIDATION', `Unknown permission ${invalid.join(', ')}.`, { fields: { permissions: 'are invalid.' } });
|
|
644
|
+
return [...new Set(role.permissions)].sort();
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function memberError(error: unknown): unknown {
|
|
648
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE/i.test(error.message)) return new CmsError('CMS_CONFLICT', 'A user with this email already exists.', { fields: { email: 'is taken.' } });
|
|
649
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back' && /FOREIGN|role/i.test(error.message)) return new CmsError('CMS_VALIDATION', 'Unknown role.');
|
|
650
|
+
return error;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
export { normalizeEmail };
|