@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.
package/ADOPTING.md CHANGED
@@ -356,6 +356,100 @@ the old table (during a rolling deploy) are not in `tenant_closings`: before
356
356
  each sweep, catch them up with one upsert (`INSERT … SELECT … ON CONFLICT
357
357
  (tenant_id) DO UPDATE`), and backfill once with a data-only migration.
358
358
 
359
+ ### Custom domains (opt-in)
360
+
361
+ A tenant claims a hostname, proves it owns the zone with a TXT record, points
362
+ the name here, and is then served on it, with a certificate the TLS ask
363
+ allows. **Optional**, like the tree and slugs: a host that passes no `domains`
364
+ boots unchanged and gets no `tenant.domains`. Nothing is added to the tenant
365
+ port, and **the domain table stays yours**: the package maps no table, names
366
+ no column and ships no migration.
367
+
368
+ ```ts
369
+ import { createApiTenant } from '@12-apps/tenant/server';
370
+ import { resolveTxt, resolve4, resolve6 } from 'node:dns/promises';
371
+
372
+ const tenant = createApiTenant({
373
+ ...config,
374
+ port,
375
+ domains: {
376
+ port: domainPort, // TenantDomainPort<Tx>: your rows, every member required
377
+ quota: domainQuota, // TenantDomainQuota<Tx>: your plan
378
+ dns: {
379
+ // YOUR resolver, as lambdas, so your tests' mock of the DNS module applies.
380
+ resolver: { txt: (n) => resolveTxt(n), ipv4: (n) => resolve4(n), ipv6: (n) => resolve6(n) },
381
+ dnsTargets: () => readTargetsFromEnv(), // read on EVERY call; [] = unknown
382
+ recordPrefix: '_yourapp-verify', // one DNS label
383
+ },
384
+ tls: {
385
+ servable: async (hostname) => …, // { tenantId } of an ACTIVE domain of a live tenant, or null
386
+ entitled: async (tenantId) => …, // the plan carries custom domains now
387
+ },
388
+ },
389
+ });
390
+ await tenant.domains?.run({ tenantId, actorId, via: 'panel' }, { operations: [{ operation: 'add', hostname: 'acme.com' }] });
391
+ await tenant.domains?.ask('acme.com'); // 'allow' | 'unknown' | 'unentitled'
392
+ ```
393
+
394
+ Every member is checked at startup, named: `domains`, `domains.port.<member>`,
395
+ `domains.quota.<member>`, `domains.dns.resolver.txt|ipv4|ipv6`,
396
+ `domains.dns.dnsTargets`, `domains.dns.recordPrefix`,
397
+ `domains.tls.servable|entitled`. A host not on `createApiTenant` yet uses the
398
+ pieces standalone, each checking its own: `createDnsChecks(dns)`,
399
+ `createTenantDomains({ port, quota, dns: checks })`, `createTlsAsk(tls)`.
400
+
401
+ - **The answer is copy-free.** `run` answers `{ ok: true, results, domains }`
402
+ (each result's `domainId` in `domains`, read once after the write) or
403
+ `{ ok: false, problems }`, each problem a KIND (`nameTaken`, `planLimit`,
404
+ `invalidHostname` with the typed `input`, …). You map each kind to your wire
405
+ code, your sentence and your status; the package makes up no id and no word.
406
+ - **The statement budget.** `rows` once and `holders` once to plan;
407
+ `mayVerify` only when the call has a verify, `reserve` only when it claims or
408
+ restores; then ONE transaction: `holders` on `tx`, `used` on `tx` when the
409
+ limit is a number, the writes in call order, an `audit` per removal and
410
+ restore; then `rows` once for the answer. A port member that adds a read is a
411
+ defect. A problem found while planning writes nothing and asks no DNS;
412
+ `validateOnly` asks no DNS either.
413
+ - **SERIALIZABLE, and `failure`.** `transaction` must run at serializable
414
+ isolation: it is what turns two concurrent claims into one winner. `failure`
415
+ classifies what the transaction threw: `'retry'` a serializable conflict
416
+ (nothing was written), `'taken'` a unique-index violation on a hostname,
417
+ `null` anything else, which the engine rethrows. Never answer `null` with a
418
+ guess.
419
+ - **The token is yours.** `claim` mints the verification token and it must be
420
+ unguessable (a random UUID or better): it is what proves ownership. A zone
421
+ apex is claimed WITH its `www.` (one domain, one token, one quota unit).
422
+ - **`archive` makes the domain unservable, not only archived**: a release that
423
+ cannot read your archive column (a rollback) must still never serve it. Set
424
+ the status your servable lookup refuses in the same write. `restore` brings
425
+ it back unverified, with the same token.
426
+ - **The resolver must be yours.** The package imports no DNS module; it calls
427
+ the three functions you pass, so a test that mocks your DNS module mocks
428
+ every lookup. Pass lambdas (`(n) => resolveTxt(n)`) rather than the
429
+ functions themselves, so a mock that leaves one out fails only the test that
430
+ calls it.
431
+ - **The TLS ask denies by default.** `ask` answers `allow` only when the name
432
+ is servable AND the tenant is entitled, so a downgrade stops renewal, not
433
+ just serving. Map `allow` to 200 and anything else to a refusal.
434
+ - **The records.** `createDomainDns({ recordPrefix })` from
435
+ `@12-apps/tenant/domains` builds what a tenant publishes (one TXT at the
436
+ root, a pointing record per name and type); import it where both the screen
437
+ and the server read it, so the prefix lives once.
438
+ - **The screen** (`@12-apps/tenant/domains/react`):
439
+ `createDomainsScreen({ copy: { locales, defaultLocale }, components: { ConfirmButton, Segmented } })`
440
+ checks every pack and both widgets at startup
441
+ (`domainsScreen.copy.locales.<tag>.records.<key>`,
442
+ `domainsScreen.components.ConfirmButton`). Each pack is
443
+ `{ records, pair, closeAlert }` (`TENANT_DOMAINS_COPY_SHAPE`): the two groups
444
+ stay apart because both say "remove" in different words. `DomainsCard`
445
+ takes this render's resolved pack and your writes (`{ writes: { errors,
446
+ isPending, dismiss }, run, remove }`, one write per domain, `remove`
447
+ rejecting with the refusal so the confirmation stays open); the test ids are
448
+ the ones a journey reads (`domains-card`, `domain-row`, `domain-verify`,
449
+ `domain-remove`, `domains-error`, `domain-restore`, …). An optional `emptyState` draws your
450
+ own empty state (keep its `domains-empty` test id) in place of the
451
+ package's, for tooling that reads your JSX, such as a search index.
452
+
359
453
  ### The schema and the migration
360
454
 
361
455
  - Copy the partial into your schema folder with
package/README.md CHANGED
@@ -35,8 +35,10 @@ data export arrive in later releases on top of the same config. How to adopt it:
35
35
 
36
36
  | Import | What | Needs |
37
37
  |---|---|---|
38
- | `@12-apps/tenant` | config types, the lifecycle's pure readings (`isTenantGone`, `sameTenantName`, `purgeAtFor`, `reminderDue`), `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`) | nothing |
39
- | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is, `tenant.lifecycle` when `lifecycle` is), `createTenantLifecycle`, `createTenantGates`, `TenantLifecycleRefusal`, and the slug resolution exports | nothing |
38
+ | `@12-apps/tenant` | config types, the lifecycle's pure readings (`isTenantGone`, `sameTenantName`, `purgeAtFor`, `reminderDue`), `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`), custom domains' server half (`createTenantDomains`, `createDnsChecks`, `createTlsAsk`, `TenantDomainPort`, `TenantDomainQuota`) | nothing |
39
+ | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is, `tenant.lifecycle` when `lifecycle` is, `tenant.domains` when `domains` is), `createTenantLifecycle`, `createTenantGates`, `TenantLifecycleRefusal`, and the slug resolution and custom domain exports | nothing |
40
+ | `@12-apps/tenant/domains` | custom domains' pure half, browser-safe: `hostnameOrNull`, `createDomainDns` (the records under your TXT prefix), the zone helpers, `domainsOf` and the record types, `canonicalHostOf`, `pairRedirectOf`, the planner | nothing |
41
+ | `@12-apps/tenant/domains/react` | `createDomainsScreen` (the domains card, every word your pack, your confirm button and segmented control injected), the records parts | `react`, `@12-apps/ui`, `@mui/icons-material` |
40
42
  | `@12-apps/tenant/hono` | `mountTenant(app, tenant)`, `mountTenantGates(app, gates)`, `tenantAdminGate`, `tenantPublicGate` | `hono` |
41
43
  | `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
