@astratra/security 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @astratra/security
2
+
3
+ Authentification, autorisation, rate limiting, WAF et WebAuthn/passkeys —
4
+ générique et découplé de toute base de données, ORM ou liste de rôles fixe.
5
+ Dépend de `@astratra/core`.
6
+
7
+ Partout où un vrai projet a besoin de persistance (révocation de session,
8
+ stockage de credentials WebAuthn, alerte de brute-force), c'est un
9
+ callback/adapter injecté, jamais un appel base de données codé en dur.
10
+
11
+ ## Auth JWT + RBAC
12
+
13
+ ```js
14
+ const { createAuthMiddleware, authorizeRoles } = require('@astratra/security');
15
+
16
+ const authMiddleware = createAuthMiddleware({
17
+ secret: process.env.JWT_SECRET,
18
+ legacySecret: process.env.JWT_SECRET_OLD, // optionnel, pour la rotation de clé
19
+ verifySession: async (decoded) => sessionStore.isActive(decoded) // vérification de révocation optionnelle
20
+ });
21
+
22
+ app.use('/api', authMiddleware);
23
+ app.delete('/api/schools/:id', authorizeRoles('owner', 'admin'), handler);
24
+ ```
25
+
26
+ ## Rate limiting
27
+
28
+ ```js
29
+ const { createApiLimiter, createLoginLimiter, createAccountLimiter } = require('@astratra/security');
30
+
31
+ app.use(createApiLimiter()); // 300 req / 15 min par défaut, ignore localhost
32
+ app.use('/auth', createLoginLimiter({
33
+ onBlocked: ({ ip, req }) => alertService.notify(`Brute-force depuis ${ip}`)
34
+ }));
35
+ app.use('/auth/login', createAccountLimiter({ onBlocked: ({ identifier }) => { /* ... */ } }));
36
+ ```
37
+
38
+ ## WAF
39
+
40
+ ```js
41
+ const { createWafMiddleware } = require('@astratra/security');
42
+ app.use(createWafMiddleware({ message: { success: false, message: 'Requête bloquée.' } }));
43
+ ```
44
+
45
+ Bloque les patterns SQLi/XSS/traversée de chemin/RCE courants dans
46
+ `req.path`, `req.query` et `req.body`.
47
+
48
+ ## WebAuthn / passkeys
49
+
50
+ ```js
51
+ const { createWebauthnService } = require('@astratra/security');
52
+
53
+ const webauthn = createWebauthnService(store, {
54
+ rpName: 'Mon App',
55
+ recoveryCodeSecret: process.env.RECOVERY_CODE_SECRET
56
+ });
57
+ ```
58
+
59
+ `store` est un adapter fourni par l'application consommatrice :
60
+ `getCredentialsForUser`, `saveCredential`, `getCredentialById`,
61
+ `updateCredentialCounter`, `saveChallenge`, `consumeChallenge`, et
62
+ optionnellement `saveRecoveryCodes`/`consumeRecoveryCode` pour les codes de
63
+ récupération. Aucun Mongoose, aucun rôle fixe autorisé à enregistrer une clé
64
+ — ce contrôle d'accès reste à la charge de l'app consommatrice.
65
+
66
+ ## Tests
67
+
68
+ ```bash
69
+ npm test --workspace @astratra/security
70
+ ```
71
+
72
+ 21 tests, aucune vraie base de données ni cérémonie WebAuthn navigateur
73
+ requise.
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@astratra/security",
3
+ "version": "0.1.0",
4
+ "description": "Generic authentication and security middleware for Astratra workspaces.",
5
+ "main": "src/index.js",
6
+ "types": "src/index.d.ts",
7
+ "type": "commonjs",
8
+ "files": [
9
+ "src"
10
+ ],
11
+ "scripts": {
12
+ "test": "jest"
13
+ },
14
+ "jest": {
15
+ "testMatch": [
16
+ "**/__tests__/**/*.test.js"
17
+ ]
18
+ },
19
+ "keywords": [
20
+ "astratra",
21
+ "security",
22
+ "auth"
23
+ ],
24
+ "license": "MIT",
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "dependencies": {
29
+ "@astratra/core": "^0.1.0",
30
+ "@simplewebauthn/server": "^13.1.2",
31
+ "express-rate-limit": "^7.5.1",
32
+ "jsonwebtoken": "^9.0.2"
33
+ },
34
+ "peerDependencies": {
35
+ "rate-limit-redis": ">=4",
36
+ "redis": ">=4"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "rate-limit-redis": {
40
+ "optional": true
41
+ },
42
+ "redis": {
43
+ "optional": true
44
+ }
45
+ },
46
+ "devDependencies": {
47
+ "jest": "30.4.2",
48
+ "rate-limit-redis": "^4.2.0",
49
+ "redis": "^4.7.0"
50
+ }
51
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,167 @@
1
+ export interface RequestLike {
2
+ body?: Record<string, unknown>;
3
+ connection?: { remoteAddress?: string };
4
+ cookies?: Record<string, string | undefined>;
5
+ headers?: Record<string, string | undefined>;
6
+ ip?: string;
7
+ path?: string;
8
+ query?: Record<string, unknown>;
9
+ user?: Record<string, unknown>;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ export interface ResponseLike {
14
+ status(statusCode: number): {
15
+ json(payload: unknown): unknown;
16
+ };
17
+ }
18
+
19
+ export type NextFunction = (error?: unknown) => unknown;
20
+ export type RequestHandler = (req: RequestLike, res: ResponseLike, next: NextFunction) => unknown;
21
+ export type Awaitable<T> = T | Promise<T>;
22
+
23
+ export interface AuthMiddlewareOptions<TDecoded = Record<string, unknown>> {
24
+ secret: string;
25
+ legacySecret?: string;
26
+ message?: unknown;
27
+ extractToken?: (req: RequestLike) => string | null | undefined;
28
+ verifySession?: (decoded: TDecoded) => Awaitable<boolean>;
29
+ }
30
+
31
+ export function createAuthMiddleware<TDecoded = Record<string, unknown>>(options: AuthMiddlewareOptions<TDecoded>): RequestHandler;
32
+ export function authorizeRoles(...roles: string[]): RequestHandler;
33
+
34
+ export interface RateLimitStore {
35
+ init?(options: unknown): unknown;
36
+ increment?(...args: unknown[]): unknown;
37
+ decrement?(...args: unknown[]): unknown;
38
+ resetKey?(...args: unknown[]): unknown;
39
+ resetAll?(...args: unknown[]): unknown;
40
+ get?(...args: unknown[]): unknown;
41
+ shutdown?(...args: unknown[]): unknown;
42
+ }
43
+
44
+ export interface RateLimitOptions {
45
+ windowMs?: number;
46
+ max?: number;
47
+ skip?: (req: RequestLike) => boolean | Promise<boolean>;
48
+ standardHeaders?: boolean | string;
49
+ legacyHeaders?: boolean;
50
+ validate?: Record<string, unknown> | boolean;
51
+ message?: unknown;
52
+ store?: RateLimitStore;
53
+ redisUrl?: string;
54
+ }
55
+
56
+ export interface LoginBlockedContext {
57
+ ip: string;
58
+ req: RequestLike;
59
+ }
60
+
61
+ export interface AccountBlockedContext extends LoginBlockedContext {
62
+ identifier: unknown;
63
+ }
64
+
65
+ export interface LoginLimiterOptions extends RateLimitOptions {
66
+ onBlocked?: (context: LoginBlockedContext) => Awaitable<void>;
67
+ }
68
+
69
+ export interface AccountLimiterOptions extends RateLimitOptions {
70
+ keyGenerator?: (req: RequestLike) => string;
71
+ onBlocked?: (context: AccountBlockedContext) => Awaitable<void>;
72
+ }
73
+
74
+ export function createApiLimiter(options?: RateLimitOptions): RequestHandler;
75
+ export function createLoginLimiter(options?: LoginLimiterOptions): RequestHandler;
76
+ export function createAccountLimiter(options?: AccountLimiterOptions): RequestHandler;
77
+ export function skipLocalhost(req: RequestLike): boolean;
78
+
79
+ export interface WafOptions {
80
+ message?: unknown;
81
+ patterns?: RegExp[];
82
+ }
83
+
84
+ export function createWafMiddleware(options?: WafOptions): RequestHandler;
85
+ export const WAF_PATTERNS: RegExp[];
86
+
87
+ export const CHALLENGE_TTL_MS: number;
88
+ export const RECOVERY_CODE_COUNT: number;
89
+
90
+ export interface WebauthnOptions {
91
+ allowedOrigins?: string | string[];
92
+ challengeTtlMs?: number;
93
+ clientUrl?: string;
94
+ recoveryCodeCount?: number;
95
+ recoveryCodeSecret?: string;
96
+ rpName?: string;
97
+ }
98
+
99
+ export interface WebauthnCredential {
100
+ id?: string;
101
+ credentialID?: string;
102
+ publicKey: string | Uint8Array;
103
+ counter: number;
104
+ transports?: string[];
105
+ deviceName?: string;
106
+ [key: string]: unknown;
107
+ }
108
+
109
+ export interface WebauthnCredentialToSave {
110
+ credentialID: string;
111
+ publicKey: string;
112
+ counter: number;
113
+ transports: string[];
114
+ deviceName: string;
115
+ }
116
+
117
+ export type WebauthnChallengeType = 'registration' | 'authentication';
118
+
119
+ export interface WebauthnChallengeMetadata {
120
+ rpID: string;
121
+ origin: string;
122
+ expiresAt: Date;
123
+ }
124
+
125
+ export interface WebauthnPendingChallenge {
126
+ challenge: string;
127
+ origin?: string;
128
+ rpID?: string;
129
+ metadata?: Partial<WebauthnChallengeMetadata>;
130
+ }
131
+
132
+ export interface WebauthnStore {
133
+ getCredentialsForUser(userId: string): Awaitable<WebauthnCredential[]>;
134
+ saveCredential(userId: string, credential: WebauthnCredentialToSave): Awaitable<void>;
135
+ getCredentialById(credentialId: string): Awaitable<WebauthnCredential | null | undefined>;
136
+ updateCredentialCounter(credentialId: string, counter: number): Awaitable<void>;
137
+ saveChallenge(userId: string, challenge: string, type: WebauthnChallengeType, metadata: WebauthnChallengeMetadata): Awaitable<void>;
138
+ consumeChallenge(userId: string, type: WebauthnChallengeType): Awaitable<WebauthnPendingChallenge | null | undefined>;
139
+ saveRecoveryCodes?(userId: string, hashes: string[]): Awaitable<void>;
140
+ consumeRecoveryCode?(userId: string, hash: string): Awaitable<boolean>;
141
+ }
142
+
143
+ export interface RpConfig {
144
+ rpName: string;
145
+ rpID: string;
146
+ origin: string;
147
+ }
148
+
149
+ export interface WebauthnService {
150
+ getRegistrationOptions(req: RequestLike, userId: string, userName: string): Promise<unknown>;
151
+ verifyRegistration(userId: string, response: unknown, deviceName?: string): Promise<{
152
+ verified: true;
153
+ isFirstDevice: boolean;
154
+ recoveryCodes: string[] | null;
155
+ }>;
156
+ getAuthenticationOptions(req: RequestLike, userId: string): Promise<unknown>;
157
+ verifyAuthentication(userId: string, response: { id: string; [key: string]: unknown }): Promise<true>;
158
+ hasCredentials(userId: string): Promise<boolean>;
159
+ generateRecoveryCodes(userId: string): Promise<string[]>;
160
+ verifyRecoveryCode(userId: string, code: string): Promise<boolean>;
161
+ hashRecoveryCode(code: string): string;
162
+ rpConfigForRequest(req: RequestLike): RpConfig;
163
+ }
164
+
165
+ export function createWebauthnService(store: WebauthnStore, options?: WebauthnOptions): WebauthnService;
166
+ export function rpConfigForRequest(req: RequestLike, options?: WebauthnOptions): RpConfig;
167
+ export function hashRecoveryCode(code: string, secret: string): string;
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ module.exports = {
2
+ ...require('./jwtAuth'),
3
+ ...require('./rateLimiters'),
4
+ ...require('./waf'),
5
+ ...require('./webauthn')
6
+ };
package/src/jwtAuth.js ADDED
@@ -0,0 +1,79 @@
1
+ const jwt = require('jsonwebtoken');
2
+
3
+ const DEFAULT_UNAUTHORIZED = {
4
+ success: false,
5
+ message: 'Unauthorized.'
6
+ };
7
+
8
+ const DEFAULT_FORBIDDEN = {
9
+ success: false,
10
+ message: 'Forbidden.'
11
+ };
12
+
13
+ const defaultExtractToken = (req) => {
14
+ const cookieToken = req.cookies && req.cookies.token;
15
+ if (cookieToken) return cookieToken;
16
+
17
+ const authorization = req.headers && req.headers.authorization;
18
+ if (authorization && authorization.startsWith('Bearer ')) {
19
+ return authorization.slice('Bearer '.length);
20
+ }
21
+
22
+ return null;
23
+ };
24
+
25
+ const verifyWithRotation = (token, secret, legacySecret) => {
26
+ try {
27
+ return jwt.verify(token, secret);
28
+ } catch (error) {
29
+ if (legacySecret && error.name === 'JsonWebTokenError') {
30
+ return jwt.verify(token, legacySecret);
31
+ }
32
+ throw error;
33
+ }
34
+ };
35
+
36
+ const createAuthMiddleware = (options = {}) => {
37
+ if (!options.secret) {
38
+ throw new Error('createAuthMiddleware requires options.secret.');
39
+ }
40
+
41
+ const extractToken = options.extractToken || defaultExtractToken;
42
+ const unauthorizedMessage = options.message || DEFAULT_UNAUTHORIZED;
43
+
44
+ return async (req, res, next) => {
45
+ try {
46
+ const token = extractToken(req);
47
+ if (!token) {
48
+ return res.status(401).json(unauthorizedMessage);
49
+ }
50
+
51
+ const decoded = verifyWithRotation(token, options.secret, options.legacySecret);
52
+
53
+ if (options.verifySession) {
54
+ const isActive = await options.verifySession(decoded);
55
+ if (!isActive) {
56
+ return res.status(401).json(unauthorizedMessage);
57
+ }
58
+ }
59
+
60
+ req.user = decoded;
61
+ return next();
62
+ } catch (_error) {
63
+ return res.status(401).json(unauthorizedMessage);
64
+ }
65
+ };
66
+ };
67
+
68
+ const authorizeRoles = (...allowedRoles) => (req, res, next) => {
69
+ if (!req.user || !allowedRoles.includes(req.user.role)) {
70
+ return res.status(403).json(DEFAULT_FORBIDDEN);
71
+ }
72
+
73
+ return next();
74
+ };
75
+
76
+ module.exports = {
77
+ createAuthMiddleware,
78
+ authorizeRoles
79
+ };
@@ -0,0 +1,214 @@
1
+ const rateLimit = require('express-rate-limit');
2
+
3
+ const DEFAULT_API_MESSAGE = {
4
+ success: false,
5
+ message: 'Too many requests.'
6
+ };
7
+
8
+ const DEFAULT_LOGIN_MESSAGE = {
9
+ success: false,
10
+ message: 'Too many login attempts. Please try again later.'
11
+ };
12
+
13
+ const DEFAULT_ACCOUNT_MESSAGE = {
14
+ success: false,
15
+ message: 'Too many attempts for this account. Please try again later.'
16
+ };
17
+
18
+ const getIp = (req) => req.ip || req.connection?.remoteAddress || '';
19
+
20
+ const skipLocalhost = (req) => {
21
+ const ip = getIp(req);
22
+ return ip === '::1' || ip === '127.0.0.1' || ip.includes('localhost');
23
+ };
24
+
25
+ const sendLimitResponse = async (req, res, next, options, onBlocked, context) => {
26
+ if (onBlocked) {
27
+ await onBlocked(context);
28
+ }
29
+
30
+ return res.status(options.statusCode).json(options.message);
31
+ };
32
+
33
+ const createMemoryStore = () => {
34
+ const MemoryStore = rateLimit.MemoryStore;
35
+ return typeof MemoryStore === 'function' ? new MemoryStore() : null;
36
+ };
37
+
38
+ const createFailoverStore = (redisStore, memoryStore, connectPromise) => {
39
+ let activeStore = memoryStore || redisStore;
40
+ let initOptions = null;
41
+ const initializedStores = new WeakSet();
42
+
43
+ const initializeStore = (store) => {
44
+ if (!store || initializedStores.has(store)) return;
45
+ if (initOptions && typeof store.init === 'function') {
46
+ store.init(initOptions);
47
+ }
48
+ initializedStores.add(store);
49
+ };
50
+
51
+ const useStore = (store) => {
52
+ activeStore = store || memoryStore || redisStore;
53
+ initializeStore(activeStore);
54
+ };
55
+
56
+ connectPromise.then(
57
+ () => useStore(redisStore),
58
+ () => useStore(memoryStore)
59
+ );
60
+
61
+ const callActiveStore = (method, args) => {
62
+ const fn = activeStore && activeStore[method];
63
+ if (typeof fn !== 'function') return undefined;
64
+ return fn.apply(activeStore, args);
65
+ };
66
+
67
+ return {
68
+ init(options) {
69
+ initOptions = options;
70
+ initializeStore(activeStore);
71
+ },
72
+ increment(...args) {
73
+ return callActiveStore('increment', args);
74
+ },
75
+ decrement(...args) {
76
+ return callActiveStore('decrement', args);
77
+ },
78
+ resetKey(...args) {
79
+ return callActiveStore('resetKey', args);
80
+ },
81
+ resetAll(...args) {
82
+ return callActiveStore('resetAll', args);
83
+ },
84
+ get(...args) {
85
+ return callActiveStore('get', args);
86
+ },
87
+ shutdown(...args) {
88
+ if (redisStore && typeof redisStore.shutdown === 'function') {
89
+ redisStore.shutdown(...args);
90
+ }
91
+ if (memoryStore && typeof memoryStore.shutdown === 'function') {
92
+ memoryStore.shutdown(...args);
93
+ }
94
+ }
95
+ };
96
+ };
97
+
98
+ const createRedisStore = (redisUrl) => {
99
+ if (!redisUrl) return undefined;
100
+
101
+ let RedisModule;
102
+ let RateLimitRedisModule;
103
+ try {
104
+ RedisModule = require('redis');
105
+ RateLimitRedisModule = require('rate-limit-redis');
106
+ } catch (_error) {
107
+ return undefined;
108
+ }
109
+
110
+ const RedisStore = RateLimitRedisModule.RedisStore || RateLimitRedisModule.default || RateLimitRedisModule;
111
+ if (typeof RedisStore !== 'function' || typeof RedisModule.createClient !== 'function') {
112
+ return undefined;
113
+ }
114
+
115
+ try {
116
+ const client = RedisModule.createClient({ url: redisUrl });
117
+ if (client && typeof client.on === 'function') {
118
+ client.on('error', () => {});
119
+ }
120
+
121
+ const redisStore = new RedisStore({
122
+ sendCommand: (...args) => client.sendCommand(args)
123
+ });
124
+ const memoryStore = createMemoryStore();
125
+ const connectPromise = Promise.resolve(client.connect()).catch(() => {
126
+ if (client && client.isOpen && typeof client.disconnect === 'function') {
127
+ client.disconnect().catch(() => {});
128
+ }
129
+ throw new Error('Redis rate limit store unavailable');
130
+ });
131
+
132
+ return createFailoverStore(redisStore, memoryStore, connectPromise);
133
+ } catch (_error) {
134
+ return createMemoryStore() || undefined;
135
+ }
136
+ };
137
+
138
+ const resolveStore = (options) => {
139
+ if (options.store) return options.store;
140
+ return createRedisStore(options.redisUrl);
141
+ };
142
+
143
+ const withOptionalStore = (limiterOptions, store) => {
144
+ if (!store) return limiterOptions;
145
+ return { ...limiterOptions, store };
146
+ };
147
+
148
+ const createApiLimiter = (options = {}) => rateLimit(withOptionalStore({
149
+ windowMs: options.windowMs || 15 * 60 * 1000,
150
+ max: options.max || 300,
151
+ skip: options.skip || skipLocalhost,
152
+ standardHeaders: options.standardHeaders ?? true,
153
+ legacyHeaders: options.legacyHeaders ?? false,
154
+ validate: options.validate || { ip: false },
155
+ message: options.message || DEFAULT_API_MESSAGE
156
+ }, resolveStore(options)));
157
+
158
+ const createLoginLimiter = (options = {}) => rateLimit(withOptionalStore({
159
+ windowMs: options.windowMs || 15 * 60 * 1000,
160
+ max: options.max || 10,
161
+ skip: options.skip,
162
+ standardHeaders: options.standardHeaders ?? true,
163
+ legacyHeaders: options.legacyHeaders ?? false,
164
+ validate: options.validate || { ip: false },
165
+ message: options.message || DEFAULT_LOGIN_MESSAGE,
166
+ handler: (req, res, next, limitOptions) => sendLimitResponse(
167
+ req,
168
+ res,
169
+ next,
170
+ limitOptions,
171
+ options.onBlocked,
172
+ { ip: getIp(req), req }
173
+ )
174
+ }, resolveStore(options)));
175
+
176
+ const defaultAccountKeyGenerator = (req) => {
177
+ const body = req.body || {};
178
+ const identifier = body.email || body.identifier || 'unknown';
179
+ return String(identifier).toLowerCase();
180
+ };
181
+
182
+ const createAccountLimiter = (options = {}) => {
183
+ const keyGenerator = options.keyGenerator || defaultAccountKeyGenerator;
184
+
185
+ return rateLimit(withOptionalStore({
186
+ windowMs: options.windowMs || 30 * 60 * 1000,
187
+ max: options.max || 20,
188
+ skip: options.skip,
189
+ standardHeaders: options.standardHeaders ?? true,
190
+ legacyHeaders: options.legacyHeaders ?? false,
191
+ validate: options.validate || { ip: false },
192
+ keyGenerator,
193
+ message: options.message || DEFAULT_ACCOUNT_MESSAGE,
194
+ handler: (req, res, next, limitOptions) => {
195
+ const body = req.body || {};
196
+ const identifier = body.email || body.identifier || 'unknown';
197
+ return sendLimitResponse(
198
+ req,
199
+ res,
200
+ next,
201
+ limitOptions,
202
+ options.onBlocked,
203
+ { identifier, ip: getIp(req), req }
204
+ );
205
+ }
206
+ }, resolveStore(options)));
207
+ };
208
+
209
+ module.exports = {
210
+ createApiLimiter,
211
+ createLoginLimiter,
212
+ createAccountLimiter,
213
+ skipLocalhost
214
+ };
package/src/waf.js ADDED
@@ -0,0 +1,51 @@
1
+ const WAF_PATTERNS = [
2
+ /(\b(union|select|insert|update|delete|drop|alter|create)\b.*\b(from|into|table|database)\b)/gi,
3
+ /(\b(or|and)\b\s+\d+\s*=\s*\d+)/gi,
4
+ /(--|#|\/\*|\*\/|;--)/g,
5
+ /(\.\.\/(\.\.\/){2,})/g,
6
+ /(\/etc\/passwd|\/proc\/self|\/dev\/null)/gi,
7
+ /(<script[\s>]|javascript:|on(error|load|click|mouseover)\s*=)/gi,
8
+ /(\$\{.*\}|\$\(.*\))/g,
9
+ /(\bexec\b|\beval\b|\bFunction\b)\s*\(/gi
10
+ ];
11
+
12
+ const DEFAULT_MESSAGE = {
13
+ success: false,
14
+ message: 'Request blocked by security policy.'
15
+ };
16
+
17
+ const safeStringify = (value) => {
18
+ if (typeof value === 'string') return value;
19
+ try {
20
+ return JSON.stringify(value || {});
21
+ } catch (_error) {
22
+ return '';
23
+ }
24
+ };
25
+
26
+ const createWafMiddleware = (options = {}) => {
27
+ const message = options.message || DEFAULT_MESSAGE;
28
+ const patterns = options.patterns || WAF_PATTERNS;
29
+
30
+ return (req, res, next) => {
31
+ const targets = [
32
+ req.path,
33
+ safeStringify(req.query),
34
+ safeStringify(req.body)
35
+ ].join(' ');
36
+
37
+ for (const pattern of patterns) {
38
+ pattern.lastIndex = 0;
39
+ if (pattern.test(targets)) {
40
+ return res.status(403).json(message);
41
+ }
42
+ }
43
+
44
+ return next();
45
+ };
46
+ };
47
+
48
+ module.exports = {
49
+ createWafMiddleware,
50
+ WAF_PATTERNS
51
+ };
@@ -0,0 +1,292 @@
1
+ const crypto = require('crypto');
2
+ const {
3
+ generateRegistrationOptions,
4
+ verifyRegistrationResponse,
5
+ generateAuthenticationOptions,
6
+ verifyAuthenticationResponse
7
+ } = require('@simplewebauthn/server');
8
+
9
+ const CHALLENGE_TTL_MS = 5 * 60 * 1000;
10
+ const RECOVERY_CODE_COUNT = 10;
11
+ const LOCALHOST_ORIGINS = [
12
+ 'http://localhost:5173',
13
+ 'http://localhost:5174',
14
+ 'http://localhost:3000'
15
+ ];
16
+
17
+ const requiredStoreMethods = [
18
+ 'getCredentialsForUser',
19
+ 'saveCredential',
20
+ 'getCredentialById',
21
+ 'updateCredentialCounter',
22
+ 'saveChallenge',
23
+ 'consumeChallenge'
24
+ ];
25
+
26
+ const optionalRecoveryStoreMethods = [
27
+ 'saveRecoveryCodes',
28
+ 'consumeRecoveryCode'
29
+ ];
30
+
31
+ const createError = (message, statusCode) => {
32
+ const error = new Error(message);
33
+ error.statusCode = statusCode;
34
+ return error;
35
+ };
36
+
37
+ const unique = (items) => [...new Set(items.filter(Boolean))];
38
+
39
+ const allowedOrigins = (options = {}) => {
40
+ const configured = options.allowedOrigins || process.env.WEBAUTHN_ALLOWED_ORIGINS || '';
41
+ const extra = Array.isArray(configured)
42
+ ? configured
43
+ : configured.split(',').map((origin) => origin.trim());
44
+ const clientUrl = options.clientUrl || process.env.CLIENT_URL;
45
+ return unique([...extra, clientUrl, ...LOCALHOST_ORIGINS]);
46
+ };
47
+
48
+ const rpConfigForRequest = (req, options = {}) => {
49
+ const requestOrigin = req?.headers?.origin;
50
+ const candidates = allowedOrigins(options);
51
+ const origin = requestOrigin && candidates.includes(requestOrigin) ? requestOrigin : candidates[0];
52
+
53
+ if (!origin) {
54
+ throw createError('No WebAuthn origin configured.', 500);
55
+ }
56
+
57
+ if (requestOrigin && !candidates.includes(requestOrigin)) {
58
+ throw createError(`WebAuthn origin is not allowed: ${requestOrigin}`, 403);
59
+ }
60
+
61
+ let rpID;
62
+ try {
63
+ rpID = new URL(origin).hostname;
64
+ } catch (_error) {
65
+ rpID = 'localhost';
66
+ }
67
+
68
+ return {
69
+ rpName: options.rpName || process.env.WEBAUTHN_RP_NAME || 'Astratra',
70
+ rpID,
71
+ origin
72
+ };
73
+ };
74
+
75
+ const assertStore = (store) => {
76
+ for (const method of requiredStoreMethods) {
77
+ if (!store || typeof store[method] !== 'function') {
78
+ throw new Error(`createWebauthnService requires store.${method}.`);
79
+ }
80
+ }
81
+ };
82
+
83
+ const assertRecoveryStore = (store) => {
84
+ for (const method of optionalRecoveryStoreMethods) {
85
+ if (typeof store[method] !== 'function') {
86
+ throw new Error(`Recovery codes require store.${method}.`);
87
+ }
88
+ }
89
+ };
90
+
91
+ const normalizeChallenge = (pending) => {
92
+ if (!pending) return null;
93
+ return {
94
+ challenge: pending.challenge,
95
+ origin: pending.origin || pending.metadata?.origin,
96
+ rpID: pending.rpID || pending.metadata?.rpID
97
+ };
98
+ };
99
+
100
+ const publicKeyToBase64Url = (publicKey) => {
101
+ if (Buffer.isBuffer(publicKey)) return publicKey.toString('base64url');
102
+ if (publicKey instanceof Uint8Array) return Buffer.from(publicKey).toString('base64url');
103
+ return String(publicKey);
104
+ };
105
+
106
+ const publicKeyFromBase64Url = (publicKey) => {
107
+ if (Buffer.isBuffer(publicKey)) return publicKey;
108
+ if (publicKey instanceof Uint8Array) return Buffer.from(publicKey);
109
+ return Buffer.from(String(publicKey), 'base64url');
110
+ };
111
+
112
+ const formatRecoveryCode = () => {
113
+ const raw = crypto.randomBytes(4).toString('hex');
114
+ return `${raw.slice(0, 4)}-${raw.slice(4)}`;
115
+ };
116
+
117
+ const hashRecoveryCode = (code, secret) => {
118
+ if (!secret) {
119
+ throw new Error('Recovery code hashing requires options.recoveryCodeSecret.');
120
+ }
121
+
122
+ return crypto.createHash('sha256').update(`${secret}:${String(code).trim().toLowerCase()}`).digest('hex');
123
+ };
124
+
125
+ const createWebauthnService = (store, options = {}) => {
126
+ assertStore(store);
127
+
128
+ const challengeTtlMs = options.challengeTtlMs || CHALLENGE_TTL_MS;
129
+ const recoveryCodeCount = options.recoveryCodeCount || RECOVERY_CODE_COUNT;
130
+
131
+ const service = {
132
+ async getRegistrationOptions(req, userId, userName) {
133
+ const { rpName, rpID, origin } = rpConfigForRequest(req, options);
134
+ const existing = await store.getCredentialsForUser(userId);
135
+
136
+ const registrationOptions = await generateRegistrationOptions({
137
+ rpName,
138
+ rpID,
139
+ userName,
140
+ userID: Buffer.from(String(userId)),
141
+ attestationType: 'none',
142
+ authenticatorSelection: {
143
+ residentKey: 'preferred',
144
+ userVerification: 'required',
145
+ authenticatorAttachment: 'platform'
146
+ },
147
+ excludeCredentials: existing.map((credential) => ({
148
+ id: credential.credentialID || credential.id,
149
+ transports: credential.transports || []
150
+ }))
151
+ });
152
+
153
+ await store.saveChallenge(userId, registrationOptions.challenge, 'registration', {
154
+ rpID,
155
+ origin,
156
+ expiresAt: new Date(Date.now() + challengeTtlMs)
157
+ });
158
+
159
+ return registrationOptions;
160
+ },
161
+
162
+ async verifyRegistration(userId, response, deviceName) {
163
+ const pending = normalizeChallenge(await store.consumeChallenge(userId, 'registration'));
164
+ if (!pending) {
165
+ throw createError('No pending WebAuthn registration challenge.', 400);
166
+ }
167
+
168
+ const verification = await verifyRegistrationResponse({
169
+ response,
170
+ expectedChallenge: pending.challenge,
171
+ expectedOrigin: pending.origin,
172
+ expectedRPID: pending.rpID
173
+ });
174
+
175
+ if (!verification.verified || !verification.registrationInfo) {
176
+ throw createError('WebAuthn registration verification failed.', 400);
177
+ }
178
+
179
+ const existing = await store.getCredentialsForUser(userId);
180
+ const isFirstDevice = existing.length === 0;
181
+ const { credential } = verification.registrationInfo;
182
+
183
+ await store.saveCredential(userId, {
184
+ credentialID: credential.id,
185
+ publicKey: publicKeyToBase64Url(credential.publicKey),
186
+ counter: credential.counter,
187
+ transports: credential.transports || [],
188
+ deviceName: deviceName || 'Device'
189
+ });
190
+
191
+ const recoveryCodes = isFirstDevice ? await service.generateRecoveryCodes(userId) : null;
192
+ return { verified: true, isFirstDevice, recoveryCodes };
193
+ },
194
+
195
+ async getAuthenticationOptions(req, userId) {
196
+ const { rpID, origin } = rpConfigForRequest(req, options);
197
+ const credentials = await store.getCredentialsForUser(userId);
198
+ if (credentials.length === 0) {
199
+ throw createError('No WebAuthn credentials registered.', 400);
200
+ }
201
+
202
+ const authenticationOptions = await generateAuthenticationOptions({
203
+ rpID,
204
+ allowCredentials: credentials.map((credential) => ({
205
+ id: credential.credentialID || credential.id,
206
+ transports: credential.transports || []
207
+ })),
208
+ userVerification: 'required'
209
+ });
210
+
211
+ await store.saveChallenge(userId, authenticationOptions.challenge, 'authentication', {
212
+ rpID,
213
+ origin,
214
+ expiresAt: new Date(Date.now() + challengeTtlMs)
215
+ });
216
+
217
+ return authenticationOptions;
218
+ },
219
+
220
+ async verifyAuthentication(userId, response) {
221
+ const pending = normalizeChallenge(await store.consumeChallenge(userId, 'authentication'));
222
+ if (!pending) {
223
+ throw createError('No pending WebAuthn authentication challenge.', 400);
224
+ }
225
+
226
+ const stored = await store.getCredentialById(response.id);
227
+ if (!stored) {
228
+ throw createError('Unknown WebAuthn credential.', 401);
229
+ }
230
+
231
+ const credentialID = stored.credentialID || stored.id;
232
+ const verification = await verifyAuthenticationResponse({
233
+ response,
234
+ expectedChallenge: pending.challenge,
235
+ expectedOrigin: pending.origin,
236
+ expectedRPID: pending.rpID,
237
+ credential: {
238
+ id: credentialID,
239
+ publicKey: publicKeyFromBase64Url(stored.publicKey),
240
+ counter: stored.counter,
241
+ transports: stored.transports || []
242
+ }
243
+ });
244
+
245
+ if (!verification.verified) {
246
+ throw createError('WebAuthn authentication verification failed.', 401);
247
+ }
248
+
249
+ await store.updateCredentialCounter(credentialID, verification.authenticationInfo.newCounter);
250
+ return true;
251
+ },
252
+
253
+ async hasCredentials(userId) {
254
+ const credentials = await store.getCredentialsForUser(userId);
255
+ return credentials.length > 0;
256
+ },
257
+
258
+ async generateRecoveryCodes(userId) {
259
+ assertRecoveryStore(store);
260
+
261
+ const codes = Array.from({ length: recoveryCodeCount }, formatRecoveryCode);
262
+ const hashes = codes.map((code) => hashRecoveryCode(code, options.recoveryCodeSecret));
263
+ await store.saveRecoveryCodes(userId, hashes);
264
+ return codes;
265
+ },
266
+
267
+ async verifyRecoveryCode(userId, code) {
268
+ assertRecoveryStore(store);
269
+
270
+ const hash = hashRecoveryCode(code, options.recoveryCodeSecret);
271
+ return store.consumeRecoveryCode(userId, hash);
272
+ },
273
+
274
+ hashRecoveryCode(code) {
275
+ return hashRecoveryCode(code, options.recoveryCodeSecret);
276
+ },
277
+
278
+ rpConfigForRequest(req) {
279
+ return rpConfigForRequest(req, options);
280
+ }
281
+ };
282
+
283
+ return service;
284
+ };
285
+
286
+ module.exports = {
287
+ createWebauthnService,
288
+ rpConfigForRequest,
289
+ hashRecoveryCode,
290
+ CHALLENGE_TTL_MS,
291
+ RECOVERY_CODE_COUNT
292
+ };