@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,437 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FLEET VIEW: a session mode in which a house user at platform scope who holds the app's fleet permission reads every
|
|
3
|
+
* partner's rows, and can change nothing.
|
|
4
|
+
*
|
|
5
|
+
* const fleet = createFleetView({ permission: 'fleet.analyse', can, scopeOf, userIdOf, idleMinutes, now: Date.now,
|
|
6
|
+
* isBackground, audit, logger, home: '/', startPath: '/fleet-view/start', stopPath: '/fleet-view/stop',
|
|
7
|
+
* readOnlyExcept: ['POST /ask', 'POST /logout'] });
|
|
8
|
+
* app.use(session); app.use(scope); app.use(bodyParser); app.use(csrf);
|
|
9
|
+
* app.use(fleet.middleware); app.use(fleet.routes(express.Router)); then every router.
|
|
10
|
+
*
|
|
11
|
+
* The owner's decisions of 29 Nov 2026: normal view always after sign-in; a deliberate one-click switch; a banner on
|
|
12
|
+
* every page; read-only; it ends on leaving, on sign-out and after a configurable idle period; entering and leaving are
|
|
13
|
+
* audited; never on together with working in a partner.
|
|
14
|
+
*
|
|
15
|
+
* SELF-CONTAINED. Nothing here needs createTenancy or any other factory of this package: every answer is the app's
|
|
16
|
+
* (`can`, `scopeOf`, `userIdOf`, `idleMinutes`, `isBackground`, `audit`), passed in. Nothing is decided once and kept:
|
|
17
|
+
* each request asks the session and the app again.
|
|
18
|
+
*
|
|
19
|
+
* READ-ONLY IN ONE PLACE. While the mode is on, the middleware refuses every request whose method is not GET, HEAD or
|
|
20
|
+
* OPTIONS before any router runs, unless it is switching fleet view (start, stop) or one of the app's
|
|
21
|
+
* `readOnlyExcept` entries. `classify(method, target)` IS that decision, so an app's test walks its own route table
|
|
22
|
+
* through the same code.
|
|
23
|
+
*
|
|
24
|
+
* FEW SESSION WRITES, EACH SAVED AT ONCE. A request in flight that carries an unsaved change writes its whole stale
|
|
25
|
+
* copy at its end, over a stop or a sign-out that happened meanwhile. So this module writes the session only when it
|
|
26
|
+
* starts, stops or ends the mode, and for the activity stamp at most once a minute (never at 0 minutes); and it saves
|
|
27
|
+
* every such write before the request goes on (idle.saveNow).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
'use strict';
|
|
31
|
+
|
|
32
|
+
const idle = require('./idle');
|
|
33
|
+
|
|
34
|
+
const isFn = (f) => typeof f === 'function';
|
|
35
|
+
function fail(message) { throw new Error(`createFleetView: ${message}`); }
|
|
36
|
+
|
|
37
|
+
const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
38
|
+
// The reasons a stop is audited with. 'left' is the stop route; 'idle', 'permission', 'scope', 'user' and 'error' are
|
|
39
|
+
// the middleware's own ends (each told to the person once); 'acting' and 'signout' are the app's, through end().
|
|
40
|
+
const REASONS = new Set(['left', 'idle', 'permission', 'scope', 'user', 'error', 'acting', 'signout']);
|
|
41
|
+
// The flash kind of the one-time notice: one the framework's ui/flash partial renders (success, success_sticky, error,
|
|
42
|
+
// warning), and one that stays until dismissed.
|
|
43
|
+
const NOTICE_KIND = 'warning';
|
|
44
|
+
|
|
45
|
+
const DEFAULT_MESSAGES = {
|
|
46
|
+
idle: (minutes) => `Fleet view ended after ${minutes} minute${minutes === 1 ? '' : 's'} without activity.`,
|
|
47
|
+
permission: 'Fleet view ended because you no longer have the permission for it.',
|
|
48
|
+
scope: 'Fleet view ended because it is only available at platform scope, not while working in a partner.',
|
|
49
|
+
user: 'Fleet view ended because it was switched on by another account.',
|
|
50
|
+
error: 'Fleet view ended because it could not be checked. You can switch it on again.',
|
|
51
|
+
readOnly: 'Fleet view is read-only. Leave fleet view to change anything.',
|
|
52
|
+
notAllowed: 'Fleet view is not available to you here.'
|
|
53
|
+
};
|
|
54
|
+
const text = (m, ...a) => (isFn(m) ? m(...a) : m);
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* A return address this app may send the browser to: a local path ONLY. "/x" and "/x?y" pass; an absolute URL, a
|
|
58
|
+
* scheme ("javascript:"), "//host", "/\host", any backslash, any control character (DEL included) or space, and
|
|
59
|
+
* anything over 2048 characters do not (the caller falls back to `home`).
|
|
60
|
+
*/
|
|
61
|
+
function isReturnPath(p) {
|
|
62
|
+
return typeof p === 'string' && p.length <= 2048 && /^\/(?![/\\])/.test(p) && !/[\\\x00-\x20\x7f]/.test(p);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A PLAIN REQUEST TARGET: "/" then only RFC 3986 path and query characters (unreserved, sub-delims, ":", "@", "/",
|
|
67
|
+
* "?", and "%" followed by two hex digits). No "#", no backslash, no space or control character, nothing outside ASCII.
|
|
68
|
+
* No honest client sends anything else, and for exactly these targets Express's own parser (parseurl's fast path, which
|
|
69
|
+
* hands any target with "#", whitespace or similar to url.parse) answers pathname = the part before the first "?".
|
|
70
|
+
*/
|
|
71
|
+
const PLAIN_TARGET = /^\/(?:[A-Za-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})*$/;
|
|
72
|
+
const isPlainTarget = (t) => typeof t === 'string' && t.length <= 8192 && PLAIN_TARGET.test(t);
|
|
73
|
+
|
|
74
|
+
// An option path (home, startPath, stopPath): plain, no query.
|
|
75
|
+
const isPlainPath = (p) => isPlainTarget(p) && !p.includes('?') && !p.includes('//');
|
|
76
|
+
|
|
77
|
+
// readOnlyExcept: a literal segment, a parameter segment; and what a parameter matches in a request: a conservative id
|
|
78
|
+
// (letters, digits, "_" and "-", at most 64), or a route table's own ":name" (so a route-table walk classifies alike).
|
|
79
|
+
const LITERAL_SEG = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/;
|
|
80
|
+
const PARAM_SEG = /^:[A-Za-z_][A-Za-z0-9_]*$/;
|
|
81
|
+
const ID_VALUE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
82
|
+
|
|
83
|
+
/** One `readOnlyExcept` entry: "METHOD /literal/or/:name/segments", a non-read method. Anything else is refused. */
|
|
84
|
+
function parseEntry(entry) {
|
|
85
|
+
const m = typeof entry === 'string' && entry.match(/^([A-Z]+) (\/[^ ]*)$/);
|
|
86
|
+
if (!m) fail(`readOnlyExcept: ${JSON.stringify(entry)} is not "METHOD /path"`);
|
|
87
|
+
const [, method, p] = m;
|
|
88
|
+
if (READ_METHODS.has(method)) fail(`readOnlyExcept: ${JSON.stringify(entry)} lists a read method, which is always allowed`);
|
|
89
|
+
const segs = p.split('/');
|
|
90
|
+
const ok = p === '/' || segs.slice(1).every((s) => (LITERAL_SEG.test(s) && s !== '.' && s !== '..') || PARAM_SEG.test(s));
|
|
91
|
+
if (!ok) fail(`readOnlyExcept: ${JSON.stringify(entry)}: the path must be literal segments (letters, digits, . _ ~ -) and :name segments, no query, wildcard, empty, dot or encoded segment`);
|
|
92
|
+
return { entry, method, segs };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function matches(e, method, segs) {
|
|
96
|
+
if (e.method !== method || e.segs.length !== segs.length) return false;
|
|
97
|
+
for (let i = 0; i < segs.length; i++) {
|
|
98
|
+
const want = e.segs[i];
|
|
99
|
+
if (PARAM_SEG.test(want)) { if (!(ID_VALUE.test(segs[i]) || PARAM_SEG.test(segs[i]))) return false; }
|
|
100
|
+
else if (want !== segs[i]) return false;
|
|
101
|
+
}
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* DOES EXPRESS DISPATCH THIS REQUEST ON THE PATH WE JUDGED? At the middleware's mount, Express routes on
|
|
107
|
+
* `req.baseUrl + req.path` (req.path is parseurl's pathname of req.url). For a plain target that is the original
|
|
108
|
+
* pathname, unless something before us rewrote req.url. One artifact is Express's own: a request for exactly the mount
|
|
109
|
+
* path ("/admin") arrives at the mount as req.path "/".
|
|
110
|
+
*/
|
|
111
|
+
function dispatchAgrees(req, pathname) {
|
|
112
|
+
if (typeof req.path !== 'string') return false;
|
|
113
|
+
const base = typeof req.baseUrl === 'string' ? req.baseUrl : '';
|
|
114
|
+
const dispatched = base + (req.path === '/' && base && pathname === base ? '' : req.path);
|
|
115
|
+
return dispatched === pathname;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* @param {object} o
|
|
120
|
+
* @param {string} o.permission REQUIRED: the app's fleet permission name
|
|
121
|
+
* @param {(req, res, permission) => boolean|Promise<boolean>} o.can REQUIRED: the app's own check; only `true` counts
|
|
122
|
+
* @param {(req) => 'platform'|'partner'|null|Promise<…>} o.scopeOf REQUIRED: the request's scope as the app decides
|
|
123
|
+
* it; a house user acting as a partner is 'partner'
|
|
124
|
+
* @param {(req) => string|number|null} o.userIdOf REQUIRED: the signed-in user's stable id, or null
|
|
125
|
+
* @param {() => number|Promise<number>} o.idleMinutes REQUIRED: the app's setting, a whole number; 0 = no idle end
|
|
126
|
+
* @param {() => number} o.now REQUIRED: the clock (ms)
|
|
127
|
+
* @param {(req) => boolean} o.isBackground REQUIRED: a request that does NOT count as activity (live streams, polls)
|
|
128
|
+
* @param {(req, action, opts) => any} o.audit REQUIRED: the app's audit helper (actingRoutes' shape)
|
|
129
|
+
* @param {{warn: Function, error: Function}} o.logger REQUIRED
|
|
130
|
+
* @param {string[]} o.readOnlyExcept REQUIRED (may be empty): "METHOD /path" entries allowed while the mode is on
|
|
131
|
+
* @param {string} o.home REQUIRED: a local path, where a start without a good return address and every stop go
|
|
132
|
+
* @param {string} o.startPath REQUIRED: the start route's full local path (always allowed through, POST only)
|
|
133
|
+
* @param {string} o.stopPath REQUIRED: the stop route's full local path (always allowed through, POST only)
|
|
134
|
+
* @param {(req, res, kind, text) => any} [o.flash] default res.flash(kind, text, callback)
|
|
135
|
+
* @param {(req) => boolean} [o.wantsJson] default: X-Requested-With: fetch, or an Accept of JSON without HTML
|
|
136
|
+
* @param {string} [o.refusalView='errors/generic'] rendered with { title, message } for a refused page request
|
|
137
|
+
* @param {object} [o.messages] idle(minutes), permission, scope, user, error, readOnly, notAllowed
|
|
138
|
+
*/
|
|
139
|
+
function createFleetView(options) {
|
|
140
|
+
const o = options || {};
|
|
141
|
+
if (typeof o.permission !== 'string' || !o.permission) fail('permission is required: the name of the app\'s fleet permission');
|
|
142
|
+
for (const k of ['can', 'scopeOf', 'userIdOf', 'idleMinutes', 'now', 'isBackground', 'audit']) {
|
|
143
|
+
if (!isFn(o[k])) fail(`${k} is required (a function; see the README, "Fleet view")`);
|
|
144
|
+
}
|
|
145
|
+
if (!o.logger || !isFn(o.logger.warn) || !isFn(o.logger.error)) fail('logger is required (warn and error)');
|
|
146
|
+
if (!Array.isArray(o.readOnlyExcept)) fail('readOnlyExcept is required: the list of "METHOD /path" requests allowed in fleet view ([] for none)');
|
|
147
|
+
for (const k of ['home', 'startPath', 'stopPath']) if (!isPlainPath(o[k])) fail(`${k} is required: a local path ("/fleet-view/stop"), with no query`);
|
|
148
|
+
if (o.startPath === o.stopPath) fail('startPath and stopPath must differ');
|
|
149
|
+
if (o.flash != null && !isFn(o.flash)) fail('flash must be a function (req, res, kind, text), which may return a promise');
|
|
150
|
+
if (o.wantsJson != null && !isFn(o.wantsJson)) fail('wantsJson must be a function (req) => boolean');
|
|
151
|
+
if (o.refusalView != null && (typeof o.refusalView !== 'string' || !o.refusalView)) fail('refusalView must be a view name');
|
|
152
|
+
|
|
153
|
+
const { permission, can, scopeOf, userIdOf, idleMinutes, now, isBackground, audit, logger, home, startPath, stopPath } = o;
|
|
154
|
+
const messages = { ...DEFAULT_MESSAGES, ...(o.messages || {}) };
|
|
155
|
+
const refusalView = o.refusalView || 'errors/generic';
|
|
156
|
+
const wantsJson = o.wantsJson || ((req) => {
|
|
157
|
+
const h = (n) => (req && isFn(req.get) ? req.get(n) : (req && req.headers && req.headers[n.toLowerCase()])) || '';
|
|
158
|
+
const accept = String(h('Accept'));
|
|
159
|
+
return h('X-Requested-With') === 'fetch' || (/application\/json/i.test(accept) && !/text\/html/i.test(accept));
|
|
160
|
+
});
|
|
161
|
+
const allowed = o.readOnlyExcept.map(parseEntry);
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* WOULD THE GUARD LET THIS THROUGH WHILE THE MODE IS ON? The guard calls exactly this, with the request's method and
|
|
165
|
+
* its RAW target (req.originalUrl, as the client sent it, at any mount). 'read' (GET, HEAD, OPTIONS), 'start' and
|
|
166
|
+
* 'leave' (POST to startPath / stopPath), 'listed' (a readOnlyExcept entry) are let through; 'refused' is refused,
|
|
167
|
+
* and so is every target that is not plain (see PLAIN_TARGET). The method is compared upper-cased (a route table's
|
|
168
|
+
* keys are lower-case); the path is the target up to "?", exactly as sent.
|
|
169
|
+
*
|
|
170
|
+
* @param {string} method
|
|
171
|
+
* @param {string} target the raw request target, or a route table's full path pattern
|
|
172
|
+
* @returns {'read'|'start'|'leave'|'listed'|'refused'}
|
|
173
|
+
*/
|
|
174
|
+
function classify(method, target) {
|
|
175
|
+
const m = String(method || '').toUpperCase();
|
|
176
|
+
if (READ_METHODS.has(m)) return 'read';
|
|
177
|
+
const t = target == null ? '' : String(target);
|
|
178
|
+
if (!isPlainTarget(t)) return 'refused';
|
|
179
|
+
const p = t.split('?')[0];
|
|
180
|
+
if (m === 'POST' && p === startPath) return 'start';
|
|
181
|
+
if (m === 'POST' && p === stopPath) return 'leave';
|
|
182
|
+
const segs = p.split('/');
|
|
183
|
+
return allowed.some((e) => matches(e, m, segs)) ? 'listed' : 'refused';
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const off = (reason, minutes) => ({ on: false, carried: true, reason, minutes });
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The signed-in user's id, SYNCHRONOUSLY (it is asked of a row read back inside the store's callback too, where
|
|
190
|
+
* nothing may be awaited). A promise for an answer is refused: it throws, which every caller treats as closed.
|
|
191
|
+
*/
|
|
192
|
+
function userOf(req) {
|
|
193
|
+
const id = userIdOf(req);
|
|
194
|
+
if (id && typeof id.then === 'function') throw new Error('userIdOf must answer synchronously (an id or null), not a promise');
|
|
195
|
+
return id;
|
|
196
|
+
}
|
|
197
|
+
/** The same question of a row read back from the store: this request, with that row as its session. */
|
|
198
|
+
const rowUser = (req, row) => userOf(Object.create(req, { session: { value: row } }));
|
|
199
|
+
|
|
200
|
+
/** The verdict for one request: { on, carried, reason?, minutes? }. Never throws: a throw from the app is 'error'. */
|
|
201
|
+
async function judge(req, res) {
|
|
202
|
+
const s = req && req.session;
|
|
203
|
+
if (!s || s.fleetViewSince == null) return { on: false, carried: false };
|
|
204
|
+
try {
|
|
205
|
+
const uid = userOf(req);
|
|
206
|
+
if (uid == null || s.fleetViewUser == null || String(uid) !== String(s.fleetViewUser)) return off('user');
|
|
207
|
+
if ((await scopeOf(req)) !== 'platform' || s.actingPartnerId != null) return off('scope');
|
|
208
|
+
if ((await can(req, res, permission)) !== true) return off('permission');
|
|
209
|
+
const minutes = await idle.readIdleMinutes(idleMinutes);
|
|
210
|
+
const last = Number.isFinite(s.fleetViewLastActive) ? s.fleetViewLastActive : s.fleetViewSince;
|
|
211
|
+
if (idle.idleEnded(last, minutes, now())) return off('idle', minutes);
|
|
212
|
+
return { on: true, carried: true, minutes, last };
|
|
213
|
+
} catch (e) {
|
|
214
|
+
logger.error(`fleet view: the check failed (${(e && e.message) || e}); the mode is off for this request and ends`);
|
|
215
|
+
return off('error');
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// The middleware's verdict for THIS request object, so a later caller on the same request (the write gate's house
|
|
220
|
+
// reading) gets the same answer without the response. Keyed by the request: nothing outlives it.
|
|
221
|
+
const verdicts = new WeakMap();
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* IS FLEET VIEW ON FOR THIS REQUEST? True only when all hold: the session carries the mode, switched on by the user
|
|
225
|
+
* `userIdOf(req)` names now; `scopeOf(req)` is 'platform' and the session carries no acting flag;
|
|
226
|
+
* `can(req, res, permission)` answers exactly true; and the idle period has not run out. Any throw is false.
|
|
227
|
+
*
|
|
228
|
+
* @returns {Promise<boolean>}
|
|
229
|
+
*/
|
|
230
|
+
async function isOn(req, res) {
|
|
231
|
+
if (req && verdicts.has(req)) return verdicts.get(req);
|
|
232
|
+
return (await judge(req, res)).on;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** MAY THIS PERSON SWITCH IT ON NOW: signed in (with an id), platform scope, not acting, holding the permission. */
|
|
236
|
+
async function mayStart(req, res) {
|
|
237
|
+
const s = req && req.session;
|
|
238
|
+
if (!s || !s.user || s.actingPartnerId != null) return false;
|
|
239
|
+
try {
|
|
240
|
+
return userOf(req) != null && (await scopeOf(req)) === 'platform' && (await can(req, res, permission)) === true;
|
|
241
|
+
} catch (e) {
|
|
242
|
+
logger.error(`fleet view: could not decide whether the switch is offered (${(e && e.message) || e}); it is not`);
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Clears the mode and audits the stop (isolated: a failed audit is logged and keeps nothing on). Not saved here. */
|
|
248
|
+
async function clear(req, reason, minutes) {
|
|
249
|
+
const s = req && req.session;
|
|
250
|
+
if (!s || s.fleetViewSince == null) return false;
|
|
251
|
+
delete s.fleetViewSince;
|
|
252
|
+
delete s.fleetViewLastActive;
|
|
253
|
+
delete s.fleetViewUser;
|
|
254
|
+
const detail = minutes != null ? { reason, minutes } : { reason };
|
|
255
|
+
try { await audit(req, 'fleet_view.stop', { detail }); }
|
|
256
|
+
catch (e) { logger.error(`fleet view: the stop (${reason}) could not be audited: ${(e && e.message) || e}`); }
|
|
257
|
+
return true;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Save now; a failed save is logged (express-session still saves the changed session at the end). */
|
|
261
|
+
async function saved(req, what) {
|
|
262
|
+
try { await idle.saveNow(req); }
|
|
263
|
+
catch (e) { logger.error(`fleet view: the session could not be saved after ${what}: ${(e && e.message) || e}`); }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* End the mode from the app's own code: when it starts working in a partner ('acting') or signs the person out
|
|
268
|
+
* ('signout', called BEFORE the session is destroyed, so the row is written). Clears the fields, audits the stop with
|
|
269
|
+
* the reason, saves the session; tells nobody. A session not in the mode: nothing, false.
|
|
270
|
+
*
|
|
271
|
+
* @returns {Promise<boolean>} whether the mode was on
|
|
272
|
+
*/
|
|
273
|
+
async function end(req, reason) {
|
|
274
|
+
if (!REASONS.has(reason)) throw new Error(`fleetView.end: reason must be one of ${[...REASONS].join(', ')}, not ${String(reason)}`);
|
|
275
|
+
const was = await clear(req, reason);
|
|
276
|
+
if (was) await saved(req, `ending fleet view (${reason})`);
|
|
277
|
+
return was;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Writes are refused for this request: the session carries the mode (the middleware has cleared it when it is not on). */
|
|
281
|
+
function writesRefused(req) {
|
|
282
|
+
const s = req && req.session;
|
|
283
|
+
return !!(s && s.fleetViewSince != null);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* An ordinary request's write (idle.writeMerged): the row read back, plus this request's own changes, plus this
|
|
288
|
+
* package's change, saved in the read's callback. Anything else writes nothing and is logged ('gone': signed out
|
|
289
|
+
* meanwhile; 'changed': the row no longer holds this mode (left, another start, another user); 'unreadable': no store
|
|
290
|
+
* to ask, or it failed; 'unmarked': fleet.loaded is not mounted). Each is judged again by the next request.
|
|
291
|
+
*/
|
|
292
|
+
async function written(req, stillOk, change, what) {
|
|
293
|
+
try {
|
|
294
|
+
const r = await idle.writeMerged(req, stillOk, change);
|
|
295
|
+
if (r.outcome !== 'saved') logger.warn(`fleet view: ${what} not written: the session's row is ${r.outcome} (re-read before the save)`);
|
|
296
|
+
return r;
|
|
297
|
+
} catch (e) {
|
|
298
|
+
logger.error(`fleet view: the session could not be saved after ${what}: ${(e && e.message) || e}`);
|
|
299
|
+
return { outcome: 'failed', row: null };
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const OWN_KEYS = ['fleetViewSince', 'fleetViewLastActive', 'fleetViewUser'];
|
|
304
|
+
const clearOwn = (t) => { for (const k of OWN_KEYS) delete t[k]; };
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* THE AUTOMATIC END (idle, permission, scope, user, error). The notice goes into the session in memory first (an app's
|
|
308
|
+
* flash may be async); then the row is re-read and, if it still holds this mode (the same start), the row plus this
|
|
309
|
+
* request's changes minus the mode is saved, in the read's callback; the stop is audited after the save. Otherwise
|
|
310
|
+
* nothing is written or audited (a sign-out or a stop that happened meanwhile stands, and the next request judges
|
|
311
|
+
* again), and the session in memory is settled so that express-session's own end-of-request save cannot bring the
|
|
312
|
+
* mode back (idle.settleUnwritten).
|
|
313
|
+
*/
|
|
314
|
+
async function autoEnd(req, res, reason, minutes) {
|
|
315
|
+
const s = req.session;
|
|
316
|
+
const pre = idle.snapshot(s);
|
|
317
|
+
const since = s.fleetViewSince;
|
|
318
|
+
await idle.noticeOnce(o.flash, logger, req, res, NOTICE_KIND, text(messages[reason], minutes));
|
|
319
|
+
const r = await written(req, (row) => row.fleetViewSince === since, clearOwn, `ending fleet view (${reason})`);
|
|
320
|
+
if (r.outcome !== 'saved' && r.outcome !== 'failed') { idle.settleUnwritten(req, pre, r.row, OWN_KEYS, r.outcome); return; }
|
|
321
|
+
if (r.outcome === 'failed') clearOwn(s);
|
|
322
|
+
const detail = minutes != null ? { reason, minutes } : { reason };
|
|
323
|
+
try { await audit(req, 'fleet_view.stop', { detail }); }
|
|
324
|
+
catch (e) { logger.error(`fleet view: the stop (${reason}) could not be audited: ${(e && e.message) || e}`); }
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// A refusal is always answered here, never passed on: the page view when the app can render it, else the sentence as
|
|
328
|
+
// text (Express 5's render throws at once when no view engine is set; that throw is caught here too).
|
|
329
|
+
function refuse(req, res, message, status = 403) {
|
|
330
|
+
if (wantsJson(req)) return res.status(status).json({ ok: false, type: 'error', code: 'FLEET_VIEW_READ_ONLY', message });
|
|
331
|
+
res.status(status);
|
|
332
|
+
const plain = () => res.type('text/plain').send(message);
|
|
333
|
+
if (!isFn(res.render)) return plain();
|
|
334
|
+
try {
|
|
335
|
+
return res.render(refusalView, { title: 'Read-only', message }, (e, html) => (e ? plain() : res.send(html)));
|
|
336
|
+
} catch (e) {
|
|
337
|
+
return plain();
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function middleware(req, res, next) {
|
|
342
|
+
try {
|
|
343
|
+
// Without the copy of the session as loaded this package cannot write a session safely: refused loudly, for the
|
|
344
|
+
// sessions that carry the mode only (every other request is untouched).
|
|
345
|
+
if (req.session && req.session.fleetViewSince != null && !idle.loadedOf(req)) {
|
|
346
|
+
return next(new Error('fleet view: mount fleet.loaded directly after the session middleware (the session as loaded is needed before this package writes it)'));
|
|
347
|
+
}
|
|
348
|
+
const v = await judge(req, res);
|
|
349
|
+
// `reading`: what this request reads by (and what the banner shows). The guard below follows `v.on`, the mode as
|
|
350
|
+
// the request found it, so a stamp that could not be written makes the request read the normal view and still
|
|
351
|
+
// refuses its writes: closed on both sides. A stamp that WAS written reads by the row read back, which still holds
|
|
352
|
+
// the mode (the same start, the same user), whatever else in it changed.
|
|
353
|
+
let reading = v.on;
|
|
354
|
+
if (v.carried && !v.on) {
|
|
355
|
+
await autoEnd(req, res, v.reason, v.minutes);
|
|
356
|
+
} else if (v.on && !idle.isBackgroundSafe(isBackground, logger, req) && idle.stampDue(v.last, v.minutes, now())) {
|
|
357
|
+
const s = req.session;
|
|
358
|
+
const pre = idle.snapshot(s);
|
|
359
|
+
const since = s.fleetViewSince; const owner = s.fleetViewUser; const t = now();
|
|
360
|
+
// The row must still hold THIS mode: the same start, switched on by the same user, and signed in as that user.
|
|
361
|
+
const r = await written(req, (row) => row.fleetViewSince === since && String(row.fleetViewUser) === String(owner)
|
|
362
|
+
&& rowUser(req, row) != null && String(rowUser(req, row)) === String(owner),
|
|
363
|
+
(target) => { target.fleetViewLastActive = t; }, 'the activity stamp');
|
|
364
|
+
if (r.outcome !== 'saved') {
|
|
365
|
+
reading = false;
|
|
366
|
+
if (r.outcome !== 'failed') idle.settleUnwritten(req, pre, r.row, OWN_KEYS, r.outcome);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
verdicts.set(req, reading);
|
|
370
|
+
const canStart = !v.on && await mayStart(req, res);
|
|
371
|
+
const here = req.method === 'GET' && isReturnPath(req.originalUrl) ? req.originalUrl : null;
|
|
372
|
+
res.locals.fleetView = { on: reading, canStart, startPath, stopPath, returnTo: here };
|
|
373
|
+
// ── THE READ-ONLY GUARD ─────────────────────────────────────────────────────────────────────────────────────
|
|
374
|
+
if (v.on) {
|
|
375
|
+
const target = String(req.originalUrl != null ? req.originalUrl : req.url);
|
|
376
|
+
const c = classify(req.method, target);
|
|
377
|
+
const rewritten = c !== 'read' && c !== 'refused' && !dispatchAgrees(req, target.split('?')[0]);
|
|
378
|
+
if (c === 'refused' || rewritten) {
|
|
379
|
+
const u = req.session.user;
|
|
380
|
+
logger.warn(`fleet view: user ${u ? u.id : '(none)'}: refused ${req.method} ${JSON.stringify(target.slice(0, 300))} (read-only${rewritten ? ', dispatched on another path' : ''})`);
|
|
381
|
+
return refuse(req, res, text(messages.readOnly));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return next();
|
|
385
|
+
} catch (e) { return next(e); }
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const backOf = (req) => {
|
|
389
|
+
const r = req.body && req.body.returnTo;
|
|
390
|
+
return isReturnPath(r) ? r : home;
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/** The start and stop routes, on a router from the app's `Router` (express.Router), mounted at the app's root. */
|
|
394
|
+
function routes(Router) {
|
|
395
|
+
if (!isFn(Router)) throw new Error('fleetView.routes: Router is required (express.Router): this package does not load express itself');
|
|
396
|
+
const router = Router();
|
|
397
|
+
router.post(startPath, (req, res, next) => {
|
|
398
|
+
(async () => {
|
|
399
|
+
if (!(await mayStart(req, res))) {
|
|
400
|
+
const u = req.session && req.session.user;
|
|
401
|
+
logger.warn(`fleet view: user ${u ? u.id : '(none)'} may not switch it on (user, scope, acting or permission)`);
|
|
402
|
+
return refuse(req, res, text(messages.notAllowed));
|
|
403
|
+
}
|
|
404
|
+
const s = req.session;
|
|
405
|
+
// Already on (a double click, a second tab): nothing changes, nothing is audited, back to the page.
|
|
406
|
+
if (s.fleetViewSince != null) return res.redirect(backOf(req));
|
|
407
|
+
// AUDITED BEFORE THE SWITCH, and a failed audit stops it: the mode is never on without its row.
|
|
408
|
+
await audit(req, 'fleet_view.start', { detail: {} });
|
|
409
|
+
const t = now();
|
|
410
|
+
s.fleetViewSince = t;
|
|
411
|
+
s.fleetViewLastActive = t;
|
|
412
|
+
s.fleetViewUser = userOf(req);
|
|
413
|
+
await idle.saveNow(req);
|
|
414
|
+
return res.redirect(backOf(req));
|
|
415
|
+
})().catch(next);
|
|
416
|
+
});
|
|
417
|
+
// SESSION-GATED, NOT PERMISSION-GATED: it is the only way out, so it must not depend on what may have been lost.
|
|
418
|
+
router.post(stopPath, (req, res, next) => {
|
|
419
|
+
(async () => {
|
|
420
|
+
if (await clear(req, 'left')) await idle.saveNow(req);
|
|
421
|
+
return res.redirect(home);
|
|
422
|
+
})().catch(next);
|
|
423
|
+
});
|
|
424
|
+
return router;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Mounted DIRECTLY after the session middleware (before any middleware that changes the session): keeps a copy of
|
|
429
|
+
* the session as loaded, for a request whose session carries the mode (idle.markLoaded). The writes this package
|
|
430
|
+
* makes on an ordinary request lay this request's own changes over the row the store holds, and need that copy.
|
|
431
|
+
*/
|
|
432
|
+
function loaded(req, res, next) { idle.markLoaded(req); next(); }
|
|
433
|
+
|
|
434
|
+
return { isOn, middleware, loaded, routes, classify, end, writesRefused, permission, startPath, stopPath };
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
module.exports = { createFleetView, isReturnPath, isPlainTarget };
|