@astratra/security 1.4.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 +63 -3
- package/package.json +1 -1
- package/src/index.d.ts +40 -0
- package/src/index.js +1 -0
- package/src/jwtAuth.js +39 -5
- 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
|
|
@@ -103,6 +127,18 @@ app.delete('/api/projects/:id', authorizeRoles('owner', 'admin'), handler);
|
|
|
103
127
|
Par défaut, le middleware limite la vérification à `HS256`. Si ton application
|
|
104
128
|
utilise un autre algorithme, configure explicitement `algorithms`.
|
|
105
129
|
|
|
130
|
+
**Session par cookie sans `cookieParserMiddleware()` monté en amont** :
|
|
131
|
+
`createAuthMiddleware` a besoin de `req.cookies` pour lire un cookie de
|
|
132
|
+
session. Si aucun token n'est trouvé (ni cookie, ni header `Authorization`)
|
|
133
|
+
**et** que `req.cookies` est `undefined` — c'est-à-dire que
|
|
134
|
+
`cookieParserMiddleware()` (section suivante) n'a jamais tourné — le
|
|
135
|
+
middleware ne renvoie pas un 401 silencieux : il transmet une
|
|
136
|
+
`AuthConfigurationError` à `next(error)`, pour distinguer une vraie
|
|
137
|
+
absence de session d'un pipeline mal monté. Un routeur monté séparément de
|
|
138
|
+
`createSaasApp()` (au lieu de passer par `options.extendRoutes`) est le cas
|
|
139
|
+
le plus courant où ça arrive — voir
|
|
140
|
+
[`docs/guides/custom-routes-wiring.md`](../../docs/guides/custom-routes-wiring.md).
|
|
141
|
+
|
|
106
142
|
## Sessions cookie HttpOnly + CSRF
|
|
107
143
|
|
|
108
144
|
```js
|
|
@@ -232,6 +268,30 @@ dans `req.path`, `req.query` et `req.body`. Elle ne remplace pas la
|
|
|
232
268
|
validation des entrées, les requêtes paramétrées, une CSP, la sanitation
|
|
233
269
|
adaptée au contexte, ni un WAF/reverse proxy réseau.
|
|
234
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
|
+
|
|
235
295
|
## CSP (Content Security Policy)
|
|
236
296
|
|
|
237
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;
|
|
@@ -141,6 +174,13 @@ export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
|
|
|
141
174
|
export function createAuthMiddleware<TDecoded = Record<string, unknown>>(options: AuthMiddlewareOptions<TDecoded>): RequestHandler;
|
|
142
175
|
export function authorizeRoles(...roles: string[]): RequestHandler;
|
|
143
176
|
|
|
177
|
+
/**
|
|
178
|
+
* Thrown by the default token extractor — and passed to `next(error)`,
|
|
179
|
+
* never swallowed into a 401 — when `req.cookies` is `undefined` (no
|
|
180
|
+
* cookie parser mounted) and no token was found by any other means either.
|
|
181
|
+
*/
|
|
182
|
+
export class AuthConfigurationError extends Error {}
|
|
183
|
+
|
|
144
184
|
export interface RevocationStore {
|
|
145
185
|
revoke(jti: string, expiresAt: number): Awaitable<void>;
|
|
146
186
|
isRevoked(jti?: string): Awaitable<boolean>;
|
package/src/index.js
CHANGED
package/src/jwtAuth.js
CHANGED
|
@@ -13,16 +13,46 @@ const DEFAULT_FORBIDDEN = {
|
|
|
13
13
|
|
|
14
14
|
const DEFAULT_ALGORITHMS = ['HS256'];
|
|
15
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Thrown by the default token extractor when `req.cookies` is `undefined` —
|
|
18
|
+
* meaning `cookieParserMiddleware()` was never mounted ahead of this
|
|
19
|
+
* middleware. That misconfiguration must never be swallowed into a plain
|
|
20
|
+
* 401 (indistinguishable from "no valid session"): it is a wiring bug, not
|
|
21
|
+
* an authentication failure, and otherwise stays silent until someone
|
|
22
|
+
* traces a session that never sticks. See docs/guides/custom-routes-wiring.md.
|
|
23
|
+
*/
|
|
24
|
+
class AuthConfigurationError extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'AuthConfigurationError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
16
31
|
const defaultExtractToken = (req) => {
|
|
17
|
-
const cookies = req.cookies
|
|
18
|
-
|
|
19
|
-
|
|
32
|
+
const cookies = req.cookies;
|
|
33
|
+
if (cookies !== undefined) {
|
|
34
|
+
const cookieToken = cookies[DEFAULT_SESSION_COOKIE_NAME] || cookies.token;
|
|
35
|
+
if (cookieToken) return cookieToken;
|
|
36
|
+
}
|
|
20
37
|
|
|
21
38
|
const authorization = req.headers && req.headers.authorization;
|
|
22
39
|
if (authorization && authorization.startsWith('Bearer ')) {
|
|
23
40
|
return authorization.slice('Bearer '.length);
|
|
24
41
|
}
|
|
25
42
|
|
|
43
|
+
// Only now, having found no token by any means, does an unparsed
|
|
44
|
+
// req.cookies become suspicious rather than merely "no cookie sent" —
|
|
45
|
+
// a mounted parser always leaves at least `{}` behind (see cookies.js),
|
|
46
|
+
// so `undefined` here can only mean the middleware never ran.
|
|
47
|
+
if (cookies === undefined) {
|
|
48
|
+
throw new AuthConfigurationError(
|
|
49
|
+
'createAuthMiddleware: req.cookies is undefined. Mount cookieParserMiddleware() ' +
|
|
50
|
+
'(from @astratra/security) before this middleware so cookie-based sessions can be read — ' +
|
|
51
|
+
'see the "Cookies" section of the @astratra/security README, or pass a custom ' +
|
|
52
|
+
'options.extractToken if this app never authenticates via cookie.'
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
26
56
|
return null;
|
|
27
57
|
};
|
|
28
58
|
|
|
@@ -90,7 +120,10 @@ const createAuthMiddleware = (options = {}) => {
|
|
|
90
120
|
|
|
91
121
|
req.user = decoded;
|
|
92
122
|
return next();
|
|
93
|
-
} catch (
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof AuthConfigurationError) {
|
|
125
|
+
return next(error);
|
|
126
|
+
}
|
|
94
127
|
return res.status(401).json(unauthorizedMessage);
|
|
95
128
|
}
|
|
96
129
|
};
|
|
@@ -106,5 +139,6 @@ const authorizeRoles = (...allowedRoles) => (req, res, next) => {
|
|
|
106
139
|
|
|
107
140
|
module.exports = {
|
|
108
141
|
createAuthMiddleware,
|
|
109
|
-
authorizeRoles
|
|
142
|
+
authorizeRoles,
|
|
143
|
+
AuthConfigurationError
|
|
110
144
|
};
|
|
@@ -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
|
};
|