@strapi/plugin-users-permissions 5.23.6 → 5.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/server/bootstrap/index.js +26 -7
  2. package/dist/server/bootstrap/index.js.map +1 -1
  3. package/dist/server/bootstrap/index.mjs +26 -7
  4. package/dist/server/bootstrap/index.mjs.map +1 -1
  5. package/dist/server/config.js +16 -0
  6. package/dist/server/config.js.map +1 -1
  7. package/dist/server/config.mjs +16 -0
  8. package/dist/server/config.mjs.map +1 -1
  9. package/dist/server/controllers/auth.js +198 -3
  10. package/dist/server/controllers/auth.js.map +1 -1
  11. package/dist/server/controllers/auth.mjs +198 -3
  12. package/dist/server/controllers/auth.mjs.map +1 -1
  13. package/dist/server/routes/content-api/auth.js +16 -0
  14. package/dist/server/routes/content-api/auth.js.map +1 -1
  15. package/dist/server/routes/content-api/auth.mjs +16 -0
  16. package/dist/server/routes/content-api/auth.mjs.map +1 -1
  17. package/dist/server/routes/content-api/validation.js +1 -0
  18. package/dist/server/routes/content-api/validation.js.map +1 -1
  19. package/dist/server/routes/content-api/validation.mjs +1 -0
  20. package/dist/server/routes/content-api/validation.mjs.map +1 -1
  21. package/dist/server/services/constants.js +19 -0
  22. package/dist/server/services/constants.js.map +1 -0
  23. package/dist/server/services/constants.mjs +17 -0
  24. package/dist/server/services/constants.mjs.map +1 -0
  25. package/dist/server/services/jwt.js +45 -2
  26. package/dist/server/services/jwt.js.map +1 -1
  27. package/dist/server/services/jwt.mjs +45 -2
  28. package/dist/server/services/jwt.mjs.map +1 -1
  29. package/dist/server/services/user.js +29 -20
  30. package/dist/server/services/user.js.map +1 -1
  31. package/dist/server/services/user.mjs +29 -20
  32. package/dist/server/services/user.mjs.map +1 -1
  33. package/package.json +3 -3
  34. package/server/bootstrap/index.js +29 -0
  35. package/server/config.js +22 -0
  36. package/server/controllers/auth.js +232 -8
  37. package/server/routes/content-api/auth.js +12 -0
  38. package/server/routes/content-api/validation.js +1 -0
  39. package/server/services/constants.js +9 -0
  40. package/server/services/jwt.js +50 -2
  41. package/server/services/user.js +11 -0
@@ -31,6 +31,12 @@ const sanitizeUser = (user, ctx) => {
31
31
  return strapi.contentAPI.sanitize.output(user, userSchema, { auth });
32
32
  };
33
33
 
