@aria-framework/customer 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 +149 -2
- package/README.md +292 -11
- package/assets/visit.js +86 -0
- package/index.js +7 -5
- package/lib/visits/index.js +28 -0
- package/lib/visits/options.js +183 -0
- package/lib/visits/record.js +76 -0
- package/lib/visits/rules.js +290 -0
- package/lib/visits/visits.js +1022 -0
- package/package.json +16 -4
- package/views/customer-visit-banner.ejs +20 -0
- package/views/customer-visit-ended.ejs +11 -0
|
@@ -0,0 +1,1022 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createVisits: WORKING IN A CUSTOMER, as one factory an app calls once with its own lists and lookups (README,
|
|
3
|
+
* "Visits"; "Customer-driven apps" v7, CD-14 to CD-25, CD-44, CD-45, CD-50, CD-60). The rules are rules.js; the two
|
|
4
|
+
* audit rows record.js; the options options.js.
|
|
5
|
+
*
|
|
6
|
+
* visits.loaded directly after the session middleware (beside fleet view's `loaded`)
|
|
7
|
+
* visits.track after the scope and fleet view's middleware, BEFORE fleet view's routes and every router
|
|
8
|
+
* visits.gate(kind) in front of each gated mount; visits.requirePermission(...) on its routes
|
|
9
|
+
* visits.routes(R) POST <mountPath>/:cus/work-in, POST <mountPath>/leave
|
|
10
|
+
* visits.entry(req, cus), visits.end(req, why), visits.endFirst(why), visits.recordEnded(session, why)
|
|
11
|
+
* visits.forget(cus), visits.current(req), visits.classify(method, path), visits.stampOf(req)
|
|
12
|
+
*
|
|
13
|
+
* THE SESSION. One key, VISIT_KEY, a session mode of @aria-framework/tenancy (createSessionMode) with its save guard
|
|
14
|
+
* (guardSave, tenancy 0.5.0): a slow request in flight while Leave runs cannot write the visit back (CD-23). Every end
|
|
15
|
+
* is written through the mode (re-read, compare, write): its stop row is written only when THIS request's write removed
|
|
16
|
+
* the visit from the stored session, and, within this process, only once per visit (a burst of requests ending the same
|
|
17
|
+
* visit at once writes one row). Across processes a duplicate stop row is possible; the reader takes the earliest.
|
|
18
|
+
*
|
|
19
|
+
* THE ROLE IS JUDGED AT HOME (CD-19). The app's `roleCan(user, perm)` is called only inside
|
|
20
|
+
* runWithTenant({ scope: 'partner', partnerId: user.partner_id }), so a house person working in partner P is judged by
|
|
21
|
+
* the house's role of that name, never P's.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
'use strict';
|
|
25
|
+
|
|
26
|
+
const crypto = require('crypto');
|
|
27
|
+
const tenancyPackage = require('@aria-framework/tenancy');
|
|
28
|
+
const R = require('./rules');
|
|
29
|
+
const record = require('./record');
|
|
30
|
+
const { checkOptions, isLocalPath, under } = require('./options');
|
|
31
|
+
|
|
32
|
+
const READ = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
33
|
+
// A plain request target (fleet view's rule): "/" then RFC 3986 path and query characters only.
|
|
34
|
+
const PLAIN_TARGET = /^\/(?:[A-Za-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9A-Fa-f]{2})*$/;
|
|
35
|
+
const ID_VALUE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
36
|
+
const PARAM = /^:[A-Za-z_][A-Za-z0-9_]*$/;
|
|
37
|
+
/** The bound on the fit memo's entries (each a visit id). */
|
|
38
|
+
const FIT_MAX = 5000;
|
|
39
|
+
|
|
40
|
+
const DEFAULT_MESSAGES = {
|
|
41
|
+
outside: 'This page is open only while you work in a customer.',
|
|
42
|
+
lookOnly: (name) => `Look only: you cannot make changes while working in ${name}.`,
|
|
43
|
+
closed: (name) => `${name} does not let you into this kind of data now.`,
|
|
44
|
+
permission: 'Your role does not allow this.',
|
|
45
|
+
unlisted: 'This is not open to you while you work in a customer.',
|
|
46
|
+
leaveFirst: (name) => `Leave ${name} first.`,
|
|
47
|
+
busy: 'Another visit started at the same moment (in another tab). Look at the page you are on, then try again.',
|
|
48
|
+
signedOut: 'You were signed out, or signed in again, in another tab. Look at the page you are on, then try again.',
|
|
49
|
+
placeChanged: 'You started or stopped working in a partner at the same moment (in another tab). Look at the page you are on, then try again.',
|
|
50
|
+
left: (name) => `You left ${name}.`,
|
|
51
|
+
started: (name, words, level) => `You are working in ${name} for ${words} (${level}).`,
|
|
52
|
+
byGrant: (name, level) => `You are working in ${name} until the customer's let-in ends (${level}).`,
|
|
53
|
+
lowered: 'The level is the most this customer and your role allow.',
|
|
54
|
+
refusal: {
|
|
55
|
+
'fleet-view': 'Leave fleet view first: a customer is never worked in from fleet view.',
|
|
56
|
+
permission: 'Your role can see customers but not work in them.',
|
|
57
|
+
'not-found': 'Not found.',
|
|
58
|
+
inactive: 'This customer is not active.',
|
|
59
|
+
closed: 'This customer has closed support access to you (Never). Only its people can change that.',
|
|
60
|
+
role: 'Your role lets you into none of the data this customer opens to you.',
|
|
61
|
+
waiting: 'Your request to come in is waiting for an answer.',
|
|
62
|
+
'not-allowed': 'This customer lets you in only when its people say so: ask to come in.'
|
|
63
|
+
},
|
|
64
|
+
invalid: {
|
|
65
|
+
reason: 'Give a reason for working in this customer.',
|
|
66
|
+
'reason-long': `The reason is too long: at most ${R.REASON_MAX} characters.`,
|
|
67
|
+
level: 'Choose look only or make changes.'
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const text = (m, ...a) => (typeof m === 'function' ? m(...a) : m);
|
|
71
|
+
const isFn = (f) => typeof f === 'function';
|
|
72
|
+
|
|
73
|
+
/** A stable text of a value (sorted keys), to compare a record read back with the one in hand. */
|
|
74
|
+
function stable(v) {
|
|
75
|
+
if (v === null || typeof v !== 'object') return JSON.stringify(v === undefined ? null : v);
|
|
76
|
+
if (Array.isArray(v)) return `[${v.map(stable).join(',')}]`;
|
|
77
|
+
return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(',')}}`;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
81
|
+
/**
|
|
82
|
+
* WHAT A NOTICE ADDED to one session key (review round 4): `told` is the key after the notice, `pre` before it. An
|
|
83
|
+
* array: the elements appended (a flash appends); an object: the same, key by key (connect-flash's `{ kind: [text] }`);
|
|
84
|
+
* anything else: the new value when it differs (undefined when it does not).
|
|
85
|
+
*/
|
|
86
|
+
function addedBy(pre, told) {
|
|
87
|
+
if (Array.isArray(told)) return told.slice(Array.isArray(pre) ? pre.length : 0);
|
|
88
|
+
if (isPlainObject(told)) {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const k of Object.keys(told)) {
|
|
91
|
+
const a = addedBy(isPlainObject(pre) ? pre[k] : undefined, told[k]);
|
|
92
|
+
if (a === undefined || (Array.isArray(a) && a.length === 0) || (isPlainObject(a) && Object.keys(a).length === 0)) continue;
|
|
93
|
+
out[k] = a;
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
return stable(pre) === stable(told) ? undefined : told;
|
|
98
|
+
}
|
|
99
|
+
/** `value` without what `added` (addedBy) names: one occurrence of each element, key by key; an emptied key removed. */
|
|
100
|
+
function takeOut(value, added) {
|
|
101
|
+
if (Array.isArray(added)) {
|
|
102
|
+
if (!Array.isArray(value)) return value;
|
|
103
|
+
const rest = value.slice();
|
|
104
|
+
for (const x of added) { const i = rest.findIndex((y) => stable(y) === stable(x)); if (i >= 0) rest.splice(i, 1); }
|
|
105
|
+
return rest;
|
|
106
|
+
}
|
|
107
|
+
if (isPlainObject(added)) {
|
|
108
|
+
if (!isPlainObject(value)) return value;
|
|
109
|
+
const out = { ...value };
|
|
110
|
+
for (const k of Object.keys(added)) {
|
|
111
|
+
if (!(k in out)) continue;
|
|
112
|
+
const v = takeOut(out[k], added[k]);
|
|
113
|
+
if (v === undefined || (Array.isArray(v) && v.length === 0) || (isPlainObject(v) && Object.keys(v).length === 0)) delete out[k]; else out[k] = v;
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
if (added === undefined) return value;
|
|
118
|
+
return stable(value) === stable(added) ? undefined : value;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function createVisits(options) {
|
|
122
|
+
const c = checkOptions(options);
|
|
123
|
+
const { tenancy, db, logger, kindKeys } = c;
|
|
124
|
+
const messages = { ...DEFAULT_MESSAGES, ...(c.messages || {}) };
|
|
125
|
+
messages.refusal = { ...DEFAULT_MESSAGES.refusal, ...((c.messages && c.messages.refusal) || {}) };
|
|
126
|
+
messages.invalid = { ...DEFAULT_MESSAGES.invalid, ...((c.messages && c.messages.invalid) || {}) };
|
|
127
|
+
const refusalView = c.refusalView || 'errors/generic';
|
|
128
|
+
const wantsJson = c.wantsJson || ((req) => {
|
|
129
|
+
const h = (n) => (req && isFn(req.get) ? req.get(n) : (req && req.headers && req.headers[n.toLowerCase()])) || '';
|
|
130
|
+
const accept = String(h('Accept'));
|
|
131
|
+
return h('X-Requested-With') === 'fetch' || (/application\/json/i.test(accept) && !/text\/html/i.test(accept));
|
|
132
|
+
});
|
|
133
|
+
const workInPath = `${c.mountPath}/:cus/work-in`;
|
|
134
|
+
const leavePath = `${c.mountPath}/leave`;
|
|
135
|
+
const statusPath = `${c.mountPath}/visit`;
|
|
136
|
+
|
|
137
|
+
// THE SESSION MODE, through the tenancy package's module object at construction (so a test can swap the factory).
|
|
138
|
+
const mode = tenancyPackage.createSessionMode({ keys: [R.VISIT_KEY], guardSave: true, logger });
|
|
139
|
+
|
|
140
|
+
// The pinned visit's facts, per request: set by gate() when it pins a request, read by stampOf and requirePermission.
|
|
141
|
+
const pinnedFacts = new WeakMap();
|
|
142
|
+
|
|
143
|
+
// ── the role, at home ───────────────────────────────────────────────────────────────────────────────────────────
|
|
144
|
+
|
|
145
|
+
/** Does the person's own role, judged at their HOME partner, hold `perm`? Only `true` counts; a throw is no. */
|
|
146
|
+
function homeHolds(user, perm) {
|
|
147
|
+
if (!user || user.partner_id == null) return false;
|
|
148
|
+
try {
|
|
149
|
+
const r = tenancy.runWithTenant({ scope: 'partner', partnerId: Number(user.partner_id) }, () => c.roleCan(user, perm));
|
|
150
|
+
if (r != null && typeof r.then === 'function') {
|
|
151
|
+
logger.error(`visits: roleCan answered a promise for "${perm}"; it must answer at once (true or false): refused`);
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
return r === true;
|
|
155
|
+
} catch (e) {
|
|
156
|
+
logger.error(`visits: roleCan threw for "${perm}" (${(e && e.message) || e}): refused`);
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/** The role's most per kind, at home. */
|
|
161
|
+
const roleMaxAtHome = (user) => Object.fromEntries(kindKeys.map((k) => [k, R.roleMaxOf(c.levels[k], (p) => homeHolds(user, p))]));
|
|
162
|
+
|
|
163
|
+
/** The access store's decide() for this person, read under the customer's own pin at `partnerId`. */
|
|
164
|
+
function readDecision(partnerId, customerId, userId) {
|
|
165
|
+
return tenancy.asCustomer(Number(partnerId), customerId, () => db.invoke(c.accessModel, 'decide', Number(userId)));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ── answers ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
169
|
+
|
|
170
|
+
function refuse(req, res, status, why, message) {
|
|
171
|
+
if (isFn(res.setHeader)) res.setHeader(R.VISIT_MARKER, why);
|
|
172
|
+
if (wantsJson(req)) return res.status(status).json({ ok: false, type: 'error', code: 'WORK_IN_REFUSED', why, message });
|
|
173
|
+
res.status(status);
|
|
174
|
+
const plain = () => res.type('text/plain').send(message);
|
|
175
|
+
if (!isFn(res.render)) return plain();
|
|
176
|
+
try {
|
|
177
|
+
return res.render(refusalView, { title: status === 404 ? 'Not found' : 'Access denied', message }, (e, html) => (e ? plain() : res.send(html)));
|
|
178
|
+
} catch (e) {
|
|
179
|
+
return plain();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* A WIRING MISTAKE the package detects on a request (a gate in front of the wrong mount, a gate or the status route
|
|
185
|
+
* with no track before it): 500 with `X-Work-In: wiring`, the cause logged at error (review round 1: these answered a
|
|
186
|
+
* bare 500 with no marker, so "every refusal carries X-Work-In" was not true of them).
|
|
187
|
+
*/
|
|
188
|
+
function wiring(req, res, cause) {
|
|
189
|
+
logger.error(`${cause}: refused`);
|
|
190
|
+
return refuse(req, res, 500, 'wiring', 'This application is not wired correctly.');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Tell the person once, on their next page (the app's flash); a failure is logged and swallowed. */
|
|
194
|
+
function notice(req, res, kind, words) {
|
|
195
|
+
return new Promise((resolve) => {
|
|
196
|
+
const failed = (e) => { try { logger.error(`visits: the notice "${words}" could not be shown: ${(e && e.message) || e}`); } catch (_) { /* nothing more */ } resolve(); };
|
|
197
|
+
try {
|
|
198
|
+
if (c.flash) return Promise.resolve(c.flash(req, res, kind, words)).then(() => resolve(), failed);
|
|
199
|
+
if (!res || !isFn(res.flash)) return failed(new Error('no flash helper (res.flash) and no `flash` option'));
|
|
200
|
+
return res.flash(kind, words, () => resolve());
|
|
201
|
+
} catch (e) { return failed(e); }
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** A path the app gave, checked at use: a local path, else the Customers list. */
|
|
206
|
+
function safePath(fn, arg) {
|
|
207
|
+
try {
|
|
208
|
+
const p = fn(arg);
|
|
209
|
+
if (isLocalPath(p)) return p;
|
|
210
|
+
logger.error(`visits: a path the app gave is not a local path (${JSON.stringify(p)}); sent to ${c.paths.customers}`);
|
|
211
|
+
} catch (e) {
|
|
212
|
+
logger.error(`visits: a path the app gave failed (${(e && e.message) || e}); sent to ${c.paths.customers}`);
|
|
213
|
+
}
|
|
214
|
+
return c.paths.customers;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ── the two rows ────────────────────────────────────────────────────────────────────────────────────────────────
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* THE REQUEST AS THE VISIT WAS MADE (review round 1): the app's audit helper stamps `acting_as_partner` from the
|
|
221
|
+
* session it is given; a visit's two rows must say how the VISIT was made, not how the session is when it ends (a
|
|
222
|
+
* visit made working in partner A that ends after the person stopped, or a house visit that ends after the person
|
|
223
|
+
* started working in A). So the helper is given a view of the request whose session says acting as the record's
|
|
224
|
+
* partner exactly when the record was made acting, and nothing else changed (every other read passes through).
|
|
225
|
+
*/
|
|
226
|
+
function asTheVisit(req, rec) {
|
|
227
|
+
const s = req && req.session;
|
|
228
|
+
if (!s || typeof s !== 'object') return req;
|
|
229
|
+
const acting = rec && rec.acting === true && Number.isSafeInteger(rec.partnerId) && rec.partnerId > 0 ? rec.partnerId : undefined;
|
|
230
|
+
const sess = Object.create(s, { actingPartnerId: { value: acting, enumerable: true, writable: true, configurable: true } });
|
|
231
|
+
const view = Object.create(req, { session: { value: sess, enumerable: true, writable: true, configurable: true } });
|
|
232
|
+
viewOf.set(view, req);
|
|
233
|
+
return view;
|
|
234
|
+
}
|
|
235
|
+
// review round 2: the view is a new object, so a lookup keyed by the request (stampOf's, an app's WeakMap) misses it:
|
|
236
|
+
// requestOf(view) is the request it was made from (and any other value as given)
|
|
237
|
+
const viewOf = new WeakMap();
|
|
238
|
+
function requestOf(r) { return (r && typeof r === 'object' && viewOf.get(r)) || r; }
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* A VISIT'S ROW, through the app's audit helper, inside the visit's own partner's scope (its trail), given the request
|
|
242
|
+
* as the visit was made. The helper MUST return the promise of its write (review round 1: "a failed start row stops the
|
|
243
|
+
* start" holds only then): an answer that is not a promise is an error naming `audit`. Resolves the write's answer;
|
|
244
|
+
* rejects on a throw or a failed write.
|
|
245
|
+
*/
|
|
246
|
+
function auditVisit(rec, req, action, opts) {
|
|
247
|
+
const pid = Number(rec && rec.partnerId);
|
|
248
|
+
const view = asTheVisit(req, rec);
|
|
249
|
+
const write = () => {
|
|
250
|
+
const r = c.audit(view, action, opts);
|
|
251
|
+
if (!r || typeof r.then !== 'function') {
|
|
252
|
+
throw new Error('createVisits: audit must return the promise of its write (it returned nothing): a fire-and-forget helper cannot stop a start whose row failed');
|
|
253
|
+
}
|
|
254
|
+
return r;
|
|
255
|
+
};
|
|
256
|
+
return Promise.resolve().then(() => (Number.isSafeInteger(pid) && pid > 0 ? tenancy.asPartner(pid, write) : write()));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* THE VISITS ENDED BY THIS PROCESS (this createVisits), each kept for the longest a visit lives, at most ENDED_MAX:
|
|
261
|
+
* claimed by the request whose own write ended the visit, so a burst of requests ending it at once writes one stop row.
|
|
262
|
+
*/
|
|
263
|
+
const ENDED_MAX = 10000;
|
|
264
|
+
const endedIds = new Map(); // claim key → when claimed (ms)
|
|
265
|
+
function claim(key, nowMs) {
|
|
266
|
+
for (const [k, at] of endedIds) { if (nowMs - at > R.VISIT_MS) endedIds.delete(k); else break; }
|
|
267
|
+
if (endedIds.has(key)) return false;
|
|
268
|
+
endedIds.set(key, nowMs);
|
|
269
|
+
while (endedIds.size > ENDED_MAX) endedIds.delete(endedIds.keys().next().value);
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
const claimKey = (rec) => (rec && typeof rec.id === 'string' && R.VISIT_ID.test(rec.id) ? rec.id : `record:${stable(rec)}`);
|
|
273
|
+
|
|
274
|
+
/** The stop row (CD-44): logged, never thrown (a failed row must not keep a visit on). */
|
|
275
|
+
async function writeStop(req, rec, ended, because) {
|
|
276
|
+
const r = rec && typeof rec === 'object' ? rec : {};
|
|
277
|
+
try {
|
|
278
|
+
await auditVisit(r, req, record.VISIT_ACTIONS.stop, {
|
|
279
|
+
entity_type: 'customer', entity_id: typeof r.customerId === 'string' && R.CUSTOMER_ID.test(r.customerId) ? r.customerId : null,
|
|
280
|
+
detail: record.stopDetail(r, ended, because, c.now())
|
|
281
|
+
});
|
|
282
|
+
} catch (e) {
|
|
283
|
+
logger.error(`visits: the stop row of visit ${claimKey(r)} (${ended}) could not be written: ${(e && e.message) || e}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* END THE SESSION'S VISIT, written through the session mode: the stored session must still hold THIS visit; then it is
|
|
289
|
+
* removed and saved. The stop row is written by the request whose OWN write removed the visit (`saved`), and, in this
|
|
290
|
+
* process, only once per visit: the claim is taken after the save (review round 1: taken before it, a burst whose
|
|
291
|
+
* first claimer lost the race to another request's write ended the visit with no stop row at all). `notice`: the
|
|
292
|
+
* CD-23 sentence, flashed BEFORE the write so it is saved with it (and not kept when nothing is written).
|
|
293
|
+
* → whether this request's write ended it.
|
|
294
|
+
*/
|
|
295
|
+
async function endWith(req, res, ended, because, o) { return (await endVisit(req, res, ended, because, o)).ended; }
|
|
296
|
+
/** endWith's work → { ended, outcome, row }: `outcome` is the write's ('saved', 'gone', 'changed', …) or 'error'. */
|
|
297
|
+
async function endVisit(req, res, ended, because, { notice: tell = false, alsoChange = null } = {}) {
|
|
298
|
+
const s = req && req.session;
|
|
299
|
+
const rec = s ? s[R.VISIT_KEY] : undefined;
|
|
300
|
+
if (rec == null) return { ended: false, outcome: 'none', row: null };
|
|
301
|
+
if (!mode.loadedOf(req)) throw new Error('visits: mount visits.loaded directly after the session middleware (the session as loaded is needed before a visit is ended)');
|
|
302
|
+
const pre = mode.snapshot(s);
|
|
303
|
+
if (tell) await notice(req, res, 'warning', R.endedText(rec && rec.customerName, ended));
|
|
304
|
+
const key = claimKey(rec);
|
|
305
|
+
const same = stable(rec);
|
|
306
|
+
let r;
|
|
307
|
+
try {
|
|
308
|
+
r = await mode.write(req, (row) => row[R.VISIT_KEY] != null && stable(row[R.VISIT_KEY]) === same,
|
|
309
|
+
(t) => { delete t[R.VISIT_KEY]; if (alsoChange) alsoChange(t); }, { pre });
|
|
310
|
+
} catch (e) {
|
|
311
|
+
logger.error(`visits: visit ${key} could not be ended (${ended}): the session could not be saved: ${(e && e.message) || e}`);
|
|
312
|
+
return { ended: false, outcome: 'error', row: null };
|
|
313
|
+
}
|
|
314
|
+
if (r.outcome !== 'saved') {
|
|
315
|
+
logger.warn(`visits: visit ${key} not ended here (${ended}): the session's row is ${r.outcome}`);
|
|
316
|
+
return { ended: false, outcome: r.outcome, row: r.row || null };
|
|
317
|
+
}
|
|
318
|
+
if (claim(key, c.now())) await writeStop(req, rec, ended, because);
|
|
319
|
+
return { ended: true, outcome: 'saved', row: r.row || null };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* DOES A STORED ROW STILL STAND WHERE A START WAS JUDGED (review round 3)? → null, or why not: 'fleet-view' (the row
|
|
324
|
+
* carries fleet view, CD-60; asked of fleet view itself, `inRow`), 'acting' or 'partner' (the row's place, read by the
|
|
325
|
+
* tenancy's own contextFor, is not the record's). Synchronous: it is asked inside the store's callback.
|
|
326
|
+
*/
|
|
327
|
+
function placeOfRow(rec, row) {
|
|
328
|
+
if (!row || typeof row !== 'object') return 'partner';
|
|
329
|
+
if (c.fleetView && c.fleetView.inRow(row)) return 'fleet-view';
|
|
330
|
+
let ctx = null;
|
|
331
|
+
try { ctx = tenancy.contextFor({ session: row }); } catch (e) { ctx = null; }
|
|
332
|
+
return R.placeProblem(rec, ctx, row.user);
|
|
333
|
+
}
|
|
334
|
+
/** A start that no longer stands where it was judged: 409, with the sentence for why. */
|
|
335
|
+
function refuseMoved(req, res, why) {
|
|
336
|
+
if (why === 'fleet-view') return refuse(req, res, 409, 'fleet-view', text(messages.refusal['fleet-view']));
|
|
337
|
+
if (why === 'acting' || why === 'partner') return refuse(req, res, 409, why, text(messages.placeChanged));
|
|
338
|
+
return refuse(req, res, 409, 'busy', text(messages.busy));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* THE SESSION'S ROW AS THE STORE HOLDS IT NOW (the start's confirming read, review round 2) → { row } (null: gone) or
|
|
343
|
+
* { unreadable: why }.
|
|
344
|
+
*/
|
|
345
|
+
function readRow(req) {
|
|
346
|
+
return new Promise((resolve) => {
|
|
347
|
+
const store = req && req.sessionStore;
|
|
348
|
+
if (!store || !isFn(store.get) || req.sessionID == null) return resolve({ unreadable: 'no session store' });
|
|
349
|
+
let answered = false;
|
|
350
|
+
const onRow = (err, row) => {
|
|
351
|
+
if (answered) return;
|
|
352
|
+
answered = true;
|
|
353
|
+
resolve(err ? { unreadable: (err && err.message) || String(err) } : { row: row || null });
|
|
354
|
+
};
|
|
355
|
+
try { store.get(req.sessionID, onRow); } catch (e) { onRow(e); }
|
|
356
|
+
return undefined;
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// ── the way in ──────────────────────────────────────────────────────────────────────────────────────────────────
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* WHAT THIS PERSON MAY DO AT THIS CUSTOMER NOW (the customer page's form): → { customer, may, why, offered, cappedBy,
|
|
364
|
+
* reasonRequired, request, access, acting, partnerId }. The customer is read under the pin of the partner the request
|
|
365
|
+
* is in (contextFor), so a house person not working in the customer's partner gets `not-found`.
|
|
366
|
+
*/
|
|
367
|
+
async function entry(req, customerId) {
|
|
368
|
+
const user = req && req.session && req.session.user;
|
|
369
|
+
const none = (why) => ({ customer: null, may: false, why, offered: Object.fromEntries(kindKeys.map((k) => [k, null])), cappedBy: {}, reasonRequired: true,
|
|
370
|
+
request: null, access: null, acting: false, partnerId: null });
|
|
371
|
+
if (!user) return none('permission');
|
|
372
|
+
const fleetViewOn = c.fleetView ? (await c.fleetView.isOn(req, req.res)) === true : false;
|
|
373
|
+
const mayWorkIn = homeHolds(user, c.permission);
|
|
374
|
+
if (fleetViewOn || !mayWorkIn) return none(R.refusal({ fleetViewOn, mayWorkIn }));
|
|
375
|
+
const ctx = tenancy.contextFor(req);
|
|
376
|
+
if (!ctx || ctx.partnerId == null || typeof customerId !== 'string' || !R.CUSTOMER_ID.test(customerId)) return none('not-found');
|
|
377
|
+
const decision = await readDecision(ctx.partnerId, customerId, user.id);
|
|
378
|
+
const roleMax = roleMaxAtHome(user);
|
|
379
|
+
const offered = R.offeredLevels(kindKeys, decision && decision.kinds, roleMax);
|
|
380
|
+
const why = R.refusal({ fleetViewOn, mayWorkIn, decision, offered, nowMs: c.now() });
|
|
381
|
+
const acting = R.actingIn(ctx, user);
|
|
382
|
+
const cappedBy = {};
|
|
383
|
+
for (const k of kindKeys) {
|
|
384
|
+
const allowed = decision && decision.kinds[k] && decision.kinds[k].allowance ? decision.kinds[k].allowance.level : null;
|
|
385
|
+
cappedBy[k] = allowed && offered[k] !== allowed ? 'role' : (allowed !== 'change' ? 'customer' : null);
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
customer: decision ? decision.customer : null, may: !why, why, offered, cappedBy,
|
|
389
|
+
reasonRequired: !R.reasonMayBeBlank({ managedInForce: !!(decision && decision.managedInForce), acting }),
|
|
390
|
+
request: decision ? decision.request : null, access: decision || null, acting, partnerId: Number(ctx.partnerId)
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// ── every request (CD-22) ───────────────────────────────────────────────────────────────────────────────────────
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* THE FIT MEMO: visit id → { at, decision, customerId }. decide() under the pin costs a transaction of several
|
|
398
|
+
* statements, and track, gate and every live event ask it, so an answer is kept at most `fitMemoMs` (0: never kept),
|
|
399
|
+
* at most FIT_MAX entries. forget(customerId) drops that customer's answers: every write in this process that can
|
|
400
|
+
* narrow a customer's access calls it AFTER the write commits, so End now ends a visit on the very next request. What
|
|
401
|
+
* the window bounds is only what no write here announces (a write in another process; a grant's end passing by the
|
|
402
|
+
* clock, where the visit's own `until` is that end anyway).
|
|
403
|
+
*
|
|
404
|
+
* THE FORGET GENERATION (review round 1): a read in flight when forget() runs may hold the answer from before the
|
|
405
|
+
* narrowing write. Its own request uses it (that request was in flight across the write), but it is never KEPT. One
|
|
406
|
+
* counter for every forget(): bounded; a forget of one customer only costs another customer's in-flight read its memo.
|
|
407
|
+
*/
|
|
408
|
+
const fitMemo = new Map();
|
|
409
|
+
let forgetGeneration = 0;
|
|
410
|
+
async function decisionFor(rec, nowMs) {
|
|
411
|
+
if (c.fitMemoMs > 0) {
|
|
412
|
+
const m = fitMemo.get(rec.id);
|
|
413
|
+
if (m && m.customerId === rec.customerId && m.at <= nowMs && nowMs - m.at < c.fitMemoMs) return m.decision;
|
|
414
|
+
}
|
|
415
|
+
const generation = forgetGeneration;
|
|
416
|
+
const decision = await readDecision(rec.partnerId, rec.customerId, rec.userId);
|
|
417
|
+
if (c.fitMemoMs > 0 && generation === forgetGeneration) {
|
|
418
|
+
fitMemo.delete(rec.id);
|
|
419
|
+
fitMemo.set(rec.id, { at: nowMs, decision, customerId: rec.customerId });
|
|
420
|
+
if (fitMemo.size > FIT_MAX) {
|
|
421
|
+
for (const [id, m] of fitMemo) if (!(m.at <= nowMs && nowMs - m.at < c.fitMemoMs)) fitMemo.delete(id);
|
|
422
|
+
while (fitMemo.size > FIT_MAX) fitMemo.delete(fitMemo.keys().next().value);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return decision;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Drop the kept answers of one customer, or of all (no argument). The app calls it AFTER every write that can narrow
|
|
429
|
+
* a customer's access has committed, and before it answers; a read in flight meanwhile is not kept.
|
|
430
|
+
*/
|
|
431
|
+
function forget(customerId) {
|
|
432
|
+
forgetGeneration++;
|
|
433
|
+
if (customerId === undefined) { fitMemo.clear(); return; }
|
|
434
|
+
for (const [id, m] of fitMemo) if (m.customerId === customerId) fitMemo.delete(id);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* THE VISIT, JUDGED FOR ONE SESSION NOW, in this order: the app's session ending (signed_out); the record (refused,
|
|
439
|
+
* `record`); its end (expired); the user (refused, `user`); fleet view carried beside it (refused, `fleet-view`,
|
|
440
|
+
* review round 3); working in a partner and the partner in force (refused,
|
|
441
|
+
* `acting` / `partner`); the work-in permission at home (refused, `role`); the fit read under the pin (refused,
|
|
442
|
+
* `setting` / `role`). A throw from the app or the store is refused, `error` (fail closed).
|
|
443
|
+
* → {} | { live: { rec, fit } } | { over: rec, ended, because }
|
|
444
|
+
*/
|
|
445
|
+
async function judgeSession(req, s, { ending = true } = {}) {
|
|
446
|
+
const rec = s ? s[R.VISIT_KEY] : undefined;
|
|
447
|
+
if (rec == null) return {};
|
|
448
|
+
const over = (ended, because = null) => ({ over: rec, ended, because });
|
|
449
|
+
if (ending) {
|
|
450
|
+
let e;
|
|
451
|
+
try { e = await c.sessionEnding(req); } catch (err) {
|
|
452
|
+
logger.error(`visits: sessionEnding threw (${(err && err.message) || err}); the visit ends`);
|
|
453
|
+
return over('refused', 'error');
|
|
454
|
+
}
|
|
455
|
+
if (e === true) return over('signed_out');
|
|
456
|
+
}
|
|
457
|
+
const now = c.now();
|
|
458
|
+
const ex = R.examine(s, now, kindKeys);
|
|
459
|
+
if (ex.over) return over(ex.why, ex.because);
|
|
460
|
+
// CD-60, THE SAFETY NET (review round 3): a session that carries fleet view beside a visit (a start and fleet view's
|
|
461
|
+
// switch racing in two tabs) ends the visit here, whatever the race was: the two are never on past one request
|
|
462
|
+
if (c.fleetView && c.fleetView.inRow(s)) return over('refused', 'fleet-view');
|
|
463
|
+
const user = s.user;
|
|
464
|
+
const place = R.placeProblem(rec, tenancy.contextFor(req), user);
|
|
465
|
+
if (place) return over('refused', place);
|
|
466
|
+
if (!homeHolds(user, c.permission)) return over('refused', 'role');
|
|
467
|
+
let decision;
|
|
468
|
+
try { decision = await decisionFor(rec, now); } catch (err) {
|
|
469
|
+
logger.error(`visits: visit ${rec.id}: the customer's access could not be read (${(err && err.message) || err}); the visit ends`);
|
|
470
|
+
return over('refused', 'error');
|
|
471
|
+
}
|
|
472
|
+
const fit = R.fitOf(rec, decision, roleMaxAtHome(user));
|
|
473
|
+
if (!fit.ok) return over('refused', fit.because);
|
|
474
|
+
return { live: { rec, fit } };
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// The judgement track made of each request: gate and requirePermission read it (and refuse loudly without it).
|
|
478
|
+
const judged = new WeakMap();
|
|
479
|
+
// The visit's own `can` for a request its gate pinned.
|
|
480
|
+
const pinnedCan = new WeakMap();
|
|
481
|
+
const unlistedLogged = new Set();
|
|
482
|
+
// Review round 1: every request a gate ran on (whatever it decided), and the functions gate() and requirePermission()
|
|
483
|
+
// made (isGate, isVisitGuard: for an app's own wiring test over its route stacks).
|
|
484
|
+
const gatedReqs = new WeakSet();
|
|
485
|
+
const gateFns = new WeakSet();
|
|
486
|
+
const guardFns = new WeakSet();
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* THE VISIT'S `can` (CD-17, CD-18, CD-19): the cap (rules.capOf: the kind open, the level, unlisted refused unless not
|
|
490
|
+
* capped) AND the person's own role judged at HOME. Never the request's own partner's role of that name.
|
|
491
|
+
*/
|
|
492
|
+
function visitCan(user, rec, fit) {
|
|
493
|
+
return (perm) => {
|
|
494
|
+
const cap = R.capOf(perm, { index: c.index, notCapped: c.notCapped, levels: rec.levels, open: fit.open });
|
|
495
|
+
if (cap === 'unlisted') {
|
|
496
|
+
if (!unlistedLogged.has(perm)) {
|
|
497
|
+
unlistedLogged.add(perm);
|
|
498
|
+
logger.warn(`visits: "${perm}" is in no kind's levels and not in notCapped: refused inside a visit (logged once)`);
|
|
499
|
+
}
|
|
500
|
+
return false;
|
|
501
|
+
}
|
|
502
|
+
return cap === 'yes' && homeHolds(user, perm);
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* TRACK (every request, CD-22, CD-23): judges the session's visit; a visit that is over ENDS here (through the session
|
|
508
|
+
* mode, its stop row once, the CD-23 sentence flashed before the write) and the rest of the request is outside. A
|
|
509
|
+
* visit in force sets `res.locals.visit` (the banner's and the menu's facts), `res.locals.visitLocked(perm)` and
|
|
510
|
+
* `res.locals.visitLockedText` (CD-18's disabled buttons).
|
|
511
|
+
*/
|
|
512
|
+
async function trackRequest(req, res) {
|
|
513
|
+
if (!loadedReqs.has(req)) {
|
|
514
|
+
// review round 1: the package's OWN mark, not the shared copy of the session (fleet view's `loaded` takes that copy
|
|
515
|
+
// for a house person working in a partner, which hid a missing visits.loaded and left the save guard off)
|
|
516
|
+
if (!loadedLogged) { loadedLogged = true; logger.error('visits: visits.loaded is not mounted (directly after the session middleware): every request is refused until it is'); }
|
|
517
|
+
return 'not-loaded';
|
|
518
|
+
}
|
|
519
|
+
// review round 2 (optional): the mounts are matched as `caseSensitive` says; Express matches them as the app's
|
|
520
|
+
// "case sensitive routing" says. When the two disagree it is said once (a mount the gate and Express spell apart)
|
|
521
|
+
if (!caseChecked && req.app && isFn(req.app.get)) {
|
|
522
|
+
caseChecked = true;
|
|
523
|
+
const appSays = req.app.get('case sensitive routing') === true;
|
|
524
|
+
if (appSays !== (c.caseSensitive === true)) logger.warn(`visits: caseSensitive is ${c.caseSensitive === true} but the app's "case sensitive routing" is ${appSays}: the gate matches the mounts ${c.caseSensitive === true ? 'by case' : 'case-blind'}, Express ${appSays ? 'by case' : 'case-blind'}`);
|
|
525
|
+
}
|
|
526
|
+
res.locals.visit = null;
|
|
527
|
+
res.locals.visitEnded = null;
|
|
528
|
+
res.locals.visitLocked = () => false;
|
|
529
|
+
res.locals.visitLockedText = '';
|
|
530
|
+
const s = req.session;
|
|
531
|
+
if (!s || s[R.VISIT_KEY] == null) { judged.set(req, {}); return; }
|
|
532
|
+
// review round 2: a session holding a visit whose save is NOT guarded (visits.loaded ran where no session was, or
|
|
533
|
+
// the session was replaced after it) could write a left visit back: refused like a missing visits.loaded
|
|
534
|
+
if (!mode.isGuarded(req)) {
|
|
535
|
+
if (!guardLogged) { guardLogged = true; logger.error('visits: a session holding a visit is not save-guarded (visits.loaded must come AFTER the session middleware): such requests are refused until it does'); }
|
|
536
|
+
return 'not-loaded';
|
|
537
|
+
}
|
|
538
|
+
if (!mode.loadedOf(req)) throw new Error('visits: mount visits.loaded directly after the session middleware (the session as loaded is needed before a visit is judged)');
|
|
539
|
+
const j = await judgeSession(req, s);
|
|
540
|
+
if (j.over) {
|
|
541
|
+
const name = (j.over && typeof j.over.customerName === 'string' && j.over.customerName) || 'the customer';
|
|
542
|
+
const ended = await endWith(req, res, j.ended, j.because, { notice: true });
|
|
543
|
+
if (ended) res.locals.visitEnded = { customerName: name, why: j.ended, text: R.endedText(name, j.ended) };
|
|
544
|
+
judged.set(req, {});
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
judged.set(req, j);
|
|
548
|
+
const { rec, fit } = j.live;
|
|
549
|
+
const user = s.user;
|
|
550
|
+
res.locals.visit = { ...factsOf(rec), open: { ...fit.open }, customerPath: safePath(c.paths.customer, rec.customerId) };
|
|
551
|
+
res.locals.visitLocked = (perm) => R.capOf(perm, { index: c.index, notCapped: c.notCapped, levels: rec.levels, open: fit.open }) === 'look-only' && homeHolds(user, perm);
|
|
552
|
+
res.locals.visitLockedText = text(messages.lookOnly, rec.customerName);
|
|
553
|
+
// CD-60: fleet view cannot be switched on while a visit is in force (its button is not offered)
|
|
554
|
+
if (res.locals.fleetView && typeof res.locals.fleetView === 'object') res.locals.fleetView = { ...res.locals.fleetView, canStart: false };
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function track(req, res, next) {
|
|
558
|
+
trackRequest(req, res).then((wrong) => (wrong === 'not-loaded'
|
|
559
|
+
? refuse(req, res, 500, 'not-loaded', 'This application is not wired correctly (visits.loaded is not mounted).') : next()), next);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// Every request visits.loaded saw (review round 1): track refuses any other.
|
|
563
|
+
const loadedReqs = new WeakSet();
|
|
564
|
+
let loadedLogged = false;
|
|
565
|
+
let guardLogged = false;
|
|
566
|
+
let caseChecked = false;
|
|
567
|
+
// review round 2: marked only when the session is there (mounted before the session middleware, it saw none)
|
|
568
|
+
function loaded(req, res, next) { if (req && req.session) loadedReqs.add(req); return mode.loaded(req, res, next); }
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* CD-60, ASKED BY FLEET VIEW'S OWN START ROUTE (tenancy 0.5.0, addStartCheck; registered below), so every target
|
|
572
|
+
* Express dispatches to that route is judged, whatever its spelling: a session that holds a visit cannot switch fleet
|
|
573
|
+
* view on ("Leave <customer> first", X-Work-In: leave-first), and the visit is left as it is (never ended by the
|
|
574
|
+
* switch). Track has already ended, earlier in the same request, a visit that is over; a record still in the session
|
|
575
|
+
* is a visit in force, or one the store still holds: refused either way. A request track did not judge (a wiring
|
|
576
|
+
* mistake) is refused too, and logged (fail closed).
|
|
577
|
+
*/
|
|
578
|
+
async function fleetStartCheck(req, res) {
|
|
579
|
+
const s = req && req.session;
|
|
580
|
+
let rec = s ? s[R.VISIT_KEY] : undefined;
|
|
581
|
+
if (rec != null && !judged.has(req)) logger.error('visits: fleet view\'s start ran on a request visits.track did not judge (mount track before fleet view\'s routes): refused');
|
|
582
|
+
if (rec == null) {
|
|
583
|
+
// review round 3: the session as LOADED holds no visit, but one may have landed since (another tab's start): the
|
|
584
|
+
// stored row is read again. A visit there refuses; a row that cannot be read throws (fleet view refuses, logged).
|
|
585
|
+
const seen = await readRow(req);
|
|
586
|
+
if (seen.unreadable) throw new Error(`visits: the session's row could not be read before fleet view's start (${seen.unreadable})`);
|
|
587
|
+
rec = seen.row ? seen.row[R.VISIT_KEY] : undefined;
|
|
588
|
+
if (rec == null) {
|
|
589
|
+
// and fleet view's own save is guarded for the visit key from here: a visit that lands between this read and
|
|
590
|
+
// that save is kept, not wiped with no stop row; the stored session then carries both, and the next request's
|
|
591
|
+
// track ends the visit (`refused`, `fleet-view`, its stop row): never both on for a request
|
|
592
|
+
mode.guard(req);
|
|
593
|
+
return null;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
const name = rec && typeof rec.customerName === 'string' && rec.customerName ? rec.customerName : 'the customer';
|
|
597
|
+
logger.warn(`visits: user ${s && s.user ? s.user.id : '(none)'}: fleet view refused while working in ${rec && rec.customerId} (leave first)`);
|
|
598
|
+
if (res && isFn(res.setHeader)) res.setHeader(R.VISIT_MARKER, 'leave-first');
|
|
599
|
+
return text(messages.leaveFirst, name);
|
|
600
|
+
}
|
|
601
|
+
if (c.fleetView) c.fleetView.addStartCheck(fleetStartCheck);
|
|
602
|
+
|
|
603
|
+
/** The full path a gate runs at for this request (Express's own: the mount plus the path below it). */
|
|
604
|
+
const fullPathOf = (req) => `${typeof req.baseUrl === 'string' ? req.baseUrl : ''}${typeof req.path === 'string' ? req.path : ''}`;
|
|
605
|
+
|
|
606
|
+
/** Is this request one of the app's `outside` entries (judged on the raw target, as fleet view judges)? */
|
|
607
|
+
function outsideMatches(req) {
|
|
608
|
+
const target = String(req.originalUrl != null ? req.originalUrl : req.url);
|
|
609
|
+
if (!PLAIN_TARGET.test(target) || target.length > 8192) return false;
|
|
610
|
+
const pathname = target.split('?')[0];
|
|
611
|
+
const base = typeof req.baseUrl === 'string' ? req.baseUrl : '';
|
|
612
|
+
const dispatched = base + (req.path === '/' && base && pathname === base ? '' : req.path);
|
|
613
|
+
if (dispatched !== pathname) return false;
|
|
614
|
+
const m = String(req.method || '').toUpperCase();
|
|
615
|
+
const segs = pathname.split('/');
|
|
616
|
+
return c.outside.some((e) => (e.method === m || (e.method === 'GET' && m === 'HEAD')) && e.segs.length === segs.length
|
|
617
|
+
&& e.segs.every((want, i) => (PARAM.test(want) ? ID_VALUE.test(segs[i]) : want === segs[i])));
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** Is this a page a person's browser shows (a GET or HEAD for HTML, not a fetch, a stream, or a path the app lists as not a page)? */
|
|
621
|
+
function isPage(req) {
|
|
622
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
|
|
623
|
+
const h = req.headers || {};
|
|
624
|
+
const accept = String(h.accept || '');
|
|
625
|
+
if (/application\/json|text\/event-stream/i.test(accept) || h['x-requested-with'] === 'fetch') return false;
|
|
626
|
+
const pathname = String(req.originalUrl || '').split('?')[0];
|
|
627
|
+
return !c.notPages.some((re) => { re.lastIndex = 0; return re.test(pathname); });
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* THE GATE, in front of a gated mount of `kind`. No visit: an `outside` entry passes; a page goes to the Customers list;
|
|
632
|
+
* anything else 403 (`outside`). In a visit: the kind not open, 403 (`closed`); look only and a state-changing method,
|
|
633
|
+
* 403 (`look-only`, CD-18), before any route runs; else every customer the request names is the pin's (CD-25), the
|
|
634
|
+
* page's `can` and visits.requirePermission are the visit's, and the rest of the request runs in
|
|
635
|
+
* tenancy.asCustomer(partner, customer) (CD-14). A session with no staff user is not a visit's: passed on, to the
|
|
636
|
+
* app's own sign-in gate. Every refusal carries `X-Work-In`.
|
|
637
|
+
*/
|
|
638
|
+
function gate(kind) {
|
|
639
|
+
if (!kindKeys.includes(kind)) throw new Error(`visits.gate: "${kind}" is not one of the kinds (${kindKeys.join(', ')})`);
|
|
640
|
+
if (!c.mounts.some((m) => m.kind === kind)) throw new Error(`visits.gate: no entry of mounts names the kind "${kind}"`);
|
|
641
|
+
const fn = function visitsGate(req, res, next) {
|
|
642
|
+
gatedReqs.add(req);
|
|
643
|
+
const s = req.session;
|
|
644
|
+
if (!s || !s.user) return next();
|
|
645
|
+
const full = fullPathOf(req);
|
|
646
|
+
const mount = mountOf(full);
|
|
647
|
+
if (!mount || mount.kind !== kind) {
|
|
648
|
+
return wiring(req, res, `visits.gate('${kind}'): it runs in front of ${JSON.stringify(full)}, which mounts gives ${mount ? `the kind "${mount.kind}"` : 'no gated mount'}`);
|
|
649
|
+
}
|
|
650
|
+
const j = judged.get(req);
|
|
651
|
+
if (!j) return wiring(req, res, 'visits.gate: visits.track did not run on this request (mount it after fleet view\'s middleware, before every router)');
|
|
652
|
+
if (!j.live) {
|
|
653
|
+
if (outsideMatches(req)) return next();
|
|
654
|
+
if (isPage(req)) { if (isFn(res.setHeader)) res.setHeader(R.VISIT_MARKER, 'outside'); return res.redirect(c.paths.customers); }
|
|
655
|
+
return refuse(req, res, 403, 'outside', text(messages.outside));
|
|
656
|
+
}
|
|
657
|
+
const { rec, fit } = j.live;
|
|
658
|
+
if (fit.open[kind] !== true) return refuse(req, res, 403, 'closed', text(messages.closed, rec.customerName));
|
|
659
|
+
if (rec.levels[kind] !== 'change' && !READ.has(String(req.method).toUpperCase())) return refuse(req, res, 403, 'look-only', text(messages.lookOnly, rec.customerName));
|
|
660
|
+
// CD-25: the customer a request names is the pin's. A multipart body is parsed after this: there the pin refuses.
|
|
661
|
+
if (c.customerParams.query.length && req.query && typeof req.query === 'object') {
|
|
662
|
+
const q = { ...req.query };
|
|
663
|
+
let changed = false;
|
|
664
|
+
for (const n of c.customerParams.query) if (q[n] !== undefined) { q[n] = rec.customerId; changed = true; }
|
|
665
|
+
if (changed) Object.defineProperty(req, 'query', { value: q, writable: true, configurable: true, enumerable: true });
|
|
666
|
+
}
|
|
667
|
+
if (req.body && typeof req.body === 'object') {
|
|
668
|
+
for (const n of c.customerParams.body) if (req.body[n] !== undefined) req.body[n] = rec.customerId;
|
|
669
|
+
}
|
|
670
|
+
const vcan = visitCan(s.user, rec, fit);
|
|
671
|
+
pinnedFacts.set(req, { ...factsOf(rec), kind });
|
|
672
|
+
pinnedCan.set(req, vcan);
|
|
673
|
+
res.locals.can = vcan;
|
|
674
|
+
return tenancy.asCustomer(rec.partnerId, rec.customerId, () => next());
|
|
675
|
+
};
|
|
676
|
+
gateFns.add(fn);
|
|
677
|
+
return fn;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* THE ROUTE GUARD FOR GATED ROUTES (fact 3 of the plan: a guard that asks the app's role check in the request's own
|
|
682
|
+
* context judges a house person by the partner's role of that name). In a request a visit's gate pinned: every
|
|
683
|
+
* permission must pass the visit's `can` (the cap and the role at home), else 403 (`permission`). Under a mount the
|
|
684
|
+
* app lists in `mounts` whose gate did NOT run on this request (a gate the app forgot): 403 (`no-gate`), logged at
|
|
685
|
+
* error, never the app's own guard (review round 1: it fell back to it, unpinned, judging a house person by the
|
|
686
|
+
* partner's role, with a kind at Never ignored). Anywhere else: the app's own requirePermission, unchanged.
|
|
687
|
+
*/
|
|
688
|
+
function requirePermission(...perms) {
|
|
689
|
+
if (!perms.length || !perms.every((p) => typeof p === 'string' && p)) throw new Error('visits.requirePermission: name at least one permission');
|
|
690
|
+
const own = c.requirePermission(...perms);
|
|
691
|
+
if (!isFn(own)) throw new Error('visits.requirePermission: the app\'s requirePermission did not return a middleware');
|
|
692
|
+
const fn = function visitsRequirePermission(req, res, next) {
|
|
693
|
+
const vcan = pinnedCan.get(req);
|
|
694
|
+
if (!vcan) {
|
|
695
|
+
const mount = gatedReqs.has(req) ? null : mountOf(fullPathOf(req));
|
|
696
|
+
if (mount) {
|
|
697
|
+
logger.error(`visits: no gate ran in front of ${JSON.stringify(fullPathOf(req))} (mount ${mount.path}, kind ${mount.kind}): refused; mount visits.gate('${mount.kind}') in front of it`);
|
|
698
|
+
return refuse(req, res, 403, 'no-gate', text(messages.permission));
|
|
699
|
+
}
|
|
700
|
+
return own(req, res, next);
|
|
701
|
+
}
|
|
702
|
+
if (perms.every((p) => vcan(p) === true)) return next();
|
|
703
|
+
return refuse(req, res, 403, 'permission', text(messages.permission));
|
|
704
|
+
};
|
|
705
|
+
guardFns.add(fn);
|
|
706
|
+
return fn;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
/**
|
|
710
|
+
* The gated mount a full path is under, or null, matched as Express dispatches: case-blind by default (review round 1:
|
|
711
|
+
* `POST /NOTES` reached the notes router and the gate answered a 500); `caseSensitive: true` for an app that set
|
|
712
|
+
* Express's "case sensitive routing".
|
|
713
|
+
*/
|
|
714
|
+
function mountOf(fullPath) {
|
|
715
|
+
const fold = (x) => (c.caseSensitive ? String(x) : String(x).toLowerCase());
|
|
716
|
+
const p = fold(fullPath);
|
|
717
|
+
return c.mounts.find((m) => under(p, fold(m.path))) || null;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* WHAT THE GATE DOES WITH A ROUTE, without a request (for an app's population test over its derived route table):
|
|
722
|
+
* → { mount, kind, outside } for a full path under a gated mount (`outside`: an `outside` entry, passed without a
|
|
723
|
+
* visit), or { mount: null, kind: null, outside: false } for a path under none.
|
|
724
|
+
*/
|
|
725
|
+
function classify(method, fullPath) {
|
|
726
|
+
const p = String(fullPath == null ? '' : fullPath).split('?')[0];
|
|
727
|
+
const mount = mountOf(p);
|
|
728
|
+
if (!mount) return { mount: null, kind: null, outside: false };
|
|
729
|
+
const m = String(method || '').toUpperCase();
|
|
730
|
+
const segs = p.split('/');
|
|
731
|
+
const outside = c.outside.some((e) => (e.method === m || (e.method === 'GET' && m === 'HEAD')) && e.segs.length === segs.length
|
|
732
|
+
&& e.segs.every((want, i) => (PARAM.test(want) ? (ID_VALUE.test(segs[i]) || PARAM.test(segs[i])) : want === segs[i])));
|
|
733
|
+
return { mount: mount.path, kind: mount.kind, outside };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* A LIVE STREAM'S VISIT (CD-24), asked per event of a session the app re-read from its store (there is no request):
|
|
738
|
+
* null when it holds no visit or one that is over, judged as track judges a request (the record, its end, the user,
|
|
739
|
+
* working in a partner and the partner in force, the work-in permission at home, the fit under the pin, the same memo),
|
|
740
|
+
* but without the app's `sessionEnding` (the stream's own session check, idle and version, stays the app's). Else
|
|
741
|
+
* `{ ctx, visit, can(perm), kindOpen(kind) }`: the customer's scope (the pin, no contact), the visit's facts, the
|
|
742
|
+
* visit's can (the cap and the role at home; resolves a boolean), and whether a kind is open to the visit now (a live
|
|
743
|
+
* event of a kind the customer has closed is not sent). It ends nothing: the session's next request does.
|
|
744
|
+
*/
|
|
745
|
+
async function forStream(sess) {
|
|
746
|
+
if (!sess || typeof sess !== 'object' || sess[R.VISIT_KEY] == null || !sess.user) return null;
|
|
747
|
+
const j = await judgeSession({ session: sess }, sess, { ending: false });
|
|
748
|
+
if (!j.live) return null;
|
|
749
|
+
const { rec, fit } = j.live;
|
|
750
|
+
const vcan = visitCan(sess.user, rec, fit);
|
|
751
|
+
return Object.freeze({
|
|
752
|
+
ctx: Object.freeze({ scope: 'customer', partnerId: rec.partnerId, customerId: rec.customerId, contactId: null }),
|
|
753
|
+
visit: factsOf(rec),
|
|
754
|
+
can: async (perm) => vcan(perm) === true,
|
|
755
|
+
kindOpen: (kind) => fit.open[kind] === true
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** The visit in force for this request, as track judged it (its public facts), or null. */
|
|
760
|
+
function current(req) {
|
|
761
|
+
const j = req && judged.get(req);
|
|
762
|
+
return j && j.live ? { ...factsOf(j.live.rec), open: { ...j.live.fit.open } } : null;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** The visit's public facts (what pages, the banner and the menu read). */
|
|
766
|
+
function factsOf(rec) {
|
|
767
|
+
const level = R.levelOf(rec.levels);
|
|
768
|
+
return Object.freeze({
|
|
769
|
+
id: rec.id, customerId: rec.customerId, customerName: rec.customerName, partnerId: rec.partnerId, acting: rec.acting,
|
|
770
|
+
levels: Object.freeze({ ...rec.levels }), level, levelLabel: R.LEVEL_WORDS[level], reason: rec.reason, managed: rec.managed,
|
|
771
|
+
startedAt: rec.startedAt, until: rec.until, untilIso: new Date(rec.until).toISOString(), leavePath, statusPath,
|
|
772
|
+
// the CD-23 sentence the page keeps ready for the typed-work notice (assets/visit.js), for any end but the hour's
|
|
773
|
+
endedText: R.endedText(rec.customerName, 'left')
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** CD-50: the partner is told when a house person, working in it, came in to one of its customers. Never awaited. */
|
|
778
|
+
function tell(facts) {
|
|
779
|
+
Promise.resolve().then(() => c.tellPartner(facts)).catch((e) => logger.warn(`visits: the partner of ${facts.customer.id} was not told the house came in: ${(e && e.message) || e}`));
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** START (POST <mountPath>/:cus/work-in): the way in, the reason, the level, one at a time, the start row, the session. */
|
|
783
|
+
async function start(req, res) {
|
|
784
|
+
const cus = req.params.cus;
|
|
785
|
+
const e = await entry(req, cus);
|
|
786
|
+
if (!e.may) return refuse(req, res, e.why === 'not-found' ? 404 : 403, e.why, text(messages.refusal[e.why]));
|
|
787
|
+
const b = req.body || {};
|
|
788
|
+
const back = safePath(c.paths.customer, cus);
|
|
789
|
+
const invalid = async (problem) => {
|
|
790
|
+
if (isFn(res.setHeader)) res.setHeader(R.VISIT_MARKER, 'invalid');
|
|
791
|
+
const m = text(messages.invalid[problem]);
|
|
792
|
+
if (wantsJson(req)) return res.status(400).json({ ok: false, type: 'error', code: 'WORK_IN_INVALID', why: problem, message: m });
|
|
793
|
+
await notice(req, res, 'error', m);
|
|
794
|
+
return res.redirect(back);
|
|
795
|
+
};
|
|
796
|
+
const asked = b.level;
|
|
797
|
+
if (!R.LEVELS.includes(asked)) return invalid('level');
|
|
798
|
+
const reason = R.cleanReason(b.reason);
|
|
799
|
+
const problem = R.reasonProblem(reason, !e.reasonRequired);
|
|
800
|
+
if (problem) return invalid(problem);
|
|
801
|
+
const user = req.session.user;
|
|
802
|
+
const lv = R.entryLevels({ asked, kinds: kindKeys, answers: e.access.kinds, roleMax: roleMaxAtHome(user) });
|
|
803
|
+
if (!R.levelOf(lv.levels)) return refuse(req, res, 403, 'not-allowed', text(messages.refusal['not-allowed']));
|
|
804
|
+
const now = c.now();
|
|
805
|
+
const rec = {
|
|
806
|
+
id: crypto.randomBytes(8).toString('hex'), userId: Number(user.id), homePartnerId: Number(user.partner_id), partnerId: e.partnerId, acting: e.acting,
|
|
807
|
+
customerId: cus, customerName: String(e.customer.name || cus).slice(0, 200), levels: lv.levels, asked, reason, managed: reason === '',
|
|
808
|
+
startedAt: now, until: R.untilOf(now, lv.grantUntil)
|
|
809
|
+
};
|
|
810
|
+
if (!R.recordOk(rec, kindKeys)) throw new Error(`visits: internal: the visit record for ${cus} is out of shape`);
|
|
811
|
+
// ONE AT A TIME (CD-21): a visit in force ends first, `left`, with its stop row. When this request's end did not land,
|
|
812
|
+
// what the STORE holds decides (review round 2: the session in memory is put back as loaded when nothing was written,
|
|
813
|
+
// so it still showed the old visit and every such start was refused `busy`, a Leave or a sign-out elsewhere included):
|
|
814
|
+
// another visit in force → refused `busy`; signed out → refused `signed-out`; no visit (ended elsewhere, its stop row
|
|
815
|
+
// the ender's) → this start goes on from no visit; the store failing → an error.
|
|
816
|
+
if (req.session[R.VISIT_KEY] != null) {
|
|
817
|
+
const out = await endVisit(req, res, 'left', null);
|
|
818
|
+
if (!out.ended) {
|
|
819
|
+
if (out.outcome === 'gone') return refuse(req, res, 409, 'signed-out', text(messages.signedOut));
|
|
820
|
+
if (out.outcome !== 'changed') throw new Error(`visits: user ${rec.userId}: the visit in force could not be ended before a start (${out.outcome})`);
|
|
821
|
+
if (out.row && out.row[R.VISIT_KEY] != null) return refuse(req, res, 409, 'busy', text(messages.busy));
|
|
822
|
+
delete req.session[R.VISIT_KEY];
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
// A START FROM NO VISIT IS GUARDED TOO (tenancy 0.5.0 mode.guard): from here a save of this request cannot write an
|
|
826
|
+
// earlier copy of the visit key back over a Leave or a newer start in another tab.
|
|
827
|
+
mode.guard(req);
|
|
828
|
+
// THE START ROW FIRST: a failed audit stops the start (the visit is never on without its row).
|
|
829
|
+
const home = await c.partnerById(rec.homePartnerId);
|
|
830
|
+
await auditVisit(rec, req, record.VISIT_ACTIONS.start, {
|
|
831
|
+
entity_type: 'customer', entity_id: cus, detail: record.startDetail(rec, { letIn: lv.letIn, grant: lv.grant, company: home && home.name })
|
|
832
|
+
});
|
|
833
|
+
const facts = factsOf(rec);
|
|
834
|
+
// The notice goes into the session BEFORE the write, so it is saved with it and nothing changes after it.
|
|
835
|
+
const pre = mode.snapshot(req.session);
|
|
836
|
+
if (!wantsJson(req)) {
|
|
837
|
+
const lowered = Object.values(rec.levels).some((l) => l && l !== asked) ? ` ${text(messages.lowered)}` : '';
|
|
838
|
+
const words = rec.until - rec.startedAt < R.VISIT_MS
|
|
839
|
+
? text(messages.byGrant, rec.customerName, facts.levelLabel) : text(messages.started, rec.customerName, R.VISIT_WORDS, facts.levelLabel);
|
|
840
|
+
await notice(req, res, 'success', `${words}${lowered}`);
|
|
841
|
+
}
|
|
842
|
+
// the keys the notice changed: taken back to the row's values when the start does not stand (its sentence would be
|
|
843
|
+
// untrue, and an app that changes the session later in the request, a layout that reads its notices, would save it)
|
|
844
|
+
const told = mode.snapshot(req.session);
|
|
845
|
+
const noticeKeys = [...new Set([...Object.keys(pre), ...Object.keys(told)])]
|
|
846
|
+
.filter((k) => k !== 'cookie' && k !== R.VISIT_KEY && stable(pre[k]) !== stable(told[k]));
|
|
847
|
+
const takeBack = (row) => {
|
|
848
|
+
for (const k of noticeKeys) {
|
|
849
|
+
if (row && row[k] !== undefined) req.session[k] = JSON.parse(JSON.stringify(row[k])); else delete req.session[k];
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
// review round 4: what the notice ADDED to each of its keys, and its removal from a value (a row this start's own
|
|
853
|
+
// write landed in still holds the notice, so taking the keys back to the row's would keep it)
|
|
854
|
+
const added = Object.fromEntries(noticeKeys.map((k) => [k, addedBy(pre[k], told[k])]));
|
|
855
|
+
const removeNotice = (t) => {
|
|
856
|
+
for (const k of noticeKeys) {
|
|
857
|
+
const v = takeOut(t[k], added[k]);
|
|
858
|
+
if (v === undefined || (isPlainObject(v) && Object.keys(v).length === 0)) delete t[k]; else t[k] = v;
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
// THE WRITE: only while the stored session holds no visit (review round 1: two starts at once in two tabs; the
|
|
862
|
+
// later write overwrote the visit the other had started, which then had no stop row), AND still stands where `entry`
|
|
863
|
+
// judged the start (review round 3: the write merges into the row, so fleet view switched on in another tab since
|
|
864
|
+
// `entry` was kept beside the visit, CD-60; working in a partner stopped or started meanwhile was not noticed).
|
|
865
|
+
let w;
|
|
866
|
+
try {
|
|
867
|
+
w = await mode.write(req, (row) => row[R.VISIT_KEY] == null && placeOfRow(rec, row) === null, (t) => { t[R.VISIT_KEY] = rec; }, { pre });
|
|
868
|
+
} catch (err) {
|
|
869
|
+
if (claim(rec.id, c.now())) await writeStop(req, rec, 'refused', 'error');
|
|
870
|
+
throw err;
|
|
871
|
+
}
|
|
872
|
+
if (w.outcome !== 'saved') {
|
|
873
|
+
// the start row just written is paired with its stop row: the record never shows a visit that never was
|
|
874
|
+
// signed out meanwhile → `signed_out`; another visit in force → `refused`, `busy`; fleet view on, or another place
|
|
875
|
+
// → `refused`, `fleet-view` / `acting` / `partner`; the store failing → `refused`, `error`
|
|
876
|
+
const why = w.outcome !== 'changed' ? null
|
|
877
|
+
: (w.row && w.row[R.VISIT_KEY] != null ? 'busy' : placeOfRow(rec, w.row) || 'busy');
|
|
878
|
+
if (claim(rec.id, c.now())) {
|
|
879
|
+
if (w.outcome === 'gone') await writeStop(req, rec, 'signed_out', null);
|
|
880
|
+
else await writeStop(req, rec, 'refused', why || 'error');
|
|
881
|
+
}
|
|
882
|
+
logger.warn(`visits: user ${rec.userId}: the start at ${cus} was not written (the session's row is ${w.outcome}${why ? `, ${why}` : ''}): refused`);
|
|
883
|
+
if (w.outcome === 'gone') return refuse(req, res, 409, 'signed-out', text(messages.signedOut));
|
|
884
|
+
if (w.outcome !== 'changed') throw new Error(`visits: user ${rec.userId}: the start at ${cus} was not written (${w.outcome})`);
|
|
885
|
+
return refuseMoved(req, res, why);
|
|
886
|
+
}
|
|
887
|
+
// THE CONFIRMING READ (review round 2): two starts whose re-reads both answered before either save landed both
|
|
888
|
+
// saved, and the later one overwrote the earlier. After this start's write has landed, the row is read once more: a
|
|
889
|
+
// row holding ANOTHER visit means this one was overwritten: its start row gets its stop row (`refused`, `busy`), its
|
|
890
|
+
// notice is taken back to the row's (the other start's write replaced the row with one read before this write
|
|
891
|
+
// landed, so without it) and the answer is 409. Gone: signed out after the write landed (stop row `signed_out`). No
|
|
892
|
+
// visit: ended elsewhere after it landed (the stop row is the ender's): the start stood. Unreadable: logged, the
|
|
893
|
+
// start stands as written. What is left (README): a confirming read that answers before the other start's save lands.
|
|
894
|
+
// Review round 3: a row (with this visit, or with none) that no longer stands where `entry` judged the start (fleet
|
|
895
|
+
// view on, another place) refuses it too: `refused` because `fleet-view` / `acting` / `partner`, 409. When the row
|
|
896
|
+
// still holds this visit it is ended through the session mode (its stop row with the end).
|
|
897
|
+
const seen = await readRow(req);
|
|
898
|
+
if (seen.unreadable) {
|
|
899
|
+
logger.error(`visits: user ${rec.userId}: the start at ${cus} could not be confirmed (${seen.unreadable}): it stands as written`);
|
|
900
|
+
} else if (seen.row === null || (seen.row[R.VISIT_KEY] != null && seen.row[R.VISIT_KEY].id !== rec.id)) {
|
|
901
|
+
takeBack(seen.row);
|
|
902
|
+
const gone = seen.row === null;
|
|
903
|
+
if (claim(rec.id, c.now())) await writeStop(req, rec, gone ? 'signed_out' : 'refused', gone ? null : 'busy');
|
|
904
|
+
logger.warn(`visits: user ${rec.userId}: the start at ${cus} was ${gone ? 'signed out' : 'overwritten by another start'} as it landed: refused`);
|
|
905
|
+
return gone ? refuse(req, res, 409, 'signed-out', text(messages.signedOut)) : refuse(req, res, 409, 'busy', text(messages.busy));
|
|
906
|
+
} else {
|
|
907
|
+
const why = placeOfRow(rec, seen.row);
|
|
908
|
+
if (why) {
|
|
909
|
+
logger.warn(`visits: user ${rec.userId}: the start at ${cus} landed where it was not judged (${why}): refused`);
|
|
910
|
+
if (seen.row[R.VISIT_KEY] != null) {
|
|
911
|
+
// still stored: ended through the session mode, its stop row written by the end (CD-23 sentence flashed). The
|
|
912
|
+
// notice keys are first taken to the row's (another tab's notice kept), and the end's own write removes what
|
|
913
|
+
// this start's notice added (review round 4: it was left beside the end's sentence)
|
|
914
|
+
takeBack(seen.row);
|
|
915
|
+
await endWith(req, res, 'refused', why, { notice: true, alsoChange: removeNotice });
|
|
916
|
+
} else {
|
|
917
|
+
takeBack(seen.row);
|
|
918
|
+
if (claim(rec.id, c.now())) await writeStop(req, rec, 'refused', why);
|
|
919
|
+
}
|
|
920
|
+
return refuseMoved(req, res, why);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
if (rec.acting) {
|
|
924
|
+
const partner = await c.partnerById(rec.partnerId).catch(() => null);
|
|
925
|
+
tell({ partnerId: rec.partnerId, partnerName: partner ? partner.name : null, customer: { id: cus, name: rec.customerName },
|
|
926
|
+
person: { id: rec.userId, name: String(user.display_name || user.username || rec.userId) }, company: { id: rec.homePartnerId, name: home ? home.name : null },
|
|
927
|
+
level: facts.level, levels: facts.levels, reason: rec.reason, letIn: { ...lv.letIn }, letInBy: lv.grant ? lv.grant.given_by_name || null : null,
|
|
928
|
+
visit: rec.id, until: facts.untilIso });
|
|
929
|
+
}
|
|
930
|
+
if (wantsJson(req)) return res.json({ ok: true, visit: facts });
|
|
931
|
+
return res.redirect(safePath(c.paths.landing, facts));
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** LEAVE (POST <mountPath>/leave): needs only a session (CD-21). Back to the customer's page. */
|
|
935
|
+
async function leave(req, res) {
|
|
936
|
+
const rec = req.session && req.session[R.VISIT_KEY];
|
|
937
|
+
if (rec == null) return res.redirect(c.paths.customers);
|
|
938
|
+
const ended = await endWith(req, res, 'left', null);
|
|
939
|
+
const cus = rec && typeof rec.customerId === 'string' && R.CUSTOMER_ID.test(rec.customerId) ? rec.customerId : null;
|
|
940
|
+
if (ended) await notice(req, res, 'success', text(messages.left, (rec && rec.customerName) || 'the customer'));
|
|
941
|
+
return res.redirect(cus ? safePath(c.paths.customer, cus) : c.paths.customers);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* THE VISIT'S STATE (GET <mountPath>/visit), for the typed-work notice (CD-23, assets/visit.js): `X-Work-In: live`
|
|
946
|
+
* while the visit is in force; `ended` when track ended it on this very request (the CD-23 sentence in `text`);
|
|
947
|
+
* `outside` when there is none. JSON, never cached. Track has judged the request before it gets here.
|
|
948
|
+
*/
|
|
949
|
+
function status(req, res, next) {
|
|
950
|
+
const j = judged.get(req);
|
|
951
|
+
if (!j) return wiring(req, res, 'visits: the status route ran before visits.track (mount track before every router)');
|
|
952
|
+
res.set('Cache-Control', 'no-store');
|
|
953
|
+
if (j.live) {
|
|
954
|
+
const f = factsOf(j.live.rec);
|
|
955
|
+
res.setHeader(R.VISIT_MARKER, 'live');
|
|
956
|
+
return res.json({ state: 'live', customer: f.customerName, level: f.level, until: f.untilIso });
|
|
957
|
+
}
|
|
958
|
+
const e = res.locals.visitEnded;
|
|
959
|
+
if (e) {
|
|
960
|
+
res.setHeader(R.VISIT_MARKER, 'ended');
|
|
961
|
+
return res.json({ state: 'ended', customer: e.customerName, why: e.why, text: e.text });
|
|
962
|
+
}
|
|
963
|
+
res.setHeader(R.VISIT_MARKER, 'outside');
|
|
964
|
+
return res.json({ state: 'outside', text: null });
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/** The routes, on a router from the app's `Router` (express.Router), mounted on the top-level app (full paths). */
|
|
968
|
+
function routes(Router) {
|
|
969
|
+
if (!isFn(Router)) throw new Error('visits.routes: Router is required (express.Router): this package does not load express itself');
|
|
970
|
+
const router = Router();
|
|
971
|
+
router.post(workInPath, (req, res, next) => { start(req, res).catch(next); });
|
|
972
|
+
router.post(leavePath, (req, res, next) => { leave(req, res).catch(next); });
|
|
973
|
+
router.get(statusPath, status);
|
|
974
|
+
return router;
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// ── the app's own ends ──────────────────────────────────────────────────────────────────────────────────────────
|
|
978
|
+
|
|
979
|
+
/** END from the app's own flows: `left` (it stops working in a partner) or `signed_out` (before destroy()). */
|
|
980
|
+
async function end(req, why) {
|
|
981
|
+
if (why !== 'left' && why !== 'signed_out') throw new Error(`visits.end: why must be 'left' or 'signed_out', not ${String(why)}`);
|
|
982
|
+
return endWith(req, req && req.res, why, null);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/** Middleware: end the visit (if any) first, then go on: in front of the app's stop-acting route. */
|
|
986
|
+
function endFirst(why) {
|
|
987
|
+
if (why !== 'left' && why !== 'signed_out') throw new Error(`visits.endFirst: why must be 'left' or 'signed_out', not ${String(why)}`);
|
|
988
|
+
return (req, res, next) => { end(req, why).then(() => next(), next); };
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* A SESSION ENDED WITHOUT A REQUEST OF ITS OWN (a back-channel sign-out deletes stored sessions): the stop row of the
|
|
993
|
+
* visit it held, from the stored session. → whether a row was written. Once per visit in this process.
|
|
994
|
+
*/
|
|
995
|
+
async function recordEnded(sess, why = 'signed_out') {
|
|
996
|
+
if (!R.VISIT_ENDINGS.includes(why)) throw new Error(`visits.recordEnded: why must be one of ${R.VISIT_ENDINGS.join(', ')}`);
|
|
997
|
+
const rec = sess && sess[R.VISIT_KEY];
|
|
998
|
+
if (!rec || !sess.user || !R.recordOk(rec, kindKeys)) return false;
|
|
999
|
+
if (!claim(rec.id, c.now())) return false;
|
|
1000
|
+
await writeStop({ session: sess, headers: {}, ip: null }, rec, why, null);
|
|
1001
|
+
return true;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/** `{ working_in, visit }` for a request a visit's gate pinned, else null: what the app's audit helper adds (CD-45). */
|
|
1005
|
+
function stampOf(req) {
|
|
1006
|
+
const r = requestOf(req);
|
|
1007
|
+
return record.stampFor((r && typeof r === 'object' && pinnedFacts.get(r)) || null);
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
return {
|
|
1011
|
+
loaded, track, gate, requirePermission, routes, entry, end, endFirst, recordEnded, stampOf, requestOf, forStream, forget, current, classify,
|
|
1012
|
+
/** Is `fn` a gate this object made (for an app's wiring test over its route stacks)? */
|
|
1013
|
+
isGate: (fn) => gateFns.has(fn),
|
|
1014
|
+
/** Is `fn` a route guard this object's requirePermission made? */
|
|
1015
|
+
isVisitGuard: (fn) => guardFns.has(fn),
|
|
1016
|
+
/** How much this process holds: the fit memo's entries (at most FIT_MAX) and the visits it ended (at most ENDED_MAX). */
|
|
1017
|
+
stats: () => ({ fitMemo: fitMemo.size, ended: endedIds.size, fitMax: FIT_MAX, endedMax: ENDED_MAX }),
|
|
1018
|
+
kinds: kindKeys, workInPath, leavePath, statusPath
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
module.exports = { createVisits };
|