@cossackframework/cms 0.9.2 → 0.9.4

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.
Files changed (120) hide show
  1. package/agent-docs.json +8 -8
  2. package/app/cossack-recipe.json +12 -8
  3. package/app/src/auth-events.ts +33 -0
  4. package/app/src/auth-input.ts +3 -0
  5. package/app/src/auth-options.ts +39 -7
  6. package/app/src/auth.ts +1309 -641
  7. package/app/src/avatars.ts +13 -0
  8. package/app/src/brand.ts +24 -2
  9. package/app/src/cms/actor.ts +13 -0
  10. package/app/src/cms/collab/room.ts +1 -1
  11. package/app/src/cms/content-api.ts +2 -1
  12. package/app/src/cms/content.ts +3 -2
  13. package/app/src/cms/dev-mail.ts +77 -0
  14. package/app/src/cms/index.ts +37 -10
  15. package/app/src/cms/maintenance.ts +1 -6
  16. package/app/src/cms/manage.ts +17 -14
  17. package/app/src/cms/middleware.ts +58 -18
  18. package/app/src/cms/network-accounts.ts +110 -0
  19. package/app/src/cms/notes-announce.ts +1 -1
  20. package/app/src/cms/people.ts +177 -0
  21. package/app/src/cms/recovery.ts +9 -14
  22. package/app/src/cms/request-calls.ts +56 -0
  23. package/app/src/cms/settings-form.ts +23 -6
  24. package/app/src/cms/settings-network.ts +8 -4
  25. package/app/src/cms/settings-search.ts +1 -0
  26. package/app/src/cms/site-editing.ts +3 -2
  27. package/app/src/cms/site-registration.ts +64 -0
  28. package/app/src/cms/site.ts +30 -19
  29. package/app/src/cms/sites.ts +182 -0
  30. package/app/src/dashboard/access.ts +3 -2
  31. package/app/src/dashboard/modules/users.ts +1 -0
  32. package/app/src/lib/permissions.ts +24 -0
  33. package/app/src/lib/uuid.ts +6 -0
  34. package/app/src/mail.ts +15 -0
  35. package/app/src/middlewares/auth.ts +6 -2
  36. package/app/src/middlewares/tenant.ts +108 -0
  37. package/app/src/pages/(site)/[...path]/index.ts +1 -1
  38. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +1 -1
  39. package/app/src/pages/api/cms/dev/mail.ts +19 -0
  40. package/app/src/pages/api/cms/forms/[slug]/index.ts +1 -1
  41. package/app/src/pages/api/cms/users/[id]/meta.ts +2 -1
  42. package/app/src/pages/auth/login/index.ts +1 -1
  43. package/app/src/pages/auth/magic/index.ts +1 -1
  44. package/app/src/pages/auth/recovery.ts +20 -0
  45. package/app/src/pages/auth/register-site/index.ts +146 -0
  46. package/app/src/pages/auth/setup/index.ts +8 -3
  47. package/app/src/pages/auth/tenant/callback.ts +23 -0
  48. package/app/src/pages/auth/tenant/redirect.ts +91 -0
  49. package/app/src/pages/auth/verify/index.ts +3 -7
  50. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +1 -1
  51. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +5 -5
  52. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +1 -1
  53. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +1 -1
  54. package/app/src/pages/dashboard/(cms)/network/index.ts +4 -2
  55. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +16 -13
  56. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +4 -2
  57. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +1 -1
  58. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +29 -10
  59. package/app/src/pages/dashboard/(cms)/network/users/index.ts +8 -7
  60. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +2 -1
  61. package/app/src/pages/dashboard/(cms)/registrations/index.ts +5 -4
  62. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +4 -1
  63. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +2 -1
  64. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +1 -1
  65. package/app/src/pages/dashboard/index.ts +3 -2
  66. package/app/src/pages/dashboard/roles/index.ts +2 -2
  67. package/app/src/pages/dashboard/users/registrations/index.ts +66 -0
  68. package/app/src/services/api-tokens.ts +86 -0
  69. package/app/src/services/rbac.ts +26 -15
  70. package/app/src/services/roles.ts +125 -35
  71. package/app/src/services/security.ts +384 -0
  72. package/app/src/services/tenants.ts +447 -0
  73. package/app/src/services/users.ts +241 -97
  74. package/app/src/tenants.ts +219 -0
  75. package/package.json +48 -12
  76. package/src/block-references.ts +3 -3
  77. package/src/collections.ts +3 -1
  78. package/src/forms.ts +4 -2
  79. package/src/hooks.ts +19 -1
  80. package/src/index.ts +4 -4
  81. package/src/isolate-core.ts +1 -1
  82. package/src/isolation.ts +1 -0
  83. package/src/manifest.ts +43 -2
  84. package/src/permissions.ts +13 -7
  85. package/src/resource.ts +85 -2
  86. package/src/server/attempts.ts +64 -0
  87. package/src/server/automations.ts +2 -2
  88. package/src/server/batch.ts +106 -0
  89. package/src/server/budget.ts +17 -0
  90. package/src/server/field-values.ts +207 -0
  91. package/src/server/forms.ts +3 -3
  92. package/src/server/host-schema.ts +55 -7
  93. package/src/server/host.ts +213 -85
  94. package/src/server/index.ts +9 -14
  95. package/src/server/isolation.ts +10 -0
  96. package/src/server/network.ts +129 -44
  97. package/src/server/outbox.ts +2 -2
  98. package/src/server/people.ts +191 -0
  99. package/src/server/reconcile.ts +5 -5
  100. package/src/server/repository.ts +243 -84
  101. package/src/server/shared-read.ts +34 -0
  102. package/src/server/site-export.ts +23 -13
  103. package/src/server/site-import.ts +12 -33
  104. package/src/server/site-settings.ts +9 -3
  105. package/src/server/sites.ts +117 -187
  106. package/src/server/stores.ts +3 -300
  107. package/src/server/taxonomies.ts +64 -13
  108. package/src/server/users.ts +151 -498
  109. package/src/settings-controls.ts +8 -4
  110. package/src/settings.ts +26 -3
  111. package/src/storage/cloudflare.ts +2 -0
  112. package/src/storage/index.ts +6 -0
  113. package/src/theme.ts +2 -2
  114. package/src/version.ts +1 -1
  115. package/app/src/cms/handoff.ts +0 -202
  116. package/src/server/accounts.ts +0 -418
  117. package/src/server/api-tokens.ts +0 -91
  118. package/src/server/auth.ts +0 -89
  119. package/src/server/handoffs.ts +0 -107
  120. package/src/server/security.ts +0 -391
