@astratra/saas-kit 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @astratra/saas-kit
2
+
3
+ Starter backend réutilisable pour démarrer une nouvelle API SaaS avec les
4
+ packages Astratra.
5
+
6
+ `createSaasApp(options)` retourne une app Express avec des routes
7
+ génériques auth, users, settings, notifications et dashboard. Il assemble :
8
+
9
+ - `@astratra/core` pour les request IDs, le format de réponse API, le 404 et
10
+ la gestion d'erreurs.
11
+ - `@astratra/security` pour le WAF, le rate limiting, l'auth JWT,
12
+ l'autorisation par rôle, et le service WebAuthn optionnel.
13
+ - `@astratra/ai` en dépendance du package pour qu'un projet puisse composer
14
+ des fonctionnalités IA à côté du starter, sans que le kit n'impose de
15
+ routes IA métier.
16
+
17
+ ## Démarrage rapide
18
+
19
+ ```js
20
+ const { createSaasApp } = require('@astratra/saas-kit');
21
+
22
+ const app = createSaasApp({
23
+ jwtSecret: process.env.JWT_SECRET,
24
+ usersStore,
25
+ settingsStore,
26
+ verifyPassword: async (user, password) => passwordService.verify(user, password),
27
+ notify: async (userId, notification) => notificationService.send(userId, notification),
28
+ roles: {
29
+ adminRoles: ['owner', 'admin']
30
+ }
31
+ });
32
+
33
+ app.listen(3000);
34
+ ```
35
+
36
+ Ça donne immédiatement à un nouveau projet une API fonctionnelle :
37
+
38
+ - `POST /auth/login`
39
+ - `GET /auth/me`
40
+ - `GET /users`
41
+ - `GET /users/:id`
42
+ - `POST /users`
43
+ - `PATCH /users/:id`
44
+ - `GET /settings`
45
+ - `PATCH /settings/:key`
46
+ - `POST /notifications/send`
47
+ - `GET /dashboard/summary`
48
+
49
+ Toutes les routes protégées suivent le même ordre de middlewares de
50
+ sécurité que la mini-app de démo : request id, parseur JSON, WAF, limiteur
51
+ API, limiteur de login pour `/auth`, auth JWT pour les modules protégés,
52
+ puis 404 et gestion d'erreurs.
53
+
54
+ ## Adapters requis
55
+
56
+ Une vraie application en production doit injecter ses propres adapters. Le
57
+ kit ne choisit ni base de données, ni algorithme de hash de mot de passe, ni
58
+ canal de notification, ni rôles spécifiques à un produit.
59
+
60
+ ```js
61
+ const usersStore = {
62
+ findByEmail(email) {},
63
+ findById(id) {},
64
+ create(userData) {},
65
+ list({ role, limit, offset }) {},
66
+ update(id, patch) {}
67
+ };
68
+
69
+ const settingsStore = {
70
+ get(key) {},
71
+ set(key, value) {},
72
+ getAll() {}
73
+ };
74
+ ```
75
+
76
+ `verifyPassword(user, password)` est également injecté, pour que
77
+ l'application consommatrice garde la main sur le hashing et les règles de
78
+ credentials. `notify(userId, { title, message, channel })` est injecté pour
79
+ que la livraison puisse être un email, un push, une notification in-app, ou
80
+ tout autre canal.
81
+
82
+ Les routes WebAuthn ne sont montées que si `webauthnStore` est fourni. Le
83
+ store est transmis au service WebAuthn de `@astratra/security`.
84
+
85
+ ## Stores mémoire — développement uniquement
86
+
87
+ Le package exporte :
88
+
89
+ ```js
90
+ const {
91
+ createMemoryUsersStore,
92
+ createMemorySettingsStore
93
+ } = require('@astratra/saas-kit');
94
+ ```
95
+
96
+ Ces stores servent uniquement au développement local, aux démos et aux
97
+ tests. Les données restent en mémoire process, ne sont pas persistantes, et
98
+ sont perdues au redémarrage. À remplacer avant toute utilisation en
99
+ production.
100
+
101
+ Si `usersStore` ou `settingsStore` sont omis, `createSaasApp` utilise ces
102
+ stores mémoire dev-only pour que le starter démarre immédiatement.
103
+ `verifyPassword` et `notify` sont toujours injectés par l'app
104
+ consommatrice ; le kit ne fournit ni algorithme de mot de passe ni
105
+ comportement de livraison de notification.
106
+
107
+ ## Tableau de bord
108
+
109
+ `GET /dashboard/summary` retourne uniquement des stats génériques de
110
+ plateforme :
111
+
112
+ ```json
113
+ {
114
+ "userCount": 2,
115
+ "roleBreakdown": {
116
+ "owner": 1,
117
+ "member": 1
118
+ }
119
+ }
120
+ ```
121
+
122
+ Les KPI spécifiques au projet doivent être ajoutés par l'app consommatrice,
123
+ en dehors de ce kit.
124
+
125
+ ## Tests
126
+
127
+ ```bash
128
+ npm test --workspace @astratra/saas-kit
129
+ ```
130
+
131
+ Les tests d'intégration utilisent `node --test` et exercent l'app Express
132
+ sans ouvrir de vrai listener réseau, ce qui les rend exécutables dans des
133
+ sandboxes restreintes.
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@astratra/saas-kit",
3
+ "version": "0.1.0",
4
+ "description": "Reusable backend starter kit that assembles Astratra core, security, and AI packages.",
5
+ "main": "src/index.js",
6
+ "types": "src/index.d.ts",
7
+ "type": "commonjs",
8
+ "files": [
9
+ "src"
10
+ ],
11
+ "scripts": {
12
+ "test": "node --test __tests__/*.test.js"
13
+ },
14
+ "keywords": [
15
+ "astratra",
16
+ "saas",
17
+ "starter"
18
+ ],
19
+ "license": "MIT",
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "dependencies": {
24
+ "@astratra/ai": "^0.1.0",
25
+ "@astratra/core": "^0.1.0",
26
+ "@astratra/security": "^0.1.0",
27
+ "express": "^4.18.3",
28
+ "jsonwebtoken": "^9.0.2"
29
+ },
30
+ "devDependencies": {
31
+ "supertest": "^7.0.0"
32
+ }
33
+ }
package/src/app.js ADDED
@@ -0,0 +1,104 @@
1
+ const express = require('express');
2
+ const {
3
+ errorMiddleware,
4
+ notFoundMiddleware,
5
+ requestIdMiddleware
6
+ } = require('@astratra/core');
7
+ const {
8
+ authorizeRoles,
9
+ createApiLimiter,
10
+ createAuthMiddleware,
11
+ createLoginLimiter,
12
+ createWafMiddleware
13
+ } = require('@astratra/security');
14
+ const createAuthRoutes = require('./modules/auth');
15
+ const createDashboardRoutes = require('./modules/dashboard');
16
+ const createNotificationsRoutes = require('./modules/notifications');
17
+ const createSettingsRoutes = require('./modules/settings');
18
+ const createUsersRoutes = require('./modules/users');
19
+ const createMemorySettingsStore = require('./stores/memorySettingsStore');
20
+ const createMemoryUsersStore = require('./stores/memoryUsersStore');
21
+ const { DEFAULT_PUBLIC_USER_FIELDS, assertAdapter } = require('./utils');
22
+
23
+ const DEFAULT_JWT_SECRET = 'saas-kit-dev-secret';
24
+ const DEFAULT_ROLES = {
25
+ adminRoles: ['owner', 'admin']
26
+ };
27
+
28
+ function normalizeOptions(options = {}) {
29
+ const jwtSecret = options.jwtSecret || process.env.JWT_SECRET || DEFAULT_JWT_SECRET;
30
+ const usersStore = options.usersStore || createMemoryUsersStore();
31
+ const settingsStore = options.settingsStore || createMemorySettingsStore();
32
+ const notify = options.notify;
33
+ const verifyPassword = options.verifyPassword;
34
+ const roles = { ...DEFAULT_ROLES, ...(options.roles || {}) };
35
+ const publicUserFields = options.publicUserFields || DEFAULT_PUBLIC_USER_FIELDS;
36
+
37
+ assertAdapter(usersStore, ['findByEmail', 'findById', 'create', 'list', 'update'], 'options.usersStore');
38
+ assertAdapter(settingsStore, ['get', 'set', 'getAll'], 'options.settingsStore');
39
+ if (typeof notify !== 'function') {
40
+ throw new Error('createSaasApp requires options.notify to be a function.');
41
+ }
42
+ if (typeof verifyPassword !== 'function') {
43
+ throw new Error('createSaasApp requires options.verifyPassword to be a function.');
44
+ }
45
+
46
+ return {
47
+ ...options,
48
+ jwtSecret,
49
+ usersStore,
50
+ settingsStore,
51
+ notify,
52
+ verifyPassword,
53
+ roles,
54
+ publicUserFields
55
+ };
56
+ }
57
+
58
+ function createSaasApp(options = {}) {
59
+ const normalized = normalizeOptions(options);
60
+ const app = express();
61
+
62
+ app.use(requestIdMiddleware);
63
+ app.use(express.json());
64
+ app.use(createWafMiddleware(normalized.waf));
65
+ app.use(createApiLimiter(normalized.apiRateLimit));
66
+
67
+ const authMiddleware = createAuthMiddleware({
68
+ secret: normalized.jwtSecret,
69
+ legacySecret: normalized.legacyJwtSecret,
70
+ verifySession: normalized.verifySession,
71
+ extractToken: normalized.extractToken
72
+ });
73
+ const authorizeAdmin = authorizeRoles(...normalized.roles.adminRoles);
74
+
75
+ app.use('/auth', createLoginLimiter(normalized.loginRateLimit), createAuthRoutes({
76
+ ...normalized,
77
+ authMiddleware
78
+ }));
79
+
80
+ app.use('/users', authMiddleware, createUsersRoutes({
81
+ usersStore: normalized.usersStore,
82
+ authorizeAdmin
83
+ }));
84
+ app.use('/settings', authMiddleware, createSettingsRoutes({
85
+ settingsStore: normalized.settingsStore,
86
+ authorizeAdmin
87
+ }));
88
+ app.use('/notifications', authMiddleware, createNotificationsRoutes({
89
+ notify: normalized.notify,
90
+ authorizeAdmin
91
+ }));
92
+ app.use('/dashboard', authMiddleware, createDashboardRoutes({
93
+ usersStore: normalized.usersStore
94
+ }));
95
+
96
+ app.use(notFoundMiddleware);
97
+ app.use(errorMiddleware);
98
+
99
+ return app;
100
+ }
101
+
102
+ module.exports = {
103
+ createSaasApp
104
+ };
package/src/index.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ import type {
2
+ AuthMiddlewareOptions,
3
+ LoginLimiterOptions,
4
+ RateLimitOptions,
5
+ WafOptions,
6
+ WebauthnOptions,
7
+ WebauthnStore
8
+ } from '@astratra/security';
9
+
10
+ export type Awaitable<T> = T | Promise<T>;
11
+
12
+ export interface SaasUser {
13
+ id?: string;
14
+ email?: string;
15
+ role?: string;
16
+ password?: string;
17
+ passwordHash?: string;
18
+ [key: string]: unknown;
19
+ }
20
+
21
+ export interface UserListOptions {
22
+ role?: string;
23
+ limit?: number;
24
+ offset?: number;
25
+ }
26
+
27
+ export interface UsersStore {
28
+ findByEmail(email: string): Awaitable<SaasUser | null>;
29
+ findById(id: string): Awaitable<SaasUser | null>;
30
+ create(userData: SaasUser): Awaitable<SaasUser>;
31
+ list(options?: UserListOptions): Awaitable<SaasUser[]>;
32
+ update(id: string, patch: Partial<SaasUser>): Awaitable<SaasUser | null>;
33
+ }
34
+
35
+ export interface MemoryUsersStoreOptions {
36
+ users?: SaasUser[];
37
+ }
38
+
39
+ export function createMemoryUsersStore(options?: MemoryUsersStoreOptions): UsersStore;
40
+
41
+ export interface SettingsStore {
42
+ get(key: string): Awaitable<unknown | null>;
43
+ set(key: string, value: unknown): Awaitable<unknown>;
44
+ getAll(): Awaitable<Record<string, unknown>>;
45
+ }
46
+
47
+ export function createMemorySettingsStore(initialSettings?: Record<string, unknown>): SettingsStore;
48
+
49
+ export interface NotificationPayload {
50
+ title: string;
51
+ message: string;
52
+ channel?: unknown;
53
+ }
54
+
55
+ export interface SaasRoles {
56
+ adminRoles?: string[];
57
+ [key: string]: unknown;
58
+ }
59
+
60
+ export interface SaasApp {
61
+ use(...handlers: unknown[]): SaasApp;
62
+ listen?(...args: unknown[]): unknown;
63
+ [key: string]: unknown;
64
+ }
65
+
66
+ export interface CreateSaasAppOptions {
67
+ jwtSecret?: string;
68
+ legacyJwtSecret?: string;
69
+ jwtExpiresIn?: string | number;
70
+ usersStore?: UsersStore;
71
+ settingsStore?: SettingsStore;
72
+ notify: (userId: string, notification: NotificationPayload) => Awaitable<unknown>;
73
+ verifyPassword: (user: SaasUser, password: string) => Awaitable<boolean>;
74
+ verifySession?: AuthMiddlewareOptions['verifySession'];
75
+ extractToken?: AuthMiddlewareOptions['extractToken'];
76
+ roles?: SaasRoles;
77
+ publicUserFields?: string[];
78
+ webauthnStore?: WebauthnStore;
79
+ webauthn?: WebauthnOptions;
80
+ waf?: WafOptions;
81
+ apiRateLimit?: RateLimitOptions;
82
+ loginRateLimit?: LoginLimiterOptions;
83
+ [key: string]: unknown;
84
+ }
85
+
86
+ export function createSaasApp(options: CreateSaasAppOptions): SaasApp;
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ const { createSaasApp } = require('./app');
2
+ const createMemorySettingsStore = require('./stores/memorySettingsStore');
3
+ const createMemoryUsersStore = require('./stores/memoryUsersStore');
4
+
5
+ module.exports = {
6
+ createSaasApp,
7
+ createMemorySettingsStore,
8
+ createMemoryUsersStore
9
+ };
@@ -0,0 +1,65 @@
1
+ const express = require('express');
2
+ const jwt = require('jsonwebtoken');
3
+ const { apiResponse, AppError, asyncHandler } = require('@astratra/core');
4
+ const { createWebauthnService } = require('@astratra/security');
5
+ const { pickPublicUser, requireBodyFields } = require('../utils');
6
+
7
+ function createAuthRoutes(options) {
8
+ const router = express.Router();
9
+ const {
10
+ jwtSecret,
11
+ usersStore,
12
+ verifyPassword,
13
+ publicUserFields,
14
+ webauthnStore,
15
+ webauthn
16
+ } = options;
17
+
18
+ router.post('/login', asyncHandler(async (req, res) => {
19
+ requireBodyFields(req.body || {}, ['email', 'password']);
20
+
21
+ const user = await usersStore.findByEmail(req.body.email);
22
+ const valid = user ? await verifyPassword(user, req.body.password) : false;
23
+ if (!user || !valid) {
24
+ throw new AppError('Invalid credentials.', 401);
25
+ }
26
+
27
+ const publicUser = pickPublicUser(user, publicUserFields);
28
+ const token = jwt.sign(publicUser, jwtSecret, { expiresIn: options.jwtExpiresIn || '1h' });
29
+ return apiResponse(res, 200, 'Login successful', { token, user: publicUser });
30
+ }));
31
+
32
+ router.get('/me', options.authMiddleware, (req, res) => (
33
+ apiResponse(res, 200, 'Current user', pickPublicUser(req.user, publicUserFields))
34
+ ));
35
+
36
+ if (webauthnStore) {
37
+ router.post('/webauthn/register/options', options.authMiddleware, asyncHandler(async (req, res) => {
38
+ const service = createWebauthnService(webauthnStore, webauthn);
39
+ const data = await service.getRegistrationOptions(req, req.user.id, req.user.email || req.user.id);
40
+ return apiResponse(res, 200, 'WebAuthn registration options', data);
41
+ }));
42
+
43
+ router.post('/webauthn/register/verify', options.authMiddleware, asyncHandler(async (req, res) => {
44
+ const service = createWebauthnService(webauthnStore, webauthn);
45
+ const data = await service.verifyRegistration(req.user.id, req.body.response, req.body.deviceName);
46
+ return apiResponse(res, 200, 'WebAuthn registration verified', data);
47
+ }));
48
+
49
+ router.post('/webauthn/authenticate/options', options.authMiddleware, asyncHandler(async (req, res) => {
50
+ const service = createWebauthnService(webauthnStore, webauthn);
51
+ const data = await service.getAuthenticationOptions(req, req.user.id);
52
+ return apiResponse(res, 200, 'WebAuthn authentication options', data);
53
+ }));
54
+
55
+ router.post('/webauthn/authenticate/verify', options.authMiddleware, asyncHandler(async (req, res) => {
56
+ const service = createWebauthnService(webauthnStore, webauthn);
57
+ const verified = await service.verifyAuthentication(req.user.id, req.body.response);
58
+ return apiResponse(res, 200, 'WebAuthn authentication verified', { verified });
59
+ }));
60
+ }
61
+
62
+ return router;
63
+ }
64
+
65
+ module.exports = createAuthRoutes;
@@ -0,0 +1,24 @@
1
+ const express = require('express');
2
+ const { apiResponse, asyncHandler } = require('@astratra/core');
3
+
4
+ function createDashboardRoutes({ usersStore }) {
5
+ const router = express.Router();
6
+
7
+ router.get('/summary', asyncHandler(async (req, res) => {
8
+ const users = await usersStore.list({ limit: Number.MAX_SAFE_INTEGER, offset: 0 });
9
+ const roleBreakdown = users.reduce((counts, user) => {
10
+ const role = user.role || 'unknown';
11
+ counts[role] = (counts[role] || 0) + 1;
12
+ return counts;
13
+ }, {});
14
+
15
+ return apiResponse(res, 200, 'Dashboard summary', {
16
+ userCount: users.length,
17
+ roleBreakdown
18
+ });
19
+ }));
20
+
21
+ return router;
22
+ }
23
+
24
+ module.exports = createDashboardRoutes;
@@ -0,0 +1,24 @@
1
+ const express = require('express');
2
+ const { apiResponse, asyncHandler } = require('@astratra/core');
3
+ const { requireBodyFields } = require('../utils');
4
+
5
+ function createNotificationsRoutes({ notify, authorizeAdmin }) {
6
+ const router = express.Router();
7
+
8
+ router.use(authorizeAdmin);
9
+
10
+ router.post('/send', asyncHandler(async (req, res) => {
11
+ requireBodyFields(req.body || {}, ['userId', 'title', 'message']);
12
+ const notification = {
13
+ title: req.body.title,
14
+ message: req.body.message,
15
+ channel: req.body.channel
16
+ };
17
+ const result = await notify(req.body.userId, notification);
18
+ return apiResponse(res, 200, 'Notification sent', result || { sent: true });
19
+ }));
20
+
21
+ return router;
22
+ }
23
+
24
+ module.exports = createNotificationsRoutes;
@@ -0,0 +1,24 @@
1
+ const express = require('express');
2
+ const { apiResponse, asyncHandler } = require('@astratra/core');
3
+ const { requireBodyFields } = require('../utils');
4
+
5
+ function createSettingsRoutes({ settingsStore, authorizeAdmin }) {
6
+ const router = express.Router();
7
+
8
+ router.use(authorizeAdmin);
9
+
10
+ router.get('/', asyncHandler(async (req, res) => {
11
+ const settings = await settingsStore.getAll();
12
+ return apiResponse(res, 200, 'Settings list', settings);
13
+ }));
14
+
15
+ router.patch('/:key', asyncHandler(async (req, res) => {
16
+ requireBodyFields(req.body || {}, ['value']);
17
+ const value = await settingsStore.set(req.params.key, req.body.value);
18
+ return apiResponse(res, 200, 'Setting updated', { key: req.params.key, value });
19
+ }));
20
+
21
+ return router;
22
+ }
23
+
24
+ module.exports = createSettingsRoutes;
@@ -0,0 +1,47 @@
1
+ const express = require('express');
2
+ const { apiResponse, AppError, asyncHandler } = require('@astratra/core');
3
+ const { requireBodyFields, sanitizeUser, toPagination } = require('../utils');
4
+
5
+ function createUsersRoutes({ usersStore, authorizeAdmin }) {
6
+ const router = express.Router();
7
+
8
+ router.use(authorizeAdmin);
9
+
10
+ router.get('/', asyncHandler(async (req, res) => {
11
+ const pagination = toPagination(req.query);
12
+ const users = await usersStore.list(pagination);
13
+ return apiResponse(res, 200, 'Users list', {
14
+ items: users.map(sanitizeUser),
15
+ limit: pagination.limit,
16
+ offset: pagination.offset
17
+ });
18
+ }));
19
+
20
+ router.get('/:id', asyncHandler(async (req, res) => {
21
+ const user = await usersStore.findById(req.params.id);
22
+ if (!user) {
23
+ throw new AppError('User not found.', 404);
24
+ }
25
+
26
+ return apiResponse(res, 200, 'User found', sanitizeUser(user));
27
+ }));
28
+
29
+ router.post('/', asyncHandler(async (req, res) => {
30
+ requireBodyFields(req.body || {}, ['email']);
31
+ const user = await usersStore.create(req.body);
32
+ return apiResponse(res, 201, 'User created', sanitizeUser(user));
33
+ }));
34
+
35
+ router.patch('/:id', asyncHandler(async (req, res) => {
36
+ const user = await usersStore.update(req.params.id, req.body || {});
37
+ if (!user) {
38
+ throw new AppError('User not found.', 404);
39
+ }
40
+
41
+ return apiResponse(res, 200, 'User updated', sanitizeUser(user));
42
+ }));
43
+
44
+ return router;
45
+ }
46
+
47
+ module.exports = createUsersRoutes;
@@ -0,0 +1,25 @@
1
+ function clone(value) {
2
+ return JSON.parse(JSON.stringify(value));
3
+ }
4
+
5
+ function createMemorySettingsStore(initialSettings = {}) {
6
+ // Dev-only adapter: stores settings in process memory and is not persistent.
7
+ const settings = new Map(Object.entries(initialSettings));
8
+
9
+ return {
10
+ async get(key) {
11
+ return settings.has(key) ? clone(settings.get(key)) : null;
12
+ },
13
+
14
+ async set(key, value) {
15
+ settings.set(key, clone(value));
16
+ return clone(value);
17
+ },
18
+
19
+ async getAll() {
20
+ return Object.fromEntries([...settings.entries()].map(([key, value]) => [key, clone(value)]));
21
+ }
22
+ };
23
+ }
24
+
25
+ module.exports = createMemorySettingsStore;
@@ -0,0 +1,72 @@
1
+ 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
+ }
14
+ ];
15
+
16
+ function clone(value) {
17
+ return JSON.parse(JSON.stringify(value));
18
+ }
19
+
20
+ function createMemoryUsersStore(options = {}) {
21
+ // Dev-only adapter: keeps data in process memory and loses it on restart.
22
+ const users = new Map();
23
+ const seedUsers = options.users || DEFAULT_USERS;
24
+ let nextId = seedUsers.length + 1;
25
+
26
+ for (const user of seedUsers) {
27
+ users.set(String(user.id), clone(user));
28
+ }
29
+
30
+ return {
31
+ async findByEmail(email) {
32
+ const normalized = String(email || '').toLowerCase();
33
+ const user = [...users.values()].find((item) => String(item.email || '').toLowerCase() === normalized);
34
+ return user ? clone(user) : null;
35
+ },
36
+
37
+ async findById(id) {
38
+ const user = users.get(String(id));
39
+ return user ? clone(user) : null;
40
+ },
41
+
42
+ async create(userData) {
43
+ const id = userData.id || `user-${nextId++}`;
44
+ const user = { ...clone(userData), id };
45
+ users.set(String(id), user);
46
+ return clone(user);
47
+ },
48
+
49
+ async list({ role, limit = 50, offset = 0 } = {}) {
50
+ let items = [...users.values()];
51
+ if (role) {
52
+ items = items.filter((user) => user.role === role);
53
+ }
54
+
55
+ const safeOffset = Math.max(Number(offset) || 0, 0);
56
+ const safeLimit = Math.max(Number(limit) || 50, 0);
57
+ return clone(items.slice(safeOffset, safeOffset + safeLimit));
58
+ },
59
+
60
+ async update(id, patch) {
61
+ const key = String(id);
62
+ const current = users.get(key);
63
+ if (!current) return null;
64
+
65
+ const updated = { ...current, ...clone(patch), id: current.id };
66
+ users.set(key, updated);
67
+ return clone(updated);
68
+ }
69
+ };
70
+ }
71
+
72
+ module.exports = createMemoryUsersStore;
package/src/utils.js ADDED
@@ -0,0 +1,59 @@
1
+ const { AppError } = require('@astratra/core');
2
+
3
+ const DEFAULT_PUBLIC_USER_FIELDS = ['id', 'email', 'role'];
4
+ const SENSITIVE_USER_FIELDS = new Set(['password', 'passwordHash', 'hash', 'salt', 'tokens']);
5
+
6
+ function pickPublicUser(user, fields = DEFAULT_PUBLIC_USER_FIELDS) {
7
+ if (!user) return null;
8
+
9
+ return fields.reduce((publicUser, field) => {
10
+ if (!SENSITIVE_USER_FIELDS.has(field) && Object.prototype.hasOwnProperty.call(user, field)) {
11
+ publicUser[field] = user[field];
12
+ }
13
+ return publicUser;
14
+ }, {});
15
+ }
16
+
17
+ function sanitizeUser(user) {
18
+ if (!user) return null;
19
+
20
+ return Object.entries(user).reduce((safeUser, [key, value]) => {
21
+ if (!SENSITIVE_USER_FIELDS.has(key)) {
22
+ safeUser[key] = value;
23
+ }
24
+ return safeUser;
25
+ }, {});
26
+ }
27
+
28
+ function assertAdapter(adapter, methods, name) {
29
+ for (const method of methods) {
30
+ if (!adapter || typeof adapter[method] !== 'function') {
31
+ throw new Error(`createSaasApp requires ${name}.${method}.`);
32
+ }
33
+ }
34
+ }
35
+
36
+ function toPagination(query = {}) {
37
+ return {
38
+ role: query.role,
39
+ limit: query.limit ? Number(query.limit) : 50,
40
+ offset: query.offset ? Number(query.offset) : 0
41
+ };
42
+ }
43
+
44
+ function requireBodyFields(body, fields) {
45
+ for (const field of fields) {
46
+ if (body[field] === undefined || body[field] === null || body[field] === '') {
47
+ throw new AppError(`${field} is required.`, 400);
48
+ }
49
+ }
50
+ }
51
+
52
+ module.exports = {
53
+ DEFAULT_PUBLIC_USER_FIELDS,
54
+ assertAdapter,
55
+ pickPublicUser,
56
+ requireBodyFields,
57
+ sanitizeUser,
58
+ toPagination
59
+ };