@12-apps/tenant 1.2.0 → 1.4.0
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/ADOPTING.md +206 -4
- package/README.md +9 -5
- package/package.json +26 -3
- package/src/config.ts +6 -2
- package/src/domains/checks.ts +124 -0
- package/src/domains/dns-names.ts +215 -0
- package/src/domains/engine.ts +309 -0
- package/src/domains/hostname.ts +38 -0
- package/src/domains/index.ts +45 -0
- package/src/domains/plan.ts +273 -0
- package/src/domains/port.ts +105 -0
- package/src/domains/react/card.tsx +216 -0
- package/src/domains/react/context.tsx +102 -0
- package/src/domains/react/copy.ts +151 -0
- package/src/domains/react/index.ts +41 -0
- package/src/domains/react/records.tsx +353 -0
- package/src/domains/react/removed.tsx +133 -0
- package/src/domains/react/row.tsx +335 -0
- package/src/domains/react/screen.ts +92 -0
- package/src/domains/record.ts +141 -0
- package/src/domains/server.ts +70 -0
- package/src/domains/tls.ts +50 -0
- package/src/hono/index.ts +51 -0
- package/src/index.ts +48 -1
- package/src/lifecycle/close.ts +191 -0
- package/src/lifecycle/context.ts +126 -0
- package/src/lifecycle/gates.ts +160 -0
- package/src/lifecycle/index.ts +127 -0
- package/src/lifecycle/pure.ts +56 -0
- package/src/lifecycle/refusal.ts +69 -0
- package/src/lifecycle/sweep.ts +139 -0
- package/src/lifecycle/types.ts +255 -0
- package/src/lifecycle/validate.ts +174 -0
- package/src/port.ts +14 -0
- package/src/server/index.ts +60 -4
- package/src/tree/index.ts +15 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tenant's custom domain AS ONE THING: the rows of a root + `www` pair
|
|
3
|
+
* folded into the one domain every reader answers with. Storage (the host's)
|
|
4
|
+
* keeps a row per name, so the TLS ask and the host-to-tenant lookup stay one
|
|
5
|
+
* indexed probe by hostname; nothing outside the host's repository ever sees
|
|
6
|
+
* the `www.` row on its own.
|
|
7
|
+
*
|
|
8
|
+
* Pure: rows in, records out. The host reads the rows (its own table, its own
|
|
9
|
+
* column names) and maps them to {@link TenantDomainRow}.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Statuses a domain row can hold. */
|
|
13
|
+
export type TenantDomainStatus = 'PENDING' | 'VERIFIED' | 'ACTIVE' | 'DISABLED' | 'FAILED';
|
|
14
|
+
|
|
15
|
+
/** One stored row, as the host reads it. */
|
|
16
|
+
export interface TenantDomainRow {
|
|
17
|
+
id: string;
|
|
18
|
+
hostname: string;
|
|
19
|
+
status: string;
|
|
20
|
+
verificationToken: string;
|
|
21
|
+
verifiedAt: Date | null;
|
|
22
|
+
dnsPointsHere: boolean | null;
|
|
23
|
+
createdAt: Date;
|
|
24
|
+
/** The root row's id on a `www.` row; null on a root (or a lone subdomain). */
|
|
25
|
+
pairRootId: string | null;
|
|
26
|
+
/** On a root row: the `www.` name is the principal address. */
|
|
27
|
+
wwwPrincipal: boolean;
|
|
28
|
+
archivedAt: Date | null;
|
|
29
|
+
archivedByUserId: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One name a domain answers on. */
|
|
33
|
+
export interface TenantDomainName {
|
|
34
|
+
hostname: string;
|
|
35
|
+
/** Did this name resolve to this deploy at the last check? `null` is unknown. */
|
|
36
|
+
dnsPointsHere: boolean | null;
|
|
37
|
+
/** The address the tenant answers on; the other name redirects to it. */
|
|
38
|
+
principal: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** A domain as everything outside the host's repository reads it. */
|
|
42
|
+
export interface TenantDomainRecord {
|
|
43
|
+
/** The ROOT row's id: the only id a domain is ever addressed by. */
|
|
44
|
+
id: string;
|
|
45
|
+
/** The claimed name: the root of a pair, or the one subdomain. */
|
|
46
|
+
hostname: string;
|
|
47
|
+
/** The pair's `www.` name, or null for a subdomain claim. */
|
|
48
|
+
wwwHostname: string | null;
|
|
49
|
+
/** Which of the pair is the principal address; always `root` for a subdomain. */
|
|
50
|
+
principal: 'root' | 'www';
|
|
51
|
+
status: TenantDomainStatus;
|
|
52
|
+
verificationToken: string;
|
|
53
|
+
verifiedAt: Date | null;
|
|
54
|
+
/**
|
|
55
|
+
* Did the domain resolve to this deploy at the last check? For a pair: `false`
|
|
56
|
+
* when either name points elsewhere, `true` when both point here, else unknown.
|
|
57
|
+
*/
|
|
58
|
+
dnsPointsHere: boolean | null;
|
|
59
|
+
/** Each name, root first. */
|
|
60
|
+
names: TenantDomainName[];
|
|
61
|
+
createdAt: Date;
|
|
62
|
+
archivedAt: Date | null;
|
|
63
|
+
archivedByUserId: string | null;
|
|
64
|
+
/** Each name's own row id: writes address a row, never a hostname (an archived row may share it). */
|
|
65
|
+
rowIds: Readonly<Record<string, string>>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A pair's pointing answer: a known `false` on either name wins, then a known `true` on both. */
|
|
69
|
+
function combinedPointing(values: readonly (boolean | null)[]): boolean | null {
|
|
70
|
+
if (values.some((value) => value === false)) return false;
|
|
71
|
+
return values.every((value) => value === true) ? true : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Fold one root row and its `www.` row (if any) into the domain. */
|
|
75
|
+
export function domainOf(root: TenantDomainRow, www?: TenantDomainRow): TenantDomainRecord {
|
|
76
|
+
const principal = www !== undefined && root.wwwPrincipal ? 'www' : 'root';
|
|
77
|
+
const names: TenantDomainName[] = [
|
|
78
|
+
{ hostname: root.hostname, dnsPointsHere: root.dnsPointsHere, principal: principal === 'root' },
|
|
79
|
+
...(www === undefined ? [] : [{ hostname: www.hostname, dnsPointsHere: www.dnsPointsHere, principal: principal === 'www' }]),
|
|
80
|
+
];
|
|
81
|
+
return {
|
|
82
|
+
id: root.id,
|
|
83
|
+
hostname: root.hostname,
|
|
84
|
+
wwwHostname: www?.hostname ?? null,
|
|
85
|
+
principal,
|
|
86
|
+
status: root.status as TenantDomainStatus,
|
|
87
|
+
verificationToken: root.verificationToken,
|
|
88
|
+
verifiedAt: root.verifiedAt,
|
|
89
|
+
dnsPointsHere: combinedPointing(names.map((name) => name.dnsPointsHere)),
|
|
90
|
+
names,
|
|
91
|
+
createdAt: root.createdAt,
|
|
92
|
+
archivedAt: root.archivedAt,
|
|
93
|
+
archivedByUserId: root.archivedByUserId,
|
|
94
|
+
rowIds: { [root.hostname]: root.id, ...(www === undefined ? {} : { [www.hostname]: www.id }) },
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Group rows (any order) into domains, keeping the roots' order. */
|
|
99
|
+
export function domainsOf(rows: readonly TenantDomainRow[]): TenantDomainRecord[] {
|
|
100
|
+
const wwwOf = new Map(
|
|
101
|
+
rows.flatMap((row) => (row.pairRootId === null ? [] : [[row.pairRootId, row] as const])),
|
|
102
|
+
);
|
|
103
|
+
return rows.filter((row) => row.pairRootId === null).map((root) => domainOf(root, wwwOf.get(root.id)));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The principal hostname of a domain. */
|
|
107
|
+
export function principalHostOf(domain: TenantDomainRecord): string {
|
|
108
|
+
return domain.principal === 'www' && domain.wwwHostname !== null ? domain.wwwHostname : domain.hostname;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The tenant's canonical host: a pair answers at its PRINCIPAL name, and only
|
|
113
|
+
* while that name is not known to point elsewhere; the oldest such domain wins,
|
|
114
|
+
* so the answer is stable when a second domain is added. Give it the tenant's
|
|
115
|
+
* ACTIVE rows, oldest first. The plan gate is the caller's.
|
|
116
|
+
*/
|
|
117
|
+
export function canonicalHostOf(activeRowsOldestFirst: readonly TenantDomainRow[]): string | null {
|
|
118
|
+
for (const domain of domainsOf(activeRowsOldestFirst)) {
|
|
119
|
+
const principal = principalHostOf(domain);
|
|
120
|
+
if (domain.names.find((name) => name.hostname === principal)?.dnsPointsHere !== false) return principal;
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Where a request on `hostname` must be sent instead: a pair's other name
|
|
127
|
+
* redirects to its principal, or null to serve it as it is. Give it the pair's
|
|
128
|
+
* rows (the root and its `www.`). Only an ACTIVE pair redirects, and only to a
|
|
129
|
+
* principal not known to point elsewhere: the same condition the canonical
|
|
130
|
+
* host holds, so neither ever bounces a visitor to a name that does not answer.
|
|
131
|
+
*/
|
|
132
|
+
export function pairRedirectOf(rows: readonly TenantDomainRow[], hostname: string): string | null {
|
|
133
|
+
const root = rows.find((row) => row.pairRootId === null);
|
|
134
|
+
if (root === undefined) return null;
|
|
135
|
+
const domain = domainOf(root, rows.find((row) => row.pairRootId === root.id));
|
|
136
|
+
const principal = principalHostOf(domain);
|
|
137
|
+
if (principal === hostname || domain.wwwHostname === null) return null;
|
|
138
|
+
const target = domain.names.find((name) => name.hostname === principal);
|
|
139
|
+
if (target?.dnsPointsHere === false || domain.status !== 'ACTIVE') return null;
|
|
140
|
+
return principal;
|
|
141
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server half of custom domains: the ports, the DNS checks through the
|
|
3
|
+
* host's resolver, the engine and the TLS ask. Runtime-free (no Node module):
|
|
4
|
+
* exported from `@12-apps/tenant` and `@12-apps/tenant/server`.
|
|
5
|
+
*/
|
|
6
|
+
import { TenantConfigError } from '../validate';
|
|
7
|
+
import { createDnsChecks, validateDnsChecksConfig, type TenantDomainDnsChecks, type TenantDomainDnsChecksConfig } from './checks';
|
|
8
|
+
import { createTenantDomains, validateDomainPorts, type TenantDomains } from './engine';
|
|
9
|
+
import type { TenantDomainPort, TenantDomainQuota } from './port';
|
|
10
|
+
import { createTlsAsk, validateTlsConfig, type TenantDomainTlsAnswer, type TenantDomainTlsConfig } from './tls';
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
createDnsChecks,
|
|
14
|
+
type TenantDomainDnsChecks,
|
|
15
|
+
type TenantDomainDnsChecksConfig,
|
|
16
|
+
} from './checks';
|
|
17
|
+
export {
|
|
18
|
+
createTenantDomains,
|
|
19
|
+
type TenantDomainAnswer,
|
|
20
|
+
type TenantDomainContext,
|
|
21
|
+
type TenantDomainOutcome,
|
|
22
|
+
type TenantDomainResult,
|
|
23
|
+
type TenantDomains,
|
|
24
|
+
type TenantDomainsConfig,
|
|
25
|
+
} from './engine';
|
|
26
|
+
export {
|
|
27
|
+
TENANT_DOMAIN_PORT_METHODS,
|
|
28
|
+
TENANT_DOMAIN_QUOTA_METHODS,
|
|
29
|
+
TENANT_DOMAIN_RESOLVER_METHODS,
|
|
30
|
+
type TenantDomainPort,
|
|
31
|
+
type TenantDomainQuota,
|
|
32
|
+
type TenantDomainResolver,
|
|
33
|
+
} from './port';
|
|
34
|
+
export { createTlsAsk, type TenantDomainTls, type TenantDomainTlsAnswer, type TenantDomainTlsConfig } from './tls';
|
|
35
|
+
|
|
36
|
+
/** Custom domains' whole config, as `createApiTenant` takes it (`domains`). Every member required. */
|
|
37
|
+
export interface TenantDomainsServerConfig<Tx = unknown> {
|
|
38
|
+
port: TenantDomainPort<Tx>;
|
|
39
|
+
quota: TenantDomainQuota<Tx>;
|
|
40
|
+
dns: TenantDomainDnsChecksConfig;
|
|
41
|
+
tls: TenantDomainTlsConfig;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** `tenant.domains`: the engine's `run`, the DNS checks, and the TLS ask. */
|
|
45
|
+
export interface ApiTenantDomains extends TenantDomains {
|
|
46
|
+
dns: TenantDomainDnsChecks;
|
|
47
|
+
ask(hostname: string): Promise<TenantDomainTlsAnswer>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Custom domains, when the host opts in: every member named under `domains.`.
|
|
52
|
+
* Left out (`undefined`), there is nothing to check.
|
|
53
|
+
*/
|
|
54
|
+
export function validateDomains(value: unknown): void {
|
|
55
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
56
|
+
throw new TenantConfigError('domains', 'must be the domains config object ({ port, quota, dns, tls }), or be left out');
|
|
57
|
+
}
|
|
58
|
+
const bag = value as Record<string, unknown>;
|
|
59
|
+
validateDomainPorts(bag, 'domains.');
|
|
60
|
+
validateDnsChecksConfig(bag.dns, 'domains.dns.');
|
|
61
|
+
validateTlsConfig(bag.tls, 'domains.tls.');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Build `tenant.domains` from a validated config. */
|
|
65
|
+
export function createApiTenantDomains<Tx>(config: TenantDomainsServerConfig<Tx>): ApiTenantDomains {
|
|
66
|
+
const dns = createDnsChecks(config.dns);
|
|
67
|
+
const engine = createTenantDomains({ port: config.port, quota: config.quota, dns });
|
|
68
|
+
const tls = createTlsAsk(config.tls);
|
|
69
|
+
return { run: engine.run, dns, ask: tls.ask };
|
|
70
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The TLS "ask": a reverse proxy with on-demand certificates asks, BEFORE
|
|
3
|
+
* ordering one for a name it has never seen, whether it may. It is the only
|
|
4
|
+
* thing between "a name points at us" and "we asked a CA for a certificate",
|
|
5
|
+
* so it is deny-by-default and two conditions must BOTH hold: the name is a
|
|
6
|
+
* servable (verified) domain of a live tenant, and that tenant is entitled to
|
|
7
|
+
* custom domains, so a downgrade stops renewal, not just serving.
|
|
8
|
+
*/
|
|
9
|
+
import { TenantConfigError } from '../validate';
|
|
10
|
+
|
|
11
|
+
export interface TenantDomainTlsConfig {
|
|
12
|
+
/** The tenant that may be served on `hostname` (an ACTIVE domain of a live tenant), or null. */
|
|
13
|
+
servable(hostname: string): Promise<{ tenantId: string } | null>;
|
|
14
|
+
/** Whether the tenant's plan carries custom domains now. */
|
|
15
|
+
entitled(tenantId: string): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type TenantDomainTlsAnswer = 'allow' | 'unknown' | 'unentitled';
|
|
19
|
+
|
|
20
|
+
export interface TenantDomainTls {
|
|
21
|
+
/** `allow` only when both hold; `unknown` no servable domain; `unentitled` the plan does not carry it. */
|
|
22
|
+
ask(hostname: string): Promise<TenantDomainTlsAnswer>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function requireFunction(bag: Record<string, unknown>, member: string, key: string): void {
|
|
26
|
+
if (bag[member] === undefined || bag[member] === null) throw new TenantConfigError(key, 'is required and missing');
|
|
27
|
+
if (typeof bag[member] !== 'function') throw new TenantConfigError(key, 'must be a function');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Check the ask's config; keys are named under `prefix` (`domains.tls.`). */
|
|
31
|
+
export function validateTlsConfig(value: unknown, prefix: string): void {
|
|
32
|
+
const where = prefix === '' ? 'tls' : prefix.replace(/\.$/, '');
|
|
33
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
34
|
+
throw new TenantConfigError(where, value === undefined || value === null ? 'is required and missing' : 'must be an object');
|
|
35
|
+
}
|
|
36
|
+
for (const member of ['servable', 'entitled'] as const) {
|
|
37
|
+
requireFunction(value as Record<string, unknown>, member, `${prefix}${member}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createTlsAsk(config: TenantDomainTlsConfig): TenantDomainTls {
|
|
42
|
+
validateTlsConfig(config, '');
|
|
43
|
+
return {
|
|
44
|
+
ask: async (hostname) => {
|
|
45
|
+
const servable = await config.servable(hostname.trim().toLowerCase());
|
|
46
|
+
if (servable === null) return 'unknown';
|
|
47
|
+
return (await config.entitled(servable.tenantId)) ? 'allow' : 'unentitled';
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
package/src/hono/index.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { Hono } from 'hono';
|
|
8
8
|
|
|
9
|
+
import type { GateRefusal, TenantGates } from '../lifecycle';
|
|
9
10
|
import type { ApiTenant } from '../server';
|
|
10
11
|
|
|
11
12
|
/** Mount every route of `tenant` on `app`, in order. Returns `app`. */
|
|
@@ -15,3 +16,53 @@ export function mountTenant<A extends Pick<Hono, 'on'>>(app: A, tenant: Pick<Api
|
|
|
15
16
|
}
|
|
16
17
|
return app;
|
|
17
18
|
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A gate middleware, typed structurally (the request it reads and the `next`
|
|
22
|
+
* it calls), so it fits any Hono version the host resolves the optional peer to.
|
|
23
|
+
*/
|
|
24
|
+
export type TenantGateMiddleware = (
|
|
25
|
+
context: { req: { raw: Request } },
|
|
26
|
+
next: () => Promise<void>,
|
|
27
|
+
) => Promise<Response | undefined>;
|
|
28
|
+
|
|
29
|
+
/** The one member of a Hono app the gate mount calls. */
|
|
30
|
+
export interface TenantGateApp {
|
|
31
|
+
use(path: string, handler: TenantGateMiddleware): unknown;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A refusal as the response every gate renders: `{ error, code, details: {} }` with its status. */
|
|
35
|
+
function refused(refusal: GateRefusal): Response {
|
|
36
|
+
return Response.json({ error: refusal.message, code: refusal.code, details: {} }, { status: refusal.status });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The admin gate as a middleware: mount it on `<admin.prefix>/*`. */
|
|
40
|
+
export function tenantAdminGate(gates: Pick<TenantGates, 'adminRefusal'>): TenantGateMiddleware {
|
|
41
|
+
return async (context, next) => {
|
|
42
|
+
const refusal = await gates.adminRefusal(context.req.raw);
|
|
43
|
+
if (refusal !== null) return refused(refusal);
|
|
44
|
+
await next();
|
|
45
|
+
return undefined;
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The public gate as a middleware: mount it on each `<public.prefix>/<family>/*`. */
|
|
50
|
+
export function tenantPublicGate(gates: Pick<TenantGates, 'publicRefusal'>): TenantGateMiddleware {
|
|
51
|
+
return async (context, next) => {
|
|
52
|
+
const refusal = await gates.publicRefusal(context.req.raw);
|
|
53
|
+
if (refusal !== null) return refused(refusal);
|
|
54
|
+
await next();
|
|
55
|
+
return undefined;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Mount both gates: `<admin.prefix>/*`, then `<public.prefix>/<family>/*` for each family. Returns `app`. */
|
|
60
|
+
export function mountTenantGates<A extends TenantGateApp>(
|
|
61
|
+
app: A,
|
|
62
|
+
gates: Pick<TenantGates, 'adminRefusal' | 'publicRefusal' | 'config'>,
|
|
63
|
+
): A {
|
|
64
|
+
app.use(`${gates.config.admin.prefix}/*`, tenantAdminGate(gates));
|
|
65
|
+
const pub = tenantPublicGate(gates);
|
|
66
|
+
for (const family of Object.keys(gates.config.public.families)) app.use(`${gates.config.public.prefix}/${family}/*`, pub);
|
|
67
|
+
return app;
|
|
68
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Backend: `@12-apps/tenant/server` (`createApiTenant`). Hono mount:
|
|
6
6
|
* `@12-apps/tenant/hono`. Frontend: `@12-apps/tenant/react`
|
|
7
|
-
* (`createWebTenant`).
|
|
7
|
+
* (`createWebTenant`). Custom domains: the engine here, the pure half in
|
|
8
|
+
* `@12-apps/tenant/domains`, the screen in `@12-apps/tenant/domains/react`. Adoption contract: ADOPTING.md.
|
|
8
9
|
*/
|
|
9
10
|
export {
|
|
10
11
|
TENANT_COPY_KEYS,
|
|
@@ -63,5 +64,51 @@ export {
|
|
|
63
64
|
type TenantSlugResolver,
|
|
64
65
|
type TenantSlugs,
|
|
65
66
|
} from './slugs';
|
|
67
|
+
export {
|
|
68
|
+
TENANT_DOMAIN_PORT_METHODS,
|
|
69
|
+
TENANT_DOMAIN_QUOTA_METHODS,
|
|
70
|
+
TENANT_DOMAIN_RESOLVER_METHODS,
|
|
71
|
+
createApiTenantDomains,
|
|
72
|
+
createDnsChecks,
|
|
73
|
+
createTenantDomains,
|
|
74
|
+
createTlsAsk,
|
|
75
|
+
validateDomains,
|
|
76
|
+
type ApiTenantDomains,
|
|
77
|
+
type TenantDomainAnswer,
|
|
78
|
+
type TenantDomainContext,
|
|
79
|
+
type TenantDomainDnsChecks,
|
|
80
|
+
type TenantDomainDnsChecksConfig,
|
|
81
|
+
type TenantDomainOutcome,
|
|
82
|
+
type TenantDomainPort,
|
|
83
|
+
type TenantDomainQuota,
|
|
84
|
+
type TenantDomainResolver,
|
|
85
|
+
type TenantDomainResult,
|
|
86
|
+
type TenantDomains,
|
|
87
|
+
type TenantDomainsConfig,
|
|
88
|
+
type TenantDomainsServerConfig,
|
|
89
|
+
type TenantDomainTls,
|
|
90
|
+
type TenantDomainTlsAnswer,
|
|
91
|
+
type TenantDomainTlsConfig,
|
|
92
|
+
} from './domains/server';
|
|
66
93
|
export { TenantConfigError, validateCoreConfig, validatePort, validateSlugs, validateTreePort } from './validate';
|
|
67
94
|
export type { DeepReadonly, TenantReadings, TenantRefusalKind } from './core';
|
|
95
|
+
export {
|
|
96
|
+
TENANT_LIFECYCLE_COPY_KEYS,
|
|
97
|
+
TENANT_REFUSAL_STATUS,
|
|
98
|
+
isTenantGone,
|
|
99
|
+
purgeAtFor,
|
|
100
|
+
reminderDue,
|
|
101
|
+
sameTenantName,
|
|
102
|
+
type GateRefusal,
|
|
103
|
+
type TenantAuditEvent,
|
|
104
|
+
type TenantBlocker,
|
|
105
|
+
type TenantBlockerCount,
|
|
106
|
+
type TenantBlockerKind,
|
|
107
|
+
type TenantCloseEntry,
|
|
108
|
+
type TenantClosingEvent,
|
|
109
|
+
type TenantClosingState,
|
|
110
|
+
type TenantLifecycleCopyPack,
|
|
111
|
+
type TenantLifecycleRefusalKind,
|
|
112
|
+
type TenantNoticePayload,
|
|
113
|
+
type TenantReminder,
|
|
114
|
+
} from './lifecycle';
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Closing a tenant and reopening it.
|
|
3
|
+
*
|
|
4
|
+
* **Close**, a dangerous act: the host's confirmation first, then the reason
|
|
5
|
+
* and (a member's close) the typed name, then ONE transaction: the
|
|
6
|
+
* conditional status move, the blockers counted AGAIN after it (anything
|
|
7
|
+
* found rolls the move back), the closing row replaced, the mirror, the audit
|
|
8
|
+
* line. After the commit, and never able to undo it: the after-close hook
|
|
9
|
+
* (stamped either way; a failure is audited and the sweep retries it), the
|
|
10
|
+
* cache invalidation and the notice.
|
|
11
|
+
*
|
|
12
|
+
* **Reopen**: the row read once, then ONE transaction: closing → the status
|
|
13
|
+
* the close started from (a valid one, else active), the row deleted, the
|
|
14
|
+
* mirror, the audit line. Then the invalidation and the notice.
|
|
15
|
+
*/
|
|
16
|
+
import type { TenantStatusSet } from '../config';
|
|
17
|
+
import type { TenantRecord } from '../port';
|
|
18
|
+
import type { LifecycleContext } from './context';
|
|
19
|
+
import { purgeAtFor, sameTenantName } from './pure';
|
|
20
|
+
import type {
|
|
21
|
+
TenantCloseEntry,
|
|
22
|
+
TenantClosingCreate,
|
|
23
|
+
TenantClosingState,
|
|
24
|
+
TenantLifecycle,
|
|
25
|
+
TenantNoticePayload,
|
|
26
|
+
} from './types';
|
|
27
|
+
|
|
28
|
+
type CloseInput<S extends string> = Parameters<TenantLifecycle<S>['close']>[0];
|
|
29
|
+
|
|
30
|
+
export function payloadOf(
|
|
31
|
+
tenant: TenantRecord,
|
|
32
|
+
name: string,
|
|
33
|
+
purgeAt: Date,
|
|
34
|
+
by: TenantCloseEntry | null,
|
|
35
|
+
reason: string | null,
|
|
36
|
+
restored: string | null = null,
|
|
37
|
+
): TenantNoticePayload {
|
|
38
|
+
return { tenantId: tenant.id, name, slug: tenant.slug, purgeAt: purgeAt.toISOString(), by, reason, restored };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Where `close` and `reopen` get their record: the caller, who read it through the port or its own lookup. */
|
|
42
|
+
const CALLER_RECORD = 'close/reopen tenant (the caller\'s record, port.bySlug/byId)';
|
|
43
|
+
|
|
44
|
+
/** The refusal for a tenant the close may not move, by the status the transaction reads. */
|
|
45
|
+
async function notClosable<S extends string, Tx>(context: LifecycleContext<S, Tx>, id: string, tx: Tx): Promise<Error> {
|
|
46
|
+
const current = await context.tenant.byId(id, tx);
|
|
47
|
+
return context.refuse(current !== null && context.isGone(current.status) ? 'alreadyClosing' : 'notActive');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The transaction: the move, the recount, the row, the mirror and the audit line. */
|
|
51
|
+
async function closeInTransaction<S extends string, Tx>(
|
|
52
|
+
context: LifecycleContext<S, Tx>,
|
|
53
|
+
input: CloseInput<S>,
|
|
54
|
+
row: TenantClosingCreate,
|
|
55
|
+
): Promise<void> {
|
|
56
|
+
const { tenant, config } = context;
|
|
57
|
+
const { ids } = tenant.config;
|
|
58
|
+
const statuses = tenant.config.statuses as unknown as TenantStatusSet<S>;
|
|
59
|
+
const from: readonly string[] = input.by === 'member' ? [statuses.active] : statuses.closableFrom;
|
|
60
|
+
const id = input.tenant.id;
|
|
61
|
+
await config.db.transaction(async (tx) => {
|
|
62
|
+
if (!from.includes(input.tenant.status)) throw await notClosable(context, id, tx);
|
|
63
|
+
if (!(await tenant.setStatusIf(id, input.tenant.status, statuses.closing, tx))) throw await notClosable(context, id, tx);
|
|
64
|
+
// After the move, in the same transaction: what landed since the page's read is seen here, and rolls the move back.
|
|
65
|
+
const blockers = await context.blockersOf(id, row.requestedAt, tx);
|
|
66
|
+
if (blockers.length > 0) throw context.refuse('closingBlocked', { pending: blockers.length }, blockers.length);
|
|
67
|
+
const table = await context.table(tx);
|
|
68
|
+
// A row an earlier close left (reopened by the platform before a stamp cleared it) is replaced: fresh stamps.
|
|
69
|
+
await table.deleteMany({ where: { tenantId: id } });
|
|
70
|
+
await table.create({ data: row });
|
|
71
|
+
if (config.mirror !== undefined) await config.mirror.replaced(tx, row);
|
|
72
|
+
await config.audit(tx, ids.audit.closeScheduled, {
|
|
73
|
+
act: 'closeScheduled',
|
|
74
|
+
tenantId: id,
|
|
75
|
+
by: input.by,
|
|
76
|
+
reason: row.reason,
|
|
77
|
+
purgeAt: row.purgeAt,
|
|
78
|
+
priorStatus: input.tenant.status,
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The after-close hook, stamped either way; a failure is audited with its stamp, in one transaction. */
|
|
84
|
+
export async function runAfterClose<S extends string, Tx>(
|
|
85
|
+
context: LifecycleContext<S, Tx>,
|
|
86
|
+
tenant: TenantRecord<S>,
|
|
87
|
+
now: Date,
|
|
88
|
+
): Promise<boolean> {
|
|
89
|
+
const { config } = context;
|
|
90
|
+
try {
|
|
91
|
+
const node = (await context.tenant.tree?.nodeOf?.(tenant.id)) ?? null;
|
|
92
|
+
await config.afterClose({ tenant, node, now });
|
|
93
|
+
} catch (error) {
|
|
94
|
+
config.onError(error, { act: 'afterClose', tenantId: tenant.id });
|
|
95
|
+
const message = (error instanceof Error ? error.message : String(error)).slice(0, 200);
|
|
96
|
+
await context.quietly('afterCloseFailed', tenant.id, () =>
|
|
97
|
+
config.db.transaction(async (tx) => {
|
|
98
|
+
await (await context.table(tx)).updateMany({
|
|
99
|
+
where: { tenantId: tenant.id, afterCloseDoneAt: null },
|
|
100
|
+
data: { afterCloseFailedAt: now },
|
|
101
|
+
});
|
|
102
|
+
if (config.mirror !== undefined) await config.mirror.event(tx, tenant.id, { kind: 'afterClose', ok: false, at: now });
|
|
103
|
+
await config.audit(tx, context.tenant.config.ids.audit.afterCloseFailed, {
|
|
104
|
+
act: 'afterCloseFailed',
|
|
105
|
+
tenantId: tenant.id,
|
|
106
|
+
error: message,
|
|
107
|
+
});
|
|
108
|
+
}),
|
|
109
|
+
);
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
// The hook went through; a missed stamp only means the sweep runs it again, which the host's hook must tolerate.
|
|
113
|
+
await context.quietly('afterCloseStamp', tenant.id, () =>
|
|
114
|
+
context.stamp(tenant.id, 'afterCloseDoneAt', now, { kind: 'afterClose', ok: true, at: now }),
|
|
115
|
+
);
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function closeTenant<S extends string, Tx>(
|
|
120
|
+
context: LifecycleContext<S, Tx>,
|
|
121
|
+
given: CloseInput<S>,
|
|
122
|
+
): Promise<TenantClosingState<S>> {
|
|
123
|
+
// A snapshot: the status the close starts from is the one the caller read, whatever happens to its object.
|
|
124
|
+
const input = { ...given, tenant: { ...given.tenant } };
|
|
125
|
+
const { config } = context;
|
|
126
|
+
const { ids } = context.tenant.config;
|
|
127
|
+
const statuses = context.tenant.config.statuses as unknown as TenantStatusSet<S>;
|
|
128
|
+
const id = input.tenant.id;
|
|
129
|
+
await config.confirmDangerousAct(input.request, { tenantId: id, by: input.by });
|
|
130
|
+
const reason = input.reason.trim();
|
|
131
|
+
if (reason.length < config.minReasonLength) throw context.refuse('reasonTooShort');
|
|
132
|
+
const name = context.nameOf(input.tenant, CALLER_RECORD);
|
|
133
|
+
if (input.by === 'member' && !sameTenantName(input.typedName ?? '', name, config.nameLocale)) {
|
|
134
|
+
throw context.refuse('nameMismatch');
|
|
135
|
+
}
|
|
136
|
+
const now = input.now ?? new Date();
|
|
137
|
+
const purgeAt = purgeAtFor(now, config.graceDays);
|
|
138
|
+
const row: TenantClosingCreate = {
|
|
139
|
+
tenantId: id,
|
|
140
|
+
requestedAt: now,
|
|
141
|
+
requestedById: input.by === 'member' ? input.actorUserId : null,
|
|
142
|
+
reason,
|
|
143
|
+
priorStatus: input.tenant.status,
|
|
144
|
+
purgeAt,
|
|
145
|
+
};
|
|
146
|
+
await closeInTransaction(context, input, row);
|
|
147
|
+
await runAfterClose(context, input.tenant, now);
|
|
148
|
+
await context.quietly('invalidate', id, () => config.invalidate(id));
|
|
149
|
+
await context.quietly('notify', id, () =>
|
|
150
|
+
config.notify(
|
|
151
|
+
ids.notifications.closingScheduled,
|
|
152
|
+
payloadOf(input.tenant, name, purgeAt, input.by, input.by === 'platform' ? reason : null),
|
|
153
|
+
),
|
|
154
|
+
);
|
|
155
|
+
return { status: statuses.closing, requestedAt: now.toISOString(), purgeAt: purgeAt.toISOString() };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function reopenTenant<S extends string, Tx>(
|
|
159
|
+
context: LifecycleContext<S, Tx>,
|
|
160
|
+
input: { tenant: TenantRecord<S>; by: TenantCloseEntry },
|
|
161
|
+
): Promise<TenantClosingState<S>> {
|
|
162
|
+
const { config } = context;
|
|
163
|
+
const { ids } = context.tenant.config;
|
|
164
|
+
const statuses = context.tenant.config.statuses as unknown as TenantStatusSet<S>;
|
|
165
|
+
const id = input.tenant.id;
|
|
166
|
+
const name = context.nameOf(input.tenant, CALLER_RECORD);
|
|
167
|
+
const row = await (await context.table()).findUnique({ where: { tenantId: id } });
|
|
168
|
+
const prior = row?.priorStatus ?? null;
|
|
169
|
+
const target = (
|
|
170
|
+
prior !== null && (statuses.all as readonly string[]).includes(prior) && !context.isGone(prior) ? prior : statuses.active
|
|
171
|
+
) as S;
|
|
172
|
+
await config.db.transaction(async (tx) => {
|
|
173
|
+
if (!(await context.tenant.setStatusIf(id, statuses.closing, target, tx))) {
|
|
174
|
+
throw context.refuse(row?.purgedAt ? 'purged' : 'notClosing');
|
|
175
|
+
}
|
|
176
|
+
await (await context.table(tx)).deleteMany({ where: { tenantId: id } });
|
|
177
|
+
if (config.mirror !== undefined) await config.mirror.deleted(tx, id, row?.requestedAt);
|
|
178
|
+
await config.audit(tx, ids.audit.closeReopened, {
|
|
179
|
+
act: 'closeReopened',
|
|
180
|
+
tenantId: id,
|
|
181
|
+
by: input.by,
|
|
182
|
+
purgeAt: row?.purgeAt ?? null,
|
|
183
|
+
restored: target,
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
await context.quietly('invalidate', id, () => config.invalidate(id));
|
|
187
|
+
await context.quietly('notify', id, () =>
|
|
188
|
+
config.notify(ids.notifications.reopened, payloadOf(input.tenant, name, row?.purgeAt ?? new Date(), null, null, target)),
|
|
189
|
+
);
|
|
190
|
+
return { status: target, requestedAt: null, purgeAt: null };
|
|
191
|
+
}
|