@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
package/ADOPTING.md
CHANGED
|
@@ -7,8 +7,8 @@ Two halves, one factory each, one config object each. Nothing is optional.
|
|
|
7
7
|
import { createApiTenant } from '@12-apps/tenant/server';
|
|
8
8
|
import { mountTenant } from '@12-apps/tenant/hono';
|
|
9
9
|
|
|
10
|
-
const tenant = createApiTenant({ statuses, ids, copy, port });
|
|
11
|
-
mountTenant(app, tenant); // mounts nothing
|
|
10
|
+
const tenant = createApiTenant({ statuses, ids, copy, port }); // + tree, slugs, lifecycle: each opt-in
|
|
11
|
+
mountTenant(app, tenant); // mounts nothing: hosts keep their own route modules
|
|
12
12
|
|
|
13
13
|
// frontend
|
|
14
14
|
import { createWebTenant } from '@12-apps/tenant/react';
|
|
@@ -92,8 +92,8 @@ const copy = { locales: { 'pt-BR': ptBR, 'en-US': enUS }, defaultLocale: 'pt-BR'
|
|
|
92
92
|
|
|
93
93
|
```ts
|
|
94
94
|
const port: TenantPort<Status, Tx> = {
|
|
95
|
-
bySlug: (slug) => …, // the CURRENT slug only: { id, slug, status } | null
|
|
96
|
-
byId: (id, tx) => …, // on tx when given: { id, slug, status } | null
|
|
95
|
+
bySlug: (slug) => …, // the CURRENT slug only: { id, slug, status, name? } | null
|
|
96
|
+
byId: (id, tx) => …, // on tx when given: { id, slug, status, name? } | null
|
|
97
97
|
setStatusIf: (id, from, to, tx) => …, // compare-and-set ON tx: true only when the row moved
|
|
98
98
|
clearProfile: (tx, id) => …, // erase the row's profile, on tx
|
|
99
99
|
timeZone: (id) => …, // IANA zone
|
|
@@ -248,6 +248,208 @@ two members and the memory are checked at startup (`slugs.port.current`,
|
|
|
248
248
|
- **One memory per channel per process**, shared by everything that reads
|
|
249
249
|
under that channel. Two memories on one channel each open a listener.
|
|
250
250
|
|
|
251
|
+
### Lifecycle (opt-in): close, reopen, the sweep, the gates
|
|
252
|
+
|
|
253
|
+
Additive: a host that passes no `lifecycle` boots unchanged and gets no
|
|
254
|
+
`tenant.lifecycle`.
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
const tenant = createApiTenant({
|
|
258
|
+
statuses, ids, copy, port, tree, // tree optional
|
|
259
|
+
lifecycle: {
|
|
260
|
+
graceDays: 30, reminderDays: { week: 7, day: 1 }, // integers, 0 < day < week < graceDays
|
|
261
|
+
minReasonLength: 3, nameLocale: 'pt-BR', sweepBatch: 200,
|
|
262
|
+
copy: { locales: { 'pt-BR': { noticePlatformScheduledTitle, noticePlatformScheduledBody,
|
|
263
|
+
noticePlatformScheduledBodyNoReason, noticeReopenedRestoredTitle, noticeReopenedRestoredBody }, … } },
|
|
264
|
+
db: { transaction: (run) => prisma.$transaction(run), table: (tx) => (tx ?? prisma).tenantClosing },
|
|
265
|
+
blockers: { kinds: [{ kind: 'patients', path: 'ward' }, …], read: (tenantId, { now, tx }) => … },
|
|
266
|
+
openDescendants: { kind: 'units', path: 'units' }, // REQUIRED with `tree`, refused without
|
|
267
|
+
confirmDangerousAct: (request, { tenantId, by }) => …, // throws to refuse (a PIN check)
|
|
268
|
+
afterClose: ({ tenant, node, now }) => …, // throws = failed: stamped, audited, retried by the sweep
|
|
269
|
+
invalidate: (tenantId) => …,
|
|
270
|
+
notify: (typeId, payload) => …, // resolves true only once RECORDED
|
|
271
|
+
onPurgeDue: (tenantId, { now }) => …, // 'purged' | 'already' | 'skipped'
|
|
272
|
+
audit: (tx, action, event) => …, // on tx; action = ids.audit[event.act]
|
|
273
|
+
locale: () => …, onError: (error, { act, tenantId }) => …,
|
|
274
|
+
mirror, // optional: an older table you are moving (below)
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
- **Your port MUST return `name` from `bySlug` and `byId`** once the lifecycle
|
|
280
|
+
is wired. `TenantRecord.name` stays optional for hosts without it; with it, a
|
|
281
|
+
record that lacks a name is a programming error, thrown as a
|
|
282
|
+
`TenantConfigError` on `port.byId` the first time the lifecycle needs it
|
|
283
|
+
(never a notice with an empty name).
|
|
284
|
+
- **The lifecycle's own sentences are a copy extension**,
|
|
285
|
+
`lifecycle.copy.locales.<tag>`, required for every tag of `copy.locales`
|
|
286
|
+
and validated per key (`lifecycle.copy.locales.pt-BR.noticePlatformScheduledBody`):
|
|
287
|
+
the platform close's title and body (with its reason, and
|
|
288
|
+
`noticePlatformScheduledBodyNoReason` when the notice carries none), and
|
|
289
|
+
`noticeReopenedRestored*`, which a reopen notice reads when it restored a
|
|
290
|
+
status other than active (`payload.restored`): a tenant reopened to
|
|
291
|
+
suspended is not live again, and its notice must not say so.
|
|
292
|
+
The base pack (`TENANT_COPY_SHAPE`) is unchanged. `blocker(kind, count,
|
|
293
|
+
detail?)` takes the blocker's optional `detail` (an amount and a date).
|
|
294
|
+
- **Two entries into one flow.** `close({ by: 'member', typedName, … })`
|
|
295
|
+
starts from `statuses.active` only and checks the typed name in
|
|
296
|
+
`nameLocale`; `close({ by: 'platform', … })` starts from any of
|
|
297
|
+
`statuses.closableFrom`, asks no name, writes `requested_by_id` null (your
|
|
298
|
+
audit line says who) and hands the reason to the scheduled notice
|
|
299
|
+
(`payload.reason`, words from `noticePlatformScheduled*`). Both record
|
|
300
|
+
`prior_status`; `reopen` restores it (or `active` when it is null or not a
|
|
301
|
+
live status).
|
|
302
|
+
- **The order of a close**: `confirmDangerousAct`, the reason, the name, then
|
|
303
|
+
ONE transaction (`setStatusIf`, your blockers read again ON `tx` plus the
|
|
304
|
+
open-descendants count, the row replaced, `mirror.replaced`, `audit`). A
|
|
305
|
+
blocker found there rolls the move back (409 `closingBlocked`, `details:
|
|
306
|
+
{ pending }`). After the commit, never inside it: `afterClose` (with the
|
|
307
|
+
tenant's tree node, so a unit can skip its root's billing), `invalidate`,
|
|
308
|
+
`notify`. A hook that throws goes to `onError` and never undoes the close.
|
|
309
|
+
- **Refusals** are `TenantLifecycleRefusal { kind, code, status, details }`,
|
|
310
|
+
`code` from your `ids.refusals`, the message from `copyFor(locale())`. The
|
|
311
|
+
statuses are fixed: 403 closing/readOnly/closed, 409 gone, alreadyClosing,
|
|
312
|
+
notActive, closingBlocked, purged, notClosing, 422 reasonTooShort,
|
|
313
|
+
nameMismatch.
|
|
314
|
+
- **Schedule `tenant.lifecycle.sweep(now)`** on your own job runner (hourly is
|
|
315
|
+
plenty). Per row: skip a tenant no longer closing or closed; retry
|
|
316
|
+
`afterClose` while it has not gone through; once due, `onPurgeDue` and stamp
|
|
317
|
+
`purged_at` on `purged` or `already`; before that, send the reminder due,
|
|
318
|
+
stamped only once `notify` answered true.
|
|
319
|
+
- **Statement budget.** `state()` reads nothing for a live tenant and one row
|
|
320
|
+
for a gone one. `blockers()` and the close add ONE `treeDescendants` read
|
|
321
|
+
when a tree is wired: with the lifecycle, that read MUST return each node's
|
|
322
|
+
`status` (`TenantTreeNode.status`), or the blocker throws a
|
|
323
|
+
`TenantConfigError` on `tree.treeDescendants`. The sweep reads one `byId`
|
|
324
|
+
per row and stamps in a transaction of its own.
|
|
325
|
+
- **Stale rows heal.** A closing row whose tenant is neither closing nor
|
|
326
|
+
closed (reopened by a release that wrote only your older table, say) is
|
|
327
|
+
deleted by the sweep, conditionally on its `requestedAt`, with
|
|
328
|
+
`mirror.deleted`, in one transaction. It takes no slot of `sweepBatch`:
|
|
329
|
+
the sweep pages on (keyset on `purgeAt`, `tenantId`) until `sweepBatch`
|
|
330
|
+
live tenants were swept or no row is left.
|
|
331
|
+
- **Gates**: `createTenantGates(tenant, { admin: { prefix, closingWrites },
|
|
332
|
+
public: { prefix, families }, lookup, holdsClose, locale })` and
|
|
333
|
+
`mountTenantGates(app, gates)` from `@12-apps/tenant/hono`. `lookup` is your
|
|
334
|
+
kept slug lookup (the status rides it: an open tenant pays nothing more); a
|
|
335
|
+
family's `fixedWords` are never looked up; `slugAfter` names words after
|
|
336
|
+
which the next segment is the slug. The middlewares are typed structurally
|
|
337
|
+
(`TenantGateMiddleware`), so they fit whatever Hono version you resolve.
|
|
338
|
+
- **Notice words without the hooks**: `createNoticeWords(tenant, { copy })`
|
|
339
|
+
answers `noticeWords` alone, for a notification registry that renders the
|
|
340
|
+
lifecycle's notices apart from the module that wires its hooks. It
|
|
341
|
+
validates the extension as the lifecycle does, and a locale without one
|
|
342
|
+
reads the default locale's.
|
|
343
|
+
- **`TenantTree.nodeOf` is optional on the type** (added in this minor, so a
|
|
344
|
+
host typing a tree of its own keeps compiling); `createTenantTree` always
|
|
345
|
+
provides it, and the lifecycle reads no node when it is absent.
|
|
346
|
+
|
|
347
|
+
#### Moving an older closing table (expand and contract)
|
|
348
|
+
|
|
349
|
+
Pass `mirror: { replaced, event, deleted }`: each runs on the package's own
|
|
350
|
+
transaction, so the two tables never disagree. `deleted(tx, tenantId, requestedAt?)`
|
|
351
|
+
hands you the deleted row's `requestedAt`: delete your old row only while it
|
|
352
|
+
is that same close, so a re-close your previous release wrote meanwhile
|
|
353
|
+
survives (absent when the package read no row: delete by tenant). Write each stamp where it is
|
|
354
|
+
still null, as the package does. Rows your PREVIOUS release wrote only into
|
|
355
|
+
the old table (during a rolling deploy) are not in `tenant_closings`: before
|
|
356
|
+
each sweep, catch them up with one upsert (`INSERT … SELECT … ON CONFLICT
|
|
357
|
+
(tenant_id) DO UPDATE`), and backfill once with a data-only migration.
|
|
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
|
+
|
|
251
453
|
### The schema and the migration
|
|
252
454
|
|
|
253
455
|
- Copy the partial into your schema folder with
|
package/README.md
CHANGED
|
@@ -26,16 +26,20 @@ This first release ships the **contract** every later behaviour extends:
|
|
|
26
26
|
- the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
|
|
27
27
|
Prisma partial with its own migration.
|
|
28
28
|
|
|
29
|
-
The lifecycle (close
|
|
30
|
-
|
|
29
|
+
The closing lifecycle (close and reopen as a dangerous act, the blockers, the
|
|
30
|
+
sweep that reminds and purges, and the admin and public gates) is opt-in:
|
|
31
|
+
`createApiTenant({ lifecycle })` and `createTenantGates`. The purge and the
|
|
32
|
+
data export arrive in later releases on top of the same config. How to adopt it: [ADOPTING.md](./ADOPTING.md).
|
|
31
33
|
|
|
32
34
|
## Entry points
|
|
33
35
|
|
|
34
36
|
| Import | What | Needs |
|
|
35
37
|
|---|---|---|
|
|
36
|
-
| `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`) | nothing |
|
|
37
|
-
| `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is), and the slug resolution exports | nothing |
|
|
38
|
-
| `@12-apps/tenant/
|
|
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` |
|
|
42
|
+
| `@12-apps/tenant/hono` | `mountTenant(app, tenant)`, `mountTenantGates(app, gates)`, `tenantAdminGate`, `tenantPublicGate` | `hono` |
|
|
39
43
|
| `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
|
|
40
44
|
| `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
|
|
41
45
|
|
package/package.json
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/tenant",
|
|
3
|
-
"version": "1.
|
|
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
|
-
"
|
|
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
|
},
|
package/src/config.ts
CHANGED
|
@@ -245,8 +245,12 @@ export interface TenantCopyPack {
|
|
|
245
245
|
readonly refusalExportExpired: string;
|
|
246
246
|
readonly pendingTitle: string;
|
|
247
247
|
readonly pendingNone: string;
|
|
248
|
-
/**
|
|
249
|
-
|
|
248
|
+
/**
|
|
249
|
+
* One line per kind of blocker; `kind` is one of the host's own blocker
|
|
250
|
+
* kinds. `detail` is whatever the host's blocker read attached to it (an
|
|
251
|
+
* amount and a date, say), passed through as given.
|
|
252
|
+
*/
|
|
253
|
+
readonly blocker: (kind: string, count: number, detail?: Readonly<Record<string, string | number>>) => string;
|
|
250
254
|
/** The shortcut that resolves a blocker of that kind. */
|
|
251
255
|
readonly shortcut: (kind: string) => string;
|
|
252
256
|
readonly dataTitle: string;
|
|
@@ -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
|
+
}
|