strapi-plugin-magic-sessionmanager 4.10.0 → 4.12.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 (31) hide show
  1. package/CHANGELOG.md +92 -6
  2. package/README.md +263 -72
  3. package/dist/admin/{Analytics-PRqsLMEx.mjs → Analytics-C_c24Uzq.mjs} +45 -75
  4. package/dist/admin/{Analytics-CdmRsigN.js → Analytics-lP0-RsVd.js} +45 -75
  5. package/dist/admin/{App-BSeYF7KA.mjs → App-DCyNPn1k.mjs} +162 -119
  6. package/dist/admin/{App-DUMCbuCr.js → App-miWDdmdX.js} +162 -119
  7. package/dist/admin/{OnlineUsersWidget-CDZ19_PT.js → OnlineUsersWidget-C6b7e4jb.js} +18 -26
  8. package/dist/admin/{OnlineUsersWidget-B5pXzqM9.mjs → OnlineUsersWidget-C6wlwENC.mjs} +18 -26
  9. package/dist/admin/{Settings-CrLzRXrA.js → Settings-D9zyn5xn.js} +9 -3
  10. package/dist/admin/{Settings-B-GRuWjT.mjs → Settings-DssYw2W4.mjs} +8 -2
  11. package/dist/admin/{de-DwUCBY1b.mjs → de--yNl7MPl.mjs} +4 -48
  12. package/dist/admin/{de-Dzo1tVoJ.js → de-DjPEATFf.js} +4 -48
  13. package/dist/admin/{en-Dd0wXfgR.mjs → en-5U7g51cH.mjs} +4 -48
  14. package/dist/admin/{en-CL5llI55.js → en-BoO12UQw.js} +4 -48
  15. package/dist/admin/{es-Cl5IwDA4.mjs → es-BJR-zCXL.mjs} +4 -48
  16. package/dist/admin/{es-CiNDwv_f.js → es-BLpEuycJ.js} +4 -48
  17. package/dist/admin/{fr-DBOQ-UDm.js → fr-BE828R9Q.js} +4 -48
  18. package/dist/admin/{fr-DhADj8Zs.mjs → fr-CeeCYQCs.mjs} +4 -48
  19. package/dist/admin/{index-CaLVyCio.js → index-CfQOMZVX.js} +9 -56
  20. package/dist/admin/{index-CHACmZsg.mjs → index-rbxJZcLv.mjs} +35 -82
  21. package/dist/admin/index.js +1 -1
  22. package/dist/admin/index.mjs +2 -2
  23. package/dist/admin/{pt-m73K1nJ0.js → pt-BWEFiuvo.js} +4 -48
  24. package/dist/admin/{pt-CT6VpDMM.mjs → pt-CorrU3yG.mjs} +4 -48
  25. package/dist/server/index.js +815 -628
  26. package/dist/server/index.mjs +815 -628
  27. package/package.json +29 -13
  28. package/dist/admin/License-BeD7Du6r.js +0 -443
  29. package/dist/admin/License-D5W_l35e.mjs +0 -443
  30. package/dist/admin/maskSensitiveValue-BWcSjow7.js +0 -9
  31. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +0 -10
package/README.md CHANGED
@@ -1,22 +1,26 @@
1
1
  # Magic Session Manager
2
2
 
3
- **See who is signed in to your Strapi app, and control their sessions.**
3
+ **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.**
4
4
 
5
- Session Manager records every sign-in of your app's users (Users & Permissions) as a session and lets admins see, end and analyse them. Strapi admin accounts are not managed here.
5
+ Magic Session Manager records every sign-in through Users & Permissions as a session. Admins see who is online, end single sessions or all sessions of a user, block accounts and review sign-in history. Your app gets logout routes, a "my devices" list for users, failed-login lockout and optional country rules. It works with Strapi's native refresh-token sessions and with several server processes on one database.
6
6
 
7
- Free and open under the MIT license. All features are available without a paid license or activation key.
7
+ Free and open source under the MIT license. Every feature works without an account, key or activation, and the plugin sends nothing to its author.
8
8
 