34
+ const extractDeviceId = (requestBody) => {
35
+ const { deviceId } = requestBody || {};
36
+
37
+ return typeof deviceId === 'string' && deviceId.length > 0 ? deviceId : undefined;
38
+ };
39
+
34
40
  module.exports = ({ strapi }) => ({
35
41
  async callback(ctx) {
36
42
  const provider = ctx.params.provider || 'local';
@@ -86,6 +92,45 @@ module.exports = ({ strapi }) => ({
86
92
  throw new ApplicationError('Your account has been blocked by an administrator');
87
93
  }
88
94
 
95
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
96
+ if (mode === 'refresh') {
97
+ const deviceId = extractDeviceId(ctx.request.body);
98
+
99
+ const refresh = await strapi
100
+ .sessionManager('users-permissions')
101
+ .generateRefreshToken(String(user.id), deviceId, { type: 'refresh' });
102
+
103
+ const access = await strapi
104
+ .sessionManager('users-permissions')
105
+ .generateAccessToken(refresh.token);
106
+ if ('error' in access) {
107
+ throw new ApplicationError('Invalid credentials');
108
+ }
109
+
110
+ const upSessions = strapi.config.get('plugin::users-permissions.sessions');
111
+ const requestHttpOnly = ctx.request.header['x-strapi-refresh-cookie'] === 'httpOnly';
112
+ if (upSessions?.httpOnly || requestHttpOnly) {
113
+ const cookieName = upSessions.cookie?.name || 'strapi_up_refresh';
114
+ const cookieOptions = {
115
+ httpOnly: true,
116
+ secure: Boolean(upSessions.cookie?.secure),
117
+ sameSite: upSessions.cookie?.sameSite ?? 'lax',
118
+ path: upSessions.cookie?.path ?? '/',
119
+ domain: upSessions.cookie?.domain,
120
+ overwrite: true,
121
+ };
122
+
123
+ ctx.cookies.set(cookieName, refresh.token, cookieOptions);
124
+ return ctx.send({ jwt: access.token, user: await sanitizeUser(user, ctx) });
125
+ }
126
+
127
+ return ctx.send({
128
+ jwt: access.token,
129
+ refreshToken: refresh.token,
130
+ user: await sanitizeUser(user, ctx),
131
+ });
132
+ }
133
+
89
134
  return ctx.send({
90
135
  jwt: getService('jwt').issue({ id: user.id }),
91
136
  user: await sanitizeUser(user, ctx),
@@ -100,6 +145,43 @@ module.exports = ({ strapi }) => ({
100
145
  throw new ForbiddenError('Your account has been blocked by an administrator');
101
146
  }
102
147
 
148
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
149
+ if (mode === 'refresh') {
150
+ const deviceId = extractDeviceId(ctx.request.body);
151
+
152
+ const refresh = await strapi
153
+ .sessionManager('users-permissions')
154
+ .generateRefreshToken(String(user.id), deviceId, { type: 'refresh' });
155
+
156
+ const access = await strapi
157
+ .sessionManager('users-permissions')
158
+ .generateAccessToken(refresh.token);
159
+ if ('error' in access) {
160
+ throw new ApplicationError('Invalid credentials');
161
+ }
162
+
163
+ const upSessions = strapi.config.get('plugin::users-permissions.sessions');
164
+ const requestHttpOnly = ctx.request.header['x-strapi-refresh-cookie'] === 'httpOnly';
165
+ if (upSessions?.httpOnly || requestHttpOnly) {
166
+ const cookieName = upSessions.cookie?.name || 'strapi_up_refresh';
167
+ const cookieOptions = {
168
+ httpOnly: true,
169
+ secure: Boolean(upSessions.cookie?.secure),
170
+ sameSite: upSessions.cookie?.sameSite ?? 'lax',
171
+ path: upSessions.cookie?.path ?? '/',
172
+ domain: upSessions.cookie?.domain,
173
+ overwrite: true,
174
+ };
175
+ ctx.cookies.set(cookieName, refresh.token, cookieOptions);
176
+ return ctx.send({ jwt: access.token, user: await sanitizeUser(user, ctx) });
177
+ }
178
+ return ctx.send({
179
+ jwt: access.token,
180
+ refreshToken: refresh.token,
181
+ user: await sanitizeUser(user, ctx),
182
+ });
183
+ }
184
+
103
185
  return ctx.send({
104
186
  jwt: getService('jwt').issue({ id: user.id }),
105
187
  user: await sanitizeUser(user, ctx),
@@ -137,7 +219,37 @@ module.exports = ({ strapi }) => ({
137
219
 
138
220
  await getService('user').edit(user.id, { password });
139
221
 
140
- ctx.send({
222
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
223
+ if (mode === 'refresh') {
224
+ const deviceId = extractDeviceId(ctx.request.body);
225
+
226
+ if (deviceId) {
227
+ // Invalidate sessions: specific device if deviceId provided
228
+ await strapi
229
+ .sessionManager('users-permissions')
230
+ .invalidateRefreshToken(String(user.id), deviceId);
231
+ }
232
+
233
+ const newDeviceId = deviceId || crypto.randomUUID();
234
+ const refresh = await strapi
235
+ .sessionManager('users-permissions')
236
+ .generateRefreshToken(String(user.id), newDeviceId, { type: 'refresh' });
237
+
238
+ const access = await strapi
239
+ .sessionManager('users-permissions')
240
+ .generateAccessToken(refresh.token);
241
+ if ('error' in access) {
242
+ throw new ApplicationError('Invalid credentials');
243
+ }
244
+
245
+ return ctx.send({
246
+ jwt: access.token,
247
+ refreshToken: refresh.token,
248
+ user: await sanitizeUser(user, ctx),
249
+ });
250
+ }
251
+
252
+ return ctx.send({
141
253
  jwt: getService('jwt').issue({ id: user.id }),
142
254
  user: await sanitizeUser(user, ctx),
143
255
  });
@@ -168,13 +280,111 @@ module.exports = ({ strapi }) => ({
168
280
  password,
169
281
  });
170
282
 
171
- // Update the user.
172
- ctx.send({
283
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
284
+ if (mode === 'refresh') {
285
+ const deviceId = extractDeviceId(ctx.request.body);
286
+
287
+ if (deviceId) {
288
+ // Invalidate sessions: specific device if deviceId provided
289
+ await strapi
290
+ .sessionManager('users-permissions')
291
+ .invalidateRefreshToken(String(user.id), deviceId);
292
+ }
293
+
294
+ const newDeviceId = deviceId || crypto.randomUUID();
295
+ const refresh = await strapi
296
+ .sessionManager('users-permissions')
297
+ .generateRefreshToken(String(user.id), newDeviceId, { type: 'refresh' });
298
+
299
+ const access = await strapi
300
+ .sessionManager('users-permissions')
301
+ .generateAccessToken(refresh.token);
302
+ if ('error' in access) {
303
+ throw new ApplicationError('Invalid credentials');
304
+ }
305
+
306
+ return ctx.send({
307
+ jwt: access.token,
308
+ refreshToken: refresh.token,
309
+ user: await sanitizeUser(user, ctx),
310
+ });
311
+ }
312
+
313
+ return ctx.send({
173
314
  jwt: getService('jwt').issue({ id: user.id }),
174
315
  user: await sanitizeUser(user, ctx),
175
316
  });
176
317
  },
318
+ async refresh(ctx) {
319
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
320
+ if (mode !== 'refresh') {
321
+ return ctx.notFound();
322
+ }
323
+
324
+ const { refreshToken } = ctx.request.body || {};
325
+ if (!refreshToken || typeof refreshToken !== 'string') {
326
+ return ctx.badRequest('Missing refresh token');
327
+ }
328
+
329
+ const rotation = await strapi
330
+ .sessionManager('users-permissions')
331
+ .rotateRefreshToken(refreshToken);
332
+ if ('error' in rotation) {
333
+ return ctx.unauthorized('Invalid refresh token');
334
+ }
335
+
336
+ const result = await strapi
337
+ .sessionManager('users-permissions')
338
+ .generateAccessToken(rotation.token);
339
+ if ('error' in result) {
340
+ return ctx.unauthorized('Invalid refresh token');
341
+ }
342
+
343
+ const upSessions = strapi.config.get('plugin::users-permissions.sessions');
344
+ const requestHttpOnly = ctx.request.header['x-strapi-refresh-cookie'] === 'httpOnly';
345
+ if (upSessions?.httpOnly || requestHttpOnly) {
346
+ const cookieName = upSessions.cookie?.name || 'strapi_up_refresh';
347
+ const cookieOptions = {
348
+ httpOnly: true,
349
+ secure: Boolean(upSessions.cookie?.secure),
350
+ sameSite: upSessions.cookie?.sameSite ?? 'lax',
351
+ path: upSessions.cookie?.path ?? '/',
352
+ domain: upSessions.cookie?.domain,
353
+ overwrite: true,
354
+ };
355
+ ctx.cookies.set(cookieName, rotation.token, cookieOptions);
356
+ return ctx.send({ jwt: result.token });
357
+ }
358
+ return ctx.send({ jwt: result.token, refreshToken: rotation.token });
359
+ },
360
+ async logout(ctx) {
361
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
362
+ if (mode !== 'refresh') {
363
+ return ctx.notFound();
364
+ }
365
+
366
+ // Invalidate all sessions for the authenticated user, or by deviceId if provided
367
+ if (!ctx.state.user) {
368
+ return ctx.unauthorized('Missing authentication');
369
+ }
370
+
371
+ const deviceId = extractDeviceId(ctx.request.body);
372
+ try {
373
+ await strapi
374
+ .sessionManager('users-permissions')
375
+ .invalidateRefreshToken(String(ctx.state.user.id), deviceId);
376
+ } catch (err) {
377
+ strapi.log.error('UP logout failed', err);
378
+ }
177
379
 
380
+ const upSessions = strapi.config.get('plugin::users-permissions.sessions');
381
+ const requestHttpOnly = ctx.request.header['x-strapi-refresh-cookie'] === 'httpOnly';
382
+ if (upSessions?.httpOnly || requestHttpOnly) {
383
+ const cookieName = upSessions.cookie?.name || 'strapi_up_refresh';
384
+ ctx.cookies.set(cookieName, '', { expires: new Date(0) });
385
+ }
386
+ return ctx.send({ ok: true });
387
+ },
178
388
  async connect(ctx, next) {
179
389
  const grant = require('grant').koa();
180
390
 
@@ -387,12 +597,26 @@ module.exports = ({ strapi }) => ({
387
597
  return ctx.send({ user: sanitizedUser });
388
598
  }
389
599
 
390
- const jwt = getService('jwt').issue(_.pick(user, ['id']));
600
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
601
+ if (mode === 'refresh') {
602
+ const deviceId = extractDeviceId(ctx.request.body) || crypto.randomUUID();
391
603
 
392
- return ctx.send({
393
- jwt,
394
- user: sanitizedUser,
395
- });
604
+ const refresh = await strapi
605
+ .sessionManager('users-permissions')
606
+ .generateRefreshToken(String(user.id), deviceId, { type: 'refresh' });
607
+
608
+ const access = await strapi
609
+ .sessionManager('users-permissions')
610
+ .generateAccessToken(refresh.token);
611
+ if ('error' in access) {
612
+ throw new ApplicationError('Invalid credentials');
613
+ }
614
+
615
+ return ctx.send({ jwt: access.token, refreshToken: refresh.token, user: sanitizedUser });
616
+ }
617
+
618
+ const jwt = getService('jwt').issue(_.pick(user, ['id']));
619
+ return ctx.send({ jwt, user: sanitizedUser });
396
620
  },
397
621
 
398
622
  async emailConfirmation(ctx, next, returnUser) {
@@ -114,5 +114,17 @@ module.exports = (strapi) => {
114
114
  },
115
115
  response: validator.authResponseSchema,
116
116
  },
117
+ {
118
+ method: 'POST',
119
+ path: '/auth/refresh',
120
+ handler: 'auth.refresh',
121
+ config: { prefix: '' },
122
+ },
123
+ {
124
+ method: 'POST',
125
+ path: '/auth/logout',
126
+ handler: 'auth.logout',
127
+ config: { prefix: '' },
128
+ },
117
129
  ];
118
130
  };
@@ -87,6 +87,7 @@ class UsersPermissionsRouteValidator extends AbstractRouteValidator {
87
87
  get authResponseSchema() {
88
88
  return z.object({
89
89
  jwt: z.string(),
90
+ refreshToken: z.string().optional(),
90
91
  user: this.userSchema,
91
92
  });
92
93
  }
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+
3
+ module.exports = {
4
+ DEFAULT_ACCESS_TOKEN_LIFESPAN: 10 * 60, // 10 minutes
5
+ DEFAULT_MAX_REFRESH_TOKEN_LIFESPAN: 30 * 24 * 60 * 60, // 30 days
6
+ DEFAULT_IDLE_REFRESH_TOKEN_LIFESPAN: 14 * 24 * 60 * 60, // 14 days
7
+ DEFAULT_MAX_SESSION_LIFESPAN: 1 * 24 * 60 * 60, // 1 day
8
+ DEFAULT_IDLE_SESSION_LIFESPAN: 2 * 60 * 60, // 2 hours
9
+ };
@@ -29,6 +29,32 @@ module.exports = ({ strapi }) => ({
29
29
  },
30
30
 
31
31
  issue(payload, jwtOptions = {}) {
32
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
33
+
34
+ if (mode === 'refresh') {
35
+ const userId = String(payload.id ?? payload.userId ?? '');
36
+ if (!userId) {
37
+ throw new Error('Cannot issue token: missing user id');
38
+ }
39
+
40
+ const issueRefreshToken = async () => {
41
+ const refresh = await strapi
42
+ .sessionManager('users-permissions')
43
+ .generateRefreshToken(userId, undefined, { type: 'refresh' });
44
+
45
+ const access = await strapi
46
+ .sessionManager('users-permissions')
47
+ .generateAccessToken(refresh.token);
48
+ if ('error' in access) {
49
+ throw new Error('Failed to generate access token');
50
+ }
51
+
52
+ return access.token;
53
+ };
54
+
55
+ return issueRefreshToken();
56
+ }
57
+
32
58
  _.defaults(jwtOptions, strapi.config.get('plugin::users-permissions.jwt'));
33
59
  return jwt.sign(
34
60
  _.clone(payload.toJSON ? payload.toJSON() : payload),
@@ -37,12 +63,34 @@ module.exports = ({ strapi }) => ({
37
63
  );
38
64
  },
39
65
 
40
- verify(token) {
66
+ async verify(token) {
67
+ const mode = strapi.config.get('plugin::users-permissions.jwtManagement', 'legacy-support');
68
+
69
+ if (mode === 'refresh') {
70
+ // Accept only access tokens minted by the SessionManager for UP
71
+ const result = strapi.sessionManager('users-permissions').validateAccessToken(token);
72
+ if (!result.isValid || result.payload.type !== 'access') {
73
+ throw new Error('Invalid token.');
74
+ }
75
+
76
+ const user = await strapi.db
77
+ .query('plugin::users-permissions.user')
78
+ .findOne({ where: { id: Number(result.payload.userId) || result.payload.userId } });
79
+ if (!user) {
80
+ throw new Error('Invalid token.');
81
+ }
82
+
83
+ return { id: user.id };
84
+ }
85
+
41
86
  return new Promise((resolve, reject) => {
87
+ const jwtConfig = strapi.config.get('plugin::users-permissions.jwt', {});
88
+ const algorithms = jwtConfig && jwtConfig.algorithm ? [jwtConfig.algorithm] : undefined;
89
+
42
90
  jwt.verify(
43
91
  token,
44
92
  strapi.config.get('plugin::users-permissions.jwtSecret'),
45
- {},
93
+ algorithms ? { algorithms } : {},
46
94
  (err, tokenPayload = {}) => {
47
95
  if (err) {
48
96
  return reject(new Error('Invalid token.'));
@@ -16,6 +16,11 @@ const { getService } = require('../utils');
16
16
 
17
17
  const USER_MODEL_UID = 'plugin::users-permissions.user';
18
18
 
19
+ const getSessionManager = () => {
20
+ const manager = strapi.sessionManager;
21
+ return manager ?? null;
22
+ };
23
+
19
24
  module.exports = ({ strapi }) => ({
20
25
  /**
21
26
  * Promise to count users
@@ -112,6 +117,12 @@ module.exports = ({ strapi }) => ({
112
117
  * @return {Promise}
113
118
  */
114
119
  async remove(params) {
120
+ // Invalidate sessions for all affected users
121
+ const sessionManager = getSessionManager();
122
+ if (sessionManager && sessionManager.hasOrigin('users-permissions') && params.id) {
123
+ await sessionManager('users-permissions').invalidateRefreshToken(String(params.id));
124
+ }
125
+
115
126
  return strapi.db.query(USER_MODEL_UID).delete({ where: params });
116
127
  },
117
128