@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.
@@ -0,0 +1,786 @@
1
+ /**
2
+ * WHO a piece of work is being done for — an app's half of db-worker's tenant contract, as one factory.
3
+ *
4
+ * THE PACKAGE CARRIES THE CONTEXT; THIS DECIDES WHAT IT SAYS. @aria-framework/db-worker moves a
5
+ * `{ scope, partnerId }` from the main thread into the worker and turns it into `set_config` on a
6
+ * pooled connection, which is what Postgres row-level security reads. It deliberately does not
7
+ * decide whose scope a request is in: that differs between a signed-in staff user, a portal
8
+ * contact, a mobile token, a service key and a cron job. This factory decides it, with the app's
9
+ * own lookups and the settings on which existing apps answer differently.
10
+ *
11
+ * WITHOUT THIS AN APP CANNOT TALK TO POSTGRES AT ALL. db-worker fails closed — an invoke with no
12
+ * context on a pooled driver throws rather than guessing — and on SQLite it is simply ignored. So
13
+ * the wiring is invisible in development and total in production, which is exactly the shape of
14
+ * failure tenancy exists to prevent, and is why it needs tests of its own rather than being
15
+ * trusted to review.
16
+ *
17
+ * THREE SHAPES OF SCOPE, and the middle one is the one to be careful about:
18
+ *
19
+ * asPartner(id, fn) a signed-in user, a portal contact, a mobile token — one tenant's rows.
20
+ * asPlatform(fn) work that legitimately spans tenants: a LOGIN (the person has not told us
21
+ * which partner they are yet), an API-key lookup, and maintenance that prunes
22
+ * every tenant's rows.
23
+ * asHouse(fn) platform scope PLUS the house partner id, so a row that must be written
24
+ * somewhere lands on the platform's own tenant. A DELETE at platform scope
25
+ * reaches every partner; an INSERT does not, because partner_id defaults to
26
+ * `current_setting('app.partner_id')` and that is unset. A failed login is
27
+ * the case: it must be audited and there is no partner to audit it against.
28
+ *
29
+ * THE SCOPE SEAM (asInstallation, acrossAll, run, forEachScope, atBoot, requestScope, forApiUser,
30
+ * asOwnerOf, asRefreshTokenOwner, forSession) is on the same object. It is how shared code says "who
31
+ * is this work for" without naming a partner; a single-tenant app carries its own seam with the same
32
+ * names and bodies that just run `fn`.
33
+ *
34
+ * THE RULE FOR THE SEAM: IT CALLS `t.x` AT CALL TIME. `t` is the object this factory returns, never a
35
+ * destructured binding, so a test (or an app) that replaces `tenancy.asHouse` is seen by the seam on
36
+ * its next call. A destructure would freeze the original function and a stub would pass through
37
+ * unnoticed.
38
+ *
39
+ * NOTHING IS CAPTURED AT REQUIRE TIME. `db` may be a getter; the house id is memoised per factory,
40
+ * not per module, so two factories in one process (a test bridge) never share one.
41
+ */
42
+
43
+ 'use strict';
44
+
45
+ const { runWithTenant, currentTenant } = require('@aria-framework/db-worker');
46
+
47
+ const DB_KINDS = new Set(['postgres', 'sqlite']);
48
+ const isFn = (f) => typeof f === 'function';
49
+
50
+ /**
51
+ * @param {object} o
52
+ * @param {object|(() => object)} o.db the app's main-thread db client (has `invoke(model, method, ...args)`), or a getter
53
+ * for it — a getter lets an app's lib/tenant.js call this before its db-client exists (a require cycle)
54
+ * @param {{warn: Function, error: Function}} o.logger
55
+ * @param {'postgres'|'sqlite'|(() => 'postgres'|'sqlite')} o.dbKind REQUIRED: which engine the app runs on, read at
56
+ * call time when a function (an app passes `() => config.dbKind`). canHostTenants() answers it.
57
+ * @param {boolean} o.platformRequiresHouse REQUIRED: honour `scope_kind = 'platform'` only for a member of the house,
58
+ * checked at use (true), or trust the stored scope (false)
59
+ * @param {string} [o.partnerModel='Partner'] the model whose `house`, `all` and `seedHouse` this calls
60
+ * @param {(session: object) => ({scope: string, partnerId: number}|null|undefined)} [o.contactScope] the context for a
61
+ * session with no staff user (a portal contact); asked only when there is no `session.user`
62
+ * @param {(partner: object) => any} [o.beforeEachPartner] awaited inside each partner's scope before forEachPartner's fn
63
+ * @param {(rawToken: string) => Promise<number|null>} [o.refreshTokenOwner] whose refresh token this is (without
64
+ * consuming it), for asRefreshTokenOwner
65
+ * @param {string} [o.unscopedRedirect='/login?reason=session_unscoped'] where requestScope sends an unscopable session
66
+ * @param {boolean} o.actingRequiresActive REQUIRED: honour an acting flag only into a partner known to be ACTIVE
67
+ * (true), or as today (false)
68
+ * @param {number} [o.activeMaxAgeMs] with actingRequiresActive: a set of active partners older than this is reloaded
69
+ * before it is trusted (for an app run as more than one process); a whole number, at least 1000; default none
70
+ * @param {number} [o.activeLoadTimeoutMs=5000] a load of the set with no answer by then counts as failed (closed); a
71
+ * whole number, at least 1000
72
+ * @param {{setTimeout: Function, clearTimeout: Function}} [o.timers] the timers that load timeout runs on (default
73
+ * the global ones; a test passes a fake clock's)
74
+ * @param {() => number} [o.now=Date.now] the clock activeMaxAgeMs is measured on
75
+ */
76
+ function createTenancy(o = {}) {
77
+ const {
78
+ db, logger, dbKind, platformRequiresHouse, partnerModel = 'Partner', contactScope, beforeEachPartner,
79
+ refreshTokenOwner, unscopedRedirect = '/login?reason=session_unscoped', actingRequiresActive, activeMaxAgeMs,
80
+ activeLoadTimeoutMs = 5000, now = Date.now,
81
+ timers = { setTimeout, clearTimeout }
82
+ } = o;
83
+ if (!db || (!isFn(db) && !isFn(db.invoke))) {
84
+ throw new Error('createTenancy: `db` is required — the app\'s db client (with invoke) or a function returning it');
85
+ }
86
+ if (!logger || !isFn(logger.warn) || !isFn(logger.error)) {
87
+ throw new Error('createTenancy: `logger` is required (with warn and error)');
88
+ }
89
+ if (dbKind == null || (!isFn(dbKind) && !DB_KINDS.has(dbKind))) {
90
+ throw new Error("createTenancy: `dbKind` is required — 'postgres', 'sqlite', or a function returning one "
91
+ + '(an app passes () => config.dbKind). It has no default: on SQLite a row\'s partner_id means nothing');
92
+ }
93
+ if (typeof platformRequiresHouse !== 'boolean') {
94
+ throw new Error('createTenancy: `platformRequiresHouse` is required (true or false). It has no default because '
95
+ + 'existing apps answer it differently; a new app passes true');
96
+ }
97
+ if (typeof actingRequiresActive !== 'boolean') {
98
+ throw new Error('createTenancy: `actingRequiresActive` is required (true or false). It has no default: false is every '
99
+ + "existing app's behaviour today; a new app passes true");
100
+ }
101
+ if (activeMaxAgeMs !== undefined && !(Number.isInteger(activeMaxAgeMs) && activeMaxAgeMs >= 1000)) {
102
+ throw new TypeError('createTenancy: activeMaxAgeMs must be a whole number of milliseconds, at least 1000 (or omitted: no age bound)');
103
+ }
104
+ // At least a second: below that a healthy but slow database answers after every load has already timed out and
105
+ // been replaced by a newer one, so no result is ever applied and acting never resumes while traffic continues.
106
+ if (!(Number.isInteger(activeLoadTimeoutMs) && activeLoadTimeoutMs >= 1000)) {
107
+ throw new TypeError('createTenancy: activeLoadTimeoutMs must be a whole number of milliseconds, at least 1000');
108
+ }
109
+ if (!timers || !isFn(timers.setTimeout) || !isFn(timers.clearTimeout)) {
110
+ throw new TypeError('createTenancy: timers must have setTimeout and clearTimeout when given');
111
+ }
112
+ if (!isFn(now)) throw new Error('createTenancy: `now` must be a function when given');
113
+ for (const [name, f] of [['contactScope', contactScope], ['beforeEachPartner', beforeEachPartner],
114
+ ['refreshTokenOwner', refreshTokenOwner]]) {
115
+ if (f !== undefined && !isFn(f)) throw new Error(`createTenancy: \`${name}\` must be a function when given`);
116
+ }
117
+ if (typeof partnerModel !== 'string' || !partnerModel) throw new Error('createTenancy: `partnerModel` must be a model name');
118
+ if (typeof unscopedRedirect !== 'string' || !unscopedRedirect.startsWith('/')) {
119
+ throw new Error('createTenancy: `unscopedRedirect` must be a path on this app');
120
+ }
121
+
122
+ const client = () => (isFn(db) ? db() : db);
123
+ const kind = () => {
124
+ const k = isFn(dbKind) ? dbKind() : dbKind;
125
+ if (!DB_KINDS.has(k)) throw new Error(`tenancy: dbKind answered ${JSON.stringify(k)}, not 'postgres' or 'sqlite'`);
126
+ return k;
127
+ };
128
+
129
+ /** One tenant. */
130
+ const asPartner = (partnerId, fn) => runWithTenant({ scope: 'partner', partnerId: Number(partnerId) }, fn);
131
+
132
+ /** Every tenant, reading. Writing a partner-scoped row from here needs an explicit partner_id. */
133
+ const asPlatform = (fn) => runWithTenant({ scope: 'platform', partnerId: null }, fn);
134
+
135
+ /**
136
+ * The house partner's id.
137
+ *
138
+ * MEMOISED, AND NOT HARD-CODED. The seed makes it 1 on most databases — but `is_house` is the thing
139
+ * that DEFINES it, and a restored or merged database is exactly the situation where the number and
140
+ * the flag stop agreeing. One query per process is not worth saving by writing the assumption down.
141
+ */
142
+ let house = null;
143
+ async function housePartnerId() {
144
+ if (house !== null) return house;
145
+ const row = await asPlatform(() => client().invoke(partnerModel, 'house'));
146
+ if (!row || !row.id) throw new Error(`tenant: no partner is marked is_house — ${partnerModel}.seedHouse() runs at boot`);
147
+ house = Number(row.id);
148
+ return house;
149
+ }
150
+
151
+ /** The house id if this factory has resolved it, else null — synchronous, for contextFor and an API guard. */
152
+ const knownHouseId = () => house;
153
+
154
+ /**
155
+ * IS THIS USER PLATFORM STAFF, AS A FACT THE APP WILL HONOUR?
156
+ *
157
+ * With `platformRequiresHouse` off: `scope_kind = 'platform'`, as the stored row says. Such an app relies on
158
+ * nobody writing 'platform' onto a non-house user (its own scope-kind guard and test).
159
+ *
160
+ * With it on: `scope_kind = 'platform'` AND a member of the HOUSE, checked here at use. A platform scope_kind on
161
+ * ANY OTHER partner's user — written by a path that did not check, a restore, a hand edit — would otherwise become
162
+ * `{ scope: 'platform', partnerId: P }`: the RLS platform arm (`true`, every tenant's rows) plus every platform-only
163
+ * permission. Such a user is NOT honoured as platform; it gets its own partner's scope (contextFor).
164
+ *
165
+ * FAIL CLOSED. An unresolved house id is "no": requestScope resolves it before asking, and an app's boot and API
166
+ * router resolve it too, so a house operator is never downgraded in practice — but a caller that skipped it gets
167
+ * the narrower answer, never the wider.
168
+ */
169
+ function isPlatformUser(user) {
170
+ if (!user || user.scope_kind !== 'platform') return false;
171
+ if (!platformRequiresHouse) return true;
172
+ if (house == null) return false;
173
+ return Number(user.partner_id) === house;
174
+ }
175
+
176
+ /** Users already logged as refused platform scope, so a session logs once rather than per request. */
177
+ const refusedPlatform = new Set();
178
+ function noteRefusedPlatform(user) {
179
+ const key = `${user.id}:${user.partner_id}`;
180
+ if (refusedPlatform.has(key)) return;
181
+ refusedPlatform.add(key);
182
+ logger.warn(`tenant: user ${user.id} has scope_kind 'platform' but belongs to partner ${user.partner_id}, `
183
+ + `not the house${house == null ? ' (the house id is not resolved yet)' : ''} — served at PARTNER scope, never platform`);
184
+ }
185
+
186
+ // -- WHICH PARTNERS ARE ACTIVE (actingRequiresActive) ---------------------------------------------
187
+ //
188
+ // DEACTIVATING A PARTNER ENDS ACTING INTO IT (the owner's decision of 29 Nov 2026). Before it, contextFor
189
+ // honoured an acting flag after re-checking only the operator's own scope kind, so an operator inside a
190
+ // partner when it was deactivated stayed inside until they switched out. contextFor is synchronous and on the
191
+ // main thread (in every source app) - it cannot read the database - so it reads a set of active partner ids
192
+ // kept here, the same way the house id is: never at require time, loaded through the db getter (atBoot loads
193
+ // it first; requestScope loads it when it is not known or too old), and reloaded by refreshActivePartners(),
194
+ // which the app calls after any partner is created, changed, activated or deactivated.
195
+ //
196
+ // CLOSED WHEN UNKNOWN. While the set is not known (never loaded, the last load failed, or older than
197
+ // activeMaxAgeMs) an acting flag is NOT honoured: the operator's own scope answers. Never the other way.
198
+ //
199
+ // ONE LOAD AT A TIME, AND THE NEWEST WINS. A refresh asked for while a load is in flight does not share that load
200
+ // (it read the table before the change the refresh is about): it schedules ONE more load after it and resolves
201
+ // with that load's answer. A request that merely needs the set shares the load in flight. A result is applied
202
+ // only if its load is the newest started, so an older load finishing late never overwrites a newer answer.
203
+ // A load with no answer within activeLoadTimeoutMs counts as failed: its waiters are answered (closed), the set
204
+ // becomes unknown, and its late result is still applied if it is still the newest.
205
+ let snapshot = null; // { active: Set<number>, inactive: Set<number>, at: number } | null (unknown)
206
+ let generation = 0; // loads started
207
+ let inflight = null; // { gen, done } — the one load not yet answered
208
+ let followUp = null; // { promise, resolve } — a load to start when the one in flight is answered
209
+ let outageLogged = false;
210
+ // STALE FROM THE MOMENT A REFRESH IS ASKED FOR. The app calls refreshActivePartners() right after a deactivation has
211
+ // committed; until a load that STARTED after that call has landed, the set held is the one from before the change, and
212
+ // an operator's request in that gap was honoured into the partner just deactivated (measured: the gated write landed).
213
+ // So the call marks the set stale at once, synchronously: a stale set is treated as unknown (closed, keys kept), and
214
+ // requestScope waits for the load that started after the mark. Only a load of generation >= freshFrom clears it.
215
+ let stale = false;
216
+ let freshFrom = 0;
217
+ // Ids met in NEITHER set that have already asked for one load. Cleared by the app's refresh and by an expiry, so
218
+ // a partner that does not exist (or exists only in another process) costs one load per change, not one per request.
219
+ const missingAsked = new Set();
220
+
221
+ /** The clock, checked: a clock that answers NaN would make "too old" never true, so it throws, before any decision. */
222
+ function clock() {
223
+ const v = now();
224
+ if (typeof v !== 'number' || !Number.isFinite(v)) {
225
+ throw new TypeError(`createTenancy: now() must return a finite number of milliseconds; it returned ${String(v)}`);
226
+ }
227
+ return v;
228
+ }
229
+
230
+ function noteFailure(e) {
231
+ if (outageLogged) return;
232
+ outageLogged = true;
233
+ logger.error(`tenant: the active partners could not be read (${e.message}) - no acting flag is honoured until they are`);
234
+ }
235
+
236
+ async function readSnapshot() {
237
+ const rows = await asPlatform(() => client().invoke(partnerModel, 'all'));
238
+ if (!Array.isArray(rows)) throw new Error(`${partnerModel}.all did not return a list`);
239
+ const activeIds = new Set();
240
+ const inactiveIds = new Set();
241
+ for (const r of rows) {
242
+ if (!r || r.id == null || !Object.prototype.hasOwnProperty.call(r, 'is_active')) {
243
+ throw new Error(`${partnerModel}.all returned a row without id and is_active`);
244
+ }
245
+ (Number(r.is_active) === 1 || r.is_active === true ? activeIds : inactiveIds).add(Number(r.id));
246
+ }
247
+ return { active: activeIds, inactive: inactiveIds };
248
+ }
249
+
250
+ /** Start a load now. Resolves when it is answered: true if its result was applied, false otherwise. */
251
+ function begin() {
252
+ const gen = ++generation;
253
+ let answer;
254
+ const done = new Promise((r) => { answer = r; });
255
+ const me = { gen, done };
256
+ inflight = me;
257
+ let answered = false;
258
+ const finish = (ok) => {
259
+ if (answered) return;
260
+ answered = true;
261
+ timers.clearTimeout(timer);
262
+ if (inflight === me) inflight = null;
263
+ answer(ok);
264
+ if (followUp && !inflight) {
265
+ const f = followUp;
266
+ followUp = null;
267
+ begin().then(f.resolve);
268
+ }
269
+ };
270
+ const timer = timers.setTimeout(() => {
271
+ noteFailure(new Error(`no answer within ${activeLoadTimeoutMs} ms`));
272
+ if (gen === generation) snapshot = null;
273
+ finish(false);
274
+ }, activeLoadTimeoutMs);
275
+ if (timer && timer.unref) timer.unref();
276
+ readSnapshot().then((snap) => {
277
+ const newest = gen === generation;
278
+ if (newest) {
279
+ snapshot = { ...snap, at: clock() };
280
+ outageLogged = false;
281
+ if (gen >= freshFrom) stale = false;
282
+ }
283
+ finish(newest);
284
+ }, (e) => {
285
+ if (gen === generation) {
286
+ snapshot = null;
287
+ noteFailure(e);
288
+ }
289
+ finish(false);
290
+ }).catch((e) => { noteFailure(e); finish(false); }); // a broken clock while applying
291
+ return done;
292
+ }
293
+
294
+ /** A load that STARTS after this call: now if none is in flight, else one more after the one in flight. */
295
+ function loadAfterNow() {
296
+ if (!inflight) return begin();
297
+ if (!followUp) {
298
+ let resolve;
299
+ const promise = new Promise((r) => { resolve = r; });
300
+ followUp = { promise, resolve };
301
+ }
302
+ return followUp.promise;
303
+ }
304
+
305
+ /**
306
+ * The set is needed: share the load in flight, or start one. While the set is STALE, only a load that started after
307
+ * the refresh that marked it will do: the one in flight if it is that recent, else the follow-up already queued, else
308
+ * a new one.
309
+ */
310
+ function ensureLoad() {
311
+ if (stale) {
312
+ if (inflight && inflight.gen >= freshFrom) return inflight.done;
313
+ if (followUp) return followUp.promise;
314
+ return begin();
315
+ }
316
+ return inflight ? inflight.done : begin();
317
+ }
318
+
319
+ /**
320
+ * Reload the set of active partners. Call after any partner is created, changed, activated or deactivated.
321
+ * The load it waits for STARTS after the call (one in flight is not shared: it may have read the table before
322
+ * the change). Resolves true when that load's result is applied; false when it failed or timed out, which
323
+ * leaves the set UNKNOWN (closed: no acting flag is honoured until a load succeeds), logged once per outage.
324
+ * Never rejects: a failed refresh after a save must not turn the save into an error, and its effect is already
325
+ * the safe one.
326
+ *
327
+ * @returns {Promise<boolean>}
328
+ */
329
+ function refreshActivePartners() {
330
+ // With the setting off nothing reads the set, so nothing is loaded for it.
331
+ if (!actingRequiresActive) return Promise.resolve(true);
332
+ missingAsked.clear();
333
+ // Stale NOW, before any load starts: the next load to begin (now, or after the one in flight) is the first fresh one.
334
+ stale = true;
335
+ freshFrom = generation + 1;
336
+ return loadAfterNow();
337
+ }
338
+
339
+ /**
340
+ * For a caller that is NOT a request (a live stream's periodic re-check before forSession): resolves true when the
341
+ * active set is known and not stale (at once if so), else waits for the pending load, bounded as requestScope's wait
342
+ * is (activeLoadTimeoutMs, twice that behind a load already in flight), and resolves whether the set is known then.
343
+ * Never rejects. With the setting off: true at once, nothing read.
344
+ *
345
+ * @returns {Promise<boolean>}
346
+ */
347
+ function whenActivePartnersKnown() {
348
+ if (!actingRequiresActive) return Promise.resolve(true);
349
+ if (snapshotIfKnown(clock())) return Promise.resolve(true);
350
+ return ensureLoad().then(() => !!snapshotIfKnown(clock()), () => false);
351
+ }
352
+
353
+ /** The loaded sets if they are known and fresh, else null; an expired set starts a reload (shared). */
354
+ function snapshotIfKnown(t) {
355
+ if (!snapshot || stale) return null;
356
+ if (activeMaxAgeMs !== undefined && t - snapshot.at > activeMaxAgeMs) return null;
357
+ return snapshot;
358
+ }
359
+
360
+ /** Users already logged as acting into a partner that is not active, so a session logs once. */
361
+ const loggedInactive = new Set();
362
+
363
+ /**
364
+ * May this platform user's acting flag be honoured? Always, with the setting off (today's behaviour). With it on:
365
+ * - an id in the loaded ACTIVE set: yes;
366
+ * - an id KNOWN INACTIVE: no, and the flag is CLEARED (the keys the stop route removes), so reactivating the
367
+ * partner later does not put the operator back inside without switching in again;
368
+ * - an id in NEITHER set (created after the last load, or in another process): no, the flag KEPT, and one
369
+ * load started after now, so the next request can be honoured;
370
+ * - the set unknown (not loaded, failed, timed out or too old): no, the flag KEPT — an outage must not switch
371
+ * everyone out for good — and a load started (shared with any in flight).
372
+ */
373
+ function actingHonoured(s, user) {
374
+ if (!actingRequiresActive) return true;
375
+ const t = clock();
376
+ const known = snapshotIfKnown(t);
377
+ if (!known) {
378
+ if (snapshot && !stale) missingAsked.clear(); // an expiry: the missing ids may ask again
379
+ ensureLoad(); // in the background; never awaited here, and it logs a failure
380
+ return false;
381
+ }
382
+ const id = Number(s.actingPartnerId);
383
+ if (known.active.has(id)) return true;
384
+ if (!known.inactive.has(id)) {
385
+ if (!missingAsked.has(id)) {
386
+ missingAsked.add(id);
387
+ loadAfterNow();
388
+ }
389
+ return false;
390
+ }
391
+ delete s.actingPartnerId;
392
+ delete s.actingPartnerName;
393
+ const key = `${user.id}:${id}`;
394
+ if (!loggedInactive.has(key)) {
395
+ loggedInactive.add(key);
396
+ logger.warn(`tenant: user ${user.id} was acting as partner ${id}, which is not active - switched out`);
397
+ }
398
+ return false;
399
+ }
400
+
401
+ /**
402
+ * Platform scope, but with the house partner available for rows that must land somewhere.
403
+ *
404
+ * THE SCOPE FOR ANONYMOUS WORK. A login, a password reset, a message arriving in a shared mailbox —
405
+ * none of them know a tenant yet, and several of them WRITE: a failed login is audited. Platform
406
+ * scope alone leaves those inserts with no partner_id to default to, so they are refused; the house
407
+ * partner is where a row that belongs to no tenant belongs.
408
+ *
409
+ * IT DOES NOT THROW WHEN THERE IS NO HOUSE PARTNER. A database from before the tenancy migration
410
+ * has no `partners` table at all, and on SQLite the context is ignored entirely — so failing here
411
+ * would turn every anonymous request into a 500 to enforce something that engine does not read. It
412
+ * falls back to a partnerless platform scope and says so once.
413
+ */
414
+ let houseWarned = false;
415
+ async function asHouse(fn) {
416
+ let id = null;
417
+ try {
418
+ id = await housePartnerId();
419
+ } catch (e) {
420
+ if (!houseWarned) {
421
+ houseWarned = true;
422
+ logger.warn(`tenant: no house partner (${e.message}) — anonymous work runs unplaced`);
423
+ }
424
+ }
425
+ return runWithTenant({ scope: 'platform', partnerId: id }, fn);
426
+ }
427
+
428
+ /**
429
+ * The scope a REQUEST is in, derived from whatever authenticated it.
430
+ *
431
+ * REFUSES TO BE VAGUE. A staff session whose row carries no partner_id cannot be scoped — that is
432
+ * a session made before the tenancy migration, and widening it to platform would hand one user
433
+ * every tenant's data. It returns null and the caller must reject the request, which is a sign-in
434
+ * again rather than a silent privilege grant.
435
+ */
436
+ function contextFor(req) {
437
+ const s = req && req.session;
438
+ const user = s && s.user;
439
+ if (user) {
440
+ if (user.partner_id == null) return null; // unscopable — refuse, never widen
441
+
442
+ // ── ACTING AS A PARTNER ──────────────────────────────────────────────────────────────────
443
+ //
444
+ // A platform operator can READ every tenant — the policy's platform arm is `true` — and cannot
445
+ // WRITE into one, because every scoped table defaults partner_id to
446
+ // `current_setting('app.partner_id')`, which for them is the HOUSE. So "add this partner's
447
+ // first record" had nowhere to go. This is the switch that fixes it, and it is deliberately
448
+ // EXPLICIT: an operator says which tenant they are working in, and everything they do lands
449
+ // there until they say otherwise.
450
+ //
451
+ // IT NARROWS, IT NEVER WIDENS. The scope becomes 'partner', so while acting the operator LOSES
452
+ // every platform-only permission — backup.restore, the partner list itself. That is not a side
453
+ // effect to work around: somebody working inside another business's workspace has no business
454
+ // restoring the installation's database, and the existing gate in @aria-framework/auth gives it
455
+ // for free.
456
+ //
457
+ // ONLY A PLATFORM USER CAN BE ACTING. The flag is set by a route that checks that, and this
458
+ // RE-CHECKS rather than trusting the session shape: a partner-scoped user with a stray
459
+ // `actingPartnerId` — a bug, a replayed session, a hand-edited store — would otherwise walk
460
+ // into another tenant. Checked at the point of USE, which is the only place it cannot be
461
+ // skipped. With `platformRequiresHouse`, "platform user" also means a member of the house
462
+ // (isPlatformUser): a non-house user carrying 'platform' can neither act nor get platform
463
+ // scope, and falls through to its own partner's scope, the most a non-house user can hold.
464
+ const platform = isPlatformUser(user);
465
+ if (!platform && user.scope_kind === 'platform') noteRefusedPlatform(user);
466
+ const acting = s.actingPartnerId;
467
+ // With `actingRequiresActive`, only into a partner known to be active (actingHonoured, above).
468
+ if (platform && acting != null && actingHonoured(s, user)) {
469
+ return { scope: 'partner', partnerId: Number(acting) };
470
+ }
471
+
472
+ return platform
473
+ // A platform user keeps platform REACH and still carries their partner, so anything they
474
+ // write lands somewhere rather than being refused for having no default.
475
+ ? { scope: 'platform', partnerId: Number(user.partner_id) }
476
+ : { scope: 'partner', partnerId: Number(user.partner_id) };
477
+ }
478
+ // A session with no staff user may still belong to somebody the app places: a portal contact is
479
+ // a customer of exactly one partner. The app's resolver answers; nothing here second-guesses it.
480
+ if (contactScope && s) {
481
+ const c = contactScope(s);
482
+ if (c) return c;
483
+ }
484
+ // Anonymous. Platform scope, and it CANNOT be narrowed by anything the request carries — a
485
+ // header or a query parameter naming a partner would be a tenant chosen by the caller.
486
+ return { scope: 'platform', partnerId: null };
487
+ }
488
+
489
+ /**
490
+ * The signed-in user's OWN records (their `users` row, their notifications) at their HOME partner.
491
+ *
492
+ * ── WHY ACTING NEEDS THIS ─────────────────────────────────────────────────────────────────────
493
+ *
494
+ * While a house operator acts as partner P the request runs at P's scope (contextFor, above), and
495
+ * the operator's own row and notifications belong to the HOUSE, so row-level security hides them:
496
+ * measured in two apps, the profile page was a 500 or came up empty, a timezone change updated the
497
+ * session but not the database, and the notification list and the bell found nothing. One app had
498
+ * worked round it with asPlatform — every tenant's rows — which answered correctly and was a widening.
499
+ *
500
+ * ── NARROW, AND KEYED ON THE SESSION, NEVER ON THE REQUEST ───────────────────────────────────
501
+ *
502
+ * The scope is `partner` at `users.partner_id`, never platform, so no other tenant's rows are
503
+ * visible through it; and `fn` is handed the signed-in user's id OUT OF THE SESSION, so a call site
504
+ * reads `asOwnPartner(req, (me) => db.invoke('User', 'findById', me))` and has no reason to name any
505
+ * other id. For a partner user this is the scope the request already had; for a house operator not
506
+ * acting it narrows platform to the house, where their own rows live. Everything else a request
507
+ * does keeps the acting scope: this is for the PERSON, not for the work they are doing inside P.
508
+ *
509
+ * @param {object} req a request with a signed-in staff session
510
+ * @param {(me: number) => any} fn given the signed-in user's id
511
+ */
512
+ function asOwnPartner(req, fn) {
513
+ const user = req && req.session && req.session.user;
514
+ if (!user || user.id == null || user.partner_id == null) {
515
+ // Refuse, never widen: requireAuth runs first, so reaching here is a wiring mistake.
516
+ throw new Error('tenant: asOwnPartner needs a signed-in user with a home partner');
517
+ }
518
+ return runWithTenant({ scope: 'partner', partnerId: Number(user.partner_id) }, () => fn(Number(user.id)));
519
+ }
520
+
521
+ /**
522
+ * Run `fn` once inside EVERY partner's scope, and sum what each returns.
523
+ *
524
+ * ── WHY A SCHEDULED JOB NEEDS THIS ────────────────────────────────────────────────────────────
525
+ *
526
+ * A scheduler wraps every job in asHouse(), which is right for the jobs that maintain PLATFORM
527
+ * tables. It is wrong for one that reads a per-tenant SETTING and then writes or deletes: platform
528
+ * scope reaches every tenant's rows, so such a job applies ONE tenant's configuration to ALL of
529
+ * them. Audit retention is exactly that shape — the house's "keep for 30 days" would delete a
530
+ * reseller's trail that the reseller had asked to keep forever. A JOB THAT NEEDS PER-TENANT SCOPE
531
+ * NARROWS INSIDE ITSELF, and this is the tool for it.
532
+ *
533
+ * IT CONTINUES PAST A FAILURE, and that is the whole reason it is a helper rather than a for-loop
534
+ * at each call site. One partner's broken configuration must not stop the other tenants being
535
+ * served — a single bad row silently disabling a job for everybody is the failure this shape
536
+ * exists to avoid — and a loop written three times is a loop that only sometimes remembers.
537
+ *
538
+ * THE PARTNER LIST IS READ AT PLATFORM SCOPE, because no single partner's scope can see it.
539
+ *
540
+ * `beforeEachPartner` (the app's hook, e.g. warming that partner's chrome so a background
541
+ * notification carries its brand) is awaited inside the partner's scope before `fn`. A hook that
542
+ * throws counts as that partner's failure; an app whose warm-up is cosmetic catches inside its hook.
543
+ *
544
+ * @param {(partner: {id: number}) => Promise<{succeeded?: number, failed?: number, lastError?: string}|void>} fn
545
+ * @param {{logger?: {error: Function}}} [opts] logs each partner's failure when given
546
+ * @returns {Promise<{succeeded: number, failed: number, lastError?: string}>} summed across partners
547
+ */
548
+ async function forEachPartner(fn, { logger: log } = {}) {
549
+ const partners = await asPlatform(() => client().invoke(partnerModel, 'all'));
550
+ let succeeded = 0;
551
+ let failed = 0;
552
+ let lastError;
553
+ for (const p of partners || []) {
554
+ try {
555
+ const r = await asPartner(p.id, async () => {
556
+ if (beforeEachPartner) await beforeEachPartner(p);
557
+ return fn(p);
558
+ });
559
+ succeeded += (r && r.succeeded) || 0;
560
+ failed += (r && r.failed) || 0;
561
+ if (r && r.lastError) lastError = r.lastError;
562
+ } catch (e) {
563
+ failed += 1;
564
+ // NAMED. "the job failed" across five tenants is not something anybody can act on.
565
+ lastError = `partner ${p.id}: ${e.message}`;
566
+ if (log) log.error(`tenant: work failed for partner ${p.id} — ${e.message}`);
567
+ }
568
+ }
569
+ return { succeeded, failed, lastError };
570
+ }
571
+
572
+ /**
573
+ * Can this installation hold more than one tenant at all?
574
+ *
575
+ * Only on Postgres. A tenancy migration's SQLite arm gives every `partner_id` column `DEFAULT 1` and
576
+ * creates no policies — the SQL helpers emit no tenant predicate there either — so a second partner
577
+ * on SQLite would have every row it ever wrote land in the HOUSE, silently, with nothing enforcing a
578
+ * boundary that does not exist. An app whose boot refuses SQLite passes `dbKind: 'postgres'` and this
579
+ * is always true; the predicate stays so callers keep one name for the question.
580
+ *
581
+ * WHY IT IS A NAMED PREDICATE. The partner model refuses to create a second partner on SQLite. What it
582
+ * cannot do is stop the REST of the app offering the feature: the nav door, the list and a New partner
583
+ * button gated on `partners.view` / `partners.manage` answer who you are and know nothing about the
584
+ * database. So an operator found the feature, filled the form in, and met the refusal at Save.
585
+ *
586
+ * THIS DOES NOT REPLACE THE MODEL'S CHECK. That one runs in the worker against the live connection,
587
+ * and it is the backstop: a gate that exists only at the route layer is one deletion away from
588
+ * putting this back.
589
+ *
590
+ * @returns {boolean}
591
+ */
592
+ function canHostTenants() {
593
+ return kind() === 'postgres';
594
+ }
595
+
596
+ // ── the scope seam ───────────────────────────────────────────────────────────────────────────
597
+ // Every body below reaches the functions above through `t`, at call time (the header's rule).
598
+
599
+ /**
600
+ * Work that belongs to the INSTALLATION rather than to any one customer: a scheduled job, a cached
601
+ * installation setting, anonymous work. Here that is the house scope — platform reach plus the
602
+ * house partner id, so a row it writes lands somewhere.
603
+ */
604
+ function asInstallation(fn) {
605
+ return t.asHouse(fn);
606
+ }
607
+
608
+ /** Work that legitimately spans everything: platform scope with no partner. Synchronous, like asPlatform. */
609
+ function acrossAll(fn) {
610
+ return t.asPlatform(fn);
611
+ }
612
+
613
+ /** Run `fn` inside an explicit context, for code that already holds a `{ scope, partnerId }`. */
614
+ function run(ctx, fn) {
615
+ return t.runWithTenant(ctx, fn);
616
+ }
617
+
618
+ /** Run `fn` once per scope and sum the outcomes, continuing past a failure (forEachPartner). */
619
+ function forEachScope(fn, opts) {
620
+ return t.forEachPartner(fn, opts);
621
+ }
622
+
623
+ /**
624
+ * Boot's scope: seed what the scope itself depends on, then run the rest of boot inside the
625
+ * installation scope.
626
+ *
627
+ * asPlatform for the seed (partners is a platform table, so it needs no partner_id), then asHouse
628
+ * for everything after it: cross-tenant reads AND writes that land on the platform's own partner,
629
+ * because every tenant-scoped table defaults partner_id to current_setting. Two statements, in that
630
+ * order, because asHouse resolves the house partner by QUERYING for it, so the seed has to exist
631
+ * first. The LISTENER must not run inside this: start it outside.
632
+ */
633
+ async function atBoot(fn) {
634
+ await t.asPlatform(() => client().invoke(partnerModel, 'seedHouse'));
635
+ // The first load of the active set: after the seed, so the house is in it. A failure leaves it unknown
636
+ // (closed, logged) and does not stop boot.
637
+ if (actingRequiresActive) await t.refreshActivePartners();
638
+ return t.asHouse(fn);
639
+ }
640
+
641
+ /**
642
+ * The per-request scope middleware.
643
+ *
644
+ * AFTER THE SESSION AND BEFORE THE FIRST ROUTER, and both halves of that matter. It reads
645
+ * req.session, so it cannot run earlier; every router mounted after it issues database work, so it
646
+ * cannot run later. Everything a route does then carries the scope, and on Postgres that scope IS
647
+ * the row-level-security predicate. On SQLite this is a no-op the driver ignores, which is precisely
648
+ * why it needs a test rather than a reviewer.
649
+ *
650
+ * A SESSION THAT CANNOT BE SCOPED IS REFUSED, not widened: the session is destroyed and the browser
651
+ * sent to sign in again (`unscopedRedirect`), never granted every tenant's data by default.
652
+ *
653
+ * WITH `platformRequiresHouse`, the house id is resolved FIRST for a user who claims platform and the
654
+ * id is not known yet, so the house's own operators are not narrowed by a cold cache. A failure to
655
+ * resolve it leaves the narrow answer (fail closed), never the wide one.
656
+ */
657
+ function requestScope(opts) {
658
+ const scoped = (req, res, next) => {
659
+ const u = req.session && req.session.user;
660
+ const pending = [];
661
+ if (platformRequiresHouse && u && u.scope_kind === 'platform' && t.knownHouseId() == null) {
662
+ pending.push(t.housePartnerId().catch(() => null));
663
+ }
664
+ // An acting flag with the active set unknown or too old: load it first, so the answer is not the closed
665
+ // one merely because nobody had asked yet. A failed load leaves it closed.
666
+ if (actingRequiresActive && u && req.session.actingPartnerId != null && !snapshotIfKnown(clock())) {
667
+ if (snapshot && !stale) missingAsked.clear(); // an expiry
668
+ pending.push(ensureLoad());
669
+ }
670
+ if (pending.length) return Promise.all(pending).then(() => establish(req, res, next)).catch(next);
671
+ return establish(req, res, next);
672
+ };
673
+ if (opts === undefined) return scoped;
674
+ // OPTIONAL, ADDITIVE: `{ actingIdle }` (what createActingIdle returned) ends working in a partner after the app's
675
+ // idle period. Its `before` runs BEFORE the scope is fixed (the request that finds the period over must not run
676
+ // in the partner), its `after` inside the scope just established. Without it, this is exactly the middleware above.
677
+ const idle = opts && typeof opts === 'object' ? opts.actingIdle : null;
678
+ if (!idle || !isFn(idle.before) || !isFn(idle.after)) {
679
+ throw new Error('requestScope: the only option is { actingIdle } (what createActingIdle returned)');
680
+ }
681
+ return (req, res, next) => idle.before(req, res, (e) => (e ? next(e)
682
+ : scoped(req, res, (e2) => (e2 ? next(e2) : idle.after(req, res, next)))));
683
+ }
684
+
685
+ function establish(req, res, next) {
686
+ const ctx = t.contextFor(req);
687
+ if (!ctx) {
688
+ return req.session.destroy(() => res.redirect(unscopedRedirect));
689
+ }
690
+ // ── AN ANONYMOUS REQUEST GOES THROUGH asHouse, NOT A NULL PARTNER ──────────────────────────
691
+ //
692
+ // contextFor returns `{scope:'platform', partnerId:null}` for a request with no session, which
693
+ // reads as correct — a login does not know its tenant yet — and is fatal for anything that
694
+ // WRITES. db-worker binds a null partnerId as '', the tenancy migration defaults partner_id to
695
+ // NULLIF(current_setting('app.partner_id', true),'')::int, and `audit_log.partner_id` is NOT
696
+ // NULL. So on Postgres every audit row written before a session exists — a login, a failed
697
+ // login, a throttle — raised a not-null violation, and every one of those call sites swallowed
698
+ // it. MEASURED: after several successful logins, the audit log held 0 rows. asHouse is async
699
+ // (it resolves the house partner once, then memoises), which is why this branch is separate
700
+ // rather than folded into contextFor's synchronous return.
701
+ if (ctx.partnerId == null) {
702
+ return t.asHouse(() => new Promise((resolve) => { next(); resolve(); }))
703
+ .catch(next);
704
+ }
705
+ t.runWithTenant(ctx, () => next());
706
+ }
707
+
708
+ /**
709
+ * Place an authenticated API principal: the scope its requests run in, or null if it has none.
710
+ *
711
+ * A NUMBER, OR A STRING OF DIGITS — nothing else. Number(x) coerced: `true` became partner 1, THE
712
+ * HOUSE; '1e3' partner 1000; '0x3', [3] and ' 3 ' passed. A digit string IS legitimate:
713
+ * users.partner_id is BIGINT and node-postgres returns int8 as a string unless a type parser is
714
+ * installed. Returns `{ scope, partnerId }` for `run()`, or null for a principal that cannot be
715
+ * placed — the caller refuses it rather than widening it.
716
+ *
717
+ * Platform scope follows isPlatformUser, so with `platformRequiresHouse` a non-house principal
718
+ * carrying 'platform' is placed at its own partner, as a session is.
719
+ */
720
+ function forApiUser(user) {
721
+ const raw = user ? user.partner_id : undefined;
722
+ const pid = typeof raw === 'number' ? raw
723
+ : (typeof raw === 'string' && /^\d+$/.test(raw) ? Number(raw) : NaN);
724
+ if (!Number.isInteger(pid) || pid <= 0) return null;
725
+ // `pid`, not a second Number(user.partner_id): the value that was VALIDATED is the one used.
726
+ return { scope: t.isPlatformUser(user) ? 'platform' : 'partner', partnerId: pid };
727
+ }
728
+
729
+ /**
730
+ * Run `fn` in the scope of the user it is for — where the user is known but the request is not yet
731
+ * narrowed (an API login issues the token pair inside the user's own scope). Takes no session, so
732
+ * it is not asOwnPartner; it trusts the user row it is given.
733
+ */
734
+ function asOwnerOf(user, fn) {
735
+ return t.asPartner(Number(user.partner_id), fn);
736
+ }
737
+
738
+ /**
739
+ * Rotate a refresh token INSIDE THE SCOPE OF WHOEVER OWNS IT.
740
+ *
741
+ * A login handler can narrow itself because it resolves the user first. Rotation cannot: the API
742
+ * package consumes and re-issues in one transaction and only then reports whose token it was. So the
743
+ * owner is read from the presented token first (the app's `refreshTokenOwner`, which does not
744
+ * consume it) and `fn` runs inside that partner's scope. A token that resolves to nothing is run
745
+ * where it stands: the package rejects it and the caller gets its 401, which is the right answer for
746
+ * an unknown token and the only one that does not leak whether it existed.
747
+ */
748
+ async function asRefreshTokenOwner(rawToken, fn) {
749
+ if (!refreshTokenOwner) {
750
+ throw new Error('tenancy: asRefreshTokenOwner needs the `refreshTokenOwner` lookup passed to createTenancy');
751
+ }
752
+ const partnerId = await refreshTokenOwner(rawToken);
753
+ return partnerId == null ? fn() : t.asPartner(partnerId, fn);
754
+ }
755
+
756
+ /**
757
+ * The scope a SESSION's requests run in, or null when the session has no signed-in user or cannot be
758
+ * placed. Read from a session object alone, with no request: a live stream asks it of a session it
759
+ * has just re-read from the store, long after the request that opened the stream ended, and compares
760
+ * the answer with the one it got when the stream was opened. So a platform user who has started
761
+ * working inside a partner since then gets a different answer, and the stream stops. Callers treat
762
+ * the value as opaque; two answers for the same scope serialise the same.
763
+ */
764
+ function forSession(session) {
765
+ if (!session || !session.user || session.user.id == null) return null;
766
+ return t.contextFor({ session });
767
+ }
768
+
769
+ const t = {
770
+ asPartner, asPlatform, asHouse, housePartnerId, contextFor, forEachPartner, canHostTenants, asOwnPartner,
771
+ // Re-exported so a caller needs one object rather than two.
772
+ runWithTenant, currentTenant,
773
+ // The house rule's two halves, for an app's other doors (an API guard, a role editor) to ask the same question.
774
+ isPlatformUser, knownHouseId,
775
+ // Call after any partner is created, changed, activated or deactivated (actingRequiresActive).
776
+ refreshActivePartners,
777
+ // For a caller that is not a request (a live stream's re-check): wait until the active set is known.
778
+ whenActivePartnersKnown,
779
+ // The seam.
780
+ asInstallation, acrossAll, run, forEachScope, atBoot, requestScope, forApiUser, asOwnerOf, asRefreshTokenOwner,
781
+ forSession
782
+ };
783
+ return t;
784
+ }
785
+
786
+ module.exports = { createTenancy };