@astratra/saas-kit 1.6.1 → 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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Astratra
3
+ Copyright (c) 2026 Astratra contributors
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
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`
@@ -90,6 +98,30 @@ L'app retournée expose aussi directement `app.authMiddleware`,
90
98
  `app.csrfMiddleware` et `app.authorizeAdmin`, au cas où tu préfères les
91
99
  monter toi-même après coup plutôt que via `extendRoutes`.
92
100
 
101
+ ### Ouvrir une session depuis ta propre route (Google, Apple, invitation)
102
+
103
+ Quand ta route a prouvé l'identité elle-même (jeton d'identité vérifié par
104
+ `createGoogleIdTokenVerifier` de `@astratra/security`, invitation acceptée),
105
+ `issueSession(res, compte)` ouvre **exactement** la session de `/auth/login` :
106
+ même jeton d'accès, même cookie `HttpOnly`, même chaîne de renouvellement.
107
+ Une seule fabrique, pour que les deux portes ne divergent jamais.
108
+
109
+ ```js
110
+ createSaasApp({
111
+ // ...
112
+ extendRoutes: (app, { issueSession }) => {
113
+ app.post('/auth/external/google', async (req, res) => {
114
+ const profile = await google(req.body.idToken);
115
+ const account = await accounts.findBySubject('google', profile.subject);
116
+ if (!account) return res.status(403).json({ code: 'not_invited' });
117
+ res.json(await issueSession(res, account)); // { token, user, refreshToken? }
118
+ });
119
+ }
120
+ });
121
+ ```
122
+
123
+ Elle est aussi exposée en `app.issueSession`.
124
+
93
125
  ## CORS
94
126
 
95
127
  `options.cors` active le CORS pour toute l'app en un seul champ de
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/saas-kit",
3
- "version": "1.6.1",
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
  }
@@ -212,16 +215,23 @@ function createSaasApp(options = {}) {
212
215
  || Boolean(userLoginSkip && userLoginSkip(req, res))
213
216
  });
214
217
 
215
- app.use('/auth', loginLimiter, createAuthRoutes({
218
+ const authRoutes = createAuthRoutes({
216
219
  ...normalized,
217
220
  authMiddleware,
218
221
  csrfMiddleware
219
- }));
222
+ });
223
+ app.use('/auth', loginLimiter, authRoutes);
224
+ /* Opens the same session as /auth/login for an identity the product proved
225
+ itself (Google, Apple, an invitation): one issuer, never a second one. */
226
+ const issueSession = authRoutes.issueSession;
220
227
 
221
228
  app.use('/users', authMiddleware, csrfMiddleware, createUsersRoutes({
222
229
  usersStore: normalized.usersStore,
223
230
  authorizeAdmin,
224
- publicUserFields: normalized.publicUserFields
231
+ publicUserFields: normalized.publicUserFields,
232
+ adminRoles: normalized.roles.adminRoles,
233
+ ownerRoles: normalized.roles.ownerRoles,
234
+ ...(normalized.writableUserFields ? { writableUserFields: normalized.writableUserFields } : {})
225
235
  }));
226
236
  app.use('/settings', authMiddleware, csrfMiddleware, createSettingsRoutes({
227
237
  settingsStore: normalized.settingsStore,
@@ -242,6 +252,7 @@ function createSaasApp(options = {}) {
242
252
  app.authMiddleware = authMiddleware;
243
253
  app.csrfMiddleware = csrfMiddleware;
244
254
  app.authorizeAdmin = authorizeAdmin;
255
+ app.issueSession = issueSession;
245
256
 
246
257
  // createSaasApp() already terminates its own middleware stack with a
247
258
  // catch-all 404 + error handler below. Any route registered on `app`
@@ -258,7 +269,7 @@ function createSaasApp(options = {}) {
258
269
  // }
259
270
  // });
260
271
  if (typeof normalized.extendRoutes === 'function') {
261
- normalized.extendRoutes(app, { authMiddleware, csrfMiddleware, authorizeAdmin, authorizeRoles });
272
+ normalized.extendRoutes(app, { authMiddleware, csrfMiddleware, authorizeAdmin, authorizeRoles, issueSession });
262
273
  }
263
274
 
264
275
  app.use(notFoundMiddleware);
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
 
@@ -79,14 +81,30 @@ export interface SaasApp {
79
81
  csrfMiddleware: RequestHandler;
80
82
  /** authorizeRoles(...options.roles.adminRoles) — the exact admin-role guard used internally. */
81
83
  authorizeAdmin: RequestHandler;
84
+ /** Opens the same session as /auth/login for an account the product proved itself. */
85
+ issueSession: IssueSession;
82
86
  [key: string]: unknown;
83
87
  }
84
88
 
89
+ /** The body /auth/login answers with. */
90
+ export interface IssuedSession {
91
+ token: string;
92
+ user: Record<string, unknown>;
93
+ refreshToken?: string;
94
+ }
95
+
96
+ /**
97
+ * Opens a session (access token, session cookie when `res` is given, refresh
98
+ * chain when enabled) for an account whose identity is already proven.
99
+ */
100
+ export type IssueSession = (res: unknown, user: { id: unknown; [key: string]: unknown }) => Promise<IssuedSession>;
101
+
85
102
  export interface ExtendRoutesContext {
86
103
  authMiddleware: RequestHandler;
87
104
  csrfMiddleware: RequestHandler;
88
105
  authorizeAdmin: RequestHandler;
89
106
  authorizeRoles: (...roles: string[]) => RequestHandler;
107
+ issueSession: IssueSession;
90
108
  }
91
109
 
92
110
  export interface CreateSaasAppOptions {
@@ -128,6 +146,11 @@ export interface CreateSaasAppOptions {
128
146
  hashPassword?: (password: string) => Promise<string> | string;
129
147
  extractToken?: AuthMiddlewareOptions['extractToken'];
130
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[];
131
154
  publicUserFields?: string[];
132
155
  cookie?: SessionCookieOptions;
133
156
  csrf?: CsrfMiddlewareOptions;
@@ -70,13 +70,15 @@ function createAuthRoutes(options) {
70
70
  }
71
71
  );
72
72
 
73
- router.post('/login', validateMiddleware(loginValidation), asyncHandler(async (req, res) => {
74
- const user = await usersStore.findByEmail(req.body.email);
75
- const valid = user ? await verifyPassword(user, req.body.password) : false;
76
- if (!user || !valid) {
77
- throw new AppError('Invalid credentials.', 401);
78
- }
79
-
73
+ /**
74
+ * Open a session for an account whose identity is already proven — by the
75
+ * password here, or by the product's own route (an ID token from Google or
76
+ * Apple, an invitation). One function, so that every way in yields exactly
77
+ * the same session: same access token, same cookie, same refresh chain.
78
+ * Returns the body the login route answers with.
79
+ */
80
+ async function issueSession(res, user) {
81
+ if (!user || user.id === undefined || user.id === null) throw new Error('issueSession requires an account with an id.');
80
82
  const publicUser = pickPublicUser(user, publicUserFields);
81
83
 
82
84
  /* A refresh token is issued only when the product asked for one. The web
@@ -90,13 +92,23 @@ function createAuthRoutes(options) {
90
92
  /* The family id travels in the access token so that signing out can revoke
91
93
  the refresh chain without the client having to hand it back. */
92
94
  const token = signAccessToken(publicUser, refresh ? { rfid: refresh.familyId } : {});
93
- setSessionCookie(res, token, cookieOptions);
95
+ if (res) setSessionCookie(res, token, cookieOptions);
94
96
 
95
- return apiResponse(res, 200, 'Login successful', {
97
+ return {
96
98
  token,
97
99
  user: publicUser,
98
100
  ...(refresh ? { refreshToken: refresh.token } : {})
99
- });
101
+ };
102
+ }
103
+
104
+ router.post('/login', validateMiddleware(loginValidation), asyncHandler(async (req, res) => {
105
+ const user = await usersStore.findByEmail(req.body.email);
106
+ const valid = user ? await verifyPassword(user, req.body.password) : false;
107
+ if (!user || !valid) {
108
+ throw new AppError('Invalid credentials.', 401);
109
+ }
110
+
111
+ return apiResponse(res, 200, 'Login successful', await issueSession(res, user));
100
112
  }));
101
113
 
102
114
  if (refreshTokenService) {
@@ -253,6 +265,7 @@ function createAuthRoutes(options) {
253
265
  }));
254
266
  }
255
267
 
268
+ router.issueSession = issueSession;
256
269
  return router;
257
270
  }
258
271
 
@@ -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) {