strapi-plugin-magic-sessionmanager 4.11.0 → 4.13.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +84 -1
  2. package/README.md +75 -24
  3. package/dist/admin/{Analytics-CBHeWeGn.js → Analytics-BikQQx_J.js} +45 -75
  4. package/dist/admin/{Analytics-D56O8Q6e.mjs → Analytics-DIY51RI_.mjs} +45 -75
  5. package/dist/admin/{App-EDIkLJdb.mjs → App-B3vaybSO.mjs} +584 -120
  6. package/dist/admin/{App-D4cBPwB_.js → App-BV1LM9Bp.js} +584 -120
  7. package/dist/admin/{OnlineUsersWidget-MwUutkKQ.mjs → OnlineUsersWidget-T-2upsDd.mjs} +18 -26
  8. package/dist/admin/{OnlineUsersWidget-BF2R2YIy.js → OnlineUsersWidget-fJogM1xl.js} +18 -26
  9. package/dist/admin/{Settings-CMzEF8EH.js → Settings-AyYka8wn.js} +1 -1
  10. package/dist/admin/{Settings-bLMyi0BN.mjs → Settings-BpBlXyMY.mjs} +1 -1
  11. package/dist/admin/{de-CxfuTF6C.mjs → de-BSCDuq1i.mjs} +41 -6
  12. package/dist/admin/{de-DVNTHmSo.js → de-z0aHRwdw.js} +41 -6
  13. package/dist/admin/{en-BcPIlQYL.mjs → en-B4Cuq9JN.mjs} +41 -6
  14. package/dist/admin/{en-BuVXIcHA.js → en-BWPOiiMt.js} +41 -6
  15. package/dist/admin/{es-CEteHmBO.js → es-CMskkUh-.js} +41 -6
  16. package/dist/admin/{es-DxHpaNA1.mjs → es-DBAmysKi.mjs} +41 -6
  17. package/dist/admin/{fr-Dw43lHg7.mjs → fr-BNGdtjEl.mjs} +41 -6
  18. package/dist/admin/{fr-BMd2-wW7.js → fr-ClJ2BkrE.js} +41 -6
  19. package/dist/admin/{index-DvNfekoR.js → index-DyE1rLW0.js} +22 -56
  20. package/dist/admin/{index-qa6Qnfkc.mjs → index-mCVi1j7e.mjs} +48 -82
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-BvO63p01.js → pt-CRh_J7JS.js} +41 -6
  24. package/dist/admin/{pt-7jnxDSX-.mjs → pt-Cl7TWsOV.mjs} +41 -6
  25. package/dist/server/index.js +1495 -51
  26. package/dist/server/index.mjs +1495 -51
  27. package/package.json +10 -2
  28. package/pics/untracked-confirm-dialog.webp +0 -0
  29. package/pics/untracked-disclosure-warning-dark.webp +0 -0
  30. package/pics/untracked-disclosure-warning.webp +0 -0
  31. package/pics/untracked-mobile-notice-warning.webp +0 -0
  32. package/pics/untracked-notice-neutral.webp +0 -0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,86 @@
