@aria-framework/tenancy 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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 };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
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); fleet view, the read-only session mode across every partner
5
+ // (createFleetView).
6
+ module.exports = {
7
+ ...require('./tenancy'),
8
+ ...require('./writeGate'),
9
+ createFleetView: require('./fleetView').createFleetView
10
+ };