strapi-plugin-magic-sessionmanager 4.8.0 β†’ 4.9.1

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 (72) hide show
  1. package/CHANGELOG.md +90 -5
  2. package/README.md +379 -641
  3. package/dist/admin/Analytics-dyJmyxO-.mjs +418 -0
  4. package/dist/admin/Analytics-lVDnHBYp.js +420 -0
  5. package/dist/admin/App-CdgiY_Y7.js +1896 -0
  6. package/dist/admin/App-Cgf_CSjw.mjs +1894 -0
  7. package/dist/admin/License-1XUfQty5.js +443 -0
  8. package/dist/admin/License-C4WSYoqY.mjs +443 -0
  9. package/dist/admin/OnlineUsersWidget-DJC4V1KS.mjs +255 -0
  10. package/dist/admin/OnlineUsersWidget-DMPtuIpm.js +274 -0
  11. package/dist/admin/SectionCard-BlWv8CRt.js +54 -0
  12. package/dist/admin/SectionCard-D51bv4Hi.mjs +55 -0
  13. package/dist/admin/Settings-0QsyY7fe.js +3570 -0
  14. package/dist/admin/Settings-DgeuUiMF.mjs +3568 -0
  15. package/dist/admin/de-BFKoGEVT.js +544 -0
  16. package/dist/admin/de-j0oZH9Pz.mjs +544 -0
  17. package/dist/admin/en-UY4Tb5tE.mjs +544 -0
  18. package/dist/admin/en-s7Ksdkcg.js +544 -0
  19. package/dist/admin/es-07OGMe_5.js +544 -0
  20. package/dist/admin/es-DGBcZwQy.mjs +544 -0
  21. package/dist/admin/fr-B6-DWhGO.mjs +544 -0
  22. package/dist/admin/fr-ETj_2UBY.js +544 -0
  23. package/dist/admin/index-Ck19e8qw.mjs +1760 -0
  24. package/dist/admin/index-D-Nr0TCm.js +1761 -0
  25. package/dist/admin/index.js +1 -1
  26. package/dist/admin/index.mjs +2 -2
  27. package/dist/admin/maskSensitiveValue-BWcSjow7.js +9 -0
  28. package/dist/admin/maskSensitiveValue-lLRhN_S7.mjs +10 -0
  29. package/dist/admin/pt-C7PwrQtV.js +544 -0
  30. package/dist/admin/pt-YMRLm9gx.mjs +544 -0
  31. package/dist/server/index.js +1092 -463
  32. package/dist/server/index.mjs +1092 -463
  33. package/package.json +10 -1
  34. package/pics/analytics.png +0 -0
  35. package/pics/dashboard-dark.png +0 -0
  36. package/pics/dashboard.png +0 -0
  37. package/pics/dashboardsessionmodal.png +0 -0
  38. package/pics/mobile-dashboard.png +0 -0
  39. package/pics/mobile-session.png +0 -0
  40. package/pics/sessioninfopanel.png +0 -0
  41. package/pics/settings1.png +0 -0
  42. package/pics/settings2.png +0 -0
  43. package/pics/widget.png +0 -0
  44. package/scripts/geoip-updater.cjs +35 -24
  45. package/dist/admin/Analytics-CaRlu5ad.js +0 -332
  46. package/dist/admin/Analytics-THqDbNX0.mjs +0 -330
  47. package/dist/admin/App-AbZwLHtF.js +0 -1263
  48. package/dist/admin/App-hSh7guii.mjs +0 -1261
  49. package/dist/admin/FormField-C8kIT2NE.mjs +0 -59
  50. package/dist/admin/FormField-b5KBvkrj.js +0 -60
  51. package/dist/admin/License-BXBVwUVu.mjs +0 -299
  52. package/dist/admin/License-CABdPwnd.js +0 -301
  53. package/dist/admin/OnlineUsersWidget-BnWFj9IM.mjs +0 -230
  54. package/dist/admin/OnlineUsersWidget-CPFAACSb.js +0 -230
  55. package/dist/admin/PluginPageLayout-BPFMcgrx.mjs +0 -42
  56. package/dist/admin/PluginPageLayout-DmNzMdqu.js +0 -43
  57. package/dist/admin/Settings-B4DNdeKx.js +0 -2152
  58. package/dist/admin/Settings-C4RsJosh.mjs +0 -2150
  59. package/dist/admin/de-AwIFTd9i.mjs +0 -450
  60. package/dist/admin/de-D23nmqnl.js +0 -450
  61. package/dist/admin/en-C5iYQ0mC.js +0 -450
  62. package/dist/admin/en-D6QEGeRh.mjs +0 -450
  63. package/dist/admin/es-CIXnsG-p.js +0 -435
  64. package/dist/admin/es-CnFfVdKw.mjs +0 -435
  65. package/dist/admin/fr-BglXE-W4.js +0 -435
  66. package/dist/admin/fr-DefoR7uH.mjs +0 -435
  67. package/dist/admin/index-BFVITQ-o.mjs +0 -624
  68. package/dist/admin/index-DlMm-NyK.js +0 -625
  69. package/dist/admin/maskSensitiveValue-1uGWmrfG.mjs +0 -20
  70. package/dist/admin/maskSensitiveValue-B9vhxPad.js +0 -19
  71. package/dist/admin/pt-J5sf7jiY.js +0 -435
  72. package/dist/admin/pt-TODwvNQA.mjs +0 -435
package/README.md CHANGED
@@ -1,234 +1,231 @@
1
- # Magic Session Manager πŸ”
1
+ # Magic Session Manager
2
2
 
3
- **See who's logged into your Strapi app - and control their sessions!**
3
+ **See who is signed in to your Strapi app, and control their sessions.**
4
4
 
5
- Track logins, monitor active users, and secure your app with one simple plugin. No complicated setup required.
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.
6
6
 
7
7
  Free and open under the MIT license. All features are available without a paid license or activation key.
8
8
 
