@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
@@ -1,9 +1,17 @@
1
- import { ClientVisibleError, getRequestContext } from '@cossackframework/core';
2
- import { isCmsError, NETWORK_ADMIN, systemPrincipal } from '@cossackframework/cms';
3
- import { MAIN_SITE, randomToken, type CmsHost, type CmsUser } from '@cossackframework/cms/server';
4
- import { currentCms, networkFor, type CmsBindings } from '../cms/index';
5
- import { getCookie } from 'hono/cookie';
6
- import { linkOrigin, manageableHere, NETWORK_ACCOUNT_LOCKED, SESSION_COOKIE_NAME, type PublicUser, type RoleAssignment } from '../auth';
1
+ import { In, sql } from '@cossackframework/database';
2
+ import { ClientVisibleError } from '@cossackframework/core';
3
+ import { uuidv7 } from '../lib/uuid';
4
+ import { canInvite, hashPassword, sendInvitation, type PublicUser } from '../auth';
5
+ import { accounts, currentTenant } from '../tenants';
6
+ import { forgetMemberships, joinCurrentTenant, leaveCurrentTenant, requireAnotherNetworkAdmin, tenantOwnAccount } from './tenants';
7
+ import * as security from './security';
8
+ import * as apiTokens from './api-tokens';
9
+ import { defaultRole } from './roles';
10
+ import { authOptions } from '../auth-options';
11
+ import { User } from '@/models/User';
12
+ import { UserRole } from '@/models/UserRole';
13
+ import { Role } from '@/models/Role';
14
+ import type { RoleAssignment } from '@/models/User';
7
15
 
