@astratra/security 1.0.2 → 1.1.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
@@ -30,10 +30,69 @@ app.delete('/api/projects/:id', authorizeRoles('owner', 'admin'), handler);
30
30
  Par défaut, le middleware limite la vérification à `HS256`. Si ton application
31
31
  utilise un autre algorithme, configure explicitement `algorithms`.
32
32
 
33
- Si tu extrais le token depuis un cookie, configure le cookie côté application
34
- avec `HttpOnly`, `Secure` en HTTPS et un `SameSite` adapte. Un cookie JWT peut
35
- nécessiter une protection CSRF selon tes routes, tes méthodes HTTP et ton
36
- mode d'authentification.
33
+ ## Sessions cookie HttpOnly + CSRF
34
+
35
+ ```js
36
+ const {
37
+ cookieParserMiddleware,
38
+ setSessionCookie,
39
+ clearSessionCookie,
40
+ createCsrfMiddleware,
41
+ DEFAULT_SESSION_COOKIE_NAME // 'astratra_session'
42
+ } = require('@astratra/security');
43
+
44
+ app.use(cookieParserMiddleware()); // peuple req.cookies, sans dépendance cookie-parser
45
+
46
+ // au login :
47
+ setSessionCookie(res, token, { sameSite: 'lax' }); // HttpOnly toujours, Secure sauf NODE_ENV=development
48
+
49
+ // au logout :
50
+ clearSessionCookie(res);
51
+
52
+ // sur les routes mutantes protégées par cookie :
53
+ app.use('/api', authMiddleware, createCsrfMiddleware({
54
+ skip: (req) => Boolean(req.headers.authorization?.startsWith('Bearer ')) // les clients Bearer ne sont pas exposés au CSRF
55
+ }));
56
+ ```
57
+
58
+ `createAuthMiddleware`'s `extractToken` par défaut lit le cookie
59
+ `astratra_session` (ou `token`, pour compatibilité) avant de retomber sur
60
+ `Authorization: Bearer`. Si tu personnalises le nom du cookie via
61
+ `setSessionCookie(res, token, { name: 'autre_nom' })`, passe le même nom à
62
+ `extractToken` — sinon le cookie posé au login ne sera jamais relu.
63
+
64
+ Le CSRF est un middleware double-submit (cookie non-`HttpOnly` +
65
+ header `x-csrf-token`) — à monter explicitement là où tu en as besoin, il
66
+ n'est jamais actif tout seul dans ce package. `@astratra/saas-kit` le monte
67
+ par défaut sur ses routes protégées, avec bypass automatique pour les
68
+ clients `Authorization: Bearer`.
69
+
70
+ ## Révocation de session JWT
71
+
72
+ ```js
73
+ const { createAuthMiddleware, createMemoryRevocationStore } = require('@astratra/security');
74
+
75
+ const revocationStore = createMemoryRevocationStore(); // dev/single-instance ; Redis/DB en prod multi-instance
76
+
77
+ const authMiddleware = createAuthMiddleware({
78
+ secret: process.env.JWT_SECRET,
79
+ revocationStore // dérive automatiquement verifySession si tu n'en fournis pas un explicite
80
+ });
81
+
82
+ // au logout, pour invalider CE token précis :
83
+ await revocationStore.revoke(decodedToken.jti, decodedToken.exp * 1000);
84
+
85
+ // au "déconnecter tous mes appareils", pour invalider TOUS les tokens de l'utilisateur :
86
+ await revocationStore.revokeAllForUser(decodedToken.id, Date.now());
87
+ ```
88
+
89
+ Sans `jti` dans le payload du JWT, `revoke()` par token précis ne peut rien
90
+ faire — c'est à l'app qui signe le token de générer un `jti` unique par
91
+ connexion. `createMemoryRevocationStore()` est un store en mémoire process,
92
+ non partagé entre instances : pour une prod multi-instance, fournis ton
93
+ propre store (Redis, etc.) qui implémente la même interface
94
+ (`revoke`, `isRevoked`, et optionnellement `revokeAllForUser`/
95
+ `isRevokedForUser`).
37
96
 
