@astratra/saas-kit 1.7.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -30,13 +30,21 @@ const app = createSaasApp({
30
30
  verifyPassword: async (user, password) => passwordService.verify(user, password),
31
31
  notify: async (userId, notification) => notificationService.send(userId, notification),
32
32
  roles: {
33
- adminRoles: ['owner', 'admin']
33
+ adminRoles: ['owner', 'admin'],
34
+ ownerRoles: ['owner']
34
35
  }
35
36
  });
36
37
 
37
38
  app.listen(3000);
38
39
  ```
39
40
 
41
+ Les routes `/users` n'écrivent que les champs de `writableUserFields` (par défaut
42
+ `email`, `role`, `name`) : `id`, mot de passe, empreinte et jetons envoyés dans
43
+ la requête sont ignorés. Un administrateur gère les comptes ordinaires ;
44
+ donner un rôle d'administrateur (propriétaire compris) ou modifier le compte
45
+ d'un autre administrateur est réservé aux `ownerRoles`. Le rôle de la personne
46
+ qui agit est relu dans le store, pas dans son jeton.
47
+
40
48
  Ça donne immédiatement à un nouveau projet une API fonctionnelle :
41
49
 
42
50
  - `POST /auth/login`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/saas-kit",
3
- "version": "1.7.0",
3
+ "version": "2.0.0",
4
4
  "description": "Reusable backend starter kit that assembles Astratra core, security, and AI packages.",
5
5
  "engines": {
6
6
  "node": ">=20"
package/src/app.js CHANGED
@@ -36,7 +36,9 @@ const { DEFAULT_PUBLIC_USER_FIELDS, assertAdapter } = require('./utils');
36
36
 
37
37
  const DEFAULT_JWT_SECRET = 'saas-kit-dev-secret';
38
38
  const DEFAULT_ROLES = {
39
- adminRoles: ['owner', 'admin']
39
+ adminRoles: ['owner', 'admin'],
40
+ /* Only these roles may grant an admin role or manage another admin (see modules/users.js). */
41
+ ownerRoles: ['owner']
40
42
  };
41
43
 
42
44
  function normalizeOptions(options = {}) {
@@ -101,6 +103,7 @@ function normalizeOptions(options = {}) {
101
103
  notify,
102
104
  verifyPassword,
103
105
  roles,
106
+ writableUserFields: Array.isArray(options.writableUserFields) ? options.writableUserFields : null,
104
107
  publicUserFields
105
108
  };
106
109
  }
@@ -225,7 +228,10 @@ function createSaasApp(options = {}) {
225
228
  app.use('/users', authMiddleware, csrfMiddleware, createUsersRoutes({
226
229
  usersStore: normalized.usersStore,
227
230
  authorizeAdmin,
228
- publicUserFields: normalized.publicUserFields
231
+ publicUserFields: normalized.publicUserFields,
232
+ adminRoles: normalized.roles.adminRoles,
233
+ ownerRoles: normalized.roles.ownerRoles,
234
+ ...(normalized.writableUserFields ? { writableUserFields: normalized.writableUserFields } : {})
229
235
  }));
230
236
  app.use('/settings', authMiddleware, csrfMiddleware, createSettingsRoutes({
231
237
  settingsStore: normalized.settingsStore,
package/src/index.d.ts CHANGED
@@ -67,6 +67,8 @@ export interface NotificationPayload {
67
67
 
68
68
  export interface SaasRoles {
69
69
  adminRoles?: string[];
70
+ /** Roles that may grant an admin role or manage another admin's account. Default ['owner']. */
71
+ ownerRoles?: string[];
70
72
  [key: string]: unknown;
71
73
  }
72
74
 
@@ -144,6 +146,11 @@ export interface CreateSaasAppOptions {
144
146
  hashPassword?: (password: string) => Promise<string> | string;
145
147
  extractToken?: AuthMiddlewareOptions['extractToken'];
146
148
  roles?: SaasRoles;
149
+ /**
150
+ * Fields an admin may write through POST/PATCH /users. Default ['email', 'role', 'name'].
151
+ * id, password, passwordHash, hash, salt and tokens are never writable there.
152
+ */
153
+ writableUserFields?: string[];
147
154
  publicUserFields?: string[];
148
155
  cookie?: SessionCookieOptions;
149
156
  csrf?: CsrfMiddlewareOptions;
@@ -3,20 +3,69 @@ const { body, param } = require('express-validator');
3
3
  const { apiResponse, AppError, asyncHandler, validateMiddleware } = require('@astratra/core');
4
4
  const { sanitizeUser, toPagination } = require('../utils');
5
5
 
6
+ /**
7
+ * The only fields an admin may write through these routes. Everything else in
8
+ * the request body is dropped — never `id`, a password, a hash, a token or any
9
+ * field the store happens to keep (mass assignment). Passwords change through
10
+ * the auth routes (reset), never here.
11
+ */
12
+ const DEFAULT_WRITABLE_USER_FIELDS = ['email', 'role', 'name'];
13
+ const NEVER_WRITABLE = new Set(['id', '_id', 'password', 'passwordHash', 'hash', 'salt', 'tokens', 'refreshToken', 'sessions']);
14
+
6
15
  const createUserValidation = [
7
16
  body('email').isEmail().withMessage('email must be a valid email address'),
8
17
  body('role').optional().isString().trim().notEmpty().withMessage('role must not be empty when provided')
9
18
  ];
10
19
 
20
+ const updateUserValidation = [
21
+ param('id').notEmpty().withMessage('id is required'),
22
+ body('email').optional().isEmail().withMessage('email must be a valid email address'),
23
+ body('role').optional().isString().trim().notEmpty().withMessage('role must not be empty when provided')
24
+ ];
25
+
11
26
  const userIdValidation = [
12
27
  param('id').notEmpty().withMessage('id is required')
13
28
  ];
14
29
 
15
- function createUsersRoutes({ usersStore, authorizeAdmin, publicUserFields }) {
30
+ function pickWritable(input, fields) {
31
+ const source = input && typeof input === 'object' ? input : {};
32
+ return fields.reduce((picked, field) => {
33
+ if (!NEVER_WRITABLE.has(field) && Object.prototype.hasOwnProperty.call(source, field)) {
34
+ picked[field] = source[field];
35
+ }
36
+ return picked;
37
+ }, {});
38
+ }
39
+
40
+ function createUsersRoutes({ usersStore, authorizeAdmin, publicUserFields, adminRoles = ['owner', 'admin'], ownerRoles = ['owner'], writableUserFields = DEFAULT_WRITABLE_USER_FIELDS }) {
16
41
  const router = express.Router();
17
42
 
18
43
  router.use(authorizeAdmin);
19
44
 
45
+ /**
46
+ * Who may grant or change what. An admin manages ordinary accounts only:
47
+ * granting an admin role (owner included), or touching another admin's
48
+ * account, is for an owner. The caller's role is read from the store, not
49
+ * from the token, so a demotion applies at once.
50
+ */
51
+ async function assertMayWrite(req, target, nextRole) {
52
+ const caller = req.user && req.user.id ? await usersStore.findById(req.user.id) : null;
53
+ const callerRole = caller ? caller.role : null;
54
+ if (!callerRole || !adminRoles.includes(callerRole)) {
55
+ throw new AppError('Forbidden.', 403);
56
+ }
57
+ if (ownerRoles.includes(callerRole)) return;
58
+ if (nextRole !== undefined && adminRoles.includes(nextRole)) {
59
+ throw new AppError('Only an owner can grant this role.', 403);
60
+ }
61
+ if (target && adminRoles.includes(target.role)) {
62
+ const self = String(target.id) === String(caller.id);
63
+ if (!self || (nextRole !== undefined && nextRole !== target.role)) {
64
+ throw new AppError('Only an owner can change this account.', 403);
65
+ }
66
+ }
67
+ }
68
+
20
69
  router.get('/', asyncHandler(async (req, res) => {
21
70
  const pagination = toPagination(req.query);
22
71
  const users = await usersStore.list(pagination);
@@ -37,12 +86,20 @@ function createUsersRoutes({ usersStore, authorizeAdmin, publicUserFields }) {
37
86
  }));
38
87
 
39
88
  router.post('/', validateMiddleware(createUserValidation), asyncHandler(async (req, res) => {
40
- const user = await usersStore.create(req.body);
89
+ const data = pickWritable(req.body, writableUserFields);
90
+ await assertMayWrite(req, null, data.role);
91
+ const user = await usersStore.create(data);
41
92
  return apiResponse(res, 201, 'User created', sanitizeUser(user, publicUserFields));
42
93
  }));
43
94
 
44
- router.patch('/:id', validateMiddleware(userIdValidation), asyncHandler(async (req, res) => {
45
- const user = await usersStore.update(req.params.id, req.body || {});
95
+ router.patch('/:id', validateMiddleware(updateUserValidation), asyncHandler(async (req, res) => {
96
+ const target = await usersStore.findById(req.params.id);
97
+ if (!target) {
98
+ throw new AppError('User not found.', 404);
99
+ }
100
+ const patch = pickWritable(req.body, writableUserFields);
101
+ await assertMayWrite(req, target, patch.role);
102
+ const user = await usersStore.update(req.params.id, patch);
46
103
  if (!user) {
47
104
  throw new AppError('User not found.', 404);
48
105
  }
@@ -54,3 +111,4 @@ function createUsersRoutes({ usersStore, authorizeAdmin, publicUserFields }) {
54
111
  }
55
112
 
56
113
  module.exports = createUsersRoutes;
114
+ module.exports.DEFAULT_WRITABLE_USER_FIELDS = DEFAULT_WRITABLE_USER_FIELDS;
@@ -1,16 +1,13 @@
1
+ /*
2
+ * Example accounts WITHOUT credentials: nobody can sign in with them. A clear
3
+ * password (the old 'password') was a ready-made login for anyone who knew the
4
+ * kit. Seed your own accounts with a hash: options.users =
5
+ * [{ id, email, role, passwordHash: await hashPassword(...) }] (@astratra/security),
6
+ * and verifyPassword: (user, p) => verifyPasswordHash(p, user.passwordHash).
7
+ */
1
8
  const DEFAULT_USERS = [
2
- {
3
- id: 'user-owner',
4
- email: 'owner@example.test',
5
- role: 'owner',
6
- password: 'password'
7
- },
8
- {
9
- id: 'user-member',
10
- email: 'member@example.test',
11
- role: 'member',
12
- password: 'password'
13
- }
9
+ { id: 'user-owner', email: 'owner@example.test', role: 'owner' },
10
+ { id: 'user-member', email: 'member@example.test', role: 'member' }
14
11
  ];
15
12
 
16
13
  function clone(value) {