9
9
  [![NPM](https://img.shields.io/npm/v/strapi-plugin-magic-sessionmanager.svg)](https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager)
10
10
  [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
11
11
 
12
- [Project site](https://schero94.github.io/Magic-Sessionmanager/)
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)
13
+
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).
13
15
 
14
16
  ---
15
17
 
16
- ## πŸ“Έ What It Looks Like
18
+ ## Contents
19
+
20
+ - [Screenshots](#screenshots)
21
+ - [Core concepts](#core-concepts)
22
+ - [Screens](#screens)
23
+ - [Compatibility](#compatibility)
24
+ - [Install](#install)
25
+ - [Session management modes](#session-management-modes)
26
+ - [Configuration](#configuration)
27
+ - [Location data and GeoIP](#location-data-and-geoip)
28
+ - [Login protection](#login-protection)
29
+ - [Alerts](#alerts)
30
+ - [Content API](#content-api)
31
+ - [Optional route policy: `session-required`](#optional-route-policy-session-required)
32
+ - [Admin API and permissions](#admin-api-and-permissions)
33
+ - [Security and privacy](#security-and-privacy)
34
+ - [Troubleshooting](#troubleshooting)
35
+ - [Development and tests](#development-and-tests)
36
+ - [Maintenance status](#maintenance-status)
37
+ - [Languages](#languages)
38
+ - [License](#license)
17
39
 
18
- ### Homepage Widget - Quick Stats at a Glance
40
+ ---
19
41
 
20
- ![Online Users Widget](pics/widget.png)
42
+ ## Screenshots
21
43
 
22
- **On your Strapi homepage:**
23
- - See online users instantly
24
- - Active in last 15/30 minutes
25
- - Total users count
26
- - Blocked users count
27
- - No need to navigate anywhere!
44
+ All screenshots use synthetic data: users `*.example.test`, IP addresses from the documentation range `203.0.113.0/24`, Strapi 5.61.
28
45
 
29
- ---
46
+ ### Sessions dashboard
30
47
 
31
- ### Main Dashboard - See All Active Sessions
48
+ ![Sessions dashboard with four stat cards (Active, Idle, Ended, All), search, status filter and a table of sessions with state badges](pics/dashboard.png)
32
49
 
33
- ![Dashboard](pics/dashboard.png)
50
+ Dark mode:
34
51
 
35
- **What you see:**
36
- - Who is logged in right now (green = online)
37
- - When they logged in
38
- - What device they're using
39
- - Their IP address and location
40
- - One-click session termination
52
+ ![Sessions dashboard in the Strapi dark theme](pics/dashboard-dark.png)
41
53
 
42
- ---
54
+ ### Session details
43
55
 
44
- ### Session Details Modal
56
+ ![Session details dialog with the state sentence, user, session, device, location and security sections and an End session button](pics/dashboardsessionmodal.png)
45
57
 
46
- ![Session Modal](pics/dashboardsessionmodal.png)
58
+ ### Sessions panel in the Content Manager
47
59
 
48
- **Click any session to see:**
49
- - Full device information
50
- - Browser and operating system
51
- - Complete session history
52
- - IP geolocation
53
- - Security risk score
60
+ ![Sessions panel next to a user in the Content Manager, showing Online, two open sessions, End all sessions and Block user](pics/sessioninfopanel.png)
54
61
 
55
- ---
56
-
57
- ### Content Manager Integration
62
+ ### Homepage widget
58
63
 
59
- ![Session Info Panel](pics/sessioninfopanel.png)
64
+ ![Online users widget with the tiles Online users, Active sessions, Idle sessions and Blocked users](pics/widget.png)
60
65
 
61
- **When viewing a user:**
62
- - Sidebar shows their active sessions
63
- - Quick actions (terminate, block)
64
- - Offline/Online status indicator
65
- - No need to leave the page!
66
+ ### Configuration
66
67
 
67
- ---
68
+ ![Configuration page, Sessions tab, with Session lifetime and Token check cards](pics/settings1.png)
68
69
 
69
- ### Settings Page
70
+ ![Configuration page, Login protection tab, with Failed sign-ins and Client IP address cards](pics/settings2.png)
70
71
 
71
- ![Settings 1](pics/settings1.png)
72
+ ### Analytics
72
73
 
73
- **Easy configuration:**
74
- - Session timeouts
75
- - Rate limiting
76
- - Email alerts
77
- - Webhook notifications
78
- - Geo-blocking rules
74
+ ![Analytics page with four KPIs, Devices and Browsers bar cards and the average session length](pics/analytics.png)
79
75
 
80
- ![Settings 2](pics/settings2.png)
76
+ ### Mobile (390 px)
81
77
 
82
- **Advanced security:**
83
- - Encryption key generator (one click!)
84
- - Country allow/block lists
85
- - VPN detection
86
- - Threat blocking
78
+ <p>
79
+ <img src="pics/mobile-dashboard.png" width="300" alt="Sessions dashboard at 390 px: the table becomes a card list with Details, End session and More buttons">
80
+ <img src="pics/mobile-session.png" width="300" alt="Session details dialog at 390 px in one column with Close and End session in the footer">
81
+ </p>
87
82
 
88
83
  ---
89
84
 
90
- ## ✨ What This Plugin Does
85
+ ## Core concepts
91
86
 
92
- ### Simple Version
87
+ **Session.** One sign-in of a user on one device, from sign-in until it ends. Every session has a **session record** with times, device, IP address and location.
93
88
 
94
- **When users login:**
95
- - Plugin saves who logged in, when, and from where
96
- - You can see them in the dashboard (see screenshot above)
97
- - You can force-logout anyone anytime
89
+ **A session is in one of three states:**
98
90
 
99
- **When users logout:**
100
- - Plugin marks their session as "logged out"
101
- - They disappear from the active sessions list
102
- - Manual logout permanently blocks session reactivation (security feature)
91
+ | State | Meaning |
92
+ | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
93
+ | **Active** | Open and used within the inactivity timeout. |
94
+ | **Idle** | Open, but not used for longer than the inactivity timeout. It ends on its next request or at the next idle check. A token refresh makes it active again. |
95
+ | **Ended** | The session can no longer be used. The user has to sign in again on this device. |
103
96
 
104
- **Session Timeout vs Manual Logout:**
105
- - **Timeout:** Session can be reactivated on next request (seamless UX)
106
- - **Manual Logout:** Session is permanently terminated (security-first)
97
+ **An ended session always shows its end reason:**
107
98
 
108
- **While users are active:**
109
- - Plugin updates their "last seen" time
110
- - You always know who's currently using your app
99
+ | End reason | Stored value | Meaning |
100
+ | ------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
101
+ | Logged out | `logout` | The user signed out. |
102
+ | Timed out | `idle` | Not used for longer than the inactivity timeout. |
103
+ | Expired | `expired` | Reached the maximum session age. |
104
+ | Ended manually | `manual` | Ended from the Strapi admin, or by the user from another of their devices. |
105
+ | User blocked | `blocked` | Ended because the user account was blocked. |
106
+ | Reason not recorded | (none) | No end reason was stored, for example because the session ended in Strapi's own session store or was recorded by an older plugin version. |
111
107
 
112
- ---
108
+ **Three verbs, three meanings:**
113
109
 
114
- ## πŸš€ Quick Install
110
+ - **End** a session: it stops working, the record stays in the history.
111
+ - **Delete record**: the record is removed from history, statistics and exports. If the session is still open, it also ends. Its token stays revoked.
112
+ - **Block** a user: the user cannot sign in, and all open sessions end. **Unblock** allows sign-in again but does not restore ended sessions.
115
113
 
116
- ### Step 1: Install
114
+ **Online** describes users, never sessions: a user is online when at least one of their sessions is Active. The dashboard, the widget and the user panel all use this one rule, based on the configured inactivity timeout.
117
115
 
118
- ```bash
119
- npm install strapi-plugin-magic-sessionmanager
120
- ```
116
+ ---
121
117
 
122
- ### Step 2: Enable Plugin
118
+ ## Screens
123
119
 
124
- Add this to `config/plugins.ts`:
120
+ | Where | Name | Answers |
121
+ | ------------------------------- | ------------------------------------------- | --------------------------------------------------------- |
122
+ | Main menu | **Session Manager** (page title "Sessions") | Which sessions exist, and which need action? |
123
+ | Dialog on the dashboard | **Session details** | What is this session, and why is it in this state? |
124
+ | Content Manager, User edit view | **Sessions** panel | What access does this user have, and how do I cut it off? |
125
+ | Strapi homepage | **Online users** widget | Who is online right now? |
126
+ | Settings β€Ί Session Manager | **Configuration** | How should sessions and sign-ins behave? |
127
+ | Settings β€Ί Session Manager | **Analytics** | How are sessions used over time and by device? |
128
+ | Settings β€Ί Session Manager | **License** | Is a license key stored, and is it valid? |
125
129
 
126
- ```typescript
127
- export default () => ({
128
- 'magic-sessionmanager': {
129
- enabled: true,
130
- },
131
- });
132
- ```
130
+ ### Sessions dashboard
133
131
 
134
- ### Step 3: Rebuild & Start
132
+ - **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).
133
+ - **How sessions work:** a collapsed legend of the three states.
134
+ - **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**.
135
+ - **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.
136
+ - **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.
137
+ - Filters, search, page and page size are kept in the URL, so `?search=<email>` is a shareable link.
138
+ - When more than 1,000 sessions exist, an alert says that counts, filters and exports cover the latest 1,000 only.
139
+ - Below the large breakpoint the IP address and Signed in columns are hidden; below the medium breakpoint the table becomes a card list.
135
140
 
136
- ```bash
137
- npm run build
138
- npm run develop
139
- ```
141
+ ### Session details
140
142
 
141
- ### Step 4: Open Dashboard
143
+ - A state sentence that explains why the session is in its state, for example "Ended {time} Β· Ended manually."
144
+ - **User** (with an **Open user** link to the Content Manager), **Session** (Signed in, Last active, Ended at, End reason), **Device** (type, browser, operating system, IP address), **Location and security** (country, city, time zone, security score "{score}/100", VPN and proxy).
145
+ - **Look up location** for sessions without a stored location. The lookup runs only when you click it, because it can send the IP address to ipapi.co.
146
+ - **Technical details** (collapsed): record ID with a copy button and the raw user agent.
147
+ - Footer: **End session** with confirmation on open sessions; ended sessions show "This session has already ended."
142
148
 
143
- 1. Go to Strapi Admin: `http://localhost:1337/admin`
144
- 2. Look in the left sidebar for **"Sessions"**
145
- 3. Click it!
146
- 4. You'll see the dashboard (like the screenshot above)
149
+ ### Sessions panel (Content Manager)
147
150
 
148
- **That's it! You're done!**
151
+ Shown on the edit view of a Users & Permissions user only.
149
152
 
150
- ---
153
+ - **Online** or **Not online**, "{n} open sessions" (active or idle) and the last activity.
154
+ - **End all sessions:** signs the user out on every device. The user can sign in again unless the account is blocked.
155
+ - **Block user** / **Unblock user:** blocking ends all open sessions and prevents sign-in. The open form's Blocked field is updated, so a later Save does not undo it. Setting the native Blocked field and saving has the same effect.
156
+ - Up to five open sessions, then **Show all sessions**, which opens the dashboard filtered by the user's email.
157
+ - For an unsaved user the panel only says "Save this user before you can manage sessions."
151
158
 
152
- ## πŸ” Security Features (Optional)
159
+ ### Online users widget
153
160
 
154
- ### Encryption Key (Recommended)
161
+ Strapi 5.13 and later. Four tiles: **Online users** (of all registered users), **Active sessions**, **Idle sessions** and **Blocked users**, plus a link **Open Session Manager**. The widget refreshes every 30 seconds.
155
162
 
156
- Your JWT tokens are encrypted before saving to database. Generate a key:
163
+ ### Settings β€Ί Session Manager
157
164
 
158
- **In Admin Panel:**
159
- 1. Go to **Sessions β†’ Settings**
160
- 2. Scroll to **"JWT Encryption Key Generator"**
161
- 3. Click **"Generate Key"**
162
- 4. Click **"Copy for .env"**
163
- 5. Paste into your `.env` file
164
- 6. Restart Strapi
165
+ Three links: **Configuration**, **Analytics** and **License**.
165
166
 
166
- **Or generate manually:**
167
- ```bash
168
- node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
169
- ```
167
+ **Configuration** has five tabs, deep-linkable with `?tab=sessions|login-protection|location-data|alerts|data-retention`:
170
168
 
171
- Then add to `.env`:
172
- ```
173
- SESSION_ENCRYPTION_KEY=your-key-here
174
- ```
169
+ | Tab | Question | Contents |
170
+ | ---------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | **Sessions** | How long does a session stay valid? | Inactivity timeout, maximum session age; Advanced: "Last active" update interval, idle check interval and method. Token check (Strict / Relaxed); Advanced: grace period after sign-in, token encryption key generator. A read-only card on what your app receives when a session is rejected. |
172
+ | **Login protection** | Which sign-ins are refused, and why? | Temporary IP lockout, Trust proxy headers, Reject suspicious sign-ins, If the location cannot be determined, Country rules (Allow only listed countries / Reject listed countries), a read-only card on why sign-ins are refused. |
173
+ | **Location data** | Where do IP location and risk data come from? | IP location lookup, Security scoring, Provider, GeoIP database status, MaxMind credentials, Update database / Force download. |
174
+ | **Alerts** | Who is told about sign-ins? | Security emails to users (with email templates) and Team notifications to Discord or Slack. |
175
+ | **Data and retention** | How long is session history kept? | Keep ended sessions for, and **Delete ended sessions**. |
175
176
 
176
- **Why?** If someone hacks your database, they can't steal user sessions! πŸ”’
177
+ **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.
177
178
 
178
- ---
179
+ **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.
179
180
 
180
- ## 🎯 Main Features Explained Simply
181
+ **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.
181
182
 
182
- ### 1. See Who's Logged In
183
+ ---
183
184
 
184
- **Dashboard Tab:**
185
- - Shows all active users
186
- - Green badge = currently online
187
- - Gray badge = logged out
188
- - Click to see details
185
+ ## Compatibility
189
186
 
190
- ### 2. Force Logout Anyone
187
+ | Item | Supported |
188
+ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
189
+ | Strapi | 5 (`@strapi/strapi` peer range `^5.0.0`). Acceptance host: Strapi 5.61.0. |
190
+ | Node.js | `^22.22.2 \|\| >=24.15.0` (`engines.node`) |
191
+ | Users & Permissions | `jwtManagement: 'refresh'` and `'legacy-support'` |
192
+ | Homepage widget | Strapi 5.13 and later (older versions have no widgets API; the rest works) |
193
+ | 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` |
191
194
 
192
- **Need to kick someone out?**
193
- 1. Find their session
194
- 2. Click **"Terminate"**
195
- 3. Magic Sessionmanager asks the configured session manager to revoke it. The behavior depends on the mode below.
195
+ ---
196
196
 
197
- ### 3. Session Details
197
+ ## Install
198
198
 
199
- **Click any session to see:**
200
- - When they logged in
201
- - Last time they did something
202
- - What browser/device they use
203
- - Their IP address
204
- - Location
199
+ ```bash
200
+ npm install strapi-plugin-magic-sessionmanager
201
+ ```
205
202
 
206
- ### 4. Multiple Devices
203
+ Enable it in `config/plugins.ts`:
207
204
 
208
- **Users can login from:**
209
- - Desktop computer
210
- - Phone
211
- - Tablet
212
- - All at the same time!
205
+ ```typescript
206
+ export default () => ({
207
+ 'magic-sessionmanager': {
208
+ enabled: true,
209
+ },
210
+ });
211
+ ```
213
212
 
214
- Each login = separate session. You can see them all and logout each individually.
213
+ Set the encryption key (required when `NODE_ENV=production`, see [Security and privacy](#security-and-privacy)), then rebuild and start:
215
214
 
216
- ### 5. Auto-Cleanup
215
+ ```bash
216
+ npm run build
217
+ npm run develop
218
+ ```
217
219
 
218
- **Inactive sessions are automatically cleaned up:**
219
- - If user doesn't do anything for 15 minutes (configurable)
220
- - Session is marked as "inactive"
221
- - Keeps your database clean
220
+ Open the Strapi admin and select **Session Manager** in the main menu. Super Admins have access automatically; for other admin roles, grant **Plugins β€Ί Session Manager β€Ί Access the Session Manager plugin** under Settings β€Ί Administration Panel β€Ί Roles.
222
221
 
223
222
  ---
224
223
 
225
- ## πŸ”’ Session management modes
224
+ ## Session management modes
226
225
 
227
- Magic Sessionmanager supports Strapi Users & Permissions end-user sessions in both the native refresh mode and the existing `legacy-support` mode.
226
+ Session Manager supports Users & Permissions end-user sessions in both the native refresh mode and the `legacy-support` mode.
228
227
 
229
- ### Native Users & Permissions sessions
230
-
231
- Set `jwtManagement` to `refresh` in the host application's Users & Permissions configuration to use Strapi's native session manager:
228
+ ### Native Users & Permissions sessions (`jwtManagement: 'refresh'`)
232
229
 
233
230
  ```typescript
234
231
  'users-permissions': {
@@ -238,76 +235,22 @@ Set `jwtManagement` to `refresh` in the host application's Users & Permissions c
238
235
  }
239
236
  ```
240
237
 
241
- In this mode, Strapi issues, rotates and revokes native sessions. Magic Sessionmanager uses that state for end-user sessions while keeping its metadata and session history, such as device, IP, GeoIP and security details. It does not issue or rotate a second token family. Rows created natively without a Magic metadata record can still appear with a `native_` ID. Missing IP, device or GeoIP values are shown as unavailable.
238
+ 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").
242
239
 
243
- The existing Magic endpoints keep their paths, methods, permissions and response envelopes. The plugin does not change the host application's authentication configuration or migrate existing session records. Set `jwtManagement: 'refresh'` in the host application to opt into native session management. Its default Content API permission setup targets only the Authenticated role and never adds these actions to Public. If an administrator saves the Authenticated role before the first protected Magic request, the plugin preserves that role's permission choices. Strapi administrator-account sessions are not managed by this plugin.
240
+ ### `legacy-support` mode
244
241
 
245
- ### Existing `legacy-support` mode
242
+ 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.
246
243
 
247
- When Users & Permissions uses `jwtManagement: 'legacy-support'`, Magic Sessionmanager keeps its existing plugin-owned session behavior. It does not switch the host to refresh mode or migrate legacy session records. Existing Magic endpoints remain available in either mode.
244
+ In both modes the existing Magic endpoints keep their paths, methods, permissions and response envelopes. The plugin does not change the host application's authentication configuration or migrate existing session records. Strapi administrator-account sessions are not managed by this plugin. The default Content API permission setup targets only the Authenticated role and never adds these actions to Public. If an administrator saves the Authenticated role before the first protected request, the plugin keeps that role's permission choices.
248
245
 
249
246
  ---
250
247
 
251
- ## 🌍 Security Features
252
-
253
- ### IP Geolocation
254
-
255
- **See where users login from:**
256
- - Country (with flag! πŸ‡©πŸ‡ͺπŸ‡ΊπŸ‡ΈπŸ‡¬πŸ‡§)
257
- - City
258
- - ISP Provider
259
- - Coordinates (for map)
260
-
261
- ### Local GeoIP Firewall (Recommended)
262
-
263
- For login blocking and city-level session display, use a local MaxMind
264
- GeoLite2 City database. This avoids remote API timeouts and rate limits in the
265
- login path while still giving the admin UI city, region, timezone and
266
- coordinates. Existing GeoLite2 Country databases remain supported as a
267
- country-only fallback.
268
-
269
- 1. Create a free MaxMind account and download `GeoLite2-City.mmdb`:
270
- https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/
271
- 2. Store the file on your Strapi server, for example:
272
- `/var/lib/strapi/GeoLite2-City.mmdb`
273
- 3. Configure the plugin:
274
-
275
- ```bash
276
- MAGIC_SESSIONMANAGER_GEOIP_DATABASE=/var/lib/strapi/GeoLite2-City.mmdb
277
- MAXMIND_EDITION_ID=GeoLite2-City
278
- MAXMIND_ACCOUNT_ID=your-account-id
279
- MAXMIND_LICENSE_KEY=your-license-key
280
- ```
281
-
282
- You can also manage this from the Strapi admin UI. Open
283
- **Magic Session Manager -> Settings -> Geofencing**, choose `local-mmdb`,
284
- enter the MaxMind account ID and license key, then use **Download / Update DB**.
285
- The plugin stores the credentials in the Strapi plugin store and never returns
286
- the license key to the browser after saving it.
287
-
288
- Download or update the database. The CLI updater needs your MaxMind
289
- credentials via environment variables (the in-admin updater stores them in the
290
- Strapi plugin store instead):
291
-
292
- ```bash
293
- export MAXMIND_ACCOUNT_ID=your_account_id
294
- export MAXMIND_LICENSE_KEY=your_license_key
295
- export MAXMIND_EDITION_ID=GeoLite2-City
296
- npm run geoip:update
297
- ```
298
-
299
- When installed as a package in a Strapi project, run the packaged binary:
248
+ ## Configuration
300
249
 
301
- ```bash
302
- npx strapi-magic-sessionmanager-geoip
303
- ```
250
+ Settings come from two places:
304
251
 
305
- The updater checks MaxMind's `Last-Modified` header first and skips the download
306
- when the local metadata is current. Use `npm run geoip:update -- --force` in the
307
- plugin repo or `npx strapi-magic-sessionmanager-geoip --force` in an installed
308
- Strapi project to force a refresh. Schedule it weekly or twice weekly with
309
- cron/systemd. MaxMind requires GeoLite databases to stay up to date and
310
- currently limits GeoLite users to 30 database downloads per day.
252
+ 1. **Static config** in `config/plugins.ts` (`config` below). Time values are in **milliseconds**.
253
+ 2. **Admin settings** (Settings β€Ί Session Manager β€Ί Configuration), stored in the plugin store in user-facing units (minutes, seconds, days). **A value saved in the admin overrides the static config.** Once the Configuration page has been saved, every field shown there comes from the stored settings.
311
254
 
312
255
  ```typescript
313
256
  // config/plugins.ts
@@ -315,532 +258,327 @@ export default () => ({
315
258
  'magic-sessionmanager': {
316
259
  enabled: true,
317
260
  config: {
318
- geoIpProvider: 'local-mmdb',
319
- geoIpDatabasePath: process.env.MAGIC_SESSIONMANAGER_GEOIP_DATABASE,
320
- // "auto": fail closed for suspicious-session blocking, fail open for plain geofencing
321
- // "block": fail closed whenever GEOIP lookup is unavailable
322
- // "allow": fail open whenever GEOIP lookup is unavailable
323
- geoLookupFailureMode: 'block',
324
- enableGeofencing: true,
325
- allowedCountries: ['DE', 'AT', 'CH'],
261
+ inactivityTimeout: 15 * 60 * 1000, // ms
262
+ lastSeenRateLimit: 30 * 1000, // ms
263
+ cleanupInterval: 30 * 60 * 1000, // ms
264
+ maxSessionAgeDays: 30,
265
+ retentionDays: 90, // -1 keeps ended sessions forever
266
+ strictSessionEnforcement: false,
267
+ geoIpProvider: 'auto', // 'auto' | 'local-mmdb' | 'ipapi' | 'disabled'
268
+ geoLookupFailureMode: 'auto', // 'auto' | 'allow' | 'block'
326
269
  },
327
270
  },
328
271
  });
329
272
  ```
330
273
 
331
- Provider options:
332
- - `local-mmdb`: local MaxMind-compatible database only
333
- - `auto`: use local database when configured, otherwise use the legacy remote provider
334
- - `ipapi`: legacy remote provider
335
- - `disabled`: no GEOIP lookup
274
+ ### Reference
275
+
276
+ Static defaults from `server/src/config/index.js`; admin units and ranges from the settings validation in `server/src/controllers/settings.js`. Out-of-range admin values are rejected with a field error, not clamped silently.
277
+
278
+ | Key | Default | Admin unit and range | Configuration tab | Meaning |
279
+ | ------------------------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
280
+ | `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. |
281
+ | `maxSessionAgeDays` | 30 | days, 1–365 | Sessions | Maximum age from sign-in, regardless of activity. Applied on the session's next request. |
282
+ | `lastSeenRateLimit` | 30 s (`30000` ms) | s, 5–300 | Sessions β€Ί Advanced | Minimum interval between "Last active" updates. |
283
+ | `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 once at server start. |
284
+ | `cleanupUseDbDirect` | `false` | boolean | Sessions β€Ί Advanced | Idle check with one SQL update instead of the Document Service (skips lifecycle hooks). |
285
+ | `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. |
286
+ | `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. |
287
+ | `maxFailedLogins` | 5 | 0–100, 0 = off | Login protection | Temporary IP lockout threshold (failed sign-ins from one IP within 15 minutes). |
288
+ | `trustedProxies` | off | boolean | Login protection | Read the client IP from proxy headers. Only behind a proxy you control. |
289
+ | `blockSuspiciousSessions` | `false` | boolean | Login protection | Reject suspicious sign-ins. |
290
+ | `geoLookupFailureMode` | `'auto'` | auto, allow, block | Login protection | What happens when the location cannot be determined. |
291
+ | `enableGeofencing` | `false` | boolean | Login protection | Use country rules. |
292
+ | `allowedCountries` / `blockedCountries` | `[]` | ISO 3166-1 alpha-2 codes | Login protection | Allow only listed countries / Reject listed countries. |
293
+ | `enableGeolocation` | `true` | boolean | Location data | IP location lookup at sign-in. Required by country rules, suspicious-sign-in checks and alerts. |
294
+ | `enableSecurityScoring` | `true` | boolean | Location data | Apply the security score thresholds (below 70: suspicious-sign-in email, below 50: rejection if enabled). |
295
+ | `geoIpProvider` | `'auto'` | auto, local-mmdb, ipapi, disabled | Location data | Where location data comes from. |
296
+ | `geoIpDatabasePath` | `MAGIC_SESSIONMANAGER_GEOIP_DATABASE` or `''` | file name | Location data β€Ί Advanced | Local MaxMind-compatible database. |
297
+ | `enableEmailAlerts` | `false` | boolean | Alerts | Security emails to users. |
298
+ | `alertOnSuspiciousLogin` / `alertOnNewLocation` / `alertOnVpnProxy` | `true` | boolean | Alerts | Which events send an email. |
299
+ | `enableWebhooks` | `false` | boolean | Alerts | Team notifications. |
300
+ | `discordWebhookUrl` / `slackWebhookUrl` | `''` | https URL on discord.com / discordapp.com, or hooks.slack.com | Alerts | Any other host is rejected. |
301
+ | `retentionDays` | 90 | days, 1–365 or -1 (forever) | Data and retention | How long records of ended sessions are kept. Checked once a day, the first time about 24 hours after the server starts. Open sessions are never deleted by retention. |
302
+ | `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. |
303
+ | `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. |
304
+
305
+ ### Environment variables
306
+
307
+ | Variable | Purpose |
308
+ | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
309
+ | `SESSION_ENCRYPTION_KEY` | Key for AES-256-GCM encryption of stored tokens. Required when `NODE_ENV=production` (startup fails without it). Keep it stable. |
310
+ | `MAGIC_SESSIONMANAGER_GEOIP_DATABASE` | Path of a local MaxMind-compatible database (also `GEOIP_DATABASE_PATH`, `GEOLITE2_CITY_MMDB`, `GEOIP_CITY_DATABASE_PATH`, `GEOLITE2_COUNTRY_MMDB`, `GEOIP_COUNTRY_DATABASE_PATH`). |
311
+ | `MAXMIND_ACCOUNT_ID`, `MAXMIND_LICENSE_KEY` | MaxMind credentials for database updates. They take precedence over credentials stored in the admin. |
312
+ | `MAXMIND_EDITION_ID` | Edition for the CLI updater, for example `GeoLite2-City`. |
336
313
 
337
- Local City and Country databases both support country firewall rules. City
338
- databases additionally populate city, region, timezone, coordinates and postal
339
- data for the admin UI. VPN/proxy/threat detection still requires a provider
340
- that supplies those risk signals; free GeoLite databases do not reliably
341
- identify VPNs or proxies.
342
-
343
- ### Threat Detection
314
+ ---
344
315
 
345
- **Automatically check if IP is:**
346
- - VPN
347
- - Proxy
348
- - Known threat
349
- - Security score (0-100)
316
+ ## Location data and GeoIP
350
317
 
351
- ### Auto-Blocking
318
+ ### IP geolocation
352
319
 
353
- **Block logins from:**
354
- - Specific countries
355
- - VPNs or proxies
356
- - Low security score IPs
357
- - Known threat IPs
320
+ IP geolocation is enabled by default and the default provider is `auto`. When no local database is available, `auto` sends the session IP address to ipapi.co for a lookup. If a local lookup fails, `auto` can also send the IP address to ipapi.co. With `geoLookupFailureMode: 'block'`, a failed local lookup does not fall back to ipapi.co. This setting does not prevent the remote lookup when no local database is available.
358
321
 
359
- ### Notifications
322
+ | Provider | Behavior |
323
+ | ------------ | ------------------------------------------------------------------------ |
324
+ | `auto` | Local database when available, with the remote fallback described above. |
325
+ | `local-mmdb` | Local MaxMind-compatible database only. |
326
+ | `ipapi` | Always sends the IP address to ipapi.co. |
327
+ | `disabled` | No lookup. |
360
328
 
361
- **Get alerts when:**
362
- - Suspicious login detected
363
- - VPN used
364
- - New location login
365
- - Send to Discord or Slack!
329
+ To avoid remote IP lookups, choose `local-mmdb`, which uses a local database and does not fall back to ipapi.co. Choose `disabled` for no GeoIP lookup, or set `enableGeolocation: false` for no GeoIP lookup. Country rules, suspicious-sign-in checks and alerts need location data, so these choices also affect them.
366
330
 
367
- ---
331
+ The MaxMind database download is a separate authenticated network request; the MaxMind database download does not send end-user session IP addresses. Local lookups use the downloaded database without contacting MaxMind.
368
332
 
369
- ## πŸ“§ Email Alerts Setup
333
+ ### Local MaxMind database (recommended)
370
334
 
371
- The Session Manager uses **Strapi's Email Plugin** to send notifications. You need to configure an email provider first.
335
+ A local GeoLite2 City database avoids remote lookups in the sign-in path and gives country, city, region, time zone and coordinates. GeoLite2 Country databases are supported as a country-only fallback. Free GeoLite databases do not detect VPNs or proxies, and local results always score 100.
372
336
 
373
- ### Step 1: Install Email Provider
337
+ 1. Create a free MaxMind account: https://dev.maxmind.com/geoip/geolite2-free-geolocation-data/
338
+ 2. In **Configuration β€Ί Location data**, choose the provider **Local database**, enter the MaxMind account ID and license key, and click **Update database**. The license key is stored in the plugin store and never returned to the browser.
374
339
 
375
- Choose one of these providers:
340
+ Or use the CLI updater with environment variables:
376
341
 
377
- **Option A: Nodemailer (Recommended)**
378
342
  ```bash
379
- npm install @strapi/provider-email-nodemailer
343
+ export MAXMIND_ACCOUNT_ID=your_account_id
344
+ export MAXMIND_LICENSE_KEY=your_license_key
345
+ export MAXMIND_EDITION_ID=GeoLite2-City
346
+ npx strapi-magic-sessionmanager-geoip # in a Strapi project
347
+ npm run geoip:update # in the plugin repository
380
348
  ```
381
349
 
382
- **Option B: SendGrid**
383
- ```bash
384
- npm install @strapi/provider-email-sendgrid
385
- ```
350
+ The updater checks MaxMind's `Last-Modified` header and skips the download when the local copy is current; add `--force` to download anyway. Schedule it weekly or twice weekly. MaxMind requires GeoLite databases to stay current and limits GeoLite users to 30 downloads per day.
386
351
 
387
- **Option C: Mailgun**
388
- ```bash
389
- npm install @strapi/provider-email-mailgun
390
- ```
352
+ ---
353
+
354
+ ## Login protection
355
+
356
+ Configuration β€Ί Login protection checks **new sign-ins only**. Existing sessions are not affected, and refused sign-ins are not recorded.
357
+
358
+ | Rule | Response | Notes |
359
+ | ----------------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
360
+ | Temporary IP lockout | 429 with `Retry-After` | After `maxFailedLogins` failed sign-ins from one IP address within 15 minutes, that address is refused for 15 minutes. User accounts are not blocked. Counted per server process. |
361
+ | Reject suspicious sign-ins | 403 | VPN, proxy or known threat address, or, with security scoring on, a score below 50. |
362
+ | Country rules | 403 | Allow only listed countries, or reject listed countries. With "Allow only listed countries", an empty list allows every country. |
363
+ | Location cannot be determined | 403 "Login temporarily unavailable" | When `geoLookupFailureMode` says reject (`auto` rejects only when "Reject suspicious sign-ins" is on). |
364
+
365
+ Requests with an ended session get **401** with the header `X-Session-Terminated-Reason` (`logout`, `manual`, `idle`, `expired` or `blocked`).
366
+
367
+ ---
368
+
369
+ ## Alerts
391
370
 
392
- ### Step 2: Configure Email Plugin
371
+ Configuration β€Ί Alerts. Both kinds are sent only when location data is available for the sign-in.
393
372
 
394
- Add to `config/plugins.ts`:
373
+ - **Security emails to users** go to the end user's own email address, not to administrators: suspicious sign-in, sign-in from a new country (differs from the user's last 50 sessions), VPN or proxy. They use Strapi's Email plugin, so configure an email provider first (for example `@strapi/provider-email-nodemailer`).
374
+ - **Team notifications** post every sign-in to Discord or Slack as `login.suspicious`, otherwise `login.new_location`, otherwise `login.success`. Only `https://discord.com`, `https://discordapp.com` and `https://hooks.slack.com` URLs are accepted; Save rejects any other URL with a field error, and an empty field clears the URL.
375
+
376
+ Example email provider configuration:
395
377
 
396
378
  ```typescript
397
- export default () => ({
398
- // Email configuration
379
+ // config/plugins.ts
380
+ export default ({ env }) => ({
399
381
  email: {
400
382
  config: {
401
383
  provider: 'nodemailer',
402
384
  providerOptions: {
403
- host: process.env.SMTP_HOST || 'smtp.gmail.com',
404
- port: process.env.SMTP_PORT || 587,
405
- auth: {
406
- user: process.env.SMTP_USER,
407
- pass: process.env.SMTP_PASSWORD,
408
- },
385
+ host: env('SMTP_HOST'),
386
+ port: env.int('SMTP_PORT', 587),
387
+ auth: { user: env('SMTP_USER'), pass: env('SMTP_PASSWORD') },
409
388
  },
410
389
  settings: {
411
- defaultFrom: process.env.SMTP_DEFAULT_FROM || 'noreply@yourapp.com',
412
- defaultReplyTo: process.env.SMTP_DEFAULT_REPLY_TO || 'support@yourapp.com',
390
+ defaultFrom: env('SMTP_DEFAULT_FROM'),
391
+ defaultReplyTo: env('SMTP_DEFAULT_REPLY_TO'),
413
392
  },
414
393
  },
415
394
  },
416
-
417
- // Session Manager configuration
418
- 'magic-sessionmanager': {
419
- enabled: true,
420
- },
395
+ 'magic-sessionmanager': { enabled: true },
421
396
  });
422
397
  ```
423
398
 
424
- ### Step 3: Add Environment Variables
425
-
426
- Add to your `.env` file:
427
-
428
- ```env
429
- SMTP_HOST=smtp.gmail.com
430
- SMTP_PORT=587
431
- SMTP_USER=your-email@gmail.com
432
- SMTP_PASSWORD=your-app-password
433
- SMTP_DEFAULT_FROM=noreply@yourapp.com
434
- SMTP_DEFAULT_REPLY_TO=support@yourapp.com
435
- ```
436
-
437
- **For Gmail:**
438
- - Use an [App Password](https://support.google.com/accounts/answer/185833), not your regular password!
439
-
440
- ### Step 4: Enable in Admin Panel
441
-
442
- 1. Go to **Sessions β†’ Settings**
443
- 2. Scroll to **"Email Notifications"**
444
- 3. Toggle **"Enable Email Alerts"** to ON
445
- 4. Customize email templates (optional)
446
- 5. Click **Save**
447
-
448
- ### Step 5: Test It
449
-
450
- Trigger a suspicious login (e.g., use a VPN) and check if the email arrives!
451
-
452
- **Troubleshooting:**
453
- - Check Strapi logs for email errors
454
- - Verify SMTP credentials are correct
455
- - Test SMTP connection with a tool like [smtp-tester](https://www.npmjs.com/package/smtp-tester)
456
-
457
399
  ---
458
400
 
459
- ## πŸ“‹ Content-API Endpoints (For Frontend/Apps)
401
+ ## Content API
460
402
 
461
- All Content-API endpoints require a valid JWT token in the `Authorization` header.
462
- Users can only access their **own** sessions.
403
+ Prefix `/api/magic-sessionmanager`. Every route requires a Users & Permissions JWT (`Authorization: Bearer <JWT>`), works on the caller's **own** sessions only and is rate-limited (writes 10, reads 120 requests per minute by default; 429 with `Retry-After`).
463
404
 
464
- ### Get My Sessions
405
+ | Method | Path | Purpose | Response |
406
+ | ------ | ------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
407
+ | GET | `/my-sessions` | Own sessions (up to 200), current session first | `{ data: [...], meta: { count, active, hasMore, limit } }` |
408
+ | GET | `/current-session` | The session of the current token | `{ data: {..., isCurrentSession: true } }`; 404 when none |
409
+ | GET | `/user/:userId/sessions` | Sessions of a user; only your own `userId` | 403 for another user |
410
+ | POST | `/logout` | End the current session (reason `logout`) | `{ message, terminated }` |
411
+ | POST | `/logout-all` | End all own sessions (reason `logout`) | `{ message, terminatedCount }` |
412
+ | POST | `/logout-others` | End all own sessions except the current one | `{ message, terminatedCount, currentSessionPreserved }` |
413
+ | DELETE | `/my-sessions/:sessionId` | End one own session that is not the current one (reason `manual`) | `{ message, success, alreadyTerminated }`; 400 for the current session, 404 for unknown or foreign IDs |
465
414
 
466
- Returns all sessions for the authenticated user.
415
+ `POST /api/auth/logout` also ends the current session; the plugin mounts it when Users & Permissions does not provide it.
467
416
 
468
- ```bash
469
- GET /api/magic-sessionmanager/my-sessions
470
- Authorization: Bearer <JWT>
471
- ```
417
+ Session objects contain `id`, `documentId`, `sessionId`, `ipAddress`, `userAgent`, `loginTime`, `lastActive`, `logoutTime`, `isActive`, `terminationReason`, `deviceType`, `browserName`, `osName`, `geoLocation`, `securityScore`, `isTrulyActive` (Active rather than Idle), `minutesSinceActive` and `isCurrentSession`. Tokens and token hashes are never returned. Use `id` / `documentId` (or the `native_` ID of a native-only row) for `DELETE /my-sessions/:sessionId`.
418
+
419
+ Example:
472
420
 
473
- **Response:**
474
421
  ```json
475
422
  {
476
423
  "data": [
477
424
  {
478
- "id": "abc123xyz",
479
- "documentId": "abc123xyz",
425
+ "id": "k2v8m1x0q9w7e5r3t1y6u4i2",
426
+ "documentId": "k2v8m1x0q9w7e5r3t1y6u4i2",
480
427
  "sessionId": "sess_m5k2h_8a3b1c2d_f9e8d7c6",
481
- "ipAddress": "192.168.1.100",
482
- "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36...",
483
- "loginTime": "2026-01-02T10:30:00.000Z",
484
- "lastActive": "2026-01-02T13:45:00.000Z",
428
+ "ipAddress": "203.0.113.24",
429
+ "loginTime": "2026-11-06T10:30:00.000Z",
430
+ "lastActive": "2026-11-06T13:45:00.000Z",
485
431
  "logoutTime": null,
486
432
  "isActive": true,
487
433
  "deviceType": "desktop",
488
- "browserName": "Chrome 143",
489
- "osName": "macOS 10.15.7",
490
- "geoLocation": null,
491
- "securityScore": null,
492
- "isCurrentSession": true,
434
+ "browserName": "Chrome",
435
+ "osName": "macOS",
493
436
  "isTrulyActive": true,
494
- "minutesSinceActive": 2
495
- },
496
- {
497
- "id": "def456uvw",
498
- "documentId": "def456uvw",
499
- "sessionId": "sess_m5k1g_7b2a0c1d_e8d7c6b5",
500
- "ipAddress": "10.0.0.50",
501
- "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)...",
502
- "loginTime": "2026-01-01T08:15:00.000Z",
503
- "lastActive": "2026-01-01T12:00:00.000Z",
504
- "logoutTime": null,
505
- "isActive": true,
506
- "deviceType": "mobile",
507
- "browserName": "Safari",
508
- "osName": "iOS 17",
509
- "geoLocation": null,
510
- "securityScore": null,
511
- "isCurrentSession": false,
512
- "isTrulyActive": false,
513
- "minutesSinceActive": 1545
437
+ "minutesSinceActive": 2,
438
+ "isCurrentSession": true
514
439
  }
515
440
  ],
516
- "meta": {
517
- "count": 2,
518
- "active": 1
519
- }
520
- }
521
- ```
522
-
523
- ### Get Current Session
524
-
525
- Returns only the session associated with the current JWT token.
526
-
527
- ```bash
528
- GET /api/magic-sessionmanager/current-session
529
- Authorization: Bearer <JWT>
530
- ```
531
-
532
- **Response:**
533
- ```json
534
- {
535
- "data": {
536
- "id": "abc123xyz",
537
- "documentId": "abc123xyz",
538
- "sessionId": "sess_m5k2h_8a3b1c2d_f9e8d7c6",
539
- "ipAddress": "192.168.1.100",
540
- "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36...",
541
- "loginTime": "2026-01-02T10:30:00.000Z",
542
- "lastActive": "2026-01-02T13:45:00.000Z",
543
- "logoutTime": null,
544
- "isActive": true,
545
- "deviceType": "desktop",
546
- "browserName": "Chrome 143",
547
- "osName": "macOS 10.15.7",
548
- "geoLocation": null,
549
- "securityScore": null,
550
- "isCurrentSession": true,
551
- "isTrulyActive": true,
552
- "minutesSinceActive": 2
553
- }
554
- }
555
- ```
556
-
557
- ### Logout (Current Session)
558
-
559
- Terminates only the current session.
560
-
561
- ```bash
562
- POST /api/magic-sessionmanager/logout
563
- Authorization: Bearer <JWT>
564
- ```
565
-
566
- **Response:**
567
- ```json
568
- {
569
- "message": "Logged out successfully"
570
- }
571
- ```
572
-
573
- ### Logout All Devices
574
-
575
- Terminates ALL sessions for the authenticated user (logs out everywhere).
576
-
577
- ```bash
578
- POST /api/magic-sessionmanager/logout-all
579
- Authorization: Bearer <JWT>
580
- ```
581
-
582
- **Response:**
583
- ```json
584
- {
585
- "message": "Logged out from all devices successfully"
586
- }
587
- ```
588
-
589
- ### Terminate Specific Session
590
-
591
- Terminates a specific session (not the current one). Useful for "Log out other devices".
592
- Use the `id` / `documentId` value from the session response. The separate `sessionId` field is a tracking identifier stored on the session record.
593
-
594
- For a native-only row, use its `native_` value from `id`. Native-only rows may not have a `documentId` or Magic metadata.
595
-
596
- ```bash
597
- DELETE /api/magic-sessionmanager/my-sessions/:documentId
598
- Authorization: Bearer <JWT>
599
- ```
600
-
601
- **Response:**
602
- ```json
603
- {
604
- "message": "Session abc123xyz terminated successfully",
605
- "success": true
606
- }
607
- ```
608
-
609
- **Error (trying to terminate current session):**
610
- ```json
611
- {
612
- "error": {
613
- "status": 400,
614
- "message": "Cannot terminate current session. Use /logout instead."
615
- }
441
+ "meta": { "count": 1, "active": 1, "hasMore": false, "limit": 200 }
616
442
  }
617
443
  ```
618
444
 
619
445
  ---
620
446
 
621
- ## πŸ“‹ Admin-API Endpoints (For Admin Panel)
622
-
623
- These endpoints require admin authentication.
624
-
625
- ### Get All Sessions
626
-
627
- ```bash
628
- GET /magic-sessionmanager/sessions
629
- ```
630
-
631
- ### Get Active Sessions Only
632
-
633
- ```bash
634
- GET /magic-sessionmanager/sessions/active
635
- ```
636
-
637
- ### Force Terminate Session
447
+ ## Optional route policy: `session-required`
638
448
 
639
- ```bash
640
- POST /magic-sessionmanager/sessions/:sessionId/terminate
641
- ```
642
-
643
- ### Terminate All User Sessions
644
-
645
- ```bash
646
- POST /magic-sessionmanager/user/:userId/terminate-all
647
- ```
648
-
649
- ### Block/Unblock User
449
+ 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.
650
450
 
651
- ```bash
652
- POST /magic-sessionmanager/user/:userId/toggle-block
653
- ```
451
+ The policy is opt-in for an explicit, per-route check on your **own** routes. It follows the same Token check setting as the global check, so it cannot make a single route stricter than the rest.
654
452
 
655
- ### Clean Inactive Sessions
656
-
657
- ```bash
658
- POST /magic-sessionmanager/sessions/clean-inactive
659
- ```
660
-
661
- ---
453
+ ```js
454
+ // src/api/order/routes/order.js
455
+ const { factories } = require('@strapi/strapi');
662
456
 
663
- ## βš™οΈ Settings You Can Change
664
-
665
- **In `config/plugins.ts`:**
666
-
667
- ```typescript
668
- 'magic-sessionmanager': {
457
+ module.exports = factories.createCoreRouter('api::order.order', {
669
458
  config: {
670
- // How often to update "last seen" (in milliseconds)
671
- lastSeenRateLimit: 30000, // Default: 30 seconds
672
-
673
- // When to mark sessions inactive (in milliseconds)
674
- inactivityTimeout: 900000, // Default: 15 minutes
459
+ find: { policies: ['plugin::magic-sessionmanager.session-required'] },
460
+ findOne: { policies: ['plugin::magic-sessionmanager.session-required'] },
675
461
  },
676
- }
462
+ });
677
463
  ```
678
464
 
679
- **In Admin Panel (Settings Tab):**
680
- - Email alerts on/off
681
- - Webhook URLs (Discord/Slack)
682
- - Countries to block/allow
683
- - VPN detection on/off
684
- - Generate encryption key
465
+ | Case | Strict token check | Relaxed token check |
466
+ | ------------------------------------------------------------------- | ------------------------------------- | ---------------------------------- |
467
+ | No authenticated user on the request (public route, API token) | allowed; the route's own auth decides | allowed |
468
+ | User cannot be resolved to a `documentId` | 401 | allowed |
469
+ | No `Authorization: Bearer` token | 401 | allowed |
470
+ | `jwtManagement: 'refresh'` and Strapi verified no native session id | 401 | allowed |
471
+ | A matching session row is open | allowed | allowed |
472
+ | The matching session row is ended | 401 "Session terminated" | 401 "Session terminated" |
473
+ | No session row matches | 401 | allowed, with a warning in the log |
474
+ | Settings or the session lookup fail | 401 | allowed |
685
475
 
686
476
  ---
687
477
 
688
- ## πŸ› Common Problems & Fixes
689
-
690
- ### I don't see the Sessions menu
691
-
692
- **Fix:**
693
- 1. Make sure plugin is in `config/plugins.ts`
694
- 2. Run `npm run build`
695
- 3. Restart Strapi
696
- 4. Refresh browser (Cmd+Shift+R)
478
+ ## Admin API and permissions
479
+
480
+ 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`.
481
+
482
+ | Method | Path | Admin UI action |
483
+ | -------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
484
+ | GET | `/sessions` | Sessions dashboard, widget, Analytics (latest 1,000; `meta.truncated` when more exist) |
485
+ | GET | `/sessions/active` | Open sessions only |
486
+ | GET | `/user/:userId/sessions` | Sessions panel |
487
+ | POST | `/sessions/:sessionId/terminate` | **End session** (reason `manual`; in refresh mode the Strapi session is revoked first; the record stays) |
488
+ | DELETE | `/sessions/:sessionId` | **Delete record** (record removed, token stays revoked; an open session also ends) |
489
+ | POST | `/sessions/clean-inactive` | **Delete ended sessions** (all users; open and idle sessions are not affected; does not run the idle check) |
490
+ | POST | `/user/:userId/terminate-all` | **End all sessions** (reason `manual`) |
491
+ | POST | `/user/:userId/toggle-block` | **Block user** / **Unblock user** |
492
+ | GET | `/users/stats` | Widget totals (`totalUsers`, `blockedUsers`) |
493
+ | GET | `/geolocation/:ipAddress` | **Look up location** |
494
+ | GET | `/geoip/status` | GeoIP database status |
495
+ | PUT | `/geoip/credentials` | Save or remove (`{ "clear": true }`) MaxMind credentials |
496
+ | POST | `/geoip/update` | Update database / Force download |
497
+ | GET, PUT | `/settings` | Configuration (PUT validates every field and returns `error.details.errors` on invalid input) |
498
+ | GET | `/license/status` | License page |
499
+ | POST | `/license/auto-create`, `/license/create`, `/license/ping`, `/license/store-key` | License service routes (no admin UI) |
500
+ | POST | `/sessions/:sessionId/simulate-timeout` | Development only; removed when `NODE_ENV` is `production` or `staging` |
501
+
502
+ **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.
503
+
504
+ 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).
697
505
 
698
- ### Sessions not being created
699
-
700
- **Fix:**
701
- 1. Check Strapi logs for errors
702
- 2. Make sure users are logging in (not already logged in)
703
- 3. Check database is working
506
+ ---
704
507
 
705
- ### 401 or 403 errors
508
+ ## Security and privacy
706
509
 
707
- **Fix:**
708
- - 401 = Not logged in (need to login as admin)
709
- - 403 = Not allowed (check you're admin, not regular user)
510
+ - **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:
710
511
 
711
- ### Database table "sessions" already exists
512
+ ```bash
513
+ node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
514
+ ```
712
515
 
713
- **Fix:**
714
- - This plugin uses `magic_sessions` table (not `sessions`)
715
- - If you see this error, another plugin is using that name
716
- - Our plugin automatically uses the correct name
516
+ - **Ownership.** Content API routes only return or end the caller's own sessions. A foreign session ID answers exactly like a missing one, so IDs cannot be probed.
517
+ - **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.
518
+ - **Password reset.** A successful password reset ends every older session of the user in both JWT modes.
519
+ - **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.
520
+ - **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.
521
+ - **Admin sessions** of Strapi administrators are out of scope.
717
522
 
718
523
  ---
719
524
 
720
- ## πŸ’‘ When To Use This Plugin
525
+ ## Troubleshooting
721
526
 
722
- **Perfect for:**
723
- - Multi-tenant apps (see which tenant users are online)
724
- - E-commerce (track customer sessions)
725
- - Collaboration tools (show who's currently working)
726
- - Security-critical apps (force-logout compromised accounts)
727
- - Compliance requirements (session audit logs)
527
+ | Problem | Fix |
528
+ | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
529
+ | 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". |
530
+ | No sessions appear | Only end-user sign-ins through Users & Permissions are recorded, not Strapi admin sign-ins. Check the Strapi log. |
531
+ | Startup fails with `SESSION_ENCRYPTION_KEY is required in production` | Set the variable and restart. |
532
+ | 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. |
533
+ | 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. |
534
+ | Location is always "β€”" | IP location lookup is off, the provider is `disabled`, or `local-mmdb` has no database. See Configuration β€Ί Location data. |
535
+ | 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". |
728
536
 
729
- **Not needed if:**
730
- - Single-user app
731
- - No need to see who's logged in
732
- - No security requirements
537
+ The plugin stores sessions in the `magic_sessions` table and revocations in its own revoked-token table.
733
538
 
734
539
  ---
735
540
 
736
- ## πŸ”§ How To Test It
737
-
738
- ### Quick Manual Test
739
-
740
- 1. **Login to your Strapi app** (frontend or admin)
741
- 2. **Go to Admin β†’ Sessions**
742
- 3. **You should see your session!**
743
- 4. **Click "Terminate" on your session**
744
- 5. **Try to use the app β†’ You're logged out!**
745
-
746
- ### With Postman
747
-
748
- **1. Login:**
749
- ```
750
- POST http://localhost:1337/api/auth/local
751
- Body: { "identifier": "user@test.com", "password": "pass123" }
752
- ```
541
+ ## Development and tests
753
542
 
754
- **2. Check session created:**
755
- ```
756
- GET http://localhost:1337/magic-sessionmanager/sessions
757
- ```
758
-
759
- **3. Logout:**
760
- ```
761
- POST http://localhost:1337/api/auth/logout
762
- Authorization: Bearer YOUR_JWT_TOKEN
543
+ ```bash
544
+ npm ci --legacy-peer-deps
545
+ npm test # node --test tests/*.test.js tests/*.test.mjs
546
+ npm run test:ts:front
547
+ npm run test:ts:back
548
+ npm run build
549
+ npm run verify
550
+ npm run verify:runtime
763
551
  ```
764
552
 
765
- **Done!**
766
-
767
- ---
768
-
769
- ## πŸ“¦ What Gets Installed
553
+ HTTP integration tests need Strapi host dependencies: set `SESSION_HTTP_STRAPI_NODE_MODULES` to the `node_modules` of a Strapi 5 host; without it they skip with a message.
770
554
 
771
- When you install this plugin, you get:
555
+ Quick manual check: sign in to your app as an end user (`POST /api/auth/local`), open Session Manager and find the session as **Active**, click **End session** and confirm, then call any Content API route with the same token: it returns 401 and the row shows **Ended Β· Ended manually**.
772
556
 
773
- - βœ… Dashboard to see all sessions
774
- - βœ… Session tracking (automatic)
775
- - βœ… Force logout buttons
776
- - βœ… Activity monitoring
777
- - βœ… Encryption (secure)
778
- - βœ… Multi-device support
779
-
780
- **All features are included for free:**
781
- - βœ… IP Geolocation
782
- - βœ… Threat detection
783
- - βœ… Auto-blocking
784
- - βœ… Email/webhook alerts
557
+ Releases use Conventional Commits and semantic-release on Node.js 22 with npm Trusted Publishing (GitHub OIDC).
785
558
 
786
559
  ---
787
560
 
788
- ## πŸ™‹ FAQ
789
-
790
- **Q: Do I need to change my Strapi code?**
791
- A: No! Just install and enable the plugin.
792
-
793
- **Q: Will this break my existing logins?**
794
- A: No! It just tracks them, doesn't change them.
561
+ ## Maintenance status
795
562
 
796
- **Q: Can users see each other's sessions?**
797
- A: No! Only admins can see all sessions. Users only see their own.
563
+ As of 2026-11-06:
798
564
 
799
- **Q: What if I uninstall the plugin?**
800
- A: Sessions will stop being tracked. Everything else works normally.
565
+ - **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).
566
+ - **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).
567
+ - **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.
568
+ - **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.
801
569
 
802
- **Q: Does it slow down my app?**
803
- A: No! It has smart rate-limiting to prevent database spam.
804
-
805
- **Q: Can I customize the dashboard?**
806
- A: Not yet, but it's planned for future versions!
570
+ Report bugs at https://github.com/Schero94/Magic-Sessionmanager/issues.
807
571
 
808
572
  ---
809
573
 
810
- ## πŸ“š Resources
574
+ ## Languages
811
575
 
812
- - **NPM:** https://www.npmjs.com/package/strapi-plugin-magic-sessionmanager
813
- - **GitHub:** https://github.com/Schero94/Magic-Sessionmanager
814
- - **Report Bugs:** https://github.com/Schero94/Magic-Sessionmanager/issues
576
+ The admin interface is available in English, German (formal "Sie"), French, Spanish and Portuguese, and follows the Strapi admin language. Dates use the admin locale.
815
577
 
816
578
  ---
817
579
 
818
- ## πŸ“„ License
819
-
820
- **MIT License** - Free to use for personal and commercial projects!
821
-
822
- **Copyright Β© 2025 Schero D.**
823
-
824
- ### Optional license-key activation
580
+ ## License
825
581
 
826
- The admin panel includes a License page where you can register an optional key. This is only used for install tracking and support context; it does not unlock or restrict any plugin feature.
827
-
828
- See [LICENSE](./LICENSE) for full terms.
829
-
830
- ---
831
-
832
- ## 🌐 Supported Languages
833
-
834
- The admin interface is available in **5 languages:**
835
-
836
- - πŸ‡¬πŸ‡§ **English** - Default
837
- - πŸ‡©πŸ‡ͺ **Deutsch** - German
838
- - πŸ‡ͺπŸ‡Έ **EspaΓ±ol** - Spanish
839
- - πŸ‡«πŸ‡· **FranΓ§ais** - French
840
- - πŸ‡΅πŸ‡Ή **PortuguΓͺs** - Portuguese
841
-
842
- Language automatically follows your Strapi admin interface setting.
843
-
844
- ---
582
+ MIT License. Copyright Β© 2025 Schero D. See [LICENSE](./LICENSE).
845
583
 
846
- **Made for Strapi v5**
584
+ **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.