@aria-framework/tenancy 0.1.0 → 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 +32 -1
- package/README.md +282 -5
- package/lib/partners/actingIdle.js +177 -0
- package/lib/partners/index.js +4 -2
- package/lib/scope/fleetView.js +437 -0
- package/lib/scope/idle.js +244 -0
- package/lib/scope/index.js +4 -2
- package/lib/scope/tenancy.js +12 -2
- package/lib/scope/writeGate.js +27 -2
- package/package.json +1 -1
- package/views/fleet-view-banner.ejs +29 -0
- package/views/fleet-view-button.ejs +23 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE IDLE END, shared by fleet view (createFleetView) and working in a partner (createActingIdle): ONE rule for when a
|
|
3
|
+
* session mode has run out, ONE rule for when its activity stamp is written, and one way of telling the person once.
|
|
4
|
+
*
|
|
5
|
+
* idleEnded(lastActiveMs, minutes, nowMs) true when `minutes` have passed since the last stamp
|
|
6
|
+
* stampDue(lastActiveMs, minutes, nowMs) true when a request that counts as activity should write a new stamp
|
|
7
|
+
* readIdleMinutes(idleMinutes) the app's setting, awaited and checked (a whole number, 0 or more)
|
|
8
|
+
* saveNow(req) req.session.save(), awaited (a no-op without a save)
|
|
9
|
+
* noticeOnce(flash, logger, req, res, kind, text) the one-line notice, through the app's flash; never throws
|
|
10
|
+
*
|
|
11
|
+
* The two modes call these through this module object (`idle.idleEnded(...)`), looked up at call time, so a test that
|
|
12
|
+
* replaces one function here is obeyed by both: that is how "one rule" is proven, by behaviour.
|
|
13
|
+
*
|
|
14
|
+
* Package-internal: an app reaches these only through the two factories.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
'use strict';
|
|
18
|
+
|
|
19
|
+
const MINUTE = 60 * 1000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* THE STAMP IS THROTTLED. Every write of the session on an ordinary request is a write that a request in flight at the
|
|
23
|
+
* same time can later undo with its stale copy (a stop, a sign-out), so the package writes as rarely as it can: at
|
|
24
|
+
* most once per ACTIVITY_STAMP_MAX_MS, and for a short period at most once per tenth of it (so the stamp is never more
|
|
25
|
+
* than a tenth of the period behind). The idle end is judged from the stamp, so a mode ends between
|
|
26
|
+
* `minutes - min(1 minute, minutes / 10)` and `minutes` after the last activity.
|
|
27
|
+
*/
|
|
28
|
+
const ACTIVITY_STAMP_MAX_MS = MINUTE;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* HAS THE IDLE PERIOD RUN OUT? `minutes` 0 means never. The period runs out AT `minutes` after the last stamp
|
|
32
|
+
* (14:59.999 after it is still on, 15:00 is off). A last-activity time that is not a number is "run out" (fail closed:
|
|
33
|
+
* a session the package did not stamp is not kept alive by default). A clock that went backwards is not "run out".
|
|
34
|
+
*/
|
|
35
|
+
function idleEnded(lastActiveMs, minutes, nowMs) {
|
|
36
|
+
if (!(Number.isInteger(minutes) && minutes >= 0)) throw new TypeError(`idle: minutes must be a whole number, 0 or more, not ${String(minutes)}`);
|
|
37
|
+
if (minutes === 0) return false;
|
|
38
|
+
if (!Number.isFinite(lastActiveMs) || !Number.isFinite(nowMs)) return true;
|
|
39
|
+
return nowMs - lastActiveMs >= minutes * MINUTE;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** SHOULD THIS REQUEST WRITE A NEW STAMP? Never at 0 minutes (no idle end: nothing is ever written for it). */
|
|
43
|
+
function stampDue(lastActiveMs, minutes, nowMs) {
|
|
44
|
+
if (!(Number.isInteger(minutes) && minutes >= 0)) throw new TypeError(`idle: minutes must be a whole number, 0 or more, not ${String(minutes)}`);
|
|
45
|
+
if (minutes === 0) return false;
|
|
46
|
+
if (!Number.isFinite(lastActiveMs)) return true;
|
|
47
|
+
return nowMs - lastActiveMs >= Math.min(ACTIVITY_STAMP_MAX_MS, (minutes * MINUTE) / 10);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The app's `idleMinutes()`, sync or async, checked: anything but a whole number of 0 or more throws. */
|
|
51
|
+
async function readIdleMinutes(idleMinutes) {
|
|
52
|
+
const m = await idleMinutes();
|
|
53
|
+
if (!(Number.isInteger(m) && m >= 0)) throw new TypeError(`idleMinutes() answered ${JSON.stringify(m)}, not a whole number of 0 or more`);
|
|
54
|
+
return m;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* SAVE THE SESSION NOW, before the request goes on: a change this package makes is never left for the end of the
|
|
59
|
+
* request, where a slow request would write it back over a stop or a sign-out that happened meanwhile (express-session
|
|
60
|
+
* saves at the end only a session changed since it was last saved; after this, it is not). Without a save function
|
|
61
|
+
* (no session store) it resolves at once.
|
|
62
|
+
*/
|
|
63
|
+
function saveNow(req) {
|
|
64
|
+
const s = req && req.session;
|
|
65
|
+
if (!s || typeof s.save !== 'function') return Promise.resolve();
|
|
66
|
+
return new Promise((resolve, reject) => s.save((err) => (err ? reject(err) : resolve())));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A STABLE KEY for a session row, to tell "the row as this request loaded it" from "the row as the store holds it now":
|
|
71
|
+
* the JSON a store would hold, with every object's keys SORTED (key order does not matter), the top-level `cookie`
|
|
72
|
+
* left out (express-session's own, rewritten by touch() on every request). As JSON does: an `undefined` member and a
|
|
73
|
+
* function are left out (in an array, null), a Date (anything with toJSON) is its toJSON() (its ISO string, which is
|
|
74
|
+
* what a store row holds), nested objects and arrays are compared all the way down, NaN and Infinity are null.
|
|
75
|
+
*/
|
|
76
|
+
function stableKey(v) {
|
|
77
|
+
if (v === undefined || typeof v === 'function') return undefined;
|
|
78
|
+
if (v === null || typeof v !== 'object') return JSON.stringify(v);
|
|
79
|
+
if (typeof v.toJSON === 'function') return stableKey(v.toJSON());
|
|
80
|
+
if (Array.isArray(v)) return `[${v.map((x) => { const k = stableKey(x); return k === undefined ? 'null' : k; }).join(',')}]`;
|
|
81
|
+
const parts = [];
|
|
82
|
+
for (const k of Object.keys(v).sort()) {
|
|
83
|
+
const inner = stableKey(v[k]);
|
|
84
|
+
if (inner !== undefined) parts.push(`${JSON.stringify(k)}:${inner}`);
|
|
85
|
+
}
|
|
86
|
+
return `{${parts.join(',')}}`;
|
|
87
|
+
}
|
|
88
|
+
function rowKey(sess) {
|
|
89
|
+
if (!sess || typeof sess !== 'object') return null;
|
|
90
|
+
const { cookie, ...data } = sess; // eslint-disable-line no-unused-vars
|
|
91
|
+
return stableKey(data);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* THE SESSION AS LOADED, kept for the requests that could write: what express-session handed the app, before any
|
|
96
|
+
* middleware changed it. `markLoaded(req)` is called directly after the session middleware (by `fleet.loaded`, or by
|
|
97
|
+
* the acting idle end's `before`, which sits there anyway); it copies the session's data (cookie aside) only when the
|
|
98
|
+
* session carries fleet view or the acting keys, and keeps the first copy. Kept per request object, nothing outlives it.
|
|
99
|
+
*/
|
|
100
|
+
const LOADED = new WeakMap();
|
|
101
|
+
const OWN_MARK_KEYS = ['fleetViewSince', 'actingPartnerId', 'actingIdleAt'];
|
|
102
|
+
function dataOf(s) {
|
|
103
|
+
const copy = JSON.parse(JSON.stringify(s));
|
|
104
|
+
delete copy.cookie;
|
|
105
|
+
return copy;
|
|
106
|
+
}
|
|
107
|
+
function markLoaded(req) {
|
|
108
|
+
const s = req && req.session;
|
|
109
|
+
if (!s || LOADED.has(req)) return;
|
|
110
|
+
if (!OWN_MARK_KEYS.some((k) => s[k] != null)) return;
|
|
111
|
+
LOADED.set(req, dataOf(s));
|
|
112
|
+
}
|
|
113
|
+
function loadedOf(req) { return (req && LOADED.get(req)) || null; }
|
|
114
|
+
|
|
115
|
+
const isPlain = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
116
|
+
const clone = (v) => (v === undefined ? undefined : JSON.parse(JSON.stringify(v)));
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* THIS REQUEST'S OWN CHANGES, laid over the row the store holds NOW: every key where the session in memory differs
|
|
120
|
+
* from the session as loaded is this request's (set or removed); every other key is taken from the store's row, so
|
|
121
|
+
* another request's write (a flash, a second factor, a version) is carried through, never written over with what this
|
|
122
|
+
* request merely held. Plain objects are merged key by key, all the way down — but ONLY where the loaded session, this
|
|
123
|
+
* request's and the row all hold a plain object at that key: two requests adding flash messages of different kinds keep
|
|
124
|
+
* both when a flash object was already there at load, and when none was (the usual case) this request's whole flash
|
|
125
|
+
* object replaces the row's. Anything else (an array, a value) changed by this request replaces the row's.
|
|
126
|
+
*/
|
|
127
|
+
function mergeRequest(target, loaded, mem) {
|
|
128
|
+
const keys = new Set([...Object.keys(loaded || {}), ...Object.keys(mem || {})]);
|
|
129
|
+
for (const k of keys) {
|
|
130
|
+
if (k === 'cookie') continue;
|
|
131
|
+
const l = loaded ? loaded[k] : undefined;
|
|
132
|
+
const m = mem ? mem[k] : undefined;
|
|
133
|
+
if (stableKey(l) === stableKey(m)) continue; // unchanged by this request: the row's stands
|
|
134
|
+
if (m === undefined) { delete target[k]; continue; } // removed by this request
|
|
135
|
+
if (isPlain(m) && isPlain(l) && isPlain(target[k])) { mergeRequest(target[k], l, m); continue; }
|
|
136
|
+
target[k] = clone(m);
|
|
137
|
+
}
|
|
138
|
+
return target;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Replace the session's data in memory (cookie aside) with `data`, in data's key order. */
|
|
142
|
+
function replaceData(s, data) {
|
|
143
|
+
for (const k of Object.keys(s)) if (k !== 'cookie') delete s[k];
|
|
144
|
+
for (const k of Object.keys(data)) if (k !== 'cookie') s[k] = data[k];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* RE-READ, MERGE, SAVE: the only way this package writes the session on an ordinary request (an activity stamp, an
|
|
149
|
+
* automatic end). After every other await of the request's own work is done, the session's row is read again from the
|
|
150
|
+
* store (`req.sessionStore.get(req.sessionID)`), and:
|
|
151
|
+
* - no row → 'gone' (the person signed out meanwhile): nothing is written
|
|
152
|
+
* - `stillOk(row)` is not true → 'changed' (the mode was left, another user, another start): nothing is
|
|
153
|
+
* written
|
|
154
|
+
* - no store, or the read fails → 'unreadable' (fail closed): nothing is written
|
|
155
|
+
* - no copy of the session as loaded → 'unmarked' (fleet.loaded is not mounted): nothing is written
|
|
156
|
+
* - otherwise, IN THE READ'S CALLBACK (nothing awaited between the answer and the save call): the row read back,
|
|
157
|
+
* plus this request's own changes (mergeRequest), plus `change(target)` (this package's: the stamp, or the fields
|
|
158
|
+
* an automatic end clears), becomes the session in memory, and req.session.save() writes it → 'saved'
|
|
159
|
+
* express-session then has nothing left to save at the end of the request: save() records the saved state, and its
|
|
160
|
+
* end-of-request save writes only a session changed after that. So the store is never overwritten a moment later by
|
|
161
|
+
* the stale copy this request loaded. What is left is the one store round trip between the answer and the save
|
|
162
|
+
* landing (README, "When the package writes the session").
|
|
163
|
+
*
|
|
164
|
+
* @returns {Promise<{ outcome: 'saved'|'gone'|'changed'|'unreadable'|'unmarked', row: object|null }>}
|
|
165
|
+
*/
|
|
166
|
+
function writeMerged(req, stillOk, change) {
|
|
167
|
+
return new Promise((resolve, reject) => {
|
|
168
|
+
const store = req && req.sessionStore;
|
|
169
|
+
const s = req && req.session;
|
|
170
|
+
if (!s || typeof s.save !== 'function' || !store || typeof store.get !== 'function' || req.sessionID == null) return resolve({ outcome: 'unreadable', row: null });
|
|
171
|
+
const loaded = loadedOf(req);
|
|
172
|
+
if (!loaded) return resolve({ outcome: 'unmarked', row: null });
|
|
173
|
+
let answered = false;
|
|
174
|
+
const onRow = (err, row) => {
|
|
175
|
+
if (answered) return undefined;
|
|
176
|
+
answered = true;
|
|
177
|
+
if (err) return resolve({ outcome: 'unreadable', row: null });
|
|
178
|
+
if (!row) return resolve({ outcome: 'gone', row: null });
|
|
179
|
+
let ok = false;
|
|
180
|
+
try { ok = stillOk(row) === true; } catch (_) { ok = false; }
|
|
181
|
+
if (!ok) return resolve({ outcome: 'changed', row });
|
|
182
|
+
let target;
|
|
183
|
+
try {
|
|
184
|
+
target = mergeRequest(dataOf(row), loaded, dataOf(s));
|
|
185
|
+
change(target);
|
|
186
|
+
} catch (e) { return reject(e); }
|
|
187
|
+
replaceData(s, target);
|
|
188
|
+
return s.save((e) => (e ? reject(e) : resolve({ outcome: 'saved', row })));
|
|
189
|
+
};
|
|
190
|
+
try { store.get(req.sessionID, onRow); } catch (e) { onRow(e); }
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* WHEN NOTHING WAS WRITTEN: this package's own keys in memory must not be written by express-session's end-of-request
|
|
196
|
+
* save either. If nothing else of the session changed in memory (against the session as loaded), the session is put back
|
|
197
|
+
* exactly as `pre` (express-session then saves nothing). If the app itself changed something (so express-session WILL
|
|
198
|
+
* save the request's copy at its end), this package's keys are aligned with the row read back (removed when the row is
|
|
199
|
+
* gone), so that save cannot bring back a mode that was left or a session's mode that was signed out.
|
|
200
|
+
*/
|
|
201
|
+
function settleUnwritten(req, pre, row, ownKeys, outcome) {
|
|
202
|
+
const s = req.session;
|
|
203
|
+
replaceData(s, pre);
|
|
204
|
+
const loaded = loadedOf(req);
|
|
205
|
+
if (!loaded || outcome === 'unreadable' || outcome === 'unmarked') return;
|
|
206
|
+
if (stableKey(dataOf(s)) === stableKey(loaded)) return;
|
|
207
|
+
for (const k of ownKeys) {
|
|
208
|
+
if (row && row[k] !== undefined) s[k] = clone(row[k]); else delete s[k];
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** A copy of the session's own data, in its key order, and putting it back exactly (so express-session sees no change). */
|
|
213
|
+
function snapshot(s) { return JSON.parse(JSON.stringify(s)); }
|
|
214
|
+
function restore(s, snap) {
|
|
215
|
+
for (const k of Object.keys(s)) if (k !== 'cookie') delete s[k];
|
|
216
|
+
for (const k of Object.keys(snap)) if (k !== 'cookie') s[k] = snap[k];
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Tell the person once, on their next page: through the app's `flash(req, res, kind, text)` when it gave one (it may
|
|
221
|
+
* return a promise), else `res.flash(kind, text, callback)` (connect-flash style WITH a callback, as actingRoutes'
|
|
222
|
+
* default). A failure is logged at error and swallowed: a notice that could not be shown must not keep a mode on.
|
|
223
|
+
*/
|
|
224
|
+
function noticeOnce(flash, logger, req, res, kind, text) {
|
|
225
|
+
return new Promise((resolve) => {
|
|
226
|
+
const failed = (e) => { try { logger.error(`idle: the notice "${text}" could not be shown: ${(e && e.message) || e}`); } catch (_) { /* nothing more */ } resolve(); };
|
|
227
|
+
try {
|
|
228
|
+
if (flash) return Promise.resolve(flash(req, res, kind, text)).then(() => resolve(), failed);
|
|
229
|
+
if (!res || typeof res.flash !== 'function') return failed(new Error('no flash helper (res.flash) and no `flash` option'));
|
|
230
|
+
return res.flash(kind, text, () => resolve());
|
|
231
|
+
} catch (e) { return failed(e); }
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** isBackground(req), with a throw counted as background: a request that cannot be judged does not extend a mode. */
|
|
236
|
+
function isBackgroundSafe(isBackground, logger, req) {
|
|
237
|
+
try { return !!isBackground(req); }
|
|
238
|
+
catch (e) {
|
|
239
|
+
try { logger.error(`idle: isBackground threw (${(e && e.message) || e}); the request is not counted as activity`); } catch (_) { /* nothing */ }
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
module.exports = { idleEnded, stampDue, readIdleMinutes, saveNow, writeMerged, settleUnwritten, markLoaded, loadedOf, mergeRequest, rowKey, stableKey, snapshot, restore, noticeOnce, isBackgroundSafe, MINUTE, ACTIVITY_STAMP_MAX_MS };
|
package/lib/scope/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
// The scope part: who a request works for and the scope seam (createTenancy); the write gate, authorship and the
|
|
4
|
-
// cross-tenant refusal handler (createWriteGate)
|
|
4
|
+
// cross-tenant refusal handler (createWriteGate); fleet view, the read-only session mode across every partner
|
|
5
|
+
// (createFleetView).
|
|
5
6
|
module.exports = {
|
|
6
7
|
...require('./tenancy'),
|
|
7
|
-
...require('./writeGate')
|
|
8
|
+
...require('./writeGate'),
|
|
9
|
+
createFleetView: require('./fleetView').createFleetView
|
|
8
10
|
};
|
package/lib/scope/tenancy.js
CHANGED
|
@@ -654,8 +654,8 @@ function createTenancy(o = {}) {
|
|
|
654
654
|
* id is not known yet, so the house's own operators are not narrowed by a cold cache. A failure to
|
|
655
655
|
* resolve it leaves the narrow answer (fail closed), never the wide one.
|
|
656
656
|
*/
|
|
657
|
-
function requestScope() {
|
|
658
|
-
|
|
657
|
+
function requestScope(opts) {
|
|
658
|
+
const scoped = (req, res, next) => {
|
|
659
659
|
const u = req.session && req.session.user;
|
|
660
660
|
const pending = [];
|
|
661
661
|
if (platformRequiresHouse && u && u.scope_kind === 'platform' && t.knownHouseId() == null) {
|
|
@@ -670,6 +670,16 @@ function createTenancy(o = {}) {
|
|
|
670
670
|
if (pending.length) return Promise.all(pending).then(() => establish(req, res, next)).catch(next);
|
|
671
671
|
return establish(req, res, next);
|
|
672
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)))));
|
|
673
683
|
}
|
|
674
684
|
|
|
675
685
|
function establish(req, res, next) {
|
package/lib/scope/writeGate.js
CHANGED
|
@@ -58,6 +58,10 @@ const COMPOSITE_TENANT_KEY = /_partner$/;
|
|
|
58
58
|
* @param {{warn: Function}} o.logger
|
|
59
59
|
* @param {(req: object) => boolean} [o.wantsJson] is this a fetch that wants JSON (default: X-Requested-With: fetch)
|
|
60
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.
|
|
61
65
|
*/
|
|
62
66
|
function createWriteGate(o = {}) {
|
|
63
67
|
const { tenancy, whileActing, messages, partnerById, logger, refusalView = 'errors/generic' } = o;
|
|
@@ -74,8 +78,22 @@ function createWriteGate(o = {}) {
|
|
|
74
78
|
throw new Error('createWriteGate: `houseReading` is required — a permission name, or null for none (a new app passes null)');
|
|
75
79
|
}
|
|
76
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;
|
|
77
94
|
if (!messages || typeof messages !== 'object') throw new Error('createWriteGate: `messages` is required');
|
|
78
|
-
const needed = ['unscopable', 'notActing', 'elsewhere'].concat(whileActing === 'readOnly' ? ['actingReadOnly'] : []
|
|
95
|
+
const needed = ['unscopable', 'notActing', 'elsewhere'].concat(whileActing === 'readOnly' ? ['actingReadOnly'] : [],
|
|
96
|
+
o.fleetView != null ? ['fleetView'] : []);
|
|
79
97
|
for (const k of needed) {
|
|
80
98
|
if (!(typeof messages[k] === 'string' || isFn(messages[k]))) {
|
|
81
99
|
throw new Error(`createWriteGate: messages.${k} is required (a sentence, or a function returning one)`);
|
|
@@ -118,6 +136,7 @@ function createWriteGate(o = {}) {
|
|
|
118
136
|
function createsLand(req) {
|
|
119
137
|
const ctx = tenancy.contextFor(req);
|
|
120
138
|
if (!ctx || ctx.partnerId == null) return false;
|
|
139
|
+
if (inFleetView(req)) return false;
|
|
121
140
|
return !(whileActing === 'readOnly' && actingElsewhere(req));
|
|
122
141
|
}
|
|
123
142
|
|
|
@@ -169,6 +188,7 @@ function createWriteGate(o = {}) {
|
|
|
169
188
|
const ctx = judged(req, 'writeScope');
|
|
170
189
|
if (!ctx || ctx.partnerId == null) return null;
|
|
171
190
|
if (req && whileActing === 'readOnly' && actingElsewhere(req)) return null;
|
|
191
|
+
if (inFleetView(req)) return null;
|
|
172
192
|
if (ctx.scope === 'partner') {
|
|
173
193
|
// SQLite: every row says partner 1 whoever wrote it — the hub's reason, kept: compare nothing there.
|
|
174
194
|
if (!tenancy.canHostTenants()) return runnerAt(ctx);
|
|
@@ -225,6 +245,9 @@ function createWriteGate(o = {}) {
|
|
|
225
245
|
* asPartner narrowing: inside one, a platform-only permission reads false and every request would look
|
|
226
246
|
* like the house reading. A request with no scope is refused, never widened.
|
|
227
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
|
+
*
|
|
228
251
|
* @param {object} req
|
|
229
252
|
* @param {(permission: string) => boolean} can the request's permission check (res.locals.can)
|
|
230
253
|
* @returns {Promise<number|null>}
|
|
@@ -234,7 +257,7 @@ function createWriteGate(o = {}) {
|
|
|
234
257
|
const ctx = tenancy.contextFor(req);
|
|
235
258
|
if (!ctx || (ctx.scope !== 'platform' && ctx.scope !== 'partner')) throw new Error('houseReadingOf: the request has no scope');
|
|
236
259
|
if (ctx.scope === 'partner') return null;
|
|
237
|
-
if (isFn(can) && can(houseReading) === true) return null;
|
|
260
|
+
if (isFn(can) && can(houseReading) === true && (fleetView === null || (await fleetView.isOn(req)) === true)) return null;
|
|
238
261
|
return tenancy.housePartnerId();
|
|
239
262
|
}
|
|
240
263
|
|
|
@@ -278,6 +301,8 @@ function createWriteGate(o = {}) {
|
|
|
278
301
|
out = { reason: 'unscopable', partner: null, message: say('unscopable', { req, rowPartnerId, what }) };
|
|
279
302
|
} else if (whileActing === 'readOnly' && acting) {
|
|
280
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 }) };
|
|
281
306
|
} else if (rowPartnerId == null || writeScope(req, rowPartnerId)) {
|
|
282
307
|
return null;
|
|
283
308
|
} else if (ctx.scope === 'platform') {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aria-framework/tenancy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
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
5
|
"license": "UNLICENSED",
|
|
6
6
|
"private": false,
|
|
@@ -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
|
+
<% } %>
|