strapi-plugin-magic-sessionmanager 4.7.1 → 4.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ ## [4.7.2](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.7.1...v4.7.2) (2026-07-11)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **auth:** restore reliable session logout ([dcade5f](https://github.com/Schero94/Magic-Sessionmanager/commit/dcade5fd98d4a10e969ce26625c86c2711fc8cb1))
7
+
1
8
  ## [4.7.1](https://github.com/Schero94/Magic-Sessionmanager/compare/v4.7.0...v4.7.1) (2026-07-10)
2
9
 
3
10
 
@@ -10082,7 +10082,6 @@ var require_bootstrap = __commonJS({
10082
10082
  }
10083
10083
  const jwtService = strapi2.plugin("users-permissions").service("jwt");
10084
10084
  let decoded = null;
10085
- let expiredButValid = false;
10086
10085
  try {
10087
10086
  decoded = await jwtService.verify(token);
10088
10087
  } catch (verifyErr) {
@@ -10092,7 +10091,6 @@ var require_bootstrap = __commonJS({
10092
10091
  const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
10093
10092
  if (jwtSecret) {
10094
10093
  decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
10095
- expiredButValid = !!decoded;
10096
10094
  }
10097
10095
  } catch {
10098
10096
  decoded = null;
@@ -10109,26 +10107,21 @@ var require_bootstrap = __commonJS({
10109
10107
  ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10110
10108
  return;
10111
10109
  }
10112
- const userDocId = await resolveUserDocumentId(strapi2, decoded.id);
10113
- const tokenHashValue = hashToken(token);
10114
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10115
- filters: {
10116
- tokenHash: tokenHashValue,
10117
- ...userDocId ? { user: { documentId: userDocId } } : {}
10118
- },
10119
- fields: ["documentId", "isActive"]
10120
- });
10121
- if (matchingSession && matchingSession.isActive) {
10122
- await sessionService.terminateSession({
10123
- sessionId: matchingSession.documentId,
10124
- reason: "logout"
10125
- });
10126
- log.info(`[LOGOUT] Session ${matchingSession.documentId} terminated (expiredButValid=${expiredButValid})`);
10110
+ const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
10111
+ if (!userDocumentId) {
10112
+ ctx.status = 401;
10113
+ ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10114
+ return;
10127
10115
  }
10116
+ await sessionService.terminateAuthenticatedSession({
10117
+ userDocumentId,
10118
+ accessToken: token,
10119
+ refreshToken: null
10120
+ });
10128
10121
  ctx.status = 200;
10129
- ctx.body = { message: "Logged out successfully" };
10122
+ ctx.body = { ok: true, message: "Logged out successfully" };
10130
10123
  } catch (err) {
10131
- log.error("Logout error:", err);
10124
+ log.error("Logout error:", err?.name || "Error");
10132
10125
  ctx.status = 500;
10133
10126
  ctx.body = { error: { status: 500, name: "InternalServerError", message: "Logout failed" } };
10134
10127
  }
@@ -10478,15 +10471,35 @@ var require_bootstrap = __commonJS({
10478
10471
  strapi2.server.use(async (ctx, next) => {
10479
10472
  if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
10480
10473
  const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
10481
- if (refreshToken) {
10482
- try {
10483
- await sessionService.terminateSessionByRefreshToken(refreshToken);
10484
- } catch (err) {
10485
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10486
- return;
10474
+ const accessToken = extractBearerToken(ctx);
10475
+ const jwtManagement = strapi2.config.get(
10476
+ "plugin::users-permissions.jwtManagement",
10477
+ "legacy-support"
10478
+ );
10479
+ await next();
10480
+ const isUsersPermissionsLogoutRoute = ctx.state?.route?.handler === "auth.logout" && ctx.state?.route?.info?.pluginName === "users-permissions";
10481
+ const isSuccessful = isUsersPermissionsLogoutRoute && ctx.status >= 200 && ctx.status < 300;
10482
+ const isLegacyMissingRoute = jwtManagement === "legacy-support" && ctx.status === 404 && isUsersPermissionsLogoutRoute;
10483
+ const authenticatedUser = ctx.state?.user;
10484
+ if (!authenticatedUser || !isSuccessful && !isLegacyMissingRoute) return;
10485
+ try {
10486
+ const userDocumentId = authenticatedUser.documentId || await resolveUserDocumentId(strapi2, authenticatedUser.id);
10487
+ if (!userDocumentId) {
10488
+ throw new Error("authenticated logout user has no resolvable documentId");
10487
10489
  }
10490
+ await sessionService.terminateAuthenticatedSession({
10491
+ userDocumentId,
10492
+ refreshToken,
10493
+ accessToken
10494
+ });
10495
+ ctx.status = 200;
10496
+ ctx.body = {
10497
+ ok: true,
10498
+ message: "Logged out successfully"
10499
+ };
10500
+ } catch (err) {
10501
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10488
10502
  }
10489
- await next();
10490
10503
  });
10491
10504
  log.info("[SUCCESS] Logout interceptor middleware mounted");
10492
10505
  }
@@ -12953,6 +12966,9 @@ var require_session2 = __commonJS({
12953
12966
  var { getPluginSettings } = require_settings_loader();
12954
12967
  var SESSION_UID = "plugin::magic-sessionmanager.session";
12955
12968
  var MAX_SESSIONS_QUERY = 1e3;
12969
+ async function lockSessionRow(trx, documentId) {
12970
+ await trx("magic_sessions").where({ document_id: documentId }).forUpdate().first("document_id");
12971
+ }
12956
12972
  module2.exports = ({ strapi: strapi2 }) => {
12957
12973
  const log = createLogger(strapi2);
12958
12974
  async function getEnhanceOpts() {
@@ -13076,6 +13092,52 @@ var require_session2 = __commonJS({
13076
13092
  });
13077
13093
  return result?.count === 1;
13078
13094
  },
13095
+ /**
13096
+ * Terminates the authenticated user's active session. A raw access token
13097
+ * is authoritative when present, and a supplied refresh token must match
13098
+ * the same row. Refresh-token-only lookup is used when access is absent.
13099
+ *
13100
+ * @param {Object} params
13101
+ * @param {string} params.userDocumentId - Authenticated user's documentId
13102
+ * @param {string|null} [params.refreshToken=null] - Raw refresh token
13103
+ * @param {string|null} [params.accessToken=null] - Raw access token
13104
+ * @returns {Promise<boolean>} Whether one owned active session was terminated
13105
+ * @throws {Error} When the Document Service lookup or termination fails
13106
+ * @sideeffect Marks the matching session inactive with logout metadata
13107
+ */
13108
+ async terminateAuthenticatedSession({
13109
+ userDocumentId,
13110
+ refreshToken = null,
13111
+ accessToken = null
13112
+ }) {
13113
+ if (!userDocumentId || !refreshToken && !accessToken) return false;
13114
+ const selectedTokenFilters = {
13115
+ user: { documentId: userDocumentId },
13116
+ isActive: true
13117
+ };
13118
+ if (accessToken) {
13119
+ selectedTokenFilters.tokenHash = hashToken(accessToken);
13120
+ if (refreshToken) {
13121
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13122
+ }
13123
+ } else {
13124
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13125
+ }
13126
+ const session = await strapi2.documents(SESSION_UID).findFirst({
13127
+ filters: selectedTokenFilters,
13128
+ fields: ["documentId"]
13129
+ });
13130
+ if (!session) return false;
13131
+ return strapi2.db.transaction(async ({ trx }) => {
13132
+ await lockSessionRow(trx, session.documentId);
13133
+ const result = await this.terminateSession({
13134
+ sessionId: session.documentId,
13135
+ reason: "logout",
13136
+ expectedFilters: selectedTokenFilters
13137
+ });
13138
+ return result?.terminatedCount === 1;
13139
+ });
13140
+ },
13079
13141
  /**
13080
13142
  * Terminates a single session, all sessions of a user, or all sessions
13081
13143
  * of a user EXCEPT one with a typed reason so the JWT-verify wrapper
@@ -13102,10 +13164,19 @@ var require_session2 = __commonJS({
13102
13164
  * `userId`. Used by
13103
13165
  * /logout-other-devices so
13104
13166
  * the caller stays logged in.
13167
+ * @param {object} [params.expectedFilters] Internal predicates that must
13168
+ * still match before a
13169
+ * single-session update.
13105
13170
  * @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
13106
13171
  * @returns {Promise<{terminatedCount: number}>}
13107
13172
  */
13108
- async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
13173
+ async terminateSession({
13174
+ sessionId,
13175
+ userId,
13176
+ exceptSessionId = null,
13177
+ reason = "manual",
13178
+ expectedFilters = null
13179
+ }) {
13109
13180
  try {
13110
13181
  const now = /* @__PURE__ */ new Date();
13111
13182
  const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
@@ -13117,7 +13188,13 @@ var require_session2 = __commonJS({
13117
13188
  logoutTime: now
13118
13189
  };
13119
13190
  if (sessionId) {
13120
- const existing = await strapi2.documents(SESSION_UID).findOne({
13191
+ const existing = expectedFilters ? await strapi2.documents(SESSION_UID).findFirst({
13192
+ filters: {
13193
+ ...expectedFilters,
13194
+ documentId: sessionId
13195
+ },
13196
+ fields: ["documentId"]
13197
+ }) : await strapi2.documents(SESSION_UID).findOne({
13121
13198
  documentId: sessionId,
13122
13199
  fields: ["documentId"]
13123
13200
  });
@@ -13549,7 +13626,7 @@ var require_session2 = __commonJS({
13549
13626
  var require_package = __commonJS({
13550
13627
  "package.json"(exports2, module2) {
13551
13628
  module2.exports = {
13552
- version: "4.7.1",
13629
+ version: "4.7.2",
13553
13630
  keywords: [
13554
13631
  "strapi",
13555
13632
  "plugin",
@@ -10088,7 +10088,6 @@ var require_bootstrap = __commonJS({
10088
10088
  }
10089
10089
  const jwtService = strapi2.plugin("users-permissions").service("jwt");
10090
10090
  let decoded = null;
10091
- let expiredButValid = false;
10092
10091
  try {
10093
10092
  decoded = await jwtService.verify(token);
10094
10093
  } catch (verifyErr) {
@@ -10098,7 +10097,6 @@ var require_bootstrap = __commonJS({
10098
10097
  const jwtSecret = strapi2.config.get("plugin::users-permissions.jwtSecret");
10099
10098
  if (jwtSecret) {
10100
10099
  decoded = jwt.verify(token, jwtSecret, { ignoreExpiration: true });
10101
- expiredButValid = !!decoded;
10102
10100
  }
10103
10101
  } catch {
10104
10102
  decoded = null;
@@ -10115,26 +10113,21 @@ var require_bootstrap = __commonJS({
10115
10113
  ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10116
10114
  return;
10117
10115
  }
10118
- const userDocId = await resolveUserDocumentId(strapi2, decoded.id);
10119
- const tokenHashValue = hashToken(token);
10120
- const matchingSession = await strapi2.documents(SESSION_UID).findFirst({
10121
- filters: {
10122
- tokenHash: tokenHashValue,
10123
- ...userDocId ? { user: { documentId: userDocId } } : {}
10124
- },
10125
- fields: ["documentId", "isActive"]
10126
- });
10127
- if (matchingSession && matchingSession.isActive) {
10128
- await sessionService.terminateSession({
10129
- sessionId: matchingSession.documentId,
10130
- reason: "logout"
10131
- });
10132
- log.info(`[LOGOUT] Session ${matchingSession.documentId} terminated (expiredButValid=${expiredButValid})`);
10116
+ const userDocumentId = await resolveUserDocumentId(strapi2, decoded.id);
10117
+ if (!userDocumentId) {
10118
+ ctx.status = 401;
10119
+ ctx.body = { error: { status: 401, name: "UnauthorizedError", message: "Invalid token" } };
10120
+ return;
10133
10121
  }
10122
+ await sessionService.terminateAuthenticatedSession({
10123
+ userDocumentId,
10124
+ accessToken: token,
10125
+ refreshToken: null
10126
+ });
10134
10127
  ctx.status = 200;
10135
- ctx.body = { message: "Logged out successfully" };
10128
+ ctx.body = { ok: true, message: "Logged out successfully" };
10136
10129
  } catch (err) {
10137
- log.error("Logout error:", err);
10130
+ log.error("Logout error:", err?.name || "Error");
10138
10131
  ctx.status = 500;
10139
10132
  ctx.body = { error: { status: 500, name: "InternalServerError", message: "Logout failed" } };
10140
10133
  }
@@ -10484,15 +10477,35 @@ var require_bootstrap = __commonJS({
10484
10477
  strapi2.server.use(async (ctx, next) => {
10485
10478
  if (ctx.path !== "/api/auth/logout" || ctx.method !== "POST") return next();
10486
10479
  const refreshToken = getIncomingRefreshToken(ctx, getRefreshCookieName(strapi2));
10487
- if (refreshToken) {
10488
- try {
10489
- await sessionService.terminateSessionByRefreshToken(refreshToken);
10490
- } catch (err) {
10491
- failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10492
- return;
10480
+ const accessToken = extractBearerToken(ctx);
10481
+ const jwtManagement = strapi2.config.get(
10482
+ "plugin::users-permissions.jwtManagement",
10483
+ "legacy-support"
10484
+ );
10485
+ await next();
10486
+ const isUsersPermissionsLogoutRoute = ctx.state?.route?.handler === "auth.logout" && ctx.state?.route?.info?.pluginName === "users-permissions";
10487
+ const isSuccessful = isUsersPermissionsLogoutRoute && ctx.status >= 200 && ctx.status < 300;
10488
+ const isLegacyMissingRoute = jwtManagement === "legacy-support" && ctx.status === 404 && isUsersPermissionsLogoutRoute;
10489
+ const authenticatedUser = ctx.state?.user;
10490
+ if (!authenticatedUser || !isSuccessful && !isLegacyMissingRoute) return;
10491
+ try {
10492
+ const userDocumentId = authenticatedUser.documentId || await resolveUserDocumentId(strapi2, authenticatedUser.id);
10493
+ if (!userDocumentId) {
10494
+ throw new Error("authenticated logout user has no resolvable documentId");
10493
10495
  }
10496
+ await sessionService.terminateAuthenticatedSession({
10497
+ userDocumentId,
10498
+ refreshToken,
10499
+ accessToken
10500
+ });
10501
+ ctx.status = 200;
10502
+ ctx.body = {
10503
+ ok: true,
10504
+ message: "Logged out successfully"
10505
+ };
10506
+ } catch (err) {
10507
+ failClosedAuthResponse({ ctx, strapi: strapi2, log, operation: "logout termination failed", error: err });
10494
10508
  }
10495
- await next();
10496
10509
  });
10497
10510
  log.info("[SUCCESS] Logout interceptor middleware mounted");
10498
10511
  }
@@ -12959,6 +12972,9 @@ var require_session2 = __commonJS({
12959
12972
  var { getPluginSettings } = require_settings_loader();
12960
12973
  var SESSION_UID = "plugin::magic-sessionmanager.session";
12961
12974
  var MAX_SESSIONS_QUERY = 1e3;
12975
+ async function lockSessionRow(trx, documentId) {
12976
+ await trx("magic_sessions").where({ document_id: documentId }).forUpdate().first("document_id");
12977
+ }
12962
12978
  module.exports = ({ strapi: strapi2 }) => {
12963
12979
  const log = createLogger(strapi2);
12964
12980
  async function getEnhanceOpts() {
@@ -13082,6 +13098,52 @@ var require_session2 = __commonJS({
13082
13098
  });
13083
13099
  return result?.count === 1;
13084
13100
  },
13101
+ /**
13102
+ * Terminates the authenticated user's active session. A raw access token
13103
+ * is authoritative when present, and a supplied refresh token must match
13104
+ * the same row. Refresh-token-only lookup is used when access is absent.
13105
+ *
13106
+ * @param {Object} params
13107
+ * @param {string} params.userDocumentId - Authenticated user's documentId
13108
+ * @param {string|null} [params.refreshToken=null] - Raw refresh token
13109
+ * @param {string|null} [params.accessToken=null] - Raw access token
13110
+ * @returns {Promise<boolean>} Whether one owned active session was terminated
13111
+ * @throws {Error} When the Document Service lookup or termination fails
13112
+ * @sideeffect Marks the matching session inactive with logout metadata
13113
+ */
13114
+ async terminateAuthenticatedSession({
13115
+ userDocumentId,
13116
+ refreshToken = null,
13117
+ accessToken = null
13118
+ }) {
13119
+ if (!userDocumentId || !refreshToken && !accessToken) return false;
13120
+ const selectedTokenFilters = {
13121
+ user: { documentId: userDocumentId },
13122
+ isActive: true
13123
+ };
13124
+ if (accessToken) {
13125
+ selectedTokenFilters.tokenHash = hashToken(accessToken);
13126
+ if (refreshToken) {
13127
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13128
+ }
13129
+ } else {
13130
+ selectedTokenFilters.refreshTokenHash = hashToken(refreshToken);
13131
+ }
13132
+ const session = await strapi2.documents(SESSION_UID).findFirst({
13133
+ filters: selectedTokenFilters,
13134
+ fields: ["documentId"]
13135
+ });
13136
+ if (!session) return false;
13137
+ return strapi2.db.transaction(async ({ trx }) => {
13138
+ await lockSessionRow(trx, session.documentId);
13139
+ const result = await this.terminateSession({
13140
+ sessionId: session.documentId,
13141
+ reason: "logout",
13142
+ expectedFilters: selectedTokenFilters
13143
+ });
13144
+ return result?.terminatedCount === 1;
13145
+ });
13146
+ },
13085
13147
  /**
13086
13148
  * Terminates a single session, all sessions of a user, or all sessions
13087
13149
  * of a user EXCEPT one with a typed reason so the JWT-verify wrapper
@@ -13108,10 +13170,19 @@ var require_session2 = __commonJS({
13108
13170
  * `userId`. Used by
13109
13171
  * /logout-other-devices so
13110
13172
  * the caller stays logged in.
13173
+ * @param {object} [params.expectedFilters] Internal predicates that must
13174
+ * still match before a
13175
+ * single-session update.
13111
13176
  * @param {'logout'|'manual'|'idle'|'expired'|'blocked'} [params.reason='manual']
13112
13177
  * @returns {Promise<{terminatedCount: number}>}
13113
13178
  */
13114
- async terminateSession({ sessionId, userId, exceptSessionId = null, reason = "manual" }) {
13179
+ async terminateSession({
13180
+ sessionId,
13181
+ userId,
13182
+ exceptSessionId = null,
13183
+ reason = "manual",
13184
+ expectedFilters = null
13185
+ }) {
13115
13186
  try {
13116
13187
  const now = /* @__PURE__ */ new Date();
13117
13188
  const validReasons = ["logout", "manual", "idle", "expired", "blocked"];
@@ -13123,7 +13194,13 @@ var require_session2 = __commonJS({
13123
13194
  logoutTime: now
13124
13195
  };
13125
13196
  if (sessionId) {
13126
- const existing = await strapi2.documents(SESSION_UID).findOne({
13197
+ const existing = expectedFilters ? await strapi2.documents(SESSION_UID).findFirst({
13198
+ filters: {
13199
+ ...expectedFilters,
13200
+ documentId: sessionId
13201
+ },
13202
+ fields: ["documentId"]
13203
+ }) : await strapi2.documents(SESSION_UID).findOne({
13127
13204
  documentId: sessionId,
13128
13205
  fields: ["documentId"]
13129
13206
  });
@@ -13555,7 +13632,7 @@ var require_session2 = __commonJS({
13555
13632
  var require_package = __commonJS({
13556
13633
  "package.json"(exports, module) {
13557
13634
  module.exports = {
13558
- version: "4.7.1",
13635
+ version: "4.7.2",
13559
13636
  keywords: [
13560
13637
  "strapi",
13561
13638
  "plugin",
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.1",
2
+ "version": "4.7.2",
3
3
  "keywords": [
4
4
  "strapi",
5
5
  "plugin",