@tansy/multi-tenant 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/admin.d.ts +2 -0
- package/admin.js +27 -0
- package/commands.d.ts +2 -0
- package/commands.js +116 -0
- package/doctor.d.ts +6 -0
- package/doctor.js +42 -0
- package/domains.d.ts +87 -0
- package/domains.js +146 -0
- package/index.d.ts +22 -0
- package/index.js +193 -0
- package/lifecycle.d.ts +122 -0
- package/lifecycle.js +211 -0
- package/messages.d.ts +308 -0
- package/messages.js +300 -0
- package/package.json +37 -4
- package/pages.d.ts +17 -0
- package/pages.js +373 -0
- package/paths.d.ts +13 -0
- package/paths.js +58 -0
- package/routes.d.ts +8 -0
- package/routes.js +684 -0
- package/tenants.d.ts +96 -0
- package/tenants.js +177 -0
- package/tools.d.ts +2 -0
- package/tools.js +138 -0
package/routes.js
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { adminPath, defineRoute, HttpError } from "tansy/plugin";
|
|
3
|
+
import { invitationMail, wordIn } from "./messages";
|
|
4
|
+
import { cancelPurge, DEFAULT_PURGE_DAYS, planOf, resumeTenant, schedulePurge, setLimits, suspendTenant } from "./lifecycle";
|
|
5
|
+
import { createWriteStream } from "node:fs";
|
|
6
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { Readable, Transform } from "node:stream";
|
|
10
|
+
import { pipeline } from "node:stream/promises";
|
|
11
|
+
import { forgetSlugs, usableSlug } from "./paths";
|
|
12
|
+
import { claimsOn, DEFAULT_RECORD, dnsHasProof, DOMAINS, domainsOf, findDomain, forgetHosts, normalizeHost, newToken, proof, RECORD_NAME } from "./domains";
|
|
13
|
+
import { EVERY_TENANT, findInvitation, findMember, findMemberById, findTenant, INVITATIONS, invitationById, invitationsOf, MEMBERS, MEMBERS_PERMISSION, membersOf, newId, ORGANIZATIONS, PLUGIN, publicTenant, reachable, RECORD_KEY, requireTenant, setActiveTenant, TENANT_ID, TENANT_SLUG, userOf, } from "./tenants";
|
|
14
|
+
const tenantId = z.string().regex(TENANT_ID);
|
|
15
|
+
const roleNames = z.array(z.string().min(1).max(64)).min(1).max(10);
|
|
16
|
+
/** The tenant this request is for. Every tenant route works on it alone, never on an id from the body. */
|
|
17
|
+
function currentTenant(principal) {
|
|
18
|
+
if (!principal.scope)
|
|
19
|
+
throw new HttpError(400, "SCOPE_REQUIRED", "Choose a tenant first.");
|
|
20
|
+
return principal.scope;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Roles someone may give in a tenant: any tenant role with the permission for every tenant,
|
|
24
|
+
* otherwise only roles they hold there themselves, so nobody hands out more than they have.
|
|
25
|
+
*/
|
|
26
|
+
async function assertCanGive(context, tenant, roles) {
|
|
27
|
+
const known = new Map((await context.tools.roles()).map((role) => [role.name, role]));
|
|
28
|
+
const unknown = roles.find((name) => known.get(name)?.scope !== "scoped");
|
|
29
|
+
if (unknown)
|
|
30
|
+
throw new HttpError(400, "UNKNOWN_ROLE", `"${unknown.slice(0, 64)}" isn't a tenant role. Mark a role "Within a tenant" under Dashboard → Roles to offer it here.`);
|
|
31
|
+
if (context.principal.permissions.has(EVERY_TENANT))
|
|
32
|
+
return;
|
|
33
|
+
const own = await findMember(context, tenant, userOf(context.principal).id);
|
|
34
|
+
const missing = roles.find((name) => !own?.roles.includes(name));
|
|
35
|
+
if (missing)
|
|
36
|
+
throw new HttpError(403, "ROLE_NOT_HELD", `Only someone who holds "${missing}" in this tenant can give it.`);
|
|
37
|
+
}
|
|
38
|
+
/** The same check for changing or removing someone: their roles must all be ones the caller could give. */
|
|
39
|
+
async function assertCanManage(context, tenant, member) {
|
|
40
|
+
if (member.roles.length)
|
|
41
|
+
await assertCanGive(context, tenant, member.roles);
|
|
42
|
+
}
|
|
43
|
+
/** Makes a tenant the one a session works in, or none. The same answer for a tenant that doesn't exist and one the caller can't reach. */
|
|
44
|
+
async function switchTo(context, value) {
|
|
45
|
+
const { principal } = context;
|
|
46
|
+
if (principal.kind !== "user")
|
|
47
|
+
throw new HttpError(400, "SESSION_REQUIRED", "Only a signed-in session can switch tenant. An API key is bound to one when it's created.");
|
|
48
|
+
if (value !== null) {
|
|
49
|
+
const tenant = await findTenant(context, value);
|
|
50
|
+
const member = tenant ? await findMember(context, tenant.id, principal.user.id) : null;
|
|
51
|
+
if (!tenant || tenant.status !== "active" || (!member && !principal.permissions.has(EVERY_TENANT)))
|
|
52
|
+
throw new HttpError(404, "SCOPE_NOT_FOUND", "This tenant doesn't exist.");
|
|
53
|
+
context.auditTarget("tenant", tenant.id, { member: Boolean(member) });
|
|
54
|
+
}
|
|
55
|
+
await setActiveTenant(context, principal.session.id, value);
|
|
56
|
+
return { current: value };
|
|
57
|
+
}
|
|
58
|
+
async function describeMember(context, member) {
|
|
59
|
+
const user = await context.system.users.get(member.userId);
|
|
60
|
+
return { id: member.id, userId: member.userId, name: user?.name ?? null, email: user?.email ?? null, roles: member.roles, createdAt: member.createdAt };
|
|
61
|
+
}
|
|
62
|
+
const DOMAINS_PERMISSION = "ext.multi-tenant:domains";
|
|
63
|
+
/** Enough for a site with a few aliases, and a limit on what one tenant can claim. */
|
|
64
|
+
const MAX_DOMAINS = 20;
|
|
65
|
+
/** The name the TXT record goes under, from the plugin's settings. */
|
|
66
|
+
async function recordName(context) {
|
|
67
|
+
const value = (await context.settings.get()).verificationRecord;
|
|
68
|
+
return typeof value === "string" && RECORD_NAME.test(value) ? value : DEFAULT_RECORD;
|
|
69
|
+
}
|
|
70
|
+
async function describeDomain(context, domain) {
|
|
71
|
+
return {
|
|
72
|
+
id: domain.id,
|
|
73
|
+
host: domain.host,
|
|
74
|
+
primary: domain.primary,
|
|
75
|
+
verified: domain.verifiedAt !== null,
|
|
76
|
+
verifiedAt: domain.verifiedAt,
|
|
77
|
+
checkedAt: domain.checkedAt,
|
|
78
|
+
// What the tenant's DNS must hold for the domain to verify.
|
|
79
|
+
record: { type: "TXT", name: `${await recordName(context)}.${domain.host}`, value: proof(domain.token) },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Another tenant's verified domain, or one of this tenant's own: the same answer either way, which names no tenant. */
|
|
83
|
+
const unavailable = () => new HttpError(409, "DOMAIN_UNAVAILABLE", "This domain can't be added to this tenant.");
|
|
84
|
+
/** After a change to which hosts route where: this server forgets what it held, and trusts the new set of origins at once. */
|
|
85
|
+
async function domainsChanged(context) {
|
|
86
|
+
forgetHosts();
|
|
87
|
+
await context.auth.refreshTrustedOrigins();
|
|
88
|
+
}
|
|
89
|
+
const DELETE_PERMISSION = "ext.multi-tenant:delete";
|
|
90
|
+
/** The largest archive an import takes. */
|
|
91
|
+
const MAX_IMPORT_BYTES = 2 * 1024 ** 3;
|
|
92
|
+
/** A tenant named in the address, for instance staff's routes that act on any tenant, suspended ones included. */
|
|
93
|
+
const tenantFromPath = (context) => requireTenant(context, context.params.id);
|
|
94
|
+
/** How many people a tenant has and has asked, against its limit on members. */
|
|
95
|
+
async function assertMemberRoom(context, tenant, adding = 1) {
|
|
96
|
+
const { members: limit } = await planOf(context, tenant);
|
|
97
|
+
if (limit === null)
|
|
98
|
+
return;
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
const pending = (await invitationsOf(context, tenant)).filter((invitation) => invitation.expiresAt !== null && Date.parse(invitation.expiresAt) > now).length;
|
|
101
|
+
if ((await membersOf(context, tenant)).length + pending + adding > limit)
|
|
102
|
+
throw new HttpError(403, "SCOPE_LIMIT_REACHED", "This tenant has reached its limit on members.");
|
|
103
|
+
}
|
|
104
|
+
const limitValue = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).nullable();
|
|
105
|
+
async function requireDomain(context, tenant) {
|
|
106
|
+
const id = Number(context.params.id);
|
|
107
|
+
const domain = Number.isSafeInteger(id) && id > 0 ? await findDomain(context, tenant, id) : null;
|
|
108
|
+
if (!domain)
|
|
109
|
+
throw new HttpError(404, "NOT_FOUND", "Domain not found.");
|
|
110
|
+
return domain;
|
|
111
|
+
}
|
|
112
|
+
export function tenantRoutes(options) {
|
|
113
|
+
// The dashboard's own host is never a tenant's, so it can't be claimed.
|
|
114
|
+
const reserved = new Set([new URL(options.siteUrl).hostname.toLowerCase()]);
|
|
115
|
+
return [
|
|
116
|
+
defineRoute({
|
|
117
|
+
method: "GET",
|
|
118
|
+
path: "/tenants",
|
|
119
|
+
access: "authenticated",
|
|
120
|
+
apiKey: true,
|
|
121
|
+
handler: async (context) => {
|
|
122
|
+
const user = userOf(context.principal);
|
|
123
|
+
const { tenants, memberships } = await reachable(context, user.id);
|
|
124
|
+
const roles = new Map(memberships.map((member) => [member.tenant, member.roles]));
|
|
125
|
+
return { current: context.principal.scope ?? null, items: tenants.map((tenant) => ({ ...publicTenant(tenant), roles: roles.get(tenant.id) ?? [] })) };
|
|
126
|
+
},
|
|
127
|
+
}),
|
|
128
|
+
defineRoute({
|
|
129
|
+
method: "POST",
|
|
130
|
+
path: "/tenants",
|
|
131
|
+
access: "permission",
|
|
132
|
+
permission: "ext.multi-tenant:create",
|
|
133
|
+
apiKey: true,
|
|
134
|
+
fresh: true,
|
|
135
|
+
audit: "multi_tenant.create",
|
|
136
|
+
body: z.object({ name: z.string().trim().min(1).max(120), slug: z.string().regex(TENANT_SLUG) }),
|
|
137
|
+
handler: async (context) => {
|
|
138
|
+
const user = userOf(context.principal);
|
|
139
|
+
// Its short name is also the path its site is served under, so it can't be one the CMS answers on.
|
|
140
|
+
if (!usableSlug(context.body.slug))
|
|
141
|
+
throw new HttpError(400, "VALIDATION_FAILED", "That short name belongs to the CMS itself. Choose another.");
|
|
142
|
+
// As the server: better-auth makes the creator the tenant's first member, with the creator role.
|
|
143
|
+
const created = await context.auth.server("/organization/create", {
|
|
144
|
+
body: { name: context.body.name, slug: context.body.slug, userId: user.id, keepCurrentActiveOrganization: true, status: "active" },
|
|
145
|
+
});
|
|
146
|
+
const tenant = await findTenant(context, created.id);
|
|
147
|
+
if (!tenant)
|
|
148
|
+
throw new Error("The new tenant wasn't saved.");
|
|
149
|
+
context.auditTarget("tenant", tenant.id, { name: tenant.name, slug: tenant.slug });
|
|
150
|
+
// Its site answers under its short name at once on this server.
|
|
151
|
+
forgetSlugs();
|
|
152
|
+
return publicTenant(tenant);
|
|
153
|
+
},
|
|
154
|
+
}),
|
|
155
|
+
defineRoute({
|
|
156
|
+
method: "GET",
|
|
157
|
+
path: "/tenant",
|
|
158
|
+
access: "authenticated",
|
|
159
|
+
apiKey: true,
|
|
160
|
+
handler: async (context) => {
|
|
161
|
+
const tenant = await findTenant(context, currentTenant(context.principal));
|
|
162
|
+
if (!tenant)
|
|
163
|
+
throw new HttpError(404, "SCOPE_NOT_FOUND", "This tenant doesn't exist.");
|
|
164
|
+
const member = context.principal.kind === "anonymous" ? null : await findMember(context, tenant.id, context.principal.user.id);
|
|
165
|
+
return { ...publicTenant(tenant), roles: member?.roles ?? [] };
|
|
166
|
+
},
|
|
167
|
+
}),
|
|
168
|
+
defineRoute({
|
|
169
|
+
method: "PATCH",
|
|
170
|
+
path: "/tenant",
|
|
171
|
+
access: "permission",
|
|
172
|
+
permission: "ext.multi-tenant:update",
|
|
173
|
+
apiKey: true,
|
|
174
|
+
audit: "multi_tenant.update",
|
|
175
|
+
body: z.object({ name: z.string().trim().min(1).max(120) }),
|
|
176
|
+
handler: async (context) => {
|
|
177
|
+
const tenant = await findTenant(context, currentTenant(context.principal));
|
|
178
|
+
if (!tenant)
|
|
179
|
+
throw new HttpError(404, "SCOPE_NOT_FOUND", "This tenant doesn't exist.");
|
|
180
|
+
await context.system.records.update(ORGANIZATIONS, tenant.recordId, { name: context.body.name });
|
|
181
|
+
context.auditTarget("tenant", tenant.id, { name: context.body.name });
|
|
182
|
+
return { ...publicTenant(tenant), name: context.body.name };
|
|
183
|
+
},
|
|
184
|
+
}),
|
|
185
|
+
defineRoute({
|
|
186
|
+
method: "POST",
|
|
187
|
+
path: "/switch",
|
|
188
|
+
access: "authenticated",
|
|
189
|
+
audit: "multi_tenant.switch",
|
|
190
|
+
body: z.object({ tenant: tenantId.nullable() }),
|
|
191
|
+
handler: (context) => switchTo(context, context.body.tenant),
|
|
192
|
+
}),
|
|
193
|
+
// The dashboard's top-bar switcher (AdminSwitcher): what to offer, and the choice.
|
|
194
|
+
defineRoute({
|
|
195
|
+
method: "GET",
|
|
196
|
+
path: "/switcher",
|
|
197
|
+
access: "authenticated",
|
|
198
|
+
handler: async (context) => {
|
|
199
|
+
const { principal } = context;
|
|
200
|
+
if (principal.kind !== "user")
|
|
201
|
+
return { current: null, options: [] };
|
|
202
|
+
const { tenants } = await reachable(context, principal.user.id);
|
|
203
|
+
const options = tenants
|
|
204
|
+
.filter((tenant) => tenant.status === "active")
|
|
205
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
206
|
+
.map((tenant) => ({ value: tenant.id, label: tenant.name }));
|
|
207
|
+
// Staff who reach every tenant can also work in none, for what isn't kept apart by tenant.
|
|
208
|
+
if (principal.permissions.has(EVERY_TENANT))
|
|
209
|
+
options.unshift({ value: null, label: wordIn((await context.system.users.get(principal.user.id))?.locale, "switcherNone") });
|
|
210
|
+
return { current: principal.scope ?? null, options };
|
|
211
|
+
},
|
|
212
|
+
}),
|
|
213
|
+
defineRoute({
|
|
214
|
+
method: "POST",
|
|
215
|
+
path: "/switcher",
|
|
216
|
+
access: "authenticated",
|
|
217
|
+
audit: "multi_tenant.switch",
|
|
218
|
+
body: z.object({ value: tenantId.nullable() }),
|
|
219
|
+
handler: (context) => switchTo(context, context.body.value),
|
|
220
|
+
}),
|
|
221
|
+
defineRoute({
|
|
222
|
+
method: "GET",
|
|
223
|
+
path: "/domains",
|
|
224
|
+
access: "permission",
|
|
225
|
+
permission: DOMAINS_PERMISSION,
|
|
226
|
+
apiKey: true,
|
|
227
|
+
handler: async (context) => {
|
|
228
|
+
const domains = await domainsOf(context, currentTenant(context.principal));
|
|
229
|
+
return { items: await Promise.all(domains.map((domain) => describeDomain(context, domain))) };
|
|
230
|
+
},
|
|
231
|
+
}),
|
|
232
|
+
defineRoute({
|
|
233
|
+
method: "POST",
|
|
234
|
+
path: "/domains",
|
|
235
|
+
access: "permission",
|
|
236
|
+
permission: DOMAINS_PERMISSION,
|
|
237
|
+
apiKey: true,
|
|
238
|
+
fresh: true,
|
|
239
|
+
audit: "multi_tenant.domain_add",
|
|
240
|
+
rateLimit: { window: 3600, max: 30 },
|
|
241
|
+
body: z.object({ host: z.string().trim().min(1).max(300) }),
|
|
242
|
+
handler: async (context) => {
|
|
243
|
+
const tenant = currentTenant(context.principal);
|
|
244
|
+
const host = normalizeHost(context.body.host, reserved);
|
|
245
|
+
if (!host)
|
|
246
|
+
throw new HttpError(400, "INVALID_DOMAIN", "Use a domain name such as www.example.com, without a path or port.");
|
|
247
|
+
const claims = await claimsOn(context, host);
|
|
248
|
+
// Claims don't block each other until one verifies, so nobody can hold a domain they don't control by naming it first.
|
|
249
|
+
if (claims.some((claim) => claim.tenant === tenant || claim.verifiedAt !== null))
|
|
250
|
+
throw unavailable();
|
|
251
|
+
if ((await domainsOf(context, tenant)).length >= MAX_DOMAINS)
|
|
252
|
+
throw new HttpError(409, "TOO_MANY_DOMAINS", `A tenant can have at most ${MAX_DOMAINS} domains.`);
|
|
253
|
+
const created = await context.system.records.create(DOMAINS, { status: "published", host, organizationId: tenant, primary: false, token: newToken() });
|
|
254
|
+
const domain = await findDomain(context, tenant, Number(created.id));
|
|
255
|
+
if (!domain)
|
|
256
|
+
throw new Error("The new domain wasn't saved.");
|
|
257
|
+
context.auditTarget("tenant_domain", String(domain.id), { tenant, host });
|
|
258
|
+
return describeDomain(context, domain);
|
|
259
|
+
},
|
|
260
|
+
}),
|
|
261
|
+
defineRoute({
|
|
262
|
+
method: "POST",
|
|
263
|
+
path: "/domains/:id/verify",
|
|
264
|
+
access: "permission",
|
|
265
|
+
permission: DOMAINS_PERMISSION,
|
|
266
|
+
apiKey: true,
|
|
267
|
+
audit: "multi_tenant.domain_verify",
|
|
268
|
+
rateLimit: { window: 3600, max: 60 },
|
|
269
|
+
handler: async (context) => {
|
|
270
|
+
const tenant = currentTenant(context.principal);
|
|
271
|
+
const domain = await requireDomain(context, tenant);
|
|
272
|
+
if (domain.verifiedAt !== null)
|
|
273
|
+
return describeDomain(context, domain);
|
|
274
|
+
if ((await claimsOn(context, domain.host)).some((claim) => claim.id !== domain.id && claim.verifiedAt !== null))
|
|
275
|
+
throw unavailable();
|
|
276
|
+
const now = new Date().toISOString();
|
|
277
|
+
const record = await recordName(context);
|
|
278
|
+
context.auditTarget("tenant_domain", String(domain.id), { tenant, host: domain.host });
|
|
279
|
+
if (!(await dnsHasProof(domain, record, options.dnsServers))) {
|
|
280
|
+
await context.system.records.update(DOMAINS, domain.id, { checkedAt: now });
|
|
281
|
+
throw new HttpError(400, "DOMAIN_NOT_VERIFIED", `No TXT record at ${record}.${domain.host} holds ${proof(domain.token)} yet. DNS changes can take a while to appear.`);
|
|
282
|
+
}
|
|
283
|
+
// The first verified domain is where the tenant's site lives until someone chooses another.
|
|
284
|
+
const hasPrimary = (await domainsOf(context, tenant)).some((other) => other.primary && other.verifiedAt !== null);
|
|
285
|
+
await context.system.records.update(DOMAINS, domain.id, { verifiedAt: now, checkedAt: now, primary: !hasPrimary });
|
|
286
|
+
await domainsChanged(context);
|
|
287
|
+
return describeDomain(context, { ...domain, verifiedAt: now, checkedAt: now, primary: !hasPrimary });
|
|
288
|
+
},
|
|
289
|
+
}),
|
|
290
|
+
defineRoute({
|
|
291
|
+
method: "POST",
|
|
292
|
+
path: "/domains/:id/primary",
|
|
293
|
+
access: "permission",
|
|
294
|
+
permission: DOMAINS_PERMISSION,
|
|
295
|
+
apiKey: true,
|
|
296
|
+
fresh: true,
|
|
297
|
+
audit: "multi_tenant.domain_primary",
|
|
298
|
+
handler: async (context) => {
|
|
299
|
+
const tenant = currentTenant(context.principal);
|
|
300
|
+
const domain = await requireDomain(context, tenant);
|
|
301
|
+
if (domain.verifiedAt === null)
|
|
302
|
+
throw new HttpError(409, "DOMAIN_NOT_VERIFIED", "Verify the domain before making it the main one.");
|
|
303
|
+
for (const other of await domainsOf(context, tenant)) {
|
|
304
|
+
if (other.primary !== (other.id === domain.id))
|
|
305
|
+
await context.system.records.update(DOMAINS, other.id, { primary: other.id === domain.id });
|
|
306
|
+
}
|
|
307
|
+
context.auditTarget("tenant_domain", String(domain.id), { tenant, host: domain.host });
|
|
308
|
+
return describeDomain(context, { ...domain, primary: true });
|
|
309
|
+
},
|
|
310
|
+
}),
|
|
311
|
+
defineRoute({
|
|
312
|
+
method: "DELETE",
|
|
313
|
+
path: "/domains/:id",
|
|
314
|
+
access: "permission",
|
|
315
|
+
permission: DOMAINS_PERMISSION,
|
|
316
|
+
apiKey: true,
|
|
317
|
+
fresh: true,
|
|
318
|
+
audit: "multi_tenant.domain_remove",
|
|
319
|
+
handler: async (context) => {
|
|
320
|
+
const tenant = currentTenant(context.principal);
|
|
321
|
+
const domain = await requireDomain(context, tenant);
|
|
322
|
+
await context.system.records.delete(DOMAINS, domain.id);
|
|
323
|
+
if (domain.primary) {
|
|
324
|
+
const next = (await domainsOf(context, tenant)).find((other) => other.verifiedAt !== null);
|
|
325
|
+
if (next)
|
|
326
|
+
await context.system.records.update(DOMAINS, next.id, { primary: true });
|
|
327
|
+
}
|
|
328
|
+
context.auditTarget("tenant_domain", String(domain.id), { tenant, host: domain.host });
|
|
329
|
+
await domainsChanged(context);
|
|
330
|
+
return null;
|
|
331
|
+
},
|
|
332
|
+
}),
|
|
333
|
+
defineRoute({
|
|
334
|
+
method: "GET",
|
|
335
|
+
path: "/roles",
|
|
336
|
+
access: "permission",
|
|
337
|
+
permission: MEMBERS_PERMISSION,
|
|
338
|
+
apiKey: true,
|
|
339
|
+
handler: async (context) => {
|
|
340
|
+
// The tenant roles the caller could give here: every one with the permission for every tenant, else those they hold.
|
|
341
|
+
const tenant = currentTenant(context.principal);
|
|
342
|
+
const scoped = (await context.tools.roles()).filter((role) => role.scope === "scoped");
|
|
343
|
+
if (context.principal.permissions.has(EVERY_TENANT))
|
|
344
|
+
return { items: scoped.map(({ name, label }) => ({ name, label })) };
|
|
345
|
+
const own = await findMember(context, tenant, userOf(context.principal).id);
|
|
346
|
+
return { items: scoped.filter((role) => own?.roles.includes(role.name)).map(({ name, label }) => ({ name, label })) };
|
|
347
|
+
},
|
|
348
|
+
}),
|
|
349
|
+
defineRoute({
|
|
350
|
+
method: "GET",
|
|
351
|
+
path: "/members",
|
|
352
|
+
access: "permission",
|
|
353
|
+
permission: MEMBERS_PERMISSION,
|
|
354
|
+
apiKey: true,
|
|
355
|
+
handler: async (context) => {
|
|
356
|
+
const members = await membersOf(context, currentTenant(context.principal));
|
|
357
|
+
return { items: await Promise.all(members.map((member) => describeMember(context, member))) };
|
|
358
|
+
},
|
|
359
|
+
}),
|
|
360
|
+
defineRoute({
|
|
361
|
+
method: "PATCH",
|
|
362
|
+
path: "/members/:id",
|
|
363
|
+
access: "permission",
|
|
364
|
+
permission: MEMBERS_PERMISSION,
|
|
365
|
+
apiKey: true,
|
|
366
|
+
audit: "multi_tenant.member_update",
|
|
367
|
+
body: z.object({ roles: roleNames }),
|
|
368
|
+
handler: async (context) => {
|
|
369
|
+
const tenant = currentTenant(context.principal);
|
|
370
|
+
const member = await findMemberById(context, tenant, context.params.id);
|
|
371
|
+
if (!member)
|
|
372
|
+
throw new HttpError(404, "NOT_FOUND", "Member not found.");
|
|
373
|
+
await assertCanManage(context, tenant, member);
|
|
374
|
+
const roles = [...new Set(context.body.roles)];
|
|
375
|
+
await assertCanGive(context, tenant, roles);
|
|
376
|
+
await context.system.records.update(MEMBERS, member.recordId, { role: roles.join(",") });
|
|
377
|
+
context.auditTarget("tenant_member", member.id, { tenant, userId: member.userId, roles });
|
|
378
|
+
return describeMember(context, { ...member, roles });
|
|
379
|
+
},
|
|
380
|
+
}),
|
|
381
|
+
defineRoute({
|
|
382
|
+
method: "DELETE",
|
|
383
|
+
path: "/members/:id",
|
|
384
|
+
access: "permission",
|
|
385
|
+
permission: MEMBERS_PERMISSION,
|
|
386
|
+
apiKey: true,
|
|
387
|
+
audit: "multi_tenant.member_remove",
|
|
388
|
+
handler: async (context) => {
|
|
389
|
+
const tenant = currentTenant(context.principal);
|
|
390
|
+
const member = await findMemberById(context, tenant, context.params.id);
|
|
391
|
+
if (!member)
|
|
392
|
+
throw new HttpError(404, "NOT_FOUND", "Member not found.");
|
|
393
|
+
await assertCanManage(context, tenant, member);
|
|
394
|
+
await context.system.records.delete(MEMBERS, member.recordId);
|
|
395
|
+
context.auditTarget("tenant_member", member.id, { tenant, userId: member.userId });
|
|
396
|
+
return null;
|
|
397
|
+
},
|
|
398
|
+
}),
|
|
399
|
+
defineRoute({
|
|
400
|
+
method: "GET",
|
|
401
|
+
path: "/invitations",
|
|
402
|
+
access: "permission",
|
|
403
|
+
permission: MEMBERS_PERMISSION,
|
|
404
|
+
apiKey: true,
|
|
405
|
+
handler: async (context) => {
|
|
406
|
+
const now = Date.now();
|
|
407
|
+
const items = (await invitationsOf(context, currentTenant(context.principal)))
|
|
408
|
+
.filter((invitation) => invitation.expiresAt !== null && Date.parse(invitation.expiresAt) > now)
|
|
409
|
+
.map(({ id, email, roles, expiresAt }) => ({ id, email, roles, expiresAt }));
|
|
410
|
+
return { items };
|
|
411
|
+
},
|
|
412
|
+
}),
|
|
413
|
+
defineRoute({
|
|
414
|
+
method: "POST",
|
|
415
|
+
path: "/invitations",
|
|
416
|
+
access: "permission",
|
|
417
|
+
permission: MEMBERS_PERMISSION,
|
|
418
|
+
apiKey: true,
|
|
419
|
+
audit: "multi_tenant.invite",
|
|
420
|
+
rateLimit: { window: 3600, max: 50 },
|
|
421
|
+
body: z.object({ email: z.email().max(254), roles: roleNames }),
|
|
422
|
+
handler: async (context) => {
|
|
423
|
+
const tenantId = currentTenant(context.principal);
|
|
424
|
+
const tenant = await findTenant(context, tenantId);
|
|
425
|
+
if (!tenant || tenant.status !== "active")
|
|
426
|
+
throw new HttpError(404, "SCOPE_NOT_FOUND", "This tenant doesn't exist.");
|
|
427
|
+
const roles = [...new Set(context.body.roles)];
|
|
428
|
+
await assertCanGive(context, tenantId, roles);
|
|
429
|
+
const email = context.body.email.toLowerCase();
|
|
430
|
+
const invited = await context.system.users.findByEmail(email);
|
|
431
|
+
if (invited && (await findMember(context, tenantId, invited.id)))
|
|
432
|
+
throw new HttpError(409, "ALREADY_MEMBER", "They're already a member of this tenant.");
|
|
433
|
+
// Inviting someone again replaces what they were sent before.
|
|
434
|
+
const earlier = (await invitationsOf(context, tenantId)).filter((invitation) => invitation.email === email);
|
|
435
|
+
await assertMemberRoom(context, tenantId, earlier.length ? 0 : 1);
|
|
436
|
+
for (const invitation of earlier) {
|
|
437
|
+
await context.system.records.update(INVITATIONS, invitation.recordId, { invitationStatus: "canceled" });
|
|
438
|
+
}
|
|
439
|
+
const settings = await context.settings.get();
|
|
440
|
+
const days = typeof settings.invitationDays === "number" ? settings.invitationDays : 7;
|
|
441
|
+
const id = newId();
|
|
442
|
+
const expiresAt = new Date(Date.now() + days * 86_400_000).toISOString();
|
|
443
|
+
await context.system.records.create(INVITATIONS, {
|
|
444
|
+
status: "published",
|
|
445
|
+
authId: id,
|
|
446
|
+
organizationId: tenantId,
|
|
447
|
+
email,
|
|
448
|
+
role: roles.join(","),
|
|
449
|
+
invitationStatus: "pending",
|
|
450
|
+
expiresAt,
|
|
451
|
+
inviterId: userOf(context.principal).id,
|
|
452
|
+
invitationCreatedAt: new Date().toISOString(),
|
|
453
|
+
});
|
|
454
|
+
// In their language when they have an account, otherwise the site's.
|
|
455
|
+
const words = invitationMail(invited?.locale ?? (await context.schema.languages()).defaultLocale, { tenant: tenant.name, inviter: userOf(context.principal).name, days });
|
|
456
|
+
await context.mail.send({
|
|
457
|
+
to: email,
|
|
458
|
+
subject: words.subject.slice(0, 200),
|
|
459
|
+
body: words.body,
|
|
460
|
+
locale: words.locale,
|
|
461
|
+
// The account page, which anyone signed in can open, lists their invitations to accept.
|
|
462
|
+
action: { label: words.action, url: `${options.siteUrl}${adminPath(`/account?invitation=${id}`)}#tenant-invitations` },
|
|
463
|
+
});
|
|
464
|
+
context.auditTarget("tenant_invitation", id, { tenant: tenantId, roles });
|
|
465
|
+
return { id, email, roles, expiresAt };
|
|
466
|
+
},
|
|
467
|
+
}),
|
|
468
|
+
defineRoute({
|
|
469
|
+
method: "DELETE",
|
|
470
|
+
path: "/invitations/:id",
|
|
471
|
+
access: "permission",
|
|
472
|
+
permission: MEMBERS_PERMISSION,
|
|
473
|
+
apiKey: true,
|
|
474
|
+
audit: "multi_tenant.invitation_cancel",
|
|
475
|
+
handler: async (context) => {
|
|
476
|
+
const tenant = currentTenant(context.principal);
|
|
477
|
+
const invitation = await findInvitation(context, tenant, context.params.id);
|
|
478
|
+
if (!invitation || invitation.status !== "pending")
|
|
479
|
+
throw new HttpError(404, "NOT_FOUND", "Invitation not found.");
|
|
480
|
+
await context.system.records.update(INVITATIONS, invitation.recordId, { invitationStatus: "canceled" });
|
|
481
|
+
context.auditTarget("tenant_invitation", invitation.id, { tenant });
|
|
482
|
+
return null;
|
|
483
|
+
},
|
|
484
|
+
}),
|
|
485
|
+
defineRoute({
|
|
486
|
+
method: "GET",
|
|
487
|
+
path: "/invitations/mine",
|
|
488
|
+
access: "authenticated",
|
|
489
|
+
handler: async (context) => {
|
|
490
|
+
// better-auth finds them by the caller's own email, and names each tenant.
|
|
491
|
+
const found = await context.auth.call("/organization/list-user-invitations");
|
|
492
|
+
const now = Date.now();
|
|
493
|
+
const items = found
|
|
494
|
+
.filter((invitation) => invitation.status === "pending" && new Date(invitation.expiresAt).getTime() > now)
|
|
495
|
+
.map((invitation) => ({ id: invitation.id, tenant: invitation.organizationId, tenantName: invitation.organizationName ?? null, roles: invitation.role.split(",").filter(Boolean), expiresAt: new Date(invitation.expiresAt).toISOString() }));
|
|
496
|
+
return { items };
|
|
497
|
+
},
|
|
498
|
+
}),
|
|
499
|
+
defineRoute({
|
|
500
|
+
method: "POST",
|
|
501
|
+
path: "/invitations/:id/accept",
|
|
502
|
+
access: "authenticated",
|
|
503
|
+
audit: "multi_tenant.invitation_accept",
|
|
504
|
+
handler: async (context) => {
|
|
505
|
+
if (!RECORD_KEY.test(context.params.id))
|
|
506
|
+
throw new HttpError(404, "NOT_FOUND", "Invitation not found.");
|
|
507
|
+
// The invitation already holds its place under the limit on members, so this only stops a tenant whose limit was lowered since.
|
|
508
|
+
const invitation = await invitationById(context, context.params.id);
|
|
509
|
+
if (invitation)
|
|
510
|
+
await assertMemberRoom(context, invitation.tenant, 0);
|
|
511
|
+
// As the invitee: better-auth checks the invitation is theirs, still pending and unexpired, and that their email is verified.
|
|
512
|
+
const accepted = await context.auth.call("/organization/accept-invitation", { body: { invitationId: context.params.id } });
|
|
513
|
+
context.auditTarget("tenant_invitation", context.params.id, { tenant: accepted.member.organizationId });
|
|
514
|
+
return { tenant: accepted.member.organizationId, member: accepted.member.id };
|
|
515
|
+
},
|
|
516
|
+
}),
|
|
517
|
+
defineRoute({
|
|
518
|
+
method: "POST",
|
|
519
|
+
path: "/invitations/:id/reject",
|
|
520
|
+
access: "authenticated",
|
|
521
|
+
audit: "multi_tenant.invitation_reject",
|
|
522
|
+
handler: async (context) => {
|
|
523
|
+
if (!RECORD_KEY.test(context.params.id))
|
|
524
|
+
throw new HttpError(404, "NOT_FOUND", "Invitation not found.");
|
|
525
|
+
await context.auth.call("/organization/reject-invitation", { body: { invitationId: context.params.id } });
|
|
526
|
+
context.auditTarget("tenant_invitation", context.params.id);
|
|
527
|
+
return null;
|
|
528
|
+
},
|
|
529
|
+
}),
|
|
530
|
+
// A tenant's life, for instance staff: its plan and limits, suspending, resuming, export, import and purge.
|
|
531
|
+
// Each names the tenant in the address, since a suspended one can't be the current tenant.
|
|
532
|
+
defineRoute({
|
|
533
|
+
method: "GET",
|
|
534
|
+
path: "/tenants/:id/plan",
|
|
535
|
+
access: "permission",
|
|
536
|
+
permission: "ext.multi-tenant:read",
|
|
537
|
+
apiKey: true,
|
|
538
|
+
handler: async (context) => {
|
|
539
|
+
const tenant = await tenantFromPath(context);
|
|
540
|
+
const [plan, usage, members] = await Promise.all([planOf(context, tenant.id), context.scope.data.usage(tenant.id), membersOf(context, tenant.id)]);
|
|
541
|
+
const { records, storageBytes, members: memberLimit, requestsPerMinute, purgeAt } = plan;
|
|
542
|
+
return { tenant: publicTenant(tenant), limits: { records, storageBytes, members: memberLimit, requestsPerMinute }, usage: { ...usage, members: members.length }, purgeAt };
|
|
543
|
+
},
|
|
544
|
+
}),
|
|
545
|
+
defineRoute({
|
|
546
|
+
method: "PUT",
|
|
547
|
+
path: "/tenants/:id/limits",
|
|
548
|
+
access: "permission",
|
|
549
|
+
permission: "ext.multi-tenant:update",
|
|
550
|
+
fresh: true,
|
|
551
|
+
audit: "multi_tenant.limits",
|
|
552
|
+
body: z.object({ records: limitValue, storageBytes: limitValue, members: limitValue, requestsPerMinute: limitValue }),
|
|
553
|
+
handler: async (context) => {
|
|
554
|
+
const tenant = await tenantFromPath(context);
|
|
555
|
+
await setLimits(context, tenant.id, context.body);
|
|
556
|
+
context.auditTarget("tenant", tenant.id, { ...context.body });
|
|
557
|
+
return context.body;
|
|
558
|
+
},
|
|
559
|
+
}),
|
|
560
|
+
defineRoute({
|
|
561
|
+
method: "POST",
|
|
562
|
+
path: "/tenants/:id/suspend",
|
|
563
|
+
access: "permission",
|
|
564
|
+
permission: DELETE_PERMISSION,
|
|
565
|
+
apiKey: true,
|
|
566
|
+
audit: "multi_tenant.suspend",
|
|
567
|
+
handler: async (context) => {
|
|
568
|
+
const tenant = await tenantFromPath(context);
|
|
569
|
+
if (tenant.status !== "suspended")
|
|
570
|
+
await suspendTenant(context, tenant);
|
|
571
|
+
context.auditTarget("tenant", tenant.id);
|
|
572
|
+
return { ...publicTenant(tenant), status: "suspended" };
|
|
573
|
+
},
|
|
574
|
+
}),
|
|
575
|
+
defineRoute({
|
|
576
|
+
method: "POST",
|
|
577
|
+
path: "/tenants/:id/resume",
|
|
578
|
+
access: "permission",
|
|
579
|
+
permission: DELETE_PERMISSION,
|
|
580
|
+
apiKey: true,
|
|
581
|
+
audit: "multi_tenant.resume",
|
|
582
|
+
handler: async (context) => {
|
|
583
|
+
const tenant = await tenantFromPath(context);
|
|
584
|
+
await resumeTenant(context, tenant);
|
|
585
|
+
context.auditTarget("tenant", tenant.id);
|
|
586
|
+
return { ...publicTenant(tenant), status: "active" };
|
|
587
|
+
},
|
|
588
|
+
}),
|
|
589
|
+
defineRoute({
|
|
590
|
+
method: "POST",
|
|
591
|
+
path: "/tenants/:id/purge",
|
|
592
|
+
access: "permission",
|
|
593
|
+
permission: DELETE_PERMISSION,
|
|
594
|
+
fresh: true,
|
|
595
|
+
audit: "multi_tenant.purge_request",
|
|
596
|
+
// The tenant's short name, typed again, so a purge is never one click.
|
|
597
|
+
body: z.object({ confirm: z.string().max(64) }),
|
|
598
|
+
handler: async (context) => {
|
|
599
|
+
const tenant = await tenantFromPath(context);
|
|
600
|
+
if (tenant.status !== "suspended")
|
|
601
|
+
throw new HttpError(409, "NOT_SUSPENDED", "Suspend the tenant first. A purge only removes a suspended tenant.");
|
|
602
|
+
if (context.body.confirm !== tenant.slug)
|
|
603
|
+
throw new HttpError(400, "CONFIRMATION_MISMATCH", "Type the tenant's short name to confirm.");
|
|
604
|
+
const value = (await context.settings.get()).purgeDays;
|
|
605
|
+
const days = typeof value === "number" && value >= 1 ? value : DEFAULT_PURGE_DAYS;
|
|
606
|
+
const purgeAt = await schedulePurge(context, tenant.id, days, userOf(context.principal).id);
|
|
607
|
+
context.auditTarget("tenant", tenant.id, { purgeAt });
|
|
608
|
+
return { purgeAt };
|
|
609
|
+
},
|
|
610
|
+
}),
|
|
611
|
+
defineRoute({
|
|
612
|
+
method: "DELETE",
|
|
613
|
+
path: "/tenants/:id/purge",
|
|
614
|
+
access: "permission",
|
|
615
|
+
permission: DELETE_PERMISSION,
|
|
616
|
+
audit: "multi_tenant.purge_cancel",
|
|
617
|
+
handler: async (context) => {
|
|
618
|
+
const tenant = await tenantFromPath(context);
|
|
619
|
+
await cancelPurge(context, tenant.id);
|
|
620
|
+
context.auditTarget("tenant", tenant.id);
|
|
621
|
+
return null;
|
|
622
|
+
},
|
|
623
|
+
}),
|
|
624
|
+
defineRoute({
|
|
625
|
+
method: "GET",
|
|
626
|
+
path: "/tenants/:id/export",
|
|
627
|
+
access: "permission",
|
|
628
|
+
permission: DELETE_PERMISSION,
|
|
629
|
+
apiKey: true,
|
|
630
|
+
audit: "multi_tenant.export",
|
|
631
|
+
rateLimit: { window: 3600, max: 10 },
|
|
632
|
+
handler: async (context) => {
|
|
633
|
+
const tenant = await tenantFromPath(context);
|
|
634
|
+
const archive = await context.scope.data.export(tenant.id);
|
|
635
|
+
context.auditTarget("tenant", tenant.id);
|
|
636
|
+
const { createReadStream, statSync } = await import("node:fs");
|
|
637
|
+
const size = statSync(archive.path).size;
|
|
638
|
+
const stream = createReadStream(archive.path);
|
|
639
|
+
stream.once("close", () => void archive.cleanup());
|
|
640
|
+
return new Response(Readable.toWeb(stream), {
|
|
641
|
+
headers: {
|
|
642
|
+
"content-type": "application/gzip",
|
|
643
|
+
"content-length": String(size),
|
|
644
|
+
"content-disposition": `attachment; filename="${archive.name}"`,
|
|
645
|
+
"cache-control": "no-store",
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
},
|
|
649
|
+
}),
|
|
650
|
+
defineRoute({
|
|
651
|
+
method: "POST",
|
|
652
|
+
path: "/tenants/:id/import",
|
|
653
|
+
access: "permission",
|
|
654
|
+
permission: "ext.multi-tenant:create",
|
|
655
|
+
apiKey: true,
|
|
656
|
+
audit: "multi_tenant.import",
|
|
657
|
+
rateLimit: { window: 3600, max: 10 },
|
|
658
|
+
handler: async (context) => {
|
|
659
|
+
const tenant = await tenantFromPath(context);
|
|
660
|
+
if (!context.request.body)
|
|
661
|
+
throw new HttpError(400, "VALIDATION_FAILED", "Send the archive as the request's body.");
|
|
662
|
+
const directory = await mkdtemp(path.join(tmpdir(), "cms-tenant-import-"));
|
|
663
|
+
try {
|
|
664
|
+
const file = path.join(directory, "archive.tar.gz");
|
|
665
|
+
let received = 0;
|
|
666
|
+
const cap = new Transform({
|
|
667
|
+
transform(chunk, _encoding, done) {
|
|
668
|
+
received += chunk.length;
|
|
669
|
+
done(received > MAX_IMPORT_BYTES ? new HttpError(413, "PAYLOAD_TOO_LARGE", "The archive is too large.") : null, chunk);
|
|
670
|
+
},
|
|
671
|
+
});
|
|
672
|
+
await pipeline(Readable.fromWeb(context.request.body), cap, createWriteStream(file));
|
|
673
|
+
const placed = await context.scope.data.import(tenant.id, file);
|
|
674
|
+
context.auditTarget("tenant", tenant.id, placed);
|
|
675
|
+
return placed;
|
|
676
|
+
}
|
|
677
|
+
finally {
|
|
678
|
+
await rm(directory, { recursive: true, force: true });
|
|
679
|
+
}
|
|
680
|
+
},
|
|
681
|
+
}),
|
|
682
|
+
];
|
|
683
|
+
}
|
|
684
|
+
export { DOMAINS_PERMISSION, EVERY_TENANT, MEMBERS_PERMISSION, PLUGIN };
|