@aria-framework/tenancy 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
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
+ */
62
+ function createWriteGate(o = {}) {
63
+ const { tenancy, whileActing, messages, partnerById, logger, refusalView = 'errors/generic' } = o;
64
+ const wantsJson = o.wantsJson || ((req) => !!req && isFn(req.get) && req.get('X-Requested-With') === 'fetch');
65
+ if (!tenancy || !['contextFor', 'currentTenant', 'runWithTenant', 'asPartner', 'housePartnerId', 'canHostTenants'].every((k) => isFn(tenancy[k]))) {
66
+ throw new Error('createWriteGate: `tenancy` is required — what createTenancy returned');
67
+ }
68
+ if (!WHILE_ACTING.has(whileActing)) {
69
+ throw new Error("createWriteGate: `whileActing` is required — 'write' or 'readOnly'. It has no default because "
70
+ + "existing apps answer it differently; a new staff app passes 'write'");
71
+ }
72
+ if (!Object.prototype.hasOwnProperty.call(o, 'houseReading')
73
+ || !(o.houseReading === null || (typeof o.houseReading === 'string' && o.houseReading))) {
74
+ throw new Error('createWriteGate: `houseReading` is required — a permission name, or null for none (a new app passes null)');
75
+ }
76
+ const houseReading = o.houseReading;
77
+ if (!messages || typeof messages !== 'object') throw new Error('createWriteGate: `messages` is required');
78
+ const needed = ['unscopable', 'notActing', 'elsewhere'].concat(whileActing === 'readOnly' ? ['actingReadOnly'] : []);
79
+ for (const k of needed) {
80
+ if (!(typeof messages[k] === 'string' || isFn(messages[k]))) {
81
+ throw new Error(`createWriteGate: messages.${k} is required (a sentence, or a function returning one)`);
82
+ }
83
+ }
84
+ if (!isFn(partnerById)) throw new Error('createWriteGate: `partnerById` is required');
85
+ if (!logger || !isFn(logger.warn)) throw new Error('createWriteGate: `logger` is required (with warn)');
86
+ if (!isFn(wantsJson)) throw new Error('createWriteGate: `wantsJson` must be a function when given');
87
+
88
+ const say = (key, info) => (isFn(messages[key]) ? messages[key](info) : messages[key]);
89
+
90
+ /**
91
+ * IS THIS REQUEST RUNNING IN ANOTHER PARTNER THAN THE SIGNED-IN USER'S OWN? Decided by the scope ACTUALLY
92
+ * MOVING (contextFor), never by the raw session flag: contextFor honours `actingPartnerId` only for a
93
+ * platform user, so a partner user's session carrying a stray flag (a bug, a replayed session, a
94
+ * hand-edited store) still runs in its own partner. Platform scope is the user's own partner: false.
95
+ */
96
+ function actingElsewhere(req) {
97
+ const user = req && req.session && req.session.user;
98
+ if (!user || user.partner_id == null) return false;
99
+ const ctx = tenancy.contextFor(req);
100
+ return !!ctx && ctx.scope === 'partner' && ctx.partnerId != null && Number(ctx.partnerId) !== Number(user.partner_id);
101
+ }
102
+
103
+ /**
104
+ * Does this request have a tenant for a new row to land in AT ALL?
105
+ *
106
+ * A partner-scoped user has their own; an acting operator has the tenant they are acting as; a platform
107
+ * operator who is NOT acting has their own partner (the house, for an ordinary house admin — by
108
+ * convention, or checked at use with `platformRequiresHouse`). All three carry a `partnerId`, and a
109
+ * platform-scope create lands correctly in the account's own tenant, so it is not refused. Only two
110
+ * shapes carry none, and both are refused: contextFor's null (unscopable, refuse, never widen) and the
111
+ * anonymous context. With `whileActing: 'readOnly'`, an operator acting as a partner has nowhere to
112
+ * create either: a create while acting would default partner_id to that partner and record no actor.
113
+ *
114
+ * "Creating FOR A PARTNER requires acting" stays exactly true: the scope narrows to a partner only when
115
+ * the operator acts. The risk left — an operator who MEANT to act and forgot, creating a house row with
116
+ * the right name and the wrong owner — is closed by the form naming its destination (platformDestination).
117
+ */
118
+ function createsLand(req) {
119
+ const ctx = tenancy.contextFor(req);
120
+ if (!ctx || ctx.partnerId == null) return false;
121
+ return !(whileActing === 'readOnly' && actingElsewhere(req));
122
+ }
123
+
124
+ /**
125
+ * THE CONTEXT THE GATE JUDGES — one rule for writeScope and readScope:
126
+ * - a request: contextFor(req), the one place that decides a request's scope (the hub's form). The scope
127
+ * that happens to surround the call does not enter into it;
128
+ * - null: a caller with no request (a job): the CURRENT scope (the noc and soc apps' form);
129
+ * - anything else, undefined included, throws: a forgotten argument must not silently pick a rule.
130
+ */
131
+ function judged(req, fnName) {
132
+ if (req === null) return tenancy.currentTenant();
133
+ if (req === undefined || typeof req !== 'object') {
134
+ throw new Error(`${fnName}: pass the request, or null for work with no request (a job) — got ${req === undefined ? 'undefined' : typeof req}`);
135
+ }
136
+ return tenancy.contextFor(req);
137
+ }
138
+
139
+ /**
140
+ * THE RUNNER RUNS IN THE CONTEXT IT JUDGED, never in whatever surrounds the call. A runner returning `fn()`
141
+ * would run at platform scope inside acrossAll, at the house inside asHouse or asOwnPartner, at another partner
142
+ * inside asPartner(other): gated in one scope, written in another — measured, with an UPDATE that reached
143
+ * another partner's row. So every non-null answer re-establishes its context with runWithTenant (the
144
+ * package's own context, the one db-worker carries into the worker), at partner scope as well as platform.
145
+ */
146
+ const runnerAt = (ctx) => {
147
+ const fixed = { scope: ctx.scope, partnerId: ctx.partnerId };
148
+ return (fn) => tenancy.runWithTenant(fixed, fn);
149
+ };
150
+
151
+ /**
152
+ * Where this request may WRITE a row that already belongs to partner `rowPartnerId` (edit it, delete it,
153
+ * or hang a new child row off it): a function running its argument in the scope to write in, or null.
154
+ *
155
+ * - no tenant to write into (createsLand's null cases) → null
156
+ * - acting as a partner with `whileActing: 'readOnly'` → null
157
+ * - PARTNER scope (a partner's staff, or an operator acting) → that partner's own rows only, run at
158
+ * that partner's scope. On SQLite not compared (the header's TWO ENGINES).
159
+ * - PLATFORM scope, not acting → the request's OWN partner's rows only
160
+ * (for house staff, the house's), run at that partner's scope; another partner's row is null: the house
161
+ * writes into a partner only while acting as it.
162
+ * Every runner runs at `{ partner, <the judged partner> }`, whatever scope it is later called inside.
163
+ *
164
+ * @param {object|null} req the request, or null for a job (the judged context is then the current scope)
165
+ * @param {number|string} rowPartnerId the row's own partner_id (BIGINT may arrive as a string)
166
+ * @returns {((fn: Function) => any)|null}
167
+ */
168
+ function writeScope(req, rowPartnerId) {
169
+ const ctx = judged(req, 'writeScope');
170
+ if (!ctx || ctx.partnerId == null) return null;
171
+ if (req && whileActing === 'readOnly' && actingElsewhere(req)) return null;
172
+ if (ctx.scope === 'partner') {
173
+ // SQLite: every row says partner 1 whoever wrote it — the hub's reason, kept: compare nothing there.
174
+ if (!tenancy.canHostTenants()) return runnerAt(ctx);
175
+ return Number(ctx.partnerId) === Number(rowPartnerId) ? runnerAt(ctx) : null;
176
+ }
177
+ if (ctx.scope === 'platform' && rowPartnerId != null && Number(ctx.partnerId) === Number(rowPartnerId)) {
178
+ // Narrowed to the row's (= the judged) partner, so row-level security bounds the write itself.
179
+ return runnerAt({ scope: 'partner', partnerId: Number(rowPartnerId) });
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * Where this request may READ a row of partner `rowPartnerId`: a function running its argument at that
186
+ * partner's scope, or null (the caller answers 404). A partner viewer — or a platform viewer ACTING as a
187
+ * partner, whose scope is then that partner's — reads only its own partner's rows; a platform viewer who
188
+ * is not acting reads any partner's row, at that row's OWN partner's scope (partner_id from the row RLS
189
+ * just admitted). The judged context follows writeScope's rule (a request, or null for a job), and every
190
+ * runner runs at `{ partner, <that partner> }` wherever it is called.
191
+ *
192
+ * THE HOUSE READING (`houseReading` set): house staff at platform scope WITHOUT that permission read only
193
+ * the house's own rows. `{ house }` is then required — the house id from houseReadingOf(req, can), or
194
+ * exactly null for any other reading. Anything else (undefined from a mistyped local, 0, a string) throws:
195
+ * a call site that got it wrong fails loudly instead of reading the fleet.
196
+ *
197
+ * @param {object|null} req
198
+ * @param {number|string} rowPartnerId
199
+ * @param {{house?: number|null}} [opts]
200
+ * @returns {((fn: Function) => any)|null}
201
+ */
202
+ function readScope(req, rowPartnerId, opts) {
203
+ let house = null;
204
+ if (houseReading) {
205
+ if (!opts || !Object.prototype.hasOwnProperty.call(opts, 'house')) {
206
+ throw new Error('readScope: this app has the house reading — pass { house } from houseReadingOf(req, can)');
207
+ }
208
+ house = opts.house;
209
+ if (!(house === null || (Number.isInteger(house) && house > 0))) {
210
+ throw new Error(`readScope: { house } must be null or the house id from houseReadingOf(req, can), not ${String(house)}`);
211
+ }
212
+ }
213
+ const ctx = judged(req, 'readScope');
214
+ if (ctx && ctx.scope === 'partner') return Number(ctx.partnerId) === Number(rowPartnerId) ? runnerAt(ctx) : null;
215
+ if (ctx && ctx.scope === 'platform') {
216
+ if (house !== null && Number(rowPartnerId) !== house) return null; // the house reading: the house's own only
217
+ return runnerAt({ scope: 'partner', partnerId: Number(rowPartnerId) });
218
+ }
219
+ return null;
220
+ }
221
+
222
+ /**
223
+ * WHICH READING: the house id when this request is the HOUSE reading (platform scope without the
224
+ * `houseReading` permission), else null. Always null when the app has no house reading. Call it BEFORE any
225
+ * asPartner narrowing: inside one, a platform-only permission reads false and every request would look
226
+ * like the house reading. A request with no scope is refused, never widened.
227
+ *
228
+ * @param {object} req
229
+ * @param {(permission: string) => boolean} can the request's permission check (res.locals.can)
230
+ * @returns {Promise<number|null>}
231
+ */
232
+ async function houseReadingOf(req, can) {
233
+ if (!houseReading) return null;
234
+ const ctx = tenancy.contextFor(req);
235
+ if (!ctx || (ctx.scope !== 'platform' && ctx.scope !== 'partner')) throw new Error('houseReadingOf: the request has no scope');
236
+ if (ctx.scope === 'partner') return null;
237
+ if (isFn(can) && can(houseReading) === true) return null;
238
+ return tenancy.housePartnerId();
239
+ }
240
+
241
+ /**
242
+ * The partner a create at PLATFORM scope would land on — the session user's own partner, the house for an
243
+ * ordinary house admin — or null when this request is not in that shape. A creating form shows it, so an
244
+ * operator who meant to act and forgot sees where Save will file the row. Read from the SESSION's own
245
+ * context, never from anything the request carries.
246
+ *
247
+ * NULL WHILE ACTING, ON PURPOSE: the acting banner already says "You are working inside <partner>" on every
248
+ * page, and a second sentence would duplicate it. Null for a partner-scoped user too.
249
+ *
250
+ * @returns {Promise<{id: number, name: string}|null>}
251
+ */
252
+ async function platformDestination(req) {
253
+ const ctx = tenancy.contextFor(req);
254
+ if (!ctx || ctx.scope !== 'platform' || ctx.partnerId == null) return null;
255
+ return partnerById(ctx.partnerId);
256
+ }
257
+
258
+ /**
259
+ * What a route says when the gate says no, or null when it says yes:
260
+ * `{ reason, partner, message }`, `reason` one of 'unscopable', 'acting', 'notActing', 'elsewhere'.
261
+ *
262
+ * `rowPartnerId` null (a create, or no such row): the create check — the unscopable sentence, or while
263
+ * acting read-only the acting one; otherwise null, and for an edit the caller's own lookup says "not
264
+ * found". `what` is the caller's noun for the log and the app's sentence ("site visit 9", "tickets").
265
+ * Every refusal is logged with who, the method and path, and whose row.
266
+ *
267
+ * @param {object} req
268
+ * @param {number|string|null} rowPartnerId
269
+ * @param {string} [what]
270
+ * @returns {Promise<{reason: string, partner: ({id:number,name:string}|null), message: string}|null>}
271
+ */
272
+ async function refusal(req, rowPartnerId, what) {
273
+ const ctx = tenancy.contextFor(req);
274
+ const user = req && req.session && req.session.user;
275
+ const acting = actingElsewhere(req);
276
+ let out = null;
277
+ if (!ctx || ctx.partnerId == null) {
278
+ out = { reason: 'unscopable', partner: null, message: say('unscopable', { req, rowPartnerId, what }) };
279
+ } else if (whileActing === 'readOnly' && acting) {
280
+ out = { reason: 'acting', partner: null, message: say('actingReadOnly', { req, rowPartnerId, what }) };
281
+ } else if (rowPartnerId == null || writeScope(req, rowPartnerId)) {
282
+ return null;
283
+ } else if (ctx.scope === 'platform') {
284
+ const p = await partnerById(Number(rowPartnerId));
285
+ const partner = p ? { id: Number(p.id), name: p.name } : null;
286
+ const name = p ? p.name : `partner ${rowPartnerId}`;
287
+ out = { reason: 'notActing', partner, message: say('notActing', { req, rowPartnerId, what, partner, name }) };
288
+ } else {
289
+ out = { reason: 'elsewhere', partner: null, message: say('elsewhere', { req, rowPartnerId, what }) };
290
+ }
291
+ logger.warn(`write gate: user ${user ? user.id : '(none)'} (partner ${user ? user.partner_id : '(none)'}`
292
+ + `${acting ? `, acting as ${ctx.partnerId}` : ''}): refused ${req && req.method} ${req && req.originalUrl}`
293
+ + `${rowPartnerId == null ? '' : ` on partner ${rowPartnerId}'s`} ${what || 'row'} (${out.reason}).`);
294
+ return out;
295
+ }
296
+
297
+ /**
298
+ * WHO a row the request writes should name as its author.
299
+ *
300
+ * A row's partner_id defaults from the request's scope, and a user column keyed `(col, partner_id) →
301
+ * users (id, partner_id)` must name a user of THAT partner. A house operator acting as P is not one: the
302
+ * key refused every note, attachment and key they wrote. So when the signed-in user is working outside
303
+ * their home partner, the composite column is NULL (`userId: null`) and they are recorded in `actedBy` —
304
+ * a single-column reference to users — with `actedByName` for a table that stores the name; an app that
305
+ * stores only the id resolves names at read time with houseOperatorNames. Otherwise `userId` is them and
306
+ * the other two are null. The house user is never re-parented and never written into a P-scoped
307
+ * composite column.
308
+ *
309
+ * FROM THE SESSION ONLY. Nothing the request carries can set `actedBy`, so a partner's user can never
310
+ * attribute their row to the house; and "outside their home partner" is read from contextFor(), the one
311
+ * place that decides the scope, so the two cannot disagree.
312
+ *
313
+ * @returns {{userId: number|null, actedBy: number|null, actedByName: string|null}}
314
+ */
315
+ function authorship(req) {
316
+ const user = req && req.session && req.session.user;
317
+ if (!user || user.id == null) throw new Error('tenant: authorship needs a signed-in user');
318
+ // No home partner (a pre-tenancy session — sign-in refuses those): nothing to be away FROM, so the user
319
+ // is the author, exactly as before this helper existed.
320
+ const ctx = user.partner_id == null ? null : tenancy.contextFor(req);
321
+ const away = !!ctx && ctx.scope === 'partner' && Number(ctx.partnerId) !== Number(user.partner_id);
322
+ return away
323
+ ? { userId: null, actedBy: Number(user.id), actedByName: user.display_name || user.username || null }
324
+ : { userId: Number(user.id), actedBy: null, actedByName: null };
325
+ }
326
+
327
+ /**
328
+ * The house operators' display names for these ids, read at the HOUSE partner's scope — partner scope, not
329
+ * platform, so nothing but house users is visible to it. For the "House — <name>" byline of a row that
330
+ * names its author in `acted_by`: the page itself may run at the acting partner's scope, where the house's
331
+ * users rows are hidden. Ids from rows, never from a request.
332
+ *
333
+ * @param {number[]} ids
334
+ * @param {{namesOf: (ids: number[]) => Promise<Array<{id: number, display_name: string}>>}} opts the app's read
335
+ * @returns {Promise<Map<number, string>>}
336
+ */
337
+ async function houseOperatorNames(ids, { namesOf } = {}) {
338
+ if (!isFn(namesOf)) throw new Error('houseOperatorNames: `namesOf` is required');
339
+ const names = new Map();
340
+ if (!ids || !ids.length) return names;
341
+ const house = await tenancy.housePartnerId();
342
+ for (const u of await tenancy.asPartner(house, () => namesOf(ids))) {
343
+ names.set(Number(u.id), u.display_name);
344
+ }
345
+ return names;
346
+ }
347
+
348
+ /**
349
+ * IS THIS ERROR A WRITE REFUSED AT THE TENANT LINE? The one test the 409 handler, a route's flash and an
350
+ * API answer share, so they cannot drift: a 23503 on a composite tenant key (fk_*_partner), for a
351
+ * signed-in user, and either
352
+ * 'acting' the request runs in the partner the user is acting as (the actor key asks for
353
+ * users(<operator>, P), and the operator is not P's staff), or
354
+ * 'platform' the user is at PLATFORM scope and not acting (every row they write defaults partner_id to
355
+ * the house, so a write that hangs off another partner's record fails its composite key).
356
+ * Anything else is null, and its caller shows what it did before. Returns `{ kind, title, message }`.
357
+ */
358
+ function crossTenantRefusalOf(err, req) {
359
+ if (!err || err.code !== '23503') return null;
360
+ if (!COMPOSITE_TENANT_KEY.test(String(err.constraint || ''))) return null;
361
+ const s = req && req.session;
362
+ if (!s || !s.user) return null;
363
+ const ctx = tenancy.contextFor(req);
364
+ if (!ctx) return null;
365
+ let kind = null;
366
+ if (s.actingPartnerId != null) {
367
+ if (ctx.scope === 'partner' && Number(ctx.partnerId) === Number(s.actingPartnerId)) kind = 'acting';
368
+ } else if (ctx.scope === 'platform') {
369
+ kind = 'platform';
370
+ }
371
+ if (!kind) return null;
372
+ const m = crossTenantMessages()[kind];
373
+ return { kind, title: m.title, message: isFn(m.message) ? m.message({ req, err }) : m.message };
374
+ }
375
+
376
+ function crossTenantMessages() {
377
+ const c = messages.crossTenant;
378
+ const ok = (x) => x && typeof x.title === 'string' && (typeof x.message === 'string' || isFn(x.message));
379
+ if (!c || !ok(c.acting) || !ok(c.platform)) {
380
+ throw new Error('createWriteGate: messages.crossTenant is required for the refusal — '
381
+ + '{ acting: {title, message}, platform: {title, message} }');
382
+ }
383
+ return c;
384
+ }
385
+
386
+ /**
387
+ * A WRITE THAT CROSSES THE TENANT LINE IS A SENTENCE, NOT A 500. An Express error handler, mounted before the
388
+ * app's own: crossTenantRefusalOf's case becomes a 409 — JSON `{ ok: false, type: 'error', code:
389
+ * 'CROSS_TENANT_WRITE', message }` for a fetch, else the `refusalView` rendered with {title, message} and
390
+ * SENT (a render callback means Express sends nothing; an earlier copy rendered and hung). EVERY other
391
+ * error is passed on untouched, and so is this one when headers are already sent or the view fails to
392
+ * render: one unhelpful error is not replaced by another.
393
+ */
394
+ function crossTenantWriteHandler() {
395
+ crossTenantMessages(); // refuse at mount, not at the first refused write
396
+ return function crossTenantWrite(err, req, res, next) {
397
+ if (!err || res.headersSent) return next(err);
398
+ const r = crossTenantRefusalOf(err, req);
399
+ if (!r) return next(err);
400
+ const u = req.session.user;
401
+ logger.warn(`write gate: user ${u.id} (partner ${u.partner_id}${r.kind === 'acting' ? `, acting as ${req.session.actingPartnerId}` : ''}) `
402
+ + `refused at the tenant line (${err.constraint}) on ${req.method} ${req.originalUrl}.`);
403
+ if (wantsJson(req)) return res.status(409).json({ ok: false, type: 'error', code: 'CROSS_TENANT_WRITE', message: r.message });
404
+ return res.status(409).render(refusalView, { title: r.title, message: r.message }, (e, html) => (e ? next(err) : res.send(html)));
405
+ };
406
+ }
407
+
408
+ return {
409
+ writeScope, readScope, createsLand, platformDestination, refusal, authorship, houseOperatorNames,
410
+ crossTenantWriteHandler,
411
+ // The handler's predicate for a route that catches its own error, the acting test for a page that hides its
412
+ // write controls, and the house reading's resolver for readScope.
413
+ crossTenantRefusalOf, actingElsewhere, houseReadingOf
414
+ };
415
+ }
416
+
417
+ module.exports = { createWriteGate };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@aria-framework/tenancy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.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
+ <% } %>