package/agent-docs.json CHANGED
@@ -121,17 +121,17 @@
121
121
  },
122
122
  {
123
123
  "id": "cms-auth-and-stores",
124
- "title": "Use CMS auth, sessions and ledgers",
125
- "summary": "The scaffolded src/auth.ts runs @cossackframework/auth on CMS users and RomeDB sessions; createCmsAuth() does the same for hand-written apps, and the host provides the session bag and ledgers.",
124
+ "title": "Use CMS users, the people port and ledgers",
125
+ "summary": "Accounts, sign-in, sessions, roles and application passwords are the dashboard package's, on the database ORM; the CMS reads users through a people port (createCMS({ people })) and keeps their slug and field values, attempt counts and the job and notification ledgers.",
126
126
  "imports": [
127
127
  "@cossackframework/cms/server"
128
128
  ],
129
- "markdown": "With the `cms` feature, the scaffold renders the shared `auth` and `dashboard` pages over CMS storage: `src/auth.ts` exports the same functions as the database variant (`loginUser`, `registerUser`, `requestPasswordReset`, `resetPassword`, `listUserSessions`, …), backed by `cms.users` and `cms.authSessions`. Starting a session records the user's `lastSignInAt`, which outlives the session; `sessionsOf`, `revokeSessionOf` and `revokeSessionsOf` serve the user screen's Sessions tab, and `createApiToken`, `listApiTokens` and `revokeApiToken` its Application passwords tab; only the user and administrators see them (`canManageAccess`). An application password acts as its user, so give an integration its own user with a narrow role. Registration follows the General settings' \"Anyone can register\" and default role; reset tokens are stored as SHA-256 hashes and one request can use each.\n\n`createCmsAuth(cms)` returns the auth middleware, a session manager on the `cms_auth_sessions` table (keyed by token, so rotation is one conditional update and exactly one concurrent rotation wins), `signIn`, `signOut`, a realtime descriptor provider whose public reference survives rotation while the fingerprint does not, and `principal(c)` for the request. Accounts and members live in relational tables. `cms.accounts` (`cms_accounts`, on the network database, the main site's) is who can sign in: email, password hash (`@cossackframework/auth`'s hasher, `cms.accounts.verifier`), status, reset tokens and the network role; sessions, second factors and application passwords belong to the account. `cms.users` (`cms_users`) are the site's members under the account's ID, with the account's name, email, avatar and status copied in and the site's roles, slug and meta: it creates (an account and its membership), lists, searches, updates (profile changes go to the account first) and removes members, manages roles, and `resolve(id)` returns the member with its principal, or null unless the account is active and a member. An account with `networkRole: 'network_admin'` (`NETWORK_ADMIN`, `isNetworkAdmin(principal)`) also acts with `*`; setup makes the first account one, sites cannot define a role with that ID, and the last active network admin cannot be disabled, demoted or deleted. `createCMS({ db, network })` puts accounts on another database; `network` defaults to `db`. `DEFAULT_ROLES` are Administrator, Editor, Author and Subscriber.\n\n`cms.sessions` is the framework session bag with one row per key, so concurrent writes to different keys never overwrite each other. `cms.oauthStates` consumes OAuth state with one conditional delete. `cms.jobs()` and `cms.notifications()` are the core RomeQL ledgers on RomeDB. `FileService` keeps bytes in Cossack object storage and ownership in RomeDB, with a `sweep()` that finishes or cleans up interrupted uploads and deletes.\n\n`cms:users` manages accounts and `cms:roles` defines roles and chooses users' roles; the dashboard lets a user manager without `cms:roles` add users only with the default role and keeps accounts that can manage roles out of its reach. `cms.uploadAvatar(userId, file, { principal })` stores a still or animated profile picture (PNG, JPEG, GIF, WebP, AVIF; 5 MB) in the media library for the user themself or a user manager, sets it on the user and returns its URL.",
129
+ "markdown": "With the `cms` feature a project mounts the dashboard package's sign-in pages and dashboard: `#app/auth` (`loginUser`, `registerUser`, `requestPasswordReset`, `listUserSessions`, `createApiToken`, …) keeps accounts, sessions, second factors, passkeys, roles and application passwords in the ORM's tables (`users`, `roles`, `user_roles`, `sessions`, `api_tokens`, …) in the same RomeDB database as the CMS. The CMS library holds none of them.\n\n`createCMS({ db, people })` takes a `PeoplePort`: `getMany`, `findByEmail`, `list`, `count`, `roles`, `role`, `defineRole`, `create`, `update`, `setRoles`, `delete`, and for a network `join`, `ownCount` and `adopt`. The CMS app fills it from the ORM's models; without one, `memoryPeople()` keeps users in memory, for tests and scripts. `cms.users` is the CMS's view of them: a `CmsUser` is the person with their roles and permissions, plus what the CMS keeps itself, the author slug (`cms_authors`) and the values of user field groups (documents in `cms/user_fields`). It creates, lists, searches, updates and deletes users through the port, `setRoles`, `defineRole`, `addMember(accountId, { roles })` for a network account, and `resolve(id)` / `principal(id)` return the request user, or null unless active. A network administrator (`person.networkAdmin`; `NETWORK_ADMIN`, `isNetworkAdmin(principal)`) also acts with `*`. `DEFAULT_ROLES` are Administrator, Editor, Author and Subscriber; a role's ID is its handle (`admin`, `editor`).\n\n`cms.attempts.attempt(kind, key, max, windowMs)` counts tries per key for forms, suggestions, recovery and site registration, and `release` gives one back. `cms.jobs()` and `cms.notifications()` are the core RomeQL ledgers on RomeDB. `FileService` keeps bytes in Cossack object storage and ownership in RomeDB, with a `sweep()` that finishes or cleans up interrupted uploads and deletes.\n\n`cms:users` manages users and `cms:roles` defines roles and chooses users' roles. `cms.uploadAvatar(userId, file, { principal })` stores a still or animated profile picture (PNG, JPEG, GIF, WebP, AVIF; 5 MB) in the media library for the user themself or a user manager, sets it on the user and returns its URL.",
130
130
  "examples": [
131
131
  {
132
132
  "id": "cms-auth-and-stores",
133
133
  "language": "typescript",
134
- "source": "import { Hono } from 'hono';\nimport { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { createCMS, createCmsAuth } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\nconst cms = createCMS({ db });\nconst kit = createCmsAuth(cms, { secure: false });\n\nexport const app = new Hono();\napp.use('*', kit.auth.middleware);\napp.post('/sign-in', async c => {\n const form = await c.req.formData();\n const signedIn = await kit.signIn(String(form.get('email')), String(form.get('password')), c);\n if (!signedIn) return c.text('Wrong email or password.', 401);\n signedIn.headers.forEach((value, name) => c.header(name, value, { append: true }));\n return c.redirect('/');\n});\napp.get('/me', c => c.json(kit.principal(c)));\n// The framework session bag, job and notification ledgers on RomeDB:\nexport const stores = { sessions: cms.sessions, jobs: cms.jobs(), notifications: cms.notifications() };\n"
134
+ "source": "import { createRomeDB, MemoryPendingWriteStore } from '@cossackframework/romedb';\nimport { createCMS, DEFAULT_ROLES, memoryPeople } from '@cossackframework/cms/server';\n\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending: new MemoryPendingWriteStore() });\n// An application passes its own port (the CMS app's reads the ORM's users); this one keeps users in memory.\nconst people = memoryPeople();\nconst cms = createCMS({ db, people });\n\nexport async function firstEditor() {\n for (const role of DEFAULT_ROLES) await cms.users.defineRole({ ...role, permissions: [...role.permissions] });\n const user = await cms.users.create({ email: 'ada@example.com', name: 'Ada Lovelace', roles: ['editor'] });\n // The principal carries the roles' permissions; pass it to resources and host methods.\n return cms.users.principal(user.id);\n}\n\nexport async function mayTry(address: string): Promise<boolean> {\n return cms.attempts.attempt('contact', address, 5, 15 * 60_000);\n}\n// The job and notification ledgers on RomeDB:\nexport const stores = { jobs: cms.jobs(), notifications: cms.notifications() };\n"
135
135
  }
136
136
  ]
137
137
  },
