@astratra/security 1.3.0 → 1.5.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 CHANGED
@@ -1,14 +1,35 @@
1
1
  # @astratra/security
2
2
 
3
3
  Primitives de sécurité applicative pour l'authentification, l'autorisation,
4
- le CORS, le rate limiting, une CSP configurable, un WAF heuristique et
5
- WebAuthn/passkeys — génériques et découplées de toute base de données, ORM
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
+
12
33
  ## CORS
13
34
 
14
35
  ```js
@@ -31,6 +52,36 @@ défaut hors `NODE_ENV=production`, désactivable via `allowDevOrigins: false`.
31
52
  `credentials: false` retire `Access-Control-Allow-Credentials` si tu n'as
32
53
  pas besoin des cookies cross-origin.
33
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
+
34
85
  ## Auth JWT + RBAC
35
86
 
36
87
  ```js
@@ -52,6 +103,18 @@ app.delete('/api/projects/:id', authorizeRoles('owner', 'admin'), handler);
52
103
  Par défaut, le middleware limite la vérification à `HS256`. Si ton application
53
104
  utilise un autre algorithme, configure explicitement `algorithms`.
54
105
 
106
+ **Session par cookie sans `cookieParserMiddleware()` monté en amont** :
107
+ `createAuthMiddleware` a besoin de `req.cookies` pour lire un cookie de
108
+ session. Si aucun token n'est trouvé (ni cookie, ni header `Authorization`)
109
+ **et** que `req.cookies` est `undefined` — c'est-à-dire que
110
+ `cookieParserMiddleware()` (section suivante) n'a jamais tourné — le
111
+ middleware ne renvoie pas un 401 silencieux : il transmet une
112
+ `AuthConfigurationError` à `next(error)`, pour distinguer une vraie
113
+ absence de session d'un pipeline mal monté. Un routeur monté séparément de
114
+ `createSaasApp()` (au lieu de passer par `options.extendRoutes`) est le cas
115
+ le plus courant où ça arrive — voir
116
+ [`docs/guides/custom-routes-wiring.md`](../../docs/guides/custom-routes-wiring.md).
117
+
55
118
  ## Sessions cookie HttpOnly + CSRF
56
119
 
57
120
  ```js
@@ -214,6 +277,52 @@ CSP statique en dev casse le websocket HMR de Vite). Voir
214
277
  `examples/dashboard-ui/vite.config.js` pour un exemple qui n'injecte la
215
278
  balise que sur `vite build`.
216
279
 
280
+ ## En-têtes de sécurité (au-delà de CSP)
281
+
282
+ ```js
283
+ const { createSecurityHeadersMiddleware } = require('@astratra/security');
284
+ app.use(createSecurityHeadersMiddleware());
285
+ ```
286
+
287
+ Complète CSP avec le reste du set standard, chacun avec une valeur par
288
+ défaut sûre pour n'importe quel projet — contrairement à CORS, rien ici ne
289
+ demande une décision spécifique au projet, donc `@astratra/saas-kit` le
290
+ monte sans condition, comme CSP :
291
+
292
+ - `X-Frame-Options: DENY` — anti clickjacking
293
+ - `X-Content-Type-Options: nosniff` — anti détection de type MIME
294
+ - `Referrer-Policy: strict-origin-when-cross-origin` — limite la fuite d'URL vers des origines tierces
295
+ - `Permissions-Policy` — refuse géoloc/caméra/micro/paiement par défaut
296
+ - `Strict-Transport-Security` (HSTS) — actif automatiquement seulement si
297
+ `NODE_ENV=production` (le forcer en dev casse le HTTP local)
298
+
299
+ Chaque en-tête est désactivable/personnalisable individuellement
300
+ (`frameOptions: false`, `hsts: { maxAge, includeSubDomains }`, etc.).
301
+
302
+ ## Journal d'événements de sécurité
303
+
304
+ ```js
305
+ const { createSecurityAuditLogger } = require('@astratra/security');
306
+ app.use(createSecurityAuditLogger());
307
+ ```
308
+
309
+ Avant, aucune des autres couches (rejet CSRF, blocage WAF, rate limit, échec
310
+ JWT) ne journalisait quoi que ce soit — une tentative d'attaque restait
311
+ invisible tant qu'elle n'avait pas réussi. Plutôt que d'accrocher un log à
312
+ chaque middleware séparément, celui-ci observe la réponse : toute requête
313
+ qui se termine en `401`/`403`/`429` (configurable via `statusCodes`) produit
314
+ une ligne structurée, peu importe quelle couche l'a produite.
315
+
316
+ ```js
317
+ app.use(createSecurityAuditLogger({
318
+ log: (message, event) => myLogger.warn(message, event), // par défaut : @astratra/core createLogger
319
+ statusCodes: [401, 403, 429]
320
+ }));
321
+ ```
322
+
323
+ `@astratra/saas-kit` le monte par défaut ; `options.securityAudit: false`
324
+ le désactive.
325
+
217
326
  ## WebAuthn / passkeys
218
327
 
219
328
  ```js
