@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
package/app/src/auth.ts
ADDED
|
@@ -0,0 +1,1082 @@
|
|
|
1
|
+
// src/auth.ts
|
|
2
|
+
//
|
|
3
|
+
// Authentication on the CMS. Users, roles, sessions and reset tokens live in RomeDB host
|
|
4
|
+
// tables; the auth library owns password hashing, credential verification, session expiry,
|
|
5
|
+
// rotation and cookies. This module exports the same functions as the database variant, so
|
|
6
|
+
// the auth and dashboard pages are shared between both.
|
|
7
|
+
|
|
8
|
+
import { getCookie } from 'hono/cookie';
|
|
9
|
+
import type { Context } from 'hono';
|
|
10
|
+
import { createAuth, createOAuth, createSessionManager, OAuthError, totpUri, type AuthSessionRecord, type OAuthKit, type OAuthUser, type TokenSet } from '@cossackframework/auth';
|
|
11
|
+
import {
|
|
12
|
+
passkeyAuthenticationOptions, passkeyRegistrationOptions, verifyPasskeyAuthentication, verifyPasskeyRegistration,
|
|
13
|
+
type AuthenticationResponseJSON, type PasskeyConfig, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON, type RegistrationResponseJSON,
|
|
14
|
+
} from '@cossackframework/auth/passkeys';
|
|
15
|
+
import { ClientVisibleError, getClientIp, getRequestContext } from '@cossackframework/core';
|
|
16
|
+
import { ANONYMOUS, hasPermission, holdsAll, isCmsError, isNetworkAdmin, PERMISSIONS, type Principal } from '@cossackframework/cms';
|
|
17
|
+
import { MAIN_SITE, networkSite, randomToken, RESET_REQUESTS, sha256Hex, type ApiToken, type CmsHost, type CmsMember, type SecurityStatus as AccountSecurity } from '@cossackframework/cms/server';
|
|
18
|
+
import { renderSVG } from 'uqr';
|
|
19
|
+
import { currentCms, networkFor, type CmsBindings } from './cms/index';
|
|
20
|
+
import { handoffSite, pendingSite } from './cms/handoff';
|
|
21
|
+
import { mailOrigin } from './cms/seo';
|
|
22
|
+
|
|
23
|
+
const SESSION_COOKIE = 'session_id';
|
|
24
|
+
const SESSION_TTL_SECONDS = 60 * 60 * 24 * 7; // 7 days
|
|
25
|
+
|
|
26
|
+
// --- Types -----------------------------------------------------------------
|
|
27
|
+
export interface RoleAssignment {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
permissions: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The safe user shape exposed to pages (`this.user`). */
|
|
34
|
+
export interface PublicUser {
|
|
35
|
+
id: string;
|
|
36
|
+
email: string;
|
|
37
|
+
name: string;
|
|
38
|
+
avatar: string | null;
|
|
39
|
+
meta: Record<string, unknown> | null;
|
|
40
|
+
roles: RoleAssignment[];
|
|
41
|
+
/** What this user may do in the CMS, for repositories and permission checks. */
|
|
42
|
+
principal: Principal;
|
|
43
|
+
/** Set by `registerUser` when the account waits for the email's confirmation link instead of signing in. */
|
|
44
|
+
verification?: 'sent';
|
|
45
|
+
/** The account waits for an administrator's approval before it can sign in. */
|
|
46
|
+
approval?: 'pending';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
declare module '@cossackframework/core' {
|
|
50
|
+
interface User {
|
|
51
|
+
id: string;
|
|
52
|
+
email: string;
|
|
53
|
+
name: string;
|
|
54
|
+
avatar: string | null;
|
|
55
|
+
meta: Record<string, unknown> | null;
|
|
56
|
+
roles: RoleAssignment[];
|
|
57
|
+
principal: Principal;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The host on the given context, or the current request's. */
|
|
62
|
+
function cms(c?: Context): CmsHost {
|
|
63
|
+
return (c?.get('cms') as CmsHost | undefined) ?? currentCms();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function publicUser(user: CmsMember): PublicUser {
|
|
67
|
+
return {
|
|
68
|
+
id: user.id, email: user.email, name: user.name, avatar: user.avatar, meta: null,
|
|
69
|
+
roles: user.assignments.map(role => ({ id: role.id, name: role.name, permissions: [...role.permissions] })),
|
|
70
|
+
principal: user.principal,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The member a signed-in account acts as on this site, or null when it is not one or is
|
|
76
|
+
* disabled. On a site other than the main one, the child session's network role stands in for
|
|
77
|
+
* the account, so the request reads only the site's database.
|
|
78
|
+
*/
|
|
79
|
+
async function member(id: string, c?: Context): Promise<PublicUser | null> {
|
|
80
|
+
const context = c ?? getRequestContext();
|
|
81
|
+
const child = context?.get('site')?.id !== MAIN_SITE ? context?.get('cms.networkRole') : undefined;
|
|
82
|
+
const user = await cms(c).users.resolve(id, child === undefined ? undefined : { networkRole: child });
|
|
83
|
+
return user ? publicUser(user) : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// --- Sessions --------------------------------------------------------------
|
|
87
|
+
export const authSessions = createSessionManager({
|
|
88
|
+
ttlSeconds: SESSION_TTL_SECONDS,
|
|
89
|
+
cookie: { name: SESSION_COOKIE },
|
|
90
|
+
store: {
|
|
91
|
+
create: (record, c) => {
|
|
92
|
+
// A handoff in progress makes the session a child of the network session.
|
|
93
|
+
const child = (c as Context).get('cms.child');
|
|
94
|
+
// createSession() says whether this sign-in used a second factor; a child session copies its network session's.
|
|
95
|
+
const secondFactor = (c as Context).get('cms.signInSecondFactor') === true;
|
|
96
|
+
// Every sign-in ends here, whatever its method: plugins hear of it through cms.user.signed-in,
|
|
97
|
+
// queued in the session's own write.
|
|
98
|
+
return (async () => {
|
|
99
|
+
const host = cms(c);
|
|
100
|
+
const user = await host.users.get(record.userId).catch(() => null);
|
|
101
|
+
const also = user ? [await host.userSignedInStatement(user, record.id)] : [];
|
|
102
|
+
const result = child ? await host.authSessions.createChild(record, child, c, { also }) : await host.authSessions.create(record, c, { secondFactor, also });
|
|
103
|
+
if (also.length) host.outboxWritten();
|
|
104
|
+
return result;
|
|
105
|
+
})();
|
|
106
|
+
},
|
|
107
|
+
read: async (id, c) => {
|
|
108
|
+
const session = await cms(c).authSessions.read(id, c);
|
|
109
|
+
if (session?.parentId) (c as Context).set('cms.networkRole', session.networkRole);
|
|
110
|
+
if (session) (c as Context).set('cms.sessionSecondFactor', session.secondFactor);
|
|
111
|
+
return session;
|
|
112
|
+
},
|
|
113
|
+
replace: (expected: AuthSessionRecord, replacement: AuthSessionRecord, now: number, c) => cms(c).authSessions.replace(expected, replacement, now, c),
|
|
114
|
+
revoke: (id, c) => cms(c).authSessions.revoke(id, c),
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
async function sessionFingerprint(token: string): Promise<string> {
|
|
119
|
+
const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token)));
|
|
120
|
+
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const auth = createAuth<PublicUser>({
|
|
124
|
+
realtime: {
|
|
125
|
+
key: 'cossack.session',
|
|
126
|
+
async capture(sessionId, _userId, c) {
|
|
127
|
+
// The public reference survives rotation; the fingerprint does not.
|
|
128
|
+
const reference = await cms(c).authSessions.publicReference(sessionId);
|
|
129
|
+
if (!reference) throw new Error('Session ended before subscription.');
|
|
130
|
+
return { reference, fingerprint: await sessionFingerprint(sessionId) };
|
|
131
|
+
},
|
|
132
|
+
async validate(data, c) {
|
|
133
|
+
const { reference, fingerprint } = (data ?? {}) as { reference?: unknown; fingerprint?: unknown };
|
|
134
|
+
if (typeof reference !== 'string' || typeof fingerprint !== 'string' || !/^[0-9a-f]{64}$/.test(fingerprint)) return null;
|
|
135
|
+
const row = await cms(c).authSessions.findByReference(reference);
|
|
136
|
+
if (!row || row.expiresAt <= Date.now() || await sessionFingerprint(row.id) !== fingerprint) return null;
|
|
137
|
+
c.set('cms.sessionSecondFactor', row.secondFactor);
|
|
138
|
+
return row.userId;
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
extractSessionId: c => getCookie(c, SESSION_COOKIE),
|
|
142
|
+
// Before setup the session table does not exist; the auth kit then treats the visitor as a guest.
|
|
143
|
+
validateSessionId: async (sessionId, c) => (await authSessions.validate(sessionId, c))?.userId ?? null,
|
|
144
|
+
resolveUserById: (userId, c) => member(userId, c),
|
|
145
|
+
createSession: async (user, c) => authSessions.create(user.id, c),
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Start a session for a sign-in, recording whether it used a second factor (an authenticator or
|
|
150
|
+
* recovery code, or a passkey). Required two-step sign-in asks that of the session: a session
|
|
151
|
+
* signed in with a password alone stays limited even after its account gains a factor.
|
|
152
|
+
*/
|
|
153
|
+
export async function createSession(userId: string, c: Context, options: { secondFactor?: boolean } = {}) {
|
|
154
|
+
c.set('cms.signInSecondFactor', options.secondFactor === true);
|
|
155
|
+
try { return await authSessions.create(userId, c); }
|
|
156
|
+
finally { c.set('cms.signInSecondFactor', false); }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
declare module 'hono' {
|
|
160
|
+
interface ContextVariableMap {
|
|
161
|
+
/** Set by createSession() for the session it is about to store. */
|
|
162
|
+
'cms.signInSecondFactor': boolean;
|
|
163
|
+
/** Whether the request's session was signed in with a second factor. */
|
|
164
|
+
'cms.sessionSecondFactor': boolean;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// --- Credentials -----------------------------------------------------------
|
|
169
|
+
/**
|
|
170
|
+
* Email and password sign in this host's accounts: network accounts on the main site, the
|
|
171
|
+
* site's own accounts on an added site. Network accounts reach an added site through the
|
|
172
|
+
* network's sign-in (`/auth/handoff`).
|
|
173
|
+
*/
|
|
174
|
+
export async function loginUser(email: string, password: string, address = clientAddress()): Promise<PublicUser | null> {
|
|
175
|
+
const host = cms();
|
|
176
|
+
// The attempt is counted before the password is checked, so guesses sent at once meet the limit too.
|
|
177
|
+
const allowed = await host.security.signInBegin(email, address);
|
|
178
|
+
if (!allowed.ok) throw new SignInLockedError(allowed.retryAfterMs);
|
|
179
|
+
const account = await host.signIn.accounts.verifier.verify(email, password);
|
|
180
|
+
if (!account) {
|
|
181
|
+
// The verifier signs in active accounts only. One that waits for approval hears so, once its password is right.
|
|
182
|
+
const waiting = await host.signIn.accounts.disabledWithPassword(email, password).catch(() => null);
|
|
183
|
+
if (waiting && await host.users.awaitingApproval(waiting.id).catch(() => false)) {
|
|
184
|
+
await host.security.signInSucceeded(email, address);
|
|
185
|
+
throw new SignInPendingError();
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
await host.security.signInSucceeded(email, address);
|
|
190
|
+
if (account.status !== 'active') return null;
|
|
191
|
+
return member(account.id);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Too many wrong passwords for the email or from the address: the sign-in is refused for a while. */
|
|
195
|
+
export class SignInLockedError extends ClientVisibleError {
|
|
196
|
+
readonly retryAfterMs: number;
|
|
197
|
+
constructor(retryAfterMs: number) {
|
|
198
|
+
super(`Too many sign-in attempts. Try again in ${Math.max(1, Math.ceil(retryAfterMs / 60_000))} minutes.`);
|
|
199
|
+
this.name = 'SignInLockedError';
|
|
200
|
+
this.retryAfterMs = retryAfterMs;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The password matched an account that waits for an administrator's approval. */
|
|
205
|
+
export class SignInPendingError extends ClientVisibleError {
|
|
206
|
+
constructor() {
|
|
207
|
+
super('Your account waits for an administrator to approve it. We will email you when it is ready.');
|
|
208
|
+
this.name = 'SignInPendingError';
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Two-step sign-in is required (Settings → General) and the account's only second factor is a
|
|
214
|
+
* passkey: a password or an email link alone is one step, so the account signs in with its passkey.
|
|
215
|
+
*/
|
|
216
|
+
export class SignInPasskeyError extends ClientVisibleError {
|
|
217
|
+
constructor() {
|
|
218
|
+
super('Two-step sign-in is required, and this account\'s second step is its passkey. Sign in with your passkey.');
|
|
219
|
+
this.name = 'SignInPasskeyError';
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** The client's address for sign-in and reset counters: the proxy header the deployment trusts, else the socket's. */
|
|
224
|
+
function clientAddress(): string {
|
|
225
|
+
const c = getRequestContext();
|
|
226
|
+
return c ? getClientIp(c) : 'unknown';
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Wrong current passwords an account may give within the window before checks stop. */
|
|
230
|
+
const PASSWORD_CHECKS = { max: 10, windowMs: 15 * 60_000 };
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Whether this is the user's current password, before they change it: their site account's, or
|
|
234
|
+
* their network account's. Wrong answers are counted per account, so an open session cannot
|
|
235
|
+
* guess its way to the password (and from there the email or the account).
|
|
236
|
+
*/
|
|
237
|
+
export async function passwordMatches(userId: string, password: string): Promise<boolean> {
|
|
238
|
+
const host = cms();
|
|
239
|
+
if (!(await host.security.attempt('password-check', userId, PASSWORD_CHECKS.max, PASSWORD_CHECKS.windowMs))) {
|
|
240
|
+
throw new ClientVisibleError('Too many wrong passwords. Wait a few minutes, then try again.');
|
|
241
|
+
}
|
|
242
|
+
const { accounts } = await host.storesOf(userId);
|
|
243
|
+
const account = await accounts.get(userId);
|
|
244
|
+
const matches = !!account && (await accounts.verifier.verify(account.email, password))?.id === userId;
|
|
245
|
+
// Only wrong passwords count against the account.
|
|
246
|
+
if (matches) await host.security.release('password-check', userId).catch(() => undefined);
|
|
247
|
+
return matches;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** What others see on an added site instead of a network account's profile, password and sign-in methods. */
|
|
251
|
+
export const NETWORK_ACCOUNT_LOCKED = 'A network account: its name, email, password and sign-in methods change on the network, by the person or a network admin. This site manages its roles.';
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Whether the request's user may change this account's profile, password, second factors,
|
|
255
|
+
* application passwords, status and membership here. On an added site a network account is the
|
|
256
|
+
* person's or a network admin's to change; on the main site, theirs, a network admin's, or one who
|
|
257
|
+
* holds every permission the account has on each of its sites. The dashboard's user permissions
|
|
258
|
+
* govern the rest.
|
|
259
|
+
*/
|
|
260
|
+
export async function manageableHere(userId: string): Promise<boolean> {
|
|
261
|
+
const host = cms();
|
|
262
|
+
const request = getRequestContext();
|
|
263
|
+
// The signed-in person's own account, read from the session: until they add a second factor
|
|
264
|
+
// that General settings require, their request principal is anonymous, yet adding one is theirs to do.
|
|
265
|
+
if ((request?.get('user') as PublicUser | undefined)?.id === userId) return true;
|
|
266
|
+
const principal = (request?.get('principal') as Principal | undefined) ?? ANONYMOUS;
|
|
267
|
+
if (principal.kind === 'user' && (principal.id === userId || isNetworkAdmin(principal))) return true;
|
|
268
|
+
if (host.siteAccounts) return (await host.users.get(userId))?.account !== 'network';
|
|
269
|
+
// On the main site the account signs in everywhere: whoever changes it must hold every
|
|
270
|
+
// permission it holds on each site it belongs to, or setting its password takes those sites too.
|
|
271
|
+
return request ? heldOnEverySite(networkFor(request.env as CmsBindings), principal, userId) : true;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Every site the account belongs to counts, whatever its status and whether the network is on:
|
|
276
|
+
* a site switched off, archived or deleted (until purged) can come back with the account still
|
|
277
|
+
* its member. A site that cannot be read makes the account unmanageable here.
|
|
278
|
+
*/
|
|
279
|
+
async function heldOnEverySite(network: ReturnType<typeof networkFor>, principal: Principal, userId: string): Promise<boolean> {
|
|
280
|
+
try {
|
|
281
|
+
const ids = ((await network.main.accounts.memberships([userId])).get(userId) ?? []).filter(id => id !== MAIN_SITE);
|
|
282
|
+
if (!ids.length) return true;
|
|
283
|
+
const records = new Map((await network.sites.getMany(ids)).map(record => [record.id, record]));
|
|
284
|
+
for (const id of ids) {
|
|
285
|
+
const record = records.get(id);
|
|
286
|
+
// A purged site has no record and no database left.
|
|
287
|
+
if (!record) continue;
|
|
288
|
+
const member = await network.hostOf(networkSite(record)).users.get(userId);
|
|
289
|
+
if (member && !holdsAll(principal, member.permissions)) return false;
|
|
290
|
+
}
|
|
291
|
+
return true;
|
|
292
|
+
} catch { return false; }
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function requireManageable(userId: string): Promise<void> {
|
|
296
|
+
if (!(await manageableHere(userId))) throw new ClientVisibleError(NETWORK_ACCOUNT_LOCKED);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Whether visitors may create accounts: the "Anyone can register" setting. */
|
|
300
|
+
export async function registrationOpen(): Promise<boolean> {
|
|
301
|
+
const c = getRequestContext();
|
|
302
|
+
const host = (c ? await handoffSite(c, networkFor(c.env as CmsBindings)) : null) ?? cms();
|
|
303
|
+
return (await host.installed()) && await host.settings.get('general.usersCanRegister');
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* True until an active network admin exists: a fresh install, or a site's database taking over
|
|
308
|
+
* as its own install. /auth/login sends visitors to /auth/setup then.
|
|
309
|
+
*/
|
|
310
|
+
export async function setupRequired(): Promise<boolean> {
|
|
311
|
+
const host = cms();
|
|
312
|
+
try { return !(await host.installed()) || !(await host.accounts.hasNetworkAdmin()); }
|
|
313
|
+
catch { return true; }
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* A new account, with the site's default role. On an added site it is a site account. On the
|
|
318
|
+
* network host for another site (the visitor came from its network sign-in) it is a network
|
|
319
|
+
* account, a member of that site only. `cms.user.before-register` filters may refuse it, change
|
|
320
|
+
* its roles or hold it for approval; Settings → General may ask for both the email's
|
|
321
|
+
* confirmation and an administrator's approval, in that order.
|
|
322
|
+
*/
|
|
323
|
+
export async function registerUser(email: string, password: string, name?: string): Promise<PublicUser> {
|
|
324
|
+
const c = getRequestContext();
|
|
325
|
+
const network = c ? networkFor(c.env as CmsBindings) : null;
|
|
326
|
+
// Registering on the network host for another site: that site's settings apply, whoever hosts the form.
|
|
327
|
+
const site = c && network ? await handoffSite(c, network) : null;
|
|
328
|
+
const siteRecord = site && c && network ? await pendingSite(c, network) : null;
|
|
329
|
+
const host = site ?? cms();
|
|
330
|
+
if (!(await registrationOpen())) throw new ClientVisibleError('Registration is closed on this site.');
|
|
331
|
+
const role = await host.settings.get('general.defaultRole');
|
|
332
|
+
const origin = linkOrigin() ?? '';
|
|
333
|
+
let draft;
|
|
334
|
+
try {
|
|
335
|
+
draft = await host.registrationDraft({ email, name: name?.trim() || email.split('@')[0]!, roles: role && (await host.users.role(role)) ? [role] : [], approval: await host.settings.get('general.approveRegistrations').catch(() => false) }, { origin });
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (isCmsError(error, 'CMS_VALIDATION')) throw new ClientVisibleError(error.message);
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
// With a sender (the one that sends the link: this request's host) and the site asking for it, the account waits for the email's link.
|
|
341
|
+
const verify = Boolean(cms().mail) && await host.settings.get('general.verifyEmail').catch(() => true);
|
|
342
|
+
// Without the site's address no link can be sent: the account is not created active instead.
|
|
343
|
+
if (verify && !origin) {
|
|
344
|
+
console.warn('[cms] registration refused: email confirmation is on, but APP_URL is not set, so no confirmation link can be sent');
|
|
345
|
+
throw new ClientVisibleError('Registration is not available right now. Ask the site\'s administrator.');
|
|
346
|
+
}
|
|
347
|
+
await replaceUnconfirmed(host, email, site !== null);
|
|
348
|
+
try {
|
|
349
|
+
// Held for approval, the account is created disabled with its place in the queue, in one write.
|
|
350
|
+
const user = await host.users.create({ email, password, name: draft.name, roles: draft.roles, ...(site ? { network: true } : {}),
|
|
351
|
+
...(draft.approval ? { approval: { verified: !verify } } : verify ? { status: 'disabled' as const } : {}) });
|
|
352
|
+
const bare = { id: user.id, email: user.email, name: user.name, avatar: user.avatar, meta: null, roles: [], principal: ANONYMOUS };
|
|
353
|
+
await host.userRegistered(user, verify ? 'verification' : draft.approval ? 'approval' : 'active').catch(() => undefined);
|
|
354
|
+
if (verify) {
|
|
355
|
+
await sendVerification(cms(), user.id, user.email, user.name, siteRecord?.id ?? null);
|
|
356
|
+
return { ...bare, verification: 'sent' };
|
|
357
|
+
}
|
|
358
|
+
if (draft.approval) return { ...bare, approval: 'pending' };
|
|
359
|
+
// The network host signs the account in; the handoff then takes it to its site.
|
|
360
|
+
return site ? bare : (await member(user.id))!;
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (isCmsError(error, 'CMS_CONFLICT')) throw new ClientVisibleError('An account with this email already exists.');
|
|
363
|
+
throw error;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* An account registered with this email that never confirmed it (created waiting, untouched since,
|
|
369
|
+
* never signed in) gives way to a new registration, so a missed or expired link, or someone
|
|
370
|
+
* registering another person's address, never locks the address. One waiting for approval stays.
|
|
371
|
+
*/
|
|
372
|
+
async function replaceUnconfirmed(host: CmsHost, email: string, network: boolean): Promise<void> {
|
|
373
|
+
const accounts = network ? host.accounts : host.signIn.accounts;
|
|
374
|
+
const account = await accounts.findByEmail(email).catch(() => null);
|
|
375
|
+
if (!account?.unconfirmed || await host.users.awaitingApproval(account.id).catch(() => false)) return;
|
|
376
|
+
await host.users.delete(account.id).catch(() => undefined);
|
|
377
|
+
await accounts.delete(account.id).catch(() => undefined);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Where links in this request's emails point: the site's own address (APP_URL for the main site,
|
|
382
|
+
* its domain for an added one), never the request's Host header, which a client chooses. Without
|
|
383
|
+
* a configured address, a request to this machine (development) uses its own origin; otherwise
|
|
384
|
+
* null, and no link is sent.
|
|
385
|
+
*/
|
|
386
|
+
export function linkOrigin(): string | null {
|
|
387
|
+
const c = getRequestContext();
|
|
388
|
+
if (!c) return env('APP_URL', '').replace(/\/+$/, '') || null;
|
|
389
|
+
return mailOrigin(c);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// --- Profile updates -------------------------------------------------------
|
|
393
|
+
export interface ProfileUpdate {
|
|
394
|
+
name?: string;
|
|
395
|
+
avatar?: string | null;
|
|
396
|
+
meta?: Record<string, unknown> | null;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** Update editable profile fields. */
|
|
400
|
+
export async function updateUserProfile(userId: string, patch: ProfileUpdate): Promise<void> {
|
|
401
|
+
await cms().users.update(userId, { ...(patch.name !== undefined ? { name: patch.name } : {}), ...(patch.avatar !== undefined ? { avatar: patch.avatar } : {}) });
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** Profile pictures are uploaded to the media library. */
|
|
405
|
+
export const avatarUploads = true;
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Store a profile picture and set it on the user; returns its URL. The signed-in user may
|
|
409
|
+
* change their own picture, and user managers anyone's.
|
|
410
|
+
*/
|
|
411
|
+
export async function uploadAvatar(userId: string, file: File): Promise<string> {
|
|
412
|
+
await requireManageable(userId);
|
|
413
|
+
const principal = (getRequestContext()?.get('principal') as Principal | undefined) ?? ANONYMOUS;
|
|
414
|
+
try { return await cms().uploadAvatar(userId, { name: file.name, contentType: file.type, size: file.size, body: file.stream() }, { principal }); }
|
|
415
|
+
catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// --- Second factors ----------------------------------------------------------
|
|
419
|
+
/** This store keeps authenticator apps, recovery codes, passkeys and application passwords. */
|
|
420
|
+
export const twoFactorAvailable = true;
|
|
421
|
+
|
|
422
|
+
/** Cookie holding a pending sign-in between the password and the second factor. */
|
|
423
|
+
export const TWO_FACTOR_COOKIE = 'two_factor';
|
|
424
|
+
|
|
425
|
+
export type { ApiToken };
|
|
426
|
+
|
|
427
|
+
/** An account's second factors and passkeys; on an added site, a network account's passkeys are the network host's. */
|
|
428
|
+
export type SecurityStatus = AccountSecurity & { passkeysManagedAt?: { name: string; href: string | null } | null };
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* After a correct password or email link: null when the user signs in at once, or the ID of a
|
|
432
|
+
* pending sign-in (5 minutes, 5 tries) that /auth/two-factor completes with a code. When
|
|
433
|
+
* two-step sign-in is required for the dashboard and the account's second factor is a passkey,
|
|
434
|
+
* having enrolled one is not having used it: throws SignInPasskeyError.
|
|
435
|
+
*/
|
|
436
|
+
export async function beginTwoFactor(userId: string): Promise<string | null> {
|
|
437
|
+
const host = cms();
|
|
438
|
+
const { security } = host.signIn;
|
|
439
|
+
if (await security.requiresCode(userId)) return security.createChallenge('signin', userId, 'password');
|
|
440
|
+
if (!(await host.settings.get('general.requireTwoFactor').catch(() => false))) return null;
|
|
441
|
+
const user = await member(userId);
|
|
442
|
+
if (user && hasPermission(user.principal, PERMISSIONS.dashboard) && await security.hasSecondFactor(userId)) throw new SignInPasskeyError();
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Finish a pending sign-in with an authenticator or recovery code. A try is spent before the
|
|
448
|
+
* code is checked, on the pending sign-in and on the account, so codes sent at once count too.
|
|
449
|
+
*/
|
|
450
|
+
export async function completeTwoFactor(challengeId: string, code: string): Promise<{ user: PublicUser; recovery: boolean } | { error: string; expired: boolean }> {
|
|
451
|
+
const { security } = cms().signIn;
|
|
452
|
+
const expired = { error: 'The sign-in expired. Enter your password again.', expired: true };
|
|
453
|
+
const pending = await security.challenge(challengeId, 'signin');
|
|
454
|
+
if (!pending?.userId) return expired;
|
|
455
|
+
const attempt = await security.secondFactorAttempt(challengeId, pending.userId);
|
|
456
|
+
if (attempt === 'expired') return expired;
|
|
457
|
+
if (attempt === 'locked') return { error: 'Too many wrong codes for this account. Try again in 15 minutes.', expired: true };
|
|
458
|
+
const used = await security.verifyCode(pending.userId, code);
|
|
459
|
+
if (!used) {
|
|
460
|
+
await security.failChallenge(challengeId);
|
|
461
|
+
const { left } = attempt;
|
|
462
|
+
return left > 0 ? { error: `That code is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.`, expired: false } : { error: 'Too many wrong codes. Enter your password again.', expired: true };
|
|
463
|
+
}
|
|
464
|
+
if (!(await security.takeChallenge(challengeId, 'signin'))) return expired;
|
|
465
|
+
await security.secondFactorSucceeded(pending.userId);
|
|
466
|
+
const user = await member(pending.userId);
|
|
467
|
+
if (!user) return { error: 'This account cannot sign in.', expired: true };
|
|
468
|
+
return { user, recovery: used === 'recovery' };
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** The second factors, passkeys and application passwords of a user's account: its site's for a site account, the network's otherwise. */
|
|
472
|
+
async function storesOf(userId: string) {
|
|
473
|
+
return cms().storesOf(userId);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export async function securityStatus(userId: string): Promise<SecurityStatus> {
|
|
477
|
+
const [status, elsewhere] = await Promise.all([(await storesOf(userId)).security.status(userId), networkPasskeys(userId)]);
|
|
478
|
+
return { ...status, passkeysManagedAt: elsewhere };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Where a network account's passkeys are kept when this is an added site: the network host.
|
|
483
|
+
* They are bound to its address and sign in there, so this site lists them and links there
|
|
484
|
+
* rather than adding or removing them. Null for site accounts and on the main site.
|
|
485
|
+
*/
|
|
486
|
+
async function networkPasskeys(userId: string): Promise<{ name: string; href: string | null } | null> {
|
|
487
|
+
const host = cms();
|
|
488
|
+
if (!host.siteAccounts || (await host.storesOf(userId)).kind !== 'network') return null;
|
|
489
|
+
const c = getRequestContext();
|
|
490
|
+
const network = networkFor(c?.env as CmsBindings);
|
|
491
|
+
const name = (await network.settings()).name || await network.main.settings.get('general.siteTitle').catch(() => 'the network');
|
|
492
|
+
let href: string | null = null;
|
|
493
|
+
try { href = new URL('/dashboard/profile/security', env('APP_URL', '')).href; } catch { /* no network address */ }
|
|
494
|
+
return { name, href };
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async function requireLocalPasskeys(userId: string): Promise<void> {
|
|
498
|
+
const elsewhere = await networkPasskeys(userId);
|
|
499
|
+
if (elsewhere) throw new ClientVisibleError(`Add or remove this account's passkeys on ${elsewhere.name}.`);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function twoFactorAsked(user: Pick<PublicUser, 'principal'>): Promise<boolean> {
|
|
503
|
+
return hasPermission(user.principal, PERMISSIONS.dashboard) && await cms().settings.get('general.requireTwoFactor').catch(() => false) === true;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Whether the request's session may not act as the user yet: General settings require two-step
|
|
508
|
+
* sign-in of staff, and the session was signed in without a second factor. That covers staff
|
|
509
|
+
* with no factor (they set one up) and a session signed in with a password alone (it signs in
|
|
510
|
+
* again with the factor), so a factor added later does not trust a session that never used it.
|
|
511
|
+
*/
|
|
512
|
+
export async function secondFactorRequired(user: PublicUser, c: Context | undefined = getRequestContext()): Promise<boolean> {
|
|
513
|
+
if (!(await twoFactorAsked(user))) return false;
|
|
514
|
+
return c?.get('cms.sessionSecondFactor') !== true;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** Whether an account itself still lacks the second factor General settings require: for application passwords, which have no sign-in of their own. */
|
|
518
|
+
export async function accountNeedsSecondFactor(user: Pick<PublicUser, 'id' | 'principal'>): Promise<boolean> {
|
|
519
|
+
if (!(await twoFactorAsked(user))) return false;
|
|
520
|
+
return !(await (await storesOf(user.id)).security.hasSecondFactor(user.id));
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Before a factor is added: a session limited by required two-step sign-in may add the
|
|
525
|
+
* account's first one (that is the setup), but not one beside a factor it never used, which
|
|
526
|
+
* would let a password alone take the account's two-step sign-in.
|
|
527
|
+
*/
|
|
528
|
+
async function requireFactorSetupAllowed(userId: string): Promise<void> {
|
|
529
|
+
const c = getRequestContext();
|
|
530
|
+
const user = c?.get('user') as PublicUser | undefined;
|
|
531
|
+
if (!user || user.id !== userId || c?.get('cms.sessionSecondFactor') === true) return;
|
|
532
|
+
if (!(await twoFactorAsked(user))) return;
|
|
533
|
+
if (await (await storesOf(userId)).security.hasSecondFactor(userId)) {
|
|
534
|
+
throw new ClientVisibleError('This account already has two-step sign-in. Sign out, then sign in again with it.');
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* After the user added a factor in this session: the session counts as using it when it was the
|
|
540
|
+
* account's first. Other sessions
|
|
541
|
+
* keep what their own sign-in used, so a password-only one stays limited; they are not ended,
|
|
542
|
+
* since whoever added the first factor (the owner, or someone with the password) would otherwise
|
|
543
|
+
* sign the other out.
|
|
544
|
+
*/
|
|
545
|
+
async function factorAdded(userId: string, hadFactor: boolean): Promise<void> {
|
|
546
|
+
const c = getRequestContext();
|
|
547
|
+
const id = c ? getCookie(c, SESSION_COOKIE) : undefined;
|
|
548
|
+
const user = c?.get('user') as PublicUser | undefined;
|
|
549
|
+
if (!c || !id || user?.id !== userId) return;
|
|
550
|
+
// Only the account's first factor counts for the session that set it up: one added beside a
|
|
551
|
+
// factor the session never used (setup raced another session's) does not.
|
|
552
|
+
if (hadFactor && c.get('cms.sessionSecondFactor') !== true) return;
|
|
553
|
+
await cms(c).authSessions.markSecondFactor(id);
|
|
554
|
+
c.set('cms.sessionSecondFactor', true);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** A new authenticator secret, its `otpauth://` URI and a QR code of it as SVG. */
|
|
558
|
+
export async function startAuthenticator(user: PublicUser): Promise<{ secret: string; uri: string; qr: string }> {
|
|
559
|
+
await requireFactorSetupAllowed(user.id);
|
|
560
|
+
const host = cms();
|
|
561
|
+
const secret = await (await storesOf(user.id)).security.startTotp(user.id);
|
|
562
|
+
const issuer = await host.settings.get('general.siteTitle').catch(() => 'Cossack');
|
|
563
|
+
const uri = totpUri({ secret, issuer, account: user.email });
|
|
564
|
+
return { secret, uri, qr: renderSVG(uri, { border: 1 }) };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Confirm the authenticator with a code from it; returns the recovery codes, shown once. */
|
|
568
|
+
export async function confirmAuthenticator(userId: string, code: string): Promise<string[]> {
|
|
569
|
+
await requireFactorSetupAllowed(userId);
|
|
570
|
+
const { security } = await storesOf(userId);
|
|
571
|
+
const hadFactor = await security.hasSecondFactor(userId);
|
|
572
|
+
let codes: string[];
|
|
573
|
+
try { codes = await security.confirmTotp(userId, code); }
|
|
574
|
+
catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
|
|
575
|
+
await factorAdded(userId, hadFactor);
|
|
576
|
+
return codes;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Before a factor is removed or replaced: a session limited by required two-step sign-in never
|
|
581
|
+
* used the account's factors, so it may not take them away (it could then set up its own and
|
|
582
|
+
* count as two-step). It signs in again with a factor first.
|
|
583
|
+
*/
|
|
584
|
+
async function requireFactorUsed(userId: string): Promise<void> {
|
|
585
|
+
const c = getRequestContext();
|
|
586
|
+
const user = c?.get('user') as PublicUser | undefined;
|
|
587
|
+
if (!user || user.id !== userId || c?.get('cms.sessionSecondFactor') === true) return;
|
|
588
|
+
if (!(await twoFactorAsked(user))) return;
|
|
589
|
+
throw new ClientVisibleError('Sign out, then sign in again with two-step sign-in to change it.');
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Check an authenticator or recovery code, counted against the account's tries as at sign-in. */
|
|
593
|
+
async function checkAccountCode(userId: string, code: string): Promise<void> {
|
|
594
|
+
const { security } = await storesOf(userId);
|
|
595
|
+
if (!(await security.codeAttempt(userId))) throw new ClientVisibleError('Too many wrong codes for this account. Try again in 15 minutes.');
|
|
596
|
+
if (!(await security.verifyCode(userId, code))) throw new ClientVisibleError('That code is not right.');
|
|
597
|
+
await security.secondFactorSucceeded(userId);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** Turning the authenticator off needs one of its codes, or a recovery code. */
|
|
601
|
+
export async function disableAuthenticator(userId: string, code: string): Promise<void> {
|
|
602
|
+
await requireFactorUsed(userId);
|
|
603
|
+
await checkAccountCode(userId, code);
|
|
604
|
+
await (await storesOf(userId)).security.disableTotp(userId);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
export async function newRecoveryCodes(userId: string, code: string): Promise<string[]> {
|
|
608
|
+
await requireFactorUsed(userId);
|
|
609
|
+
await checkAccountCode(userId, code);
|
|
610
|
+
return (await storesOf(userId)).security.regenerateRecoveryCodes(userId);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Remove a user's second factors, for a user manager helping someone who lost their device. */
|
|
614
|
+
export async function resetSecondFactors(userId: string): Promise<void> {
|
|
615
|
+
await requireManageable(userId);
|
|
616
|
+
await (await storesOf(userId)).security.reset(userId);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** The site's relying party for passkeys: this host, and the origins the browser may report. */
|
|
620
|
+
function passkeySite(c: Context, siteName: string): PasskeyConfig {
|
|
621
|
+
const url = new URL(c.req.url);
|
|
622
|
+
const origins = new Set([url.origin]);
|
|
623
|
+
if (c.req.header('x-forwarded-proto') === 'https') origins.add(`https://${url.host}`);
|
|
624
|
+
const configured = env('APP_URL', '');
|
|
625
|
+
if (configured) { try { origins.add(new URL(configured).origin); } catch { /* not a URL */ } }
|
|
626
|
+
return { rpName: siteName, rpID: url.hostname, origin: [...origins] };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
export async function passkeyRegistration(c: Context, user: PublicUser): Promise<{ challenge: string; options: PublicKeyCredentialCreationOptionsJSON }> {
|
|
630
|
+
await requireLocalPasskeys(user.id);
|
|
631
|
+
await requireFactorSetupAllowed(user.id);
|
|
632
|
+
const host = cms(c);
|
|
633
|
+
const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
|
|
634
|
+
const { security } = await host.storesOf(user.id);
|
|
635
|
+
const existing = await security.passkeys(user.id);
|
|
636
|
+
const options = await passkeyRegistrationOptions(site, { id: user.id, name: user.email, displayName: user.name }, existing.map(passkey => ({ ...passkey, transports: passkey.transports ?? undefined })));
|
|
637
|
+
return { challenge: await security.createChallenge('passkey-register', user.id, options.challenge), options };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
export async function addPasskey(c: Context, user: PublicUser, challengeId: string, response: RegistrationResponseJSON, name: string): Promise<void> {
|
|
641
|
+
await requireLocalPasskeys(user.id);
|
|
642
|
+
const host = cms(c);
|
|
643
|
+
const { security } = await host.storesOf(user.id);
|
|
644
|
+
const pending = await security.challenge(challengeId, 'passkey-register');
|
|
645
|
+
if (!pending || pending.userId !== user.id || !(await security.takeChallenge(challengeId, 'passkey-register'))) throw new ClientVisibleError('The passkey request expired. Try again.');
|
|
646
|
+
const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
|
|
647
|
+
const passkey = await verifyPasskeyRegistration(site, response, pending.challenge);
|
|
648
|
+
if (!passkey) throw new ClientVisibleError('The passkey could not be verified.');
|
|
649
|
+
await requireFactorSetupAllowed(user.id);
|
|
650
|
+
const hadFactor = await security.hasSecondFactor(user.id);
|
|
651
|
+
try { await security.addPasskey(user.id, passkey, name); }
|
|
652
|
+
catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
|
|
653
|
+
await factorAdded(user.id, hadFactor);
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
export async function removePasskey(userId: string, id: string): Promise<void> {
|
|
657
|
+
await requireLocalPasskeys(userId);
|
|
658
|
+
await requireFactorUsed(userId);
|
|
659
|
+
await (await storesOf(userId)).security.removePasskey(userId, id);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Passkey sign-in challenges anyone may ask for, each a stored row: per client address, and for
|
|
664
|
+
* the whole host so many addresses together cannot fill the database (challenges live 5 minutes).
|
|
665
|
+
*/
|
|
666
|
+
export const PASSKEY_CHALLENGES = Object.freeze({ windowMs: 10 * 60_000, perAddress: 30, perHost: 2000 });
|
|
667
|
+
|
|
668
|
+
/** A passkey signs in this host's accounts, bound to this host: the network's on the main site, the site's own on an added site. */
|
|
669
|
+
export async function passkeySignIn(c: Context): Promise<{ challenge: string; options: PublicKeyCredentialRequestOptionsJSON }> {
|
|
670
|
+
const host = cms(c);
|
|
671
|
+
const counters = host.signIn.security;
|
|
672
|
+
if (!(await counters.attempt('passkey-options', `a:${clientAddress()}`, PASSKEY_CHALLENGES.perAddress, PASSKEY_CHALLENGES.windowMs))
|
|
673
|
+
|| !(await counters.attempt('passkey-options', 'host', PASSKEY_CHALLENGES.perHost, PASSKEY_CHALLENGES.windowMs))) {
|
|
674
|
+
throw new ClientVisibleError('Too many passkey sign-ins were started. Try again in a few minutes, or sign in with your password.');
|
|
675
|
+
}
|
|
676
|
+
const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
|
|
677
|
+
const options = await passkeyAuthenticationOptions(site);
|
|
678
|
+
return { challenge: await host.signIn.security.createChallenge('passkey-signin', null, options.challenge), options };
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** The user a passkey signs in, after checking its signature against the challenge. */
|
|
682
|
+
export async function completePasskeySignIn(c: Context, challengeId: string, response: AuthenticationResponseJSON): Promise<PublicUser | null> {
|
|
683
|
+
const host = cms(c);
|
|
684
|
+
const { security } = host.signIn;
|
|
685
|
+
const pending = await security.challenge(challengeId, 'passkey-signin');
|
|
686
|
+
if (!pending || !(await security.takeChallenge(challengeId, 'passkey-signin'))) return null;
|
|
687
|
+
const passkey = await security.passkey(response?.id);
|
|
688
|
+
if (!passkey) return null;
|
|
689
|
+
const site = passkeySite(c, await host.settings.get('general.siteTitle').catch(() => 'Cossack'));
|
|
690
|
+
const verified = await verifyPasskeyAuthentication(site, response, pending.challenge, { ...passkey, transports: passkey.transports ?? undefined });
|
|
691
|
+
if (!verified) return null;
|
|
692
|
+
await security.usePasskey(passkey.id, verified.counter);
|
|
693
|
+
return member(passkey.userId, c);
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// --- Application passwords -------------------------------------------------
|
|
697
|
+
/** Application passwords sign apps and scripts in to the content API. */
|
|
698
|
+
export const apiTokensAvailable = true;
|
|
699
|
+
|
|
700
|
+
export async function listApiTokens(userId: string): Promise<ApiToken[]> {
|
|
701
|
+
return await manageableHere(userId) ? (await storesOf(userId)).apiTokens.list(userId) : [];
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/** A new application password; the token is shown once. A network account's work on every site it belongs to. */
|
|
705
|
+
export async function createApiToken(userId: string, name: string, scope: 'read' | 'write', expiresInDays: number | null = null): Promise<string> {
|
|
706
|
+
await requireManageable(userId);
|
|
707
|
+
// An application password signs in without a second factor: an account that General settings
|
|
708
|
+
// require to have one gets passwords only once it does.
|
|
709
|
+
const owner = await member(userId);
|
|
710
|
+
if (owner && (await accountNeedsSecondFactor(owner) || (owner.id === (getRequestContext()?.get('user') as PublicUser | undefined)?.id && await secondFactorRequired(owner)))) throw new ClientVisibleError('This site requires two-step sign-in: set it up under Profile → Security before creating application passwords.');
|
|
711
|
+
const expiresAt = expiresInDays && expiresInDays > 0 ? Date.now() + Math.trunc(expiresInDays) * 86_400_000 : null;
|
|
712
|
+
try { return (await (await storesOf(userId)).apiTokens.create(userId, { name, scope, expiresAt })).token; }
|
|
713
|
+
catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
export async function revokeApiToken(userId: string, id: string): Promise<void> {
|
|
717
|
+
await requireManageable(userId);
|
|
718
|
+
// A session that never used the account's second factor may not take its tokens away either.
|
|
719
|
+
await requireFactorUsed(userId);
|
|
720
|
+
await (await storesOf(userId)).apiTokens.revoke(userId, id).catch(() => undefined);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// --- Password reset ----------------------------------------------------------
|
|
724
|
+
/**
|
|
725
|
+
* Creates a reset token and emails it. Reads the `EMAIL` binding and `MAIL_FROM` via the
|
|
726
|
+
* global helpers. Unknown emails and a missing send_email binding are silent no-ops. On an
|
|
727
|
+
* added site, a member with a network account gets the network's reset link.
|
|
728
|
+
*/
|
|
729
|
+
export async function requestPasswordReset(email: string, _requestOrigin?: string): Promise<void> {
|
|
730
|
+
const host = cms();
|
|
731
|
+
// The link goes to the site's own address, never the Host the request named.
|
|
732
|
+
let resetBaseUrl = linkOrigin();
|
|
733
|
+
if (!resetBaseUrl) {
|
|
734
|
+
console.warn('[cms] A password reset was requested, but the site has no address (APP_URL): the link was not sent.');
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
// A flood of requests for one email or from one address sends nothing after the first few.
|
|
738
|
+
const address = clientAddress();
|
|
739
|
+
const byEmail = await host.security.attempt('reset', `e:${email.trim().toLowerCase()}`, RESET_REQUESTS.perEmail, RESET_REQUESTS.windowMs);
|
|
740
|
+
const byAddress = await host.security.attempt('reset', `a:${address}`, RESET_REQUESTS.perAddress, RESET_REQUESTS.windowMs);
|
|
741
|
+
if (!byEmail || !byAddress) return;
|
|
742
|
+
let reset = await host.signIn.accounts.createPasswordReset(email);
|
|
743
|
+
if (!reset && host.siteAccounts && (await host.users.findByEmail(email).catch(() => null))?.account === 'network') {
|
|
744
|
+
const network = env('APP_URL', '');
|
|
745
|
+
reset = network ? await host.accounts.createPasswordReset(email) : null;
|
|
746
|
+
resetBaseUrl = network;
|
|
747
|
+
}
|
|
748
|
+
if (!reset) return; // do NOT leak whether the email exists
|
|
749
|
+
if (!host.mail) {
|
|
750
|
+
console.warn('[cms] A password reset was requested, but no email sender is configured (an EMAIL binding, or SMTP_HOST on Node): the link was not sent.');
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
const resetUrl = `${resetBaseUrl.replace(/\/$/, '')}/auth/reset-password?token=${reset.token}`;
|
|
754
|
+
await host.mail.send({ kind: 'reset', to: reset.account.email, subject: 'Reset your password',
|
|
755
|
+
text: `We received a request to reset your password. Choose a new one here; the link works for one hour:\n${resetUrl}\n\nIf you did not ask for it, ignore this email.` });
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** One request can use a token; the account's sessions end with the change. */
|
|
759
|
+
export async function resetPassword(token: string, newPassword: string): Promise<boolean> {
|
|
760
|
+
return cms().signIn.accounts.resetPassword(token, newPassword);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
// --- Logout ----------------------------------------------------------------
|
|
764
|
+
/** Signing out of a site signs out of the network too, and so of every site the session reached. */
|
|
765
|
+
export async function logout(c: Context): Promise<{ headers: Headers }> {
|
|
766
|
+
const id = getCookie(c, SESSION_COOKIE) ?? '';
|
|
767
|
+
const session = id ? await cms(c).authSessions.read(id, c).catch(() => null) : null;
|
|
768
|
+
const headers = await authSessions.revoke(id, c);
|
|
769
|
+
if (session?.parentId) await networkFor(c.env as CmsBindings).main.authSessions.revokeByReference(session.userId, session.parentId).catch(() => false);
|
|
770
|
+
return { headers };
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/** Clear the same cookie policy used for creation and rotation. */
|
|
774
|
+
export const expiredSessionCookie = authSessions.expiredCookie;
|
|
775
|
+
|
|
776
|
+
// --- Session management (for the /dashboard/sessions page) -----------------
|
|
777
|
+
export interface SessionInfo {
|
|
778
|
+
/** Public management reference. Never the bearer token used in the cookie. */
|
|
779
|
+
reference: string;
|
|
780
|
+
expiresAt: string;
|
|
781
|
+
createdAt: string;
|
|
782
|
+
current: boolean;
|
|
783
|
+
location: string | null;
|
|
784
|
+
userAgent: string | null;
|
|
785
|
+
ipAddress: string | null;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function sessionOwner(c: Context): { userId: string; currentId: string } {
|
|
789
|
+
const user = c.get('user') as PublicUser | undefined;
|
|
790
|
+
const currentId = getCookie(c, SESSION_COOKIE);
|
|
791
|
+
if (!user?.id || !currentId) throw new ClientVisibleError('Sign in to manage sessions.');
|
|
792
|
+
return { userId: user.id, currentId };
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** Lists only the authenticated caller's active sessions as safe DTOs. */
|
|
796
|
+
export async function listUserSessions(c: Context): Promise<SessionInfo[]> {
|
|
797
|
+
return sessionsOf(c, sessionOwner(c).userId);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* Any user's active sessions, for the user screen. The page decides who may see them;
|
|
802
|
+
* the caller's own session is marked current.
|
|
803
|
+
*/
|
|
804
|
+
export async function sessionsOf(c: Context, userId: string): Promise<SessionInfo[]> {
|
|
805
|
+
await requireManageable(userId);
|
|
806
|
+
const host = cms(c);
|
|
807
|
+
const currentId = getCookie(c, SESSION_COOKIE);
|
|
808
|
+
const current = currentId ? await host.authSessions.publicReference(currentId) : null;
|
|
809
|
+
return (await host.authSessions.listForUser(userId, Date.now())).map(row => ({
|
|
810
|
+
reference: row.reference, createdAt: new Date(row.createdAt).toISOString(), expiresAt: new Date(row.expiresAt).toISOString(),
|
|
811
|
+
current: row.reference === current, location: null, userAgent: row.userAgent, ipAddress: row.ip,
|
|
812
|
+
}));
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** End one of a user's sessions, never the caller's own. */
|
|
816
|
+
export async function revokeSessionOf(c: Context, userId: string, reference: string): Promise<boolean> {
|
|
817
|
+
await requireManageable(userId);
|
|
818
|
+
return cms(c).authSessions.revokeByReference(userId, reference, getCookie(c, SESSION_COOKIE));
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** End all of a user's sessions except the caller's own. */
|
|
822
|
+
export async function revokeSessionsOf(c: Context, userId: string): Promise<void> {
|
|
823
|
+
await requireManageable(userId);
|
|
824
|
+
await cms(c).authSessions.revokeAllForUser(userId, getCookie(c, SESSION_COOKIE));
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Revoke one other session owned by the authenticated caller. */
|
|
828
|
+
export async function revokeSession(c: Context, reference: string): Promise<boolean> {
|
|
829
|
+
const { userId, currentId } = sessionOwner(c);
|
|
830
|
+
return cms(c).authSessions.revokeByReference(userId, reference, currentId);
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** Revoke the caller's sessions, optionally keeping the current one. */
|
|
834
|
+
export async function revokeAllUserSessions(c: Context, keepCurrent = false): Promise<void> {
|
|
835
|
+
const { userId, currentId } = sessionOwner(c);
|
|
836
|
+
await cms(c).authSessions.revokeAllForUser(userId, keepCurrent ? currentId : undefined);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** The session cookie name, exported so pages/middleware can read it. */
|
|
840
|
+
export const SESSION_COOKIE_NAME = SESSION_COOKIE;
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* A person deletes their own account: the password confirms it, the site's only administrator
|
|
844
|
+
* may not, every session ends, and the account goes with its memberships. Returns the headers
|
|
845
|
+
* that clear the browser's session.
|
|
846
|
+
*/
|
|
847
|
+
export async function deleteOwnAccount(c: Context, userId: string, password: string): Promise<{ headers: Headers }> {
|
|
848
|
+
if (!(await passwordMatches(userId, password))) throw new ClientVisibleError('The password is not right.');
|
|
849
|
+
const host = cms();
|
|
850
|
+
const me = await host.users.get(userId);
|
|
851
|
+
if (!me) throw new ClientVisibleError('The account was not found.');
|
|
852
|
+
if (me.permissions.includes('*')) {
|
|
853
|
+
const admins = await host.users.list({ role: 'admin', limit: 2 });
|
|
854
|
+
if (admins.total <= 1) throw new ClientVisibleError('You are the only administrator. Make someone else an administrator first.');
|
|
855
|
+
}
|
|
856
|
+
await revokeSessionsOf(c, userId);
|
|
857
|
+
const { headers } = await logout(c);
|
|
858
|
+
await host.users.delete(userId);
|
|
859
|
+
return { headers };
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** How long a confirmation link lives. */
|
|
863
|
+
const VERIFICATION_TTL_MS = 48 * 60 * 60_000;
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Send the confirmation link, from and to the host that registered the account (this request's);
|
|
867
|
+
* the token's hash in its cache names the account, and the site it registered for when that is
|
|
868
|
+
* another (a network registration), until it is opened or two days pass.
|
|
869
|
+
*/
|
|
870
|
+
async function sendVerification(host: CmsHost, userId: string, email: string, name: string, site: string | null): Promise<void> {
|
|
871
|
+
const origin = linkOrigin();
|
|
872
|
+
if (!host.mail || !origin) return;
|
|
873
|
+
const token = randomToken(32);
|
|
874
|
+
await host.cache.set(`verify:${await sha256Hex(token)}`, { user: userId, ...(site ? { site } : {}) }, VERIFICATION_TTL_MS);
|
|
875
|
+
const title = await host.settings.get('general.siteTitle').catch(() => '');
|
|
876
|
+
await host.mail.send({ kind: 'verification', to: email, from: host.mailFrom, subject: `Confirm your email for ${title || 'the site'}`,
|
|
877
|
+
text: `Hello ${name || email},\n\nConfirm your email address to finish creating your account on ${title || origin}:\n${origin.replace(/\/$/, '')}/auth/verify?token=${token}\n\nThe link works for two days. If you did not register, ignore this email.` });
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* Open a confirmation link: the token is spent, and the account becomes active, or keeps
|
|
882
|
+
* waiting for an administrator's approval (`pending`). Null for an unknown or expired link.
|
|
883
|
+
*/
|
|
884
|
+
/**
|
|
885
|
+
* The email of the account a sign-in or confirmation link is for, read without spending the
|
|
886
|
+
* link: its page shows it, so someone opening a link another person sent sees whose account
|
|
887
|
+
* it would sign them into. Null for a link that is not valid.
|
|
888
|
+
*/
|
|
889
|
+
export async function linkAccountEmail(kind: 'magic' | 'verify', token: string): Promise<string | null> {
|
|
890
|
+
if (!/^[A-Za-z0-9_-]{20,128}$/.test(token)) return null;
|
|
891
|
+
const host = cms();
|
|
892
|
+
const found = await host.cache.get<{ user: string }>(`${kind}:${await sha256Hex(token)}`).catch(() => undefined);
|
|
893
|
+
if (!found?.user) return null;
|
|
894
|
+
const user = await host.users.get(found.user).catch(() => null);
|
|
895
|
+
if (user?.email) return user.email;
|
|
896
|
+
const account = await host.accounts.get(found.user).catch(() => null);
|
|
897
|
+
return account?.email ?? null;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
export async function verifyEmail(token: string): Promise<{ user: string; pending: boolean; site?: string } | null> {
|
|
901
|
+
if (!/^[A-Za-z0-9_-]{20,128}$/.test(token)) return null;
|
|
902
|
+
const key = `verify:${await sha256Hex(token)}`;
|
|
903
|
+
const found = await cms().cache.take<{ user: string; site?: string }>(key);
|
|
904
|
+
if (!found?.user) return null;
|
|
905
|
+
// A network registration for another site waits on that site: its approval, its member.
|
|
906
|
+
const c = getRequestContext();
|
|
907
|
+
const record = found.site && c ? await networkFor(c.env as CmsBindings).sites.get(found.site).catch(() => null) : null;
|
|
908
|
+
const host = record ? networkFor(c!.env as CmsBindings).hostOf(networkSite(record)) : cms();
|
|
909
|
+
if (await host.users.confirmRegistration(found.user)) return { user: found.user, pending: true };
|
|
910
|
+
// Only an account still waiting for this link becomes active: one an administrator disabled (or changed) since stays as it is.
|
|
911
|
+
const account = await (await host.storesOf(found.user)).accounts.get(found.user).catch(() => null);
|
|
912
|
+
if (!account?.unconfirmed) return null;
|
|
913
|
+
await host.users.setStatus(found.user, 'active');
|
|
914
|
+
return { user: found.user, pending: false, ...(record ? { site: record.id } : {}) };
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* Approve a member who waits for it: their account becomes active and they get an email saying
|
|
919
|
+
* so. False when they were not waiting; `CMS_VALIDATION` before their email is confirmed.
|
|
920
|
+
*/
|
|
921
|
+
export async function approveRegistration(userId: string): Promise<boolean> {
|
|
922
|
+
const host = cms();
|
|
923
|
+
if (!(await host.users.approve(userId))) return false;
|
|
924
|
+
const user = await host.users.get(userId);
|
|
925
|
+
// The site's configured address, never the request's Host, which a caller could set.
|
|
926
|
+
const origin = linkOrigin();
|
|
927
|
+
if (user && host.mail) {
|
|
928
|
+
const title = await host.settings.get('general.siteTitle').catch(() => '');
|
|
929
|
+
const where = origin ? ` Sign in at:\n${origin.replace(/\/$/, '')}/auth/login\n` : '\n';
|
|
930
|
+
await host.mail.send({ to: user.email, from: host.mailFrom, subject: `Your account on ${title || 'the site'} is ready`,
|
|
931
|
+
text: `Hello ${user.name || user.email},\n\nAn administrator approved your account.${where}` }).catch(() => undefined);
|
|
932
|
+
}
|
|
933
|
+
return true;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** How long a sign-in link lives. */
|
|
937
|
+
const MAGIC_LINK_TTL_MS = 15 * 60_000;
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* Email a one-time sign-in link to an active account. Nothing says whether the email exists; a
|
|
941
|
+
* flood for one address or from one client stops after a few. Without a mail sender, nothing is sent.
|
|
942
|
+
*/
|
|
943
|
+
export async function requestMagicLink(email: string, _requestOrigin?: string): Promise<void> {
|
|
944
|
+
const host = cms();
|
|
945
|
+
const origin = linkOrigin();
|
|
946
|
+
if (!origin) return;
|
|
947
|
+
const address = clientAddress();
|
|
948
|
+
const allowedEmail = await host.security.attempt('magic', `e:${email.trim().toLowerCase()}`, RESET_REQUESTS.perEmail, RESET_REQUESTS.windowMs);
|
|
949
|
+
const allowedAddress = await host.security.attempt('magic', `a:${address}`, RESET_REQUESTS.perAddress, RESET_REQUESTS.windowMs);
|
|
950
|
+
if (!allowedEmail || !allowedAddress || !host.mail) return;
|
|
951
|
+
const account = await host.signIn.accounts.findByEmail(email).catch(() => null);
|
|
952
|
+
if (!account || account.status !== 'active') return;
|
|
953
|
+
const token = randomToken(32);
|
|
954
|
+
await host.cache.set(`magic:${await sha256Hex(token)}`, { user: account.id }, MAGIC_LINK_TTL_MS);
|
|
955
|
+
const title = await host.settings.get('general.siteTitle').catch(() => '');
|
|
956
|
+
await host.mail.send({ kind: 'magic-link', to: account.email, from: host.mailFrom, subject: `Sign in to ${title || 'the site'}`,
|
|
957
|
+
text: `Open this link to sign in; it works once, for fifteen minutes:\n${origin}/auth/magic?token=${token}\n\nIf you did not ask for it, ignore this email.` });
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
/** Spend a sign-in link: the account's ID, or null for a link that is unknown, spent or expired. */
|
|
961
|
+
export async function consumeMagicLink(token: string): Promise<string | null> {
|
|
962
|
+
if (!/^[A-Za-z0-9_-]{20,128}$/.test(token)) return null;
|
|
963
|
+
const host = cms();
|
|
964
|
+
const key = `magic:${await sha256Hex(token)}`;
|
|
965
|
+
// Taken in one conditional delete, so two requests with the same link cannot both sign in.
|
|
966
|
+
const found = await host.cache.take<{ user: string }>(key);
|
|
967
|
+
if (!found?.user) return null;
|
|
968
|
+
const account = await host.signIn.accounts.get(found.user).catch(() => null);
|
|
969
|
+
return account && account.status === 'active' ? account.id : null;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// --- OAuth -------------------------------------------------------------------
|
|
973
|
+
// The site's providers are its `oauth` option (src/cms.config.ts). Each reads
|
|
974
|
+
// <PROVIDER>_CLIENT_ID and <PROVIDER>_CLIENT_SECRET; OAUTH_SECRET signs the state, which the
|
|
975
|
+
// host's store spends once. /auth/<provider>/redirect and /callback are the routes.
|
|
976
|
+
//
|
|
977
|
+
// A provider proves an email address, as a sign-in link does: the account with that verified
|
|
978
|
+
// address signs in, and still takes its second step. No provider identity is stored.
|
|
979
|
+
const oauthVariables = (provider: string) => ({
|
|
980
|
+
clientId: `${provider.toUpperCase()}_CLIENT_ID`,
|
|
981
|
+
clientSecret: `${provider.toUpperCase()}_CLIENT_SECRET`,
|
|
982
|
+
});
|
|
983
|
+
|
|
984
|
+
/** Whether this site offers the provider. */
|
|
985
|
+
export function oauthProvider(provider: string): boolean {
|
|
986
|
+
try { return cms().oauth.includes(provider); }
|
|
987
|
+
catch { return false; }
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
function oauthConfigurationError(c: Context, provider: string): OAuthError | null {
|
|
991
|
+
if (!oauthProvider(provider)) return new OAuthError('COSSACK_OAUTH_PROVIDER_UNKNOWN');
|
|
992
|
+
const variables = oauthVariables(provider);
|
|
993
|
+
const env = c.env as Record<string, unknown>;
|
|
994
|
+
if ([variables.clientId, variables.clientSecret].some(name => !String(env[name] ?? '').trim())) return new OAuthError('COSSACK_OAUTH_CREDENTIALS_MISSING');
|
|
995
|
+
if (String(env.OAUTH_SECRET ?? '').length < 16) return new OAuthError('COSSACK_OAUTH_SECRET_INVALID');
|
|
996
|
+
return null;
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
function oauthUnavailable(c: Context, error: OAuthError): Response {
|
|
1000
|
+
console.warn('[Cossack OAuth]', error.toJSON());
|
|
1001
|
+
const { message, ...diagnostic } = error.toJSON();
|
|
1002
|
+
return c.json({ error: message, ...diagnostic }, error.status);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
function createOAuthForRequest(c: Context): OAuthKit {
|
|
1006
|
+
const host = cms(c);
|
|
1007
|
+
const env = c.env as Record<string, unknown>;
|
|
1008
|
+
return createOAuth({
|
|
1009
|
+
secret: String(env.OAUTH_SECRET ?? ''),
|
|
1010
|
+
stateStore: host.oauthStates,
|
|
1011
|
+
providers: Object.fromEntries(host.oauth.map(provider => {
|
|
1012
|
+
const variables = oauthVariables(provider);
|
|
1013
|
+
return [provider, { clientId: String(env[variables.clientId] ?? ''), clientSecret: String(env[variables.clientSecret] ?? ''), redirectUrl: `/auth/${provider}/callback` }];
|
|
1014
|
+
})),
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
export const oauth: OAuthKit = {
|
|
1019
|
+
redirect: (provider) => async (c, next) => {
|
|
1020
|
+
const error = oauthConfigurationError(c, provider);
|
|
1021
|
+
if (error) return oauthUnavailable(c, error);
|
|
1022
|
+
return createOAuthForRequest(c).redirect(provider)(c, next);
|
|
1023
|
+
},
|
|
1024
|
+
callback: (provider, options) => async (c, next) => {
|
|
1025
|
+
const error = oauthConfigurationError(c, provider);
|
|
1026
|
+
if (error) return oauthUnavailable(c, error);
|
|
1027
|
+
return createOAuthForRequest(c).callback(provider, options)(c, next);
|
|
1028
|
+
},
|
|
1029
|
+
};
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* The provider sent the visitor back. Its verified email names the account: an active one signs
|
|
1033
|
+
* in (through its second step, when it has one), and an unknown one becomes an account when
|
|
1034
|
+
* registration is open, with the site's default role and its approval rule. The sign-in page
|
|
1035
|
+
* says why a sign-in did not happen (`?oauth=<reason>`).
|
|
1036
|
+
*/
|
|
1037
|
+
export async function handleOAuthUser(_provider: string, oauthUser: OAuthUser, _tokens: TokenSet, c: Context) {
|
|
1038
|
+
const refused = (reason: 'unverified' | 'closed' | 'pending' | 'inactive' | 'passkey') => c.redirect(`/auth/login?oauth=${reason}`);
|
|
1039
|
+
const email = oauthUser.emailVerified === true && typeof oauthUser.email === 'string' ? oauthUser.email.trim().toLowerCase() : '';
|
|
1040
|
+
// Only an address the provider verified may name or create an account.
|
|
1041
|
+
if (!email) return refused('unverified');
|
|
1042
|
+
const host = cms(c);
|
|
1043
|
+
// The provider confirmed the address: a registration that never confirmed it gives way.
|
|
1044
|
+
await replaceUnconfirmed(host, email, false);
|
|
1045
|
+
let account = await host.signIn.accounts.findByEmail(email).catch(() => null);
|
|
1046
|
+
if (!account) {
|
|
1047
|
+
if (!(await registrationOpen())) return refused('closed');
|
|
1048
|
+
const role = await host.settings.get('general.defaultRole');
|
|
1049
|
+
let draft;
|
|
1050
|
+
try {
|
|
1051
|
+
draft = await host.registrationDraft({ email, name: (oauthUser.name ?? oauthUser.nickname ?? '').trim() || email.split('@')[0]!,
|
|
1052
|
+
roles: role && (await host.users.role(role)) ? [role] : [], approval: await host.settings.get('general.approveRegistrations').catch(() => false) }, { origin: linkOrigin() ?? '' });
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
if (isCmsError(error, 'CMS_VALIDATION')) return refused('closed');
|
|
1055
|
+
throw error;
|
|
1056
|
+
}
|
|
1057
|
+
// The account has no password anyone knows: it signs in with the provider, or sets one through "Forgot password".
|
|
1058
|
+
const user = await host.users.create({ email, password: randomToken(48), name: draft.name, roles: draft.roles,
|
|
1059
|
+
...(draft.approval ? { approval: { verified: true } } : {}) });
|
|
1060
|
+
await host.userRegistered(user, draft.approval ? 'approval' : 'active').catch(() => undefined);
|
|
1061
|
+
if (draft.approval) return refused('pending');
|
|
1062
|
+
account = await host.signIn.accounts.get(user.id).catch(() => null);
|
|
1063
|
+
}
|
|
1064
|
+
if (!account || account.status !== 'active') {
|
|
1065
|
+
return refused(account && await host.users.awaitingApproval(account.id).catch(() => false) ? 'pending' : 'inactive');
|
|
1066
|
+
}
|
|
1067
|
+
// The provider stands in for the password only: an enrolled authenticator is still asked for.
|
|
1068
|
+
let pending: string | null;
|
|
1069
|
+
try { pending = await beginTwoFactor(account.id); }
|
|
1070
|
+
catch (error) {
|
|
1071
|
+
if (!(error instanceof SignInPasskeyError)) throw error;
|
|
1072
|
+
return refused('passkey');
|
|
1073
|
+
}
|
|
1074
|
+
if (pending) {
|
|
1075
|
+
const secure = new URL(c.req.url).protocol === 'https:';
|
|
1076
|
+
c.header('set-cookie', `${TWO_FACTOR_COOKIE}=${pending}; Path=/; HttpOnly; SameSite=Lax; Max-Age=300${secure ? '; Secure' : ''}`, { append: true });
|
|
1077
|
+
return c.redirect('/auth/two-factor');
|
|
1078
|
+
}
|
|
1079
|
+
const { headers } = await authSessions.create(account.id, c);
|
|
1080
|
+
headers.forEach((value, key) => c.header(key, value, { append: key.toLowerCase() === 'set-cookie' }));
|
|
1081
|
+
return c.redirect(config('auth.redirectAfterLogin'));
|
|
1082
|
+
}
|