@@ -143,7 +143,7 @@
143
143
  "@cossackframework/cms",
144
144
  "@cossackframework/cms/server"
145
145
  ],
146
- "markdown": "**Scheduling.** Saving `published` with a future `publishedAt` stores `scheduled`; `cms.runSchedule()` (run by maintenance every minute) publishes due entries as `system:scheduler`, so outbox events and webhooks fire then. `pending` means pending review. Visitors read `published` only.\n\n**Previews and autosave.** `cms.createPreviewLink(resource, id, principal)` returns a 7-day token stored as its SHA-256; `cms.previewByToken(token)` reads the entry whatever its status, and `revokePreviewLinks` ends them. `cms.autosave(resource, id | 'new', principal, values)`, `latestAutosave` and `discardAutosave` keep one autosave per user and entry.\n\n**Revisions.** `repository.revision(id, n)`, `repository.restore(id, n, { expectedRevision })` (keeps status, publication time, slug, nesting and language) and `compareRecords(fields, before, after)` / `diffWords(a, b)` for word-level diffs.\n\n**Redirects.** When a published entry's URL changes, the update's batch records a 301 from the old URL, retargets redirects to it and drops one from the new URL; path changes of collections and taxonomies add prefix redirects (`/old/*` to `/new/*`). `cms.redirects.match(path)` serves paths without content; `save`, `list`, `delete` and `hit` manage them. Statuses: 301, 302, 307, 308 and 410.\n\n**API and webhooks.** `cms.apiTokens.create(userId, { name, scope })` returns `cms_<id>.<secret>` once; `cms.tokenPrincipal(token)` resolves it (read-only tokens may only GET). `cms.webhooks.save({ name, url, events, collections })` subscribes to `entry.created`, `entry.updated`, `entry.published`, `entry.unpublished` and `entry.deleted`; deliveries are queued from the outbox and sent by `cms.webhooks.dispatch()` with `X-Cossack-Signature: sha256=` HMAC of `<timestamp>.<body>` (check with `verifyWebhookSignature`), retried over six attempts.\n\n**Comments.** `cms.postComment(input, { principal, ip })` applies Settings → Discussion (sign-in, name and email, closing after N days, thread depth, moderation of all or first-time commenters, links, disallowed words) and a 15-second throttle per address; `cms.moderateComments(ids, status | 'delete', principal)` needs `cms:comments`.\n\n**Patterns and languages.** The built-in `patterns` collection holds reusable blocks; a `core/pattern` block references a synced one. `cms.saveLanguages({ default, others }, principal)` sets the site's languages; other languages' URLs get a `/<code>` prefix from `entryUrls`, `cms.translations(collection, record)` maps languages to entries and `cms.translateEntry(collection, id, locale, principal)` starts a draft translation.\n\n**Images.** Pass `images: ImageTransformer` (the Images binding on Workers, sharp on Node) to `createCMS`; `cms.files.variant(id, { width, height, accept })` makes and keeps resized AVIF/WebP variants, `setEdits(id, { crop, focus })` crops and sets the focal point, and `imageSrcset(file)` lists variants for `srcset`.\n\n**Sign-in security.** `cms.security` keeps authenticator secrets (`startTotp`, `confirmTotp`, `verifyCode`), recovery codes, passkeys and short-lived challenges for pending sign-ins.",
146
+ "markdown": "**Scheduling.** Saving `published` with a future `publishedAt` stores `scheduled`; `cms.runSchedule()` (run by maintenance every minute) publishes due entries as `system:scheduler`, so outbox events and webhooks fire then. `pending` means pending review. Visitors read `published` only.\n\n**Previews and autosave.** `cms.createPreviewLink(resource, id, principal)` returns a 7-day token stored as its SHA-256; `cms.previewByToken(token)` reads the entry whatever its status, and `revokePreviewLinks` ends them. `cms.autosave(resource, id | 'new', principal, values)`, `latestAutosave` and `discardAutosave` keep one autosave per user and entry.\n\n**Revisions.** `repository.revision(id, n)`, `repository.restore(id, n, { expectedRevision })` (keeps status, publication time, slug, nesting and language) and `compareRecords(fields, before, after)` / `diffWords(a, b)` for word-level diffs.\n\n**Redirects.** When a published entry's URL changes, the update's batch records a 301 from the old URL, retargets redirects to it and drops one from the new URL; path changes of collections and taxonomies add prefix redirects (`/old/*` to `/new/*`). `cms.redirects.match(path)` serves paths without content; `save`, `list`, `delete` and `hit` manage them. Statuses: 301, 302, 307, 308 and 410.\n\n**API and webhooks.** Application passwords (`cms_<id>.<secret>`, read-only or read and write) are the dashboard package's: `createApiToken`, `listApiTokens` and `revokeApiToken` in `#app/auth`. `cms.webhooks.save({ name, url, events, collections })` subscribes to `entry.created`, `entry.updated`, `entry.published`, `entry.unpublished` and `entry.deleted`; deliveries are queued from the outbox and sent by `cms.webhooks.dispatch()` with `X-Cossack-Signature: sha256=` HMAC of `<timestamp>.<body>` (check with `verifyWebhookSignature`), retried over six attempts.\n\n**Comments.** `cms.postComment(input, { principal, ip })` applies Settings → Discussion (sign-in, name and email, closing after N days, thread depth, moderation of all or first-time commenters, links, disallowed words) and a 15-second throttle per address; `cms.moderateComments(ids, status | 'delete', principal)` needs `cms:comments`.\n\n**Patterns and languages.** The built-in `patterns` collection holds reusable blocks; a `core/pattern` block references a synced one. `cms.saveLanguages({ default, others }, principal)` sets the site's languages; other languages' URLs get a `/<code>` prefix from `entryUrls`, `cms.translations(collection, record)` maps languages to entries and `cms.translateEntry(collection, id, locale, principal)` starts a draft translation.\n\n**Images.** Pass `images: ImageTransformer` (the Images binding on Workers, sharp on Node) to `createCMS`; `cms.files.variant(id, { width, height, accept })` makes and keeps resized AVIF/WebP variants, `setEdits(id, { crop, focus })` crops and sets the focal point, and `imageSrcset(file)` lists variants for `srcset`.",
147
147
  "examples": [
148
148
  {
149
149
  "id": "cms-publishing",
@@ -189,16 +189,16 @@
189
189
  {
190
190
  "id": "cms-multisite",
191
191
  "title": "Run a network of sites",
192
- "summary": "CmsNetwork resolves a request's host to a site with its own RomeDB database, shares accounts from the main (network) database, hands sign-ins to sites as child sessions, and creates, archives and deletes sites.",
192
+ "summary": "CmsNetwork resolves a request's host to a site with its own RomeDB database and creates, archives and deletes sites; the site registry (the dashboard package's tenants) and the shared accounts are the application's.",
193
193
  "imports": [
194
194
  "@cossackframework/cms/server"
195
195
  ],
196
- "markdown": "Every CMS install is a network of one site. The main database (the network database) holds the accounts (`cms_accounts`, `cms.accounts`) and the site registry (`cms_sites`, `cms_site_domains`); each added site has its own database with the same host schema, its own members (`cms_users`, `cms.users`), roles, content and settings. No query spans two databases.\n\n`new CmsNetwork({ db, host, open, directory, networkHost })` builds one per isolate: `host(site, db)` must call `createCMS({ db, network, site: site.id, sessionsEnded: ended => network.endSessions(ended) })`; `open(site)` opens a site's database by `site.database`; `directory` (`organizationDatabases` for a RomeDB Cloud organization or `romedb serve --directory`, `fileDatabases` on Node) creates and deletes them. `network.resolve(host)` returns `site`, `redirect` (an alias to its primary domain), `archived` or `missing`; while the network has one site every host serves it. `network.hostOf(site)` keeps 32 hosts per isolate. Media of an added site sits under `sites/<id>/` (`prefixedStorage`).\n\nSign-in happens only on the network host. A site sends visitors to the network's `/auth/handoff`; the network issues a one-use code (`network.handoffs`), and the site trades it for a child session in its own database that carries the network role, so site requests read only the site's database. Ending a network session (sign-out, password reset, suspension, new network role, deleting the account) ends its child sessions through `sessionsEnded`. A network admin (`NETWORK_ADMIN`, `isNetworkAdmin`) acts with `*` on every site; setup makes the first account one, and the last cannot be removed.\n\nNetwork admins manage sites: `createSite({ name, host, admin, starter?, language? }, { principal })` records each step (database, schema, roles and settings with the network's defaults, first administrator) and resumes after a failure; `addDomain`, `checkDomain` (the domain's `/.well-known/cossack-site` must answer with the site ID before it becomes primary), `removeDomain`; `setSiteStatus` (archive, delete, restore) and `purgeDeleted` (30 days after deletion); `deleteAccount` removes an account from every site, then the account. `setPluginState(name, 'network' | 'available' | 'hidden', { principal })` runs a plugin on every site with the grants approved then (sites migrate it as they load and cannot disable it), leaves it to each site, or hides it; `setThemeState(name, 'available' | 'hidden')` controls which themes sites may choose (`host.availableThemes()`). `saveSettings({ defaultTheme, defaultPlugins, defaultLanguage })` sets what new sites start with. The CMS app's `/dashboard/network` pages use these. See docs/cms/multisite.md.",
196
+ "markdown": "Every CMS install is a network of one site. Each added site has its own database with the same host schema, its own members, roles, content and settings. No query spans two databases. The registry of sites and the accounts they share are the application's: in the CMS app the sites are the dashboard package's tenants (`tenants`, `tenant_domains` in the main database), and a member of a site is a row of that site's `users` under the account's ID.\n\n`new CmsNetwork({ db, sites, host, open, directory, networkHost, memberSites, inSite })` builds one per isolate: `sites` is a `SitesStore` (`memorySites()` for tests and scripts); `host(site, db)` must call `createCMS({ db, network, site: site.id, people })`; `open(site)` opens a site's database by `site.database`; `directory` (`organizationDatabases` for a RomeDB Cloud organization or `romedb serve --directory`, `fileDatabases` on Node) creates and deletes them; `memberSites(accountId)` lists the added sites an account belongs to and `inSite(site, work)` runs work on a site's users in that site's database. `network.resolve(host)` returns `site`, `redirect` (an alias to its primary domain), `archived` or `missing`; while the network has one site every host serves it. `network.hostOf(site)` keeps 32 hosts per isolate. Media of an added site sits under `sites/<id>/` (`prefixedStorage`).\n\nSign-in is the dashboard package's (`tenants.signIn`): with shared sign-in a site sends visitors to the main host's `/auth/tenant/redirect`, which issues a one-use code the site trades at `/auth/tenant/callback` for a session in its own database; ending any session of the family ends all of it. A network administrator (`NETWORK_ADMIN`, `isNetworkAdmin`) acts with `*` on every site; setup makes the first account one, and the last cannot be removed.\n\nNetwork admins manage sites: `createSite({ name, host, admin, starter?, language? }, { principal })` records each step (database, schema, roles and settings with the network's defaults, first administrator) and resumes after a failure; `addDomain`, `checkDomain` (the domain's `/.well-known/cossack-site` must answer with the site ID before it becomes primary), `removeDomain`; `setSiteStatus` (archive, delete, restore) and `purgeDeleted` (30 days after deletion). `setPluginState(name, 'network' | 'available' | 'hidden', { principal })` runs a plugin on every site with the grants approved then (sites migrate it as they load and cannot disable it), leaves it to each site, or hides it; `setThemeState(name, 'available' | 'hidden')` controls which themes sites may choose (`host.availableThemes()`). `saveSettings({ defaultTheme, defaultPlugins, defaultLanguage })` sets what new sites start with. The CMS app's `/dashboard/network` pages use these. See docs/cms/multisite.md.",
197
197
  "examples": [
198
198
  {
199
199
  "id": "cms-multisite",
200
200
  "language": "typescript",
201
- "source": "import { createRomeDB, MemoryPendingWriteStore, organizationDatabases } from '@cossackframework/romedb';\nimport { CmsNetwork, createCMS, type Principal } from '@cossackframework/cms/server';\n\nconst pending = new MemoryPendingWriteStore();\nconst organization = organizationDatabases({ url: 'https://cloud.romedb.com/v1/organizations/0b6c1a43-5a2e-4f0e-9b37-2f1e8c0d4a11', token: 'organization-key' });\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending });\n\n// The main database holds the accounts and the site registry; each added site has its own.\nconst network: CmsNetwork = new CmsNetwork({\n db,\n networkHost: () => 'example.com',\n directory: organization,\n open: site => createRomeDB({ url: organization.url(site.database), token: 'organization-key', pending }),\n host: (site, siteDb) => createCMS({ db: siteDb, network: db, site: site.id, sessionsEnded: ended => network.endSessions(ended) }),\n});\n\nexport async function hostFor(hostName: string) {\n const found = await network.resolve(hostName);\n return found.kind === 'site' ? network.hostOf(found.site) : null;\n}\n\nexport function addBlog(principal: Principal, admin: string) {\n return network.createSite({ name: 'Blog', host: 'blog.example.com', admin }, { principal });\n}\n"
201
+ "source": "import { createRomeDB, MemoryPendingWriteStore, organizationDatabases } from '@cossackframework/romedb';\nimport { CmsNetwork, createCMS, memoryPeople, memorySites, type Principal } from '@cossackframework/cms/server';\n\nconst pending = new MemoryPendingWriteStore();\nconst organization = organizationDatabases({ url: 'https://cloud.romedb.com/v1/organizations/0b6c1a43-5a2e-4f0e-9b37-2f1e8c0d4a11', token: 'organization-key' });\nconst db = createRomeDB({ url: 'http://127.0.0.1:4321', token: 'local-service-token', pending });\n\n// The application keeps the site registry and the accounts; these keep them in memory.\nconst accounts = memoryPeople();\nconst members = new Map<string, ReturnType<typeof memoryPeople>>();\nconst peopleOf = (site: string) => site === 'main' ? accounts : members.get(site) ?? members.set(site, memoryPeople({ network: accounts })).get(site)!;\n\nconst network: CmsNetwork = new CmsNetwork({\n db,\n sites: memorySites(),\n networkHost: () => 'example.com',\n directory: organization,\n open: site => createRomeDB({ url: organization.url(site.database), token: 'organization-key', pending }),\n host: (site, siteDb) => createCMS({ db: siteDb, network: db, site: site.id, people: peopleOf(site.id) }),\n});\n\nexport async function hostFor(hostName: string) {\n const found = await network.resolve(hostName);\n return found.kind === 'site' ? network.hostOf(found.site) : null;\n}\n\nexport function addBlog(principal: Principal, admin: string) {\n return network.createSite({ name: 'Blog', host: 'blog.example.com', admin }, { principal });\n}\n"
202
202
  }
203
203
  ]
204
204
  },
@@ -6,25 +6,24 @@
6
6
  "src/pages/dashboard/(cms)/",
7
7
  "src/pages/(site)/",
8
8
  "src/pages/auth/setup/",
9
- "src/pages/auth/verify/",
10
- "src/pages/auth/magic/",
11
9
  "src/pages/api/cms/",
12
10
  "src/pages/api/auth/",
13
11
  "src/config/cms.ts",
14
12
  "src/plugins/default-theme/",
15
13
  "src/pages/dashboard/index.ts",
16
14
  "src/brand.ts",
17
- "src/auth.ts",
18
15
  "src/auth-options.ts",
19
16
  "src/passkeys.client.ts",
20
- "src/services/users.ts",
21
- "src/services/roles.ts",
22
- "src/services/rbac.ts",
23
17
  "src/lib/permissions.ts",
24
18
  "src/dashboard/access.ts",
25
19
  "src/dashboard/icons.ts",
26
20
  "src/dashboard/head.ts",
27
- "src/dashboard/user-sections.ts"
21
+ "src/dashboard/user-sections.ts",
22
+ "src/mail.ts",
23
+ "src/avatars.ts",
24
+ "src/auth-events.ts",
25
+ "src/services/rbac.ts",
26
+ "src/pages/auth/register-site/"
28
27
  ],
29
28
  "shell": [
30
29
  "src/pages/auth/",
@@ -35,7 +34,12 @@
35
34
  "src/auth-bot-check.ts",
36
35
  "src/auth-bot-token.ts",
37
36
  "src/config/auth.ts",
38
- "src/auth-providers.ts"
37
+ "src/auth-providers.ts",
38
+ "src/auth.ts",
39
+ "src/tenants.ts",
40
+ "src/services/",
41
+ "src/middlewares/tenant.ts",
42
+ "src/lib/uuid.ts"
39
43
  ],
40
44
  "rendered": [
41
45
  "src/cms.config.ts"
@@ -0,0 +1,33 @@
1
+ // What the CMS does around sign-in, for the shared sign-in code (auth.ts): plugins have a say
2
+ // in a registration (`cms.user.before-register`), and the site hears of registrations and
3
+ // sign-ins (`cms.user.registered`, `cms.user.signed-in`, through the outbox).
4
+ import { ClientVisibleError, getRequestContext } from '@cossackframework/core';
5
+ import { isCmsError } from '@cossackframework/cms';
6
+ import { currentCms } from './cms/index';
7
+
8
+ export interface AuthUserRef { id: string; email: string; name: string }
9
+
10
+ export const authEvents = {
11
+ async beforeRegister(draft: { email: string; name: string }): Promise<{ name: string }> {
12
+ const cms = currentCms();
13
+ const c = getRequestContext();
14
+ try {
15
+ const settings = await cms.settings.all();
16
+ const role = settings['general.defaultRole'];
17
+ const result = await cms.registrationDraft({ email: draft.email, name: draft.name.trim() || draft.email.split('@')[0]!, roles: role && (await cms.users.role(role)) ? [role] : [], approval: settings['general.approveRegistrations'] === true },
18
+ { origin: c ? new URL(c.req.url).origin : '' });
19
+ return { name: result.name };
20
+ } catch (error) {
21
+ if (isCmsError(error)) throw new ClientVisibleError(error.message);
22
+ throw error;
23
+ }
24
+ },
25
+ async registered(user: AuthUserRef, state: 'active' | 'verification' | 'approval' = 'active'): Promise<void> {
26
+ await currentCms().userRegistered(user, state).catch(() => undefined);
27
+ },
28
+ async signedIn(user: { id: string }): Promise<void> {
29
+ const cms = currentCms();
30
+ const member = await cms.users.get(user.id).catch(() => null);
31
+ if (member) await cms.userSignedIn({ id: member.id, email: member.email, name: member.name }, '').catch(() => undefined);
32
+ },
33
+ };
@@ -16,6 +16,9 @@ export type LoginInput = InputOf<typeof loginInput>;
16
16
  export const registerInput = input.object({ name: input.string({ maxLength: 191 }), email, password, turnstile });
17
17
  export type RegisterInput = InputOf<typeof registerInput>;
18
18
 
19
+ export const setupInput = input.object({ code: input.string({ required: true, maxLength: 512 }), name: input.string({ maxLength: 191 }), email, password });
20
+ export type SetupInput = InputOf<typeof setupInput>;
21
+
19
22
  export const resetRequestInput = input.object({ email, turnstile });
20
23
  export type ResetRequestInput = InputOf<typeof resetRequestInput>;
21
24
 
@@ -1,13 +1,20 @@
1
- // The choices the shared sign-in pages and dashboard read. A project on the database ORM
2
- // states them in src/dashboard.config.ts. The CMS always has email and password (with passkeys
3
- // and sign-in links, which its auth.ts adds) and every account screen; the OAuth providers are
4
- // the site's `oauth` option in src/cms.config.ts.
1
+ // The choices the shared sign-in pages, the dashboard and the sign-in code (auth.ts) read. A
2
+ // project on the dashboard package alone states them in src/dashboard.config.ts; the CMS
3
+ // reads them from the site: the OAuth providers from `oauth` in src/cms.config.ts, and
4
+ // registration and two-step sign-in from Settings → General, as they are for this request.
5
+ import { getRequestContext } from '@cossackframework/core';
6
+ import { settingRoles, type SiteSettings } from '@cossackframework/cms';
5
7
  import type { DashboardNavigationItem } from './dashboard/types';
6
- import { currentCms } from './cms/index';
7
8
 
9
+ /** The OAuth providers of this request's site. Read from the request, not through ./cms/index, which imports the sign-in code that reads these options. */
8
10
  function providers(): string[] {
9
- try { return [...currentCms().oauth]; }
10
- catch { return []; }
11
+ const cms = getRequestContext()?.get('cms' as never) as { oauth?: readonly string[] } | undefined;
12
+ return cms?.oauth ? [...cms.oauth] : [];
13
+ }
14
+
15
+ /** The site's settings of this request; src/cms/middleware.ts reads them once and keeps them here. */
16
+ function settings(): Partial<SiteSettings> {
17
+ return (getRequestContext()?.get('cms.settings' as never) as Partial<SiteSettings> | undefined) ?? {};
11
18
  }
12
19
 
13
20
  export const authOptions = {
@@ -18,4 +25,29 @@ export const authOptions = {
18
25
  redirectAfterLogin: '/dashboard',
19
26
  /** The CMS's screens come from its own navigation and its plugins, not from this list. */
20
27
  navigation: [] as DashboardNavigationItem[],
28
+ /** Settings → General: who registers, and what a new account waits for. */
29
+ get registration() {
30
+ const site = settings();
31
+ return { open: site['general.usersCanRegister'] === true, verifyEmail: site['general.verifyEmail'] !== false, approve: site['general.approveRegistrations'] === true, defaultRole: site['general.defaultRole'] ?? '' };
32
+ },
33
+ /** Settings → General: two-step sign-in for the people who use the dashboard. */
34
+ get security() {
35
+ const site = settings();
36
+ return { requireTwoFactor: site['general.requireTwoFactor'] === true, twoFactorRoles: settingRoles(site['general.twoFactorRoles']) };
37
+ },
38
+ /**
39
+ * A network's sites are the dashboard package's tenants. Each site signs in its own accounts,
40
+ * and people with a network account sign in on the network host (shared sign-in).
41
+ */
42
+ tenants: { enabled: true, signIn: 'shared' as 'host' | 'shared', verifyDomains: true },
43
+ /** Application passwords start with `cms_`. */
44
+ tokenPrefix: 'cms',
45
+ /** On a site of a network: members with a network account. */
46
+ accountLabels: {
47
+ shared: 'Network account',
48
+ sharedNotice: '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.',
49
+ },
50
+ /** The CMS's setup code. */
51
+ setupCodeVariable: 'CMS_SETUP_CODE',
52
+ recoveryCodeVariable: 'CMS_RECOVERY_CODE',
21
53
  };