38
97
  ## Rate limiting
39
98
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/security",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Generic authentication and security middleware for Astratra workspaces.",
5
5
  "main": "src/index.js",
6
6
  "types": "src/index.d.ts",
package/src/cookies.js ADDED
@@ -0,0 +1,96 @@
1
+ const DEFAULT_SESSION_COOKIE_NAME = 'astratra_session';
2
+ const PAST_DATE = 'Thu, 01 Jan 1970 00:00:00 GMT';
3
+
4
+ const sameSiteValue = (sameSite) => {
5
+ const value = sameSite || 'lax';
6
+ const normalized = String(value).toLowerCase();
7
+ if (normalized === 'strict') return 'Strict';
8
+ if (normalized === 'none') return 'None';
9
+ return 'Lax';
10
+ };
11
+
12
+ const secureValue = (options = {}) => {
13
+ if (options.secure !== undefined) return Boolean(options.secure);
14
+ return process.env.NODE_ENV !== 'development';
15
+ };
16
+
17
+ const appendSetCookie = (res, cookie) => {
18
+ const current = typeof res.getHeader === 'function' ? res.getHeader('Set-Cookie') : undefined;
19
+ if (!current) {
20
+ return res.setHeader('Set-Cookie', cookie);
21
+ }
22
+ if (Array.isArray(current)) {
23
+ return res.setHeader('Set-Cookie', [...current, cookie]);
24
+ }
25
+ return res.setHeader('Set-Cookie', [current, cookie]);
26
+ };
27
+
28
+ const serializeCookie = (name, value, options = {}) => {
29
+ const parts = [`${name}=${value}`];
30
+ if (options.maxAgeMs !== undefined) {
31
+ parts.push(`Max-Age=${Math.floor(options.maxAgeMs / 1000)}`);
32
+ }
33
+ if (options.expires) {
34
+ parts.push(`Expires=${options.expires}`);
35
+ }
36
+ if (options.domain) {
37
+ parts.push(`Domain=${options.domain}`);
38
+ }
39
+ parts.push(`Path=${options.path || '/'}`);
40
+ if (options.httpOnly) {
41
+ parts.push('HttpOnly');
42
+ }
43
+ if (secureValue(options)) {
44
+ parts.push('Secure');
45
+ }
46
+ parts.push(`SameSite=${sameSiteValue(options.sameSite)}`);
47
+ return parts.join('; ');
48
+ };
49
+
50
+ const parseCookieHeader = (header) => {
51
+ if (!header) return {};
52
+ return String(header).split(';').reduce((cookies, part) => {
53
+ const index = part.indexOf('=');
54
+ if (index === -1) return cookies;
55
+ const name = part.slice(0, index).trim();
56
+ const value = part.slice(index + 1).trim();
57
+ if (name) cookies[name] = value;
58
+ return cookies;
59
+ }, {});
60
+ };
61
+
62
+ const cookieParserMiddleware = () => (req, res, next) => {
63
+ if (!req.cookies) {
64
+ const headers = req.headers || {};
65
+ req.cookies = parseCookieHeader(headers.cookie || headers.Cookie);
66
+ }
67
+ next();
68
+ };
69
+
70
+ const setSessionCookie = (res, token, options = {}) => appendSetCookie(res, serializeCookie(
71
+ options.name || DEFAULT_SESSION_COOKIE_NAME,
72
+ token,
73
+ {
74
+ ...options,
75
+ httpOnly: true
76
+ }
77
+ ));
78
+
79
+ const clearSessionCookie = (res, options = {}) => appendSetCookie(res, serializeCookie(
80
+ options.name || DEFAULT_SESSION_COOKIE_NAME,
81
+ '',
82
+ {
83
+ ...options,
84
+ httpOnly: true,
85
+ maxAgeMs: 0,
86
+ expires: PAST_DATE
87
+ }
88
+ ));
89
+
90
+ module.exports = {
91
+ DEFAULT_SESSION_COOKIE_NAME,
92
+ parseCookieHeader,
93
+ cookieParserMiddleware,
94
+ setSessionCookie,
95
+ clearSessionCookie
96
+ };
package/src/csrf.js ADDED
@@ -0,0 +1,102 @@
1
+ const crypto = require('crypto');
2
+
3
+ const DEFAULT_CSRF_COOKIE_NAME = 'astratra_csrf';
4
+ const DEFAULT_CSRF_HEADER_NAME = 'x-csrf-token';
5
+ const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
6
+
7
+ const sameSiteValue = (sameSite) => {
8
+ const value = sameSite || 'lax';
9
+ const normalized = String(value).toLowerCase();
10
+ if (normalized === 'strict') return 'Strict';
11
+ if (normalized === 'none') return 'None';
12
+ return 'Lax';
13
+ };
14
+
15
+ const secureValue = (options = {}) => {
16
+ if (options.secure !== undefined) return Boolean(options.secure);
17
+ return process.env.NODE_ENV !== 'development';
18
+ };
19
+
20
+ const appendSetCookie = (res, cookie) => {
21
+ const current = typeof res.getHeader === 'function' ? res.getHeader('Set-Cookie') : undefined;
22
+ if (!current) {
23
+ return res.setHeader('Set-Cookie', cookie);
24
+ }
25
+ if (Array.isArray(current)) {
26
+ return res.setHeader('Set-Cookie', [...current, cookie]);
27
+ }
28
+ return res.setHeader('Set-Cookie', [current, cookie]);
29
+ };
30
+
31
+ const parseCookieHeader = (header) => {
32
+ if (!header) return {};
33
+ return String(header).split(';').reduce((cookies, part) => {
34
+ const index = part.indexOf('=');
35
+ if (index === -1) return cookies;
36
+ const name = part.slice(0, index).trim();
37
+ const value = part.slice(index + 1).trim();
38
+ if (name) cookies[name] = value;
39
+ return cookies;
40
+ }, {});
41
+ };
42
+
43
+ const cookieValue = (req, name) => {
44
+ if (req.cookies && req.cookies[name]) return req.cookies[name];
45
+ const headers = req.headers || {};
46
+ const parsed = parseCookieHeader(headers.cookie || headers.Cookie);
47
+ return parsed[name];
48
+ };
49
+
50
+ const headerValue = (req, name) => {
51
+ if (typeof req.get === 'function') return req.get(name);
52
+ const headers = req.headers || {};
53
+ return headers[name.toLowerCase()] || headers[name];
54
+ };
55
+
56
+ const setCsrfCookie = (res, token, options = {}) => {
57
+ const parts = [
58
+ `${options.name || DEFAULT_CSRF_COOKIE_NAME}=${token}`,
59
+ `Path=${options.path || '/'}`
60
+ ];
61
+ if (options.domain) {
62
+ parts.push(`Domain=${options.domain}`);
63
+ }
64
+ if (secureValue(options)) {
65
+ parts.push('Secure');
66
+ }
67
+ parts.push(`SameSite=${sameSiteValue(options.sameSite)}`);
68
+ appendSetCookie(res, parts.join('; '));
69
+ };
70
+
71
+ const createCsrfMiddleware = (options = {}) => {
72
+ const cookieName = options.name || DEFAULT_CSRF_COOKIE_NAME;
73
+ const headerName = options.headerName || DEFAULT_CSRF_HEADER_NAME;
74
+
75
+ return (req, res, next) => {
76
+ if (options.skip && options.skip(req)) {
77
+ return next();
78
+ }
79
+
80
+ let token = cookieValue(req, cookieName);
81
+ if (!token) {
82
+ token = crypto.randomBytes(32).toString('hex');
83
+ setCsrfCookie(res, token, { ...options, name: cookieName });
84
+ }
85
+
86
+ const method = String(req.method || 'GET').toUpperCase();
87
+ if (SAFE_METHODS.has(method)) {
88
+ return next();
89
+ }
90
+
91
+ if (headerValue(req, headerName) !== token) {
92
+ return res.status(403).json({ success: false, message: 'Invalid CSRF token.' });
93
+ }
94
+
95
+ return next();
96
+ };
97
+ };
98
+
99
+ module.exports = {
100
+ DEFAULT_CSRF_COOKIE_NAME,
101
+ createCsrfMiddleware
102
+ };
package/src/index.d.ts CHANGED
@@ -11,6 +11,8 @@ export interface RequestLike {
11
11
  }
