@astratra/security 1.2.0 → 1.4.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 +136 -3
- package/package.json +1 -1
- package/src/auditLogger.js +59 -0
- package/src/cors.js +56 -0
- package/src/encryption.js +80 -0
- package/src/index.d.ts +109 -0
- package/src/index.js +5 -0
- package/src/passwordHashing.js +91 -0
- package/src/securityHeaders.js +49 -0
- package/src/webauthn.js +64 -0
package/README.md
CHANGED
|
@@ -1,14 +1,87 @@
|
|
|
1
1
|
# @astratra/security
|
|
2
2
|
|
|
3
3
|
Primitives de sécurité applicative pour l'authentification, l'autorisation,
|
|
4
|
-
le rate limiting, une CSP configurable,
|
|
5
|
-
WebAuthn/passkeys — génériques et découplées de toute
|
|
6
|
-
ou liste de rôles fixe. Dépend de `@astratra/core`.
|
|
4
|
+
le CORS, le chiffrement de champ, le rate limiting, une CSP configurable,
|
|
5
|
+
un WAF heuristique et WebAuthn/passkeys — génériques et découplées de toute
|
|
6
|
+
base de données, ORM ou liste de rôles fixe. Dépend de `@astratra/core`.
|
|
7
7
|
|
|
8
8
|
Partout où un vrai projet a besoin de persistance (révocation de session,
|
|
9
9
|
stockage de credentials WebAuthn, alerte de brute-force), c'est un
|
|
10
10
|
callback/adapter injecté, jamais un appel base de données codé en dur.
|
|
11
11
|
|
|
12
|
+
## Chiffrement de champ (au repos)
|
|
13
|
+
|
|
14
|
+
Astratra ne s'intercale jamais entre ton app et ta base de données — rien
|
|
15
|
+
en amont ne chiffre tes données à ta place. `createFieldCipher` fournit une
|
|
16
|
+
primitive AES-256-GCM authentifiée (une donnée altérée ou une mauvaise clé
|
|
17
|
+
échoue au déchiffrement plutôt que de retourner du charabia silencieusement)
|
|
18
|
+
pour chiffrer un champ sensible avant de l'écrire dans n'importe quel store :
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
const { createFieldCipher, generateFieldEncryptionKey } = require('@astratra/security');
|
|
22
|
+
|
|
23
|
+
// Une fois, à la mise en place — garde la clé en secret (variable d'env),
|
|
24
|
+
// jamais dans le dépôt. La faire tourner rend les anciennes valeurs
|
|
25
|
+
// indéchiffrables : prévois un plan de ré-encryption si tu veux la changer.
|
|
26
|
+
console.log(generateFieldEncryptionKey());
|
|
27
|
+
|
|
28
|
+
const cipher = createFieldCipher({ key: process.env.FIELD_ENCRYPTION_KEY });
|
|
29
|
+
const stored = cipher.encrypt('4242-4242-4242-4242'); // string unique, safe pour n'importe quel champ/colonne
|
|
30
|
+
const plain = cipher.decrypt(stored);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## CORS
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
const { createCorsMiddleware } = require('@astratra/security');
|
|
37
|
+
|
|
38
|
+
// À monter EN PREMIER, avant tout autre middleware — les en-têtes CORS,
|
|
39
|
+
// y compris sur la réponse de preflight OPTIONS, doivent être posés avant
|
|
40
|
+
// qu'un autre handler ne puisse court-circuiter la requête.
|
|
41
|
+
app.use(createCorsMiddleware({
|
|
42
|
+
allowedOrigins: (process.env.CORS_ORIGIN || '').split(',').filter(Boolean)
|
|
43
|
+
}));
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Astratra n'impose aucune politique CORS fixe — les origines autorisées sont
|
|
47
|
+
spécifiques à chaque projet. `@astratra/saas-kit` expose cette primitive via
|
|
48
|
+
`options.cors`, montée automatiquement au bon endroit — voir son README.
|
|
49
|
+
|
|
50
|
+
Origines `http://127.0.0.1`/`http://localhost` (tout port) autorisées par
|
|
51
|
+
défaut hors `NODE_ENV=production`, désactivable via `allowDevOrigins: false`.
|
|
52
|
+
`credentials: false` retire `Access-Control-Allow-Credentials` si tu n'as
|
|
53
|
+
pas besoin des cookies cross-origin.
|
|
54
|
+
|
|
55
|
+
## Hachage de mot de passe
|
|
56
|
+
|
|
57
|
+
`verifyPassword` reste un callback fourni par l'app consommatrice —
|
|
58
|
+
Astratra ne décide toujours pas comment tu authentifies un utilisateur.
|
|
59
|
+
Mais avant, aucune primitive n'existait pour le hachage lui-même : rien
|
|
60
|
+
n'empêchait un `===` en clair ou un MD5 sans sel. `hashPassword`/
|
|
61
|
+
`verifyPasswordHash` utilisent scrypt (natif à Node, aucune dépendance
|
|
62
|
+
bcrypt/argon2 à ajouter), avec sel aléatoire et comparaison à temps
|
|
63
|
+
constant :
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
const { hashPassword, verifyPasswordHash } = require('@astratra/security');
|
|
67
|
+
|
|
68
|
+
// à l'inscription
|
|
69
|
+
const passwordHash = await hashPassword(rawPassword);
|
|
70
|
+
await usersStore.create({ email, passwordHash });
|
|
71
|
+
|
|
72
|
+
// dans verifyPassword passé à createSaasApp
|
|
73
|
+
const app = createSaasApp({
|
|
74
|
+
// ...
|
|
75
|
+
verifyPassword: async (user, password) => verifyPasswordHash(password, user.passwordHash)
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Le sel et le facteur de coût scrypt voyagent avec la chaîne retournée — pas
|
|
80
|
+
besoin de colonnes séparées. `verifyPasswordHash` ne lève jamais d'exception
|
|
81
|
+
sur une entrée invalide (mot de passe erroné, hash étranger ou corrompu) :
|
|
82
|
+
elle retourne toujours `false`, donc un appelant peut traiter le résultat
|
|
83
|
+
comme un booléen sans `try/catch`.
|
|
84
|
+
|
|
12
85
|
## Auth JWT + RBAC
|
|
13
86
|
|
|
14
87
|
```js
|
|
@@ -192,6 +265,52 @@ CSP statique en dev casse le websocket HMR de Vite). Voir
|
|
|
192
265
|
`examples/dashboard-ui/vite.config.js` pour un exemple qui n'injecte la
|
|
193
266
|
balise que sur `vite build`.
|
|
194
267
|
|
|
268
|
+
## En-têtes de sécurité (au-delà de CSP)
|
|
269
|
+
|
|
270
|
+
```js
|
|
271
|
+
const { createSecurityHeadersMiddleware } = require('@astratra/security');
|
|
272
|
+
app.use(createSecurityHeadersMiddleware());
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
Complète CSP avec le reste du set standard, chacun avec une valeur par
|
|
276
|
+
défaut sûre pour n'importe quel projet — contrairement à CORS, rien ici ne
|
|
277
|
+
demande une décision spécifique au projet, donc `@astratra/saas-kit` le
|
|
278
|
+
monte sans condition, comme CSP :
|
|
279
|
+
|
|
280
|
+
- `X-Frame-Options: DENY` — anti clickjacking
|
|
281
|
+
- `X-Content-Type-Options: nosniff` — anti détection de type MIME
|
|
282
|
+
- `Referrer-Policy: strict-origin-when-cross-origin` — limite la fuite d'URL vers des origines tierces
|
|
283
|
+
- `Permissions-Policy` — refuse géoloc/caméra/micro/paiement par défaut
|
|
284
|
+
- `Strict-Transport-Security` (HSTS) — actif automatiquement seulement si
|
|
285
|
+
`NODE_ENV=production` (le forcer en dev casse le HTTP local)
|
|
286
|
+
|
|
287
|
+
Chaque en-tête est désactivable/personnalisable individuellement
|
|
288
|
+
(`frameOptions: false`, `hsts: { maxAge, includeSubDomains }`, etc.).
|
|
289
|
+
|
|
290
|
+
## Journal d'événements de sécurité
|
|
291
|
+
|
|
292
|
+
```js
|
|
293
|
+
const { createSecurityAuditLogger } = require('@astratra/security');
|
|
294
|
+
app.use(createSecurityAuditLogger());
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
Avant, aucune des autres couches (rejet CSRF, blocage WAF, rate limit, échec
|
|
298
|
+
JWT) ne journalisait quoi que ce soit — une tentative d'attaque restait
|
|
299
|
+
invisible tant qu'elle n'avait pas réussi. Plutôt que d'accrocher un log à
|
|
300
|
+
chaque middleware séparément, celui-ci observe la réponse : toute requête
|
|
301
|
+
qui se termine en `401`/`403`/`429` (configurable via `statusCodes`) produit
|
|
302
|
+
une ligne structurée, peu importe quelle couche l'a produite.
|
|
303
|
+
|
|
304
|
+
```js
|
|
305
|
+
app.use(createSecurityAuditLogger({
|
|
306
|
+
log: (message, event) => myLogger.warn(message, event), // par défaut : @astratra/core createLogger
|
|
307
|
+
statusCodes: [401, 403, 429]
|
|
308
|
+
}));
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
`@astratra/saas-kit` le monte par défaut ; `options.securityAudit: false`
|
|
312
|
+
le désactive.
|
|
313
|
+
|
|
195
314
|
## WebAuthn / passkeys
|
|
196
315
|
|
|
197
316
|
```js
|
|
@@ -212,6 +331,20 @@ récupération. Aucun Mongoose, aucun rôle fixe autorisé à enregistrer une cl
|
|
|
212
331
|
présenter WebAuthn comme un argument de sécurité fort, prévois une revue de
|
|
213
332
|
sécurité externe sur l'intégration complète.
|
|
214
333
|
|
|
334
|
+
Pour développer/tester sans écrire de store tout de suite,
|
|
335
|
+
`createMemoryWebauthnStore()` fournit une implémentation en mémoire
|
|
336
|
+
conforme au contrat complet — credentials perdues au redémarrage, à
|
|
337
|
+
remplacer par une vraie base avant la prod :
|
|
338
|
+
|
|
339
|
+
```js
|
|
340
|
+
const { createWebauthnService, createMemoryWebauthnStore } = require('@astratra/security');
|
|
341
|
+
|
|
342
|
+
const webauthn = createWebauthnService(createMemoryWebauthnStore(), {
|
|
343
|
+
rpName: 'Mon App',
|
|
344
|
+
recoveryCodeSecret: process.env.RECOVERY_CODE_SECRET
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
215
348
|
## Tests
|
|
216
349
|
|
|
217
350
|
```bash
|
package/package.json
CHANGED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const { createLogger } = require('@astratra/core');
|
|
2
|
+
|
|
3
|
+
const DEFAULT_STATUS_CODES = [401, 403, 429];
|
|
4
|
+
|
|
5
|
+
const clientIp = (req) => {
|
|
6
|
+
const forwarded = req.headers && (req.headers['x-forwarded-for'] || req.headers['X-Forwarded-For']);
|
|
7
|
+
if (forwarded) return String(forwarded).split(',')[0].trim();
|
|
8
|
+
return (req.connection && req.connection.remoteAddress) || req.ip || undefined;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A security event trail — none of the other layers (CSRF rejection, WAF
|
|
13
|
+
* block, rate limit, failed JWT auth) logged anything anywhere by default,
|
|
14
|
+
* so an attack attempt was invisible until it succeeded. This observes the
|
|
15
|
+
* response instead of hooking into each middleware individually: any
|
|
16
|
+
* request that ends in one of statusCodes (401/403/429 by default) gets a
|
|
17
|
+
* structured log line, regardless of which layer produced it.
|
|
18
|
+
*
|
|
19
|
+
* Mount early — as early as possible in the stack, and definitely before
|
|
20
|
+
* any router that mounts on a sub-path (e.g. app.use('/users', ...)).
|
|
21
|
+
* Express strips the mount prefix from req.url while a request is inside
|
|
22
|
+
* such a router and only restores it once that router's handling fully
|
|
23
|
+
* unwinds; a response that ends WITHOUT calling next() (an auth rejection,
|
|
24
|
+
* for instance) can fire 'finish' while still inside that stripped
|
|
25
|
+
* context. Reading req.path/req.originalUrl lazily inside the 'finish'
|
|
26
|
+
* listener would then see the truncated path. Capturing method/path/ip
|
|
27
|
+
* up front, before next(), sidesteps that entirely.
|
|
28
|
+
*/
|
|
29
|
+
const createSecurityAuditLogger = (options = {}) => {
|
|
30
|
+
const statusCodes = new Set(options.statusCodes || DEFAULT_STATUS_CODES);
|
|
31
|
+
const log = options.log || createLogger('astratra-security-audit').warn;
|
|
32
|
+
|
|
33
|
+
return (req, res, next) => {
|
|
34
|
+
const method = req.method;
|
|
35
|
+
const path = req.originalUrl || req.path || req.url;
|
|
36
|
+
const ip = clientIp(req);
|
|
37
|
+
// requestIdMiddleware (@astratra/core) sets req.requestId, not req.id —
|
|
38
|
+
// accept either so this also works standalone, ahead of/without it.
|
|
39
|
+
const requestId = req.requestId || req.id;
|
|
40
|
+
|
|
41
|
+
res.on('finish', () => {
|
|
42
|
+
if (!statusCodes.has(res.statusCode)) return;
|
|
43
|
+
|
|
44
|
+
log('security_event', {
|
|
45
|
+
status: res.statusCode,
|
|
46
|
+
method,
|
|
47
|
+
path,
|
|
48
|
+
ip,
|
|
49
|
+
requestId,
|
|
50
|
+
timestamp: new Date().toISOString()
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
next();
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
module.exports = {
|
|
58
|
+
createSecurityAuditLogger
|
|
59
|
+
};
|
package/src/cors.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const DEFAULT_ALLOWED_HEADERS = 'content-type, authorization, x-csrf-token';
|
|
2
|
+
const DEFAULT_ALLOWED_METHODS = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
|
|
3
|
+
|
|
4
|
+
const isAllowedDevOrigin = (origin) => {
|
|
5
|
+
if (process.env.NODE_ENV === 'production') return false;
|
|
6
|
+
try {
|
|
7
|
+
const url = new URL(origin);
|
|
8
|
+
return ['127.0.0.1', 'localhost'].includes(url.hostname);
|
|
9
|
+
} catch {
|
|
10
|
+
return false;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* CORS middleware. Astratra intentionally has no fixed opinion on which
|
|
16
|
+
* origins to allow — that's project-specific — but leaving CORS entirely
|
|
17
|
+
* unaddressed pushed every consumer (including create-astratra-app's own
|
|
18
|
+
* generated template) to hand-roll the same ~15 lines. This promotes that
|
|
19
|
+
* proven logic into a shared, configurable primitive, matching the pattern
|
|
20
|
+
* already used for createWafMiddleware / createCspMiddleware.
|
|
21
|
+
*
|
|
22
|
+
* Passing `options.cors` to createSaasApp mounts this as the FIRST
|
|
23
|
+
* middleware, ahead of everything else — CORS headers, including on the
|
|
24
|
+
* preflight OPTIONS response, must be set before any other handler can
|
|
25
|
+
* short-circuit the request. Omit `options.cors` and nothing changes.
|
|
26
|
+
*/
|
|
27
|
+
const createCorsMiddleware = (options = {}) => {
|
|
28
|
+
const allowed = new Set(options.allowedOrigins || []);
|
|
29
|
+
const allowDevOrigins = options.allowDevOrigins !== false;
|
|
30
|
+
const allowCredentials = options.credentials !== false;
|
|
31
|
+
const allowedHeaders = options.allowedHeaders || DEFAULT_ALLOWED_HEADERS;
|
|
32
|
+
const allowedMethods = options.allowedMethods || DEFAULT_ALLOWED_METHODS;
|
|
33
|
+
|
|
34
|
+
return (req, res, next) => {
|
|
35
|
+
const origin = req.headers && (req.headers.origin || req.headers.Origin);
|
|
36
|
+
if (origin && (allowed.has(origin) || (allowDevOrigins && isAllowedDevOrigin(origin)))) {
|
|
37
|
+
res.setHeader('Access-Control-Allow-Origin', origin);
|
|
38
|
+
res.setHeader('Vary', 'Origin');
|
|
39
|
+
if (allowCredentials) {
|
|
40
|
+
res.setHeader('Access-Control-Allow-Credentials', 'true');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
res.setHeader('Access-Control-Allow-Headers', allowedHeaders);
|
|
44
|
+
res.setHeader('Access-Control-Allow-Methods', allowedMethods);
|
|
45
|
+
|
|
46
|
+
if (String(req.method || 'GET').toUpperCase() === 'OPTIONS') {
|
|
47
|
+
res.status(204).end();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
return next();
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
module.exports = {
|
|
55
|
+
createCorsMiddleware
|
|
56
|
+
};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
|
|
3
|
+
const ALGORITHM = 'aes-256-gcm';
|
|
4
|
+
const KEY_LENGTH = 32;
|
|
5
|
+
const IV_LENGTH = 12;
|
|
6
|
+
|
|
7
|
+
const normalizeKey = (key) => {
|
|
8
|
+
if (Buffer.isBuffer(key)) {
|
|
9
|
+
if (key.length !== KEY_LENGTH) {
|
|
10
|
+
throw new Error(`createFieldCipher requires a ${KEY_LENGTH}-byte key, got ${key.length} bytes.`);
|
|
11
|
+
}
|
|
12
|
+
return key;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
if (typeof key === 'string') {
|
|
16
|
+
const base64Decoded = Buffer.from(key, 'base64');
|
|
17
|
+
if (base64Decoded.length === KEY_LENGTH) return base64Decoded;
|
|
18
|
+
const hexDecoded = Buffer.from(key, 'hex');
|
|
19
|
+
if (hexDecoded.length === KEY_LENGTH) return hexDecoded;
|
|
20
|
+
throw new Error(`createFieldCipher requires a ${KEY_LENGTH}-byte key encoded as base64 or hex (got a string that decodes to neither length).`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
throw new Error('createFieldCipher requires options.key as a Buffer or a base64/hex string.');
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Field-level encryption for values you write to a store yourself —
|
|
28
|
+
* Astratra never touches your data on its way to a database, so nothing
|
|
29
|
+
* upstream of this can encrypt it for you. AES-256-GCM, authenticated
|
|
30
|
+
* (tamper-evident: a modified ciphertext or wrong key fails to decrypt
|
|
31
|
+
* rather than silently returning garbage).
|
|
32
|
+
*
|
|
33
|
+
* Generate a key once: crypto.randomBytes(32).toString('base64'), store it
|
|
34
|
+
* as a secret (env var), never in the repo. Rotating the key means old
|
|
35
|
+
* ciphertexts become undecryptable — plan a re-encryption path if you
|
|
36
|
+
* expect to rotate.
|
|
37
|
+
*
|
|
38
|
+
* const cipher = createFieldCipher({ key: process.env.FIELD_ENCRYPTION_KEY });
|
|
39
|
+
* const stored = cipher.encrypt('4242-4242-4242-4242'); // single string, safe for any column/field
|
|
40
|
+
* const plain = cipher.decrypt(stored);
|
|
41
|
+
*/
|
|
42
|
+
const createFieldCipher = (options = {}) => {
|
|
43
|
+
const key = normalizeKey(options.key);
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
encrypt(plaintext) {
|
|
47
|
+
if (plaintext === null || plaintext === undefined) {
|
|
48
|
+
throw new Error('createFieldCipher.encrypt requires a non-null value.');
|
|
49
|
+
}
|
|
50
|
+
const iv = crypto.randomBytes(IV_LENGTH);
|
|
51
|
+
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
|
52
|
+
const ciphertext = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()]);
|
|
53
|
+
const authTag = cipher.getAuthTag();
|
|
54
|
+
return [iv.toString('base64url'), authTag.toString('base64url'), ciphertext.toString('base64url')].join('.');
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
decrypt(payload) {
|
|
58
|
+
const parts = String(payload || '').split('.');
|
|
59
|
+
if (parts.length !== 3) {
|
|
60
|
+
throw new Error('createFieldCipher.decrypt received a malformed payload.');
|
|
61
|
+
}
|
|
62
|
+
const [ivPart, authTagPart, ciphertextPart] = parts;
|
|
63
|
+
const iv = Buffer.from(ivPart, 'base64url');
|
|
64
|
+
const authTag = Buffer.from(authTagPart, 'base64url');
|
|
65
|
+
const ciphertext = Buffer.from(ciphertextPart, 'base64url');
|
|
66
|
+
|
|
67
|
+
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
|
|
68
|
+
decipher.setAuthTag(authTag);
|
|
69
|
+
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
|
70
|
+
return plaintext.toString('utf8');
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const generateFieldEncryptionKey = () => crypto.randomBytes(KEY_LENGTH).toString('base64');
|
|
76
|
+
|
|
77
|
+
module.exports = {
|
|
78
|
+
createFieldCipher,
|
|
79
|
+
generateFieldEncryptionKey
|
|
80
|
+
};
|
package/src/index.d.ts
CHANGED
|
@@ -22,6 +22,108 @@ export type NextFunction = (error?: unknown) => unknown;
|
|
|
22
22
|
export type RequestHandler = (req: RequestLike, res: ResponseLike, next: NextFunction) => unknown;
|
|
23
23
|
export type Awaitable<T> = T | Promise<T>;
|
|
24
24
|
|
|
25
|
+
export interface CorsMiddlewareOptions {
|
|
26
|
+
/** Explicit list of allowed origins (exact match on the Origin header). */
|
|
27
|
+
allowedOrigins?: string[];
|
|
28
|
+
/** Allow http(s)://127.0.0.1|localhost:* outside NODE_ENV=production. Default true. */
|
|
29
|
+
allowDevOrigins?: boolean;
|
|
30
|
+
/** Sets Access-Control-Allow-Credentials: true. Default true (matches cookie-based sessions). */
|
|
31
|
+
credentials?: boolean;
|
|
32
|
+
allowedHeaders?: string;
|
|
33
|
+
allowedMethods?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Astratra has no fixed opinion on which origins to allow — that's
|
|
38
|
+
* project-specific — but leaves this primitive available rather than
|
|
39
|
+
* making every consumer hand-roll it. Mount first, ahead of every other
|
|
40
|
+
* middleware, so CORS headers apply to the preflight OPTIONS response too.
|
|
41
|
+
*/
|
|
42
|
+
export function createCorsMiddleware(options?: CorsMiddlewareOptions): RequestHandler;
|
|
43
|
+
|
|
44
|
+
export interface SecurityHeadersOptions {
|
|
45
|
+
/** X-Frame-Options value, or false to omit. Defaults to "DENY". */
|
|
46
|
+
frameOptions?: string | false;
|
|
47
|
+
/** Sets X-Content-Type-Options: nosniff. Defaults to true. */
|
|
48
|
+
contentTypeOptions?: boolean;
|
|
49
|
+
/** Referrer-Policy value, or false to omit. Defaults to "strict-origin-when-cross-origin". */
|
|
50
|
+
referrerPolicy?: string | false;
|
|
51
|
+
/** Permissions-Policy value, or false to omit. Defaults to a minimal deny-list (geolocation, camera, microphone, payment). */
|
|
52
|
+
permissionsPolicy?: string | false;
|
|
53
|
+
/** Strict-Transport-Security: true/false, or { maxAge, includeSubDomains } to customize. Defaults to true only when NODE_ENV=production (HSTS on plain HTTP dev breaks things). */
|
|
54
|
+
hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The standard header-hardening set beyond CSP: clickjacking (X-Frame-Options),
|
|
59
|
+
* MIME sniffing (X-Content-Type-Options), referrer leakage (Referrer-Policy),
|
|
60
|
+
* browser feature access (Permissions-Policy), and HTTP downgrade (HSTS).
|
|
61
|
+
* Every option has a safe universal default, so createSaasApp mounts this
|
|
62
|
+
* unconditionally.
|
|
63
|
+
*/
|
|
64
|
+
export function createSecurityHeadersMiddleware(options?: SecurityHeadersOptions): RequestHandler;
|
|
65
|
+
|
|
66
|
+
export interface SecurityEvent {
|
|
67
|
+
status: number;
|
|
68
|
+
method: string;
|
|
69
|
+
path: string;
|
|
70
|
+
ip: string | undefined;
|
|
71
|
+
requestId: string | undefined;
|
|
72
|
+
timestamp: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface SecurityAuditLoggerOptions {
|
|
76
|
+
/** Response status codes that trigger a log line. Defaults to [401, 403, 429]. */
|
|
77
|
+
statusCodes?: number[];
|
|
78
|
+
/** Custom sink, e.g. (message, event) => yourLogger.warn(message, event). Defaults to @astratra/core's createLogger('astratra-security-audit').warn. */
|
|
79
|
+
log?: (message: string, event: SecurityEvent) => void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Logs a structured event for any request whose response lands on one of
|
|
84
|
+
* statusCodes (401/403/429 by default) — auth failures, CSRF/WAF blocks,
|
|
85
|
+
* and rate limiting all end up here without each layer needing its own
|
|
86
|
+
* logging call, since this observes the response rather than the
|
|
87
|
+
* middleware that produced it.
|
|
88
|
+
*/
|
|
89
|
+
export function createSecurityAuditLogger(options?: SecurityAuditLoggerOptions): RequestHandler;
|
|
90
|
+
|
|
91
|
+
export interface PasswordHashOptions {
|
|
92
|
+
/** scrypt cost factor (N), must be a power of 2. Defaults to 16384. */
|
|
93
|
+
cost?: number;
|
|
94
|
+
/** scrypt block size (r). Defaults to 8. */
|
|
95
|
+
blockSize?: number;
|
|
96
|
+
/** scrypt parallelization (p). Defaults to 1. */
|
|
97
|
+
parallelization?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Hashes a password with scrypt (Node built-in, no bcrypt/argon2 dependency). The salt and cost factor travel with the returned string. */
|
|
101
|
+
export function hashPassword(password: string, options?: PasswordHashOptions): Promise<string>;
|
|
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
|
+
export function verifyPasswordHash(password: string, hash: string): Promise<boolean>;
|
|
104
|
+
|
|
105
|
+
export interface FieldCipherOptions {
|
|
106
|
+
/** A 32-byte AES-256 key, as a Buffer or a base64/hex-encoded string. */
|
|
107
|
+
key: Buffer | string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface FieldCipher {
|
|
111
|
+
/** Encrypts a value (AES-256-GCM) into a single opaque string, safe to store in any field/column. */
|
|
112
|
+
encrypt(plaintext: string | number): string;
|
|
113
|
+
/** Decrypts a value produced by encrypt(). Throws if the key is wrong or the payload was tampered with. */
|
|
114
|
+
decrypt(payload: string): string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Field-level encryption for values written to a store you control — Astratra
|
|
119
|
+
* doesn't sit between your app and your database, so nothing upstream
|
|
120
|
+
* encrypts data for you. Generate a key with generateFieldEncryptionKey()
|
|
121
|
+
* once and keep it as a secret; rotating it makes old ciphertexts
|
|
122
|
+
* undecryptable.
|
|
123
|
+
*/
|
|
124
|
+
export function createFieldCipher(options: FieldCipherOptions): FieldCipher;
|
|
125
|
+
export function generateFieldEncryptionKey(): string;
|
|
126
|
+
|
|
25
127
|
export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
|
|
26
128
|
secret: string;
|
|
27
129
|
legacySecret?: string;
|
|
@@ -227,3 +329,10 @@ export interface WebauthnService {
|
|
|
227
329
|
export function createWebauthnService(store: WebauthnStore, options?: WebauthnOptions): WebauthnService;
|
|
228
330
|
export function rpConfigForRequest(req: RequestLike, options?: WebauthnOptions): RpConfig;
|
|
229
331
|
export function hashRecoveryCode(code: string, secret: string): string;
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Reference in-memory WebauthnStore implementation. Fine for local dev and
|
|
335
|
+
* tests — credentials are lost on restart, so this is not a production
|
|
336
|
+
* credential store.
|
|
337
|
+
*/
|
|
338
|
+
export function createMemoryWebauthnStore(): WebauthnStore;
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
module.exports = {
|
|
2
|
+
...require('./cors'),
|
|
3
|
+
...require('./encryption'),
|
|
2
4
|
...require('./jwtAuth'),
|
|
5
|
+
...require('./passwordHashing'),
|
|
3
6
|
...require('./rateLimiters'),
|
|
7
|
+
...require('./securityHeaders'),
|
|
8
|
+
...require('./auditLogger'),
|
|
4
9
|
...require('./waf'),
|
|
5
10
|
...require('./webauthn'),
|
|
6
11
|
...require('./csp'),
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
const crypto = require('crypto');
|
|
2
|
+
const { promisify } = require('util');
|
|
3
|
+
|
|
4
|
+
const scrypt = promisify(crypto.scrypt);
|
|
5
|
+
|
|
6
|
+
const ALGORITHM = 'scrypt';
|
|
7
|
+
const DEFAULT_COST = 16384; // N — CPU/memory cost factor, must be a power of 2
|
|
8
|
+
const DEFAULT_BLOCK_SIZE = 8; // r
|
|
9
|
+
const DEFAULT_PARALLELIZATION = 1; // p
|
|
10
|
+
const SALT_LENGTH = 16;
|
|
11
|
+
const KEY_LENGTH = 64;
|
|
12
|
+
|
|
13
|
+
function scryptOptions(cost, blockSize, parallelization) {
|
|
14
|
+
// Node's default maxmem (32MB) caps N*r*128 — pass an explicit maxmem so a
|
|
15
|
+
// higher cost factor doesn't throw "Invalid options: N too large" for a
|
|
16
|
+
// caller that reasonably wants extra hardening.
|
|
17
|
+
return { N: cost, r: blockSize, p: parallelization, maxmem: 128 * cost * blockSize * 2 };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Password hashing Astratra never had — verifyPassword was always a
|
|
22
|
+
* callback the app supplies, and the framework offered no guidance on how
|
|
23
|
+
* to hash in the first place. scrypt is a Node built-in memory-hard KDF
|
|
24
|
+
* (no bcrypt/argon2 dependency to add), constant-time verified.
|
|
25
|
+
*
|
|
26
|
+
* const hash = await hashPassword('correct horse battery staple');
|
|
27
|
+
* // store `hash` — it already carries its own salt and cost factor
|
|
28
|
+
* const ok = await verifyPasswordHash('correct horse battery staple', hash);
|
|
29
|
+
*/
|
|
30
|
+
async function hashPassword(password, options = {}) {
|
|
31
|
+
if (typeof password !== 'string' || password.length === 0) {
|
|
32
|
+
throw new Error('hashPassword requires a non-empty string password.');
|
|
33
|
+
}
|
|
34
|
+
const cost = options.cost || DEFAULT_COST;
|
|
35
|
+
const blockSize = options.blockSize || DEFAULT_BLOCK_SIZE;
|
|
36
|
+
const parallelization = options.parallelization || DEFAULT_PARALLELIZATION;
|
|
37
|
+
|
|
38
|
+
const salt = crypto.randomBytes(SALT_LENGTH);
|
|
39
|
+
const derivedKey = await scrypt(password, salt, KEY_LENGTH, scryptOptions(cost, blockSize, parallelization));
|
|
40
|
+
|
|
41
|
+
return [
|
|
42
|
+
ALGORITHM,
|
|
43
|
+
cost,
|
|
44
|
+
blockSize,
|
|
45
|
+
parallelization,
|
|
46
|
+
salt.toString('base64url'),
|
|
47
|
+
derivedKey.toString('base64url')
|
|
48
|
+
].join('$');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Verifies a password against a hash produced by hashPassword(). Returns
|
|
53
|
+
* false for a wrong password AND for a malformed/foreign hash — never
|
|
54
|
+
* throws on bad input, so a caller can always treat a falsy result as
|
|
55
|
+
* "reject the login" without a try/catch.
|
|
56
|
+
*/
|
|
57
|
+
async function verifyPasswordHash(password, hash) {
|
|
58
|
+
if (typeof password !== 'string' || typeof hash !== 'string') return false;
|
|
59
|
+
|
|
60
|
+
const parts = hash.split('$');
|
|
61
|
+
if (parts.length !== 6 || parts[0] !== ALGORITHM) return false;
|
|
62
|
+
|
|
63
|
+
const [, costStr, blockSizeStr, parallelizationStr, saltB64, keyB64] = parts;
|
|
64
|
+
const cost = Number(costStr);
|
|
65
|
+
const blockSize = Number(blockSizeStr);
|
|
66
|
+
const parallelization = Number(parallelizationStr);
|
|
67
|
+
// Bounds match what hashPassword() would ever produce — a hash string
|
|
68
|
+
// claiming a wildly larger cost/key length is malformed (or adversarial),
|
|
69
|
+
// not a slower-but-valid hash, so reject before scrypt() allocates for it.
|
|
70
|
+
if (!Number.isFinite(cost) || cost <= 0 || cost > 1 << 20) return false;
|
|
71
|
+
if (!Number.isFinite(blockSize) || blockSize <= 0 || blockSize > 64) return false;
|
|
72
|
+
if (!Number.isFinite(parallelization) || parallelization <= 0 || parallelization > 16) return false;
|
|
73
|
+
|
|
74
|
+
let salt;
|
|
75
|
+
let expectedKey;
|
|
76
|
+
try {
|
|
77
|
+
salt = Buffer.from(saltB64, 'base64url');
|
|
78
|
+
expectedKey = Buffer.from(keyB64, 'base64url');
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
if (expectedKey.length === 0 || expectedKey.length > 256) return false;
|
|
83
|
+
|
|
84
|
+
const derivedKey = await scrypt(password, salt, expectedKey.length, scryptOptions(cost, blockSize, parallelization));
|
|
85
|
+
return crypto.timingSafeEqual(derivedKey, expectedKey);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
module.exports = {
|
|
89
|
+
hashPassword,
|
|
90
|
+
verifyPasswordHash
|
|
91
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
const DEFAULT_PERMISSIONS_POLICY = 'geolocation=(), camera=(), microphone=(), payment=()';
|
|
2
|
+
const DEFAULT_HSTS_MAX_AGE = 15552000; // 180 days
|
|
3
|
+
|
|
4
|
+
const isProduction = () => process.env.NODE_ENV === 'production';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The standard response-header hardening set beyond CSP (which
|
|
8
|
+
* createCspMiddleware already covers separately): clickjacking, MIME
|
|
9
|
+
* sniffing, referrer leakage, browser feature access, and HTTP downgrade.
|
|
10
|
+
* Every header here has a safe universal default — unlike CORS, nothing
|
|
11
|
+
* here needs a project-specific decision — so createSaasApp mounts this
|
|
12
|
+
* unconditionally, the same way it already does for CSP and the WAF.
|
|
13
|
+
*/
|
|
14
|
+
const createSecurityHeadersMiddleware = (options = {}) => {
|
|
15
|
+
const frameOptions = options.frameOptions === undefined ? 'DENY' : options.frameOptions;
|
|
16
|
+
const contentTypeOptions = options.contentTypeOptions !== false;
|
|
17
|
+
const referrerPolicy = options.referrerPolicy === undefined ? 'strict-origin-when-cross-origin' : options.referrerPolicy;
|
|
18
|
+
const permissionsPolicy = options.permissionsPolicy === undefined ? DEFAULT_PERMISSIONS_POLICY : options.permissionsPolicy;
|
|
19
|
+
const hsts = options.hsts === undefined ? isProduction() : options.hsts;
|
|
20
|
+
const hstsMaxAge = (hsts && typeof hsts === 'object' && hsts.maxAge) || DEFAULT_HSTS_MAX_AGE;
|
|
21
|
+
const hstsIncludeSubDomains = !(hsts && typeof hsts === 'object' && hsts.includeSubDomains === false);
|
|
22
|
+
|
|
23
|
+
return (req, res, next) => {
|
|
24
|
+
if (frameOptions) {
|
|
25
|
+
res.setHeader('X-Frame-Options', frameOptions);
|
|
26
|
+
}
|
|
27
|
+
if (contentTypeOptions) {
|
|
28
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
29
|
+
}
|
|
30
|
+
if (referrerPolicy) {
|
|
31
|
+
res.setHeader('Referrer-Policy', referrerPolicy);
|
|
32
|
+
}
|
|
33
|
+
if (permissionsPolicy) {
|
|
34
|
+
res.setHeader('Permissions-Policy', permissionsPolicy);
|
|
35
|
+
}
|
|
36
|
+
if (hsts) {
|
|
37
|
+
res.setHeader(
|
|
38
|
+
'Strict-Transport-Security',
|
|
39
|
+
`max-age=${hstsMaxAge}${hstsIncludeSubDomains ? '; includeSubDomains' : ''}`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
next();
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
module.exports = {
|
|
47
|
+
createSecurityHeadersMiddleware,
|
|
48
|
+
DEFAULT_PERMISSIONS_POLICY
|
|
49
|
+
};
|
package/src/webauthn.js
CHANGED
|
@@ -299,8 +299,72 @@ const createWebauthnService = (store, options = {}) => {
|
|
|
299
299
|
return service;
|
|
300
300
|
};
|
|
301
301
|
|
|
302
|
+
/**
|
|
303
|
+
* Reference in-memory implementation of the WebauthnStore contract required
|
|
304
|
+
* by createWebauthnService — matches every method assertStore() checks for,
|
|
305
|
+
* same pattern as createMemoryUsersStore/createMemorySettingsStore in
|
|
306
|
+
* @astratra/saas-kit. Fine for local dev and tests; credentials vanish on
|
|
307
|
+
* restart, so swap in your own persistent store (a real database) before
|
|
308
|
+
* production — this only removes the "no default at all" gap, it isn't a
|
|
309
|
+
* production-ready credential store.
|
|
310
|
+
*/
|
|
311
|
+
const createMemoryWebauthnStore = () => {
|
|
312
|
+
const credentialsByUser = new Map();
|
|
313
|
+
const credentialsById = new Map();
|
|
314
|
+
const challenges = new Map();
|
|
315
|
+
const recoveryCodesByUser = new Map();
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
async getCredentialsForUser(userId) {
|
|
319
|
+
return [...(credentialsByUser.get(String(userId)) || [])];
|
|
320
|
+
},
|
|
321
|
+
|
|
322
|
+
async saveCredential(userId, credential) {
|
|
323
|
+
const record = { ...credential, userId: String(userId), id: credential.credentialID };
|
|
324
|
+
const list = credentialsByUser.get(String(userId)) || [];
|
|
325
|
+
list.push(record);
|
|
326
|
+
credentialsByUser.set(String(userId), list);
|
|
327
|
+
credentialsById.set(credential.credentialID, record);
|
|
328
|
+
},
|
|
329
|
+
|
|
330
|
+
async getCredentialById(credentialId) {
|
|
331
|
+
return credentialsById.get(credentialId) || null;
|
|
332
|
+
},
|
|
333
|
+
|
|
334
|
+
async updateCredentialCounter(credentialId, counter) {
|
|
335
|
+
const record = credentialsById.get(credentialId);
|
|
336
|
+
if (record) record.counter = counter;
|
|
337
|
+
},
|
|
338
|
+
|
|
339
|
+
async saveChallenge(userId, challenge, type, metadata = {}) {
|
|
340
|
+
challenges.set(`${userId}:${type}`, { challenge, ...metadata });
|
|
341
|
+
},
|
|
342
|
+
|
|
343
|
+
async consumeChallenge(userId, type) {
|
|
344
|
+
const key = `${userId}:${type}`;
|
|
345
|
+
const pending = challenges.get(key) || null;
|
|
346
|
+
challenges.delete(key);
|
|
347
|
+
return pending;
|
|
348
|
+
},
|
|
349
|
+
|
|
350
|
+
async saveRecoveryCodes(userId, hashes) {
|
|
351
|
+
recoveryCodesByUser.set(String(userId), [...hashes]);
|
|
352
|
+
},
|
|
353
|
+
|
|
354
|
+
async consumeRecoveryCode(userId, hash) {
|
|
355
|
+
const codes = recoveryCodesByUser.get(String(userId)) || [];
|
|
356
|
+
const index = codes.indexOf(hash);
|
|
357
|
+
if (index === -1) return false;
|
|
358
|
+
codes.splice(index, 1);
|
|
359
|
+
recoveryCodesByUser.set(String(userId), codes);
|
|
360
|
+
return true;
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
};
|
|
364
|
+
|
|
302
365
|
module.exports = {
|
|
303
366
|
createWebauthnService,
|
|
367
|
+
createMemoryWebauthnStore,
|
|
304
368
|
rpConfigForRequest,
|
|
305
369
|
hashRecoveryCode,
|
|
306
370
|
CHALLENGE_TTL_MS,
|