@aria-framework/tenancy 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,912 @@
1
- # Temporary Holding Version
1
+ # @aria-framework/tenancy
2
+
3
+ The main-thread half of a multi-tenant app. Version 0.1.0 is built in three parts; each documents itself below.
4
+
5
+ ## Scope
6
+
7
+ Who a request works for, the scope seam, and the write gate. Two factories, each called once by the app.
8
+
9
+ ### `createTenancy(options)`
10
+
11
+ ```js
12
+ // lib/tenant.js — the app's file stays at its path; lib/scope.js re-exports the same object
13
+ const tenancy = createTenancy({
14
+ db: () => require('./db-client'), // the main-thread client, or a getter (a require cycle)
15
+ logger: require('./logger'),
16
+ dbKind: () => require('../config').dbKind, // read at call time
17
+ platformRequiresHouse: true, // a new app: true
18
+ actingRequiresActive: true, // a new app: true
19
+ refreshTokenOwner: (raw) => db.invoke('RefreshToken', 'partnerForHash', hashRefresh(raw))
20
+ });
21
+ module.exports = tenancy; // the object itself: see "the seam calls at call time"
22
+ ```
23
+
24
+ | Option | Required | Default | What it is | Which app passes what |
25
+ |---|---|---|---|---|
26
+ | `db` | yes | | the db client (`invoke(model, method, ...args)`), or a function returning it | every app |
27
+ | `logger` | yes | | `{ warn, error }` | every app |
28
+ | `dbKind` | **yes, no default** | | `'postgres'`, `'sqlite'`, or a function returning one; `canHostTenants()` answers it, and the write gate compares a row's partner at partner scope only on Postgres | an app that still tests on SQLite (the hub, the desk): `() => config.dbKind`; an app whose server refuses SQLite at boot (starter, soc, noc, wall): `'postgres'` — for the soc app this keeps the partner comparison its gate copies make today even in a harness on SQLite |
29
+ | `platformRequiresHouse` | **yes, no default** | | `true`: `scope_kind = 'platform'` is honoured only for a member of the house, checked at use, failing closed while the house id is unresolved; `false`: the stored scope is trusted | the desk: `true`; hub, soc, noc, wall: `false`; **a new app: `true`** (owner's answer 1) |
30
+ | `partnerModel` | no | `'Partner'` | the model whose `house`, `all`, `seedHouse` are invoked | the same in every app |
31
+ | `contactScope(session)` | no | none | the context for a session with **no staff user** (a portal contact): return `{ scope, partnerId }` or null. Asked only then; nothing else is done with it | the desk (its portal contact). Step 6's customer tier is a second resolver here |
32
+ | `beforeEachPartner(partner)` | no | none | awaited inside each partner's scope before `forEachPartner`'s `fn`; a throw is that partner's failure | the desk (warms the partner's chrome, catching its own error) |
33
+ | `refreshTokenOwner(raw)` | no | none | the partner of a refresh token, without consuming it; `asRefreshTokenOwner` throws without it | an app with the API |
34
+ | `unscopedRedirect` | no | `'/login?reason=session_unscoped'` | where `requestScope` sends a session it destroyed | the same in every app |
35
+ | `actingRequiresActive` | **yes, no default** | | `true`: an acting flag is honoured only into a partner known to be ACTIVE; deactivating a partner ends acting into it for every request that begins after the deactivating call has returned (see "What is guaranteed" below; the owner's decision of 29 Nov 2026). `false`: as today | every existing app: `false` today, turned on at its own adoption; **a new app: `true`** |
36
+ | `activeMaxAgeMs` | no | none | with `actingRequiresActive`: a set of active partners older than this is reloaded before it is trusted (an app run as more than one process); a whole number, at least 1000 | |
37
+ | `activeLoadTimeoutMs` | no | `5000` | a load of that set with no answer by then counts as failed: the requests waiting on it are answered closed; a whole number, at least 1000 (below that a healthy but slow database can answer every load after it was already replaced by a newer one, and acting never resumes while traffic continues) | |
38
+ | `timers` | no | the global `setTimeout`/`clearTimeout` | what that timeout runs on; a test passes a fake clock's | |
39
+ | `now` | no | `Date.now` | the clock `activeMaxAgeMs` is measured on | |
40
+
41
+ It returns one object. Every name and signature of the starter's `lib/tenant.js` and `lib/scope.js`:
42
+
43
+ | Function | |
44
+ |---|---|
45
+ | `asPartner(partnerId, fn)` | runs `fn` at `{ scope: 'partner', partnerId: Number(partnerId) }` |
46
+ | `asPlatform(fn)` | `{ scope: 'platform', partnerId: null }` (synchronous) |
47
+ | `asHouse(fn)` → Promise | platform scope with the house id; partnerless (warned once) when there is no house |
48
+ | `housePartnerId()` → Promise\<number> | memoised per factory, read from `is_house` |
49
+ | `contextFor(req)` → `{ scope, partnerId }` \| null | the starter's body: null for a staff user with no `partner_id`; acting honoured only for a platform user; anonymous is platform with no partner |
50
+ | `forEachPartner(fn, { logger } = {})` → Promise\<{ succeeded, failed, lastError }> | every partner, each in its own scope, past failures |
51
+ | `canHostTenants()` → boolean | `dbKind === 'postgres'` |
52
+ | `asOwnPartner(req, fn(me))` | the signed-in user's own rows at their HOME partner, partner scope, the id from the session; throws without one |
53
+ | `runWithTenant(ctx, fn)`, `currentTenant()` | db-worker's, re-exported |
54
+ | `asInstallation(fn)`, `acrossAll(fn)`, `run(ctx, fn)`, `forEachScope(fn, opts)` | the seam: `asHouse`, `asPlatform`, `runWithTenant`, `forEachPartner` |
55
+ | `atBoot(fn)` → Promise | seeds the house at platform scope, then runs `fn` in the house scope |
56
+ | `requestScope()` → middleware | after the session, before the first router; an unscopable session destroyed and redirected; anonymous through `asHouse`; with `platformRequiresHouse` the house id is resolved first |
57
+ | `forApiUser(user)` → `{ scope, partnerId }` \| null | a number or a digit string, nothing else; platform per `isPlatformUser` |
58
+ | `asOwnerOf(user, fn)` | `asPartner(user.partner_id, fn)` |
59
+ | `asRefreshTokenOwner(rawToken, fn)` → Promise | `fn` in the token owner's scope, or where it stands for an unknown token |
60
+ | `forSession(session)` → `{ scope, partnerId }` \| null | `contextFor` from a session alone; null with no user |
61
+
62
+ Two more, for an app's other doors to ask the house rule the same way: `isPlatformUser(user)` and `knownHouseId()`.
63
+ And `refreshActivePartners()` → Promise\<boolean> and `whenActivePartnersKnown()` → Promise\<boolean> (below).
64
+
65
+ **Acting requires an active partner** (`actingRequiresActive: true`). `contextFor` is synchronous on the main thread
66
+ and cannot read the database, so it reads a set of active partner ids kept by the factory:
67
+
68
+ - **First load:** `atBoot`, after the house is seeded. `requestScope` also loads it before answering a request that
69
+ carries an acting flag while the set is unknown or older than `activeMaxAgeMs`; a synchronous `contextFor` that
70
+ meets an unknown set starts a load in the background.
71
+ - **Refresh:** the app calls `tenancy.refreshActivePartners()` after any partner is created, changed, activated or
72
+ deactivated (from `createProvisioner`'s `onPartnersChanged`, beside `createHostTenant`'s `forget()`). It reads `Partner.all`
73
+ at platform scope (each row must carry `is_active`), resolves `true`, or `false` on a failure or timeout; it never
74
+ rejects. The load it waits for always STARTS after the call: one already in flight may have read the table before
75
+ the change, so a refresh asked for meanwhile runs one more load after it (several such refreshes share that one).
76
+ **The call marks the set stale at once**, synchronously, before any load starts: from that moment a request
77
+ carrying an acting flag waits in `requestScope` for that fresh load (as it does when the set is unknown), and a
78
+ synchronous `contextFor` is closed with the keys kept; when the load lands the new set applies, and a fresh load
79
+ that fails leaves the set unknown (closed). **How long such a request can wait:** EVERY partner change marks the set
80
+ stale (a rename too: the app's callback cannot know which change matters), so after any change a request carrying an
81
+ acting flag waits for the reload: normally milliseconds, at most `activeLoadTimeoutMs` (twice that if a load was
82
+ already in flight), and if the load did not land it is then answered closed, with its keys kept. **A caller that
83
+ is not a request** (a live stream's periodic re-check) awaits `tenancy.whenActivePartnersKnown()` before
84
+ `forSession(session)`: it resolves `true` at once when the set is known and not stale, else waits for the pending
85
+ load with the same bound and resolves whether the set is known then (`false` at the bound; it never rejects); with
86
+ the setting off it resolves `true` at once and reads nothing. Without it, a stream re-checked during a stale window
87
+ gets the closed answer (the operator's own scope) and stops an acting operator's stream on every partner edit. With
88
+ `@aria-framework/notify`, that place is `createLiveAuth`'s `deps.scopeOf(session)` (it may return a promise):
89
+ `scopeOf: async (s) => { await tenancy.whenActivePartnersKnown(); return tenancy.forSession(s); }`.
90
+ **What is guaranteed, and no more:** a request that begins after the deactivating call has returned is not acting into that partner; a request already running inside the partner when the deactivation commits finishes there; and between the commit and the callback's refresh (a few milliseconds, inside the same call) a request may still be honoured.
91
+ - **One load at a time, the newest wins:** requests that only need the set share the load in flight; a result is
92
+ applied only if its load is the newest started, so an older load answering late never overwrites a newer one. A
93
+ load with no answer within `activeLoadTimeoutMs` counts as failed (its waiters are answered closed, the set becomes
94
+ unknown); its late result is still applied if it is still the newest. **What an operator sees while loads time
95
+ out:** an operator who was acting works at their own scope (the house's view, nothing written into the partner),
96
+ with the acting flag kept, until a load succeeds; then they are back inside the partner without switching in again.
97
+ A refresh with the setting off resolves `true` at once and reads nothing.
98
+ - **Closed when unknown:** while the set is not known (not loaded yet, the last load failed, or too old), no acting
99
+ flag is honoured: the operator's own scope answers. A failed load is logged once per outage. The flag is kept.
100
+ - **Three answers for a known set:** a partner in the loaded active set is honoured. A partner KNOWN INACTIVE is not,
101
+ and `actingPartnerId` and `actingPartnerName` (the keys the stop route removes) are deleted from the session, so
102
+ reactivating it normally does not put the operator back inside without switching in again. Not always: a request
103
+ that overlapped the deactivation (began before the keys were cleared, finished after) can save its older copy of the
104
+ session over the cleared keys, and then the operator is inside again once the partner is active again (a partner
105
+ they may enter anyway). A partner in NEITHER set
106
+ (created after the last load, or in another process) is not honoured, its keys are kept, and it starts one load
107
+ after now so the next request can be honoured. Each such id starts at most one load until the app's next
108
+ `refreshActivePartners()` or the next `activeMaxAgeMs` expiry, so an id that does not exist cannot cost a load per
109
+ request.
110
+ - **A bad clock throws:** a `now()` that answers anything but a finite number throws at first use, before any
111
+ decision (otherwise "too old" would never be true and the set never reloaded).
112
+ - **More than one process:** a refresh reaches only the process that ran it. An app run as two or more processes
113
+ either tells the others (its own message between them, each calling `refreshActivePartners()`), or passes
114
+ `activeMaxAgeMs`, so each process reloads a set older than that before trusting it (a failed reload is unknown).
115
+ - **You must wire the refresh.** Without a `refreshActivePartners()` call after each partner change and without
116
+ `activeMaxAgeMs`, acting into a deactivated partner continues for ever (until the process restarts). So an app MUST
117
+ wire `createProvisioner`'s `onPartnersChanged` to `tenancy.refreshActivePartners()`, and an app run as more than one process
118
+ MUST ALSO pass `activeMaxAgeMs` (or tell the other processes).
119
+ - **A string id** in the session (`actingPartnerId: '3'`, as a session store may hand back) is honoured as partner 3,
120
+ as every source app's `contextFor` does today (each reads it through `Number(...)`).
121
+ - The write gate needs nothing: it judges `contextFor(req)`, so an operator acting into a partner that has just been
122
+ deactivated is answered as an operator who is not acting (no write into that partner).
123
+
124
+ **The seam calls at call time.** Every seam function (and `requestScope`) reaches the others through the returned
125
+ object when it runs, so a test that replaces `tenancy.asHouse` is seen by `asInstallation` and `requestScope`. An
126
+ app that exports a spread copy (`{ ...tenancy, extra }`) breaks that for stubs placed on the copy: export the object
127
+ and add extras to it.
128
+
129
+ ### `createWriteGate(options)`
130
+
131
+ The house writes into a partner **only while acting as it** (the owner's rule of 23 Oct 2026): at platform scope a
132
+ house user writes the house's own rows, never another partner's. Edits and deletes ask the same gate as creates: an
133
+ UPDATE or DELETE of an existing row that records no actor is refused by nothing in the database at platform scope.
134
+
135
+ ```js
136
+ const gate = createWriteGate({
137
+ tenancy, whileActing: 'write', houseReading: null, logger,
138
+ partnerById: (id) => db.invoke('Partner', 'byId', id),
139
+ messages: {
140
+ unscopable: 'Your account is not associated with a partner, so it cannot change anything.',
141
+ notActing: ({ name }) => `Switch to ${name} to edit this.`,
142
+ elsewhere: 'This belongs to another partner.',
143
+ crossTenant: { acting: { title, message }, platform: { title, message } } // for crossTenantWriteHandler
144
+ }
145
+ });
146
+ ```
147
+
148
+ | Option | Required | What it is | Which app passes what |
149
+ |---|---|---|---|
150
+ | `tenancy` | yes | what `createTenancy` returned | |
151
+ | `whileActing` | **yes, no default** | `'write'`: an operator acting as a partner writes there; `'readOnly'`: nothing (creates included) | the desk: `'readOnly'`; hub, soc, noc: `'write'`; **a new staff app: `'write'`** (owner's answer 5) |
152
+ | `houseReading` | **yes, no default** (null is an answer, absent is not) | the permission whose ABSENCE at platform scope makes a request the house reading: it reads only the house's rows | the soc app: its fleet permission; every other app: `null`; **a new app: `null`** (owner's answer 4) |
153
+ | `messages` | yes | the app's sentences: `unscopable`, `notActing`, `elsewhere`, `actingReadOnly` (for `'readOnly'`), `crossTenant` (for the handler). Each a string or a function of `{ req, rowPartnerId, what, partner, name }` | each app its own |
154
+ | `partnerById(id)` | yes | a partner `{ id, name }` by id, in the request's scope | |
155
+ | `logger` | yes | `{ warn }`: every refusal is logged once | |
156
+ | `wantsJson(req)` | no | default: `X-Requested-With: fetch` | |
157
+ | `refusalView` | no | default `'errors/generic'`: the view the handler renders with `{ title, message }` | |
158
+
159
+ | Function | |
160
+ |---|---|
161
+ | `writeScope(req, rowPartnerId)` → runner \| null | the scope to WRITE an existing row in (see the table); `req` null for a job |
162
+ | `readScope(req, rowPartnerId, { house }?)` → runner \| null | the scope to READ it in; `req` null for a job; `{ house }` required when `houseReading` is set, and exactly null or the house id |
163
+ | `createsLand(req)` → boolean | does the request carry a tenant for a new row (false while acting read-only) |
164
+ | `platformDestination(req)` → Promise\<{ id, name } \| null> | the partner a platform-scope create lands on, for the form to name |
165
+ | `refusal(req, rowPartnerId, what)` → Promise\<{ reason, partner, message } \| null> | what to say when the gate says no; `rowPartnerId` null is a create (or no such row) |
166
+ | `authorship(req)` → `{ userId, actedBy, actedByName }` | from the session only: while working outside the home partner the composite user column is null and the operator is `actedBy` |
167
+ | `houseOperatorNames(ids, { namesOf })` → Promise\<Map> | house users' names, read at the house partner's scope |
168
+ | `crossTenantWriteHandler()` → Express error handler | a 23503 on a composite tenant key (`fk_*_partner`) becomes a 409 sentence, JSON for a fetch; every other error is passed on untouched |
169
+ | `crossTenantRefusalOf(err, req)` → `{ kind, title, message }` \| null | the handler's predicate, for a route that catches and flashes its own error |
170
+ | `actingElsewhere(req)` → boolean | the scope moved off the user's own partner (never the raw session flag) |
171
+ | `houseReadingOf(req, can)` → Promise\<number \| null> | the house id when the request is the house reading, for `readScope` |
172
+
173
+ **Which context the gate judges, and where its runner runs** (one rule for `writeScope` and `readScope`):
174
+
175
+ - given a request, the judged context is `contextFor(req)`, whatever scope surrounds the call (the hub's form);
176
+ - given `null` (a job, no request), it is the current scope at the call (the noc and soc apps' form);
177
+ - `undefined`, or anything that is not an object, throws: a forgotten argument cannot silently pick a rule.
178
+
179
+ Every runner runs its callback with `runWithTenant` at `{ scope: 'partner', partnerId: <the judged partner> }`, at
180
+ partner scope as at platform scope, so it runs there even when called inside `acrossAll`, `asHouse`, `asOwnPartner`,
181
+ `asPlatform` or another partner's `asPartner`: a route cannot gate in one scope and write in another.
182
+
183
+ `writeScope`, case by case (`whileActing: 'readOnly'` differs only in the acting rows):
184
+
185
+ | Request | Row | Answer |
186
+ |---|---|---|
187
+ | unscopable, anonymous, or no row | any | null |
188
+ | partner scope (partner staff) | its own partner's | runs at that partner |
189
+ | partner scope | another partner's | null on Postgres; **runs at the judged partner on SQLite** (every row says partner 1 there whoever wrote it, so the column means nothing) |
190
+ | acting as P, `'write'` | P's | runs at P (another partner's: as partner scope above) |
191
+ | acting as P, `'readOnly'` | any | null |
192
+ | platform scope, not acting | the user's own partner's (the house's) | runs at that partner's scope (`asPartner`) |
193
+ | platform scope, not acting | another partner's | null, on both engines |
194
+
195
+ ## Hosts
196
+
197
+ Which partner a request's host name belongs to, and the brand, time zone and idle timeout a page shows for its
198
+ tenant. A wrong answer here serves one partner's sign-in page and branding as another's, so every rule below is the
199
+ apps' own, moved unchanged, and every setting that differs between apps is required.
200
+
201
+ ### `hostname` (pure functions)
202
+
203
+ `const { hostname } = require('@aria-framework/tenancy')`. No database, no state; safe in the worker and on the main
204
+ thread.
205
+
206
+ | Function | What it does |
207
+ |---|---|
208
+ | `normaliseHost(raw)` | WRITE side: an operator's typed host → lower case, no trailing dot; `null` for empty (clears the field); throws a sentence naming the problem (scheme, path, port, wildcard, underscore, single label, length). |
209
+ | `hostFromHeader(value)` | READ side: a `Host` (or forwarded) value → the host, port and trailing dot stripped, lower case; `null` for anything that cannot be a vanity host (IPv6 literal, single label, empty, missing). The first entry of a comma list. Uses the same pattern as `normaliseHost`, so a header can only match a host the write side would accept. |
210
+ | `normaliseDomain(domain)` / `labelFromDomain(domain)` | A company domain, canonical (`www.` dropped, IDN to punycode), and its label (`acme.co.za` → `acme-co-za`; over 63 characters, truncated plus a digest so it stays injective). |
211
+ | `randomLabel()` | A 10-character Crockford base32 label for a partner with no domain. |
212
+ | `hostFor(label, base, { reservedLabels })` | `<label>.<base>`, validated. Refuses: no base domain; a reserved label (any case); a label that is not one valid DNS label. |
213
+ | `assertLabelNotReserved(label, { reservedLabels })` | The one reserved-label refusal (`hostFor` and an edit route both use it). |
214
+ | `refuseReservedHost(host, base, { reservedLabels })` | For an edit route's free-text host: refuses `<reserved>.<base>`; a no-op off the base or for two labels left of it. |
215
+ | `isHostLabel(v)` | One lower-case DNS label, 1 to 63 characters. |
216
+ | `PARTNER_BASE_DOMAIN_KEY`, `MAX_HOSTNAME`, `MAX_LABEL` | `'partner_base_domain'`, 253, 63. |
217
+
218
+ **`reservedLabels` is REQUIRED** on the three functions that take it (an array; a missing or malformed one throws).
219
+ The hub passes `['registry', 'node', 'apt']`; every other app passes `[]`. No owner answer covers it: a new app passes
220
+ `[]` unless it serves its own components under the partner base domain.
221
+
222
+ ### `createHostTenant({ tenancy, db, logger, trustForwardedHost, chrome, isSignedIn, onForget, maxAgeMs })`
223
+
224
+ Returns `{ middleware(), partnerIdForRequest(req), partnerOfHost(host), forget() }`.
225
+
226
+ - `middleware()`: for the LOGIN routers only (mount it with `router.use()` or per route inside them, never with
227
+ `app.use()`: on the app it would let a forged `Host` narrow an authenticated request). An anonymous request on an
228
+ active partner's host runs the rest of the router inside `asPartner(<that partner>)`, with `req.partnerId` and
229
+ `req.partnerHost` set; any other host (unknown, bare IP, `localhost`, IPv6, none) runs inside `asPartner(<house>)`:
230
+ partner scope, never `asHouse()`'s platform scope. `chrome.applyTo(res)` is re-run inside the narrowed scope. A
231
+ signed-in session is stepped around. If the tenant cannot be decided at all (no map ever loaded and the read fails,
232
+ or the house cannot be found), it logs a warning and leaves the scope the request already had (the login page stays
233
+ up; the trade is named in the code).
234
+ - `partnerIdForRequest(req)`: the host's active partner, else the house. Does NOT step aside for a signed-in session
235
+ and does NOT fail open: a failure throws. For a customer portal comparing a session with the host it arrived on.
236
+ - `partnerOfHost(host)`: the host's active partner or `null` (never the house). For a sign-in provider's realm.
237
+ - `forget()`: drop the map; the next lookup reads it again. Call it after every write that can change the mapping
238
+ (create, host change, activate, deactivate). It reaches THIS process only.
239
+
240
+ | Setting | Default | Who needs what |
241
+ |---|---|---|
242
+ | `tenancy` | required | the scope part's `createTenancy()` result; this part calls `asPartner`, `asPlatform`, `housePartnerId` |
243
+ | `db` | required | the app's `DbClient`; reads `Partner.all` at platform scope |
244
+ | `logger` | required | `info`, `warn` |
245
+ | `trustForwardedHost` | **required, no default** (a boolean) | every app passes `config.trustForwardedHost`, which all six derive as `TRUST_FORWARDED_HOST === 'true'` (off unless set). No owner answer covers it; a new app does the same. |
246
+ | `chrome` | required | the app's request chrome (`lib/requestChrome.js`, its `applyTo(res)`) |
247
+ | `isSignedIn(session)` | **required, no default** | the starter, hub, soc, noc and wall apps pass `(s) => !!s.user`; the desk passes `(s) => !!(s.user \|\| s.contact)` (its portal contact). Left out, a default would narrow the desk's signed-in contacts by whatever host they visit, so construction throws instead. A new app passes `(s) => !!s.user` unless it has another signed-in session kind. |
248
+ | `onForget()` | none | the noc app passes its hub sign-in host store's reset until it adopts the hub packages' own store |
249
+ | `maxAgeMs` | none (no age bound) | a whole number of milliseconds, at least 1000. The noc app passes `60000` (see row 10 under Adopting it). The other five apps have no bound and pass nothing |
250
+ | `now()` | `Date.now` | a test seam (a fake clock); apps pass nothing. It must return a finite number: anything else throws at first use, naming the option, before any read |
251
+
252
+ **Which header decides.** `false`: the raw `Host` header, always, whatever else the request carries. `true`:
253
+ `req.hostname`. In the Express version this package is tested with (5.2), that reads `X-Forwarded-Host` (its first
254
+ entry) whenever Express's `trust proxy` function accepts the address of the peer that connected, and `Host`
255
+ otherwise. With `trust proxy = 1` that is EVERY peer (one hop is trusted, whoever it is); with `true` it is always.
256
+ So with `trustForwardedHost: true`, any client that reaches the app's port directly, or through a proxy that passes
257
+ the header on unchanged, chooses the tenant by sending one header.
258
+
259
+ Turning it on therefore means: the proxy in front must OVERWRITE `X-Forwarded-Host` on every request, and it must be
260
+ the only way in (the app's port reachable from that proxy alone). Never set Express's `trust proxy` to `true`. On the
261
+ proxies the apps' deployment notes cover:
262
+
263
+ - **Apache (httpd 2.4):** `ProxyPreserveHost` is Off by default, so always set `ProxyPreserveHost On`. When it
264
+ proxies, Apache adds `X-Forwarded-Host`, and if the client already sent one it APPENDS its own after the client's
265
+ (a comma-separated list), so the FIRST entry, the one Express reads, is the client's. That is why, before turning
266
+ `trustForwardedHost` on, the same virtual host needs `RequestHeader unset X-Forwarded-Host`, in the default (late)
267
+ mode, not `early` (which the documentation describes as a testing and debugging aid). The documentation does not
268
+ say in which order that directive and the proxy's own header are applied, so test it (below).
269
+ - **nginx:** by default it sends `Host: $proxy_host` (the backend's name), so always set
270
+ `proxy_set_header Host $host;`. Before turning `trustForwardedHost` on, also set
271
+ `proxy_set_header X-Forwarded-Host $host;`, which replaces a client-sent value; without it a client-sent
272
+ `X-Forwarded-Host` reaches the app unchanged. Put both lines at the SAME level as any other `proxy_set_header`
273
+ lines: a level that defines any `proxy_set_header` of its own inherits none from the levels above.
274
+ - **Caddy (2.5.0 or later):** `reverse_proxy` passes the client's `Host` through unchanged, and sets
275
+ `X-Forwarded-Host` itself, ignoring a client-sent value unless the client's address is listed in
276
+ `trusted_proxies`. Nothing needs setting; never list a source you do not control in `trusted_proxies`; leave
277
+ `trustForwardedHost` off, since `Host` already carries the right value.
278
+
279
+ **Test it on the deployment, whatever the proxy** (the only proof that holds for an actual configuration). Through
280
+ the proxy, on a host that no partner owns, send a forged header naming a partner's host:
281
+
282
+ ```sh
283
+ curl -s -o /dev/null -w '%{http_code}\n' -H 'X-Forwarded-Host: <a partner host>' https://<the installation's own address>/login
284
+ ```
285
+
286
+ and confirm the sign-in page that comes back is the house's, not that partner's (its brand on the page, or the
287
+ app's log line for the request), and that the app does not see `forged.example` when you send
288
+ `-H 'X-Forwarded-Host: forged.example'` (log `req.hostname` and `req.headers['x-forwarded-host']` once on a test
289
+ route). A forged value that reaches the app means the proxy is not overwriting the header: leave
290
+ `trustForwardedHost` off.
291
+
292
+ Behind a proxy that does not preserve `Host` (Apache's default, `ProxyPreserveHost Off`), every partner address
293
+ serves the house's sign-in.
294
+
295
+ **How stale the map can be.** It holds active partners with a `portal_host` only (lower-cased). Without `maxAgeMs`
296
+ it has no age: it is read once and kept until `forget()` or a restart, so a partner deactivated without `forget()`
297
+ keeps resolving by its host in that process until one of the two. With `maxAgeMs`, a map older than that is read
298
+ again on the next lookup, which bounds the staleness in a process that was never told. A reload that FAILS (after
299
+ `forget()` or past the age) answers from the last map it built; it is not cached, so the next lookup tries again, and
300
+ the first good reload replaces the map. The price, named: during such a failure a partner deactivated just before it
301
+ still resolves.
302
+
303
+ **An outage is logged once.** The first failed reload logs `Partner hosts: reload failed, keeping the last map (...)`
304
+ at warn; while reloads keep failing, at most one line a minute follows (`reload still failing ... N failed reload(s)
305
+ since the last line`); the first good reload logs `reload succeeded again after N failed reload(s)` at info. (With no
306
+ map ever loaded, the middleware's own fail-open warning is still written per request: the boot-time case.)
307
+
308
+ ### `createTenantChrome({ tenancy, db, fields })`
309
+
310
+ Returns `{ chromeFor(partnerId), forget(partnerId?), cachedSessionTimeoutMs(partnerId), cached(field, fallback) }`.
311
+
312
+ - `chromeFor(id)`: one value per field, read with `db.invoke('Settings', <method>)` inside `asPartner(id)` (so a
313
+ partner always gets its own row, whatever scope asks) and cached per partner. `chromeFor(null)` answers each field's
314
+ `fallback` and caches nothing.
315
+ - `forget(id)` drops one partner's entry; `forget()` drops all. Call it after a settings save and after a partner is
316
+ created or re-provisioned.
317
+ - `cachedSessionTimeoutMs(id)`: synchronous, cache only. **`null` before that partner's chrome is warm, and for a null
318
+ id**; never another tenant's number. Once warm, for a tenant with no `session_timeout_minutes` it is
319
+ `28800000` (480 minutes: the apps' `Settings.getSessionTimeoutMinutes` returns 480 for a missing or invalid value,
320
+ and `STARTER_FIELDS`' `read` also maps a falsy answer to 480). Never `undefined`. Every app's caller keeps its fallback
321
+ (`… || dbClient.getSessionTimeoutMs()`), so the live-update check, which now stops a stream on a timeout that is not
322
+ a positive finite number, never sees the `null`: keep that fallback when adopting.
323
+ - `cached(field, fallback)`: the CURRENT tenant's cached `field` (by `tenancy.currentTenant().partnerId`),
324
+ synchronously, or `fallback` when it is cold, there is no tenant, or the lookup throws. Pass a neutral fallback.
325
+
326
+ The cache key is db-worker's `tenantCacheKey({ scope: 'partner', partnerId })`: every entry is read at partner scope,
327
+ so `p:<id>` is the honest key; a platform-scope request for the house gets the house's chrome, as today. There is no
328
+ platform entry.
329
+
330
+ | Setting | Default | Who needs what |
331
+ |---|---|---|
332
+ | `tenancy` | required | calls `asPartner`, `currentTenant` |
333
+ | `db` | required | the app's `DbClient` |
334
+ | `fields` | **required, no default**; must include `sessionTimeoutMs` (every app's idle gate and live-update check read it through `cachedSessionTimeoutMs`, so a list without it is refused rather than answering `undefined`) | the starter, hub, soc, noc and wall apps pass `createTenantChrome.STARTER_FIELDS`: `displayTimezone` (`getDisplayTimezone`, `v \|\| 'UTC'`, fallback `'UTC'`) and `sessionTimeoutMs` (`getSessionTimeoutMinutes`, `(v \|\| 480) * 60000`, fallback 480 minutes). The desk passes four: `brandName` (`getBrandName`, its neutral brand as fallback), `displayTimezone` (`getDisplayTimezone`, fallback `'UTC'`), `dateStyle` (`getDateStyle`, fallback `{ format: null, clock: null }`), those three without `read` (the getters' own defaults), and `sessionTimeoutMs` as above. Left out, the desk would serve its neutral brand to every partner, silently, so construction throws instead. A new app passes `STARTER_FIELDS` plus any per-tenant field it shows. |
335
+
336
+ A field is `{ method, fallback, read? }`: `method` names the `Settings` getter, `read(raw)` turns its answer into the
337
+ cached value (without it the answer is cached as it comes), `fallback` is the value with no tenant.
338
+
339
+ ## Partners
340
+
341
+ The partner store and provisioning (plan piece 10), and working inside a partner: the acting routes, the locals and
342
+ the banner (piece 11). Everything here takes the app's own `tenancy` (the `createTenancy` result), db client, audit
343
+ helper and permission gate as arguments; the package holds no permission name, no app's prefix and no app's styling.
344
+
345
+ ### `createPartnerStore(options)` — the partner model's nine methods
346
+
347
+ ```js
348
+ // models/Partner.js (runs in the worker)
349
+ const { sql } = require('@aria-framework/db-worker');
350
+ const store = createPartnerStore({
351
+ driver: () => database.driver(), // a GETTER, read at every call, never a handle captured at load
352
+ sql, // db-worker's sql (the app's lib/sql.js re-export)
353
+ mintRef: () => publicId('partner'), // REQUIRED: a new reference in THIS app's own prefix
354
+ refShape: (ref) => isPublicId(ref, 'partner'), // REQUIRED: a GIVEN reference's shape check, or null for any
355
+ refPolicy: 'permanent', // REQUIRED: 'editable' | 'permanent' | (current, newRef, {tx, opts}) => locked
356
+ counts: { staff: { table: 'users', where: 'c.is_active = 1' }, customers: { table: 'customers' } }, // REQUIRED ({} for none)
357
+ nameMaxLength: 200, // REQUIRED: a whole number, or null for no limit
358
+ houseName: () => identity.appBrand, // REQUIRED: the house's name at seed
359
+ mintHouseRef: true, // REQUIRED: mint the house's reference at seed (below, per app)
360
+ writesRequirePlatform: true, // REQUIRED: refuse create/update/setActive/seedHouse below platform scope
361
+ allOrder: 'house-first', // REQUIRED: 'house-first' (the house, then by name) or 'id'
362
+ messages: {}, // optional: hostRequired, postgresOnly, hostCleared, houseDeactivate
363
+ normaliseHost, // optional: the host rule of the write path (hostname.normaliseHost)
364
+ paginate, // optional: @aria-framework/kit's paginate, for the paged list
365
+ extraColumns: [], // optional: the app's own columns (below)
366
+ onChange: async (tx, event) => {}, // optional: INSIDE the transaction, after a change
367
+ onDeactivate: async (tx, event) => {} // optional: INSIDE the transaction, on every deactivate
368
+ });
369
+ module.exports = { ...store, ...hubReceiveMethods };
370
+ ```
371
+
372
+ | Method | What it does |
373
+ |---|---|
374
+ | `seedHouse()` | Creates the house (`is_house = 1`, `houseName`; a reference from `mintRef` only with `mintHouseRef`) if there is none. Idempotent: `{ seeded, id }`; a second seed never touches the reference. |
375
+ | `house()`, `all()`, `byId(id)` | The house; every partner, deactivated ones included (with `portal_host`, `domain`, `is_active` and every `list` extra column), in `allOrder`; one row. |
376
+ | `byPortalHost(host)` | The ACTIVE partner owning a host, by `lower()`; a deactivated partner's host resolves to nobody. |
377
+ | `listWithCounts()` / `listWithCounts({ q, page, pageSize })` | The admin list with the app's `counts`. **Refused below platform scope on Postgres** (db-worker's `assertPlatformScope`, `code: 'tenant_scope_refused'`): at a partner's scope every count would silently be that partner's. With an argument: one page, `q` searching names case-blind and escaped, `{ rows, total, pager }`. |
378
+ | `create(fields)` | Refuses a missing name, one over `nameMaxLength`, a given reference failing `refShape` (`code: 'PARTNER_REF_SHAPE'`, checked first), a missing host, SQLite, and a duplicate name, domain, host or given reference, each with a sentence naming the holder. Mints the reference when none is given. Takes `is_active` (default active) and the `create` extra columns. |
379
+ | `update(id, fields, opts)` | ONE transaction. Name clash; the reference by `refPolicy`; `portal_host` written only when the key is present (normalised by `normaliseHost`, never cleared for a non-house partner, host clash refused); `domain` written only with the host, duplicate refused; `update` extra columns preserved when omitted. `onChange(tx, { id, op: 'update', before, after, opts })` when a row changed. |
380
+ | `setActive(id, active, opts)` | ONE transaction. The house cannot be deactivated. `UPDATE … AND is_active <> ?`, so a repeat changes 0 rows. On deactivate: that partner's `users.session_version` bumped, then `onDeactivate(tx, { id, changes, opts })` (on every deactivate call, as the source does; both idempotent). `onChange(tx, { id, op: 'setActive', active, opts })` only when the flag moved. A hook that throws rolls everything back. |
381
+
382
+ **`mintHouseRef`** (required, no default). `true`: the house gets a minted reference at seed, as every other partner
383
+ does at create (the hub, whose reference is permanent and NOT NULL). `false`: the house is seeded with a NULL
384
+ reference, which the apps attached to the hub NEED: their hub-receive code binds the hub's house id to it once
385
+ (`… WHERE is_house = 1 AND external_ref IS NULL`) and refuses a house document when the house already holds another
386
+ reference, so a minted one would make the hub's house document refused for ever. Per app: hub `true`; starter, soc,
387
+ noc, wall `false` (their seed writes no reference today); the desk seeds its house in a migration and does not call it.
388
+ A new standalone app takes the starter's `false`; one that will be attached to the hub must pass `false`.
389
+
390
+ **`writesRequirePlatform`** (required, no default). `partners` has no row-level security, so nothing below the store
391
+ stops a write at a partner's scope: at partner A's scope an `update` or `setActive` writes partner B, and a
392
+ deactivation's sign-out of B's users is then filtered away by the policy on `users`, leaving B deactivated with its
393
+ people still signed in. That is every source's behaviour (the platform-only permission in front is the only guard), and
394
+ `false` keeps it. `true` makes `create`, `update`, `setActive` and `seedHouse` refuse unless the transaction runs
395
+ at platform scope (db-worker's `assertPlatformScope`, `code: 'tenant_scope_refused'`; Postgres only), before anything
396
+ is written. **A new app passes `true`** (the owner's answer, D-0005). For the existing apps it is each adoption's
397
+ choice; what `true` would change, from reading every caller at `origin/main`:
398
+
399
+ | App | Callers of create / update / setActive / seedHouse, and their scope today | What `true` would change |
400
+ |---|---|---|
401
+ | a new app | — | `true` |
402
+ | starter | `seedHouse` in `lib/scope.js` under `asPlatform`; the partners routes (update, setActive) behind platform-only `partners.manage`, so at the request's platform scope; `createPartner` from that route | Nothing found |
403
+ | hub | `seedHouse` in `server.js` under `asPlatform`; the partners routes (update, setActive, create through provisioning) behind platform-only `partners.manage` | Nothing found |
404
+ | soc | `seedHouse` under `asPlatform` (`server.js`); the partners routes as above; `lib/hubPartner.js` (update, create through provisioning) and `routes/ops.js` (update) all inside `asHouse()`, which is platform scope | Nothing found (its `setActiveFromHub` and `bindHouseRef` are its own methods, not the store's) |
405
+ | noc | as soc (`lib/scope.js` seed, `lib/hubPartner.js` and `routes/ops.js` in `asHouse()`) | Nothing found |
406
+ | wall | as soc (`lib/scope.js` seed, `lib/hubPartner.js` in `asHouse()`) | Nothing found |
407
+ | desk | the partners routes (update, setActive) behind platform-only `partners.manage`; `lib/hubPartner.js` (update, setActive, create through provisioning) and `routes/ops.js` (setActive) inside `asHouse()`; no `seedHouse` | Nothing found |
408
+
409
+ "Nothing found" is a reading of those files, not a run: each adoption confirms it with the app's own suites, and any
410
+ script or job outside `lib/`, `routes/` and the boot file that writes partners is not covered by it. One is known: the
411
+ hub's test harness `scripts/lib/syncWorld.js` (line 76) calls `seedHouse` through its in-process bridge with no scope
412
+ wrapper. It runs on SQLite today, where nothing is refused; pointed at PostgreSQL with `true` it would be, so the hub
413
+ wraps it in `asPlatform` at adoption.
414
+
415
+ **On SQLite `writesRequirePlatform` does nothing** (the scope assertion is PostgreSQL-only, as in the sources), so an
416
+ app's SQLite chain can never show the guard working: its PostgreSQL gate must carry the test.
417
+
418
+ **`refPolicy`.** `'editable'` writes the reference as given, an absent or empty one stored as NULL (the starter's
419
+ contract). `'permanent'` refuses any named value but the stored one, NULL and empty included (`code:
420
+ 'PARTNER_REF_PERMANENT'`, nothing saved), and never writes the column. A function is asked only when the reference
421
+ would change, with the current row: `true` locks it (`code: 'PARTNER_REF_LOCKED'`); `{ code, message }` locks it with
422
+ the app's own code and sentence (soc `PARTNER_REF_HUB_BOUND` / `PARTNER_REF_HAS_DATA`, wall `PARTNER_REF_HUB_BOUND` /
423
+ `PARTNER_REF_HAS_TENANT_DATA`, noc `PARTNER_REF_LOCKED` / `PARTNER_REF_HAS_TENANTS`), so its API answers do not change;
424
+ or it may throw its own typed refusal. This package imports no hub code: the app passes its own predicate.
425
+
426
+ **`extraColumns`**: `[{ name, create?, update?, list?, param?, read? }]`. `create: true` inserts the column when the
427
+ field is present; `update: true` writes it, preserving the stored value when omitted (`read(stored)` turns the stored
428
+ value back into a field, `param(value)` into a statement parameter: a JSON column passes `sql.jsonColumn` /
429
+ `sql.jsonParam`); `update: 'now'` stamps `sql.now()` on every update; `list: true` selects it in `all()` and the list.
430
+
431
+ ### `createProvisioner(options)` — creating a partner and seeding it
432
+
433
+ ```js
434
+ // lib/partnerProvision.js (main thread)
435
+ module.exports = createProvisioner({
436
+ tenancy, db, rbac, logger, // REQUIRED: asPartner (+ currentTenant), invoke, refresh(id), info/error
437
+ writesRequirePlatform: true, // REQUIRED: the same value the partner store is given (below)
438
+ seeds: [ // REQUIRED, the app's own list, run in order INSIDE asPartner(id)
439
+ { name: 'roles', run: ({ db }) => db.invoke('Role', 'seedDefaults').then((r) => r && r.seeded) },
440
+ { name: 'templates', run: ({ db }) => db.invoke('EmailTemplate', 'seedDefaults').then((r) => r && r.seeded) },
441
+ { name: 'reports', run: ({ db }) => db.invoke('Report', 'seedDefaults').then((r) => r && r.seeded) }
442
+ ],
443
+ deactivateWith: (id, opts) => db.invoke('Partner', 'setActive', id, 0), // REQUIRED (an attached app: its hub path)
444
+ onPartnersChanged: [ // REQUIRED: a function, or a list: all started at once, each isolated
445
+ () => tenancy.refreshActivePartners(), // first: it is the one that ends acting
446
+ () => hosts.forget()
447
+ ]
448
+ });
449
+ ```
450
+
451
+ - **`onPartnersChanged(event)`** is the ONE callback after a write to the partner list has committed, on the main
452
+ thread, **for every write that goes through the provisioner**: after `createPartner` (`{ op: 'create', id }`, also
453
+ when a half-built partner could not be deactivated), after the deactivation of a half-built partner (`{ op:
454
+ 'deactivate', id }`: `deactivateWith` invokes the store directly and the provisioner fires once after it, so it
455
+ must not go through `write` as well), after `updatePartner` and `setPartnerActive` (`{ op: 'update' | 'activate' |
456
+ 'deactivate', id, changes }`), and after **`write(method, ...args)`**, which invokes any store method directly
457
+ (`write('setActiveFromHub', id, 0)`, `write('bindHouseRef', ref)`, `write('update', id, fields)`), fires once after
458
+ it returned, not when it throws, and returns its answer unchanged (`{ op: method, id, changes }`, `id` when the
459
+ first argument is one). **`partnersChanged(event)`** is the same guarded notifier on its own, for a write the app
460
+ makes some other way: call it right after the write returns. **The app wires the callback to both `tenancy.refreshActivePartners()`
461
+ (`createTenancy`) and `hosts.forget()` (`createHostTenant`).** It is a function or a LIST of functions: every entry
462
+ is STARTED AT ONCE, in array order (each called before any is awaited), each ISOLATED, and the write answers only
463
+ after all have settled. One that throws or rejects (a host `forget()` whose app `onForget` throws) is logged at
464
+ error, naming its position (`onPartnersChanged entry 2 of 2`), and stops none of the others; so the stale mark and
465
+ the host forget both happen at once, and order does not matter for correctness (keep the refresh first by
466
+ convention). **Every entry must settle**: nothing bounds one that never does, and it would hold the write's
467
+ response for ever. The package's own two do: `refreshActivePartners()` is bounded by `activeLoadTimeoutMs` (twice
468
+ that behind a load in flight), `forget()` is synchronous. Nothing a subscriber does changes the write's answer; a
469
+ write that throws fires nothing.
470
+ - **The store's write methods called directly do NOT fire it** (the store runs in the worker, inside the write's
471
+ transaction, and cannot reach a main-thread cache; its `onChange` is for in-transaction work). So every main-thread
472
+ write to the partner list goes through the provisioner (`updatePartner`, `setPartnerActive`, `write`) or calls
473
+ `partnersChanged()` right after. **The attached apps' hub-receive paths are the ones to convert**: soc, noc and wall
474
+ `lib/hubPartner.js` (`update`, `setActiveFromHub`, `bindHouseRef`, `setHubHost`, and wall's `applyHubBlock` / `setHubVersion`), soc
475
+ and noc `routes/ops.js` (`setActiveFromHub`, `update`), wall `routes/ops.js` (`setActiveFromHub`), and the desk's
476
+ `lib/hubPartner.js` / `routes/ops.js` (`update`, `setActive`, `bindHouseRef`). Otherwise a partner deactivated AT THE
477
+ HUB, the normal way for an attached app, would not end acting into it nor clear its host until a restart.
478
+ - `provision(partnerId, opts)` runs every seed inside the partner's scope, then **`rbac.refresh(partnerId)` after
479
+ every provision**, the re-provision route's included. Returns `{ <seed name>: what it returned }`. A seed that
480
+ returns `undefined` is an error; `ctx.rows(model, method, …args)` is a read that refuses anything but an array (an
481
+ empty array has to mean empty). A seed gets `{ db, partnerId, rows, tenancy, opts }`.
482
+ **`tenancy` is there by convention, not as a guard**: the desk needs it to read the house's canned replies and
483
+ knowledge-base categories (`tenancy.asPartner(houseId, …)`) before seeding them into the new partner. A seed can
484
+ therefore leave the new partner's scope; one that WRITES outside it must say so in a comment beside the write.
485
+ - `createPartner(fields, opts)` invokes `Partner.create(fields[, opts])`, provisions, logs one info line, returns the
486
+ partner with `seeded`. On a failure it calls `deactivateWith(id, opts)` and throws an error with `partnerId`,
487
+ `deactivated` and `cause`. **If the deactivation itself fails, that is logged at error and the error says the
488
+ partner is still active (`deactivated: false`)** (every copy swallowed it with `.catch(() => {})` while the log said
489
+ "left DEACTIVATED"). The failure path cannot itself fail: every log call is guarded, so a throwing logger never
490
+ replaces the provisioning error, and one that throws on success never turns a provisioned partner into a failed one.
491
+ - **`writesRequirePlatform`** (required, no default; pass the same value as the store's). `true`: `createPartner`,
492
+ `provision`, `updatePartner`, `setPartnerActive` and `write` refuse unless the CURRENT tenant context is platform
493
+ scope (`tenancy.currentTenant()`, read on the main thread; `code: 'tenant_scope_refused'`), BEFORE anything is
494
+ written or any seed runs: `provision(B)` runs its seeds inside `asPartner(B)`, so without it a caller at partner A's
495
+ scope (A's staff, or an operator ACTING as A) seeds B. It reads no database, so it refuses on SQLite too, where the
496
+ store's own check does nothing. `false`: today's behaviour (the platform-only permission in front is the only
497
+ guard). This follows Platform decision D-0005 point 1, extended by the coordinator from the partner table to
498
+ provisioning and reported to the owner. A new app passes `true`; what `true` would change in each existing app,
499
+ from reading the callers of `createPartner` and `provision` at `origin/main` (not a run):
500
+
501
+ | App | Callers, and their scope today | What `true` would change |
502
+ |---|---|---|
503
+ | a new app | — | `true` |
504
+ | starter | the partners routes (create, re-provision) behind platform-only `partners.manage`; `scripts/test-pg.js` inside `asHouse` | Nothing found in the routes. `scripts/test-partner-lifecycle.js` line 383 calls `provision(made.id)` with no scope wrapper in the lines read: verify at adoption, wrap it in `asPlatform` if refused |
505
+ | hub | the partners routes as above; `scripts/seed-showcase.js` inside `asHouse` | Nothing found in the routes. `scripts/test-partner-lifecycle.js` line 704: as the starter's |
506
+ | soc | the partners routes as above; `lib/hubPartner.js` (create) inside `asHouse()`; `scripts/lib/askWorld.js` at platform scope | Nothing found |
507
+ | noc | the partners routes as above; `lib/hubPartner.js` inside `asHouse()`; its `*-pg.js` test scripts inside `asHouse` | Nothing found |
508
+ | wall | the partners routes as above; `lib/hubPartner.js` inside `asHouse()`; `scripts/test-pg.js` at platform scope | Nothing found in the routes. `scripts/test-partner-lifecycle.js` line 381: as the starter's |
509
+ | desk | the partners routes as above; `lib/hubPartner.js` inside `asHouse()`; `scripts/prepare-test-db.js` inside `asHouse` | Nothing found in the routes. `scripts/test-partner-lifecycle.js` line 334: as the starter's. Its seeds that read the house (`tenancy.asPartner(houseId, …)`) run after the check, so they are unaffected |
510
+
511
+ ### `actingRoutes(options)`, `actingLocals(options)`, `views/acting-banner.ejs`
512
+
513
+ ```js
514
+ // routes/partners.js: mounted BEFORE every '/:id' route (Express matches in declaration order)
515
+ router.use(actingRoutes({
516
+ Router: express.Router, tenancy, db, audit, requirePermission,
517
+ permission: 'partners.manage', // REQUIRED: the app's own permission name
518
+ landing: '/', // REQUIRED: a local path; '//host' and 'http:' are refused
519
+ refuseInactive: true, // REQUIRED, no default (below)
520
+ auditScopes: { start: 'house', stop: 'partner' }, // REQUIRED, no default (below): where the two audit rows land
521
+ logger, // { error }: REQUIRED when an auditScopes value is 'both'
522
+ messages: {}, // optional: house, inactive(name), started(name), notActing, stopped, unknown
523
+ flash: undefined, // optional: (req, res, type, message) => void | Promise (below)
524
+ notFound: undefined // optional: (req, res) => the app's 404 answer (below)
525
+ }));
526
+ // app.js, after the session and scope middleware
527
+ app.use(actingLocals({ tenancy, readOnly: false /* the write gate's whileActing === 'readOnly' */, note: null }));
528
+ app.set('views', [path.join(__dirname, 'views'), require('@aria-framework/tenancy').viewsDir /* , … */]);
529
+ // views/partials/staff-head.ejs
530
+ <%- include('acting-banner') %>
531
+ ```
532
+
533
+ - **Two things the routes need from the app, unless it overrides them:** a flash helper with the shape
534
+ `res.flash(type, message, callback)`, WITH a callback (the redirect happens inside it; a helper of another shape
535
+ answers a 500), and a view `errors/404` (rendered with `{ title: 'Not found' }`). An app whose helpers differ passes
536
+ `flash(req, res, type, message)` (it may return a promise; the redirect follows when it settles, a rejection is
537
+ `next(err)`) and/or `notFound(req, res)`; neither has a default other than those two.
538
+ - `POST /:id/act-as` (behind `requirePermission(permission)`; a non-digit id falls through before the gate): an
539
+ unknown id answers the app's `errors/404` view (or flashes `messages.unknown`); the house and, with
540
+ `refuseInactive`, a deactivated partner are refused with a flash, **audited nothing and switched nothing**.
541
+ Otherwise **`partner.act_as_start` is audited BEFORE the switch**, so the row lands in the operator's own scope (the
542
+ house; with `auditScopes.start: 'both'` a second row in the partner too), then the session's `actingPartnerId` / `actingPartnerName` are set and the browser goes to `landing`.
543
+ - `POST /stop-acting` is **not behind any permission** (acting removes the platform-only ones, and the way out must not
544
+ depend on them): a user who is not platform staff gets the 404 view; an operator not acting is sent to `landing`;
545
+ otherwise the flags are cleared and **`partner.act_as_stop` is audited AFTER the switch back** (in the scope
546
+ `auditScopes.stop` names: with `'partner'`, every app's value today, it lands in the partner the operator was
547
+ inside, because the request's tenant was fixed when the request began; NOT in the house), then back to the
548
+ mount (`back` when set; else `req.baseUrl`, checked at request time to be a local path; else `landing`). Both save callbacks pass a store error to `next(err)`, never throw.
549
+ - `actingLocals` sets `actingPartnerName` **only when `tenancy.contextFor(req)` shows the scope has moved to that
550
+ partner** (a partner user's stray acting flag, which the scope code ignores, draws no banner), `actingReadOnly`
551
+ (`readOnly` while acting), `actingStopPath` (default `/admin/partners/stop-acting`) and `actingNote`.
552
+ - The banner escapes the name, needs the app's `csrfToken()` while it shows (it throws without it), and keeps the
553
+ starter's classes.
554
+
555
+ **`auditScopes: { start, stop }`** (required, no default). Where the two rows land: `start` is `'house'` or
556
+ `'both'`; `stop` is `'partner'`, `'house'` or `'both'`. `'house'` is the operator's own scope (`contextFor` once
557
+ the acting keys are absent), `'partner'` the partner acted in, `'both'` one row in each. The owner decided on 29 Nov
558
+ 2026 that the stop entry goes into both logs.
559
+
560
+ - **What each row contains.** Both rows of a pair are built by the app's own `audit(req, action, opts)` from the same
561
+ request, so they are the same action and detail: the operator, as the app's own helper writes an actor (`actor_type: 'staff'`, the house user's id and display name or username; an app's helper may add more: the hub's also writes the actor's email and public id), the partner
562
+ (`entity_type: 'partner'`, `entity_id`), the start's `detail: { name }`, the address the request came from (`ip_address`) and the user agent. So with `'both'` (or today's `stop: 'partner'`) a partner's audit log shows who of the house staff acted, by name and id, and from which address. Neither carries
563
+ the acting stamp (`acting_as_partner`): the start row is written before the keys are set and the stop row after
564
+ they are removed, as today. Only `partner_id` differs, from the scope each is written in. The partner's row is what
565
+ the source's stop row is today, nothing more.
566
+ - **Order and failure.** The start rows are written before the switch, the stop rows after the switch back, as today.
567
+ The row today's code writes (the start row in the house, the stop row in the partner) is called exactly as today, in
568
+ the request's context: a synchronous throw from the app's `audit` stops the switch at the start (as the source);
569
+ an asynchronous failure is the app's helper's to log, as today. With `stop: 'house'` the one stop row is written in
570
+ the operator's own scope (`tenancy.run(contextFor(req), …)`), with today's failure behaviour. The ADDED row of a
571
+ `'both'` is written in its own scope (`tenancy.run`) and isolated: a throw or a rejected promise from `audit` is
572
+ logged at error (`logger`) and undoes no switch and fails no request.
573
+
574
+ | App | `auditScopes` |
575
+ |---|---|
576
+ | starter, hub, soc, noc, wall, desk | `{ start: 'house', stop: 'partner' }` (today's, in all six) |
577
+ | a new app | `stop: 'both'` (decided); `start`: owner to confirm: `'house'` or `'both'` |
578
+
579
+ **`refuseInactive`, and acting inside a partner that is deactivated** (the owner's answers 2 and D-0005). The rule as
580
+ decided: no house operator works inside a deactivated partner. Two halves enforce it: **the switch refuses a deactivated
581
+ partner** (`refuseInactive`, here), and **an operator already inside a partner when it is deactivated is no longer
582
+ acting in any request that begins after the deactivating call has returned** once the app passes `actingRequiresActive: true` to `createTenancy` (`contextFor` stops honouring an acting
583
+ flag for a partner that is not active; the scope part learns of the change through `tenancy.refreshActivePartners()`, which the app calls from `onPartnersChanged`, and the banner
584
+ follows `contextFor`, so it disappears with it). **Both are on for a new app; each existing app turns them on at its own
585
+ adoption.** `refuseInactive` is required with no default so that no existing app changes silently.
586
+
587
+ `tenancy` functions this part calls: `asPartner(partnerId, fn)` and `currentTenant()` (the provisioner), `contextFor(req)`
588
+ (`actingLocals`, and the stop route for a `stop` of `'house'` or `'both'`) and `run(context, fn)` (the acting routes, for a
589
+ row written outside the request's own scope).
590
+
591
+ ## Wiring the three parts
592
+
593
+ The three parts were built against stand-ins for each other; this is how they join, and it is exactly the assembly
594
+ `test/integration/` runs on PostgreSQL under row-level security and on SQLite (its `helpers.js` holds the same lines
595
+ between its `WIRING` markers). `test/integration/surface.js` checks EVERY code block of this section: the first must
596
+ equal those lines; any other must appear in `helpers.js` line by line in the same order (`/* … */` stands for
597
+ anything, a trailing `//` comment is ignored), unless its first line is `// illustrative:`, which marks a sketch of
598
+ app code the integration app has no counterpart for.
599
+
600
+ ```js
601
+ // The main thread. `db` is the app's db client, `logger` its logger, `rbac` its role cache (`refresh(partnerId)`);
602
+ // `dbKind`, `actingRequiresActive`, `writesRequirePlatform` and `refuseInactive` are the app's settings (a new app:
603
+ // 'postgres', true, true, true; ONE writesRequirePlatform constant goes to the store and the provisioner); MESSAGES its sentences;
604
+ // `auditScopes` for actingRoutes (every existing app: { start: 'house', stop: 'partner' }; a new app: stop 'both').
605
+ const {
606
+ createTenancy, createWriteGate, createHostTenant, createTenantChrome, createProvisioner, actingRoutes, actingLocals, viewsDir
607
+ } = require('@aria-framework/tenancy');
608
+
609
+ // 1. The scope part first: everything else takes `tenancy`.
610
+ const tenancy = createTenancy({ db, logger, dbKind, platformRequiresHouse: true, actingRequiresActive });
611
+
612
+ // 2. The hosts part: the per-tenant chrome, the request chrome that applies it, then host resolution.
613
+ const chrome = createTenantChrome({ tenancy, db, fields: createTenantChrome.STARTER_FIELDS });
614
+ const requestChrome = {
615
+ async applyTo(res) {
616
+ const t = tenancy.currentTenant();
617
+ const c = await chrome.chromeFor(t ? t.partnerId : null);
618
+ res.locals.displayTimezone = c.displayTimezone;
619
+ }
620
+ };
621
+ const hosts = createHostTenant({
622
+ tenancy, db, logger, trustForwardedHost: false, chrome: requestChrome, isSignedIn: (s) => !!s.user
623
+ });
624
+
625
+ // 3. The partners part: ONE callback after every committed write to the partner list, to BOTH caches.
626
+ const provisioner = createProvisioner({
627
+ tenancy, db, rbac, logger, writesRequirePlatform, // the same value the partner store is given
628
+ seeds: [
629
+ { name: 'roles', run: ({ db: d }) => d.invoke('Role', 'seedDefaults').then((r) => r.seeded) },
630
+ { name: 'settings', run: ({ db: d, opts }) => d.invoke('Settings', 'seedDefaults', opts && opts.timezone).then((r) => r.seeded) }
631
+ ],
632
+ deactivateWith: (id) => db.invoke('Partner', 'setActive', id, 0),
633
+ // All started at once, each isolated, all settled before the write answers; the active set first by convention.
634
+ onPartnersChanged: [
635
+ () => tenancy.refreshActivePartners(), // marks the active set stale at once, then reloads it
636
+ () => hosts.forget() // the host map: re-read at the next lookup
637
+ ]
638
+ });
639
+
640
+ // 4. The write gate.
641
+ const gate = createWriteGate({
642
+ tenancy, whileActing: 'write', houseReading: null, messages: MESSAGES, logger,
643
+ partnerById: (id) => db.invoke('Partner', 'byId', id)
644
+ });
645
+ ```
646
+
647
+ ```js
648
+ // app.js, in this order (the app supplies res.flash(type, message, callback) and an errors/404 view, or passes
649
+ // actingRoutes its own flash and notFound)
650
+ app.set('views', [path.join(__dirname, 'views'), viewsDir]);
651
+ app.use(session({ /* … */ }));
652
+ app.use(tenancy.requestScope()); // after the session, before the first router
653
+ app.use(actingLocals({ tenancy, readOnly: false })); // after the scope: it asks contextFor
654
+ app.use((req, res, next) => { requestChrome.applyTo(res).then(() => next(), next); });
655
+ loginRouter.use(hosts.middleware()); // the login routers only, never app.use
656
+ app.use('/admin/partners', actingRoutes({ Router: express.Router, tenancy, db, audit, requirePermission, logger,
657
+ permission: 'partners.manage', landing: '/dashboard', refuseInactive, auditScopes })); // before the app's '/:id' routes
658
+ app.use('/admin/partners', partnerRoutes); // its writes: provisioner.createPartner / updatePartner / setPartnerActive / provision
659
+ ```
660
+
661
+ ```js
662
+ // illustrative: the worker and the boot file of a real app (the integration app builds its models in fixtures.js)
663
+ // models/Partner.js: the partner model is the store (scope reads its house/all/seedHouse, hosts its all, the acting
664
+ // routes and the gate its byId), given the same writesRequirePlatform as the provisioner.
665
+ module.exports = createPartnerStore({ driver: () => database.driver(), sql, writesRequirePlatform, /* … */ });
666
+ // server.js
667
+ await tenancy.atBoot(async () => { /* the rest of boot, in the house scope */ });
668
+ ```
669
+
670
+ **Order.** Construct `tenancy` first (every other factory takes it), then the chrome and `hosts` (the provisioner's
671
+ callback needs `hosts`), then the provisioner, then the gate. Mount the session, `tenancy.requestScope()`,
672
+ `actingLocals`, the request chrome, and only then the routers.
673
+
674
+ **At boot**, `tenancy.atBoot(fn)`: it seeds the house (`Partner.seedHouse()` at platform scope, which
675
+ `writesRequirePlatform: true` requires), then makes the first load of the active-partner set (with
676
+ `actingRequiresActive`), then runs `fn` in the house scope. Nothing else needs a first load: the host map is read at
677
+ its first lookup and each partner's chrome at its first use. Until the active set is loaded, an acting flag is not
678
+ honoured by a synchronous `contextFor`; a request carrying one makes `requestScope` load the set first.
679
+
680
+ **The callback** is a list: the provisioner STARTS every entry at once, in array order, each isolated, and answers the
681
+ write after all have settled, so a host `forget()` that throws (an app's `onForget`) stops nothing, and the stale mark
682
+ and the host forget both happen at once; order does not matter for correctness (the refresh first by convention).
683
+ Every entry must settle (the package's two do: the refresh is bounded by `activeLoadTimeoutMs`, `forget()` is
684
+ synchronous). A refresh marks the active set stale at once, so a request carrying an acting flag that arrives while
685
+ its load is in flight waits for it (normally milliseconds, at most `activeLoadTimeoutMs`, twice that behind a load
686
+ already in flight; after ANY partner change, a rename included); a live stream's re-check awaits
687
+ `tenancy.whenActivePartnersKnown()` before `forSession`. **What is guaranteed, and no more:** a request that begins after the deactivating call has returned is not acting into that partner; a request already running inside the partner when the deactivation commits finishes there; and between the commit and the callback's refresh (a few milliseconds, inside the same call) a request may still be honoured. Reactivating the partner normally does not put an operator back inside; a request that overlapped the
688
+ deactivation can save its older session over the cleared keys, and then the operator is inside again once the
689
+ partner is active again.
690
+
691
+ **What the callback does not cover**, and what the app calls instead:
692
+
693
+ - a store write the app invokes directly (`db.invoke('Partner', …)`): go through `provisioner.write(method, …args)`,
694
+ or call `provisioner.partnersChanged()` right after. A write that does neither leaves acting into a deactivated
695
+ partner honoured and its host resolving until the next change (pinned in `test/integration/`);
696
+ - `provisioner.provision(id)` (a re-provision) and a settings save fire no callback: call `chrome.forget(id)` after each;
697
+ - another process: neither cache is shared. Pass `activeMaxAgeMs` (scope) and `maxAgeMs` (hosts), or tell the other
698
+ processes, each calling `hosts.forget()` and `tenancy.refreshActivePartners()`.
699
+
700
+ **Every name that crosses a part**, with the part that owns it:
701
+
702
+ | Name | Owner | Who uses it |
703
+ |---|---|---|
704
+ | `createTenancy(...)` → `tenancy` | scope | passed as `tenancy` to `createWriteGate`, `createHostTenant`, `createTenantChrome`, `createProvisioner`, `actingRoutes`, `actingLocals` |
705
+ | `tenancy.asPartner(id, fn)` | scope | hosts (`createHostTenant`, `createTenantChrome`), partners (`createProvisioner`: every seed runs inside it) |
706
+ | `tenancy.asPlatform(fn)` | scope | hosts (`createHostTenant` reads `Partner.all` in it) |
707
+ | `tenancy.housePartnerId()` | scope | hosts (`createHostTenant`: an unknown host narrows to the house) |
708
+ | `tenancy.currentTenant()` | scope | hosts (`createTenantChrome`'s `cached`; the app's request chrome), partners (`createProvisioner`'s `writesRequirePlatform`) |
709
+ | `tenancy.contextFor(req)` | scope | partners (`actingLocals`: the banner shows only when the scope moved) |
710
+ | `tenancy.refreshActivePartners()` | scope | the app, from `createProvisioner`'s `onPartnersChanged` |
711
+ | `tenancy.requestScope()`, `tenancy.atBoot(fn)` | scope | the app (mount; boot) |
712
+ | `actingRequiresActive` (option of `createTenancy`) | scope | ends acting into a partner deactivated through the provisioner |
713
+ | `hosts.forget()` | hosts | the app, from `createProvisioner`'s `onPartnersChanged` |
714
+ | `hosts.middleware()`, `hosts.partnerIdForRequest(req)`, `hosts.partnerOfHost(host)` | hosts | the app (login routers; a portal comparing a session with its host; a sign-in realm) |
715
+ | `chrome.forget(id)` | hosts | the app, after a settings save and after `provisioner.provision(id)` |
716
+ | `onPartnersChanged(event)` (option of `createProvisioner`) | partners | fired after every committed write through the provisioner; a function or a list, each entry isolated; the app passes `[() => tenancy.refreshActivePartners(), () => hosts.forget()]` |
717
+ | `writesRequirePlatform` (option of `createProvisioner`) | partners | refuses `createPartner`, `provision`, `updatePartner`, `setPartnerActive`, `write` unless `tenancy.currentTenant()` is platform scope; on both engines; the same value as the store's |
718
+ | `provisioner.createPartner`, `updatePartner`, `setPartnerActive`, `write`, `partnersChanged` | partners | the app's main-thread writes to the partner list |
719
+ | `writesRequirePlatform` (option of `createPartnerStore`) | partners | refuses a store write below platform scope: a partner's staff, and an operator ACTING as a partner (acting is partner scope) |
720
+ | `auditScopes` (option of `actingRoutes`) | partners | where the act-as start and stop rows land: `'house'` runs the app's `audit` in the operator's own scope (`tenancy.run`), `'partner'` in the partner, `'both'` in each |
721
+ | `tenancy.whenActivePartnersKnown()` | scope | the app, before `forSession` in a live stream's re-check (`@aria-framework/notify`'s `deps.scopeOf`) |
722
+ | `tenancy.run(ctx, fn)` | scope | partners (`actingRoutes`: a row written in an explicit scope) |
723
+ | `refuseInactive` (option of `actingRoutes`) | partners | refuses the switch into a deactivated partner; `actingRequiresActive` ends one already inside |
724
+ | `Partner.house()`, `Partner.seedHouse()` | partners (the store) | scope (`housePartnerId`, `atBoot`) |
725
+ | `Partner.all()` (with `id`, `is_active`, `portal_host`) | partners (the store) | scope (the active set), hosts (the host map) |
726
+ | `Partner.byId(id)` (with `name`, `is_house`, `is_active`) | partners (the store) | partners (`actingRoutes`), scope (the gate's `partnerById`, passed by the app) |
727
+ | session `actingPartnerId`, `actingPartnerName` | partners (`actingRoutes` writes them) | scope (`contextFor` reads them and, for a partner known inactive, deletes them) |
728
+ | `req.partnerId`, `req.partnerHost` | hosts (the middleware sets them) | the app's login routes |
729
+ | `res.locals.actingPartnerName`, `actingReadOnly`, `actingStopPath`, `actingNote` | partners (`actingLocals`) | partners (`views/acting-banner.ejs`, under `viewsDir`) |
730
+
731
+ ## Adopting it
732
+
733
+ _(per part: what an app deletes, what it passes in, and a table "What changes for an adopting app")_
734
+
735
+ ### Scope
736
+
737
+ - **Before adopting, search for every place the app calls the gate (its `writeScope`/`readScope`/`canAddTo` copies)
738
+ inside `asPartner`, `asHouse`, `asOwnPartner`, `asPlatform` or `acrossAll`.** That is where the old code and the
739
+ package can differ: the package's runner runs in the context it judged, the old partner-scope runner ran in the
740
+ surrounding one.
741
+ - `lib/tenant.js` becomes the `createTenancy` call (plus the app's own extras, added to the same object) and
742
+ `lib/scope.js` re-exports it. The hub and soc app delete their inline request-scope middleware in `app.js` for
743
+ `tenancy.requestScope()`; the desk deletes `middleware/tenant.js`.
744
+ - The write gate: the soc app deletes `canAddTo` and its five `readScope`/`writeScope` copies; the noc app deletes
745
+ `lib/customerScope.js` (keeping `canAddFirewallFor` over `gate.writeScope`); the hub deletes `createsLandInThisTenant`,
746
+ `writesReachThisTenant`, `editRefusal`, `platformDestination`, `authorship`, `houseOperatorNames` from `lib/tenant.js`;
747
+ the desk deletes `lib/tenantWriteRefusal.js` and mounts `gate.crossTenantWriteHandler()` before its error handler.
748
+
749
+ **What changes for an adopting app**
750
+
751
+ | # | App | Difference between the app's copy and the package | Keeps today's behaviour | Or intended by |
752
+ |---|---|---|---|---|
753
+ | 1 | hub, desk | `canHostTenants()` read `config.dbKind` | `dbKind: () => config.dbKind` | |
754
+ | 2 | starter, noc, wall | `canHostTenants()` returned `true` | `dbKind: 'postgres'` | |
755
+ | 2a | soc | `canHostTenants()` read `config.dbKind`, but its server refuses SQLite at boot (`lib/requirePostgres.js`) | `dbKind: 'postgres'` (so a harness on SQLite keeps the partner comparison its gate copies make) | |
756
+ | 3 | desk | platform scope honoured only for a house member (`isPlatformUser`), its middleware resolving the house first | `platformRequiresHouse: true` | |
757
+ | 4 | hub, soc, noc, wall, starter | the stored `scope_kind` trusted | `platformRequiresHouse: false` | the starter and new apps: `true` (owner's answer 1, at its own adoption) |
758
+ | 5 | desk | **for the desk's own session to confirm at its adoption:** a desk staff user with no partner is refused by the package (`contextFor` null, the session destroyed), where the desk's own code today widens them to the anonymous platform scope, or to a contact's partner when the session also carries a contact (its `middleware/auth.js` refuses such a user elsewhere) | | plan §1 row 25, "starter ahead" |
759
+ | 6 | desk | a portal contact placed inside `contextFor` | `contactScope: (s) => s.contact && s.contact.partner_id != null ? { scope: 'partner', partnerId: Number(s.contact.partner_id) } : null` | |
760
+ | 7 | desk | `forEachPartner` warmed the partner's chrome, swallowing its failure | `beforeEachPartner: (p) => chromeFor(p.id).catch(() => {})` | |
761
+ | 8 | desk | its API guard placed a platform principal by `isPlatformUser` | `forApiUser` does the same when `platformRequiresHouse` is true | |
762
+ | 9 | noc, wall | `lib/scope.js` had no `forSession` | | plan §3 rows 2, 4, "starter ahead" |
763
+ | 10 | every app | `asRefreshTokenOwner` required the API package and the `RefreshToken` model itself | `refreshTokenOwner: (raw) => db.invoke('RefreshToken', 'partnerForHash', hashRefresh(raw))` | |
764
+ | 11 | every app | a test replacing `require('./tenant').asHouse` was seen by the seam | export the tenancy object itself (see "the seam calls at call time") | |
765
+ | 12 | desk | the house id's error and the refused-platform log named its own migration | | log wording only |
766
+ | 13 | hub | `writesReachThisTenant` (a boolean) answered yes at partner scope without comparing | `writeScope` does not compare on SQLite (`dbKind`) | on Postgres it compares (plan §3, corrected by the controller) |
767
+ | 14 | hub | at platform scope the house's own row was written at platform scope with the house id | | the runner writes it at `asPartner(house)` (plan §3: the runner shape) |
768
+ | 15 | hub | `editRefusal` returned `{ partner, message }` and logged nothing | its two sentences as `messages.unscopable` and `messages.notActing` (a function of `{ name }`) | `refusal` adds `reason` and logs each refusal (the desk's log) |
769
+ | 16 | hub | `authorship` returned `{ userId, actedBy }`; `houseOperatorNames(ids)` read `User.displayNamesByIds` | `houseOperatorNames(ids, { namesOf: (ids) => db.invoke('User', 'displayNamesByIds', ids) })` | `authorship` also returns `actedByName` (the soc and noc apps' field; unused by the hub) |
770
+ | 17 | hub | `platformDestination` read `Partner.byId` itself | `partnerById: (id) => db.invoke('Partner', 'byId', id)` | |
771
+ | 18 | soc | `canAddTo` answered yes at any partner scope (and with no context) without comparing | | plan piece 7: replaced by `writeScope`, which compares on Postgres |
772
+ | 19 | soc, noc | `writeScope(customer)` / `readScope(customer)` took the row, read `currentTenant()`, and at partner scope ran the callback in whatever scope surrounded it | a route passes `req`; a job passes `null` (`writeScope(null, row.partner_id)`, `readScope(null, row.partner_id)`), which judges the current scope as today | every runner, on every branch, runs in the context it judged, never in the surrounding scope (see "Which context the gate judges") |
773
+ | 20 | soc | the house reading: `readingOfRequest` + `housePartnerId` passed into its `readScope(customer, house)` | `houseReading: '<its fleet permission>'`, `readScope(pid, { house: await gate.houseReadingOf(req, res.locals.can) })` | `readScope` throws when `{ house }` is missing |
774
+ | 21 | desk | **for the desk's own session to confirm at its adoption:** `otherPartnerRefusal` compared the row with the user's OWN partner; acting on a row saying the house was allowed (reachable only on SQLite, where every row says 1) | | `'readOnly'` refuses every write while acting (its 23 Oct rule, now without the SQLite gap) |
775
+ | 22 | desk | **for the desk's own session to confirm at its adoption:** on SQLite the desk's own-partner comparison is not made, so a non-house partner user's write to a row saying partner 1 is no longer refused. Unreachable while SQLite holds only the house; the desk checks whether its SQLite test chain asserts that refusal | | the hub's SQLite rule |
776
+ | 23 | desk | `actingCreateRefusal(req, what)`; acting on a missing row (null) answered null, then "not found" | `refusal(req, null, what)` / `createsLand(req)` | acting with no row now gets the acting sentence first |
777
+ | 24 | desk | **for the desk's own session to confirm at its adoption:** `actingAuthorRefusal` matched the raw acting flag and an actor-column word in the constraint | | the acting 409 is decided as its `isActingCrossTenantWrite` decided it: any composite tenant key (`fk_*_partner`), the scope moved to the flagged partner; a stray flag on a partner user no longer gets the acting sentence |
778
+ | 25 | desk | two handlers, two views' titles in code | `messages.crossTenant`, `refusalView: 'errors/generic'` | one handler |
779
+ | 26 | desk | `flashTextFor`, `isPlatformCrossTenantWrite`, `isActingElsewhere` | `crossTenantRefusalOf(err, req)` (+ its own flash sentence per `kind`), `actingElsewhere(req)` | |
780
+ | 27 | hub, soc, noc, wall | no cross-tenant refusal handler: such a write was a 500 | | mounting `crossTenantWriteHandler()` is the app's choice at adoption (it needs a view) |
781
+ | 28 | every app | an acting flag was honoured into a deactivated partner until the operator switched out | `actingRequiresActive: false` | `true` at each app's own adoption (the owner's decision of 29 Nov 2026), with `tenancy.refreshActivePartners()` called from `createProvisioner`'s `onPartnersChanged` |
782
+ | 29 | soc, noc | a job that gated a write with `writeScope(customer)` judged the current scope | it passes `null` as the request | |
783
+ | 30 | every app | (with `actingRequiresActive: true`) a request arriving while a refresh's load was in flight was answered from the set held before the change | | intended: `refreshActivePartners()` marks the set stale at once; such a request waits for the fresh load |
784
+
785
+ ### Hosts
786
+
787
+ The three files keep their paths and become the package's, so no `require` moves:
788
+
789
+ ```js
790
+ // lib/hostname.js
791
+ const { hostname } = require('@aria-framework/tenancy');
792
+ const RESERVED = { reservedLabels: [] }; // the hub: ['registry', 'node', 'apt']
793
+ module.exports = {
794
+ ...hostname,
795
+ hostFor: (label, base) => hostname.hostFor(label, base, RESERVED),
796
+ refuseReservedHost: (host, base) => hostname.refuseReservedHost(host, base, RESERVED),
797
+ assertLabelNotReserved: (label) => hostname.assertLabelNotReserved(label, RESERVED)
798
+ // the hub keeps hostLabelOf, partnerHostLabel, partnerHubHost here
799
+ };
800
+
801
+ // lib/tenantChrome.js
802
+ const { createTenantChrome } = require('@aria-framework/tenancy');
803
+ module.exports = createTenantChrome({ tenancy: require('./tenant'), db: require('./db-client'), fields: createTenantChrome.STARTER_FIELDS });
804
+
805
+ // middleware/hostTenant.js
806
+ const ht = require('@aria-framework/tenancy').createHostTenant({
807
+ tenancy: require('../lib/tenant'), db: require('../lib/db-client'), logger: require('../lib/logger'),
808
+ trustForwardedHost: require('../config').trustForwardedHost, chrome: require('../lib/requestChrome'),
809
+ isSignedIn: (s) => !!s.user // the desk: (s) => !!(s.user || s.contact)
810
+ // the noc app also: maxAgeMs: 60000, onForget: <its hub host store's reset>
811
+ });
812
+ module.exports = { hostTenant: ht.middleware, forget: ht.forget, partnerIdForRequest: ht.partnerIdForRequest, partnerOfHost: ht.partnerOfHost };
813
+ ```
814
+
815
+ The apps' own source checks of WHERE the middleware is mounted (the login routers only, never `app.js`, the
816
+ `forget()` count in the partner routes, the invite router, the partner model's host refusal) stay in each app's
817
+ `test-host-tenant.js`; the cases about the moved code are in this package's `test/hosts/`.
818
+
819
+ **Every code path in the app that creates, changes, activates or deactivates a partner must call `forget()`** (the
820
+ partner routes, a hub-receive path, any provisioning that runs in a serving process). The package cannot see those
821
+ writes. Test the obligation through the app's own route: deactivate a partner there, then ask `partnerOfHost` (or
822
+ sign in) on its host and expect `null` (the house); a count of `forget()` calls in the source is not enough on its
823
+ own. `forget()` reaches one process only: an app run as more than one process must tell the others, or accept the
824
+ `maxAgeMs` bound as the longest a deactivated host may still resolve there.
825
+
826
+ **What changes for an adopting app**
827
+
828
+ | # | App | Difference between its copy and the package | Keeps today's behaviour / why it changes |
829
+ |---|---|---|---|
830
+ | 1 | all | `hostFor`, `refuseReservedHost`, `assertLabelNotReserved` take a required `{ reservedLabels }` | pass `[]` (the hub its three) through the wrapper above |
831
+ | 2 | hub | its `RESERVED_LABELS` list is the caller's option, no longer an export | `reservedLabels: ['registry', 'node', 'apt']`; its test reading `RESERVED_LABELS` reads its own constant |
832
+ | 3 | hub | the reserved refusal says "reserved for this installation's own components (…)" instead of "the hub's own components (…)" | intended (the package names no app); the hub's `test-host-tenant.js` message regex changes with it |
833
+ | 4 | all | `hostFor` also refuses a label that is not one valid DNS label | intended (the hub's rule that a partner's label is one label); every caller in the six apps passes `labelFromDomain(…)` or `randomLabel()`, which always give one |
834
+ | 5 | desk | the no-base-domain refusal names the Partners screen, not "Admin, Settings" | intended: the desk's own base-domain form is on its Partners list (appendix §4 row 2) |
835
+ | 6 | desk | hostname comments say "installation's own address" for "vendor's portal" | wording only |
836
+ | 7 | all | `trustForwardedHost` is passed in, not read from `config` inside the middleware | pass `config.trustForwardedHost` |
837
+ | 8 | all | `chrome` (the request chrome to re-apply) is passed in | pass `lib/requestChrome.js` |
838
+ | 9 | starter, hub, soc, wall, desk | a host-map reload that fails after `forget()` answers the last map (and warns) instead of failing open to the request's prior scope (middleware) or throwing (lookups) | intended: the noc app's fix (plan piece 8; appendix §5 row 3) |
839
+ | 10 | noc | the map's AGE: today its portal map is bounded at about 60 s only while something reads its hub host store (a read of that store when it is older than 60 s drops the host map too); with hub sign-in off nothing reads the store and there is no bound. Every other app's map has no age bound (it changes only on `forget()` or a restart). The hub host store itself was built from the SAME `Partner.all` read and cleared by the same `forget()`; the package has no load hook | pass `maxAgeMs: 60000`: keeps its bound, and with hub sign-in off makes it stricter than today (a reload at most once a minute; harmless), and pass `onForget` to clear the store; the store then does its own read (or adopts the hub packages' store, step 3). Its `H12` case (the hub address survives a failed reload) stays with the store. The other apps pass no `maxAgeMs` (keeps theirs) |
840
+ | 11 | noc | the extra exports `loadHosts`, `_hostMapForTests`, `HUB_HOSTS_MAX_AGE_MS`, `_hubAgeForTests` | not in the package; its tests use `partnerOfHost`/`forget()` |
841
+ | 12 | all | `isSignedIn` is required: the session test is passed in | five apps pass `(s) => !!s.user`; the desk `(s) => !!(s.user \|\| s.contact)` (a contact is stepped around as well as a staff session) |
842
+ | 13 | desk | the request fields are `req.partnerId` / `req.partnerHost`, not `req.portalPartnerId` / `req.portalHost` | intended: plan piece 8 (the desk renames on adoption) |
843
+ | 14 | desk | warnings say "Partner host(s)" and "a username in two tenants" for "Portal host(s)" and "a contact" | wording only |
844
+ | 15 | hub | `partnerForRequest` is named `partnerIdForRequest` | export it under the old name too, or rename the portal's calls; the function is the same |
845
+ | 16 | hub | its `lib/oidc/mount.js` keeps a second `rawHostOf(req, trustForwardedHost)` with the same rule | not moved (not in the plan); a candidate to call the package instead |
846
+ | 17 | all | chrome `fields` is required and must include `sessionTimeoutMs` | five apps pass `createTenantChrome.STARTER_FIELDS`; the desk its four (brand, zone, date style, timeout) |
847
+ | 18 | desk | `brandNow()` | `chrome.cached('brandName', <its neutral brand>)` |
848
+ | 19 | all | the chrome cache key is `p:<id>` (db-worker's `tenantCacheKey`) instead of the number | none visible: the same entries, `forget(id)` drops the same one |
849
+ | 20 | all | while host-map reloads keep failing, one warning at the start, at most one a minute after, one info line on recovery, instead of a warning per lookup | intended (review of the package) |
850
+ | 21 | all | the reserved-label, IDN and `isHostLabel` examples in comments and tests use invented names | wording only |
851
+
852
+ ### Partners
853
+
854
+ - `models/Partner.js` becomes `{ ...createPartnerStore({...}), ...` the app's hub-receive and own methods `}` (the hub
855
+ keeps `ensureExternalRefs`, `setDesk`, `setTakeover`, `ensureHouseDesk`; the attached apps their `byExternalRef`,
856
+ `setActiveFromHub`, `setHubVersion`, …). An app-specific refusal before a core method (the desk's hub-managed name,
857
+ active state and host flag) stays as a wrapper around that method.
858
+ - `lib/partnerProvision.js` becomes the `createProvisioner` call; the re-provision route drops its own
859
+ `rbac.refresh` (the desk) because `provision` does it.
860
+ - `routes/partners.js` deletes its `stop-acting` and `/:id/act-as` handlers and mounts `actingRoutes` before its first
861
+ `/:id` route; `app.js` replaces its `actingPartnerName` (and `actingReadOnly`) locals with `actingLocals`;
862
+ `views/partials/staff-head.ejs` replaces its banner block with `include('acting-banner')` and adds `viewsDir`. An app
863
+ test that reads the banner's condition out of `staff-head.ejs` (the starter's `test-act-as-partner.js`) re-points
864
+ at the package's view, whose own tests now hold it.
865
+ - Every main-thread write to the partner list goes through the provisioner (`updatePartner`, `setPartnerActive`,
866
+ `write`) or calls `partnersChanged()` after it; an attached app converts its hub-receive paths (named under
867
+ "Partners"). **Test obligation at adoption:** deactivate a partner through the app's OWN hub-receive path and assert
868
+ the callback fired; once the three parts are joined, also that acting into that partner has ended and its host no
869
+ longer resolves.
870
+
871
+ What changes for an adopting app:
872
+
873
+ | # | Difference between the app's copy and the package | App | Keeps today's behaviour / intended change |
874
+ |---|---|---|---|
875
+ | 1 | `listWithCounts` refuses below platform scope on Postgres | starter, hub, noc, wall, desk | Intended (plan piece 10; the soc app has it). Every caller already runs at platform scope (`partners.view` is platform-only). |
876
+ | 2 | The counts per line | starter `staff`+`records`; hub `staff`; soc, noc `staff`+`customers`; wall `staff`+`records`+`customers`; desk `staff`+`customers`+`tickets` | `counts`: each app passes its own. |
877
+ | 3 | Paged and searchable list | desk | Pass `paginate` and call `listWithCounts({ q, page, pageSize })`: same SQL shape; the others call it with no argument and get the array. |
878
+ | 4 | The house's reference at seed | hub mints it; starter, soc, noc, wall leave it NULL (the attached apps bind the hub's house id to it later); the desk seeds its house in a migration | `mintHouseRef`: hub `true`, starter, soc, noc, wall `false`. No change for any app. |
879
+ | 5 | A given reference's shape checked on create | hub | `refShape: (r) => isPublicId(r, 'partner')`; the others `null`. The sentence is now generic (it no longer spells the `prt_` alphabet). |
880
+ | 6 | A given reference already held is refused by name on create | starter, soc, noc, wall, desk | Intended (plan row 18); before, the unique index refused it with the index's name. |
881
+ | 7 | Name length limit | hub 200 (its entry-limits helper) | `nameMaxLength: 200` (sentence: "may be at most 200 characters"); the others `null`. |
882
+ | 8 | `update` and `setActive` in one transaction, `setActive` a no-op when unchanged (`changes = 0`) | starter, soc, noc, wall, desk | Intended (plan rows 19, 22). A route that audits activate/deactivate unconditionally should check `changes` (the hub's "No change"; plan piece 13). |
883
+ | 9 | The reference on update | starter, desk `'editable'`; hub `'permanent'`; soc, noc, wall their hub-bound predicate (throwing their own `PARTNER_REF_*` codes) | `refPolicy`. |
884
+ | 10 | Host normalised in the model | hub | `normaliseHost`; the others' routes already normalise (passing it too is harmless). |
885
+ | 11 | Editable domain on update | desk | Same: only with the host key; the others never send `domain`. |
886
+ | 12 | Commercial fields preserved when omitted, `updated_at` stamped | hub | `extraColumns: [{ name: 'legal_name', update: true }, …, { name: 'contact', update: true, read: sql.jsonColumn, param: (v) => sql.jsonParam(v \|\| {}) }, { name: 'updated_at', update: 'now' }]`. |
887
+ | 13 | Sync bump on a document change; jobs on an active change | hub | `onChange`: it decides "document moved" from `before`/`after`; the base domain is read before the transaction by the hub's wrapper and passed in `opts`. |
888
+ | 14 | Portal sessions, unused codes, trusted browsers ended on deactivate | hub | `onDeactivate`. |
889
+ | 15 | `create` takes `is_active`, `hub_version`, `hub_received`, `hub_ref` | soc, noc, wall, desk | `is_active` is core; the rest are `extraColumns` with `create: true` (validation such as `hub_version`'s stays in the app's wrapper). |
890
+ | 16 | `all()` selects `hub_host` | noc | `extraColumns: [{ name: 'hub_host', list: true }]`. |
891
+ | 17 | The seeds | starter, hub, soc, noc, wall: Role, EmailTemplate, Report; desk: its seven (house reads through `ctx.tenancy`) | `seeds`. A seed returning `undefined` is now an error (plan row 9, intended). |
892
+ | 18 | RBAC refreshed after every provision | all but the desk (whose route did it) | Intended (plan row 23). |
893
+ | 19 | The provisioning log line | all | Wording: `roles=true, templates=true, reports=3`. |
894
+ | 20 | The deactivation of a half-built partner | starter, hub `setActive`; desk `setActive` with its hub opts; soc, noc, wall `setActiveFromHub` | `deactivateWith`. A failure is logged at error and the error says the partner is still active (plan section 9, intended). |
895
+ | 21 | The error carries `partnerId` (also `deactivated`, `cause`) | all but the desk | Intended (plan row 11). The desk's sentence becomes the starter's. |
896
+ | 22 | After a switch the browser goes to | starter, noc `/`; hub, soc, wall, desk `/dashboard` | `landing`. |
897
+ | 23 | Acting inside a deactivated partner | desk refuses; the other five allow | `refuseInactive` (desk `true`). The owner's answer 2 moves every app to `true` at its adoption: intended, said in each adoption PR. |
898
+ | 24 | The act-as sentences, and a flash for an unknown id | desk (its house sentence, its read-only "started" sentence, "No such partner.") | `messages`; the others the defaults (the starter's). |
899
+ | 25 | The banner shows only when the scope has moved to the acting partner | all but the desk | Intended (plan section 9): a correct session sees no difference. |
900
+ | 26 | The banner's read-only wording and `actingReadOnly` | desk | `actingLocals({ readOnly: true, note: '<its sentence>' })`; the others `readOnly: false`. |
901
+ | 27 | Back after a refusal or a stop | all (`/admin/partners`) | Same while mounted at `/admin/partners` (`req.baseUrl`, checked to be a local path, else `landing`); `back` overrides. |
902
+ | 28 | Writes to the partner table at a partner's scope | all write through (no guard but the permission) | `writesRequirePlatform: false` keeps it; `true` for a new app; per app, what `true` changes is in the table under "Partners" (nothing found for any). |
903
+ | 29 | Order of `all()` | desk by id (its forEachPartner visit order and the Ask partner list show it; the AI usage page only maps names); the others the house, then by name | `allOrder`: desk `'id'`, the others `'house-first'`. |
904
+ | 30 | The store's operator sentences | desk (the vendor's portal in the host sentences, "Move this installation to Postgres", its house-deactivation sentence) | Store `messages` (`hostRequired`, `postgresOnly`, `hostCleared`, `houseDeactivate`); the acting sentences through `actingRoutes`'s `messages` (`house`, `started`, `unknown`). Every desk sentence the package carries is reachable. |
905
+ | 31 | `create` with `is_active` undefined | soc, noc, wall default it to active | Same: omitted or `undefined` is active, a given falsy value inactive. |
906
+ | 32 | The locked-reference error code | soc, noc, wall their own codes | Same: the predicate returns `{ code, message }` or throws its own error. |
907
+ | 33 | The partner-list caches after a write | the starter's routes call `forgetPartnerHosts()` after create, update and setActive, and not after a failed create's deactivation (each app: verify at adoption) | `onPartnersChanged` (required), fired by the provisioner after every committed write, the half-built partner's deactivation included; the routes call `updatePartner` / `setPartnerActive`, the hub-receive paths `write(...)`. Intended for the failed-create case and for a partner deactivated at the hub (soc, noc and the desk already call the hosts `forget` in `routes/ops.js`, the wall does not; none calls `tenancy.refreshActivePartners()`, which is new). |
908
+ | 34 | `seedHouse` with no scope wrapper | hub `scripts/lib/syncWorld.js` line 76 (a SQLite harness) | Refused only if run on PostgreSQL with `writesRequirePlatform: true`: the hub wraps it in `asPlatform` at adoption. |
909
+ | 35 | Provisioning (`createPartner`, `provision`, `updatePartner`, `setPartnerActive`, `write`) at a partner's scope | all go through (the permission in front is the only guard) | `createProvisioner`'s `writesRequirePlatform: false` keeps it; `true` for a new app (D-0005 point 1, extended to provisioning); per app, what `true` changes is in the table under `createProvisioner` |
910
+ | 36 | One change callback doing both refreshes | none today (new) | `onPartnersChanged` may be a list, each entry isolated; pass `[() => tenancy.refreshActivePartners(), () => hosts.forget()]` |
911
+ | 37 | The act-as routes' flash and 404 | all: `res.flash(type, message, callback)` and `errors/404` | Same by default; `flash` and `notFound` for an app whose helpers differ |
2
912
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.