1
+ # [4.13.0](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.12.0...v4.13.0) (2026-11-12)
2
+
3
+
4
+ ### Features
5
+
6
+ * explain and diagnose untracked Strapi sessions, link sign-ins outside intercepted routes ([#15](https://github.com/Schero94/Magic-Sessionmanager/issues/15)) ([0a8d584](https://github.com/Schero94/Magic-Sessionmanager/commit/0a8d584c1c802c61b412f581c8317a64a77fb336))
7
+
8
+ ## [Unreleased]
9
+
10
+ Release type: minor (`feat` and `fix`), no breaking change. No migration needed; existing routes and responses are unchanged, `GET /sessions/stats` gains one field.
11
+
12
+ ### Fixed
13
+
14
+ * **Strapi sessions created outside Strapi's own REST auth routes are now linked** (`jwtManagement: 'refresh'`). They used to stay without session details and showed up in the "open Strapi sessions" notice:
15
+ * hosts with a custom REST prefix (`api.rest.prefix`, for example `/v1`): no login, refresh, password change or logout was tracked;
16
+ * the GraphQL `login`, `register` and `emailConfirmation` mutations;
17
+ * custom login routes and other plugins that create a session with `strapi.sessionManager('users-permissions')` or the refresh-mode `jwt.issue()` and return the token in the response;
18
+ * intercepted routes whose response carries only an access token (refresh-mode `jwt.issue()`); they no longer fail closed, and an unawaited `jwt.issue()` Promise is resolved so the client gets a real token instead of `{}`.
19
+ * A sign-in that the plugin failed closed (503) before its Strapi session was resolved no longer leaves that Strapi session open.
20
+ * The untracked-session count no longer includes sessions past their absolute expiry (`absoluteExpiresAt`), which Strapi already rejects.
21
+
22
+ ### Added
23
+
24
+ * `GET /magic-sessionmanager/sessions/native-only/summary` (admin, `plugin::magic-sessionmanager.access`, read rate limit): count-only diagnostics of untracked Strapi sessions. Created before or after this plugin started tracking, per creation month, by how Strapi created them (sign-in with device details, password change or reset, token only), by device class (from Strapi's device label, first 2,000 rows) and expiring within 7 and 30 days. No session IDs, user data or IP addresses.
25
+ * `POST /magic-sessionmanager/sessions/native-only/end` (admin, `plugin::magic-sessionmanager.access`, signed-in administrators only, 5 requests per minute): ends untracked Users & Permissions sessions in batches of 200, at most 5,000 per request, and reports how many remain. Strapi administrator sessions, sessions listed in the plugin and sessions younger than two minutes are never touched. Logged with counts only.
26
+ * `GET /sessions/stats` returns `nativeOnlyAfterTracking`: untracked sessions created after the tracking start, or `null` when unknown. The tracking start is stored once at startup in refresh mode (plugin store key `nativeTracking`): the login time of the oldest linked session, or the first start of this version.
27
+
28
+ ### Changed
29
+
30
+ * **Untracked-session notice on the dashboard.** The blue notice "N open Strapi sessions have no session details" is replaced. It now says these are still-valid Strapi sign-ins (refresh tokens) that are not in the list and are not active or online sessions. It is neutral when every one predates tracking (legacy, expires on its own) and a warning, "possible tracking gap", when any was created afterwards. "Why?" opens the summary; "End these sessions" ends them after a confirmation. "How sessions work" explains untracked sign-ins. All five languages.
31
+
32
+ ### Known limits
33
+
34
+ * A session whose token never appears in the response that created it (a token sent by email or another channel, stored server-side, created by a background job) cannot be linked. It stays untracked and counts as "created after tracking". Return Strapi's `{ jwt, refreshToken }` from custom login code, or end such sessions from the dashboard.
35
+
36
+ # [4.12.0](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.11.0...v4.12.0) (2026-11-10)
37
+
38
+
39
+ ### Features
40
+
41
+ * **sessions:** page, filter and count sessions on the server ([#9](https://github.com/Schero94/Magic-Sessionmanager/issues/9)) ([c389614](https://github.com/Schero94/Magic-Sessionmanager/commit/c38961432d4415ded4b9c37c80414dbe787e518a))
42
+
43
+ ### 4.12.0 details
44
+
45
+ No breaking change. Callers of `GET /sessions` without paging parameters get the same response as before.
46
+
47
+ ### Changed
48
+
49
+ * **No 1,000-session limit in the admin.** The dashboard used to load the latest 1,000 sessions and filter, search and page them in the browser, so counts, filters and exports stopped at 1,000 and every load read and enriched all of them. The list is now paged, filtered, searched and sorted on the server with exact totals; only the 25 to 100 rows on the screen are loaded and enriched.
50
+ * **The homepage widget loads counts only** (`GET /sessions/stats`) instead of the whole session list every 30 seconds.
51
+ * **Analytics covers every session** (`GET /sessions/analytics`): counts, sessions per device and browser, distinct users and the average length are computed in SQL and cached for 30 seconds.
52
+ * **Export covers every matching session** up to 50,000 (newest first), read in batches of 1,000 with a cursor. A larger result says so.
53
+ * **In `refresh` mode** the list reconciles the rows on the page with one query on Strapi's session table instead of listing the sessions of every user. Open Strapi sessions without session details from this plugin are counted in a notice; they stay listed on each user's sessions panel.
54
+
55
+ ### Added
56
+
57
+ * `GET /sessions` and `GET /sessions/active` accept `page`, `pageSize` (1-100), `status`, `reason`, `search` (up to 100 characters) and `sort` (whitelisted values). Unknown or out-of-range parameters return 400; pages that start after the first 50,000 matching sessions return 400.
58
+ * `GET /sessions/stats`, `GET /sessions/analytics` and `GET /sessions/export`, protected like every admin route (`plugin::magic-sessionmanager.access`).
59
+ * Database indexes for the list, counts and export (`login_time`, `last_active`, `is_active` with `last_active`, `login_time` or `termination_reason`, and `native_session_id`), created at startup if missing.
60
+
61
+ ### Security
62
+
63
+ * The list, statistics, analytics, export and `/users/stats` routes use the read rate limit (120 per minute per admin, raised with `rateLimitReadMax`).
64
+ * CSV exports neutralise cells that start with `=`, `+`, `-`, `@`, a tab or a carriage return (spreadsheet formula injection).
65
+
66
+ ### Performance
67
+
68
+ Measured on PostgreSQL 16 with 50,000 sessions over 10,000 users (Strapi 5.61, synthetic data):
69
+
70
+ | Request | 4.11.0 | This release |
71
+ | --- | --- | --- |
72
+ | Dashboard (`legacy-support` mode) | 30 ms, 1,000 rows (730 KB), counts capped at 1,000 | 7 ms for a page of 25 (18 KB); 12 ms page plus exact counts |
73
+ | Dashboard (`refresh` mode) | 892 ms, 10,319 queries | 16 ms page plus counts, 13 queries |
74
+ | Widget (`refresh` mode) | 814 ms, 10,328 queries | 10 ms, 10 queries, counts only |
75
+ | Analytics | latest 1,000 sessions only | every session; 5 ms when cached (30 s) |
76
+
77
+ Most remaining queries per request are Strapi's admin authentication, permission check and the rate limiter; the plugin's own list work is a COUNT, the page and one user lookup. Admin requests no longer run the end-user "last seen" lookup (three queries each).
78
+
79
+ ### Migration
80
+
81
+ 1. Nothing to do. Rebuild the admin (`npm run build`) after upgrading.
82
+ 2. Scripts that call `GET /magic-sessionmanager/sessions` without `page` keep working unchanged; add `?page=1&pageSize=100` to page through every session.
83
+
1
84
  # [4.11.0](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.10.0...v4.11.0) (2026-11-07)
2
85
 
3
86
 
@@ -5,7 +88,7 @@
5
88
 
6
89
  * remove the license feature and every license server call ([#8](https://github.com/Schero94/Magic-Sessionmanager/issues/8)) ([c5ba2ef](https://github.com/Schero94/Magic-Sessionmanager/commit/c5ba2ef6b3e32f11cfadaed479a6d2e5688b3415))
7
90
 
8
- ## [Unreleased]
91
+ ## 4.11.0 details (written before the release)
9
92
 
10
93
  Release type: minor. `feat:` removes the license feature; `fix:` corrects the package metadata. No `BREAKING CHANGE` footer, see "Version decision" below.
11
94
 
package/README.md CHANGED
@@ -1,3 +1,7 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/Schero94/Magic-Sessionmanager/main/docs/site/img/icon.svg" alt="Magic Session Manager icon" width="96" height="96" />
3
+ </p>
4
+
1
5
  # Magic Session Manager
2
6
 
3
7
  **See who is signed in to your Strapi 5 app, end any session in one click, and stop password guessing before it reaches your users.**
@@ -121,6 +125,14 @@ All screenshots use synthetic data: users `*.example.test`, IP addresses from th
121
125
 
122
126
  ![Analytics page with four KPIs, Devices and Browsers bar cards and the average session length](pics/analytics.png)
123
127
 
128
+ ### Untracked Strapi sign-ins (refresh mode)
129
+
130
+ ![Neutral notice: 37 older Strapi sign-ins are not tracked, with Why? and End these sessions](pics/untracked-notice-neutral.webp)
131
+
132
+ ![Warning notice "Possible tracking gap" with the opened Why? summary: before/after tracking, how Strapi created them, expiry, per month and devices](pics/untracked-disclosure-warning.webp)
133
+
134
+ ![End untracked Strapi sign-ins confirmation dialog](pics/untracked-confirm-dialog.webp)
135
+
124
136
  ### Mobile (390 px)
125
137
 
126
138
  <p>
@@ -176,13 +188,14 @@ All screenshots use synthetic data: users `*.example.test`, IP addresses from th
176
188
 
177
189
  ### Sessions dashboard
178
190
 
179
- - **Header:** title "Sessions", the links **Analytics** and **Settings** (opens Configuration), and **Export** (CSV or JSON of the filtered list across all pages, with an "End reason" column and never any tokens).
191
+ - **Header:** title "Sessions", the links **Analytics** and **Settings** (opens Configuration), and **Export** (CSV or JSON of every session that matches the filter, up to 50,000 newest, with an "End reason" column and never any tokens).
180
192
  - **How sessions work:** a collapsed legend of the three states.
181
193
  - **Four stat cards** that set the status filter: **Active** ("{n} users online"), **Idle**, **Ended** ("{a} logged out · {b} timed out · {c} other reasons") and **All**.
182
194
  - **Action bar:** search by user, email, IP or device; **Status** filter (All sessions, Open, Active, Idle, Ended); an **End reason** filter when Ended is selected; Refresh. "Last updated" shows when the list was loaded; it also refreshes every 10 minutes.
183
195
  - **Table:** Status (badge and a second line, for example "Ended manually · {date}"), User, Device, IP address, Signed in, Last active and the row actions **View details**, **End session** (disabled on ended rows) and **More actions › Delete record**. Clicking a row opens the details.
184
196
  - Filters, search, page and page size are kept in the URL, so `?search=<email>` is a shareable link.
185
- - When more than 1,000 sessions exist, an alert says that counts, filters and exports cover the latest 1,000 only.
197
+ - Search, filters, sorting and paging run on the server, so the list, the counts and the page numbers cover every session, however many there are. Only the 25 to 100 rows on the screen are loaded.
198
+ - In `refresh` mode, a notice above the cards counts **untracked Strapi sign-ins**: refresh tokens Strapi still accepts that have no session details from this plugin. They are not in the list and are not active or online sessions; each user's sessions panel lists them. The notice is neutral when all of them were created before this plugin started tracking, and a warning ("Possible tracking gap") when any was created afterwards. **Why?** opens a count-only summary; **End these sessions** ends them after a confirmation. See [Untracked Strapi sessions](#untracked-strapi-sessions).
186
199
  - Below the large breakpoint the IP address and Signed in columns are hidden; below the medium breakpoint the table becomes a card list.
187
200
 
188
201
  ### Session details
@@ -223,7 +236,7 @@ Two links: **Configuration** and **Analytics**.
223
236
 
224
237
  **Save** applies the whole form; **Discard changes** re-loads the stored values (it does not restore defaults). Leaving with unsaved changes asks first. Settings are saved in the database; other server processes apply them within 30 seconds.
225
238
 
226
- **Analytics** shows All sessions, Active sessions, Sign-ins in the last 24 hours and in the last 7 days (rolling windows), sessions by device and by browser, and the average session length, all from the latest loaded sessions.
239
+ **Analytics** shows All sessions, Active sessions, Sign-ins in the last 24 hours and in the last 7 days (rolling windows), sessions by device and by browser, and the average session length, computed on the server over every session (cached for 30 seconds).
227
240
 
228
241
  ---
229
242
 
@@ -285,6 +298,31 @@ Session Manager supports Users & Permissions end-user sessions in both the nativ
285
298
 
286
299
  In this mode Strapi issues, rotates and revokes native sessions. Session Manager uses that state for end-user sessions and keeps its own metadata and history (device, IP address, location, security score). It does not issue or rotate a second token family. Rows created natively without a Session Manager record can appear with a `native_` ID; the admin marks them as "Strapi session", and their device, IP address and location are shown as "—" ("Not recorded").
287
300
 
301
+ ### Untracked Strapi sessions
302
+
303
+ Strapi keeps its own session table (`admin::session`). The plugin links each Users & Permissions session it sees to a session record. A session without a record is **untracked**: its refresh token still works until it expires (Strapi defaults: 14 days idle, 30 days at most), but it is not in the dashboard list and never counts as active or online. The dashboard notice shows how many there are; the number counts unexpired refresh tokens, not people.
304
+
305
+ Which sign-ins are linked (tested with Strapi 5.61 on SQLite and PostgreSQL, `/api` and a custom `api.rest.prefix`):
306
+
307
+ | How the session is created | Linked |
308
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
309
+ | `POST /auth/local`, `/auth/local/register`, `GET /auth/:provider/callback`, `POST /auth/refresh` (the rotated session), `/auth/change-password`, `/auth/reset-password` | Yes, under any REST prefix |
310
+ | `GET /auth/email-confirmation` | Creates no session (redirects) |
311
+ | GraphQL `login`, `register`, `emailConfirmation` mutations | Yes |
312
+ | Custom routes or other plugins that call `strapi.sessionManager('users-permissions')` or the refresh-mode `jwt.issue()` and **return the token in the response** (`jwt`) | Yes, from the access token in the response |
313
+ | Code that **does not return the token** in the response that created it (token sent by email or another channel, stored server-side, created by a cron job or script) | **No.** The plugin cannot see which client holds it. It stays untracked. |
314
+ | Sessions created before this plugin started linking sessions | No; they expire on their own |
315
+
316
+ For the last two rows: return Strapi's `{ jwt, refreshToken }` (or the refresh cookie) from custom login code so the plugin can link it, or end untracked sessions from the dashboard.
317
+
318
+ **Reading the summary** (`GET /magic-sessionmanager/sessions/native-only/summary`, also behind **Why?**):
319
+
320
+ - `beforeTracking` / `afterTracking`: created before or after `trackingSince`, the date from which the plugin links sessions (stored once at startup as the login time of the oldest linked session, or the first start of this version). Only `beforeTracking` > 0: legacy rows, nothing to do; they disappear within the refresh-token lifetime. `afterTracking` > 0 and growing: a sign-in path the plugin does not see.
321
+ - `bySource`: `signIn` rows carry Strapi's sign-in details (local, register, provider callback, GraphQL login), `passwordChange` rows come from a password change or reset, `tokenOnly` rows from `jwt.issue()` or custom code. A growing `afterTracking` with `tokenOnly` points at custom code or another plugin; with `signIn`, at a login route on a path the plugin does not intercept that does not return the token.
322
+ - `byMonth`, `earlier`, `byDevice` (desktop, mobile, unknown, from Strapi's device label over at most 2,000 rows), `expiring.within7Days` / `within30Days`.
323
+
324
+ **Ending them** (`POST /magic-sessionmanager/sessions/native-only/end`, **End these sessions**) deletes untracked Users & Permissions rows from Strapi's session table, so their refresh tokens stop working; access tokens already issued run out within Strapi's access-token lifetime (10 minutes by default). Strapi administrator sessions, sessions listed in the plugin and sessions younger than two minutes are never touched. At most 5,000 per request; the response says how many remain.
325
+
288
326
  ### `legacy-support` mode
289
327
 
290
328
  With `jwtManagement: 'legacy-support'`, Session Manager keeps its plugin-owned session behavior. It does not switch the host to refresh mode or migrate existing session records.
@@ -587,8 +625,13 @@ Prefix `/magic-sessionmanager` (Strapi admin API). Every route requires an authe
587
625
 
588
626
  | Method | Path | Admin UI action |
589
627
  | -------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
590
- | GET | `/sessions` | Sessions dashboard, widget, Analytics (latest 1,000; `meta.truncated` when more exist) |
591
- | GET | `/sessions/active` | Open sessions only |
628
+ | GET | `/sessions` | Sessions dashboard: `?page=&pageSize=` (1-100), `status`, `reason`, `search`, `sort`; see below |
629
+ | GET | `/sessions/active` | Active sessions only; same paging parameters |
630
+ | GET | `/sessions/stats` | Dashboard cards and widget: counts only, cached 5 seconds per process |
631
+ | GET | `/sessions/native-only/summary` | **Why?** on the untracked-session notice: counts only, no query parameters (400 otherwise) |
632
+ | POST | `/sessions/native-only/end` | **End these sessions**: empty body; signed-in administrators only (admin API tokens get 403); 5 per minute |
633
+ | GET | `/sessions/analytics` | Analytics page: counts and grouped counts over every session, cached 30 seconds |
634
+ | GET | `/sessions/export` | Export batches of up to 1,000 rows, newest first; follow `meta.nextCursor` |
592
635
  | GET | `/user/:userId/sessions` | Sessions panel |
593
636
  | POST | `/sessions/:sessionId/terminate` | **End session** (reason `manual`; in refresh mode the Strapi session is revoked first; the record stays) |
594
637
  | DELETE | `/sessions/:sessionId` | **Delete record** (record removed, token stays revoked; an open session also ends) |
@@ -603,6 +646,12 @@ Prefix `/magic-sessionmanager` (Strapi admin API). Every route requires an authe
603
646
  | GET, PUT | `/settings` | Configuration (PUT validates every field and returns `error.details.errors` on invalid input) |
604
647
  | POST | `/sessions/:sessionId/simulate-timeout` | Development only; removed when `NODE_ENV` is `production` or `staging` |
605
648
 
649
+ **Session list parameters.** `page` (from 1), `pageSize` (1-100), `status` (`all`, `open`, `active`, `idle`, `ended`), `reason` (with `status=ended`: `logout`, `idle`, `expired`, `manual`, `blocked`, `unrecorded`), `search` (up to 100 characters; matches email, username, IP address, browser, operating system and device type) and `sort` (`loginTime:desc`, `loginTime:asc`, `lastActive:desc`, `lastActive:asc`). The response is `{ data, meta: { pagination: { page, pageSize, total, pageCount } } }` with exact totals. Unknown or out-of-range parameters return 400. Pages that start after the first 50,000 matching sessions return 400; narrow the filter or use the export, which walks every row with a cursor. Without `page` and `pageSize`, `GET /sessions` keeps the 4.x response (latest 1,000 rows, `meta.truncated`) for existing scripts.
650
+
651
+ Both untracked-session routes use the same `plugin::magic-sessionmanager.access` permission as **End session**; the plugin has no separate read-only permission. `POST /sessions/native-only/end` returns `{ data: { ended, remaining, limit } }` and writes one log line with the counts only, 409 while another clean-up runs.
652
+
653
+ The list, statistics, analytics, export, untracked-session summary and `/users/stats` routes share the read rate limit (120 requests per minute per admin, raise it with `rateLimitReadMax`).
654
+
606
655
  **Block / unblock** (`toggle-block`): send `{ "blocked": true }` or `{ "blocked": false }`. This sets the state, is safe to retry and is what the admin UI sends. A request without a body still toggles, but is deprecated, because a retry after a lost response can reverse the intended state. A non-boolean `blocked` returns 400. The response contains `blocked` and `mode` (`explicit` or `toggle`). Blocking ends all open sessions with the reason `blocked`; if that fails, the response is 500 and the request can be retried.
607
656
 
608
657
  Errors use Strapi's `{ data: null, error }` envelope: 400 for invalid input, 404 for unknown IDs, 500 for server-side failures, 502 for a failed MaxMind download, 409 for a settings save based on an outdated `revision`.
@@ -765,16 +814,17 @@ Measured over HTTP on an isolated Strapi 5.61 host with one PostgreSQL 16 databa
765
814
 
766
815
  The plugin sits in the request path of every authenticated Content API call, so it keeps that path short:
767
816
 
768
- | Work | How it is kept cheap |
769
- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
770
- | Session check per request | One lookup by token hash. Startup creates the indexes `idx_magic_sessions_token_hash` and `idx_magic_sessions_refresh_hash` if they are missing. |
771
- | "Last active" updates | At most one write per session per `lastSeenRateLimit` (30 seconds by default), as a conditional update. |
772
- | Settings | Cached for 30 seconds per process; a shared revision is checked at most every 2 seconds (one primary-key read). |
773
- | User lookups | Resolving a user's `documentId` is cached for 5 minutes per process. |
774
- | ipapi.co lookups | Results are cached for 24 hours (failures for 5 minutes) and shared across processes, with the IP stored only as a hash. A local MaxMind database avoids the network call entirely. |
775
- | Admin lists | The dashboard and Analytics load at most the latest 1,000 sessions and say so when more exist. `GET /my-sessions` returns at most 200. |
776
- | Idle cleanup | Runs on one process per interval (job lease). In `legacy-support` mode, `cleanupUseDbDirect: true` ends idle sessions with a single SQL update instead of one Document Service call per session. |
777
- | Old history | Retention deletes ended sessions older than `retentionDays` (90 by default) once a day, so the table does not grow without bound. |
817
+ | Work | How it is kept cheap |
818
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
819
+ | Session check per request | One lookup by token hash. Startup creates the indexes `idx_magic_sessions_token_hash` and `idx_magic_sessions_refresh_hash` if they are missing. |
820
+ | Admin list and counts | Paged in SQL with exact `COUNT` totals; indexes on `login_time`, `last_active`, `is_active` combinations, `termination_reason` and `native_session_id`. Measured on PostgreSQL 16 with 50,000 sessions: a dashboard page in about 7-10 ms, page plus counts in about 12-16 ms. |
821
+ | "Last active" updates | At most one write per session per `lastSeenRateLimit` (30 seconds by default), as a conditional update. |
822
+ | Settings | Cached for 30 seconds per process; a shared revision is checked at most every 2 seconds (one primary-key read). |
823
+ | User lookups | Resolving a user's `documentId` is cached for 5 minutes per process. |
824
+ | ipapi.co lookups | Results are cached for 24 hours (failures for 5 minutes) and shared across processes, with the IP stored only as a hash. A local MaxMind database avoids the network call entirely. |
825
+ | Admin lists | Only the visible page (25-100 rows) is loaded and enriched. Counts for the cards and the widget are cached 5 seconds per process, Analytics 30 seconds. `GET /my-sessions` returns at most 200. |
826
+ | Idle cleanup | Runs on one process per interval (job lease). In `legacy-support` mode, `cleanupUseDbDirect: true` ends idle sessions with a single SQL update instead of one Document Service call per session. |
827
+ | Old history | Retention deletes ended sessions older than `retentionDays` (90 by default) once a day, so the table does not grow without bound. |
778
828
 
779
829
  ---
780
830
 
@@ -799,15 +849,16 @@ The plugin sits in the request path of every authenticated Content API call, so
799
849
 
800
850
  ## Troubleshooting
801
851
 
802
- | Problem | Fix |
803
- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
804
- | No Session Manager menu item | Check `config/plugins.ts`, run `npm run build`, restart, hard-refresh the browser. For non-Super-Admin roles, grant "Access the Session Manager plugin". |
805
- | No sessions appear | Only end-user sign-ins through Users & Permissions are recorded, not Strapi admin sign-ins. Check the Strapi log. |
806
- | Startup fails with `SESSION_ENCRYPTION_KEY is required in production` | Set the variable and restart. |
807
- | 401 on every request after a sign-in | Check the `X-Session-Terminated-Reason` header. With Strict token check, tokens without a session record are rejected. |
808
- | 429 on sign-in | Temporary IP lockout. Wait 15 minutes or raise `maxFailedLogins`. Behind a proxy, turn on Trust proxy headers so the lockout targets the real client. With `Retry-After: 1`: more sign-ins from one address were running at once than `maxFailedLogins`; retry after a second. |
809
- | Location is always "—" | IP location lookup is off, the provider is `disabled`, or `local-mmdb` has no database. See Configuration › Location data. |
810
- | Numbers differ from 4.x | The widget and Analytics now count Active and Idle by the configured inactivity timeout; "Online now" is now "Active sessions". |
852
+ | Problem | Fix |
853
+ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
854
+ | No Session Manager menu item | Check `config/plugins.ts`, run `npm run build`, restart, hard-refresh the browser. For non-Super-Admin roles, grant "Access the Session Manager plugin". |
855
+ | No sessions appear | Only end-user sign-ins through Users & Permissions are recorded, not Strapi admin sign-ins. Check the Strapi log. |
856
+ | Startup fails with `SESSION_ENCRYPTION_KEY is required in production` | Set the variable and restart. |
857
+ | 401 on every request after a sign-in | Check the `X-Session-Terminated-Reason` header. With Strict token check, tokens without a session record are rejected. |
858
+ | 429 on sign-in | Temporary IP lockout. Wait 15 minutes or raise `maxFailedLogins`. Behind a proxy, turn on Trust proxy headers so the lockout targets the real client. With `Retry-After: 1`: more sign-ins from one address were running at once than `maxFailedLogins`; retry after a second. |
859
+ | Location is always "—" | IP location lookup is off, the provider is `disabled`, or `local-mmdb` has no database. See Configuration › Location data. |
860
+ | Notice "Strapi sign-ins are not tracked" | These are unexpired Strapi refresh tokens without session details, not online users. Open **Why?**: only "Before tracking" means legacy rows that expire on their own; a growing "After tracking" means a sign-in path that does not return its token. See [Untracked Strapi sessions](#untracked-strapi-sessions). |
861
+ | Numbers differ from 4.x | The widget and Analytics now count Active and Idle by the configured inactivity timeout; "Online now" is now "Active sessions". |
811
862
 
812
863
  The plugin stores sessions in the `magic_sessions` table and revocations in its own revoked-token table.
813
864
 
@@ -9,18 +9,11 @@ const styled = require("styled-components");
9
9
  const designSystem = require("@strapi/design-system");
10
10
  const icons = require("@strapi/icons");
11
11
  const symbols = require("@strapi/icons/symbols");
12
- const index = require("./index-DvNfekoR.js");
12
+ const index = require("./index-DyE1rLW0.js");
13
13
  const SectionCard = require("./SectionCard-BlWv8CRt.js");
14
14
  const _interopDefault = (e) => e && e.__esModule ? e : { default: e };
15
15
  const styled__default = /* @__PURE__ */ _interopDefault(styled);
16
16
  const ANALYTICS_UNKNOWN_KEY = "unknown";
17
- function increment(target, key) {
18
- target[key] = (target[key] || 0) + 1;
19
- }
20
- function getUserKey(session) {
21
- return session?.user?.documentId || session?.user?.id || session?.user?.email || session?.user?.username || null;
22
- }
23
- const toTime = (value) => value ? Date.parse(value) : Number.NaN;
24
17
  const VERSION_TOKEN = /^v?\d[\w.]*$/i;
25
18
  function toNameBucket(value) {
26
19
  if (typeof value !== "string") return ANALYTICS_UNKNOWN_KEY;
@@ -36,22 +29,6 @@ function getDeviceBucket(session) {
36
29
  function getBrowserBucket(session) {
37
30
  return toNameBucket(session?.browserName);
38
31
  }
39
- function getSessionDurationMinutes(session, now = Date.now()) {
40
- const start = toTime(session?.loginTime);
41
- if (!Number.isFinite(start)) return null;
42
- const lastActive = toTime(session?.lastActive);
43
- const logoutTime = toTime(session?.logoutTime);
44
- let end;
45
- if (session?.isActive) {
46
- end = Number.isFinite(lastActive) ? lastActive : now;
47
- } else if (Number.isFinite(logoutTime)) {
48
- end = logoutTime;
49
- } else {
50
- end = lastActive;
51
- }
52
- if (!Number.isFinite(end)) return null;
53
- return Math.max(0, Math.floor((end - start) / 6e4));
54
- }
55
32
  function getAnalyticsBarRows(counts) {
56
33
  const entries = Object.entries(counts || {}).filter(
57
34
  ([, count]) => Number.isFinite(count) && count > 0
@@ -67,49 +44,50 @@ function getAnalyticsBarRows(counts) {
67
44
  percent: Math.max(0, Math.min(100, Math.round(count / max * 100)))
68
45
  }));
69
46
  }
70
- function computeSessionAnalytics(sessions = [], { now = Date.now() } = {}) {
71
- const rows = Array.isArray(sessions) ? sessions : [];
72
- const dayAgo = now - 24 * 60 * 60 * 1e3;
73
- const weekAgo = now - 7 * 24 * 60 * 60 * 1e3;
74
- const devices = {};
75
- const browsers = {};
76
- const uniqueUsers = /* @__PURE__ */ new Set();
77
- const durations = [];
78
- let activeSessions = 0;
79
- let idleSessions = 0;
80
- let endedSessions = 0;
81
- let signInsLast24Hours = 0;
82
- let signInsLast7Days = 0;
83
- for (const session of rows) {
84
- const loginTime = toTime(session?.loginTime);
85
- if (Number.isFinite(loginTime)) {
86
- if (loginTime > dayAgo) signInsLast24Hours++;
87
- if (loginTime > weekAgo) signInsLast7Days++;
88
- }
89
- if (session?.isActive) {
90
- if (session.isTrulyActive) activeSessions++;
91
- else idleSessions++;
92
- } else {
93
- endedSessions++;
47
+ function mergeGroups(groups, bucket) {
48
+ const out = {};
49
+ for (const group of Array.isArray(groups) ? groups : []) {
50
+ const count = Number(group?.count);
51
+ if (!Number.isInteger(count) || count <= 0) continue;
52
+ const key = bucket(group?.value ?? null);
53
+ out[key] = (out[key] || 0) + count;
54
+ }
55
+ return out;
56
+ }
57
+ function analyticsFromServer(payload) {
58
+ const data = (
59
+ /** @type {any} */
60
+ payload?.data
61
+ );
62
+ const counts = [
63
+ "totalSessions",
64
+ "activeSessions",
65
+ "idleSessions",
66
+ "endedSessions",
67
+ "signInsLast24Hours",
68
+ "signInsLast7Days",
69
+ "uniqueUsers",
70
+ "avgSessionDuration"
71
+ ];
72
+ for (const key of counts) {
73
+ if (!Number.isInteger(data?.[key]) || data[key] < 0) {
74
+ throw new Error("Invalid session analytics response");
94
75
  }
95
- increment(devices, getDeviceBucket(session));
96
- increment(browsers, getBrowserBucket(session));
97
- const userKey = getUserKey(session);
98
- if (userKey) uniqueUsers.add(userKey);
99
- const duration = getSessionDurationMinutes(session, now);
100
- if (duration !== null) durations.push(duration);
76
+ }
77
+ if (!Array.isArray(data.devices) || !Array.isArray(data.browsers)) {
78
+ throw new Error("Invalid session analytics response");
101
79
  }
102
80
  return {
103
- totalSessions: rows.length,
104
- activeSessions,
105
- idleSessions,
106
- endedSessions,
107
- signInsLast24Hours,
108
- signInsLast7Days,
109
- devices,
110
- browsers,
111
- uniqueUsers: uniqueUsers.size,
112
- avgSessionDuration: durations.length > 0 ? Math.floor(durations.reduce((sum, duration) => sum + duration, 0) / durations.length) : 0
81
+ totalSessions: data.totalSessions,
82
+ activeSessions: data.activeSessions,
83
+ idleSessions: data.idleSessions,
84
+ endedSessions: data.endedSessions,
85
+ signInsLast24Hours: data.signInsLast24Hours,
86
+ signInsLast7Days: data.signInsLast7Days,
87
+ devices: mergeGroups(data.devices, (value) => getDeviceBucket({ deviceType: value })),
88
+ browsers: mergeGroups(data.browsers, (value) => getBrowserBucket({ browserName: value })),
89
+ uniqueUsers: data.uniqueUsers,
90
+ avgSessionDuration: data.avgSessionDuration
113
91
  };
114
92
  }
115
93
  const BAR_ROW_INLINE_REM = 24;
@@ -197,7 +175,6 @@ const AnalyticsPage = () => {
197
175
  const [loading, setLoading] = react.useState(true);
198
176
  const [refreshing, setRefreshing] = react.useState(false);
199
177
  const [analytics, setAnalytics] = react.useState(null);
200
- const [truncated, setTruncated] = react.useState(false);
201
178
  const [updatedAt, setUpdatedAt] = react.useState(null);
202
179
  const [loadError, setLoadError] = react.useState(false);
203
180
  const [forbidden, setForbidden] = react.useState(false);
@@ -206,10 +183,8 @@ const AnalyticsPage = () => {
206
183
  if (requestPendingRef.current) return;
207
184
  requestPendingRef.current = true;
208
185
  try {
209
- const { data } = await get(`/${index.pluginId}/sessions`);
210
- const sessions = index.requireSessionList(data);
211
- setAnalytics(computeSessionAnalytics(sessions));
212
- setTruncated(data?.meta?.truncated === true);
186
+ const { data } = await get(`/${index.pluginId}/sessions/analytics`);
187
+ setAnalytics(analyticsFromServer(data));
213
188
  setUpdatedAt(Date.now());
214
189
  setLoadError(false);
215
190
  } catch (err) {
@@ -241,7 +216,7 @@ const AnalyticsPage = () => {
241
216
  const subtitle = analytics ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "epsilon", textColor: "neutral600", tag: "p", children: [
242
217
  t(
243
218
  "analytics.subtitle",
244
- "{count, plural, =0 {No sessions are loaded yet.} one {Based on the latest # loaded session.} other {Based on the latest # loaded sessions.}}",
219
+ "{count, plural, =0 {No sessions yet.} one {Based on all # session.} other {Based on all # sessions.}}",
245
220
  { count: totalSessions }
246
221
  ),
247
222
  updatedAt ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
@@ -302,11 +277,6 @@ const AnalyticsPage = () => {
302
277
  primaryAction: headerActions,
303
278
  children: [
304
279
  errorAlert,
305
- truncated ? /* @__PURE__ */ jsxRuntime.jsx(index.PersistentAlert, { variant: "default", closeLabel: t("common.close", "Close"), children: /* @__PURE__ */ jsxRuntime.jsx(index.ReadableText, { variant: "omega", textColor: "neutral800", tag: "span", children: t(
306
- "analytics.truncated",
307
- "Only the latest {count, number} sessions are loaded. Counts, filters and exports cover these sessions only.",
308
- { count: totalSessions }
309
- ) }) }) : null,
310
280
  hasSessions ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
311
281
  /* @__PURE__ */ jsxRuntime.jsxs(index.StatGrid, { label: t("analytics.stats.label", "Session overview"), alignValues: true, children: [
312
282
  /* @__PURE__ */ jsxRuntime.jsx(