@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,447 @@
1
+ // Tenants: the list, their domains and their members. Rows are in the main database; a
2
+ // tenant's roles and member rows are in its own. See src/tenants.ts for the two scopes.
3
+ import { ClientVisibleError, getRequestContext } from '@cossackframework/core';
4
+ import { sql, TENANT_DATABASE } from '@cossackframework/database';
5
+ import { uuidv7 } from '../lib/uuid';
6
+ import { accounts, asMainAccount, currentTenant, forgetTenantHosts, inTenant, mainHost, RESERVED_SLUGS, setTenantRegistrationOn, setTenantsRunning, TENANT_SLUG, tenantRegistrationOn, tenantsEnabled, tenantsRunning, withTenant, type TenantInfo } from '../tenants';
7
+ import * as security from './security';
8
+ import { authOptions } from '../auth-options';
9
+ import { Tenant } from '@/models/Tenant';
10
+ import { TenantDomain } from '@/models/TenantDomain';
11
+ import { TenantMember } from '@/models/TenantMember';
12
+ import { TenantNetwork } from '@/models/TenantNetwork';
13
+ import { User } from '@/models/User';
14
+ import { Role } from '@/models/Role';
15
+ import { UserRole } from '@/models/UserRole';
16
+ import { UserSecurity } from '@/models/UserSecurity';
17
+ import { Passkey } from '@/models/Passkey';
18
+ import { ApiToken } from '@/models/ApiToken';
19
+
20
+ export interface TenantSummary extends TenantInfo {
21
+ readonly createdAt: string;
22
+ readonly members: number;
23
+ readonly domains: TenantDomainSummary[];
24
+ /** When a deleted tenant is purged. */
25
+ readonly purgedAt?: string;
26
+ }
27
+
28
+ export interface TenantDomainSummary { readonly host: string; readonly primary: boolean; readonly verified: boolean }
29
+
30
+ /** How long a deleted tenant can be restored. */
31
+ export const TENANT_PURGE_MS = 30 * 24 * 60 * 60 * 1000;
32
+
33
+ export interface TenantMemberSummary {
34
+ readonly id: string;
35
+ readonly email: string;
36
+ readonly name: string;
37
+ readonly roles: string[];
38
+ }
39
+
40
+ const HOST = /^(?=.{1,191}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
41
+
42
+ /** Tenants are managed on the main host, by network administrators. A seeder or a command has no request and may. */
43
+ function required(): void {
44
+ if (!tenantsEnabled) throw new ClientVisibleError('Tenants are not turned on (src/dashboard.config.ts).');
45
+ if (currentTenant()) throw new ClientVisibleError('Tenants are managed on the main host.');
46
+ const c = getRequestContext();
47
+ if (c && (c.get('user' as never) as { networkAdmin?: boolean } | undefined)?.networkAdmin !== true) throw new ClientVisibleError('Only a network administrator manages tenants.');
48
+ }
49
+
50
+ export interface NetworkAdminSummary { readonly id: string; readonly email: string; readonly name: string }
51
+
52
+ /** The accounts that reach every tenant. */
53
+ export async function listNetworkAdmins(): Promise<NetworkAdminSummary[]> {
54
+ required();
55
+ return (await User.find({ where: { networkAdmin: true }, order: { email: 'asc' }, take: 500 })).map(user => ({ id: user.id, email: user.email, name: user.name ?? '' }));
56
+ }
57
+
58
+ /** Make the account with this email a network administrator, or stop it being one. The last active one stays. */
59
+ export async function setNetworkAdmin(email: string, admin: boolean): Promise<void> {
60
+ required();
61
+ const account = await User.findOne({ where: { email: email.trim().toLowerCase() } });
62
+ if (!account) throw new ClientVisibleError('No account has this email.');
63
+ if (!admin) await requireAnotherNetworkAdmin(account.id, 'left without the role');
64
+ await User.update({ id: account.id }, { networkAdmin: admin });
65
+ }
66
+
67
+ /** In the main database: refuse a change that would leave no active network administrator. */
68
+ export async function requireAnotherNetworkAdmin(userId: string, change: string): Promise<void> {
69
+ const account = await User.findOne({ where: { id: userId } });
70
+ if (!account?.networkAdmin) return;
71
+ const others = (await User.find({ where: { networkAdmin: true, status: 'active' }, take: 2 })).filter(user => user.id !== userId);
72
+ if (!others.length) throw new ClientVisibleError(`The last network administrator cannot be ${change}.`);
73
+ }
74
+
75
+ function info(row: Tenant): TenantInfo {
76
+ return { id: row.id, slug: row.slug, name: row.name, database: row.database, status: row.status };
77
+ }
78
+
79
+ /** Every tenant, newest first, with its member count and domains. */
80
+ export async function listTenants(): Promise<TenantSummary[]> {
81
+ required();
82
+ const [rows, members, domains] = await Promise.all([
83
+ Tenant.find({ order: { createdAt: 'desc' }, take: 500 }),
84
+ TenantMember.find({ take: 20_000 }),
85
+ TenantDomain.find({ take: 5000 }),
86
+ ]);
87
+ const primaryOf = (id: string) => domains.find(domain => domain.tenantId === id && domain.isPrimary && domain.verifiedAt)?.host;
88
+ return rows.map(row => ({
89
+ ...info(row),
90
+ ...(primaryOf(row.id) ? { primaryHost: primaryOf(row.id)! } : {}),
91
+ createdAt: row.createdAt.toISOString(),
92
+ members: members.filter(member => member.tenantId === row.id).length,
93
+ domains: domains.filter(domain => domain.tenantId === row.id).map(domain => ({ host: domain.host, primary: domain.isPrimary, verified: domain.verifiedAt !== null }))
94
+ .sort((a, b) => a.host < b.host ? -1 : 1),
95
+ ...(row.status === 'deleted' && row.deletedAt ? { purgedAt: new Date(row.deletedAt.getTime() + TENANT_PURGE_MS).toISOString() } : {}),
96
+ }));
97
+ }
98
+
99
+ export async function getTenant(id: string): Promise<TenantInfo | null> {
100
+ required();
101
+ const row = await Tenant.findOne({ where: { id } });
102
+ return row ? info(row) : null;
103
+ }
104
+
105
+ /**
106
+ * Make a tenant: its row, its database (created or opened, with every migration), the main
107
+ * tenant's roles copied into it, and the creator as its administrator. A tenant that failed
108
+ * half-way stays `creating` and unreachable; creating it again with the same slug finishes it.
109
+ */
110
+ export async function createTenant(input: { name: string; slug: string }, creator: { id: string }): Promise<TenantInfo> {
111
+ required();
112
+ return makeTenant(input, creator, true);
113
+ }
114
+
115
+ /** How many tenants one account registers in a day. */
116
+ export const TENANT_REGISTRATIONS = Object.freeze({ max: 3, windowMs: 24 * 60 * 60 * 1000 });
117
+
118
+ /** Whether signed-in accounts make tenants of their own, on the main host. A network administrator turns it on. */
119
+ export async function tenantRegistrationOpen(): Promise<boolean> {
120
+ return tenantsEnabled && !currentTenant() && await tenantsRunning() && await tenantRegistrationOn();
121
+ }
122
+
123
+ export async function setTenantRegistration(on: boolean): Promise<void> {
124
+ required();
125
+ await setTenantRegistrationOn(on);
126
+ }
127
+
128
+ /**
129
+ * A signed-in main account makes a tenant of its own and is its administrator. It needs the
130
+ * network's registration setting; an account registers at most three a day.
131
+ */
132
+ export async function registerTenant(input: { name: string; slug: string }, user: { id: string }): Promise<TenantInfo> {
133
+ if (!await tenantRegistrationOpen()) throw new ClientVisibleError('Registration of tenants is closed.');
134
+ if (!await security.attempt('tenant-registration', `u:${user.id}`, TENANT_REGISTRATIONS.max, TENANT_REGISTRATIONS.windowMs)) throw new ClientVisibleError('You registered three tenants today. Try again tomorrow.');
135
+ return makeTenant(input, user, false);
136
+ }
137
+
138
+ /** Who started a tenant that is still being created: a network setting, gone once the tenant is active. */
139
+ const creatorKey = (id: string) => `tenant.creator:${id}`;
140
+
141
+ /** `manager`: a network administrator makes it, and may finish a tenant someone else started. */
142
+ async function makeTenant(input: { name: string; slug: string }, creator: { id: string }, manager: boolean): Promise<TenantInfo> {
143
+ const name = input.name.trim();
144
+ const slug = input.slug.trim().toLowerCase();
145
+ if (!name || name.length > 120) throw new ClientVisibleError('Give the tenant a name of at most 120 characters.');
146
+ if (!TENANT_SLUG.test(slug) || RESERVED_SLUGS.includes(slug)) throw new ClientVisibleError('The address is lowercase letters, digits and hyphens, and not a reserved word.');
147
+ const database = slug.replaceAll('-', '_');
148
+ if (!TENANT_DATABASE.test(database)) throw new ClientVisibleError('The address is too long.');
149
+ let row = await Tenant.findOne({ where: { slug } });
150
+ if (row && row.status !== 'creating') throw new ClientVisibleError('A tenant with this address already exists.');
151
+ // A tenant that is being created is finished by the account that started it, or by a network
152
+ // administrator: nobody else becomes its administrator by asking for the same address.
153
+ if (row && !manager && (await TenantNetwork.findOne({ where: { key: creatorKey(row.id) } }))?.value !== creator.id) {
154
+ throw new ClientVisibleError('A tenant with this address already exists.');
155
+ }
156
+ if (!row) {
157
+ const id = uuidv7();
158
+ await Tenant.insert({ id, slug, name, database, status: 'creating', createdAt: new Date() });
159
+ await TenantNetwork.upsert({ key: creatorKey(id), value: creator.id, updatedAt: new Date() }, ['key']);
160
+ row = (await Tenant.findOne({ where: { id } }))!;
161
+ }
162
+ const tenant = info(row);
163
+ const roles = await Role.find({ take: 500 });
164
+ try {
165
+ await withTenant(tenant, async () => {
166
+ // Opening the database applied the migrations. The main tenant's roles are its first roles.
167
+ const known = new Set((await Role.find({ take: 500 })).map(role => role.name));
168
+ const missing = roles.filter(role => !known.has(role.name));
169
+ if (missing.length) await Role.insert(missing.map(role => ({ id: role.id, name: role.name, permissions: role.permissions, createdAt: new Date() })));
170
+ });
171
+ } catch (error) {
172
+ console.error(`[tenants] could not prepare the database of ${slug}`, error);
173
+ throw new ClientVisibleError(`The tenant's database could not be opened: ${error instanceof Error ? error.message : 'unknown error'}`);
174
+ }
175
+ await addMemberById(tenant, creator.id, ['admin']);
176
+ await Tenant.update({ id: tenant.id }, { status: 'active' });
177
+ await TenantNetwork.delete({ key: creatorKey(tenant.id) });
178
+ forgetTenantHosts();
179
+ return { ...tenant, status: 'active' };
180
+ }
181
+
182
+ /**
183
+ * Archive a tenant (its hosts answer 503, its data stays), delete it (its hosts answer 404; it
184
+ * can be restored for 30 days) or bring it back.
185
+ */
186
+ export async function setTenantStatus(id: string, status: 'active' | 'archived' | 'deleted'): Promise<void> {
187
+ required();
188
+ const row = await Tenant.findOne({ where: { id } });
189
+ if (!row || row.status === 'creating') throw new ClientVisibleError('Tenant not found.');
190
+ await Tenant.update({ id }, { status, deletedAt: status === 'deleted' ? new Date() : null });
191
+ forgetTenantHosts();
192
+ }
193
+
194
+ /**
195
+ * Forget the tenants that were deleted more than 30 days ago: their rows, domains and
196
+ * memberships. Their databases are not dropped here: a file or a database is yours to remove.
197
+ * Returns what was purged, so a schedule or a script can remove each database.
198
+ */
199
+ export async function purgeDeletedTenants(now = Date.now()): Promise<TenantInfo[]> {
200
+ const due = (await Tenant.find({ where: { status: 'deleted' }, take: 500 })).filter(row => row.deletedAt && row.deletedAt.getTime() + TENANT_PURGE_MS <= now);
201
+ for (const row of due) {
202
+ await TenantMember.delete({ tenantId: row.id });
203
+ await TenantDomain.delete({ tenantId: row.id });
204
+ await Tenant.delete({ id: row.id, status: 'deleted' });
205
+ }
206
+ if (due.length) forgetTenantHosts();
207
+ return due.map(info);
208
+ }
209
+
210
+ /** Whether tenants' hosts answer (the Tenants screen's switch). */
211
+ export async function networkRunning(): Promise<boolean> {
212
+ required();
213
+ return tenantsRunning();
214
+ }
215
+
216
+ export async function setNetworkRunning(on: boolean): Promise<void> {
217
+ required();
218
+ await setTenantsRunning(on);
219
+ }
220
+
221
+ /** Give a tenant a host name of its own. The name must point at this application. */
222
+ export async function addTenantDomain(id: string, host: string): Promise<void> {
223
+ required();
224
+ const name = host.trim().toLowerCase().replace(/\.$/, '');
225
+ const main = mainHost();
226
+ if (!HOST.test(name)) throw new ClientVisibleError('Enter a host name, such as app.example.com.');
227
+ if (main && (name === main || name.endsWith(`.${main}`))) throw new ClientVisibleError(`Names under ${main} are tenants' own addresses.`);
228
+ if (!await Tenant.exists({ id })) throw new ClientVisibleError('Tenant not found.');
229
+ if (await TenantDomain.exists({ host: name })) throw new ClientVisibleError('This host name is already in use.');
230
+ // Without verification (src/dashboard.config.ts), a network administrator's word is enough.
231
+ await TenantDomain.insert({ host: name, tenantId: id, isPrimary: false, verifiedAt: authOptions.tenants.verifyDomains ? null : new Date(), createdAt: new Date() });
232
+ forgetTenantHosts();
233
+ }
234
+
235
+ /**
236
+ * Check that a domain points at this application: it must answer
237
+ * `/.well-known/cossack-tenant` with the tenant's ID, which this application does for every
238
+ * host a tenant asked for. The domain reaches the tenant from then on.
239
+ */
240
+ export async function verifyTenantDomain(id: string, host: string): Promise<void> {
241
+ required();
242
+ const domain = await TenantDomain.findOne({ where: { host, tenantId: id } });
243
+ if (!domain) throw new ClientVisibleError('Domain not found.');
244
+ if (domain.verifiedAt) return;
245
+ const base = new URL(env('APP_URL', '') || 'https://localhost');
246
+ let answer = '';
247
+ try {
248
+ const response = await fetch(`${base.protocol}//${host}${base.port ? `:${base.port}` : ''}/.well-known/cossack-tenant`, { redirect: 'manual', signal: AbortSignal.timeout(8000) });
249
+ answer = response.ok ? (await response.text()).trim().slice(0, 200) : '';
250
+ } catch { /* unreachable: not verified */ }
251
+ if (answer !== id) throw new ClientVisibleError(`${host} does not point at this application yet. Point its DNS here and try again.`);
252
+ await TenantDomain.update({ host, tenantId: id }, { verifiedAt: new Date() });
253
+ forgetTenantHosts();
254
+ }
255
+
256
+ /** Make a verified domain the tenant's address (its other hosts redirect there), or none with an empty host. */
257
+ export async function setPrimaryTenantDomain(id: string, host: string): Promise<void> {
258
+ required();
259
+ if (host) {
260
+ const domain = await TenantDomain.findOne({ where: { host, tenantId: id } });
261
+ if (!domain) throw new ClientVisibleError('Domain not found.');
262
+ if (!domain.verifiedAt) throw new ClientVisibleError('Verify the domain before making it the primary one.');
263
+ }
264
+ await TenantDomain.update({ tenantId: id }, { isPrimary: false });
265
+ if (host) await TenantDomain.update({ host, tenantId: id }, { isPrimary: true });
266
+ forgetTenantHosts();
267
+ }
268
+
269
+ export async function removeTenantDomain(id: string, host: string): Promise<void> {
270
+ required();
271
+ await TenantDomain.delete({ host, tenantId: id });
272
+ forgetTenantHosts();
273
+ }
274
+
275
+ /**
276
+ * Make an account a member of a tenant: a member row under the account's ID in the tenant's
277
+ * database (email and name copied, no password), its roles there, and the membership in the
278
+ * main database. Call it in the main database's scope. Roles are given by ID.
279
+ */
280
+ export async function addMemberById(tenant: TenantInfo, userId: string, roleNames: readonly string[] = []): Promise<void> {
281
+ const account = await User.findOne({ where: { id: userId } });
282
+ if (!account) throw new ClientVisibleError('Account not found.');
283
+ await withTenant(tenant, () => joinHere(account, roleNames));
284
+ await TenantMember.upsert({ tenantId: tenant.id, userId, createdAt: new Date() }, ['tenantId', 'userId']);
285
+ }
286
+
287
+ /** In a tenant's scope: the member row and roles of an account. */
288
+ async function joinHere(account: User, roleNames: readonly string[]): Promise<void> {
289
+ if (await User.exists({ id: account.id })) {
290
+ await User.update({ id: account.id }, { email: account.email, name: account.name, avatar: account.avatar, status: 'active' });
291
+ } else {
292
+ await User.insert({ id: account.id, email: account.email, name: account.name, passwordHash: null, avatar: account.avatar, meta: null, status: 'active', createdAt: new Date() });
293
+ }
294
+ if (!roleNames.length) return;
295
+ const roles = (await Role.find({ take: 500 })).filter(role => roleNames.includes(role.id));
296
+ for (const role of roles) await UserRole.upsert({ userId: account.id, roleId: role.id, createdAt: new Date() }, ['userId', 'roleId']);
297
+ }
298
+
299
+ /** Add the account with this email to a tenant, from the main host's Tenants screen. */
300
+ export async function addTenantMember(id: string, email: string, roleNames: readonly string[] = []): Promise<void> {
301
+ required();
302
+ const row = await Tenant.findOne({ where: { id } });
303
+ if (!row) throw new ClientVisibleError('Tenant not found.');
304
+ const account = await User.findOne({ where: { email: email.trim().toLowerCase() } });
305
+ if (!account) throw new ClientVisibleError('No account has this email. The person registers first.');
306
+ await addMemberById(info(row), account.id, roleNames);
307
+ }
308
+
309
+ export async function removeTenantMember(id: string, userId: string): Promise<void> {
310
+ required();
311
+ const row = await Tenant.findOne({ where: { id } });
312
+ if (!row) throw new ClientVisibleError('Tenant not found.');
313
+ await withTenant(info(row), leaveHere.bind(null, userId));
314
+ await TenantMember.delete({ tenantId: id, userId });
315
+ }
316
+
317
+ /** In a tenant's scope: remove the member row and roles. */
318
+ async function leaveHere(userId: string): Promise<void> {
319
+ await UserRole.delete({ userId });
320
+ await User.delete({ id: userId });
321
+ }
322
+
323
+ /** A tenant's members with their roles there. */
324
+ export async function listTenantMembers(id: string): Promise<TenantMemberSummary[]> {
325
+ required();
326
+ const row = await Tenant.findOne({ where: { id } });
327
+ if (!row) return [];
328
+ return withTenant(info(row), async () => {
329
+ const [users, assignments, roles] = await Promise.all([User.find({ order: { email: 'asc' }, take: 1000 }), UserRole.find({ take: 20_000 }), Role.find({ take: 500 })]);
330
+ const names = new Map(roles.map(role => [role.id, role.name]));
331
+ return users.map(user => ({ id: user.id, email: user.email, name: user.name ?? '',
332
+ roles: assignments.filter(assignment => assignment.userId === user.id).map(assignment => names.get(assignment.roleId) ?? '').filter(Boolean).sort() }));
333
+ });
334
+ }
335
+
336
+ // --- Inside a tenant's own request (its Users screen) -------------------------------------
337
+
338
+ /**
339
+ * In a tenant's request: make the account with this email a member, creating the account when
340
+ * there is none. An existing account keeps its password; `password` is for a new one.
341
+ */
342
+ export async function joinCurrentTenant(input: { email: string; name?: string; passwordHash: string | null }): Promise<{ id: string; created: boolean }> {
343
+ const tenant = currentTenant();
344
+ if (!tenant) throw new Error('Not a tenant request.');
345
+ if (await inTenant(() => User.exists({ email: input.email }))) throw new ClientVisibleError('An account with this email is already here.');
346
+ // The main account with this email becomes a member. Without one, the new account is this tenant's own.
347
+ const account = await asMainAccount(() => accounts(() => User.findOne({ where: { email: input.email } })));
348
+ if (!account) {
349
+ if (!input.passwordHash) throw new ClientVisibleError('Set a password for the new account.');
350
+ const id = uuidv7();
351
+ await inTenant(() => User.insert({ id, email: input.email, name: input.name ?? null, passwordHash: input.passwordHash, avatar: null, meta: null, status: 'active', tenantAccount: true, createdAt: new Date() }));
352
+ return { id, created: true };
353
+ }
354
+ await inTenant(() => joinHere(account, []));
355
+ await asMainAccount(() => accounts(() => TenantMember.upsert({ tenantId: tenant.id, userId: account.id, createdAt: new Date() }, ['tenantId', 'userId'])));
356
+ return { id: account.id, created: false };
357
+ }
358
+
359
+ /** In a tenant's request: whether the user is an account of this tenant only (not a member with a main account). */
360
+ export async function tenantOwnAccount(userId: string): Promise<boolean> {
361
+ if (!currentTenant()) return false;
362
+ return inTenant(async () => (await User.findOne({ where: { id: userId } }))?.tenantAccount === true);
363
+ }
364
+
365
+ /** In a tenant's request: the account stops being a member. The account itself stays. */
366
+ export async function leaveCurrentTenant(userId: string): Promise<void> {
367
+ const tenant = currentTenant();
368
+ if (!tenant) throw new Error('Not a tenant request.');
369
+ await inTenant(async () => { await sql`DELETE FROM sessions WHERE user_id = ${userId}`; await leaveHere(userId); });
370
+ await asMainAccount(() => accounts(() => TenantMember.delete({ tenantId: tenant.id, userId })));
371
+ }
372
+
373
+ /** In the main database: forget an account's memberships, when the account is deleted. */
374
+ export async function forgetMemberships(userId: string): Promise<void> {
375
+ await TenantMember.delete({ userId });
376
+ }
377
+
378
+ /** The tenants an account is a member of, for a switcher. */
379
+ export async function tenantsOf(userId: string): Promise<TenantInfo[]> {
380
+ if (!tenantsEnabled) return [];
381
+ return accounts(async () => {
382
+ const memberships = await TenantMember.find({ where: { userId }, take: 500 });
383
+ if (!memberships.length) return [];
384
+ const ids = new Set(memberships.map(membership => membership.tenantId));
385
+ return (await Tenant.find({ take: 500 })).filter(row => ids.has(row.id) && row.status === 'active').map(info);
386
+ });
387
+ }
388
+
389
+ /** The rows of an account that move with it: its authenticator app and recovery codes. */
390
+ async function takeSecurity(userId: string): Promise<UserSecurity | null> {
391
+ const row = await UserSecurity.findOne({ where: { userId } });
392
+ if (row) await UserSecurity.delete({ userId });
393
+ // Passkeys belong to the host they were made on, and application passwords name the account's home: both are set up again.
394
+ await Passkey.delete({ userId });
395
+ await ApiToken.delete({ userId });
396
+ return row;
397
+ }
398
+
399
+ async function giveSecurity(row: UserSecurity | null): Promise<void> {
400
+ if (row) await UserSecurity.insert({ userId: row.userId, totpSecret: row.totpSecret, totpConfirmedAt: row.totpConfirmedAt, totpLastStep: row.totpLastStep, recovery: row.recovery, updatedAt: new Date() });
401
+ }
402
+
403
+ /**
404
+ * Move an account between a tenant and the main database, keeping its ID, password and
405
+ * authenticator app. `main`: an account of this tenant only becomes one every tenant can have
406
+ * as a member, and stays a member here. `tenant`: a main account that is a member of this
407
+ * tenant only, and no network administrator, becomes this tenant's own. Its sessions end, and
408
+ * it sets up passkeys and application passwords again. Call it in the main database's scope.
409
+ */
410
+ export async function moveAccount(tenant: TenantInfo, userId: string, to: 'main' | 'tenant'): Promise<void> {
411
+ required();
412
+ const here = await withTenant(tenant, () => User.findOne({ where: { id: userId } }));
413
+ if (!here) throw new ClientVisibleError('This tenant has no such user.');
414
+ // Each direction writes the account where it goes first, and removes it where it was only
415
+ // after that worked: a failure half-way leaves the account where it was, with its password.
416
+ if (to === 'main') {
417
+ if (!here.tenantAccount) throw new ClientVisibleError('This is a shared account already.');
418
+ if (await User.exists({ email: here.email })) throw new ClientVisibleError('Another shared account has this email.');
419
+ const kept = await withTenant(tenant, () => UserSecurity.findOne({ where: { userId } }));
420
+ await User.insert({ id: here.id, email: here.email, name: here.name, passwordHash: here.passwordHash, avatar: here.avatar, meta: here.meta, status: here.status, createdAt: here.createdAt });
421
+ await giveSecurity(kept);
422
+ await TenantMember.upsert({ tenantId: tenant.id, userId, createdAt: new Date() }, ['tenantId', 'userId']);
423
+ await withTenant(tenant, async () => {
424
+ await sql`DELETE FROM sessions WHERE user_id = ${userId}`;
425
+ await takeSecurity(userId);
426
+ await User.update({ id: userId }, { tenantAccount: false, passwordHash: null });
427
+ });
428
+ return;
429
+ }
430
+ if (here.tenantAccount) throw new ClientVisibleError('This is an account of this tenant already.');
431
+ const account = await User.findOne({ where: { id: userId } });
432
+ if (!account) throw new ClientVisibleError('Account not found.');
433
+ if (account.networkAdmin) throw new ClientVisibleError('A network administrator keeps a shared account.');
434
+ if ((await TenantMember.find({ where: { userId }, take: 3 })).some(member => member.tenantId !== tenant.id)) throw new ClientVisibleError('This account is a member of other tenants too.');
435
+ const kept = await UserSecurity.findOne({ where: { userId } });
436
+ await withTenant(tenant, async () => {
437
+ await sql`DELETE FROM sessions WHERE user_id = ${userId}`;
438
+ await User.update({ id: userId }, { tenantAccount: true, passwordHash: account.passwordHash, email: account.email, name: account.name, status: account.status });
439
+ await UserSecurity.delete({ userId });
440
+ await giveSecurity(kept);
441
+ });
442
+ await sql`DELETE FROM sessions WHERE user_id = ${userId}`;
443
+ await takeSecurity(userId);
444
+ await UserRole.delete({ userId });
445
+ await TenantMember.delete({ userId });
446
+ await User.delete({ id: userId });
447
+ }