@astratra/security 1.14.0 → 1.15.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.
- package/README.md +99 -22
- package/package.json +7 -12
- package/src/csrf.js +13 -1
- package/src/encryption.js +7 -1
- package/src/idTokens.js +5 -4
- package/src/index.d.ts +123 -13
- package/src/index.js +2 -0
- package/src/jwt.js +256 -0
- package/src/jwtAuth.js +22 -4
- package/src/mongoSanitize.js +19 -2
- package/src/rateLimit.js +235 -0
- package/src/rateLimiters.js +30 -141
- package/src/redisRateLimitStore.js +153 -0
- package/src/requestBody.js +20 -0
- package/src/revocation.js +4 -1
- package/src/totp.js +149 -0
- package/src/waf.js +6 -5
package/src/rateLimiters.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
const rateLimit = require('express-rate-limit');
|
|
2
1
|
const { createLogger } = require('@astratra/core');
|
|
2
|
+
const { bodyLeftUnparsed } = require('./requestBody');
|
|
3
|
+
const { createRateLimit, createMemoryRateLimitStore, ipKey, requestIp } = require('./rateLimit');
|
|
4
|
+
|
|
5
|
+
// Exportés sous ce nom : la clé d'une adresse pour un limiteur écrit par le projet.
|
|
6
|
+
const rateLimitKeyForIp = ipKey;
|
|
7
|
+
const { createRedisRateLimitStore: createRedisStoreWithOptions } = require('./redisRateLimitStore');
|
|
3
8
|
|
|
4
9
|
const logger = createLogger('rate-limiters');
|
|
5
10
|
|
|
@@ -18,7 +23,11 @@ const DEFAULT_ACCOUNT_MESSAGE = {
|
|
|
18
23
|
message: 'Too many attempts for this account. Please try again later.'
|
|
19
24
|
};
|
|
20
25
|
|
|
21
|
-
const getIp =
|
|
26
|
+
const getIp = requestIp;
|
|
27
|
+
|
|
28
|
+
// Une adresse IPv6 compte pour tout son bloc /56 : sinon chacun change d'adresse
|
|
29
|
+
// dans son bloc et repart avec un compteur neuf. IPv4 reste l'adresse exacte.
|
|
30
|
+
const clientKey = (req) => ipKey(getIp(req));
|
|
22
31
|
|
|
23
32
|
const skipLocalhost = (req) => {
|
|
24
33
|
const ip = getIp(req);
|
|
@@ -33,138 +42,16 @@ const sendLimitResponse = async (req, res, next, options, onBlocked, context) =>
|
|
|
33
42
|
return res.status(options.statusCode).json(options.message);
|
|
34
43
|
};
|
|
35
44
|
|
|
36
|
-
const createMemoryStore = () => {
|
|
37
|
-
const MemoryStore = rateLimit.MemoryStore;
|
|
38
|
-
return typeof MemoryStore === 'function' ? new MemoryStore() : null;
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
const createFailoverStore = (redisStore, memoryStore, connectPromise) => {
|
|
42
|
-
let activeStore = memoryStore || redisStore;
|
|
43
|
-
let initOptions = null;
|
|
44
|
-
const initializedStores = new WeakSet();
|
|
45
|
-
|
|
46
|
-
const initializeStore = (store) => {
|
|
47
|
-
if (!store || initializedStores.has(store)) return;
|
|
48
|
-
if (initOptions && typeof store.init === 'function') {
|
|
49
|
-
store.init(initOptions);
|
|
50
|
-
}
|
|
51
|
-
initializedStores.add(store);
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
const useStore = (store) => {
|
|
55
|
-
activeStore = store || memoryStore || redisStore;
|
|
56
|
-
initializeStore(activeStore);
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
connectPromise.then(
|
|
60
|
-
() => useStore(redisStore),
|
|
61
|
-
() => useStore(memoryStore)
|
|
62
|
-
);
|
|
63
|
-
|
|
64
|
-
const callActiveStore = (method, args) => {
|
|
65
|
-
const fn = activeStore && activeStore[method];
|
|
66
|
-
if (typeof fn !== 'function') return undefined;
|
|
67
|
-
return fn.apply(activeStore, args);
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
return {
|
|
71
|
-
init(options) {
|
|
72
|
-
initOptions = options;
|
|
73
|
-
initializeStore(activeStore);
|
|
74
|
-
},
|
|
75
|
-
increment(...args) {
|
|
76
|
-
return callActiveStore('increment', args);
|
|
77
|
-
},
|
|
78
|
-
decrement(...args) {
|
|
79
|
-
return callActiveStore('decrement', args);
|
|
80
|
-
},
|
|
81
|
-
resetKey(...args) {
|
|
82
|
-
return callActiveStore('resetKey', args);
|
|
83
|
-
},
|
|
84
|
-
resetAll(...args) {
|
|
85
|
-
return callActiveStore('resetAll', args);
|
|
86
|
-
},
|
|
87
|
-
get(...args) {
|
|
88
|
-
return callActiveStore('get', args);
|
|
89
|
-
},
|
|
90
|
-
shutdown(...args) {
|
|
91
|
-
if (redisStore && typeof redisStore.shutdown === 'function') {
|
|
92
|
-
redisStore.shutdown(...args);
|
|
93
|
-
}
|
|
94
|
-
if (memoryStore && typeof memoryStore.shutdown === 'function') {
|
|
95
|
-
memoryStore.shutdown(...args);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
const createRedisStore = (redisUrl, prefix) => {
|
|
102
|
-
if (!redisUrl) return undefined;
|
|
103
|
-
|
|
104
|
-
let RedisModule;
|
|
105
|
-
let RateLimitRedisModule;
|
|
106
|
-
try {
|
|
107
|
-
RedisModule = require('redis');
|
|
108
|
-
RateLimitRedisModule = require('rate-limit-redis');
|
|
109
|
-
} catch (_error) {
|
|
110
|
-
return undefined;
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const RedisStore = RateLimitRedisModule.RedisStore || RateLimitRedisModule.default || RateLimitRedisModule;
|
|
114
|
-
if (typeof RedisStore !== 'function' || typeof RedisModule.createClient !== 'function') {
|
|
115
|
-
return undefined;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
try {
|
|
119
|
-
const client = RedisModule.createClient({ url: redisUrl });
|
|
120
|
-
if (client && typeof client.on === 'function') {
|
|
121
|
-
client.on('error', () => {});
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const memoryStore = createMemoryStore();
|
|
125
|
-
const connectPromise = Promise.resolve(client.connect()).catch(() => {
|
|
126
|
-
if (client && client.isOpen && typeof client.disconnect === 'function') {
|
|
127
|
-
client.disconnect().catch(() => {});
|
|
128
|
-
}
|
|
129
|
-
throw new Error('Redis rate limit store unavailable');
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
/* Une promesse qui se resout toujours : elle dit si la connexion a abouti,
|
|
133
|
-
elle n'echoue jamais. Sans elle, chaque commande en attente deviendrait
|
|
134
|
-
un second consommateur de connectPromise, et donc un second rejet. */
|
|
135
|
-
const connected = connectPromise.then(() => true, () => false);
|
|
136
|
-
|
|
137
|
-
/* rate-limit-redis charge son script d'increment DEPUIS son constructeur,
|
|
138
|
-
avant que la connexion soit ouverte, et n'attend pas la promesse qu'il
|
|
139
|
-
obtient. Envoyer directement rejetait donc contre un client ferme, et ce
|
|
140
|
-
rejet n'appartenait a personne : Node tuait le processus au demarrage,
|
|
141
|
-
meme avec un Redis parfaitement disponible.
|
|
142
|
-
|
|
143
|
-
Attendre ici transforme cette premiere commande en commande mise en file.
|
|
144
|
-
Et quand la connexion a echoue, le failover a deja bascule sur le store
|
|
145
|
-
memoire : ce store-ci ne sera jamais interroge, sa commande de demarrage
|
|
146
|
-
n'a plus rien a envoyer et se resout sans rien casser. */
|
|
147
|
-
const redisStore = new RedisStore({
|
|
148
|
-
...(prefix ? { prefix } : {}),
|
|
149
|
-
sendCommand: async (...args) => {
|
|
150
|
-
if (!(await connected)) return undefined;
|
|
151
|
-
return client.sendCommand(args);
|
|
152
|
-
}
|
|
153
|
-
});
|
|
154
|
-
|
|
155
|
-
return createFailoverStore(redisStore, memoryStore, connectPromise);
|
|
156
|
-
} catch (_error) {
|
|
157
|
-
return createMemoryStore() || undefined;
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
|
|
161
45
|
// Store Redis générique : le namespace est choisi par le projet consommateur.
|
|
162
46
|
// Astratra ne connaît donc aucun domaine métier (auth, commandes, réservations…).
|
|
163
|
-
const createRedisRateLimitStore = (
|
|
47
|
+
const createRedisRateLimitStore = (options = {}) => createRedisStoreWithOptions(options);
|
|
164
48
|
|
|
165
|
-
|
|
49
|
+
/* Avec redisUrl seul, chaque sorte de limiteur a son espace de clés : sous un même préfixe, la clé (l'adresse) était
|
|
50
|
+
la même pour la limite de l'API et pour celle de la connexion. Les requêtes ordinaires remplissaient alors le
|
|
51
|
+
compteur de la connexion (10 par défaut), et la personne ne pouvait plus se connecter. */
|
|
52
|
+
const resolveStore = (options, kind) => {
|
|
166
53
|
if (options.store) return options.store;
|
|
167
|
-
return
|
|
54
|
+
return createRedisStoreWithOptions({ redisUrl: options.redisUrl, prefix: `rl:${kind}:` });
|
|
168
55
|
};
|
|
169
56
|
|
|
170
57
|
const withOptionalStore = (limiterOptions, store) => {
|
|
@@ -184,25 +71,23 @@ const defaultApiSkip = () => (process.env.NODE_ENV === 'production' ? undefined
|
|
|
184
71
|
const createApiLimiter = (options = {}) => {
|
|
185
72
|
const fallback = options.max || 300;
|
|
186
73
|
const { area } = options;
|
|
187
|
-
return
|
|
74
|
+
return createRateLimit(withOptionalStore({
|
|
188
75
|
windowMs: options.windowMs || 15 * 60 * 1000,
|
|
189
76
|
max: area ? (req) => area(req)?.max || fallback : fallback,
|
|
190
|
-
...(area ? { keyGenerator: (req) => `${area(req)?.name || 'default'}:${
|
|
77
|
+
...(area ? { keyGenerator: (req) => `${area(req)?.name || 'default'}:${clientKey(req)}` } : {}),
|
|
191
78
|
skip: options.skip ?? defaultApiSkip(),
|
|
192
79
|
standardHeaders: options.standardHeaders ?? true,
|
|
193
80
|
legacyHeaders: options.legacyHeaders ?? false,
|
|
194
|
-
validate: options.validate || { ip: false },
|
|
195
81
|
message: options.message || DEFAULT_API_MESSAGE
|
|
196
|
-
}, resolveStore(options)));
|
|
82
|
+
}, resolveStore(options, 'api')));
|
|
197
83
|
};
|
|
198
84
|
|
|
199
|
-
const createLoginLimiter = (options = {}) =>
|
|
85
|
+
const createLoginLimiter = (options = {}) => createRateLimit(withOptionalStore({
|
|
200
86
|
windowMs: options.windowMs || 15 * 60 * 1000,
|
|
201
87
|
max: options.max || 10,
|
|
202
88
|
skip: options.skip,
|
|
203
89
|
standardHeaders: options.standardHeaders ?? true,
|
|
204
90
|
legacyHeaders: options.legacyHeaders ?? false,
|
|
205
|
-
validate: options.validate || { ip: false },
|
|
206
91
|
message: options.message || DEFAULT_LOGIN_MESSAGE,
|
|
207
92
|
handler: (req, res, next, limitOptions) => sendLimitResponse(
|
|
208
93
|
req,
|
|
@@ -212,7 +97,7 @@ const createLoginLimiter = (options = {}) => rateLimit(withOptionalStore({
|
|
|
212
97
|
options.onBlocked,
|
|
213
98
|
{ ip: getIp(req), req }
|
|
214
99
|
)
|
|
215
|
-
}, resolveStore(options)));
|
|
100
|
+
}, resolveStore(options, 'login')));
|
|
216
101
|
|
|
217
102
|
// Avertit une seule fois par processus (fonction partagée par toute instance
|
|
218
103
|
// de createAccountLimiter utilisant la clé par défaut) : le problème est un
|
|
@@ -229,7 +114,7 @@ const defaultAccountKeyGenerator = (req) => {
|
|
|
229
114
|
// un attaquant peut essayer des mots de passe sur des comptes DIFFÉRENTS
|
|
230
115
|
// sans jamais être freiné par compte, et des utilisateurs légitimes sans
|
|
231
116
|
// rapport entre eux peuvent se faire bloquer les uns par les autres.
|
|
232
|
-
if (req
|
|
117
|
+
if (bodyLeftUnparsed(req) && !warnedUnparsedBody) {
|
|
233
118
|
warnedUnparsedBody = true;
|
|
234
119
|
logger.warn(
|
|
235
120
|
'req.body est undefined dans createAccountLimiter() — à monter APRÈS ' +
|
|
@@ -246,13 +131,12 @@ const defaultAccountKeyGenerator = (req) => {
|
|
|
246
131
|
const createAccountLimiter = (options = {}) => {
|
|
247
132
|
const keyGenerator = options.keyGenerator || defaultAccountKeyGenerator;
|
|
248
133
|
|
|
249
|
-
return
|
|
134
|
+
return createRateLimit(withOptionalStore({
|
|
250
135
|
windowMs: options.windowMs || 30 * 60 * 1000,
|
|
251
136
|
max: options.max || 20,
|
|
252
137
|
skip: options.skip,
|
|
253
138
|
standardHeaders: options.standardHeaders ?? true,
|
|
254
139
|
legacyHeaders: options.legacyHeaders ?? false,
|
|
255
|
-
validate: options.validate || { ip: false },
|
|
256
140
|
keyGenerator,
|
|
257
141
|
message: options.message || DEFAULT_ACCOUNT_MESSAGE,
|
|
258
142
|
handler: (req, res, next, limitOptions) => {
|
|
@@ -267,10 +151,15 @@ const createAccountLimiter = (options = {}) => {
|
|
|
267
151
|
{ identifier, ip: getIp(req), req }
|
|
268
152
|
);
|
|
269
153
|
}
|
|
270
|
-
}, resolveStore(options)));
|
|
154
|
+
}, resolveStore(options, 'account')));
|
|
271
155
|
};
|
|
272
156
|
|
|
157
|
+
// Des noms seuls dans cet objet (pas d'expression) : Node lit ces exports sans exécuter le fichier pour les imports
|
|
158
|
+
// nommés d'un module ES (import { createRateLimit } from '@astratra/security').
|
|
273
159
|
module.exports = {
|
|
160
|
+
createRateLimit,
|
|
161
|
+
createMemoryRateLimitStore,
|
|
162
|
+
rateLimitKeyForIp,
|
|
274
163
|
createRedisRateLimitStore,
|
|
275
164
|
createApiLimiter,
|
|
276
165
|
createLoginLimiter,
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
const { createLogger } = require('@astratra/core');
|
|
3
|
+
const { createMemoryRateLimitStore } = require('./rateLimit');
|
|
4
|
+
|
|
5
|
+
const logger = createLogger('rate-limit-redis');
|
|
6
|
+
|
|
7
|
+
/*
|
|
8
|
+
* Le magasin Redis du limiteur, sans rate-limit-redis :
|
|
9
|
+
* - le compteur et son expiration s'écrivent en une seule opération (script Lua) : une panne entre les deux ne laisse
|
|
10
|
+
* jamais un compteur sans fin ;
|
|
11
|
+
* - les clés sont hachées (SHA-256) : ni adresse ni e-mail en clair dans Redis, et une clé immense envoyée par un
|
|
12
|
+
* client ne fait pas une clé immense dans Redis ;
|
|
13
|
+
* - tant que Redis n'est pas joignable (au démarrage, ou s'il tombe), le compte se fait en mémoire : la limite reste
|
|
14
|
+
* appliquée, par serveur, au lieu de laisser passer ou de faire échouer chaque requête.
|
|
15
|
+
*/
|
|
16
|
+
const INCREMENT = `local n = redis.call('INCR', KEYS[1])
|
|
17
|
+
local ttl = redis.call('PTTL', KEYS[1])
|
|
18
|
+
if ttl < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]); ttl = tonumber(ARGV[1]) end
|
|
19
|
+
return {n, ttl}`;
|
|
20
|
+
const DECREMENT = `local n = tonumber(redis.call('GET', KEYS[1]) or '0')
|
|
21
|
+
if n > 0 then return redis.call('DECR', KEYS[1]) end
|
|
22
|
+
return 0`;
|
|
23
|
+
const READ = `local n = redis.call('GET', KEYS[1])
|
|
24
|
+
if not n then return nil end
|
|
25
|
+
return {tonumber(n), redis.call('PTTL', KEYS[1])}`;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* `redisUrl` : le magasin ouvre sa propre connexion (paquet `redis`, à installer par le projet). Ou `sendCommand(args)` /
|
|
29
|
+
* `client` : une connexion du projet (node-redis : client.sendCommand ; ioredis : (args) => client.call(...args)).
|
|
30
|
+
* `prefix` : l'espace des clés, choisi par le projet (« rl: » par défaut).
|
|
31
|
+
* `commandTimeoutMs` : au-delà, une commande compte comme une panne (un Redis figé garde la connexion ouverte sans
|
|
32
|
+
* répondre : sans ce délai, la requête attendait sans fin). `retryAfterMs` : après une panne, le compte se fait en
|
|
33
|
+
* mémoire pendant ce temps avant de réessayer Redis, pour que chaque requête n'attende pas le délai.
|
|
34
|
+
*/
|
|
35
|
+
function createRedisRateLimitStore({ redisUrl, prefix = 'rl:', sendCommand, client, hashKeys = true, commandTimeoutMs = 1000, retryAfterMs = 2000 } = {}) {
|
|
36
|
+
let send = sendCommand || (client && typeof client.sendCommand === 'function' ? (args) => client.sendCommand(args) : null);
|
|
37
|
+
let ownClient = null;
|
|
38
|
+
let ready = Boolean(send);
|
|
39
|
+
if (!send) {
|
|
40
|
+
if (!redisUrl) return undefined;
|
|
41
|
+
let RedisModule;
|
|
42
|
+
try {
|
|
43
|
+
RedisModule = require('redis');
|
|
44
|
+
} catch {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
if (!RedisModule || typeof RedisModule.createClient !== 'function') return undefined;
|
|
48
|
+
// Sans file d'attente hors connexion : une commande envoyée pendant une coupure échoue tout de suite (et le compte
|
|
49
|
+
// passe en mémoire) au lieu d'attendre, requête suspendue, que Redis revienne.
|
|
50
|
+
ownClient = RedisModule.createClient({
|
|
51
|
+
url: redisUrl,
|
|
52
|
+
disableOfflineQueue: true,
|
|
53
|
+
socket: { connectTimeout: 3000, reconnectStrategy: (retries) => Math.min(200 * (retries + 1), 5000) },
|
|
54
|
+
});
|
|
55
|
+
if (typeof ownClient.on === 'function') {
|
|
56
|
+
ownClient.on('error', () => {});
|
|
57
|
+
ownClient.on('ready', () => {
|
|
58
|
+
ready = true;
|
|
59
|
+
});
|
|
60
|
+
ownClient.on('end', () => {
|
|
61
|
+
ready = false;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
send = (args) => ownClient.sendCommand(args);
|
|
65
|
+
Promise.resolve()
|
|
66
|
+
.then(() => ownClient.connect())
|
|
67
|
+
.then(() => {
|
|
68
|
+
ready = true;
|
|
69
|
+
})
|
|
70
|
+
.catch(() => {
|
|
71
|
+
ready = false;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const memory = createMemoryRateLimitStore();
|
|
76
|
+
let windowMs = 60_000;
|
|
77
|
+
let warned = false;
|
|
78
|
+
const redisKey = (key) => prefix + (hashKeys ? crypto.createHash('sha256').update(String(key)).digest('hex') : String(key));
|
|
79
|
+
let downUntil = 0;
|
|
80
|
+
const withTimeout = (promise) => {
|
|
81
|
+
let timer;
|
|
82
|
+
return Promise.race([
|
|
83
|
+
promise,
|
|
84
|
+
new Promise((_, reject) => {
|
|
85
|
+
timer = setTimeout(() => reject(new Error('Redis command timed out')), commandTimeoutMs);
|
|
86
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
87
|
+
}),
|
|
88
|
+
]).finally(() => clearTimeout(timer));
|
|
89
|
+
};
|
|
90
|
+
const viaRedis = async (operation, fallback) => {
|
|
91
|
+
if (!ready || Date.now() < downUntil) return fallback();
|
|
92
|
+
try {
|
|
93
|
+
const result = await withTimeout(Promise.resolve().then(operation));
|
|
94
|
+
warned = false;
|
|
95
|
+
return result;
|
|
96
|
+
} catch {
|
|
97
|
+
downUntil = Date.now() + retryAfterMs;
|
|
98
|
+
if (!warned) {
|
|
99
|
+
warned = true;
|
|
100
|
+
logger.warn('Redis ne répond pas : les limites de requêtes se comptent en mémoire de ce serveur jusqu’à son retour.');
|
|
101
|
+
}
|
|
102
|
+
return fallback();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
localKeys: false,
|
|
108
|
+
prefix,
|
|
109
|
+
init(options = {}) {
|
|
110
|
+
if (Number.isFinite(options.windowMs) && options.windowMs > 0) windowMs = options.windowMs;
|
|
111
|
+
memory.init({ windowMs });
|
|
112
|
+
},
|
|
113
|
+
increment(key) {
|
|
114
|
+
return viaRedis(async () => {
|
|
115
|
+
const reply = await send(['EVAL', INCREMENT, '1', redisKey(key), String(windowMs)]);
|
|
116
|
+
const totalHits = Number(reply[0]);
|
|
117
|
+
const ttl = Number(reply[1]);
|
|
118
|
+
if (!Number.isFinite(totalHits)) throw new Error('unexpected Redis reply');
|
|
119
|
+
return { totalHits, resetTime: new Date(Date.now() + (ttl > 0 ? ttl : windowMs)) };
|
|
120
|
+
}, () => memory.increment(key));
|
|
121
|
+
},
|
|
122
|
+
decrement(key) {
|
|
123
|
+
return viaRedis(async () => {
|
|
124
|
+
await send(['EVAL', DECREMENT, '1', redisKey(key)]);
|
|
125
|
+
}, () => memory.decrement(key));
|
|
126
|
+
},
|
|
127
|
+
resetKey(key) {
|
|
128
|
+
// Effacé des deux côtés : un compte fait en mémoire pendant une coupure ne survit pas à une remise à zéro.
|
|
129
|
+
return Promise.all([viaRedis(() => send(['DEL', redisKey(key)]), () => undefined), memory.resetKey(key)]).then(() => undefined);
|
|
130
|
+
},
|
|
131
|
+
get(key) {
|
|
132
|
+
return viaRedis(async () => {
|
|
133
|
+
const reply = await send(['EVAL', READ, '1', redisKey(key)]);
|
|
134
|
+
if (!reply) return undefined;
|
|
135
|
+
return { totalHits: Number(reply[0]), resetTime: new Date(Date.now() + Math.max(Number(reply[1]), 0)) };
|
|
136
|
+
}, () => memory.get(key));
|
|
137
|
+
},
|
|
138
|
+
async resetAll() {
|
|
139
|
+
await memory.resetAll();
|
|
140
|
+
},
|
|
141
|
+
shutdown() {
|
|
142
|
+
memory.shutdown();
|
|
143
|
+
if (ownClient) {
|
|
144
|
+
ready = false;
|
|
145
|
+
Promise.resolve()
|
|
146
|
+
.then(() => (ownClient.isOpen ? ownClient.quit() : undefined))
|
|
147
|
+
.catch(() => {});
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
module.exports = { createRedisRateLimitStore, REDIS_INCREMENT_SCRIPT: INCREMENT };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* La requête annonce-t-elle un corps ?
|
|
3
|
+
*
|
|
4
|
+
* Express 4 donnait toujours un objet à req.body dès qu'un analyseur
|
|
5
|
+
* (express.json…) était monté, même pour un GET. Express 5 le laisse à
|
|
6
|
+
* undefined quand la requête n'a pas de corps. « req.body est undefined » ne
|
|
7
|
+
* prouve donc un mauvais ordre de montage que si un corps a été envoyé.
|
|
8
|
+
*/
|
|
9
|
+
function hasRequestBody(req) {
|
|
10
|
+
const headers = req && req.headers;
|
|
11
|
+
if (!headers) return false;
|
|
12
|
+
if (headers['transfer-encoding'] !== undefined) return true;
|
|
13
|
+
const length = Number(headers['content-length']);
|
|
14
|
+
return Number.isFinite(length) && length > 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Corps envoyé mais jamais lu par un analyseur monté plus tôt. */
|
|
18
|
+
const bodyLeftUnparsed = (req) => req.body === undefined && hasRequestBody(req);
|
|
19
|
+
|
|
20
|
+
module.exports = { hasRequestBody, bodyLeftUnparsed };
|
package/src/revocation.js
CHANGED
|
@@ -39,8 +39,11 @@ const createMemoryRevocationStore = () => {
|
|
|
39
39
|
const revokedBefore = revokedUsers.get(userId);
|
|
40
40
|
if (revokedBefore === undefined) return false;
|
|
41
41
|
|
|
42
|
+
// Sans date d'émission lisible, rien ne prouve que le jeton est postérieur
|
|
43
|
+
// à « déconnecter partout » : il est révoqué.
|
|
44
|
+
if (issuedAtSeconds === undefined || issuedAtSeconds === null || issuedAtSeconds === '') return true;
|
|
42
45
|
const issuedAtMs = Number(issuedAtSeconds) * 1000;
|
|
43
|
-
if (!Number.isFinite(issuedAtMs)) return
|
|
46
|
+
if (!Number.isFinite(issuedAtMs)) return true;
|
|
44
47
|
|
|
45
48
|
return issuedAtMs <= revokedBefore;
|
|
46
49
|
}
|
package/src/totp.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const crypto = require('node:crypto');
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* La double authentification par code à six chiffres (TOTP, RFC 6238, sur HOTP, RFC 4226), écrite avec node:crypto
|
|
5
|
+
* (elle remplace otplib). Les mêmes codes, les mêmes vérifications et les mêmes adresses otpauth:// qu'otplib 13 sur
|
|
6
|
+
* des vecteurs enregistrés, et les vecteurs des RFC 4226 et 6238.
|
|
7
|
+
*
|
|
8
|
+
* Différences voulues :
|
|
9
|
+
* - un code mal formé (« abcdef », « 12345 ») est simplement invalide, au lieu de lever une exception ;
|
|
10
|
+
* - `afterStep` refuse un code déjà servi (le même code rejoué dans sa fenêtre de 30 s) ;
|
|
11
|
+
* - un émetteur ou un nom de compte contenant « : » est refusé (le format otpauth le sépare par « : ») ;
|
|
12
|
+
* - tous les pas de la fenêtre sont comparés en temps constant, sans s'arrêter au premier qui correspond.
|
|
13
|
+
* La limite des essais (6 chiffres = un million de codes) reste à la charge de la route : voir createAccountLimiter.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
17
|
+
const HASHES = { sha1: 'sha1', sha256: 'sha256', sha512: 'sha512' };
|
|
18
|
+
|
|
19
|
+
class TotpError extends Error {
|
|
20
|
+
constructor(message) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = 'TotpError';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Base32 (RFC 4648), en majuscules, sans remplissage. */
|
|
27
|
+
function base32Encode(buffer) {
|
|
28
|
+
let bits = 0;
|
|
29
|
+
let value = 0;
|
|
30
|
+
let out = '';
|
|
31
|
+
for (const byte of buffer) {
|
|
32
|
+
value = (value << 8) | byte;
|
|
33
|
+
bits += 8;
|
|
34
|
+
while (bits >= 5) {
|
|
35
|
+
out += ALPHABET[(value >>> (bits - 5)) & 31];
|
|
36
|
+
bits -= 5;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31];
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Base32 lu sans tenir compte de la casse, des espaces ni du remplissage ; un autre caractère est refusé. */
|
|
44
|
+
function base32Decode(text) {
|
|
45
|
+
if (typeof text !== 'string') throw new TotpError('secret must be a base32 string');
|
|
46
|
+
// La longueur d'abord, et le remplissage retiré par une boucle : l'expression « =+$ » s'emballait sur une longue
|
|
47
|
+
// suite de « = » (trouvé par assertSafeRegex).
|
|
48
|
+
if (text.length > 1024) throw new TotpError('secret too long');
|
|
49
|
+
let clean = text.replace(/[\s-]/g, '');
|
|
50
|
+
let end = clean.length;
|
|
51
|
+
while (end > 0 && clean[end - 1] === '=') end -= 1;
|
|
52
|
+
clean = clean.slice(0, end).toUpperCase();
|
|
53
|
+
let bits = 0;
|
|
54
|
+
let value = 0;
|
|
55
|
+
const out = [];
|
|
56
|
+
for (const char of clean) {
|
|
57
|
+
const index = ALPHABET.indexOf(char);
|
|
58
|
+
if (index < 0) throw new TotpError('secret is not valid base32');
|
|
59
|
+
value = (value << 5) | index;
|
|
60
|
+
bits += 5;
|
|
61
|
+
if (bits >= 8) {
|
|
62
|
+
out.push((value >>> (bits - 8)) & 255);
|
|
63
|
+
bits -= 8;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return Buffer.from(out);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const keyOf = (secret) => {
|
|
70
|
+
const key = Buffer.isBuffer(secret) ? secret : base32Decode(secret);
|
|
71
|
+
if (key.length < 10) throw new TotpError('secret must be at least 80 bits (RFC 4226)');
|
|
72
|
+
return key;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const optionsOf = ({ digits = 6, algorithm = 'sha1', period = 30 } = {}) => {
|
|
76
|
+
if (!Number.isInteger(digits) || digits < 6 || digits > 10) throw new TotpError('digits must be between 6 and 10');
|
|
77
|
+
if (!HASHES[algorithm]) throw new TotpError('algorithm must be sha1, sha256 or sha512');
|
|
78
|
+
if (!Number.isInteger(period) || period < 1 || period > 3600) throw new TotpError('period must be a number of seconds');
|
|
79
|
+
return { digits, algorithm, period };
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Un secret neuf (20 octets, en base32 : 32 caractères), comme otplib. */
|
|
83
|
+
function generateTotpSecret({ bytes = 20 } = {}) {
|
|
84
|
+
if (!Number.isInteger(bytes) || bytes < 10 || bytes > 64) throw new TotpError('bytes must be between 10 and 64');
|
|
85
|
+
return base32Encode(crypto.randomBytes(bytes));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Le code HOTP (RFC 4226) d'un compteur. */
|
|
89
|
+
function hotp(secret, counter, options = {}) {
|
|
90
|
+
const { digits, algorithm } = optionsOf(options);
|
|
91
|
+
if (!Number.isSafeInteger(counter) || counter < 0) throw new TotpError('counter must be a non-negative integer');
|
|
92
|
+
const message = Buffer.alloc(8);
|
|
93
|
+
message.writeBigUInt64BE(BigInt(counter));
|
|
94
|
+
const mac = crypto.createHmac(HASHES[algorithm], keyOf(secret)).update(message).digest();
|
|
95
|
+
const offset = mac[mac.length - 1] & 0x0f;
|
|
96
|
+
const code = (mac.readUInt32BE(offset) & 0x7fffffff) % 10 ** digits;
|
|
97
|
+
return String(code).padStart(digits, '0');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Le code TOTP (RFC 6238) d'un instant (`epoch` en secondes, maintenant par défaut). */
|
|
101
|
+
function totp(secret, { epoch = Math.floor(Date.now() / 1000), ...options } = {}) {
|
|
102
|
+
const { period } = optionsOf(options);
|
|
103
|
+
return hotp(secret, Math.floor(epoch / period), options);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Vérifie un code. `epochTolerance` (secondes, 30 par défaut : un pas avant ou après) couvre le décalage d'horloge du
|
|
108
|
+
* téléphone ; `afterStep` refuse un pas déjà servi (gardez `timeStep` du dernier code accepté). Rend
|
|
109
|
+
* { valid, delta, timeStep, epoch } ; un code mal formé est invalide, sans exception.
|
|
110
|
+
*/
|
|
111
|
+
function verifyTotp({ secret, token, epoch = Math.floor(Date.now() / 1000), epochTolerance = 30, afterStep, ...options } = {}) {
|
|
112
|
+
const { digits, period } = optionsOf(options);
|
|
113
|
+
const key = keyOf(secret);
|
|
114
|
+
if (typeof token !== 'string' || token.length !== digits || !/^\d+$/.test(token)) return { valid: false, reason: 'format' };
|
|
115
|
+
if (!Number.isFinite(epochTolerance) || epochTolerance < 0 || epochTolerance > 10 * period) throw new TotpError('epochTolerance must be between 0 and 10 periods');
|
|
116
|
+
const current = Math.floor(epoch / period);
|
|
117
|
+
const first = Math.floor((epoch - epochTolerance) / period);
|
|
118
|
+
const last = Math.floor((epoch + epochTolerance) / period);
|
|
119
|
+
const given = Buffer.from(token);
|
|
120
|
+
let matched = null;
|
|
121
|
+
// Chaque pas de la fenêtre est comparé, même après une correspondance : le temps ne dit pas lequel a servi.
|
|
122
|
+
for (let step = first; step <= last; step++) {
|
|
123
|
+
if (step < 0) continue;
|
|
124
|
+
const expected = Buffer.from(hotp(key, step, options));
|
|
125
|
+
if (crypto.timingSafeEqual(expected, given) && matched === null) matched = step;
|
|
126
|
+
}
|
|
127
|
+
if (matched === null) return { valid: false, reason: 'mismatch' };
|
|
128
|
+
if (afterStep !== undefined && afterStep !== null && matched <= afterStep) return { valid: false, reason: 'replay', timeStep: matched };
|
|
129
|
+
return { valid: true, delta: matched - current, timeStep: matched, epoch };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** L'adresse otpauth:// à montrer en QR code (format des applications d'authentification). */
|
|
133
|
+
function totpUri({ issuer, label, secret, digits = 6, algorithm = 'sha1', period = 30 }) {
|
|
134
|
+
optionsOf({ digits, algorithm, period });
|
|
135
|
+
for (const [name, value] of [['issuer', issuer], ['label', label]]) {
|
|
136
|
+
if (typeof value !== 'string' || !value || value.length > 256) throw new TotpError(`${name} must be a non-empty string`);
|
|
137
|
+
if (value.includes(':')) throw new TotpError(`${name} must not contain ":" (it separates issuer and account in otpauth URIs)`);
|
|
138
|
+
}
|
|
139
|
+
keyOf(secret);
|
|
140
|
+
const extra = [];
|
|
141
|
+
extra.push(`secret=${typeof secret === 'string' ? secret.replace(/[\s=-]/g, '').toUpperCase() : base32Encode(secret)}`);
|
|
142
|
+
extra.push(`issuer=${encodeURIComponent(issuer)}`);
|
|
143
|
+
if (algorithm !== 'sha1') extra.push(`algorithm=${algorithm.toUpperCase()}`);
|
|
144
|
+
if (digits !== 6) extra.push(`digits=${digits}`);
|
|
145
|
+
if (period !== 30) extra.push(`period=${period}`);
|
|
146
|
+
return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(label)}?${extra.join('&')}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
module.exports = { generateTotpSecret, totp, hotp, verifyTotp, totpUri, base32Encode, base32Decode, TotpError };
|
package/src/waf.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const { createLogger } = require('@astratra/core');
|
|
2
|
+
const { bodyLeftUnparsed } = require('./requestBody');
|
|
2
3
|
|
|
3
4
|
const logger = createLogger('waf');
|
|
4
5
|
|
|
@@ -36,13 +37,13 @@ const createWafMiddleware = (options = {}) => {
|
|
|
36
37
|
let warnedUnparsedBody = false;
|
|
37
38
|
|
|
38
39
|
return (req, res, next) => {
|
|
39
|
-
//
|
|
40
|
-
// express.urlencoded...) n'a tourné avant ce middleware
|
|
41
|
-
//
|
|
42
|
-
//
|
|
40
|
+
// Un corps envoyé mais laissé à `undefined` signifie qu'aucun body-parser
|
|
41
|
+
// (express.json, express.urlencoded...) n'a tourné avant ce middleware.
|
|
42
|
+
// Express 5 laisse aussi req.body à `undefined` quand la requête n'a pas
|
|
43
|
+
// de corps : seul un corps annoncé (voir requestBody.js) compte. Sans cette détection, ce middleware inspectait silencieusement
|
|
43
44
|
// une chaîne vide à la place du corps de la requête : aucune erreur,
|
|
44
45
|
// aucun log, juste une protection qui ne protégeait rien.
|
|
45
|
-
if (req
|
|
46
|
+
if (bodyLeftUnparsed(req) && !warnedUnparsedBody) {
|
|
46
47
|
warnedUnparsedBody = true;
|
|
47
48
|
logger.warn(
|
|
48
49
|
'req.body est undefined — createWafMiddleware() doit être monté APRÈS ' +
|