42
44
  | `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
package/package.json CHANGED
@@ -1,15 +1,17 @@
1
1
  {
2
2
  "name": "@12-apps/tenant",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
- "description": "Domain-agnostic tenant behaviours: the lifecycle of a tenant (closing, reopening, the purge and the data export), configured by each host with its own status set, ids, copy packs and a required tenant port. The tenant row stays the host's: the package reads and writes it only through the port, and owns two tables of its own (tenant_closings, tenant_data_exports) keyed by an opaque tenant id with no foreign key. Backend factory (./server), Hono mount (./hono), frontend factory (./react) and the package-owned Prisma partial + migrations. Adoption contract in ADOPTING.md.",
7
+ "description": "Domain-agnostic tenant behaviours: the lifecycle of a tenant (closing, reopening, the purge and the data export), configured by each host with its own status set, ids, copy packs and a required tenant port. The tenant row stays the host's: the package reads and writes it only through the port, and owns two tables of its own (tenant_closings, tenant_data_exports) keyed by an opaque tenant id with no foreign key. Custom domains as an opt-in port (the engine in . and ./server, the pure half in ./domains, the screen in ./domains/react). Backend factory (./server), Hono mount (./hono), frontend factory (./react) and the package-owned Prisma partial + migrations. Adoption contract in ADOPTING.md.",
8
8
  "exports": {
9
9
  ".": "./src/index.ts",
10
10
  "./server": "./src/server/index.ts",
11
11
  "./hono": "./src/hono/index.ts",
12
12
  "./react": "./src/react/index.ts",
13
+ "./domains": "./src/domains/index.ts",
14
+ "./domains/react": "./src/domains/react/index.ts",
13
15
  "./manifest": "./src/manifest/index.ts",
14
16
  "./package.json": "./package.json"
15
17
  },
@@ -24,26 +26,47 @@
24
26
  "clean": "rm -rf node_modules coverage dist"
25
27
  },
26
28
  "peerDependencies": {
29
+ "@12-apps/ui": ">=6.119.0",
27
30
  "@12-apps/wiring": ">=1.3.0",
28
- "hono": ">=4.0.0"
31
+ "@mui/icons-material": ">=6.0.0",
32
+ "hono": ">=4.0.0",
33
+ "react": ">=19.0.0"
29
34
  },
30
35
  "peerDependenciesMeta": {
36
+ "@12-apps/ui": {
37
+ "optional": true
38
+ },
31
39
  "@12-apps/wiring": {
32
40
  "optional": true
33
41
  },
42
+ "@mui/icons-material": {
43
+ "optional": true
44
+ },
34
45
  "hono": {
35
46
  "optional": true
47
+ },
48
+ "react": {
49
+ "optional": true
36
50
  }
37
51
  },
38
52
  "devDependencies": {
39
53
  "@12-apps/eslint-config": "^1.22.0",
40
54
  "@12-apps/typescript-config": "^1.21.0",
55
+ "@12-apps/ui": "^6.121.0",
41
56
  "@12-apps/wiring": "^1.17.0",
42
57
  "@electric-sql/pglite": "^0.2.17",
58
+ "@mui/icons-material": "^6.5.0",
59
+ "@mui/material": "^6.5.0",
60
+ "@testing-library/react": "^16.1.0",
43
61
  "@types/node": "^22.15.3",
62
+ "@types/react": "19.2.2",
63
+ "@types/react-dom": "19.2.2",
44
64
  "eslint": "^9.39.1",
45
65
  "eslint-plugin-test-flakiness": "^1.4.0",
46
66
  "hono": "^4.6.0",
67
+ "jsdom": "^25.0.1",
68
+ "react": "^19.2.0",
69
+ "react-dom": "^19.2.0",
47
70
  "typescript": "^5.9.2",
48
71
  "vitest": "^3.2.4"
49
72
  },
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The two DNS questions about a custom domain, through the HOST's resolver.
3
+ *
4
+ * - **Ownership** (`ownsRecord`): the TXT record at `<prefix>.<hostname>`
5
+ * carries the token the host minted. It proves the claimant controls the
6
+ * zone, which is the only thing that makes serving the name, and asking a CA
7
+ * for a certificate on its behalf, legitimate. Pointing an A record at an IP
8
+ * needs no relationship with the IP's owner, so it proves nothing.
9
+ * - **Pointing** (`pointsHere`): does the name resolve to this deploy? The
10
+ * failure it makes visible LOOKS LIKE SUCCESS: the TXT verifies, the domain
11
+ * goes ACTIVE, and the DNS still points somewhere else. So it is ADVISORY:
12
+ * it never gates verification, and a resolver failure is unknown (`null`),
13
+ * never "not pointed".
14
+ *
15
+ * Neither ever throws. The resolver is the host's so a host's tests can
16
+ * replace it; nothing here imports a DNS module.
17
+ */
18
+ import { TenantConfigError } from '../validate';
19
+ import { createDomainDns, validateRecordPrefix } from './dns-names';
20
+ import { TENANT_DOMAIN_RESOLVER_METHODS, type TenantDomainResolver } from './port';
21
+
22
+ export interface TenantDomainDnsChecksConfig {
23
+ resolver: TenantDomainResolver;
24
+ /** Where names must point: the deploy's public address(es). Read on EVERY call; empty = unknown. */
25
+ dnsTargets: () => string[];
26
+ /** The TXT record's label, one DNS label (`_verify`). */
27
+ recordPrefix: string;
28
+ }
29
+
30
+ export interface TenantDomainDnsChecks {
31
+ /** The deploy's targets, as `dnsTargets()` answers now. */
32
+ targets(): string[];
33
+ /** True when `token` is published at the verification record. Never throws. */
34
+ ownsRecord(hostname: string, token: string): Promise<boolean>;
35
+ /**
36
+ * `true` an address of the name is one of ours; `false` it resolves, to
37
+ * nothing of ours; `null` unknown (no target, a failed or empty lookup).
38
+ */
39
+ pointsHere(hostname: string): Promise<boolean | null>;
40
+ }
41
+
42
+ type Bag = Record<string, unknown>;
43
+ const isBag = (value: unknown): value is Bag => typeof value === 'object' && value !== null && !Array.isArray(value);
44
+
45
+ function requireFunction(bag: Bag, name: string, key: string): void {
46
+ if (bag[name] === undefined || bag[name] === null) throw new TenantConfigError(key, 'is required and missing');
47
+ if (typeof bag[name] !== 'function') throw new TenantConfigError(key, 'must be a function');
48
+ }
49
+
50
+ /** Check the checks' config; keys are named under `prefix` (`domains.dns.`). */
51
+ export function validateDnsChecksConfig(value: unknown, prefix: string): void {
52
+ const where = prefix === '' ? 'dns' : prefix.replace(/\.$/, '');
53
+ if (!isBag(value)) {
54
+ throw new TenantConfigError(where, value === undefined || value === null ? 'is required and missing' : 'must be an object');
55
+ }
56
+ if (!isBag(value.resolver)) {
57
+ throw new TenantConfigError(
58
+ `${prefix}resolver`,
59
+ value.resolver === undefined || value.resolver === null ? 'is required and missing' : 'must be an object',
60
+ );
61
+ }
62
+ for (const method of TENANT_DOMAIN_RESOLVER_METHODS) {
63
+ requireFunction(value.resolver, method, `${prefix}resolver.${method}`);
64
+ }
65
+ requireFunction(value, 'dnsTargets', `${prefix}dnsTargets`);
66
+ validateRecordPrefix(value.recordPrefix, `${prefix}recordPrefix`);
67
+ }
68
+
69
+ /**
70
+ * One spelling per address. The resolver answers IPv6 compressed and lower
71
+ * case (`2001:db8::1`), but a target is hand-typed and may arrive as
72
+ * `2001:DB8:0:0::1`: the same address, which a plain compare would call "not
73
+ * pointed here". `URL` canonicalises a bracketed IPv6 host per RFC 5952;
74
+ * anything else (IPv4, a hostname) is only lower-cased.
75
+ */
76
+ function canonicalAddress(address: string): string {
77
+ const bare = address.trim().toLowerCase();
78
+ if (!bare.includes(':')) return bare;
79
+ try {
80
+ return new URL(`http://[${bare.replace(/^\[|\]$/g, '')}]/`).hostname.replace(/^\[|\]$/g, '');
81
+ } catch {
82
+ return bare;
83
+ }
84
+ }
85
+
86
+ export function createDnsChecks(config: TenantDomainDnsChecksConfig): TenantDomainDnsChecks {
87
+ validateDnsChecksConfig(config, '');
88
+ const { resolver, dnsTargets } = config;
89
+ const records = createDomainDns({ recordPrefix: config.recordPrefix });
90
+
91
+ /**
92
+ * Every A and AAAA record for the name. Both families are asked, and either
93
+ * failing alone must not erase the other's answer: `allSettled`, not `all`.
94
+ */
95
+ async function addressesOf(hostname: string): Promise<string[]> {
96
+ const results = await Promise.allSettled([
97
+ Promise.resolve().then(() => resolver.ipv4(hostname)),
98
+ Promise.resolve().then(() => resolver.ipv6(hostname)),
99
+ ]);
100
+ return results.flatMap((result) => (result.status === 'fulfilled' ? result.value : []));
101
+ }
102
+
103
+ return {
104
+ targets: () => dnsTargets(),
105
+ ownsRecord: async (hostname, token) => {
106
+ try {
107
+ // TXT values may be split at 255 bytes: each record's chunks are joined before comparing.
108
+ const found = await resolver.txt(records.verificationRecordName(hostname));
109
+ return found.some((chunks) => chunks.join('').trim() === token);
110
+ } catch {
111
+ // NXDOMAIN, no record, a timeout: unverified, never an error. Retrying is the answer to both.
112
+ return false;
113
+ }
114
+ },
115
+ pointsHere: async (hostname) => {
116
+ const targets = dnsTargets();
117
+ if (targets.length === 0) return null;
118
+ const addresses = await addressesOf(hostname);
119
+ if (addresses.length === 0) return null;
120
+ const ours = new Set(targets.map(canonicalAddress));
121
+ return addresses.some((address) => ours.has(canonicalAddress(address)));
122
+ },
123
+ };
124
+ }
@@ -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
+ }