@@ -234,6 +343,20 @@ récupération. Aucun Mongoose, aucun rôle fixe autorisé à enregistrer une cl
234
343
  présenter WebAuthn comme un argument de sécurité fort, prévois une revue de
235
344
  sécurité externe sur l'intégration complète.
236
345
 
346
+ Pour développer/tester sans écrire de store tout de suite,
347
+ `createMemoryWebauthnStore()` fournit une implémentation en mémoire
348
+ conforme au contrat complet — credentials perdues au redémarrage, à
349
+ remplacer par une vraie base avant la prod :
350
+
351
+ ```js
352
+ const { createWebauthnService, createMemoryWebauthnStore } = require('@astratra/security');
353
+
354
+ const webauthn = createWebauthnService(createMemoryWebauthnStore(), {
355
+ rpName: 'Mon App',
356
+ recoveryCodeSecret: process.env.RECOVERY_CODE_SECRET
357
+ });
358
+ ```
359
+
237
360
  ## Tests
238
361
 
239
362
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/security",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "Generic authentication and security middleware for Astratra workspaces.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -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
+ };
@@ -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
@@ -41,6 +41,89 @@ export interface CorsMiddlewareOptions {
41
41
  */
42
42
  export function createCorsMiddleware(options?: CorsMiddlewareOptions): RequestHandler;
43
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
+
44
127
  export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
45
128
  secret: string;
46
129
  legacySecret?: string;
@@ -58,6 +141,13 @@ export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
58
141
  export function createAuthMiddleware<TDecoded = Record<string, unknown>>(options: AuthMiddlewareOptions<TDecoded>): RequestHandler;
59
142
  export function authorizeRoles(...roles: string[]): RequestHandler;
60
143
 
144
+ /**
145
+ * Thrown by the default token extractor — and passed to `next(error)`,
146
+ * never swallowed into a 401 — when `req.cookies` is `undefined` (no
147
+ * cookie parser mounted) and no token was found by any other means either.
148
+ */
149
+ export class AuthConfigurationError extends Error {}
150
+
61
151
  export interface RevocationStore {
62
152
  revoke(jti: string, expiresAt: number): Awaitable<void>;
63
153
  isRevoked(jti?: string): Awaitable<boolean>;
@@ -246,3 +336,10 @@ export interface WebauthnService {
246
336
  export function createWebauthnService(store: WebauthnStore, options?: WebauthnOptions): WebauthnService;
247
337
  export function rpConfigForRequest(req: RequestLike, options?: WebauthnOptions): RpConfig;
248
338
  export function hashRecoveryCode(code: string, secret: string): string;
339
+
340
+ /**
341
+ * Reference in-memory WebauthnStore implementation. Fine for local dev and
342
+ * tests — credentials are lost on restart, so this is not a production
343
+ * credential store.
344
+ */
345
+ export function createMemoryWebauthnStore(): WebauthnStore;
package/src/index.js CHANGED
@@ -1,7 +1,11 @@
1
1
  module.exports = {
2
2
  ...require('./cors'),
3
+ ...require('./encryption'),
3
4
  ...require('./jwtAuth'),
5
+ ...require('./passwordHashing'),
4
6
  ...require('./rateLimiters'),
7
+ ...require('./securityHeaders'),
8
+ ...require('./auditLogger'),
5
9
  ...require('./waf'),
6
10
  ...require('./webauthn'),
7
11
  ...require('./csp'),
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
- const cookieToken = cookies[DEFAULT_SESSION_COOKIE_NAME] || cookies.token;
19
- if (cookieToken) return cookieToken;
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 (_error) {
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,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,