webspresso 0.0.108 → 0.0.109
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 +21 -0
- package/README.md +3 -3
- package/bin/commands/add-esbuild.js +7 -3
- package/bin/commands/add-tailwind.js +9 -5
- package/bin/commands/build.js +20 -4
- package/bin/commands/dev.js +57 -7
- package/bin/commands/doctor.js +42 -1
- package/bin/commands/favicon-generate.js +10 -3
- package/bin/commands/new.js +8 -3
- package/bin/commands/start.js +3 -1
- package/bin/utils/add-command.js +16 -0
- package/core/app.js +45 -3
- package/core/auth/authenticate.js +3 -3
- package/core/auth/hash.js +167 -43
- package/core/auth/index.js +13 -1
- package/core/auth/jwt.js +21 -2
- package/core/auth/manager.js +63 -14
- package/core/auth/middleware.js +4 -2
- package/core/auth/oauth.js +5 -1
- package/core/auth/tokens.js +7 -2
- package/core/auth/totp.js +42 -6
- package/core/auth/user-agent.js +2 -0
- package/core/client/adapter/datastar.js +1254 -0
- package/core/client/api.js +1033 -0
- package/core/client/controller.js +1081 -0
- package/core/client/debug.js +367 -0
- package/core/client/forms.js +1021 -0
- package/core/client/fragments.js +738 -0
- package/core/client/index.d.ts +40 -0
- package/core/client/index.js +347 -0
- package/core/client/lite.js +164 -0
- package/core/client/server-fragments.js +859 -0
- package/core/client/utils.js +144 -0
- package/core/compression/middleware.js +277 -26
- package/core/context/app-context.js +25 -3
- package/core/context/request.js +32 -4
- package/core/errors/middleware.js +14 -0
- package/core/events/dispatcher.js +33 -0
- package/core/forms/flash.js +136 -102
- package/core/health/middleware.js +36 -6
- package/core/http/pipeline.js +45 -6
- package/core/index.js +21 -7
- package/core/kernel/view.js +41 -10
- package/core/metrics/middleware.js +30 -6
- package/core/metrics/registry.js +13 -5
- package/core/orm/cache/fingerprint.js +32 -11
- package/core/orm/cache/layer.js +19 -2
- package/core/orm/hidden.js +145 -0
- package/core/orm/model.js +48 -2
- package/core/orm/query-builder.js +343 -6
- package/core/orm/query-filters.js +14 -2
- package/core/orm/repository.js +64 -13
- package/core/orm/schema-helpers.js +9 -6
- package/core/orm/transaction.js +50 -6
- package/core/orm/types.js +4 -0
- package/core/queue/adapters/database.js +184 -2
- package/core/queue/adapters/memory.js +153 -5
- package/core/queue/adapters/redis.js +59 -4
- package/core/queue/job.js +14 -1
- package/core/queue/manager.js +115 -0
- package/core/resilience/circuit-breaker.js +27 -8
- package/core/services/builtins/exchange.js +174 -7
- package/core/services/builtins/file-manager.js +36 -0
- package/core/services/builtins/mail.js +27 -0
- package/core/services/builtins/queue.js +144 -0
- package/core/services/builtins/security.js +118 -0
- package/core/services/builtins/webhook.js +110 -0
- package/core/services/executor.js +38 -16
- package/core/services/index.js +4 -1
- package/core/sse/stream.js +28 -5
- package/core/utils/timeout.js +8 -1
- package/core/validation/compiler.js +10 -7
- package/index.d.ts +1127 -71
- package/index.js +124 -8
- package/package.json +75 -26
- package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
- package/plugins/admin-panel/index.js +19 -8
- package/plugins/csrf/index.js +3 -3
- package/plugins/data-exchange/export.js +214 -0
- package/plugins/data-exchange/import.js +48 -5
- package/plugins/data-exchange/index.js +70 -28
- package/plugins/data-exchange/preview.js +266 -0
- package/plugins/data-exchange/template.js +242 -0
- package/plugins/email/admin-component.js +783 -141
- package/plugins/email/api-handlers.js +51 -1
- package/plugins/email/index.js +5 -0
- package/plugins/email/service.js +48 -0
- package/plugins/file-manager/admin-component.js +1546 -70
- package/plugins/file-manager/api-handlers.js +166 -1
- package/plugins/file-manager/core.js +598 -8
- package/plugins/file-manager/index.js +8 -0
- package/plugins/index.js +7 -0
- package/plugins/mcp/auth.js +3 -3
- package/plugins/oauth/index.js +36 -3
- package/plugins/queue/admin-component.js +1092 -0
- package/plugins/queue/api-handlers.js +248 -0
- package/plugins/queue/index.js +69 -0
- package/plugins/rest-resources/index.js +7 -2
- package/plugins/security/admin-component.js +689 -0
- package/plugins/security/api-handlers.js +169 -0
- package/plugins/security/audit.js +153 -0
- package/plugins/security/bruteforce.js +244 -0
- package/plugins/security/firewall.js +459 -0
- package/plugins/security/headers.js +214 -0
- package/plugins/security/honeypot.js +234 -0
- package/plugins/security/incident-recorder.js +137 -0
- package/plugins/security/index.js +211 -0
- package/plugins/seo-checker/analyzer.js +20 -7
- package/plugins/upload/index.js +36 -0
- package/plugins/webhooks/admin-component.js +702 -175
- package/plugins/webhooks/api-handlers.js +75 -1
- package/plugins/webhooks/dispatcher.js +290 -11
- package/plugins/webhooks/index.js +37 -2
- package/plugins/webhooks/sender.js +56 -0
- package/plugins/xlsx/engine.js +19 -4
- package/src/api/api-loader.js +19 -1
- package/src/bundle/index.js +443 -17
- package/src/client-runtime/mount.js +9 -2
- package/src/dev/api-typegen.js +1300 -0
- package/src/dev/banner.js +10 -1
- package/src/dev/colors.js +1 -1
- package/src/dev/index.js +7 -1
- package/src/dev/typegen.js +173 -17
- package/src/dev-reload/index.js +1 -1
- package/src/discovery/file-route-parser.js +17 -3
- package/src/discovery/scan-routes.js +4 -1
- package/src/file-router.js +249 -69
- package/src/helpers.js +46 -26
- package/src/njk-frontmatter.js +30 -4
- package/src/routing/cascading.js +26 -8
- package/src/routing/mount-discovered-routes.js +69 -0
- package/src/server.js +237 -66
- package/.agents/ADMIN.md +0 -426
- package/.agents/AGENTS.md +0 -96
- package/.agents/ARCHITECTURE.md +0 -163
- package/.agents/AUTH.md +0 -581
- package/.agents/CACHE.md +0 -148
- package/.agents/CLI.md +0 -649
- package/.agents/COMPRESSION.md +0 -59
- package/.agents/CONTEXT.md +0 -152
- package/.agents/CONVENTIONS.md +0 -50
- package/.agents/EARLY_HINTS.md +0 -120
- package/.agents/EMAIL.md +0 -223
- package/.agents/ERRORS.md +0 -260
- package/.agents/EVENTS.md +0 -179
- package/.agents/FLAGS.md +0 -118
- package/.agents/HEALTH.md +0 -118
- package/.agents/LIMITS.md +0 -109
- package/.agents/LOGGING.md +0 -93
- package/.agents/MCP.md +0 -103
- package/.agents/METRICS.md +0 -127
- package/.agents/MIGRATION_JOBS.md +0 -95
- package/.agents/ORM.md +0 -700
- package/.agents/PLUGINS.md +0 -729
- package/.agents/QUEUE.md +0 -290
- package/.agents/RATE_LIMIT.md +0 -147
- package/.agents/REALTIME.md +0 -213
- package/.agents/RESILIENCE.md +0 -235
- package/.agents/ROUTING.md +0 -605
- package/.agents/SCALE_OUT.md +0 -109
- package/.agents/SECRETS.md +0 -117
- package/.agents/SERVICES.md +0 -341
- package/.agents/SHUTDOWN.md +0 -74
- package/.agents/STREAMING.md +0 -108
- package/.agents/WORKFLOW.md +0 -27
- package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
- package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
- package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
- package/.agents/skills/webspresso-framework/SKILL.md +0 -89
- package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
- package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
- package/.agents/skills/webspresso-services/SKILL.md +0 -134
- package/.cursorrules +0 -14
- package/AGENTS.md +0 -203
- package/CLAUDE.md +0 -54
- package/core/kernel/run-demo.js +0 -58
- package/plugins/admin-panel/styles.js +0 -9
- package/plugins/data-exchange/export-xlsx.js +0 -119
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security Admin REST API Handlers
|
|
3
|
+
* Supplies backend endpoints for the Mithril.js Security Dashboard SPA.
|
|
4
|
+
* @module plugins/security/api-handlers
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const { auditSecurityPosture } = require('./audit');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Factory for Security API Handlers
|
|
13
|
+
*
|
|
14
|
+
* @param {Object} context
|
|
15
|
+
* @param {import('./firewall').FirewallManager} context.firewall
|
|
16
|
+
* @param {import('./incident-recorder').IncidentRecorder} context.incidentRecorder
|
|
17
|
+
* @param {Object} [context.options]
|
|
18
|
+
* @param {Object} [context.app]
|
|
19
|
+
* @returns {Record<string, Function>}
|
|
20
|
+
*/
|
|
21
|
+
function createSecurityApiHandlers(context = {}) {
|
|
22
|
+
const { firewall, incidentRecorder, options = {}, app } = context;
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
/**
|
|
26
|
+
* GET /stats
|
|
27
|
+
*/
|
|
28
|
+
async getStatsHandler(req, res) {
|
|
29
|
+
try {
|
|
30
|
+
const firewallStats = firewall.getStats();
|
|
31
|
+
const incidentStats = incidentRecorder.getStats();
|
|
32
|
+
const audit = auditSecurityPosture({ options, firewall, incidentRecorder, app });
|
|
33
|
+
|
|
34
|
+
res.json({
|
|
35
|
+
status: 'ok',
|
|
36
|
+
activeBans: firewallStats.activeBans,
|
|
37
|
+
permanentBans: firewallStats.permanentBans,
|
|
38
|
+
autoBans24h: firewallStats.autoBans24h,
|
|
39
|
+
totalBans: firewallStats.totalBans,
|
|
40
|
+
totalViolations: firewallStats.totalViolations,
|
|
41
|
+
whitelistCount: firewallStats.whitelistCount,
|
|
42
|
+
blacklistCount: firewallStats.blacklistCount,
|
|
43
|
+
incidents24h: incidentStats.last24hCount,
|
|
44
|
+
incidentBreakdown: incidentStats.breakdown,
|
|
45
|
+
securityScore: audit.score,
|
|
46
|
+
securityGrade: audit.grade,
|
|
47
|
+
passedChecks: audit.passedChecks,
|
|
48
|
+
totalChecks: audit.totalChecks,
|
|
49
|
+
});
|
|
50
|
+
} catch (err) {
|
|
51
|
+
res.status(500).json({ error: 'Failed to retrieve security stats', message: err.message });
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* GET /banned
|
|
57
|
+
*/
|
|
58
|
+
async listBannedIpsHandler(req, res) {
|
|
59
|
+
try {
|
|
60
|
+
const { page = 1, limit = 25, search, reason } = req.query;
|
|
61
|
+
const result = firewall.listBanned({ page, limit, search, reason });
|
|
62
|
+
res.json(result);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
res.status(500).json({ error: 'Failed to list banned IPs', message: err.message });
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* POST /ban
|
|
70
|
+
*/
|
|
71
|
+
async banIpHandler(req, res) {
|
|
72
|
+
try {
|
|
73
|
+
const { ip, reason, duration, meta } = req.body || {};
|
|
74
|
+
if (!ip || typeof ip !== 'string') {
|
|
75
|
+
return res.status(400).json({ error: 'IP address is required.' });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const record = firewall.ban(ip.trim(), {
|
|
79
|
+
reason: reason || 'manual_ban',
|
|
80
|
+
duration: duration || '24h',
|
|
81
|
+
meta: meta || {},
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
if (incidentRecorder) {
|
|
85
|
+
incidentRecorder.record({
|
|
86
|
+
type: 'manual_ban',
|
|
87
|
+
ip: record.ip,
|
|
88
|
+
reason: record.reason,
|
|
89
|
+
actionTaken: 'banned',
|
|
90
|
+
details: { duration, isPermanent: record.isPermanent },
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
res.status(201).json({
|
|
95
|
+
status: 'ok',
|
|
96
|
+
message: `IP ${record.ip} successfully banned.`,
|
|
97
|
+
ban: record,
|
|
98
|
+
});
|
|
99
|
+
} catch (err) {
|
|
100
|
+
res.status(400).json({ error: 'Failed to ban IP', message: err.message });
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* POST /unban
|
|
106
|
+
*/
|
|
107
|
+
async unbanIpHandler(req, res) {
|
|
108
|
+
try {
|
|
109
|
+
const ip = req.body?.ip || req.params?.ip;
|
|
110
|
+
if (!ip) {
|
|
111
|
+
return res.status(400).json({ error: 'IP address is required to unban.' });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const unbanned = firewall.unban(ip);
|
|
115
|
+
if (!unbanned) {
|
|
116
|
+
return res.status(404).json({ error: 'IP was not found in banned list.' });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
res.json({
|
|
120
|
+
status: 'ok',
|
|
121
|
+
message: `IP ${ip} unbanned successfully.`,
|
|
122
|
+
});
|
|
123
|
+
} catch (err) {
|
|
124
|
+
res.status(500).json({ error: 'Failed to unban IP', message: err.message });
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* GET /incidents
|
|
130
|
+
*/
|
|
131
|
+
async listIncidentsHandler(req, res) {
|
|
132
|
+
try {
|
|
133
|
+
const { limit = 50, type, search } = req.query;
|
|
134
|
+
const result = incidentRecorder.list({ limit, type, search });
|
|
135
|
+
res.json(result);
|
|
136
|
+
} catch (err) {
|
|
137
|
+
res.status(500).json({ error: 'Failed to retrieve security incidents', message: err.message });
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* POST /clear-incidents
|
|
143
|
+
*/
|
|
144
|
+
async clearIncidentsHandler(req, res) {
|
|
145
|
+
try {
|
|
146
|
+
incidentRecorder.clear();
|
|
147
|
+
res.json({ status: 'ok', message: 'Security incidents cleared.' });
|
|
148
|
+
} catch (err) {
|
|
149
|
+
res.status(500).json({ error: 'Failed to clear incidents', message: err.message });
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* GET /audit
|
|
155
|
+
*/
|
|
156
|
+
async getAuditHandler(req, res) {
|
|
157
|
+
try {
|
|
158
|
+
const audit = auditSecurityPosture({ options, firewall, incidentRecorder, app });
|
|
159
|
+
res.json(audit);
|
|
160
|
+
} catch (err) {
|
|
161
|
+
res.status(500).json({ error: 'Failed to run security audit', message: err.message });
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
module.exports = {
|
|
168
|
+
createSecurityApiHandlers,
|
|
169
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security Posture Audit & Checklist Engine
|
|
3
|
+
* Evaluates active security defenses, configuration headers, and cookie flags.
|
|
4
|
+
* @module plugins/security/audit
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Perform a comprehensive security posture audit
|
|
11
|
+
*
|
|
12
|
+
* @param {Object} context
|
|
13
|
+
* @param {Object} [context.app]
|
|
14
|
+
* @param {Object} [context.options] - Plugin configuration options
|
|
15
|
+
* @param {import('./firewall').FirewallManager} [context.firewall]
|
|
16
|
+
* @param {import('./incident-recorder').IncidentRecorder} [context.incidentRecorder]
|
|
17
|
+
* @returns {Object} Security report with checklist, score, grade and actionable recommendations
|
|
18
|
+
*/
|
|
19
|
+
function auditSecurityPosture(context = {}) {
|
|
20
|
+
const { options = {}, firewall, incidentRecorder, app } = context;
|
|
21
|
+
|
|
22
|
+
const checks = [];
|
|
23
|
+
let scorePoints = 0;
|
|
24
|
+
const maxPoints = 100;
|
|
25
|
+
|
|
26
|
+
// 1. Content Security Policy (CSP) (15 pts)
|
|
27
|
+
const cspEnabled = options.headers?.csp !== false && options.csp !== false;
|
|
28
|
+
checks.push({
|
|
29
|
+
id: 'csp',
|
|
30
|
+
category: 'headers',
|
|
31
|
+
title: 'Content Security Policy (CSP)',
|
|
32
|
+
description: 'Restricts script and asset execution origins to prevent XSS attacks.',
|
|
33
|
+
passed: cspEnabled,
|
|
34
|
+
weight: 15,
|
|
35
|
+
recommendation: cspEnabled ? null : 'Enable Content Security Policy in securityPlugin options ({ headers: { csp: true } }).',
|
|
36
|
+
});
|
|
37
|
+
if (cspEnabled) scorePoints += 15;
|
|
38
|
+
|
|
39
|
+
// 2. Strict-Transport-Security (HSTS) (15 pts)
|
|
40
|
+
const hstsEnabled = options.headers?.hsts !== false && options.hsts !== false;
|
|
41
|
+
checks.push({
|
|
42
|
+
id: 'hsts',
|
|
43
|
+
category: 'headers',
|
|
44
|
+
title: 'Strict-Transport-Security (HSTS)',
|
|
45
|
+
description: 'Enforces HTTPS encryption across all subdomains and modern browsers.',
|
|
46
|
+
passed: hstsEnabled,
|
|
47
|
+
weight: 15,
|
|
48
|
+
recommendation: hstsEnabled ? null : 'Configure HSTS headers to ensure all client traffic is upgraded to HTTPS.',
|
|
49
|
+
});
|
|
50
|
+
if (hstsEnabled) scorePoints += 15;
|
|
51
|
+
|
|
52
|
+
// 3. Clickjacking Protection (X-Frame-Options) (10 pts)
|
|
53
|
+
const frameGuard = options.headers?.frameGuard !== false && options.frameGuard !== false;
|
|
54
|
+
checks.push({
|
|
55
|
+
id: 'clickjacking',
|
|
56
|
+
category: 'headers',
|
|
57
|
+
title: 'Clickjacking Protection (X-Frame-Options)',
|
|
58
|
+
description: 'Prevents the application from being embedded inside malicious iframes.',
|
|
59
|
+
passed: Boolean(frameGuard),
|
|
60
|
+
weight: 10,
|
|
61
|
+
recommendation: frameGuard ? null : 'Set X-Frame-Options to SAMEORIGIN or DENY.',
|
|
62
|
+
});
|
|
63
|
+
if (frameGuard) scorePoints += 10;
|
|
64
|
+
|
|
65
|
+
// 4. MIME Sniffing Defense (X-Content-Type-Options) (10 pts)
|
|
66
|
+
const noSniff = options.headers?.noSniff !== false && options.noSniff !== false;
|
|
67
|
+
checks.push({
|
|
68
|
+
id: 'nosniff',
|
|
69
|
+
category: 'headers',
|
|
70
|
+
title: 'MIME-Sniffing Defense (nosniff)',
|
|
71
|
+
description: 'Blocks browsers from MIME-sniffing a response away from declared content type.',
|
|
72
|
+
passed: Boolean(noSniff),
|
|
73
|
+
weight: 10,
|
|
74
|
+
recommendation: noSniff ? null : 'Enable X-Content-Type-Options: nosniff header.',
|
|
75
|
+
});
|
|
76
|
+
if (noSniff) scorePoints += 10;
|
|
77
|
+
|
|
78
|
+
// 5. IP Firewall & Auto-Ban Engine (15 pts)
|
|
79
|
+
const firewallEnabled = options.firewall !== false;
|
|
80
|
+
const autoBanEnabled = firewall?.autoBanEnabled ?? (options.firewall?.autoBan?.enabled !== false);
|
|
81
|
+
checks.push({
|
|
82
|
+
id: 'firewall',
|
|
83
|
+
category: 'firewall',
|
|
84
|
+
title: 'IP Firewall & Auto-Ban Engine',
|
|
85
|
+
description: 'Automatically bans suspicious IPs exceeding violation thresholds.',
|
|
86
|
+
passed: firewallEnabled && autoBanEnabled,
|
|
87
|
+
weight: 15,
|
|
88
|
+
recommendation: (firewallEnabled && autoBanEnabled) ? null : 'Activate Firewall and Auto-Ban engine to stop repeat attackers.',
|
|
89
|
+
});
|
|
90
|
+
if (firewallEnabled && autoBanEnabled) scorePoints += 15;
|
|
91
|
+
|
|
92
|
+
// 6. Honeypot & Threat Traps (15 pts)
|
|
93
|
+
const honeypotsActive = options.honeypot !== false;
|
|
94
|
+
checks.push({
|
|
95
|
+
id: 'honeypot',
|
|
96
|
+
category: 'threats',
|
|
97
|
+
title: 'Honeypot & Exploit Scanner Traps',
|
|
98
|
+
description: 'Catches automated vulnerability scans probing for .env, .git, or CMS endpoints.',
|
|
99
|
+
passed: honeypotsActive,
|
|
100
|
+
weight: 15,
|
|
101
|
+
recommendation: honeypotsActive ? null : 'Enable honeypot trap routes to neutralize automated vulnerability scanners.',
|
|
102
|
+
});
|
|
103
|
+
if (honeypotsActive) scorePoints += 15;
|
|
104
|
+
|
|
105
|
+
// 7. Brute-Force & Credential Stuffing Guard (10 pts)
|
|
106
|
+
const bruteForceActive = options.bruteForce !== false;
|
|
107
|
+
checks.push({
|
|
108
|
+
id: 'bruteforce',
|
|
109
|
+
category: 'auth',
|
|
110
|
+
title: 'Brute-Force & Login Protection',
|
|
111
|
+
description: 'Monitors authentication endpoints and throttles repeated credential guessing.',
|
|
112
|
+
passed: bruteForceActive,
|
|
113
|
+
weight: 10,
|
|
114
|
+
recommendation: bruteForceActive ? null : 'Enable brute-force protection across authentication routes.',
|
|
115
|
+
});
|
|
116
|
+
if (bruteForceActive) scorePoints += 10;
|
|
117
|
+
|
|
118
|
+
// 8. Session Secret Strength (10 pts)
|
|
119
|
+
const sessionSecret = process.env.SESSION_SECRET || '';
|
|
120
|
+
const secretStrong = sessionSecret.length >= 32;
|
|
121
|
+
checks.push({
|
|
122
|
+
id: 'secret_strength',
|
|
123
|
+
category: 'env',
|
|
124
|
+
title: 'Session Secret Key Entropy',
|
|
125
|
+
description: 'Ensures cryptographic keys have at least 32 characters of high-entropy random bytes.',
|
|
126
|
+
passed: secretStrong,
|
|
127
|
+
weight: 10,
|
|
128
|
+
recommendation: secretStrong ? null : 'Generate a strong 32+ character random SESSION_SECRET in production.',
|
|
129
|
+
});
|
|
130
|
+
if (secretStrong) scorePoints += 10;
|
|
131
|
+
|
|
132
|
+
const score = Math.round((scorePoints / maxPoints) * 100);
|
|
133
|
+
|
|
134
|
+
let grade = 'F';
|
|
135
|
+
if (score >= 95) grade = 'A+';
|
|
136
|
+
else if (score >= 85) grade = 'A';
|
|
137
|
+
else if (score >= 70) grade = 'B';
|
|
138
|
+
else if (score >= 50) grade = 'C';
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
score,
|
|
142
|
+
grade,
|
|
143
|
+
checks,
|
|
144
|
+
totalChecks: checks.length,
|
|
145
|
+
passedChecks: checks.filter(c => c.passed).length,
|
|
146
|
+
failedChecks: checks.filter(c => !c.passed).length,
|
|
147
|
+
auditedAt: new Date().toISOString(),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
module.exports = {
|
|
152
|
+
auditSecurityPosture,
|
|
153
|
+
};
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brute-Force & Credential Stuffing Guard
|
|
3
|
+
* Zero-dependency native Node.js implementation.
|
|
4
|
+
* @module plugins/security/bruteforce
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const { extractClientIp, parseWindow, formatResetSeconds } = require('../../core/rate-limit/utils');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Default target routes subject to brute-force monitoring
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_AUTH_ROUTES = [
|
|
15
|
+
'/api/auth/login',
|
|
16
|
+
'/_admin/api/auth/login',
|
|
17
|
+
'/auth/login',
|
|
18
|
+
'/login',
|
|
19
|
+
'/api/auth/reset-password',
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Brute-force attempt tracker
|
|
24
|
+
*/
|
|
25
|
+
class BruteForceTracker {
|
|
26
|
+
/**
|
|
27
|
+
* @param {Object} [options]
|
|
28
|
+
* @param {number} [options.maxAttempts=5] - Maximum failed attempts before lockout
|
|
29
|
+
* @param {string|number} [options.window='15m'] - Sliding tracking window
|
|
30
|
+
* @param {string|number} [options.lockout='15m'] - Lockout duration
|
|
31
|
+
* @param {boolean} [options.progressiveDelay=true] - Add artificial delay on successive failures
|
|
32
|
+
* @param {number} [options.delayStepMs=200] - Milliseconds delay per failure
|
|
33
|
+
*/
|
|
34
|
+
constructor(options = {}) {
|
|
35
|
+
this.maxAttempts = options.maxAttempts || 5;
|
|
36
|
+
this.windowMs = parseWindow(options.window || '15m');
|
|
37
|
+
this.lockoutMs = parseWindow(options.lockout || '15m');
|
|
38
|
+
this.progressiveDelay = options.progressiveDelay !== false;
|
|
39
|
+
this.delayStepMs = options.delayStepMs || 200;
|
|
40
|
+
|
|
41
|
+
this.attempts = new Map(); // ip -> { count: number, firstAttempt: number, lockedUntil: number|null }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Check if an IP is locked out
|
|
46
|
+
* @param {string} ip
|
|
47
|
+
* @returns {{ locked: boolean, remainingSeconds: number, attempts: number }}
|
|
48
|
+
*/
|
|
49
|
+
check(ip) {
|
|
50
|
+
const record = this.attempts.get(ip);
|
|
51
|
+
if (!record) {
|
|
52
|
+
return { locked: false, remainingSeconds: 0, attempts: 0 };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
|
|
57
|
+
// Check if lockout has expired
|
|
58
|
+
if (record.lockedUntil) {
|
|
59
|
+
if (now < record.lockedUntil) {
|
|
60
|
+
const remainingSeconds = Math.ceil((record.lockedUntil - now) / 1000);
|
|
61
|
+
return { locked: true, remainingSeconds, attempts: record.count };
|
|
62
|
+
}
|
|
63
|
+
// Lockout expired, reset
|
|
64
|
+
this.attempts.delete(ip);
|
|
65
|
+
return { locked: false, remainingSeconds: 0, attempts: 0 };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Check if tracking window has expired
|
|
69
|
+
if (now - record.firstAttempt > this.windowMs) {
|
|
70
|
+
this.attempts.delete(ip);
|
|
71
|
+
return { locked: false, remainingSeconds: 0, attempts: 0 };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return { locked: false, remainingSeconds: 0, attempts: record.count };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Record a failed login attempt
|
|
79
|
+
* @param {string} ip
|
|
80
|
+
* @returns {{ locked: boolean, attempts: number, lockedUntil: number|null }}
|
|
81
|
+
*/
|
|
82
|
+
recordFailure(ip) {
|
|
83
|
+
const now = Date.now();
|
|
84
|
+
let record = this.attempts.get(ip);
|
|
85
|
+
|
|
86
|
+
if (!record || (now - record.firstAttempt > this.windowMs && !record.lockedUntil)) {
|
|
87
|
+
record = { count: 1, firstAttempt: now, lockedUntil: null };
|
|
88
|
+
} else {
|
|
89
|
+
record.count++;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let locked = false;
|
|
93
|
+
if (record.count >= this.maxAttempts) {
|
|
94
|
+
record.lockedUntil = now + this.lockoutMs;
|
|
95
|
+
locked = true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
this.attempts.set(ip, record);
|
|
99
|
+
return {
|
|
100
|
+
locked,
|
|
101
|
+
attempts: record.count,
|
|
102
|
+
lockedUntil: record.lockedUntil,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Reset attempts on successful login
|
|
108
|
+
* @param {string} ip
|
|
109
|
+
*/
|
|
110
|
+
recordSuccess(ip) {
|
|
111
|
+
this.attempts.delete(ip);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Get delay in milliseconds to apply to the request
|
|
116
|
+
* @param {string} ip
|
|
117
|
+
* @returns {number}
|
|
118
|
+
*/
|
|
119
|
+
getDelayMs(ip) {
|
|
120
|
+
if (!this.progressiveDelay) return 0;
|
|
121
|
+
const record = this.attempts.get(ip);
|
|
122
|
+
if (!record || record.count <= 1) return 0;
|
|
123
|
+
return Math.min(2000, (record.count - 1) * this.delayStepMs);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Create Brute-Force guard middleware
|
|
129
|
+
*
|
|
130
|
+
* @param {Object} [options]
|
|
131
|
+
* @param {import('./firewall').FirewallManager} [options.firewall]
|
|
132
|
+
* @param {import('./incident-recorder').IncidentRecorder} [options.incidentRecorder]
|
|
133
|
+
* @param {string[]} [options.routes] - Target routes to monitor
|
|
134
|
+
* @param {number} [options.maxAttempts=5]
|
|
135
|
+
* @param {string|number} [options.window='15m']
|
|
136
|
+
* @param {string|number} [options.lockout='15m']
|
|
137
|
+
* @param {boolean} [options.banOnExceeded=false] - Auto-ban on firewall when brute-force threshold reached
|
|
138
|
+
* @returns {Function} Express middleware
|
|
139
|
+
*/
|
|
140
|
+
function createBruteForceMiddleware(options = {}) {
|
|
141
|
+
const routes = (options.routes || DEFAULT_AUTH_ROUTES).map(r => r.toLowerCase());
|
|
142
|
+
const tracker = new BruteForceTracker(options);
|
|
143
|
+
const { firewall, incidentRecorder, banOnExceeded = false } = options;
|
|
144
|
+
|
|
145
|
+
return function bruteForceMiddleware(req, res, next) {
|
|
146
|
+
const rawPath = (req.path || req.url || '').split('?')[0].toLowerCase();
|
|
147
|
+
const isTargetRoute = routes.some(target => rawPath === target || rawPath.endsWith(target));
|
|
148
|
+
|
|
149
|
+
if (!isTargetRoute) {
|
|
150
|
+
return next();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const clientIp = extractClientIp(req);
|
|
154
|
+
|
|
155
|
+
if (firewall && firewall.isWhitelisted(clientIp)) {
|
|
156
|
+
return next();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 1. Check if IP is currently locked out
|
|
160
|
+
const status = tracker.check(clientIp);
|
|
161
|
+
if (status.locked) {
|
|
162
|
+
res.setHeader('Retry-After', String(status.remainingSeconds));
|
|
163
|
+
|
|
164
|
+
if (incidentRecorder) {
|
|
165
|
+
incidentRecorder.record({
|
|
166
|
+
type: 'bruteforce',
|
|
167
|
+
ip: clientIp,
|
|
168
|
+
method: req.method,
|
|
169
|
+
path: req.originalUrl || req.url,
|
|
170
|
+
userAgent: req.headers?.['user-agent'],
|
|
171
|
+
reason: `Brute-force lockout active (${status.attempts} failed attempts)`,
|
|
172
|
+
actionTaken: 'throttled',
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
res.status(429).json({
|
|
177
|
+
error: 'Too Many Requests',
|
|
178
|
+
message: 'Account authentication temporarily locked due to multiple failed attempts. Please try again later.',
|
|
179
|
+
retryAfter: status.remainingSeconds,
|
|
180
|
+
});
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// 2. Apply progressive delay if needed
|
|
185
|
+
const delayMs = tracker.getDelayMs(clientIp);
|
|
186
|
+
const continueExecution = () => {
|
|
187
|
+
// Intercept response finish
|
|
188
|
+
res.on('finish', () => {
|
|
189
|
+
const statusCode = res.statusCode;
|
|
190
|
+
|
|
191
|
+
// HTTP 401 Unauthorized indicates failed credential check
|
|
192
|
+
if (statusCode === 401) {
|
|
193
|
+
const result = tracker.recordFailure(clientIp);
|
|
194
|
+
|
|
195
|
+
if (result.locked) {
|
|
196
|
+
if (incidentRecorder) {
|
|
197
|
+
incidentRecorder.record({
|
|
198
|
+
type: 'bruteforce',
|
|
199
|
+
ip: clientIp,
|
|
200
|
+
method: req.method,
|
|
201
|
+
path: req.originalUrl || req.url,
|
|
202
|
+
userAgent: req.headers?.['user-agent'],
|
|
203
|
+
reason: `Brute-force threshold exceeded (${result.attempts} failures)`,
|
|
204
|
+
actionTaken: banOnExceeded ? 'banned' : 'throttled',
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (firewall) {
|
|
209
|
+
if (banOnExceeded) {
|
|
210
|
+
firewall.ban(clientIp, {
|
|
211
|
+
reason: 'auto_ban: brute_force threshold exceeded',
|
|
212
|
+
duration: tracker.lockoutMs,
|
|
213
|
+
});
|
|
214
|
+
} else {
|
|
215
|
+
firewall.recordViolation(clientIp, {
|
|
216
|
+
type: 'bruteforce',
|
|
217
|
+
weight: 2,
|
|
218
|
+
path: req.originalUrl || req.url,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
} else if (statusCode >= 200 && statusCode < 300) {
|
|
224
|
+
// Successful login resets tracker
|
|
225
|
+
tracker.recordSuccess(clientIp);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
next();
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
if (delayMs > 0) {
|
|
233
|
+
setTimeout(continueExecution, delayMs);
|
|
234
|
+
} else {
|
|
235
|
+
continueExecution();
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
module.exports = {
|
|
241
|
+
createBruteForceMiddleware,
|
|
242
|
+
BruteForceTracker,
|
|
243
|
+
DEFAULT_AUTH_ROUTES,
|
|
244
|
+
};
|