@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
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MAY THIS REQUEST WRITE THAT ROW — the write gate, authorship, and the cross-tenant refusal, as one factory.
|
|
3
|
+
*
|
|
4
|
+
* ── THE RULE (the owner's, 23 Oct 2026; every app's refusal wording carries it) ───────────────────
|
|
5
|
+
*
|
|
6
|
+
* The house writes into a partner ONLY WHILE ACTING AS IT. A house user who has not switched to partner P
|
|
7
|
+
* may VIEW P's rows at platform scope — the support case the policy's platform arm exists for — but may
|
|
8
|
+
* not CHANGE them: a row written there defaults its partner_id to the session's, the house, and creating
|
|
9
|
+
* anything for a partner requires acting. The house's OWN rows are written without switching. Whether an
|
|
10
|
+
* operator who IS acting may write at all is the app's setting (`whileActing`): a staff app writes
|
|
11
|
+
* (`'write'`), the desk app is read-only while acting (`'readOnly'`).
|
|
12
|
+
*
|
|
13
|
+
* ── ONE GATE FOR CREATES, EDITS AND DELETES ──────────────────────────────────────────────────────
|
|
14
|
+
*
|
|
15
|
+
* Most writes into another partner are refused by a composite tenant key without help. A write that only
|
|
16
|
+
* UPDATEs or DELETEs an EXISTING row and records no actor writes no key, and the policy's platform arm
|
|
17
|
+
* checks `true`, so NOTHING refuses it: a time entry's edit, an attachment's delete, a customer's
|
|
18
|
+
* deactivation, at platform scope, reached another partner's row with nothing in the way (found in the
|
|
19
|
+
* desk app). So edits and deletes ask this gate exactly as creates do.
|
|
20
|
+
*
|
|
21
|
+
* ── THE RUNNER, NOT A BOOLEAN ────────────────────────────────────────────────────────────────────
|
|
22
|
+
*
|
|
23
|
+
* writeScope hands back the function to write IN, or null. A route that gates in one scope and writes in
|
|
24
|
+
* another cannot be written with it: at platform scope the runner narrows to the row's own partner
|
|
25
|
+
* (asPartner), so row-level security stays the boundary for the write itself.
|
|
26
|
+
*
|
|
27
|
+
* ── TWO ENGINES ──────────────────────────────────────────────────────────────────────────────────
|
|
28
|
+
*
|
|
29
|
+
* On Postgres, at PARTNER scope, the row's partner is compared with the scope's: a read and a write that
|
|
30
|
+
* see different rows cannot both pass. On SQLite it is NOT compared, on purpose: every row carries the
|
|
31
|
+
* literal `DEFAULT 1` whichever tenant wrote it, so the comparison would compare against a constant (an
|
|
32
|
+
* app that still tests on SQLite measured exactly that failure), and SQLite holds only the house anyway.
|
|
33
|
+
* The engine is read from tenancy.canHostTenants(), the one place that answers it.
|
|
34
|
+
*
|
|
35
|
+
* NOT A PERMISSION, AND NOT A SUBSTITUTE FOR ONE. `customers.edit` answers whether this person may write;
|
|
36
|
+
* this answers whether this REQUEST'S SCOPE may write this ROW. A route needs both, and neither implies
|
|
37
|
+
* the other.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
'use strict';
|
|
41
|
+
|
|
42
|
+
const isFn = (f) => typeof f === 'function';
|
|
43
|
+
const WHILE_ACTING = new Set(['write', 'readOnly']);
|
|
44
|
+
// A composite tenant key, as the framework's generator names it: fk_<table>_<column>_partner. The single-column
|
|
45
|
+
// key from partner_id to partners is fk_<table>_partner_id, which does not end so, and is not a tenant-line refusal.
|
|
46
|
+
const COMPOSITE_TENANT_KEY = /_partner$/;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* @param {object} o
|
|
50
|
+
* @param {object} o.tenancy what createTenancy returned (contextFor, currentTenant, runWithTenant, asPartner,
|
|
51
|
+
* housePartnerId, canHostTenants are used)
|
|
52
|
+
* @param {'write'|'readOnly'} o.whileActing REQUIRED: may an operator acting as a partner write there
|
|
53
|
+
* @param {string|null} o.houseReading REQUIRED, null for none: the permission whose ABSENCE at platform scope makes a
|
|
54
|
+
* request the "house reading" (it reads only the house's own rows)
|
|
55
|
+
* @param {object} o.messages the app's sentences (README, "The write gate's messages")
|
|
56
|
+
* @param {(id: number) => Promise<{id: number, name: string}|null>} o.partnerById a partner by id, read in the
|
|
57
|
+
* request's scope (the refusal names it; a creating form names its destination)
|
|
58
|
+
* @param {{warn: Function}} o.logger
|
|
59
|
+
* @param {(req: object) => boolean} [o.wantsJson] is this a fetch that wants JSON (default: X-Requested-With: fetch)
|
|
60
|
+
* @param {string} [o.refusalView='errors/generic'] the view crossTenantWriteHandler renders with {title, message}
|
|
61
|
+
* @param {object} [o.fleetView] OPTIONAL, ADDITIVE: what createFleetView returned. Absent: exactly 0.1.0. Present: the
|
|
62
|
+
* house reading becomes "the house's rows unless the `houseReading` permission is held AND fleet view is on"
|
|
63
|
+
* (houseReadingOf), and while the mode is on no write is allowed at all (writeScope null, createsLand false,
|
|
64
|
+
* refusal reason 'fleetView' with messages.fleetView, required then). Needs `houseReading` set.
|
|
65
|
+
*/
|
|
66
|
+
function createWriteGate(o = {}) {
|
|
67
|
+
const { tenancy, whileActing, messages, partnerById, logger, refusalView = 'errors/generic' } = o;
|
|
68
|
+
const wantsJson = o.wantsJson || ((req) => !!req && isFn(req.get) && req.get('X-Requested-With') === 'fetch');
|
|
69
|
+
if (!tenancy || !['contextFor', 'currentTenant', 'runWithTenant', 'asPartner', 'housePartnerId', 'canHostTenants'].every((k) => isFn(tenancy[k]))) {
|
|
70
|
+
throw new Error('createWriteGate: `tenancy` is required — what createTenancy returned');
|
|
71
|
+
}
|
|
72
|
+
if (!WHILE_ACTING.has(whileActing)) {
|
|
73
|
+
throw new Error("createWriteGate: `whileActing` is required — 'write' or 'readOnly'. It has no default because "
|
|
74
|
+
+ "existing apps answer it differently; a new staff app passes 'write'");
|
|
75
|
+
}
|
|
76
|
+
if (!Object.prototype.hasOwnProperty.call(o, 'houseReading')
|
|
77
|
+
|| !(o.houseReading === null || (typeof o.houseReading === 'string' && o.houseReading))) {
|
|
78
|
+
throw new Error('createWriteGate: `houseReading` is required — a permission name, or null for none (a new app passes null)');
|
|
79
|
+
}
|
|
80
|
+
const houseReading = o.houseReading;
|
|
81
|
+
const fleetView = o.fleetView == null ? null : o.fleetView;
|
|
82
|
+
if (fleetView !== null) {
|
|
83
|
+
if (!['isOn', 'writesRefused'].every((k) => isFn(fleetView[k]))) {
|
|
84
|
+
throw new Error('createWriteGate: `fleetView` must be what createFleetView returned (isOn, writesRefused)');
|
|
85
|
+
}
|
|
86
|
+
if (!houseReading) {
|
|
87
|
+
throw new Error('createWriteGate: `fleetView` needs `houseReading` (the permission fleet view widens the house reading for); with null there is no house reading to widen');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
// While fleet view is on, nothing is written (the mode is read-only). Judged from the session (the fleet view's
|
|
91
|
+
// middleware has cleared a mode that is not on), so this is synchronous; a request it never saw that carries the
|
|
92
|
+
// mode is refused too: closed, not open.
|
|
93
|
+
const inFleetView = (req) => fleetView !== null && !!req && fleetView.writesRefused(req) === true;
|
|
94
|
+
if (!messages || typeof messages !== 'object') throw new Error('createWriteGate: `messages` is required');
|
|
95
|
+
const needed = ['unscopable', 'notActing', 'elsewhere'].concat(whileActing === 'readOnly' ? ['actingReadOnly'] : [],
|
|
96
|
+
o.fleetView != null ? ['fleetView'] : []);
|
|
97
|
+
for (const k of needed) {
|
|
98
|
+
if (!(typeof messages[k] === 'string' || isFn(messages[k]))) {
|
|
99
|
+
throw new Error(`createWriteGate: messages.${k} is required (a sentence, or a function returning one)`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (!isFn(partnerById)) throw new Error('createWriteGate: `partnerById` is required');
|
|
103
|
+
if (!logger || !isFn(logger.warn)) throw new Error('createWriteGate: `logger` is required (with warn)');
|
|
104
|
+
if (!isFn(wantsJson)) throw new Error('createWriteGate: `wantsJson` must be a function when given');
|
|
105
|
+
|
|
106
|
+
const say = (key, info) => (isFn(messages[key]) ? messages[key](info) : messages[key]);
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* IS THIS REQUEST RUNNING IN ANOTHER PARTNER THAN THE SIGNED-IN USER'S OWN? Decided by the scope ACTUALLY
|
|
110
|
+
* MOVING (contextFor), never by the raw session flag: contextFor honours `actingPartnerId` only for a
|
|
111
|
+
* platform user, so a partner user's session carrying a stray flag (a bug, a replayed session, a
|
|
112
|
+
* hand-edited store) still runs in its own partner. Platform scope is the user's own partner: false.
|
|
113
|
+
*/
|
|
114
|
+
function actingElsewhere(req) {
|
|
115
|
+
const user = req && req.session && req.session.user;
|
|
116
|
+
if (!user || user.partner_id == null) return false;
|
|
117
|
+
const ctx = tenancy.contextFor(req);
|
|
118
|
+
return !!ctx && ctx.scope === 'partner' && ctx.partnerId != null && Number(ctx.partnerId) !== Number(user.partner_id);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Does this request have a tenant for a new row to land in AT ALL?
|
|
123
|
+
*
|
|
124
|
+
* A partner-scoped user has their own; an acting operator has the tenant they are acting as; a platform
|
|
125
|
+
* operator who is NOT acting has their own partner (the house, for an ordinary house admin — by
|
|
126
|
+
* convention, or checked at use with `platformRequiresHouse`). All three carry a `partnerId`, and a
|
|
127
|
+
* platform-scope create lands correctly in the account's own tenant, so it is not refused. Only two
|
|
128
|
+
* shapes carry none, and both are refused: contextFor's null (unscopable, refuse, never widen) and the
|
|
129
|
+
* anonymous context. With `whileActing: 'readOnly'`, an operator acting as a partner has nowhere to
|
|
130
|
+
* create either: a create while acting would default partner_id to that partner and record no actor.
|
|
131
|
+
*
|
|
132
|
+
* "Creating FOR A PARTNER requires acting" stays exactly true: the scope narrows to a partner only when
|
|
133
|
+
* the operator acts. The risk left — an operator who MEANT to act and forgot, creating a house row with
|
|
134
|
+
* the right name and the wrong owner — is closed by the form naming its destination (platformDestination).
|
|
135
|
+
*/
|
|
136
|
+
function createsLand(req) {
|
|
137
|
+
const ctx = tenancy.contextFor(req);
|
|
138
|
+
if (!ctx || ctx.partnerId == null) return false;
|
|
139
|
+
if (inFleetView(req)) return false;
|
|
140
|
+
return !(whileActing === 'readOnly' && actingElsewhere(req));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* THE CONTEXT THE GATE JUDGES — one rule for writeScope and readScope:
|
|
145
|
+
* - a request: contextFor(req), the one place that decides a request's scope (the hub's form). The scope
|
|
146
|
+
* that happens to surround the call does not enter into it;
|
|
147
|
+
* - null: a caller with no request (a job): the CURRENT scope (the noc and soc apps' form);
|
|
148
|
+
* - anything else, undefined included, throws: a forgotten argument must not silently pick a rule.
|
|
149
|
+
*/
|
|
150
|
+
function judged(req, fnName) {
|
|
151
|
+
if (req === null) return tenancy.currentTenant();
|
|
152
|
+
if (req === undefined || typeof req !== 'object') {
|
|
153
|
+
throw new Error(`${fnName}: pass the request, or null for work with no request (a job) — got ${req === undefined ? 'undefined' : typeof req}`);
|
|
154
|
+
}
|
|
155
|
+
return tenancy.contextFor(req);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* THE RUNNER RUNS IN THE CONTEXT IT JUDGED, never in whatever surrounds the call. A runner returning `fn()`
|
|
160
|
+
* would run at platform scope inside acrossAll, at the house inside asHouse or asOwnPartner, at another partner
|
|
161
|
+
* inside asPartner(other): gated in one scope, written in another — measured, with an UPDATE that reached
|
|
162
|
+
* another partner's row. So every non-null answer re-establishes its context with runWithTenant (the
|
|
163
|
+
* package's own context, the one db-worker carries into the worker), at partner scope as well as platform.
|
|
164
|
+
*/
|
|
165
|
+
const runnerAt = (ctx) => {
|
|
166
|
+
const fixed = { scope: ctx.scope, partnerId: ctx.partnerId };
|
|
167
|
+
return (fn) => tenancy.runWithTenant(fixed, fn);
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Where this request may WRITE a row that already belongs to partner `rowPartnerId` (edit it, delete it,
|
|
172
|
+
* or hang a new child row off it): a function running its argument in the scope to write in, or null.
|
|
173
|
+
*
|
|
174
|
+
* - no tenant to write into (createsLand's null cases) → null
|
|
175
|
+
* - acting as a partner with `whileActing: 'readOnly'` → null
|
|
176
|
+
* - PARTNER scope (a partner's staff, or an operator acting) → that partner's own rows only, run at
|
|
177
|
+
* that partner's scope. On SQLite not compared (the header's TWO ENGINES).
|
|
178
|
+
* - PLATFORM scope, not acting → the request's OWN partner's rows only
|
|
179
|
+
* (for house staff, the house's), run at that partner's scope; another partner's row is null: the house
|
|
180
|
+
* writes into a partner only while acting as it.
|
|
181
|
+
* Every runner runs at `{ partner, <the judged partner> }`, whatever scope it is later called inside.
|
|
182
|
+
*
|
|
183
|
+
* @param {object|null} req the request, or null for a job (the judged context is then the current scope)
|
|
184
|
+
* @param {number|string} rowPartnerId the row's own partner_id (BIGINT may arrive as a string)
|
|
185
|
+
* @returns {((fn: Function) => any)|null}
|
|
186
|
+
*/
|
|
187
|
+
function writeScope(req, rowPartnerId) {
|
|
188
|
+
const ctx = judged(req, 'writeScope');
|
|
189
|
+
if (!ctx || ctx.partnerId == null) return null;
|
|
190
|
+
if (req && whileActing === 'readOnly' && actingElsewhere(req)) return null;
|
|
191
|
+
if (inFleetView(req)) return null;
|
|
192
|
+
if (ctx.scope === 'partner') {
|
|
193
|
+
// SQLite: every row says partner 1 whoever wrote it — the hub's reason, kept: compare nothing there.
|
|
194
|
+
if (!tenancy.canHostTenants()) return runnerAt(ctx);
|
|
195
|
+
return Number(ctx.partnerId) === Number(rowPartnerId) ? runnerAt(ctx) : null;
|
|
196
|
+
}
|
|
197
|
+
if (ctx.scope === 'platform' && rowPartnerId != null && Number(ctx.partnerId) === Number(rowPartnerId)) {
|
|
198
|
+
// Narrowed to the row's (= the judged) partner, so row-level security bounds the write itself.
|
|
199
|
+
return runnerAt({ scope: 'partner', partnerId: Number(rowPartnerId) });
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Where this request may READ a row of partner `rowPartnerId`: a function running its argument at that
|
|
206
|
+
* partner's scope, or null (the caller answers 404). A partner viewer — or a platform viewer ACTING as a
|
|
207
|
+
* partner, whose scope is then that partner's — reads only its own partner's rows; a platform viewer who
|
|
208
|
+
* is not acting reads any partner's row, at that row's OWN partner's scope (partner_id from the row RLS
|
|
209
|
+
* just admitted). The judged context follows writeScope's rule (a request, or null for a job), and every
|
|
210
|
+
* runner runs at `{ partner, <that partner> }` wherever it is called.
|
|
211
|
+
*
|
|
212
|
+
* THE HOUSE READING (`houseReading` set): house staff at platform scope WITHOUT that permission read only
|
|
213
|
+
* the house's own rows. `{ house }` is then required — the house id from houseReadingOf(req, can), or
|
|
214
|
+
* exactly null for any other reading. Anything else (undefined from a mistyped local, 0, a string) throws:
|
|
215
|
+
* a call site that got it wrong fails loudly instead of reading the fleet.
|
|
216
|
+
*
|
|
217
|
+
* @param {object|null} req
|
|
218
|
+
* @param {number|string} rowPartnerId
|
|
219
|
+
* @param {{house?: number|null}} [opts]
|
|
220
|
+
* @returns {((fn: Function) => any)|null}
|
|
221
|
+
*/
|
|
222
|
+
function readScope(req, rowPartnerId, opts) {
|
|
223
|
+
let house = null;
|
|
224
|
+
if (houseReading) {
|
|
225
|
+
if (!opts || !Object.prototype.hasOwnProperty.call(opts, 'house')) {
|
|
226
|
+
throw new Error('readScope: this app has the house reading — pass { house } from houseReadingOf(req, can)');
|
|
227
|
+
}
|
|
228
|
+
house = opts.house;
|
|
229
|
+
if (!(house === null || (Number.isInteger(house) && house > 0))) {
|
|
230
|
+
throw new Error(`readScope: { house } must be null or the house id from houseReadingOf(req, can), not ${String(house)}`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
const ctx = judged(req, 'readScope');
|
|
234
|
+
if (ctx && ctx.scope === 'partner') return Number(ctx.partnerId) === Number(rowPartnerId) ? runnerAt(ctx) : null;
|
|
235
|
+
if (ctx && ctx.scope === 'platform') {
|
|
236
|
+
if (house !== null && Number(rowPartnerId) !== house) return null; // the house reading: the house's own only
|
|
237
|
+
return runnerAt({ scope: 'partner', partnerId: Number(rowPartnerId) });
|
|
238
|
+
}
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* WHICH READING: the house id when this request is the HOUSE reading (platform scope without the
|
|
244
|
+
* `houseReading` permission), else null. Always null when the app has no house reading. Call it BEFORE any
|
|
245
|
+
* asPartner narrowing: inside one, a platform-only permission reads false and every request would look
|
|
246
|
+
* like the house reading. A request with no scope is refused, never widened.
|
|
247
|
+
*
|
|
248
|
+
* WITH `fleetView`: the permission alone no longer widens. Platform scope reads every partner only when the
|
|
249
|
+
* permission is held AND `fleetView.isOn(req)` answers true; otherwise the house's own rows.
|
|
250
|
+
*
|
|
251
|
+
* @param {object} req
|
|
252
|
+
* @param {(permission: string) => boolean} can the request's permission check (res.locals.can)
|
|
253
|
+
* @returns {Promise<number|null>}
|
|
254
|
+
*/
|
|
255
|
+
async function houseReadingOf(req, can) {
|
|
256
|
+
if (!houseReading) return null;
|
|
257
|
+
const ctx = tenancy.contextFor(req);
|
|
258
|
+
if (!ctx || (ctx.scope !== 'platform' && ctx.scope !== 'partner')) throw new Error('houseReadingOf: the request has no scope');
|
|
259
|
+
if (ctx.scope === 'partner') return null;
|
|
260
|
+
if (isFn(can) && can(houseReading) === true && (fleetView === null || (await fleetView.isOn(req)) === true)) return null;
|
|
261
|
+
return tenancy.housePartnerId();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* The partner a create at PLATFORM scope would land on — the session user's own partner, the house for an
|
|
266
|
+
* ordinary house admin — or null when this request is not in that shape. A creating form shows it, so an
|
|
267
|
+
* operator who meant to act and forgot sees where Save will file the row. Read from the SESSION's own
|
|
268
|
+
* context, never from anything the request carries.
|
|
269
|
+
*
|
|
270
|
+
* NULL WHILE ACTING, ON PURPOSE: the acting banner already says "You are working inside <partner>" on every
|
|
271
|
+
* page, and a second sentence would duplicate it. Null for a partner-scoped user too.
|
|
272
|
+
*
|
|
273
|
+
* @returns {Promise<{id: number, name: string}|null>}
|
|
274
|
+
*/
|
|
275
|
+
async function platformDestination(req) {
|
|
276
|
+
const ctx = tenancy.contextFor(req);
|
|
277
|
+
if (!ctx || ctx.scope !== 'platform' || ctx.partnerId == null) return null;
|
|
278
|
+
return partnerById(ctx.partnerId);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* What a route says when the gate says no, or null when it says yes:
|
|
283
|
+
* `{ reason, partner, message }`, `reason` one of 'unscopable', 'acting', 'notActing', 'elsewhere'.
|
|
284
|
+
*
|
|
285
|
+
* `rowPartnerId` null (a create, or no such row): the create check — the unscopable sentence, or while
|
|
286
|
+
* acting read-only the acting one; otherwise null, and for an edit the caller's own lookup says "not
|
|
287
|
+
* found". `what` is the caller's noun for the log and the app's sentence ("site visit 9", "tickets").
|
|
288
|
+
* Every refusal is logged with who, the method and path, and whose row.
|
|
289
|
+
*
|
|
290
|
+
* @param {object} req
|
|
291
|
+
* @param {number|string|null} rowPartnerId
|
|
292
|
+
* @param {string} [what]
|
|
293
|
+
* @returns {Promise<{reason: string, partner: ({id:number,name:string}|null), message: string}|null>}
|
|
294
|
+
*/
|
|
295
|
+
async function refusal(req, rowPartnerId, what) {
|
|
296
|
+
const ctx = tenancy.contextFor(req);
|
|
297
|
+
const user = req && req.session && req.session.user;
|
|
298
|
+
const acting = actingElsewhere(req);
|
|
299
|
+
let out = null;
|
|
300
|
+
if (!ctx || ctx.partnerId == null) {
|
|
301
|
+
out = { reason: 'unscopable', partner: null, message: say('unscopable', { req, rowPartnerId, what }) };
|
|
302
|
+
} else if (whileActing === 'readOnly' && acting) {
|
|
303
|
+
out = { reason: 'acting', partner: null, message: say('actingReadOnly', { req, rowPartnerId, what }) };
|
|
304
|
+
} else if (inFleetView(req)) {
|
|
305
|
+
out = { reason: 'fleetView', partner: null, message: say('fleetView', { req, rowPartnerId, what }) };
|
|
306
|
+
} else if (rowPartnerId == null || writeScope(req, rowPartnerId)) {
|
|
307
|
+
return null;
|
|
308
|
+
} else if (ctx.scope === 'platform') {
|
|
309
|
+
const p = await partnerById(Number(rowPartnerId));
|
|
310
|
+
const partner = p ? { id: Number(p.id), name: p.name } : null;
|
|
311
|
+
const name = p ? p.name : `partner ${rowPartnerId}`;
|
|
312
|
+
out = { reason: 'notActing', partner, message: say('notActing', { req, rowPartnerId, what, partner, name }) };
|
|
313
|
+
} else {
|
|
314
|
+
out = { reason: 'elsewhere', partner: null, message: say('elsewhere', { req, rowPartnerId, what }) };
|
|
315
|
+
}
|
|
316
|
+
logger.warn(`write gate: user ${user ? user.id : '(none)'} (partner ${user ? user.partner_id : '(none)'}`
|
|
317
|
+
+ `${acting ? `, acting as ${ctx.partnerId}` : ''}): refused ${req && req.method} ${req && req.originalUrl}`
|
|
318
|
+
+ `${rowPartnerId == null ? '' : ` on partner ${rowPartnerId}'s`} ${what || 'row'} (${out.reason}).`);
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* WHO a row the request writes should name as its author.
|
|
324
|
+
*
|
|
325
|
+
* A row's partner_id defaults from the request's scope, and a user column keyed `(col, partner_id) →
|
|
326
|
+
* users (id, partner_id)` must name a user of THAT partner. A house operator acting as P is not one: the
|
|
327
|
+
* key refused every note, attachment and key they wrote. So when the signed-in user is working outside
|
|
328
|
+
* their home partner, the composite column is NULL (`userId: null`) and they are recorded in `actedBy` —
|
|
329
|
+
* a single-column reference to users — with `actedByName` for a table that stores the name; an app that
|
|
330
|
+
* stores only the id resolves names at read time with houseOperatorNames. Otherwise `userId` is them and
|
|
331
|
+
* the other two are null. The house user is never re-parented and never written into a P-scoped
|
|
332
|
+
* composite column.
|
|
333
|
+
*
|
|
334
|
+
* FROM THE SESSION ONLY. Nothing the request carries can set `actedBy`, so a partner's user can never
|
|
335
|
+
* attribute their row to the house; and "outside their home partner" is read from contextFor(), the one
|
|
336
|
+
* place that decides the scope, so the two cannot disagree.
|
|
337
|
+
*
|
|
338
|
+
* @returns {{userId: number|null, actedBy: number|null, actedByName: string|null}}
|
|
339
|
+
*/
|
|
340
|
+
function authorship(req) {
|
|
341
|
+
const user = req && req.session && req.session.user;
|
|
342
|
+
if (!user || user.id == null) throw new Error('tenant: authorship needs a signed-in user');
|
|
343
|
+
// No home partner (a pre-tenancy session — sign-in refuses those): nothing to be away FROM, so the user
|
|
344
|
+
// is the author, exactly as before this helper existed.
|
|
345
|
+
const ctx = user.partner_id == null ? null : tenancy.contextFor(req);
|
|
346
|
+
const away = !!ctx && ctx.scope === 'partner' && Number(ctx.partnerId) !== Number(user.partner_id);
|
|
347
|
+
return away
|
|
348
|
+
? { userId: null, actedBy: Number(user.id), actedByName: user.display_name || user.username || null }
|
|
349
|
+
: { userId: Number(user.id), actedBy: null, actedByName: null };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The house operators' display names for these ids, read at the HOUSE partner's scope — partner scope, not
|
|
354
|
+
* platform, so nothing but house users is visible to it. For the "House — <name>" byline of a row that
|
|
355
|
+
* names its author in `acted_by`: the page itself may run at the acting partner's scope, where the house's
|
|
356
|
+
* users rows are hidden. Ids from rows, never from a request.
|
|
357
|
+
*
|
|
358
|
+
* @param {number[]} ids
|
|
359
|
+
* @param {{namesOf: (ids: number[]) => Promise<Array<{id: number, display_name: string}>>}} opts the app's read
|
|
360
|
+
* @returns {Promise<Map<number, string>>}
|
|
361
|
+
*/
|
|
362
|
+
async function houseOperatorNames(ids, { namesOf } = {}) {
|
|
363
|
+
if (!isFn(namesOf)) throw new Error('houseOperatorNames: `namesOf` is required');
|
|
364
|
+
const names = new Map();
|
|
365
|
+
if (!ids || !ids.length) return names;
|
|
366
|
+
const house = await tenancy.housePartnerId();
|
|
367
|
+
for (const u of await tenancy.asPartner(house, () => namesOf(ids))) {
|
|
368
|
+
names.set(Number(u.id), u.display_name);
|
|
369
|
+
}
|
|
370
|
+
return names;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* IS THIS ERROR A WRITE REFUSED AT THE TENANT LINE? The one test the 409 handler, a route's flash and an
|
|
375
|
+
* API answer share, so they cannot drift: a 23503 on a composite tenant key (fk_*_partner), for a
|
|
376
|
+
* signed-in user, and either
|
|
377
|
+
* 'acting' the request runs in the partner the user is acting as (the actor key asks for
|
|
378
|
+
* users(<operator>, P), and the operator is not P's staff), or
|
|
379
|
+
* 'platform' the user is at PLATFORM scope and not acting (every row they write defaults partner_id to
|
|
380
|
+
* the house, so a write that hangs off another partner's record fails its composite key).
|
|
381
|
+
* Anything else is null, and its caller shows what it did before. Returns `{ kind, title, message }`.
|
|
382
|
+
*/
|
|
383
|
+
function crossTenantRefusalOf(err, req) {
|
|
384
|
+
if (!err || err.code !== '23503') return null;
|
|
385
|
+
if (!COMPOSITE_TENANT_KEY.test(String(err.constraint || ''))) return null;
|
|
386
|
+
const s = req && req.session;
|
|
387
|
+
if (!s || !s.user) return null;
|
|
388
|
+
const ctx = tenancy.contextFor(req);
|
|
389
|
+
if (!ctx) return null;
|
|
390
|
+
let kind = null;
|
|
391
|
+
if (s.actingPartnerId != null) {
|
|
392
|
+
if (ctx.scope === 'partner' && Number(ctx.partnerId) === Number(s.actingPartnerId)) kind = 'acting';
|
|
393
|
+
} else if (ctx.scope === 'platform') {
|
|
394
|
+
kind = 'platform';
|
|
395
|
+
}
|
|
396
|
+
if (!kind) return null;
|
|
397
|
+
const m = crossTenantMessages()[kind];
|
|
398
|
+
return { kind, title: m.title, message: isFn(m.message) ? m.message({ req, err }) : m.message };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function crossTenantMessages() {
|
|
402
|
+
const c = messages.crossTenant;
|
|
403
|
+
const ok = (x) => x && typeof x.title === 'string' && (typeof x.message === 'string' || isFn(x.message));
|
|
404
|
+
if (!c || !ok(c.acting) || !ok(c.platform)) {
|
|
405
|
+
throw new Error('createWriteGate: messages.crossTenant is required for the refusal — '
|
|
406
|
+
+ '{ acting: {title, message}, platform: {title, message} }');
|
|
407
|
+
}
|
|
408
|
+
return c;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* A WRITE THAT CROSSES THE TENANT LINE IS A SENTENCE, NOT A 500. An Express error handler, mounted before the
|
|
413
|
+
* app's own: crossTenantRefusalOf's case becomes a 409 — JSON `{ ok: false, type: 'error', code:
|
|
414
|
+
* 'CROSS_TENANT_WRITE', message }` for a fetch, else the `refusalView` rendered with {title, message} and
|
|
415
|
+
* SENT (a render callback means Express sends nothing; an earlier copy rendered and hung). EVERY other
|
|
416
|
+
* error is passed on untouched, and so is this one when headers are already sent or the view fails to
|
|
417
|
+
* render: one unhelpful error is not replaced by another.
|
|
418
|
+
*/
|
|
419
|
+
function crossTenantWriteHandler() {
|
|
420
|
+
crossTenantMessages(); // refuse at mount, not at the first refused write
|
|
421
|
+
return function crossTenantWrite(err, req, res, next) {
|
|
422
|
+
if (!err || res.headersSent) return next(err);
|
|
423
|
+
const r = crossTenantRefusalOf(err, req);
|
|
424
|
+
if (!r) return next(err);
|
|
425
|
+
const u = req.session.user;
|
|
426
|
+
logger.warn(`write gate: user ${u.id} (partner ${u.partner_id}${r.kind === 'acting' ? `, acting as ${req.session.actingPartnerId}` : ''}) `
|
|
427
|
+
+ `refused at the tenant line (${err.constraint}) on ${req.method} ${req.originalUrl}.`);
|
|
428
|
+
if (wantsJson(req)) return res.status(409).json({ ok: false, type: 'error', code: 'CROSS_TENANT_WRITE', message: r.message });
|
|
429
|
+
return res.status(409).render(refusalView, { title: r.title, message: r.message }, (e, html) => (e ? next(err) : res.send(html)));
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
return {
|
|
434
|
+
writeScope, readScope, createsLand, platformDestination, refusal, authorship, houseOperatorNames,
|
|
435
|
+
crossTenantWriteHandler,
|
|
436
|
+
// The handler's predicate for a route that catches its own error, the acting test for a page that hides its
|
|
437
|
+
// write controls, and the house reading's resolver for readScope.
|
|
438
|
+
crossTenantRefusalOf, actingElsewhere, houseReadingOf
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
module.exports = { createWriteGate };
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/tenancy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Aria App Framework — tenancy module. What runs on the main thread of a multi-tenant app, as factories an app calls once with its own lookups and settings: who a request works for and the scope seam, the write gate with authorship and the cross-tenant refusal handler, host resolution and per-tenant chrome, the partner store and provisioning, the acting routes and banner. The schema side (the tenant filter, the manifest, the settings layer, the migration command) is in @aria-framework/db-worker. No rule about who may see or do what lives here: each is a setting the app passes.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"private": false,
|
|
7
|
+
"publishConfig": {
|
|
8
|
+
"access": "public"
|
|
9
|
+
},
|
|
10
|
+
"main": "index.js",
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"lib/",
|
|
14
|
+
"views/",
|
|
15
|
+
"README.md",
|
|
16
|
+
"CHANGELOG.md"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node test/run.js",
|
|
20
|
+
"prepublishOnly": "node ../../test/packaging.js tenancy"
|
|
21
|
+
},
|
|
22
|
+
"peerDependencies": {
|
|
23
|
+
"@aria-framework/db-worker": ">=0.29.0",
|
|
24
|
+
"express": ">=4"
|
|
25
|
+
},
|
|
26
|
+
"peerDependenciesMeta": {
|
|
27
|
+
"express": {
|
|
28
|
+
"optional": true
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@electric-sql/pglite": "^0.5.8",
|
|
33
|
+
"better-sqlite3": "^12.10.0",
|
|
34
|
+
"ejs": "^6.0.1",
|
|
35
|
+
"express": "^5.2.1",
|
|
36
|
+
"express-session": "^1.19.0"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
<%#
|
|
2
|
+
THE ACTING BANNER: on every page while a house operator works inside a partner, with the only way out.
|
|
3
|
+
|
|
4
|
+
[%- include('acting-banner') %] (substitute < > for [ ]), at the top of the shared staff layout, outside the page
|
|
5
|
+
container so it spans the full width and cannot be mistaken for page content: somebody who forgets they are inside
|
|
6
|
+
another business's workspace will create that business's data believing it is their own.
|
|
7
|
+
|
|
8
|
+
ON EVERY PAGE, because the operator loses the partner-management permission while acting: the page that started it
|
|
9
|
+
cannot be reached, so a banner shown only there would be shown nowhere. This is also the ONLY way out, which is why
|
|
10
|
+
the route it posts to is session-gated rather than permission-gated.
|
|
11
|
+
|
|
12
|
+
LOCALS (set by actingLocals; absent, the banner draws nothing):
|
|
13
|
+
actingPartnerName the partner's name, set ONLY when the request's scope has actually moved there (escaped here)
|
|
14
|
+
actingStopPath where the way out posts (default /admin/partners/stop-acting)
|
|
15
|
+
actingNote optional: replaces the second sentence (an app where acting is read-only says what is)
|
|
16
|
+
csrfToken a FUNCTION csrfToken() -> string, bound into the views by the app; REQUIRED while the banner
|
|
17
|
+
shows, because its form posts. Without it this throws rather than draw a form the CSRF check
|
|
18
|
+
would refuse.
|
|
19
|
+
-%>
|
|
20
|
+
<% if (locals.actingPartnerName) { %>
|
|
21
|
+
<% if (typeof locals.csrfToken !== 'function') throw new Error('acting-banner: the local "csrfToken" is required while acting (a function csrfToken() -> string)'); %>
|
|
22
|
+
<div class="alert alert-warning border-0 rounded-0 mb-0 d-flex align-items-center justify-content-between py-2 px-4">
|
|
23
|
+
<div>
|
|
24
|
+
<i class="bi bi-people-fill"></i>
|
|
25
|
+
You are working inside <strong><%= actingPartnerName %></strong>.
|
|
26
|
+
<%= locals.actingNote || 'Everything you create lands there, and platform-only settings are unavailable.' %>
|
|
27
|
+
</div>
|
|
28
|
+
<form method="POST" action="<%= locals.actingStopPath || '/admin/partners/stop-acting' %>" class="m-0">
|
|
29
|
+
<input type="hidden" name="_csrf" value="<%= csrfToken() %>">
|
|
30
|
+
<button type="submit" class="btn btn-sm btn-dark">Stop working in <%= actingPartnerName %></button>
|
|
31
|
+
</form>
|
|
32
|
+
</div>
|
|
33
|
+
<% } %>
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
<%#
|
|
2
|
+
THE FLEET VIEW BANNER: on every page while fleet view is on, with the way out.
|
|
3
|
+
|
|
4
|
+
[%- include('fleet-view-banner') %] (substitute < > for [ ]), at the top of the shared staff layout, beside
|
|
5
|
+
include('acting-banner') and like it outside the page container. The two never show together: fleet view is off
|
|
6
|
+
while working in a partner.
|
|
7
|
+
|
|
8
|
+
Violet, told apart from the yellow acting banner by its classes: the app adds the two rules the README names
|
|
9
|
+
("Fleet view", the banner and the button). No inline style, no script, no event handler.
|
|
10
|
+
|
|
11
|
+
LOCALS (set by the fleet view's middleware; absent, the banner draws nothing):
|
|
12
|
+
fleetView { on, canStart, startPath, stopPath, returnTo }: drawn only when fleetView.on is true
|
|
13
|
+
csrfToken a FUNCTION csrfToken() -> string, bound into the views by the app; REQUIRED while the banner
|
|
14
|
+
shows, because its form posts. Without it this throws rather than draw a form the CSRF check
|
|
15
|
+
would refuse.
|
|
16
|
+
-%>
|
|
17
|
+
<% if (locals.fleetView && locals.fleetView.on === true) { %>
|
|
18
|
+
<% if (typeof locals.csrfToken !== 'function') throw new Error('fleet-view-banner: the local "csrfToken" is required while fleet view is on (a function csrfToken() -> string)'); %>
|
|
19
|
+
<div class="fleet-view-banner border-0 rounded-0 mb-0 d-flex align-items-center justify-content-between py-2 px-4" role="status">
|
|
20
|
+
<div>
|
|
21
|
+
<i class="bi bi-globe2"></i>
|
|
22
|
+
<strong>Fleet view.</strong> You are looking at every partner's customers. Read-only.
|
|
23
|
+
</div>
|
|
24
|
+
<form method="POST" action="<%= locals.fleetView.stopPath %>" class="m-0">
|
|
25
|
+
<input type="hidden" name="_csrf" value="<%= csrfToken() %>">
|
|
26
|
+
<button type="submit" class="btn btn-sm btn-dark">Leave fleet view</button>
|
|
27
|
+
</form>
|
|
28
|
+
</div>
|
|
29
|
+
<% } %>
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
<%#
|
|
2
|
+
THE FLEET VIEW SWITCH: the top-bar button that switches fleet view on, shown only to a person who may.
|
|
3
|
+
|
|
4
|
+
[%- include('fleet-view-button') %] (substitute < > for [ ]), in the shared top bar of every staff page.
|
|
5
|
+
|
|
6
|
+
One click, no confirmation (the owner's decision): it posts to the start route with the current page as the return
|
|
7
|
+
address, which the route checks again (a local path of this app only, else the app's home).
|
|
8
|
+
|
|
9
|
+
LOCALS (set by the fleet view's middleware; absent, the button draws nothing):
|
|
10
|
+
fleetView { on, canStart, startPath, stopPath, returnTo }: drawn only when fleetView.canStart is true
|
|
11
|
+
(never while it is on: the banner is the way out then)
|
|
12
|
+
csrfToken a FUNCTION csrfToken() -> string; REQUIRED while the button shows (it throws without it)
|
|
13
|
+
-%>
|
|
14
|
+
<% if (locals.fleetView && locals.fleetView.canStart === true && locals.fleetView.on !== true) { %>
|
|
15
|
+
<% if (typeof locals.csrfToken !== 'function') throw new Error('fleet-view-button: the local "csrfToken" is required while the switch is offered (a function csrfToken() -> string)'); %>
|
|
16
|
+
<form method="POST" action="<%= locals.fleetView.startPath %>" class="d-inline m-0">
|
|
17
|
+
<input type="hidden" name="_csrf" value="<%= csrfToken() %>">
|
|
18
|
+
<% if (locals.fleetView.returnTo) { %>
|
|
19
|
+
<input type="hidden" name="returnTo" value="<%= locals.fleetView.returnTo %>">
|
|
20
|
+
<% } %>
|
|
21
|
+
<button type="submit" class="btn btn-sm btn-outline-secondary btn-fleet-view">Fleet view</button>
|
|
22
|
+
</form>
|
|
23
|
+
<% } %>
|