@astratra/security 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 +51 -3
- package/package.json +1 -1
- package/src/index.d.ts +33 -0
- package/src/index.js +1 -0
- package/src/mongoSanitize.js +63 -0
- package/src/passwordHashing.js +34 -1
package/README.md
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
# @astratra/security
|
|
2
2
|
|
|
3
3
|
Primitives de sécurité applicative pour l'authentification, l'autorisation,
|
|
4
|
-
le CORS, le chiffrement de champ,
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
le CORS, le chiffrement de champ, la force du mot de passe, l'anti-injection
|
|
5
|
+
Mongo, le rate limiting, une CSP configurable, un WAF heuristique et
|
|
6
|
+
WebAuthn/passkeys — génériques et découplées de toute base de données, ORM
|
|
7
|
+
ou liste de rôles fixe. Dépend de `@astratra/core`.
|
|
7
8
|
|
|
8
9
|
Partout où un vrai projet a besoin de persistance (révocation de session,
|
|
9
10
|
stockage de credentials WebAuthn, alerte de brute-force), c'est un
|
|
@@ -82,6 +83,29 @@ sur une entrée invalide (mot de passe erroné, hash étranger ou corrompu) :
|
|
|
82
83
|
elle retourne toujours `false`, donc un appelant peut traiter le résultat
|
|
83
84
|
comme un booléen sans `try/catch`.
|
|
84
85
|
|
|
86
|
+
### Force du mot de passe
|
|
87
|
+
|
|
88
|
+
`hashPassword` ne jugeait jamais si un mot de passe valait la peine d'être
|
|
89
|
+
haché — n'importe quel projet consommateur pouvait accepter `"aaaaaaaa"` ou
|
|
90
|
+
`"12345678"` comme nouveau mot de passe. `isStrongPassword` comble ce trou,
|
|
91
|
+
sans imposer de message d'erreur ni de langue (chaque app garde la main sur
|
|
92
|
+
son propre texte) :
|
|
93
|
+
|
|
94
|
+
```js
|
|
95
|
+
const { isStrongPassword } = require('@astratra/security');
|
|
96
|
+
|
|
97
|
+
if (!isStrongPassword(nouveauMotDePasse)) {
|
|
98
|
+
return res.status(400).json({ message: 'Mot de passe trop faible.' });
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
8 caractères minimum + majuscule + minuscule + chiffre + caractère spécial,
|
|
103
|
+
toutes exigences activées par défaut et individuellement désactivables :
|
|
104
|
+
|
|
105
|
+
```js
|
|
106
|
+
isStrongPassword(candidat, { minLength: 12, requireSpecial: false });
|
|
107
|
+
```
|
|
108
|
+
|
|
85
109
|
## Auth JWT + RBAC
|
|
86
110
|
|
|
87
111
|
```js
|
|
@@ -244,6 +268,30 @@ dans `req.path`, `req.query` et `req.body`. Elle ne remplace pas la
|
|
|
244
268
|
validation des entrées, les requêtes paramétrées, une CSP, la sanitation
|
|
245
269
|
adaptée au contexte, ni un WAF/reverse proxy réseau.
|
|
246
270
|
|
|
271
|
+
## Anti-injection Mongo (opérateurs `$`/`.`)
|
|
272
|
+
|
|
273
|
+
```js
|
|
274
|
+
const { createMongoSanitizeMiddleware } = require('@astratra/security');
|
|
275
|
+
app.use(createMongoSanitizeMiddleware());
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
Retire de `req.body`/`req.query`/`req.params` toute clé qui commence par
|
|
279
|
+
`$` ou contient un `.` — les opérateurs Mongo (`$gt`, `$ne`, `$where`...) et
|
|
280
|
+
les chemins imbriqués. Trouvé sur un projet consommateur réel : une route
|
|
281
|
+
passait `req.query.date` tel quel dans un filtre Mongoose ; comme le
|
|
282
|
+
parseur `qs` d'Express transforme `?date[$gt]=` en objet imbriqué plutôt
|
|
283
|
+
qu'en chaîne, ce paramètre non typé devenait un opérateur Mongo choisi par
|
|
284
|
+
l'appelant. Aucune requête légitime n'envoie une clé JSON littéralement
|
|
285
|
+
préfixée par `$` ou contenant un point — sans risque de faux positif sur un
|
|
286
|
+
usage normal.
|
|
287
|
+
|
|
288
|
+
Mute les objets en place plutôt que de réassigner `req.query` (getter
|
|
289
|
+
seul sur certaines configurations Express/routeur — une réassignation y
|
|
290
|
+
échouerait silencieusement ou lèverait selon la version).
|
|
291
|
+
|
|
292
|
+
Monté par défaut, sans configuration, par `createSaasApp()` (voir
|
|
293
|
+
`@astratra/saas-kit`) — pas besoin d'y penser route par route.
|
|
294
|
+
|
|
247
295
|
## CSP (Content Security Policy)
|
|
248
296
|
|
|
249
297
|
```js
|
package/package.json
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -102,6 +102,39 @@ export function hashPassword(password: string, options?: PasswordHashOptions): P
|
|
|
102
102
|
/** Verifies a password against a hash from hashPassword(). Constant-time; returns false (never throws) for a wrong password or a malformed/foreign hash. */
|
|
103
103
|
export function verifyPasswordHash(password: string, hash: string): Promise<boolean>;
|
|
104
104
|
|
|
105
|
+
export interface PasswordStrengthOptions {
|
|
106
|
+
/** Minimum length. Defaults to 8. */
|
|
107
|
+
minLength?: number;
|
|
108
|
+
/** Require at least one A-Z character. Defaults to true. */
|
|
109
|
+
requireUppercase?: boolean;
|
|
110
|
+
/** Require at least one a-z character. Defaults to true. */
|
|
111
|
+
requireLowercase?: boolean;
|
|
112
|
+
/** Require at least one 0-9 character. Defaults to true. */
|
|
113
|
+
requireDigit?: boolean;
|
|
114
|
+
/** Require at least one non-alphanumeric character. Defaults to true. */
|
|
115
|
+
requireSpecial?: boolean;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Checks password strength (length + character categories) — a policy Astratra never enforced before, left entirely to each consumer app. */
|
|
119
|
+
export function isStrongPassword(password: string, options?: PasswordStrengthOptions): boolean;
|
|
120
|
+
export const DEFAULT_PASSWORD_MIN_LENGTH: number;
|
|
121
|
+
|
|
122
|
+
export interface MongoSanitizeOptions {
|
|
123
|
+
/** Which request properties to clean. Defaults to ['body', 'query', 'params']. */
|
|
124
|
+
targets?: Array<'body' | 'query' | 'params'>;
|
|
125
|
+
/** If set, a stripped key is kept under this renamed key instead of being dropped silently — useful for logging what was blocked. */
|
|
126
|
+
replaceWith?: string;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Strips `$`-prefixed and dotted keys (Mongo operator injection, e.g.
|
|
131
|
+
* `?date[$gt]=` via Express's bracket-notation query parsing) from
|
|
132
|
+
* req.body/req.query/req.params before a route can pass them into a
|
|
133
|
+
* database filter. Mutates in place — never reassigns req.query, which is
|
|
134
|
+
* getter-only on some Express/router setups.
|
|
135
|
+
*/
|
|
136
|
+
export function createMongoSanitizeMiddleware(options?: MongoSanitizeOptions): RequestHandler;
|
|
137
|
+
|
|
105
138
|
export interface FieldCipherOptions {
|
|
106
139
|
/** A 32-byte AES-256 key, as a Buffer or a base64/hex-encoded string. */
|
|
107
140
|
key: Buffer | string;
|
package/src/index.js
CHANGED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
function isPlainObject(value) {
|
|
2
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
// Mutates in place rather than reassigning req.body/req.query/req.params —
|
|
6
|
+
// req.query in particular is a getter-only property on some Express/router
|
|
7
|
+
// setups, so `req.query = clean` silently breaks in ways that are easy to
|
|
8
|
+
// miss in dev and only surface under a specific framework version.
|
|
9
|
+
function stripDangerousKeys(value, replaceWith) {
|
|
10
|
+
if (Array.isArray(value)) {
|
|
11
|
+
value.forEach((item) => stripDangerousKeys(item, replaceWith));
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
if (!isPlainObject(value)) return value;
|
|
15
|
+
|
|
16
|
+
for (const key of Object.keys(value)) {
|
|
17
|
+
// `$`-prefixed keys are Mongo query operators ($gt, $where, $ne...);
|
|
18
|
+
// dotted keys reach into nested/array fields ("services.0.date"). Either
|
|
19
|
+
// one, if it survives from req.query/req.body into a driver call like
|
|
20
|
+
// Model.find({ date }), turns a simple equality filter the app wrote
|
|
21
|
+
// into an attacker-chosen query — found via a real consumer route that
|
|
22
|
+
// passed `date` from req.query straight into a Mongoose filter, letting
|
|
23
|
+
// `?date[$gt]=` (Express's default `qs` parser turns bracket notation
|
|
24
|
+
// into a nested object) return every document instead of one day's.
|
|
25
|
+
if (key.startsWith('$') || key.includes('.')) {
|
|
26
|
+
const original = value[key];
|
|
27
|
+
delete value[key];
|
|
28
|
+
if (replaceWith !== undefined) value[replaceWith] = original;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
stripDangerousKeys(value[key], replaceWith);
|
|
32
|
+
}
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const DEFAULT_TARGETS = ['body', 'query', 'params'];
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Strips Mongo operator injection out of req.body/req.query/req.params
|
|
40
|
+
* before it reaches a database call — see stripDangerousKeys() for the bug
|
|
41
|
+
* this closes. Safe as a blanket default: no legitimate REST client sends a
|
|
42
|
+
* literal `$`-prefixed or dotted JSON key, so there's no plausible request
|
|
43
|
+
* this rejects that a normal client would ever send.
|
|
44
|
+
*
|
|
45
|
+
* createMongoSanitizeMiddleware({ replaceWith: '_blocked' }) keeps the
|
|
46
|
+
* offending value under a renamed key instead of dropping it silently, if a
|
|
47
|
+
* consumer wants to log/inspect what was stripped.
|
|
48
|
+
*/
|
|
49
|
+
const createMongoSanitizeMiddleware = (options = {}) => {
|
|
50
|
+
const targets = options.targets || DEFAULT_TARGETS;
|
|
51
|
+
const replaceWith = options.replaceWith;
|
|
52
|
+
|
|
53
|
+
return (req, res, next) => {
|
|
54
|
+
for (const target of targets) {
|
|
55
|
+
if (req[target] && typeof req[target] === 'object') {
|
|
56
|
+
stripDangerousKeys(req[target], replaceWith);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return next();
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
module.exports = { createMongoSanitizeMiddleware };
|
package/src/passwordHashing.js
CHANGED
|
@@ -85,7 +85,40 @@ async function verifyPasswordHash(password, hash) {
|
|
|
85
85
|
return crypto.timingSafeEqual(derivedKey, expectedKey);
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
const DEFAULT_MIN_LENGTH = 8;
|
|
89
|
+
const REGEX_UPPERCASE = /[A-Z]/;
|
|
90
|
+
const REGEX_LOWERCASE = /[a-z]/;
|
|
91
|
+
const REGEX_DIGIT = /\d/;
|
|
92
|
+
const REGEX_SPECIAL = /[^A-Za-z0-9]/;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Astratra hashed passwords (above) but never judged whether one was worth
|
|
96
|
+
* hashing in the first place — every consumer app was free to accept
|
|
97
|
+
* "aaaaaaaa" or "12345678" as a new password. Found by a real consumer app
|
|
98
|
+
* that had to hand-roll this check itself, with no way to share it with its
|
|
99
|
+
* other Astratra-based projects.
|
|
100
|
+
*
|
|
101
|
+
* All four categories are required by default (length, uppercase, lowercase,
|
|
102
|
+
* digit, special character) — each individually toggleable for a consumer
|
|
103
|
+
* with different requirements.
|
|
104
|
+
*
|
|
105
|
+
* const ok = isStrongPassword(candidate);
|
|
106
|
+
* const relaxed = isStrongPassword(candidate, { requireSpecial: false, minLength: 10 });
|
|
107
|
+
*/
|
|
108
|
+
function isStrongPassword(password, options = {}) {
|
|
109
|
+
if (typeof password !== 'string') return false;
|
|
110
|
+
const minLength = options.minLength || DEFAULT_MIN_LENGTH;
|
|
111
|
+
if (password.length < minLength) return false;
|
|
112
|
+
if (options.requireUppercase !== false && !REGEX_UPPERCASE.test(password)) return false;
|
|
113
|
+
if (options.requireLowercase !== false && !REGEX_LOWERCASE.test(password)) return false;
|
|
114
|
+
if (options.requireDigit !== false && !REGEX_DIGIT.test(password)) return false;
|
|
115
|
+
if (options.requireSpecial !== false && !REGEX_SPECIAL.test(password)) return false;
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
|
|
88
119
|
module.exports = {
|
|
89
120
|
hashPassword,
|
|
90
|
-
verifyPasswordHash
|
|
121
|
+
verifyPasswordHash,
|
|
122
|
+
isStrongPassword,
|
|
123
|
+
DEFAULT_PASSWORD_MIN_LENGTH: DEFAULT_MIN_LENGTH
|
|
91
124
|
};
|