9
- [![NPM](https://img.shields.io/npm/v/strapi-plugin-magic-sessionmanager.svg)](https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager)
10
- [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
9
+ [![npm version](https://img.shields.io/npm/v/strapi-plugin-magic-sessionmanager.svg)](https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager)
10
+ [![npm downloads](https://img.shields.io/npm/dm/strapi-plugin-magic-sessionmanager.svg)](https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager)
11
+ [![Tests](https://github.com/Schero94/Magic-Sessionmanager/actions/workflows/test.yml/badge.svg)](https://github.com/Schero94/Magic-Sessionmanager/actions/workflows/test.yml)
12
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
11
13
 
12
- [Project site](https://schero94.github.io/Magic-Sessionmanager/) · [npm](https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager) · [Issues](https://github.com/Schero94/Magic-Sessionmanager/issues) · [Changelog](CHANGELOG.md)
14
+ Live docs: [https://schero94.github.io/Magic-Sessionmanager/](https://schero94.github.io/Magic-Sessionmanager/) · [npm](https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager) · [Changelog](CHANGELOG.md) · [Report a bug](https://github.com/Schero94/Magic-Sessionmanager/issues/new/choose) · [Discussions](https://github.com/Schero94/Magic-Sessionmanager/discussions)
13
15
 
14
- > **Release status.** The admin UI shown here is the redesign on the branch `claude/sessionmanager-ui-redesign`, which carries the fixes for the next release. Version 4.8.0 on npm was published before its acceptance gates closed and is **not accepted**; see [Maintenance status](#maintenance-status).
16
+ ![Sessions dashboard with four stat cards (Active, Idle, Ended, All), search, status filter and a table of sessions with state badges](pics/dashboard.png)
15
17
 
16
18
  ---
17
19
 
18
20
  ## Contents
19
21
 
22
+ - [Features](#features)
23
+ - [Quick start (1 minute)](#quick-start-1-minute)
20
24
  - [Screenshots](#screenshots)
21
25
  - [Core concepts](#core-concepts)
22
26
  - [Screens](#screens)
@@ -28,27 +32,70 @@ Free and open under the MIT license. All features are available without a paid l
28
32
  - [Login protection](#login-protection)
29
33
  - [Alerts](#alerts)
30
34
  - [Content API](#content-api)
35
+ - [Examples](#examples)
31
36
  - [Optional route policy: `session-required`](#optional-route-policy-session-required)
32
37
  - [Admin API and permissions](#admin-api-and-permissions)
33
38
  - [Running several instances (Railway replicas, pm2 cluster)](#running-several-instances-railway-replicas-pm2-cluster)
39
+ - [Performance](#performance)
34
40
  - [Security and privacy](#security-and-privacy)
35
41
  - [Troubleshooting](#troubleshooting)
42
+ - [FAQ](#faq)
43
+ - [Migration and upgrading](#migration-and-upgrading)
36
44
  - [Development and tests](#development-and-tests)
45
+ - [Contributing](#contributing)
37
46
  - [Maintenance status](#maintenance-status)
38
47
  - [Languages](#languages)
39
48
  - [License](#license)
40
49
 
41
50
  ---
42
51
 
43
- ## Screenshots
52
+ ## Features
53
+
54
+ | Area | What you get |
55
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | Overview | A sessions dashboard with Active, Idle and Ended counts, search, filters, CSV and JSON export, and a details dialog per session (device, browser, IP address, location, security score). |
57
+ | Control | End one session, end all sessions of a user, delete a record, or block a user. Ended sessions are rejected on the next request with 401 and a reason header. |
58
+ | Your users | Content API routes for "my sessions", "current session", log out, log out everywhere and log out other devices. Each user only ever sees their own sessions. |
59
+ | Login protection | Temporary IP lockout after failed sign-ins, Content API rate limits, optional rejection of VPN, proxy or low-score sign-ins, and country allow or block lists. |
60
+ | Location | IP location from a local MaxMind GeoLite2 database (no third party in the sign-in path) or from ipapi.co, or turned off. |
61
+ | Alerts | Security emails to the user through Strapi's Email plugin and sign-in notifications to Discord or Slack. |
62
+ | Admin integration | A Sessions panel next to each user in the Content Manager and an Online users widget on the Strapi homepage. |
63
+ | Native Strapi sessions | Works with `jwtManagement: 'refresh'` (Strapi's own sessions and refresh tokens) and with `'legacy-support'`. |
64
+ | Several processes | Lockout, rate limits, jobs and settings stay consistent across pm2 workers and Railway replicas that share one database. |
65
+ | Privacy | Stored tokens are encrypted (AES-256-GCM) and never returned. Retention deletes old history automatically. No telemetry. |
44
66
 
45
- All screenshots use synthetic data: users `*.example.test`, IP addresses from the documentation range `203.0.113.0/24`, Strapi 5.61.
67
+ ---
46
68
 
47
- ### Sessions dashboard
69
+ ## Quick start (1 minute)
48
70
 
49
- ![Sessions dashboard with four stat cards (Active, Idle, Ended, All), search, status filter and a table of sessions with state badges](pics/dashboard.png)
71
+ ```bash
72
+ npm install strapi-plugin-magic-sessionmanager
73
+ ```
74
+
75
+ ```typescript
76
+ // config/plugins.ts
77
+ export default () => ({
78
+ 'magic-sessionmanager': { enabled: true },
79
+ });
80
+ ```
81
+
82
+ ```bash
83
+ # a stable key for token encryption (startup fails without it in production)
84
+ echo "SESSION_ENCRYPTION_KEY=$(node -e "console.log(require('crypto').randomBytes(32).toString('base64'))")" >> .env
85
+ npm run build && npm run develop
86
+ ```
87
+
88
+ Sign in to your app as an end user (`POST /api/auth/local`), open **Session Manager** in the admin menu and the new session is listed as **Active**. End it, and the same token gets 401 on its next request.
89
+
90
+ Yarn and pnpm work the same way (`yarn add strapi-plugin-magic-sessionmanager`, `pnpm add strapi-plugin-magic-sessionmanager`).
91
+
92
+ ---
93
+
94
+ ## Screenshots
50
95
 
51
- Dark mode:
96
+ All screenshots use synthetic data: users `*.example.test`, IP addresses from the documentation range `203.0.113.0/24`, Strapi 5.61.
97
+
98
+ ### Sessions dashboard in dark mode
52
99
 
53
100
  ![Sessions dashboard in the Strapi dark theme](pics/dashboard-dark.png)
54
101
 
@@ -126,17 +173,17 @@ Dark mode:
126
173
  | Strapi homepage | **Online users** widget | Who is online right now? |
127
174
  | Settings › Session Manager | **Configuration** | How should sessions and sign-ins behave? |
128
175
  | Settings › Session Manager | **Analytics** | How are sessions used over time and by device? |
129
- | Settings › Session Manager | **License** | Is a license key stored, and is it valid? |
130
176
 
131
177
  ### Sessions dashboard
132
178
 
133
- - **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).
179
+ - **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).
134
180
  - **How sessions work:** a collapsed legend of the three states.
135
181
  - **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**.
136
182
  - **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.
137
183
  - **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.
138
184
  - Filters, search, page and page size are kept in the URL, so `?search=<email>` is a shareable link.
139
- - When more than 1,000 sessions exist, an alert says that counts, filters and exports cover the latest 1,000 only.
185
+ - 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.
186
+ - In `refresh` mode, open Strapi sessions that have no session details from this plugin (for example sign-ins from before it was installed) are counted in a notice and listed on each user's sessions panel.
140
187
  - Below the large breakpoint the IP address and Signed in columns are hidden; below the medium breakpoint the table becomes a card list.
141
188
 
142
189
  ### Session details
@@ -163,7 +210,7 @@ Strapi 5.13 and later. Four tiles: **Online users** (of all registered users), *
163
210
 
164
211
  ### Settings › Session Manager
165
212
 
166
- Three links: **Configuration**, **Analytics** and **License**.
213
+ Two links: **Configuration** and **Analytics**.
167
214
 
168
215
  **Configuration** has five tabs, deep-linkable with `?tab=sessions|login-protection|location-data|alerts|data-retention`:
169
216
 
@@ -177,21 +224,22 @@ Three links: **Configuration**, **Analytics** and **License**.
177
224
 
178
225
  **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.
179
226
 
180
- **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.
181
-
182
- **License** shows whether an optional license key is stored and whether it is valid. It is read-only. All features are available with or without a key.
227
+ **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).
183
228
 
184
229
  ---
185
230
 
186
231
  ## Compatibility
187
232
 
188
- | Item | Supported |
189
- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
190
- | Strapi | 5 (`@strapi/strapi` peer range `^5.0.0`). Acceptance host: Strapi 5.61.0. |
191
- | Node.js | `^22.22.2 \|\| >=24.15.0` (`engines.node`) |
192
- | Users & Permissions | `jwtManagement: 'refresh'` and `'legacy-support'` |
193
- | Homepage widget | Strapi 5.13 and later (older versions have no widgets API; the rest works) |
194
- | Admin peer dependencies | `@strapi/design-system` `^2.0.0`, `@strapi/icons` `^2.0.0`, `react` / `react-dom` `^18.3.1`, `react-intl` `^6.0.0`, `react-router-dom` `^6.0.0`, `styled-components` `^6.0.0` |
233
+ | Item | Supported |
234
+ | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
235
+ | Strapi | 5 (`@strapi/strapi` peer range `^5.0.0`). Acceptance host: Strapi 5.61.0. |
236
+ | Node.js | `^22.22.2 \|\| >=24.15.0` (`engines.node`) |
237
+ | Users & Permissions | `jwtManagement: 'refresh'` and `'legacy-support'` |
238
+ | Homepage widget | Strapi 5.13 and later (older versions have no widgets API; the rest works) |
239
+ | Required peers | `@strapi/strapi` `^5.0.0`, `@strapi/plugin-users-permissions` `^5.0.0`, `react` / `react-dom` `^18.0.0`, `react-router-dom` `^6.0.0`, `styled-components` `^6.0.0`. A new Strapi 5 app already has all of them. |
240
+ | Optional peers | `@strapi/design-system` `^2.0.0`, `@strapi/icons` `^2.0.0`, `react-intl` `^6.0.0`. Strapi's admin brings them; they are marked optional so npm, Yarn and pnpm do not warn. |
241
+ | Package managers | npm, Yarn 1 and pnpm. Installing into a fresh Strapi 5.61 app prints no warning about this plugin. |
242
+ | Databases | PostgreSQL, MySQL, SQLite (several processes need PostgreSQL or MySQL, see [Running several instances](#running-several-instances-railway-replicas-pm2-cluster)). |
195
243
 
196
244
  ---
197
245
 
@@ -278,14 +326,14 @@ Static defaults from `server/src/config/index.js`; admin units and ranges from t
278
326
 
279
327
  | Key | Default | Admin unit and range | Configuration tab | Meaning |
280
328
  | ------------------------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
281
- | `inactivityTimeout` | 15 min (`900000` ms) | min, 1–1440 | Sessions | Unused this long, a session becomes idle and then ends as "Timed out". Also decides who counts as online. |
282
- | `maxSessionAgeDays` | 30 | days, 1–365 | Sessions | Maximum age from sign-in, regardless of activity. Applied on the session's next request. |
283
- | `lastSeenRateLimit` | 30 s (`30000` ms) | s, 5–300 | Sessions › Advanced | Minimum interval between "Last active" updates. |
284
- | `cleanupInterval` | 30 min (`1800000` ms) | min, 5–1440 | Sessions › Advanced | How often the idle check runs. It ends idle sessions and deletes nothing. It also runs at server start; with several instances only one runs it per interval. |
329
+ | `inactivityTimeout` | 15 min (`900000` ms) | min, 1 to 1440 | Sessions | Unused this long, a session becomes idle and then ends as "Timed out". Also decides who counts as online. |
330
+ | `maxSessionAgeDays` | 30 | days, 1 to 365 | Sessions | Maximum age from sign-in, regardless of activity. Applied on the session's next request. |
331
+ | `lastSeenRateLimit` | 30 s (`30000` ms) | s, 5 to 300 | Sessions › Advanced | Minimum interval between "Last active" updates. |
332
+ | `cleanupInterval` | 30 min (`1800000` ms) | min, 5 to 1440 | Sessions › Advanced | How often the idle check runs. It ends idle sessions and deletes nothing. It also runs at server start; with several instances only one runs it per interval. |
285
333
  | `cleanupUseDbDirect` | `false` | boolean | Sessions › Advanced | Idle check with one SQL update instead of the Document Service (skips lifecycle hooks). |
286
334
  | `strictSessionEnforcement` | `false` (Relaxed) | boolean | Sessions | Strict rejects tokens without a session record and requests where the check itself fails. Ended, expired and revoked sessions and blocked users are rejected in both modes. |
287
- | `sessionCreationGraceMs` | `5000` | ms, 0–30000 (shown in seconds) | Sessions › Advanced | Window after sign-in in which a token is accepted while its record is being created. |
288
- | `maxFailedLogins` | 5 | 0–100, 0 = off | Login protection | Temporary IP lockout threshold (failed sign-ins from one IP within 15 minutes). |
335
+ | `sessionCreationGraceMs` | `5000` | ms, 0 to 30000 (shown in seconds) | Sessions › Advanced | Window after sign-in in which a token is accepted while its record is being created. |
336
+ | `maxFailedLogins` | 5 | 0 to 100, 0 = off | Login protection | Temporary IP lockout threshold (failed sign-ins from one IP within 15 minutes). |
289
337
  | `trustedProxies` | off | boolean | Login protection | Read the client IP from proxy headers. Only behind a proxy you control. |
290
338
  | `blockSuspiciousSessions` | `false` | boolean | Login protection | Reject suspicious sign-ins. |
291
339
  | `geoLookupFailureMode` | `'auto'` | auto, allow, block | Login protection | What happens when the location cannot be determined. |
@@ -299,8 +347,8 @@ Static defaults from `server/src/config/index.js`; admin units and ranges from t
299
347
  | `alertOnSuspiciousLogin` / `alertOnNewLocation` / `alertOnVpnProxy` | `true` | boolean | Alerts | Which events send an email. |
300
348
  | `enableWebhooks` | `false` | boolean | Alerts | Team notifications. |
301
349
  | `discordWebhookUrl` / `slackWebhookUrl` | `''` | https URL on discord.com / discordapp.com, or hooks.slack.com | Alerts | Any other host is rejected. |
302
- | `retentionDays` | 90 | days, 1–365 or -1 (forever) | Data and retention | How long records of ended sessions are kept. Checked once a day across all instances, the first time about 5 minutes after the server starts. Open sessions are never deleted by retention. |
303
- | `rateLimitWriteMax` / `rateLimitReadMax` / `rateLimitWindowSeconds` | 10 / 120 / 60 | 1–1000 / 1–10000 / 10–3600 | not shown | Content API rate limits. Not editable in the UI; Save keeps the stored values. The write limit can only be made stricter than the route floor. |
350
+ | `retentionDays` | 90 | days, 1 to 365 or -1 (forever) | Data and retention | How long records of ended sessions are kept. Checked once a day across all instances, the first time about 5 minutes after the server starts. Open sessions are never deleted by retention. |
351
+ | `rateLimitWriteMax` / `rateLimitReadMax` / `rateLimitWindowSeconds` | 10 / 120 / 60 | 1 to 1000 / 1 to 10000 / 10 to 3600 | not shown | Content API rate limits. Not editable in the UI; Save keeps the stored values. The write limit can only be made stricter than the route floor. |
304
352
  | `emailTemplates` | empty | subject ≤ 200, HTML ≤ 10,000 (sanitised), text ≤ 5,000 characters | Alerts › Edit email templates | As soon as any template has content, only stored templates are used. Fill in all three, or none. |
305
353
 
306
354
  ### Environment variables
@@ -445,6 +493,64 @@ Example:
445
493
 
446
494
  ---
447
495
 
496
+ ## Examples
497
+
498
+ All examples use a synthetic host `https://api.example.test` and a placeholder token.
499
+
500
+ **A "Your devices" list in your app.** Load the caller's sessions; the current one comes first.
501
+
502
+ ```js
503
+ const res = await fetch('https://api.example.test/api/magic-sessionmanager/my-sessions', {
504
+ headers: { Authorization: `Bearer ${jwt}` },
505
+ });
506
+ const { data, meta } = await res.json();
507
+ // data[0].isCurrentSession === true, meta.active = number of open sessions
508
+ ```
509
+
510
+ **Sign out one other device** (not the current one):
511
+
512
+ ```bash
513
+ curl -X DELETE https://api.example.test/api/magic-sessionmanager/my-sessions/k2v8m1x0q9w7e5r3t1y6u4i2 \
514
+ -H "Authorization: Bearer <JWT>"
515
+ # {"message":"...","success":true,"alreadyTerminated":false}
516
+ ```
517
+
518
+ **Sign out everywhere except here** (for example after a password change):
519
+
520
+ ```bash
521
+ curl -X POST https://api.example.test/api/magic-sessionmanager/logout-others \
522
+ -H "Authorization: Bearer <JWT>"
523
+ # {"message":"2 other session(s) terminated","terminatedCount":2,"currentSessionPreserved":true}
524
+ ```
525
+
526
+ **React to an ended session in the client.** A request with an ended session gets 401 and the header `X-Session-Terminated-Reason`. Browsers only let cross-origin JavaScript read that header when CORS exposes it:
527
+
528
+ ```js
529
+ // config/middlewares.js
530
+ module.exports = [
531
+ // ...
532
+ { name: 'strapi::cors', config: { expose: ['X-Session-Terminated-Reason'] } },
533
+ // ...
534
+ ];
535
+ ```
536
+
537
+ ```js
538
+ async function api(path, jwt) {
539
+ const res = await fetch(`https://api.example.test${path}`, {
540
+ headers: { Authorization: `Bearer ${jwt}` },
541
+ });
542
+ if (res.status === 401) {
543
+ const reason = res.headers.get('X-Session-Terminated-Reason'); // logout, manual, idle, expired, blocked
544
+ if (reason === 'blocked') showMessage('This account is blocked.');
545
+ else if (reason) showMessage('You were signed out. Please sign in again.');
546
+ redirectToLogin();
547
+ }
548
+ return res.json();
549
+ }
550
+ ```
551
+
552
+ ---
553
+
448
554
  ## Optional route policy: `session-required`
449
555
 
450
556
  You do **not** need this policy for session revocation. The plugin wraps the Users & Permissions JWT check for every Content API request, so an ended, expired or revoked session is rejected on all routes without configuration. No plugin route attaches the policy.
@@ -480,29 +586,34 @@ module.exports = factories.createCoreRouter('api::order.order', {
480
586
 
481
587
  Prefix `/magic-sessionmanager` (Strapi admin API). Every route requires an authenticated Strapi admin **and** the permission `plugin::magic-sessionmanager.access` ("Access the Session Manager plugin"). The same permission controls the menu link, the settings links, the widget and the user panel. Admin responses never contain tokens or the internal `sessionId`.
482
588
 
483
- | Method | Path | Admin UI action |
484
- | -------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
485
- | GET | `/sessions` | Sessions dashboard, widget, Analytics (latest 1,000; `meta.truncated` when more exist) |
486
- | GET | `/sessions/active` | Open sessions only |
487
- | GET | `/user/:userId/sessions` | Sessions panel |
488
- | POST | `/sessions/:sessionId/terminate` | **End session** (reason `manual`; in refresh mode the Strapi session is revoked first; the record stays) |
489
- | DELETE | `/sessions/:sessionId` | **Delete record** (record removed, token stays revoked; an open session also ends) |
490
- | POST | `/sessions/clean-inactive` | **Delete ended sessions** (all users; open and idle sessions are not affected; does not run the idle check) |
491
- | POST | `/user/:userId/terminate-all` | **End all sessions** (reason `manual`) |
492
- | POST | `/user/:userId/toggle-block` | **Block user** / **Unblock user** |
493
- | GET | `/users/stats` | Widget totals (`totalUsers`, `blockedUsers`) |
494
- | GET | `/geolocation/:ipAddress` | **Look up location** |
495
- | GET | `/geoip/status` | GeoIP database status |
496
- | PUT | `/geoip/credentials` | Save or remove (`{ "clear": true }`) MaxMind credentials |
497
- | POST | `/geoip/update` | Update database / Force download |
498
- | GET, PUT | `/settings` | Configuration (PUT validates every field and returns `error.details.errors` on invalid input) |
499
- | GET | `/license/status` | License page |
500
- | POST | `/license/auto-create`, `/license/create`, `/license/ping`, `/license/store-key` | License service routes (no admin UI) |
501
- | POST | `/sessions/:sessionId/simulate-timeout` | Development only; removed when `NODE_ENV` is `production` or `staging` |
589
+ | Method | Path | Admin UI action |
590
+ | -------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
591
+ | GET | `/sessions` | Sessions dashboard: `?page=&pageSize=` (1-100), `status`, `reason`, `search`, `sort`; see below |
592
+ | GET | `/sessions/active` | Active sessions only; same paging parameters |
593
+ | GET | `/sessions/stats` | Dashboard cards and widget: counts only, cached 5 seconds per process |
594
+ | GET | `/sessions/analytics` | Analytics page: counts and grouped counts over every session, cached 30 seconds |
595
+ | GET | `/sessions/export` | Export batches of up to 1,000 rows, newest first; follow `meta.nextCursor` |
596
+ | GET | `/user/:userId/sessions` | Sessions panel |
597
+ | POST | `/sessions/:sessionId/terminate` | **End session** (reason `manual`; in refresh mode the Strapi session is revoked first; the record stays) |
598
+ | DELETE | `/sessions/:sessionId` | **Delete record** (record removed, token stays revoked; an open session also ends) |
599
+ | POST | `/sessions/clean-inactive` | **Delete ended sessions** (all users; open and idle sessions are not affected; does not run the idle check) |
600
+ | POST | `/user/:userId/terminate-all` | **End all sessions** (reason `manual`) |
601
+ | POST | `/user/:userId/toggle-block` | **Block user** / **Unblock user** |
602
+ | GET | `/users/stats` | Widget totals (`totalUsers`, `blockedUsers`) |
603
+ | GET | `/geolocation/:ipAddress` | **Look up location** |
604
+ | GET | `/geoip/status` | GeoIP database status |
605
+ | PUT | `/geoip/credentials` | Save or remove (`{ "clear": true }`) MaxMind credentials |
606
+ | POST | `/geoip/update` | Update database / Force download |
607
+ | GET, PUT | `/settings` | Configuration (PUT validates every field and returns `error.details.errors` on invalid input) |
608
+ | POST | `/sessions/:sessionId/simulate-timeout` | Development only; removed when `NODE_ENV` is `production` or `staging` |
609
+
610
+ **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.
611
+
612
+ The list, statistics, analytics, export and `/users/stats` routes share the read rate limit (120 requests per minute per admin, raise it with `rateLimitReadMax`).
502
613
 
503
614
  **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.
504
615
 
505
- 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, 503 when the license server is unreachable).
616
+ 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`.
506
617
 
507
618
  ---
508
619
 
@@ -512,17 +623,17 @@ The plugin works with several Strapi processes that share one database, for exam
512
623
 
513
624
  ### What is shared and how
514
625
 
515
- | State | How it stays consistent across processes |
516
- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
517
- | Session validity (end, block, revoke, idle, expiry) | Read from `magic_sessions` on every request. State changes are conditional updates (`UPDATE … WHERE isActive = …`), so a stale read on one process can never revive a terminated session or overwrite a `manual` / `blocked` reason set by another one. |
518
- | Failed-login lockout (`maxFailedLogins`) | One counter per client IP (stored as a SHA-256 hash) in `magic_sm_counters`, updated with a single atomic `UPDATE`. A lock or a successful sign-in applies on every process at once and survives restarts. |
519
- | Content API rate limits | Same shared counters, keyed by route template and caller. The configured limit is the limit for the whole cluster, not per process. |
520
- | Idle cleanup, retention | A job lease in `magic_sm_leases`: every process keeps its timer, but only the process that takes the lease runs the job. Cleanup runs about once per `cleanupInterval`, retention once per day (first run about 5 minutes after a start). |
521
- | Permission setup, session indexes, plugin-store writes (settings, GeoIP credentials, license data) | A cluster-wide critical section: `pg_advisory_xact_lock` on PostgreSQL, a lease row on SQLite and MySQL. Duplicate Core Store rows and duplicate Authenticated-role permissions left by older versions are removed automatically. |
522
- | Settings cache | Each save bumps a shared revision. Every process checks it at most every 2 seconds and reloads when it changed, so a new policy applies everywhere within about 2 seconds. |
523
- | Concurrent settings saves | The admin sends the revision it loaded. If another administrator saved in between, the save is refused with 409 and nothing is overwritten. API clients that send no `revision` keep the previous behaviour. |
524
- | ipapi.co results and back-off | Shared through `magic_sm_cache` (IP stored only as a hash), so one lookup or one HTTP 429 serves all processes. |
525
- | `SESSION_ENCRYPTION_KEY` | Each process compares an HMAC check value of its key (never the key) at start and logs an error when instances use different keys. |
626
+ | State | How it stays consistent across processes |
627
+ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
628
+ | Session validity (end, block, revoke, idle, expiry) | Read from `magic_sessions` on every request. State changes are conditional updates (`UPDATE … WHERE isActive = …`), so a stale read on one process can never revive a terminated session or overwrite a `manual` / `blocked` reason set by another one. |
629
+ | Failed-login lockout (`maxFailedLogins`) | One counter per client IP (stored as a SHA-256 hash) in `magic_sm_counters`, updated with a single atomic `UPDATE`. A lock or a successful sign-in applies on every process at once and survives restarts. |
630
+ | Content API rate limits | Same shared counters, keyed by route template and caller. The configured limit is the limit for the whole cluster, not per process. |
631
+ | Idle cleanup, retention | A job lease in `magic_sm_leases`: every process keeps its timer, but only the process that takes the lease runs the job. Cleanup runs about once per `cleanupInterval`, retention once per day (first run about 5 minutes after a start). |
632
+ | Permission setup, session indexes, plugin-store writes (settings, GeoIP credentials) | A cluster-wide critical section: `pg_advisory_xact_lock` on PostgreSQL, a lease row on SQLite and MySQL. Duplicate Core Store rows and duplicate Authenticated-role permissions left by older versions are removed automatically. |
633
+ | Settings cache | Each save bumps a shared revision. Every process checks it at most every 2 seconds and reloads when it changed, so a new policy applies everywhere within about 2 seconds. |
634
+ | Concurrent settings saves | The admin sends the revision it loaded. If another administrator saved in between, the save is refused with 409 and nothing is overwritten. API clients that send no `revision` keep the previous behaviour. |
635
+ | ipapi.co results and back-off | Shared through `magic_sm_cache` (IP stored only as a hash), so one lookup or one HTTP 429 serves all processes. |
636
+ | `SESSION_ENCRYPTION_KEY` | Each process compares an HMAC check value of its key (never the key) at start and logs an error when instances use different keys. |
526
637
 
527
638
  The three `magic_sm_*` tables are created at startup with portable statements (PostgreSQL, MySQL, SQLite 3.24+). The database user needs the `CREATE` privilege once. Strapi leaves tables it does not manage untouched.
528
639
 
@@ -658,6 +769,24 @@ Measured over HTTP on an isolated Strapi 5.61 host with one PostgreSQL 16 databa
658
769
 
659
770
  ---
660
771
 
772
+ ## Performance
773
+
774
+ The plugin sits in the request path of every authenticated Content API call, so it keeps that path short:
775
+
776
+ | Work | How it is kept cheap |
777
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
778
+ | 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. |
779
+ | 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. |
780
+ | "Last active" updates | At most one write per session per `lastSeenRateLimit` (30 seconds by default), as a conditional update. |
781
+ | Settings | Cached for 30 seconds per process; a shared revision is checked at most every 2 seconds (one primary-key read). |
782
+ | User lookups | Resolving a user's `documentId` is cached for 5 minutes per process. |
783
+ | 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. |
784
+ | 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. |
785
+ | 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. |
786
+ | Old history | Retention deletes ended sessions older than `retentionDays` (90 by default) once a day, so the table does not grow without bound. |
787
+
788
+ ---
789
+
661
790
  ## Security and privacy
662
791
 
663
792
  - **Encryption key.** Stored tokens are encrypted with AES-256-GCM using `SESSION_ENCRYPTION_KEY`. In production, startup fails without it. Outside production a derived development key is used with a warning. Changing the key makes existing encrypted tokens unreadable, so keep it stable. Generate one in **Configuration › Sessions › Advanced** ("Copy for .env" copies `SESSION_ENCRYPTION_KEY="…"`; nothing is saved in Strapi) or with:
@@ -670,6 +799,8 @@ Measured over HTTP on an isolated Strapi 5.61 host with one PostgreSQL 16 databa
670
799
  - **Revocation.** Ended, expired and revoked sessions and blocked users are rejected on every Content API request, in both token check modes. Tokens of deleted records stay on a revocation list.
671
800
  - **Password reset.** A successful password reset ends every older session of the user in both JWT modes.
672
801
  - **Privacy.** Session records contain IP addresses, user agents and location data. With the `auto` or `ipapi` provider, IP addresses can be sent to ipapi.co; use `local-mmdb` or turn off IP location lookup to avoid that. The details dialog never looks up a location unless you click **Look up location**. Set **Keep ended sessions for** to match your retention policy, and use **Delete ended sessions** or **Delete record** to remove history.
802
+ - **What leaves your server.** Only what you turn on: IP lookups at ipapi.co (provider `auto` without a local database, or `ipapi`), Discord or Slack webhooks (Team notifications), emails through your own Email provider (Security emails) and the MaxMind database download when you click **Update database** or run the updater. There is no telemetry, no install ping and no license check.
803
+ - **Reporting a vulnerability.** Please do not post exploit details in a public issue. Open an issue that asks for a private contact, or use the email address on the maintainer's GitHub profile, and you will get a reply before anything is published.
673
804
  - **Secrets.** MaxMind license keys are never returned to the browser. Webhook URLs grant posting rights to your channel; treat them as secrets. Exports never contain tokens.
674
805
  - **Admin sessions** of Strapi administrators are out of scope.
675
806
 
@@ -691,6 +822,59 @@ The plugin stores sessions in the `magic_sessions` table and revocations in its
691
822
 
692
823
  ---
693
824
 
825
+ ## FAQ
826
+
827
+ **Does it manage Strapi admin accounts?**
828
+ No. It manages end users of Users & Permissions (`plugin::users-permissions.user`). Strapi administrator sessions are out of scope.
829
+
830
+ **Do I need a license key, account or activation?**
831
+ No. Everything is free under MIT, and the plugin does not contact any license or telemetry server. The only key you may add is your own MaxMind key for the GeoLite2 database.
832
+
833
+ **Do I have to add the `session-required` policy to my routes?**
834
+ No. Revocation works on every Content API route without configuration. The policy is an optional, explicit per-route check.
835
+
836
+ **Does it work with `jwtManagement: 'refresh'`?**
837
+ Yes. Strapi issues, rotates and revokes its own sessions; the plugin adds device, IP address, location and history, and ends the native session when you end it in the admin.
838
+
839
+ **Can I run it on Railway with several replicas, or with pm2 in cluster mode?**
840
+ Yes, with PostgreSQL or MySQL shared by all processes. See [Running several instances](#running-several-instances-railway-replicas-pm2-cluster). No sticky sessions or Redis are needed.
841
+
842
+ **Does it send my users' IP addresses anywhere?**
843
+ Only if location lookup uses ipapi.co: provider `ipapi`, or `auto` without a local database. Choose `local-mmdb` with a MaxMind database, or `disabled`, to keep IP addresses on your server.
844
+
845
+ **Why do my sign-ins get 429?**
846
+ The temporary IP lockout counts failed sign-ins per IP address. Behind a proxy, turn on Koa's proxy mode or **Trust proxy headers**, otherwise all users share the proxy's address. See [Troubleshooting](#troubleshooting).
847
+
848
+ **What happens to my data when I uninstall?**
849
+ Session history lives in the content-type tables `magic_sessions` and `magic_session_revocations`, which Strapi's schema sync manages. The three coordination tables `magic_sm_counters`, `magic_sm_leases` and `magic_sm_cache` are not managed by Strapi and stay until you drop them.
850
+
851
+ ---
852
+
853
+ ## Migration and upgrading
854
+
855
+ ### To the next release (license removal, from 4.10.x)
856
+
857
+ Nothing to do for most apps.
858
+
859
+ 1. The Settings › Session Manager › License page is gone; Settings shows **Configuration** and **Analytics**. Bookmarks to `/admin/settings/magic-sessionmanager/license` open an empty settings page, as any unknown settings route does in Strapi 5.61.
860
+ 2. The admin routes `GET /magic-sessionmanager/license/status` and `POST /magic-sessionmanager/license/{auto-create,create,ping,store-key}` are removed. Only the plugin's own License page called them. If you scripted them with an admin token, remove those calls.
861
+ 3. On first start the plugin deletes its stored `licenseKey`, `lastValidated` and `deviceId` values from the Core Store. Your MaxMind credentials and all settings stay.
862
+ 4. The environment variables `MAGIC_LICENSE_SERVER_URL` and `MAGIC_LICENSE_TIMEOUT_MS` are no longer read; you can delete them.
863
+ 5. `@strapi/utils` moved from `peerDependencies` to `dependencies`, and `@strapi/design-system`, `@strapi/icons` and `react-intl` are now optional peers. Package managers stop warning about them; no change in your `package.json` is needed.
864
+
865
+ ### From 4.8.x or older 4.x
866
+
867
+ Upgrade to the latest 4.x directly. Notable changes on the way:
868
+
869
+ - 4.9.0: `POST /magic-sessionmanager/user/:userId/toggle-block` should get `{ "blocked": true }` or `{ "blocked": false }`; a bodyless toggle still works but is deprecated. Settings reject out-of-range values with field errors instead of clamping them.
870
+ - 4.10.0: three tables (`magic_sm_counters`, `magic_sm_leases`, `magic_sm_cache`) are created at startup; the database user needs the `CREATE` privilege once. Lockout counters start empty after the upgrade. `coordination: { enabled: false }` restores per-process state.
871
+
872
+ ### From 3.x (Strapi 4) to 4.x (Strapi 5)
873
+
874
+ Version 4.0.0 moved to Strapi 5 and its Document Service API. Upgrade Strapi itself first with the [official Strapi 5 upgrade guide](https://docs.strapi.io/cms/migration/v4-to-v5/introduction-and-faq), then install the latest 4.x of this plugin, rebuild the admin (`npm run build`) and restart. Sessions are addressed by `documentId` in 4.x; clients that stored numeric session ids must switch to `documentId`.
875
+
876
+ ---
877
+
694
878
  ## Development and tests
695
879
 
696
880
  ```bash
@@ -712,14 +896,23 @@ Releases use Conventional Commits and semantic-release on Node.js 22 with npm Tr
712
896
 
713
897
  ---
714
898
 
899
+ ## Contributing
900
+
901
+ Issues and pull requests are welcome.
902
+
903
+ - Bugs and feature ideas: [open an issue](https://github.com/Schero94/Magic-Sessionmanager/issues/new/choose) (templates included). Questions: [Discussions](https://github.com/Schero94/Magic-Sessionmanager/discussions).
904
+ - Pull requests: branch from `main`, write a failing test first, and use Conventional Commits (`fix:`, `feat:`, `docs:`; a breaking change needs a `BREAKING CHANGE:` footer). Before you push, run `npm run lint`, `npm run format:check`, `npm test`, both type checks and `npm run build && npm run verify`.
905
+ - Use synthetic data only in tests, screenshots and issues: `*.example.test` addresses and IP addresses from `203.0.113.0/24`. Never paste real tokens.
906
+
907
+ ---
908
+
715
909
  ## Maintenance status
716
910
 
717
- As of 2026-11-06:
911
+ Actively maintained for the Strapi 5 line. Releases are cut by semantic-release from `main` using Conventional Commits and published to npm with npm Trusted Publishing (GitHub OIDC). Dependabot proposes weekly dependency updates; patch and minor updates are merged only after lint, tests, both type checks, build and `verify` pass.
718
912
 
719
- - **4.8.0 is not accepted.** It was released before its acceptance gates closed. Known defects in 4.8.0, fixed on the redesign branch: the Session details dialog had no accessible name; Settings field hints, including the GeoIP privacy note, did not render; three Settings alerts had unnamed close buttons and country chips could not be removed with the keyboard; in `legacy-support` mode a password reset left older sessions usable; a failed block followed by a retry of the bodyless toggle unblocked the user; the Content API rate limiter could be bypassed by varying the path. See [CHANGELOG.md](CHANGELOG.md).
720
- - **Accepted on the redesign branch:** clean install, 749 of 749 tests, both type checks, build, `verify` and `verify:runtime`, `npm pack --dry-run`; desktop and mobile browser passes for every screen on an isolated Strapi 5.61.0 host with synthetic data; the strict source symmetry contract (no `window.confirm`, emoji, colour literals, px font sizes or custom media queries).
721
- - **Still open before the next release:** full keyboard and screen-reader walks in five locales, dark-mode contrast, the complete state matrix, measured layout symmetry at every breakpoint, a fresh-database host boot, and a consent decision for the `auto` provider's ipapi.co default.
722
- - **Dependency advisories:** the recorded high-severity findings come through the Strapi 5 core dependency chain (`braces` GHSA-vfj7-8cjw-p6xm, Zod GHSA-mrhx-c7xc-m3w5 via `@strapi/utils` 5.61.0). No compatible fix exists; the forced npm fix downgrades to Strapi 4, so none was applied.
913
+ Dependency advisories: the remaining high-severity findings come through the Strapi 5 core dependency chain (`braces` GHSA-vfj7-8cjw-p6xm, Zod GHSA-mrhx-c7xc-m3w5 via `@strapi/utils` 5.61.0). The plugin cannot fix them; the forced npm fix would downgrade to Strapi 4, so it is not applied.
914
+
915
+ Version 4.8.0 was published before its acceptance gates closed and has known defects that 4.9.0 fixed (see the [CHANGELOG](CHANGELOG.md)). Use 4.9.0 or later.
723
916
 
724
917
  Report bugs at https://github.com/Schero94/Magic-Sessionmanager/issues.
725
918
 
@@ -734,5 +927,3 @@ The admin interface is available in English, German (formal "Sie"), French, Span
734
927
  ## License
735
928
 
736
929
  MIT License. Copyright © 2025 Schero D. See [LICENSE](./LICENSE).
737
-
738
- **License page.** Settings › Session Manager › License shows whether an optional license key is stored and valid. The key is used for install tracking and support context only; it does not unlock or restrict any feature.