@aria-framework/tenancy 0.0.0-stage → 0.2.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/CHANGELOG.md +104 -0
- package/README.md +1188 -2
- package/index.js +19 -0
- package/lib/hosts/hostTenant.js +379 -0
- package/lib/hosts/hostname.js +321 -0
- package/lib/hosts/index.js +8 -0
- package/lib/hosts/tenantChrome.js +184 -0
- package/lib/partners/acting.js +216 -0
- package/lib/partners/actingIdle.js +177 -0
- package/lib/partners/index.js +10 -0
- package/lib/partners/provisioner.js +247 -0
- package/lib/partners/store.js +460 -0
- package/lib/scope/fleetView.js +437 -0
- package/lib/scope/idle.js +244 -0
- package/lib/scope/index.js +10 -0
- package/lib/scope/tenancy.js +786 -0
- package/lib/scope/writeGate.js +442 -0
- package/package.json +36 -4
- package/views/acting-banner.ejs +33 -0
- package/views/fleet-view-banner.ejs +29 -0
- package/views/fleet-view-button.ejs +23 -0
package/README.md
CHANGED
|
@@ -1,3 +1,1189 @@
|
|
|
1
|
-
#
|
|
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. `requestScope({ actingIdle })` (0.2.0, optional) adds the idle end of working in a partner around it ("The idle end of working in a partner", under Partners) |
|
|
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
|
+
| `fleetView` | no (0.2.0; absent is 0.1.0) | what `createFleetView` returned. The house reading becomes **the house's rows unless the `houseReading` permission is held AND fleet view is on**; while the mode is on no write is allowed at all: `writeScope` null (the house's own rows too), `createsLand` false, `refusal` `{ reason: 'fleetView' }` with `messages.fleetView` (required then). Needs `houseReading` set. A job (`null` request) is unaffected. `whileActing` is untouched beside it: it governs the acting case, and fleet view is never on while acting | an app adopting fleet view |
|
|
159
|
+
|
|
160
|
+
| Function | |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `writeScope(req, rowPartnerId)` → runner \| null | the scope to WRITE an existing row in (see the table); `req` null for a job |
|
|
163
|
+
| `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 |
|
|
164
|
+
| `createsLand(req)` → boolean | does the request carry a tenant for a new row (false while acting read-only) |
|
|
165
|
+
| `platformDestination(req)` → Promise\<{ id, name } \| null> | the partner a platform-scope create lands on, for the form to name |
|
|
166
|
+
| `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) |
|
|
167
|
+
| `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` |
|
|
168
|
+
| `houseOperatorNames(ids, { namesOf })` → Promise\<Map> | house users' names, read at the house partner's scope |
|
|
169
|
+
| `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 |
|
|
170
|
+
| `crossTenantRefusalOf(err, req)` → `{ kind, title, message }` \| null | the handler's predicate, for a route that catches and flashes its own error |
|
|
171
|
+
| `actingElsewhere(req)` → boolean | the scope moved off the user's own partner (never the raw session flag) |
|
|
172
|
+
| `houseReadingOf(req, can)` → Promise\<number \| null> | the house id when the request is the house reading, for `readScope`; with `fleetView`, null (every partner) only when `can(houseReading)` AND `fleetView.isOn(req)` |
|
|
173
|
+
|
|
174
|
+
**Which context the gate judges, and where its runner runs** (one rule for `writeScope` and `readScope`):
|
|
175
|
+
|
|
176
|
+
- given a request, the judged context is `contextFor(req)`, whatever scope surrounds the call (the hub's form);
|
|
177
|
+
- given `null` (a job, no request), it is the current scope at the call (the noc and soc apps' form);
|
|
178
|
+
- `undefined`, or anything that is not an object, throws: a forgotten argument cannot silently pick a rule.
|
|
179
|
+
|
|
180
|
+
Every runner runs its callback with `runWithTenant` at `{ scope: 'partner', partnerId: <the judged partner> }`, at
|
|
181
|
+
partner scope as at platform scope, so it runs there even when called inside `acrossAll`, `asHouse`, `asOwnPartner`,
|
|
182
|
+
`asPlatform` or another partner's `asPartner`: a route cannot gate in one scope and write in another.
|
|
183
|
+
|
|
184
|
+
`writeScope`, case by case (`whileActing: 'readOnly'` differs only in the acting rows):
|
|
185
|
+
|
|
186
|
+
| Request | Row | Answer |
|
|
187
|
+
|---|---|---|
|
|
188
|
+
| unscopable, anonymous, or no row | any | null |
|
|
189
|
+
| partner scope (partner staff) | its own partner's | runs at that partner |
|
|
190
|
+
| 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) |
|
|
191
|
+
| acting as P, `'write'` | P's | runs at P (another partner's: as partner scope above) |
|
|
192
|
+
| acting as P, `'readOnly'` | any | null |
|
|
193
|
+
| platform scope, not acting | the user's own partner's (the house's) | runs at that partner's scope (`asPartner`) |
|
|
194
|
+
| platform scope, not acting | another partner's | null, on both engines |
|
|
195
|
+
|
|
196
|
+
### `createFleetView(options)` — fleet view
|
|
197
|
+
|
|
198
|
+
A **session mode** (the owner's decisions of 29 Nov 2026). The normal view, always after sign-in, is your own
|
|
199
|
+
organisation's customers (house staff at platform scope: the house's own); holding the fleet permission changes nothing
|
|
200
|
+
there. A house user at platform scope who holds it switches fleet view on with one click (no confirmation). While it is
|
|
201
|
+
on, a banner shows on every page, pages read every partner's rows, and **nothing can be changed**. It ends when the
|
|
202
|
+
person leaves it, when they sign out, and after the app's idle period. Entering and leaving are audited. It is never on
|
|
203
|
+
together with working in a partner. Each app has its own switch (each has its own session).
|
|
204
|
+
|
|
205
|
+
Self-contained: an app that takes this package for fleet view alone passes in what it needs. Nothing else of this
|
|
206
|
+
package (`createTenancy` included) is required.
|
|
207
|
+
|
|
208
|
+
```js
|
|
209
|
+
// an app with its own lib/tenant.js
|
|
210
|
+
const fleet = createFleetView({
|
|
211
|
+
permission: 'fleet.analyse', // the app's fleet permission
|
|
212
|
+
can: (req, res, p) => res.locals.can(p), // the app's own check; only `true` counts
|
|
213
|
+
scopeOf: (req) => (tenant.contextFor(req) || {}).scope, // 'platform' | 'partner' | none; acting is 'partner'
|
|
214
|
+
userIdOf: (req) => (req.session.user ? req.session.user.id : null), // the signed-in user's stable id, synchronously
|
|
215
|
+
idleMinutes: () => settings.fleetViewIdleMinutes, // sync or async; a whole number; 0 = no idle end (apps: 15)
|
|
216
|
+
now: Date.now,
|
|
217
|
+
isBackground, // live streams and polls: NOT activity (the notify package's predicate)
|
|
218
|
+
audit, // (req, action, opts), the app's staff audit helper
|
|
219
|
+
logger, // { warn, error }
|
|
220
|
+
readOnlyExcept: ['POST /ask', 'POST /search/:id/run', 'POST /logout'], // REQUIRED, may be []
|
|
221
|
+
home: '/', startPath: '/fleet-view/start', stopPath: '/fleet-view/stop',
|
|
222
|
+
flash: undefined, wantsJson: undefined, refusalView: undefined, messages: {} // optional, below
|
|
223
|
+
});
|
|
224
|
+
app.use(session); app.use(fleet.loaded); // DIRECTLY after the session: the session as loaded
|
|
225
|
+
app.use(scopeMiddleware); app.use(bodyParser); app.use(csrf);
|
|
226
|
+
app.use(fleet.middleware); // after session and scope, BEFORE the app's flash-to-locals and EVERY router
|
|
227
|
+
app.use(fleet.routes(express.Router)); // POST startPath, POST stopPath (full paths: mount on the top-level app)
|
|
228
|
+
// views: [..., require('@aria-framework/tenancy').viewsDir]; in the layout:
|
|
229
|
+
// <%- include('fleet-view-banner') %> beside include('acting-banner'), outside the page container
|
|
230
|
+
// <%- include('fleet-view-button') %> in the top bar
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Every function option and `permission`, `logger`, `readOnlyExcept`, `home`, `startPath` and `stopPath` is **required
|
|
234
|
+
with no default**: an absent or malformed one is refused at construction, by name. `flash` defaults to
|
|
235
|
+
`res.flash(kind, text, callback)` (connect-flash style WITH a callback, as `actingRoutes`), `wantsJson` to
|
|
236
|
+
`X-Requested-With: fetch` or an `Accept` of JSON without HTML, `refusalView` to `'errors/generic'` (rendered with
|
|
237
|
+
`{ title, message }`), `messages` to the sentences below.
|
|
238
|
+
|
|
239
|
+
**Requirements on the app** (each is a way the guarantee is lost if the app does otherwise):
|
|
240
|
+
|
|
241
|
+
- `fleet.loaded` is mounted **directly after the session middleware**, and the middleware after the session and scope
|
|
242
|
+
middleware and **before every router**: a router mounted earlier is not guarded;
|
|
243
|
+
- the start and stop routes sit **behind the app's CSRF middleware** (both are state-changing POSTs);
|
|
244
|
+
- the app's sign-out **calls `await fleet.end(req, 'signout')` before it destroys the session**, so the audit trail
|
|
245
|
+
has the row (after `destroy()` there is no session to end);
|
|
246
|
+
- an idle end is audited when the **next request** detects it, and never if no request follows;
|
|
247
|
+
- **WebSocket and other socket traffic does not pass through Express middleware**: whatever it can change is the app's
|
|
248
|
+
to gate itself.
|
|
249
|
+
|
|
250
|
+
**`isOn(req, res)` → Promise\<boolean>.** True only when ALL of these hold on this request:
|
|
251
|
+
|
|
252
|
+
1. the session carries the mode (`req.session.fleetViewSince`, set only by the start route), switched on by the user
|
|
253
|
+
`userIdOf(req)` names NOW (`fleetViewUser`, stored at the start): another account signed in on the same session ends
|
|
254
|
+
it (reason `user`);
|
|
255
|
+
2. `scopeOf(req)` answers `'platform'`, and the session carries no `actingPartnerId`;
|
|
256
|
+
3. `can(req, res, permission)` answers exactly `true` (a truthy non-boolean is not held);
|
|
257
|
+
4. the idle period has not run out: `idleMinutes()` is 0, or less than that many minutes have passed since the last
|
|
258
|
+
activity stamp `fleetViewLastActive` (at exactly the period it is off).
|
|
259
|
+
|
|
260
|
+
Decided on every request from the session and the app's answers; nothing is kept across requests (the middleware's
|
|
261
|
+
verdict is reused only for the same request object, so a later call on that request, the write gate's house reading,
|
|
262
|
+
needs no `res`). A revoked permission, a start of acting or another account makes it false on the next request.
|
|
263
|
+
**It fails closed:** a throw from `can`, `scopeOf`, `userIdOf` or `idleMinutes`, or an `idleMinutes()` that is not a
|
|
264
|
+
whole number of 0 or more, is false; through the middleware the mode then ends (reason `error`) and the person sees the
|
|
265
|
+
normal view with one line, "Fleet view ended because it could not be checked. You can switch it on again."
|
|
266
|
+
|
|
267
|
+
**`middleware`**, per request:
|
|
268
|
+
|
|
269
|
+
- the session carries the mode but `isOn` is false: the mode ends. The person is told once through `flash` with kind
|
|
270
|
+
**`'warning'`** (one the framework's `ui/flash` partial renders, and one that stays until dismissed): "Fleet view ended
|
|
271
|
+
after N minutes without activity.", "… because you no longer have the permission for it.", "… because it is only
|
|
272
|
+
available at platform scope, not while working in a partner.", "… because it was switched on by another account.", or
|
|
273
|
+
the `error` line above. Then the row is re-read and, if it still holds the mode, the row (with this request's changes) minus the
|
|
274
|
+
mode is saved before the request goes on, and `fleet_view.stop` is audited with the reason (`idle` with `minutes`,
|
|
275
|
+
`permission`, `scope`, `user`, `error`); otherwise nothing is written or audited (below). Mount it before the middleware that
|
|
276
|
+
moves flash messages into the page's locals, so the line shows on this very page;
|
|
277
|
+
- the mode is on, the request is not background and a stamp is due: `fleetViewLastActive = now()`, written only after a
|
|
278
|
+
re-read (below) and saved before the request goes on. A stamp is due at most once a minute (`ACTIVITY_STAMP_MAX_MS`), for a period under ten minutes
|
|
279
|
+
at most once per tenth of it, and **never at 0 minutes**. The idle end is judged from the stamp, so the mode ends
|
|
280
|
+
between `minutes − min(1 minute, minutes/10)` and `minutes` after the last activity. A background request
|
|
281
|
+
(`isBackground`, or one whose `isBackground` throws) is still judged, it only does not count: without this a page
|
|
282
|
+
left open would keep the mode on for ever through its live stream;
|
|
283
|
+
- `res.locals.fleetView = { on, canStart, startPath, stopPath, returnTo }`: `canStart` (offer the switch) is true only
|
|
284
|
+
while off, for a signed-in user with an id, at platform scope, not acting, holding the permission; `returnTo` is this
|
|
285
|
+
GET page's own address when it is a safe return address, else null;
|
|
286
|
+
- **the read-only guard**, in this same one place (below).
|
|
287
|
+
|
|
288
|
+
**When the package writes the session, and what is left.** express-session writes a request's session at the END of
|
|
289
|
+
the request when it changed since it was last saved, so a slow request that carries an unsaved change writes back what
|
|
290
|
+
it loaded, over a stop or a sign-out that happened meanwhile. This package writes the session at these times only:
|
|
291
|
+
when fleet view starts or stops (the two routes), when the app calls `end`, when the middleware ends the mode by
|
|
292
|
+
itself, and for the activity stamp, which is due at most once a minute and never at 0 minutes (the acting idle end:
|
|
293
|
+
its clock's start and removal, its stamp, and its automatic end). Start, stop and `end` are the person's own act on
|
|
294
|
+
their current session and are saved at once.
|
|
295
|
+
|
|
296
|
+
**Every other write is the row read back, plus this request's changes, plus this package's change.** After all of the
|
|
297
|
+
request's own checks are done (`userIdOf`, `scopeOf`, `can`, `idleMinutes`), the session's row is read again from the
|
|
298
|
+
store (`req.sessionStore.get(req.sessionID)`). If it still holds the same mode (fleet view: the same start, switched
|
|
299
|
+
on by the same user, signed in as that user; acting: the same partner), what is written is: that row as the store holds
|
|
300
|
+
it now; over it, every key this request itself changed in memory since the session was loaded (an earlier middleware's
|
|
301
|
+
`lastActivity`, this package's notice), objects merged key by key; and this package's own change (the stamp, or the
|
|
302
|
+
mode's fields removed by an automatic end). That becomes the session in memory and is saved, in the read's callback,
|
|
303
|
+
with nothing awaited between the answer and the save call. express-session's own end-of-request save then has nothing
|
|
304
|
+
left to write, because `save()` records the saved state and it writes only a session changed after that; so the store
|
|
305
|
+
is not overwritten a moment later by the stale copy this request loaded (`test/scope/sessionRaces.js`, "express-session's
|
|
306
|
+
own end-of-request save"). So another request's write (a flash, a second factor, a session version) is carried
|
|
307
|
+
through, and an earlier middleware's write never makes this package skip: the stamp is written and the automatic end
|
|
308
|
+
happens on the first request past the period, with its stop row, whatever else changed in the row.
|
|
309
|
+
|
|
310
|
+
**What a request sees when the row changed under it.** If the row still holds the same mode, the page reads by it
|
|
311
|
+
(fleet view on, the stamp written), whatever else changed. If the row is gone (the person signed out), no longer holds
|
|
312
|
+
the mode (left in another tab, another account signed in, acting stopped), or cannot be read (no `sessionStore`, or
|
|
313
|
+
`get` fails), nothing is written or audited, the request reads the normal view (no banner on that page) while its writes
|
|
314
|
+
are still refused, and the next request judges again; this package's keys in memory are put back, or aligned with the
|
|
315
|
+
row read back when the app itself changed the session in memory, so express-session's end-of-request save cannot bring
|
|
316
|
+
a left mode back.
|
|
317
|
+
|
|
318
|
+
**What is left, in plain words.** (1) One store round trip, between the re-read's answer and the save landing: a write
|
|
319
|
+
by another request that lands in it is overwritten, and **a sign-out that lands in it is undone by an upserting session
|
|
320
|
+
store (the apps' PostgreSQL store, like MemoryStore, upserts on `set`): the signed-out session is re-created, signed
|
|
321
|
+
in** (`test/scope/sessionRaces.js`, "THE REMAINDER, documented"). (2) A key that BOTH this request and another changed
|
|
322
|
+
in the wait takes this request's value. For flash messages that means: two of the same kind in one array, the other's
|
|
323
|
+
is lost; two of different kinds are both kept ONLY when the session already held a flash object when this request loaded
|
|
324
|
+
it (the objects are then merged key by key) — when it held none, which is the usual case, this request's flash object
|
|
325
|
+
replaces the other's whole; and a request that consumes a flash drops one added during its wait. The same is true of ANY
|
|
326
|
+
code in the app that writes the session during a request that
|
|
327
|
+
overlaps another (consuming a flash message is enough); an app that wants this closed for good needs a store-level
|
|
328
|
+
guard (a store whose `set` will not re-create a row that was destroyed, or that merges), which this package does not
|
|
329
|
+
provide.
|
|
330
|
+
|
|
331
|
+
**Mounting order that remains:** `fleet.loaded` (or the acting idle end's `loaded`; either serves both) directly after
|
|
332
|
+
the session middleware, before anything that changes the session: it keeps the session as loaded, which tells this
|
|
333
|
+
request's own changes from the row's. A session in fleet view that reaches the middleware without it is answered
|
|
334
|
+
with an error (not silently written). `userIdOf` must answer synchronously.
|
|
335
|
+
|
|
336
|
+
**The cost:** at most one extra store read per session per stamp interval (one minute; a tenth of a period under ten
|
|
337
|
+
minutes), plus one at each automatic end, plus one when the acting clock starts or is removed. A request that is not
|
|
338
|
+
due a stamp reads nothing extra. The copy of the session as loaded (one serialisation) is taken only for a session that
|
|
339
|
+
carries fleet view or the acting keys; every other request of every user takes none.
|
|
340
|
+
|
|
341
|
+
**The read-only guard.** While the mode is on, every request whose method is not GET, HEAD or OPTIONS is refused before
|
|
342
|
+
any router runs, unless `classify` lets it through: the start route (a double click or a second tab is harmless: it
|
|
343
|
+
changes nothing and goes back to the page), the stop route, or a `readOnlyExcept` entry. A page request gets 403 and
|
|
344
|
+
`refusalView` with "Fleet view is read-only. Leave fleet view to change anything."; with no view engine (Express 5's
|
|
345
|
+
`render` throws at once) or a view that fails, the same sentence as `text/plain`, still 403; a request that asks for
|
|
346
|
+
JSON gets 403 `{ ok: false, type: 'error', code: 'FLEET_VIEW_READ_ONLY', message }`. Nothing is written, no downstream
|
|
347
|
+
handler runs, and the refusal is logged at warn.
|
|
348
|
+
|
|
349
|
+
- **What it judges.** The RAW request target, `req.originalUrl`, as the client sent it (at any mount, in a sub-app
|
|
350
|
+
too: entries and paths are full paths from the top-level app). First, a target that is not **plain** is refused
|
|
351
|
+
outright: anything but `/` followed by RFC 3986 path and query characters (letters, digits, `- . _ ~ ! $ & ' ( ) * +
|
|
352
|
+
, ; = : @ / ?`, and `%` with two hex digits); so `#`, a backslash, a space or control character, anything outside
|
|
353
|
+
ASCII. No honest client sends these, and they are what makes Express's parser disagree with a plain split: for any
|
|
354
|
+
target with `#` or whitespace parseurl falls back to `url.parse`, which cuts at the `#` and turns backslashes into
|
|
355
|
+
slashes, so `POST /search/1\delete#/run` is dispatched to `/search/:id/delete`. For a plain target, parseurl's own
|
|
356
|
+
answer (its fast path) is the part before the first `?`, and that is the path judged. Then, for a request it would
|
|
357
|
+
let through, the guard also requires that Express dispatches on that path at its mount (`req.baseUrl + req.path`,
|
|
358
|
+
Express's own pathname there): a URL rewritten by earlier middleware is refused.
|
|
359
|
+
- **How an entry matches.** Exactly: the same method; the same number of segments (a trailing slash is another
|
|
360
|
+
path); each literal segment equal, case included; each `:name` segment one conservative id: letters, digits, `_`
|
|
361
|
+
and `-`, 1 to 64 characters, never `%`, `.`, `+`, `@` or a slash (or a route table's own `:name`, so a route-table
|
|
362
|
+
walk classifies alike). An entry that is not `METHOD /literal/or/:name/segments` (literal segments of letters,
|
|
363
|
+
digits, `. _ ~ -`; no query, wildcard, empty, dot, encoded or mixed segment) is refused at construction. So `/ASK`,
|
|
364
|
+
`/ask/`, `/a%73k`, `/askme`, `/ask/x`, `/./ask`, `/search/1.2/run` and `PUT /ask` are refused when only `POST /ask`
|
|
365
|
+
and `POST /search/:id/run` are listed.
|
|
366
|
+
- **Its limits.** No method override is honoured anywhere in this stack today (none of the framework, the hub, soc or
|
|
367
|
+
noc mounts one); an app that adds one mounts it BEFORE this middleware, so the guard judges the effective method.
|
|
368
|
+
**A GET handler that changes data is the app's defect, not this guard's**: the guard trusts that GET, HEAD and
|
|
369
|
+
OPTIONS only read. So does an entry the app lists: list only requests that read (a question, a search) or only end
|
|
370
|
+
something (signing out), and know that a listed path reaches whatever the app routes there.
|
|
371
|
+
|
|
372
|
+
**`routes(Router)`**: `POST startPath` and `POST stopPath`, on a router from the app's `express.Router`, mounted on the
|
|
373
|
+
top-level app (the paths are full paths).
|
|
374
|
+
|
|
375
|
+
- Start: allowed only for a signed-in user whose `userIdOf` is not null, at platform scope, not acting (the session's
|
|
376
|
+
`actingPartnerId`, whatever `scopeOf` says), holding the permission; anyone else (a partner's user, an acting house
|
|
377
|
+
user, a house user without the permission, no id, no user, no session) gets 403 with "Fleet view is not available to
|
|
378
|
+
you here.", nothing set, nothing audited. Already on: nothing changes, nothing is audited, back to the page.
|
|
379
|
+
Otherwise `fleet_view.start` is audited BEFORE the session fields are set (a failing audit stops the start), the
|
|
380
|
+
fields (`fleetViewSince`, `fleetViewLastActive`, `fleetViewUser`) are set and saved, and the browser goes back to
|
|
381
|
+
`req.body.returnTo` when it is a safe return address, else `home`. A **safe return address** is a local path of this
|
|
382
|
+
app only: it starts with one `/` not followed by `/` or `\`, has no backslash anywhere, no control character (DEL
|
|
383
|
+
included) or space, and is at most 2048 characters. An absolute URL, `//host`, `///host`, `/\host`, a scheme
|
|
384
|
+
(`javascript:`, `data:`), a bare name, an empty value or a CR/LF all fall back to `home`.
|
|
385
|
+
- Stop: **session-gated, not permission-gated** (it is the only way out, so it must not depend on a permission that may
|
|
386
|
+
be gone): when the session carries the mode, the fields are cleared, `fleet_view.stop` audited with reason `left`,
|
|
387
|
+
the session saved, and the browser goes to `home`; otherwise straight to `home`, nothing audited or written.
|
|
388
|
+
|
|
389
|
+
**`classify(method, target)`** → `'read' | 'start' | 'leave' | 'listed' | 'refused'`: what the guard decides for that
|
|
390
|
+
request while the mode is on, without a request object. The guard calls exactly this with `req.method` and
|
|
391
|
+
`req.originalUrl`. The method is compared upper-cased (an Express route table's keys are lower-case). **How an app
|
|
392
|
+
proves its whole population read-only:** walk its derived route table (every router, every method, with full paths),
|
|
393
|
+
and assert that every non-GET route classifies `'refused'` unless it is deliberately in `readOnlyExcept`; floor the
|
|
394
|
+
population against a count taken another way.
|
|
395
|
+
|
|
396
|
+
**`end(req, reason)`** → Promise\<boolean>: for the app's own flows, when it starts working in a partner (`'acting'`) or
|
|
397
|
+
signs a person out (`'signout'`, before `destroy()`). Clears the fields, audits the stop with the reason, saves the
|
|
398
|
+
session; tells nobody. False, with nothing audited or written, when the mode was not on. An app that offers "work in
|
|
399
|
+
this partner" from fleet view lists that act-as route in `readOnlyExcept` and calls `end(req, 'acting')` in it.
|
|
400
|
+
|
|
401
|
+
**`writesRefused(req)`** → boolean: the session carries the mode (for the write gate; the middleware has already cleared
|
|
402
|
+
a mode that is not on).
|
|
403
|
+
|
|
404
|
+
**Audit actions.** `fleet_view.start` (`{ detail: {} }`) and `fleet_view.stop` (`{ detail: { reason } }`, with `minutes`
|
|
405
|
+
for `idle`), through the app's `audit(req, action, opts)` in the request's own scope (the house, at platform scope).
|
|
406
|
+
Reasons: `left` (the stop route), `idle`, `permission`, `scope`, `user`, `error` (the middleware), `acting`, `signout`
|
|
407
|
+
(`end`).
|
|
408
|
+
|
|
409
|
+
**The settings an app owns:** the permission's name and who holds it; the idle minutes (the apps default to 15, 0 = no
|
|
410
|
+
idle end; the plan puts it on Sign-in & security, platform only); `readOnlyExcept`; the three paths; the CSS. The two
|
|
411
|
+
partials use the classes `fleet-view-banner` and `btn-fleet-view`; the app adds:
|
|
412
|
+
|
|
413
|
+
```css
|
|
414
|
+
.fleet-view-banner { background: color-mix(in srgb, #7C3AED 16%, var(--bs-body-bg)); border-bottom: 2px solid #7C3AED; }
|
|
415
|
+
.btn-fleet-view { border-color: #7C3AED; color: #7C3AED; }
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
Both partials need the app's `csrfToken()` while they draw (they throw without it), draw nothing without
|
|
419
|
+
`locals.fleetView`, and carry no inline script, style or event handler.
|
|
420
|
+
|
|
421
|
+
**With the write gate:** pass the fleet view to `createWriteGate({ …, houseReading: '<the same permission>', fleetView:
|
|
422
|
+
fleet })` (above).
|
|
423
|
+
|
|
424
|
+
## Hosts
|
|
425
|
+
|
|
426
|
+
Which partner a request's host name belongs to, and the brand, time zone and idle timeout a page shows for its
|
|
427
|
+
tenant. A wrong answer here serves one partner's sign-in page and branding as another's, so every rule below is the
|
|
428
|
+
apps' own, moved unchanged, and every setting that differs between apps is required.
|
|
429
|
+
|
|
430
|
+
### `hostname` (pure functions)
|
|
431
|
+
|
|
432
|
+
`const { hostname } = require('@aria-framework/tenancy')`. No database, no state; safe in the worker and on the main
|
|
433
|
+
thread.
|
|
434
|
+
|
|
435
|
+
| Function | What it does |
|
|
436
|
+
|---|---|
|
|
437
|
+
| `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). |
|
|
438
|
+
| `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. |
|
|
439
|
+
| `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). |
|
|
440
|
+
| `randomLabel()` | A 10-character Crockford base32 label for a partner with no domain. |
|
|
441
|
+
| `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. |
|
|
442
|
+
| `assertLabelNotReserved(label, { reservedLabels })` | The one reserved-label refusal (`hostFor` and an edit route both use it). |
|
|
443
|
+
| `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. |
|
|
444
|
+
| `isHostLabel(v)` | One lower-case DNS label, 1 to 63 characters. |
|
|
445
|
+
| `PARTNER_BASE_DOMAIN_KEY`, `MAX_HOSTNAME`, `MAX_LABEL` | `'partner_base_domain'`, 253, 63. |
|
|
446
|
+
|
|
447
|
+
**`reservedLabels` is REQUIRED** on the three functions that take it (an array; a missing or malformed one throws).
|
|
448
|
+
The hub passes `['registry', 'node', 'apt']`; every other app passes `[]`. No owner answer covers it: a new app passes
|
|
449
|
+
`[]` unless it serves its own components under the partner base domain.
|
|
450
|
+
|
|
451
|
+
### `createHostTenant({ tenancy, db, logger, trustForwardedHost, chrome, isSignedIn, onForget, maxAgeMs })`
|
|
452
|
+
|
|
453
|
+
Returns `{ middleware(), partnerIdForRequest(req), partnerOfHost(host), forget() }`.
|
|
454
|
+
|
|
455
|
+
- `middleware()`: for the LOGIN routers only (mount it with `router.use()` or per route inside them, never with
|
|
456
|
+
`app.use()`: on the app it would let a forged `Host` narrow an authenticated request). An anonymous request on an
|
|
457
|
+
active partner's host runs the rest of the router inside `asPartner(<that partner>)`, with `req.partnerId` and
|
|
458
|
+
`req.partnerHost` set; any other host (unknown, bare IP, `localhost`, IPv6, none) runs inside `asPartner(<house>)`:
|
|
459
|
+
partner scope, never `asHouse()`'s platform scope. `chrome.applyTo(res)` is re-run inside the narrowed scope. A
|
|
460
|
+
signed-in session is stepped around. If the tenant cannot be decided at all (no map ever loaded and the read fails,
|
|
461
|
+
or the house cannot be found), it logs a warning and leaves the scope the request already had (the login page stays
|
|
462
|
+
up; the trade is named in the code).
|
|
463
|
+
- `partnerIdForRequest(req)`: the host's active partner, else the house. Does NOT step aside for a signed-in session
|
|
464
|
+
and does NOT fail open: a failure throws. For a customer portal comparing a session with the host it arrived on.
|
|
465
|
+
- `partnerOfHost(host)`: the host's active partner or `null` (never the house). For a sign-in provider's realm.
|
|
466
|
+
- `forget()`: drop the map; the next lookup reads it again. Call it after every write that can change the mapping
|
|
467
|
+
(create, host change, activate, deactivate). It reaches THIS process only.
|
|
468
|
+
|
|
469
|
+
| Setting | Default | Who needs what |
|
|
470
|
+
|---|---|---|
|
|
471
|
+
| `tenancy` | required | the scope part's `createTenancy()` result; this part calls `asPartner`, `asPlatform`, `housePartnerId` |
|
|
472
|
+
| `db` | required | the app's `DbClient`; reads `Partner.all` at platform scope |
|
|
473
|
+
| `logger` | required | `info`, `warn` |
|
|
474
|
+
| `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. |
|
|
475
|
+
| `chrome` | required | the app's request chrome (`lib/requestChrome.js`, its `applyTo(res)`) |
|
|
476
|
+
| `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. |
|
|
477
|
+
| `onForget()` | none | the noc app passes its hub sign-in host store's reset until it adopts the hub packages' own store |
|
|
478
|
+
| `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 |
|
|
479
|
+
| `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 |
|
|
480
|
+
|
|
481
|
+
**Which header decides.** `false`: the raw `Host` header, always, whatever else the request carries. `true`:
|
|
482
|
+
`req.hostname`. In the Express version this package is tested with (5.2), that reads `X-Forwarded-Host` (its first
|
|
483
|
+
entry) whenever Express's `trust proxy` function accepts the address of the peer that connected, and `Host`
|
|
484
|
+
otherwise. With `trust proxy = 1` that is EVERY peer (one hop is trusted, whoever it is); with `true` it is always.
|
|
485
|
+
So with `trustForwardedHost: true`, any client that reaches the app's port directly, or through a proxy that passes
|
|
486
|
+
the header on unchanged, chooses the tenant by sending one header.
|
|
487
|
+
|
|
488
|
+
Turning it on therefore means: the proxy in front must OVERWRITE `X-Forwarded-Host` on every request, and it must be
|
|
489
|
+
the only way in (the app's port reachable from that proxy alone). Never set Express's `trust proxy` to `true`. On the
|
|
490
|
+
proxies the apps' deployment notes cover:
|
|
491
|
+
|
|
492
|
+
- **Apache (httpd 2.4):** `ProxyPreserveHost` is Off by default, so always set `ProxyPreserveHost On`. When it
|
|
493
|
+
proxies, Apache adds `X-Forwarded-Host`, and if the client already sent one it APPENDS its own after the client's
|
|
494
|
+
(a comma-separated list), so the FIRST entry, the one Express reads, is the client's. That is why, before turning
|
|
495
|
+
`trustForwardedHost` on, the same virtual host needs `RequestHeader unset X-Forwarded-Host`, in the default (late)
|
|
496
|
+
mode, not `early` (which the documentation describes as a testing and debugging aid). The documentation does not
|
|
497
|
+
say in which order that directive and the proxy's own header are applied, so test it (below).
|
|
498
|
+
- **nginx:** by default it sends `Host: $proxy_host` (the backend's name), so always set
|
|
499
|
+
`proxy_set_header Host $host;`. Before turning `trustForwardedHost` on, also set
|
|
500
|
+
`proxy_set_header X-Forwarded-Host $host;`, which replaces a client-sent value; without it a client-sent
|
|
501
|
+
`X-Forwarded-Host` reaches the app unchanged. Put both lines at the SAME level as any other `proxy_set_header`
|
|
502
|
+
lines: a level that defines any `proxy_set_header` of its own inherits none from the levels above.
|
|
503
|
+
- **Caddy (2.5.0 or later):** `reverse_proxy` passes the client's `Host` through unchanged, and sets
|
|
504
|
+
`X-Forwarded-Host` itself, ignoring a client-sent value unless the client's address is listed in
|
|
505
|
+
`trusted_proxies`. Nothing needs setting; never list a source you do not control in `trusted_proxies`; leave
|
|
506
|
+
`trustForwardedHost` off, since `Host` already carries the right value.
|
|
507
|
+
|
|
508
|
+
**Test it on the deployment, whatever the proxy** (the only proof that holds for an actual configuration). Through
|
|
509
|
+
the proxy, on a host that no partner owns, send a forged header naming a partner's host:
|
|
510
|
+
|
|
511
|
+
```sh
|
|
512
|
+
curl -s -o /dev/null -w '%{http_code}\n' -H 'X-Forwarded-Host: <a partner host>' https://<the installation's own address>/login
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
and confirm the sign-in page that comes back is the house's, not that partner's (its brand on the page, or the
|
|
516
|
+
app's log line for the request), and that the app does not see `forged.example` when you send
|
|
517
|
+
`-H 'X-Forwarded-Host: forged.example'` (log `req.hostname` and `req.headers['x-forwarded-host']` once on a test
|
|
518
|
+
route). A forged value that reaches the app means the proxy is not overwriting the header: leave
|
|
519
|
+
`trustForwardedHost` off.
|
|
520
|
+
|
|
521
|
+
Behind a proxy that does not preserve `Host` (Apache's default, `ProxyPreserveHost Off`), every partner address
|
|
522
|
+
serves the house's sign-in.
|
|
523
|
+
|
|
524
|
+
**How stale the map can be.** It holds active partners with a `portal_host` only (lower-cased). Without `maxAgeMs`
|
|
525
|
+
it has no age: it is read once and kept until `forget()` or a restart, so a partner deactivated without `forget()`
|
|
526
|
+
keeps resolving by its host in that process until one of the two. With `maxAgeMs`, a map older than that is read
|
|
527
|
+
again on the next lookup, which bounds the staleness in a process that was never told. A reload that FAILS (after
|
|
528
|
+
`forget()` or past the age) answers from the last map it built; it is not cached, so the next lookup tries again, and
|
|
529
|
+
the first good reload replaces the map. The price, named: during such a failure a partner deactivated just before it
|
|
530
|
+
still resolves.
|
|
531
|
+
|
|
532
|
+
**An outage is logged once.** The first failed reload logs `Partner hosts: reload failed, keeping the last map (...)`
|
|
533
|
+
at warn; while reloads keep failing, at most one line a minute follows (`reload still failing ... N failed reload(s)
|
|
534
|
+
since the last line`); the first good reload logs `reload succeeded again after N failed reload(s)` at info. (With no
|
|
535
|
+
map ever loaded, the middleware's own fail-open warning is still written per request: the boot-time case.)
|
|
536
|
+
|
|
537
|
+
### `createTenantChrome({ tenancy, db, fields })`
|
|
538
|
+
|
|
539
|
+
Returns `{ chromeFor(partnerId), forget(partnerId?), cachedSessionTimeoutMs(partnerId), cached(field, fallback) }`.
|
|
540
|
+
|
|
541
|
+
- `chromeFor(id)`: one value per field, read with `db.invoke('Settings', <method>)` inside `asPartner(id)` (so a
|
|
542
|
+
partner always gets its own row, whatever scope asks) and cached per partner. `chromeFor(null)` answers each field's
|
|
543
|
+
`fallback` and caches nothing.
|
|
544
|
+
- `forget(id)` drops one partner's entry; `forget()` drops all. Call it after a settings save and after a partner is
|
|
545
|
+
created or re-provisioned.
|
|
546
|
+
- `cachedSessionTimeoutMs(id)`: synchronous, cache only. **`null` before that partner's chrome is warm, and for a null
|
|
547
|
+
id**; never another tenant's number. Once warm, for a tenant with no `session_timeout_minutes` it is
|
|
548
|
+
`28800000` (480 minutes: the apps' `Settings.getSessionTimeoutMinutes` returns 480 for a missing or invalid value,
|
|
549
|
+
and `STARTER_FIELDS`' `read` also maps a falsy answer to 480). Never `undefined`. Every app's caller keeps its fallback
|
|
550
|
+
(`… || dbClient.getSessionTimeoutMs()`), so the live-update check, which now stops a stream on a timeout that is not
|
|
551
|
+
a positive finite number, never sees the `null`: keep that fallback when adopting.
|
|
552
|
+
- `cached(field, fallback)`: the CURRENT tenant's cached `field` (by `tenancy.currentTenant().partnerId`),
|
|
553
|
+
synchronously, or `fallback` when it is cold, there is no tenant, or the lookup throws. Pass a neutral fallback.
|
|
554
|
+
|
|
555
|
+
The cache key is db-worker's `tenantCacheKey({ scope: 'partner', partnerId })`: every entry is read at partner scope,
|
|
556
|
+
so `p:<id>` is the honest key; a platform-scope request for the house gets the house's chrome, as today. There is no
|
|
557
|
+
platform entry.
|
|
558
|
+
|
|
559
|
+
| Setting | Default | Who needs what |
|
|
560
|
+
|---|---|---|
|
|
561
|
+
| `tenancy` | required | calls `asPartner`, `currentTenant` |
|
|
562
|
+
| `db` | required | the app's `DbClient` |
|
|
563
|
+
| `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. |
|
|
564
|
+
|
|
565
|
+
A field is `{ method, fallback, read? }`: `method` names the `Settings` getter, `read(raw)` turns its answer into the
|
|
566
|
+
cached value (without it the answer is cached as it comes), `fallback` is the value with no tenant.
|
|
567
|
+
|
|
568
|
+
## Partners
|
|
569
|
+
|
|
570
|
+
The partner store and provisioning (plan piece 10), and working inside a partner: the acting routes, the locals and
|
|
571
|
+
the banner (piece 11). Everything here takes the app's own `tenancy` (the `createTenancy` result), db client, audit
|
|
572
|
+
helper and permission gate as arguments; the package holds no permission name, no app's prefix and no app's styling.
|
|
573
|
+
|
|
574
|
+
### `createPartnerStore(options)` — the partner model's nine methods
|
|
575
|
+
|
|
576
|
+
```js
|
|
577
|
+
// models/Partner.js (runs in the worker)
|
|
578
|
+
const { sql } = require('@aria-framework/db-worker');
|
|
579
|
+
const store = createPartnerStore({
|
|
580
|
+
driver: () => database.driver(), // a GETTER, read at every call, never a handle captured at load
|
|
581
|
+
sql, // db-worker's sql (the app's lib/sql.js re-export)
|
|
582
|
+
mintRef: () => publicId('partner'), // REQUIRED: a new reference in THIS app's own prefix
|
|
583
|
+
refShape: (ref) => isPublicId(ref, 'partner'), // REQUIRED: a GIVEN reference's shape check, or null for any
|
|
584
|
+
refPolicy: 'permanent', // REQUIRED: 'editable' | 'permanent' | (current, newRef, {tx, opts}) => locked
|
|
585
|
+
counts: { staff: { table: 'users', where: 'c.is_active = 1' }, customers: { table: 'customers' } }, // REQUIRED ({} for none)
|
|
586
|
+
nameMaxLength: 200, // REQUIRED: a whole number, or null for no limit
|
|
587
|
+
houseName: () => identity.appBrand, // REQUIRED: the house's name at seed
|
|
588
|
+
mintHouseRef: true, // REQUIRED: mint the house's reference at seed (below, per app)
|
|
589
|
+
writesRequirePlatform: true, // REQUIRED: refuse create/update/setActive/seedHouse below platform scope
|
|
590
|
+
allOrder: 'house-first', // REQUIRED: 'house-first' (the house, then by name) or 'id'
|
|
591
|
+
messages: {}, // optional: hostRequired, postgresOnly, hostCleared, houseDeactivate
|
|
592
|
+
normaliseHost, // optional: the host rule of the write path (hostname.normaliseHost)
|
|
593
|
+
paginate, // optional: @aria-framework/kit's paginate, for the paged list
|
|
594
|
+
extraColumns: [], // optional: the app's own columns (below)
|
|
595
|
+
onChange: async (tx, event) => {}, // optional: INSIDE the transaction, after a change
|
|
596
|
+
onDeactivate: async (tx, event) => {} // optional: INSIDE the transaction, on every deactivate
|
|
597
|
+
});
|
|
598
|
+
module.exports = { ...store, ...hubReceiveMethods };
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
| Method | What it does |
|
|
602
|
+
|---|---|
|
|
603
|
+
| `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. |
|
|
604
|
+
| `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. |
|
|
605
|
+
| `byPortalHost(host)` | The ACTIVE partner owning a host, by `lower()`; a deactivated partner's host resolves to nobody. |
|
|
606
|
+
| `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 }`. |
|
|
607
|
+
| `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. |
|
|
608
|
+
| `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. |
|
|
609
|
+
| `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. |
|
|
610
|
+
|
|
611
|
+
**`mintHouseRef`** (required, no default). `true`: the house gets a minted reference at seed, as every other partner
|
|
612
|
+
does at create (the hub, whose reference is permanent and NOT NULL). `false`: the house is seeded with a NULL
|
|
613
|
+
reference, which the apps attached to the hub NEED: their hub-receive code binds the hub's house id to it once
|
|
614
|
+
(`… WHERE is_house = 1 AND external_ref IS NULL`) and refuses a house document when the house already holds another
|
|
615
|
+
reference, so a minted one would make the hub's house document refused for ever. Per app: hub `true`; starter, soc,
|
|
616
|
+
noc, wall `false` (their seed writes no reference today); the desk seeds its house in a migration and does not call it.
|
|
617
|
+
A new standalone app takes the starter's `false`; one that will be attached to the hub must pass `false`.
|
|
618
|
+
|
|
619
|
+
**`writesRequirePlatform`** (required, no default). `partners` has no row-level security, so nothing below the store
|
|
620
|
+
stops a write at a partner's scope: at partner A's scope an `update` or `setActive` writes partner B, and a
|
|
621
|
+
deactivation's sign-out of B's users is then filtered away by the policy on `users`, leaving B deactivated with its
|
|
622
|
+
people still signed in. That is every source's behaviour (the platform-only permission in front is the only guard), and
|
|
623
|
+
`false` keeps it. `true` makes `create`, `update`, `setActive` and `seedHouse` refuse unless the transaction runs
|
|
624
|
+
at platform scope (db-worker's `assertPlatformScope`, `code: 'tenant_scope_refused'`; Postgres only), before anything
|
|
625
|
+
is written. **A new app passes `true`** (the owner's answer, D-0005). For the existing apps it is each adoption's
|
|
626
|
+
choice; what `true` would change, from reading every caller at `origin/main`:
|
|
627
|
+
|
|
628
|
+
| App | Callers of create / update / setActive / seedHouse, and their scope today | What `true` would change |
|
|
629
|
+
|---|---|---|
|
|
630
|
+
| a new app | — | `true` |
|
|
631
|
+
| 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 |
|
|
632
|
+
| hub | `seedHouse` in `server.js` under `asPlatform`; the partners routes (update, setActive, create through provisioning) behind platform-only `partners.manage` | Nothing found |
|
|
633
|
+
| 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) |
|
|
634
|
+
| noc | as soc (`lib/scope.js` seed, `lib/hubPartner.js` and `routes/ops.js` in `asHouse()`) | Nothing found |
|
|
635
|
+
| wall | as soc (`lib/scope.js` seed, `lib/hubPartner.js` in `asHouse()`) | Nothing found |
|
|
636
|
+
| 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 |
|
|
637
|
+
|
|
638
|
+
"Nothing found" is a reading of those files, not a run: each adoption confirms it with the app's own suites, and any
|
|
639
|
+
script or job outside `lib/`, `routes/` and the boot file that writes partners is not covered by it. One is known: the
|
|
640
|
+
hub's test harness `scripts/lib/syncWorld.js` (line 76) calls `seedHouse` through its in-process bridge with no scope
|
|
641
|
+
wrapper. It runs on SQLite today, where nothing is refused; pointed at PostgreSQL with `true` it would be, so the hub
|
|
642
|
+
wraps it in `asPlatform` at adoption.
|
|
643
|
+
|
|
644
|
+
**On SQLite `writesRequirePlatform` does nothing** (the scope assertion is PostgreSQL-only, as in the sources), so an
|
|
645
|
+
app's SQLite chain can never show the guard working: its PostgreSQL gate must carry the test.
|
|
646
|
+
|
|
647
|
+
**`refPolicy`.** `'editable'` writes the reference as given, an absent or empty one stored as NULL (the starter's
|
|
648
|
+
contract). `'permanent'` refuses any named value but the stored one, NULL and empty included (`code:
|
|
649
|
+
'PARTNER_REF_PERMANENT'`, nothing saved), and never writes the column. A function is asked only when the reference
|
|
650
|
+
would change, with the current row: `true` locks it (`code: 'PARTNER_REF_LOCKED'`); `{ code, message }` locks it with
|
|
651
|
+
the app's own code and sentence (soc `PARTNER_REF_HUB_BOUND` / `PARTNER_REF_HAS_DATA`, wall `PARTNER_REF_HUB_BOUND` /
|
|
652
|
+
`PARTNER_REF_HAS_TENANT_DATA`, noc `PARTNER_REF_LOCKED` / `PARTNER_REF_HAS_TENANTS`), so its API answers do not change;
|
|
653
|
+
or it may throw its own typed refusal. This package imports no hub code: the app passes its own predicate.
|
|
654
|
+
|
|
655
|
+
**`extraColumns`**: `[{ name, create?, update?, list?, param?, read? }]`. `create: true` inserts the column when the
|
|
656
|
+
field is present; `update: true` writes it, preserving the stored value when omitted (`read(stored)` turns the stored
|
|
657
|
+
value back into a field, `param(value)` into a statement parameter: a JSON column passes `sql.jsonColumn` /
|
|
658
|
+
`sql.jsonParam`); `update: 'now'` stamps `sql.now()` on every update; `list: true` selects it in `all()` and the list.
|
|
659
|
+
|
|
660
|
+
### `createProvisioner(options)` — creating a partner and seeding it
|
|
661
|
+
|
|
662
|
+
```js
|
|
663
|
+
// lib/partnerProvision.js (main thread)
|
|
664
|
+
module.exports = createProvisioner({
|
|
665
|
+
tenancy, db, rbac, logger, // REQUIRED: asPartner (+ currentTenant), invoke, refresh(id), info/error
|
|
666
|
+
writesRequirePlatform: true, // REQUIRED: the same value the partner store is given (below)
|
|
667
|
+
seeds: [ // REQUIRED, the app's own list, run in order INSIDE asPartner(id)
|
|
668
|
+
{ name: 'roles', run: ({ db }) => db.invoke('Role', 'seedDefaults').then((r) => r && r.seeded) },
|
|
669
|
+
{ name: 'templates', run: ({ db }) => db.invoke('EmailTemplate', 'seedDefaults').then((r) => r && r.seeded) },
|
|
670
|
+
{ name: 'reports', run: ({ db }) => db.invoke('Report', 'seedDefaults').then((r) => r && r.seeded) }
|
|
671
|
+
],
|
|
672
|
+
deactivateWith: (id, opts) => db.invoke('Partner', 'setActive', id, 0), // REQUIRED (an attached app: its hub path)
|
|
673
|
+
onPartnersChanged: [ // REQUIRED: a function, or a list: all started at once, each isolated
|
|
674
|
+
() => tenancy.refreshActivePartners(), // first: it is the one that ends acting
|
|
675
|
+
() => hosts.forget()
|
|
676
|
+
]
|
|
677
|
+
});
|
|
678
|
+
```
|
|
679
|
+
|
|
680
|
+
- **`onPartnersChanged(event)`** is the ONE callback after a write to the partner list has committed, on the main
|
|
681
|
+
thread, **for every write that goes through the provisioner**: after `createPartner` (`{ op: 'create', id }`, also
|
|
682
|
+
when a half-built partner could not be deactivated), after the deactivation of a half-built partner (`{ op:
|
|
683
|
+
'deactivate', id }`: `deactivateWith` invokes the store directly and the provisioner fires once after it, so it
|
|
684
|
+
must not go through `write` as well), after `updatePartner` and `setPartnerActive` (`{ op: 'update' | 'activate' |
|
|
685
|
+
'deactivate', id, changes }`), and after **`write(method, ...args)`**, which invokes any store method directly
|
|
686
|
+
(`write('setActiveFromHub', id, 0)`, `write('bindHouseRef', ref)`, `write('update', id, fields)`), fires once after
|
|
687
|
+
it returned, not when it throws, and returns its answer unchanged (`{ op: method, id, changes }`, `id` when the
|
|
688
|
+
first argument is one). **`partnersChanged(event)`** is the same guarded notifier on its own, for a write the app
|
|
689
|
+
makes some other way: call it right after the write returns. **The app wires the callback to both `tenancy.refreshActivePartners()`
|
|
690
|
+
(`createTenancy`) and `hosts.forget()` (`createHostTenant`).** It is a function or a LIST of functions: every entry
|
|
691
|
+
is STARTED AT ONCE, in array order (each called before any is awaited), each ISOLATED, and the write answers only
|
|
692
|
+
after all have settled. One that throws or rejects (a host `forget()` whose app `onForget` throws) is logged at
|
|
693
|
+
error, naming its position (`onPartnersChanged entry 2 of 2`), and stops none of the others; so the stale mark and
|
|
694
|
+
the host forget both happen at once, and order does not matter for correctness (keep the refresh first by
|
|
695
|
+
convention). **Every entry must settle**: nothing bounds one that never does, and it would hold the write's
|
|
696
|
+
response for ever. The package's own two do: `refreshActivePartners()` is bounded by `activeLoadTimeoutMs` (twice
|
|
697
|
+
that behind a load in flight), `forget()` is synchronous. Nothing a subscriber does changes the write's answer; a
|
|
698
|
+
write that throws fires nothing.
|
|
699
|
+
- **The store's write methods called directly do NOT fire it** (the store runs in the worker, inside the write's
|
|
700
|
+
transaction, and cannot reach a main-thread cache; its `onChange` is for in-transaction work). So every main-thread
|
|
701
|
+
write to the partner list goes through the provisioner (`updatePartner`, `setPartnerActive`, `write`) or calls
|
|
702
|
+
`partnersChanged()` right after. **The attached apps' hub-receive paths are the ones to convert**: soc, noc and wall
|
|
703
|
+
`lib/hubPartner.js` (`update`, `setActiveFromHub`, `bindHouseRef`, `setHubHost`, and wall's `applyHubBlock` / `setHubVersion`), soc
|
|
704
|
+
and noc `routes/ops.js` (`setActiveFromHub`, `update`), wall `routes/ops.js` (`setActiveFromHub`), and the desk's
|
|
705
|
+
`lib/hubPartner.js` / `routes/ops.js` (`update`, `setActive`, `bindHouseRef`). Otherwise a partner deactivated AT THE
|
|
706
|
+
HUB, the normal way for an attached app, would not end acting into it nor clear its host until a restart.
|
|
707
|
+
- `provision(partnerId, opts)` runs every seed inside the partner's scope, then **`rbac.refresh(partnerId)` after
|
|
708
|
+
every provision**, the re-provision route's included. Returns `{ <seed name>: what it returned }`. A seed that
|
|
709
|
+
returns `undefined` is an error; `ctx.rows(model, method, …args)` is a read that refuses anything but an array (an
|
|
710
|
+
empty array has to mean empty). A seed gets `{ db, partnerId, rows, tenancy, opts }`.
|
|
711
|
+
**`tenancy` is there by convention, not as a guard**: the desk needs it to read the house's canned replies and
|
|
712
|
+
knowledge-base categories (`tenancy.asPartner(houseId, …)`) before seeding them into the new partner. A seed can
|
|
713
|
+
therefore leave the new partner's scope; one that WRITES outside it must say so in a comment beside the write.
|
|
714
|
+
- `createPartner(fields, opts)` invokes `Partner.create(fields[, opts])`, provisions, logs one info line, returns the
|
|
715
|
+
partner with `seeded`. On a failure it calls `deactivateWith(id, opts)` and throws an error with `partnerId`,
|
|
716
|
+
`deactivated` and `cause`. **If the deactivation itself fails, that is logged at error and the error says the
|
|
717
|
+
partner is still active (`deactivated: false`)** (every copy swallowed it with `.catch(() => {})` while the log said
|
|
718
|
+
"left DEACTIVATED"). The failure path cannot itself fail: every log call is guarded, so a throwing logger never
|
|
719
|
+
replaces the provisioning error, and one that throws on success never turns a provisioned partner into a failed one.
|
|
720
|
+
- **`writesRequirePlatform`** (required, no default; pass the same value as the store's). `true`: `createPartner`,
|
|
721
|
+
`provision`, `updatePartner`, `setPartnerActive` and `write` refuse unless the CURRENT tenant context is platform
|
|
722
|
+
scope (`tenancy.currentTenant()`, read on the main thread; `code: 'tenant_scope_refused'`), BEFORE anything is
|
|
723
|
+
written or any seed runs: `provision(B)` runs its seeds inside `asPartner(B)`, so without it a caller at partner A's
|
|
724
|
+
scope (A's staff, or an operator ACTING as A) seeds B. It reads no database, so it refuses on SQLite too, where the
|
|
725
|
+
store's own check does nothing. `false`: today's behaviour (the platform-only permission in front is the only
|
|
726
|
+
guard). This follows Platform decision D-0005 point 1, extended by the coordinator from the partner table to
|
|
727
|
+
provisioning and reported to the owner. A new app passes `true`; what `true` would change in each existing app,
|
|
728
|
+
from reading the callers of `createPartner` and `provision` at `origin/main` (not a run):
|
|
729
|
+
|
|
730
|
+
| App | Callers, and their scope today | What `true` would change |
|
|
731
|
+
|---|---|---|
|
|
732
|
+
| a new app | — | `true` |
|
|
733
|
+
| 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 |
|
|
734
|
+
| 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 |
|
|
735
|
+
| soc | the partners routes as above; `lib/hubPartner.js` (create) inside `asHouse()`; `scripts/lib/askWorld.js` at platform scope | Nothing found |
|
|
736
|
+
| noc | the partners routes as above; `lib/hubPartner.js` inside `asHouse()`; its `*-pg.js` test scripts inside `asHouse` | Nothing found |
|
|
737
|
+
| 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 |
|
|
738
|
+
| 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 |
|
|
739
|
+
|
|
740
|
+
### `actingRoutes(options)`, `actingLocals(options)`, `views/acting-banner.ejs`
|
|
741
|
+
|
|
742
|
+
```js
|
|
743
|
+
// routes/partners.js: mounted BEFORE every '/:id' route (Express matches in declaration order)
|
|
744
|
+
router.use(actingRoutes({
|
|
745
|
+
Router: express.Router, tenancy, db, audit, requirePermission,
|
|
746
|
+
permission: 'partners.manage', // REQUIRED: the app's own permission name
|
|
747
|
+
landing: '/', // REQUIRED: a local path; '//host' and 'http:' are refused
|
|
748
|
+
refuseInactive: true, // REQUIRED, no default (below)
|
|
749
|
+
auditScopes: { start: 'house', stop: 'partner' }, // REQUIRED, no default (below): where the two audit rows land
|
|
750
|
+
logger, // { error }: REQUIRED when an auditScopes value is 'both'
|
|
751
|
+
messages: {}, // optional: house, inactive(name), started(name), notActing, stopped, unknown
|
|
752
|
+
flash: undefined, // optional: (req, res, type, message) => void | Promise (below)
|
|
753
|
+
notFound: undefined // optional: (req, res) => the app's 404 answer (below)
|
|
754
|
+
}));
|
|
755
|
+
// app.js, after the session and scope middleware
|
|
756
|
+
app.use(actingLocals({ tenancy, readOnly: false /* the write gate's whileActing === 'readOnly' */, note: null }));
|
|
757
|
+
app.set('views', [path.join(__dirname, 'views'), require('@aria-framework/tenancy').viewsDir /* , … */]);
|
|
758
|
+
// views/partials/staff-head.ejs
|
|
759
|
+
<%- include('acting-banner') %>
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
- **Two things the routes need from the app, unless it overrides them:** a flash helper with the shape
|
|
763
|
+
`res.flash(type, message, callback)`, WITH a callback (the redirect happens inside it; a helper of another shape
|
|
764
|
+
answers a 500), and a view `errors/404` (rendered with `{ title: 'Not found' }`). An app whose helpers differ passes
|
|
765
|
+
`flash(req, res, type, message)` (it may return a promise; the redirect follows when it settles, a rejection is
|
|
766
|
+
`next(err)`) and/or `notFound(req, res)`; neither has a default other than those two.
|
|
767
|
+
- `POST /:id/act-as` (behind `requirePermission(permission)`; a non-digit id falls through before the gate): an
|
|
768
|
+
unknown id answers the app's `errors/404` view (or flashes `messages.unknown`); the house and, with
|
|
769
|
+
`refuseInactive`, a deactivated partner are refused with a flash, **audited nothing and switched nothing**.
|
|
770
|
+
Otherwise **`partner.act_as_start` is audited BEFORE the switch**, so the row lands in the operator's own scope (the
|
|
771
|
+
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`.
|
|
772
|
+
- `POST /stop-acting` is **not behind any permission** (acting removes the platform-only ones, and the way out must not
|
|
773
|
+
depend on them): a user who is not platform staff gets the 404 view; an operator not acting is sent to `landing`;
|
|
774
|
+
otherwise the flags are cleared and **`partner.act_as_stop` is audited AFTER the switch back** (in the scope
|
|
775
|
+
`auditScopes.stop` names: with `'partner'`, every app's value today, it lands in the partner the operator was
|
|
776
|
+
inside, because the request's tenant was fixed when the request began; NOT in the house), then back to the
|
|
777
|
+
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.
|
|
778
|
+
- `actingLocals` sets `actingPartnerName` **only when `tenancy.contextFor(req)` shows the scope has moved to that
|
|
779
|
+
partner** (a partner user's stray acting flag, which the scope code ignores, draws no banner), `actingReadOnly`
|
|
780
|
+
(`readOnly` while acting), `actingStopPath` (default `/admin/partners/stop-acting`) and `actingNote`.
|
|
781
|
+
- The banner escapes the name, needs the app's `csrfToken()` while it shows (it throws without it), and keeps the
|
|
782
|
+
starter's classes.
|
|
783
|
+
|
|
784
|
+
**`auditScopes: { start, stop }`** (required, no default). Where the two rows land: `start` is `'house'` or
|
|
785
|
+
`'both'`; `stop` is `'partner'`, `'house'` or `'both'`. `'house'` is the operator's own scope (`contextFor` once
|
|
786
|
+
the acting keys are absent), `'partner'` the partner acted in, `'both'` one row in each. The owner decided on 29 Nov
|
|
787
|
+
2026 that the stop entry goes into both logs, and that a NEW app's start entry does too (`start: 'both'`).
|
|
788
|
+
|
|
789
|
+
- **What each row contains.** Both rows of a pair are built by the app's own `audit(req, action, opts)` from the same
|
|
790
|
+
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
|
|
791
|
+
(`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
|
|
792
|
+
the acting stamp (`acting_as_partner`): the start row is written before the keys are set and the stop row after
|
|
793
|
+
they are removed, as today. Only `partner_id` differs, from the scope each is written in. The partner's row is what
|
|
794
|
+
the source's stop row is today, nothing more.
|
|
795
|
+
- **Order and failure.** The start rows are written before the switch, the stop rows after the switch back, as today.
|
|
796
|
+
The row today's code writes (the start row in the house, the stop row in the partner) is called exactly as today, in
|
|
797
|
+
the request's context: a synchronous throw from the app's `audit` stops the switch at the start (as the source);
|
|
798
|
+
an asynchronous failure is the app's helper's to log, as today. With `stop: 'house'` the one stop row is written in
|
|
799
|
+
the operator's own scope (`tenancy.run(contextFor(req), …)`), with today's failure behaviour. The ADDED row of a
|
|
800
|
+
`'both'` is written in its own scope (`tenancy.run`) and isolated: a throw or a rejected promise from `audit` is
|
|
801
|
+
logged at error (`logger`) and undoes no switch and fails no request.
|
|
802
|
+
|
|
803
|
+
| App | `auditScopes` |
|
|
804
|
+
|---|---|
|
|
805
|
+
| starter, hub, soc, noc, wall, desk | `{ start: 'house', stop: 'partner' }` (today's, in all six) |
|
|
806
|
+
| a new app | `{ start: 'both', stop: 'both' }` (both decided by the owner) |
|
|
807
|
+
|
|
808
|
+
**`refuseInactive`, and acting inside a partner that is deactivated** (the owner's answers 2 and D-0005). The rule as
|
|
809
|
+
decided: no house operator works inside a deactivated partner. Two halves enforce it: **the switch refuses a deactivated
|
|
810
|
+
partner** (`refuseInactive`, here), and **an operator already inside a partner when it is deactivated is no longer
|
|
811
|
+
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
|
|
812
|
+
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
|
|
813
|
+
follows `contextFor`, so it disappears with it). **Both are on for a new app; each existing app turns them on at its own
|
|
814
|
+
adoption.** `refuseInactive` is required with no default so that no existing app changes silently.
|
|
815
|
+
|
|
816
|
+
`tenancy` functions this part calls: `asPartner(partnerId, fn)` and `currentTenant()` (the provisioner), `contextFor(req)`
|
|
817
|
+
(`actingLocals`, and the stop route for a `stop` of `'house'` or `'both'`) and `run(context, fn)` (the acting routes, for a
|
|
818
|
+
row written outside the request's own scope).
|
|
819
|
+
|
|
820
|
+
### `createActingIdle(options)` — the idle end of working in a partner
|
|
821
|
+
|
|
822
|
+
Working in a partner can end after a period without activity that the app sets (the owner's decision of 29 Nov 2026;
|
|
823
|
+
**0, the apps' default, is today's behaviour: no idle end, and not one session write from this piece on any
|
|
824
|
+
request**). One implementation, mounted either way:
|
|
825
|
+
|
|
826
|
+
```js
|
|
827
|
+
const actingIdle = createActingIdle({
|
|
828
|
+
idleMinutes: () => settings.actingIdleMinutes, // REQUIRED, sync or async, a whole number; 0 = no idle end
|
|
829
|
+
now: Date.now, isBackground, audit, logger, // REQUIRED (logger: { error })
|
|
830
|
+
auditScopes: { stop: 'partner' }, // REQUIRED, no default: actingRoutes' auditScopes.stop (existing apps 'partner', a new app 'both')
|
|
831
|
+
run: tenancy.run, // REQUIRED for 'partner' and 'both': (ctx, fn), runs fn in a tenant context
|
|
832
|
+
flash: undefined, messages: {} // optional: res.flash(kind, text, callback) by default; idle(minutes, name), error(name)
|
|
833
|
+
});
|
|
834
|
+
// an app with its own acting code and scope middleware:
|
|
835
|
+
app.use(session); app.use(actingIdle.loaded); // directly after the session (needed when anything sits before `before`)
|
|
836
|
+
app.use(actingIdle.before); app.use(appScopeMiddleware); app.use(actingIdle.after);
|
|
837
|
+
// an app on this package's scope part (the same two halves, run around it):
|
|
838
|
+
app.use(tenancy.requestScope({ actingIdle }));
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
- **Requirement:** an app with its own acting code keeps the acting keys every app uses today,
|
|
842
|
+
`req.session.actingPartnerId` and `req.session.actingPartnerName` (hub, soc and noc set exactly these in
|
|
843
|
+
`routes/partners.js`; soc also in `lib/hubSso.js`).
|
|
844
|
+
- **Why two halves.** The end must happen BEFORE the scope middleware fixes the request's tenant: ended after it, the
|
|
845
|
+
very request that found the period over would still run, and write, inside the partner. `before` judges the period and
|
|
846
|
+
clears `actingPartnerId` / `actingPartnerName`; the scope middleware then places the request in the operator's own
|
|
847
|
+
scope; `after` tells the person once, re-reads the row and, if it still works in that partner, saves the session
|
|
848
|
+
and audits `partner.act_as_stop` (`entity_type: 'partner'`, `entity_id`, `detail: { reason: 'idle',
|
|
849
|
+
minutes }`) where `auditScopes.stop` says (`'partner'`: in the partner acted in, through `run`; `'house'`: in the
|
|
850
|
+
operator's own scope, where the request now runs; `'both'`: one row in each); otherwise the session is left as it was
|
|
851
|
+
loaded and nothing is audited. The notice has kind `'warning'`: "Working in <name> ended after N minutes without
|
|
852
|
+
activity." A failing audit row is logged and changes nothing else. The partner's name is the one the act-as route
|
|
853
|
+
stored; the framework's `ui/flash` partial escapes every message (`<%= %>`), which is what makes putting it in the
|
|
854
|
+
notice safe: an app rendering flash messages unescaped must not.
|
|
855
|
+
- **The clock** is the session's `actingIdleAt: { partnerId, at }`. It starts at the first request that sees the partner
|
|
856
|
+
being worked in (a clock for another partner, or none, starts afresh), moves on a request that is not background
|
|
857
|
+
(`isBackground`: live streams and polls) when a stamp is due (at most once a minute, as fleet view's), and is removed
|
|
858
|
+
when the session is not acting. Each of these writes is preceded by a re-read of the session's row and made only if it
|
|
859
|
+
still works in that partner (an automatic end found otherwise is not written and not audited); at 0 minutes none of
|
|
860
|
+
them happens. The rules are the ones fleet view uses (`lib/scope/idle.js`), and the same window applies (see
|
|
861
|
+
"When the package writes the session" under fleet view).
|
|
862
|
+
- **Fail closed:** a throw from `idleMinutes()`, or an answer that is not a whole number of 0 or more, ends working in the
|
|
863
|
+
partner (reason `error`, told), never keeps it unchecked. Not acting, it writes nothing.
|
|
864
|
+
- `tenancy.requestScope()` with no argument is exactly 0.1.0's middleware; its only option is `{ actingIdle }`, and
|
|
865
|
+
anything else is refused. `actingRoutes`, `actingLocals` and the banner are unchanged: the idle end needs no option on
|
|
866
|
+
them (the banner follows `contextFor`, which no longer sees the acting keys).
|
|
867
|
+
|
|
868
|
+
## Wiring the three parts
|
|
869
|
+
|
|
870
|
+
The three parts were built against stand-ins for each other; this is how they join, and it is exactly the assembly
|
|
871
|
+
`test/integration/` runs on PostgreSQL under row-level security and on SQLite (its `helpers.js` holds the same lines
|
|
872
|
+
between its `WIRING` markers). `test/integration/surface.js` checks EVERY code block of this section: the first must
|
|
873
|
+
equal those lines; any other must appear in `helpers.js` line by line in the same order (`/* … */` stands for
|
|
874
|
+
anything, a trailing `//` comment is ignored), unless its first line is `// illustrative:`, which marks a sketch of
|
|
875
|
+
app code the integration app has no counterpart for.
|
|
876
|
+
|
|
877
|
+
```js
|
|
878
|
+
// The main thread. `db` is the app's db client, `logger` its logger, `rbac` its role cache (`refresh(partnerId)`);
|
|
879
|
+
// `dbKind`, `actingRequiresActive`, `writesRequirePlatform` and `refuseInactive` are the app's settings (a new app:
|
|
880
|
+
// 'postgres', true, true, true; ONE writesRequirePlatform constant goes to the store and the provisioner); MESSAGES its sentences;
|
|
881
|
+
// `auditScopes` for actingRoutes (every existing app: { start: 'house', stop: 'partner' }; a new app: { start: 'both', stop: 'both' }).
|
|
882
|
+
const {
|
|
883
|
+
createTenancy, createWriteGate, createHostTenant, createTenantChrome, createProvisioner, actingRoutes, actingLocals, viewsDir
|
|
884
|
+
} = require('@aria-framework/tenancy');
|
|
885
|
+
|
|
886
|
+
// 1. The scope part first: everything else takes `tenancy`.
|
|
887
|
+
const tenancy = createTenancy({ db, logger, dbKind, platformRequiresHouse: true, actingRequiresActive });
|
|
888
|
+
|
|
889
|
+
// 2. The hosts part: the per-tenant chrome, the request chrome that applies it, then host resolution.
|
|
890
|
+
const chrome = createTenantChrome({ tenancy, db, fields: createTenantChrome.STARTER_FIELDS });
|
|
891
|
+
const requestChrome = {
|
|
892
|
+
async applyTo(res) {
|
|
893
|
+
const t = tenancy.currentTenant();
|
|
894
|
+
const c = await chrome.chromeFor(t ? t.partnerId : null);
|
|
895
|
+
res.locals.displayTimezone = c.displayTimezone;
|
|
896
|
+
}
|
|
897
|
+
};
|
|
898
|
+
const hosts = createHostTenant({
|
|
899
|
+
tenancy, db, logger, trustForwardedHost: false, chrome: requestChrome, isSignedIn: (s) => !!s.user
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
// 3. The partners part: ONE callback after every committed write to the partner list, to BOTH caches.
|
|
903
|
+
const provisioner = createProvisioner({
|
|
904
|
+
tenancy, db, rbac, logger, writesRequirePlatform, // the same value the partner store is given
|
|
905
|
+
seeds: [
|
|
906
|
+
{ name: 'roles', run: ({ db: d }) => d.invoke('Role', 'seedDefaults').then((r) => r.seeded) },
|
|
907
|
+
{ name: 'settings', run: ({ db: d, opts }) => d.invoke('Settings', 'seedDefaults', opts && opts.timezone).then((r) => r.seeded) }
|
|
908
|
+
],
|
|
909
|
+
deactivateWith: (id) => db.invoke('Partner', 'setActive', id, 0),
|
|
910
|
+
// All started at once, each isolated, all settled before the write answers; the active set first by convention.
|
|
911
|
+
onPartnersChanged: [
|
|
912
|
+
() => tenancy.refreshActivePartners(), // marks the active set stale at once, then reloads it
|
|
913
|
+
() => hosts.forget() // the host map: re-read at the next lookup
|
|
914
|
+
]
|
|
915
|
+
});
|
|
916
|
+
|
|
917
|
+
// 4. The write gate.
|
|
918
|
+
const gate = createWriteGate({
|
|
919
|
+
tenancy, whileActing: 'write', houseReading: null, messages: MESSAGES, logger,
|
|
920
|
+
partnerById: (id) => db.invoke('Partner', 'byId', id)
|
|
921
|
+
});
|
|
922
|
+
```
|
|
923
|
+
|
|
924
|
+
```js
|
|
925
|
+
// app.js, in this order (the app supplies res.flash(type, message, callback) and an errors/404 view, or passes
|
|
926
|
+
// actingRoutes its own flash and notFound)
|
|
927
|
+
app.set('views', [path.join(__dirname, 'views'), viewsDir]);
|
|
928
|
+
app.use(session({ /* … */ }));
|
|
929
|
+
app.use(tenancy.requestScope()); // after the session, before the first router
|
|
930
|
+
app.use(actingLocals({ tenancy, readOnly: false })); // after the scope: it asks contextFor
|
|
931
|
+
app.use((req, res, next) => { requestChrome.applyTo(res).then(() => next(), next); });
|
|
932
|
+
loginRouter.use(hosts.middleware()); // the login routers only, never app.use
|
|
933
|
+
app.use('/admin/partners', actingRoutes({ Router: express.Router, tenancy, db, audit, requirePermission, logger,
|
|
934
|
+
permission: 'partners.manage', landing: '/dashboard', refuseInactive, auditScopes })); // before the app's '/:id' routes
|
|
935
|
+
app.use('/admin/partners', partnerRoutes); // its writes: provisioner.createPartner / updatePartner / setPartnerActive / provision
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
```js
|
|
939
|
+
// illustrative: the worker and the boot file of a real app (the integration app builds its models in fixtures.js)
|
|
940
|
+
// models/Partner.js: the partner model is the store (scope reads its house/all/seedHouse, hosts its all, the acting
|
|
941
|
+
// routes and the gate its byId), given the same writesRequirePlatform as the provisioner.
|
|
942
|
+
module.exports = createPartnerStore({ driver: () => database.driver(), sql, writesRequirePlatform, /* … */ });
|
|
943
|
+
// server.js
|
|
944
|
+
await tenancy.atBoot(async () => { /* the rest of boot, in the house scope */ });
|
|
945
|
+
```
|
|
946
|
+
|
|
947
|
+
**Order.** Construct `tenancy` first (every other factory takes it), then the chrome and `hosts` (the provisioner's
|
|
948
|
+
callback needs `hosts`), then the provisioner, then the gate. Mount the session, `tenancy.requestScope()`,
|
|
949
|
+
`actingLocals`, the request chrome, and only then the routers.
|
|
950
|
+
|
|
951
|
+
**At boot**, `tenancy.atBoot(fn)`: it seeds the house (`Partner.seedHouse()` at platform scope, which
|
|
952
|
+
`writesRequirePlatform: true` requires), then makes the first load of the active-partner set (with
|
|
953
|
+
`actingRequiresActive`), then runs `fn` in the house scope. Nothing else needs a first load: the host map is read at
|
|
954
|
+
its first lookup and each partner's chrome at its first use. Until the active set is loaded, an acting flag is not
|
|
955
|
+
honoured by a synchronous `contextFor`; a request carrying one makes `requestScope` load the set first.
|
|
956
|
+
|
|
957
|
+
**The callback** is a list: the provisioner STARTS every entry at once, in array order, each isolated, and answers the
|
|
958
|
+
write after all have settled, so a host `forget()` that throws (an app's `onForget`) stops nothing, and the stale mark
|
|
959
|
+
and the host forget both happen at once; order does not matter for correctness (the refresh first by convention).
|
|
960
|
+
Every entry must settle (the package's two do: the refresh is bounded by `activeLoadTimeoutMs`, `forget()` is
|
|
961
|
+
synchronous). A refresh marks the active set stale at once, so a request carrying an acting flag that arrives while
|
|
962
|
+
its load is in flight waits for it (normally milliseconds, at most `activeLoadTimeoutMs`, twice that behind a load
|
|
963
|
+
already in flight; after ANY partner change, a rename included); a live stream's re-check awaits
|
|
964
|
+
`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
|
|
965
|
+
deactivation can save its older session over the cleared keys, and then the operator is inside again once the
|
|
966
|
+
partner is active again.
|
|
967
|
+
|
|
968
|
+
**What the callback does not cover**, and what the app calls instead:
|
|
969
|
+
|
|
970
|
+
- a store write the app invokes directly (`db.invoke('Partner', …)`): go through `provisioner.write(method, …args)`,
|
|
971
|
+
or call `provisioner.partnersChanged()` right after. A write that does neither leaves acting into a deactivated
|
|
972
|
+
partner honoured and its host resolving until the next change (pinned in `test/integration/`);
|
|
973
|
+
- `provisioner.provision(id)` (a re-provision) and a settings save fire no callback: call `chrome.forget(id)` after each;
|
|
974
|
+
- another process: neither cache is shared. Pass `activeMaxAgeMs` (scope) and `maxAgeMs` (hosts), or tell the other
|
|
975
|
+
processes, each calling `hosts.forget()` and `tenancy.refreshActivePartners()`.
|
|
976
|
+
|
|
977
|
+
**Every name that crosses a part**, with the part that owns it:
|
|
978
|
+
|
|
979
|
+
| Name | Owner | Who uses it |
|
|
980
|
+
|---|---|---|
|
|
981
|
+
| `createTenancy(...)` → `tenancy` | scope | passed as `tenancy` to `createWriteGate`, `createHostTenant`, `createTenantChrome`, `createProvisioner`, `actingRoutes`, `actingLocals` |
|
|
982
|
+
| `tenancy.asPartner(id, fn)` | scope | hosts (`createHostTenant`, `createTenantChrome`), partners (`createProvisioner`: every seed runs inside it) |
|
|
983
|
+
| `tenancy.asPlatform(fn)` | scope | hosts (`createHostTenant` reads `Partner.all` in it) |
|
|
984
|
+
| `tenancy.housePartnerId()` | scope | hosts (`createHostTenant`: an unknown host narrows to the house) |
|
|
985
|
+
| `tenancy.currentTenant()` | scope | hosts (`createTenantChrome`'s `cached`; the app's request chrome), partners (`createProvisioner`'s `writesRequirePlatform`) |
|
|
986
|
+
| `tenancy.contextFor(req)` | scope | partners (`actingLocals`: the banner shows only when the scope moved) |
|
|
987
|
+
| `tenancy.refreshActivePartners()` | scope | the app, from `createProvisioner`'s `onPartnersChanged` |
|
|
988
|
+
| `tenancy.requestScope()`, `tenancy.atBoot(fn)` | scope | the app (mount; boot) |
|
|
989
|
+
| `actingRequiresActive` (option of `createTenancy`) | scope | ends acting into a partner deactivated through the provisioner |
|
|
990
|
+
| `hosts.forget()` | hosts | the app, from `createProvisioner`'s `onPartnersChanged` |
|
|
991
|
+
| `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) |
|
|
992
|
+
| `chrome.forget(id)` | hosts | the app, after a settings save and after `provisioner.provision(id)` |
|
|
993
|
+
| `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()]` |
|
|
994
|
+
| `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 |
|
|
995
|
+
| `provisioner.createPartner`, `updatePartner`, `setPartnerActive`, `write`, `partnersChanged` | partners | the app's main-thread writes to the partner list |
|
|
996
|
+
| `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) |
|
|
997
|
+
| `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 |
|
|
998
|
+
| `tenancy.whenActivePartnersKnown()` | scope | the app, before `forSession` in a live stream's re-check (`@aria-framework/notify`'s `deps.scopeOf`) |
|
|
999
|
+
| `tenancy.run(ctx, fn)` | scope | partners (`actingRoutes`: a row written in an explicit scope) |
|
|
1000
|
+
| `refuseInactive` (option of `actingRoutes`) | partners | refuses the switch into a deactivated partner; `actingRequiresActive` ends one already inside |
|
|
1001
|
+
| `Partner.house()`, `Partner.seedHouse()` | partners (the store) | scope (`housePartnerId`, `atBoot`) |
|
|
1002
|
+
| `Partner.all()` (with `id`, `is_active`, `portal_host`) | partners (the store) | scope (the active set), hosts (the host map) |
|
|
1003
|
+
| `Partner.byId(id)` (with `name`, `is_house`, `is_active`) | partners (the store) | partners (`actingRoutes`), scope (the gate's `partnerById`, passed by the app) |
|
|
1004
|
+
| session `actingPartnerId`, `actingPartnerName` | partners (`actingRoutes` writes them) | scope (`contextFor` reads them and, for a partner known inactive, deletes them) |
|
|
1005
|
+
| `req.partnerId`, `req.partnerHost` | hosts (the middleware sets them) | the app's login routes |
|
|
1006
|
+
| `res.locals.actingPartnerName`, `actingReadOnly`, `actingStopPath`, `actingNote` | partners (`actingLocals`) | partners (`views/acting-banner.ejs`, under `viewsDir`) |
|
|
1007
|
+
|
|
1008
|
+
## Adopting it
|
|
1009
|
+
|
|
1010
|
+
_(per part: what an app deletes, what it passes in, and a table "What changes for an adopting app")_
|
|
1011
|
+
|
|
1012
|
+
### Scope
|
|
1013
|
+
|
|
1014
|
+
- **Before adopting, search for every place the app calls the gate (its `writeScope`/`readScope`/`canAddTo` copies)
|
|
1015
|
+
inside `asPartner`, `asHouse`, `asOwnPartner`, `asPlatform` or `acrossAll`.** That is where the old code and the
|
|
1016
|
+
package can differ: the package's runner runs in the context it judged, the old partner-scope runner ran in the
|
|
1017
|
+
surrounding one.
|
|
1018
|
+
- `lib/tenant.js` becomes the `createTenancy` call (plus the app's own extras, added to the same object) and
|
|
1019
|
+
`lib/scope.js` re-exports it. The hub and soc app delete their inline request-scope middleware in `app.js` for
|
|
1020
|
+
`tenancy.requestScope()`; the desk deletes `middleware/tenant.js`.
|
|
1021
|
+
- The write gate: the soc app deletes `canAddTo` and its five `readScope`/`writeScope` copies; the noc app deletes
|
|
1022
|
+
`lib/customerScope.js` (keeping `canAddFirewallFor` over `gate.writeScope`); the hub deletes `createsLandInThisTenant`,
|
|
1023
|
+
`writesReachThisTenant`, `editRefusal`, `platformDestination`, `authorship`, `houseOperatorNames` from `lib/tenant.js`;
|
|
1024
|
+
the desk deletes `lib/tenantWriteRefusal.js` and mounts `gate.crossTenantWriteHandler()` before its error handler.
|
|
1025
|
+
|
|
1026
|
+
**What changes for an adopting app**
|
|
1027
|
+
|
|
1028
|
+
| # | App | Difference between the app's copy and the package | Keeps today's behaviour | Or intended by |
|
|
1029
|
+
|---|---|---|---|---|
|
|
1030
|
+
| 1 | hub, desk | `canHostTenants()` read `config.dbKind` | `dbKind: () => config.dbKind` | |
|
|
1031
|
+
| 2 | starter, noc, wall | `canHostTenants()` returned `true` | `dbKind: 'postgres'` | |
|
|
1032
|
+
| 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) | |
|
|
1033
|
+
| 3 | desk | platform scope honoured only for a house member (`isPlatformUser`), its middleware resolving the house first | `platformRequiresHouse: true` | |
|
|
1034
|
+
| 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) |
|
|
1035
|
+
| 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" |
|
|
1036
|
+
| 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` | |
|
|
1037
|
+
| 7 | desk | `forEachPartner` warmed the partner's chrome, swallowing its failure | `beforeEachPartner: (p) => chromeFor(p.id).catch(() => {})` | |
|
|
1038
|
+
| 8 | desk | its API guard placed a platform principal by `isPlatformUser` | `forApiUser` does the same when `platformRequiresHouse` is true | |
|
|
1039
|
+
| 9 | noc, wall | `lib/scope.js` had no `forSession` | | plan §3 rows 2, 4, "starter ahead" |
|
|
1040
|
+
| 10 | every app | `asRefreshTokenOwner` required the API package and the `RefreshToken` model itself | `refreshTokenOwner: (raw) => db.invoke('RefreshToken', 'partnerForHash', hashRefresh(raw))` | |
|
|
1041
|
+
| 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") | |
|
|
1042
|
+
| 12 | desk | the house id's error and the refused-platform log named its own migration | | log wording only |
|
|
1043
|
+
| 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) |
|
|
1044
|
+
| 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) |
|
|
1045
|
+
| 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) |
|
|
1046
|
+
| 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) |
|
|
1047
|
+
| 17 | hub | `platformDestination` read `Partner.byId` itself | `partnerById: (id) => db.invoke('Partner', 'byId', id)` | |
|
|
1048
|
+
| 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 |
|
|
1049
|
+
| 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") |
|
|
1050
|
+
| 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 |
|
|
1051
|
+
| 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) |
|
|
1052
|
+
| 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 |
|
|
1053
|
+
| 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 |
|
|
1054
|
+
| 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 |
|
|
1055
|
+
| 25 | desk | two handlers, two views' titles in code | `messages.crossTenant`, `refusalView: 'errors/generic'` | one handler |
|
|
1056
|
+
| 26 | desk | `flashTextFor`, `isPlatformCrossTenantWrite`, `isActingElsewhere` | `crossTenantRefusalOf(err, req)` (+ its own flash sentence per `kind`), `actingElsewhere(req)` | |
|
|
1057
|
+
| 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) |
|
|
1058
|
+
| 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` |
|
|
1059
|
+
| 29 | soc, noc | a job that gated a write with `writeScope(customer)` judged the current scope | it passes `null` as the request | |
|
|
1060
|
+
| 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 |
|
|
1061
|
+
|
|
1062
|
+
### Hosts
|
|
1063
|
+
|
|
1064
|
+
The three files keep their paths and become the package's, so no `require` moves:
|
|
1065
|
+
|
|
1066
|
+
```js
|
|
1067
|
+
// lib/hostname.js
|
|
1068
|
+
const { hostname } = require('@aria-framework/tenancy');
|
|
1069
|
+
const RESERVED = { reservedLabels: [] }; // the hub: ['registry', 'node', 'apt']
|
|
1070
|
+
module.exports = {
|
|
1071
|
+
...hostname,
|
|
1072
|
+
hostFor: (label, base) => hostname.hostFor(label, base, RESERVED),
|
|
1073
|
+
refuseReservedHost: (host, base) => hostname.refuseReservedHost(host, base, RESERVED),
|
|
1074
|
+
assertLabelNotReserved: (label) => hostname.assertLabelNotReserved(label, RESERVED)
|
|
1075
|
+
// the hub keeps hostLabelOf, partnerHostLabel, partnerHubHost here
|
|
1076
|
+
};
|
|
1077
|
+
|
|
1078
|
+
// lib/tenantChrome.js
|
|
1079
|
+
const { createTenantChrome } = require('@aria-framework/tenancy');
|
|
1080
|
+
module.exports = createTenantChrome({ tenancy: require('./tenant'), db: require('./db-client'), fields: createTenantChrome.STARTER_FIELDS });
|
|
1081
|
+
|
|
1082
|
+
// middleware/hostTenant.js
|
|
1083
|
+
const ht = require('@aria-framework/tenancy').createHostTenant({
|
|
1084
|
+
tenancy: require('../lib/tenant'), db: require('../lib/db-client'), logger: require('../lib/logger'),
|
|
1085
|
+
trustForwardedHost: require('../config').trustForwardedHost, chrome: require('../lib/requestChrome'),
|
|
1086
|
+
isSignedIn: (s) => !!s.user // the desk: (s) => !!(s.user || s.contact)
|
|
1087
|
+
// the noc app also: maxAgeMs: 60000, onForget: <its hub host store's reset>
|
|
1088
|
+
});
|
|
1089
|
+
module.exports = { hostTenant: ht.middleware, forget: ht.forget, partnerIdForRequest: ht.partnerIdForRequest, partnerOfHost: ht.partnerOfHost };
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
The apps' own source checks of WHERE the middleware is mounted (the login routers only, never `app.js`, the
|
|
1093
|
+
`forget()` count in the partner routes, the invite router, the partner model's host refusal) stay in each app's
|
|
1094
|
+
`test-host-tenant.js`; the cases about the moved code are in this package's `test/hosts/`.
|
|
1095
|
+
|
|
1096
|
+
**Every code path in the app that creates, changes, activates or deactivates a partner must call `forget()`** (the
|
|
1097
|
+
partner routes, a hub-receive path, any provisioning that runs in a serving process). The package cannot see those
|
|
1098
|
+
writes. Test the obligation through the app's own route: deactivate a partner there, then ask `partnerOfHost` (or
|
|
1099
|
+
sign in) on its host and expect `null` (the house); a count of `forget()` calls in the source is not enough on its
|
|
1100
|
+
own. `forget()` reaches one process only: an app run as more than one process must tell the others, or accept the
|
|
1101
|
+
`maxAgeMs` bound as the longest a deactivated host may still resolve there.
|
|
1102
|
+
|
|
1103
|
+
**What changes for an adopting app**
|
|
1104
|
+
|
|
1105
|
+
| # | App | Difference between its copy and the package | Keeps today's behaviour / why it changes |
|
|
1106
|
+
|---|---|---|---|
|
|
1107
|
+
| 1 | all | `hostFor`, `refuseReservedHost`, `assertLabelNotReserved` take a required `{ reservedLabels }` | pass `[]` (the hub its three) through the wrapper above |
|
|
1108
|
+
| 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 |
|
|
1109
|
+
| 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 |
|
|
1110
|
+
| 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 |
|
|
1111
|
+
| 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) |
|
|
1112
|
+
| 6 | desk | hostname comments say "installation's own address" for "vendor's portal" | wording only |
|
|
1113
|
+
| 7 | all | `trustForwardedHost` is passed in, not read from `config` inside the middleware | pass `config.trustForwardedHost` |
|
|
1114
|
+
| 8 | all | `chrome` (the request chrome to re-apply) is passed in | pass `lib/requestChrome.js` |
|
|
1115
|
+
| 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) |
|
|
1116
|
+
| 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) |
|
|
1117
|
+
| 11 | noc | the extra exports `loadHosts`, `_hostMapForTests`, `HUB_HOSTS_MAX_AGE_MS`, `_hubAgeForTests` | not in the package; its tests use `partnerOfHost`/`forget()` |
|
|
1118
|
+
| 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) |
|
|
1119
|
+
| 13 | desk | the request fields are `req.partnerId` / `req.partnerHost`, not `req.portalPartnerId` / `req.portalHost` | intended: plan piece 8 (the desk renames on adoption) |
|
|
1120
|
+
| 14 | desk | warnings say "Partner host(s)" and "a username in two tenants" for "Portal host(s)" and "a contact" | wording only |
|
|
1121
|
+
| 15 | hub | `partnerForRequest` is named `partnerIdForRequest` | export it under the old name too, or rename the portal's calls; the function is the same |
|
|
1122
|
+
| 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 |
|
|
1123
|
+
| 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) |
|
|
1124
|
+
| 18 | desk | `brandNow()` | `chrome.cached('brandName', <its neutral brand>)` |
|
|
1125
|
+
| 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 |
|
|
1126
|
+
| 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) |
|
|
1127
|
+
| 21 | all | the reserved-label, IDN and `isHostLabel` examples in comments and tests use invented names | wording only |
|
|
1128
|
+
|
|
1129
|
+
### Partners
|
|
1130
|
+
|
|
1131
|
+
- `models/Partner.js` becomes `{ ...createPartnerStore({...}), ...` the app's hub-receive and own methods `}` (the hub
|
|
1132
|
+
keeps `ensureExternalRefs`, `setDesk`, `setTakeover`, `ensureHouseDesk`; the attached apps their `byExternalRef`,
|
|
1133
|
+
`setActiveFromHub`, `setHubVersion`, …). An app-specific refusal before a core method (the desk's hub-managed name,
|
|
1134
|
+
active state and host flag) stays as a wrapper around that method.
|
|
1135
|
+
- `lib/partnerProvision.js` becomes the `createProvisioner` call; the re-provision route drops its own
|
|
1136
|
+
`rbac.refresh` (the desk) because `provision` does it.
|
|
1137
|
+
- `routes/partners.js` deletes its `stop-acting` and `/:id/act-as` handlers and mounts `actingRoutes` before its first
|
|
1138
|
+
`/:id` route; `app.js` replaces its `actingPartnerName` (and `actingReadOnly`) locals with `actingLocals`;
|
|
1139
|
+
`views/partials/staff-head.ejs` replaces its banner block with `include('acting-banner')` and adds `viewsDir`. An app
|
|
1140
|
+
test that reads the banner's condition out of `staff-head.ejs` (the starter's `test-act-as-partner.js`) re-points
|
|
1141
|
+
at the package's view, whose own tests now hold it.
|
|
1142
|
+
- Every main-thread write to the partner list goes through the provisioner (`updatePartner`, `setPartnerActive`,
|
|
1143
|
+
`write`) or calls `partnersChanged()` after it; an attached app converts its hub-receive paths (named under
|
|
1144
|
+
"Partners"). **Test obligation at adoption:** deactivate a partner through the app's OWN hub-receive path and assert
|
|
1145
|
+
the callback fired; once the three parts are joined, also that acting into that partner has ended and its host no
|
|
1146
|
+
longer resolves.
|
|
1147
|
+
|
|
1148
|
+
What changes for an adopting app:
|
|
1149
|
+
|
|
1150
|
+
| # | Difference between the app's copy and the package | App | Keeps today's behaviour / intended change |
|
|
1151
|
+
|---|---|---|---|
|
|
1152
|
+
| 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). |
|
|
1153
|
+
| 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. |
|
|
1154
|
+
| 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. |
|
|
1155
|
+
| 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. |
|
|
1156
|
+
| 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). |
|
|
1157
|
+
| 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. |
|
|
1158
|
+
| 7 | Name length limit | hub 200 (its entry-limits helper) | `nameMaxLength: 200` (sentence: "may be at most 200 characters"); the others `null`. |
|
|
1159
|
+
| 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). |
|
|
1160
|
+
| 9 | The reference on update | starter, desk `'editable'`; hub `'permanent'`; soc, noc, wall their hub-bound predicate (throwing their own `PARTNER_REF_*` codes) | `refPolicy`. |
|
|
1161
|
+
| 10 | Host normalised in the model | hub | `normaliseHost`; the others' routes already normalise (passing it too is harmless). |
|
|
1162
|
+
| 11 | Editable domain on update | desk | Same: only with the host key; the others never send `domain`. |
|
|
1163
|
+
| 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' }]`. |
|
|
1164
|
+
| 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`. |
|
|
1165
|
+
| 14 | Portal sessions, unused codes, trusted browsers ended on deactivate | hub | `onDeactivate`. |
|
|
1166
|
+
| 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). |
|
|
1167
|
+
| 16 | `all()` selects `hub_host` | noc | `extraColumns: [{ name: 'hub_host', list: true }]`. |
|
|
1168
|
+
| 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). |
|
|
1169
|
+
| 18 | RBAC refreshed after every provision | all but the desk (whose route did it) | Intended (plan row 23). |
|
|
1170
|
+
| 19 | The provisioning log line | all | Wording: `roles=true, templates=true, reports=3`. |
|
|
1171
|
+
| 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). |
|
|
1172
|
+
| 21 | The error carries `partnerId` (also `deactivated`, `cause`) | all but the desk | Intended (plan row 11). The desk's sentence becomes the starter's. |
|
|
1173
|
+
| 22 | After a switch the browser goes to | starter, noc `/`; hub, soc, wall, desk `/dashboard` | `landing`. |
|
|
1174
|
+
| 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. |
|
|
1175
|
+
| 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). |
|
|
1176
|
+
| 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. |
|
|
1177
|
+
| 26 | The banner's read-only wording and `actingReadOnly` | desk | `actingLocals({ readOnly: true, note: '<its sentence>' })`; the others `readOnly: false`. |
|
|
1178
|
+
| 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. |
|
|
1179
|
+
| 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). |
|
|
1180
|
+
| 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'`. |
|
|
1181
|
+
| 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. |
|
|
1182
|
+
| 31 | `create` with `is_active` undefined | soc, noc, wall default it to active | Same: omitted or `undefined` is active, a given falsy value inactive. |
|
|
1183
|
+
| 32 | The locked-reference error code | soc, noc, wall their own codes | Same: the predicate returns `{ code, message }` or throws its own error. |
|
|
1184
|
+
| 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). |
|
|
1185
|
+
| 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. |
|
|
1186
|
+
| 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` |
|
|
1187
|
+
| 36 | One change callback doing both refreshes | none today (new) | `onPartnersChanged` may be a list, each entry isolated; pass `[() => tenancy.refreshActivePartners(), () => hosts.forget()]` |
|
|
1188
|
+
| 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
1189
|
|
|
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.
|