@aria-framework/notify 0.7.0 → 0.8.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 CHANGED
@@ -2,6 +2,68 @@
2
2
 
3
3
  Older releases are recorded in the README's "Upgrading to …" sections; this file starts at 0.7.0.
4
4
 
5
+ ## 0.8.0 — 2026-11-17
6
+
7
+ **The live-updates strip says why, waits out a blip, retries a failed connection, survives a sign-in in another tab, and
8
+ every stream end is logged.** The live-updates follow-ups plan (`.claude/plans/live-updates-followups.md`), approved by
9
+ the owner on 17 Nov 2026 as recommended. Backward compatible: README "Upgrading to 0.8.0" has what an app gets by only
10
+ bumping, what each mixed-version combination does during a deploy, the small change each app makes, what an app must
11
+ not do (adopt `reauth` without the `u=` check; answer the probe endpoint 404/2xx when signed out) and the known limits.
12
+
13
+ Client (`assets/bell.js`, `assets/live.js`, `views/notify/bell.ejs`):
14
+ - **The words per reason**, from one map with the control per row (Refresh, Sign in, none); unknown reasons get the
15
+ generic words; `data-live-reason` kept, `data-live-control` added. README has the table.
16
+ - **An 8 s grace** before "Reconnecting…" for an unplanned drop (visible tab only, cancelled by a reopen). A stop is
17
+ never delayed. A planned renewal (`live-renew`) shows nothing at any moment.
18
+ - **`live-stop reauth`**: reopened once per page load WITH the topics; the new request is judged from scratch; a second
19
+ `reauth` or a refusal ends with its own words (a second reauth: "You signed in again in another tab. Refresh to
20
+ continue." — a row added to the approved table in review of #41).
21
+ - **Retry after a CLOSED EventSource** (any non-200, which the browser never retries): a probe of `<base>/recent`, then
22
+ 5 / 10 / 30 / 60 s, then every 60 s, each ±20 % (drawn per step), only while visible; a probe answer that lands after
23
+ the tab hid opens nothing (a hidden tab's stream would count against the per-session cap and could evict a visible one). A probe that meets the sign-in page (redirect) or a plain 401
24
+ stops the page, signed out, with a Sign in control; `session_recheck_required` is left to session-recheck.js. At most
25
+ 30 requests per tab in any 15 minutes (measured: 21 all down, 29 worst case; 33 only if every jitter draw were -20 %).
26
+ - **A region re-fetch** answered 401, or redirected to a sign-in path without the region, shows "signed out".
27
+ - **`notifUser`** on the bell partial → `data-notif-user` → `u=` on every stream, for the route's `user_changed` check.
28
+ - New DOM event `aria:sse-stop` `{ reason }` (bell.js's own stop); `aria:sse-down` carries `detail.closed`; the
29
+ re-dispatched `live-stop` frame carries `reopening` (set by bell.js, never trusted from the server).
30
+
31
+ Hub (`hub.js`):
32
+ - **`hub.renew(res, reason = 'renew')`** — the planned end: `live-renew`, ended, forgotten. For an app's own cut
33
+ (`limitStream`: `hub.renew(res, 'sso_cut')`). Safe on a res the hub never registered.
34
+ - **`hub.refuse(res, reason, { userId, sessionId, audience?, topics? })`** — an app's refusal at attach: `live-stop`,
35
+ ended, logged `status=refused`.
36
+ - **One log line per stream end**: `notify: stream end user= sid=<sha256 first 8> reason= age= topics= audience=`;
37
+ debug for `client_closed` / `renew` / `sso_cut`, info otherwise; `createHub({ logEnds: false })` turns it off. No raw
38
+ session id, cookie, topic id or name. A reason that is not a short word is logged as `other`.
39
+ - **`pageUserChanged(query, userId)`** (exported) — the refuse-only `user_changed` test; `sidTag(sessionId)` exported.
40
+
41
+ Tests: `test/live-resilience.js` (jsdom on a fake clock: grace, renewal, retry schedule and counts, hidden, signed out,
42
+ reauth, user_changed, every row of the table DISPLAYED, region sign-in), `test/hub-ends.js` (real sockets: renew,
43
+ refuse, the log line and its levels, the no-secrets scan, a deleted session stopped and forgotten),
44
+ `test/live-reauth.js` (bell.js + live.js in jsdom against a real http server with an EventSource that follows the
45
+ WHATWG model: the four security properties end to end, the app cut). `test/live-client.js`'s drop checks run on the
46
+ fake clock past the grace.
47
+
48
+ ## 0.7.1 — 2026-11-16
49
+
50
+ **Fix: "Live updates paused. Refresh to see changes." no longer stays on screen after the stream reconnects.**
51
+ The strip carries Bootstrap's `d-flex` (`display:flex !important`), which beats the `hidden` attribute (reboot's
52
+ `[hidden]{display:none!important}` comes first at the same specificity). 0.7.0 hid it with `strip.hidden = true` only,
53
+ so after ANY momentary drop (the hub sign-in cutting streams at 30 minutes, a network blip) the strip stayed visible
54
+ for good while the regions were live again; the tests read the attribute, not what is displayed.
55
+
56
+ - `live.js` hides the strip (and the "N new" bar) with `hidden` AND Bootstrap's `d-none`, and shows it by removing both.
57
+ - `bell.css` adds `.live-strip[hidden], .live-newbar[hidden] { display:none !important }` — two selectors' worth of
58
+ specificity, so it wins over `.d-flex` in any order and without depending on the host's CSS framework.
59
+ - **New, additive:** the strip carries `data-live-reason` — `down` (the stream dropped) or the live-stop's reason
60
+ (`too_many`, `evicted`, `off`, …) — and drops it when hidden. The words are unchanged.
61
+ - Tests (`test/live-client.js`) now read the strip's COMPUTED display under Bootstrap 5.3.3's own rules: down → shown
62
+ (flex), reopen → not displayed and undimmed, live-stop → shown and stays; each mechanism alone. jsdom settles two
63
+ `!important` declarations by order, not specificity, so the bell.css rule's specificity is asserted structurally.
64
+
65
+ No app code changes: bump `@aria-framework/notify` to `^0.7.1` and refresh the lockfile.
66
+
5
67
  ## 0.7.0 — 2026-11-04
6
68
 
7
69
  Carries 0.6.0 (per-audience stream caps), which was merged but never published: **publish 0.7.0 only**.
package/README.md CHANGED
@@ -245,15 +245,71 @@ not navigate. Every swap is announced as
245
245
  listen on the document and need nothing). `data-live-list` makes it a list of `[data-row-id]` rows (the marker may
246
246
  sit on the row or its first cell): with `data-live-insert` (draw it on page 1, default sort, no filter) and nothing
247
247
  ticked, new rows are put in and marked New; otherwise a bar says "N new. Show them". Every reconnect catches every
248
- region up once (there is no replay). When the stream drops or is stopped, a strip says "Live updates paused" with a
248
+ region up once (there is no replay). When the stream drops or is stopped, a strip says why (0.8.0: the words per reason,
249
+ the grace and the retry are below; before it, "Live updates paused" with a
249
250
  Refresh button — or, when the app refused the topics with the reason `off` (0.5.1: its installation-wide switch),
250
- "Live updates are off". Frames that arrive after this page submitted a form are ignored (the mid-navigation trap above)
251
+ "Live updates are off". The strip carries `data-live-reason` (0.7.1: `down`, or the stop's reason) and clears on the
252
+ next open; it is hidden with `hidden` AND `d-none`, and bell.css (linked by the bell partial) keeps
253
+ `.live-strip[hidden]` undisplayed, because Bootstrap's `.d-flex` beats the bare attribute. Frames that arrive after this page submitted a form are ignored (the mid-navigation trap above)
251
254
  until the page navigates — or, for a submit that does not (a download, `target=_blank`), until it is visible again
252
255
  or 8 s pass; a submit a script prevented is not a navigation.
253
256
 
254
257
  Still one process: a write in another process (an ingest server, a node server) reaches no stream
255
258
  here. Such a page needs a re-check in the web process, or a shared bus — neither is in this module.
256
259
 
260
+ ### Why a page is not live, said and logged (0.8.0)
261
+
262
+ **The strip says why**, from one map in `assets/live.js` (the words and the control per reason; `data-live-reason` names
263
+ the reason and `data-live-control` the control — `refresh`, `signin` or `none`):
264
+
265
+ | Reason | Words | Control | Clears by itself |
266
+ |---|---|---|---|
267
+ | `down` (reconnecting, after the grace) | Reconnecting… | none | yes |
268
+ | `closed` (a non-200; bell.js retries) | Live updates stopped. Trying again… | Refresh | yes |
269
+ | `signed_out` (a stop, the probe, a region re-fetch) | You've been signed out. Sign in again to see changes. | Sign in | no |
270
+ | `user_changed` | You signed in as someone else in another tab. Refresh to continue. | Refresh | no |
271
+ | `reauth` (a second one on the page; bell.js honours one) | You signed in again in another tab. Refresh to continue. | Refresh | no |
272
+ | `not_allowed`, `no_permission`, `no_scope` | Your access has changed. Refresh to see this page. | Refresh | no |
273
+ | `scope_changed`, `reading_changed` | You switched view in another tab. Refresh to see changes. | Refresh | no |
274
+ | `too_many`, `evicted` | Live updates paused: too many open tabs. Close one and refresh, or refresh to see changes. | Refresh | no |
275
+ | `off` | Live updates are off. Refresh to see changes. | Refresh | no |
276
+ | `check_failed` | Can't check for changes right now. Refresh to try again. | Refresh | no |
277
+ | `busy`, `too_many_topics`, anything else | Live updates paused. Refresh to see changes. | Refresh | no |
278
+
279
+ Both controls reload the page (a signed-out reload lands on the sign-in page).
280
+
281
+ - **A grace for unplanned drops.** `aria:sse-down` shows "Reconnecting…" only once the drop has lasted **8 s** with the
282
+ tab visible; a reopen within that cancels it. The server's `retry: 5000` means a network-error reconnect takes at
283
+ least 5 s, so a shorter grace would hide almost nothing. A stop is never delayed.
284
+ - **A planned end shows nothing.** `live-renew` (the hub's lifetime, or an app's cut through `hub.renew(res, reason)`)
285
+ is reopened at once by bell.js, with no error and so no strip; the reopen is a reconnect, so the regions catch up.
286
+ - **`reauth`.** An app answers `{ stop: 'reauth' }` (per event) when the stream's session is GONE from the store — a
287
+ sign-in in another tab regenerated it, while the browser now holds a new cookie. bell.js reopens ONCE per page load
288
+ with the same topics; that new request is judged from scratch (requireAuth, the app's re-check, attach) under the
289
+ cookie it carries, and nothing of the stopped stream is kept (the hub has forgotten it, and the old session id is
290
+ never read again). A refusal of the reopen shows its own words; a second `reauth` is an ordinary stop.
291
+ - **`user_changed`.** With `notifUser` given to the bell partial, every stream carries `u=<id>`; the route refuses
292
+ `user_changed` when it is not the session's user (`notify.pageUserChanged(req.query, userId)`). Refuse-only: it can
293
+ add a refusal, never grant; without `u` nothing is checked.
294
+ - **Retry after a failed connection.** A browser never retries an EventSource whose request answered anything but a 200
295
+ `text/event-stream`. bell.js does: one probe of `<base>/recent` (fetch, `redirect: 'manual'`), then the stream again,
296
+ 5 / 10 / 30 / 60 s (each ±20 %, drawn per step) after each failure, then every 60 s (±20 %), indefinitely, **only while the tab is visible** (hidden: no
297
+ request at all; visible again: at once, the schedule from the start). The probe reads: a redirect (requireAuth's 302
298
+ to the sign-in page) or a 401 other than `session_recheck_required` → stopped, signed out, never asked again; 401
299
+ `session_recheck_required` → left to the app's session-recheck.js (it reloads), the schedule goes on; 429, 5xx or a
300
+ network error → the next step; anything else (200, 204, a 404 where an app has no `<base>/recent`) → the stream is
301
+ asked. A probe that said "up" in the last 90 s is not asked again. Never two streams per page; the timers are
302
+ cleared on a successful open, on hide and on `pagehide`; a probe answer that lands after the tab hid opens nothing.
303
+ The request budget is in "Upgrading to 0.8.0".
304
+ - **A region re-fetch that meets the sign-in page** shows "signed out": a 401 (not `session_recheck_required`), or a
305
+ fetch the server REDIRECTED (`r.redirected`) to a path whose last segment is `login`, `signin` or `sign-in` and whose
306
+ answer lacks the region. Other non-200s stay silent; a 200 without the region (not redirected) changes nothing.
307
+ - **One log line per stream end** — `notify: stream end user=4 sid=1a2b3c4d reason=signed_out age=93 topics=2
308
+ audience=staff`, plus ` status=refused` for a refusal at attach (`hub.refuse`, or a cap). `sid` is sha256 of the
309
+ session id, first 8 hex; no raw session id, cookie, topic id or name is ever written. Debug for `client_closed`,
310
+ `renew`, `sso_cut` (every navigation, every renewal); info for the rest. `createHub({ logEnds: false })` turns it
311
+ off; `closeAll()` (shutdown) writes none.
312
+
257
313
  ## Audiences (0.6.0)
258
314
 
259
315
  A stream carries an **audience**. `staff` is the default — a `subscribe` that passes none is exactly what it was in
@@ -334,3 +390,80 @@ stream of it is refused `busy`, exactly as a derived 0 is.
334
390
  `.notif-what`) should be checked. The time reads `1d`, not `1d ago`.
335
391
  - **An app that wants the ticket line** adds `context` to the items `/recent` returns; without it
336
392
  the row is as before plus the body's first line.
393
+
394
+ ### Upgrading to 0.8.0
395
+
396
+ **Backward compatible. An app that only bumps** (`^0.8.0`, lockfile) gets the new words, the 8 s grace, the retry after
397
+ a failed connection, the region sign-in check and the log line, and behaves as on 0.7.1 for the rest: its 30-minute
398
+ cut (a bare `res.end()`) is a drop the browser reconnects in about 5 s, inside the grace, so the flash is gone even
399
+ before the app adds its renewal line; a replaced session still ends `signed_out` (now worded "You've been signed out",
400
+ whose Sign in reload shows the page again under the new cookie); its hand-written refusal frames still work but are not
401
+ logged.
402
+
403
+ **Mixed versions during a deploy.**
404
+ - *Old page JS (0.7.x, cached) against a 0.8.0 server:* `live-renew` from `hub.renew` was already reopened at once by
405
+ 0.7.x bell.js, so the renewal works; a `reauth` stop is an ordinary stop there (bell-only, "Live updates paused…",
406
+ a reload clears it); `u=` is not sent, so `user_changed` is never checked; refusals read "Live updates paused…".
407
+ - *New page JS against an old (0.7.x) server:* no `reauth` or renewal frame ever comes, so a 30-minute cut is a plain
408
+ drop (hidden by the grace) and a replaced session ends `signed_out`; the server ignores `u=`; a 502 while the server
409
+ restarts is retried and recovers by itself (0.7.x stayed stuck until a tab switch).
410
+
411
+ **What each app must do** (one small PR each, after the bump):
412
+ 1. **The renewal before the 30-minute cut — Soc101, Noc101, DiTwys** (`lib/hubSso.js` `limitStream`; Ops101 has none).
413
+ Give `limitStream` a third argument and call it at the deadline instead of `res.end()`:
414
+ `function limitStream(req, res, onDeadline = () => res.end())` … `setTimeout(() => { try { onDeadline(); } catch (_) {} }, …)`,
415
+ and in `routes/notifications.js`: `require('../lib/hubSso').limitStream(req, res, () => hub.renew(res, 'sso_cut'))`.
416
+ A stream refused before it subscribed is still told and ended by `renew`, and not logged twice.
417
+ 2. **`reauth` AND `user_changed`, in the SAME PR — all four apps' staff streams.**
418
+ - `lib/live.js` `decide`, the staff branch: right after `stored = await deps.loadSession(sessionId)`,
419
+ `if (stored == null) return { stop: 'reauth' };` — only for a session that is GONE. Idle, a session-version change,
420
+ a user mismatch, act-as switched and the contact checks keep their reasons. Add `'reauth'` and `'user_changed'` to
421
+ `REASONS`.
422
+ - the bell partial gets `notifUser` (`include('notify/bell', { notifUser: currentUser.id })`), and the stream route,
423
+ after the headers and before attach's answer is used:
424
+ `if (notify.pageUserChanged(req.query, userId)) return hub.refuse(res, 'user_changed', { userId, sessionId: req.sessionID });`
425
+ 3. **Refusals through the hub — all four apps** (`routes/notifications.js`, and Ops101 `routes/portal.js` `GET
426
+ /portal/live/stream`): replace `res.write(… live-stop …); return res.end();` with
427
+ `return hub.refuse(res, asked.refused, { userId, sessionId: req.sessionID, topics: [].concat(req.query.topic || []) })`
428
+ (the portal: `audience: 'contact'` and its own session reference).
429
+ 4. **The probe endpoint (`<base>/recent`) must answer a signed-out caller with a 401 or a same-origin redirect to the
430
+ sign-in page.** A 404 or any 2xx reads as "up": the stream is retried, and a signed-out page is never told. The staff
431
+ `/notifications/recent` routes (requireAuth: 302 to `/login`) and Ops101's `/portal/live/recent` (requireContact:
432
+ 302 to `/portal/login`, else 204) already do. **DiTwys:** its contact pages' base `/signage/live` has no `/recent`,
433
+ and a 204 route behind the contact pin would NOT do — with no `session.contact` the router's
434
+ `staffOrContact` / `pinRequest` answers 404 (read as "up"), and an unauthenticated 204 reads as "up" too. Add
435
+ `GET /signage/live/recent` REACHABLE BEFORE the 404-ing pin, answering 401 (or a redirect to the portal sign-in)
436
+ when there is no contact and 204 otherwise.
437
+ 5. **Soc101's dashboard stream** (`lib/dashboardLive.js` ~127–131 re-reads the session and stops `signed_out`): bell.js
438
+ honours `reauth` only on a page with topics, and the dashboard rides the stream through `data-notif-stream-param`
439
+ with none. Recommended for the Soc PR: leave the dashboard on `signed_out` and say in its comment that a session
440
+ replaced in another tab needs a Refresh there (sending `reauth` would only change its words, not reopen it).
441
+ 6. **Tests to copy — against each app's OWN route:** `test/live-reauth.js` shows the shape, but it passes against its
442
+ model route even if an app skips `u=`. Each app's live tests must assert, on its real `routes/notifications.js` and
443
+ `lib/live.js`: `decide` returns `reauth` only for a missing session (idle, a version bump and a user mismatch still
444
+ `signed_out`); after a session replacement the stream route refuses another user (`user_changed`), a session
445
+ without the permission and another partner scope (SECURITY (ii)); the probe endpoint answers a signed-out caller
446
+ 401 or a redirect; `limitStream`'s deadline writes `live-renew` before the end (a 10 ms `STREAM_LIFETIME_MS`).
447
+
448
+ **An app must not:**
449
+ - **adopt `reauth` without the `u=` check** (`notifUser` in the bell partial + `pageUserChanged` in the stream route).
450
+ With `reauth` alone, user A's page reopens under user B's cookie when B signs in in another tab, and its regions
451
+ re-render as B. Both land in the same PR.
452
+ - **answer `<base>/recent` with a 404 or a 2xx for a signed-out caller** (item 4).
453
+ - **send `reauth` for anything but a session gone from the store** — it is the one stop the page reopens.
454
+
455
+ **Not covered, by design:** portal contacts do not get `reauth` (their streams are judged from the portal session row,
456
+ not the session store; a replaced contact session stays `signed_out`). The Soc dashboard (item 5).
457
+
458
+ **Request budget.** Per stuck tab, measured in the package: at most 21 requests in any 15 minutes when everything is
459
+ down, 29 when the probe answers and the stream fails (page load included; 33 only if every jitter draw were −20 %). In
460
+ the hub-SSO apps session-recheck.js adds one fetch of the stream URL per CLOSED EventSource, so the real figure there is
461
+ about 45 per 15 minutes — still far under the per-person 2000.
462
+
463
+ **Known limits:**
464
+ - F misses a signed-out page whose URL still carries `?realm=`: the deep link sends the re-fetch cross-origin to the hub
465
+ and the fetch fails CORS (silently, as other failures). The stream's probe still catches the sign-out.
466
+ - `showStrip` does nothing while `leaving` (pre-existing since 0.5.0): a stop within 8 s of a submit that did not
467
+ navigate (a download) is not shown.
468
+ - The 90 s probe reuse can delay "signed out" by up to about 90 s after a probe that said "up".
469
+ - `reauth` is honoured once per page load; a second one says "You signed in again in another tab. Refresh to continue."
package/assets/bell.css CHANGED
@@ -87,6 +87,12 @@
87
87
  .notif-row.is-read .notif-body{color:var(--text-faint, var(--bs-secondary-color));}
88
88
 
89
89
  /* ── Live page regions (assets/live.js, 0.5.0) ─────────────────────────────────────────────── */
90
+ /* 0.7.1: a hidden strip or bar is NOT displayed, whatever the host's CSS. Both carry Bootstrap's .d-flex
91
+ * (display:flex !important), which beats the [hidden] attribute (reboot's rule comes first at the same
92
+ * specificity), so 0.7.0's "Live updates paused" strip stayed on screen after every reconnect. Two classes'
93
+ * worth of specificity outranks .d-flex in any order; live.js also toggles .d-none. */
94
+ .live-strip[hidden],
95
+ .live-newbar[hidden]{display:none !important;}
90
96
  .live-paused{opacity:.6;transition:opacity .2s;}
91
97
  .live-new{background:rgba(var(--brand-rgb, var(--bs-primary-rgb)), .07);transition:background 2s;}
92
98
  .live-new-pill{display:inline-block;margin-right:.4em;padding:0 .45em;border-radius:1em;font-size:.72em;font-weight:600;
package/assets/bell.js CHANGED
@@ -43,9 +43,18 @@
43
43
  * never asked for again on this page. A bell-only stream that is stopped is closed and
44
44
  * NOT reopened — the browser's own retry would otherwise ask every 5 s for a stream the
45
45
  * server has just refused. A reload, or the next page, asks afresh.
46
- * live-renew the stream reached its lifetime: reopened at once (a reconnect, so the page's
47
- * regions catch up), never left to the 5 s retry.
48
- * A dropped stream is announced as 'aria:sse-down' (assets/live.js shows "Live updates paused").
46
+ * 0.8.0 — `live-stop reauth` (the session the stream was opened under is gone from the
47
+ * store: a sign-in in another tab replaced it) is reopened ONCE per page load WITH the
48
+ * topics; the server judges that new request from scratch under the cookie it carries.
49
+ * A second reauth is an ordinary stop. The re-dispatched frame carries `reopening`
50
+ * (this file's word, always set here) so live.js shows nothing for the one honoured.
51
+ * live-renew a PLANNED end — the hub's lifetime, or an app's own cut through hub.renew(): reopened
52
+ * at once (a reconnect, so the page's regions catch up), never left to the 5 s retry.
53
+ * A dropped stream is announced as 'aria:sse-down' (detail.closed: the browser gave up); live.js shows
54
+ * "Reconnecting…" only after an 8 s grace. 0.8.0: a CLOSED connection (any non-200 answer, which the
55
+ * browser never retries) is retried here — a probe of <base>/recent, then 5 / 10 / 30 / 60 s (±20 %), then every
56
+ * 60 s, only while visible; a probe that meets the sign-in page stops the page ('aria:sse-stop'
57
+ * { reason: 'signed_out' }). data-notif-user on the root (bell.ejs notifUser) adds `u=` to the stream.
49
58
  *
50
59
  * XSS-safe by construction: rows are createElement/textContent, and only a same-origin PATH may
51
60
  * become a row's href — a link that ever carried attacker-influenced text would otherwise execute
@@ -271,7 +280,30 @@
271
280
  // ── The stream ──────────────────────────────────────────────────────────────────────────────
272
281
  var es = null;
273
282
  var firstOpen = true;
274
- var stopped = false; // a live-stop: this page does not ask again
283
+ var stopped = false; // a live-stop (or the probe found the session signed out): this page does not ask again
284
+ var reauthUsed = false; // 0.8.0: a `reauth` stop is honoured ONCE per page load, never twice (no loop)
285
+ var USER = menu.getAttribute('data-notif-user') || ''; // 0.8.0: who the page was drawn for (`user_changed`)
286
+
287
+ // 0.8.0 — AFTER A FAILED CONNECTION. The browser does not retry an EventSource whose request answered anything but a
288
+ // 200 text/event-stream (a 302 to the sign-in page, a 401, a 429, a 502 during a deploy): it is CLOSED for good. So
289
+ // this file does: first one probe of the cheap JSON endpoint (<base>/recent), then the stream again, at RETRY_MS (±20 %)
290
+ // after each failure, the last step repeated for as long as the page is visible. Hidden: nothing is asked; visible again:
291
+ // at once, the schedule from the start. A redirect (the sign-in page) or a 401 other than session_recheck_required on
292
+ // the probe is a signed-out session: stopped, said so, never asked again. session_recheck_required is the hub
293
+ // sign-in's re-check, which the app's session-recheck.js turns into a reload; the schedule goes on meanwhile.
294
+ var RETRY_MS = [5000, 10000, 30000, 60000];
295
+ var STABLE_MS = 60000; // a stream that stays open this long starts the next outage's schedule from the start
296
+ // A probe that said "up" this recently is not asked again: the next step reopens the stream directly. Without it a
297
+ // stream route that fails while /recent answers would cost a probe AND a stream every step (36 requests in the first
298
+ // 15 minutes); with it 29 at most in any 15 minutes with the jitter drawn as a browser draws it (33 only if every draw
299
+ // were the -20 % extreme), whatever fails (test/live-resilience.js counts them).
300
+ var PROBE_REUSE_MS = 90000;
301
+ var lastProbeOk = null;
302
+ var retrying = false; // in an outage: a failed connection not yet followed by a stream that stayed open
303
+ var retryStep = 0;
304
+ var retryTimer = null;
305
+ var stableTimer = null;
306
+ var probing = false;
275
307
 
276
308
  function streamUrl() {
277
309
  var params = [];
@@ -279,34 +311,119 @@
279
311
  var p = el.getAttribute('data-notif-stream-param');
280
312
  if (p) params.push(p);
281
313
  });
314
+ if (USER) params.push('u=' + encodeURIComponent(USER));
282
315
  TOPICS.forEach(function (t) { params.push('topic=' + encodeURIComponent(t)); });
283
316
  return BASE + '/stream' + (params.length ? '?' + params.join('&') : '');
284
317
  }
285
318
 
319
+ function clearTimers() {
320
+ if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
321
+ if (stableTimer) { clearTimeout(stableTimer); stableTimer = null; }
322
+ }
323
+
324
+ /** The page's live part ends here for good, said by THIS file (not a frame): live.js shows the words for `reason`. */
325
+ function stopHere(reason) {
326
+ stopped = true;
327
+ clearTimers();
328
+ closeStream();
329
+ document.dispatchEvent(new CustomEvent('aria:sse-stop', { detail: { reason: reason } }));
330
+ }
331
+
332
+ function retryLater() {
333
+ if (stopped || es) return;
334
+ if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
335
+ retrying = true;
336
+ if (document.visibilityState === 'hidden') return; // resumed by visibilitychange
337
+ // ±20 % jitter, drawn per step, so the tabs a deploy dropped together do not all come back in the same second.
338
+ var delay = Math.round(RETRY_MS[Math.min(retryStep, RETRY_MS.length - 1)] * (0.8 + 0.4 * Math.random()));
339
+ retryStep += 1;
340
+ retryTimer = setTimeout(function () {
341
+ retryTimer = null;
342
+ if (lastProbeOk != null && Date.now() - lastProbeOk <= PROBE_REUSE_MS) openStream(); else probe();
343
+ }, delay);
344
+ }
345
+
346
+ function probe() {
347
+ if (stopped || es || probing || document.visibilityState === 'hidden') return;
348
+ probing = true;
349
+ fetch(BASE + '/recent', { credentials: 'same-origin', redirect: 'manual', headers: { 'X-Requested-With': 'fetch' } })
350
+ .then(function (r) {
351
+ probing = false;
352
+ if (stopped || es) return null;
353
+ // A redirect of a JSON endpoint is requireAuth sending a signed-out request to the sign-in page.
354
+ if (r.type === 'opaqueredirect' || (r.status >= 300 && r.status < 400)) { stopHere('signed_out'); return null; }
355
+ if (r.status === 401) {
356
+ return r.text().then(function (t) {
357
+ if (/session_recheck_required/.test(t || '')) still(); else stopHere('signed_out');
358
+ }, function () { stopHere('signed_out'); });
359
+ }
360
+ // Unavailable (429, 5xx; a network error below): wait for the next step and ask again. Anything else — a 200, a
361
+ // 204, or a 4xx such as a 404 where an app has no <base>/recent — says the server is up and the session not
362
+ // signed out as far as the probe can tell: the stream is asked; failing again, it schedules the next step.
363
+ if (r.status === 429 || r.status >= 500 || r.status === 0) { still(); return null; }
364
+ lastProbeOk = Date.now();
365
+ // An answer that lands after the tab hid opens nothing: a hidden tab's stream would hold a place under the
366
+ // per-session cap (6) and could evict a VISIBLE tab's. visibilitychange probes again when it is shown.
367
+ if (document.visibilityState === 'hidden') return null;
368
+ openStream();
369
+ return null;
370
+ }, function () { probing = false; still(); });
371
+ }
372
+
373
+ /** Still down after a probe: say so (the strip may not be up yet — a tab that came back) and wait for the next step. */
374
+ function still() {
375
+ document.dispatchEvent(new CustomEvent('aria:sse-down', { detail: { closed: true } }));
376
+ retryLater();
377
+ }
378
+
286
379
  function openStream() {
287
380
  if (!window.EventSource || es || stopped) return;
288
381
  try {
289
- es = new EventSource(streamUrl());
290
- es.onmessage = function (ev) {
382
+ var src = new EventSource(streamUrl());
383
+ es = src;
384
+ src.onmessage = function (ev) {
291
385
  var d = null;
292
386
  try { d = JSON.parse(ev.data); } catch (_) { /* keep the notif behaviour */ }
293
- // EVERY frame goes back out as a DOM event — the seam that lets app features (a live
294
- // ticket page, a draft indicator, a version-skew banner) ride this connection without
295
- // knowing it exists, and without burning a second one.
296
- if (d) document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
297
387
  if (d && d.type === 'live-stop') {
388
+ // 0.8.0 `reauth`: the session this stream was opened under is gone from the store (a sign-in in another tab
389
+ // replaced it). Reopened ONCE with the same topics: the new request is judged from scratch under whatever
390
+ // cookie the browser holds now. Anything else, a second reauth included, is a stop. `reopening` is this file's
391
+ // word, always set here, so live.js knows not to show a strip for the one honoured.
392
+ var honour = d.reason === 'reauth' && !reauthUsed && TOPICS.length > 0;
393
+ d = Object.assign({}, d, { reopening: honour });
394
+ document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
298
395
  closeStream();
396
+ if (honour) { reauthUsed = true; openStream(); return; }
299
397
  if (TOPICS.length) { TOPICS = []; openStream(); } else { stopped = true; }
300
398
  return;
301
399
  }
400
+ // EVERY frame goes back out as a DOM event — the seam that lets app features (a live
401
+ // ticket page, a draft indicator, a version-skew banner) ride this connection without
402
+ // knowing it exists, and without burning a second one.
403
+ if (d) document.dispatchEvent(new CustomEvent('aria:sse', { detail: d }));
404
+ // live-renew: a PLANNED end (the hub's lifetime, an app's own cut via hub.renew): reopened at once, no error, no
405
+ // strip; the reopen is an ordinary reconnect, so the page's regions catch up.
302
406
  if (d && d.type === 'live-renew') { closeStream(); openStream(); return; }
303
407
  var forPage = !!d && d.id != null && TOPICS.indexOf(d.type + ':' + d.id) !== -1;
304
408
  if (!forPage && (!d || QUIET.indexOf(d.type) === -1)) sync();
305
409
  };
306
- es.onerror = function () {
307
- document.dispatchEvent(new CustomEvent('aria:sse-down', { detail: {} }));
410
+ src.onerror = function () {
411
+ if (src !== es) return; // a source this file already let go of
412
+ // readyState 2 (CLOSED): the browser gave up (a non-200 answer) and will not retry; anything else, it will.
413
+ var closed = src.readyState === 2;
414
+ document.dispatchEvent(new CustomEvent('aria:sse-down', { detail: { closed: closed } }));
415
+ if (!closed) return;
416
+ closeStream();
417
+ if (stopped) return;
418
+ // The first failure of an outage is probed at once; every later one waits its step.
419
+ if (!retrying) { retrying = true; probe(); } else { retryLater(); }
308
420
  };
309
- es.onopen = function () {
421
+ src.onopen = function () {
422
+ if (src !== es) return;
423
+ if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
424
+ if (retrying && !stableTimer) {
425
+ stableTimer = setTimeout(function () { stableTimer = null; retrying = false; retryStep = 0; }, STABLE_MS);
426
+ }
310
427
  sync(); // self-heal the badge on every open, reconnects included
311
428
  var wasFirst = firstOpen;
312
429
  firstOpen = false;
@@ -314,13 +431,18 @@
314
431
  };
315
432
  } catch (e) { es = null; }
316
433
  }
317
- function closeStream() { if (es) { es.close(); es = null; } }
434
+ function closeStream() {
435
+ if (es) { var s = es; es = null; s.close(); }
436
+ clearTimers();
437
+ }
318
438
 
319
439
  openStream();
320
- // Release the connection when leaving or backgrounding; reopen on visible/bfcache restore.
440
+ // Release the connection when leaving or backgrounding; reopen on visible/bfcache restore. Leaving or hiding also
441
+ // cancels a pending retry (closeStream clears the timers); visible again retries at once, the schedule from the start.
321
442
  window.addEventListener('pagehide', closeStream);
322
443
  document.addEventListener('visibilitychange', function () {
323
- if (document.visibilityState === 'hidden') { closeStream(); }
324
- else { sync(); openStream(); }
444
+ if (document.visibilityState === 'hidden') { closeStream(); return; }
445
+ sync();
446
+ if (retrying) { retryStep = 0; probe(); } else { openStream(); }
325
447
  });
326
448
  })();
package/assets/live.js CHANGED
@@ -28,11 +28,17 @@
28
28
  * push written while handling it reaches the very page that caused it (README, "A push reaches the
29
29
  * page that CAUSED it"). A submit a script prevented is not a navigation and sets nothing.
30
30
  *
31
- * "LIVE UPDATES PAUSED": a strip above the first region, with a Refresh button, when the stream
32
- * drops (aria:sse-down) or is stopped (a live-stop frame — "too many open tabs" for too_many, and
33
- * "Live updates are off" for `off`, the reason an app gives when it has switched live pages off); the
34
- * regions are dimmed. It clears on the next open, which also catches the regions up. A hidden tab
35
- * closes its stream on purpose (bell.js) and shows no strip.
31
+ * THE STRIP (0.8.0): a line above the first region that says WHY the page is not live, from one map
32
+ * (WORDS, below: the words and the control for each reason; an unknown reason gets the generic words),
33
+ * and the regions dimmed. Its `data-live-reason` names the reason, `data-live-control` the control.
34
+ * - an UNPLANNED drop (aria:sse-down) shows "Reconnecting…" only after GRACE_MS (8 s) with the tab
35
+ * visible and no reopen meanwhile: a blip, or the browser's own 5 s retry, never flashes it. A
36
+ * connection the browser gave up on (bell.js retries it) says "Live updates stopped. Trying again…";
37
+ * both clear on the next open, which also catches the regions up.
38
+ * - a PLANNED end (live-renew; a `reauth` bell.js honours) shows nothing at all.
39
+ * - a STOP (a live-stop frame; aria:sse-stop, bell.js's own — the probe found the session signed
40
+ * out; a region re-fetch that met the sign-in page) shows at once, never after a grace, and stays.
41
+ * A hidden tab closes its stream on purpose (bell.js) and shows no strip.
36
42
  */
37
43
  (function () {
38
44
  'use strict';
@@ -50,6 +56,35 @@
50
56
  var strip = null;
51
57
  var LEAVE_MS = 8000; // a submit that has not navigated by then did not navigate (a download, target=_blank)
52
58
  var HELD_MS = 2000;
59
+ var GRACE_MS = 8000; // 0.8.0: an unplanned drop is announced only once it has lasted this long
60
+ var graceTimer = null;
61
+ var downKind = null; // 'down' (the browser is reconnecting) or 'closed' (it gave up; bell.js retries)
62
+
63
+ /**
64
+ * THE WORDS (0.8.0, the live-updates follow-ups plan's table D, approved 17 Nov 2026): reason -> [words, control].
65
+ * The control is 'refresh' (a Refresh button), 'signin' (a Sign in button: a reload lands on the sign-in page) or ''
66
+ * (none). One map, so a reason cannot have words without a control or the other way round.
67
+ */
68
+ var ACCESS = ['Your access has changed. Refresh to see this page.', 'refresh'];
69
+ var SWITCHED = ['You switched view in another tab. Refresh to see changes.', 'refresh'];
70
+ var TABS = ['Live updates paused: too many open tabs. Close one and refresh, or refresh to see changes.', 'refresh'];
71
+ var WORDS = {
72
+ down: ['Reconnecting\u2026', ''],
73
+ closed: ['Live updates stopped. Trying again\u2026', 'refresh'],
74
+ signed_out: ['You\'ve been signed out. Sign in again to see changes.', 'signin'],
75
+ user_changed: ['You signed in as someone else in another tab. Refresh to continue.', 'refresh'],
76
+ // A SECOND reauth on this page (bell.js honours one per page load): added to the approved table in review of #41.
77
+ reauth: ['You signed in again in another tab. Refresh to continue.', 'refresh'],
78
+ not_allowed: ACCESS, no_permission: ACCESS, no_scope: ACCESS,
79
+ scope_changed: SWITCHED, reading_changed: SWITCHED,
80
+ too_many: TABS, evicted: TABS,
81
+ off: ['Live updates are off. Refresh to see changes.', 'refresh'],
82
+ check_failed: ['Can\'t check for changes right now. Refresh to try again.', 'refresh']
83
+ };
84
+ var GENERIC = ['Live updates paused. Refresh to see changes.', 'refresh']; // busy, too_many_topics, anything unknown
85
+ function wordsFor(reason) {
86
+ return Object.prototype.hasOwnProperty.call(WORDS, reason) ? WORDS[reason] : GENERIC;
87
+ }
53
88
 
54
89
  function topicsOf(el) {
55
90
  return (el.getAttribute('data-live-topic') || '').split(/\s+/).filter(Boolean);
@@ -85,25 +120,50 @@
85
120
  var btn = document.createElement('button');
86
121
  btn.type = 'button';
87
122
  btn.className = 'btn btn-sm btn-outline-secondary';
88
- btn.textContent = 'Refresh';
123
+ btn.setAttribute('data-live-strip-control', '');
124
+ // Both controls reload: Refresh redraws the page; Sign in lands on the sign-in page, which brings the person back.
89
125
  btn.addEventListener('click', function () { window.location.reload(); });
90
126
  strip.appendChild(btn);
91
127
  REGIONS[0].parentNode.insertBefore(strip, REGIONS[0]);
92
128
  }
93
- // 'off' (0.5.1): the APP switched live updates off (an installation-wide switch, the live-updates plan's D8) and
94
- // refused the page's topics for that reason — nothing is paused that will resume, so the strip says so.
95
- strip.querySelector('[data-live-strip-words]').textContent = reason === 'off'
96
- ? 'Live updates are off. Refresh to see changes.'
97
- : (reason === 'too_many' || reason === 'evicted')
98
- ? 'Live updates paused: too many open tabs. Close one and refresh, or refresh to see changes.'
99
- : 'Live updates paused. Refresh to see changes.';
100
- strip.hidden = false;
129
+ var w = wordsFor(reason || 'down');
130
+ strip.querySelector('[data-live-strip-words]').textContent = w[0];
131
+ var control = strip.querySelector('[data-live-strip-control]');
132
+ control.textContent = w[1] === 'signin' ? 'Sign in' : 'Refresh';
133
+ control.hidden = !w[1];
134
+ strip.setAttribute('data-live-control', w[1] || 'none');
135
+ // data-live-reason (0.7.1): the reason word — 'down', 'closed', or the stop's own (too_many, signed_out, …).
136
+ strip.setAttribute('data-live-reason', reason || 'down');
137
+ setShown(strip, true);
101
138
  REGIONS.forEach(function (r) { r.classList.add('live-paused'); });
102
139
  }
103
140
  function clearStrip() {
104
- if (strip) strip.hidden = true;
141
+ if (strip) { setShown(strip, false); strip.removeAttribute('data-live-reason'); strip.removeAttribute('data-live-control'); }
105
142
  REGIONS.forEach(function (r) { r.classList.remove('live-paused'); });
106
143
  }
144
+ function clearGrace() { if (graceTimer) { clearTimeout(graceTimer); graceTimer = null; } }
145
+ /** The page's live part has stopped for good (a stop frame, bell.js's own stop, a region that met the sign-in page). */
146
+ function stopWith(reason) {
147
+ clearGrace();
148
+ downKind = null;
149
+ stopped = reason || 'stopped';
150
+ showStrip(stopped);
151
+ }
152
+ function stripShowsDrop() {
153
+ var r = strip && !strip.hidden ? strip.getAttribute('data-live-reason') : null;
154
+ return r === 'down' || r === 'closed';
155
+ }
156
+ /**
157
+ * SHOW OR HIDE an element that carries a Bootstrap display utility (0.7.1). The `hidden` attribute alone does not
158
+ * hide it: Bootstrap 5.3's `.d-flex{display:flex!important}` comes after reboot's `[hidden]{display:none!important}`
159
+ * at the same specificity, so it wins, and 0.7.0's strip stayed on screen after every reconnect. So: `hidden` (what
160
+ * assistive tech reads) AND `d-none` (Bootstrap's own `display:none!important`, later than `.d-flex` in its sheet),
161
+ * with bell.css's `.live-strip[hidden]` rule as the guard that does not depend on Bootstrap's order.
162
+ */
163
+ function setShown(el, on) {
164
+ el.hidden = !on;
165
+ el.classList.toggle('d-none', !on);
166
+ }
107
167
 
108
168
  // ── Re-fetch and swap ─────────────────────────────────────────────────────────────────────
109
169
  /**
@@ -196,7 +256,7 @@
196
256
  if (bar.parentNode) bar.parentNode.removeChild(bar);
197
257
  };
198
258
  bar.__fresh = fresh;
199
- bar.hidden = false;
259
+ setShown(bar, true);
200
260
  }
201
261
 
202
262
  /** Replace `el` by `fresh`, marking rows `fresh` has that `el` had not. */
@@ -242,6 +302,11 @@
242
302
 
243
303
  function srcOf(el) { return el.getAttribute('data-live-src') || window.location.href; }
244
304
 
305
+ /** Is this URL's path a sign-in page's (a last segment login, signin or sign-in)? */
306
+ function signInPath(u) {
307
+ try { return /(^|\/)(login|sign-?in)\/?$/i.test(new URL(u, window.location.href).pathname); } catch (_) { return false; }
308
+ }
309
+
245
310
  function refresh(ids) {
246
311
  // A submit that may not navigate (a download): a HELD region stays held — it is caught up once listening again.
247
312
  if (leaving) { hold(ids); return; }
@@ -263,16 +328,30 @@
263
328
  // X-Live-Fragment marks the page's own re-fetch: @aria-framework/auth 0.16.0 lets it through without
264
329
  // counting it as activity, so a page left open still idles out.
265
330
  return fetch(src, { credentials: 'same-origin', headers: { 'X-Requested-With': 'fetch', 'X-Live-Fragment': '1' } })
266
- .then(function (r) { return r.ok ? r.text() : null; })
267
- .then(function (html) {
268
- if (html == null) return;
331
+ .then(function (r) {
332
+ // 0.8.0 (F) — SIGNED OUT, SEEN BY A RE-FETCH. Two signals, neither a guess from the page's text:
333
+ // a 401 — except session_recheck_required, the hub sign-in's re-check, which session-recheck.js reloads;
334
+ // a fetch the server REDIRECTED to a sign-in path (/login, /…/login, /signin, /sign-in), checked below
335
+ // together with the region missing from the answer (requireAuth answers a signed-out request with a 302 to
336
+ // its loginPath; fetch follows it, so it lands as a 200 HTML page with r.redirected and r.url set).
337
+ if (r.status === 401) {
338
+ return r.text().then(function (t) { if (!/session_recheck_required/.test(t || '')) stopWith('signed_out'); return null; },
339
+ function () { stopWith('signed_out'); return null; });
340
+ }
341
+ if (!r.ok) return null; // other non-200s stay silent: the next frame or reconnect tries again
342
+ var toSignIn = !!r.redirected && signInPath(r.url);
343
+ return r.text().then(function (t) { return { html: t, toSignIn: toSignIn }; });
344
+ })
345
+ .then(function (got) {
346
+ if (got == null) return;
269
347
  if (leaving) { hold(bySrc[src].map(function (el) { return el.id; })); return; }
270
- var doc = new DOMParser().parseFromString(html, 'text/html');
348
+ var doc = new DOMParser().parseFromString(got.html, 'text/html');
271
349
  bySrc[src].forEach(function (el) {
272
350
  var cur = document.getElementById(el.id) || el;
273
351
  var fresh = doc.getElementById(el.id);
274
- // No such element in the answer: not this page (a sign-in page is a 200 too). Nothing changes.
275
- if (!fresh || !fresh.hasAttribute('data-live-topic')) return;
352
+ // No such element in the answer: not this page (a sign-in page is a 200 too). Nothing changes — and when the
353
+ // server redirected the re-fetch to a sign-in path, the page says so (0.8.0).
354
+ if (!fresh || !fresh.hasAttribute('data-live-topic')) { if (got.toSignIn && !stopped) stopWith('signed_out'); return; }
276
355
  // Someone started working in it while the answer was on its way: hold it, never swap.
277
356
  if (workedIn(cur)) { hold([cur.id]); return; }
278
357
  apply(cur, fresh);
@@ -287,17 +366,38 @@
287
366
 
288
367
  document.addEventListener('aria:sse', function (ev) {
289
368
  var d = ev.detail || {};
290
- if (d.type === 'live-stop') { stopped = d.reason || 'stopped'; showStrip(stopped); return; }
369
+ if (d.type === 'live-stop') {
370
+ // A `reauth` bell.js reopens (once, with the topics) is not a stop: nothing shows, the reopen catches up.
371
+ if (d.reopening === true) return;
372
+ stopWith(d.reason);
373
+ return;
374
+ }
291
375
  if (d.id == null || leaving) return;
292
376
  var t = d.type + ':' + d.id;
293
377
  var ids = REGIONS.filter(function (r) { return topicsOf(r).indexOf(t) !== -1; }).map(function (r) { return r.id; });
294
378
  if (ids.length) refresh(ids);
295
379
  });
296
- document.addEventListener('aria:sse-down', function () {
297
- if (document.visibilityState === 'hidden') return;
298
- showStrip('down');
380
+ // bell.js's own stop (0.8.0): its probe found the session signed out.
381
+ document.addEventListener('aria:sse-stop', function (ev) {
382
+ stopWith((ev.detail && ev.detail.reason) || 'stopped');
383
+ });
384
+ document.addEventListener('aria:sse-down', function (ev) {
385
+ if (document.visibilityState === 'hidden' || stopped) return;
386
+ downKind = ev.detail && ev.detail.closed ? 'closed' : 'down';
387
+ // Already announced: only the words move (Reconnecting… -> stopped, trying again). Else after the grace.
388
+ if (stripShowsDrop()) { showStrip(downKind); return; }
389
+ if (graceTimer) return;
390
+ graceTimer = setTimeout(function () {
391
+ graceTimer = null;
392
+ if (downKind && !stopped && document.visibilityState !== 'hidden') showStrip(downKind);
393
+ }, GRACE_MS);
394
+ });
395
+ document.addEventListener('visibilitychange', function () {
396
+ if (document.visibilityState === 'hidden') clearGrace(); // bell.js closes the stream; a hidden tab shows nothing
299
397
  });
300
398
  document.addEventListener('aria:sse-open', function (ev) {
399
+ clearGrace();
400
+ downKind = null;
301
401
  // After a live-stop bell.js keeps the BELL open without topics: this page is still not live.
302
402
  if (stopped) return;
303
403
  clearStrip();
package/hub.js CHANGED
@@ -43,10 +43,20 @@
43
43
  * however many contacts open tabs, staff keep `perProcess` − the named caps in reserve. Over its cap a
44
44
  * new stream of that audience is refused `busy`, like the process cap — never another audience's
45
45
  * stream evicted (two contacts of two partners are strangers; one's tab must not end the other's).
46
+ *
47
+ * 0.8.0 — HOW A STREAM ENDS, SAID AND LOGGED. `renew(res, reason)` is the planned end (live-renew: the page reopens at
48
+ * once, no strip) for an app that cuts streams on its own clock; `refuse(res, reason, who)` is an app's refusal at
49
+ * attach. Every end — client gone, a stop, an eviction, the lifetime, renew, a refusal — writes ONE line,
50
+ * `notify: stream end user=… sid=<sha256 first 8> reason=… age=<s> topics=<n> audience=…` (` status=refused` for a
51
+ * refusal): debug for client_closed / renew / sso_cut, info for the rest; `logEnds: false` turns it off. A stop reason
52
+ * only ever comes from the server (authorize, refuse, the caps); `reauth` is the app's answer for a stream whose
53
+ * session is gone from the store, and bell.js reopens it once.
46
54
  */
47
55
 
48
56
  'use strict';
49
57
 
58
+ const crypto = require('crypto');
59
+
50
60
  const HEARTBEAT_MS = 25000; // keep idle connections alive through proxies
51
61
 
52
62
  /**
@@ -71,6 +81,35 @@ const COALESCE_MS = 750; // publishSoon(): one frame per topic per this win
71
81
 
72
82
  const frame = (obj) => `data: ${JSON.stringify(obj)}\n\n`;
73
83
 
84
+ /**
85
+ * 0.8.0 — THE END-OF-STREAM LINE. One line per stream end (and per refusal at attach), so "why did this page stop" has an
86
+ * answer in the log. Debug for the ends every navigation and every renewal make; info for the rest (a stop or a refusal
87
+ * is something a person sees on screen).
88
+ */
89
+ const DEBUG_REASONS = Object.freeze(['client_closed', 'renew', 'sso_cut']);
90
+
91
+ /** The session id as the log may carry it: sha256, first 8 hex. Enough to tie two lines of one session together; never
92
+ * the id itself, which is a bearer credential while the session lives. */
93
+ function sidTag(sessionId) {
94
+ if (sessionId == null || sessionId === '') return '-';
95
+ return crypto.createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 8);
96
+ }
97
+
98
+ /** A reason as the log prints it: a short word, never free text a caller passed through. */
99
+ const reasonWord = (r) => (/^[a-z_]{1,32}$/.test(String(r)) ? String(r) : 'other');
100
+
101
+ /**
102
+ * Did the PAGE render for another user than the one this request is signed in as (0.8.0, `user_changed`)? The page sends
103
+ * `u=<user id>` (views/notify/bell.ejs `notifUser`); a different user signed in in another tab replaces the cookie, so a
104
+ * stream (re)opened by the old page would otherwise refresh the old user's page under the new user. REFUSE-ONLY: it can
105
+ * add a refusal, never grant anything — an absent `u` is "not asked", the 0.7.x behaviour.
106
+ */
107
+ function pageUserChanged(query, userId) {
108
+ if (!query || query.u == null || query.u === '') return false;
109
+ const u = Array.isArray(query.u) ? query.u[0] : query.u;
110
+ return String(u) !== String(userId);
111
+ }
112
+
74
113
  function positive(v, name) {
75
114
  const n = Number(v);
76
115
  if (!Number.isFinite(n) || n < 1) throw new Error(`notify: createHub limit ${name} must be a positive number (got ${JSON.stringify(v)})`);
@@ -100,7 +139,7 @@ function audienceCaps(given, perProcess) {
100
139
 
101
140
  function createHub({
102
141
  heartbeatMs = HEARTBEAT_MS, limits = {}, authorize = null, recheckMs = RECHECK_MS,
103
- coalesceMs = COALESCE_MS, now = () => Date.now(), logger = console
142
+ coalesceMs = COALESCE_MS, now = () => Date.now(), logger = console, logEnds = true
104
143
  } = {}) {
105
144
  const L = {};
106
145
  for (const k of Object.keys(LIMITS)) if (k !== 'perAudience') L[k] = positive(limits[k] === undefined ? LIMITS[k] : limits[k], k);
@@ -152,12 +191,29 @@ function createHub({
152
191
  if (!set.size) map.delete(k);
153
192
  };
154
193
 
155
- /** Tell a stream why it gets no more frames, and end it. bell.js does not reconnect after it. */
194
+ /** Tell a stream why it gets no more frames, and end it. bell.js does not reconnect after it (0.8.0: `reauth` once). */
156
195
  function stopRes(res, reason) {
196
+ const sub = subs.get(res);
197
+ if (sub && !sub.endReason) sub.endReason = reason;
157
198
  try { res.write(frame({ type: 'live-stop', reason })); } catch (_) { /* gone */ }
158
199
  try { res.end(); } catch (_) { /* gone */ }
159
200
  }
160
201
 
202
+ /**
203
+ * THE LINE (0.8.0). `notify: stream end user=<id> sid=<sha256 first 8> reason=<word> age=<s> topics=<n> audience=<a>`,
204
+ * plus ` status=refused` for a stream refused at attach. Never the raw session id, a cookie, a topic's id or a name.
205
+ */
206
+ function logEnd({ userId, sessionId, reason, openedAt, topics, audience, refused: wasRefused }) {
207
+ if (!logEnds) return;
208
+ const r = reasonWord(reason || 'client_closed');
209
+ const age = openedAt == null ? 0 : Math.max(0, Math.round((now() - openedAt) / 1000));
210
+ const uid = Number.isFinite(Number(userId)) && userId !== null && userId !== '' ? Number(userId) : '-';
211
+ const aud = /^[a-z_]{1,32}$/.test(String(audience)) ? audience : DEFAULT_AUDIENCE;
212
+ const line = `notify: stream end user=${uid} sid=${sidTag(sessionId)} reason=${r} age=${age} topics=${Number(topics) || 0} audience=${aud}${wasRefused ? ' status=refused' : ''}`;
213
+ const level = !wasRefused && DEBUG_REASONS.includes(r) ? 'debug' : 'info';
214
+ try { if (logger && typeof logger[level] === 'function') logger[level](line); } catch (_) { /* noop */ }
215
+ }
216
+
161
217
  /** The keys a subscription asks for: the one `entity` (0.4.0) and `topics` (0.5.0), de-duplicated. */
162
218
  function keysOf(opts) {
163
219
  const out = [];
@@ -178,13 +234,46 @@ function createHub({
178
234
  if (sub && sub.unsubscribe) sub.unsubscribe();
179
235
  }
180
236
 
181
- function refused(res, reason) {
237
+ function refused(res, reason, who) {
182
238
  stopRes(res, reason);
239
+ logEnd({ ...who, reason, openedAt: null, refused: true });
183
240
  const noop = function unsubscribe() {};
184
241
  noop.refused = reason;
185
242
  return noop;
186
243
  }
187
244
 
245
+ /**
246
+ * REFUSE A STREAM AT ATTACH (0.8.0) — the app's own refusal (its topic check said no, live updates are off, the page's
247
+ * user changed): told `live-stop <reason>`, ended, and logged like every other end. Replaces the app's hand-written
248
+ * frame + `res.end()`, so attach refusals are in the log too. `who`: { userId, sessionId, audience?, topics? } — the
249
+ * session id is hashed before it is logged, and only the topics' COUNT is. Returns the same no-op unsubscribe carrying
250
+ * `.refused` that subscribe returns for a stream it refused.
251
+ */
252
+ function refuse(res, reason, who = {}) {
253
+ return refused(res, String(reason), {
254
+ userId: who.userId, sessionId: who.sessionId,
255
+ audience: who.audience == null ? DEFAULT_AUDIENCE : who.audience,
256
+ topics: Array.isArray(who.topics) ? who.topics.length : Number(who.topics) || 0
257
+ });
258
+ }
259
+
260
+ /**
261
+ * RENEW A STREAM (0.8.0): `live-renew`, ended, forgotten — the PLANNED end. bell.js reopens at once without an error,
262
+ * so no strip, and the reopen is a new request judged afresh (requireAuth, the app's re-check, attach). For an app that
263
+ * ends streams on its own clock (the hub sign-in's 30-minute cut, `limitStream`): call this instead of `res.end()`.
264
+ * `reason` names it in the log (`sso_cut`; default `renew`). A `res` the hub never registered (refused, or not yet
265
+ * subscribed) is still told and ended, and not logged: a refusal was logged when it was refused.
266
+ */
267
+ function renew(res, reason = 'renew') {
268
+ const sub = subs.get(res);
269
+ if (sub && !sub.endReason) sub.endReason = reasonWord(reason);
270
+ if (!res.writableEnded) {
271
+ try { res.write(frame({ type: 'live-renew' })); } catch (_) { /* gone */ }
272
+ try { res.end(); } catch (_) { /* gone */ }
273
+ }
274
+ if (sub && sub.unsubscribe) sub.unsubscribe();
275
+ }
276
+
188
277
  const held = (a) => (audiences.get(a) || new Set()).size;
189
278
  const heldAll = () => [DEFAULT_AUDIENCE, ...Object.keys(L.perAudience)].map((a) => `${a} ${held(a)}`).join(', ');
190
279
 
@@ -228,7 +317,8 @@ function createHub({
228
317
  if (audience !== DEFAULT_AUDIENCE && !Object.prototype.hasOwnProperty.call(L.perAudience, audience)) {
229
318
  throw new Error(`notify: subscribe audience ${JSON.stringify(audience)} is neither ${DEFAULT_AUDIENCE} nor one of limits.perAudience (${Object.keys(L.perAudience).join(', ')})`);
230
319
  }
231
- if (keys.length > L.topicsPerStream) return refused(res, 'too_many_topics');
320
+ const who = { userId: uid, sessionId: sid, audience, topics: keys.length };
321
+ if (keys.length > L.topicsPerStream) return refused(res, 'too_many_topics', who);
232
322
  const isLive = keys.length > 0;
233
323
  // A BELL-ONLY stream is capped per USER (never per session: the bell is per person), before the process cap, so one
234
324
  // user opening bells in a loop evicts their own oldest instead of filling the process and starving everyone else.
@@ -246,14 +336,15 @@ function createHub({
246
336
  // process cap so the log names the cap that actually refused it. The default audience has no cap of its own here.
247
337
  if (audience !== DEFAULT_AUDIENCE && held(audience) >= L.perAudience[audience]) {
248
338
  logBusy('audience', audience);
249
- return refused(res, 'busy');
339
+ return refused(res, 'busy', who);
250
340
  }
251
341
  if (subs.size >= L.perProcess) {
252
342
  logBusy('process', audience);
253
- return refused(res, 'busy');
343
+ return refused(res, 'busy', who);
254
344
  }
255
345
 
256
- const sub = { userId: uid, sessionId: sid, audience, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null };
346
+ const sub = { userId: uid, sessionId: sid, audience, keys, meta: opts.meta, verdicts: new Map(), closed: false, timer: null, unsubscribe: null,
347
+ openedAt: now(), endReason: null };
257
348
  subs.set(res, sub);
258
349
  add(users, uid, res);
259
350
  add(audiences, audience, res);
@@ -272,16 +363,15 @@ function createHub({
272
363
  for (const k of keys) remove(entities, k, res);
273
364
  if (isLive && sid) remove(sessions, sid, res);
274
365
  if (isLive) remove(liveUsers, uid, res); else remove(bellUsers, uid, res);
366
+ // The one line per end (0.8.0): the reason recorded by whoever ended it (a stop, an eviction, the lifetime, renew()),
367
+ // else the client went away (a navigation, a closed tab, a hidden tab).
368
+ logEnd({ userId: uid, sessionId: sid, reason: sub.endReason || 'client_closed', openedAt: sub.openedAt, topics: keys.length, audience });
275
369
  }
276
370
  sub.unsubscribe = unsubscribe;
277
371
 
278
372
  // THE LIFETIME: renewed, not refused. The client reconnects at once and catches up (bell.js
279
373
  // on `live-renew`), and the new stream is judged afresh — a scope cannot outlive it.
280
- sub.timer = setTimeout(() => {
281
- try { res.write(frame({ type: 'live-renew' })); } catch (_) { /* gone */ }
282
- try { res.end(); } catch (_) { /* gone */ }
283
- unsubscribe();
284
- }, L.lifetimeMs);
374
+ sub.timer = setTimeout(() => renew(res, 'renew'), L.lifetimeMs);
285
375
  if (sub.timer.unref) sub.timer.unref();
286
376
  return unsubscribe;
287
377
  }
@@ -433,7 +523,7 @@ function createHub({
433
523
  audiences.clear();
434
524
  }
435
525
 
436
- return { subscribe, pushUsers, pushEntity, publish, publishSoon, watched, stats, streamStats, closeAll };
526
+ return { subscribe, refuse, renew, pushUsers, pushEntity, publish, publishSoon, watched, stats, streamStats, closeAll };
437
527
  }
438
528
 
439
- module.exports = { createHub, HEARTBEAT_MS, LIMITS, DEFAULT_AUDIENCE, RECHECK_MS, COALESCE_MS };
529
+ module.exports = { createHub, pageUserChanged, sidTag, HEARTBEAT_MS, LIMITS, DEFAULT_AUDIENCE, RECHECK_MS, COALESCE_MS };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/notify",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery (with topics, caps per session, user, audience and process, and a per-event authorise hook for live pages), and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -29,7 +29,7 @@
29
29
  "jsdom": "^30.0.1"
30
30
  },
31
31
  "scripts": {
32
- "test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/live-hub.js && node test/emit.js && node test/bell.js && node test/bell-rows.js && node test/live-client.js",
32
+ "test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/live-hub.js && node test/hub-ends.js && node test/emit.js && node test/bell.js && node test/bell-rows.js && node test/live-client.js && node test/live-resilience.js && node test/live-reauth.js",
33
33
  "prepublishOnly": "node ../../test/packaging.js notify"
34
34
  }
35
35
  }
@@ -11,7 +11,11 @@
11
11
  and with JS off the bell stays a working link to the notifications page)
12
12
  notifWidth dropdown width (default '340px')
13
13
  notifAssets where assets/ is mounted (default '/js/notify'; bell.css is linked from it,
14
- so the unread look ships with the markup and an app cannot forget it) %>
14
+ so the unread look ships with the markup and an app cannot forget it)
15
+ notifUser 0.8.0: the id of the user (or contact key) the page is drawn for. bell.js sends it
16
+ on the stream as `u=`, so the route can refuse `user_changed` when another user
17
+ has signed in in another tab (hub.js pageUserChanged). Refuse-only: absent, nothing
18
+ is checked (the 0.7.x behaviour). Not a secret: the page is that user's. %>
15
19
  <%
16
20
  var __base = (typeof notifBase === 'undefined') ? '/notifications' : notifBase;
17
21
  var __fill = (typeof notifFill === 'undefined') ? 'load' : notifFill;
@@ -19,9 +23,10 @@
19
23
  var __unread = (typeof notifUnread === 'undefined') ? 0 : Number(notifUnread) || 0;
20
24
  var __width = (typeof notifWidth === 'undefined') ? '340px' : notifWidth;
21
25
  var __assets = (typeof notifAssets === 'undefined') ? '/js/notify' : notifAssets;
26
+ var __user = (typeof notifUser === 'undefined' || notifUser === null) ? '' : String(notifUser);
22
27
  %>
23
28
  <link rel="stylesheet" href="<%= __assets %>/bell.css">
24
- <div class="dropdown" id="notif-menu" data-notif-base="<%= __base %>" data-notif-fill="<%= __fill %>"<% if (__quiet) { %> data-notif-quiet="<%= __quiet %>"<% } %>>
29
+ <div class="dropdown" id="notif-menu" data-notif-base="<%= __base %>" data-notif-fill="<%= __fill %>"<% if (__quiet) { %> data-notif-quiet="<%= __quiet %>"<% } %><% if (__user) { %> data-notif-user="<%= __user %>"<% } %>>
25
30
  <a href="<%= __base %>" class="bell-btn" role="button"
26
31
  data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false" title="Notifications">
27
32
  <i class="bi bi-bell"></i>