diff --git a/.agents/skills/strapi-plugin-maintenance/SKILL.md b/.agents/skills/strapi-plugin-maintenance/SKILL.md index f972837..950e053 100644 --- a/.agents/skills/strapi-plugin-maintenance/SKILL.md +++ b/.agents/skills/strapi-plugin-maintenance/SKILL.md @@ -19,4 +19,4 @@ Keep Playwright CLI evidence private and value-free. Its accessibility snapshots Use spec-first development: define acceptance criteria and API response/error contracts before implementation. -Every behavior change starts with a written current-state and target-state analysis covering screens, controls, routes, roles, data, known gaps and non-goals. Define acceptance criteria and API response/error contracts before implementation, then add a failing regression test first. A primary task should take no more than four meaningful user interactions from the plugin entry page; exclude login and mandatory security confirmations, and measure and document any justified exception. Use the Strapi Design System, responsive layouts, keyboard accessibility and explicit loading, empty, success and error states. Enforce authentication, plugin permissions, validation and owner boundaries server-side. Keep API error contracts consistent within each Strapi surface and never return stack traces or internal details. Do not log secrets, tokens, cookies, request bodies, email, IP or stable user/session identifiers. Use fakes for providers and record unverified behavior accurately. Magic Session Manager remains limited to Users & Permissions end-user sessions; Strapi Admin sessions are outside scope. +Every behavior change starts with a written current-state and target-state analysis covering screens, controls, routes, roles, data, known gaps and non-goals. Define acceptance criteria and API response/error contracts before implementation, then add a failing regression test first. A primary task should take no more than four meaningful user interactions from the plugin entry page; exclude login and mandatory security confirmations, and measure and document any justified exception. Use the Strapi Design System, responsive layouts, keyboard accessibility and explicit loading, empty, success and error states. Enforce authentication, plugin permissions, validation and owner boundaries server-side. Keep API error contracts consistent within each Strapi surface and never return stack traces or internal details. Do not log secrets, tokens, cookies, request bodies, email, IP or stable user/session identifiers. Use fakes for providers and record unverified behavior accurately. Magic Session Manager tracks Users & Permissions end-user sessions. Since 4.14 it also shows Strapi admin panel sessions read-only from Strapi's own `admin::session` rows (origin `admin`) and signs admins out through `strapi.sessionManager('admin').invalidateRefreshToken`; never mix admin rows into end-user numbers, never store admin IPs or user agents, and keep the separate `admin-sessions.read` / `admin-sessions.revoke` actions. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b246473..6e3a75e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -121,3 +121,62 @@ jobs: MSM_TEST_PG_URL: postgres://strapi:strapi@localhost:5432/magic_sessionmanager_ci MSM_CONCURRENCY_REQUIRE: sqlite,postgres run: npm run test:concurrency + + admin-sessions: + name: Real Strapi HTTP suites (SQLite + PostgreSQL) + runs-on: ubuntu-latest + timeout-minutes: 20 + + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: strapi + POSTGRES_PASSWORD: strapi + POSTGRES_DB: magic_sessionmanager_http + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + cache: npm + + - name: Install dependencies + run: npm ci --legacy-peer-deps + + # The suites boot the Strapi version from this repository's devDependencies + # (no separate host app) and fail instead of skipping when it is missing. + - name: Admin panel sessions on SQLite + env: + SESSION_HTTP_REQUIRED: '1' + SESSION_HTTP_STRAPI_NODE_MODULES: ${{ github.workspace }}/node_modules + run: node --test tests/isolated-admin-sessions-http.test.js + + - name: Admin panel sessions on PostgreSQL + env: + SESSION_HTTP_REQUIRED: '1' + SESSION_HTTP_STRAPI_NODE_MODULES: ${{ github.workspace }}/node_modules + SESSION_HTTP_DB: postgres + MSM_TEST_PG_URL: postgres://strapi:strapi@localhost:5432/magic_sessionmanager_http + run: node --test tests/isolated-admin-sessions-http.test.js + + - name: Existing HTTP access suite (legacy and refresh mode) + env: + SESSION_HTTP_REQUIRED: '1' + SESSION_HTTP_STRAPI_NODE_MODULES: ${{ github.workspace }}/node_modules + run: | + node --test tests/isolated-http-access.test.js + SESSION_HTTP_MODE=refresh node --test tests/isolated-http-access.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e3f7513..3262c2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,28 @@ +## [Unreleased] + +Release type: minor (`feat`), no breaking change. Existing routes, responses, numbers, widgets, settings and Content API features are unchanged. No migration needed. + +### Added + +* **Admin panel sessions.** A new **Admin panel** view on the Session Manager page (`/admin/plugins/magic-sessionmanager/admin-panel`), next to the app-user dashboard, shows who can use the Strapi admin panel and who is signed in: every admin with roles, status (Signed in, Not signed in, Deactivated, Invited), last activity and the signed-in browsers (Strapi's device label, signed in, last active, latest end, "This browser", "Remember me"). Search, a sign-in status filter and pagination run on the server. All five languages. +* **Sign admins out.** **Sign out** (one browser) and **Sign out everywhere**, each confirmed. Strapi 5.62 checks the admin session on every admin request, so the admin is signed out on their next click and lands on the login page; there is no waiting for the access token to expire. The plugin deletes every Strapi session record of the browser, so older access tokens of rotated records stop working too. Signing yourself out of the current browser shows a warning. **Manage in Settings** links to Strapi's Settings › Users to deactivate an account. +* Admin routes `GET /magic-sessionmanager/admin-sessions/admins`, `GET /magic-sessionmanager/admin-sessions/admins/:adminId/sessions`, `POST /magic-sessionmanager/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out` and `POST /magic-sessionmanager/admin-sessions/admins/:adminId/sign-out-everywhere` (contracts in the README). +* RBAC actions `plugin::magic-sessionmanager.admin-sessions.read` ("Read admin panel sessions") and `plugin::magic-sessionmanager.admin-sessions.revoke` ("Sign out admins"), granted to Super Admin only by default. + +### Security + +* Sign-outs need a signed-in administrator (admin API tokens get 403), are limited to 10 per minute per admin, and write one info log line with admin ids and counts only (`[magic-sessionmanager] Admin sign-out: actor=… target=… scope=one|all ended=…`), plus the Strapi event `magic-sessionmanager.admin-sessions.signed-out`. +* An admin without the Super Admin role cannot sign out a Super Admin (403 `super-admin-protected`), so the last active Super Admin can never be signed out by someone else. +* A session id that is not a live session of the given admin answers 404, like an unknown id. Responses never contain tokens, device ids or password fields. The plugin stores nothing about admins; Strapi records no IP address for admin sessions. + +### Changed + +* Admin session rows (`origin = 'admin'`) stay out of every app-user number; regression tests now cover the dashboard statistics, the untracked-session count and the widget totals with admin sessions present. + +### Tests + +* Real-HTTP suite `tests/isolated-admin-sessions-http.test.js` on SQLite and PostgreSQL: admins sign in through `POST /admin/login`; listing, sign-out of one browser and everywhere, self sign-out, Super Admin guard, RBAC denials, rate limit, rejected next request and refresh. New CI job runs it, plus the existing HTTP access suite in both JWT modes, against the Strapi 5.62 devDependencies (`@strapi/plugin-users-permissions` is now a devDependency). + ## [4.13.1](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.13.0...v4.13.1) (2026-11-17) diff --git a/README.md b/README.md index 94de78d..530762a 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **See who is signed in to your Strapi 5 app, end any session in one click, and stop password guessing before it reaches your users.** -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. +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. A separate **Admin panel** view shows who is signed in to the Strapi admin panel itself and signs an admin out of one browser or everywhere. 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. @@ -66,6 +66,7 @@ Live docs: [https://schero94.github.io/Magic-Sessionmanager/](https://schero94.g | Location | IP location from a local MaxMind GeoLite2 database (no third party in the sign-in path) or from ipapi.co, or turned off. | | Alerts | Security emails to the user through Strapi's Email plugin and sign-in notifications to Discord or Slack. | | Admin integration | A Sessions panel next to each user in the Content Manager and an Online users widget on the Strapi homepage. | +| Admin panel sessions | Who can use the Strapi admin panel, who is signed in, on which browser and since when. Sign an admin out of one browser or everywhere; it takes effect on their next click. | | Native Strapi sessions | Works with `jwtManagement: 'refresh'` (Strapi's own sessions and refresh tokens) and with `'legacy-support'`. | | Several processes | Lockout, rate limits, jobs and settings stay consistent across pm2 workers and Railway replicas that share one database. | | Privacy | Stored tokens are encrypted (AES-256-GCM) and never returned. Retention deletes old history automatically. No telemetry. | @@ -99,7 +100,7 @@ Yarn and pnpm work the same way (`yarn add strapi-plugin-magic-sessionmanager`, ## Screenshots -All screenshots use synthetic data: users `*.example.test`, IP addresses from the documentation range `203.0.113.0/24`, Strapi 5.61. The [full gallery](https://schero94.github.io/Magic-Sessionmanager/#screenshots) on the project site also shows dark mode, every settings tab, the untracked sign-in dialogs and more mobile views. +All screenshots use synthetic data: users `*.example.test`, IP addresses from the documentation range `203.0.113.0/24`, Strapi 5.61. The [full gallery](https://schero94.github.io/Magic-Sessionmanager/#screenshots) on the project site also shows Analytics, dark mode, every settings tab, the untracked sign-in dialogs and more mobile views. ### Session details @@ -117,14 +118,16 @@ All screenshots use synthetic data: users `*.example.test`, IP addresses from th ![Configuration page, Sessions tab, with Session lifetime and Token check cards](https://schero94.github.io/Magic-Sessionmanager/img/settings1.webp) -### Analytics - -![Analytics page with four KPIs, Devices and Browsers bar cards and the average session length](https://schero94.github.io/Magic-Sessionmanager/img/analytics.webp) - ### Untracked Strapi sign-ins (refresh mode) ![Neutral notice: 37 older Strapi sign-ins are not tracked, with Why? and End these sessions](https://schero94.github.io/Magic-Sessionmanager/img/untracked-notice-neutral.webp) +### Admin panel sessions + +Strapi 5.62, synthetic admins `*.example.test`. The [gallery](https://schero94.github.io/Magic-Sessionmanager/#screenshots) also shows the sessions dialog, the sign-out confirmation, what the signed-out admin sees, dark mode and the phone layout. + +![Admin panel sessions: view switch App users / Admin panel, cards Signed-in admins, Not signed in and All admins, an explanation of how signing out works, search, a sign-in status filter and a table of admins with roles, status and last activity](https://schero94.github.io/Magic-Sessionmanager/img/admin-panel.webp) + ### Mobile (390 px) Sessions dashboard at 390 px: the table becomes a card list with Details, End session and More buttons @@ -166,14 +169,15 @@ All screenshots use synthetic data: users `*.example.test`, IP addresses from th ## Screens -| Where | Name | Answers | -| ------------------------------- | ------------------------------------------- | --------------------------------------------------------- | -| Main menu | **Session Manager** (page title "Sessions") | Which sessions exist, and which need action? | -| Dialog on the dashboard | **Session details** | What is this session, and why is it in this state? | -| Content Manager, User edit view | **Sessions** panel | What access does this user have, and how do I cut it off? | -| Strapi homepage | **Online users** widget | Who is online right now? | -| Settings › Session Manager | **Configuration** | How should sessions and sign-ins behave? | -| Settings › Session Manager | **Analytics** | How are sessions used over time and by device? | +| Where | Name | Answers | +| ------------------------------- | ------------------------------------------- | -------------------------------------------------------------------- | +| Main menu | **Session Manager** (page title "Sessions") | Which sessions exist, and which need action? | +| Dialog on the dashboard | **Session details** | What is this session, and why is it in this state? | +| Content Manager, User edit view | **Sessions** panel | What access does this user have, and how do I cut it off? | +| Strapi homepage | **Online users** widget | Who is online right now? | +| Session Manager › Admin panel | **Admin panel sessions** | Who is signed in to this admin panel, and how do I sign someone out? | +| Settings › Session Manager | **Configuration** | How should sessions and sign-ins behave? | +| Settings › Session Manager | **Analytics** | How are sessions used over time and by device? | ### Sessions dashboard @@ -187,6 +191,19 @@ All screenshots use synthetic data: users `*.example.test`, IP addresses from th - In `refresh` mode, a notice above the cards counts **untracked Strapi sign-ins**: refresh tokens Strapi still accepts that have no session details from this plugin. They are not in the list and are not active or online sessions; each user's sessions panel lists them. The notice is neutral when all of them were created before this plugin started tracking, and a warning ("Possible tracking gap") when any was created afterwards. **Why?** opens a count-only summary; **End these sessions** ends them after a confirmation. See [Untracked Strapi sessions](#untracked-strapi-sessions). - Below the large breakpoint the IP address and Signed in columns are hidden; below the medium breakpoint the table becomes a card list. +### Admin panel sessions + +Open **Session Manager** and switch to **Admin panel** (the switch below the title; shown only to roles with "Read admin panel sessions"). The view lists Strapi admin accounts, not your app's users, and none of its numbers appear on the App users dashboard, the widget or Analytics. + +- **Cards:** **Signed-in admins** (with the number of signed-in browsers), **Not signed in** (including deactivated and invited accounts) and **All admins** (with the number of active accounts). Each card filters the list. +- **How signing out works:** signing out takes effect on the admin's next click, because Strapi checks the admin session on every admin request. The admin can sign in again with their password; to stop that, deactivate the account in Settings › Users (**Manage admins** in the header). The card also shows the idle timeouts your host runs with (`admin.auth.sessions`). +- **Search and filter:** name or email; **All admins**, **Signed in**, **Not signed in**. Search, filter and paging run on the server and live in the URL. +- **Table** (cards below 768 px): Admin (with a **You** badge), Roles, Status (**Signed in** · "{n} sessions", **Not signed in**, **Deactivated**, **Invited**), Last active, and the actions **View sessions** and **Sign out everywhere**. +- **Sessions of an admin:** one entry per signed-in browser with Strapi's device label (for example "Chrome on macOS"), **This browser**, **Remember me**, Signed in, Last active and **Ends at the latest**. **Sign out** ends that browser, **Sign out everywhere** ends all of them, **Manage in Settings** opens the admin in Settings › Users. +- **Confirmation:** every sign-out asks first. Signing yourself out of the browser you are using shows a warning; you are then taken to the login page. +- **Protection:** an admin without the Super Admin role cannot sign out a Super Admin, so the last active Super Admin can never be signed out by someone else. The view explains this instead of showing a disabled button. +- Strapi stores no IP address and no full user agent for admin sessions, so the view shows none. "Last active" is the last time the browser renewed its access token (Strapi's own signal), not every click. + ### Session details - A state sentence that explains why the session is in its state, for example "Ended {time} · Ended manually." @@ -231,16 +248,17 @@ Two links: **Configuration** and **Analytics**. ## Compatibility -| Item | Supported | -| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Strapi | 5 (`@strapi/strapi` peer range `^5.0.0`). Acceptance host: Strapi 5.62.0. | -| Node.js | `^22.22.2 \|\| >=24.15.0` (`engines.node`) | -| Users & Permissions | `jwtManagement: 'refresh'` and `'legacy-support'` | -| Homepage widget | Strapi 5.13 and later (older versions have no widgets API; the rest works) | -| 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. | -| 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. | -| Package managers | npm, Yarn 1 and pnpm. Installing into a fresh Strapi 5.61 app prints no warning about this plugin. | -| Databases | PostgreSQL, MySQL, SQLite (several processes need PostgreSQL or MySQL, see [Running several instances](#running-several-instances-railway-replicas-pm2-cluster)). | +| Item | Supported | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Strapi | 5 (`@strapi/strapi` peer range `^5.0.0`). Acceptance host: Strapi 5.62.0. | +| Node.js | `^22.22.2 \|\| >=24.15.0` (`engines.node`) | +| Users & Permissions | `jwtManagement: 'refresh'` and `'legacy-support'` | +| Homepage widget | Strapi 5.13 and later (older versions have no widgets API; the rest works) | +| Admin panel sessions | Strapi 5 with Strapi's session manager (`strapi.sessionManager`, admin origin); tested with 5.62.0. Without it the view says it is not available and the sign-out routes return 503. | +| 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. | +| 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. | +| Package managers | npm, Yarn 1 and pnpm. Installing into a fresh Strapi 5.61 app prints no warning about this plugin. | +| Databases | PostgreSQL, MySQL, SQLite (several processes need PostgreSQL or MySQL, see [Running several instances](#running-several-instances-railway-replicas-pm2-cluster)). | --- @@ -610,30 +628,41 @@ module.exports = factories.createCoreRouter('api::order.order', { ## Admin API and permissions -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`. - -| Method | Path | Admin UI action | -| -------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -| GET | `/sessions` | Sessions dashboard: `?page=&pageSize=` (1-100), `status`, `reason`, `search`, `sort`; see below | -| GET | `/sessions/active` | Active sessions only; same paging parameters | -| GET | `/sessions/stats` | Dashboard cards and widget: counts only, cached 5 seconds per process | -| GET | `/sessions/native-only/summary` | **Why?** on the untracked-session notice: counts only, no query parameters (400 otherwise) | -| POST | `/sessions/native-only/end` | **End these sessions**: empty body; signed-in administrators only (admin API tokens get 403); 5 per minute | -| GET | `/sessions/analytics` | Analytics page: counts and grouped counts over every session, cached 30 seconds | -| GET | `/sessions/export` | Export batches of up to 1,000 rows, newest first; follow `meta.nextCursor` | -| GET | `/user/:userId/sessions` | Sessions panel | -| POST | `/sessions/:sessionId/terminate` | **End session** (reason `manual`; in refresh mode the Strapi session is revoked first; the record stays) | -| DELETE | `/sessions/:sessionId` | **Delete record** (record removed, token stays revoked; an open session also ends) | -| POST | `/sessions/clean-inactive` | **Delete ended sessions** (all users; open and idle sessions are not affected; does not run the idle check) | -| POST | `/user/:userId/terminate-all` | **End all sessions** (reason `manual`) | -| POST | `/user/:userId/toggle-block` | **Block user** / **Unblock user** | -| GET | `/users/stats` | Widget totals (`totalUsers`, `blockedUsers`) | -| GET | `/geolocation/:ipAddress` | **Look up location** | -| GET | `/geoip/status` | GeoIP database status | -| PUT | `/geoip/credentials` | Save or remove (`{ "clear": true }`) MaxMind credentials | -| POST | `/geoip/update` | Update database / Force download | -| GET, PUT | `/settings` | Configuration (PUT validates every field and returns `error.details.errors` on invalid input) | -| POST | `/sessions/:sessionId/simulate-timeout` | Development only; removed when `NODE_ENV` is `production` or `staging` | +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` of a Users & Permissions session. + +The **Admin panel sessions** routes need two more permissions, which only the Super Admin role has by default (Settings › Administration Panel › Roles › Plugins › Session Manager › Admin panel): + +| Permission | Name in the role editor | Allows | +| ---------------------------------------------------- | ------------------------- | ---------------------------------------------------------- | +| `plugin::magic-sessionmanager.admin-sessions.read` | Read admin panel sessions | The Admin panel view and its two GET routes | +| `plugin::magic-sessionmanager.admin-sessions.revoke` | Sign out admins | **Sign out** and **Sign out everywhere** (also needs read) | + +| Method | Path | Admin UI action | +| -------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| GET | `/sessions` | Sessions dashboard: `?page=&pageSize=` (1-100), `status`, `reason`, `search`, `sort`; see below | +| GET | `/sessions/active` | Active sessions only; same paging parameters | +| GET | `/sessions/stats` | Dashboard cards and widget: counts only, cached 5 seconds per process | +| GET | `/sessions/native-only/summary` | **Why?** on the untracked-session notice: counts only, no query parameters (400 otherwise) | +| POST | `/sessions/native-only/end` | **End these sessions**: empty body; signed-in administrators only (admin API tokens get 403); 5 per minute | +| GET | `/sessions/analytics` | Analytics page: counts and grouped counts over every session, cached 30 seconds | +| GET | `/sessions/export` | Export batches of up to 1,000 rows, newest first; follow `meta.nextCursor` | +| GET | `/user/:userId/sessions` | Sessions panel | +| POST | `/sessions/:sessionId/terminate` | **End session** (reason `manual`; in refresh mode the Strapi session is revoked first; the record stays) | +| DELETE | `/sessions/:sessionId` | **Delete record** (record removed, token stays revoked; an open session also ends) | +| POST | `/sessions/clean-inactive` | **Delete ended sessions** (all users; open and idle sessions are not affected; does not run the idle check) | +| POST | `/user/:userId/terminate-all` | **End all sessions** (reason `manual`) | +| POST | `/user/:userId/toggle-block` | **Block user** / **Unblock user** | +| GET | `/users/stats` | Widget totals (`totalUsers`, `blockedUsers`) | +| GET | `/geolocation/:ipAddress` | **Look up location** | +| GET | `/geoip/status` | GeoIP database status | +| PUT | `/geoip/credentials` | Save or remove (`{ "clear": true }`) MaxMind credentials | +| POST | `/geoip/update` | Update database / Force download | +| GET, PUT | `/settings` | Configuration (PUT validates every field and returns `error.details.errors` on invalid input) | +| POST | `/sessions/:sessionId/simulate-timeout` | Development only; removed when `NODE_ENV` is `production` or `staging` | +| GET | `/admin-sessions/admins` | Admin panel view: `?page=&pageSize=` (1-100), `search` (up to 100 characters, name or email), `filter` (`all`, `signed-in`, `not-signed-in`); needs `admin-sessions.read` | +| GET | `/admin-sessions/admins/:adminId/sessions` | **View sessions**: one entry per signed-in browser; needs `admin-sessions.read` | +| POST | `/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out` | **Sign out** one browser; needs `admin-sessions.revoke`; signed-in administrators only; 10 per minute | +| POST | `/admin-sessions/admins/:adminId/sign-out-everywhere` | **Sign out everywhere**; needs `admin-sessions.revoke`; signed-in administrators only; 10 per minute | **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. @@ -643,6 +672,10 @@ The list, statistics, analytics, export, untracked-session summary and `/users/s **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. +**Admin panel sessions.** `GET /admin-sessions/admins` returns `{ data: [{ id, name, email, roles: [{ name, superAdmin }], account, self, sessionCount, lastActiveAt, canSignOut, protectedReason }], meta: { supported, pagination, stats: { signedInAdmins, activeSessions, activeAccounts, totalAdmins }, policy, truncated } }`. `account` is `active`, `deactivated` or `invited`. `GET …/sessions` returns `{ data: [{ id, device, signedInAt, lastActiveAt, endsAt, rememberMe, current }], meta: { admin, policy } }`; `id` is the Strapi session id of the browser's newest session record (32 hexadecimal characters). No token, refresh token, device id or password field is ever returned. Both sign-out routes return `{ data: { ended, signedOutSelf } }`: `signedOutSelf` is `true` when the browser that sent the request was signed out. Answers: 404 for an unknown admin, and for a session id that is not a live session of that admin (no probing of other admins' sessions); 403 with `error.details.reason` `super-admin-protected` when an admin without the Super Admin role tries to sign out a Super Admin, or `browser-session-required` for admin API tokens; 429 after 10 sign-outs per minute per admin; 503 when the Strapi version has no session manager (`meta.supported: false` on the GET routes). Each sign-out writes one log line, `[magic-sessionmanager] Admin sign-out: actor= target= scope=one|all ended=`, at info level (no email, session id or token), and emits the Strapi event `magic-sessionmanager.admin-sessions.signed-out` with the same fields. + +**How a sign-out works (Strapi 5.62).** The plugin deletes Strapi's own session records of that browser (`strapi.sessionManager('admin').invalidateRefreshToken(adminId, deviceId)`, the same call Strapi's logout makes) or of every browser (`invalidateRefreshToken(adminId)`). Strapi's admin authentication checks the session record on every admin request (`isSessionActive`), so the admin's next request returns 401 and the admin panel cannot renew its token: it shows the login page. There is no waiting period for the 30-minute access token (`accessTokenLifespan`). The plugin deletes every record of the browser, not only the newest one: an older access token belongs to an older, rotated record, and deleting just the newest record (`revokeSessionById`) would leave that token working until it expires. The integration suite proves both. Admin API tokens (Settings › Admin tokens) are separate from sessions and are not affected. + 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`. --- @@ -832,7 +865,7 @@ The plugin sits in the request path of every authenticated Content API call, so - **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. - **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. - **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. -- **Admin sessions** of Strapi administrators are out of scope. +- **Admin panel sessions.** The Admin panel view reads Strapi's own `admin::session` records (origin `admin`) and stores nothing of its own: no IP address, user agent or sign-in history. Only Super Admin can see or sign out admins until another role is granted `admin-sessions.read` / `admin-sessions.revoke`; a delegated role cannot sign out a Super Admin. Sign-outs need a signed-in administrator (not an admin API token), are rate limited and logged with admin ids and counts only. --- @@ -841,7 +874,8 @@ The plugin sits in the request path of every authenticated Content API call, so | Problem | Fix | | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 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". | -| No sessions appear | Only end-user sign-ins through Users & Permissions are recorded, not Strapi admin sign-ins. Check the Strapi log. | +| No **Admin panel** switch on the Session Manager page | Your role needs "Read admin panel sessions" (Settings › Roles › Plugins › Session Manager). Super Admin has it by default. | +| No sessions appear | Only end-user sign-ins through Users & Permissions are recorded on this dashboard; Strapi admin sign-ins are under **Admin panel**. Check the Strapi log. | | Startup fails with `SESSION_ENCRYPTION_KEY is required in production` | Set the variable and restart. | | 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. | | 429 on sign-in | Temporary IP lockout. Wait 15 minutes or raise `maxFailedLogins`. Behind a proxy, turn on Trust proxy headers so the lockout targets the real client. With `Retry-After: 1`: more sign-ins from one address were running at once than `maxFailedLogins`; retry after a second. | @@ -856,7 +890,10 @@ The plugin stores sessions in the `magic_sessions` table and revocations in its ## FAQ **Does it manage Strapi admin accounts?** -No. It manages end users of Users & Permissions (`plugin::users-permissions.user`). Strapi administrator sessions are out of scope. +It shows who is signed in to the Strapi admin panel and signs admins out (**Admin panel** view). It does not create, edit or deactivate admin accounts; that stays in Strapi's Settings › Users. Everything else in the plugin is about end users of Users & Permissions (`plugin::users-permissions.user`). + +**When does signing out an admin take effect?** +On the admin's next request, usually their next click: Strapi 5.62 checks the session record on every admin request. They can sign in again with their password unless you deactivate the account in Settings › Users. **Do I need a license key, account or activation?** 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. @@ -919,7 +956,14 @@ npm run verify npm run verify:runtime ``` -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. +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. This repository's own `node_modules` works (its devDependencies include Strapi 5.62 and Users & Permissions), which is what CI uses: + +```bash +SESSION_HTTP_REQUIRED=1 SESSION_HTTP_STRAPI_NODE_MODULES=$PWD/node_modules node --test tests/isolated-admin-sessions-http.test.js +# PostgreSQL: add SESSION_HTTP_DB=postgres MSM_TEST_PG_URL=postgres://user:pass@127.0.0.1:5432/db +``` + +The admin panel suite signs synthetic admins in through `POST /admin/login` and checks listing, signing out one browser and everywhere, self sign-out, the Super Admin guard, RBAC denials, the rate limit, that the next request and the refresh are rejected, and that admin sessions never reach the app-user numbers. 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**. diff --git a/admin/src/components/SessionViewNav.jsx b/admin/src/components/SessionViewNav.jsx new file mode 100644 index 0000000..f416989 --- /dev/null +++ b/admin/src/components/SessionViewNav.jsx @@ -0,0 +1,92 @@ +import { useIntl } from 'react-intl'; +import { NavLink } from 'react-router-dom'; +import { Flex, Typography } from '@strapi/design-system'; +import { useRBAC } from '@strapi/strapi/admin'; +import styled from 'styled-components'; +import pluginId from '../pluginId'; +import pluginPermissions from '../permissions'; +import { getTranslation } from '../utils/getTranslation'; + +/** Admin paths of the two session views (relative to the admin root). */ +export const SESSION_VIEW_PATHS = Object.freeze({ + users: `/plugins/${pluginId}`, + admins: `/plugins/${pluginId}/admin-panel`, +}); + +/** + * One view link, drawn like a DS tab: neutral text, the current view in + * primary with a bottom bar. The bar is a 2 px border inside the element, so + * the row height does not change between states. Touch targets are at least + * 32 px tall at every width (WCAG 2.5.8 and the plugin's mobile rule). + */ +const ViewLink = styled(NavLink)` + display: inline-flex; + align-items: center; + min-height: 4rem; + padding: 0 ${({ theme }) => theme.spaces[4]}; + border-bottom: 2px solid transparent; + color: ${({ theme }) => theme.colors.neutral600}; + text-decoration: none; + white-space: nowrap; + + &:hover { + color: ${({ theme }) => theme.colors.neutral800}; + } + + &[aria-current='page'] { + color: ${({ theme }) => theme.colors.primary700}; + border-bottom-color: ${({ theme }) => theme.colors.primary600}; + } + + &:focus-visible { + outline: 2px solid ${({ theme }) => theme.colors.primary600}; + outline-offset: -2px; + } +`; + +/** Navigation landmark with a hairline under both links. */ +const ViewNav = styled.nav` + border-bottom: 1px solid ${({ theme }) => theme.colors.neutral150}; + min-width: 0; +`; + +/** + * Switch between the app-user sessions and the Strapi admin panel sessions. + * A navigation landmark with two links (not ARIA tabs: each view is its own + * route). It renders nothing for admins who may not read admin panel + * sessions, so their dashboard looks exactly as before; hiding it is UX + * only, the server checks every route. + * + * @param {object} props + * @param {'users'|'admins'} props.current The view on screen. + * @returns {import('react').ReactElement|null} View switch, or null. + */ +const SessionViewNav = ({ current }) => { + const { formatMessage } = useIntl(); + const t = (id, defaultMessage) => formatMessage({ id: getTranslation(id), defaultMessage }); + const { + allowedActions: { canRead }, + isLoading, + } = useRBAC(pluginPermissions.adminSessionsRead); + + if (isLoading || (!canRead && current !== 'admins')) return null; + + const link = (view, label) => ( + + + {label} + + + ); + + return ( + + + {link('users', t('views.users', 'App users'))} + {link('admins', t('views.admins', 'Admin panel'))} + + + ); +}; + +export default SessionViewNav; diff --git a/admin/src/pages/AdminPanel/AdminList.jsx b/admin/src/pages/AdminPanel/AdminList.jsx new file mode 100644 index 0000000..e3babbc --- /dev/null +++ b/admin/src/pages/AdminPanel/AdminList.jsx @@ -0,0 +1,309 @@ +import { useIntl } from 'react-intl'; +import { + Badge, + Box, + Button, + Flex, + IconButton, + IconButtonGroup, + Table, + Tbody, + Td, + Th, + Thead, + Tr, + Typography, + VisuallyHidden, +} from '@strapi/design-system'; +import { Eye, SignOut } from '@strapi/icons'; +import { getTranslation } from '../../utils/getTranslation'; + +/** + * "You" and "This browser" badges. The DS primary variant measured 2.43:1 in + * the dark theme, so the primary surface keeps neutral800 text (high contrast + * in both themes, like the Idle badge). + */ +export const HIGHLIGHT_BADGE = { backgroundColor: 'primary100', textColor: 'neutral800' }; +import { getBadgeColors } from '../../components/ui/StatusBadge'; +import { LastActive } from '../Dashboard/SessionTable'; +import { getAdminStatusPresentation } from './adminPanelModel.mjs'; + +/** Cells that share the remaining width and cut long values instead of scrolling. */ +const SHRINKING_ADMIN_CELL = { maxWidth: 0, width: '34%' }; +const SHRINKING_ROLES_CELL = { maxWidth: 0, width: '22%' }; + +/** + * Translation helper bound to the plugin prefix. + * + * @returns {(id: string, defaultMessage: string, values?: object) => string} + */ +const useT = () => { + const { formatMessage } = useIntl(); + return (id, defaultMessage, values) => + formatMessage({ id: getTranslation(id), defaultMessage }, values); +}; + +/** + * Name, "You" badge and e-mail of an admin. Long values are cut with an + * ellipsis; the full value is in the title attribute and in the sessions + * dialog. + * + * @param {{admin: object}} props Admin row. + * @returns {import('react').ReactElement} Identity block. + */ +export const AdminIdentity = ({ admin }) => { + const t = useT(); + return ( + + + + {admin.name} + + {admin.self ? ( + + {t('adminPanel.you', 'You')} + + ) : null} + + + {admin.email} + + + ); +}; + +/** + * Role names, comma separated. "Super Admin" is the role name Strapi stores. + * + * @param {{admin: object}} props Admin row. + * @returns {import('react').ReactElement} Roles line. + */ +export const AdminRoles = ({ admin }) => { + const t = useT(); + const names = (admin.roles || []).map((role) => role.name).filter(Boolean); + const text = names.length ? names.join(', ') : t('adminPanel.roles.none', 'No role'); + return ( + + {text} + + ); +}; + +/** + * State badge plus a neutral second line ("2 sessions", "No open session"). + * + * @param {{admin: object}} props Admin row. + * @returns {import('react').ReactElement} Status block. + */ +export const AdminStatus = ({ admin }) => { + const t = useT(); + const status = getAdminStatusPresentation(admin); + return ( + + + {t(status.label.messageId, status.label.defaultMessage)} + + + {t(status.detail.messageId, status.detail.defaultMessage, status.detail.values)} + + + ); +}; + +/** + * Admins as a table (from the DS medium breakpoint). Row actions are icon + * buttons with contextual names; "Sign out everywhere" appears only when the + * server says it is allowed and the admin has a session. + * + * @param {object} props + * @param {object[]} props.admins Admin rows of the page. + * @param {string} props.labelledBy Id of the caption. + * @param {boolean} props.canRevoke Caller may sign admins out. + * @param {(admin: object, trigger: HTMLElement|null) => void} props.onView Opens the sessions dialog. + * @param {(admin: object, trigger: HTMLElement|null) => void} props.onSignOutEverywhere Asks to sign out everywhere. + * @param {boolean} [props.busy] A refresh is running. + * @returns {import('react').ReactElement} Table. + */ +export const AdminTable = ({ + admins, + labelledBy, + canRevoke, + onView, + onSignOutEverywhere, + busy, +}) => { + const t = useT(); + return ( + + + + + + + + + + + + + {admins.map((admin) => ( + + + + + + + + ))} + +
+ + {t('adminPanel.table.admin', 'Admin')} + + + + {t('adminPanel.table.roles', 'Roles')} + + + + {t('adminPanel.table.status', 'Status')} + + + + {t('adminPanel.table.lastActive', 'Last active')} + + + {t('adminPanel.table.actions', 'Actions')} +
+ + + + + + + + + + + onView(admin, event.currentTarget)} + > + + + {canRevoke && admin.canSignOut ? ( + onSignOutEverywhere(admin, event.currentTarget)} + > + + + ) : null} + + +
+
+ ); +}; + +/** + * Admins as cards (below the DS medium breakpoint): the same fields as the + * table, with text buttons that fill the card width. + * + * @param {object} props Same as AdminTable. + * @param {object[]} props.admins Admin rows. + * @param {string} props.labelledBy Id of the caption. + * @param {boolean} props.canRevoke Caller may sign admins out. + * @param {(admin: object, trigger: HTMLElement|null) => void} props.onView Opens the sessions dialog. + * @param {(admin: object, trigger: HTMLElement|null) => void} props.onSignOutEverywhere Asks to sign out everywhere. + * @returns {import('react').ReactElement} Card list. + */ +export const AdminCardList = ({ admins, labelledBy, canRevoke, onView, onSignOutEverywhere }) => { + const t = useT(); + return ( + + {admins.map((admin) => ( + + + + + + + + {t('adminPanel.table.lastActive', 'Last active')} + + + + + + + + {canRevoke && admin.canSignOut ? ( + + ) : null} + + + + ))} + + ); +}; diff --git a/admin/src/pages/AdminPanel/AdminSessionsModal.jsx b/admin/src/pages/AdminPanel/AdminSessionsModal.jsx new file mode 100644 index 0000000..07dd425 --- /dev/null +++ b/admin/src/pages/AdminPanel/AdminSessionsModal.jsx @@ -0,0 +1,293 @@ +import { useIntl } from 'react-intl'; +import { Link } from 'react-router-dom'; +import { + Badge, + Box, + Button, + Flex, + LinkButton, + Loader, + Modal, + Typography, +} from '@strapi/design-system'; +import { SignOut } from '@strapi/icons'; +import { getTranslation } from '../../utils/getTranslation'; +import { useSessionFormatters } from '../../utils/useSessionFormatters'; +import { PropertyList } from '../../components/ui'; +import Alert from '../../components/PersistentAlert'; +import { LastActive } from '../Dashboard/SessionTable'; +import { AdminRoles, AdminStatus, HIGHLIGHT_BADGE } from './AdminList'; + +/** + * Translation helper bound to the plugin prefix. + * + * @returns {(id: string, defaultMessage: string, values?: object) => string} + */ +const useT = () => { + const { formatMessage } = useIntl(); + return (id, defaultMessage, values) => + formatMessage({ id: getTranslation(id), defaultMessage }, values); +}; + +/** + * Absolute date in the admin locale, as a machine-readable time element. + * + * @param {{value: string|null}} props ISO date. + * @returns {import('react').ReactElement|null} Date, or null when missing. + */ +const DateValue = ({ value }) => { + const { formatDate } = useSessionFormatters(); + if (!value) return null; + return ( + + {formatDate(value)} + + ); +}; + +/** + * One signed-in browser: device label (Strapi's own "Chrome on macOS"), + * "This browser" and "Remember me" badges, sign-in, last activity and the + * latest end, plus "Sign out". + * + * @param {object} props + * @param {object} props.session Session row from the API. + * @param {object} props.admin Admin of the dialog. + * @param {boolean} props.canSignOut Button is shown. + * @param {(session: object, trigger: HTMLElement|null) => void} props.onSignOut Asks for confirmation. + * @returns {import('react').ReactElement} Session card. + */ +const SessionCard = ({ session, admin, canSignOut, onSignOut }) => { + const t = useT(); + const device = session.device || t('adminPanel.session.unknownDevice', 'Unknown browser'); + return ( + + + + + + {device} + + {session.current ? ( + {t('adminPanel.session.current', 'This browser')} + ) : null} + {session.rememberMe ? ( + {t('adminPanel.session.rememberMe', 'Remember me')} + ) : null} + + {canSignOut ? ( + + ) : null} + + : undefined, + }, + { + id: 'lastActive', + label: t('adminPanel.session.lastActiveAt', 'Last active'), + value: session.lastActiveAt, + render: session.lastActiveAt ? ( + + ) : undefined, + }, + { + id: 'endsAt', + label: t('adminPanel.session.endsAt', 'Ends at the latest'), + value: session.endsAt, + render: session.endsAt ? : undefined, + fullWidth: true, + }, + ]} + /> + + + ); +}; + +/** + * Sessions of one admin. The body explains states that have no action + * (not signed in, deactivated, invited, Super Admin protected) instead of + * showing disabled buttons. "Manage in Settings > Users" opens Strapi's own + * user page, where an account can be deactivated. + * + * @param {object} props + * @param {object} props.admin Admin row (the list row, refreshed from the dialog request). + * @param {object[]} props.sessions Live sessions, newest first. + * @param {boolean} props.loading First load of the sessions. + * @param {boolean} props.error Loading failed. + * @param {() => void} props.onRetry Loads again. + * @param {boolean} props.canRevoke Caller may sign admins out. + * @param {(session: object, trigger: HTMLElement|null) => void} props.onSignOut Asks to sign out one browser. + * @param {(trigger: HTMLElement|null) => void} props.onSignOutEverywhere Asks to sign out everywhere. + * @param {() => void} props.onClose Closes the dialog. + * @param {(event: Event) => void} [props.onCloseAutoFocus] Focus handling after close. + * @returns {import('react').ReactElement} Modal. + */ +const AdminSessionsModal = ({ + admin, + sessions, + loading, + error, + onRetry, + canRevoke, + onSignOut, + onSignOutEverywhere, + onClose, + onCloseAutoFocus, +}) => { + const t = useT(); + const canSignOut = canRevoke && admin.account === 'active' && !admin.protectedReason; + const settingsPath = `/settings/users/${admin.id}`; + + let notice = null; + if (admin.account !== 'active') { + notice = ( + + {t( + 'adminPanel.dialog.inactive.body', + 'Strapi rejects every request of a deactivated or invited account, so there is nothing to sign out.' + )} + + ); + } else if (admin.protectedReason === 'super-admin-protected' && canRevoke) { + notice = ( + + {t( + 'adminPanel.dialog.protected.body', + 'Only a Super Admin can sign out a Super Admin. This keeps at least one Super Admin able to work at all times.' + )} + + ); + } + + return ( + (open ? null : onClose())}> + + + + {t('adminPanel.dialog.title', 'Sessions of {name}', { name: admin.name })} + + + + + , + }, + { + id: 'status', + label: t('adminPanel.table.status', 'Status'), + render: , + fullWidth: true, + }, + ]} + /> + {notice} + {loading ? ( + + {t('adminPanel.dialog.loading', 'Loading sessions')} + + ) : null} + {!loading && error ? ( + + {t('common.tryAgain', 'Try again')} + + } + > + {t('adminPanel.dialog.error', 'The sessions could not be loaded.')} + + ) : null} + {!loading && !error && admin.account === 'active' && sessions.length === 0 ? ( + + {t( + 'adminPanel.dialog.empty', + '{name} is not signed in. Sessions appear here after the next sign-in.', + { name: admin.name } + )} + + ) : null} + {!loading && sessions.length > 0 ? ( + + {sessions.map((session) => ( + + ))} + + ) : null} + + + + + + + + + + {t('adminPanel.dialog.manage', 'Manage in Settings')} + + {canSignOut && sessions.length > 0 ? ( + + ) : null} + + + + + + ); +}; + +export default AdminSessionsModal; diff --git a/admin/src/pages/AdminPanel/adminPanelModel.mjs b/admin/src/pages/AdminPanel/adminPanelModel.mjs new file mode 100644 index 0000000..670b3f8 --- /dev/null +++ b/admin/src/pages/AdminPanel/adminPanelModel.mjs @@ -0,0 +1,184 @@ +/** + * Pure helpers of the Admin panel sessions view: URL state, request + * parameters, status mapping, durations and error mapping. No React, so + * `node --test` covers them without a bundler. + */ + +/** List filters, same values as the API. */ +export const ADMIN_FILTER_OPTIONS = Object.freeze(['all', 'signed-in', 'not-signed-in']); + +/** Page sizes offered by the pagination footer. */ +export const ADMIN_PAGE_SIZE_OPTIONS = Object.freeze(['10', '25', '50', '100']); + +/** Default page size. */ +export const ADMIN_DEFAULT_PAGE_SIZE = '25'; + +/** Longest search the API accepts. */ +export const ADMIN_MAX_SEARCH_LENGTH = 100; + +/** + * Reads the view state from the URL query (useQueryParams). Unknown or + * out-of-range values fall back to the defaults instead of failing the page. + * + * @param {Record|undefined} query Parsed URL query. + * @returns {{page: number, pageSize: number, filter: string, search: string}} View state. + */ +export function parseAdminPanelQuery(query = {}) { + const page = Number.parseInt(String(query?.page ?? ''), 10); + const pageSize = String(query?.pageSize ?? ''); + const filter = String(query?.filter ?? ''); + // The search is stored URI-encoded (encodeSearchQuery), like the dashboard. + let search = ''; + if (typeof query?.search === 'string') { + try { + search = decodeURIComponent(query.search).trim(); + } catch { + search = query.search.trim(); + } + } + return { + page: Number.isInteger(page) && page >= 1 && page <= 1_000_000 ? page : 1, + pageSize: Number( + ADMIN_PAGE_SIZE_OPTIONS.includes(pageSize) ? pageSize : ADMIN_DEFAULT_PAGE_SIZE + ), + filter: ADMIN_FILTER_OPTIONS.includes(filter) ? filter : 'all', + search: search.slice(0, ADMIN_MAX_SEARCH_LENGTH), + }; +} + +/** + * Query parameters for `GET /admin-sessions/admins`. + * + * @param {{page: number, pageSize: number, filter: string, search: string}} state View state. + * @returns {Record} Request parameters (empty search omitted). + */ +export function buildAdminListParams(state) { + return { + page: state.page, + pageSize: state.pageSize, + filter: state.filter, + ...(state.search ? { search: state.search } : {}), + }; +} + +/** + * Whether search or filter narrows the list (for "Clear filters"). + * + * @param {{filter: string, search: string}} state View state. + * @returns {boolean} + */ +export function hasAdminFilters(state) { + return state.filter !== 'all' || Boolean(state.search); +} + +/** + * Badge and second line of an admin row. Colour never carries meaning + * alone: every state has its own label. Danger is reserved for destructive + * buttons, so a deactivated account is neutral. + * + * @param {{account: string, sessionCount: number}} row Admin row from the API. + * @returns {{key: string, tone: string, label: {messageId: string, defaultMessage: string}, + * detail: {messageId: string, defaultMessage: string, values?: object}}} Presentation. + */ +export function getAdminStatusPresentation(row) { + if (row?.account === 'invited') { + return { + key: 'invited', + tone: 'secondary', + label: { messageId: 'adminPanel.status.invited', defaultMessage: 'Invited' }, + detail: { + messageId: 'adminPanel.status.invited.detail', + defaultMessage: 'Invitation not accepted yet', + }, + }; + } + if (row?.account === 'deactivated') { + return { + key: 'deactivated', + tone: 'neutral', + label: { messageId: 'adminPanel.status.deactivated', defaultMessage: 'Deactivated' }, + detail: { + messageId: 'adminPanel.status.deactivated.detail', + defaultMessage: 'Cannot sign in', + }, + }; + } + const count = Number(row?.sessionCount) || 0; + if (count > 0) { + return { + key: 'signed-in', + tone: 'success', + label: { messageId: 'adminPanel.status.signedIn', defaultMessage: 'Signed in' }, + detail: { + messageId: 'adminPanel.status.signedIn.detail', + defaultMessage: '{count, plural, one {# session} other {# sessions}}', + values: { count }, + }, + }; + } + return { + key: 'not-signed-in', + tone: 'neutral', + label: { messageId: 'adminPanel.status.notSignedIn', defaultMessage: 'Not signed in' }, + detail: { + messageId: 'adminPanel.status.notSignedIn.detail', + defaultMessage: 'No open session', + }, + }; +} + +/** + * Splits a duration in seconds into the largest whole unit for an ICU + * plural message ("2 hours", "14 days", "30 minutes"). + * + * @param {unknown} seconds Duration in seconds. + * @returns {{unit: 'days'|'hours'|'minutes', count: number}|null} Null for invalid input. + */ +export function splitDuration(seconds) { + const value = Number(seconds); + if (!Number.isFinite(value) || value <= 0) return null; + if (value % 86400 === 0) return { unit: 'days', count: value / 86400 }; + if (value % 3600 === 0) return { unit: 'hours', count: value / 3600 }; + return { unit: 'minutes', count: Math.max(1, Math.round(value / 60)) }; +} + +/** + * Maps a failed sign-out to a translated message. The server's own 403 + * reason decides between the Super Admin guard and a missing permission. + * + * @param {unknown} error Rejected value of the request (Strapi FetchError). + * @returns {{messageId: string, defaultMessage: string}} Message descriptor. + */ +export function getSignOutErrorMessage(error) { + const response = /** @type {any} */ (error)?.response; + const status = Number(response?.status ?? /** @type {any} */ (error)?.status); + const reason = response?.data?.error?.details?.reason; + if (status === 403 && reason === 'super-admin-protected') { + return { + messageId: 'adminPanel.signOut.error.protected', + defaultMessage: 'Only a Super Admin can sign out a Super Admin.', + }; + } + if (status === 403) { + return { + messageId: 'adminPanel.signOut.error.forbidden', + defaultMessage: 'You do not have permission to sign admins out.', + }; + } + if (status === 404) { + return { + messageId: 'adminPanel.signOut.error.gone', + defaultMessage: 'This session has already ended. The list is up to date now.', + }; + } + if (status === 429) { + return { + messageId: 'adminPanel.signOut.error.rateLimited', + defaultMessage: 'Too many sign-outs in a short time. Wait a minute and try again.', + }; + } + return { + messageId: 'adminPanel.signOut.error.generic', + defaultMessage: 'The admin could not be signed out. Try again.', + }; +} diff --git a/admin/src/pages/AdminPanel/index.jsx b/admin/src/pages/AdminPanel/index.jsx new file mode 100644 index 0000000..97b6c5c --- /dev/null +++ b/admin/src/pages/AdminPanel/index.jsx @@ -0,0 +1,662 @@ +import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; +import { useIntl } from 'react-intl'; +import { Link } from 'react-router-dom'; +import { + Pagination, + useFetchClient, + useNotification, + useQueryParams, + useRBAC, +} from '@strapi/strapi/admin'; +import { + Button, + Dialog, + EmptyStateLayout, + Flex, + IconButton, + LinkButton, + Loader, + SingleSelect, + SingleSelectOption, + Typography, + VisuallyHidden, +} from '@strapi/design-system'; +import { ArrowClockwise, Check, Cross, User } from '@strapi/icons'; +import { EmptyDocuments } from '@strapi/icons/symbols'; +import styled from 'styled-components'; +import pluginId from '../../pluginId'; +import pluginPermissions from '../../permissions'; +import { getTranslation } from '../../utils/getTranslation'; +import { isCancelledRequest, logSafeAdminError } from '../../utils/safeAdminLog.mjs'; +import { restoreDialogFocus } from '../../utils/restoreDialogFocus.mjs'; +import { useBreakpoint } from '../../utils/useBreakpoint'; +import { ConfirmAction, PageShell, StatCard, StatGrid } from '../../components/ui'; +import Alert from '../../components/PersistentAlert'; +import ReadableText from '../../components/ReadableText'; +import SessionViewNav from '../../components/SessionViewNav'; +import SessionSearch from '../Dashboard/SessionSearch'; +import { encodeSearchQuery, getErrorStatus } from '../Dashboard/dashboardModel.mjs'; +import { AdminCardList, AdminTable } from './AdminList'; +import AdminSessionsModal from './AdminSessionsModal'; +import { + ADMIN_DEFAULT_PAGE_SIZE, + ADMIN_FILTER_OPTIONS, + ADMIN_PAGE_SIZE_OPTIONS, + buildAdminListParams, + getSignOutErrorMessage, + hasAdminFilters, + parseAdminPanelQuery, + splitDuration, +} from './adminPanelModel.mjs'; + +/** Strapi's own user management (deactivate, roles, password). */ +const SETTINGS_USERS_PATH = '/settings/users'; + +/** Same 32 px touch target wrapper as the dashboard pagination. */ +const PaginationTargets = styled.div` + nav a { + min-width: 3.2rem; + } + + & > div { + flex-wrap: wrap; + gap: ${({ theme }) => theme.spaces[2]} ${({ theme }) => theme.spaces[4]}; + } + + & > div > div > span { + white-space: nowrap; + } +`; + +const EMPTY_STATS = { signedInAdmins: 0, activeSessions: 0, activeAccounts: 0, totalAdmins: 0 }; + +/** + * Admin panel sessions (IA in docs/plans/2026-11-17-admin-panel-sessions-design.md): + * who can use this Strapi admin panel, who is signed in right now, and how to + * sign someone out. Separate from the app-user dashboard; its numbers never + * mix with app-user numbers. Search, filter and pagination run on the server + * and live in the URL. Signing out asks for confirmation, states the real + * effect (next click, Strapi checks every request) and refreshes in place. + * + * @returns {import('react').ReactElement} Admin panel sessions page. + */ +const AdminPanelPage = () => { + const { formatMessage } = useIntl(); + const { get, post } = useFetchClient(); + const { toggleNotification } = useNotification(); + const { isBelowMedium } = useBreakpoint(); + const [{ query }, setQuery] = useQueryParams(); + const t = (id, defaultMessage, values) => + formatMessage({ id: getTranslation(id), defaultMessage }, values); + const view = parseAdminPanelQuery(query); + const { + allowedActions: { canRevoke }, + } = useRBAC(pluginPermissions.adminSessionsRevoke); + + const [admins, setAdmins] = useState([]); + const [meta, setMeta] = useState(null); + const [loading, setLoading] = useState(true); + const [refreshing, setRefreshing] = useState(false); + const [loadError, setLoadError] = useState(false); + const [selected, setSelected] = useState(null); + const [dialogSessions, setDialogSessions] = useState([]); + const [dialogLoading, setDialogLoading] = useState(false); + const [dialogError, setDialogError] = useState(false); + const [pending, setPending] = useState(null); + const requestIdRef = useRef(0); + const dialogRequestRef = useRef(0); + const hasLoadedRef = useRef(false); + const openerRef = useRef(null); + const confirmReturnRef = useRef(null); + const captionRef = useRef(null); + const pageRef = useRef(null); + const captionId = `admin-list-caption-${useId().replace(/:/g, '')}`; + + // `view` is rebuilt from the URL on every render; its four fields are the inputs. + const listParams = useMemo( + () => + buildAdminListParams({ + page: view.page, + pageSize: view.pageSize, + filter: view.filter, + search: view.search, + }), + [view.page, view.pageSize, view.filter, view.search] + ); + + /** + * Loads one page of admins with statistics. The first load shows the page + * loader; later loads keep the list mounted (focus and scroll stay) and a + * failed refresh keeps the last data under an error alert. + * + * @returns {Promise} + */ + const fetchAdmins = useCallback(async () => { + const requestId = requestIdRef.current + 1; + requestIdRef.current = requestId; + if (hasLoadedRef.current) setRefreshing(true); + else setLoading(true); + try { + const response = await get(`/${pluginId}/admin-sessions/admins`, { params: listParams }); + if (requestId !== requestIdRef.current) return; + const body = response?.data || {}; + setAdmins(Array.isArray(body.data) ? body.data : []); + setMeta(body.meta || null); + setLoadError(false); + hasLoadedRef.current = true; + } catch (err) { + if (requestId !== requestIdRef.current || isCancelledRequest(err)) return; + setLoadError(true); + logSafeAdminError('adminPanel.load', err); + } finally { + if (requestId === requestIdRef.current) { + setLoading(false); + setRefreshing(false); + } + } + }, [get, listParams]); + + useEffect(() => { + // eslint-disable-next-line react-hooks/set-state-in-effect -- state updates run after await; the compiler cannot see through the callback + fetchAdmins(); + }, [fetchAdmins]); + + /** + * Loads the sessions of the admin in the dialog. + * + * @param {object} admin Admin row. + * @returns {Promise} + */ + const fetchDialogSessions = useCallback( + async (admin) => { + const requestId = dialogRequestRef.current + 1; + dialogRequestRef.current = requestId; + setDialogLoading(true); + try { + const response = await get(`/${pluginId}/admin-sessions/admins/${admin.id}/sessions`); + if (requestId !== dialogRequestRef.current) return; + const body = response?.data || {}; + setDialogSessions(Array.isArray(body.data) ? body.data : []); + if (body.meta?.admin) setSelected((current) => (current ? body.meta.admin : current)); + setDialogError(false); + } catch (err) { + if (requestId !== dialogRequestRef.current || isCancelledRequest(err)) return; + setDialogError(true); + logSafeAdminError('adminPanel.sessions', err); + } finally { + if (requestId === dialogRequestRef.current) setDialogLoading(false); + } + }, + [get] + ); + + const openDialog = (admin, trigger) => { + openerRef.current = trigger; + setSelected(admin); + setDialogSessions([]); + setDialogError(false); + fetchDialogSessions(admin); + }; + + const closeDialog = () => { + dialogRequestRef.current += 1; + setSelected(null); + setDialogSessions([]); + }; + + // Keep the URL page inside the result range after filtering or sign-outs. + const pagination = meta?.pagination || { page: 1, pageCount: 1, total: 0 }; + useEffect(() => { + if (!loading && !refreshing && view.page > pagination.pageCount) { + setQuery({ page: String(pagination.pageCount) }, 'push', true); + } + }, [loading, refreshing, view.page, pagination.pageCount, setQuery]); + + const handleFilterChange = (value) => { + const filter = String(value); + setQuery({ filter: filter === 'all' ? undefined : filter, page: '1' }); + }; + + const handleSearch = useCallback( + (value) => setQuery({ search: encodeSearchQuery(value), page: '1' }, 'push', true), + [setQuery] + ); + + const handleClearFilters = () => { + setQuery({ search: undefined, filter: undefined, page: '1' }); + captionRef.current?.focus(); + }; + + /** + * Opens the confirmation for one browser or for every browser of an admin. + * + * @param {object} admin Admin row. + * @param {object|null} session Session row, or null for "everywhere". + * @param {HTMLElement|null} trigger Button that asked, for focus return. + * @returns {void} + */ + const askSignOut = (admin, session, trigger) => { + confirmReturnRef.current = trigger; + setPending({ admin, session }); + }; + + /** + * Signs out after confirmation and refreshes the list (and the dialog). + * Errors are reported and rethrown so the confirmation stays open; a 404 + * means the session already ended, which only needs a refresh. + * + * @returns {Promise} + */ + const confirmSignOut = async () => { + if (!pending) return; + const { admin, session } = pending; + const device = session?.device || t('adminPanel.session.unknownDevice', 'Unknown browser'); + const url = session + ? `/${pluginId}/admin-sessions/admins/${admin.id}/sessions/${session.id}/sign-out` + : `/${pluginId}/admin-sessions/admins/${admin.id}/sign-out-everywhere`; + try { + const response = await post(url); + const result = response?.data?.data || {}; + if (result.signedOutSelf) { + toggleNotification({ + type: 'warning', + message: t( + 'adminPanel.signOut.success.self', + 'You signed yourself out of this browser. The login page opens next.' + ), + }); + } else { + toggleNotification({ + type: 'success', + message: session + ? t('adminPanel.signOut.success.one', '{name} was signed out of {device}.', { + name: admin.name, + device, + }) + : t('adminPanel.signOut.success.all', '{name} was signed out everywhere.', { + name: admin.name, + }), + }); + } + await Promise.all([fetchAdmins(), selected ? fetchDialogSessions(selected) : null]); + } catch (err) { + logSafeAdminError('adminPanel.signOut', err); + const message = getSignOutErrorMessage(err); + toggleNotification({ + type: getErrorStatus(err) === 404 ? 'warning' : 'danger', + message: t(message.messageId, message.defaultMessage), + }); + if (getErrorStatus(err) === 404) { + // Already ended: refresh and let the confirmation close normally. + await Promise.all([fetchAdmins(), selected ? fetchDialogSessions(selected) : null]); + return; + } + throw err; + } + }; + + const stats = meta?.stats || EMPTY_STATS; + const supported = meta?.supported !== false; + const showData = !loading && Boolean(meta) && supported; + const filtersActive = hasAdminFilters(view); + + const durationText = (seconds) => { + const parts = splitDuration(seconds); + if (!parts) return ''; + if (parts.unit === 'days') + return t('adminPanel.duration.days', '{count, plural, one {# day} other {# days}}', parts); + if (parts.unit === 'hours') + return t('adminPanel.duration.hours', '{count, plural, one {# hour} other {# hours}}', parts); + return t( + 'adminPanel.duration.minutes', + '{count, plural, one {# minute} other {# minutes}}', + parts + ); + }; + + const statusCard = (filter) => ({ + onClick: () => handleFilterChange(filter), + pressed: view.filter === filter, + }); + + // Confirmation copy (IA 3.3). The body always says when it takes effect and + // that the admin can sign in again; self sign-out of this browser warns. + let confirm = null; + if (pending) { + const { admin, session } = pending; + const device = session?.device || t('adminPanel.session.unknownDevice', 'Unknown browser'); + const includesThisBrowser = admin.self && (session ? session.current : true); + const body = session + ? t( + 'adminPanel.confirm.one.body', + '{name} is signed out of {device} on their next click in the admin panel. They can sign in again with their password.', + { name: admin.name, device } + ) + : t( + 'adminPanel.confirm.all.body', + 'Every session of {name} ends on their next click in the admin panel. They can sign in again with their password. To stop them from signing in, deactivate the account in Settings > Users.', + { name: admin.name } + ); + confirm = { + title: includesThisBrowser + ? t('adminPanel.confirm.self.title', 'Sign yourself out?') + : session + ? t('adminPanel.confirm.one.title', 'Sign {name} out of this browser?', { + name: admin.name, + }) + : t('adminPanel.confirm.all.title', 'Sign {name} out everywhere?', { name: admin.name }), + body: ( + + {/* A node body needs its own Dialog.Description (accessible description). */} + {body} + {includesThisBrowser ? ( + + {t( + 'adminPanel.confirm.self.warning', + 'This includes the browser you are using now. You will be taken to the login page.' + )} + + ) : null} + + ), + label: session + ? t('adminPanel.session.signOut', 'Sign out') + : t('adminPanel.actions.signOutEverywhereShort', 'Sign out everywhere'), + }; + } + + const listProps = { + admins, + labelledBy: captionId, + canRevoke: Boolean(canRevoke), + onView: openDialog, + onSignOutEverywhere: (admin, trigger) => askSignOut(admin, null, trigger), + busy: refreshing, + }; + + const policy = meta?.policy; + const range = + pagination.total > 0 + ? { + from: (pagination.page - 1) * pagination.pageSize + 1, + to: Math.min(pagination.page * pagination.pageSize, pagination.total), + } + : null; + + return ( + }> + {t('adminPanel.manageUsers', 'Manage admins')} + + } + > + + + + {!loading && loadError ? ( + + {t('common.tryAgain', 'Try again')} + + } + > + + {t('adminPanel.error.load', 'Admin sessions could not be loaded.')} + + + ) : null} + + {loading ? ( + + {t('adminPanel.loading', 'Loading admins')} + + ) : null} + + {!loading && meta && !supported ? ( + + + ); +}; + +export default AdminPanelPage; diff --git a/admin/src/pages/App.jsx b/admin/src/pages/App.jsx index 56d3d41..4645161 100644 --- a/admin/src/pages/App.jsx +++ b/admin/src/pages/App.jsx @@ -1,11 +1,34 @@ -import HomePage from './HomePage'; import { Page } from '@strapi/strapi/admin'; +import { Route, Routes } from 'react-router-dom'; +import HomePage from './HomePage'; +import AdminPanelPage from './AdminPanel'; import pluginPermissions from '../permissions'; +/** + * Plugin page router. Strapi mounts this component at + * `plugins/magic-sessionmanager/*`: the index is the app-user dashboard, and + * `admin-panel` lists Strapi admin panel sessions. Both need plugin access; + * the admin panel view also needs `admin-sessions.read`. These checks only + * decide what is rendered; every API route enforces the same actions. + * + * @returns {import('react').ReactElement} Plugin routes. + */ const App = () => { return ( - + + } /> + + + + } + /> + {/* Unknown sub-paths keep showing the dashboard, as before 4.14. */} + } /> + ); }; diff --git a/admin/src/pages/Dashboard/SessionSearch.jsx b/admin/src/pages/Dashboard/SessionSearch.jsx index 1267697..0c53bdf 100644 --- a/admin/src/pages/Dashboard/SessionSearch.jsx +++ b/admin/src/pages/Dashboard/SessionSearch.jsx @@ -29,9 +29,11 @@ const SEARCH_DEBOUNCE_MS = 300; * @param {object} props * @param {string} props.value Current search from the URL. * @param {(value: string) => void} props.onSearch Writes the search to the URL. + * @param {string} [props.label] Accessible label; defaults to the session search label. + * @param {string} [props.placeholder] Placeholder; defaults to the session search hint. * @returns {import('react').ReactElement} Search form. */ -const SessionSearch = ({ value, onSearch }) => { +const SessionSearch = ({ value, onSearch, label, placeholder }) => { const { formatMessage } = useIntl(); const t = (id, defaultMessage) => formatMessage({ id: getTranslation(id), defaultMessage }); const [draft, setDraft] = useState(value); @@ -77,9 +79,11 @@ const SessionSearch = ({ value, onSearch }) => { apply(''); }} clearLabel={t('homepage.search.clear', 'Clear search')} - placeholder={t('homepage.search.placeholder', 'Search user, email, IP or device')} + placeholder={ + placeholder ?? t('homepage.search.placeholder', 'Search user, email, IP or device') + } > - {t('homepage.search.label', 'Search sessions')} + {label ?? t('homepage.search.label', 'Search sessions')} diff --git a/admin/src/pages/HomePage.jsx b/admin/src/pages/HomePage.jsx index 5e3a424..de8f76c 100644 --- a/admin/src/pages/HomePage.jsx +++ b/admin/src/pages/HomePage.jsx @@ -53,6 +53,7 @@ import { PageShell, StatCard, StatGrid } from '../components/ui'; import SessionDetailModal from '../components/SessionDetailModal'; import Alert from '../components/PersistentAlert'; import ReadableText from '../components/ReadableText'; +import SessionViewNav from '../components/SessionViewNav'; import SessionTable from './Dashboard/SessionTable'; import SessionCardList from './Dashboard/SessionCardList'; import SessionSearch from './Dashboard/SessionSearch'; @@ -705,6 +706,8 @@ const HomePage = () => { gap={6} minWidth={0} > + + {!loading && loadError ? ( Benutzer.", + "adminPanel.confirm.all.title": "{name} überall abmelden?", + "adminPanel.confirm.one.body": "{name} wird beim nächsten Klick im Admin-Panel von {device} abgemeldet. Eine erneute Anmeldung mit dem Passwort ist möglich.", + "adminPanel.confirm.one.title": "{name} von diesem Browser abmelden?", + "adminPanel.confirm.self.title": "Sich selbst abmelden?", + "adminPanel.confirm.self.warning": "Das betrifft auch den Browser, den Sie gerade verwenden. Danach öffnet sich die Anmeldeseite.", + "adminPanel.dialog.email": "E-Mail", + "adminPanel.dialog.empty": "{name} ist nicht angemeldet. Sitzungen erscheinen hier nach der nächsten Anmeldung.", + "adminPanel.dialog.error": "Die Sitzungen konnten nicht geladen werden.", + "adminPanel.dialog.inactive.body": "Strapi lehnt jede Anfrage eines deaktivierten oder eingeladenen Kontos ab. Es gibt daher nichts abzumelden.", + "adminPanel.dialog.inactive.title": "Keine nutzbare Sitzung", + "adminPanel.dialog.listLabel": "Angemeldete Browser", + "adminPanel.dialog.loading": "Sitzungen werden geladen", + "adminPanel.dialog.manage": "In den Einstellungen verwalten", + "adminPanel.dialog.protected.body": "Nur ein Super Admin kann einen Super Admin abmelden. So bleibt immer mindestens ein Super Admin arbeitsfähig.", + "adminPanel.dialog.protected.title": "Super Admin", + "adminPanel.dialog.title": "Sitzungen von {name}", + "adminPanel.duration.days": "{count, plural, one {# Tag} other {# Tagen}}", + "adminPanel.duration.hours": "{count, plural, one {# Stunde} other {# Stunden}}", + "adminPanel.duration.minutes": "{count, plural, one {# Minute} other {# Minuten}}", + "adminPanel.empty": "Noch keine Administratorkonten.", + "adminPanel.error.load": "Die Admin-Sitzungen konnten nicht geladen werden.", + "adminPanel.filter.all": "Alle Administratoren", + "adminPanel.filter.label": "Anmeldestatus", + "adminPanel.filter.notSignedIn": "Nicht angemeldet", + "adminPanel.filter.signedIn": "Angemeldet", + "adminPanel.howItWorks.body": "Das Abmelden wirkt beim nächsten Klick des Administrators: Strapi prüft die Sitzung bei jeder Anfrage an das Admin-Panel. Eine erneute Anmeldung mit dem Passwort ist möglich; um das zu verhindern, deaktivieren Sie das Konto unter Einstellungen > Benutzer. Admin-API-Tokens sind nicht betroffen. Strapi speichert für Admin-Sitzungen keine IP-Adressen.", + "adminPanel.howItWorks.policy": "Ohne Aktivität endet eine Sitzung nach {idle}, mit „Angemeldet bleiben“ nach {rememberIdle}.", + "adminPanel.howItWorks.title": "So funktioniert das Abmelden", + "adminPanel.list.heading": "Liste der Administratoren", + "adminPanel.loading": "Administratoren werden geladen", + "adminPanel.manageUsers": "Administratoren verwalten", + "adminPanel.noResults": "Keine Administratoren entsprechen Ihrer Suche oder Ihrem Filter.", + "adminPanel.noResults.reset": "Filter zurücksetzen", + "adminPanel.refreshing": "Administratoren werden aktualisiert", + "adminPanel.roles.none": "Keine Rolle", + "adminPanel.search.label": "Administratoren suchen", + "adminPanel.search.placeholder": "Name oder E-Mail suchen", + "adminPanel.session.current": "Dieser Browser", + "adminPanel.session.endsAt": "Endet spätestens", + "adminPanel.session.lastActiveAt": "Zuletzt aktiv", + "adminPanel.session.rememberMe": "Angemeldet bleiben", + "adminPanel.session.signOut": "Abmelden", + "adminPanel.session.signOutLabel": "{name} von {device} abmelden", + "adminPanel.session.signedInAt": "Angemeldet am", + "adminPanel.session.unknownDevice": "Unbekannter Browser", + "adminPanel.signOut.error.forbidden": "Sie haben keine Berechtigung, Administratoren abzumelden.", + "adminPanel.signOut.error.generic": "Der Administrator konnte nicht abgemeldet werden. Bitte versuchen Sie es erneut.", + "adminPanel.signOut.error.gone": "Diese Sitzung ist bereits beendet. Die Liste ist jetzt aktuell.", + "adminPanel.signOut.error.protected": "Nur ein Super Admin kann einen Super Admin abmelden.", + "adminPanel.signOut.error.rateLimited": "Zu viele Abmeldungen in kurzer Zeit. Warten Sie eine Minute und versuchen Sie es erneut.", + "adminPanel.signOut.success.all": "{name} wurde überall abgemeldet.", + "adminPanel.signOut.success.one": "{name} wurde von {device} abgemeldet.", + "adminPanel.signOut.success.self": "Sie haben sich von diesem Browser abgemeldet. Als Nächstes öffnet sich die Anmeldeseite.", + "adminPanel.stats.active": "{count, plural, one {# aktives Konto} other {# aktive Konten}}", + "adminPanel.stats.all": "Alle Administratoren", + "adminPanel.stats.label": "Statistik der Administratoren", + "adminPanel.stats.notSignedIn": "Nicht angemeldet", + "adminPanel.stats.notSignedIn.detail": "Inklusive deaktivierter und eingeladener Konten", + "adminPanel.stats.sessions": "{count, plural, one {# Sitzung} other {# Sitzungen}} insgesamt", + "adminPanel.stats.signedIn": "Angemeldete Administratoren", + "adminPanel.status.deactivated": "Deaktiviert", + "adminPanel.status.deactivated.detail": "Kann sich nicht anmelden", + "adminPanel.status.invited": "Eingeladen", + "adminPanel.status.invited.detail": "Einladung noch nicht angenommen", + "adminPanel.status.notSignedIn": "Nicht angemeldet", + "adminPanel.status.notSignedIn.detail": "Keine offene Sitzung", + "adminPanel.status.signedIn": "Angemeldet", + "adminPanel.status.signedIn.detail": "{count, plural, one {# Sitzung} other {# Sitzungen}}", + "adminPanel.subtitle": "Wer im Admin-Panel dieser Strapi-Instanz angemeldet ist. Die Benutzer Ihrer App finden Sie unter App-Benutzer.", + "adminPanel.table.actions": "Aktionen", + "adminPanel.table.admin": "Administrator", + "adminPanel.table.lastActive": "Zuletzt aktiv", + "adminPanel.table.roles": "Rollen", + "adminPanel.table.status": "Anmeldestatus", + "adminPanel.title": "Sitzungen im Admin-Panel", + "adminPanel.unsupported": "Sitzungen im Admin-Panel sind in dieser Strapi-Version nicht verfügbar. Sie benötigen Strapi 5 mit Sitzungsverwaltung (getestet mit 5.62).", + "adminPanel.you": "Sie", + "views.admins": "Admin-Panel", + "views.label": "Sitzungsansichten", + "views.users": "App-Benutzer" } diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index 445bc72..cd4a7b6 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -531,5 +531,93 @@ "homepage.untracked.summary.mobile": "Mobile", "homepage.untracked.summary.unknownDevice": "Unknown device", "homepage.untracked.summary.next": "Sessions created after tracking started point to a sign-in path this plugin does not see: a custom login route, GraphQL sign-ins or a plugin that issues tokens. The plugin documentation explains each case. Older sessions need no action.", - "homepage.howItWorks.untracked": "Strapi also keeps its own list of sign-ins (refresh tokens). A sign-in that has no session details here, for example one from before this plugin tracked sessions, is not in this list and is never counted as active or online. A notice above the cards shows how many there are and why." + "homepage.howItWorks.untracked": "Strapi also keeps its own list of sign-ins (refresh tokens). A sign-in that has no session details here, for example one from before this plugin tracked sessions, is not in this list and is never counted as active or online. A notice above the cards shows how many there are and why.", + "adminPanel.actions.refresh": "Refresh admins", + "adminPanel.actions.signOutEverywhere": "Sign out {name} everywhere", + "adminPanel.actions.signOutEverywhereShort": "Sign out everywhere", + "adminPanel.actions.view": "View sessions of {name}", + "adminPanel.actions.viewShort": "View sessions", + "adminPanel.caption": "{from, number}–{to, number} of {total, plural, one {# admin} other {# admins}}", + "adminPanel.captionNone": "0 admins", + "adminPanel.confirm.all.body": "Every session of {name} ends on their next click in the admin panel. They can sign in again with their password. To stop them from signing in, deactivate the account in Settings > Users.", + "adminPanel.confirm.all.title": "Sign {name} out everywhere?", + "adminPanel.confirm.one.body": "{name} is signed out of {device} on their next click in the admin panel. They can sign in again with their password.", + "adminPanel.confirm.one.title": "Sign {name} out of this browser?", + "adminPanel.confirm.self.title": "Sign yourself out?", + "adminPanel.confirm.self.warning": "This includes the browser you are using now. You will be taken to the login page.", + "adminPanel.dialog.email": "Email", + "adminPanel.dialog.empty": "{name} is not signed in. Sessions appear here after the next sign-in.", + "adminPanel.dialog.error": "The sessions could not be loaded.", + "adminPanel.dialog.inactive.body": "Strapi rejects every request of a deactivated or invited account, so there is nothing to sign out.", + "adminPanel.dialog.inactive.title": "No usable session", + "adminPanel.dialog.listLabel": "Signed-in browsers", + "adminPanel.dialog.loading": "Loading sessions", + "adminPanel.dialog.manage": "Manage in Settings", + "adminPanel.dialog.protected.body": "Only a Super Admin can sign out a Super Admin. This keeps at least one Super Admin able to work at all times.", + "adminPanel.dialog.protected.title": "Super Admin", + "adminPanel.dialog.title": "Sessions of {name}", + "adminPanel.duration.days": "{count, plural, one {# day} other {# days}}", + "adminPanel.duration.hours": "{count, plural, one {# hour} other {# hours}}", + "adminPanel.duration.minutes": "{count, plural, one {# minute} other {# minutes}}", + "adminPanel.empty": "No admin accounts yet.", + "adminPanel.error.load": "Admin sessions could not be loaded.", + "adminPanel.filter.all": "All admins", + "adminPanel.filter.label": "Sign-in status", + "adminPanel.filter.notSignedIn": "Not signed in", + "adminPanel.filter.signedIn": "Signed in", + "adminPanel.howItWorks.body": "Signing out takes effect on the admin’s next click: Strapi checks the session on every admin request. They can sign in again with their password; to stop that, deactivate the account in Settings > Users. Admin API tokens are not affected. Strapi records no IP address for admin sessions.", + "adminPanel.howItWorks.policy": "Without activity a session ends after {idle}, or after {rememberIdle} when “Remember me” was ticked.", + "adminPanel.howItWorks.title": "How signing out works", + "adminPanel.list.heading": "Admin list", + "adminPanel.loading": "Loading admins", + "adminPanel.manageUsers": "Manage admins", + "adminPanel.noResults": "No admins match your search or filter.", + "adminPanel.noResults.reset": "Clear filters", + "adminPanel.refreshing": "Updating admins", + "adminPanel.roles.none": "No role", + "adminPanel.search.label": "Search admins", + "adminPanel.search.placeholder": "Search name or email", + "adminPanel.session.current": "This browser", + "adminPanel.session.endsAt": "Ends at the latest", + "adminPanel.session.lastActiveAt": "Last active", + "adminPanel.session.rememberMe": "Remember me", + "adminPanel.session.signOut": "Sign out", + "adminPanel.session.signOutLabel": "Sign {name} out of {device}", + "adminPanel.session.signedInAt": "Signed in", + "adminPanel.session.unknownDevice": "Unknown browser", + "adminPanel.signOut.error.forbidden": "You do not have permission to sign admins out.", + "adminPanel.signOut.error.generic": "The admin could not be signed out. Try again.", + "adminPanel.signOut.error.gone": "This session has already ended. The list is up to date now.", + "adminPanel.signOut.error.protected": "Only a Super Admin can sign out a Super Admin.", + "adminPanel.signOut.error.rateLimited": "Too many sign-outs in a short time. Wait a minute and try again.", + "adminPanel.signOut.success.all": "{name} was signed out everywhere.", + "adminPanel.signOut.success.one": "{name} was signed out of {device}.", + "adminPanel.signOut.success.self": "You signed yourself out of this browser. The login page opens next.", + "adminPanel.stats.active": "{count, plural, one {# active account} other {# active accounts}}", + "adminPanel.stats.all": "All admins", + "adminPanel.stats.label": "Admin statistics", + "adminPanel.stats.notSignedIn": "Not signed in", + "adminPanel.stats.notSignedIn.detail": "Includes deactivated and invited accounts", + "adminPanel.stats.sessions": "{count, plural, one {# session} other {# sessions}} in total", + "adminPanel.stats.signedIn": "Signed-in admins", + "adminPanel.status.deactivated": "Deactivated", + "adminPanel.status.deactivated.detail": "Cannot sign in", + "adminPanel.status.invited": "Invited", + "adminPanel.status.invited.detail": "Invitation not accepted yet", + "adminPanel.status.notSignedIn": "Not signed in", + "adminPanel.status.notSignedIn.detail": "No open session", + "adminPanel.status.signedIn": "Signed in", + "adminPanel.status.signedIn.detail": "{count, plural, one {# session} other {# sessions}}", + "adminPanel.subtitle": "Who is signed in to this Strapi admin panel. Your app’s users are under App users.", + "adminPanel.table.actions": "Actions", + "adminPanel.table.admin": "Admin", + "adminPanel.table.lastActive": "Last active", + "adminPanel.table.roles": "Roles", + "adminPanel.table.status": "Status", + "adminPanel.title": "Admin panel sessions", + "adminPanel.unsupported": "Admin panel sessions are not available on this Strapi version. They need Strapi 5 with session management (tested with 5.62).", + "adminPanel.you": "You", + "views.admins": "Admin panel", + "views.label": "Session views", + "views.users": "App users" } diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index 5d8d415..cc61179 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -531,5 +531,93 @@ "homepage.untracked.summary.mobile": "Móvil", "homepage.untracked.summary.unknownDevice": "Dispositivo desconocido", "homepage.untracked.summary.next": "Las sesiones creadas después de empezar el seguimiento apuntan a una vía de inicio de sesión que este plugin no ve: una ruta de inicio de sesión propia, inicios de sesión por GraphQL o un plugin que emite tokens. La documentación del plugin explica cada caso. Las sesiones más antiguas no requieren ninguna acción.", - "homepage.howItWorks.untracked": "Strapi también mantiene su propia lista de inicios de sesión (tokens de actualización). Un inicio de sesión sin detalles de sesión aquí, por ejemplo de antes de que este plugin hiciera seguimiento, no aparece en esta lista y nunca cuenta como activo o en línea. Un aviso encima de las tarjetas muestra cuántos hay y por qué." + "homepage.howItWorks.untracked": "Strapi también mantiene su propia lista de inicios de sesión (tokens de actualización). Un inicio de sesión sin detalles de sesión aquí, por ejemplo de antes de que este plugin hiciera seguimiento, no aparece en esta lista y nunca cuenta como activo o en línea. Un aviso encima de las tarjetas muestra cuántos hay y por qué.", + "adminPanel.actions.refresh": "Actualizar administradores", + "adminPanel.actions.signOutEverywhere": "Cerrar la sesión de {name} en todas partes", + "adminPanel.actions.signOutEverywhereShort": "Cerrar sesión en todas partes", + "adminPanel.actions.view": "Ver las sesiones de {name}", + "adminPanel.actions.viewShort": "Ver sesiones", + "adminPanel.caption": "{from, number}–{to, number} de {total, plural, one {# administrador} other {# administradores}}", + "adminPanel.captionNone": "0 administradores", + "adminPanel.confirm.all.body": "Todas las sesiones de {name} terminan con su próximo clic en el panel de administración. Podrá volver a iniciar sesión con su contraseña. Para impedirlo, desactive la cuenta en Configuración > Usuarios.", + "adminPanel.confirm.all.title": "¿Cerrar la sesión de {name} en todas partes?", + "adminPanel.confirm.one.body": "La sesión de {name} en {device} se cierra con su próximo clic en el panel de administración. Podrá volver a iniciar sesión con su contraseña.", + "adminPanel.confirm.one.title": "¿Cerrar la sesión de {name} en este navegador?", + "adminPanel.confirm.self.title": "¿Cerrar su propia sesión?", + "adminPanel.confirm.self.warning": "Esto incluye el navegador que está usando ahora. Después se abrirá la página de inicio de sesión.", + "adminPanel.dialog.email": "Correo electrónico", + "adminPanel.dialog.empty": "{name} no ha iniciado sesión. Las sesiones aparecen aquí tras el próximo inicio de sesión.", + "adminPanel.dialog.error": "No se pudieron cargar las sesiones.", + "adminPanel.dialog.inactive.body": "Strapi rechaza todas las solicitudes de una cuenta desactivada o invitada, así que no hay ninguna sesión que cerrar.", + "adminPanel.dialog.inactive.title": "Ninguna sesión utilizable", + "adminPanel.dialog.listLabel": "Navegadores con sesión iniciada", + "adminPanel.dialog.loading": "Cargando sesiones", + "adminPanel.dialog.manage": "Gestionar en Configuración", + "adminPanel.dialog.protected.body": "Solo un Super Admin puede cerrar la sesión de un Super Admin. Así, al menos un Super Admin puede trabajar en todo momento.", + "adminPanel.dialog.protected.title": "Super Admin", + "adminPanel.dialog.title": "Sesiones de {name}", + "adminPanel.duration.days": "{count, plural, one {# día} other {# días}}", + "adminPanel.duration.hours": "{count, plural, one {# hora} other {# horas}}", + "adminPanel.duration.minutes": "{count, plural, one {# minuto} other {# minutos}}", + "adminPanel.empty": "Todavía no hay cuentas de administrador.", + "adminPanel.error.load": "No se pudieron cargar las sesiones de administración.", + "adminPanel.filter.all": "Todos los administradores", + "adminPanel.filter.label": "Estado de inicio de sesión", + "adminPanel.filter.notSignedIn": "Sin sesión iniciada", + "adminPanel.filter.signedIn": "Con sesión iniciada", + "adminPanel.howItWorks.body": "Cerrar la sesión surte efecto con el próximo clic del administrador: Strapi comprueba la sesión en cada solicitud de administración. Podrá volver a iniciar sesión con su contraseña; para impedirlo, desactive la cuenta en Configuración > Usuarios. Los tokens de API de administración no se ven afectados. Strapi no registra direcciones IP para las sesiones de administración.", + "adminPanel.howItWorks.policy": "Sin actividad, una sesión termina tras {idle}, o tras {rememberIdle} si se marcó «Recordarme».", + "adminPanel.howItWorks.title": "Cómo funciona el cierre de sesión", + "adminPanel.list.heading": "Lista de administradores", + "adminPanel.loading": "Cargando administradores", + "adminPanel.manageUsers": "Gestionar administradores", + "adminPanel.noResults": "Ningún administrador coincide con su búsqueda o filtro.", + "adminPanel.noResults.reset": "Borrar filtros", + "adminPanel.refreshing": "Actualizando administradores", + "adminPanel.roles.none": "Sin rol", + "adminPanel.search.label": "Buscar administradores", + "adminPanel.search.placeholder": "Buscar nombre o correo electrónico", + "adminPanel.session.current": "Este navegador", + "adminPanel.session.endsAt": "Termina a más tardar", + "adminPanel.session.lastActiveAt": "Última actividad", + "adminPanel.session.rememberMe": "Recordarme", + "adminPanel.session.signOut": "Cerrar sesión", + "adminPanel.session.signOutLabel": "Cerrar la sesión de {name} en {device}", + "adminPanel.session.signedInAt": "Inicio de sesión", + "adminPanel.session.unknownDevice": "Navegador desconocido", + "adminPanel.signOut.error.forbidden": "No tiene permiso para cerrar la sesión de administradores.", + "adminPanel.signOut.error.generic": "No se pudo cerrar la sesión del administrador. Inténtelo de nuevo.", + "adminPanel.signOut.error.gone": "Esta sesión ya terminó. La lista está actualizada.", + "adminPanel.signOut.error.protected": "Solo un Super Admin puede cerrar la sesión de un Super Admin.", + "adminPanel.signOut.error.rateLimited": "Demasiados cierres de sesión en poco tiempo. Espere un minuto e inténtelo de nuevo.", + "adminPanel.signOut.success.all": "Se cerró la sesión de {name} en todas partes.", + "adminPanel.signOut.success.one": "Se cerró la sesión de {name} en {device}.", + "adminPanel.signOut.success.self": "Ha cerrado su sesión en este navegador. A continuación se abre la página de inicio de sesión.", + "adminPanel.stats.active": "{count, plural, one {# cuenta activa} other {# cuentas activas}}", + "adminPanel.stats.all": "Todos los administradores", + "adminPanel.stats.label": "Estadísticas de administradores", + "adminPanel.stats.notSignedIn": "Sin sesión iniciada", + "adminPanel.stats.notSignedIn.detail": "Incluye cuentas desactivadas e invitadas", + "adminPanel.stats.sessions": "{count, plural, one {# sesión} other {# sesiones}} en total", + "adminPanel.stats.signedIn": "Administradores con sesión iniciada", + "adminPanel.status.deactivated": "Desactivado", + "adminPanel.status.deactivated.detail": "No puede iniciar sesión", + "adminPanel.status.invited": "Invitado", + "adminPanel.status.invited.detail": "Invitación aún no aceptada", + "adminPanel.status.notSignedIn": "Sin sesión iniciada", + "adminPanel.status.notSignedIn.detail": "Ninguna sesión abierta", + "adminPanel.status.signedIn": "Con sesión iniciada", + "adminPanel.status.signedIn.detail": "{count, plural, one {# sesión} other {# sesiones}}", + "adminPanel.subtitle": "Quién ha iniciado sesión en este panel de administración de Strapi. Los usuarios de su aplicación están en Usuarios de la aplicación.", + "adminPanel.table.actions": "Acciones", + "adminPanel.table.admin": "Administrador", + "adminPanel.table.lastActive": "Última actividad", + "adminPanel.table.roles": "Roles", + "adminPanel.table.status": "Estado", + "adminPanel.title": "Sesiones del panel de administración", + "adminPanel.unsupported": "Las sesiones del panel de administración no están disponibles en esta versión de Strapi. Requieren Strapi 5 con gestión de sesiones (probado con 5.62).", + "adminPanel.you": "Usted", + "views.admins": "Panel de administración", + "views.label": "Vistas de sesiones", + "views.users": "Usuarios de la aplicación" } diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index 6772c38..7e8bbac 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -531,5 +531,93 @@ "homepage.untracked.summary.mobile": "Mobile", "homepage.untracked.summary.unknownDevice": "Appareil inconnu", "homepage.untracked.summary.next": "Les sessions créées après le début du suivi indiquent un mode de connexion que ce plugin ne voit pas : une route de connexion personnalisée, des connexions GraphQL ou un plugin qui émet des jetons. La documentation du plugin explique chaque cas. Les sessions plus anciennes ne demandent aucune action.", - "homepage.howItWorks.untracked": "Strapi tient aussi sa propre liste de connexions (jetons d’actualisation). Une connexion sans détails de session ici, par exemple antérieure au suivi par ce plugin, ne figure pas dans cette liste et n’est jamais comptée comme active ou en ligne. Un avis au-dessus des cartes indique combien il y en a et pourquoi." + "homepage.howItWorks.untracked": "Strapi tient aussi sa propre liste de connexions (jetons d’actualisation). Une connexion sans détails de session ici, par exemple antérieure au suivi par ce plugin, ne figure pas dans cette liste et n’est jamais comptée comme active ou en ligne. Un avis au-dessus des cartes indique combien il y en a et pourquoi.", + "adminPanel.actions.refresh": "Actualiser les administrateurs", + "adminPanel.actions.signOutEverywhere": "Déconnecter {name} partout", + "adminPanel.actions.signOutEverywhereShort": "Déconnecter partout", + "adminPanel.actions.view": "Voir les sessions de {name}", + "adminPanel.actions.viewShort": "Voir les sessions", + "adminPanel.caption": "{from, number}–{to, number} sur {total, plural, one {# administrateur} other {# administrateurs}}", + "adminPanel.captionNone": "0 administrateur", + "adminPanel.confirm.all.body": "Toutes les sessions de {name} prennent fin à son prochain clic dans le panneau d’administration. Une nouvelle connexion avec le mot de passe reste possible. Pour l’empêcher, désactivez le compte dans Paramètres > Utilisateurs.", + "adminPanel.confirm.all.title": "Déconnecter {name} partout ?", + "adminPanel.confirm.one.body": "{name} est déconnecté de {device} à son prochain clic dans le panneau d’administration. Une nouvelle connexion avec le mot de passe reste possible.", + "adminPanel.confirm.one.title": "Déconnecter {name} de ce navigateur ?", + "adminPanel.confirm.self.title": "Vous déconnecter ?", + "adminPanel.confirm.self.warning": "Cela inclut le navigateur que vous utilisez actuellement. La page de connexion s’ouvrira ensuite.", + "adminPanel.dialog.email": "E-mail", + "adminPanel.dialog.empty": "{name} n’est pas connecté. Les sessions apparaissent ici après la prochaine connexion.", + "adminPanel.dialog.error": "Les sessions n’ont pas pu être chargées.", + "adminPanel.dialog.inactive.body": "Strapi refuse toute requête d’un compte désactivé ou invité : il n’y a donc rien à déconnecter.", + "adminPanel.dialog.inactive.title": "Aucune session utilisable", + "adminPanel.dialog.listLabel": "Navigateurs connectés", + "adminPanel.dialog.loading": "Chargement des sessions", + "adminPanel.dialog.manage": "Gérer dans les paramètres", + "adminPanel.dialog.protected.body": "Seul un Super Admin peut déconnecter un Super Admin. Ainsi, au moins un Super Admin peut toujours travailler.", + "adminPanel.dialog.protected.title": "Super Admin", + "adminPanel.dialog.title": "Sessions de {name}", + "adminPanel.duration.days": "{count, plural, one {# jour} other {# jours}}", + "adminPanel.duration.hours": "{count, plural, one {# heure} other {# heures}}", + "adminPanel.duration.minutes": "{count, plural, one {# minute} other {# minutes}}", + "adminPanel.empty": "Aucun compte administrateur pour l’instant.", + "adminPanel.error.load": "Les sessions d’administration n’ont pas pu être chargées.", + "adminPanel.filter.all": "Tous les administrateurs", + "adminPanel.filter.label": "État de connexion", + "adminPanel.filter.notSignedIn": "Non connectés", + "adminPanel.filter.signedIn": "Connectés", + "adminPanel.howItWorks.body": "La déconnexion prend effet au prochain clic de l’administrateur : Strapi vérifie la session à chaque requête d’administration. Une nouvelle connexion avec le mot de passe reste possible ; pour l’empêcher, désactivez le compte dans Paramètres > Utilisateurs. Les jetons d’API d’administration ne sont pas concernés. Strapi n’enregistre aucune adresse IP pour les sessions d’administration.", + "adminPanel.howItWorks.policy": "Sans activité, une session se termine après {idle}, ou après {rememberIdle} si « Se souvenir de moi » était coché.", + "adminPanel.howItWorks.title": "Fonctionnement de la déconnexion", + "adminPanel.list.heading": "Liste des administrateurs", + "adminPanel.loading": "Chargement des administrateurs", + "adminPanel.manageUsers": "Gérer les administrateurs", + "adminPanel.noResults": "Aucun administrateur ne correspond à votre recherche ou à votre filtre.", + "adminPanel.noResults.reset": "Effacer les filtres", + "adminPanel.refreshing": "Mise à jour des administrateurs", + "adminPanel.roles.none": "Aucun rôle", + "adminPanel.search.label": "Rechercher des administrateurs", + "adminPanel.search.placeholder": "Rechercher un nom ou un e-mail", + "adminPanel.session.current": "Ce navigateur", + "adminPanel.session.endsAt": "Se termine au plus tard", + "adminPanel.session.lastActiveAt": "Dernière activité", + "adminPanel.session.rememberMe": "Se souvenir de moi", + "adminPanel.session.signOut": "Déconnecter", + "adminPanel.session.signOutLabel": "Déconnecter {name} de {device}", + "adminPanel.session.signedInAt": "Connecté le", + "adminPanel.session.unknownDevice": "Navigateur inconnu", + "adminPanel.signOut.error.forbidden": "Vous n’avez pas l’autorisation de déconnecter des administrateurs.", + "adminPanel.signOut.error.generic": "L’administrateur n’a pas pu être déconnecté. Veuillez réessayer.", + "adminPanel.signOut.error.gone": "Cette session est déjà terminée. La liste est maintenant à jour.", + "adminPanel.signOut.error.protected": "Seul un Super Admin peut déconnecter un Super Admin.", + "adminPanel.signOut.error.rateLimited": "Trop de déconnexions en peu de temps. Attendez une minute et réessayez.", + "adminPanel.signOut.success.all": "{name} a été déconnecté partout.", + "adminPanel.signOut.success.one": "{name} a été déconnecté de {device}.", + "adminPanel.signOut.success.self": "Vous vous êtes déconnecté de ce navigateur. La page de connexion s’ouvre ensuite.", + "adminPanel.stats.active": "{count, plural, one {# compte actif} other {# comptes actifs}}", + "adminPanel.stats.all": "Tous les administrateurs", + "adminPanel.stats.label": "Statistiques des administrateurs", + "adminPanel.stats.notSignedIn": "Non connectés", + "adminPanel.stats.notSignedIn.detail": "Y compris les comptes désactivés et invités", + "adminPanel.stats.sessions": "{count, plural, one {# session} other {# sessions}} au total", + "adminPanel.stats.signedIn": "Administrateurs connectés", + "adminPanel.status.deactivated": "Désactivé", + "adminPanel.status.deactivated.detail": "Ne peut pas se connecter", + "adminPanel.status.invited": "Invité", + "adminPanel.status.invited.detail": "Invitation pas encore acceptée", + "adminPanel.status.notSignedIn": "Non connecté", + "adminPanel.status.notSignedIn.detail": "Aucune session ouverte", + "adminPanel.status.signedIn": "Connecté", + "adminPanel.status.signedIn.detail": "{count, plural, one {# session} other {# sessions}}", + "adminPanel.subtitle": "Qui est connecté à ce panneau d’administration Strapi. Les utilisateurs de votre application se trouvent sous Utilisateurs de l’application.", + "adminPanel.table.actions": "Actions", + "adminPanel.table.admin": "Administrateur", + "adminPanel.table.lastActive": "Dernière activité", + "adminPanel.table.roles": "Rôles", + "adminPanel.table.status": "État", + "adminPanel.title": "Sessions du panneau d’administration", + "adminPanel.unsupported": "Les sessions du panneau d’administration ne sont pas disponibles dans cette version de Strapi. Elles nécessitent Strapi 5 avec la gestion des sessions (testé avec 5.62).", + "adminPanel.you": "Vous", + "views.admins": "Panneau d’administration", + "views.label": "Vues des sessions", + "views.users": "Utilisateurs de l’application" } diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 0c36803..6efab1e 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -531,5 +531,93 @@ "homepage.untracked.summary.mobile": "Celular", "homepage.untracked.summary.unknownDevice": "Dispositivo desconhecido", "homepage.untracked.summary.next": "Sessões criadas depois do início do rastreamento indicam um caminho de login que este plugin não vê: uma rota de login própria, logins via GraphQL ou um plugin que emite tokens. A documentação do plugin explica cada caso. Sessões mais antigas não exigem nenhuma ação.", - "homepage.howItWorks.untracked": "O Strapi também mantém sua própria lista de logins (tokens de atualização). Um login sem detalhes de sessão aqui, por exemplo de antes de este plugin rastrear sessões, não está nesta lista e nunca conta como ativo ou online. Um aviso acima dos cartões mostra quantos existem e por quê." + "homepage.howItWorks.untracked": "O Strapi também mantém sua própria lista de logins (tokens de atualização). Um login sem detalhes de sessão aqui, por exemplo de antes de este plugin rastrear sessões, não está nesta lista e nunca conta como ativo ou online. Um aviso acima dos cartões mostra quantos existem e por quê.", + "adminPanel.actions.refresh": "Atualizar administradores", + "adminPanel.actions.signOutEverywhere": "Encerrar a sessão de {name} em todos os lugares", + "adminPanel.actions.signOutEverywhereShort": "Encerrar sessão em todos os lugares", + "adminPanel.actions.view": "Ver as sessões de {name}", + "adminPanel.actions.viewShort": "Ver sessões", + "adminPanel.caption": "{from, number}–{to, number} de {total, plural, one {# administrador} other {# administradores}}", + "adminPanel.captionNone": "0 administradores", + "adminPanel.confirm.all.body": "Todas as sessões de {name} terminam no próximo clique no painel de administração. Um novo login com a senha continua possível. Para impedi-lo, desative a conta em Configurações > Usuários.", + "adminPanel.confirm.all.title": "Encerrar a sessão de {name} em todos os lugares?", + "adminPanel.confirm.one.body": "A sessão de {name} em {device} termina no próximo clique no painel de administração. Um novo login com a senha continua possível.", + "adminPanel.confirm.one.title": "Encerrar a sessão de {name} neste navegador?", + "adminPanel.confirm.self.title": "Encerrar a sua própria sessão?", + "adminPanel.confirm.self.warning": "Isto inclui o navegador que você está usando agora. Em seguida, a página de login será aberta.", + "adminPanel.dialog.email": "E-mail", + "adminPanel.dialog.empty": "{name} não está conectado. As sessões aparecem aqui após o próximo login.", + "adminPanel.dialog.error": "Não foi possível carregar as sessões.", + "adminPanel.dialog.inactive.body": "O Strapi recusa todas as solicitações de uma conta desativada ou convidada, portanto não há sessão para encerrar.", + "adminPanel.dialog.inactive.title": "Nenhuma sessão utilizável", + "adminPanel.dialog.listLabel": "Navegadores conectados", + "adminPanel.dialog.loading": "Carregando sessões", + "adminPanel.dialog.manage": "Gerenciar nas Configurações", + "adminPanel.dialog.protected.body": "Somente um Super Admin pode encerrar a sessão de um Super Admin. Assim, pelo menos um Super Admin sempre pode trabalhar.", + "adminPanel.dialog.protected.title": "Super Admin", + "adminPanel.dialog.title": "Sessões de {name}", + "adminPanel.duration.days": "{count, plural, one {# dia} other {# dias}}", + "adminPanel.duration.hours": "{count, plural, one {# hora} other {# horas}}", + "adminPanel.duration.minutes": "{count, plural, one {# minuto} other {# minutos}}", + "adminPanel.empty": "Ainda não há contas de administrador.", + "adminPanel.error.load": "Não foi possível carregar as sessões de administração.", + "adminPanel.filter.all": "Todos os administradores", + "adminPanel.filter.label": "Status de login", + "adminPanel.filter.notSignedIn": "Não conectados", + "adminPanel.filter.signedIn": "Conectados", + "adminPanel.howItWorks.body": "O encerramento da sessão vale a partir do próximo clique do administrador: o Strapi verifica a sessão em cada solicitação de administração. Um novo login com a senha continua possível; para impedi-lo, desative a conta em Configurações > Usuários. Os tokens de API de administração não são afetados. O Strapi não registra endereços IP para sessões de administração.", + "adminPanel.howItWorks.policy": "Sem atividade, uma sessão termina após {idle}, ou após {rememberIdle} quando “Lembrar de mim” foi marcado.", + "adminPanel.howItWorks.title": "Como funciona o encerramento de sessão", + "adminPanel.list.heading": "Lista de administradores", + "adminPanel.loading": "Carregando administradores", + "adminPanel.manageUsers": "Gerenciar administradores", + "adminPanel.noResults": "Nenhum administrador corresponde à sua busca ou filtro.", + "adminPanel.noResults.reset": "Limpar filtros", + "adminPanel.refreshing": "Atualizando administradores", + "adminPanel.roles.none": "Sem função", + "adminPanel.search.label": "Buscar administradores", + "adminPanel.search.placeholder": "Buscar nome ou e-mail", + "adminPanel.session.current": "Este navegador", + "adminPanel.session.endsAt": "Termina no máximo em", + "adminPanel.session.lastActiveAt": "Última atividade", + "adminPanel.session.rememberMe": "Lembrar de mim", + "adminPanel.session.signOut": "Encerrar sessão", + "adminPanel.session.signOutLabel": "Encerrar a sessão de {name} em {device}", + "adminPanel.session.signedInAt": "Login em", + "adminPanel.session.unknownDevice": "Navegador desconhecido", + "adminPanel.signOut.error.forbidden": "Você não tem permissão para encerrar sessões de administradores.", + "adminPanel.signOut.error.generic": "Não foi possível encerrar a sessão do administrador. Tente novamente.", + "adminPanel.signOut.error.gone": "Esta sessão já terminou. A lista está atualizada agora.", + "adminPanel.signOut.error.protected": "Somente um Super Admin pode encerrar a sessão de um Super Admin.", + "adminPanel.signOut.error.rateLimited": "Muitos encerramentos de sessão em pouco tempo. Aguarde um minuto e tente novamente.", + "adminPanel.signOut.success.all": "A sessão de {name} foi encerrada em todos os lugares.", + "adminPanel.signOut.success.one": "A sessão de {name} em {device} foi encerrada.", + "adminPanel.signOut.success.self": "Você encerrou a sua sessão neste navegador. Em seguida, a página de login será aberta.", + "adminPanel.stats.active": "{count, plural, one {# conta ativa} other {# contas ativas}}", + "adminPanel.stats.all": "Todos os administradores", + "adminPanel.stats.label": "Estatísticas de administradores", + "adminPanel.stats.notSignedIn": "Não conectados", + "adminPanel.stats.notSignedIn.detail": "Inclui contas desativadas e convidadas", + "adminPanel.stats.sessions": "{count, plural, one {# sessão} other {# sessões}} no total", + "adminPanel.stats.signedIn": "Administradores conectados", + "adminPanel.status.deactivated": "Desativado", + "adminPanel.status.deactivated.detail": "Não pode fazer login", + "adminPanel.status.invited": "Convidado", + "adminPanel.status.invited.detail": "Convite ainda não aceito", + "adminPanel.status.notSignedIn": "Não conectado", + "adminPanel.status.notSignedIn.detail": "Nenhuma sessão aberta", + "adminPanel.status.signedIn": "Conectado", + "adminPanel.status.signedIn.detail": "{count, plural, one {# sessão} other {# sessões}}", + "adminPanel.subtitle": "Quem está conectado a este painel de administração do Strapi. Os usuários do seu aplicativo ficam em Usuários do aplicativo.", + "adminPanel.table.actions": "Ações", + "adminPanel.table.admin": "Administrador", + "adminPanel.table.lastActive": "Última atividade", + "adminPanel.table.roles": "Funções", + "adminPanel.table.status": "Status de login", + "adminPanel.title": "Sessões do painel de administração", + "adminPanel.unsupported": "As sessões do painel de administração não estão disponíveis nesta versão do Strapi. Elas exigem o Strapi 5 com gerenciamento de sessões (testado com 5.62).", + "adminPanel.you": "Você", + "views.admins": "Painel de administração", + "views.label": "Visualizações de sessões", + "views.users": "Usuários do aplicativo" } diff --git a/docs/plans/2026-11-17-admin-panel-sessions-design.md b/docs/plans/2026-11-17-admin-panel-sessions-design.md new file mode 100644 index 0000000..4a3c5e4 --- /dev/null +++ b/docs/plans/2026-11-17-admin-panel-sessions-design.md @@ -0,0 +1,98 @@ +# Admin panel sessions: design + +Date: 2026-11-17. Target release: 4.14.0 (minor, additive). Requested by the owner: "see the admins who are signed in to the Strapi admin panel, and be able to sign them out". + +## 1. Research (installed Strapi 5.62.0, docs checked 2026-11-17) + +Sources: installed `@strapi/core@5.62.0` `dist/services/session-manager.js`, `@strapi/admin@5.62.0` `dist/server/server/src/strategies/admin.js`, `controllers/authentication.js`, `controllers/authenticated-session.js`, `routes/users.js`, `bootstrap.js`, `content-types/session.js`, `shared/utils/session-auth.js`, `@strapi/utils@5.62.0` `dist/sessions.js`; docs https://docs.strapi.io/cms/configurations/admin-panel (Session management) and Context7 `/strapi/documentation`. + +| Question | Answer (5.62.0) | +| ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Where are admin sessions stored? | `admin::session` (`strapi_sessions`), shared with Users & Permissions refresh mode. Admin rows have `origin = 'admin'`. Fields: `userId` (string admin id), `sessionId`, `deviceId` (required), `childId`, `type` (`refresh` = "remember me", `session` = browser session), `status` (`active`, `rotated`), `metadata` (`{ loginAt, deviceName }`), `expiresAt`, `absoluteExpiresAt`, `createdAt`. No IP address and no raw user agent are stored. | +| What is one "signed-in browser"? | One `deviceId`. Every access-token renewal (`POST /admin/access-token`) rotates the refresh record: the old row becomes `rotated` (`childId` set), a new `active` row is created. `createdAt` of the active row is Strapi's own "last active" signal (`sanitizeSessionEntry`). | +| Access token lifespan | `admin.auth.sessions.accessTokenLifespan`, default 1800 s (30 min). Session idle 7200 s (2 h), max 30 days; refresh ("remember me") idle 14 days, max 30 days. | +| Does a revoked admin keep working until the access token expires? | **No.** `strategies/admin.js` calls `sessionManager('admin').isSessionActive(payload.sessionId)` on **every** admin API request. `isSessionActive` returns false when the row is gone. Deleting the rows ends the admin's next request with 401; the panel then fails to renew (`rotateRefreshToken` finds no row) and shows the login page. | +| Pitfall | `isSessionActive` does not check `status`. An older access token whose row is now `rotated` stays valid until that token's `exp` (up to `accessTokenLifespan`) if only the `active` row is deleted (`revokeSessionById`). So the plugin deletes **every row of the device** (`invalidateRefreshToken(userId, deviceId)`, the same call Strapi's own logout makes). Then no access token of that browser survives. | +| "Sign out everywhere" | `invalidateRefreshToken(userId)` deletes every admin row of that admin (Strapi logout without deviceId does the same). | +| Last sign-in | Strapi stores no "last login" on `admin::user`. `metadata.loginAt` exists only while a session row exists. The view shows "Not signed in" without a date. | +| Strapi's own UI | 5.62 has `GET/DELETE /admin/users/me/sessions` for the signed-in admin's **own** sessions only. Nothing lists or ends other admins' sessions. | +| Admin API tokens | `admin-token` strategy, independent of sessions. Signing out does not revoke admin API tokens; the docs and dialog say so. | + +## 2. Current state + +- Dashboard, widget, Analytics and the side panel cover Users & Permissions sessions only. The dashboard subtitle says "Strapi administrators are not listed." +- `countNativeOnly` (4.13.0) filters `origin = 'users-permissions'`, so admin rows never enter end-user numbers. This must stay so (regression tests added). +- RBAC: one action `plugin::magic-sessionmanager.access`. + +## 3. Target state + +### 3.1 IA + +- The plugin page gets a two-item view switch below the header: **App users** (existing dashboard, unchanged) and **Admin panel** (new route `plugins/magic-sessionmanager/admin-panel`). The switch is a `nav` with two links (`aria-current="page"`), shown only to admins who may read admin sessions. Admin numbers never appear on the App users view and vice versa. +- Question the Admin panel view answers: "Who can use this admin panel, who is signed in right now, and how do I sign someone out?" +- Glossary: **Admin** (Strapi admin account), **Signed in** (has at least one live admin session), **Session** (one signed-in browser), **Sign out** (end one session), **Sign out everywhere** (end all sessions of one admin). "End" stays reserved for app-user sessions, "Deactivate" belongs to Strapi's Settings > Users. + +### 3.2 Screen + +1. Header: title "Admin panel sessions", subtitle "Who is signed in to this Strapi admin panel. Your app's users are under App users." +2. View switch. +3. Three stat cards (count-only, never mixed with user numbers): **Signed-in admins**, **Admin sessions** (signed-in browsers), **Active admin accounts**. Clicking a card filters the list. +4. Info card: "Signing out takes effect on the admin's next click: Strapi checks the session on every admin request. They can sign in again with their password. To stop someone from signing in, deactivate them in Settings > Users." plus link to `/settings/users`. Also states that admin API tokens are not affected and that Strapi records no IP address for admin sessions. +5. Toolbar: search (name or email), filter (All admins, Signed in, Not signed in), Refresh. +6. List: table at >= medium, cards below. Columns: Admin (name, email, "You" badge), Roles, Status (Signed in · N sessions / Not signed in / Deactivated / Invited), Last active, Actions (View sessions, Sign out everywhere). Pagination (10/25/50/100), state in the URL. +7. Sessions dialog per admin: one row per browser: device ("Chrome on macOS" from Strapi, or "Unknown browser"), signed in, last active, ends at the latest (idle/absolute expiry), "Remember me" badge, "This browser" badge. Action: Sign out. Footer: Sign out everywhere, link "Manage in Settings > Users". + +States: first load (`Page.Loading`-style loader), refresh (inline, list stays mounted), empty (only happens when filter/search excludes everyone: "No admins match your search or filter." + Clear filters), error ("Admin sessions could not be loaded." + Try again, last data kept on refresh), no permission (`Page.NoPermissions` on the route; switch hidden), unsupported host (`strapi.sessionManager` missing: explanation, no actions). + +### 3.3 Actions and foot-guns + +| Action | Dialog title | Body | Confirm | +| ------------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | +| Sign out one session | "Sign out of this browser?" | "{name} is signed out of {device} on their next click in the admin panel. They can sign in again with their password." | Sign out | +| Sign out everywhere | "Sign out {name} everywhere?" | "All {count} sessions end on {name}'s next click. They can sign in again with their password. To block access, deactivate the account in Settings > Users." | Sign out everywhere | +| Self (current browser included) | "Sign yourself out?" | warning alert: "This includes this browser. You will be taken to the login page." | Sign out | + +Guards (server-side, mirrored in the UI with a disabled button and a reason): + +- **Super Admins are protected from delegated roles.** An actor without the Super Admin role cannot sign out a Super Admin (403). This also guarantees the last active Super Admin can never be signed out by someone else. A Super Admin may sign themselves out (warning shown). +- Revoke requires a person in the browser (`ctx.state.auth.strategy.name === 'admin'`); admin API tokens get 403. +- No action on deactivated or invited accounts (Strapi already rejects their requests); Settings > Users link instead. + +### 3.4 API (admin router, prefix `/magic-sessionmanager`) + +| Method, path | Policies | Rate limit | Response | +| ------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------- | +| `GET /admin-sessions/admins?page&pageSize&search&filter` | `isAuthenticatedAdmin`, `hasPermissions [access, admin-sessions.read]` | read 120/min | `{ data: AdminRow[], meta: { pagination, stats, policy, viewer } }` | +| `GET /admin-sessions/admins/:adminId/sessions` | same | read | `{ data: SessionRow[], meta: { admin } }`; 404 for unknown admin | +| `POST /admin-sessions/admins/:adminId/sessions/:sessionId/sign-out` | `[access, admin-sessions.read, admin-sessions.revoke]` | write 10/min | `{ data: { ended, signedOutSelf } }`; 404 unknown admin or session (also "session of another admin"); 403 guard | +| `POST /admin-sessions/admins/:adminId/sign-out-everywhere` | same | write 10/min | `{ data: { ended, signedOutSelf } }` | + +- `AdminRow`: `{ id, name, email, roles: [{ name, superAdmin }], account: 'active'|'deactivated'|'invited', self, sessionCount, lastActiveAt, canSignOut, protectedReason }`. +- `SessionRow`: `{ id (sessionId of the newest active row), device, signedInAt, lastActiveAt, endsAt, rememberMe, current }`. Never tokens, `deviceId`, `childId`, hashes or numeric row ids. +- Validation: zod strict query (page 1..1e6, pageSize 1..100, search <= 100, filter enum), `adminId` `^[0-9]{1,12}$`, `sessionId` `^[a-f0-9]{32}$` (Strapi's `randomBytes(16).hex`). 400 with field errors. +- Audit: `strapi.log.info('[magic-sessionmanager] admin sign-out', { actorId, targetId, scope, ended })` (admin numeric ids only, no email, no session id, no token). Also `strapi.eventHub.emit('magic-sessionmanager.admin-sessions.signed-out', same payload)` for hosts that forward audit events. +- Unsupported host (no `strapi.sessionManager`, no `admin` origin): GET returns `meta.supported = false` and empty data; POST returns 503 "Admin session management is not available on this Strapi version.". +- RBAC actions `admin-sessions.read` ("Read admin panel sessions") and `admin-sessions.revoke` ("Sign out admins"), subCategory "Admin panel". Strapi grants every registered action to Super Admin at boot; other roles get nothing until granted. + +### 3.5 Click paths (from the plugin entry page) + +| Task | Steps | +| ----------------------------- | ----------------------------------------------------------------------------- | +| See who is signed in | 1: Admin panel | +| Sign out one admin everywhere | 1: Admin panel, 2: Sign out everywhere (row), + confirm | +| Sign out one browser | 1: Admin panel, 2: View sessions, 3: Sign out, + confirm | +| Find an admin | 1: Admin panel, 2: type in search | +| Deactivate an admin | 1: Admin panel, 2: View sessions, 3: Manage in Settings > Users (Strapi page) | + +## 4. Non-goals + +- No storage of admin IPs, user agents or login history; the plugin reads what Strapi stores. +- No deactivation, role change or password reset (Strapi's Settings > Users does that). +- No change to App users routes, numbers, widget, side panel, settings or content-API features. + +## 5. Tests + +- Unit: query parsing, grouping by device, status mapping, guards, DTO allowlist (no token/hash/deviceId), audit log content, route policy matrix. +- Regression: dashboard stats, widget user stats and untracked-session counts unchanged with admin rows present. +- Integration (real Strapi 5.62.0, SQLite and PostgreSQL): admins signed in through `POST /admin/login`; list, sign out one, sign out everywhere, self sign-out flag, Super Admin guard, RBAC denial for an Editor and for a role with read only, access token rejected on the next request, refresh (`POST /admin/access-token`) rejected, old access token of a rotated row rejected. +- Browser acceptance on an isolated 5.62.0 host from the packed tarball. diff --git a/docs/site/img/admin-panel-confirm.webp b/docs/site/img/admin-panel-confirm.webp new file mode 100644 index 0000000..b6de462 Binary files /dev/null and b/docs/site/img/admin-panel-confirm.webp differ diff --git a/docs/site/img/admin-panel-dark.webp b/docs/site/img/admin-panel-dark.webp new file mode 100644 index 0000000..fa522ff Binary files /dev/null and b/docs/site/img/admin-panel-dark.webp differ diff --git a/docs/site/img/admin-panel-mobile.webp b/docs/site/img/admin-panel-mobile.webp new file mode 100644 index 0000000..a053048 Binary files /dev/null and b/docs/site/img/admin-panel-mobile.webp differ diff --git a/docs/site/img/admin-panel-sessions.webp b/docs/site/img/admin-panel-sessions.webp new file mode 100644 index 0000000..dccdd0b Binary files /dev/null and b/docs/site/img/admin-panel-sessions.webp differ diff --git a/docs/site/img/admin-panel-signed-out.webp b/docs/site/img/admin-panel-signed-out.webp new file mode 100644 index 0000000..98f345f Binary files /dev/null and b/docs/site/img/admin-panel-signed-out.webp differ diff --git a/docs/site/img/admin-panel.webp b/docs/site/img/admin-panel.webp new file mode 100644 index 0000000..3be2a55 Binary files /dev/null and b/docs/site/img/admin-panel.webp differ diff --git a/docs/site/index.html b/docs/site/index.html index 1cecd1a..de1da08 100644 --- a/docs/site/index.html +++ b/docs/site/index.html @@ -280,6 +280,14 @@

Online users widget

users, Active sessions, Idle sessions and Blocked users, refreshed every 30 seconds.

+
+

Admin panel sessions

+

+ Who can use the Strapi admin panel and who is signed in, on which browser and since + when. Sign an admin out of one browser or everywhere; it takes effect on their next + click. Separate from your app's users, Super Admin only by default. +

+

Configuration

@@ -438,6 +446,61 @@

Screenshots

/>
Online users widget
+
+ Admin panel sessions: view switch App users and Admin panel, cards Signed-in admins, Not signed in and All admins, how signing out works, search, a sign-in status filter and a table of admins with roles, status and last activity. +
Admin panel sessions (Strapi 5.62)
+
+
+ Sessions of one admin: every signed-in browser with device, signed in, last active and latest end, Sign out per browser, Sign out everywhere and Manage in Settings. +
Sessions of one admin
+
+
+ Confirmation: Sign Clara Muster out of this browser? She is signed out on her next click and can sign in again with her password. +
Sign-out confirmation
+
+
+ The signed-out admin after the next click: the Strapi login page. +
What the signed-out admin sees
+
+
+ Admin panel sessions in the Strapi dark theme. +
Admin panel sessions in dark mode
+

Mobile, 390 px

@@ -464,6 +527,17 @@

Mobile, 390 px

/>
Session details on a phone
+
+ Admin panel sessions at 390 px wide: the table becomes a card list with View sessions and Sign out everywhere buttons. +
Admin panel sessions on a phone
+
@@ -682,7 +756,11 @@

API and permissions

Admin routes live under /magic-sessionmanager in the Strapi admin API. Each one requires an authenticated admin and the permission plugin::magic-sessionmanager.access, which also controls the menu link, - settings links, widget and user panel. + settings links, widget and user panel. The admin panel session routes also need + plugin::magic-sessionmanager.admin-sessions.read ("Read admin panel + sessions"), and signing out + plugin::magic-sessionmanager.admin-sessions.revoke + ("Sign out admins"). Only Super Admin has both by default.

@@ -769,6 +847,25 @@

API and permissions

+ + + + + + + + + +
/settings Configuration
GET + /admin-sessions/admins, + /admin-sessions/admins/:adminId/sessions + Admin panel view and View sessions (admin-sessions.read)
POST + /admin-sessions/admins/:adminId/sessions/:sessionId/sign-out, + /admin-sessions/admins/:adminId/sign-out-everywhere + + Sign out, Sign out everywhere (admin-sessions.revoke; signed-in + admins only; 10 per minute; a delegated role cannot sign out a Super Admin) +
@@ -882,8 +979,12 @@

Secrets

- Strapi administrator sessions are out of scope. To report a vulnerability, do not post - exploit details publicly: open a + Signing out an admin deletes Strapi's own session records of that browser (or of every + browser). Strapi 5.62 checks the admin session on every admin request, so the admin is + signed out on their next click, without waiting for the access token to expire. Admin + API tokens are not affected. The plugin stores nothing about admins, and Strapi records + no IP address for admin sessions. Every sign-out is logged with admin ids and counts + only. To report a vulnerability, do not post exploit details publicly: open a GitHub issue that asks for a private contact, without credentials or personal data.

@@ -1060,8 +1161,17 @@

FAQ

Does it manage Strapi admin accounts?

- No. It manages end users of Users & Permissions. Strapi administrator sessions are - out of scope. + It shows who is signed in to the Strapi admin panel and signs admins out (the Admin + panel view). Creating, editing and deactivating admins stays in Strapi's Settings › + Users. Everything else is about end users of Users & Permissions. +

+
+
+ When does signing out an admin take effect? +

+ On the admin's next request, usually their next click: Strapi 5.62 checks the session + on every admin request. They can sign in again with their password unless you + deactivate the account in Settings › Users.

diff --git a/gates/admin-sessions.md b/gates/admin-sessions.md new file mode 100644 index 0000000..2723f38 --- /dev/null +++ b/gates/admin-sessions.md @@ -0,0 +1,38 @@ +# Admin panel sessions (4.14.0) + +Branch `feat/admin-sessions`, 2026-11-17. Design: `docs/plans/2026-11-17-admin-panel-sessions-design.md`. Synthetic data only (`*.example.test`); no production database was read. + +## Fact: when does a revoked admin stop working? + +Strapi 5.62.0 `@strapi/admin/dist/server/server/src/strategies/admin.js` calls `sessionManager('admin').isSessionActive(payload.sessionId)` on every admin request; `@strapi/core/dist/services/session-manager.js` `isSessionActive` returns false once the row is gone. So a sign-out takes effect on the admin's next request, not after `accessTokenLifespan` (default 1800 s). `isSessionActive` does not check `status`, so an access token bound to a `rotated` row survives `revokeSessionById` (which deletes only the active row) until its own expiry; the plugin therefore deletes every row of the device (`invalidateRefreshToken(userId, deviceId)`). + +- [x] Proven over HTTP: `tests/isolated-admin-sessions-http.test.js` subtests "sign out one browser: next request 401, renewal 401" and "Strapi revokeSessionById alone leaves a rotated access token valid". +- [x] Proven in the browser: the signed-out admin's next click (Media Library) ended on `/admin/auth/login` after 802 ms; the panel's own `/admin/access-token` renewal answered 401. + +## Tests + +- [x] `npm test`: 849 pass, 0 fail, 0 skipped (local run includes the host-dependent suites against the workbench test-app, Strapi 5.58). +- [x] `tests/isolated-admin-sessions-http.test.js` against this repo's Strapi 5.62.0: SQLite 14/14, PostgreSQL 16 14/14 (13 subtests plus the suite) (admins signed in through `POST /admin/login`). +- [x] `tests/isolated-http-access.test.js` against Strapi 5.62.0: legacy 37/37, refresh 39/39 (route inventory updated to 25 dev routes). +- [x] `npm run lint`, `npm run format:check`, `test:ts:front`, `test:ts:back`, `build`, `verify`, `verify:runtime` clean. +- [x] `npm audit --omit=dev`: unchanged baseline, 5 high, all picomatch GHSA-fc5q-39xc-vjpf through `@strapi/utils` (documented in the README); the new devDependency `@strapi/plugin-users-permissions` 5.62.0 is not in the production tree. + +## Browser acceptance + +Isolated host 127.0.0.1:1387, Strapi 5.62.0, packed tarball, SQLite, `jwtManagement: 'refresh'`, random secrets, egress blocked (only expected attempt: `api.github.com` releases, blocked). Playwright 1.65.1, Chromium; `measure.js` from the workbench skill. Fixtures: 29 synthetic admins (Super Admin, Editor, Author, a read-only role, a delegated revoker role, one invited, one deactivated). + +- [x] Matrix: 5 screens (App users view, admin list, sessions dialog, own sessions dialog, sign-out-everywhere confirmation) x 10 widths (1440, 1280, 1080, 1079, 1024, 768, 767, 520, 390, 320) x light/dark = 100 stops. documentOverflow 0, rowHeightMismatch, offScaleGaps, clippedText, smallTargets, lowContrast, elementsOutsideViewport all empty, no action outside the viewport, no inner horizontal scroll. +- [x] Fixed during acceptance: DS primary badge 2.43:1 in dark ("You", "This browser"); confirmation body without `Dialog.Description` (Radix warning); filter select not full width at 390/320. +- [x] Note: once a light-theme stop at 768 measured the DS danger button at 3.3:1 because the mouse hovered it after the click that opened the dialog (DS hover colour); re-measured 0 findings with the pointer moved away. +- [x] Click paths (24/24 checks): see who is signed in 1, find an admin 2, sign one browser out 3 + confirm, sign out everywhere 2 + confirm, self sign-out 3 + confirm (warning shown, Cancel returns focus to the trigger), deactivate via Strapi 3. +- [x] Second browser (Clara, Chrome): working before; after the sign-out her next click lands on the login page. +- [x] States: load error with Try again (mocked 500), retry loads; unsupported host (mocked); no results with Clear filters; read-only role sees no sign-out buttons; delegated role sees no sign-out for Super Admins and an explanation; Editor without plugin access gets Strapi's no-permission page and no menu link. +- [x] Keyboard: 45 Tab stops, focus never lost on the page (BODY only when the browser wraps past the document end); Escape closes the dialog and focus returns to "View sessions"; after "Sign out everywhere" focus moves to the list caption. Search input and Strapi pagination links show their focus ring on a wrapper or pseudo-element (DS / Strapi components), not on the element itself. +- [x] Locales de, fr, es, pt at 1440 and 320: no ICU or id leaks, no English, overflow 0, no clipping, no low contrast. +- [x] Console: 0 plugin messages, except the deliberate `[adminPanel.load] Request failed (HTTP 500)` warning for the mocked load error. Core: `useRBAC` object warning and React Router future-flag warning (also on `/admin/auth/login` and native pages). Egress: blocked `api.github.com`. Expected: 401s in the signed-out browser. +- [x] Screenshots for README and Pages from the same synthetic host, opened and checked (no real data, no tokens, `127.0.0.1` only): `docs/site/img/admin-panel*.webp` (240 KB total). + +## Open + +- [ ] CI on the pull request (the workflow runs on `pull_request` only). +- [ ] MySQL: not run (no local server). The queries use the Query Engine only (`$in`, `$notIn`, `$containsi`, `$null`, `$gt`). diff --git a/package-lock.json b/package-lock.json index 9e0d546..430dbdb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,7 @@ "@semantic-release/release-notes-generator": "^14.1.1", "@strapi/design-system": "^2.3.1", "@strapi/icons": "^2.3.1", + "@strapi/plugin-users-permissions": "^5.62.0", "@strapi/sdk-plugin": "^6.1.1", "@strapi/strapi": "^5.62.0", "better-sqlite3": "^13.0.3", @@ -10058,6 +10059,213 @@ "npm": ">=6.0.0" } }, + "node_modules/@strapi/plugin-users-permissions": { + "version": "5.62.0", + "resolved": "https://registry.npmjs.org/@strapi/plugin-users-permissions/-/plugin-users-permissions-5.62.0.tgz", + "integrity": "sha512-i8uA994ky5RLm1fQ+DDnzxkQP8aJ0Ys+TcoUV2+55E9OLrUhq/UBUOm3ENA4xTn1VYA+5sA1r+rOhGGdGAxU+g==", + "dev": true, + "license": "SEE LICENSE IN LICENSE", + "dependencies": { + "@strapi/design-system": "2.3.1", + "@strapi/icons": "2.3.1", + "@strapi/utils": "5.62.0", + "bcryptjs": "2.4.3", + "formik": "2.4.9", + "immer": "9.0.21", + "jsonwebtoken": "9.0.3", + "koa": "2.16.4", + "koa2-ratelimit": "^1.1.3", + "lodash": "4.18.1", + "prop-types": "^15.8.1", + "react-intl": "6.6.2", + "react-query": "3.39.3", + "react-redux": "8.1.3", + "url-join": "4.0.1", + "yup": "0.32.9", + "zod": "4.4.3" + }, + "engines": { + "node": ">=22.0.0 <=26.x.x", + "npm": ">=6.0.0" + }, + "peerDependencies": { + "@strapi/admin": "^5.0.0", + "@strapi/strapi": "^5.0.0", + "react": "^18.0.0", + "react-dom": "^18.0.0", + "react-router-dom": "^6.30.3", + "styled-components": "^6.0.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/ecma402-abstract": { + "version": "1.18.2", + "resolved": "https://registry.npmjs.org/@formatjs/ecma402-abstract/-/ecma402-abstract-1.18.2.tgz", + "integrity": "sha512-+QoPW4csYALsQIl8GbN14igZzDbuwzcpWrku9nyMXlaqAlwRBgl5V+p0vWMGFqHOw37czNXaP/lEk4wbLgcmtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/intl-localematcher": "0.5.4", + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/fast-memoize": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@formatjs/fast-memoize/-/fast-memoize-2.2.0.tgz", + "integrity": "sha512-hnk/nY8FyrL5YxwP9e4r9dqeM6cAbo8PeU9UjyXojZMNvVad2Z06FAVHyR3Ecw6fza+0GH7vdJgiKIVXTMbSBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/icu-messageformat-parser": { + "version": "2.7.6", + "resolved": "https://registry.npmjs.org/@formatjs/icu-messageformat-parser/-/icu-messageformat-parser-2.7.6.tgz", + "integrity": "sha512-etVau26po9+eewJKYoiBKP6743I1br0/Ie00Pb/S/PtmYfmjTcOn2YCh2yNkSZI12h6Rg+BOgQYborXk46BvkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "@formatjs/icu-skeleton-parser": "1.8.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/icu-skeleton-parser": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@formatjs/icu-skeleton-parser/-/icu-skeleton-parser-1.8.0.tgz", + "integrity": "sha512-QWLAYvM0n8hv7Nq5BEs4LKIjevpVpbGLAJgOaYzg9wABEoX1j0JO1q2/jVkO6CVlq0dbsxZCngS5aXbysYueqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/intl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/@formatjs/intl/-/intl-2.10.0.tgz", + "integrity": "sha512-X3xT9guVkKDS86EKV80lS0KxoazUglkJTGZO66sKY7otgl0VeStPA8B3u8UkKT47PexVV98fUzjpkchYmbe9nw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "@formatjs/fast-memoize": "2.2.0", + "@formatjs/icu-messageformat-parser": "2.7.6", + "@formatjs/intl-displaynames": "6.6.6", + "@formatjs/intl-listformat": "7.5.5", + "intl-messageformat": "10.5.11", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "typescript": "^4.7 || 5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/intl-displaynames": { + "version": "6.6.6", + "resolved": "https://registry.npmjs.org/@formatjs/intl-displaynames/-/intl-displaynames-6.6.6.tgz", + "integrity": "sha512-Dg5URSjx0uzF8VZXtHb6KYZ6LFEEhCbAbKoYChYHEOnMFTw/ZU3jIo/NrujzQD2EfKPgQzIq73LOUvW6Z/LpFA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "@formatjs/intl-localematcher": "0.5.4", + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/intl-listformat": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@formatjs/intl-listformat/-/intl-listformat-7.5.5.tgz", + "integrity": "sha512-XoI52qrU6aBGJC9KJddqnacuBbPlb/bXFN+lIFVFhQ1RnFHpzuFrlFdjD9am2O7ZSYsyqzYRpkVcXeT1GHkwDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "@formatjs/intl-localematcher": "0.5.4", + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/@formatjs/intl-localematcher": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/@formatjs/intl-localematcher/-/intl-localematcher-0.5.4.tgz", + "integrity": "sha512-zTwEpWOzZ2CiKcB93BLngUX59hQkuZjT2+SAQEscSm52peDW/getsawMcWF1rGRpMCX6D7nSJA3CzJ8gn13N/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/intl-messageformat": { + "version": "10.5.11", + "resolved": "https://registry.npmjs.org/intl-messageformat/-/intl-messageformat-10.5.11.tgz", + "integrity": "sha512-eYq5fkFBVxc7GIFDzpFQkDOZgNayNTQn4Oufe8jw6YY6OHVw70/4pA3FyCsQ0Gb2DnvEJEMmN2tOaXUGByM+kg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "@formatjs/fast-memoize": "2.2.0", + "@formatjs/icu-messageformat-parser": "2.7.6", + "tslib": "^2.4.0" + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/react-intl": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/react-intl/-/react-intl-6.6.2.tgz", + "integrity": "sha512-IpW2IkLtGENSFlX3vfH11rjuCIsW0VyjT0Q1pPKMZPtT2z1FxLt4weFT5Ezti2TScT1xiyb3aQBFth9EB7jzAg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@formatjs/ecma402-abstract": "1.18.2", + "@formatjs/icu-messageformat-parser": "2.7.6", + "@formatjs/intl": "2.10.0", + "@formatjs/intl-displaynames": "6.6.6", + "@formatjs/intl-listformat": "7.5.5", + "@types/hoist-non-react-statics": "^3.3.1", + "@types/react": "16 || 17 || 18", + "hoist-non-react-statics": "^3.3.2", + "intl-messageformat": "10.5.11", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "react": "^16.6.0 || 17 || 18", + "typescript": "^4.7 || 5" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/url-join": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", + "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@strapi/plugin-users-permissions/node_modules/yup": { + "version": "0.32.9", + "resolved": "https://registry.npmjs.org/yup/-/yup-0.32.9.tgz", + "integrity": "sha512-Ci1qN+i2H0XpY7syDQ0k5zKQ/DoxO0LzPg8PAR/X4Mpj6DqaeCoIYEEjDJwhArh3Fa7GWbQQVDZKeXYlSH4JMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.10.5", + "@types/lodash": "^4.14.165", + "lodash": "^4.17.20", + "lodash-es": "^4.17.15", + "nanoclone": "^0.2.1", + "property-expr": "^2.0.4", + "toposort": "^2.0.2" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/@strapi/provider-email-sendmail": { "version": "5.62.0", "resolved": "https://registry.npmjs.org/@strapi/provider-email-sendmail/-/provider-email-sendmail-5.62.0.tgz", diff --git a/package.json b/package.json index d6e3e34..76a84eb 100644 --- a/package.json +++ b/package.json @@ -80,6 +80,7 @@ "@semantic-release/release-notes-generator": "^14.1.1", "@strapi/design-system": "^2.3.1", "@strapi/icons": "^2.3.1", + "@strapi/plugin-users-permissions": "^5.62.0", "@strapi/sdk-plugin": "^6.1.1", "@strapi/strapi": "^5.62.0", "better-sqlite3": "^13.0.3", diff --git a/scripts/check-i18n.mjs b/scripts/check-i18n.mjs index 182c499..9d62cb0 100644 --- a/scripts/check-i18n.mjs +++ b/scripts/check-i18n.mjs @@ -41,6 +41,8 @@ export const NAMESPACES = [ 'analytics', 'settings', 'notifications', + 'adminPanel', + 'views', ]; const ID = String.raw`(?:${NAMESPACES.join('|')})(?:\.[A-Za-z0-9_-]+)+`; diff --git a/server/src/controllers/admin-sessions.js b/server/src/controllers/admin-sessions.js new file mode 100644 index 0000000..ee8ea2d --- /dev/null +++ b/server/src/controllers/admin-sessions.js @@ -0,0 +1,197 @@ +'use strict'; + +// @ts-check + +/** @import { Context } from 'koa' */ + +const { + AdminSignOutError, + adminParamsSchema, + listAdminSessions, + listAdmins, + listQuerySchema, + parseInput, + sessionParamsSchema, + signOutAdmin, +} = require('../utils/admin-sessions'); +const { sendServerError, sendValidationError } = require('../utils/http-errors'); +const { createLogger } = require('../utils/logger'); + +/** + * The caller as the admin-session helpers need it: id, roles and the session + * that backs this request (set by Strapi's `admin` auth strategy). + * + * @param {Context} ctx Koa context. + * @returns {{id: any, roles: any[], sessionId: string|null}} Caller. + */ +function actorFrom(ctx) { + const user = ctx.state?.user || {}; + const session = ctx.state?.session; + return { + id: user.id, + roles: Array.isArray(user.roles) ? user.roles : [], + sessionId: typeof session?.id === 'string' ? session.id : null, + }; +} + +/** + * Picks the named route parameters. Koa's router can add positional keys + * (for example `0`) to `ctx.params`, so the strict schemas see only the + * parameters this route declares. + * + * @param {Context} ctx Koa context. + * @param {string[]} names Declared parameter names. + * @returns {Record} Named parameters. + */ +function routeParams(ctx, names) { + /** @type {Record} */ + const out = {}; + const params = /** @type {any} */ (ctx).params || {}; + for (const name of names) out[name] = params[name]; + return out; +} + +/** + * Admin panel session endpoints. Every route is admin-only and gated by + * `plugin::magic-sessionmanager.access` plus `admin-sessions.read`; the + * sign-out routes also need `admin-sessions.revoke` (see routes/admin.js). + * + * @param {{strapi: any}} deps Strapi instance. + * @returns {Record Promise>} Controller actions. + */ +module.exports = ({ strapi }) => { + const log = createLogger(strapi); + + /** + * Maps a failure to the response. Known sign-out errors keep their status + * and fixed message; anything else is a 500 without details. + * + * @param {Context} ctx Koa context. + * @param {unknown} error Thrown value. + * @param {string} operation Name for the log line. + * @returns {unknown} Response helper result. + */ + const fail = (ctx, error, operation) => { + if (error instanceof AdminSignOutError) { + if (error.status === 404) return ctx.notFound(error.message); + if (error.status === 403) return ctx.forbidden(error.message, { reason: error.reason }); + return sendServerError(ctx, 503, error.message); + } + log.error(`Admin sessions: ${operation} failed`, /** @type {any} */ (error)?.name || 'Error'); + return sendServerError(ctx, 500, 'Admin sessions could not be processed.'); + }; + + return { + /** + * Lists admin users with their live admin-panel sessions summary. + * + * @route GET /magic-sessionmanager/admin-sessions/admins + * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-sessions.read; + * read rate limit. + * @param {Context} ctx Reads `ctx.query.page` (1..1e6), `pageSize` (1..100), `search` + * (<= 100 chars, name or email) and `filter` (`all`|`signed-in`|`not-signed-in`). + * @returns {Promise} 200 `{ data: AdminRow[], meta: { supported, pagination, stats, + * policy, truncated } }`; 400 ValidationError with field errors; 500 fixed message. + */ + async listAdmins(ctx) { + const parsed = parseInput(listQuerySchema, ctx.query); + if (!parsed.ok) return sendValidationError(ctx, 'Invalid query', parsed.errors); + try { + ctx.body = await listAdmins(strapi, parsed.value, actorFrom(ctx)); + return ctx.body; + } catch (error) { + return fail(ctx, error, 'list'); + } + }, + + /** + * Lists the live sessions (one per signed-in browser) of one admin. + * + * @route GET /magic-sessionmanager/admin-sessions/admins/:adminId/sessions + * @auth Admin JWT or admin API token; admin::hasPermissions access + admin-sessions.read; + * read rate limit. + * @param {Context} ctx Reads `ctx.params.adminId` (positive integer). + * @returns {Promise} 200 `{ data: SessionRow[], meta: { supported, admin, policy } }`; + * 400 invalid id; 404 unknown admin; 500 fixed message. No tokens, device ids or hashes. + */ + async listAdminSessions(ctx) { + const parsed = parseInput(adminParamsSchema, routeParams(ctx, ['adminId'])); + if (!parsed.ok) return sendValidationError(ctx, 'Invalid parameters', parsed.errors); + try { + const body = await listAdminSessions(strapi, parsed.value.adminId, actorFrom(ctx)); + if (!body) return ctx.notFound('Admin not found'); + ctx.body = body; + return ctx.body; + } catch (error) { + return fail(ctx, error, 'sessions'); + } + }, + + /** + * Signs one admin out of one browser. + * + * @route POST /magic-sessionmanager/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out + * @auth Admin JWT only (admin API tokens get 403); admin::hasPermissions access + + * admin-sessions.read + admin-sessions.revoke; write rate limit (10/min per admin). + * A Super Admin can only be signed out by a Super Admin or themselves. + * @param {Context} ctx Reads `ctx.params.adminId` and `ctx.params.sessionId` (32 hex chars). + * @returns {Promise} 200 `{ data: { ended, signedOutSelf } }`; 400 invalid params; + * 403 not a browser session or Super Admin guard; 404 unknown admin, or a session that is + * not a live session of that admin; 503 no session manager; 500 fixed message. + * @sideeffect Deletes the target browser's `admin::session` rows; writes an audit log line. + */ + async signOutSession(ctx) { + if (ctx.state?.auth?.strategy?.name !== 'admin') { + return ctx.forbidden('Sign in to the admin panel to sign admins out.', { + reason: 'browser-session-required', + }); + } + const parsed = parseInput(sessionParamsSchema, routeParams(ctx, ['adminId', 'sessionId'])); + if (!parsed.ok) return sendValidationError(ctx, 'Invalid parameters', parsed.errors); + try { + const result = await signOutAdmin(strapi, { + actor: actorFrom(ctx), + adminId: parsed.value.adminId, + sessionId: parsed.value.sessionId, + }); + ctx.body = { data: { ended: result.ended, signedOutSelf: result.signedOutSelf } }; + return ctx.body; + } catch (error) { + return fail(ctx, error, 'sign-out'); + } + }, + + /** + * Signs one admin out of every browser. + * + * @route POST /magic-sessionmanager/admin-sessions/admins/:adminId/sign-out-everywhere + * @auth Admin JWT only (admin API tokens get 403); admin::hasPermissions access + + * admin-sessions.read + admin-sessions.revoke; write rate limit (10/min per admin). + * A Super Admin can only be signed out by a Super Admin or themselves. + * @param {Context} ctx Reads `ctx.params.adminId`. + * @returns {Promise} 200 `{ data: { ended, signedOutSelf } }`; 400 invalid id; + * 403 not a browser session or Super Admin guard; 404 unknown admin; 503 no session + * manager; 500 fixed message. + * @sideeffect Deletes every `admin::session` row of the target admin; writes an audit log line. + */ + async signOutEverywhere(ctx) { + if (ctx.state?.auth?.strategy?.name !== 'admin') { + return ctx.forbidden('Sign in to the admin panel to sign admins out.', { + reason: 'browser-session-required', + }); + } + const parsed = parseInput(adminParamsSchema, routeParams(ctx, ['adminId'])); + if (!parsed.ok) return sendValidationError(ctx, 'Invalid parameters', parsed.errors); + try { + const result = await signOutAdmin(strapi, { + actor: actorFrom(ctx), + adminId: parsed.value.adminId, + }); + ctx.body = { data: { ended: result.ended, signedOutSelf: result.signedOutSelf } }; + return ctx.body; + } catch (error) { + return fail(ctx, error, 'sign-out-everywhere'); + } + }, + }; +}; diff --git a/server/src/controllers/index.js b/server/src/controllers/index.js index 9840dd1..a2a5419 100644 --- a/server/src/controllers/index.js +++ b/server/src/controllers/index.js @@ -3,9 +3,11 @@ const session = require('./session'); const settings = require('./settings'); const geoip = require('./geoip'); +const adminSessions = require('./admin-sessions'); module.exports = { session, settings, geoip, + 'admin-sessions': adminSessions, }; diff --git a/server/src/register.js b/server/src/register.js index bcd56a2..95eb75a 100644 --- a/server/src/register.js +++ b/server/src/register.js @@ -9,7 +9,9 @@ const USER_UID = 'plugin::users-permissions.user'; /** * Plugin register hook. * - * - Registers the `access` RBAC action for admin access control. + * - Registers the `access` RBAC action for admin access control and the + * `admin-sessions.read` / `admin-sessions.revoke` actions for the Strapi + * admin panel sessions view. * - Removes the `sessions` relation field from the User content type so it * doesn't clutter the default edit view (sessions are displayed via the * SessionInfoPanel side panel). @@ -35,6 +37,23 @@ module.exports = async ({ strapi }) => { subCategory: 'General', pluginName: 'magic-sessionmanager', }, + // Strapi admin panel sessions (4.14). Strapi grants every registered + // action to the Super Admin role at boot; other roles get nothing until + // a Super Admin grants it in Settings > Roles. + { + section: 'plugins', + displayName: 'Read admin panel sessions', + uid: 'admin-sessions.read', + subCategory: 'Admin panel', + pluginName: 'magic-sessionmanager', + }, + { + section: 'plugins', + displayName: 'Sign out admins', + uid: 'admin-sessions.revoke', + subCategory: 'Admin panel', + pluginName: 'magic-sessionmanager', + }, ]); try { diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index bbd8052..6852cc6 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -17,7 +17,11 @@ * "Editor" or "Author" without explicit plugin access) could * bypass the hidden UI menu and call this API directly via curl. * - * The `access` permission is registered in `server/src/register.js`. + * The Strapi admin panel session routes (`/admin-sessions/...`) also require + * `admin-sessions.read`, and the sign-out routes `admin-sessions.revoke` + * (`adminSessionsPolicy()`); `hasPermissions` needs ALL listed actions. + * + * The permissions are registered in `server/src/register.js`. * By Strapi convention: * - the Super-Admin role owns every plugin permission automatically, * - other admin roles only receive it when a Super-Admin explicitly @@ -29,6 +33,8 @@ */ const PLUGIN_ACCESS_ACTION = 'plugin::magic-sessionmanager.access'; +const ADMIN_SESSIONS_READ_ACTION = 'plugin::magic-sessionmanager.admin-sessions.read'; +const ADMIN_SESSIONS_REVOKE_ACTION = 'plugin::magic-sessionmanager.admin-sessions.revoke'; /** * Returns the policy chain that every admin route in this plugin must use. @@ -53,6 +59,35 @@ const adminPolicy = () => [ * * @returns {Array} */ +/** + * Policy chain of the Strapi admin panel session routes. `hasPermissions` + * requires ALL listed actions, so a role needs plugin access plus the + * admin-session action(s). Only Super Admin has them by default. + * + * @param {string[]} actions Additional admin-session actions. + * @returns {Array} + */ +const adminSessionsPolicy = (actions) => [ + 'admin::isAuthenticatedAdmin', + { + name: 'admin::hasPermissions', + config: { actions: [PLUGIN_ACCESS_ACTION, ...actions] }, + }, +]; + +/** + * Write rate limit for signing admins out: 10 per minute per admin user (the + * write profile can only be tightened in the settings). + * + * @returns {Array} + */ +const adminSignOutRateLimit = () => [ + { + name: 'plugin::magic-sessionmanager.rate-limit', + config: { profile: 'write', max: 10, window: 60_000 }, + }, +]; + const adminReadRateLimit = () => [ { name: 'plugin::magic-sessionmanager.rate-limit', @@ -207,6 +242,48 @@ const baseRoutes = [ }, }, + // ===================== STRAPI ADMIN PANEL SESSIONS ===================== + { + method: 'GET', + path: '/admin-sessions/admins', + handler: 'admin-sessions.listAdmins', + config: { + policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]), + middlewares: adminReadRateLimit(), + description: 'List Strapi admins with their admin panel sessions (admin)', + }, + }, + { + method: 'GET', + path: '/admin-sessions/admins/:adminId/sessions', + handler: 'admin-sessions.listAdminSessions', + config: { + policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION]), + middlewares: adminReadRateLimit(), + description: 'List the admin panel sessions of one Strapi admin (admin)', + }, + }, + { + method: 'POST', + path: '/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out', + handler: 'admin-sessions.signOutSession', + config: { + policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]), + middlewares: adminSignOutRateLimit(), + description: 'Sign a Strapi admin out of one browser (admin)', + }, + }, + { + method: 'POST', + path: '/admin-sessions/admins/:adminId/sign-out-everywhere', + handler: 'admin-sessions.signOutEverywhere', + config: { + policies: adminSessionsPolicy([ADMIN_SESSIONS_READ_ACTION, ADMIN_SESSIONS_REVOKE_ACTION]), + middlewares: adminSignOutRateLimit(), + description: 'Sign a Strapi admin out of every browser (admin)', + }, + }, + // ============================ GEOLOCATION ============================ { method: 'GET', diff --git a/server/src/utils/admin-sessions.js b/server/src/utils/admin-sessions.js new file mode 100644 index 0000000..34a42d5 --- /dev/null +++ b/server/src/utils/admin-sessions.js @@ -0,0 +1,683 @@ +'use strict'; + +// @ts-check + +/** + * Strapi admin panel sessions: who can use the admin panel, who is signed in, + * and signing an admin out. + * + * This module only reads what Strapi itself stores. Strapi 5 keeps admin + * sessions in `admin::session` (`strapi_sessions`) with `origin = 'admin'`, + * one `deviceId` per signed-in browser. Every access-token renewal rotates the + * refresh row: the previous row becomes `rotated` (it is not deleted) and a new + * `active` row is created, so `createdAt` of the active row is the last time + * the browser renewed its token. Rows store `metadata.deviceName` (a coarse + * label such as "Chrome on macOS") and `metadata.loginAt`; no IP address and + * no raw user agent. + * + * Revocation: the admin auth strategy of Strapi 5.62 + * (`@strapi/admin/dist/server/server/src/strategies/admin.js`) calls + * `sessionManager('admin').isSessionActive(sessionId)` on every request, and + * `isSessionActive` only checks that the row exists and has not expired. It + * does not check `status`, so an access token bound to a `rotated` row keeps + * working until its own expiry if only the active row is deleted. Signing out + * therefore deletes every row of the browser (`invalidateRefreshToken(userId, + * deviceId)`, the call Strapi's own logout makes) or of the admin + * (`invalidateRefreshToken(userId)`), and the admin's next request fails. + * + * Admin rows never reach Users & Permissions numbers: those queries filter + * `origin = 'users-permissions'` (`native-only-insight.js`, `session-list.js`). + * + * Docs: https://docs.strapi.io/cms/configurations/admin-panel (Session + * management); Query Engine https://docs.strapi.io/cms/api/query-engine. + */ + +const { z } = require('@strapi/utils'); + +const ADMIN_ORIGIN = 'admin'; +const SESSION_UID = 'admin::session'; +const ADMIN_USER_UID = 'admin::user'; +const SUPER_ADMIN_CODE = 'strapi-super-admin'; + +/** Largest page an admin can request. */ +const MAX_PAGE_SIZE = 100; +/** Longest accepted search text. */ +const MAX_SEARCH_LENGTH = 100; +/** Upper bound of live admin session rows read for one overview. */ +const MAX_ACTIVE_ROWS = 10_000; +/** Admin list filters. */ +const ADMIN_FILTERS = Object.freeze(['all', 'signed-in', 'not-signed-in']); + +/** Strapi defaults, used when the host does not override them. */ +const DEFAULT_POLICY = Object.freeze({ + accessTokenLifespan: 30 * 60, + idleSessionLifespan: 2 * 60 * 60, + maxSessionLifespan: 30 * 24 * 60 * 60, + idleRefreshTokenLifespan: 14 * 24 * 60 * 60, + maxRefreshTokenLifespan: 30 * 24 * 60 * 60, +}); + +const listQuerySchema = z.strictObject({ + page: z.coerce.number().int().min(1).max(1_000_000).default(1), + pageSize: z.coerce.number().int().min(1).max(MAX_PAGE_SIZE).default(25), + search: z + .string() + .trim() + .max(MAX_SEARCH_LENGTH, `search must be at most ${MAX_SEARCH_LENGTH} characters`) + .default(''), + filter: z.enum(ADMIN_FILTERS).default('all'), +}); + +const adminParamsSchema = z.strictObject({ + adminId: z.string().regex(/^[1-9][0-9]{0,11}$/, 'adminId must be a positive integer'), +}); + +const sessionParamsSchema = z.strictObject({ + adminId: z.string().regex(/^[1-9][0-9]{0,11}$/, 'adminId must be a positive integer'), + sessionId: z.string().regex(/^[a-f0-9]{32}$/, 'sessionId must be a Strapi session id'), +}); + +/** + * Validates input against a schema without echoing values back. + * + * @template T + * @param {import('zod').ZodType} schema Strict zod schema. + * @param {unknown} input Raw query or params object. + * @returns {{ok: true, value: T}|{ok: false, errors: Array<{path: string[], message: string}>}} + * Parsed value, or one error per invalid field. + */ +function parseInput(schema, input) { + const result = schema.safeParse(input ?? {}); + if (result.success) return { ok: true, value: result.data }; + return { + ok: false, + errors: result.error.issues.map((issue) => ({ + path: issue.path.map(String), + message: issue.message, + })), + }; +} + +/** + * Returns Strapi's admin-origin session manager, or null when this Strapi + * version has no session manager or no `admin` origin (older 5.x hosts). + * + * @param {any} strapi Running Strapi instance. + * @returns {any|null} `strapi.sessionManager('admin')`, or null. + */ +function getAdminSessionManager(strapi) { + const manager = strapi?.sessionManager; + if (typeof manager !== 'function') return null; + if (typeof manager.hasOrigin === 'function' && !manager.hasOrigin(ADMIN_ORIGIN)) return null; + if (!strapi?.contentTypes?.[SESSION_UID]) return null; + try { + const origin = manager(ADMIN_ORIGIN); + return origin && typeof origin.invalidateRefreshToken === 'function' ? origin : null; + } catch { + return null; + } +} + +/** + * Admin session lifetimes the host runs with, in seconds. Shown in the UI so + * every time it states comes from the real configuration. + * + * @param {any} strapi Running Strapi instance. + * @returns {typeof DEFAULT_POLICY} Lifetimes in seconds. + */ +function readSessionPolicy(strapi) { + const read = (key) => { + const value = Number(strapi?.config?.get?.(`admin.auth.sessions.${key}`)); + return Number.isFinite(value) && value > 0 ? value : DEFAULT_POLICY[key]; + }; + return { + accessTokenLifespan: read('accessTokenLifespan'), + idleSessionLifespan: read('idleSessionLifespan'), + maxSessionLifespan: read('maxSessionLifespan'), + idleRefreshTokenLifespan: read('idleRefreshTokenLifespan'), + maxRefreshTokenLifespan: read('maxRefreshTokenLifespan'), + }; +} + +/** + * Converts a stored date to an ISO string, or null. + * + * @param {unknown} value Date, string or nothing. + * @returns {string|null} ISO 8601 date or null. + */ +function toIso(value) { + if (!value) return null; + const date = value instanceof Date ? value : new Date(String(value)); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + +/** + * Query Engine condition for admin session rows Strapi still accepts: origin + * admin, status active, idle and absolute expiry in the future. + * + * @param {Date} now Current time. + * @returns {object} Query Engine `where`. + */ +function liveSessionWhere(now) { + return { + origin: ADMIN_ORIGIN, + status: 'active', + expiresAt: { $gt: now }, + $or: [{ absoluteExpiresAt: { $null: true } }, { absoluteExpiresAt: { $gt: now } }], + }; +} + +/** + * Reads live admin session rows, optionally for one admin. Token-free columns + * only; the session table holds no tokens, but `childId` and row ids are not + * read either. + * + * @param {any} strapi Running Strapi instance. + * @param {{userId?: string, withMetadata?: boolean, now?: Date}} [options] + * @returns {Promise<{rows: Array>, truncated: boolean}>} Rows, and + * whether the overview cap was reached. + */ +async function readLiveRows(strapi, { userId, withMetadata = false, now = new Date() } = {}) { + const select = ['userId', 'sessionId', 'deviceId', 'type', 'createdAt', 'expiresAt']; + select.push('absoluteExpiresAt'); + if (withMetadata) select.push('metadata'); + const rows = await strapi.db.query(SESSION_UID).findMany({ + select, + where: { ...liveSessionWhere(now), ...(userId ? { userId } : {}) }, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + limit: MAX_ACTIVE_ROWS + 1, + }); + const list = Array.isArray(rows) ? rows : []; + return { rows: list.slice(0, MAX_ACTIVE_ROWS), truncated: list.length > MAX_ACTIVE_ROWS }; +} + +/** + * Groups live rows into signed-in browsers (one per `deviceId`). Strapi signs + * out per device, so one group is what one "Sign out" ends. + * + * @param {Array>} rows Live rows of one admin, newest first. + * @param {string|null} currentDeviceId Device of the caller's own request. + * @returns {Array<{id: string, device: string|null, signedInAt: string|null, + * lastActiveAt: string|null, endsAt: string|null, rememberMe: boolean, current: boolean}>} + * Sessions, most recently active first. `id` is the sessionId of the newest row. + */ +function groupSessionsByDevice(rows, currentDeviceId) { + /** @type {Map} */ + const groups = new Map(); + for (const row of rows) { + const key = String(row.deviceId || row.sessionId); + const metadata = row.metadata && typeof row.metadata === 'object' ? row.metadata : {}; + const lastActiveAt = toIso(row.createdAt); + const signedInAt = toIso(metadata.loginAt); + const idle = toIso(row.expiresAt); + const absolute = toIso(row.absoluteExpiresAt); + const endsAt = idle && absolute ? (idle < absolute ? idle : absolute) : idle || absolute; + const existing = groups.get(key); + if (!existing) { + groups.set(key, { + id: String(row.sessionId), + device: + typeof metadata.deviceName === 'string' && metadata.deviceName.trim() + ? metadata.deviceName.trim().slice(0, 120) + : null, + signedInAt, + lastActiveAt, + endsAt, + rememberMe: row.type === 'refresh', + current: Boolean(currentDeviceId) && key === currentDeviceId, + }); + continue; + } + if (signedInAt && (!existing.signedInAt || signedInAt < existing.signedInAt)) { + existing.signedInAt = signedInAt; + } + if (endsAt && (!existing.endsAt || endsAt > existing.endsAt)) existing.endsAt = endsAt; + if (row.type === 'refresh') existing.rememberMe = true; + } + return [...groups.values()].sort((a, b) => + String(b.lastActiveAt || '').localeCompare(String(a.lastActiveAt || '')) + ); +} + +/** + * Account state of an admin user as Strapi enforces it. + * + * @param {Record} user Admin user row. + * @returns {'active'|'deactivated'|'invited'} `invited` = registration not finished. + */ +function accountState(user) { + if (user?.isActive === true && user?.blocked !== true) return 'active'; + if (user?.hasRegistrationToken) return 'invited'; + return 'deactivated'; +} + +/** + * Whether an admin user holds the Super Admin role. + * + * @param {Record|null|undefined} user Admin user with `roles`. + * @returns {boolean} + */ +function isSuperAdmin(user) { + return Array.isArray(user?.roles) && user.roles.some((role) => role?.code === SUPER_ADMIN_CODE); +} + +/** + * Display name of an admin: first and last name, else username, else email. + * + * @param {Record} user Admin user row. + * @returns {string} Name, at most 200 characters. + */ +function displayName(user) { + const name = [user?.firstname, user?.lastname] + .filter((part) => typeof part === 'string' && part.trim()) + .join(' ') + .trim(); + return (name || user?.username || user?.email || '').slice(0, 200); +} + +/** + * Decides whether `actor` may sign `target` out. The rule is mirrored in the + * UI, but this function is the enforcement point. + * + * - A Super Admin can only be signed out by a Super Admin or by themselves. + * Since the actor is a signed-in, active admin, this also means the last + * active Super Admin can never be signed out by someone else. + * - Deactivated or invited accounts have no usable session (Strapi rejects + * their requests); there is nothing to sign out. + * + * @param {{id: any, roles?: any[]}} actor Signed-in admin. + * @param {Record} target Target admin with `roles`. + * @returns {null|'super-admin-protected'|'account-inactive'} Null when allowed, else the reason. + */ +function signOutBlockReason(actor, target) { + if (accountState(target) !== 'active') return 'account-inactive'; + const self = String(actor?.id) === String(target?.id); + if (!self && isSuperAdmin(target) && !isSuperAdmin(actor)) return 'super-admin-protected'; + return null; +} + +/** + * Loads an admin user with roles and the fields the view needs. Password, + * reset and registration tokens are not returned (only whether a + * registration token exists). + * + * @param {any} strapi Running Strapi instance. + * @param {string|number} id Admin user id. + * @returns {Promise|null>} Admin user or null. + */ +async function findAdmin(strapi, id) { + const user = await strapi.db.query(ADMIN_USER_UID).findOne({ + where: { id: Number(id) }, + select: ['id', 'firstname', 'lastname', 'username', 'email', 'isActive', 'blocked'], + populate: { roles: { select: ['id', 'name', 'code'] } }, + }); + if (!user) return null; + const pending = await strapi.db.query(ADMIN_USER_UID).count({ + where: { id: Number(id), registrationToken: { $notNull: true } }, + }); + return { ...user, hasRegistrationToken: Number(pending) > 0 }; +} + +/** + * The device of the caller's own request, so the view can mark "This + * browser" and warn before a self sign-out. + * + * @param {any} strapi Running Strapi instance. + * @param {{userId: string, sessionId?: string|null}} viewer Caller. + * @returns {Promise} Device id, or null. + */ +async function findCurrentDeviceId(strapi, { userId, sessionId }) { + if (typeof sessionId !== 'string' || !sessionId) return null; + const row = await strapi.db.query(SESSION_UID).findOne({ + select: ['userId', 'deviceId', 'origin'], + where: { sessionId }, + }); + if (!row || row.origin !== ADMIN_ORIGIN || String(row.userId) !== String(userId)) return null; + return typeof row.deviceId === 'string' ? row.deviceId : null; +} + +/** + * Shapes one admin for the list. Allowlisted fields only. + * + * @param {Record} user Admin user with roles. + * @param {{count: number, lastActiveAt: string|null}|undefined} live Live session summary. + * @param {{id: any, roles?: any[]}} actor Caller. + * @returns {Record} Admin row DTO. + */ +function toAdminRow(user, live, actor) { + const account = accountState(user); + const blockReason = signOutBlockReason(actor, user); + const sessionCount = account === 'active' ? live?.count || 0 : 0; + return { + id: Number(user.id), + name: displayName(user), + email: typeof user.email === 'string' ? user.email : '', + roles: (Array.isArray(user.roles) ? user.roles : []).map((role) => ({ + name: String(role?.name || ''), + superAdmin: role?.code === SUPER_ADMIN_CODE, + })), + account, + self: String(actor?.id) === String(user.id), + sessionCount, + lastActiveAt: account === 'active' ? live?.lastActiveAt || null : null, + canSignOut: blockReason === null && sessionCount > 0, + protectedReason: blockReason === 'super-admin-protected' ? blockReason : null, + }; +} + +/** + * Summarises live rows per admin: number of signed-in browsers and the latest + * activity. + * + * @param {Array>} rows Live rows. + * @returns {Map}>} + */ +function summariseByAdmin(rows) { + const map = new Map(); + for (const row of rows) { + const key = String(row.userId); + let entry = map.get(key); + if (!entry) { + entry = { count: 0, lastActiveAt: null, devices: new Set() }; + map.set(key, entry); + } + const device = String(row.deviceId || row.sessionId); + if (!entry.devices.has(device)) { + entry.devices.add(device); + entry.count += 1; + } + const at = toIso(row.createdAt); + if (at && (!entry.lastActiveAt || at > entry.lastActiveAt)) entry.lastActiveAt = at; + } + return map; +} + +/** + * One page of admin users with their live session summary, plus count-only + * statistics over all admins. + * + * @param {any} strapi Running Strapi instance. + * @param {{page: number, pageSize: number, search: string, filter: string}} query Parsed query. + * @param {{id: any, roles?: any[]}} actor Caller. + * @returns {Promise<{data: object[], meta: object}>} Response body. + */ +async function listAdmins(strapi, query, actor) { + const policy = readSessionPolicy(strapi); + if (!getAdminSessionManager(strapi)) { + return { + data: [], + meta: { + supported: false, + pagination: { page: 1, pageSize: query.pageSize, total: 0, pageCount: 1 }, + stats: null, + policy, + truncated: false, + }, + }; + } + + const users = strapi.db.query(ADMIN_USER_UID); + const { rows, truncated } = await readLiveRows(strapi); + const summary = summariseByAdmin(rows); + + // Only active accounts can use a session; the auth strategy rejects others. + // `blocked` may be NULL on older rows; `$ne: true` would drop those in SQL. + const activeAccountWhere = { + isActive: true, + $or: [{ blocked: false }, { blocked: { $null: true } }], + }; + const liveIds = [...summary.keys()] + .filter((id) => /^[0-9]{1,12}$/.test(id)) + .map((id) => Number(id)); + const signedInIds = liveIds.length + ? ( + await users.findMany({ + select: ['id'], + where: { id: { $in: liveIds }, ...activeAccountWhere }, + }) + ).map((row) => Number(row.id)) + : []; + + /** @type {any[]} */ + const conditions = []; + if (query.search) { + const text = query.search; + conditions.push({ + $or: [ + { firstname: { $containsi: text } }, + { lastname: { $containsi: text } }, + { username: { $containsi: text } }, + { email: { $containsi: text } }, + ], + }); + } + if (query.filter === 'signed-in') + conditions.push({ id: { $in: signedInIds.length ? signedInIds : [0] } }); + if (query.filter === 'not-signed-in' && signedInIds.length) { + conditions.push({ id: { $notIn: signedInIds } }); + } + const where = conditions.length ? { $and: conditions } : {}; + + const [total, activeAccounts, totalAdmins, pageRows] = await Promise.all([ + users.count({ where }), + users.count({ where: activeAccountWhere }), + users.count({}), + users.findMany({ + where, + select: ['id', 'firstname', 'lastname', 'username', 'email', 'isActive', 'blocked'], + populate: { roles: { select: ['id', 'name', 'code'] } }, + orderBy: [{ firstname: 'asc' }, { lastname: 'asc' }, { email: 'asc' }, { id: 'asc' }], + offset: (query.page - 1) * query.pageSize, + limit: query.pageSize, + }), + ]); + + const pageIds = (Array.isArray(pageRows) ? pageRows : []).map((row) => Number(row.id)); + const invited = pageIds.length + ? new Set( + ( + await users.findMany({ + select: ['id'], + where: { id: { $in: pageIds }, registrationToken: { $notNull: true } }, + }) + ).map((row) => Number(row.id)) + ) + : new Set(); + + const signedIn = new Set(signedInIds.map(String)); + let activeSessions = 0; + for (const [id, entry] of summary) if (signedIn.has(id)) activeSessions += entry.count; + + const count = Number(total) || 0; + return { + data: (Array.isArray(pageRows) ? pageRows : []).map((user) => + toAdminRow( + { ...user, hasRegistrationToken: invited.has(Number(user.id)) }, + summary.get(String(user.id)), + actor + ) + ), + meta: { + supported: true, + pagination: { + page: query.page, + pageSize: query.pageSize, + total: count, + pageCount: Math.max(1, Math.ceil(count / query.pageSize)), + }, + stats: { + signedInAdmins: signedInIds.length, + activeSessions, + activeAccounts: Number(activeAccounts) || 0, + totalAdmins: Number(totalAdmins) || 0, + }, + policy, + truncated, + }, + }; +} + +/** + * Live sessions of one admin, one entry per signed-in browser. + * + * @param {any} strapi Running Strapi instance. + * @param {string} adminId Validated admin id. + * @param {{id: any, roles?: any[], sessionId?: string|null}} actor Caller. + * @returns {Promise<{data: object[], meta: object}|null>} Response body, or null when the admin does not exist. + */ +async function listAdminSessions(strapi, adminId, actor) { + const target = await findAdmin(strapi, adminId); + if (!target) return null; + const supported = Boolean(getAdminSessionManager(strapi)); + const adminRow = toAdminRow(target, undefined, actor); + if (!supported || adminRow.account !== 'active') { + return { + data: [], + meta: { supported, admin: adminRow, policy: readSessionPolicy(strapi) }, + }; + } + const currentDeviceId = adminRow.self + ? await findCurrentDeviceId(strapi, { userId: String(actor.id), sessionId: actor.sessionId }) + : null; + const { rows } = await readLiveRows(strapi, { userId: String(target.id), withMetadata: true }); + const sessions = groupSessionsByDevice(rows, currentDeviceId); + const blockReason = signOutBlockReason(actor, target); + return { + data: sessions, + meta: { + supported, + admin: { + ...adminRow, + sessionCount: sessions.length, + lastActiveAt: sessions[0]?.lastActiveAt || null, + canSignOut: blockReason === null && sessions.length > 0, + }, + policy: readSessionPolicy(strapi), + }, + }; +} + +/** + * Error raised when a sign-out is not allowed or not possible. The + * controller maps `status` to the response. + */ +class AdminSignOutError extends Error { + /** + * @param {403|404|503} status HTTP status to answer. + * @param {string} message Fixed, caller-safe message. + * @param {string} [reason] Machine-readable reason for the UI. + */ + constructor(status, message, reason) { + super(message); + this.name = 'AdminSignOutError'; + this.status = status; + this.reason = reason || null; + } +} + +/** + * Signs an admin out of one browser or everywhere by deleting Strapi's + * session rows. The admin's next request is rejected by Strapi's admin auth + * strategy (no row, `isSessionActive` false) and the panel cannot renew its + * token, so it shows the login page. + * + * @param {any} strapi Running Strapi instance. + * @param {{actor: {id: any, roles?: any[], sessionId?: string|null}, adminId: string, sessionId?: string}} input + * Caller, validated target admin id and, for one browser, a validated session id. + * @returns {Promise<{ended: number, signedOutSelf: boolean, scope: 'one'|'all'}>} Number of + * browsers signed out and whether the caller's own browser was among them. + * @throws {AdminSignOutError} 404 unknown admin or session, 403 guard, 503 no session manager. + * @sideeffect Deletes `admin::session` rows of the target admin (origin admin only) and + * writes one audit log line with admin ids and counts (no email, session id or token). + */ +async function signOutAdmin(strapi, { actor, adminId, sessionId }) { + const manager = getAdminSessionManager(strapi); + if (!manager) { + throw new AdminSignOutError( + 503, + 'Admin session management is not available on this Strapi version.' + ); + } + const target = await findAdmin(strapi, adminId); + if (!target) throw new AdminSignOutError(404, 'Admin not found'); + + const blockReason = signOutBlockReason(actor, target); + if (blockReason === 'super-admin-protected') { + throw new AdminSignOutError( + 403, + 'Only a Super Admin can sign out a Super Admin.', + 'super-admin-protected' + ); + } + + const userId = String(target.id); + const { rows } = await readLiveRows(strapi, { userId }); + const devices = groupSessionsByDevice(rows, null); + const self = String(actor.id) === userId; + const currentDeviceId = self + ? await findCurrentDeviceId(strapi, { userId, sessionId: actor.sessionId }) + : null; + + let ended; + let signedOutSelf; + if (sessionId) { + // The session must be a live row of THIS admin; anything else is 404, so + // ids of other admins cannot be probed. + const row = await strapi.db.query(SESSION_UID).findOne({ + select: ['userId', 'deviceId', 'origin'], + where: { sessionId, ...liveSessionWhere(new Date()) }, + }); + if (!row || String(row.userId) !== userId || row.origin !== ADMIN_ORIGIN) { + throw new AdminSignOutError(404, 'Session not found'); + } + if (blockReason === 'account-inactive') throw new AdminSignOutError(404, 'Session not found'); + await manager.invalidateRefreshToken(userId, String(row.deviceId)); + ended = 1; + signedOutSelf = Boolean(currentDeviceId) && String(row.deviceId) === currentDeviceId; + } else { + await manager.invalidateRefreshToken(userId); + ended = blockReason === 'account-inactive' ? 0 : devices.length; + signedOutSelf = self && Boolean(currentDeviceId); + } + + const scope = sessionId ? 'one' : 'all'; + const audit = `[magic-sessionmanager] Admin sign-out: actor=${Number(actor.id)} target=${Number( + target.id + )} scope=${scope} ended=${ended}`; + strapi.log.info(audit); + try { + strapi.eventHub?.emit?.('magic-sessionmanager.admin-sessions.signed-out', { + actorId: Number(actor.id), + targetId: Number(target.id), + scope, + ended, + }); + } catch { + // An event listener failure must not undo or hide a completed sign-out. + } + return { ended, signedOutSelf, scope }; +} + +module.exports = { + ADMIN_FILTERS, + ADMIN_ORIGIN, + AdminSignOutError, + DEFAULT_POLICY, + MAX_PAGE_SIZE, + SUPER_ADMIN_CODE, + accountState, + adminParamsSchema, + displayName, + getAdminSessionManager, + groupSessionsByDevice, + isSuperAdmin, + listAdminSessions, + listAdmins, + listQuerySchema, + parseInput, + readSessionPolicy, + sessionParamsSchema, + signOutAdmin, + signOutBlockReason, + summariseByAdmin, +}; diff --git a/tests/admin-dashboard-actions.test.mjs b/tests/admin-dashboard-actions.test.mjs index 5ef6fa8..00c65ba 100644 --- a/tests/admin-dashboard-actions.test.mjs +++ b/tests/admin-dashboard-actions.test.mjs @@ -259,11 +259,11 @@ test('the search is always visible with a placeholder, never an icon-only button assert.match(search, //, + /\{label \?\? t\('homepage\.search\.label', 'Search sessions'\)\}\s*<\/Searchbar>/, 'the search has a label' ); }); diff --git a/tests/admin-i18n-completeness.test.mjs b/tests/admin-i18n-completeness.test.mjs index c0d6112..b58c9e0 100644 --- a/tests/admin-i18n-completeness.test.mjs +++ b/tests/admin-i18n-completeness.test.mjs @@ -168,6 +168,8 @@ const SAME_AS_ENGLISH = { 'https://hooks.slack.com/services/XXXX/XXXX/XXXX', '{count} min', '{minutes} min', + // Strapi's own role name, shown untranslated in every admin language. + 'Super Admin', ]), de: new Set([ 'Status', @@ -199,7 +201,7 @@ const SAME_AS_ENGLISH = { '15 minutes', '{count, plural, one {# session} other {# sessions}}', ]), - es: new Set(['General', 'Error', 'Total', 'Bot']), + es: new Set(['General', 'Error', 'Total', 'Bot', 'Roles']), pt: new Set(['Status', 'Online', 'Offline', 'Tablet', 'Login', 'Logout', 'Total', 'Bot']), }; diff --git a/tests/admin-layout-contract.test.mjs b/tests/admin-layout-contract.test.mjs index 68cc3a6..1461544 100644 --- a/tests/admin-layout-contract.test.mjs +++ b/tests/admin-layout-contract.test.mjs @@ -154,7 +154,7 @@ test('dashboard action bar sits above the list it filters, labelled and responsi 'search full width below the medium breakpoint' ); assert.ok( - / readFileSync(new URL(`../${path}`, import.meta.url), 'utf8'); + +test('URL state falls back to safe defaults and decodes the search', () => { + assert.deepEqual(parseAdminPanelQuery({}), { + page: 1, + pageSize: 25, + filter: 'all', + search: '', + }); + assert.deepEqual( + parseAdminPanelQuery({ + page: '3', + pageSize: '50', + filter: 'signed-in', + search: 'ada%40example', + }), + { page: 3, pageSize: 50, filter: 'signed-in', search: 'ada@example' } + ); + assert.deepEqual( + parseAdminPanelQuery({ page: '-2', pageSize: '7', filter: 'x', search: '%E0' }), + { + page: 1, + pageSize: 25, + filter: 'all', + search: '%E0', + } + ); + assert.equal(parseAdminPanelQuery({ search: 'x'.repeat(150) }).search.length, 100); + assert.deepEqual(buildAdminListParams({ page: 1, pageSize: 25, filter: 'all', search: '' }), { + page: 1, + pageSize: 25, + filter: 'all', + }); + assert.equal(hasAdminFilters({ filter: 'all', search: '' }), false); + assert.equal(hasAdminFilters({ filter: 'not-signed-in', search: '' }), true); +}); + +test('each admin state has its own label; danger is never used for a state', () => { + const keys = [ + { account: 'active', sessionCount: 2 }, + { account: 'active', sessionCount: 0 }, + { account: 'deactivated', sessionCount: 0 }, + { account: 'invited', sessionCount: 0 }, + ].map((row) => getAdminStatusPresentation(row)); + assert.deepEqual( + keys.map((entry) => entry.key), + ['signed-in', 'not-signed-in', 'deactivated', 'invited'] + ); + assert.ok(keys.every((entry) => entry.tone !== 'danger')); + assert.deepEqual(keys[0].detail.values, { count: 2 }); +}); + +test('durations use the largest whole unit', () => { + assert.deepEqual(splitDuration(7200), { unit: 'hours', count: 2 }); + assert.deepEqual(splitDuration(1209600), { unit: 'days', count: 14 }); + assert.deepEqual(splitDuration(1800), { unit: 'minutes', count: 30 }); + assert.equal(splitDuration(0), null); + assert.equal(splitDuration('x'), null); +}); + +test('sign-out errors map to honest messages', () => { + const fetchError = (status, reason) => ({ + response: { status, data: { error: { details: reason ? { reason } : {} } } }, + }); + assert.equal( + getSignOutErrorMessage(fetchError(403, 'super-admin-protected')).messageId, + 'adminPanel.signOut.error.protected' + ); + assert.equal( + getSignOutErrorMessage(fetchError(403)).messageId, + 'adminPanel.signOut.error.forbidden' + ); + assert.equal(getSignOutErrorMessage(fetchError(404)).messageId, 'adminPanel.signOut.error.gone'); + assert.equal( + getSignOutErrorMessage(fetchError(429)).messageId, + 'adminPanel.signOut.error.rateLimited' + ); + assert.equal( + getSignOutErrorMessage(new Error('x')).messageId, + 'adminPanel.signOut.error.generic' + ); +}); + +test('the admin panel view is its own protected route; the dashboard is unchanged for other roles', () => { + const app = read('admin/src/pages/App.jsx'); + assert.match(app, /\} \/>/); + assert.match( + app, + /path="admin-panel"[\s\S]*?/ + ); + assert.match(app, /\} \/>/); + const nav = read('admin/src/components/SessionViewNav.jsx'); + assert.match(nav, /useRBAC\(pluginPermissions\.adminSessionsRead\)/); + assert.match(nav, /if \(isLoading \|\| \(!canRead && current !== 'admins'\)\) return null;/); + assert.match(nav, / { + const page = read('admin/src/pages/AdminPanel/index.jsx'); + assert.match(page, //); + assert.match(modal, /`\/settings\/users\/\$\{admin\.id\}`/); +}); diff --git a/tests/admin-sessions.test.js b/tests/admin-sessions.test.js new file mode 100644 index 0000000..6b87041 --- /dev/null +++ b/tests/admin-sessions.test.js @@ -0,0 +1,314 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { + accountState, + adminParamsSchema, + displayName, + getAdminSessionManager, + groupSessionsByDevice, + listAdmins, + listQuerySchema, + parseInput, + readSessionPolicy, + sessionParamsSchema, + signOutAdmin, + signOutBlockReason, + summariseByAdmin, +} = require('../server/src/utils/admin-sessions'); +const controllerFactory = require('../server/src/controllers/admin-sessions'); + +const SUPER = { code: 'strapi-super-admin', name: 'Super Admin' }; +const EDITOR = { code: 'strapi-editor', name: 'Editor' }; + +test('list query is strict and bounded', () => { + assert.deepEqual(parseInput(listQuerySchema, {}).value, { + page: 1, + pageSize: 25, + search: '', + filter: 'all', + }); + assert.equal(parseInput(listQuerySchema, { pageSize: '101' }).ok, false); + assert.equal(parseInput(listQuerySchema, { filter: 'everyone' }).ok, false); + assert.equal(parseInput(listQuerySchema, { extra: '1' }).ok, false); + assert.equal(parseInput(listQuerySchema, { search: 'x'.repeat(101) }).ok, false); + const rejected = parseInput(listQuerySchema, { search: 'x'.repeat(101) }); + assert.ok(!JSON.stringify(rejected.errors).includes('xxxxx'), 'errors never echo input'); +}); + +test('route parameters accept only positive integer ids and Strapi session ids', () => { + assert.equal(parseInput(adminParamsSchema, { adminId: '12' }).ok, true); + for (const adminId of ['0', '-1', '1.5', 'abc', '1'.repeat(13), '1 OR 1=1']) { + assert.equal(parseInput(adminParamsSchema, { adminId }).ok, false, adminId); + } + const sessionId = 'a'.repeat(32); + assert.equal(parseInput(sessionParamsSchema, { adminId: '3', sessionId }).ok, true); + for (const bad of ['A'.repeat(32), 'a'.repeat(31), 'a'.repeat(33), '../x']) { + assert.equal(parseInput(sessionParamsSchema, { adminId: '3', sessionId: bad }).ok, false); + } +}); + +test('live rows are grouped per browser, newest first, without device ids', () => { + const rows = [ + { + userId: '1', + sessionId: 'b'.repeat(32), + deviceId: 'dev-2', + type: 'session', + createdAt: '2026-11-17T10:00:00.000Z', + expiresAt: '2026-11-17T12:00:00.000Z', + absoluteExpiresAt: '2026-12-17T10:00:00.000Z', + metadata: { deviceName: 'Firefox on Linux', loginAt: '2026-11-17T09:00:00.000Z' }, + }, + { + userId: '1', + sessionId: 'a'.repeat(32), + deviceId: 'dev-1', + type: 'refresh', + createdAt: '2026-11-17T08:00:00.000Z', + expiresAt: '2026-12-01T08:00:00.000Z', + absoluteExpiresAt: '2026-11-20T08:00:00.000Z', + metadata: { loginAt: '2026-11-16T08:00:00.000Z' }, + }, + { + // Second family on the same browser: same group, earlier login wins. + userId: '1', + sessionId: 'c'.repeat(32), + deviceId: 'dev-1', + type: 'session', + createdAt: '2026-11-17T07:00:00.000Z', + expiresAt: '2026-11-17T09:00:00.000Z', + absoluteExpiresAt: null, + metadata: { loginAt: '2026-11-15T08:00:00.000Z', deviceName: 'Safari' }, + }, + ]; + const groups = groupSessionsByDevice(rows, 'dev-1'); + assert.equal(groups.length, 2); + assert.deepEqual(groups[0], { + id: 'b'.repeat(32), + device: 'Firefox on Linux', + signedInAt: '2026-11-17T09:00:00.000Z', + lastActiveAt: '2026-11-17T10:00:00.000Z', + endsAt: '2026-11-17T12:00:00.000Z', + rememberMe: false, + current: false, + }); + assert.equal(groups[1].id, 'a'.repeat(32)); + assert.equal(groups[1].device, null, 'unknown device stays unknown'); + assert.equal(groups[1].signedInAt, '2026-11-15T08:00:00.000Z'); + assert.equal( + groups[1].endsAt, + '2026-11-20T08:00:00.000Z', + 'absolute expiry caps the idle expiry' + ); + assert.equal(groups[1].rememberMe, true); + assert.equal(groups[1].current, true); + assert.ok(!JSON.stringify(groups).includes('dev-1')); + + const summary = summariseByAdmin(rows); + assert.equal(summary.get('1').count, 2); + assert.equal(summary.get('1').lastActiveAt, '2026-11-17T10:00:00.000Z'); +}); + +test('account state follows what Strapi enforces', () => { + assert.equal(accountState({ isActive: true, blocked: false }), 'active'); + assert.equal(accountState({ isActive: true, blocked: null }), 'active'); + assert.equal(accountState({ isActive: true, blocked: true }), 'deactivated'); + assert.equal(accountState({ isActive: false }), 'deactivated'); + assert.equal(accountState({ isActive: false, hasRegistrationToken: true }), 'invited'); + assert.equal( + displayName({ firstname: 'Ada', lastname: 'Owner', email: 'a@example.test' }), + 'Ada Owner' + ); + assert.equal(displayName({ email: 'a@example.test' }), 'a@example.test'); +}); + +test('only a Super Admin (or the admin themselves) can sign out a Super Admin', () => { + const superA = { id: 1, roles: [SUPER], isActive: true }; + const superB = { id: 2, roles: [SUPER], isActive: true }; + const editor = { id: 3, roles: [EDITOR], isActive: true }; + const delegate = { id: 4, roles: [{ code: 'custom-revoker' }], isActive: true }; + assert.equal(signOutBlockReason(superA, superB), null); + assert.equal( + signOutBlockReason(superA, superA), + null, + 'self sign-out is allowed (with a warning)' + ); + assert.equal(signOutBlockReason(superA, editor), null); + assert.equal(signOutBlockReason(delegate, superA), 'super-admin-protected'); + assert.equal(signOutBlockReason(delegate, editor), null); + assert.equal( + signOutBlockReason(superA, { id: 5, roles: [EDITOR], isActive: false }), + 'account-inactive' + ); +}); + +test('session policy reads the host configuration with Strapi defaults', () => { + const values = { 'admin.auth.sessions.accessTokenLifespan': 600 }; + const policy = readSessionPolicy({ config: { get: (key) => values[key] } }); + assert.equal(policy.accessTokenLifespan, 600); + assert.equal(policy.idleSessionLifespan, 7200); + assert.equal(policy.maxSessionLifespan, 2592000); +}); + +test('hosts without Strapi session management are reported as unsupported', async () => { + assert.equal(getAdminSessionManager({}), null); + const noOrigin = Object.assign(() => ({}), { hasOrigin: () => false }); + assert.equal(getAdminSessionManager({ sessionManager: noOrigin, contentTypes: {} }), null); + const body = await listAdmins( + { config: { get: () => undefined } }, + { page: 1, pageSize: 25, search: '', filter: 'all' }, + { id: 1 } + ); + assert.equal(body.meta.supported, false); + assert.deepEqual(body.data, []); + await assert.rejects( + signOutAdmin({ config: { get: () => undefined } }, { actor: { id: 1 }, adminId: '2' }), + (error) => error.status === 503 + ); +}); + +/** + * Minimal Strapi double for the sign-out path: one admin user table and one + * session table, plus a recording session manager. + */ +function fakeStrapi({ users, sessions }) { + const calls = []; + const logs = []; + const events = []; + const matches = (row, where = {}) => + Object.entries(where).every(([key, value]) => { + if (key === '$or') return value.some((clause) => matches(row, clause)); + if (value && typeof value === 'object' && !(value instanceof Date)) { + if ('$gt' in value) return row[key] && new Date(row[key]) > value.$gt; + if ('$null' in value) return row[key] === null || row[key] === undefined; + if ('$notNull' in value) return row[key] !== null && row[key] !== undefined; + return true; + } + return String(row[key]) === String(value); + }); + const manager = { + async invalidateRefreshToken(userId, deviceId) { + calls.push({ userId, deviceId }); + }, + }; + const sessionManager = Object.assign(() => manager, { hasOrigin: () => true }); + return { + calls, + logs, + events, + strapi: { + sessionManager, + contentTypes: { 'admin::session': {} }, + config: { get: () => undefined }, + log: { info: (line) => logs.push(line), error() {}, warn() {} }, + eventHub: { emit: (name, payload) => events.push({ name, payload }) }, + db: { + query(uid) { + const table = uid === 'admin::user' ? users : sessions; + return { + async findOne({ where }) { + return table.find((row) => matches(row, where)) || null; + }, + async findMany({ where }) { + return table.filter((row) => matches(row, where)); + }, + async count({ where }) { + return table.filter((row) => matches(row, where)).length; + }, + }; + }, + }, + }, + }; +} + +test('sign-out deletes per browser, flags self sign-out and audits without personal data', async () => { + const future = new Date(Date.now() + 3600_000).toISOString(); + const users = [ + { id: 1, email: 'ada@example.test', isActive: true, roles: [SUPER] }, + { id: 2, email: 'erin@example.test', isActive: true, roles: [EDITOR] }, + ]; + const sessions = [ + { + userId: '1', + sessionId: 'a'.repeat(32), + deviceId: 'dev-ada', + origin: 'admin', + status: 'active', + expiresAt: future, + createdAt: future, + }, + { + userId: '2', + sessionId: 'b'.repeat(32), + deviceId: 'dev-erin', + origin: 'admin', + status: 'active', + expiresAt: future, + createdAt: future, + }, + ]; + const fake = fakeStrapi({ users, sessions }); + const actor = { id: 1, roles: [SUPER], sessionId: 'a'.repeat(32) }; + + const one = await signOutAdmin(fake.strapi, { actor, adminId: '2', sessionId: 'b'.repeat(32) }); + assert.deepEqual(one, { ended: 1, signedOutSelf: false, scope: 'one' }); + assert.deepEqual(fake.calls.at(-1), { userId: '2', deviceId: 'dev-erin' }); + + await assert.rejects( + signOutAdmin(fake.strapi, { actor, adminId: '2', sessionId: 'a'.repeat(32) }), + (error) => error.status === 404, + 'a session of another admin is not found' + ); + + const self = await signOutAdmin(fake.strapi, { actor, adminId: '1' }); + assert.deepEqual(self, { ended: 1, signedOutSelf: true, scope: 'all' }); + assert.deepEqual(fake.calls.at(-1), { userId: '1', deviceId: undefined }); + + assert.deepEqual(fake.logs, [ + '[magic-sessionmanager] Admin sign-out: actor=1 target=2 scope=one ended=1', + '[magic-sessionmanager] Admin sign-out: actor=1 target=1 scope=all ended=1', + ]); + const serialized = JSON.stringify([fake.logs, fake.events]); + for (const secret of ['example.test', 'dev-ada', 'a'.repeat(32)]) { + assert.ok(!serialized.includes(secret), `audit leaks ${secret.slice(0, 8)}`); + } + assert.equal(fake.events[0].name, 'magic-sessionmanager.admin-sessions.signed-out'); + + const delegate = { id: 2, roles: [{ code: 'custom' }], sessionId: null }; + await assert.rejects( + signOutAdmin(fake.strapi, { actor: delegate, adminId: '1' }), + (error) => error.status === 403 && error.reason === 'super-admin-protected' + ); + assert.equal(fake.calls.length, 2, 'a refused sign-out deletes nothing'); +}); + +test('sign-out routes refuse admin API tokens before touching anything', async () => { + let touched = false; + const strapi = { + log: { error() {}, info() {}, warn() {} }, + config: { get: () => undefined }, + get sessionManager() { + touched = true; + return undefined; + }, + }; + const controller = controllerFactory({ strapi }); + for (const action of ['signOutSession', 'signOutEverywhere']) { + let forbidden = null; + const ctx = { + state: { user: { id: 1 }, auth: { strategy: { name: 'admin-token' } } }, + params: { adminId: '2', sessionId: 'a'.repeat(32) }, + forbidden: (message, details) => { + forbidden = { message, details }; + return forbidden; + }, + }; + await controller[action](ctx); + assert.equal(forbidden.details.reason, 'browser-session-required'); + } + assert.equal(touched, false); +}); diff --git a/tests/isolated-admin-sessions-http.test.js b/tests/isolated-admin-sessions-http.test.js new file mode 100644 index 0000000..29690de --- /dev/null +++ b/tests/isolated-admin-sessions-http.test.js @@ -0,0 +1,637 @@ +'use strict'; + +// Real Strapi 5 HTTP boundary for the admin panel sessions view. Admins sign in +// through POST /admin/login (synthetic accounts, random passwords), so every +// session row is created by Strapi itself. Runs on SQLite by default, and on +// PostgreSQL when SESSION_HTTP_DB=postgres and MSM_TEST_PG_URL are set (a +// throwaway schema is created and dropped). +// +// SESSION_HTTP_STRAPI_NODE_MODULES=$PWD/node_modules SESSION_HTTP_REQUIRED=1 \ +// node --test tests/isolated-admin-sessions-http.test.js +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const net = require('node:net'); + +const { resolveHostDependencies, assertHostAvailable } = require('./helpers/host-dependencies'); + +const sourceRoot = path.resolve(__dirname, '..'); +const dbKind = process.env.SESSION_HTTP_DB === 'postgres' ? 'postgres' : 'sqlite'; +const host = resolveHostDependencies([ + '@strapi/strapi', + '@strapi/plugin-users-permissions', + dbKind === 'postgres' ? 'pg' : 'better-sqlite3', +]); +const pgUrl = process.env.MSM_TEST_PG_URL || ''; +const pgMissing = dbKind === 'postgres' && !pgUrl; + +const SESSION_UID = 'admin::session'; + +test( + `isolated Strapi admin panel sessions over HTTP (${dbKind})`, + { + timeout: 240000, + skip: + host.skip || + (pgMissing && process.env.SESSION_HTTP_REQUIRED !== '1' ? 'MSM_TEST_PG_URL not set' : false), + }, + async (t) => { + assertHostAvailable(host); + if (pgMissing) throw new Error('SESSION_HTTP_DB=postgres needs MSM_TEST_PG_URL'); + const hostModules = host.modules; + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'sessionmanager-admin-')); + const plugin = path.join(root, 'plugin'); + for (const dir of ['config', 'plugin', 'src', 'public', 'public/uploads']) { + fs.mkdirSync(path.join(root, dir), { recursive: true }); + } + fs.symlinkSync(hostModules, path.join(root, 'node_modules'), 'dir'); + const write = (filename, contents) => fs.writeFileSync(path.join(root, filename), contents); + write( + 'package.json', + JSON.stringify({ + name: 'isolated-sessionmanager-admin', + version: '0.0.0', + private: true, + dependencies: { '@strapi/plugin-users-permissions': '*' }, + }) + ); + write( + 'plugin/package.json', + JSON.stringify({ + name: 'isolated-sessionmanager-source', + version: '0.0.0', + strapi: { kind: 'plugin', name: 'magic-sessionmanager' }, + }) + ); + write( + 'plugin/strapi-server.js', + `module.exports = require(${JSON.stringify(path.join(sourceRoot, 'server/src/index.js'))});\n` + ); + + const schema = `msm_admin_${crypto.randomBytes(4).toString('hex')}`; + let pgAdmin = null; + if (dbKind === 'postgres') { + const { Client } = require(path.join(hostModules, 'pg')); + pgAdmin = new Client({ connectionString: pgUrl }); + await pgAdmin.connect(); + await pgAdmin.query(`CREATE SCHEMA "${schema}"`); + write( + 'config/database.js', + `module.exports = { connection: { client: 'postgres', connection: { connectionString: ${JSON.stringify(pgUrl)}, schema: ${JSON.stringify(schema)} }, pool: { min: 0, max: 5 } } };\n` + ); + } else { + write( + 'config/database.js', + `module.exports = { connection: { client: 'sqlite', connection: { filename: ${JSON.stringify(path.join(root, 'test.sqlite'))} }, useNullAsDefault: true } };\n` + ); + } + write( + 'config/server.js', + `module.exports = { host: '127.0.0.1', port: 1337, app: { keys: [process.env.TEST_HTTP_SECRET_A, process.env.TEST_HTTP_SECRET_B] }, logger: { updates: { enabled: false } } };\n` + ); + // Short access tokens are not needed: revocation is checked per request. + write( + 'config/admin.js', + `module.exports = { auth: { secret: process.env.TEST_HTTP_SECRET_A }, apiToken: { salt: process.env.TEST_HTTP_SECRET_B }, transfer: { token: { salt: process.env.TEST_HTTP_SECRET_A } }, rateLimit: { enabled: false } };\n` + ); + write( + 'config/plugins.js', + `module.exports = { 'users-permissions': { enabled: true, config: { jwtSecret: process.env.TEST_HTTP_SECRET_B, jwtManagement: 'refresh' } }, 'magic-sessionmanager': { enabled: true, resolve: ${JSON.stringify(plugin)}, config: { enableGeolocation: false, geoIpProvider: 'disabled', enableWebhooks: false, enableEmailAlerts: false } } };\n` + ); + + // Egress guard: only loopback to the test server and the local database. + const allowedPorts = new Set(); + if (dbKind === 'postgres') allowedPorts.add(Number(new URL(pgUrl).port || 5432)); + const originalConnect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function (...args) { + const options = Array.isArray(args[0]) + ? args[0][0] + : typeof args[0] === 'object' + ? args[0] + : { port: args[0], host: args[1] }; + if (options?.path) return originalConnect.apply(this, args); // unix socket (pg) + const target = options.host || options.hostname || 'localhost'; + if ( + !allowedPorts.has(Number(options.port)) || + !['127.0.0.1', '::1', 'localhost'].includes(target) + ) { + throw new Error('Outbound network disabled in isolated test'); + } + return originalConnect.apply(this, args); + }; + process.env.NODE_ENV = 'test'; + process.env.STRAPI_TELEMETRY_DISABLED = 'true'; + process.env.ENV_PATH = path.join(root, 'no-dotenv'); + process.env.TEST_HTTP_SECRET_A = crypto.randomBytes(32).toString('hex'); + process.env.TEST_HTTP_SECRET_B = crypto.randomBytes(32).toString('hex'); + process.env.SESSION_ENCRYPTION_KEY = crypto.randomBytes(32).toString('hex'); + const originalCwd = process.cwd(); + process.chdir(root); + + let app; + t.after(async () => { + try { + if (app) await app.destroy(); + } finally { + net.Socket.prototype.connect = originalConnect; + process.chdir(originalCwd); + if (pgAdmin) { + await pgAdmin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`).catch(() => {}); + await pgAdmin.end().catch(() => {}); + } + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + const { createStrapi } = require(path.join(hostModules, '@strapi/strapi')); + app = createStrapi({ appDir: root, distDir: root, serveAdminPanel: false }); + await app.load(); + const auditLines = []; + const originalInfo = app.log.info.bind(app.log); + app.log.info = (message, ...rest) => { + if (typeof message === 'string' && message.includes('Admin sign-out')) { + auditLines.push(message); + } + return originalInfo(message, ...rest); + }; + app.log.level = 'error'; + await new Promise((resolve) => app.server.listen(0, '127.0.0.1', resolve)); + const port = app.server.httpServer.address().port; + allowedPorts.add(port); + assert.throws(() => net.connect({ host: '192.0.2.1', port }), /Outbound network disabled/); + + /** + * Calls the test server. Never logs tokens or cookies. + * + * @param {string} method HTTP method. + * @param {string} url Path. + * @param {{token?: string|null, cookie?: string, body?: object}} [options] + * @returns {Promise<{status: number, body: any, cookie: string|null}>} + */ + const request = async (method, url, { token, cookie, body } = {}) => { + const response = await fetch(`http://127.0.0.1:${port}${url}`, { + method, + headers: { + ...(token ? { authorization: `Bearer ${token}` } : {}), + ...(cookie ? { cookie } : {}), + ...(body ? { 'content-type': 'application/json' } : {}), + 'user-agent': + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + const refresh = response.headers + .getSetCookie() + .find((value) => value.startsWith('strapi_admin_refresh=')); + const text = await response.text(); + let parsed; + try { + parsed = text ? JSON.parse(text) : null; + } catch { + parsed = text; + } + return { + status: response.status, + body: parsed, + cookie: refresh ? refresh.split(';')[0] : null, + }; + }; + + const passwords = new Map(); + // The admin panel sends a per-browser UUID as deviceId. + const devices = new Map(); + const device = (name) => { + if (!devices.has(name)) devices.set(name, crypto.randomUUID()); + return devices.get(name); + }; + const newPassword = () => `Aa1!${crypto.randomBytes(12).toString('base64url')}`; + + // First Super Admin through Strapi's own registration route. + const ownerPassword = newPassword(); + const registered = await request('POST', '/admin/register-admin', { + body: { + email: 'ada.owner@example.test', + firstname: 'Ada', + lastname: 'Owner', + password: ownerPassword, + }, + }); + assert.equal(registered.status, 200, 'first admin registered'); + passwords.set('ada.owner@example.test', ownerPassword); + + const roles = app.db.query('admin::role'); + const superRole = await roles.findOne({ where: { code: 'strapi-super-admin' } }); + const editorRole = await roles.findOne({ where: { code: 'strapi-editor' } }); + const createRole = async (code, actions) => { + const role = await roles.create({ data: { name: `Synthetic ${code}`, code } }); + for (const action of actions) { + await app.db + .query('admin::permission') + .create({ data: { action, conditions: [], role: role.id } }); + } + return role; + }; + const readerRole = await createRole('synthetic-reader', [ + 'plugin::magic-sessionmanager.access', + 'plugin::magic-sessionmanager.admin-sessions.read', + ]); + const revokerRole = await createRole('synthetic-revoker', [ + 'plugin::magic-sessionmanager.access', + 'plugin::magic-sessionmanager.admin-sessions.read', + 'plugin::magic-sessionmanager.admin-sessions.revoke', + ]); + const hash = (password) => app.admin.services.auth.hashPassword(password); + const createAdmin = async (email, firstname, roleId, extra = {}) => { + const password = newPassword(); + passwords.set(email, password); + return app.db.query('admin::user').create({ + data: { + email, + firstname, + lastname: 'Example', + password: await hash(password), + isActive: true, + blocked: false, + roles: [roleId], + ...extra, + }, + }); + }; + const owner = await app.db + .query('admin::user') + .findOne({ where: { email: 'ada.owner@example.test' } }); + const bert = await createAdmin('bert.super@example.test', 'Bert', superRole.id); + const erin = await createAdmin('erin.editor@example.test', 'Erin', editorRole.id); + await createAdmin('rita.reader@example.test', 'Rita', readerRole.id); + await createAdmin('vic.revoker@example.test', 'Vic', revokerRole.id); + await createAdmin('ina.invited@example.test', 'Ina', editorRole.id, { + isActive: false, + registrationToken: crypto.randomBytes(20).toString('hex'), + }); + await createAdmin('dan.deactivated@example.test', 'Dan', editorRole.id, { isActive: false }); + + /** + * Signs in through Strapi's admin login route. + * + * @param {string} email Synthetic admin email. + * @param {string} deviceId Browser id the admin panel would send. + * @returns {Promise<{token: string, cookie: string}>} + */ + const login = async (email, deviceId) => { + const result = await request('POST', '/admin/login', { + body: { email, password: passwords.get(email), deviceId, rememberMe: false }, + }); + assert.equal( + result.status, + 200, + `login of a synthetic admin (${result.status} ${result.body?.error?.message})` + ); + assert.ok(result.body.data.token && result.cookie); + return { token: result.body.data.token, cookie: result.cookie }; + }; + /** Renews like the admin panel does (rotates the refresh row). */ + const renew = async (session) => { + const result = await request('POST', '/admin/access-token', { cookie: session.cookie }); + return result.status === 200 + ? { status: 200, token: result.body.data.token, cookie: result.cookie || session.cookie } + : { status: result.status }; + }; + const me = async (token) => (await request('GET', '/admin/users/me', { token })).status; + const api = (suffix) => `/magic-sessionmanager/admin-sessions${suffix}`; + + const ada1 = await login('ada.owner@example.test', device('ada-laptop')); + const ada2 = await login('ada.owner@example.test', device('ada-tablet')); + const bert1 = await login('bert.super@example.test', device('bert-1')); + const erin1 = await login('erin.editor@example.test', device('erin-1')); + const erin2 = await login('erin.editor@example.test', device('erin-2')); + const rita1 = await login('rita.reader@example.test', device('rita-1')); + const vic1 = await login('vic.revoker@example.test', device('vic-1')); + + await t.test( + 'Super Admin holds the new actions automatically and sees every admin', + async () => { + const result = await request('GET', api('/admins?pageSize=100'), { token: ada1.token }); + assert.equal(result.status, 200); + const { data, meta } = result.body; + assert.equal(meta.supported, true); + assert.equal(meta.pagination.total, 7); + // Registration signs Ada in once, plus her two logins: 8 browsers in total. + assert.deepEqual(meta.stats, { + signedInAdmins: 5, + activeSessions: 8, + activeAccounts: 5, + totalAdmins: 7, + }); + assert.equal(meta.policy.accessTokenLifespan, 1800); + const byEmail = Object.fromEntries(data.map((row) => [row.email, row])); + assert.equal(byEmail['ada.owner@example.test'].self, true); + assert.equal(byEmail['ada.owner@example.test'].sessionCount, 3); + assert.equal(byEmail['ina.invited@example.test'].account, 'invited'); + assert.equal(byEmail['dan.deactivated@example.test'].account, 'deactivated'); + assert.equal(byEmail['dan.deactivated@example.test'].canSignOut, false); + assert.deepEqual(byEmail['bert.super@example.test'].roles, [ + { name: 'Super Admin', superAdmin: true }, + ]); + const serialized = JSON.stringify(result.body); + for (const forbidden of [ + device('ada-laptop'), + device('ada-tablet'), + 'password', + 'registrationToken', + 'refresh', + ada1.token, + ]) { + assert.ok(!serialized.includes(forbidden), `list leaks ${forbidden.slice(0, 12)}`); + } + } + ); + + await t.test('filters, search and pagination run on the server', async () => { + const signedIn = await request('GET', api('/admins?filter=signed-in&pageSize=2&page=2'), { + token: ada1.token, + }); + assert.equal(signedIn.body.meta.pagination.total, 5); + assert.equal(signedIn.body.data.length, 2); + const notSignedIn = await request('GET', api('/admins?filter=not-signed-in'), { + token: ada1.token, + }); + assert.deepEqual(notSignedIn.body.data.map((row) => row.email).sort(), [ + 'dan.deactivated@example.test', + 'ina.invited@example.test', + ]); + const search = await request('GET', api('/admins?search=RITA'), { token: ada1.token }); + assert.deepEqual( + search.body.data.map((row) => row.email), + ['rita.reader@example.test'] + ); + for (const bad of [ + '?pageSize=101', + '?filter=everyone', + '?unknown=1', + `?search=${'x'.repeat(101)}`, + ]) { + const rejected = await request('GET', api(`/admins${bad}`), { token: ada1.token }); + assert.equal(rejected.status, 400, bad); + assert.equal(rejected.body.error.name, 'BadRequestError'); + assert.equal(rejected.body.error.details.errors[0].name, 'ValidationError'); + } + }); + + await t.test('session list groups by browser and marks the caller', async () => { + const result = await request('GET', api(`/admins/${owner.id}/sessions`), { + token: ada1.token, + }); + assert.equal(result.status, 200, JSON.stringify(result.body?.error)); + assert.equal(result.body.data.length, 3); + const current = result.body.data.filter((row) => row.current); + assert.equal(current.length, 1); + for (const row of result.body.data) { + assert.match(row.id, /^[a-f0-9]{32}$/); + assert.deepEqual(Object.keys(row).sort(), [ + 'current', + 'device', + 'endsAt', + 'id', + 'lastActiveAt', + 'rememberMe', + 'signedInAt', + ]); + assert.equal(row.device, 'Chrome on macOS'); + } + assert.equal( + (await request('GET', api('/admins/999999/sessions'), { token: ada1.token })).status, + 404 + ); + assert.equal( + (await request('GET', api('/admins/abc/sessions'), { token: ada1.token })).status, + 400 + ); + }); + + await t.test('RBAC: anonymous 401, Editor 403, read-only role cannot sign out', async () => { + assert.equal((await request('GET', api('/admins'))).status, 401); + assert.equal((await request('GET', api('/admins'), { token: erin1.token })).status, 403); + assert.equal((await request('GET', api('/admins'), { token: rita1.token })).status, 200); + const denied = await request('POST', api(`/admins/${erin.id}/sign-out-everywhere`), { + token: rita1.token, + }); + assert.equal(denied.status, 403); + assert.equal(await me(erin1.token), 200, 'denied call did not sign Erin out'); + }); + + await t.test( + 'a delegated role cannot sign out a Super Admin (last-Super-Admin guard)', + async () => { + // Vic's role may sign admins out, but not Super Admins: neither Ada nor Bert. + for (const target of [owner, bert]) { + const result = await request('POST', api(`/admins/${target.id}/sign-out-everywhere`), { + token: vic1.token, + }); + assert.equal(result.status, 403); + assert.equal(result.body.error.details.reason, 'super-admin-protected'); + } + assert.equal(await me(bert1.token), 200); + assert.equal(await me(ada1.token), 200); + const listed = await request('GET', api('/admins?search=bert'), { token: vic1.token }); + assert.equal(listed.body.data[0].canSignOut, false); + assert.equal(listed.body.data[0].protectedReason, 'super-admin-protected'); + } + ); + + await t.test( + 'sign out one browser: next request 401, renewal 401, other browser untouched', + async () => { + const sessions = await request('GET', api(`/admins/${erin.id}/sessions`), { + token: vic1.token, + }); + assert.equal(sessions.body.data.length, 2); + // Erin's first browser renews once, so its first access token is bound to a rotated row. + const renewed = await renew(erin1); + assert.equal(renewed.status, 200); + assert.equal(await me(erin1.token), 200, 'old access token works before the sign-out'); + assert.equal(await me(renewed.token), 200); + const rows = await app.db.query(SESSION_UID).findMany({ + where: { userId: String(erin.id), deviceId: device('erin-1'), status: 'active' }, + }); + assert.equal(rows.length, 1); + const result = await request( + 'POST', + api(`/admins/${erin.id}/sessions/${rows[0].sessionId}/sign-out`), + { token: vic1.token } + ); + assert.equal(result.status, 200); + assert.deepEqual(result.body.data, { ended: 1, signedOutSelf: false }); + assert.equal(await me(renewed.token), 401, 'current access token rejected at once'); + assert.equal( + await me(erin1.token), + 401, + 'access token of the rotated row rejected at once' + ); + assert.equal((await renew(renewed)).status, 401, 'refresh cookie no longer renews'); + assert.equal(await me(erin2.token), 200, 'the other browser stays signed in'); + } + ); + + await t.test( + 'Strapi revokeSessionById alone leaves a rotated access token valid (why we delete per device)', + async () => { + const probe = await login('bert.super@example.test', device('bert-probe')); + const renewed = await renew(probe); + assert.equal(renewed.status, 200); + const active = await app.db.query(SESSION_UID).findOne({ + where: { userId: String(bert.id), deviceId: device('bert-probe'), status: 'active' }, + }); + const revoked = await app + .sessionManager('admin') + .revokeSessionById(String(bert.id), active.sessionId); + assert.equal(revoked, true); + assert.equal(await me(renewed.token), 401); + assert.equal( + await me(probe.token), + 200, + 'Strapi still accepts the token of the rotated row' + ); + await app + .sessionManager('admin') + .invalidateRefreshToken(String(bert.id), device('bert-probe')); + assert.equal(await me(probe.token), 401); + } + ); + + await t.test('a session id of another admin is 404 (no probing)', async () => { + const bertRow = await app.db.query(SESSION_UID).findOne({ + where: { userId: String(bert.id), deviceId: device('bert-1'), status: 'active' }, + }); + const result = await request( + 'POST', + api(`/admins/${erin.id}/sessions/${bertRow.sessionId}/sign-out`), + { token: ada1.token } + ); + assert.equal(result.status, 404); + const missing = await request( + 'POST', + api(`/admins/${erin.id}/sessions/${'0'.repeat(32)}/sign-out`), + { token: ada1.token } + ); + assert.equal(missing.status, 404); + const malformed = await request( + 'POST', + api(`/admins/${erin.id}/sessions/not-a-session/sign-out`), + { + token: ada1.token, + } + ); + assert.equal(malformed.status, 400); + assert.equal(await me(bert1.token), 200); + }); + + await t.test('sign out everywhere ends every browser of the admin', async () => { + const result = await request('POST', api(`/admins/${erin.id}/sign-out-everywhere`), { + token: ada1.token, + }); + assert.equal(result.status, 200); + assert.deepEqual(result.body.data, { ended: 1, signedOutSelf: false }); + assert.equal(await me(erin2.token), 401); + assert.equal( + await app.db.query(SESSION_UID).count({ where: { userId: String(erin.id) } }), + 0 + ); + }); + + await t.test('self sign-out: another own browser, then this browser', async () => { + const own = await request('GET', api(`/admins/${owner.id}/sessions`), { token: ada1.token }); + const other = own.body.data.find((row) => !row.current); + const current = own.body.data.find((row) => row.current); + const first = await request( + 'POST', + api(`/admins/${owner.id}/sessions/${other.id}/sign-out`), + { + token: ada1.token, + } + ); + assert.deepEqual(first.body.data, { ended: 1, signedOutSelf: false }); + assert.equal(await me(ada2.token), 401); + assert.equal(await me(ada1.token), 200); + const second = await request( + 'POST', + api(`/admins/${owner.id}/sessions/${current.id}/sign-out`), + { + token: ada1.token, + } + ); + assert.deepEqual(second.body.data, { ended: 1, signedOutSelf: true }); + assert.equal(await me(ada1.token), 401, 'the caller is signed out too'); + const again = await login('ada.owner@example.test', device('ada-laptop')); + assert.equal(await me(again.token), 200, 'the Super Admin can sign in again'); + ada1.token = again.token; + }); + + await t.test('every sign-out wrote one audit line with ids and counts only', () => { + assert.ok(auditLines.length >= 4); + for (const line of auditLines) { + assert.match( + line, + /^\[magic-sessionmanager\] Admin sign-out: actor=\d+ target=\d+ scope=(one|all) ended=\d+$/ + ); + } + }); + + await t.test('admin rows never reach the app-user numbers', async () => { + // One untracked Users & Permissions refresh session next to many admin rows. + const role = await app.db + .query('plugin::users-permissions.role') + .findOne({ where: { type: 'authenticated' } }); + const user = await app.db.query('plugin::users-permissions.user').create({ + data: { + username: 'una.user', + email: 'una.user@example.test', + provider: 'local', + confirmed: true, + blocked: false, + role: role.id, + }, + }); + await app + .sessionManager('users-permissions') + .generateRefreshToken(String(user.id), device('una'), { + type: 'refresh', + }); + const adminRows = await app.db.query(SESSION_UID).count({ where: { origin: 'admin' } }); + assert.ok(adminRows >= 4); + const stats = await request('GET', '/magic-sessionmanager/sessions/stats', { + token: ada1.token, + }); + assert.equal(stats.status, 200); + const counts = stats.body.data ?? stats.body; + assert.equal(counts.total, 0); + assert.equal(counts.active, 0); + assert.equal(counts.usersOnline, 0); + assert.equal(counts.nativeOnly, 1, 'only the Users & Permissions session is counted'); + const userStats = await request('GET', '/magic-sessionmanager/users/stats', { + token: ada1.token, + }); + assert.equal(userStats.status, 200); + const usersBody = userStats.body.data ?? userStats.body; + assert.equal(usersBody.totalUsers ?? usersBody.total, 1); + }); + + await t.test('sign-out is limited to 10 requests per minute per admin', async () => { + const statuses = []; + for (let i = 0; i < 12; i++) { + statuses.push( + ( + await request('POST', api(`/admins/${erin.id}/sign-out-everywhere`), { + token: vic1.token, + }) + ).status + ); + } + assert.ok(statuses.includes(429), `statuses: ${statuses.join(',')}`); + assert.equal(statuses.filter((status) => status === 200).length <= 10, true); + assert.equal((await request('GET', api('/admins'), { token: vic1.token })).status, 200); + }); + } +); diff --git a/tests/isolated-http-access.test.js b/tests/isolated-http-access.test.js index f828f40..960d1a0 100644 --- a/tests/isolated-http-access.test.js +++ b/tests/isolated-http-access.test.js @@ -261,11 +261,12 @@ test( 'every registered admin route denies anonymous, editor and content-user principals', async () => { const routes = require('../server/src/routes/admin').routes; - assert.equal(routes.length, 21); + assert.equal(routes.length, 25); for (const route of routes) { const pathname = route.path .replace(':sessionId', otherSession.documentId) .replace(':userId', other.documentId) + .replace(':adminId', '1') .replace(':ipAddress', '192.0.2.1'); for (const [kind, token] of [ ['anonymous', null], @@ -1318,7 +1319,23 @@ test( const testUser = await createUser('admin-target'); const sessionToken = await jwt.issue({ id: testUser.id }); const target = await createSession(testUser, 'admin-target-session', sessionToken); + // A separate synthetic admin with one Strapi admin session, so the + // sign-out routes never end the session of the calling admin. + const adminTarget = await app.db.query('admin::user').create({ + data: { + email: 'admin-session-target@example.invalid', + firstname: 'Synthetic', + lastname: 'Target', + isActive: true, + roles: [editorRole.id], + }, + }); + const adminTargetSession = await app + .sessionManager('admin') + .generateRefreshToken(String(adminTarget.id), crypto.randomUUID(), { type: 'session' }); const targets = { + 'POST /admin-sessions/admins/:adminId/sessions/:sessionId/sign-out': + adminTargetSession.sessionId, 'POST /sessions/:sessionId/terminate': target.documentId, 'DELETE /sessions/:sessionId': target.documentId, 'POST /sessions/:sessionId/simulate-timeout': target.documentId, @@ -1340,6 +1357,7 @@ test( const pathname = route.path .replace(':sessionId', targets[key] || target.documentId) .replace(':userId', testUser.documentId) + .replace(':adminId', String(adminTarget.id)) .replace(':ipAddress', '192.0.2.1'); const result = await request( route.method, diff --git a/tests/route-contracts.test.js b/tests/route-contracts.test.js index d2e4a14..c2ef9ce 100644 --- a/tests/route-contracts.test.js +++ b/tests/route-contracts.test.js @@ -53,6 +53,18 @@ test('all Session Manager admin API paths and handlers stay in the reviewed inve ['POST', '/user/:userId/terminate-all', 'session.terminateAllUserSessions'], ['POST', '/user/:userId/toggle-block', 'session.toggleUserBlock'], ['GET', '/users/stats', 'session.getUserStatsAdmin'], + ['GET', '/admin-sessions/admins', 'admin-sessions.listAdmins'], + ['GET', '/admin-sessions/admins/:adminId/sessions', 'admin-sessions.listAdminSessions'], + [ + 'POST', + '/admin-sessions/admins/:adminId/sessions/:sessionId/sign-out', + 'admin-sessions.signOutSession', + ], + [ + 'POST', + '/admin-sessions/admins/:adminId/sign-out-everywhere', + 'admin-sessions.signOutEverywhere', + ], ['GET', '/geolocation/:ipAddress', 'session.getIpGeolocation'], ['GET', '/geoip/status', 'geoip.getStatus'], ['PUT', '/geoip/credentials', 'geoip.storeCredentials'], @@ -71,6 +83,31 @@ test('all Session Manager admin API paths and handlers stay in the reviewed inve ); }); +test('admin panel session routes need their own actions, and sign-out is write rate limited', () => { + const actionsOf = (route) => + route.config.policies.find((policy) => policy?.name === 'admin::hasPermissions').config.actions; + const adminSessionRoutes = adminRoutes.filter(({ path }) => path.startsWith('/admin-sessions/')); + assert.equal(adminSessionRoutes.length, 4); + for (const route of adminSessionRoutes) { + const actions = actionsOf(route); + assert.ok(actions.includes('plugin::magic-sessionmanager.access')); + assert.ok(actions.includes('plugin::magic-sessionmanager.admin-sessions.read')); + const limit = route.config.middlewares[0]; + assert.equal(limit.name, 'plugin::magic-sessionmanager.rate-limit'); + if (route.method === 'GET') { + assert.ok(!actions.includes('plugin::magic-sessionmanager.admin-sessions.revoke')); + assert.equal(limit.config.profile, 'read'); + } else { + assert.ok(actions.includes('plugin::magic-sessionmanager.admin-sessions.revoke')); + assert.deepEqual(limit.config, { profile: 'write', max: 10, window: 60_000 }); + } + } + // Existing routes keep the plugin action only; the new actions are not required there. + for (const route of adminRoutes.filter(({ path }) => !path.startsWith('/admin-sessions/'))) { + assert.deepEqual(actionsOf(route), ['plugin::magic-sessionmanager.access']); + } +}); + test('every content API route has a real controller action and JWT protection', () => { for (const route of contentRoutes) { assertHandlerExists(route);