@astratra/security 1.1.1 → 1.3.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 +48 -1
- package/package.json +1 -1
- package/src/cors.js +56 -0
- package/src/csrf.js +55 -2
- package/src/index.d.ts +27 -0
- package/src/index.js +1 -0
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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, un WAF heuristique et
|
|
4
|
+
le CORS, le rate limiting, une CSP configurable, un WAF heuristique et
|
|
5
5
|
WebAuthn/passkeys — génériques et découplées de toute base de données, ORM
|
|
6
6
|
ou liste de rôles fixe. Dépend de `@astratra/core`.
|
|
7
7
|
|
|
@@ -9,6 +9,28 @@ 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
|
+
## CORS
|
|
13
|
+
|
|
14
|
+
```js
|
|
15
|
+
const { createCorsMiddleware } = require('@astratra/security');
|
|
16
|
+
|
|
17
|
+
// À monter EN PREMIER, avant tout autre middleware — les en-têtes CORS,
|
|
18
|
+
// y compris sur la réponse de preflight OPTIONS, doivent être posés avant
|
|
19
|
+
// qu'un autre handler ne puisse court-circuiter la requête.
|
|
20
|
+
app.use(createCorsMiddleware({
|
|
21
|
+
allowedOrigins: (process.env.CORS_ORIGIN || '').split(',').filter(Boolean)
|
|
22
|
+
}));
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Astratra n'impose aucune politique CORS fixe — les origines autorisées sont
|
|
26
|
+
spécifiques à chaque projet. `@astratra/saas-kit` expose cette primitive via
|
|
27
|
+
`options.cors`, montée automatiquement au bon endroit — voir son README.
|
|
28
|
+
|
|
29
|
+
Origines `http://127.0.0.1`/`http://localhost` (tout port) autorisées par
|
|
30
|
+
défaut hors `NODE_ENV=production`, désactivable via `allowDevOrigins: false`.
|
|
31
|
+
`credentials: false` retire `Access-Control-Allow-Credentials` si tu n'as
|
|
32
|
+
pas besoin des cookies cross-origin.
|
|
33
|
+
|
|
12
34
|
## Auth JWT + RBAC
|
|
13
35
|
|
|
14
36
|
```js
|
|
@@ -67,6 +89,31 @@ n'est jamais actif tout seul dans ce package. `@astratra/saas-kit` le monte
|
|
|
67
89
|
par défaut sur ses routes protégées, avec bypass automatique pour les
|
|
68
90
|
clients `Authorization: Bearer`.
|
|
69
91
|
|
|
92
|
+
**Piège classique** : si tu ne montes `createCsrfMiddleware` que sur tes
|
|
93
|
+
routes mutantes (POST/PATCH/DELETE — le réflexe naturel), la toute première
|
|
94
|
+
requête mutante d'un client émet elle-même le cookie CSRF *dans sa propre
|
|
95
|
+
réponse* — le client ne peut jamais l'avoir lu à temps, donc elle échoue
|
|
96
|
+
systématiquement avec `403 Invalid CSRF token`, même avec des identifiants
|
|
97
|
+
valides. Le cookie doit exister *avant* la première requête mutante.
|
|
98
|
+
|
|
99
|
+
`createCsrfCookiePrimer(options)` résout ça : il amorce le cookie sur toute
|
|
100
|
+
requête sûre (GET/HEAD/OPTIONS) sans jamais valider de token, à monter une
|
|
101
|
+
seule fois, globalement, avant toutes les routes.
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
app.use(cookieParserMiddleware());
|
|
105
|
+
app.use(createCsrfCookiePrimer()); // amorce le cookie sur tout GET, avant les routes
|
|
106
|
+
|
|
107
|
+
// ensuite, comme avant : createCsrfMiddleware() valide sur tes routes mutantes
|
|
108
|
+
app.use('/api', authMiddleware, createCsrfMiddleware({
|
|
109
|
+
skip: (req) => Boolean(req.headers.authorization?.startsWith('Bearer '))
|
|
110
|
+
}));
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Les deux vérifient le cookie déjà mis en file sur la même réponse avant d'en
|
|
114
|
+
émettre un nouveau — les monter tous les deux sur la même requête ne pose
|
|
115
|
+
jamais deux cookies différents.
|
|
116
|
+
|
|
70
117
|
## Révocation de session JWT
|
|
71
118
|
|
|
72
119
|
```js
|
package/package.json
CHANGED
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
|
+
};
|
package/src/csrf.js
CHANGED
|
@@ -47,6 +47,26 @@ const cookieValue = (req, name) => {
|
|
|
47
47
|
return parsed[name];
|
|
48
48
|
};
|
|
49
49
|
|
|
50
|
+
// A Set-Cookie queued earlier in the SAME response (e.g. by
|
|
51
|
+
// createCsrfCookiePrimer running ahead of a route's own createCsrfMiddleware)
|
|
52
|
+
// never shows up in req.cookies — that only reflects cookies the client sent
|
|
53
|
+
// on THIS request. Without this check, two CSRF-aware middlewares on one
|
|
54
|
+
// request/response pair would each mint and queue their own token.
|
|
55
|
+
const queuedCookieValue = (res, name) => {
|
|
56
|
+
if (typeof res.getHeader !== 'function') return undefined;
|
|
57
|
+
const current = res.getHeader('Set-Cookie');
|
|
58
|
+
if (!current) return undefined;
|
|
59
|
+
const cookies = Array.isArray(current) ? current : [current];
|
|
60
|
+
for (const cookie of cookies) {
|
|
61
|
+
const [pair] = String(cookie).split(';');
|
|
62
|
+
const index = pair.indexOf('=');
|
|
63
|
+
if (index !== -1 && pair.slice(0, index).trim() === name) {
|
|
64
|
+
return pair.slice(index + 1).trim();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
};
|
|
69
|
+
|
|
50
70
|
const headerValue = (req, name) => {
|
|
51
71
|
if (typeof req.get === 'function') return req.get(name);
|
|
52
72
|
const headers = req.headers || {};
|
|
@@ -77,7 +97,7 @@ const createCsrfMiddleware = (options = {}) => {
|
|
|
77
97
|
return next();
|
|
78
98
|
}
|
|
79
99
|
|
|
80
|
-
let token = cookieValue(req, cookieName);
|
|
100
|
+
let token = cookieValue(req, cookieName) || queuedCookieValue(res, cookieName);
|
|
81
101
|
if (!token) {
|
|
82
102
|
token = crypto.randomBytes(32).toString('hex');
|
|
83
103
|
setCsrfCookie(res, token, { ...options, name: cookieName });
|
|
@@ -96,7 +116,40 @@ const createCsrfMiddleware = (options = {}) => {
|
|
|
96
116
|
};
|
|
97
117
|
};
|
|
98
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Issues the CSRF cookie on any safe request (GET/HEAD/OPTIONS) without
|
|
121
|
+
* ever validating a token. Meant to be mounted once, globally, ahead of
|
|
122
|
+
* all routes — so the double-submit cookie exists by the time a client
|
|
123
|
+
* makes its first mutating request, regardless of which routes happen to
|
|
124
|
+
* mount `createCsrfMiddleware` themselves.
|
|
125
|
+
*
|
|
126
|
+
* Without this, a route that only wires `createCsrfMiddleware` on its
|
|
127
|
+
* mutating handlers (POST/PATCH/DELETE) issues the cookie in the SAME
|
|
128
|
+
* response as the request that needed it validated — the client can never
|
|
129
|
+
* have read it in time, so the very first mutating request always fails
|
|
130
|
+
* with "Invalid CSRF token."
|
|
131
|
+
*/
|
|
132
|
+
const createCsrfCookiePrimer = (options = {}) => {
|
|
133
|
+
const cookieName = options.name || DEFAULT_CSRF_COOKIE_NAME;
|
|
134
|
+
|
|
135
|
+
return (req, res, next) => {
|
|
136
|
+
const method = String(req.method || 'GET').toUpperCase();
|
|
137
|
+
if (!SAFE_METHODS.has(method)) {
|
|
138
|
+
return next();
|
|
139
|
+
}
|
|
140
|
+
if (options.skip && options.skip(req)) {
|
|
141
|
+
return next();
|
|
142
|
+
}
|
|
143
|
+
if (!cookieValue(req, cookieName) && !queuedCookieValue(res, cookieName)) {
|
|
144
|
+
const token = crypto.randomBytes(32).toString('hex');
|
|
145
|
+
setCsrfCookie(res, token, { ...options, name: cookieName });
|
|
146
|
+
}
|
|
147
|
+
return next();
|
|
148
|
+
};
|
|
149
|
+
};
|
|
150
|
+
|
|
99
151
|
module.exports = {
|
|
100
152
|
DEFAULT_CSRF_COOKIE_NAME,
|
|
101
|
-
createCsrfMiddleware
|
|
153
|
+
createCsrfMiddleware,
|
|
154
|
+
createCsrfCookiePrimer
|
|
102
155
|
};
|
package/src/index.d.ts
CHANGED
|
@@ -22,6 +22,25 @@ 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
|
+
|
|
25
44
|
export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
|
|
26
45
|
secret: string;
|
|
27
46
|
legacySecret?: string;
|
|
@@ -75,6 +94,14 @@ export interface CsrfMiddlewareOptions {
|
|
|
75
94
|
|
|
76
95
|
export function createCsrfMiddleware(options?: CsrfMiddlewareOptions): RequestHandler;
|
|
77
96
|
|
|
97
|
+
/**
|
|
98
|
+
* Issues the CSRF cookie on safe requests (GET/HEAD/OPTIONS) without ever
|
|
99
|
+
* validating a token. Mount once, globally, ahead of all routes so the
|
|
100
|
+
* double-submit cookie exists before a client's first mutating request —
|
|
101
|
+
* see createCsrfMiddleware's README section on double-submit CSRF.
|
|
102
|
+
*/
|
|
103
|
+
export function createCsrfCookiePrimer(options?: Pick<CsrfMiddlewareOptions, 'name' | 'sameSite' | 'secure' | 'path' | 'domain' | 'skip'>): RequestHandler;
|
|
104
|
+
|
|
78
105
|
export interface RateLimitStore {
|
|
79
106
|
init?(options: unknown): unknown;
|
|
80
107
|
increment?(...args: unknown[]): unknown;
|