@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/index.js ADDED
@@ -0,0 +1,193 @@
1
+ import { z } from "zod";
2
+ import { organization } from "better-auth/plugins/organization";
3
+ import { defaultStatements } from "better-auth/plugins/organization/access";
4
+ import { definePlugin } from "tansy/plugin";
5
+ import { EVERY_TENANT, MEMBERS_PERMISSION, tenantRoutes } from "./routes";
6
+ import { tenantCommands } from "./commands";
7
+ import { tenantChecks } from "./doctor";
8
+ import { tenantTools } from "./tools";
9
+ import { messages } from "./messages";
10
+ import { DEFAULT_RECORD, DOMAINS, domainsSchema, originFor, primaryHost, RECORD_NAME, tenantForHost, verifiedHosts } from "./domains";
11
+ import { DEFAULT_PURGE_DAYS, expireInvitations, PLANS, plansSchema, recheckDomains, runDuePurges, scopeLimitsOf } from "./lifecycle";
12
+ import { basePathOf, tenantForPath } from "./paths";
13
+ import { activeTenant, ensureDefaultTenant, findMember, findTenant, listTenants, membershipsOf, PLUGIN, SYSTEM_COLLECTIONS, TENANT_HEADER, TENANT_ID } from "./tenants";
14
+ export { DEFAULT_TENANT, TENANT_HEADER } from "./tenants";
15
+ export const TENANT_ADMIN = `${PLUGIN}-admin`;
16
+ export const TENANT_EDITOR = `${PLUGIN}-editor`;
17
+ export const TENANT_STAFF = `${PLUGIN}-staff`;
18
+ /** better-auth's organization plugin, as this plugin sets it up. Its own role checks use the CMS's roles. */
19
+ function organizations(access) {
20
+ const control = access?.accessControl({
21
+ statements: defaultStatements,
22
+ roles: "scoped",
23
+ // A tenant role that manages members can do so in better-auth's terms too. Nothing else.
24
+ grant: (permissions) => (permissions.has(MEMBERS_PERMISSION) ? { member: ["create", "update", "delete"], invitation: ["create", "cancel"] } : {}),
25
+ });
26
+ return organization({
27
+ ...(control ? { ac: control.ac, roles: control.roles } : {}),
28
+ creatorRole: TENANT_ADMIN,
29
+ // Every endpoint is closed to HTTP. Tenants are made by this plugin's routes, after their checks.
30
+ allowUserToCreateOrganization: false,
31
+ disableOrganizationDeletion: true,
32
+ requireEmailVerificationOnInvitation: true,
33
+ schema: {
34
+ organization: {
35
+ additionalFields: {
36
+ // "suspended" closes the tenant: no request resolves to it. Records stay.
37
+ status: { type: "string", required: false, defaultValue: "active", input: true },
38
+ },
39
+ },
40
+ },
41
+ });
42
+ }
43
+ /** Every path the organization plugin serves, read from the plugin itself, so an upgrade that adds one closes it too. */
44
+ const ORGANIZATION_PATHS = Object.values(organizations().endpoints)
45
+ .map((endpoint) => endpoint.path)
46
+ .filter((path) => typeof path === "string");
47
+ const optionsSchema = z.object({
48
+ siteUrl: z.url({ protocol: /^https?$/ }),
49
+ scopeNewCollections: z.boolean(),
50
+ dnsServers: z.array(z.string().min(1).max(100)).max(5).optional(),
51
+ });
52
+ /**
53
+ * Many sites, or customers, in one instance: each tenant has its own records in every
54
+ * collection marked scoped, its own members and their roles. Tenants, members and
55
+ * invitations are better-auth's organization plugin. Core keeps every tenant's records apart,
56
+ * below roles and rules (SECURITY_MODEL.md, "Row scopes"), so a request for one tenant never
57
+ * reads or writes another's. See internal/MULTI_TENANT_PLAN.md.
58
+ */
59
+ export function multiTenant(options) {
60
+ const parsed = optionsSchema.parse({ siteUrl: options.siteUrl.replace(/\/+$/, ""), scopeNewCollections: options.scopeNewCollections ?? true, ...(options.dnsServers?.length ? { dnsServers: options.dnsServers } : {}) });
61
+ return definePlugin({
62
+ name: PLUGIN,
63
+ version: "0.1.1",
64
+ apiVersion: 1,
65
+ requires: { cms: "^0.1.1" },
66
+ options: { schema: optionsSchema, value: parsed },
67
+ admin: { server: "@tansy/multi-tenant/admin" },
68
+ messages,
69
+ permissions: { "ext.multi-tenant": ["create", "read", "update", "delete", "members", "domains", "all"] },
70
+ scopedPermissions: [MEMBERS_PERMISSION],
71
+ systemCollections: [...SYSTEM_COLLECTIONS, DOMAINS, PLANS],
72
+ settings: {
73
+ permission: "ext.multi-tenant:update",
74
+ fields: [
75
+ { type: "number", name: "invitationDays", label: "Invitations last", description: "Days before an invitation to a tenant expires.", default: 7, min: 1, max: 60, integer: true },
76
+ { type: "text", name: "verificationRecord", label: "Verification record", description: "The name a tenant's TXT record goes under, before their domain, to prove they control it.", default: DEFAULT_RECORD, maxLength: 63 },
77
+ { type: "number", name: "purgeDays", label: "Days before a purge", description: "How long a suspended tenant waits, once its removal is asked for, before everything it has is deleted. It can be resumed until then.", default: DEFAULT_PURGE_DAYS, min: 1, max: 90, integer: true },
78
+ ],
79
+ },
80
+ auth: {
81
+ plugins: (_settings, _context, access) => [organizations(access)],
82
+ serverOnlyPaths: ORGANIZATION_PATHS,
83
+ // Members sign in on their tenant's own domain, once it's verified.
84
+ trustedOrigins: async (context) => [...(await verifiedHosts(context)).keys()].map((host) => originFor(host, parsed.siteUrl)),
85
+ },
86
+ scope: {
87
+ label: "Tenant",
88
+ everyValue: EVERY_TENANT,
89
+ scopeNewCollections: parsed.scopeNewCollections,
90
+ resolve: async ({ host, headers, path, principal }, context) => {
91
+ // A verified domain decides for everyone: a tenant's site is that tenant's, whoever asks.
92
+ const byHost = await tenantForHost(context, host);
93
+ if (byHost)
94
+ return byHost;
95
+ // No tenant has verified this host, so it is the instance's own address, where a first
96
+ // segment naming a tenant serves that tenant's site: /acme/blog/hello. Read below the
97
+ // host, and never on a tenant's domain, so a path can't move a visitor between tenants.
98
+ // The CMS's own addresses are left out, so a tenant can't be reached under /api or /dashboard.
99
+ const byPath = await tenantForPath(context, path);
100
+ if (byPath)
101
+ return byPath;
102
+ // Visitors get a tenant from its domain or its prefix only. A header is never enough for them.
103
+ if (principal.kind === "anonymous")
104
+ return null;
105
+ const named = headers.get(TENANT_HEADER)?.trim();
106
+ if (named)
107
+ return named;
108
+ if (principal.kind !== "user")
109
+ return null;
110
+ // The session's choice may be stale, as when they've left the tenant since: then it's ignored, not refused.
111
+ const active = await activeTenant(context, principal.session.id);
112
+ if (active && (principal.permissions.has(EVERY_TENANT) || (await findMember(context, active, principal.user.id))))
113
+ return active;
114
+ // With no choice that applies, a member works in the first tenant they joined. Staff who reach every tenant work in none until they choose.
115
+ if (principal.permissions.has(EVERY_TENANT))
116
+ return null;
117
+ const [first] = (await membershipsOf(context, principal.user.id)).sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""));
118
+ return first?.tenant ?? null;
119
+ },
120
+ exists: async (value, context) => (await findTenant(context, value))?.status === "active",
121
+ rolesFor: async (principal, value, context) => (await findMember(context, value, principal.user.id))?.roles ?? [],
122
+ initial: (context) => ensureDefaultTenant(context),
123
+ values: async (context) => (await listTenants(context)).filter((tenant) => tenant.status === "active").map((tenant) => tenant.id),
124
+ // Without a domain of its own, a tenant's site is served under its short name on the instance's address.
125
+ basePath: (value, context) => basePathOf(context, value),
126
+ // Links in a tenant's emails and feeds go to its own domain, once it has a verified one.
127
+ siteUrl: async (value, context) => {
128
+ const host = await primaryHost(context, value);
129
+ return host ? originFor(host, parsed.siteUrl) : null;
130
+ },
131
+ // A tenant's plan: core enforces records, bytes of files and requests a minute.
132
+ limits: (value, context) => scopeLimitsOf(context, value),
133
+ },
134
+ migrations: [{
135
+ id: "001-roles",
136
+ up: async ({ roles }) => {
137
+ await roles.ensure({
138
+ name: TENANT_ADMIN,
139
+ label: "Tenant admin",
140
+ description: "Runs one tenant: its records, redirects, site name and look, and its members.",
141
+ scope: "scoped",
142
+ permissions: ["dashboard:access", "collection:read", "file:create", "record:list", "record:read", "record:create", "record:update", "record:delete", "record:publish", "redirect:read", "redirect:manage", "setting:site", MEMBERS_PERMISSION],
143
+ });
144
+ await roles.ensure({
145
+ name: TENANT_EDITOR,
146
+ label: "Tenant editor",
147
+ description: "Writes one tenant's records.",
148
+ scope: "scoped",
149
+ permissions: ["dashboard:access", "collection:read", "file:create", "record:list", "record:read", "record:create", "record:update"],
150
+ });
151
+ await roles.ensure({
152
+ name: TENANT_STAFF,
153
+ label: "Tenant staff",
154
+ description: "Sees every tenant and works in any of them with their other roles. Each switch is audited.",
155
+ permissions: ["dashboard:access", EVERY_TENANT, "ext.multi-tenant:read"],
156
+ });
157
+ },
158
+ }, {
159
+ id: "002-domains",
160
+ up: async ({ schema }) => {
161
+ if (await schema.describe(DOMAINS))
162
+ throw new Error(`A collection called "${DOMAINS}" already exists, and the multi-tenant plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
163
+ await schema.apply(domainsSchema());
164
+ },
165
+ }, {
166
+ id: "003-lifecycle",
167
+ up: async ({ schema }) => {
168
+ if (await schema.describe(PLANS))
169
+ throw new Error(`A collection called "${PLANS}" already exists, and the multi-tenant plugin didn't create it. Rename it under Dashboard → Collections, then start again.`);
170
+ await schema.apply(plansSchema());
171
+ // When a verified domain's proof went missing, so it stops routing only after a grace period.
172
+ await schema.addFields(DOMAINS, [{ name: "failingSince", type: "datetime", config: {} }]);
173
+ },
174
+ }],
175
+ jobs: [
176
+ { name: "multi-tenant.purge", cron: "11 * * * *", handler: (context) => runDuePurges(context) },
177
+ { name: "multi-tenant.invitations", cron: "29 * * * *", handler: (context) => expireInvitations(context) },
178
+ {
179
+ name: "multi-tenant.domains",
180
+ cron: "47 4 * * *",
181
+ handler: async (context) => {
182
+ const value = (await context.settings.get()).verificationRecord;
183
+ await recheckDomains(context, typeof value === "string" && RECORD_NAME.test(value) ? value : DEFAULT_RECORD, parsed.dnsServers);
184
+ },
185
+ },
186
+ ],
187
+ doctor: () => tenantChecks(parsed),
188
+ routes: tenantRoutes(parsed),
189
+ tools: tenantTools(),
190
+ commands: tenantCommands(),
191
+ });
192
+ }
193
+ export { TENANT_ID };
package/lifecycle.d.ts ADDED
@@ -0,0 +1,122 @@
1
+ import type { ExtensionContext, ScopeLimits } from "tansy/plugin";
2
+ import { dnsHasProof } from "./domains";
3
+ import { type Tenant } from "./tenants";
4
+ /**
5
+ * A tenant's life after it's made (Phase 24): its limits, closing it (suspend) and opening it
6
+ * again, and removing it for good, which waits some days after it's asked for. Kept in a
7
+ * system-owned collection beside the organization, one record per tenant, since better-auth's
8
+ * organization has no place for them.
9
+ */
10
+ export declare const PLANS = "multi-tenant-plans";
11
+ /** Days between asking for a purge and it happening, unless the settings say otherwise. */
12
+ export declare const DEFAULT_PURGE_DAYS = 7;
13
+ export interface TenantLimits {
14
+ records: number | null;
15
+ storageBytes: number | null;
16
+ members: number | null;
17
+ requestsPerMinute: number | null;
18
+ }
19
+ export interface Plan extends TenantLimits {
20
+ id: number | null;
21
+ tenant: string;
22
+ /** When the purge happens. Null when none was asked for. */
23
+ purgeAt: string | null;
24
+ purgeRequestedBy: string | null;
25
+ }
26
+ export declare const NO_LIMITS: TenantLimits;
27
+ export declare const plansSchema: () => {
28
+ version: number;
29
+ collections: {
30
+ slug: string;
31
+ name: string;
32
+ description: string;
33
+ urlPattern: null;
34
+ rules: {
35
+ listRule: null;
36
+ viewRule: null;
37
+ createRule: null;
38
+ updateRule: null;
39
+ deleteRule: null;
40
+ };
41
+ fields: ({
42
+ name: string;
43
+ type: string;
44
+ config: {
45
+ required: boolean;
46
+ maxLength: number;
47
+ unique: boolean;
48
+ format?: undefined;
49
+ min?: undefined;
50
+ };
51
+ } | {
52
+ name: string;
53
+ type: string;
54
+ config: {
55
+ format: string;
56
+ min: number;
57
+ required?: undefined;
58
+ maxLength?: undefined;
59
+ unique?: undefined;
60
+ };
61
+ } | {
62
+ name: string;
63
+ type: string;
64
+ config: {
65
+ required?: undefined;
66
+ maxLength?: undefined;
67
+ unique?: undefined;
68
+ format?: undefined;
69
+ min?: undefined;
70
+ };
71
+ } | {
72
+ name: string;
73
+ type: string;
74
+ config: {
75
+ maxLength: number;
76
+ required?: undefined;
77
+ unique?: undefined;
78
+ format?: undefined;
79
+ min?: undefined;
80
+ };
81
+ })[];
82
+ }[];
83
+ };
84
+ /** A tenant's plan. One that was never set has no limits and no purge. */
85
+ export declare function planOf(context: ExtensionContext, tenant: string): Promise<Plan>;
86
+ export declare const setLimits: (context: ExtensionContext, tenant: string, limits: TenantLimits) => Promise<Plan>;
87
+ /** What core enforces (records, bytes, requests). Members are counted by this plugin's own routes. */
88
+ export declare function scopeLimitsOf(context: ExtensionContext, tenant: string): Promise<ScopeLimits | null>;
89
+ /** Closes a tenant: nothing resolves to it, so no reads, no writes and no sign-in to it. Its data stays. */
90
+ export declare const suspendTenant: (context: ExtensionContext, tenant: Tenant & {
91
+ recordId: number;
92
+ }) => Promise<void>;
93
+ /** Opens a suspended tenant again, and calls off a purge it was waiting for. */
94
+ export declare function resumeTenant(context: ExtensionContext, tenant: Tenant & {
95
+ recordId: number;
96
+ }): Promise<void>;
97
+ /** Asks for a suspended tenant to be removed for good after `days`. */
98
+ export declare function schedulePurge(context: ExtensionContext, tenant: string, days: number, by: string): Promise<string>;
99
+ export declare const cancelPurge: (context: ExtensionContext, tenant: string) => Promise<Plan>;
100
+ /**
101
+ * Removes a tenant and everything it had: core removes its rows and files, then this plugin
102
+ * its members, invitations, domains, plan and the organization itself. Sessions that had it
103
+ * as their choice forget it.
104
+ */
105
+ export declare function purgeTenant(context: ExtensionContext, tenant: string): Promise<{
106
+ records: number;
107
+ files: number;
108
+ }>;
109
+ /** The job: purges every suspended tenant whose waiting period is over. A tenant resumed meanwhile has no date any more. */
110
+ export declare function runDuePurges(context: ExtensionContext, now?: Date): Promise<void>;
111
+ /**
112
+ * The job: checks each verified domain's proof is still in DNS. One whose proof has been gone
113
+ * for three days stops routing, so a domain that changed hands can't keep serving a tenant.
114
+ */
115
+ export declare function recheckDomains(context: ExtensionContext, record: string, servers: string[] | undefined, now?: Date, hasProof?: typeof dnsHasProof): Promise<void>;
116
+ /** The job: invitations past their date are marked expired, so lists and limits stop counting them. */
117
+ export declare function expireInvitations(context: ExtensionContext, now?: Date): Promise<void>;
118
+ /** Every tenant's status, for the dashboard's danger zone and limits. */
119
+ export declare function plansFor(context: ExtensionContext, tenants?: Tenant[]): Promise<{
120
+ tenant: Tenant;
121
+ plan: Plan;
122
+ }[]>;
package/lifecycle.js ADDED
@@ -0,0 +1,211 @@
1
+ import { DOMAINS, dnsHasProof, forgetHosts } from "./domains";
2
+ import { forgetSlugs } from "./paths";
3
+ import { findTenant, INVITATIONS, listTenants, MEMBERS, ORGANIZATIONS, PLUGIN, SESSIONS, TENANT_ID } from "./tenants";
4
+ /**
5
+ * A tenant's life after it's made (Phase 24): its limits, closing it (suspend) and opening it
6
+ * again, and removing it for good, which waits some days after it's asked for. Kept in a
7
+ * system-owned collection beside the organization, one record per tenant, since better-auth's
8
+ * organization has no place for them.
9
+ */
10
+ export const PLANS = `${PLUGIN}-plans`;
11
+ /** Days between asking for a purge and it happening, unless the settings say otherwise. */
12
+ export const DEFAULT_PURGE_DAYS = 7;
13
+ /** A verified domain whose proof is gone this long stops routing. Short DNS outages don't. */
14
+ const DOMAIN_GRACE_MS = 3 * 86_400_000;
15
+ export const NO_LIMITS = { records: null, storageBytes: null, members: null, requestsPerMinute: null };
16
+ export const plansSchema = () => ({
17
+ version: 1,
18
+ collections: [{
19
+ slug: PLANS,
20
+ name: "Tenant plans",
21
+ description: "Each tenant's limits, and when a tenant asked to be removed will be. Only the multi-tenant plugin writes these.",
22
+ urlPattern: null,
23
+ rules: { listRule: null, viewRule: null, createRule: null, updateRule: null, deleteRule: null },
24
+ fields: [
25
+ { name: "organizationId", type: "text", config: { required: true, maxLength: 64, unique: true } },
26
+ { name: "records", type: "number", config: { format: "integer", min: 0 } },
27
+ { name: "storageBytes", type: "number", config: { format: "integer", min: 0 } },
28
+ { name: "members", type: "number", config: { format: "integer", min: 0 } },
29
+ { name: "requestsPerMinute", type: "number", config: { format: "integer", min: 0 } },
30
+ { name: "purgeAt", type: "datetime", config: {} },
31
+ { name: "purgeRequestedBy", type: "text", config: { maxLength: 64 } },
32
+ ],
33
+ }],
34
+ });
35
+ const str = (value) => (typeof value === "string" ? value : "");
36
+ const limit = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null);
37
+ const quotedTenant = (tenant) => {
38
+ if (!TENANT_ID.test(tenant))
39
+ throw new Error(`Not a tenant id: ${JSON.stringify(tenant).slice(0, 80)}`);
40
+ return `"${tenant}"`;
41
+ };
42
+ const toPlan = (tenant, row) => ({
43
+ id: row ? Number(row.id) : null,
44
+ tenant,
45
+ records: limit(row?.records),
46
+ storageBytes: limit(row?.storageBytes),
47
+ members: limit(row?.members),
48
+ requestsPerMinute: limit(row?.requestsPerMinute),
49
+ purgeAt: str(row?.purgeAt) || null,
50
+ purgeRequestedBy: str(row?.purgeRequestedBy) || null,
51
+ });
52
+ /** Routes can trust the new set of origins at once. Jobs can't, and leave it to core's next read, within half a minute. */
53
+ const refreshOrigins = (context) => context.auth?.refreshTrustedOrigins();
54
+ async function all(records, filter) {
55
+ const items = [];
56
+ for (let page = 1;; page += 1) {
57
+ const result = await records.list(PLANS, { filter, perPage: 200, page, sort: "id" });
58
+ items.push(...result.items);
59
+ if (page >= result.totalPages)
60
+ return items;
61
+ }
62
+ }
63
+ /** A tenant's plan. One that was never set has no limits and no purge. */
64
+ export async function planOf(context, tenant) {
65
+ const [row] = await all(context.system.records, `organizationId = ${quotedTenant(tenant)}`);
66
+ return toPlan(tenant, row ?? null);
67
+ }
68
+ async function savePlan(context, tenant, patch) {
69
+ const current = await planOf(context, tenant);
70
+ if (current.id === null)
71
+ await context.system.records.create(PLANS, { status: "published", organizationId: tenant, ...patch });
72
+ else
73
+ await context.system.records.update(PLANS, current.id, patch);
74
+ await context.scope.forgetLimits(tenant);
75
+ return { ...current, ...patch };
76
+ }
77
+ export const setLimits = (context, tenant, limits) => savePlan(context, tenant, limits);
78
+ /** What core enforces (records, bytes, requests). Members are counted by this plugin's own routes. */
79
+ export async function scopeLimitsOf(context, tenant) {
80
+ const plan = await planOf(context, tenant);
81
+ return { records: plan.records, storageBytes: plan.storageBytes, requestsPerMinute: plan.requestsPerMinute };
82
+ }
83
+ async function setStatus(context, tenant, status) {
84
+ await context.system.records.update(ORGANIZATIONS, tenant.recordId, { organizationStatus: status });
85
+ // Its domains, and its path prefix, stop (or start) routing to it at once on this server.
86
+ forgetHosts();
87
+ forgetSlugs();
88
+ }
89
+ /** Closes a tenant: nothing resolves to it, so no reads, no writes and no sign-in to it. Its data stays. */
90
+ export const suspendTenant = (context, tenant) => setStatus(context, tenant, "suspended");
91
+ /** Opens a suspended tenant again, and calls off a purge it was waiting for. */
92
+ export async function resumeTenant(context, tenant) {
93
+ await setStatus(context, tenant, "active");
94
+ const plan = await planOf(context, tenant.id);
95
+ if (plan.purgeAt)
96
+ await savePlan(context, tenant.id, { purgeAt: null, purgeRequestedBy: null });
97
+ }
98
+ /** Asks for a suspended tenant to be removed for good after `days`. */
99
+ export async function schedulePurge(context, tenant, days, by) {
100
+ const purgeAt = new Date(Date.now() + days * 86_400_000).toISOString();
101
+ await savePlan(context, tenant, { purgeAt, purgeRequestedBy: by });
102
+ return purgeAt;
103
+ }
104
+ export const cancelPurge = (context, tenant) => savePlan(context, tenant, { purgeAt: null, purgeRequestedBy: null });
105
+ async function deleteWhere(context, slug, filter) {
106
+ for (;;) {
107
+ const { items } = await context.system.records.list(slug, { filter, perPage: 200, page: 1, sort: "id" });
108
+ if (!items.length)
109
+ return;
110
+ for (const item of items)
111
+ await context.system.records.delete(slug, Number(item.id));
112
+ }
113
+ }
114
+ /**
115
+ * Removes a tenant and everything it had: core removes its rows and files, then this plugin
116
+ * its members, invitations, domains, plan and the organization itself. Sessions that had it
117
+ * as their choice forget it.
118
+ */
119
+ export async function purgeTenant(context, tenant) {
120
+ const removed = await context.scope.data.purge(tenant);
121
+ const quoted = quotedTenant(tenant);
122
+ await deleteWhere(context, MEMBERS, `organizationId = ${quoted}`);
123
+ await deleteWhere(context, INVITATIONS, `organizationId = ${quoted}`);
124
+ await deleteWhere(context, DOMAINS, `organizationId = ${quoted}`);
125
+ for (;;) {
126
+ const { items } = await context.system.records.list(SESSIONS, { filter: `activeOrganizationId = ${quoted}`, perPage: 200, page: 1, sort: "id" });
127
+ if (!items.length)
128
+ break;
129
+ for (const item of items)
130
+ await context.system.records.update(SESSIONS, Number(item.id), { activeOrganizationId: null });
131
+ }
132
+ await deleteWhere(context, PLANS, `organizationId = ${quoted}`);
133
+ await deleteWhere(context, ORGANIZATIONS, `authId = ${quoted}`);
134
+ forgetHosts();
135
+ forgetSlugs();
136
+ await refreshOrigins(context);
137
+ await context.scope.forgetLimits(tenant);
138
+ return removed;
139
+ }
140
+ /** The job: purges every suspended tenant whose waiting period is over. A tenant resumed meanwhile has no date any more. */
141
+ export async function runDuePurges(context, now = new Date()) {
142
+ const due = (await all(context.system.records, "purgeAt != null")).map((row) => toPlan(str(row.organizationId), row)).filter((plan) => plan.purgeAt && Date.parse(plan.purgeAt) <= now.getTime());
143
+ for (const plan of due) {
144
+ const tenant = await findTenant(context, plan.tenant);
145
+ // Only ever a suspended one: a purge asked of an open tenant is a mistake, kept until someone looks.
146
+ if (tenant && tenant.status !== "suspended")
147
+ continue;
148
+ try {
149
+ const removed = await purgeTenant(context, plan.tenant);
150
+ console.info(`[multi-tenant] purged ${plan.tenant}: ${removed.records} records and ${removed.files} files`);
151
+ }
152
+ catch (error) {
153
+ console.error(`[multi-tenant] purging ${plan.tenant} failed, and will be tried again`, error);
154
+ }
155
+ }
156
+ }
157
+ /**
158
+ * The job: checks each verified domain's proof is still in DNS. One whose proof has been gone
159
+ * for three days stops routing, so a domain that changed hands can't keep serving a tenant.
160
+ */
161
+ export async function recheckDomains(context, record, servers, now = new Date(), hasProof = dnsHasProof) {
162
+ let changed = false;
163
+ for (let page = 1;; page += 1) {
164
+ const result = await context.system.records.list(DOMAINS, { filter: "verifiedAt != null", perPage: 200, page, sort: "id" });
165
+ for (const row of result.items) {
166
+ const domain = { id: Number(row.id), host: str(row.host), token: str(row.token), primary: row.primary === true };
167
+ const stamp = now.toISOString();
168
+ if (await hasProof(domain, record, servers)) {
169
+ await context.system.records.update(DOMAINS, domain.id, { checkedAt: stamp, failingSince: null });
170
+ continue;
171
+ }
172
+ const since = str(row.failingSince);
173
+ if (!since) {
174
+ await context.system.records.update(DOMAINS, domain.id, { checkedAt: stamp, failingSince: stamp });
175
+ }
176
+ else if (now.getTime() - Date.parse(since) >= DOMAIN_GRACE_MS) {
177
+ await context.system.records.update(DOMAINS, domain.id, { checkedAt: stamp, verifiedAt: null, primary: false, failingSince: null });
178
+ changed = true;
179
+ console.warn(`[multi-tenant] ${domain.host} lost its verification: its TXT record has been missing since ${since}.`);
180
+ }
181
+ else {
182
+ await context.system.records.update(DOMAINS, domain.id, { checkedAt: stamp });
183
+ }
184
+ }
185
+ if (page >= result.totalPages)
186
+ break;
187
+ }
188
+ if (changed) {
189
+ forgetHosts();
190
+ await refreshOrigins(context);
191
+ }
192
+ }
193
+ /** The job: invitations past their date are marked expired, so lists and limits stop counting them. */
194
+ export async function expireInvitations(context, now = new Date()) {
195
+ const expired = [];
196
+ for (let page = 1;; page += 1) {
197
+ const result = await context.system.records.list(INVITATIONS, { filter: `invitationStatus = "pending"`, perPage: 200, page, sort: "id" });
198
+ for (const item of result.items)
199
+ if (Date.parse(str(item.expiresAt)) <= now.getTime())
200
+ expired.push(Number(item.id));
201
+ if (page >= result.totalPages)
202
+ break;
203
+ }
204
+ for (const id of expired)
205
+ await context.system.records.update(INVITATIONS, id, { invitationStatus: "expired" });
206
+ }
207
+ /** Every tenant's status, for the dashboard's danger zone and limits. */
208
+ export async function plansFor(context, tenants) {
209
+ const list = tenants ?? await listTenants(context);
210
+ return Promise.all(list.map(async (tenant) => ({ tenant, plan: await planOf(context, tenant.id) })));
211
+ }