@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
@@ -0,0 +1,13 @@
1
+ // Where an uploaded profile picture goes, for the shared sign-in code (auth.ts): the site's
2
+ // media library.
3
+ import { getRequestContext } from '@cossackframework/core';
4
+ import { ANONYMOUS, type Principal } from '@cossackframework/cms';
5
+ import { currentCms } from './cms/index';
6
+
7
+ export const avatarUploads = true;
8
+
9
+ /** Store the picture in the media library, as the signed-in user, and answer its URL. */
10
+ export async function storeAvatar(userId: string, file: File): Promise<string> {
11
+ const principal = (getRequestContext()?.get('principal') as Principal | undefined) ?? ANONYMOUS;
12
+ return currentCms().uploadAvatar(userId, { name: file.name, contentType: file.type, size: file.size, body: file.stream() }, { principal });
13
+ }
package/app/src/brand.ts CHANGED
@@ -2,7 +2,9 @@
2
2
  import { getRequestContext } from '@cossackframework/core';
3
3
  import { MAIN_SITE } from '@cossackframework/cms';
4
4
  import { currentCms, networkFor, siteUrl, type CmsBindings } from './cms/index';
5
- import { pendingSite } from './cms/handoff';
5
+ import { getCookie } from 'hono/cookie';
6
+ import type { Context } from 'hono';
7
+ import type { CmsNetwork, NetworkSite } from '@cossackframework/cms/server';
6
8
 
7
9
  export async function siteName(): Promise<string> {
8
10
  try { return await currentCms().settings.get('general.siteTitle'); }
@@ -48,7 +50,7 @@ export async function signInBrand(): Promise<SignInBrand> {
48
50
  const env = c.env as CmsBindings;
49
51
  const network = networkFor(env);
50
52
  if (c.get('site') && c.get('site').id !== MAIN_SITE) {
51
- return own(env.APP_URL ? { href: '/auth/handoff', name: (await network.settings()).name || await network.main.settings.get('general.siteTitle') } : null);
53
+ return own(env.APP_URL ? { href: '/auth/tenant/start', name: (await network.settings()).name || await network.main.settings.get('general.siteTitle') } : null);
52
54
  }
53
55
  const site = await pendingSite(c, network);
54
56
  if (!site) return own();
@@ -66,3 +68,23 @@ export async function signInBrand(): Promise<SignInBrand> {
66
68
  };
67
69
  } catch { return own(); }
68
70
  }
