@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/src/jwt.js ADDED
@@ -0,0 +1,256 @@
1
+ const crypto = require('node:crypto');
2
+
3
+ /*
4
+ * Les jetons JWT (RFC 7519) signés en JWS compact (RFC 7515), écrits ici avec node:crypto (ils remplacent
5
+ * jsonwebtoken). Même forme de jeton, mêmes revendications, mêmes noms d'erreur (JsonWebTokenError, TokenExpiredError,
6
+ * NotBeforeError) : comparé à jsonwebtoken 9 sur des centaines de vecteurs enregistrés avant son retrait.
7
+ *
8
+ * Plus strict là où c'est sans regret :
9
+ * - la liste des algorithmes est obligatoire à la vérification, et « none » n'existe pas ;
10
+ * - une clé ne sert qu'à sa famille : un secret HMAC ne peut pas être une clé publique (confusion d'algorithme), une
11
+ * clé EC doit être de la courbe de l'algorithme, une clé RSA d'au moins 2 048 bits ;
12
+ * - chaque morceau doit être du base64url exact (pas de remplissage, pas d'autre alphabet), la signature HMAC est
13
+ * comparée en temps constant, un en-tête « crit » est refusé (aucune extension n'est comprise) ;
14
+ * - la charge doit être un objet JSON, et le jeton ne dépasse pas `maxTokenLength` (16 Kio par défaut) ;
15
+ * - toute entrée abîmée est refusée par une JsonWebTokenError, jamais par une autre exception.
16
+ */
17
+
18
+ class JsonWebTokenError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = 'JsonWebTokenError';
22
+ }
23
+ }
24
+ class TokenExpiredError extends JsonWebTokenError {
25
+ constructor(message, expiredAt) {
26
+ super(message);
27
+ this.name = 'TokenExpiredError';
28
+ this.expiredAt = expiredAt;
29
+ }
30
+ }
31
+ class NotBeforeError extends JsonWebTokenError {
32
+ constructor(message, date) {
33
+ super(message);
34
+ this.name = 'NotBeforeError';
35
+ this.date = date;
36
+ }
37
+ }
38
+
39
+ const HASH = { 256: 'sha256', 384: 'sha384', 512: 'sha512' };
40
+ const EC_CURVE = { ES256: 'prime256v1', ES384: 'secp384r1', ES512: 'secp521r1' };
41
+ const EC_SIGNATURE_LENGTH = { ES256: 64, ES384: 96, ES512: 132 };
42
+ const ALGORITHMS = ['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512'];
43
+ const DEFAULT_MAX_TOKEN_LENGTH = 16 * 1024;
44
+ const BASE64URL = /^[A-Za-z0-9_-]*$/;
45
+
46
+ const family = (alg) => alg.slice(0, 2);
47
+ const hashOf = (alg) => HASH[alg.slice(2)];
48
+
49
+ /* Les durées écrites comme jsonwebtoken les lisait (module ms) : un nombre de secondes, ou un texte « 15m », « 2 days »,
50
+ « 1.5h » ; un texte sans unité compte en millisecondes. */
51
+ const UNITS = {
52
+ ms: 1, msec: 1, msecs: 1, millisecond: 1, milliseconds: 1,
53
+ s: 1000, sec: 1000, secs: 1000, second: 1000, seconds: 1000,
54
+ m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000,
55
+ h: 3_600_000, hr: 3_600_000, hrs: 3_600_000, hour: 3_600_000, hours: 3_600_000,
56
+ d: 86_400_000, day: 86_400_000, days: 86_400_000,
57
+ w: 604_800_000, week: 604_800_000, weeks: 604_800_000,
58
+ y: 31_557_600_000, yr: 31_557_600_000, yrs: 31_557_600_000, year: 31_557_600_000, years: 31_557_600_000,
59
+ };
60
+ function timespan(value, timestamp) {
61
+ if (typeof value === 'number' && Number.isFinite(value)) return Math.floor(timestamp + value);
62
+ if (typeof value === 'string' && value.length <= 100) {
63
+ // Sans ambiguïté : les chiffres avant la virgule ne peuvent être pris que d'une façon. L'expression du module ms
64
+ // (« (?:\d+)?\.?\d+ ») s'emballait sur une longue suite de chiffres (trouvé par assertSafeRegex).
65
+ const match = /^(-?(?:\d+(?:\.\d+)?|\.\d+)) *([a-z]+)?$/i.exec(value);
66
+ if (match) {
67
+ const unit = UNITS[(match[2] || 'ms').toLowerCase()];
68
+ if (unit) return Math.floor(timestamp + (Number(match[1]) * unit) / 1000);
69
+ }
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ const encodeJson = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
75
+
76
+ /** Une partie base64url exacte, décodée ; null si elle ne l'est pas (remplissage, autre alphabet, écriture non canonique). */
77
+ function decodeSegment(segment) {
78
+ if (typeof segment !== 'string' || !BASE64URL.test(segment) || segment.length % 4 === 1) return null;
79
+ const bytes = Buffer.from(segment, 'base64url');
80
+ return bytes.toString('base64url') === segment ? bytes : null;
81
+ }
82
+
83
+ function parseJsonSegment(segment) {
84
+ const bytes = decodeSegment(segment);
85
+ if (!bytes) return undefined;
86
+ try {
87
+ return JSON.parse(bytes.toString('utf8'));
88
+ } catch {
89
+ return undefined;
90
+ }
91
+ }
92
+
93
+ /** Le jeton découpé sans rien vérifier ({ header, payload, signature }), ou null. */
94
+ function decodeJwt(token, { complete = false } = {}) {
95
+ if (typeof token !== 'string') return null;
96
+ const parts = token.split('.');
97
+ if (parts.length !== 3) return null;
98
+ const header = parseJsonSegment(parts[0]);
99
+ const payload = parseJsonSegment(parts[1]);
100
+ if (!header || typeof header !== 'object' || Array.isArray(header) || payload === undefined) return null;
101
+ return complete ? { header, payload, signature: parts[2] } : payload;
102
+ }
103
+
104
+ const looksLikePem = (text) => /-----BEGIN [A-Z ]*KEY-----/.test(text) || /-----BEGIN CERTIFICATE-----/.test(text);
105
+
106
+ /** La clé pour l'algorithme, vérifiée : une clé d'une autre famille est refusée (pas de confusion d'algorithme). */
107
+ function keyFor(alg, key, usage) {
108
+ if (family(alg) === 'HS') {
109
+ if (key && typeof key === 'object' && typeof key.type === 'string' && !Buffer.isBuffer(key)) {
110
+ if (key.type !== 'secret') throw new JsonWebTokenError(`secretOrPublicKey must be a symmetric key when using ${alg}`);
111
+ return key;
112
+ }
113
+ if (typeof key === 'string' && looksLikePem(key)) throw new JsonWebTokenError(`secretOrPublicKey must be a symmetric key when using ${alg}`);
114
+ if ((typeof key !== 'string' && !Buffer.isBuffer(key)) || key.length === 0) throw new JsonWebTokenError('secret or public key must be provided');
115
+ return crypto.createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key, 'utf8'));
116
+ }
117
+ let keyObject;
118
+ try {
119
+ if (key && typeof key === 'object' && typeof key.type === 'string' && !Buffer.isBuffer(key)) keyObject = key;
120
+ else if (usage === 'sign') keyObject = crypto.createPrivateKey(key);
121
+ else keyObject = crypto.createPublicKey(key);
122
+ } catch {
123
+ throw new JsonWebTokenError(`the key cannot be read for ${alg}`);
124
+ }
125
+ if (keyObject.type === 'secret') throw new JsonWebTokenError(`a symmetric key cannot be used for ${alg}`);
126
+ if (usage === 'sign' && keyObject.type !== 'private') throw new JsonWebTokenError(`a private key is needed to sign with ${alg}`);
127
+ if (usage === 'verify' && keyObject.type === 'private') keyObject = crypto.createPublicKey(keyObject);
128
+ const type = keyObject.asymmetricKeyType;
129
+ if (family(alg) === 'ES') {
130
+ if (type !== 'ec' || keyObject.asymmetricKeyDetails.namedCurve !== EC_CURVE[alg]) throw new JsonWebTokenError(`"alg" parameter "${alg}" requires curve "${EC_CURVE[alg]}"`);
131
+ } else {
132
+ if (type !== 'rsa' && !(family(alg) === 'PS' && type === 'rsa-pss')) throw new JsonWebTokenError(`"alg" parameter for "${type}" key type must be one of: ${type === 'ec' ? 'ES256, ES384, ES512' : 'RS256, RS384, RS512, PS256, PS384, PS512'}.`);
133
+ if (keyObject.asymmetricKeyDetails.modulusLength < 2048) throw new JsonWebTokenError(`${alg} requires a key size of 2048 bits or larger`);
134
+ }
135
+ return keyObject;
136
+ }
137
+
138
+ function signatureOf(alg, input, key) {
139
+ const hash = hashOf(alg);
140
+ if (family(alg) === 'HS') return crypto.createHmac(hash, key).update(input).digest();
141
+ if (family(alg) === 'ES') return crypto.sign(hash, Buffer.from(input), { key, dsaEncoding: 'ieee-p1363' });
142
+ if (family(alg) === 'PS') return crypto.sign(hash, Buffer.from(input), { key, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST });
143
+ return crypto.sign(hash, Buffer.from(input), key);
144
+ }
145
+
146
+ function signatureMatches(alg, input, signature, key) {
147
+ const hash = hashOf(alg);
148
+ if (family(alg) === 'HS') {
149
+ const expected = crypto.createHmac(hash, key).update(input).digest();
150
+ return signature.length === expected.length && crypto.timingSafeEqual(signature, expected);
151
+ }
152
+ try {
153
+ if (family(alg) === 'ES') {
154
+ if (signature.length !== EC_SIGNATURE_LENGTH[alg]) return false;
155
+ return crypto.verify(hash, Buffer.from(input), { key, dsaEncoding: 'ieee-p1363' }, signature);
156
+ }
157
+ if (family(alg) === 'PS') return crypto.verify(hash, Buffer.from(input), { key, padding: crypto.constants.RSA_PKCS1_PSS_PADDING, saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST }, signature);
158
+ return crypto.verify(hash, Buffer.from(input), key, signature);
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ const CLAIM_OPTIONS = { audience: 'aud', issuer: 'iss', subject: 'sub', jwtid: 'jti' };
165
+
166
+ /**
167
+ * Signe un jeton. Options : algorithm (HS256 par défaut), expiresIn, notBefore, audience, issuer, subject, jwtid,
168
+ * keyid, header, noTimestamp. Une revendication donnée deux fois (dans la charge et en option) est refusée.
169
+ */
170
+ function signJwt(payload, key, options = {}) {
171
+ const alg = options.algorithm || 'HS256';
172
+ if (!ALGORITHMS.includes(alg)) throw new JsonWebTokenError('"algorithm" must be a valid string enum value');
173
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new JsonWebTokenError('payload must be a plain object');
174
+ const claims = { ...payload };
175
+ const timestamp = typeof claims.iat === 'number' ? claims.iat : Math.floor(Date.now() / 1000);
176
+ if (options.noTimestamp) delete claims.iat;
177
+ else claims.iat = timestamp;
178
+ if (options.notBefore !== undefined) {
179
+ if (claims.nbf !== undefined) throw new JsonWebTokenError('Bad "options.notBefore" option the payload already has an "nbf" property.');
180
+ claims.nbf = timespan(options.notBefore, timestamp);
181
+ if (claims.nbf === undefined) throw new JsonWebTokenError('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
182
+ }
183
+ if (options.expiresIn !== undefined) {
184
+ if (claims.exp !== undefined) throw new JsonWebTokenError('Bad "options.expiresIn" option the payload already has an "exp" property.');
185
+ claims.exp = timespan(options.expiresIn, timestamp);
186
+ if (claims.exp === undefined) throw new JsonWebTokenError('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
187
+ }
188
+ for (const [option, claim] of Object.entries(CLAIM_OPTIONS)) {
189
+ if (options[option] === undefined) continue;
190
+ if (claims[claim] !== undefined) throw new JsonWebTokenError(`Bad "options.${option}" option. The payload already has an "${claim}" property.`);
191
+ claims[claim] = options[option];
192
+ }
193
+ const header = { alg, typ: 'JWT', ...(options.keyid !== undefined ? { kid: options.keyid } : {}), ...(options.header || {}) };
194
+ header.alg = alg;
195
+ const input = `${encodeJson(header)}.${encodeJson(claims)}`;
196
+ return `${input}.${signatureOf(alg, input, keyFor(alg, key, 'sign')).toString('base64url')}`;
197
+ }
198
+
199
+ /**
200
+ * Vérifie un jeton et rend sa charge. Options : algorithms (obligatoire), issuer (texte ou liste), audience (texte,
201
+ * expression ou liste), subject, jwtid, clockTolerance (secondes), clockTimestamp, maxAge, maxTokenLength, complete.
202
+ */
203
+ function verifyJwt(token, key, options = {}) {
204
+ const algorithms = options.algorithms;
205
+ if (!Array.isArray(algorithms) || !algorithms.length || !algorithms.every((a) => ALGORITHMS.includes(a))) {
206
+ throw new JsonWebTokenError('verifyJwt needs options.algorithms (one or more of ' + ALGORITHMS.join(', ') + ')');
207
+ }
208
+ if (typeof token !== 'string' || !token) throw new JsonWebTokenError('jwt must be provided');
209
+ if (token.length > (options.maxTokenLength || DEFAULT_MAX_TOKEN_LENGTH)) throw new JsonWebTokenError('jwt too long');
210
+ const parts = token.split('.');
211
+ if (parts.length !== 3) throw new JsonWebTokenError('jwt malformed');
212
+ const header = parseJsonSegment(parts[0]);
213
+ if (!header || typeof header !== 'object' || Array.isArray(header)) throw new JsonWebTokenError('invalid token');
214
+ if (header.crit !== undefined) throw new JsonWebTokenError('unsupported critical header');
215
+ if (typeof header.alg !== 'string' || !algorithms.includes(header.alg)) throw new JsonWebTokenError('invalid algorithm');
216
+ if (!parts[2]) throw new JsonWebTokenError('jwt signature is required');
217
+ const signature = decodeSegment(parts[2]);
218
+ if (!signature) throw new JsonWebTokenError('invalid signature');
219
+ const verificationKey = keyFor(header.alg, key, 'verify');
220
+ if (!signatureMatches(header.alg, `${parts[0]}.${parts[1]}`, signature, verificationKey)) throw new JsonWebTokenError('invalid signature');
221
+
222
+ const payload = parseJsonSegment(parts[1]);
223
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw new JsonWebTokenError('invalid token');
224
+ const now = options.clockTimestamp !== undefined ? options.clockTimestamp : Math.floor(Date.now() / 1000);
225
+ const tolerance = options.clockTolerance || 0;
226
+
227
+ if (payload.nbf !== undefined && !options.ignoreNotBefore) {
228
+ if (typeof payload.nbf !== 'number') throw new JsonWebTokenError('invalid nbf value');
229
+ if (payload.nbf > now + tolerance) throw new NotBeforeError('jwt not active', new Date(payload.nbf * 1000));
230
+ }
231
+ if (payload.exp !== undefined && !options.ignoreExpiration) {
232
+ if (typeof payload.exp !== 'number') throw new JsonWebTokenError('invalid exp value');
233
+ if (now >= payload.exp + tolerance) throw new TokenExpiredError('jwt expired', new Date(payload.exp * 1000));
234
+ }
235
+ if (options.audience !== undefined) {
236
+ const wanted = Array.isArray(options.audience) ? options.audience : [options.audience];
237
+ const given = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
238
+ const match = given.some((aud) => wanted.some((w) => (w instanceof RegExp ? typeof aud === 'string' && w.test(aud) : w === aud)));
239
+ if (!match) throw new JsonWebTokenError(`jwt audience invalid. expected: ${wanted.join(' or ')}`);
240
+ }
241
+ if (options.issuer !== undefined) {
242
+ const wanted = Array.isArray(options.issuer) ? options.issuer : [options.issuer];
243
+ if (typeof payload.iss !== 'string' || !wanted.includes(payload.iss)) throw new JsonWebTokenError(`jwt issuer invalid. expected: ${wanted.join(',')}`);
244
+ }
245
+ if (options.subject !== undefined && payload.sub !== options.subject) throw new JsonWebTokenError(`jwt subject invalid. expected: ${options.subject}`);
246
+ if (options.jwtid !== undefined && payload.jti !== options.jwtid) throw new JsonWebTokenError(`jwt jwtid invalid. expected: ${options.jwtid}`);
247
+ if (options.maxAge !== undefined) {
248
+ if (typeof payload.iat !== 'number') throw new JsonWebTokenError('iat required when maxAge is specified');
249
+ const limit = timespan(options.maxAge, payload.iat);
250
+ if (limit === undefined) throw new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
251
+ if (now >= limit + tolerance) throw new TokenExpiredError('maxAge exceeded', new Date(limit * 1000));
252
+ }
253
+ return options.complete ? { header, payload, signature: parts[2] } : payload;
254
+ }
255
+
256
+ module.exports = { signJwt, verifyJwt, decodeJwt, JsonWebTokenError, TokenExpiredError, NotBeforeError, JWT_ALGORITHMS: ALGORITHMS };
package/src/jwtAuth.js CHANGED
@@ -1,4 +1,4 @@
1
- const jwt = require('jsonwebtoken');
1
+ const { verifyJwt } = require('./jwt');
2
2
  const { DEFAULT_SESSION_COOKIE_NAME } = require('./cookies');
3
3
 
4
4
  const DEFAULT_UNAUTHORIZED = {
@@ -64,12 +64,30 @@ const verificationOptionsFrom = (options = {}) => ({
64
64
  ...(options.maxAge ? { maxAge: options.maxAge } : {})
65
65
  });
66
66
 
67
+ /* Un jeton émis « dans le futur » (iat après maintenant) échappait à « déconnecter partout », qui révoque ce qui a été
68
+ émis AVANT la déconnexion : un serveur à l'horloge en avance en produit, et jsonwebtoken ne le vérifie pas. Au-delà
69
+ de la tolérance d'horloge (clockTolerance, une minute par défaut), il est refusé ; un iat qui n'est pas un nombre
70
+ aussi (trouvé par les jetons piégés de @astratra/testkit/security). */
71
+ const DEFAULT_FUTURE_IAT_TOLERANCE_SECONDS = 60;
72
+
73
+ const assertIssuedAt = (decoded, verificationOptions) => {
74
+ if (!decoded || typeof decoded !== 'object' || decoded.iat === undefined) return decoded;
75
+ if (typeof decoded.iat !== 'number' || !Number.isFinite(decoded.iat)) {
76
+ throw Object.assign(new Error('jwt iat must be a number'), { name: 'JsonWebTokenError' });
77
+ }
78
+ const tolerance = verificationOptions.clockTolerance !== undefined ? verificationOptions.clockTolerance : DEFAULT_FUTURE_IAT_TOLERANCE_SECONDS;
79
+ if (decoded.iat > Math.floor(Date.now() / 1000) + tolerance) {
80
+ throw Object.assign(new Error('jwt issued in the future'), { name: 'JsonWebTokenError' });
81
+ }
82
+ return decoded;
83
+ };
84
+
67
85
  const verifyWithRotation = (token, secret, legacySecret, verificationOptions) => {
68
86
  try {
69
- return jwt.verify(token, secret, verificationOptions);
87
+ return assertIssuedAt(verifyJwt(token, secret, verificationOptions), verificationOptions);
70
88
  } catch (error) {
71
89
  if (legacySecret && error.name === 'JsonWebTokenError') {
72
- return jwt.verify(token, legacySecret, verificationOptions);
90
+ return assertIssuedAt(verifyJwt(token, legacySecret, verificationOptions), verificationOptions);
73
91
  }
74
92
  throw error;
75
93
  }
@@ -91,7 +109,7 @@ const createAuthMiddleware = (options = {}) => {
91
109
  if (
92
110
  decoded &&
93
111
  decoded.id !== undefined &&
94
- decoded.iat !== undefined &&
112
+ // Même sans iat : un jeton sans date ne doit pas échapper à « déconnecter partout ».
95
113
  typeof options.revocationStore.isRevokedForUser === 'function'
96
114
  ) {
97
115
  const revokedByUser = await options.revocationStore.isRevokedForUser(decoded.id, decoded.iat);
@@ -35,6 +35,21 @@ function stripDangerousKeys(value, replaceWith) {
35
35
 
36
36
  const DEFAULT_TARGETS = ['body', 'query', 'params'];
37
37
 
38
+ /* Express 5 définit req.query par un lecteur (getter) qui relit l'adresse à
39
+ chaque accès : nettoyer l'objet rendu une première fois ne servait à rien,
40
+ le suivant revenait intact (« ?date[$gt]= » atteignait la route). L'objet
41
+ nettoyé devient donc la valeur propre de req.query. Rien à faire quand la
42
+ propriété est déjà une simple valeur (Express 4, req.body, req.params). */
43
+ function keepCleaned(req, target, value) {
44
+ const own = Object.getOwnPropertyDescriptor(req, target);
45
+ if (own && 'value' in own) return;
46
+ try {
47
+ Object.defineProperty(req, target, { value, writable: true, configurable: true, enumerable: true });
48
+ } catch (_error) {
49
+ /* Propriété verrouillée : l'objet a au moins été nettoyé en place. */
50
+ }
51
+ }
52
+
38
53
  /**
39
54
  * Strips Mongo operator injection out of req.body/req.query/req.params
40
55
  * before it reaches a database call — see stripDangerousKeys() for the bug
@@ -52,8 +67,10 @@ const createMongoSanitizeMiddleware = (options = {}) => {
52
67
 
53
68
  return (req, res, next) => {
54
69
  for (const target of targets) {
55
- if (req[target] && typeof req[target] === 'object') {
56
- stripDangerousKeys(req[target], replaceWith);
70
+ const value = req[target];
71
+ if (value && typeof value === 'object') {
72
+ stripDangerousKeys(value, replaceWith);
73
+ keepCleaned(req, target, value);
57
74
  }
58
75
  }
59
76
  return next();
@@ -0,0 +1,235 @@
1
+ const net = require('node:net');
2
+
3
+ /**
4
+ * Le limiteur de requêtes, écrit ici sans dépendance (il remplace express-rate-limit et rate-limit-redis) :
5
+ * une fenêtre fixe par clé, un magasin interchangeable (mémoire, Redis, ou celui du projet), les en-têtes
6
+ * RateLimit-* et la réponse 429. Les options et l'interface des magasins sont celles qu'utilisaient déjà les
7
+ * projets (init, increment, decrement, resetKey, get, resetAll, shutdown), pour qu'aucun n'ait à changer.
8
+ */
9
+
10
+ const DEFAULT_IPV6_SUBNET = 56;
11
+
12
+ /** Les huit groupes de 16 bits d'une adresse IPv6, ou null. Accepte « :: », la fin en IPv4 et un identifiant de zone. */
13
+ function ipv6Groups(address) {
14
+ let text = String(address).split('%')[0];
15
+ if (!net.isIPv6(text)) return null;
16
+ // Une fin en IPv4 (::ffff:1.2.3.4) devient deux groupes. Découpée sans expression régulière : une expression non
17
+ // ancrée sur une longue suite de chiffres s'emballait (trouvé par assertSafeRegex de @astratra/testkit/security).
18
+ const tail = text.slice(text.lastIndexOf(':') + 1);
19
+ if (net.isIPv4(tail)) {
20
+ const parts = tail.split('.').map(Number);
21
+ text = text.slice(0, -tail.length) + `${((parts[0] << 8) | parts[1]).toString(16)}:${((parts[2] << 8) | parts[3]).toString(16)}`;
22
+ }
23
+ const [head, rest] = text.split('::');
24
+ const left = head ? head.split(':') : [];
25
+ const right = rest !== undefined && rest !== '' ? rest.split(':') : [];
26
+ const missing = 8 - left.length - right.length;
27
+ const groups = [...left, ...Array(rest !== undefined ? missing : 0).fill('0'), ...right].map((g) => parseInt(g, 16));
28
+ return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) ? groups : null;
29
+ }
30
+
31
+ /** L'écriture courte (RFC 5952) : minuscules, sans zéros de tête, la plus longue suite de zéros remplacée par « :: ». */
32
+ function formatIpv6(groups) {
33
+ let bestStart = -1;
34
+ let bestLength = 1;
35
+ for (let i = 0; i < 8; ) {
36
+ if (groups[i] !== 0) {
37
+ i += 1;
38
+ continue;
39
+ }
40
+ let j = i;
41
+ while (j < 8 && groups[j] === 0) j += 1;
42
+ if (j - i > bestLength) {
43
+ bestStart = i;
44
+ bestLength = j - i;
45
+ }
46
+ i = j;
47
+ }
48
+ const hex = groups.map((g) => g.toString(16));
49
+ if (bestStart === -1) return hex.join(':');
50
+ return `${hex.slice(0, bestStart).join(':')}::${hex.slice(bestStart + bestLength).join(':')}`;
51
+ }
52
+
53
+ /**
54
+ * La clé d'une adresse : une adresse IPv4 telle quelle (même écrite en IPv6, « ::ffff:1.2.3.4 ») ; une adresse IPv6
55
+ * compte pour tout son bloc (/56 par défaut), sinon chacun change d'adresse dans son bloc et repart avec un compteur
56
+ * neuf. `subnet` à false garde l'adresse exacte.
57
+ */
58
+ function ipKey(address, subnet = DEFAULT_IPV6_SUBNET) {
59
+ const ip = String(address || '');
60
+ if (!ip || net.isIPv4(ip)) return ip;
61
+ const groups = ipv6Groups(ip);
62
+ if (!groups) return ip;
63
+ // IPv4 écrite en IPv6 (::ffff:a.b.c.d) : c'est l'adresse IPv4 qui compte.
64
+ if (groups.slice(0, 5).every((g) => g === 0) && groups[5] === 0xffff) {
65
+ return `${groups[6] >> 8}.${groups[6] & 0xff}.${groups[7] >> 8}.${groups[7] & 0xff}`;
66
+ }
67
+ if (!subnet) return formatIpv6(groups);
68
+ const masked = groups.map((g, i) => {
69
+ const bitsBefore = i * 16;
70
+ if (bitsBefore >= subnet) return 0;
71
+ if (bitsBefore + 16 <= subnet) return g;
72
+ return g & (0xffff << (16 - (subnet - bitsBefore))) & 0xffff;
73
+ });
74
+ return `${formatIpv6(masked)}/${subnet}`;
75
+ }
76
+
77
+ const requestIp = (req) => (req && (req.ip || (req.connection && req.connection.remoteAddress) || (req.socket && req.socket.remoteAddress))) || '';
78
+
79
+ /**
80
+ * Le magasin en mémoire : une fenêtre fixe par clé. Les clés expirées sont retirées à chaque fenêtre (minuterie qui
81
+ * ne retient pas le processus) et quand la table dépasse `maxKeys` : un afflux de clés neuves ne fait pas grossir la
82
+ * mémoire sans fin.
83
+ */
84
+ function createMemoryRateLimitStore({ maxKeys = 100_000 } = {}) {
85
+ const counters = new Map();
86
+ let windowMs = 60_000;
87
+ let timer = null;
88
+ const sweep = (now = Date.now()) => {
89
+ for (const [key, counter] of counters) if (counter.resetAt <= now) counters.delete(key);
90
+ };
91
+ const schedule = () => {
92
+ if (timer) clearInterval(timer);
93
+ timer = setInterval(sweep, windowMs);
94
+ if (typeof timer.unref === 'function') timer.unref();
95
+ };
96
+ return {
97
+ localKeys: true,
98
+ init(options = {}) {
99
+ if (Number.isFinite(options.windowMs) && options.windowMs > 0) windowMs = options.windowMs;
100
+ schedule();
101
+ },
102
+ async get(key) {
103
+ const counter = counters.get(key);
104
+ if (!counter || counter.resetAt <= Date.now()) return undefined;
105
+ return { totalHits: counter.hits, resetTime: new Date(counter.resetAt) };
106
+ },
107
+ async increment(key) {
108
+ const now = Date.now();
109
+ let counter = counters.get(key);
110
+ if (!counter || counter.resetAt <= now) {
111
+ if (!counter && counters.size >= maxKeys) sweep(now);
112
+ counter = { hits: 0, resetAt: now + windowMs };
113
+ counters.set(key, counter);
114
+ }
115
+ counter.hits += 1;
116
+ return { totalHits: counter.hits, resetTime: new Date(counter.resetAt) };
117
+ },
118
+ async decrement(key) {
119
+ const counter = counters.get(key);
120
+ if (counter && counter.hits > 0) counter.hits -= 1;
121
+ },
122
+ async resetKey(key) {
123
+ counters.delete(key);
124
+ },
125
+ async resetAll() {
126
+ counters.clear();
127
+ },
128
+ shutdown() {
129
+ if (timer) clearInterval(timer);
130
+ timer = null;
131
+ counters.clear();
132
+ },
133
+ };
134
+ }
135
+
136
+ const defaultHandler = (req, res, _next, options) => {
137
+ res.status(options.statusCode);
138
+ const message = options.message;
139
+ if (message !== null && typeof message === 'object') return res.json(message);
140
+ if (typeof res.send === 'function') return res.send(message);
141
+ return res.json(message);
142
+ };
143
+
144
+ /**
145
+ * Le middleware. Options (celles qu'acceptait express-rate-limit, sauf `validate`, sans objet ici) :
146
+ * windowMs, limit ou max (nombre, ou fonction (req, res) qui rend un nombre), keyGenerator (req, res), skip (req, res),
147
+ * message (valeur ou fonction (req, res)), statusCode, handler (req, res, next, options), standardHeaders,
148
+ * legacyHeaders, store, passOnStoreError, requestPropertyName, skipSuccessfulRequests, skipFailedRequests,
149
+ * requestWasSuccessful (req, res), ipv6Subnet.
150
+ */
151
+ function createRateLimit(options = {}) {
152
+ const windowMs = Number.isFinite(options.windowMs) && options.windowMs > 0 ? options.windowMs : 60_000;
153
+ const limitOption = options.limit !== undefined ? options.limit : options.max !== undefined ? options.max : 5;
154
+ const statusCode = options.statusCode || 429;
155
+ const standardHeaders = options.standardHeaders === undefined ? true : options.standardHeaders;
156
+ const legacyHeaders = Boolean(options.legacyHeaders);
157
+ const requestPropertyName = options.requestPropertyName || 'rateLimit';
158
+ const ipv6Subnet = options.ipv6Subnet === undefined ? DEFAULT_IPV6_SUBNET : options.ipv6Subnet;
159
+ const keyGenerator = options.keyGenerator || ((req) => ipKey(requestIp(req), ipv6Subnet));
160
+ const handler = options.handler || defaultHandler;
161
+ const requestWasSuccessful = options.requestWasSuccessful || ((_req, res) => res.statusCode < 400);
162
+ const store = options.store || createMemoryRateLimitStore();
163
+ if (typeof store.increment !== 'function') throw new TypeError('createRateLimit: the store needs an increment(key) method.');
164
+ if (typeof store.init === 'function') store.init({ windowMs });
165
+
166
+ const middleware = async function rateLimitMiddleware(req, res, next) {
167
+ try {
168
+ if (options.skip && (await options.skip(req, res))) return next();
169
+ const key = String(await keyGenerator(req, res));
170
+ let counted;
171
+ try {
172
+ counted = await store.increment(key);
173
+ } catch (storeError) {
174
+ // Un magasin en panne ne laisse jamais passer sans compter, sauf choix explicite du projet.
175
+ if (options.passOnStoreError) return next();
176
+ return next(storeError);
177
+ }
178
+ const totalHits = Number(counted && counted.totalHits);
179
+ if (!Number.isFinite(totalHits)) return next(new Error('rate limit store returned no hit count'));
180
+ const resetTime = counted.resetTime instanceof Date ? counted.resetTime : new Date(Date.now() + windowMs);
181
+ const limit = Number(typeof limitOption === 'function' ? await limitOption(req, res) : limitOption);
182
+ const remaining = Math.max(limit - totalHits, 0);
183
+ if (req && typeof req === 'object') req[requestPropertyName] = { limit, used: totalHits, remaining, resetTime, key };
184
+
185
+ const secondsLeft = Math.max(0, Math.ceil((resetTime.getTime() - Date.now()) / 1000));
186
+ if (!res.headersSent && typeof res.setHeader === 'function') {
187
+ if (standardHeaders) {
188
+ res.setHeader('RateLimit-Policy', `${limit};w=${Math.ceil(windowMs / 1000)}`);
189
+ res.setHeader('RateLimit-Limit', String(limit));
190
+ res.setHeader('RateLimit-Remaining', String(remaining));
191
+ res.setHeader('RateLimit-Reset', String(secondsLeft));
192
+ }
193
+ if (legacyHeaders) {
194
+ res.setHeader('X-RateLimit-Limit', String(limit));
195
+ res.setHeader('X-RateLimit-Remaining', String(remaining));
196
+ res.setHeader('X-RateLimit-Reset', String(Math.ceil(resetTime.getTime() / 1000)));
197
+ }
198
+ }
199
+
200
+ if ((options.skipSuccessfulRequests || options.skipFailedRequests) && typeof res.on === 'function') {
201
+ let settled = false;
202
+ const settle = async (closedEarly) => {
203
+ if (settled) return;
204
+ settled = true;
205
+ const success = !closedEarly && requestWasSuccessful(req, res);
206
+ if ((success && options.skipSuccessfulRequests) || (!success && options.skipFailedRequests)) {
207
+ try {
208
+ if (typeof store.decrement === 'function') await store.decrement(key);
209
+ } catch {
210
+ // Un décompte manqué ne fait que garder la requête comptée : jamais plus permissif.
211
+ }
212
+ }
213
+ };
214
+ res.on('finish', () => settle(false));
215
+ res.on('close', () => settle(!res.writableFinished));
216
+ }
217
+
218
+ if (totalHits > limit) {
219
+ if (!res.headersSent && typeof res.setHeader === 'function' && (standardHeaders || legacyHeaders)) res.setHeader('Retry-After', String(secondsLeft));
220
+ const message = typeof options.message === 'function' ? await options.message(req, res) : options.message;
221
+ return handler(req, res, next, { ...options, windowMs, limit, statusCode, message: message === undefined ? 'Too many requests, please try again later.' : message });
222
+ }
223
+ return next();
224
+ } catch (error) {
225
+ return next(error);
226
+ }
227
+ };
228
+
229
+ middleware.resetKey = (key) => (typeof store.resetKey === 'function' ? store.resetKey(String(key)) : undefined);
230
+ middleware.getKey = (key) => (typeof store.get === 'function' ? store.get(String(key)) : undefined);
231
+ middleware.store = store;
232
+ return middleware;
233
+ }
234
+
235
+ module.exports = { createRateLimit, createMemoryRateLimitStore, ipKey, requestIp, DEFAULT_IPV6_SUBNET };