@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,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE DNS RECORDS a tenant publishes for its custom domain: one module for the
|
|
3
|
+
* screen that shows them and the server read that hands them to an agent, so
|
|
4
|
+
* what a person sees and what an agent is told cannot drift. Constants and
|
|
5
|
+
* pure functions only: no copy, no React, no Node, so a browser bundle and a
|
|
6
|
+
* server import the same file.
|
|
7
|
+
*
|
|
8
|
+
* The NAME a person types into their DNS provider is RELATIVE to the zone.
|
|
9
|
+
* Providers do not ask for a fully qualified name: they show a host-name field
|
|
10
|
+
* with the zone already printed after it, so pasting the full
|
|
11
|
+
* `_verify.acme.com.br` there creates `_verify.acme.com.br.acme.com.br`, which
|
|
12
|
+
* never verifies. They want the part BEFORE the zone, and `@` (or nothing) for
|
|
13
|
+
* the zone itself.
|
|
14
|
+
*
|
|
15
|
+
* Finding the zone needs the public suffix: `acme.com.br` is a zone (`com.br`
|
|
16
|
+
* is the suffix) while `shop.acme.com` is a subdomain of `acme.com`. The full
|
|
17
|
+
* Public Suffix List is a dependency for one card, so this is a deliberate
|
|
18
|
+
* heuristic: every second level the list has under `.br`, plus the common
|
|
19
|
+
* ones under other two-letter country TLDs (`co.uk` and its kind). A name it
|
|
20
|
+
* gets wrong still has its full form beside it (`fqdn`), so a miss costs a
|
|
21
|
+
* read, not a dead domain.
|
|
22
|
+
*
|
|
23
|
+
* THE PAIR. A zone apex is claimed with its `www.` as ONE domain: one TXT
|
|
24
|
+
* record at the root proves both, and BOTH names point here. A subdomain stays
|
|
25
|
+
* one name.
|
|
26
|
+
*
|
|
27
|
+
* The TXT record's label (the prefix) is the host's: `createDomainDns` takes it
|
|
28
|
+
* as config and refuses anything that is not one DNS label.
|
|
29
|
+
*/
|
|
30
|
+
import { TenantConfigError } from '../validate';
|
|
31
|
+
|
|
32
|
+
/** Second-level labels that, under a two-letter TLD other than `.br`, are part of the suffix. */
|
|
33
|
+
const SECOND_LEVEL_SUFFIXES = new Set(['com', 'net', 'org', 'edu', 'gov', 'co', 'ac', 'ltd', 'plc']);
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Every second level under `.br` (the Public Suffix List's `br` section: the
|
|
37
|
+
* categories, the states and the cities). A miss here names the A record
|
|
38
|
+
* wrongly: `acme.rec.br` read as the subdomain `acme` of `rec.br`.
|
|
39
|
+
*/
|
|
40
|
+
const BR_SECOND_LEVELS = new Set([
|
|
41
|
+
'9guacu', 'abc', 'adm', 'adv', 'agr', 'aju', 'am', 'anani', 'aparecida', 'app', 'arq', 'art',
|
|
42
|
+
'ato', 'b', 'barueri', 'belem', 'bhz', 'bib', 'bio', 'blog', 'bmd', 'boavista', 'bsb',
|
|
43
|
+
'campinagrande', 'campinas', 'caxias', 'cim', 'cng', 'cnt', 'com', 'contagem', 'coop', 'coz',
|
|
44
|
+
'cri', 'cuiaba', 'curitiba', 'def', 'des', 'det', 'dev', 'ecn', 'eco', 'edu', 'emp', 'enf',
|
|
45
|
+
'eng', 'esp', 'etc', 'eti', 'far', 'feira', 'flog', 'floripa', 'fm', 'fnd', 'fortal', 'fot',
|
|
46
|
+
'foz', 'fst', 'g12', 'geo', 'ggf', 'goiania', 'gov', 'gru', 'imb', 'ind', 'inf', 'jab', 'jampa',
|
|
47
|
+
'jdf', 'joinville', 'jor', 'jus', 'leg', 'leilao', 'lel', 'log', 'londrina', 'macapa', 'maceio',
|
|
48
|
+
'manaus', 'maringa', 'mat', 'med', 'mil', 'morena', 'mp', 'mus', 'natal', 'net', 'niteroi',
|
|
49
|
+
'nom', 'not', 'ntr', 'odo', 'ong', 'org', 'osasco', 'palmas', 'poa', 'ppg', 'pro', 'psc', 'psi',
|
|
50
|
+
'pvh', 'qsl', 'radio', 'rec', 'recife', 'rep', 'ribeirao', 'rio', 'riobranco', 'riopreto',
|
|
51
|
+
'salvador', 'sampa', 'santamaria', 'santoandre', 'saobernardo', 'saogonca', 'seg', 'sjc', 'slg',
|
|
52
|
+
'slz', 'sorocaba', 'srv', 'taxi', 'tc', 'tec', 'teo', 'the', 'tmp', 'trd', 'tur', 'tv', 'udi',
|
|
53
|
+
'vet', 'vix', 'vlog', 'wiki', 'zlg', 'ac', 'al', 'ap', 'ba', 'ce', 'df', 'es', 'go', 'ma', 'mg',
|
|
54
|
+
'ms', 'mt', 'pa', 'pb', 'pe', 'pi', 'pr', 'rj', 'rn', 'ro', 'rr', 'rs', 'sc', 'se', 'sp', 'to',
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
/** How many trailing labels of `labels` are the public suffix. */
|
|
58
|
+
function suffixLength(labels: readonly string[]): number {
|
|
59
|
+
if (labels.length < 3) return 1;
|
|
60
|
+
const tld = labels[labels.length - 1] ?? '';
|
|
61
|
+
const second = labels[labels.length - 2] ?? '';
|
|
62
|
+
if (tld === 'br') return BR_SECOND_LEVELS.has(second) ? 2 : 1;
|
|
63
|
+
return tld.length === 2 && SECOND_LEVEL_SUFFIXES.has(second) ? 2 : 1;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The zone a hostname lives in: `shop.acme.com.br` → `acme.com.br`. */
|
|
67
|
+
export function dnsZoneOf(hostname: string): string {
|
|
68
|
+
const labels = hostname.toLowerCase().replace(/\.$/, '').split('.');
|
|
69
|
+
return labels.slice(-(suffixLength(labels) + 1)).join('.');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** True when the hostname IS its zone (`acme.com.br`), not a subdomain of it. */
|
|
73
|
+
export function isZoneApex(hostname: string): boolean {
|
|
74
|
+
return dnsZoneOf(hostname) === hostname.toLowerCase().replace(/\.$/, '');
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The provider's host-name field for `fqdn` inside `hostname`'s zone: `@` for
|
|
79
|
+
* the zone itself, otherwise the labels before it
|
|
80
|
+
* (`_verify.shop.acme.com.br` → `_verify.shop`).
|
|
81
|
+
*/
|
|
82
|
+
export function relativeDnsName(fqdn: string, hostname: string): string {
|
|
83
|
+
// A row that reached the screen without its record name renders an empty
|
|
84
|
+
// field rather than taking the whole page down.
|
|
85
|
+
if (!fqdn || !hostname) return '';
|
|
86
|
+
const name = fqdn.toLowerCase().replace(/\.$/, '');
|
|
87
|
+
const zone = dnsZoneOf(hostname);
|
|
88
|
+
if (name === zone) return '@';
|
|
89
|
+
return name.endsWith(`.${zone}`) ? name.slice(0, -(zone.length + 1)) : name;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The `www.` a root claim registers beside it, or null for a subdomain claim,
|
|
94
|
+
* which stays one name. A hostname that already starts with `www.` is a
|
|
95
|
+
* subdomain of its zone, so it is never doubled.
|
|
96
|
+
*/
|
|
97
|
+
export function wwwCompanionOf(hostname: string): string | null {
|
|
98
|
+
const host = hostname.toLowerCase().replace(/\.$/, '');
|
|
99
|
+
return isZoneApex(host) ? `www.${host}` : null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The DNS record type that carries a target: AAAA for IPv6, A for IPv4, CNAME for a hostname. */
|
|
103
|
+
export type PointingRecordType = 'A' | 'AAAA' | 'CNAME';
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Which record a target goes into. An IPv6 address pasted into an A record is
|
|
107
|
+
* refused by every registrar, so a dual-stacked deploy has to say which of its
|
|
108
|
+
* addresses is which. Any colon means IPv6: no IPv4 address or hostname
|
|
109
|
+
* contains one.
|
|
110
|
+
*/
|
|
111
|
+
export function pointingRecordType(target: string): PointingRecordType {
|
|
112
|
+
if (target.includes(':')) return 'AAAA';
|
|
113
|
+
return /^\d{1,3}(\.\d{1,3}){3}$/.test(target) ? 'A' : 'CNAME';
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** One record as a provider's form asks for it. */
|
|
117
|
+
export interface DnsRecordSpec {
|
|
118
|
+
type: 'TXT' | PointingRecordType;
|
|
119
|
+
/** Relative to the zone: `@`, `www`, `shop`, the TXT prefix. */
|
|
120
|
+
name: string;
|
|
121
|
+
/** The same name, fully qualified, for a provider that asks for it. */
|
|
122
|
+
fqdn: string;
|
|
123
|
+
/** One record per value (a TXT has one; a deploy may have several IPs). */
|
|
124
|
+
values: string[];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Everything a tenant publishes for one domain. */
|
|
128
|
+
export interface TenantDomainDns {
|
|
129
|
+
zone: string;
|
|
130
|
+
/** `apex`: the root + `www` pair; `subdomain`: one name. */
|
|
131
|
+
kind: 'apex' | 'subdomain';
|
|
132
|
+
/** The names the domain answers on: the root and its `www.`, or the one subdomain. */
|
|
133
|
+
hostnames: string[];
|
|
134
|
+
/** The ownership TXT record, at the root for a pair (it proves both names). */
|
|
135
|
+
verification: DnsRecordSpec;
|
|
136
|
+
/**
|
|
137
|
+
* Where each name points: one record per name and record type, in the
|
|
138
|
+
* deploy's target order. Empty when the deploy does not know its address.
|
|
139
|
+
*/
|
|
140
|
+
pointing: DnsRecordSpec[];
|
|
141
|
+
/**
|
|
142
|
+
* The relative names whose OTHER pointing records must be deleted: an old
|
|
143
|
+
* site's A/AAAA (and a subdomain's CNAME) keep answering beside ours.
|
|
144
|
+
*/
|
|
145
|
+
replaceRecordsNamed: string[];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The DNS records of one domain, under the host's TXT prefix. */
|
|
149
|
+
export interface TenantDomainDnsRecords {
|
|
150
|
+
/** The validated prefix, as given. */
|
|
151
|
+
readonly recordPrefix: string;
|
|
152
|
+
/** The FQDN the ownership TXT record lives at: one per domain, at the root for a pair. */
|
|
153
|
+
verificationRecordName(hostname: string): string;
|
|
154
|
+
/**
|
|
155
|
+
* The records for a domain: `hostname` is the claimed name (the ROOT of a
|
|
156
|
+
* pair), `wwwHostname` its companion or null, `verificationToken` the TXT value.
|
|
157
|
+
*/
|
|
158
|
+
recordsOf(
|
|
159
|
+
domain: { hostname: string; wwwHostname: string | null; verificationToken: string },
|
|
160
|
+
dnsTargets: readonly string[],
|
|
161
|
+
): TenantDomainDns;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** One DNS label, an underscore allowed in front (`_verify`), as a TXT record's owner name takes it. */
|
|
165
|
+
const RECORD_PREFIX_RE = /^_?[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
|
166
|
+
|
|
167
|
+
/** The TXT prefix, checked. Throws {@link TenantConfigError} under `key`. */
|
|
168
|
+
export function validateRecordPrefix(value: unknown, key: string): string {
|
|
169
|
+
if (value === undefined || value === null) throw new TenantConfigError(key, 'is required and missing');
|
|
170
|
+
if (typeof value !== 'string' || !RECORD_PREFIX_RE.test(value) || value.length > 63) {
|
|
171
|
+
throw new TenantConfigError(key, 'must be one lowercase DNS label (letters, digits, "-", an optional leading "_")');
|
|
172
|
+
}
|
|
173
|
+
return value;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** One record per type for `fqdn`, in the deploy's order: an A with its IPv4s, an AAAA with its IPv6s. */
|
|
177
|
+
function pointingFor(fqdn: string, zoneHost: string, dnsTargets: readonly string[]): DnsRecordSpec[] {
|
|
178
|
+
const types = dnsTargets.map(pointingRecordType);
|
|
179
|
+
return [...new Set(types)].map((type) => ({
|
|
180
|
+
type,
|
|
181
|
+
name: relativeDnsName(fqdn, zoneHost),
|
|
182
|
+
fqdn,
|
|
183
|
+
values: dnsTargets.filter((_, at) => types[at] === type),
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The record builder under the host's TXT prefix (`{ recordPrefix }`, required, one DNS label). */
|
|
188
|
+
export function createDomainDns(config: { recordPrefix: string }): TenantDomainDnsRecords {
|
|
189
|
+
if (config === null || typeof config !== 'object') {
|
|
190
|
+
throw new TenantConfigError('recordPrefix', 'is required and missing');
|
|
191
|
+
}
|
|
192
|
+
const recordPrefix = validateRecordPrefix((config as { recordPrefix?: unknown }).recordPrefix, 'recordPrefix');
|
|
193
|
+
const verificationRecordName = (hostname: string): string => `${recordPrefix}.${hostname}`;
|
|
194
|
+
return {
|
|
195
|
+
recordPrefix,
|
|
196
|
+
verificationRecordName,
|
|
197
|
+
recordsOf: (domain, dnsTargets) => {
|
|
198
|
+
const hostnames = domain.wwwHostname === null ? [domain.hostname] : [domain.hostname, domain.wwwHostname];
|
|
199
|
+
const txt = verificationRecordName(domain.hostname);
|
|
200
|
+
return {
|
|
201
|
+
zone: dnsZoneOf(domain.hostname),
|
|
202
|
+
kind: domain.wwwHostname === null ? 'subdomain' : 'apex',
|
|
203
|
+
hostnames,
|
|
204
|
+
verification: {
|
|
205
|
+
type: 'TXT',
|
|
206
|
+
name: relativeDnsName(txt, domain.hostname),
|
|
207
|
+
fqdn: txt,
|
|
208
|
+
values: [domain.verificationToken],
|
|
209
|
+
},
|
|
210
|
+
pointing: hostnames.flatMap((host) => pointingFor(host, domain.hostname, dnsTargets)),
|
|
211
|
+
replaceRecordsNamed: hostnames.map((host) => relativeDnsName(host, domain.hostname)),
|
|
212
|
+
};
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
}
|
|
@@ -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';
|