71
+
72
+ /**
73
+ * On the network host: the site that sent the visitor here to sign in (shared sign-in keeps
74
+ * its address in the `tenant_return` cookie until they are signed in), or null.
75
+ */
76
+ async function pendingSite(c: Context, network: CmsNetwork): Promise<NetworkSite | null> {
77
+ const host = new URLSearchParams(getCookie(c, 'tenant_return') ?? '').get('host');
78
+ if (!host) return null;
79
+ const found = await network.resolve(host).catch(() => null);
80
+ return found?.kind === 'site' && found.site.id !== MAIN_SITE ? found.site : null;
81
+ }
82
+
83
+ /** What the network host is called on a site's pages: the network's name, or the main site's title. */
84
+ export async function mainSiteName(): Promise<string> {
85
+ const c = getRequestContext();
86
+ try {
87
+ const network = networkFor(c!.env as CmsBindings);
88
+ return (await network.settings()).name || await network.main.settings.get('general.siteTitle') || 'the network';
89
+ } catch { return 'the network'; }
90
+ }
@@ -0,0 +1,13 @@
1
+ // The caller of a request as the shared access helpers (services/rbac.ts) take them.
2
+ import { NETWORK_ADMIN, type Principal } from '@cossackframework/cms';
3
+ import type { PublicUser } from '#app/auth';
4
+
5
+ /**
6
+ * A principal as a user of the shared helpers: an application password's request has no
7
+ * session user, so its principal's permissions stand in as one role.
8
+ */
9
+ export function userOfPrincipal(principal: Extract<Principal, { kind: 'user' }>): PublicUser {
10
+ return { id: principal.id, email: '', name: '', avatar: null, meta: null,
11
+ roles: [{ id: 'principal', name: 'principal', permissions: [...principal.permissions] }],
12
+ ...(principal.roles.includes(NETWORK_ADMIN) ? { networkAdmin: true } : {}) };
13
+ }
@@ -92,7 +92,7 @@ export const requireEntryEditor: MiddlewareHandler = defineServerMiddleware(asyn
92
92
  const { resource } = routeResource(cms, route);
93
93
  const repository = cms.resource(resource.id);
94
94
  const record = await repository.get(id, { principal });
95
- allowed = record !== null && repository.canUpdate(record, principal);
95
+ allowed = record !== null && await repository.canUpdate(record, { principal });
96
96
  } catch (error) {
97
97
  // Only a passing database error keeps an earlier yes, and only for a while: a lost
98
98
  // entry, collection or right, an inactive plugin or a pending migration refuses.
@@ -25,9 +25,10 @@ export async function apiEntries(cms: CmsHost, collection: CollectionDefinition,
25
25
  // The password itself never leaves. A protected entry's fields stay with those who may edit
26
26
  // it, and a members-only entry's with signed-in users: others get its core fields alone.
27
27
  const withheld = withheldFields(cms, collection);
28
+ const editable = principal === undefined ? new Set<string>() : await repository.editable(records, { principal });
28
29
  records = records.map(record => {
29
30
  const { password, ...rest } = record;
30
- const editor = principal !== undefined && repository.canUpdate(record, principal);
31
+ const editor = editable.has(record.id);
31
32
  const lock = entryLock(record, { editor, signedIn: principal?.kind === 'user', roles: principal?.kind === 'user' ? principal.roles : [] });
32
33
  if (!lock) return (typeof password === 'string' && password ? (editor ? record : rest) : rest) as RecordShape;
33
34
  const bare = Object.fromEntries(Object.entries(rest).filter(([name]) => !withheld.has(name))) as unknown as RecordShape;
@@ -358,7 +358,7 @@ export async function duplicateEntry(cms: CmsHost, route: string, id: string, pr
358
358
  const source = await repository.get(id, { principal });
359
359
  if (!source) throw new CmsError('CMS_NOT_FOUND', 'The entry does not exist.');
360
360
  // A copy holds everything the entry does: a reader the entry is locked for gets no copy to open.
361
- if (lockedCopy(source, repository.canUpdate(source, principal))) throw new CmsError('CMS_FORBIDDEN', 'Only its editors can copy a protected or members-only entry.');
361
+ if (lockedCopy(source, await repository.canUpdate(source, { principal }))) throw new CmsError('CMS_FORBIDDEN', 'Only its editors can copy a protected or members-only entry.');
362
362
  const input: Record<string, unknown> = {};
363
363
  for (const [name, declaration] of Object.entries(resource.fields)) {
364
364
  // Empty fields stay unset: the repository refuses null where a field has no value.
@@ -497,8 +497,9 @@ export async function* exportEntries(cms: CmsHost, route: string, principal: Pri
497
497
  // may change in full, others without their password, and none the caller could not open
498
498
  // (a protected entry, or members-only for other roles).
499
499
  const roles = principal.kind === 'user' ? principal.roles : [];
500
+ const editable = await repository.editable(page.records, { principal });
500
501
  const records = page.records.flatMap(record => {
501
- if (repository.canUpdate(record, principal)) return [record];
502
+ if (editable.has(record.id)) return [record];
502
503
  if (entryLock(record, { editor: false, signedIn: principal.kind === 'user', roles })) return [];
503
504
  const { password: _password, ...rest } = record;
504
505
  return [rest as RecordShape];
@@ -0,0 +1,77 @@
1
+ import type { Context } from 'hono';
2
+ import type { MailTransport } from '@cossackframework/cms/server';
3
+
4
+ /** An email the CMS sent while APP_URL names this machine. */
5
+ export interface DevMail {
6
+ readonly site: string;
7
+ readonly to: string;
8
+ readonly from: string;
9
+ readonly subject: string;
10
+ readonly text: string;
11
+ readonly html: string;
12
+ readonly replyTo?: string;
13
+ /** When it was sent, in milliseconds since the epoch. */
14
+ readonly sentAt: number;
15
+ }
16
+
17
+ /** The mail this isolate sent in development, oldest first; the newest 200. */
18
+ const sent: DevMail[] = [];
19
+ const KEPT = 200;
20
+
21
+ /**
22
+ * Development: every email a site sends is kept in memory and printed in the dev server's
23
+ * terminal, so a script reads an invitation's or a reset's link from `GET /api/cms/dev/mail`
24
+ * instead of a mail service. With a transport (the local `EMAIL` binding, or `mail` in
25
+ * src/cms.config.ts), the email goes there too; without one, it goes nowhere else.
26
+ */
27
+ export function devMailTransport(site: string, transport: MailTransport | undefined): MailTransport {
28
+ return {
29
+ async send(message) {
30
+ sent.push({ site, to: message.to, from: message.from, subject: message.subject, text: message.text, html: message.html,
31
+ ...(message.replyTo ? { replyTo: message.replyTo } : {}), sentAt: Date.now() });
32
+ if (sent.length > KEPT) sent.splice(0, sent.length - KEPT);
33
+ console.log(`[cms] mail to ${message.to}: ${message.subject}\n${message.text}\n`);
34
+ return transport?.send(message);
35
+ },
36
+ };
37
+ }
38
+
39
+ /** The hosts whose only transport is the development one: their mail is kept and printed, and sent nowhere. */
40
+ const keptOnly = new WeakSet<object>();
41
+
42
+ /** Note that this host has no transport of its own. Returns the host. */
43
+ export function markMailKeptOnly<T extends object>(host: T): T {
44
+ keptOnly.add(host);
45
+ return host;
46
+ }
47
+
48
+ /** Whether the host's mail is only kept for `GET /api/cms/dev/mail`, because no sender is configured. */
49
+ export function mailKeptOnly(host: object): boolean {
50
+ return keptOnly.has(host);
51
+ }
52
+
53
+ /** The mail kept so far, oldest first; `to` keeps one recipient's. */
54
+ export function devMail(to?: string): DevMail[] {
55
+ const wanted = to?.trim().toLowerCase();
56
+ return sent.filter(mail => !wanted || mail.to.toLowerCase() === wanted);
57
+ }
58
+
59
+ /** Forget the mail kept so far. */
60
+ export function clearDevMail(): void {
61
+ sent.length = 0;
62
+ }
63
+
64
+ /**
65
+ * Whether the request may read the development mail: APP_URL names this machine, and so does
66
+ * the address the request reached. A deployment whose APP_URL was left local still answers 404
67
+ * to a request from outside.
68
+ */
69
+ export function devMailOpen(c: Context, appUrl: string | undefined): boolean {
70
+ return local(appUrl) && local(c.req.url);
71
+ }
72
+
73
+ function local(address: string | undefined): boolean {
74
+ let host: string;
75
+ try { host = address ? new URL(address).hostname : ''; } catch { return false; }
76
+ return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host.endsWith('.localhost');
77
+ }
@@ -9,7 +9,15 @@ import { plugins } from '@cossackframework/framework/plugins';
9
9
  import { modules, options as projectOptions, resources, storage as projectStorage } from '@/cms.config';
10
10
  import { announceNoteEvent } from './notes-announce';
11
11
  import { reservedRouteSegments } from './reserved-paths';
12
- import registry from 'virtual:cossack-pages';
12
+ import { requestCallsSignal } from './request-calls';
13
+ import { devMailTransport, markMailKeptOnly } from './dev-mail';
14
+ import { ormPeople } from './people';
15
+ import { tenantSites } from './sites';
16
+ import { accounts, asMainAccount, withTenant } from '../tenants';
17
+ import { TenantMember } from '@/models/TenantMember';
18
+ // The page files' names only. The pages registry imports every layout on the server, and the
19
+ // layouts import this module: through the registry it would import itself (requests.md C8).
20
+ import pageFiles from 'virtual:cossack-page-files';
13
21
 
14
22
  /**
15
23
  * The environment bindings the CMS application reads. The project's storage (`storage` in
@@ -94,7 +102,10 @@ export function networkFor(env: CmsBindings): CmsNetwork {
94
102
  const connection = store.databaseConnection(env);
95
103
  const key = `${connection.url}\n${connection.token ?? ''}`;
96
104
  if (current?.key !== key) {
97
- const db = createRomeDB({ ...connection, pending: store.pendingWrites(env), reconcilers: cmsReconcilers() });
105
+ // On Workers a request's database calls end with it (cms/request-calls.ts), or a call of a
106
+ // request that ended first would keep one of the client's places for good.
107
+ const calls = store.cancelsRequestIo ? { requestSignal: requestCallsSignal } : {};
108
+ const db = createRomeDB({ ...connection, pending: store.pendingWrites(env), reconcilers: cmsReconcilers(), ...calls });
98
109
  const storage = store.mediaStorage(env);
99
110
  const images = store.imageTransformer(env);
100
111
  const mail = env.EMAIL;
@@ -106,23 +117,33 @@ export function networkFor(env: CmsBindings): CmsNetwork {
106
117
  const network: CmsNetwork = new CmsNetwork({
107
118
  db,
108
119
  networkHost: () => urlOf(env.APP_URL)?.host,
109
- ...(multisite ? { open: site => createRomeDB({ ...store.siteDatabase(env, site.database)!, pending: store.pendingWrites(env, site.database), reconcilers: cmsReconcilers() }) } : {}),
120
+ ...(multisite ? { open: site => createRomeDB({ ...store.siteDatabase(env, site.database)!, pending: store.pendingWrites(env, site.database), reconcilers: cmsReconcilers(), ...calls }) } : {}),
110
121
  ...(directory ? { directory } : {}),
111
122
  hostUrl: host => siteUrl(env, { host })!,
123
+ // Sites are the dashboard package's tenants; a site's users are in the site's own database.
124
+ sites: tenantSites,
125
+ inSite: (site, work) => site.id === MAIN_SITE ? asMainAccount(() => accounts(work)) : withTenant({ id: site.id, slug: site.id, name: site.name ?? site.id, database: site.database, status: 'active' }, work),
126
+ memberSites: accountId => asMainAccount(() => accounts(async () => (await TenantMember.find({ where: { userId: accountId }, take: 500 })).map(member => member.tenantId))),
112
127
  host: (site, siteDb) => {
113
128
  // What the project sets in src/cms.config.ts goes over the defaults below.
114
129
  const project = typeof projectOptions === 'function' ? projectOptions(env as Record<string, unknown>, site) : projectOptions;
115
- return createCMS({
130
+ // The project's transport, else the EMAIL binding. In development the mail is also kept for
131
+ // GET /api/cms/dev/mail and printed (cms/dev-mail.ts), with or without a transport.
132
+ const transport = project.mail ?? (mail ? { send: (message: Parameters<NonNullable<typeof mail>['send']>[0]) => mail.send(message) } : undefined);
133
+ const siteMail = localAddress(env.APP_URL) ? devMailTransport(site.id, transport) : transport;
134
+ // Health still reports a missing sender while development keeps the mail.
135
+ const made = (host: CmsHost) => siteMail && !transport ? markMailKeptOnly(host) : host;
136
+ return made(createCMS({
116
137
  db: siteDb, network: db, site: site.id, modules, resources, plugins,
138
+ // Accounts, roles and sign-in are the dashboard package's, on the ORM (specs/cms-on-dashboard.md).
139
+ people: ormPeople,
117
140
  // A site whose APP_URL is this machine is in development: its webhooks may stay local. No APP_URL is no exception.
118
141
  localWebhooks: localAddress(env.APP_URL),
119
142
  ...(webhookFetch && !localAddress(env.APP_URL) ? { webhookFetch } : {}),
120
143
  // A site's media keys start with sites/<id>/; the main site keeps its own.
121
144
  ...(storage ? { storage: site.id === MAIN_SITE ? storage : prefixedStorage(storage, `sites/${site.id}/`) } : {}),
122
145
  ...(images ? { images } : {}), siteUrl: () => siteUrl(env, site),
123
- ...(mail ? { mail: { send: message => mail.send(message) }, mailFrom: env.MAIL_FROM || 'no-reply@example.com' } : {}),
124
- // Ending a network session ends the child sessions sites made from it.
125
- sessionsEnded: ended => network.endSessions(ended),
146
+ ...(siteMail ? { mailFrom: env.MAIL_FROM || 'no-reply@example.com' } : {}),
126
147
  // A note's webhooks and emails, from the outbox job its write queued.
127
148
  announceNote: announceNoteEvent,
128
149
  purgers: [...purgers(env, site), ...(project.purgers ?? [])],
@@ -133,11 +154,12 @@ export function networkFor(env: CmsBindings): CmsNetwork {
133
154
  // Every binding, for a plugin granted unrestricted access.
134
155
  env: env as Record<string, unknown>,
135
156
  runner: pluginRunner,
136
- ...(({ purgers: _purgers, reservedPaths: _reserved, updates: _updates, ...rest }) => rest)(project),
157
+ ...(({ purgers: _purgers, reservedPaths: _reserved, updates: _updates, mail: _mail, ...rest }) => rest)(project),
158
+ ...(siteMail ? { mail: siteMail } : {}),
137
159
  // An entry's slug cannot take the address of a page: the CMS's routes, every page file of the
138
160
  // application (the project's, the CMS's and plugins'), and what the project names itself.
139
- reservedPaths: [...new Set([...DEFAULT_RESERVED_PATHS, ...reservedRouteSegments(Object.keys(registry.pages)), ...(project.reservedPaths ?? [])])],
140
- });
161
+ reservedPaths: [...new Set([...DEFAULT_RESERVED_PATHS, ...reservedRouteSegments(pageFiles), ...(project.reservedPaths ?? [])])],
162
+ }));
141
163
  },
142
164
  });
143
165
  current = { key, network };
@@ -189,3 +211,8 @@ export function localAddress(appUrl: string | undefined): boolean {
189
211
  const host = urlOf(appUrl)?.hostname;
190
212
  return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host?.endsWith('.localhost') === true;
191
213
  }
214
+
215
+ /** A site's RomeDB database by the site's ID, for the application's own tables there (src/orm/factory.ts: `tenantORM`). */
216
+ export async function siteDatabase(env: CmsBindings, id: string) {
217
+ return networkFor(env).databaseOf(id);
218
+ }
@@ -21,7 +21,6 @@ export async function runNetworkMaintenance(network: CmsNetwork, options: { warm
21
21
  const updates = updateSettingsOf(network);
22
22
  if (updates?.check && await network.main.installed().catch(() => false)) await refreshUpdateCheck(network, updates).catch(error => console.error('[cms] the update check failed', error));
23
23
  if (!network.multisite || !(await network.main.installed())) return;
24
- await network.handoffs.purgeExpired();
25
24
  // Sites deleted 30 days ago lose their database and media.
26
25
  await network.purgeDeleted().catch(error => console.error('[cms] could not purge deleted sites', error));
27
26
  // Off, the network serves its main site only.
@@ -61,12 +60,8 @@ export async function runMaintenance(cms: CmsHost, options: { warm?: boolean } =
61
60
  () => cms.webhooks.dispatch({ limit: 20 }),
62
61
  () => cms.outbox.prune(),
63
62
  () => cms.webhooks.prune(),
64
- () => cms.sessions.purgeExpired(),
65
- () => cms.oauthStates.purgeExpired(Date.now()),
66
- () => cms.accounts.purgeExpiredResets(),
67
63
  () => cms.previews.purgeExpired(),
68
- () => cms.security.purgeExpired(),
69
- () => cms.security.purgeAttempts(),
64
+ () => cms.attempts.purge(),
70
65
  () => cms.autosaves.purge(),
71
66
  () => cms.drafts.purge(),
72
67
  () => purgeOrphanNotes(cms),
@@ -10,10 +10,11 @@ import {
10
10
  BLOCK_ID, checkNoteRange, CmsError, CONTENT_STATUSES, findBlock, hasPermission, indexedRowField, isNetworkAdmin, MAIN_SITE, MENU_LIMITS, menuItemId, noteThreads, PERMISSIONS, recordSchema, recordTitle, richTextBlocks,
11
11
  ANONYMOUS, mediaKind, mediaUrl, type MediaKind, type SnippetPart,
12
12
  type Block, type FieldFilter, type MenuItem, type MenuShape, type Note, type NoteThread, type Principal, type RecordShape, type RichTextDoc, redirectProblems, type Redirect, type RedirectStatus, type FieldDeclaration, WEBHOOK_EVENTS, COMMENT_STATUSES, type Webhook, type CommentShape, type CommentStatus } from '@cossackframework/cms';
13
- import { networkSite, type ApiToken, type CmsHost, type NetworkSite, type SiteRecord } from '@cossackframework/cms/server';
14
- import { createApiToken, listApiTokens, manageableHere, NETWORK_ACCOUNT_LOCKED, revokeApiToken, type PublicUser } from '../auth';
13
+ import { networkSite, type CmsHost, type NetworkSite, type SiteRecord } from '@cossackframework/cms/server';
14
+ import { createApiToken, listApiTokens, revokeApiToken, type ApiToken, type PublicUser } from '../auth';
15
+ import { userOfPrincipal } from './actor';
15
16
  import { canAssignRoles, canGrantRoles, canManageUser } from '../services/rbac';
16
- import { changeUserPassword, createUser, deleteUser, getUser, listUsers, syncUserRoles, updateUser, type UserDetail, type UserSummary } from '../services/users';
17
+ import { changeUserPassword, createUser, deleteUser, getUser, listUsers, setUserStatus, syncUserRoles, updateUser, type UserDetail, type UserSummary } from '../services/users';
17
18
  import { apiEntries, apiPatterns, withheldFields, type ApiEntry } from './content-api';
18
19
  import { entryLock } from './site';
19
20
  import { routeResource } from './content';
@@ -48,7 +49,7 @@ function allowed(c: Context, permission: string, refusal: string): Principal & {
48
49
  /** The signed-in user as the RBAC helpers see them; a token request has no `user` on the context. */
49
50
  function actor(c: Context): PublicUser {
50
51
  const principal = signedIn(c);
51
- return (c.get('user') as PublicUser | undefined) ?? { id: principal.id, email: '', name: '', avatar: null, meta: null, roles: [], principal };
52
+ return (c.get('user') as PublicUser | undefined) ?? userOfPrincipal(principal);
52
53
  }
53
54
 
54
55
  function integer(value: unknown, fallback: number, min: number, max: number): number {
@@ -247,8 +248,9 @@ export async function entriesList(c: Context, name: string, query: Query): Promi
247
248
  if (q) {
248
249
  // A locked entry the reader may not open stays out: that it matched would tell what its content says.
249
250
  const signedIn = principal.kind === 'user';
250
- const records = (await repository.search(q, { limit: perPage, where }, { principal }))
251
- .filter(record => !entryLock(record, { editor: repository.canUpdate(record, principal), signedIn, roles: signedIn ? principal.roles : [] }));
251
+ const found = await repository.search(q, { limit: perPage, where }, { principal });
252
+ const editable = await repository.editable(found, { principal });
253
+ const records = found.filter(record => !entryLock(record, { editor: editable.has(record.id), signedIn, roles: signedIn ? principal.roles : [] }));
252
254
  return { items: await apiEntries(cms, collection, records, html, principal), page: 1, pages: 1, total: records.length };
253
255
  }
254
256
  // `sort=publishedAt:asc`, `sort=title`: a scalar field of the collection; the default follows what is listed.
@@ -275,7 +277,8 @@ export async function entriesList(c: Context, name: string, query: Query): Promi
275
277
  for (let offset = 0; ; offset += LOCKED_SCAN_BATCH) {
276
278
  if (offset >= LOCKED_SCAN_LIMIT) { truncated = true; break; }
277
279
  const batch = await repository.list({ where, order, limit: LOCKED_SCAN_BATCH, offset }, { principal });
278
- open.push(...batch.records.filter(record => !entryLock(record, { editor: repository.canUpdate(record, principal), signedIn: true, roles: principal.roles })));
280
+ const editable = await repository.editable(batch.records, { principal });
281
+ open.push(...batch.records.filter(record => !entryLock(record, { editor: editable.has(record.id), signedIn: true, roles: principal.roles })));
279
282
  if (!batch.more && !batch.next) break;
280
283
  }
281
284
  const pages = Math.max(1, Math.ceil(open.length / perPage));
@@ -519,7 +522,7 @@ export async function notesForEntry(c: Context, name: string, id: string, status
519
522
  const principal = c.get('principal');
520
523
  const record = await entryOf(cms, resource, id, principal);
521
524
  // Notes are the editors' discussion: publishing an entry does not publish them.
522
- if (!cms.resource(resource).canUpdate(record, principal)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to read notes on this entry.');
525
+ if (!await cms.resource(resource).canUpdate(record, { principal })) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to read notes on this entry.');
523
526
  if (status !== undefined && status !== '' && status !== 'open' && status !== 'resolved') throw new CmsError('CMS_VALIDATION', 'status is open or resolved.');
524
527
  return { threads: noteThreads(await cms.notes.forEntry(resource, id)).filter(thread => !status || thread.root.status === status) };
525
528
  }
@@ -536,7 +539,7 @@ export async function noteAdd(c: Context, name: string, id: string, input: Body)
536
539
  const resource = `cms/${collection.name}`;
537
540
  const repository = cms.resource(resource);
538
541
  const record = await entryOf(cms, resource, id, principal);
539
- if (!repository.canUpdate(record, principal)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to leave notes on this entry.');
542
+ if (!await repository.canUpdate(record, { principal })) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to leave notes on this entry.');
540
543
  const author = await cms.users.get(principal.id).catch(() => null);
541
544
  // Its webhooks and emails follow from the outbox, queued with the note.
542
545
  const note = await cms.notes.create({
@@ -556,7 +559,7 @@ async function editableNote(c: Context, noteId: string): Promise<{ note: Note; r
556
559
  const repository = cms.resource(note.resource);
557
560
  const record = await repository.get(note.recordId, { principal });
558
561
  if (!record) throw new CmsError('CMS_NOT_FOUND', 'Note not found.');
559
- if (!repository.canUpdate(record, principal)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to change notes on this entry.');
562
+ if (!await repository.canUpdate(record, { principal })) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to change notes on this entry.');
560
563
  return { note, record, principal };
561
564
  }
562
565
 
@@ -602,7 +605,7 @@ export async function notesAcross(c: Context, status: string | undefined, limit:
602
605
  if (owner !== 'cms' || !resourceName) continue;
603
606
  let record: RecordShape | null;
604
607
  try { record = await cms.resource(entry.resource).get(entry.recordId, { principal }); } catch { continue; }
605
- if (!record || !cms.resource(entry.resource).canUpdate(record, principal)) continue;
608
+ if (!record || !await cms.resource(entry.resource).canUpdate(record, { principal })) continue;
606
609
  const threads = noteThreads(await cms.notes.forEntry(entry.resource, entry.recordId)).filter(thread => !status || thread.root.status === status);
607
610
  if (!threads.length) continue;
608
611
  items.push({ collection: resourceName, entryId: entry.recordId, title: recordTitle(record, cms.resourceById(entry.resource).titleField), status: typeof record.status === 'string' ? record.status : null, threads });
@@ -689,8 +692,7 @@ export async function userUpdate(c: Context, id: string, input: Body): Promise<U
689
692
  if (input.status !== undefined) {
690
693
  if (input.status !== 'active' && input.status !== 'disabled') throw new CmsError('CMS_VALIDATION', 'status is active or disabled.');
691
694
  if (id === me.id) throw new CmsError('CMS_VALIDATION', 'Your own account stays active.');
692
- if (!(await manageableHere(id))) throw new CmsError('CMS_FORBIDDEN', NETWORK_ACCOUNT_LOCKED);
693
- await c.get('cms').users.setStatus(id, input.status);
695
+ await setUserStatus(id, input.status);
694
696
  }
695
697
  return (await getUser(id))!;
696
698
  }
@@ -1036,7 +1038,8 @@ export async function siteCreate(c: Context, input: Body): Promise<SiteView> {
1036
1038
  const name = text(input.name, 'name', { max: 120 });
1037
1039
  const host = text(input.host, 'host', { max: 253 }).toLowerCase();
1038
1040
  const email = text(input.admin, 'admin', { required: false, max: 254 });
1039
- const admin = email ? await network.main.accounts.findByEmail(email) : await network.main.accounts.get(principal.id);
1041
+ // Accounts of the network are the main site's users.
1042
+ const admin = email ? await network.main.users.findByEmail(email) : await network.main.users.get(principal.id);
1040
1043
  if (!admin) throw new CmsError('CMS_VALIDATION', 'No network account has that email. Add the person under Network → Users first.', { fields: { admin: 'is not a network account.' } });
1041
1044
  const id = text(input.id, 'id', { required: false, max: 63 });
1042
1045
  const language = text(input.language, 'language', { required: false, max: 16 });
@@ -1,13 +1,16 @@
1
- import type { Context, MiddlewareHandler } from 'hono';
1
+ import type { Context, MiddlewareHandler, Next } from 'hono';
2
2
  import { getCookie } from 'hono/cookie';
3
3
  import { enforceRateLimit, getClientIp, getSupportedLocales, LOCALE_COOKIE_NAME, setRequestLocale } from '@cossackframework/core';
4
- import { ANONYMOUS, escapeHtml, hasPermission, PERMISSIONS, type Principal, DEFAULT_ICON_STYLE, isIconStyle } from '@cossackframework/cms';
5
- import { MAIN, MAIN_SITE, networkSite, type SiteResolution } from '@cossackframework/cms/server';
4
+ import { ANONYMOUS, escapeHtml, hasPermission, PERMISSIONS, userPrincipal, type Principal, DEFAULT_ICON_STYLE, isIconStyle } from '@cossackframework/cms';
5
+ import { MAIN_SITE, networkSite, type SiteResolution } from '@cossackframework/cms/server';
6
6
  import { cmsFor, networkFor, type CmsBindings } from './index';
7
- import { handoff } from './handoff';
7
+ import { inTenantDatabase, sharedSignInOnMainHost, sharedSignInOnTenantHost } from '../middlewares/tenant';
8
+ import { hostName, mainHost } from '../tenants';
8
9
  import { dashboardPalette } from '../dashboard/head';
9
10
  import { runMaintenance } from './maintenance';
10
- import { accountNeedsSecondFactor, secondFactorRequired, type PublicUser } from '../auth';
11
+ import { answered, withRequestCalls } from './request-calls';
12
+ import { apiTokenUser, secondFactorRequired, securityStatus, type PublicUser } from '../auth';
13
+ import { authOptions } from '../auth-options';
11
14
 
12
15
  /**
13
16
  * For `createApp({ isPluginActive })`: a rendered plugin's pages, layouts and HTTP handlers
@@ -28,11 +31,20 @@ const lastMaintenance = new Map<string, number>();
28
31
  * Maintenance also runs at most once a minute for each site. A host no site claims gets a 404,
29
32
  * an alias redirects to its site's primary domain, and an archived site shows only its dashboard.
30
33
  */
31
- export const cmsMiddleware: MiddlewareHandler = async (c, next) => {
34
+ export const cmsMiddleware: MiddlewareHandler = (c, next) => withRequestCalls(c, () => serveSite(c, next));
35
+
36
+ async function serveSite(c: Context, next: Next): Promise<Response | void> {
32
37
  const network = networkFor(c.env as CmsBindings);
33
38
  const url = new URL(c.req.url);
34
- // Before setup the registry does not exist yet: the main site answers.
35
- let found: SiteResolution = await network.resolve(url.host).catch(() => ({ kind: 'site', site: MAIN }));
39
+ // Before setup the registry does not exist yet and the main site answers (`resolve` says so).
40
+ // A lookup that fails answers 503: serving the main site at another site's address would show,
41
+ // and let caches keep, the wrong site's pages.
42
+ let found: SiteResolution;
43
+ try { found = await network.resolve(url.host); }
44
+ catch (error) {
45
+ console.error('[cms] could not look up the site of', url.host, error);
46
+ return c.text('The site is unavailable for a moment. Try again shortly.', 503, { 'retry-after': '5', 'cache-control': 'no-store' });
47
+ }
36
48
  // API clients name a site on the network host: `X-Cossack-Site: blog` (or `?site=blog` on the MCP
37
49
  // endpoint) serves that site, so a tool need not reach the site's own address.
38
50
  const requested = requestedSite(c, url);
@@ -59,16 +71,21 @@ export const cmsMiddleware: MiddlewareHandler = async (c, next) => {
59
71
  c.set('site', found.site);
60
72
  c.set('network', network);
61
73
  c.set('principal', ANONYMOUS);
62
- // Sign-in happens on the network host; other sites get their sessions through a handoff.
63
- const routed = await handoff(c, network, found.site);
64
- if (routed) return routed;
74
+ // A site of the network is a tenant of the dashboard package: its accounts and sessions are in
75
+ // its own database, which the rest of the request runs in. People with a network account
76
+ // sign in on the network host, which sends them back with a one-time code (shared sign-in).
77
+ const site = found.site;
78
+ const serve = async (): Promise<Response | void> => {
65
79
  // Before setup the definition tables do not exist yet; built-in collections apply.
66
80
  await cms.ready().catch(error => console.error('[cms] could not load collections', error));
67
81
  // Settings → Interface: the style every icon of this request is drawn in (`iconStyle()` in
68
82
  // cms/icons.ts reads it) and the dashboard's palettes (`dashboardHead()` in dashboard/head.ts).
69
- const [style, palette, accent] = await Promise.all((['interface.iconStyle', 'interface.palette', 'interface.accent'] as const).map(key => cms.settings.get(key).catch(() => undefined)));
83
+ const settings = await cms.settings.all().catch(() => undefined);
84
+ const style = settings?.['interface.iconStyle'];
70
85
  c.set('cms.iconStyle', isIconStyle(style) ? style : DEFAULT_ICON_STYLE);
71
- c.set('cms.palette', dashboardPalette(palette, accent));
86
+ c.set('cms.palette', dashboardPalette(settings?.['interface.palette'], settings?.['interface.accent']));
87
+ // The shared sign-in code reads registration and two-step sign-in from these (src/auth-options.ts).
88
+ c.set('cms.settings', settings ?? {});
72
89
  // Until a user picks a language (Profile → Dashboard language), the dashboard speaks the
73
90
  // site's default one when a catalog has it. Site pages then switch to their content's language.
74
91
  const supported = getSupportedLocales();
@@ -78,6 +95,8 @@ export const cmsMiddleware: MiddlewareHandler = async (c, next) => {
78
95
  }
79
96
  const writes = cms.outboxWrites;
80
97
  await next();
98
+ // The outbox and maintenance below outlive the answer: their database calls must not end with it.
99
+ answered(c);
81
100
  securityHeaders(c, url);
82
101
  // The API answers for the site `X-Cossack-Site` names: a shared cache keeps one answer per site.
83
102
  if (url.pathname.startsWith('/api/') && !/(^|,)\s*x-cossack-site\s*(,|$)/i.test(c.res.headers.get('vary') ?? '')) c.header('vary', 'X-Cossack-Site', { append: true });
@@ -87,7 +106,14 @@ export const cmsMiddleware: MiddlewareHandler = async (c, next) => {
87
106
  lastMaintenance.set(found.site.database, now);
88
107
  later(c, runMaintenance(cms, { warm: false }));
89
108
  }
90
- };
109
+ };
110
+ if (site.id === MAIN_SITE) return sharedSignInOnMainHost(c) ?? serve();
111
+ const main = mainHost();
112
+ // An API client that names the site on the network host is not a visitor to send elsewhere.
113
+ const routed = main && !requested ? sharedSignInOnTenantHost(c, hostName(c.req.url), main) : null;
114
+ if (routed) return routed;
115
+ return inTenantDatabase(c, { id: site.id, slug: site.id, name: site.name ?? site.id, database: site.database, status: 'active', ...(site.host ? { primaryHost: site.host } : {}) }, serve);
116
+ }
91
117
 
92
118
  /**
93
119
  * Headers every response carries unless the route set its own: no MIME sniffing, a tight
@@ -108,9 +134,22 @@ function securityHeaders(c: Context, url: URL): void {
108
134
  * application password (`Authorization: Bearer cms_…`) signs the request in instead; read-only
109
135
  * passwords may only read, and token requests skip the session's same-origin checks.
110
136
  */
137
+ /** The request principal of a signed-in user: their roles' names and permissions here; a network administrator's role carries `*`. */
138
+ export function principalOf(user: PublicUser): Principal {
139
+ return userPrincipal(user.id, user.roles.map(role => role.id), user.roles.flatMap(role => role.permissions));
140
+ }
141
+
142
+ /** Whether Settings → General ask this account for two-step sign-in and it has no second factor yet. */
143
+ async function accountNeedsSecondFactor(user: PublicUser): Promise<boolean> {
144
+ const { requireTwoFactor, twoFactorRoles } = authOptions.security;
145
+ if (!requireTwoFactor || (twoFactorRoles.length > 0 && !user.roles.some(role => twoFactorRoles.includes(role.id) || twoFactorRoles.includes(role.name)))) return false;
146
+ const status = await securityStatus(user.id);
147
+ return !status.totp && status.passkeys.length === 0;
148
+ }
149
+
111
150
  export const cmsPrincipal: MiddlewareHandler = async (c, next) => {
112
151
  const user = c.get('user') as PublicUser | undefined;
113
- let session = user?.principal as Principal | undefined;
152
+ let session = user ? principalOf(user) : undefined;
114
153
  // Staff that General settings require to use two-step sign-in act with their session only
115
154
  // once they have a second factor. Until then the session is anonymous everywhere (the site,
116
155
  // Live Edit, previews, server methods), so no page has to repeat the check; signing in and
@@ -122,10 +161,11 @@ export const cmsPrincipal: MiddlewareHandler = async (c, next) => {
122
161
  c.set('principal', session ?? ANONYMOUS);
123
162
  const header = c.req.header('authorization') ?? '';
124
163
  if (!user && /^Bearer cms_/i.test(header) && API_PATH.test(c.req.path)) {
125
- const token = await c.get('cms').tokenPrincipal(header.slice(7).trim()).catch(() => null);
126
- if (!token) return c.json({ error: 'The application password is not valid.', code: 'CMS_UNAUTHENTICATED' }, 401, { 'www-authenticate': 'Bearer' });
164
+ const verified = await apiTokenUser(header.slice(7).trim()).catch(() => null);
165
+ if (!verified) return c.json({ error: 'The application password is not valid.', code: 'CMS_UNAUTHENTICATED' }, 401, { 'www-authenticate': 'Bearer' });
166
+ const token = { principal: principalOf(verified.user), scope: verified.scope };
127
167
  // An application password made before the requirement was turned on stops working too.
128
- if (token.principal.kind === 'user' && await accountNeedsSecondFactor({ id: token.principal.id, principal: token.principal }).catch(() => true)) return secondFactorRefusal(c);
168
+ if (await accountNeedsSecondFactor(verified.user).catch(() => true)) return secondFactorRefusal(c);
129
169
  if (token.scope === 'read' && c.req.path !== MCP_PATH && !['GET', 'HEAD', 'OPTIONS'].includes(c.req.method)) return c.json({ error: 'This application password can only read.', code: 'CMS_FORBIDDEN' }, 403);
130
170
  c.set('principal', token.principal);
131
171
  c.set('cms.token', true);