@astratra/saas-kit 1.5.0 → 1.6.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
@@ -129,6 +129,25 @@ createSaasApp({
129
129
  Non défini par défaut (comportement Express standard, inchangé) — dépend du
130
130
  déploiement, Astratra ne peut pas le deviner à ta place.
131
131
 
132
+ `apiRateLimit`/`loginRateLimit` sont transmis tels quels à
133
+ `createApiLimiter`/`createLoginLimiter` (`@astratra/security`) : pour isoler
134
+ leurs compteurs sur une même instance Redis, fournis un store namespacé via
135
+ `createRedisRateLimitStore({ redisUrl, prefix })` :
136
+
137
+ ```js
138
+ const { createRedisRateLimitStore } = require('@astratra/security');
139
+
140
+ createSaasApp({
141
+ // ...
142
+ apiRateLimit: {
143
+ store: createRedisRateLimitStore({ redisUrl, prefix: 'mon-app:rate:api:' })
144
+ },
145
+ loginRateLimit: {
146
+ store: createRedisRateLimitStore({ redisUrl, prefix: 'mon-app:rate:connexion:' })
147
+ }
148
+ });
149
+ ```
150
+
132
151
  Le cookie CSRF (`astratra_csrf`) est amorcé automatiquement sur toute
133
152
  requête sûre (GET/HEAD/OPTIONS) dès le démarrage de l'app — y compris tes
134
153
  propres routes `GET` ajoutées via `extendRoutes` — donc pas besoin de monter
@@ -165,6 +184,76 @@ Bearer` (mobile/API — non exposés au CSRF) et `POST /auth/login`
165
184
  `POST /auth/logout-all` invalide tous les JWT actifs de l'utilisateur, pas
166
185
  seulement celui de la requête courante.
167
186
 
187
+ ## Rester connecté, réinitialiser, notifier un téléphone
188
+
189
+ Trois choses qu'une application mobile réclame et qu'une application web n'a
190
+ pas toujours. Les trois sont **éteintes par défaut** ou montées seulement quand
191
+ tu fournis ce qu'il faut : une app fraîchement générée démarre sans
192
+ configuration.
193
+
194
+ ### Rafraîchissement de session
195
+
196
+ ```js
197
+ createSaasApp({
198
+ refreshTokens: { enabled: true, ttlMs: 30 * 24 * 60 * 60 * 1000 }
199
+ });
200
+ ```
201
+
202
+ `/auth/login` renvoie alors un `refreshToken` en plus du `token`, et
203
+ `/auth/refresh` l'échange contre un couple neuf. Le mécanisme est celui de
204
+ `@astratra/security` : rotation à chaque usage, empreinte en base, et un rejeu
205
+ révoque toute la chaîne issue de cette connexion.
206
+
207
+ Éteint, la route `/auth/refresh` **n'existe pas** — le client web sur cookie
208
+ `HttpOnly` n'en a pas besoin, et lui donner un identifiant à longue vie qu'il
209
+ n'utilise jamais ne ferait qu'élargir la cible.
210
+
211
+ Se déconnecter révoque aussi la chaîne : révoquer le seul jeton d'accès
212
+ laisserait la session revenir au prochain renouvellement.
213
+
214
+ ### Mot de passe oublié
215
+
216
+ ```js
217
+ createSaasApp({
218
+ hashPassword: async (password) => bcrypt.hash(password, 12),
219
+ passwordReset: {
220
+ send: async ({ user, token }) => mailer.send({
221
+ to: user.email,
222
+ subject: 'Réinitialiser votre mot de passe',
223
+ text: `https://app.exemple.cd/reset?token=${token}`
224
+ })
225
+ }
226
+ });
227
+ ```
228
+
229
+ Sans `send`, les routes ne sont **pas montées du tout** : accepter des demandes
230
+ qui ne partent nulle part en répondant « c'est envoyé » est le pire des deux
231
+ mondes.
232
+
233
+ `/auth/forgot-password` répond **toujours pareil**, adresse connue ou non.
234
+ « Aucun compte avec cet e-mail » transforme l'écran en annuaire : on lui donne
235
+ une liste, il dit gratuitement lesquelles ont un compte ici.
236
+
237
+ `/auth/reset-password` consomme le lien (usage unique — consommer **supprime**)
238
+ et **révoque toutes les sessions** de la personne. C'est l'étape qu'on oublie :
239
+ quelqu'un qui réinitialise son mot de passe est peut-être en train de reprendre
240
+ un compte volé, et laisser vivre les sessions du voleur rend l'opération vaine.
241
+
242
+ ### Enregistrement des téléphones
243
+
244
+ ```js
245
+ createSaasApp({ devicesStore }); // adaptateur mémoire par défaut
246
+ ```
247
+
248
+ `POST /notifications/devices`, `GET /notifications/devices/:installationId`,
249
+ `DELETE /notifications/devices/:installationId` — le contrat qu'attend
250
+ `@astratra/native` côté application.
251
+
252
+ Ces routes sont **avant** le garde d'administration du module : enregistrer son
253
+ propre téléphone n'est pas un acte d'administration, c'est ce que fait toute
254
+ application mobile au démarrage. Chacune est bornée à `req.user.id`, jamais à
255
+ l'identifiant de l'URL — un identifiant d'installation se devine.
256
+
168
257
  ## Validation des entrées
169
258
 
170
259
  `POST /auth/login`, `POST /users`, `PATCH /settings/:key` et
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/saas-kit",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Reusable backend starter kit that assembles Astratra core, security, and AI packages.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -26,7 +26,7 @@
26
26
  "dependencies": {
27
27
  "@astratra/ai": "^1.0.0",
28
28
  "@astratra/core": "^1.0.0",
29
- "@astratra/security": "^1.6.0",
29
+ "@astratra/security": "^1.10.0",
30
30
  "express": "^4.18.3",
31
31
  "express-validator": "^7.3.2",
32
32
  "jsonwebtoken": "^9.0.2"
package/src/app.js CHANGED
@@ -14,7 +14,9 @@ const {
14
14
  createCsrfCookiePrimer,
15
15
  createCsrfMiddleware,
16
16
  createLoginLimiter,
17
+ createMemoryRefreshTokenStore,
17
18
  createMemoryRevocationStore,
19
+ createRefreshTokenService,
18
20
  createMongoSanitizeMiddleware,
19
21
  createSecurityAuditLogger,
20
22
  createSecurityHeadersMiddleware,
@@ -28,6 +30,8 @@ const createSettingsRoutes = require('./modules/settings');
28
30
  const createUsersRoutes = require('./modules/users');
29
31
  const createMemorySettingsStore = require('./stores/memorySettingsStore');
30
32
  const createMemoryUsersStore = require('./stores/memoryUsersStore');
33
+ const createMemoryPasswordResetStore = require('./stores/memoryPasswordResetStore');
34
+ const createMemoryDevicesStore = require('./stores/memoryDevicesStore');
31
35
  const { DEFAULT_PUBLIC_USER_FIELDS, assertAdapter } = require('./utils');
32
36
 
33
37
  const DEFAULT_JWT_SECRET = 'saas-kit-dev-secret';
@@ -45,6 +49,27 @@ function normalizeOptions(options = {}) {
45
49
  const usersStore = options.usersStore || createMemoryUsersStore();
46
50
  const settingsStore = options.settingsStore || createMemorySettingsStore();
47
51
  const revocationStore = options.revocationStore || createMemoryRevocationStore();
52
+ const devicesStore = options.devicesStore || createMemoryDevicesStore();
53
+
54
+ /* Off unless asked for. A refresh token is a long-lived credential: it is
55
+ handed out because a product needs it, never because a default said so. */
56
+ const refreshConfig = options.refreshTokens || {};
57
+ const refreshTokenService = refreshConfig.enabled
58
+ ? (refreshConfig.service || createRefreshTokenService({
59
+ store: refreshConfig.store || createMemoryRefreshTokenStore(),
60
+ ttlMs: refreshConfig.ttlMs
61
+ }))
62
+ : null;
63
+
64
+ /* The reset routes exist only when there is a way to deliver the link.
65
+ Mounting them without a sender would accept requests that go nowhere and
66
+ report success — the worst of both. */
67
+ const passwordReset = options.passwordReset;
68
+ const hashPassword = options.hashPassword;
69
+ if (passwordReset && typeof passwordReset.send === 'function' && typeof hashPassword !== 'function') {
70
+ throw new Error('createSaasApp requires options.hashPassword when options.passwordReset.send is provided.');
71
+ }
72
+ const passwordResetStore = (passwordReset && passwordReset.store) || createMemoryPasswordResetStore();
48
73
  const notify = options.notify;
49
74
  const verifyPassword = options.verifyPassword;
50
75
  const roles = { ...DEFAULT_ROLES, ...(options.roles || {}) };
@@ -68,6 +93,11 @@ function normalizeOptions(options = {}) {
68
93
  usersStore,
69
94
  settingsStore,
70
95
  revocationStore,
96
+ devicesStore,
97
+ refreshTokenService,
98
+ passwordReset,
99
+ passwordResetStore,
100
+ hashPassword,
71
101
  notify,
72
102
  verifyPassword,
73
103
  roles,
@@ -185,7 +215,8 @@ function createSaasApp(options = {}) {
185
215
  }));
186
216
  app.use('/notifications', authMiddleware, csrfMiddleware, createNotificationsRoutes({
187
217
  notify: normalized.notify,
188
- authorizeAdmin
218
+ authorizeAdmin,
219
+ devicesStore: normalized.devicesStore
189
220
  }));
190
221
  app.use('/dashboard', authMiddleware, csrfMiddleware, createDashboardRoutes({
191
222
  usersStore: normalized.usersStore
package/src/index.d.ts CHANGED
@@ -13,7 +13,9 @@ import type {
13
13
  SessionCookieOptions,
14
14
  WafOptions,
15
15
  WebauthnOptions,
16
- WebauthnStore
16
+ WebauthnStore,
17
+ RefreshTokenService,
18
+ RefreshTokenStore
17
19
  } from '@astratra/security';
18
20
 
19
21
  export type Awaitable<T> = T | Promise<T>;
@@ -100,6 +102,30 @@ export interface CreateSaasAppOptions {
100
102
  verifyPassword: (user: SaasUser, password: string) => Awaitable<boolean>;
101
103
  verifySession?: AuthMiddlewareOptions['verifySession'];
102
104
  revocationStore?: RevocationStore;
105
+ /** Phones registered for push. Defaults to an in-memory adapter. */
106
+ devicesStore?: DevicesStore;
107
+ /**
108
+ * Long-lived renewal. OFF unless enabled: a refresh token is handed out
109
+ * because a product needs it, never because a default said so.
110
+ */
111
+ refreshTokens?: {
112
+ enabled?: boolean;
113
+ ttlMs?: number;
114
+ store?: RefreshTokenStore;
115
+ service?: RefreshTokenService;
116
+ };
117
+ /**
118
+ * Password reset. The routes exist only when `send` is provided — mounting
119
+ * them without a transport would accept requests that go nowhere.
120
+ * Requires `hashPassword`.
121
+ */
122
+ passwordReset?: {
123
+ send(payload: { user: Record<string, unknown>; token: string }): Promise<unknown>;
124
+ ttlMs?: number;
125
+ store?: PasswordResetStore;
126
+ };
127
+ /** Required alongside passwordReset.send. */
128
+ hashPassword?: (password: string) => Promise<string> | string;
103
129
  extractToken?: AuthMiddlewareOptions['extractToken'];
104
130
  roles?: SaasRoles;
105
131
  publicUserFields?: string[];
@@ -157,3 +183,41 @@ export interface CreateSaasAppOptions {
157
183
  }
158
184
 
159
185
  export function createSaasApp(options: CreateSaasAppOptions): SaasApp;
186
+
187
+ /* ───────────────── Devices and password resets ───────────────── */
188
+
189
+ export interface RegisteredDevice {
190
+ installationId: string;
191
+ pushToken: string;
192
+ platform?: string;
193
+ deviceName?: string;
194
+ userId: string;
195
+ enabled?: boolean;
196
+ updatedAt?: number;
197
+ }
198
+
199
+ export interface DevicesStore {
200
+ /** Keyed on the installation id: a re-registration updates, never duplicates. */
201
+ upsert(device: RegisteredDevice): Promise<RegisteredDevice>;
202
+ find(installationId: string): Promise<RegisteredDevice | null>;
203
+ listForUser(userId: string): Promise<RegisteredDevice[]>;
204
+ remove(installationId: string): Promise<unknown>;
205
+ }
206
+
207
+ export interface PasswordResetRecord {
208
+ /** SHA-256 of the token. The token itself is never stored. */
209
+ hash: string;
210
+ userId: string;
211
+ expiresAt: number;
212
+ }
213
+
214
+ export interface PasswordResetStore {
215
+ save(record: PasswordResetRecord): Promise<unknown>;
216
+ find(hash: string): Promise<PasswordResetRecord | null>;
217
+ /** Single use: consuming deletes, so a replay finds nothing. */
218
+ consume(hash: string): Promise<PasswordResetRecord | null>;
219
+ deleteForUser(userId: string): Promise<unknown>;
220
+ }
221
+
222
+ export function createMemoryDevicesStore(): DevicesStore;
223
+ export function createMemoryPasswordResetStore(): PasswordResetStore;
package/src/index.js CHANGED
@@ -1,9 +1,13 @@
1
1
  const { createSaasApp } = require('./app');
2
2
  const createMemorySettingsStore = require('./stores/memorySettingsStore');
3
3
  const createMemoryUsersStore = require('./stores/memoryUsersStore');
4
+ const createMemoryPasswordResetStore = require('./stores/memoryPasswordResetStore');
5
+ const createMemoryDevicesStore = require('./stores/memoryDevicesStore');
4
6
 
5
7
  module.exports = {
6
8
  createSaasApp,
7
9
  createMemorySettingsStore,
8
- createMemoryUsersStore
10
+ createMemoryUsersStore,
11
+ createMemoryPasswordResetStore,
12
+ createMemoryDevicesStore
9
13
  };
@@ -46,11 +46,30 @@ function createAuthRoutes(options) {
46
46
  verifyPassword,
47
47
  publicUserFields,
48
48
  webauthnStore,
49
- webauthn
49
+ webauthn,
50
+ refreshTokenService,
51
+ passwordResetStore,
52
+ passwordReset,
53
+ hashPassword
50
54
  } = options;
51
55
  const cookieOptions = cookieOptionsFrom(options);
52
56
  const csrfMiddleware = options.csrfMiddleware || ((req, res, next) => next());
53
57
 
58
+ /**
59
+ * One place that mints an access token, because two would drift: the refresh
60
+ * route must produce a token indistinguishable from the login one.
61
+ */
62
+ const signAccessToken = (publicUser, claims = {}) => jwt.sign(
63
+ { ...publicUser, jti: crypto.randomUUID(), ...claims },
64
+ jwtSecret,
65
+ {
66
+ expiresIn: options.jwtExpiresIn || '1h',
67
+ algorithm: options.jwtAlgorithms[0],
68
+ ...(options.jwtIssuer ? { issuer: options.jwtIssuer } : {}),
69
+ ...(options.jwtAudience ? { audience: options.jwtAudience } : {})
70
+ }
71
+ );
72
+
54
73
  router.post('/login', validateMiddleware(loginValidation), asyncHandler(async (req, res) => {
55
74
  const user = await usersStore.findByEmail(req.body.email);
56
75
  const valid = user ? await verifyPassword(user, req.body.password) : false;
@@ -59,21 +78,66 @@ function createAuthRoutes(options) {
59
78
  }
60
79
 
61
80
  const publicUser = pickPublicUser(user, publicUserFields);
62
- const jti = crypto.randomUUID();
63
- const token = jwt.sign({ ...publicUser, jti }, jwtSecret, {
64
- expiresIn: options.jwtExpiresIn || '1h',
65
- algorithm: options.jwtAlgorithms[0],
66
- ...(options.jwtIssuer ? { issuer: options.jwtIssuer } : {}),
67
- ...(options.jwtAudience ? { audience: options.jwtAudience } : {})
68
- });
81
+
82
+ /* A refresh token is issued only when the product asked for one. The web
83
+ client rides on an HttpOnly cookie and needs none; handing it a
84
+ long-lived credential it never uses only widens the target. */
85
+ let refresh = null;
86
+ if (refreshTokenService) {
87
+ refresh = await refreshTokenService.issue({ userId: String(user.id) });
88
+ }
89
+
90
+ /* The family id travels in the access token so that signing out can revoke
91
+ the refresh chain without the client having to hand it back. */
92
+ const token = signAccessToken(publicUser, refresh ? { rfid: refresh.familyId } : {});
69
93
  setSessionCookie(res, token, cookieOptions);
70
- return apiResponse(res, 200, 'Login successful', { token, user: publicUser });
94
+
95
+ return apiResponse(res, 200, 'Login successful', {
96
+ token,
97
+ user: publicUser,
98
+ ...(refresh ? { refreshToken: refresh.token } : {})
99
+ });
71
100
  }));
72
101
 
102
+ if (refreshTokenService) {
103
+ /* No auth middleware here, deliberately: the access token is expected to
104
+ be DEAD by the time this is called. The refresh token is the credential.
105
+ No CSRF either — this route is for Bearer clients, which cookies-based
106
+ CSRF does not apply to, and a cookie client never needs it. */
107
+ router.post('/refresh', asyncHandler(async (req, res) => {
108
+ let rotated;
109
+ try {
110
+ rotated = await refreshTokenService.rotate(req.body && req.body.refreshToken);
111
+ } catch (_error) {
112
+ /* Invalid, expired, replayed: the client is told the same thing in all
113
+ three cases. Which one it was is our business, not an attacker's. */
114
+ throw new AppError('Session expired. Please sign in again.', 401);
115
+ }
116
+
117
+ const user = await usersStore.findById(rotated.userId);
118
+ if (!user) throw new AppError('Session expired. Please sign in again.', 401);
119
+
120
+ const publicUser = pickPublicUser(user, publicUserFields);
121
+ const token = signAccessToken(publicUser, { rfid: rotated.familyId });
122
+ setSessionCookie(res, token, cookieOptions);
123
+
124
+ return apiResponse(res, 200, 'Session refreshed', {
125
+ token,
126
+ user: publicUser,
127
+ refreshToken: rotated.token
128
+ });
129
+ }));
130
+ }
131
+
73
132
  router.post('/logout', options.authMiddleware, csrfMiddleware, asyncHandler(async (req, res) => {
74
133
  if (options.revocationStore && req.user && req.user.jti) {
75
134
  await options.revocationStore.revoke(req.user.jti, req.user.exp * 1000);
76
135
  }
136
+ /* Revoking the access token alone would leave the refresh token alive —
137
+ the session would come back on the next renewal. */
138
+ if (refreshTokenService && req.user && req.user.rfid) {
139
+ await refreshTokenService.revokeFamily(req.user.rfid);
140
+ }
77
141
  clearSessionCookie(res, cookieOptions);
78
142
  return res.status(200).json({ success: true });
79
143
  }));
@@ -82,10 +146,83 @@ function createAuthRoutes(options) {
82
146
  if (options.revocationStore && req.user && req.user.id && typeof options.revocationStore.revokeAllForUser === 'function') {
83
147
  await options.revocationStore.revokeAllForUser(req.user.id, Date.now());
84
148
  }
149
+ if (refreshTokenService && req.user && req.user.id) {
150
+ await refreshTokenService.revokeAllForUser(String(req.user.id));
151
+ }
85
152
  clearSessionCookie(res, cookieOptions);
86
153
  return res.status(200).json({ success: true });
87
154
  }));
88
155
 
156
+ if (passwordReset && typeof passwordReset.send === 'function') {
157
+ const resetTtlMs = passwordReset.ttlMs || 60 * 60 * 1000;
158
+ const fingerprint = (token) => crypto.createHash('sha256').update(String(token)).digest('hex');
159
+
160
+ /**
161
+ * THE ANSWER NEVER DEPENDS ON WHETHER THE ADDRESS EXISTS.
162
+ *
163
+ * "No account with that email" turns this screen into a directory: feed it
164
+ * a list and it tells you, for free, which addresses have accounts here.
165
+ * So the reply, the status and the timing-free path are identical either
166
+ * way; only the sending differs, and that is invisible from outside.
167
+ */
168
+ router.post('/forgot-password', validateMiddleware([
169
+ body('email').isEmail().withMessage('email must be a valid email address')
170
+ ]), asyncHandler(async (req, res) => {
171
+ const user = await usersStore.findByEmail(req.body.email);
172
+
173
+ if (user) {
174
+ /* Hex, not base64url: a '--' in the token would be read as an SQL
175
+ comment by the WAF and blocked, making that reset link permanently
176
+ unusable. See @astratra/security's refresh tokens for the full
177
+ story. */
178
+ const token = crypto.randomBytes(32).toString('hex');
179
+ await passwordResetStore.save({
180
+ hash: fingerprint(token),
181
+ userId: String(user.id),
182
+ expiresAt: Date.now() + resetTtlMs
183
+ });
184
+ try {
185
+ await passwordReset.send({ user: pickPublicUser(user, publicUserFields), token });
186
+ } catch (_error) {
187
+ /* A mail transport that is down must not become an oracle either:
188
+ the caller is told the same thing as always. */
189
+ }
190
+ }
191
+
192
+ return apiResponse(res, 200, 'If that address has an account, a reset link is on its way.', null);
193
+ }));
194
+
195
+ router.post('/reset-password', validateMiddleware([
196
+ body('token').notEmpty().withMessage('token is required'),
197
+ body('password').notEmpty().withMessage('password is required')
198
+ ]), asyncHandler(async (req, res) => {
199
+ /* Consuming DELETES the record, so a second attempt with the same link
200
+ finds nothing — the single-use rule needs no extra flag. */
201
+ const record = await passwordResetStore.consume(fingerprint(req.body.token));
202
+ if (!record || record.expiresAt <= Date.now()) {
203
+ throw new AppError('This reset link is no longer valid.', 400);
204
+ }
205
+
206
+ const user = await usersStore.findById(record.userId);
207
+ if (!user) throw new AppError('This reset link is no longer valid.', 400);
208
+
209
+ await usersStore.update(record.userId, { password: await hashPassword(req.body.password) });
210
+
211
+ /* The step everyone forgets. Someone resetting a password may be
212
+ recovering a stolen account: leaving the thief's sessions alive makes
213
+ the whole exercise pointless. */
214
+ if (options.revocationStore && typeof options.revocationStore.revokeAllForUser === 'function') {
215
+ await options.revocationStore.revokeAllForUser(record.userId, Date.now());
216
+ }
217
+ if (refreshTokenService) {
218
+ await refreshTokenService.revokeAllForUser(record.userId);
219
+ }
220
+ await passwordResetStore.deleteForUser(record.userId);
221
+
222
+ return apiResponse(res, 200, 'Password updated. Please sign in again.', null);
223
+ }));
224
+ }
225
+
89
226
  router.get('/me', options.authMiddleware, (req, res) => (
90
227
  apiResponse(res, 200, 'Current user', pickPublicUser(req.user, publicUserFields))
91
228
  ));
@@ -1,6 +1,6 @@
1
1
  const express = require('express');
2
2
  const { body } = require('express-validator');
3
- const { apiResponse, asyncHandler, validateMiddleware } = require('@astratra/core');
3
+ const { AppError, apiResponse, asyncHandler, validateMiddleware } = require('@astratra/core');
4
4
 
5
5
  const sendNotificationValidation = [
6
6
  body('userId').trim().notEmpty().withMessage('userId is required'),
@@ -8,9 +8,68 @@ const sendNotificationValidation = [
8
8
  body('message').trim().notEmpty().isLength({ max: 5000 }).withMessage('message must be between 1 and 5000 characters')
9
9
  ];
10
10
 
11
- function createNotificationsRoutes({ notify, authorizeAdmin }) {
11
+ const deviceValidation = [
12
+ body('installationId').trim().notEmpty().withMessage('installationId is required'),
13
+ body('pushToken').trim().notEmpty().withMessage('pushToken is required')
14
+ ];
15
+
16
+ function createNotificationsRoutes({ notify, authorizeAdmin, devicesStore }) {
12
17
  const router = express.Router();
13
18
 
19
+ /*
20
+ * Devices come FIRST, before the admin guard below.
21
+ *
22
+ * A person registering their own phone is not an administrative act — it is
23
+ * the most ordinary thing a mobile app does on launch. Behind
24
+ * `authorizeAdmin` nobody but an owner could ever receive a notification.
25
+ *
26
+ * Every route here is scoped to req.user.id, never to the id in the URL: an
27
+ * installation id is guessable, and without the check anyone could read or
28
+ * delete somebody else's device.
29
+ */
30
+ if (devicesStore) {
31
+ router.post('/devices', validateMiddleware(deviceValidation), asyncHandler(async (req, res) => {
32
+ /* Keyed on the installation id, so a re-registration UPDATES the row.
33
+ Keyed on the push token — which rotates — one phone would pile up
34
+ dead rows, and every send would get slower and noisier. */
35
+ const device = await devicesStore.upsert({
36
+ installationId: String(req.body.installationId),
37
+ pushToken: String(req.body.pushToken),
38
+ platform: req.body.platform ? String(req.body.platform) : undefined,
39
+ deviceName: req.body.deviceName ? String(req.body.deviceName) : undefined,
40
+ userId: String(req.user.id),
41
+ updatedAt: Date.now()
42
+ });
43
+ return apiResponse(res, 200, 'Device registered', {
44
+ registered: true,
45
+ enabled: device.enabled !== false
46
+ });
47
+ }));
48
+
49
+ router.get('/devices', asyncHandler(async (req, res) => (
50
+ apiResponse(res, 200, 'Registered devices', await devicesStore.listForUser(String(req.user.id)))
51
+ )));
52
+
53
+ router.get('/devices/:installationId', asyncHandler(async (req, res) => {
54
+ const device = await devicesStore.find(req.params.installationId);
55
+ /* Someone else's device reads as "not registered" rather than as
56
+ "forbidden": a 403 would confirm the id exists. */
57
+ if (!device || device.userId !== String(req.user.id)) {
58
+ return apiResponse(res, 200, 'Device status', { registered: false, enabled: false });
59
+ }
60
+ return apiResponse(res, 200, 'Device status', { registered: true, enabled: device.enabled !== false });
61
+ }));
62
+
63
+ router.delete('/devices/:installationId', asyncHandler(async (req, res) => {
64
+ const device = await devicesStore.find(req.params.installationId);
65
+ if (!device || device.userId !== String(req.user.id)) {
66
+ throw new AppError('Device not found.', 404);
67
+ }
68
+ await devicesStore.remove(req.params.installationId);
69
+ return apiResponse(res, 200, 'Device removed', { removed: true });
70
+ }));
71
+ }
72
+
14
73
  router.use(authorizeAdmin);
15
74
 
16
75
  router.post('/send', validateMiddleware(sendNotificationValidation), asyncHandler(async (req, res) => {
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The phones a person receives notifications on.
3
+ *
4
+ * Keyed on the INSTALLATION id, not on the push token: the push token changes
5
+ * on reinstall, on restore, whenever the platform feels like it. Keyed on the
6
+ * token, one phone becomes six rows, five of them dead, and every send gets
7
+ * slower and noisier.
8
+ *
9
+ * Dev-only adapter: in process memory, lost on restart.
10
+ */
11
+ function createMemoryDevicesStore() {
12
+ const devices = new Map();
13
+
14
+ return {
15
+ async upsert(device) {
16
+ const existing = devices.get(device.installationId);
17
+ const record = { ...(existing || {}), ...device, enabled: device.enabled !== false };
18
+ devices.set(record.installationId, record);
19
+ return { ...record };
20
+ },
21
+ async find(installationId) {
22
+ const record = devices.get(installationId);
23
+ return record ? { ...record } : null;
24
+ },
25
+ async listForUser(userId) {
26
+ return [...devices.values()]
27
+ .filter((device) => device.userId === userId)
28
+ .map((device) => ({ ...device }));
29
+ },
30
+ async remove(installationId) {
31
+ return devices.delete(installationId);
32
+ }
33
+ };
34
+ }
35
+
36
+ module.exports = createMemoryDevicesStore;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Reset tokens, kept as fingerprints.
3
+ *
4
+ * Same rule as refresh tokens: what is stored must not be usable. A leaked
5
+ * table of reset tokens is a leaked table of accounts, and unlike a password
6
+ * these need no cracking — they ARE the credential.
7
+ *
8
+ * Dev-only adapter: it lives in process memory, so a restart invalidates every
9
+ * pending reset link.
10
+ */
11
+ function createMemoryPasswordResetStore() {
12
+ const byHash = new Map();
13
+
14
+ return {
15
+ async save(record) {
16
+ byHash.set(record.hash, { ...record });
17
+ },
18
+ async find(hash) {
19
+ const record = byHash.get(hash);
20
+ return record ? { ...record } : null;
21
+ },
22
+ /** Single use: consuming DELETES, so a replay finds nothing at all. */
23
+ async consume(hash) {
24
+ const record = byHash.get(hash);
25
+ byHash.delete(hash);
26
+ return record ? { ...record } : null;
27
+ },
28
+ async deleteForUser(userId) {
29
+ for (const [hash, record] of byHash) {
30
+ if (record.userId === userId) byHash.delete(hash);
31
+ }
32
+ }
33
+ };
34
+ }
35
+
36
+ module.exports = createMemoryPasswordResetStore;