@12-apps/tenant 1.3.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.
@@ -0,0 +1,309 @@
1
+ /**
2
+ * THE ONE ENGINE behind every change to a tenant's custom domains: a panel's
3
+ * one-operation calls and an agent's bulk write run exactly this, so removing
4
+ * a domain, restoring it and choosing its principal behave the same on both.
5
+ *
6
+ * All or nothing, in three passes:
7
+ * 1. every operation is checked against the tenant's domains and every other
8
+ * tenant's live names (`./plan.ts`): each problem named, nothing written;
9
+ * 2. the DNS lookups a `verify` needs run next, OUTSIDE the transaction (they
10
+ * can take seconds and change nothing here);
11
+ * 3. ONE serializable transaction re-checks the names and the plan's count and
12
+ * applies everything, with an audit line per removal and per restore.
13
+ *
14
+ * Statements, in order: `rows`, `holders`, (`mayVerify`), (`reserve`); then, in
15
+ * the transaction, `holders` again and `used` when the limit is a number, the
16
+ * writes, the audits; then ONE `rows` for the answer. Copy-free: problems are
17
+ * kinds, and the host words them.
18
+ */
19
+ import { TenantConfigError } from '../validate';
20
+ import type { TenantDomainDnsChecks } from './checks';
21
+ import {
22
+ claimableNames,
23
+ claimsOf,
24
+ guardedOf,
25
+ namesOf,
26
+ planDomainOperations,
27
+ unitsOf,
28
+ type TenantDomainOperation,
29
+ type TenantDomainProblem,
30
+ type TenantDomainStep,
31
+ } from './plan';
32
+ import {
33
+ TENANT_DOMAIN_PORT_METHODS,
34
+ TENANT_DOMAIN_QUOTA_METHODS,
35
+ type TenantDomainPort,
36
+ type TenantDomainQuota,
37
+ } from './port';
38
+ import { domainsOf, type TenantDomainRecord } from './record';
39
+
40
+ /** Who acts and from where. `via` is opaque: it reaches the quota and the audit line as given. */
41
+ export interface TenantDomainContext {
42
+ tenantId: string;
43
+ /** Who removes, recorded on the removed row. */
44
+ actorId: string | null;
45
+ via: string;
46
+ }
47
+
48
+ export type TenantDomainOutcome =
49
+ | 'created'
50
+ | 'unchanged'
51
+ | 'verified'
52
+ | 'not_verified'
53
+ | 'updated'
54
+ | 'archived'
55
+ | 'restored'
56
+ | 'would_apply';
57
+
58
+ export interface TenantDomainResult {
59
+ index: number;
60
+ operation: TenantDomainOperation['operation'];
61
+ outcome: TenantDomainOutcome;
62
+ /** The names the operation is about. */
63
+ hostnames: string[];
64
+ /** The domain the result is about (in `domains`), or null for a previewed new claim. */
65
+ domainId: string | null;
66
+ }
67
+
68
+ export type TenantDomainAnswer =
69
+ | { ok: true; validateOnly: boolean; results: TenantDomainResult[]; domains: TenantDomainRecord[] }
70
+ | { ok: false; problems: TenantDomainProblem[] };
71
+
72
+ export interface TenantDomainsConfig<Tx = unknown> {
73
+ port: TenantDomainPort<Tx>;
74
+ quota: TenantDomainQuota<Tx>;
75
+ dns: TenantDomainDnsChecks;
76
+ }
77
+
78
+ export interface TenantDomains {
79
+ /** Run a call's operations, all or nothing. */
80
+ run(
81
+ ctx: TenantDomainContext,
82
+ body: { operations: readonly TenantDomainOperation[]; validateOnly?: boolean },
83
+ ): Promise<TenantDomainAnswer>;
84
+ }
85
+
86
+ type Bag = Record<string, unknown>;
87
+ const isBag = (value: unknown): value is Bag => typeof value === 'object' && value !== null && !Array.isArray(value);
88
+
89
+ function requireMembers(value: unknown, key: string, members: readonly string[]): void {
90
+ if (!isBag(value)) {
91
+ throw new TenantConfigError(key, value === undefined || value === null ? 'is required and missing' : 'must be an object');
92
+ }
93
+ for (const member of members) {
94
+ if (value[member] === undefined || value[member] === null) {
95
+ throw new TenantConfigError(`${key}.${member}`, 'is required and missing');
96
+ }
97
+ if (typeof value[member] !== 'function') throw new TenantConfigError(`${key}.${member}`, 'must be a function');
98
+ }
99
+ }
100
+
101
+ /** Check the port and the quota; keys are named under `prefix` (`domains.`). */
102
+ export function validateDomainPorts(value: Bag, prefix: string): void {
103
+ requireMembers(value.port, `${prefix}port`, TENANT_DOMAIN_PORT_METHODS);
104
+ requireMembers(value.quota, `${prefix}quota`, TENANT_DOMAIN_QUOTA_METHODS);
105
+ }
106
+
107
+ /** Raised inside the transaction when a race took a name or the plan's last unit. */
108
+ class RaceRefusal extends Error {
109
+ constructor(readonly problem: TenantDomainProblem) {
110
+ super(`@12-apps/tenant: domain race (${problem.kind})`);
111
+ }
112
+ }
113
+
114
+ type Found = ReadonlyMap<string, { verified: boolean; pointsHere: Readonly<Record<string, boolean | null>> }>;
115
+ type Applied = { id: string; outcome: TenantDomainOutcome };
116
+ type Writer<Tx, K extends TenantDomainStep['kind']> = (
117
+ tx: Tx,
118
+ ctx: TenantDomainContext,
119
+ step: Extract<TenantDomainStep, { kind: K }>,
120
+ found: Found,
121
+ now: Date,
122
+ ) => Promise<Applied>;
123
+
124
+ function writersOf<Tx>(port: TenantDomainPort<Tx>): { [K in TenantDomainStep['kind']]: Writer<Tx, K> } {
125
+ const audit = (tx: Tx, ctx: TenantDomainContext, step: Extract<TenantDomainStep, { kind: 'archive' | 'restore' }>) =>
126
+ port.audit(tx, { act: step.kind, tenantId: ctx.tenantId, domain: step.domain, reason: step.reason, via: ctx.via });
127
+ return {
128
+ add: async (tx, ctx, step) => ({
129
+ id: (await port.claim(tx, ctx.tenantId, step.hostname, step.principal)).id,
130
+ outcome: 'created',
131
+ }),
132
+ noop: async (_tx, _ctx, step) => ({ id: step.domain.id, outcome: 'unchanged' }),
133
+ principal: async (tx, ctx, step) => {
134
+ await port.setPrincipal(tx, ctx.tenantId, step.domain.id, step.principal);
135
+ return { id: step.domain.id, outcome: 'updated' };
136
+ },
137
+ verify: async (tx, ctx, step, found, now) => {
138
+ const outcome = found.get(step.domain.id) ?? { verified: false, pointsHere: {} };
139
+ await port.recordCheck(tx, ctx.tenantId, step.domain, outcome, now);
140
+ return { id: step.domain.id, outcome: outcome.verified ? 'verified' : 'not_verified' };
141
+ },
142
+ archive: async (tx, ctx, step, _found, now) => {
143
+ await port.archive(tx, ctx.tenantId, step.domain.id, now, ctx.actorId);
144
+ await audit(tx, ctx, step);
145
+ return { id: step.domain.id, outcome: 'archived' };
146
+ },
147
+ restore: async (tx, ctx, step) => {
148
+ await port.restore(tx, ctx.tenantId, step.domain.id);
149
+ await audit(tx, ctx, step);
150
+ return { id: step.domain.id, outcome: 'restored' };
151
+ },
152
+ };
153
+ }
154
+
155
+ /** The DNS answers every `verify` needs, by domain id: the TXT at the root, and where each name points. */
156
+ async function lookups(dns: TenantDomainDnsChecks, steps: readonly TenantDomainStep[]): Promise<Found> {
157
+ const verifies = steps.filter((step): step is Extract<TenantDomainStep, { kind: 'verify' }> => step.kind === 'verify');
158
+ const answers = await Promise.all(
159
+ verifies.map(async ({ domain }) => {
160
+ const names = namesOf(domain);
161
+ const [verified, pointing] = await Promise.all([
162
+ dns.ownsRecord(domain.hostname, domain.verificationToken),
163
+ Promise.all(names.map((name) => dns.pointsHere(name))),
164
+ ]);
165
+ return [domain.id, { verified, pointsHere: Object.fromEntries(names.map((name, at) => [name, pointing[at] ?? null])) }] as const;
166
+ }),
167
+ );
168
+ return new Map(answers);
169
+ }
170
+
171
+ /** What `validateOnly` answers: each step as it would go, writing nothing and asking no DNS. */
172
+ const previewOf = (step: TenantDomainStep) => ({
173
+ step,
174
+ id: step.kind === 'add' ? null : step.domain.id,
175
+ outcome: step.kind === 'noop' ? ('unchanged' as const) : ('would_apply' as const),
176
+ });
177
+
178
+ /** The quota refusal, told on each claim and restore. */
179
+ function quotaProblems(steps: readonly TenantDomainStep[], kind: 'planRequired' | 'planLimit'): TenantDomainProblem[] {
180
+ return steps.flatMap((step) =>
181
+ step.kind === 'add' || step.kind === 'restore'
182
+ ? [{ index: step.index, kind, hostname: step.kind === 'add' ? step.hostname : step.domain.hostname }]
183
+ : [],
184
+ );
185
+ }
186
+
187
+ interface EngineDeps<Tx> {
188
+ port: TenantDomainPort<Tx>;
189
+ quota: TenantDomainQuota<Tx>;
190
+ dns: TenantDomainDnsChecks;
191
+ writers: { [K in TenantDomainStep['kind']]: Writer<Tx, K> };
192
+ }
193
+
194
+ /** Re-check, in the transaction, what a concurrent call could have changed: the names and the plan's count. */
195
+ async function recheck<Tx>(
196
+ deps: EngineDeps<Tx>,
197
+ tx: Tx,
198
+ ctx: TenantDomainContext,
199
+ steps: readonly TenantDomainStep[],
200
+ limit: number | null,
201
+ ): Promise<void> {
202
+ const claims = new Set(claimsOf(steps));
203
+ const guarded = [...new Set(claimsOf(steps).flatMap((name) => guardedOf(name)))];
204
+ // This tenant's own rows block only the names it claims; another tenant's block their roots too.
205
+ const holder = (await deps.port.holders(guarded, tx)).find(
206
+ (row) => claims.has(row.hostname) || row.tenantId !== ctx.tenantId,
207
+ );
208
+ if (holder !== undefined) {
209
+ const kind = holder.tenantId === ctx.tenantId ? 'nameHeldHere' : 'nameTaken';
210
+ throw new RaceRefusal({ index: null, kind, hostname: holder.hostname });
211
+ }
212
+ const units = unitsOf(steps);
213
+ if (units > 0 && typeof limit === 'number' && (await deps.quota.used(ctx.tenantId, tx)) + units > limit) {
214
+ throw new RaceRefusal({ index: null, kind: 'planLimit', hostname: null });
215
+ }
216
+ }
217
+
218
+ /** What a thrown transaction means: a problem, or rethrown. */
219
+ function problemOf<Tx>(deps: EngineDeps<Tx>, error: unknown, steps: readonly TenantDomainStep[]): TenantDomainProblem {
220
+ if (error instanceof RaceRefusal) return error.problem;
221
+ const kind = deps.port.failure(error);
222
+ if (kind === 'retry') return { index: null, kind: 'retry', hostname: null };
223
+ if (kind !== 'taken') throw error;
224
+ const name = claimsOf(steps)[0] ?? '';
225
+ return { index: null, kind: 'nameTaken', hostname: name || null };
226
+ }
227
+
228
+ /** The one transaction: re-check, then every step in call order; a race is a problem, never a partial write. */
229
+ async function commit<Tx>(
230
+ deps: EngineDeps<Tx>,
231
+ ctx: TenantDomainContext,
232
+ steps: readonly TenantDomainStep[],
233
+ limit: number | null,
234
+ ): Promise<{ applied: ({ step: TenantDomainStep } & Applied)[] } | { problems: TenantDomainProblem[] }> {
235
+ const found = await lookups(deps.dns, steps);
236
+ const now = new Date();
237
+ try {
238
+ const applied = await deps.port.transaction(async (tx) => {
239
+ await recheck(deps, tx, ctx, steps, limit);
240
+ const out: ({ step: TenantDomainStep } & Applied)[] = [];
241
+ for (const step of steps) {
242
+ const write = deps.writers[step.kind] as Writer<Tx, TenantDomainStep['kind']>;
243
+ out.push({ step, ...(await write(tx, ctx, step, found, now)) });
244
+ }
245
+ return out;
246
+ });
247
+ return { applied };
248
+ } catch (error) {
249
+ return { problems: [problemOf(deps, error, steps)] };
250
+ }
251
+ }
252
+
253
+ /** The answer: each step's result, and every domain as it is now (ONE re-read). */
254
+ async function answer<Tx>(
255
+ deps: EngineDeps<Tx>,
256
+ tenantId: string,
257
+ operations: readonly TenantDomainOperation[],
258
+ applied: readonly { step: TenantDomainStep; id: string | null; outcome: TenantDomainOutcome }[],
259
+ validateOnly: boolean,
260
+ ): Promise<TenantDomainAnswer> {
261
+ const domains = domainsOf(await deps.port.rows(tenantId));
262
+ const results = applied.map(({ step, id, outcome }) => ({
263
+ index: step.index,
264
+ operation: (operations[step.index] as TenantDomainOperation).operation,
265
+ outcome,
266
+ hostnames: step.kind === 'add' ? step.names : namesOf(step.domain),
267
+ domainId: id,
268
+ }));
269
+ return { ok: true, validateOnly, results, domains };
270
+ }
271
+
272
+ /** Read and plan: the steps, or every problem (the quota's refusal included). */
273
+ async function planned<Tx>(
274
+ deps: EngineDeps<Tx>,
275
+ ctx: TenantDomainContext,
276
+ operations: readonly TenantDomainOperation[],
277
+ ): Promise<{ steps: TenantDomainStep[]; limit: number | null } | { problems: TenantDomainProblem[] }> {
278
+ const domains = domainsOf(await deps.port.rows(ctx.tenantId));
279
+ const holders = await deps.port.holders(claimableNames(operations, domains));
280
+ const entitled = operations.some((operation) => operation.operation === 'verify')
281
+ ? await deps.quota.mayVerify(ctx.tenantId, ctx.via)
282
+ : true;
283
+ const takenElsewhere = new Set(
284
+ holders.filter((holder) => holder.tenantId !== ctx.tenantId).map((holder) => holder.hostname),
285
+ );
286
+ const { steps, problems } = planDomainOperations({ operations, domains, takenElsewhere, entitled });
287
+ if (problems.length > 0) return { problems };
288
+ const units = unitsOf(steps);
289
+ if (units === 0) return { steps, limit: null };
290
+ const reserved = await deps.quota.reserve(ctx.tenantId, units, ctx.via);
291
+ return 'refused' in reserved ? { problems: quotaProblems(steps, reserved.refused) } : { steps, limit: reserved.limit };
292
+ }
293
+
294
+ export function createTenantDomains<Tx>(config: TenantDomainsConfig<Tx>): TenantDomains {
295
+ if (!isBag(config)) throw new TenantConfigError('config', 'is required and missing');
296
+ validateDomainPorts(config as unknown as Bag, '');
297
+ requireMembers((config as unknown as Bag).dns, 'dns', ['targets', 'ownsRecord', 'pointsHere']);
298
+ const deps: EngineDeps<Tx> = { port: config.port, quota: config.quota, dns: config.dns, writers: writersOf(config.port) };
299
+ return {
300
+ run: async (ctx, body) => {
301
+ const { operations } = body;
302
+ const plan = await planned(deps, ctx, operations);
303
+ if ('problems' in plan) return { ok: false, problems: plan.problems };
304
+ if (body.validateOnly === true) return answer(deps, ctx.tenantId, operations, plan.steps.map(previewOf), true);
305
+ const done = await commit(deps, ctx, plan.steps, plan.limit);
306
+ return 'problems' in done ? { ok: false, problems: done.problems } : answer(deps, ctx.tenantId, operations, done.applied, false);
307
+ },
308
+ };
309
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Hostname grammar for a tenant's custom domain: lowercase labels, at least
3
+ * one dot, no scheme, no path, no port, no trailing dot, no wildcard.
4
+ *
5
+ * Deliberately strict: this string is concatenated into DNS lookups and
6
+ * compared against a TLS SNI value, so anything exotic is rejected at the door
7
+ * rather than normalised into something surprising.
8
+ */
9
+ const HOSTNAME_RE = /^(?=.{4,253}$)[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$/;
10
+
11
+ /** What a person pastes (case, a scheme, a path, a trailing dot) reduced to the bare name. */
12
+ function stripped(raw: string): string {
13
+ const noScheme = raw
14
+ .trim()
15
+ .toLowerCase()
16
+ .replace(/^https?:\/\//, '');
17
+ // Everything from the first slash on is a path. A cut, not a `/\/.*$/`
18
+ // replace, which backtracks polynomially on a run of slashes (CodeQL).
19
+ const slash = noScheme.indexOf('/');
20
+ const host = slash === -1 ? noScheme : noScheme.slice(0, slash);
21
+ return host.replace(/\.$/, '');
22
+ }
23
+
24
+ /** The input reduced to the stored hostname, or null when it is not one. */
25
+ export function hostnameOrNull(raw: string): string | null {
26
+ const host = stripped(raw);
27
+ return HOSTNAME_RE.test(host) ? host : null;
28
+ }
29
+
30
+ /**
31
+ * The hostname a draft in a form would claim, or null: the server's own
32
+ * reading (scheme, path and case dropped), with a looser grammar, because it
33
+ * only decides whether a preview of the claim is worth showing.
34
+ */
35
+ export function draftHostname(raw: string): string | null {
36
+ const host = stripped(raw);
37
+ return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(host) ? host : null;
38
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * `@12-apps/tenant/domains`: the browser-safe half of custom domains. Pure
3
+ * functions and types only (no Node module, no dependency), so a screen, a
4
+ * shared host package and the server import the same file.
5
+ *
6
+ * The server half (the ports, the DNS checks, the engine, the TLS ask) is in
7
+ * `@12-apps/tenant` and `@12-apps/tenant/server`; the screen in
8
+ * `@12-apps/tenant/domains/react`. Adoption: ADOPTING.md, "Custom domains".
9
+ */
10
+ export { draftHostname, hostnameOrNull } from './hostname';
11
+ export {
12
+ createDomainDns,
13
+ dnsZoneOf,
14
+ isZoneApex,
15
+ pointingRecordType,
16
+ relativeDnsName,
17
+ wwwCompanionOf,
18
+ type DnsRecordSpec,
19
+ type PointingRecordType,
20
+ type TenantDomainDns,
21
+ type TenantDomainDnsRecords,
22
+ } from './dns-names';
23
+ export {
24
+ canonicalHostOf,
25
+ domainOf,
26
+ domainsOf,
27
+ pairRedirectOf,
28
+ principalHostOf,
29
+ type TenantDomainName,
30
+ type TenantDomainRecord,
31
+ type TenantDomainRow,
32
+ type TenantDomainStatus,
33
+ } from './record';
34
+ export {
35
+ claimOf,
36
+ claimableNames,
37
+ guardedOf,
38
+ namesOf,
39
+ planDomainOperations,
40
+ unitsOf,
41
+ type TenantDomainOperation,
42
+ type TenantDomainProblem,
43
+ type TenantDomainProblemKind,
44
+ type TenantDomainStep,
45
+ } from './plan';
@@ -0,0 +1,273 @@
1
+ /**
2
+ * The CHECK pass of the domain operations: every operation is read against
3
+ * the tenant's domains and every other tenant's live names, and turned into
4
+ * the step it will take, or a named problem. Pure: nothing is read, written or
5
+ * asked of DNS here; the engine (`./engine.ts`) reads what this needs first.
6
+ *
7
+ * Problems are KINDS, never sentences or wire codes: the host maps each kind
8
+ * to its own code and its own words.
9
+ */
10
+ import { isZoneApex, wwwCompanionOf } from './dns-names';
11
+ import { hostnameOrNull } from './hostname';
12
+ import type { TenantDomainRecord } from './record';
13
+
14
+ /** One operation on a tenant's domains. A removal and a restore may carry a reason. */
15
+ export type TenantDomainOperation =
16
+ | { operation: 'add'; hostname: string; principal?: 'root' | 'www' }
17
+ | { operation: 'verify'; id?: string; hostname?: string }
18
+ | { operation: 'setPrincipal'; id?: string; hostname?: string; principal: 'root' | 'www' }
19
+ | { operation: 'archive' | 'restore'; id?: string; hostname?: string; reason?: string };
20
+
21
+ export type TenantDomainProblemKind =
22
+ | 'invalidHostname'
23
+ | 'nameTaken'
24
+ | 'nameHeldHere'
25
+ | 'planLimit'
26
+ | 'planRequired'
27
+ | 'notFound'
28
+ | 'notAPair'
29
+ | 'nameNotFree'
30
+ | 'removed'
31
+ | 'duplicateTarget'
32
+ | 'retry';
33
+
34
+ /**
35
+ * One refused operation (`index`), or the call as a whole (`index: null`, a
36
+ * race found in the transaction). `hostname` is the name the problem is about;
37
+ * `input` is what was typed, for `invalidHostname`.
38
+ */
39
+ export interface TenantDomainProblem {
40
+ index: number | null;
41
+ kind: TenantDomainProblemKind;
42
+ hostname: string | null;
43
+ input?: string;
44
+ }
45
+
46
+ /** What one checked operation will do. */
47
+ export type TenantDomainStep =
48
+ | { index: number; kind: 'add'; hostname: string; names: string[]; principal: 'root' | 'www' }
49
+ | { index: number; kind: 'noop'; domain: TenantDomainRecord }
50
+ | { index: number; kind: 'principal'; domain: TenantDomainRecord; principal: 'root' | 'www' }
51
+ | { index: number; kind: 'verify'; domain: TenantDomainRecord }
52
+ | { index: number; kind: 'archive'; domain: TenantDomainRecord; reason: string | null }
53
+ | { index: number; kind: 'restore'; domain: TenantDomainRecord; reason: string | null };
54
+
55
+ type AddOperation = Extract<TenantDomainOperation, { operation: 'add' }>;
56
+ type TargetOperation = Exclude<TenantDomainOperation, { operation: 'add' }>;
57
+
58
+ const isLive = (domain: TenantDomainRecord) => domain.archivedAt === null;
59
+
60
+ /** Every name a domain answers on, root first. */
61
+ export const namesOf = (domain: TenantDomainRecord): string[] => domain.names.map((name) => name.hostname);
62
+
63
+ /** The names a claim takes: the root and its `www.`, or the one subdomain. */
64
+ export function claimOf(host: string): string[] {
65
+ const www = wwwCompanionOf(host);
66
+ return www === null ? [host] : [host, www];
67
+ }
68
+
69
+ /**
70
+ * The names a claim must find free in OTHER tenants: its own, and, for a `www.`
71
+ * of a root domain, that root, whose `www.` belongs to whoever holds it (a root
72
+ * claimed before the pair existed has no `www.` row of its own).
73
+ */
74
+ export function guardedOf(host: string): string[] {
75
+ const parent = host.startsWith('www.') ? host.slice(4) : null;
76
+ return parent !== null && isZoneApex(parent) ? [...claimOf(host), parent] : claimOf(host);
77
+ }
78
+
79
+ /** The tenant's domain an operation names: by id, or by either name (a live one first; for a restore, the latest removed). */
80
+ function targetOf(domains: readonly TenantDomainRecord[], operation: TargetOperation): TenantDomainRecord | null {
81
+ if (operation.id !== undefined) return domains.find((domain) => domain.id === operation.id) ?? null;
82
+ const host = hostnameOrNull(operation.hostname ?? '');
83
+ if (host === null) return null;
84
+ const matching = domains.filter((domain) => namesOf(domain).includes(host));
85
+ const removed = matching
86
+ .filter((domain) => !isLive(domain))
87
+ .sort((a, b) => (b.archivedAt?.getTime() ?? 0) - (a.archivedAt?.getTime() ?? 0));
88
+ const live = matching.filter(isLive);
89
+ return (operation.operation === 'restore' ? (removed[0] ?? live[0]) : (live[0] ?? removed[0])) ?? null;
90
+ }
91
+
92
+ interface Planner {
93
+ domains: TenantDomainRecord[];
94
+ /** Live names held by OTHER tenants, among the names this call claims. */
95
+ takenElsewhere: Set<string>;
96
+ claimed: Set<string>;
97
+ targeted: Set<string>;
98
+ /** Domains a restore of this call targeted, whose one `verify` may follow (consumed by it). */
99
+ restored: Set<string>;
100
+ /**
101
+ * Live and ACTIVE domains a restore of this call found already back. The
102
+ * verify that follows is answered `unchanged`: a stale restore must never
103
+ * re-check, and so possibly take down, a domain that is serving.
104
+ */
105
+ servingAlready: Set<string>;
106
+ problems: TenantDomainProblem[];
107
+ steps: TenantDomainStep[];
108
+ entitled: boolean;
109
+ }
110
+
111
+ const fail = (planner: Planner, index: number, kind: TenantDomainProblemKind, hostname: string | null): void => {
112
+ planner.problems.push({ index, kind, hostname });
113
+ };
114
+
115
+ /** A name this tenant holds on a live domain. */
116
+ const heldHere = (planner: Planner, name: string) =>
117
+ planner.domains.some((domain) => isLive(domain) && namesOf(domain).includes(name));
118
+
119
+ /** The step of an add whose name the tenant already holds: unchanged, or the principal it asks for. */
120
+ function ownAdd(planner: Planner, index: number, own: TenantDomainRecord, principal: AddOperation['principal']): void {
121
+ if (planner.targeted.has(own.id)) return fail(planner, index, 'duplicateTarget', own.hostname);
122
+ planner.targeted.add(own.id);
123
+ const changes = principal !== undefined && principal !== own.principal && own.wwwHostname !== null;
124
+ planner.steps.push(changes ? { index, kind: 'principal', domain: own, principal } : { index, kind: 'noop', domain: own });
125
+ }
126
+
127
+ /** Why a new claim of `names` is refused, or null: twice in this call, another domain of this tenant, another tenant. */
128
+ function claimProblem(
129
+ planner: Planner,
130
+ host: string,
131
+ names: readonly string[],
132
+ ): { kind: 'duplicateTarget' | 'nameHeldHere' | 'nameTaken'; name: string } | null {
133
+ const twice = names.find((name) => planner.claimed.has(name));
134
+ if (twice !== undefined) return { kind: 'duplicateTarget', name: twice };
135
+ const mine = names.find((name) => heldHere(planner, name));
136
+ if (mine !== undefined) return { kind: 'nameHeldHere', name: mine };
137
+ const taken = guardedOf(host).find((name) => planner.takenElsewhere.has(name));
138
+ return taken === undefined ? null : { kind: 'nameTaken', name: taken };
139
+ }
140
+
141
+ function planAdd(planner: Planner, index: number, operation: AddOperation): void {
142
+ const host = hostnameOrNull(operation.hostname);
143
+ if (host === null) {
144
+ planner.problems.push({ index, kind: 'invalidHostname', hostname: null, input: operation.hostname });
145
+ return;
146
+ }
147
+ const names = claimOf(host);
148
+ if (operation.principal === 'www' && names.length === 1) return fail(planner, index, 'notAPair', host);
149
+ // Idempotent on the name: the tenant's own live domain answering on it is answered as it is.
150
+ const own = planner.domains.find((domain) => isLive(domain) && (domain.hostname === host || domain.wwwHostname === host));
151
+ if (own !== undefined) return ownAdd(planner, index, own, operation.principal);
152
+ const refused = claimProblem(planner, host, names);
153
+ if (refused !== null) return fail(planner, index, refused.kind, refused.name);
154
+ names.forEach((name) => planner.claimed.add(name));
155
+ planner.steps.push({ index, kind: 'add', hostname: host, names, principal: operation.principal ?? 'root' });
156
+ }
157
+
158
+ type TargetPlan = (planner: Planner, index: number, domain: TenantDomainRecord, operation: TargetOperation) => void;
159
+
160
+ /** An act only a live domain takes, or, for a `verify`, one this call restores before it. */
161
+ const liveOnly =
162
+ (then: TargetPlan): TargetPlan =>
163
+ (planner, index, domain, operation) =>
164
+ isLive(domain) || (operation.operation === 'verify' && planner.restored.has(domain.id))
165
+ ? then(planner, index, domain, operation)
166
+ : fail(planner, index, 'removed', domain.hostname);
167
+
168
+ const reasonOf = (operation: TargetOperation): string | null =>
169
+ 'reason' in operation ? (operation.reason ?? null) : null;
170
+
171
+ /** A restore takes its names back only while every one is still free, of every tenant, this one included. */
172
+ function busyNameOf(planner: Planner, domain: TenantDomainRecord): string | undefined {
173
+ return namesOf(domain)
174
+ .flatMap((name) => guardedOf(name).map((guarded) => ({ name, guarded })))
175
+ .find(
176
+ ({ name, guarded }) =>
177
+ planner.takenElsewhere.has(guarded) || heldHere(planner, name) || planner.claimed.has(name),
178
+ )?.guarded;
179
+ }
180
+
181
+ const TARGET_PLANS: Record<TargetOperation['operation'], TargetPlan> = {
182
+ verify: liveOnly((planner, index, domain) => {
183
+ if (planner.servingAlready.has(domain.id)) return void planner.steps.push({ index, kind: 'noop', domain });
184
+ return planner.entitled
185
+ ? void planner.steps.push({ index, kind: 'verify', domain })
186
+ : fail(planner, index, 'planRequired', domain.hostname);
187
+ }),
188
+ setPrincipal: liveOnly((planner, index, domain, operation) => {
189
+ if (domain.wwwHostname === null) return fail(planner, index, 'notAPair', domain.hostname);
190
+ const principal = (operation as Extract<TargetOperation, { operation: 'setPrincipal' }>).principal;
191
+ planner.steps.push(
192
+ domain.principal === principal ? { index, kind: 'noop', domain } : { index, kind: 'principal', domain, principal },
193
+ );
194
+ }),
195
+ archive: (planner, index, domain, operation) => {
196
+ planner.steps.push(
197
+ isLive(domain) ? { index, kind: 'archive', domain, reason: reasonOf(operation) } : { index, kind: 'noop', domain },
198
+ );
199
+ },
200
+ restore: (planner, index, domain, operation) => {
201
+ // Its verify may follow whatever this restore answers: `unchanged` on a live domain (a stale
202
+ // removed list, another tab), or a refusal that is the call's one real problem.
203
+ planner.restored.add(domain.id);
204
+ if (isLive(domain) && domain.status === 'ACTIVE') planner.servingAlready.add(domain.id);
205
+ if (isLive(domain)) return void planner.steps.push({ index, kind: 'noop', domain });
206
+ const busy = busyNameOf(planner, domain);
207
+ if (busy !== undefined) return fail(planner, index, 'nameNotFree', busy);
208
+ namesOf(domain).forEach((name) => planner.claimed.add(name));
209
+ planner.steps.push({ index, kind: 'restore', domain, reason: reasonOf(operation) });
210
+ },
211
+ };
212
+
213
+ function planTargeted(planner: Planner, index: number, operation: TargetOperation): void {
214
+ const domain = targetOf(planner.domains, operation);
215
+ if (domain === null) return fail(planner, index, 'notFound', operation.hostname ?? null);
216
+ // One entry per domain, but for the `verify` that may follow its `restore` (a restore button sends both).
217
+ const verifiesRestored = operation.operation === 'verify' && planner.restored.has(domain.id);
218
+ if (planner.targeted.has(domain.id) && !verifiesRestored) return fail(planner, index, 'duplicateTarget', domain.hostname);
219
+ planner.targeted.add(domain.id);
220
+ TARGET_PLANS[operation.operation](planner, index, domain, operation);
221
+ if (verifiesRestored) planner.restored.delete(domain.id);
222
+ }
223
+
224
+ /** Every name the call may claim (adds' and restores'), to ask who else holds it in ONE read. */
225
+ export function claimableNames(
226
+ operations: readonly TenantDomainOperation[],
227
+ domains: readonly TenantDomainRecord[],
228
+ ): string[] {
229
+ return operations.flatMap((operation) => {
230
+ if (operation.operation === 'add') {
231
+ const host = hostnameOrNull(operation.hostname);
232
+ return host === null ? [] : guardedOf(host);
233
+ }
234
+ const domain = operation.operation === 'restore' ? targetOf(domains, operation) : null;
235
+ return domain === null ? [] : namesOf(domain).flatMap((name) => guardedOf(name));
236
+ });
237
+ }
238
+
239
+ /** How many quota units the steps take: one per new claim and per restore. */
240
+ export const unitsOf = (steps: readonly TenantDomainStep[]): number =>
241
+ steps.filter((step) => step.kind === 'add' || step.kind === 'restore').length;
242
+
243
+ /** The names the steps claim: a new claim's and a restore's. */
244
+ export const claimsOf = (steps: readonly TenantDomainStep[]): string[] =>
245
+ steps.flatMap((step) => (step.kind === 'add' ? step.names : step.kind === 'restore' ? namesOf(step.domain) : []));
246
+
247
+ /**
248
+ * Check every operation; nothing is written. The steps in call order, or every
249
+ * problem. `takenElsewhere` is the live names OTHER tenants hold among
250
+ * {@link claimableNames}; `entitled` whether a `verify` may run at all.
251
+ */
252
+ export function planDomainOperations(input: {
253
+ operations: readonly TenantDomainOperation[];
254
+ domains: TenantDomainRecord[];
255
+ takenElsewhere: ReadonlySet<string>;
256
+ entitled: boolean;
257
+ }): { steps: TenantDomainStep[]; problems: TenantDomainProblem[] } {
258
+ const planner: Planner = {
259
+ domains: input.domains,
260
+ takenElsewhere: new Set(input.takenElsewhere),
261
+ claimed: new Set(),
262
+ targeted: new Set(),
263
+ restored: new Set(),
264
+ servingAlready: new Set(),
265
+ problems: [],
266
+ steps: [],
267
+ entitled: input.entitled,
268
+ };
269
+ input.operations.forEach((operation, index) =>
270
+ operation.operation === 'add' ? planAdd(planner, index, operation) : planTargeted(planner, index, operation),
271
+ );
272
+ return planner.problems.length > 0 ? { steps: [], problems: planner.problems } : { steps: planner.steps, problems: [] };
273
+ }