@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 ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ What changed in each release of `@tansy/multi-tenant`. Releases up to 0.1.0 went out with every other package
4
+ on one version and are described in [tansy's changelog](../../CHANGELOG.md).
5
+
6
+ ## 0.1.1 — 2026-11-22
7
+
8
+ No changes of its own. Released beside `tansy` 0.1.1, from which every package moves on its own
9
+ version, and it now requires it: the `tansy` peer range is ^0.1.1.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohamed Salah
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ <!-- Generated by scripts/package-metadata.mjs. Change that script, not this file. -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @tansy/multi-tenant
4
+
5
+ Many tenants on one tansy: organizations with their own members, roles, domains, content, files and limits.
6
+
7
+ ```bash
8
+ npm install @tansy/multi-tenant
9
+ ```
10
+
11
+ Add it to `tansy.config.ts`. See [the multi-tenant plugin documentation](https://github.com/mhmdsalahsebai/tansy/blob/main/docs/plugins/multi-tenant.md) for what it adds and the options it takes.
12
+
13
+ A first-party plugin for [tansy](https://github.com/mhmdsalahsebai/tansy), a self-hosted, runtime-schema CMS for Next.js. MIT licensed.
package/admin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ declare const _default: import("tansy/admin").AdminPluginParts;
2
+ export default _default;
package/admin.js ADDED
@@ -0,0 +1,27 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { defineAdminPlugin } from "tansy/admin";
3
+ import { AccountTenants, TenantDomains, TenantMembers, TenantsList } from "./pages";
4
+ /** Three buildings side by side, in the navigation's 16 by 16 box. */
5
+ const ICON = {
6
+ paths: ["M1.75 14.5a.75.75 0 0 1 0-1.5H2V3.5A1.5 1.5 0 0 1 3.5 2h4A1.5 1.5 0 0 1 9 3.5V6h3.5A1.5 1.5 0 0 1 14 7.5V13h.25a.75.75 0 0 1 0 1.5H1.75ZM4 4.5v1h1.5v-1H4Zm0 3v1h1.5v-1H4Zm0 3v1h1.5v-1H4Zm6-2v1h1.5v-1H10Zm0 3v1h1.5v-1H10Z"],
7
+ };
8
+ function Tenants({ user }) {
9
+ const can = (action) => user.permissions.includes(`ext.multi-tenant:${action}`);
10
+ return _jsx(TenantsList, { canCreate: can("create"), canManage: can("read"), canUpdate: can("update"), canDelete: can("delete") });
11
+ }
12
+ function Members({ user }) {
13
+ return _jsx(TenantMembers, { canRename: user.permissions.includes("ext.multi-tenant:update") });
14
+ }
15
+ export default defineAdminPlugin({
16
+ pages: [
17
+ // Everyone in the dashboard sees the tenants they can work in. The route lists only those.
18
+ { path: "tenants", title: "Tenants", component: Tenants },
19
+ // Within the current tenant: a tenant admin holds this there, staff through their instance roles.
20
+ { path: "tenants/members", title: "Members", permission: "ext.multi-tenant:members", component: Members },
21
+ // Instance staff only: a domain decides which tenant a host's visitors see.
22
+ { path: "tenants/domains", title: "Domains", permission: "ext.multi-tenant:domains", component: TenantDomains },
23
+ ],
24
+ section: { title: "Tenants", icon: ICON, items: [{ page: "tenants" }, { page: "tenants/members" }, { page: "tenants/domains" }, { settings: true }] },
25
+ switcher: { label: "Tenant", options: "/switcher", select: "/switcher" },
26
+ accountPanels: [{ id: "tenants", component: AccountTenants }],
27
+ });
package/commands.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { type PluginCommand } from "tansy/plugin";
2
+ export declare function tenantCommands(): PluginCommand[];
package/commands.js ADDED
@@ -0,0 +1,116 @@
1
+ import { createReadStream, createWriteStream, statSync } from "node:fs";
2
+ import { Readable } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
4
+ import { defineCommand } from "tansy/plugin";
5
+ import { TENANT_HEADER } from "./tenants";
6
+ const pad = (value, width) => value.padEnd(width, " ");
7
+ /** A table, so a terminal shows columns rather than JSON nobody can read. */
8
+ function table(rows, log) {
9
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
10
+ for (const row of rows)
11
+ log(row.map((cell, column) => pad(cell, widths[column])).join(" ").trimEnd());
12
+ }
13
+ const bytes = (value) => (value === null ? "—" : value >= 1024 ** 2 ? `${(value / 1024 ** 2).toFixed(1)} MiB` : `${value} B`);
14
+ const count = (value) => (value === null ? "—" : String(value));
15
+ /** The tenant a command works on, which every one of these takes as a word, never as a flag. */
16
+ function tenantArgument(context, command) {
17
+ const id = context.args[1];
18
+ if (!id)
19
+ context.fail(`Usage: tansy tenant ${command} <tenant id>. Run cms tenant list for the ids.`);
20
+ return id;
21
+ }
22
+ async function list(context) {
23
+ const { items } = await context.api.request("/tenants");
24
+ if (!items.length)
25
+ return context.log("This instance has no tenants the key can see.");
26
+ table([["ID", "SHORT NAME", "NAME", "STATUS"], ...items.map((tenant) => [tenant.id, tenant.slug, tenant.name, tenant.status])], context.log);
27
+ }
28
+ async function show(context) {
29
+ const id = tenantArgument(context, "show");
30
+ const plan = await context.api.request(`/tenants/${encodeURIComponent(id)}/plan`);
31
+ const { tenant, limits, usage } = plan;
32
+ context.log(`${tenant.name} (${tenant.slug}) ${tenant.id} ${tenant.status}`);
33
+ table([
34
+ ["", "USING", "LIMIT"],
35
+ ["Records", String(usage.records), count(limits.records)],
36
+ ["Files", bytes(usage.storageBytes), bytes(limits.storageBytes)],
37
+ ["Members", String(usage.members), count(limits.members)],
38
+ ["Requests a minute", "—", count(limits.requestsPerMinute)],
39
+ ], context.log);
40
+ if (plan.purgeAt)
41
+ context.log(`\nEverything this tenant has is deleted at ${plan.purgeAt} unless it is resumed first.`);
42
+ }
43
+ async function domains(context) {
44
+ const tenant = typeof context.flags.tenant === "string" ? context.flags.tenant : undefined;
45
+ if (!tenant)
46
+ context.fail("Usage: tansy tenant domains --tenant <tenant id>. A key bound to one tenant already names it, and then --tenant must match.");
47
+ const { items } = await context.api.request("/domains", { headers: { [TENANT_HEADER]: tenant } });
48
+ if (!items.length)
49
+ return context.log("This tenant has claimed no domain.");
50
+ table([
51
+ ["HOST", "STATE", "MAIN", "TXT RECORD"],
52
+ ...items.map((domain) => [domain.host, domain.verified ? "verified" : "waiting", domain.primary ? "yes" : "", domain.verified ? "" : `${domain.record.name} = ${domain.record.value}`]),
53
+ ], context.log);
54
+ }
55
+ const statusChange = (command) => async (context) => {
56
+ const id = tenantArgument(context, command);
57
+ const tenant = await context.api.request(`/tenants/${encodeURIComponent(id)}/${command}`, { method: "POST" });
58
+ context.log(command === "suspend"
59
+ ? `${tenant.name} is suspended. Its domains, members and keys now reach nothing, and everything it has stays where it is.`
60
+ : `${tenant.name} is active again, and any purge it was waiting for is called off.`);
61
+ };
62
+ async function exportTenant(context) {
63
+ const id = tenantArgument(context, "export");
64
+ const response = await context.api.fetch(`/tenants/${encodeURIComponent(id)}/export`);
65
+ if (!response.ok || !response.body) {
66
+ const text = await response.text();
67
+ return context.fail(`The server answered ${response.status}: ${text.slice(0, 400)}`);
68
+ }
69
+ const named = /filename="([^"]+)"/.exec(response.headers.get("content-disposition") ?? "")?.[1];
70
+ const out = typeof context.flags.out === "string" ? context.flags.out : (named ?? `${id}.tar.gz`);
71
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(out));
72
+ context.log(`Wrote ${out} (${bytes(statSync(out).size)}). It holds everything this tenant has, so keep it as you would a backup.`);
73
+ }
74
+ async function importTenant(context) {
75
+ const id = tenantArgument(context, "import");
76
+ const file = typeof context.flags.in === "string" ? context.flags.in : undefined;
77
+ if (!file)
78
+ context.fail("Usage: tansy tenant import <tenant id> --in <archive>. The tenant must exist and have no data yet.");
79
+ const size = statSync(file).size;
80
+ const response = await context.api.fetch(`/tenants/${encodeURIComponent(id)}/import`, {
81
+ method: "POST",
82
+ headers: { "content-type": "application/gzip", "content-length": String(size) },
83
+ // Node streams the file rather than holding an archive of any size in memory.
84
+ body: Readable.toWeb(createReadStream(file)),
85
+ });
86
+ const text = await response.text();
87
+ if (!response.ok)
88
+ return context.fail(`The server answered ${response.status}: ${text.slice(0, 400)}`);
89
+ const placed = JSON.parse(text);
90
+ context.log(`Placed ${placed.records} records and ${placed.files} files in ${id}.`);
91
+ }
92
+ const actions = {
93
+ list,
94
+ show,
95
+ domains,
96
+ suspend: statusChange("suspend"),
97
+ resume: statusChange("resume"),
98
+ export: exportTenant,
99
+ import: importTenant,
100
+ };
101
+ export function tenantCommands() {
102
+ return [
103
+ defineCommand({
104
+ name: "tenant",
105
+ usage: "cms tenant <list | show <id> | domains --tenant <id> | suspend <id> | resume <id> | export <id> [--out <file>] | import <id> --in <file>>",
106
+ describe: "Run this instance's tenants through the API, as the key in TANSY_API_KEY. Making one, its limits and a purge are the dashboard's.",
107
+ run: async (context) => {
108
+ const action = actions[context.args[0] ?? ""];
109
+ if (!action) {
110
+ context.fail(`Usage: tansy tenant <${Object.keys(actions).join(" | ")}>. Making a tenant, setting its limits and asking for a purge all need a person signed in, so they are in the dashboard under Tenants.`);
111
+ }
112
+ await action(context);
113
+ },
114
+ }),
115
+ ];
116
+ }
package/doctor.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { DoctorCheck } from "tansy/plugin";
2
+ export declare function tenantChecks(options: {
3
+ siteUrl: string;
4
+ scopeNewCollections: boolean;
5
+ dnsServers?: string[];
6
+ }): DoctorCheck[];
package/doctor.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What `tansy doctor` says about this plugin. It runs with no server and no database, so these are
3
+ * about the options the app passes in `tansy.config.ts`: the kind of mistake that works until a real
4
+ * tenant hits it. Counting tenants or finding a domain whose DNS has gone would need the database,
5
+ * and those belong to the dashboard's Tenants page and the daily jobs.
6
+ */
7
+ /** A DNS server as the resolver takes it: a host or address, with an optional port. */
8
+ const SERVER = /^(\[[0-9a-fA-F:]+\]|[A-Za-z0-9.-]+)(:\d{1,5})?$/;
9
+ const LOCAL = /^(localhost|127\.0\.0\.1|\[::1\]|::1)$/;
10
+ export function tenantChecks(options) {
11
+ const checks = [];
12
+ const dashboard = new URL(options.siteUrl);
13
+ // Invitation emails and each tenant's own site address are built from this.
14
+ checks.push({
15
+ ok: !LOCAL.test(dashboard.hostname),
16
+ label: "the dashboard's address is one other people can reach",
17
+ fix: `siteUrl is ${dashboard.origin}, so invitation emails link there and a tenant with no verified domain has no site address. Set it to this instance's public address.`,
18
+ warning: true,
19
+ });
20
+ const bad = (options.dnsServers ?? []).filter((server) => !SERVER.test(server));
21
+ if (options.dnsServers?.length) {
22
+ checks.push({
23
+ ok: bad.length === 0,
24
+ label: "its DNS servers are addresses",
25
+ fix: `dnsServers has ${bad.map((server) => JSON.stringify(server)).join(", ")}, which isn't a host or address with an optional port, such as "10.0.0.2" or "10.0.0.2:5353". Domains would never verify.`,
26
+ });
27
+ checks.push({
28
+ ok: !options.dnsServers.some((server) => LOCAL.test(server.replace(/:\d+$/, ""))),
29
+ label: "its DNS servers aren't this machine",
30
+ fix: "dnsServers points at this machine, which is how the test suite stands in for DNS. In production a tenant could then prove a domain it doesn't own.",
31
+ warning: true,
32
+ });
33
+ }
34
+ // Off means a new collection is shared by every tenant, which is easy to miss until one tenant reads another's rows.
35
+ checks.push({
36
+ ok: options.scopeNewCollections,
37
+ label: "new collections keep each tenant's records apart",
38
+ fix: "scopeNewCollections is false, so a collection made under Collections is shared by every tenant until someone turns its scope on, on the collection's schema page.",
39
+ warning: true,
40
+ });
41
+ return checks;
42
+ }
package/domains.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ import type { ExtensionContext } from "tansy/plugin";
2
+ /**
3
+ * A tenant's domains: the hosts its site answers on. A domain routes, and its origin is
4
+ * trusted for signing in, only once DNS shows the tenant controls it: a TXT record at
5
+ * `<record>.<host>` holding the token this plugin gave. Kept in a system-owned collection
6
+ * that isn't scoped, since a request's host is read before its tenant is known.
7
+ */
8
+ export declare const DOMAINS = "multi-tenant-domains";
9
+ export declare const DEFAULT_RECORD = "_cms-verification";
10
+ /** Lower-case host names with at least one dot, such as client.example or www.client.example. */
11
+ export declare const HOST: RegExp;
12
+ /** The name the TXT record goes under, before the host. */
13
+ export declare const RECORD_NAME: RegExp;
14
+ export interface Domain {
15
+ id: number;
16
+ tenant: string;
17
+ host: string;
18
+ primary: boolean;
19
+ token: string;
20
+ verifiedAt: string | null;
21
+ checkedAt: string | null;
22
+ createdAt: string | null;
23
+ }
24
+ export declare const domainsSchema: () => {
25
+ version: number;
26
+ collections: {
27
+ slug: string;
28
+ name: string;
29
+ description: string;
30
+ urlPattern: null;
31
+ rules: {
32
+ listRule: null;
33
+ viewRule: null;
34
+ createRule: null;
35
+ updateRule: null;
36
+ deleteRule: null;
37
+ };
38
+ fields: ({
39
+ name: string;
40
+ type: string;
41
+ config: {
42
+ required: boolean;
43
+ maxLength: number;
44
+ hidden?: undefined;
45
+ };
46
+ } | {
47
+ name: string;
48
+ type: string;
49
+ config: {
50
+ required?: undefined;
51
+ maxLength?: undefined;
52
+ hidden?: undefined;
53
+ };
54
+ } | {
55
+ name: string;
56
+ type: string;
57
+ config: {
58
+ maxLength: number;
59
+ hidden: boolean;
60
+ required?: undefined;
61
+ };
62
+ })[];
63
+ }[];
64
+ };
65
+ export declare const domainsOf: (context: ExtensionContext, tenant: string) => Promise<Domain[]>;
66
+ export declare function findDomain(context: ExtensionContext, tenant: string, id: number): Promise<Domain | null>;
67
+ /** Every claim on a host, by any tenant. At most one is verified. */
68
+ export declare const claimsOn: (context: ExtensionContext, host: string) => Promise<Domain[]>;
69
+ export declare const newToken: () => string;
70
+ /** A host a person typed, as stored: lower-case, no scheme, path, port or trailing dot. Null when it isn't one a tenant can have. */
71
+ export declare function normalizeHost(value: string, reserved: ReadonlySet<string>): string | null;
72
+ export declare function forgetHosts(): void;
73
+ export declare function verifiedHosts(context: ExtensionContext): Promise<Map<string, string>>;
74
+ /** The tenant whose verified domain this host is, or null. */
75
+ export declare function tenantForHost(context: ExtensionContext, host: string | null): Promise<string | null>;
76
+ /** A tenant's main verified domain: the one marked primary, or else the first verified. Null with none. */
77
+ export declare function primaryHost(context: ExtensionContext, tenant: string): Promise<string | null>;
78
+ /** What a tenant's site is served from, for trusted origins: the dashboard's own scheme and port, on the tenant's host. */
79
+ export declare function originFor(host: string, siteUrl: string): string;
80
+ /** The TXT value that proves a tenant controls a host. */
81
+ export declare const proof: (token: string) => string;
82
+ /**
83
+ * Whether DNS holds the proof for this domain. A lookup that fails is a no, so a resolver
84
+ * that's down never verifies anything. `servers` replaces the system's resolvers, such as
85
+ * for a private network or tests.
86
+ */
87
+ export declare function dnsHasProof(domain: Pick<Domain, "host" | "token">, record: string, servers?: string[]): Promise<boolean>;
package/domains.js ADDED
@@ -0,0 +1,146 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { Resolver } from "node:dns/promises";
3
+ import { isIP } from "node:net";
4
+ import { PLUGIN, TENANT_ID } from "./tenants";
5
+ /**
6
+ * A tenant's domains: the hosts its site answers on. A domain routes, and its origin is
7
+ * trusted for signing in, only once DNS shows the tenant controls it: a TXT record at
8
+ * `<record>.<host>` holding the token this plugin gave. Kept in a system-owned collection
9
+ * that isn't scoped, since a request's host is read before its tenant is known.
10
+ */
11
+ export const DOMAINS = `${PLUGIN}-domains`;
12
+ export const DEFAULT_RECORD = "_cms-verification";
13
+ /** Lower-case host names with at least one dot, such as client.example or www.client.example. */
14
+ export const HOST = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
15
+ /** The name the TXT record goes under, before the host. */
16
+ export const RECORD_NAME = /^_?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
17
+ const str = (value) => (typeof value === "string" ? value : "");
18
+ export const domainsSchema = () => ({
19
+ version: 1,
20
+ collections: [{
21
+ slug: DOMAINS,
22
+ name: "Tenant domains",
23
+ description: "The hosts each tenant's site answers on. Only the multi-tenant plugin writes these.",
24
+ urlPattern: null,
25
+ rules: { listRule: null, viewRule: null, createRule: null, updateRule: null, deleteRule: null },
26
+ fields: [
27
+ { name: "host", type: "text", config: { required: true, maxLength: 253 } },
28
+ { name: "organizationId", type: "text", config: { required: true, maxLength: 64 } },
29
+ { name: "primary", type: "boolean", config: {} },
30
+ { name: "token", type: "text", config: { maxLength: 64, hidden: true } },
31
+ { name: "verifiedAt", type: "datetime", config: {} },
32
+ { name: "checkedAt", type: "datetime", config: {} },
33
+ ],
34
+ }],
35
+ });
36
+ const toDomain = (row) => ({
37
+ id: Number(row.id),
38
+ tenant: str(row.organizationId),
39
+ host: str(row.host),
40
+ primary: row.primary === true,
41
+ token: str(row.token),
42
+ verifiedAt: str(row.verifiedAt) || null,
43
+ checkedAt: str(row.checkedAt) || null,
44
+ createdAt: str(row.createdAt) || null,
45
+ });
46
+ async function all(records, filter) {
47
+ const items = [];
48
+ for (let page = 1;; page += 1) {
49
+ const result = await records.list(DOMAINS, { filter, perPage: 200, page, sort: "id" });
50
+ items.push(...result.items.map(toDomain));
51
+ if (page >= result.totalPages)
52
+ return items;
53
+ }
54
+ }
55
+ const quotedHost = (host) => {
56
+ if (!HOST.test(host))
57
+ throw new Error(`Not a host: ${JSON.stringify(host).slice(0, 80)}`);
58
+ return `"${host}"`;
59
+ };
60
+ const quotedTenant = (tenant) => {
61
+ if (!TENANT_ID.test(tenant))
62
+ throw new Error(`Not a tenant id: ${JSON.stringify(tenant).slice(0, 80)}`);
63
+ return `"${tenant}"`;
64
+ };
65
+ export const domainsOf = (context, tenant) => all(context.system.records, `organizationId = ${quotedTenant(tenant)}`);
66
+ export async function findDomain(context, tenant, id) {
67
+ return (await domainsOf(context, tenant)).find((domain) => domain.id === id) ?? null;
68
+ }
69
+ /** Every claim on a host, by any tenant. At most one is verified. */
70
+ export const claimsOn = (context, host) => all(context.system.records, `host = ${quotedHost(host)}`);
71
+ export const newToken = () => randomBytes(18).toString("base64url").replace(/[-_]/g, "").slice(0, 24);
72
+ /** A host a person typed, as stored: lower-case, no scheme, path, port or trailing dot. Null when it isn't one a tenant can have. */
73
+ export function normalizeHost(value, reserved) {
74
+ let host = value.trim().toLowerCase();
75
+ if (/^[a-z][a-z0-9+.-]*:\/\//.test(host)) {
76
+ try {
77
+ host = new URL(host).hostname;
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
83
+ host = host.replace(/\.$/, "");
84
+ if (!HOST.test(host) || isIP(host) || host.endsWith(".localhost") || reserved.has(host))
85
+ return null;
86
+ return host;
87
+ }
88
+ const cache = (globalThis.cmsTenantHosts ??= { map: new Map(), loadedAt: 0, loading: null });
89
+ const FRESH_MS = 15_000;
90
+ export function forgetHosts() {
91
+ cache.loadedAt = 0;
92
+ }
93
+ async function loadHosts(context) {
94
+ const verified = (await all(context.system.records, "verifiedAt != null")).sort((a, b) => (a.verifiedAt ?? "").localeCompare(b.verifiedAt ?? ""));
95
+ const map = new Map();
96
+ // The first to verify keeps a host. A later claim can't verify while it stands, so this only settles a race.
97
+ for (const domain of verified)
98
+ if (!map.has(domain.host))
99
+ map.set(domain.host, domain.tenant);
100
+ return map;
101
+ }
102
+ export async function verifiedHosts(context) {
103
+ if (cache.loadedAt && Date.now() - cache.loadedAt < FRESH_MS)
104
+ return cache.map;
105
+ cache.loading ??= loadHosts(context).then((map) => {
106
+ cache.map = map;
107
+ cache.loadedAt = Date.now();
108
+ return map;
109
+ }).finally(() => { cache.loading = null; });
110
+ return cache.loading;
111
+ }
112
+ /** The tenant whose verified domain this host is, or null. */
113
+ export async function tenantForHost(context, host) {
114
+ if (!host || !HOST.test(host))
115
+ return null;
116
+ return (await verifiedHosts(context)).get(host) ?? null;
117
+ }
118
+ /** A tenant's main verified domain: the one marked primary, or else the first verified. Null with none. */
119
+ export async function primaryHost(context, tenant) {
120
+ const verified = (await domainsOf(context, tenant)).filter((domain) => domain.verifiedAt).sort((a, b) => Number(b.primary) - Number(a.primary) || (a.verifiedAt ?? "").localeCompare(b.verifiedAt ?? ""));
121
+ return verified[0]?.host ?? null;
122
+ }
123
+ /** What a tenant's site is served from, for trusted origins: the dashboard's own scheme and port, on the tenant's host. */
124
+ export function originFor(host, siteUrl) {
125
+ const site = new URL(siteUrl);
126
+ return `${site.protocol}//${host}${site.port ? `:${site.port}` : ""}`;
127
+ }
128
+ /** The TXT value that proves a tenant controls a host. */
129
+ export const proof = (token) => `cms-verification=${token}`;
130
+ /**
131
+ * Whether DNS holds the proof for this domain. A lookup that fails is a no, so a resolver
132
+ * that's down never verifies anything. `servers` replaces the system's resolvers, such as
133
+ * for a private network or tests.
134
+ */
135
+ export async function dnsHasProof(domain, record, servers) {
136
+ const resolver = new Resolver({ timeout: 3000, tries: 2 });
137
+ if (servers?.length)
138
+ resolver.setServers(servers);
139
+ try {
140
+ const answers = await resolver.resolveTxt(`${record}.${domain.host}`);
141
+ return answers.some((chunks) => chunks.join("") === proof(domain.token));
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
package/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { TENANT_ID } from "./tenants";
2
+ export { DEFAULT_TENANT, TENANT_HEADER } from "./tenants";
3
+ export declare const TENANT_ADMIN = "multi-tenant-admin";
4
+ export declare const TENANT_EDITOR = "multi-tenant-editor";
5
+ export declare const TENANT_STAFF = "multi-tenant-staff";
6
+ export interface MultiTenantOptions {
7
+ /** Where the dashboard is, for links in invitation emails. */
8
+ siteUrl: string;
9
+ /** Whether a collection made under Collections keeps each tenant's records apart unless it says otherwise. Default true. */
10
+ scopeNewCollections?: boolean;
11
+ /** DNS servers that verify tenants' domains, such as ["10.0.0.2"] or ["127.0.0.1:5353"]. The system's own when left out. */
12
+ dnsServers?: string[];
13
+ }
14
+ /**
15
+ * Many sites, or customers, in one instance: each tenant has its own records in every
16
+ * collection marked scoped, its own members and their roles. Tenants, members and
17
+ * invitations are better-auth's organization plugin. Core keeps every tenant's records apart,
18
+ * below roles and rules (SECURITY_MODEL.md, "Row scopes"), so a request for one tenant never
19
+ * reads or writes another's. See internal/MULTI_TENANT_PLAN.md.
20
+ */
21
+ export declare function multiTenant(options: MultiTenantOptions): import("tansy/plugin").CmsPlugin;
22
+ export { TENANT_ID };