@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
package/CHANGELOG.md
CHANGED
|
@@ -1,9 +1,40 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## 0.
|
|
3
|
+
## 0.2.0
|
|
4
4
|
|
|
5
5
|
_(not yet released)_
|
|
6
6
|
|
|
7
|
+
Additive: fleet view, and an idle end for working in a partner (the owner's decisions of 29 Nov 2026). Everything 0.1.0
|
|
8
|
+
exports keeps its path, identity and behaviour; an app that only bumps notices nothing.
|
|
9
|
+
|
|
10
|
+
- Scope: `createFleetView({ permission, can, scopeOf, userIdOf, idleMinutes, now, isBackground, audit, logger, readOnlyExcept, home,
|
|
11
|
+
startPath, stopPath, flash, wantsJson, refusalView, messages })`, self-contained (no other factory of this package
|
|
12
|
+
needed): `isOn(req, res)`, `middleware` (the idle end with its one-time notice, the activity clock, the locals, the
|
|
13
|
+
read-only guard), `routes(Router)` (start, stop), `classify(method, path)` (the guard's decision, for an app's
|
|
14
|
+
route-table test), `end(req, reason)`, `writesRefused(req)`. Audited as `fleet_view.start` and `fleet_view.stop`
|
|
15
|
+
(`detail.reason`: `left`, `idle`, `permission`, `scope`, `user`, `error`, `acting`, `signout`). The guard judges the raw
|
|
16
|
+
target and refuses one that is not plain (`#`, backslash, control characters) and one Express would dispatch on another
|
|
17
|
+
path; a `:name` entry segment matches a conservative id only. The session is written only on start, stop and end and
|
|
18
|
+
for a throttled activity stamp (never at 0 minutes); the stamp and the automatic end (and the acting idle end's writes)
|
|
19
|
+
re-read the session's row and, if it still holds the same mode, write that row plus the request's own changes (against
|
|
20
|
+
the session as loaded, kept by `fleet.loaded` / the acting `loaded`, mounted directly after the session) plus the
|
|
21
|
+
package's change; otherwise nothing. What remains is one store round trip
|
|
22
|
+
(README, "When the package writes the session").
|
|
23
|
+
- Views: `fleet-view-banner.ejs` and `fleet-view-button.ejs` beside `acting-banner.ejs` (classes `fleet-view-banner`,
|
|
24
|
+
`btn-fleet-view`; the app adds two CSS rules).
|
|
25
|
+
- Scope: `createWriteGate`'s optional `fleetView`: the house reading becomes "the house's rows unless the permission is
|
|
26
|
+
held AND fleet view is on"; while the mode is on `writeScope` is null, `createsLand` false and `refusal` answers
|
|
27
|
+
`reason: 'fleetView'` (`messages.fleetView` required then). Absent: 0.1.0.
|
|
28
|
+
- Partners: `createActingIdle({ idleMinutes, now, isBackground, audit, logger, auditScopes, run, flash, messages })` with `before` and
|
|
29
|
+
`after` around an app's own scope middleware, and `tenancy.requestScope({ actingIdle })` running the same two halves
|
|
30
|
+
around this package's. 0 minutes is no idle end and no session write. The stop row follows `auditScopes.stop`.
|
|
31
|
+
`requestScope()` with no argument is 0.1.0's.
|
|
32
|
+
- One idle rule (`lib/scope/idle.js`) for both modes.
|
|
33
|
+
- README: "Fleet view", "The idle end of working in a partner"; a new app's `auditScopes.start` is `'both'` (the owner's
|
|
34
|
+
decision; it said "owner to confirm").
|
|
35
|
+
|
|
36
|
+
## 0.1.0 — 2026-11-29 (UTC, as published)
|
|
37
|
+
|
|
7
38
|
- Scope: `createTenancy({ db, logger, dbKind, platformRequiresHouse, partnerModel, contactScope, beforeEachPartner,
|
|
8
39
|
refreshTokenOwner, unscopedRedirect, actingRequiresActive, activeMaxAgeMs, activeLoadTimeoutMs, now, timers })` — the starter's `lib/tenant.js` and `lib/scope.js` (every name and signature),
|
|
9
40
|
plus `asOwnPartner` (the hub, the soc app), the desk app's house rule (`platformRequiresHouse`, `isPlatformUser`,
|
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ It returns one object. Every name and signature of the starter's `lib/tenant.js`
|
|
|
53
53
|
| `runWithTenant(ctx, fn)`, `currentTenant()` | db-worker's, re-exported |
|
|
54
54
|
| `asInstallation(fn)`, `acrossAll(fn)`, `run(ctx, fn)`, `forEachScope(fn, opts)` | the seam: `asHouse`, `asPlatform`, `runWithTenant`, `forEachPartner` |
|
|
55
55
|
| `atBoot(fn)` → Promise | seeds the house at platform scope, then runs `fn` in the house scope |
|
|
56
|
-
| `requestScope()` → middleware | after the session, before the first router; an unscopable session destroyed and redirected; anonymous through `asHouse`; with `platformRequiresHouse` the house id is resolved first |
|
|
56
|
+
| `requestScope()` → middleware | after the session, before the first router; an unscopable session destroyed and redirected; anonymous through `asHouse`; with `platformRequiresHouse` the house id is resolved first. `requestScope({ actingIdle })` (0.2.0, optional) adds the idle end of working in a partner around it ("The idle end of working in a partner", under Partners) |
|
|
57
57
|
| `forApiUser(user)` → `{ scope, partnerId }` \| null | a number or a digit string, nothing else; platform per `isPlatformUser` |
|
|
58
58
|
| `asOwnerOf(user, fn)` | `asPartner(user.partner_id, fn)` |
|
|
59
59
|
| `asRefreshTokenOwner(rawToken, fn)` → Promise | `fn` in the token owner's scope, or where it stands for an unknown token |
|
|
@@ -155,6 +155,7 @@ const gate = createWriteGate({
|
|
|
155
155
|
| `logger` | yes | `{ warn }`: every refusal is logged once | |
|
|
156
156
|
| `wantsJson(req)` | no | default: `X-Requested-With: fetch` | |
|
|
157
157
|
| `refusalView` | no | default `'errors/generic'`: the view the handler renders with `{ title, message }` | |
|
|
158
|
+
| `fleetView` | no (0.2.0; absent is 0.1.0) | what `createFleetView` returned. The house reading becomes **the house's rows unless the `houseReading` permission is held AND fleet view is on**; while the mode is on no write is allowed at all: `writeScope` null (the house's own rows too), `createsLand` false, `refusal` `{ reason: 'fleetView' }` with `messages.fleetView` (required then). Needs `houseReading` set. A job (`null` request) is unaffected. `whileActing` is untouched beside it: it governs the acting case, and fleet view is never on while acting | an app adopting fleet view |
|
|
158
159
|
|
|
159
160
|
| Function | |
|
|
160
161
|
|---|---|
|
|
@@ -168,7 +169,7 @@ const gate = createWriteGate({
|
|
|
168
169
|
| `crossTenantWriteHandler()` → Express error handler | a 23503 on a composite tenant key (`fk_*_partner`) becomes a 409 sentence, JSON for a fetch; every other error is passed on untouched |
|
|
169
170
|
| `crossTenantRefusalOf(err, req)` → `{ kind, title, message }` \| null | the handler's predicate, for a route that catches and flashes its own error |
|
|
170
171
|
| `actingElsewhere(req)` → boolean | the scope moved off the user's own partner (never the raw session flag) |
|
|
171
|
-
| `houseReadingOf(req, can)` → Promise\<number \| null> | the house id when the request is the house reading, for `readScope` |
|
|
172
|
+
| `houseReadingOf(req, can)` → Promise\<number \| null> | the house id when the request is the house reading, for `readScope`; with `fleetView`, null (every partner) only when `can(houseReading)` AND `fleetView.isOn(req)` |
|
|
172
173
|
|
|
173
174
|
**Which context the gate judges, and where its runner runs** (one rule for `writeScope` and `readScope`):
|
|
174
175
|
|
|
@@ -192,6 +193,234 @@ partner scope as at platform scope, so it runs there even when called inside `ac
|
|
|
192
193
|
| platform scope, not acting | the user's own partner's (the house's) | runs at that partner's scope (`asPartner`) |
|
|
193
194
|
| platform scope, not acting | another partner's | null, on both engines |
|
|
194
195
|
|
|
196
|
+
### `createFleetView(options)` — fleet view
|
|
197
|
+
|
|
198
|
+
A **session mode** (the owner's decisions of 29 Nov 2026). The normal view, always after sign-in, is your own
|
|
199
|
+
organisation's customers (house staff at platform scope: the house's own); holding the fleet permission changes nothing
|
|
200
|
+
there. A house user at platform scope who holds it switches fleet view on with one click (no confirmation). While it is
|
|
201
|
+
on, a banner shows on every page, pages read every partner's rows, and **nothing can be changed**. It ends when the
|
|
202
|
+
person leaves it, when they sign out, and after the app's idle period. Entering and leaving are audited. It is never on
|
|
203
|
+
together with working in a partner. Each app has its own switch (each has its own session).
|
|
204
|
+
|
|
205
|
+
Self-contained: an app that takes this package for fleet view alone passes in what it needs. Nothing else of this
|
|
206
|
+
package (`createTenancy` included) is required.
|
|
207
|
+
|
|
208
|
+
```js
|
|
209
|
+
// an app with its own lib/tenant.js
|
|
210
|
+
const fleet = createFleetView({
|
|
211
|
+
permission: 'fleet.analyse', // the app's fleet permission
|
|
212
|
+
can: (req, res, p) => res.locals.can(p), // the app's own check; only `true` counts
|
|
213
|
+
scopeOf: (req) => (tenant.contextFor(req) || {}).scope, // 'platform' | 'partner' | none; acting is 'partner'
|
|
214
|
+
userIdOf: (req) => (req.session.user ? req.session.user.id : null), // the signed-in user's stable id, synchronously
|
|
215
|
+
idleMinutes: () => settings.fleetViewIdleMinutes, // sync or async; a whole number; 0 = no idle end (apps: 15)
|
|
216
|
+
now: Date.now,
|
|
217
|
+
isBackground, // live streams and polls: NOT activity (the notify package's predicate)
|
|
218
|
+
audit, // (req, action, opts), the app's staff audit helper
|
|
219
|
+
logger, // { warn, error }
|
|
220
|
+
readOnlyExcept: ['POST /ask', 'POST /search/:id/run', 'POST /logout'], // REQUIRED, may be []
|
|
221
|
+
home: '/', startPath: '/fleet-view/start', stopPath: '/fleet-view/stop',
|
|
222
|
+
flash: undefined, wantsJson: undefined, refusalView: undefined, messages: {} // optional, below
|
|
223
|
+
});
|
|
224
|
+
app.use(session); app.use(fleet.loaded); // DIRECTLY after the session: the session as loaded
|
|
225
|
+
app.use(scopeMiddleware); app.use(bodyParser); app.use(csrf);
|
|
226
|
+
app.use(fleet.middleware); // after session and scope, BEFORE the app's flash-to-locals and EVERY router
|
|
227
|
+
app.use(fleet.routes(express.Router)); // POST startPath, POST stopPath (full paths: mount on the top-level app)
|
|
228
|
+
// views: [..., require('@aria-framework/tenancy').viewsDir]; in the layout:
|
|
229
|
+
// <%- include('fleet-view-banner') %> beside include('acting-banner'), outside the page container
|
|
230
|
+
// <%- include('fleet-view-button') %> in the top bar
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Every function option and `permission`, `logger`, `readOnlyExcept`, `home`, `startPath` and `stopPath` is **required
|
|
234
|
+
with no default**: an absent or malformed one is refused at construction, by name. `flash` defaults to
|
|
235
|
+
`res.flash(kind, text, callback)` (connect-flash style WITH a callback, as `actingRoutes`), `wantsJson` to
|
|
236
|
+
`X-Requested-With: fetch` or an `Accept` of JSON without HTML, `refusalView` to `'errors/generic'` (rendered with
|
|
237
|
+
`{ title, message }`), `messages` to the sentences below.
|
|
238
|
+
|
|
239
|
+
**Requirements on the app** (each is a way the guarantee is lost if the app does otherwise):
|
|
240
|
+
|
|
241
|
+
- `fleet.loaded` is mounted **directly after the session middleware**, and the middleware after the session and scope
|
|
242
|
+
middleware and **before every router**: a router mounted earlier is not guarded;
|
|
243
|
+
- the start and stop routes sit **behind the app's CSRF middleware** (both are state-changing POSTs);
|
|
244
|
+
- the app's sign-out **calls `await fleet.end(req, 'signout')` before it destroys the session**, so the audit trail
|
|
245
|
+
has the row (after `destroy()` there is no session to end);
|
|
246
|
+
- an idle end is audited when the **next request** detects it, and never if no request follows;
|
|
247
|
+
- **WebSocket and other socket traffic does not pass through Express middleware**: whatever it can change is the app's
|
|
248
|
+
to gate itself.
|
|
249
|
+
|
|
250
|
+
**`isOn(req, res)` → Promise\<boolean>.** True only when ALL of these hold on this request:
|
|
251
|
+
|
|
252
|
+
1. the session carries the mode (`req.session.fleetViewSince`, set only by the start route), switched on by the user
|
|
253
|
+
`userIdOf(req)` names NOW (`fleetViewUser`, stored at the start): another account signed in on the same session ends
|
|
254
|
+
it (reason `user`);
|
|
255
|
+
2. `scopeOf(req)` answers `'platform'`, and the session carries no `actingPartnerId`;
|
|
256
|
+
3. `can(req, res, permission)` answers exactly `true` (a truthy non-boolean is not held);
|
|
257
|
+
4. the idle period has not run out: `idleMinutes()` is 0, or less than that many minutes have passed since the last
|
|
258
|
+
activity stamp `fleetViewLastActive` (at exactly the period it is off).
|
|
259
|
+
|
|
260
|
+
Decided on every request from the session and the app's answers; nothing is kept across requests (the middleware's
|
|
261
|
+
verdict is reused only for the same request object, so a later call on that request, the write gate's house reading,
|
|
262
|
+
needs no `res`). A revoked permission, a start of acting or another account makes it false on the next request.
|
|
263
|
+
**It fails closed:** a throw from `can`, `scopeOf`, `userIdOf` or `idleMinutes`, or an `idleMinutes()` that is not a
|
|
264
|
+
whole number of 0 or more, is false; through the middleware the mode then ends (reason `error`) and the person sees the
|
|
265
|
+
normal view with one line, "Fleet view ended because it could not be checked. You can switch it on again."
|
|
266
|
+
|
|
267
|
+
**`middleware`**, per request:
|
|
268
|
+
|
|
269
|
+
- the session carries the mode but `isOn` is false: the mode ends. The person is told once through `flash` with kind
|
|
270
|
+
**`'warning'`** (one the framework's `ui/flash` partial renders, and one that stays until dismissed): "Fleet view ended
|
|
271
|
+
after N minutes without activity.", "… because you no longer have the permission for it.", "… because it is only
|
|
272
|
+
available at platform scope, not while working in a partner.", "… because it was switched on by another account.", or
|
|
273
|
+
the `error` line above. Then the row is re-read and, if it still holds the mode, the row (with this request's changes) minus the
|
|
274
|
+
mode is saved before the request goes on, and `fleet_view.stop` is audited with the reason (`idle` with `minutes`,
|
|
275
|
+
`permission`, `scope`, `user`, `error`); otherwise nothing is written or audited (below). Mount it before the middleware that
|
|
276
|
+
moves flash messages into the page's locals, so the line shows on this very page;
|
|
277
|
+
- the mode is on, the request is not background and a stamp is due: `fleetViewLastActive = now()`, written only after a
|
|
278
|
+
re-read (below) and saved before the request goes on. A stamp is due at most once a minute (`ACTIVITY_STAMP_MAX_MS`), for a period under ten minutes
|
|
279
|
+
at most once per tenth of it, and **never at 0 minutes**. The idle end is judged from the stamp, so the mode ends
|
|
280
|
+
between `minutes − min(1 minute, minutes/10)` and `minutes` after the last activity. A background request
|
|
281
|
+
(`isBackground`, or one whose `isBackground` throws) is still judged, it only does not count: without this a page
|
|
282
|
+
left open would keep the mode on for ever through its live stream;
|
|
283
|
+
- `res.locals.fleetView = { on, canStart, startPath, stopPath, returnTo }`: `canStart` (offer the switch) is true only
|
|
284
|
+
while off, for a signed-in user with an id, at platform scope, not acting, holding the permission; `returnTo` is this
|
|
285
|
+
GET page's own address when it is a safe return address, else null;
|
|
286
|
+
- **the read-only guard**, in this same one place (below).
|
|
287
|
+
|
|
288
|
+
**When the package writes the session, and what is left.** express-session writes a request's session at the END of
|
|
289
|
+
the request when it changed since it was last saved, so a slow request that carries an unsaved change writes back what
|
|
290
|
+
it loaded, over a stop or a sign-out that happened meanwhile. This package writes the session at these times only:
|
|
291
|
+
when fleet view starts or stops (the two routes), when the app calls `end`, when the middleware ends the mode by
|
|
292
|
+
itself, and for the activity stamp, which is due at most once a minute and never at 0 minutes (the acting idle end:
|
|
293
|
+
its clock's start and removal, its stamp, and its automatic end). Start, stop and `end` are the person's own act on
|
|
294
|
+
their current session and are saved at once.
|
|
295
|
+
|
|
296
|
+
**Every other write is the row read back, plus this request's changes, plus this package's change.** After all of the
|
|
297
|
+
request's own checks are done (`userIdOf`, `scopeOf`, `can`, `idleMinutes`), the session's row is read again from the
|
|
298
|
+
store (`req.sessionStore.get(req.sessionID)`). If it still holds the same mode (fleet view: the same start, switched
|
|
299
|
+
on by the same user, signed in as that user; acting: the same partner), what is written is: that row as the store holds
|
|
300
|
+
it now; over it, every key this request itself changed in memory since the session was loaded (an earlier middleware's
|
|
301
|
+
`lastActivity`, this package's notice), objects merged key by key; and this package's own change (the stamp, or the
|
|
302
|
+
mode's fields removed by an automatic end). That becomes the session in memory and is saved, in the read's callback,
|
|
303
|
+
with nothing awaited between the answer and the save call. express-session's own end-of-request save then has nothing
|
|
304
|
+
left to write, because `save()` records the saved state and it writes only a session changed after that; so the store
|
|
305
|
+
is not overwritten a moment later by the stale copy this request loaded (`test/scope/sessionRaces.js`, "express-session's
|
|
306
|
+
own end-of-request save"). So another request's write (a flash, a second factor, a session version) is carried
|
|
307
|
+
through, and an earlier middleware's write never makes this package skip: the stamp is written and the automatic end
|
|
308
|
+
happens on the first request past the period, with its stop row, whatever else changed in the row.
|
|
309
|
+
|
|
310
|
+
**What a request sees when the row changed under it.** If the row still holds the same mode, the page reads by it
|
|
311
|
+
(fleet view on, the stamp written), whatever else changed. If the row is gone (the person signed out), no longer holds
|
|
312
|
+
the mode (left in another tab, another account signed in, acting stopped), or cannot be read (no `sessionStore`, or
|
|
313
|
+
`get` fails), nothing is written or audited, the request reads the normal view (no banner on that page) while its writes
|
|
314
|
+
are still refused, and the next request judges again; this package's keys in memory are put back, or aligned with the
|
|
315
|
+
row read back when the app itself changed the session in memory, so express-session's end-of-request save cannot bring
|
|
316
|
+
a left mode back.
|
|
317
|
+
|
|
318
|
+
**What is left, in plain words.** (1) One store round trip, between the re-read's answer and the save landing: a write
|
|
319
|
+
by another request that lands in it is overwritten, and **a sign-out that lands in it is undone by an upserting session
|
|
320
|
+
store (the apps' PostgreSQL store, like MemoryStore, upserts on `set`): the signed-out session is re-created, signed
|
|
321
|
+
in** (`test/scope/sessionRaces.js`, "THE REMAINDER, documented"). (2) A key that BOTH this request and another changed
|
|
322
|
+
in the wait takes this request's value. For flash messages that means: two of the same kind in one array, the other's
|
|
323
|
+
is lost; two of different kinds are both kept ONLY when the session already held a flash object when this request loaded
|
|
324
|
+
it (the objects are then merged key by key) — when it held none, which is the usual case, this request's flash object
|
|
325
|
+
replaces the other's whole; and a request that consumes a flash drops one added during its wait. The same is true of ANY
|
|
326
|
+
code in the app that writes the session during a request that
|
|
327
|
+
overlaps another (consuming a flash message is enough); an app that wants this closed for good needs a store-level
|
|
328
|
+
guard (a store whose `set` will not re-create a row that was destroyed, or that merges), which this package does not
|
|
329
|
+
provide.
|
|
330
|
+
|
|
331
|
+
**Mounting order that remains:** `fleet.loaded` (or the acting idle end's `loaded`; either serves both) directly after
|
|
332
|
+
the session middleware, before anything that changes the session: it keeps the session as loaded, which tells this
|
|
333
|
+
request's own changes from the row's. A session in fleet view that reaches the middleware without it is answered
|
|
334
|
+
with an error (not silently written). `userIdOf` must answer synchronously.
|
|
335
|
+
|
|
336
|
+
**The cost:** at most one extra store read per session per stamp interval (one minute; a tenth of a period under ten
|
|
337
|
+
minutes), plus one at each automatic end, plus one when the acting clock starts or is removed. A request that is not
|
|
338
|
+
due a stamp reads nothing extra. The copy of the session as loaded (one serialisation) is taken only for a session that
|
|
339
|
+
carries fleet view or the acting keys; every other request of every user takes none.
|
|
340
|
+
|
|
341
|
+
**The read-only guard.** While the mode is on, every request whose method is not GET, HEAD or OPTIONS is refused before
|
|
342
|
+
any router runs, unless `classify` lets it through: the start route (a double click or a second tab is harmless: it
|
|
343
|
+
changes nothing and goes back to the page), the stop route, or a `readOnlyExcept` entry. A page request gets 403 and
|
|
344
|
+
`refusalView` with "Fleet view is read-only. Leave fleet view to change anything."; with no view engine (Express 5's
|
|
345
|
+
`render` throws at once) or a view that fails, the same sentence as `text/plain`, still 403; a request that asks for
|
|
346
|
+
JSON gets 403 `{ ok: false, type: 'error', code: 'FLEET_VIEW_READ_ONLY', message }`. Nothing is written, no downstream
|
|
347
|
+
handler runs, and the refusal is logged at warn.
|
|
348
|
+
|
|
349
|
+
- **What it judges.** The RAW request target, `req.originalUrl`, as the client sent it (at any mount, in a sub-app
|
|
350
|
+
too: entries and paths are full paths from the top-level app). First, a target that is not **plain** is refused
|
|
351
|
+
outright: anything but `/` followed by RFC 3986 path and query characters (letters, digits, `- . _ ~ ! $ & ' ( ) * +
|
|
352
|
+
, ; = : @ / ?`, and `%` with two hex digits); so `#`, a backslash, a space or control character, anything outside
|
|
353
|
+
ASCII. No honest client sends these, and they are what makes Express's parser disagree with a plain split: for any
|
|
354
|
+
target with `#` or whitespace parseurl falls back to `url.parse`, which cuts at the `#` and turns backslashes into
|
|
355
|
+
slashes, so `POST /search/1\delete#/run` is dispatched to `/search/:id/delete`. For a plain target, parseurl's own
|
|
356
|
+
answer (its fast path) is the part before the first `?`, and that is the path judged. Then, for a request it would
|
|
357
|
+
let through, the guard also requires that Express dispatches on that path at its mount (`req.baseUrl + req.path`,
|
|
358
|
+
Express's own pathname there): a URL rewritten by earlier middleware is refused.
|
|
359
|
+
- **How an entry matches.** Exactly: the same method; the same number of segments (a trailing slash is another
|
|
360
|
+
path); each literal segment equal, case included; each `:name` segment one conservative id: letters, digits, `_`
|
|
361
|
+
and `-`, 1 to 64 characters, never `%`, `.`, `+`, `@` or a slash (or a route table's own `:name`, so a route-table
|
|
362
|
+
walk classifies alike). An entry that is not `METHOD /literal/or/:name/segments` (literal segments of letters,
|
|
363
|
+
digits, `. _ ~ -`; no query, wildcard, empty, dot, encoded or mixed segment) is refused at construction. So `/ASK`,
|
|
364
|
+
`/ask/`, `/a%73k`, `/askme`, `/ask/x`, `/./ask`, `/search/1.2/run` and `PUT /ask` are refused when only `POST /ask`
|
|
365
|
+
and `POST /search/:id/run` are listed.
|
|
366
|
+
- **Its limits.** No method override is honoured anywhere in this stack today (none of the framework, the hub, soc or
|
|
367
|
+
noc mounts one); an app that adds one mounts it BEFORE this middleware, so the guard judges the effective method.
|
|
368
|
+
**A GET handler that changes data is the app's defect, not this guard's**: the guard trusts that GET, HEAD and
|
|
369
|
+
OPTIONS only read. So does an entry the app lists: list only requests that read (a question, a search) or only end
|
|
370
|
+
something (signing out), and know that a listed path reaches whatever the app routes there.
|
|
371
|
+
|
|
372
|
+
**`routes(Router)`**: `POST startPath` and `POST stopPath`, on a router from the app's `express.Router`, mounted on the
|
|
373
|
+
top-level app (the paths are full paths).
|
|
374
|
+
|
|
375
|
+
- Start: allowed only for a signed-in user whose `userIdOf` is not null, at platform scope, not acting (the session's
|
|
376
|
+
`actingPartnerId`, whatever `scopeOf` says), holding the permission; anyone else (a partner's user, an acting house
|
|
377
|
+
user, a house user without the permission, no id, no user, no session) gets 403 with "Fleet view is not available to
|
|
378
|
+
you here.", nothing set, nothing audited. Already on: nothing changes, nothing is audited, back to the page.
|
|
379
|
+
Otherwise `fleet_view.start` is audited BEFORE the session fields are set (a failing audit stops the start), the
|
|
380
|
+
fields (`fleetViewSince`, `fleetViewLastActive`, `fleetViewUser`) are set and saved, and the browser goes back to
|
|
381
|
+
`req.body.returnTo` when it is a safe return address, else `home`. A **safe return address** is a local path of this
|
|
382
|
+
app only: it starts with one `/` not followed by `/` or `\`, has no backslash anywhere, no control character (DEL
|
|
383
|
+
included) or space, and is at most 2048 characters. An absolute URL, `//host`, `///host`, `/\host`, a scheme
|
|
384
|
+
(`javascript:`, `data:`), a bare name, an empty value or a CR/LF all fall back to `home`.
|
|
385
|
+
- Stop: **session-gated, not permission-gated** (it is the only way out, so it must not depend on a permission that may
|
|
386
|
+
be gone): when the session carries the mode, the fields are cleared, `fleet_view.stop` audited with reason `left`,
|
|
387
|
+
the session saved, and the browser goes to `home`; otherwise straight to `home`, nothing audited or written.
|
|
388
|
+
|
|
389
|
+
**`classify(method, target)`** → `'read' | 'start' | 'leave' | 'listed' | 'refused'`: what the guard decides for that
|
|
390
|
+
request while the mode is on, without a request object. The guard calls exactly this with `req.method` and
|
|
391
|
+
`req.originalUrl`. The method is compared upper-cased (an Express route table's keys are lower-case). **How an app
|
|
392
|
+
proves its whole population read-only:** walk its derived route table (every router, every method, with full paths),
|
|
393
|
+
and assert that every non-GET route classifies `'refused'` unless it is deliberately in `readOnlyExcept`; floor the
|
|
394
|
+
population against a count taken another way.
|
|
395
|
+
|
|
396
|
+
**`end(req, reason)`** → Promise\<boolean>: for the app's own flows, when it starts working in a partner (`'acting'`) or
|
|
397
|
+
signs a person out (`'signout'`, before `destroy()`). Clears the fields, audits the stop with the reason, saves the
|
|
398
|
+
session; tells nobody. False, with nothing audited or written, when the mode was not on. An app that offers "work in
|
|
399
|
+
this partner" from fleet view lists that act-as route in `readOnlyExcept` and calls `end(req, 'acting')` in it.
|
|
400
|
+
|
|
401
|
+
**`writesRefused(req)`** → boolean: the session carries the mode (for the write gate; the middleware has already cleared
|
|
402
|
+
a mode that is not on).
|
|
403
|
+
|
|
404
|
+
**Audit actions.** `fleet_view.start` (`{ detail: {} }`) and `fleet_view.stop` (`{ detail: { reason } }`, with `minutes`
|
|
405
|
+
for `idle`), through the app's `audit(req, action, opts)` in the request's own scope (the house, at platform scope).
|
|
406
|
+
Reasons: `left` (the stop route), `idle`, `permission`, `scope`, `user`, `error` (the middleware), `acting`, `signout`
|
|
407
|
+
(`end`).
|
|
408
|
+
|
|
409
|
+
**The settings an app owns:** the permission's name and who holds it; the idle minutes (the apps default to 15, 0 = no
|
|
410
|
+
idle end; the plan puts it on Sign-in & security, platform only); `readOnlyExcept`; the three paths; the CSS. The two
|
|
411
|
+
partials use the classes `fleet-view-banner` and `btn-fleet-view`; the app adds:
|
|
412
|
+
|
|
413
|
+
```css
|
|
414
|
+
.fleet-view-banner { background: color-mix(in srgb, #7C3AED 16%, var(--bs-body-bg)); border-bottom: 2px solid #7C3AED; }
|
|
415
|
+
.btn-fleet-view { border-color: #7C3AED; color: #7C3AED; }
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
Both partials need the app's `csrfToken()` while they draw (they throw without it), draw nothing without
|
|
419
|
+
`locals.fleetView`, and carry no inline script, style or event handler.
|
|
420
|
+
|
|
421
|
+
**With the write gate:** pass the fleet view to `createWriteGate({ …, houseReading: '<the same permission>', fleetView:
|
|
422
|
+
fleet })` (above).
|
|
423
|
+
|
|
195
424
|
## Hosts
|
|
196
425
|
|
|
197
426
|
Which partner a request's host name belongs to, and the brand, time zone and idle timeout a page shows for its
|
|
@@ -555,7 +784,7 @@ app.set('views', [path.join(__dirname, 'views'), require('@aria-framework/tenanc
|
|
|
555
784
|
**`auditScopes: { start, stop }`** (required, no default). Where the two rows land: `start` is `'house'` or
|
|
556
785
|
`'both'`; `stop` is `'partner'`, `'house'` or `'both'`. `'house'` is the operator's own scope (`contextFor` once
|
|
557
786
|
the acting keys are absent), `'partner'` the partner acted in, `'both'` one row in each. The owner decided on 29 Nov
|
|
558
|
-
2026 that the stop entry goes into both logs.
|
|
787
|
+
2026 that the stop entry goes into both logs, and that a NEW app's start entry does too (`start: 'both'`).
|
|
559
788
|
|
|
560
789
|
- **What each row contains.** Both rows of a pair are built by the app's own `audit(req, action, opts)` from the same
|
|
561
790
|
request, so they are the same action and detail: the operator, as the app's own helper writes an actor (`actor_type: 'staff'`, the house user's id and display name or username; an app's helper may add more: the hub's also writes the actor's email and public id), the partner
|
|
@@ -574,7 +803,7 @@ the acting keys are absent), `'partner'` the partner acted in, `'both'` one row
|
|
|
574
803
|
| App | `auditScopes` |
|
|
575
804
|
|---|---|
|
|
576
805
|
| starter, hub, soc, noc, wall, desk | `{ start: 'house', stop: 'partner' }` (today's, in all six) |
|
|
577
|
-
| a new app | `stop: 'both'` (decided
|
|
806
|
+
| a new app | `{ start: 'both', stop: 'both' }` (both decided by the owner) |
|
|
578
807
|
|
|
579
808
|
**`refuseInactive`, and acting inside a partner that is deactivated** (the owner's answers 2 and D-0005). The rule as
|
|
580
809
|
decided: no house operator works inside a deactivated partner. Two halves enforce it: **the switch refuses a deactivated
|
|
@@ -588,6 +817,54 @@ adoption.** `refuseInactive` is required with no default so that no existing app
|
|
|
588
817
|
(`actingLocals`, and the stop route for a `stop` of `'house'` or `'both'`) and `run(context, fn)` (the acting routes, for a
|
|
589
818
|
row written outside the request's own scope).
|
|
590
819
|
|
|
820
|
+
### `createActingIdle(options)` — the idle end of working in a partner
|
|
821
|
+
|
|
822
|
+
Working in a partner can end after a period without activity that the app sets (the owner's decision of 29 Nov 2026;
|
|
823
|
+
**0, the apps' default, is today's behaviour: no idle end, and not one session write from this piece on any
|
|
824
|
+
request**). One implementation, mounted either way:
|
|
825
|
+
|
|
826
|
+
```js
|
|
827
|
+
const actingIdle = createActingIdle({
|
|
828
|
+
idleMinutes: () => settings.actingIdleMinutes, // REQUIRED, sync or async, a whole number; 0 = no idle end
|
|
829
|
+
now: Date.now, isBackground, audit, logger, // REQUIRED (logger: { error })
|
|
830
|
+
auditScopes: { stop: 'partner' }, // REQUIRED, no default: actingRoutes' auditScopes.stop (existing apps 'partner', a new app 'both')
|
|
831
|
+
run: tenancy.run, // REQUIRED for 'partner' and 'both': (ctx, fn), runs fn in a tenant context
|
|
832
|
+
flash: undefined, messages: {} // optional: res.flash(kind, text, callback) by default; idle(minutes, name), error(name)
|
|
833
|
+
});
|
|
834
|
+
// an app with its own acting code and scope middleware:
|
|
835
|
+
app.use(session); app.use(actingIdle.loaded); // directly after the session (needed when anything sits before `before`)
|
|
836
|
+
app.use(actingIdle.before); app.use(appScopeMiddleware); app.use(actingIdle.after);
|
|
837
|
+
// an app on this package's scope part (the same two halves, run around it):
|
|
838
|
+
app.use(tenancy.requestScope({ actingIdle }));
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
- **Requirement:** an app with its own acting code keeps the acting keys every app uses today,
|
|
842
|
+
`req.session.actingPartnerId` and `req.session.actingPartnerName` (hub, soc and noc set exactly these in
|
|
843
|
+
`routes/partners.js`; soc also in `lib/hubSso.js`).
|
|
844
|
+
- **Why two halves.** The end must happen BEFORE the scope middleware fixes the request's tenant: ended after it, the
|
|
845
|
+
very request that found the period over would still run, and write, inside the partner. `before` judges the period and
|
|
846
|
+
clears `actingPartnerId` / `actingPartnerName`; the scope middleware then places the request in the operator's own
|
|
847
|
+
scope; `after` tells the person once, re-reads the row and, if it still works in that partner, saves the session
|
|
848
|
+
and audits `partner.act_as_stop` (`entity_type: 'partner'`, `entity_id`, `detail: { reason: 'idle',
|
|
849
|
+
minutes }`) where `auditScopes.stop` says (`'partner'`: in the partner acted in, through `run`; `'house'`: in the
|
|
850
|
+
operator's own scope, where the request now runs; `'both'`: one row in each); otherwise the session is left as it was
|
|
851
|
+
loaded and nothing is audited. The notice has kind `'warning'`: "Working in <name> ended after N minutes without
|
|
852
|
+
activity." A failing audit row is logged and changes nothing else. The partner's name is the one the act-as route
|
|
853
|
+
stored; the framework's `ui/flash` partial escapes every message (`<%= %>`), which is what makes putting it in the
|
|
854
|
+
notice safe: an app rendering flash messages unescaped must not.
|
|
855
|
+
- **The clock** is the session's `actingIdleAt: { partnerId, at }`. It starts at the first request that sees the partner
|
|
856
|
+
being worked in (a clock for another partner, or none, starts afresh), moves on a request that is not background
|
|
857
|
+
(`isBackground`: live streams and polls) when a stamp is due (at most once a minute, as fleet view's), and is removed
|
|
858
|
+
when the session is not acting. Each of these writes is preceded by a re-read of the session's row and made only if it
|
|
859
|
+
still works in that partner (an automatic end found otherwise is not written and not audited); at 0 minutes none of
|
|
860
|
+
them happens. The rules are the ones fleet view uses (`lib/scope/idle.js`), and the same window applies (see
|
|
861
|
+
"When the package writes the session" under fleet view).
|
|
862
|
+
- **Fail closed:** a throw from `idleMinutes()`, or an answer that is not a whole number of 0 or more, ends working in the
|
|
863
|
+
partner (reason `error`, told), never keeps it unchecked. Not acting, it writes nothing.
|
|
864
|
+
- `tenancy.requestScope()` with no argument is exactly 0.1.0's middleware; its only option is `{ actingIdle }`, and
|
|
865
|
+
anything else is refused. `actingRoutes`, `actingLocals` and the banner are unchanged: the idle end needs no option on
|
|
866
|
+
them (the banner follows `contextFor`, which no longer sees the acting keys).
|
|
867
|
+
|
|
591
868
|
## Wiring the three parts
|
|
592
869
|
|
|
593
870
|
The three parts were built against stand-ins for each other; this is how they join, and it is exactly the assembly
|
|
@@ -601,7 +878,7 @@ app code the integration app has no counterpart for.
|
|
|
601
878
|
// The main thread. `db` is the app's db client, `logger` its logger, `rbac` its role cache (`refresh(partnerId)`);
|
|
602
879
|
// `dbKind`, `actingRequiresActive`, `writesRequirePlatform` and `refuseInactive` are the app's settings (a new app:
|
|
603
880
|
// 'postgres', true, true, true; ONE writesRequirePlatform constant goes to the store and the provisioner); MESSAGES its sentences;
|
|
604
|
-
// `auditScopes` for actingRoutes (every existing app: { start: 'house', stop: 'partner' }; a new app: stop 'both').
|
|
881
|
+
// `auditScopes` for actingRoutes (every existing app: { start: 'house', stop: 'partner' }; a new app: { start: 'both', stop: 'both' }).
|
|
605
882
|
const {
|
|
606
883
|
createTenancy, createWriteGate, createHostTenant, createTenantChrome, createProvisioner, actingRoutes, actingLocals, viewsDir
|
|
607
884
|
} = require('@aria-framework/tenancy');
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WORKING IN A PARTNER ENDS AFTER A PERIOD WITHOUT ACTIVITY, when the app sets one (the owner's decision of 29 Nov 2026;
|
|
3
|
+
* 0, the default the apps pass, is today's behaviour: no idle end, and NOT ONE session write from this module).
|
|
4
|
+
*
|
|
5
|
+
* const actingIdle = createActingIdle({ idleMinutes, now, isBackground, audit, logger,
|
|
6
|
+
* auditScopes: { stop: 'partner' }, run });
|
|
7
|
+
* // EITHER with the app's own scope middleware (an app with its own acting code):
|
|
8
|
+
* app.use(session); app.use(actingIdle.before); app.use(appScopeMiddleware); app.use(actingIdle.after);
|
|
9
|
+
* // OR with this package's: app.use(tenancy.requestScope({ actingIdle })) (it runs the two halves itself)
|
|
10
|
+
*
|
|
11
|
+
* TWO HALVES, AND THE ORDER IS THE POINT. The end must happen BEFORE the scope middleware fixes the request's tenant:
|
|
12
|
+
* ended after it, the very request that found the period over would still run (and write) inside the partner. So
|
|
13
|
+
* `before` judges the period and clears the acting keys; the scope middleware then places the request in the
|
|
14
|
+
* operator's own scope; `after` writes the stop row where `auditScopes.stop` says (the same setting actingRoutes
|
|
15
|
+
* takes), tells the person once, and saves the session.
|
|
16
|
+
*
|
|
17
|
+
* The session keys are the ones every app uses: `actingPartnerId`, `actingPartnerName`. The activity clock is
|
|
18
|
+
* `actingIdleAt: { partnerId, at }`: started at the first request that sees a partner being worked in (a clock for
|
|
19
|
+
* another partner, or none, starts afresh), moved by a request that is not background when a stamp is due
|
|
20
|
+
* (idle.stampDue: at most once a minute), removed when the session is not acting. Every such write is saved at once,
|
|
21
|
+
* before the request goes on. At 0 minutes none of this happens. The rules are idle.js's, the ones fleet view uses.
|
|
22
|
+
* A throw from `idleMinutes()` ends the acting (reason 'error'), never keeps it unchecked.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
'use strict';
|
|
26
|
+
|
|
27
|
+
const idle = require('../scope/idle');
|
|
28
|
+
|
|
29
|
+
const isFn = (f) => typeof f === 'function';
|
|
30
|
+
function fail(message) { throw new Error(`createActingIdle: ${message}`); }
|
|
31
|
+
|
|
32
|
+
const STOPS = new Set(['partner', 'house', 'both']);
|
|
33
|
+
// A kind the framework's ui/flash partial renders, and one that stays until dismissed.
|
|
34
|
+
const NOTICE_KIND = 'warning';
|
|
35
|
+
const DEFAULT_MESSAGES = {
|
|
36
|
+
idle: (minutes, name) => `Working in ${name} ended after ${minutes} minute${minutes === 1 ? '' : 's'} without activity.`,
|
|
37
|
+
error: (name) => `Working in ${name} ended because it could not be checked. You can start it again.`
|
|
38
|
+
};
|
|
39
|
+
const ENDED = Symbol('actingIdle.ended');
|
|
40
|
+
const say = (m, ...a) => (isFn(m) ? m(...a) : m);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {object} o
|
|
44
|
+
* @param {() => number|Promise<number>} o.idleMinutes REQUIRED: the app's setting, a whole number; 0 = no idle end
|
|
45
|
+
* @param {() => number} o.now REQUIRED: the clock (ms)
|
|
46
|
+
* @param {(req) => boolean} o.isBackground REQUIRED: a request that does NOT count as activity
|
|
47
|
+
* @param {(req, action, opts) => any} o.audit REQUIRED: the app's audit helper (actingRoutes' shape)
|
|
48
|
+
* @param {{error: Function}} o.logger REQUIRED
|
|
49
|
+
* @param {{stop: 'partner'|'house'|'both'}} o.auditScopes REQUIRED, no default: where the stop row lands, as
|
|
50
|
+
* actingRoutes' auditScopes.stop (every existing app: 'partner'; a new app: 'both')
|
|
51
|
+
* @param {(ctx, fn) => any} [o.run] REQUIRED for 'partner' and 'both': the app's runner of `fn` in a tenant context
|
|
52
|
+
* (this package's tenancy.run), for the row written in the partner
|
|
53
|
+
* @param {(req, res, kind, text) => any} [o.flash] default res.flash(kind, text, callback)
|
|
54
|
+
* @param {object} [o.messages] idle(minutes, name), error(name)
|
|
55
|
+
*/
|
|
56
|
+
function createActingIdle(options) {
|
|
57
|
+
const o = options || {};
|
|
58
|
+
for (const k of ['idleMinutes', 'now', 'isBackground', 'audit']) if (!isFn(o[k])) fail(`${k} is required (a function)`);
|
|
59
|
+
if (!o.logger || !isFn(o.logger.error)) fail('logger is required (error)');
|
|
60
|
+
const sc = o.auditScopes;
|
|
61
|
+
if (!sc || typeof sc !== 'object' || !STOPS.has(sc.stop)) {
|
|
62
|
+
fail("auditScopes is required, with no default: { stop: 'partner' | 'house' | 'both' }, the same value as actingRoutes' auditScopes.stop");
|
|
63
|
+
}
|
|
64
|
+
if (sc.stop !== 'house' && !isFn(o.run)) fail(`run is required for auditScopes.stop '${sc.stop}': (ctx, fn), the app's runner of fn in a tenant context (tenancy.run)`);
|
|
65
|
+
if (o.flash != null && !isFn(o.flash)) fail('flash must be a function (req, res, kind, text), which may return a promise');
|
|
66
|
+
const { idleMinutes, now, isBackground, audit, logger } = o;
|
|
67
|
+
const messages = { ...DEFAULT_MESSAGES, ...(o.messages || {}) };
|
|
68
|
+
const logged = (what) => (e) => { try { logger.error(`acting idle: ${what}: ${(e && e.message) || e}`); } catch (_) { /* nothing */ } };
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* An ordinary request's write (idle.writeMerged): the row read back, plus this request's own changes, plus this
|
|
72
|
+
* package's change, saved in the read's callback. Anything else writes nothing, is logged, and the session in memory is
|
|
73
|
+
* settled so express-session's own end-of-request save cannot bring acting back ('gone': signed out meanwhile;
|
|
74
|
+
* 'changed': acting was stopped or moved; 'unreadable': no store to ask, or it failed). The next request judges again.
|
|
75
|
+
*/
|
|
76
|
+
const OWN_KEYS = ['actingPartnerId', 'actingPartnerName', 'actingIdleAt'];
|
|
77
|
+
async function written(req, stillOk, change, what, pre) {
|
|
78
|
+
let r;
|
|
79
|
+
try { r = await idle.writeMerged(req, stillOk, change); }
|
|
80
|
+
catch (e) { logged(`the session could not be saved after ${what}`)(e); return 'failed'; }
|
|
81
|
+
if (r.outcome !== 'saved') {
|
|
82
|
+
try { logger.error(`acting idle: ${what} not written: the session's row is ${r.outcome} (re-read before the save)`); } catch (_) { /* nothing */ }
|
|
83
|
+
idle.settleUnwritten(req, pre || idle.snapshot(req.session), r.row, OWN_KEYS, r.outcome);
|
|
84
|
+
}
|
|
85
|
+
return r.outcome;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Mounted DIRECTLY after the session middleware, when anything that changes the session (an auth middleware's
|
|
90
|
+
* lastActivity, for one) sits between the session and `before`: keeps the session as loaded (idle.markLoaded, the
|
|
91
|
+
* same as fleet view's `loaded`; either one serves both). `before` takes it itself when nothing is mounted between.
|
|
92
|
+
*/
|
|
93
|
+
function loaded(req, res, next) { idle.markLoaded(req); next(); }
|
|
94
|
+
|
|
95
|
+
/** Mounted after the session (and `loaded`, if anything is between), BEFORE the scope middleware. */
|
|
96
|
+
function before(req, res, next) {
|
|
97
|
+
const s = req.session;
|
|
98
|
+
if (!s) return next();
|
|
99
|
+
idle.markLoaded(req); // the session as loaded: this is the place right after the session middleware
|
|
100
|
+
const acting = s.actingPartnerId != null;
|
|
101
|
+
return idle.readIdleMinutes(idleMinutes).then(async (minutes) => {
|
|
102
|
+
// 0 = no idle end: nothing is read from the session's clock and NOTHING is written, on any request.
|
|
103
|
+
if (minutes === 0) return next();
|
|
104
|
+
if (!acting) {
|
|
105
|
+
if (s.actingIdleAt === undefined) return next();
|
|
106
|
+
await written(req, (row) => row.actingPartnerId == null, (t) => { delete t.actingIdleAt; }, 'removing the clock');
|
|
107
|
+
return next();
|
|
108
|
+
}
|
|
109
|
+
const pid = Number(s.actingPartnerId);
|
|
110
|
+
const mark = s.actingIdleAt;
|
|
111
|
+
const stillActing = (row) => row.actingPartnerId != null && Number(row.actingPartnerId) === pid;
|
|
112
|
+
if (!mark || typeof mark !== 'object' || Number(mark.partnerId) !== pid || !Number.isFinite(mark.at)) {
|
|
113
|
+
const at = now(); // the clock starts at the first request that sees it
|
|
114
|
+
await written(req, stillActing, (t) => { t.actingIdleAt = { partnerId: pid, at }; }, 'starting the clock');
|
|
115
|
+
return next();
|
|
116
|
+
}
|
|
117
|
+
if (idle.idleEnded(mark.at, minutes, now())) return stop(req, 'idle', minutes, next);
|
|
118
|
+
if (!idle.isBackgroundSafe(isBackground, logger, req) && idle.stampDue(mark.at, minutes, now())) {
|
|
119
|
+
const at = now();
|
|
120
|
+
await written(req, stillActing, (t) => { t.actingIdleAt = { partnerId: pid, at }; }, 'the activity stamp');
|
|
121
|
+
}
|
|
122
|
+
return next();
|
|
123
|
+
}, (e) => {
|
|
124
|
+
if (!acting) { logged('the idle setting could not be read (not acting: nothing to end)')(e); return next(); }
|
|
125
|
+
logged(`the check failed; working in partner ${Number(s.actingPartnerId)} ends`)(e);
|
|
126
|
+
return stop(req, 'error', undefined, next);
|
|
127
|
+
}).catch(next);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The keys are cleared HERE, before the scope is fixed (the request then runs in the operator's own scope); what the
|
|
131
|
+
// session held is kept, to settle the session with if the end cannot be written (after()).
|
|
132
|
+
function stop(req, reason, minutes, next) {
|
|
133
|
+
const s = req.session;
|
|
134
|
+
req[ENDED] = { partnerId: Number(s.actingPartnerId), name: s.actingPartnerName || `partner ${Number(s.actingPartnerId)}`, reason, minutes, snap: idle.snapshot(s) };
|
|
135
|
+
delete s.actingPartnerId;
|
|
136
|
+
delete s.actingPartnerName;
|
|
137
|
+
delete s.actingIdleAt;
|
|
138
|
+
return next();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Writes one stop row; isolated (a failure is logged, nothing else changes). */
|
|
142
|
+
function row(req, opts, partnerId) {
|
|
143
|
+
return Promise.resolve()
|
|
144
|
+
.then(() => (partnerId == null ? audit(req, 'partner.act_as_stop', opts)
|
|
145
|
+
: o.run({ scope: 'partner', partnerId }, () => audit(req, 'partner.act_as_stop', opts))))
|
|
146
|
+
.catch(logged(`the stop of partner ${opts.entity_id} could not be audited${partnerId == null ? '' : ' in the partner'}`));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Mounted right AFTER the scope middleware: the request now runs in the operator's own scope. The notice goes into
|
|
151
|
+
* the session in memory; the row is re-read and, if it is still working in that partner, the row plus this request's
|
|
152
|
+
* changes minus the acting keys is saved (in the read's callback); then the stop row lands where auditScopes.stop says
|
|
153
|
+
* ('house': here; 'partner': in the partner, through `run`; 'both': one in each). Otherwise nothing is written or
|
|
154
|
+
* audited (a sign-out or a stop that happened meanwhile stands) and the session in memory is settled. This request
|
|
155
|
+
* itself still runs in the operator's own scope.
|
|
156
|
+
*/
|
|
157
|
+
function after(req, res, next) {
|
|
158
|
+
const ended = req[ENDED];
|
|
159
|
+
if (!ended) return next();
|
|
160
|
+
delete req[ENDED];
|
|
161
|
+
const detail = ended.minutes != null ? { reason: ended.reason, minutes: ended.minutes } : { reason: ended.reason };
|
|
162
|
+
const opts = { entity_type: 'partner', entity_id: ended.partnerId, detail };
|
|
163
|
+
return (async () => {
|
|
164
|
+
await idle.noticeOnce(o.flash, logger, req, res, NOTICE_KIND,
|
|
165
|
+
ended.reason === 'idle' ? say(messages.idle, ended.minutes, ended.name) : say(messages.error, ended.name));
|
|
166
|
+
const r = await written(req, (rw) => rw.actingPartnerId != null && Number(rw.actingPartnerId) === ended.partnerId,
|
|
167
|
+
(t) => { for (const k of OWN_KEYS) delete t[k]; }, 'the idle end', ended.snap);
|
|
168
|
+
if (r !== 'saved' && r !== 'failed') return;
|
|
169
|
+
if (sc.stop !== 'house') await row(req, opts, ended.partnerId);
|
|
170
|
+
if (sc.stop !== 'partner') await row(req, opts, null);
|
|
171
|
+
})().then(() => next(), next);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return { loaded, before, after };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
module.exports = { createActingIdle };
|
package/lib/partners/index.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
// The partners part: the partner store and provisioning (piece 10); the acting routes, locals and banner (piece 11)
|
|
3
|
+
// The partners part: the partner store and provisioning (piece 10); the acting routes, locals and banner (piece 11);
|
|
4
|
+
// the idle end of working in a partner (createActingIdle).
|
|
4
5
|
const { createPartnerStore } = require('./store');
|
|
5
6
|
const { createProvisioner } = require('./provisioner');
|
|
6
7
|
const { actingRoutes, actingLocals, viewsDir } = require('./acting');
|
|
8
|
+
const { createActingIdle } = require('./actingIdle');
|
|
7
9
|
|
|
8
|
-
module.exports = { createPartnerStore, createProvisioner, actingRoutes, actingLocals, viewsDir };
|
|
10
|
+
module.exports = { createPartnerStore, createProvisioner, actingRoutes, actingLocals, viewsDir, createActingIdle };
|