12
12
 
13
13
  export interface ResponseLike {
14
+ getHeader?(name: string): unknown;
15
+ setHeader?(name: string, value: unknown): unknown;
14
16
  status(statusCode: number): {
15
17
  json(payload: unknown): unknown;
16
18
  };
@@ -31,11 +33,48 @@ export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
31
33
  message?: unknown;
32
34
  extractToken?: (req: RequestLike) => string | null | undefined;
33
35
  verifySession?: (decoded: TDecoded) => Awaitable<boolean>;
36
+ revocationStore?: RevocationStore;
34
37
  }
35
38
 
36
39
  export function createAuthMiddleware<TDecoded = Record<string, unknown>>(options: AuthMiddlewareOptions<TDecoded>): RequestHandler;
37
40
  export function authorizeRoles(...roles: string[]): RequestHandler;
38
41
 
42
+ export interface RevocationStore {
43
+ revoke(jti: string, expiresAt: number): Awaitable<void>;
44
+ isRevoked(jti?: string): Awaitable<boolean>;
45
+ revokeAllForUser?(userId: string, revokedBeforeMs: number): Awaitable<void>;
46
+ isRevokedForUser?(userId: string, issuedAtSeconds: number): Awaitable<boolean>;
47
+ }
48
+
49
+ export function createMemoryRevocationStore(): RevocationStore;
50
+
51
+ export interface SessionCookieOptions {
52
+ name?: string;
53
+ sameSite?: 'lax' | 'strict' | 'none' | string;
54
+ secure?: boolean;
55
+ path?: string;
56
+ domain?: string;
57
+ maxAgeMs?: number;
58
+ }
59
+
60
+ export const DEFAULT_SESSION_COOKIE_NAME: string;
61
+ export function parseCookieHeader(header?: string): Record<string, string>;
62
+ export function cookieParserMiddleware(): RequestHandler;
63
+ export function setSessionCookie(res: ResponseLike, token: string, options?: SessionCookieOptions): unknown;
64
+ export function clearSessionCookie(res: ResponseLike, options?: SessionCookieOptions): unknown;
65
+
66
+ export interface CsrfMiddlewareOptions {
67
+ name?: string;
68
+ headerName?: string;
69
+ sameSite?: 'lax' | 'strict' | 'none' | string;
70
+ secure?: boolean;
71
+ path?: string;
72
+ domain?: string;
73
+ skip?: (req: RequestLike) => boolean;
74
+ }
75
+
76
+ export function createCsrfMiddleware(options?: CsrfMiddlewareOptions): RequestHandler;
77
+
39
78
  export interface RateLimitStore {
40
79
  init?(options: unknown): unknown;
41
80
  increment?(...args: unknown[]): unknown;
package/src/index.js CHANGED
@@ -3,5 +3,8 @@ module.exports = {
3
3
  ...require('./rateLimiters'),
4
4
  ...require('./waf'),
5
5
  ...require('./webauthn'),
6
- ...require('./csp')
6
+ ...require('./csp'),
7
+ ...require('./cookies'),
8
+ ...require('./csrf'),
9
+ ...require('./revocation')
7
10
  };
package/src/jwtAuth.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const jwt = require('jsonwebtoken');
2
+ const { DEFAULT_SESSION_COOKIE_NAME } = require('./cookies');
2
3
 
3
4
  const DEFAULT_UNAUTHORIZED = {
4
5
  success: false,
@@ -13,7 +14,8 @@ const DEFAULT_FORBIDDEN = {
13
14
  const DEFAULT_ALGORITHMS = ['HS256'];
14
15
 
15
16
  const defaultExtractToken = (req) => {
16
- const cookieToken = req.cookies && req.cookies.token;
17
+ const cookies = req.cookies || {};
18
+ const cookieToken = cookies[DEFAULT_SESSION_COOKIE_NAME] || cookies.token;
17
19
  if (cookieToken) return cookieToken;
18
20
 
19
21
  const authorization = req.headers && req.headers.authorization;
@@ -51,6 +53,24 @@ const createAuthMiddleware = (options = {}) => {
51
53
  const extractToken = options.extractToken || defaultExtractToken;
52
54
  const unauthorizedMessage = options.message || DEFAULT_UNAUTHORIZED;
53
55
  const verificationOptions = verificationOptionsFrom(options);
56
+ const verifySession = options.verifySession || (options.revocationStore
57
+ ? async (decoded) => {
58
+ const revokedByToken = await options.revocationStore.isRevoked(decoded && decoded.jti);
59
+ if (revokedByToken) return false;
60
+
61
+ if (
62
+ decoded &&
63
+ decoded.id !== undefined &&
64
+ decoded.iat !== undefined &&
65
+ typeof options.revocationStore.isRevokedForUser === 'function'
66
+ ) {
67
+ const revokedByUser = await options.revocationStore.isRevokedForUser(decoded.id, decoded.iat);
68
+ if (revokedByUser) return false;
69
+ }
70
+
71
+ return true;
72
+ }
73
+ : undefined);
54
74
 
55
75
  return async (req, res, next) => {
56
76
  try {
@@ -61,8 +81,8 @@ const createAuthMiddleware = (options = {}) => {
61
81
 
62
82
  const decoded = verifyWithRotation(token, options.secret, options.legacySecret, verificationOptions);
63
83
 
64
- if (options.verifySession) {
65
- const isActive = await options.verifySession(decoded);
84
+ if (verifySession) {
85
+ const isActive = await verifySession(decoded);
66
86
  if (!isActive) {
67
87
  return res.status(401).json(unauthorizedMessage);
68
88
  }
@@ -0,0 +1,52 @@
1
+ const purgeExpired = (revokedTokenIds, now = Date.now()) => {
2
+ for (const [jti, expiresAt] of revokedTokenIds.entries()) {
3
+ if (expiresAt < now) {
4
+ revokedTokenIds.delete(jti);
5
+ }
6
+ }
7
+ };
8
+
9
+ const createMemoryRevocationStore = () => {
10
+ const revokedTokenIds = new Map();
11
+ const revokedUsers = new Map();
12
+
13
+ return {
14
+ async revoke(jti, expiresAt) {
15
+ purgeExpired(revokedTokenIds);
16
+ if (!jti) return;
17
+
18
+ const expiresAtMs = Number(expiresAt);
19
+ revokedTokenIds.set(jti, Number.isFinite(expiresAtMs) ? expiresAtMs : Date.now());
20
+ },
21
+
22
+ async isRevoked(jti) {
23
+ purgeExpired(revokedTokenIds);
24
+ if (!jti) return false;
25
+
26
+ return revokedTokenIds.has(jti);
27
+ },
28
+
29
+ async revokeAllForUser(userId, revokedBeforeMs = Date.now()) {
30
+ if (!userId) return;
31
+
32
+ const revokedBefore = Number(revokedBeforeMs);
33
+ revokedUsers.set(userId, Number.isFinite(revokedBefore) ? revokedBefore : Date.now());
34
+ },
35
+
36
+ async isRevokedForUser(userId, issuedAtSeconds) {
37
+ if (!userId) return false;
38
+
39
+ const revokedBefore = revokedUsers.get(userId);
40
+ if (revokedBefore === undefined) return false;
41
+
42
+ const issuedAtMs = Number(issuedAtSeconds) * 1000;
43
+ if (!Number.isFinite(issuedAtMs)) return false;
44
+
45
+ return issuedAtMs <= revokedBefore;
46
+ }
47
+ };
48
+ };
49
+
50
+ module.exports = {
51
+ createMemoryRevocationStore
52
+ };