8
16
  export interface UserSummary {
9
17
  id: string;
@@ -11,17 +19,18 @@ export interface UserSummary {
11
19
  name: string;
12
20
  avatar: string | null;
13
21
  createdAt: string;
14
- /** When the user last signed in, recorded when a session starts; null when never. */
22
+ /** Start of the user's newest sign-in session; null when none is left. */
15
23
  lastSignedInAt: string | null;
16
24
  roles: RoleAssignment[];
17
- /** On an added site, *Network account* for members who sign in through the network. */
25
+ /** A label beside the name in lists, such as the kind of account. */
18
26
  badge?: string;
19
27
  }
20
28
 
21
29
  export interface UserDetail extends UserSummary {
22
- /** The account administers the network: only another network admin changes it. */
23
- networkAdmin?: true;
24
- /** For others on an added site, why a network account's profile, password and sign-in methods are not changed here. */
30
+ /**
31
+ * Why only the user can change their profile, password and sign-in methods here, when others
32
+ * manage them elsewhere; this site still manages the user's roles.
33
+ */
25
34
  lockedProfile?: string;
26
35
  }
27
36
 
@@ -43,10 +52,10 @@ export interface CreateUserInput {
43
52
  email: string;
44
53
  /** Required unless `invite` is set. */
45
54
  password?: string;
46
- /** Send an invitation: the account starts with a random password and an email with a link to set one, good for seven days. */
55
+ /** Email a link to set the password instead of setting one here. It needs an email sender and APP_URL. */
47
56
  invite?: boolean;
48
57
  name?: string;
49
- /** Roles chosen by someone who may assign them; otherwise the default role. */
58
+ /** Roles chosen by someone who may assign them; otherwise none. */
50
59
  roleIds?: string[];
51
60
  }
52
61
 
@@ -56,118 +65,253 @@ export interface UpdateUserInput {
56
65
  avatar?: string | null;
57
66
  }
58
67
 
59
- function summary(user: CmsUser): UserSummary {
60
- return {
61
- id: user.id, email: user.email, name: user.name, avatar: user.avatar, createdAt: new Date(user.createdAt).toISOString(),
62
- lastSignedInAt: user.lastSignInAt === null ? null : new Date(user.lastSignInAt).toISOString(),
63
- roles: user.assignments.map(role => ({ id: role.id, name: role.name, permissions: [...role.permissions] })),
64
- // Site accounts are an added site's own; members with a network account are marked.
65
- ...(currentCms().siteAccounts && user.account === 'network' ? { badge: 'Network account' } : {}),
66
- };
68
+ type RoleRow = { userId?: string; id: string; name: string; permissions: string | string[] | null };
69
+
70
+ // A JSON column arrives as text from SQLite and already parsed from PostgreSQL and MySQL.
71
+ function safeParseStrings(raw: string | string[] | null): string[] {
72
+ if (!raw) return [];
73
+ try {
74
+ const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
75
+ return Array.isArray(parsed) ? parsed.filter((value) => typeof value === 'string') : [];
76
+ } catch {
77
+ return [];
78
+ }
79
+ }
80
+
81
+ function parseRoles(rows: readonly RoleRow[]): RoleAssignment[] {
82
+ return rows.map((row) => ({
83
+ id: row.id,
84
+ name: row.name,
85
+ permissions: safeParseStrings(row.permissions),
86
+ }));
87
+ }
88
+
89
+ /** Each user's newest auth session start. Sign-out deletes the session, and with it this time. */
90
+ async function lastSignIns(userIds: readonly string[]): Promise<Map<string, string>> {
91
+ if (!userIds.length) return new Map();
92
+ // The sessions of this host: a tenant's are in its own database.
93
+ const rows = (await sql<{ userId: string; lastSignedInAt: string | null }>`
94
+ SELECT user_id AS userId, MAX(created_at) AS lastSignedInAt
95
+ FROM sessions
96
+ WHERE user_id IN (${userIds}) AND kind = 'auth'
97
+ GROUP BY user_id
98
+ `).rows;
99
+ const times = new Map<string, string>();
100
+ for (const row of rows) {
101
+ const at = row.lastSignedInAt ? new Date(row.lastSignedInAt) : null;
102
+ if (at && !Number.isNaN(at.getTime())) times.set(row.userId, at.toISOString());
103
+ }
104
+ return times;
67
105
  }
68
106
 
69
- /** CMS failures carry safe text; pages show it. */
70
- async function visible<T>(work: Promise<T>): Promise<T> {
71
- try { return await work; }
72
- catch (error) { throw isCmsError(error) ? new ClientVisibleError(error.message) : error; }
107
+ async function roleRowsForUsers(userIds: readonly string[]): Promise<readonly RoleRow[]> {
108
+ if (!userIds.length) return [];
109
+ return (await sql<RoleRow>`
110
+ SELECT ur.user_id AS userId, r.id, r.name, r.permissions
111
+ FROM user_roles ur
112
+ INNER JOIN roles r ON r.id = ur.role_id
113
+ WHERE ur.user_id IN (${userIds})
114
+ `).rows;
73
115
  }
74
116
 
75
117
  export async function listUsers(options: ListUsersOptions = {}): Promise<ListUsersResult> {
76
- const page = Math.max(1, options.page ?? 1);
77
- const pageSize = Math.min(Math.max(1, options.pageSize ?? 20), 100);
78
- const result = await currentCms().users.list({ search: options.search, role: options.roleId, limit: pageSize, offset: (page - 1) * pageSize });
79
- return { items: result.items.map(summary), total: result.total, page, pageSize };
118
+ const { search, roleId, page = 1, pageSize = 20 } = options;
119
+ const safePage = Math.max(1, page);
120
+ const safeSize = Math.max(1, pageSize);
121
+ const like = search ? `%${search}%` : null;
122
+ const roleFilter = roleId
123
+ ? sql.fragment`AND u.id IN (SELECT user_id FROM user_roles WHERE role_id = ${roleId})`
124
+ : sql.fragment``;
125
+ const searchFilter = like
126
+ ? sql.fragment`AND (u.name LIKE ${like} OR u.email LIKE ${like})`
127
+ : sql.fragment``;
128
+
129
+ const [pageResult, countResult] = await Promise.all([
130
+ sql<{ id: string; email: string; name: string | null; avatar: string | null; createdAt: string; tenantAccount: boolean | number }>`
131
+ SELECT u.id, u.email, u.name, u.avatar, u.created_at AS createdAt, u.tenant_account AS tenantAccount
132
+ FROM users u
133
+ WHERE 1 = 1 ${searchFilter} ${roleFilter}
134
+ ORDER BY u.created_at DESC
135
+ LIMIT ${safeSize} OFFSET ${(safePage - 1) * safeSize}
136
+ `,
137
+ sql<{ total: number }>`
138
+ SELECT COUNT(*) AS total FROM users u
139
+ WHERE 1 = 1 ${searchFilter} ${roleFilter}
140
+ `,
141
+ ]);
142
+ // In a tenant, members whose account every tenant shares are marked.
143
+ const tenant = currentTenant() !== null;
144
+ const items: UserSummary[] = pageResult.rows.map(({ tenantAccount, ...row }) => ({
145
+ ...row,
146
+ ...(tenant && !tenantAccount ? { badge: authOptions.accountLabels.shared } : {}),
147
+ name: row.name ?? '',
148
+ lastSignedInAt: null,
149
+ roles: [],
150
+ }));
151
+ const [roleRows, signIns] = await Promise.all([
152
+ roleRowsForUsers(items.map((user) => user.id)),
153
+ lastSignIns(items.map((user) => user.id)),
154
+ ]);
155
+ const byUser = new Map<string, RoleAssignment[]>();
156
+ for (const row of roleRows) {
157
+ const roles = byUser.get(row.userId!) ?? [];
158
+ roles.push(...parseRoles([row]));
159
+ byUser.set(row.userId!, roles);
160
+ }
161
+ for (const item of items) {
162
+ item.roles = byUser.get(item.id) ?? [];
163
+ item.lastSignedInAt = signIns.get(item.id) ?? null;
164
+ }
165
+ return {
166
+ items,
167
+ total: Number(countResult.rows[0]?.total ?? 0),
168
+ page: safePage,
169
+ pageSize: safeSize,
170
+ };
80
171
  }
81
172
 
82
173
  export async function getUser(id: string): Promise<UserDetail | null> {
83
- const user = await currentCms().users.get(id);
174
+ const user = await User.findOne({ where: { id } });
84
175
  if (!user) return null;
85
- const cms = currentCms();
86
- const networkAdmin = user.account === 'network' && (await cms.accounts.get(id))?.networkRole === NETWORK_ADMIN;
87
- return { ...summary(user), ...(networkAdmin ? { networkAdmin: true as const } : {}), ...(await manageableHere(id) ? {} : { lockedProfile: NETWORK_ACCOUNT_LOCKED }) };
88
- }
89
-
90
- /** A new account with the chosen roles, or General settings' default role. */
91
- export async function createUser(input: CreateUserInput): Promise<Omit<PublicUser, 'principal'>> {
92
- const cms = currentCms();
93
- let roles: string[];
94
- if (input.roleIds) {
95
- roles = [...new Set(input.roleIds)];
96
- for (const id of roles) if (!(await cms.users.role(id))) throw new ClientVisibleError('Choose roles that exist.');
97
- } else {
98
- const role = await cms.settings.get('general.defaultRole');
99
- roles = role && (await cms.users.role(role)) ? [role] : [];
176
+ return {
177
+ id: user.id,
178
+ email: user.email,
179
+ name: user.name ?? '',
180
+ avatar: user.avatar,
181
+ createdAt: user.createdAt.toISOString(),
182
+ lastSignedInAt: (await lastSignIns([id])).get(id) ?? null,
183
+ roles: parseRoles(await roleRowsForUsers([id])),
184
+ // In a tenant a member's account is shared, so only its owner changes it. The tenant's own accounts are its to manage.
185
+ ...(currentTenant() && !user.tenantAccount ? { lockedProfile: authOptions.accountLabels.sharedNotice } : {}),
186
+ };
187
+ }
188
+
189
+ /** A password nobody knows, for an account that is invited to set its own. */
190
+ function unknownPassword(): string {
191
+ return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32))));
192
+ }
193
+
194
+ export async function createUser(input: CreateUserInput): Promise<PublicUser> {
195
+ // In a tenant an existing main account joins without a password; only a new account needs one.
196
+ if (!input.invite && !input.password && !currentTenant()) throw new ClientVisibleError('Set a password or send an invitation.');
197
+ if (input.invite && !canInvite()) throw new ClientVisibleError('No email sender is configured, so invitations cannot be sent. Set a password instead.');
198
+ if (input.invite) input = { ...input, password: unknownPassword() };
199
+ // In a tenant: the account with this email becomes a member; a new account is made when there is none.
200
+ if (currentTenant()) {
201
+ const joined = await joinCurrentTenant({ email: input.email, ...(input.name ? { name: input.name } : {}), passwordHash: input.password ? await hashPassword(input.password) : null });
202
+ const roleIds = [...new Set(input.roleIds ?? [])];
203
+ if (roleIds.length) {
204
+ const known = await Role.find({ where: { id: In(roleIds) } });
205
+ if (known.length !== roleIds.length) throw new ClientVisibleError('Choose roles that exist.');
206
+ await syncUserRoles(joined.id, roleIds);
207
+ }
208
+ // A member with a main account has its password already.
209
+ if (input.invite && joined.created) await sendInvitation(joined.id);
210
+ return { id: joined.id, email: input.email, name: input.name ?? '', avatar: null, meta: null, roles: [] };
100
211
  }
101
- if (!input.invite && !input.password) throw new ClientVisibleError('Set a password or send an invitation.');
102
- if (input.invite && !cms.mail) throw new ClientVisibleError('No email sender is configured, so invitations cannot be sent. Set a password instead.');
103
- const password = input.invite ? randomToken(32) : input.password!;
104
- const user = await visible(cms.users.create({ email: input.email, password, name: input.name?.trim() || input.email.split('@')[0]!, roles }));
105
- if (input.invite) await sendInvitation(cms, user.email, user.name);
106
- return { ...summary(user), meta: null };
107
- }
108
-
109
- /** The invitation: a link to set a password, good for seven days, from the site's sender. */
110
- async function sendInvitation(cms: CmsHost, email: string, name: string): Promise<void> {
111
- const reset = await cms.signIn.accounts.createPasswordReset(email, { ttlMs: 7 * 24 * 60 * 60_000 });
112
- // The site's own address, never the request's Host: without one, no link is sent.
113
- const origin = linkOrigin();
114
- if (!reset || !cms.mail || !origin) return;
115
- const title = await cms.settings.get('general.siteTitle').catch(() => '');
116
- const link = `${origin.replace(/\/$/, '')}/auth/reset-password?token=${reset.token}`;
117
- await cms.mail.send({ kind: 'invitation', to: email, from: cms.mailFrom, subject: `You are invited to ${title || 'the site'}`,
118
- text: `Hello ${name || email},\n\nAn account was made for you on ${title || origin}. Set your password here within seven days:\n${link}\n\nIf you were not expecting this, ignore this email.` });
119
- }
120
-
121
- /** A network account on an added site keeps its name, email and picture unless the person or a network admin changes them. */
122
- export async function updateUser(id: string, patch: UpdateUserInput): Promise<void> {
123
- const cms = currentCms();
124
- if (!(await manageableHere(id))) {
125
- const user = await cms.users.get(id);
126
- if (user && (Object.keys(patch) as (keyof UpdateUserInput)[]).some(key => patch[key] !== undefined && patch[key] !== user[key])) throw new ClientVisibleError(NETWORK_ACCOUNT_LOCKED);
127
- return;
212
+ if (await User.exists({ email: input.email })) {
213
+ throw new ClientVisibleError('An account with this email already exists.');
214
+ }
215
+ const id = uuidv7();
216
+ await User.insert({
217
+ id,
218
+ email: input.email,
219
+ name: input.name ?? null,
220
+ passwordHash: await hashPassword(input.password!),
221
+ avatar: null,
222
+ meta: null,
223
+ createdAt: new Date(),
224
+ });
225
+ // Roles chosen by someone who may assign them; otherwise the default role, when one is set.
226
+ const fallback = input.roleIds === undefined ? await defaultRole() : null;
227
+ const roleIds = [...new Set(input.roleIds ?? (fallback ? [fallback.id] : []))];
228
+ if (roleIds.length) {
229
+ const known = await Role.find({ where: { id: In(roleIds) } });
230
+ if (known.length !== roleIds.length) throw new ClientVisibleError('Choose roles that exist.');
231
+ await syncUserRoles(id, roleIds);
128
232
  }
129
- await visible(cms.users.update(id, patch));
233
+ if (input.invite) await sendInvitation(id);
234
+ return { id, email: input.email, name: input.name ?? '', avatar: null, meta: null, roles: [] };
235
+ }
236
+
237
+ const SHARED_ACCOUNT = authOptions.accountLabels.sharedNotice;
238
+
239
+ export async function updateUser(id: string, patch: UpdateUserInput): Promise<void> {
240
+ if (currentTenant() && !await tenantOwnAccount(id)) throw new ClientVisibleError(SHARED_ACCOUNT);
241
+ if (Object.keys(patch).length) await User.update({ id }, patch);
130
242
  }
131
243
 
132
244
  /**
133
- * Set a user's password. Every other session of the account ends, so whoever had the old
134
- * password is signed out; the caller's own session stays when it is their own password.
245
+ * Let a user sign in, or stop them: a disabled account is a guest with every session it has.
246
+ * In a tenant a member's account is shared, so only the tenant's own accounts change here.
135
247
  */
248
+ export async function setUserStatus(id: string, status: 'active' | 'disabled'): Promise<void> {
249
+ if (currentTenant() && !await tenantOwnAccount(id)) throw new ClientVisibleError(SHARED_ACCOUNT);
250
+ if (status === 'disabled') {
251
+ await requireAnotherAdmin(id, 'disabled');
252
+ if (!currentTenant()) await requireAnotherNetworkAdmin(id, 'disabled');
253
+ }
254
+ await User.update({ id }, { status });
255
+ if (status === 'disabled') await sql`DELETE FROM sessions WHERE user_id = ${id} AND kind = 'auth'`;
256
+ }
257
+
136
258
  export async function changeUserPassword(id: string, newPassword: string): Promise<void> {
137
- if (!(await manageableHere(id))) throw new ClientVisibleError(NETWORK_ACCOUNT_LOCKED);
138
- const cms = currentCms();
139
- if (!(await visible(cms.users.setPassword(id, newPassword)))) throw new ClientVisibleError('User not found.');
140
- const c = getRequestContext();
141
- const own = c && (c.get('user') as { id?: string } | undefined)?.id === id ? getCookie(c, SESSION_COOKIE_NAME) : undefined;
142
- // On an added site, a network account's sessions are the network host's; its sites' child sessions end with them.
143
- const sessions = cms.siteAccounts && (await cms.storesOf(id)).kind === 'network' && c ? networkFor(c.env as CmsBindings).main.authSessions : cms.authSessions;
144
- await sessions.revokeAllForUser(id, own);
259
+ if (currentTenant() && !await tenantOwnAccount(id)) throw new ClientVisibleError(SHARED_ACCOUNT);
260
+ if (!(await User.exists({ id }))) throw new ClientVisibleError('User not found.');
261
+ await User.update({ id }, { passwordHash: await hashPassword(newPassword) });
145
262
  }
146
263
 
147
264
  /**
148
- * On the main site, deletes the account: from every site it belongs to, then what signs it in.
149
- * On another site, removes the member and their roles: a site account goes with them, a network
150
- * account stays. Content keeps its author ID. The last network admin cannot be deleted.
265
+ * Refuse a change that would leave nobody active with the admin role here (in this tenant, or
266
+ * in the application without tenants). `keeps` says whether the user still has the role after it.
151
267
  */
268
+ async function requireAnotherAdmin(userId: string, change: string, keeps = false): Promise<void> {
269
+ if (keeps) return;
270
+ const admin = await Role.findOne({ where: { id: 'admin' } });
271
+ if (!admin || !await UserRole.exists({ userId, roleId: admin.id })) return;
272
+ const others = (await sql<{ total: number }>`
273
+ SELECT COUNT(*) AS total FROM user_roles ur INNER JOIN users u ON u.id = ur.user_id
274
+ WHERE ur.role_id = ${admin.id} AND ur.user_id <> ${userId} AND u.status = 'active'
275
+ `).rows[0];
276
+ if (!Number(others?.total ?? 0)) throw new ClientVisibleError(`The last administrator cannot be ${change}.`);
277
+ }
278
+
152
279
  export async function deleteUser(id: string): Promise<void> {
153
- const c = getRequestContext();
154
- const cms = currentCms();
155
- if (c?.get('site')?.id && c.get('site').id !== MAIN_SITE) { await visible(cms.users.delete(id)); return; }
156
- // Deleting on the main site removes the account from every site it belongs to.
157
- if (!(await manageableHere(id))) throw new ClientVisibleError(NETWORK_ACCOUNT_LOCKED);
158
- await visible(networkFor(c!.env as CmsBindings).deleteAccount(id, { principal: systemPrincipal('users') }));
280
+ await requireAnotherAdmin(id, 'removed');
281
+ // In a tenant: a member leaves, and the account stays. The tenant's own account goes, with what belongs to it.
282
+ if (currentTenant() && await tenantOwnAccount(id)) {
283
+ await sql`DELETE FROM sessions WHERE user_id = ${id}`;
284
+ await apiTokens.revokeAll(id);
285
+ await security.reset(id);
286
+ await UserRole.delete({ userId: id });
287
+ await User.delete({ id });
288
+ return;
289
+ }
290
+ if (currentTenant()) return leaveCurrentTenant(id);
291
+ await requireAnotherNetworkAdmin(id, 'removed');
292
+ await UserRole.delete({ userId: id });
293
+ await User.delete({ id });
294
+ await forgetMemberships(id);
159
295
  }
160
296
 
161
297
  export async function assignRole(userId: string, roleId: string): Promise<void> {
162
- const user = await currentCms().users.get(userId);
163
- if (user) await syncUserRoles(userId, [...new Set([...user.roles, roleId])]);
298
+ await UserRole.upsert(
299
+ { userId, roleId, createdAt: new Date() },
300
+ ['userId', 'roleId'],
301
+ );
164
302
  }
165
303
 
166
304
  export async function removeRole(userId: string, roleId: string): Promise<void> {
167
- const user = await currentCms().users.get(userId);
168
- if (user) await syncUserRoles(userId, user.roles.filter(role => role !== roleId));
305
+ if (roleId === 'admin') await requireAnotherAdmin(userId, 'left without the admin role');
306
+ await UserRole.delete({ userId, roleId });
169
307
  }
170
308
 
171
309
  export async function syncUserRoles(userId: string, roleIds: string[]): Promise<void> {
172
- await visible(currentCms().users.setRoles(userId, roleIds));
310
+ const admin = await Role.findOne({ where: { id: 'admin' } });
311
+ await requireAnotherAdmin(userId, 'left without the admin role', !!admin && roleIds.includes(admin.id));
312
+ await UserRole.delete({ userId });
313
+ if (roleIds.length) {
314
+ const createdAt = new Date();
315
+ await UserRole.insert(roleIds.map((roleId) => ({ userId, roleId, createdAt })));
316
+ }
173
317
  }
@@ -0,0 +1,219 @@
1
+ // Tenants (src/dashboard.config.ts: `tenants`). Each tenant has its own database; accounts,
2
+ // sessions and the list of tenants are in the application's own ("main") database.
3
+ //
4
+ // A request for a tenant's host runs in that tenant's ORM scope, so models and services reach
5
+ // the tenant's database. Account code steps back to the main database with `accounts()`.
6
+ // With tenants off, or on the main host, both are the same database and these do nothing.
7
+ import { tenantORM } from '@/orm/factory';
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
+ import type { Context } from 'hono';
10
+ import type { ORM } from '@cossackframework/database';
11
+ import { getRequestContext } from '@cossackframework/core';
12
+ import { authOptions } from './auth-options';
13
+ import { Tenant } from '@/models/Tenant';
14
+ import { TenantDomain } from '@/models/TenantDomain';
15
+ import { TenantNetwork } from '@/models/TenantNetwork';
16
+
17
+ /** The tenant a request is for. */
18
+ export interface TenantInfo {
19
+ readonly id: string;
20
+ readonly slug: string;
21
+ readonly name: string;
22
+ readonly database: string;
23
+ readonly status: 'creating' | 'active' | 'archived' | 'deleted';
24
+ /** The tenant's primary domain, when it has one: its other hosts redirect there. */
25
+ readonly primaryHost?: string;
26
+ }
27
+
28
+ const TENANT = 'tenant';
29
+ const MAIN_ORM = 'tenant:main-orm';
30
+ const TENANT_ORM = 'tenant:orm';
31
+
32
+ export const tenantsEnabled = authOptions.tenants.enabled;
33
+ export const sharedSignIn = tenantsEnabled && authOptions.tenants.signIn === 'shared';
34
+
35
+ /** A tenant's slug: a DNS label. `www`, `main` and `new` are not tenants. */
36
+ export const TENANT_SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
37
+ export const RESERVED_SLUGS: readonly string[] = ['www', 'main', 'new', 'app', 'api', 'admin'];
38
+
39
+ /** A request's host name: lowercase, without the port. */
40
+ export function hostName(url: string): string {
41
+ try { return new URL(url).hostname.toLowerCase(); } catch { return ''; }
42
+ }
43
+
44
+ /** The main host, from APP_URL. Without APP_URL every request is the main tenant's. */
45
+ export function mainHost(): string {
46
+ return hostName(env('APP_URL', ''));
47
+ }
48
+
49
+ /**
50
+ * What `withTenant()` sets for the work it runs. It is kept beside the work, not on the request:
51
+ * a request may run work for several tenants at once, and each sees its own.
52
+ */
53
+ interface TenantScope {
54
+ readonly tenant: TenantInfo | null;
55
+ readonly main: ORM | undefined;
56
+ readonly orm: ORM;
57
+ readonly home: 'tenant' | 'main' | undefined;
58
+ }
59
+ const tenantScope = new AsyncLocalStorage<TenantScope>();
60
+
61
+ /** The tenant of this request, or null on the main host (and with tenants off). Inside `withTenant()`: the tenant of that work. */
62
+ export function currentTenant(c: Context | undefined = getRequestContext()): TenantInfo | null {
63
+ const scope = tenantScope.getStore();
64
+ if (scope) return scope.tenant;
65
+ return (c?.get(TENANT as never) as TenantInfo | undefined) ?? null;
66
+ }
67
+
68
+ /** The request's marks, or those of the `withTenant()` the caller is in. */
69
+ function marks(): { main: ORM | undefined; orm: ORM | undefined; home: 'tenant' | 'main' | undefined } {
70
+ const scope = tenantScope.getStore();
71
+ if (scope) return scope;
72
+ const c = getRequestContext();
73
+ return { main: c?.get(MAIN_ORM as never) as ORM | undefined, orm: c?.get(TENANT_ORM as never) as ORM | undefined, home: c?.get(ACCOUNT_HOME as never) as 'tenant' | 'main' | undefined };
74
+ }
75
+
76
+ /**
77
+ * Run account code against the main database: accounts, sessions, second factors, tokens,
78
+ * the list of tenants. Inside a tenant's request it steps out of the tenant's database.
79
+ */
80
+ export function accounts<T>(work: () => Promise<T>): Promise<T> {
81
+ const { main, home } = marks();
82
+ // A tenant's own account keeps everything in the tenant's database.
83
+ if ((accountHome.getStore() ?? home) === 'tenant') return inTenant(work);
84
+ return main ? main.run(work) : work();
85
+ }
86
+
87
+ // Where the account that the running code is about lives: the main database, or the tenant's
88
+ // own for an account of that tenant only. Unset: the signed-in user's, else the main one.
89
+ const accountHome = new AsyncLocalStorage<'tenant' | 'main'>();
90
+ const ACCOUNT_HOME = 'tenant:account-home';
91
+
92
+ /** Run code about an account of this tenant only: `accounts()` inside it reaches the tenant's database. */
93
+ export function asTenantAccount<T>(work: () => Promise<T>): Promise<T> {
94
+ return currentTenant() ? accountHome.run('tenant', work) : work();
95
+ }
96
+
97
+ /** Run code about an account of the main database, whoever is signed in. */
98
+ export function asMainAccount<T>(work: () => Promise<T>): Promise<T> {
99
+ return accountHome.run('main', work);
100
+ }
101
+
102
+ /** Whether the running code is about an account of this tenant only. */
103
+ export function tenantAccountHome(): boolean {
104
+ return currentTenant() !== null && (accountHome.getStore() ?? marks().home) === 'tenant';
105
+ }
106
+
107
+ /** @internal The signed-in user of this request is an account of this tenant only. */
108
+ export function markTenantAccountRequest(c: Context): void {
109
+ c.set(ACCOUNT_HOME as never, 'tenant' as never);
110
+ }
111
+
112
+ /** Run code against the request's tenant database again, from inside `accounts()`. */
113
+ export function inTenant<T>(work: () => Promise<T>): Promise<T> {
114
+ const { orm } = marks();
115
+ return orm ? orm.run(work) : work();
116
+ }
117
+
118
+ /** Run code against one tenant's database, whatever the request's host: the main host's Tenants screen uses it. */
119
+ export async function withTenant<T>(tenant: Pick<TenantInfo, 'database' | 'slug'> & Partial<TenantInfo>, work: () => Promise<T>): Promise<T> {
120
+ const c = getRequestContext();
121
+ const opened = await tenantORM(c?.env, tenant);
122
+ const outer = marks();
123
+ try {
124
+ return await tenantScope.run({
125
+ // `accounts()` inside the work still reaches the main database.
126
+ main: outer.main ?? (c?.get('orm' as never) as ORM | undefined),
127
+ orm: opened.orm,
128
+ // With the whole tenant given, it is the current one for the work: code that asks which
129
+ // tenant it is in gets this one, and the signed-in user's own home does not count there.
130
+ tenant: tenant.id ? tenant as TenantInfo : currentTenant(),
131
+ home: tenant.id ? undefined : outer.home,
132
+ }, () => opened.orm.run(work));
133
+ } finally {
134
+ await opened.release();
135
+ }
136
+ }
137
+
138
+ function info(row: Tenant, primaryHost?: string): TenantInfo {
139
+ return { id: row.id, slug: row.slug, name: row.name, database: row.database, status: row.status, ...(primaryHost ? { primaryHost } : {}) };
140
+ }
141
+
142
+ // Whether the network of tenants runs: a setting in the main database, remembered for half a minute.
143
+ let running: { at: number; value: boolean } | undefined;
144
+
145
+ /** Whether tenants' hosts answer. A network administrator turns the network off and on; off, only the main host answers. Called in the main database's scope. */
146
+ export async function tenantsRunning(): Promise<boolean> {
147
+ if (!tenantsEnabled) return false;
148
+ if (running && Date.now() - running.at < LOOKUP_MS) return running.value;
149
+ const row = await TenantNetwork.findOne({ where: { key: 'enabled' } });
150
+ running = { at: Date.now(), value: row?.value !== 'false' };
151
+ return running.value;
152
+ }
153
+
154
+ /** Turn the network of tenants on or off. Tenants keep their data while it is off. */
155
+ export async function setTenantsRunning(on: boolean): Promise<void> {
156
+ await TenantNetwork.upsert({ key: 'enabled', value: on ? 'true' : 'false', updatedAt: new Date() }, ['key']);
157
+ running = undefined;
158
+ forgetTenantHosts();
159
+ }
160
+
161
+ /** Whether a signed-in account may make a tenant of its own (the Tenants screen's setting). Off by default. */
162
+ export async function tenantRegistrationOn(): Promise<boolean> {
163
+ return (await TenantNetwork.findOne({ where: { key: 'registration' } }))?.value === 'on';
164
+ }
165
+
166
+ export async function setTenantRegistrationOn(on: boolean): Promise<void> {
167
+ await TenantNetwork.upsert({ key: 'registration', value: on ? 'on' : 'off', updatedAt: new Date() }, ['key']);
168
+ }
169
+
170
+ /** The tenant that asked for this host as a domain, verified or not: its ID answers `/.well-known/cossack-tenant`. */
171
+ export async function tenantClaimingHost(host: string): Promise<string | null> {
172
+ return (await TenantDomain.findOne({ where: { host } }))?.tenantId ?? null;
173
+ }
174
+
175
+ // Which tenant a host is, remembered for half a minute.
176
+ const lookups = new Map<string, { at: number; tenant: TenantInfo | null }>();
177
+ const LOOKUP_MS = 30_000;
178
+
179
+ /** Forget remembered hosts, after a tenant or a domain changed. Other servers follow within half a minute. */
180
+ export function forgetTenantHosts(): void {
181
+ lookups.clear();
182
+ }
183
+
184
+ /** The tenant a host name reaches: `<slug>.<main host>` or one of its domains. Called in the main database's scope. */
185
+ export async function tenantOfHost(host: string, main = mainHost()): Promise<TenantInfo | null> {
186
+ const known = lookups.get(host);
187
+ if (known && Date.now() - known.at < LOOKUP_MS) return known.tenant;
188
+ let row: Tenant | null = null;
189
+ if (main && host.endsWith(`.${main}`)) {
190
+ const slug = host.slice(0, -main.length - 1);
191
+ if (TENANT_SLUG.test(slug)) row = await Tenant.findOne({ where: { slug } });
192
+ }
193
+ if (!row) {
194
+ const domain = await TenantDomain.findOne({ where: { host } });
195
+ // A domain reaches its tenant once it was verified.
196
+ if (domain?.verifiedAt) row = await Tenant.findOne({ where: { id: domain.tenantId } });
197
+ }
198
+ const primary = row ? await TenantDomain.findOne({ where: { tenantId: row.id, isPrimary: true } }) : null;
199
+ const tenant = row ? info(row, primary?.verifiedAt ? primary.host : undefined) : null;
200
+ if (lookups.size > 2000) lookups.clear();
201
+ lookups.set(host, { at: Date.now(), tenant });
202
+ return tenant;
203
+ }
204
+
205
+ /** The address of a tenant's host (or the main host for null), with APP_URL's scheme and port. */
206
+ export function tenantOrigin(tenant: Pick<TenantInfo, 'slug' | 'primaryHost'> | null): string | null {
207
+ const configured = env('APP_URL', '');
208
+ if (!configured) return null;
209
+ const url = new URL(configured);
210
+ if (tenant) url.hostname = tenant.primaryHost ?? `${tenant.slug}.${url.hostname}`;
211
+ return url.origin;
212
+ }
213
+
214
+ /** @internal The middleware's marks on the request. */
215
+ export function markTenantRequest(c: Context, tenant: TenantInfo, main: ORM, orm: ORM): void {
216
+ c.set(TENANT as never, tenant as never);
217
+ c.set(MAIN_ORM as never, main as never);
218
+ c.set(TENANT_ORM as never, orm as never);
219
+ }