webspresso 0.0.108 → 0.0.110

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.
Files changed (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -3
  3. package/bin/commands/add-esbuild.js +7 -3
  4. package/bin/commands/add-tailwind.js +9 -5
  5. package/bin/commands/build.js +20 -4
  6. package/bin/commands/dev.js +57 -7
  7. package/bin/commands/doctor.js +42 -1
  8. package/bin/commands/favicon-generate.js +10 -3
  9. package/bin/commands/new.js +8 -3
  10. package/bin/commands/start.js +3 -1
  11. package/bin/utils/add-command.js +16 -0
  12. package/core/app.js +45 -3
  13. package/core/auth/authenticate.js +3 -3
  14. package/core/auth/hash.js +167 -43
  15. package/core/auth/index.js +13 -1
  16. package/core/auth/jwt.js +21 -2
  17. package/core/auth/manager.js +63 -14
  18. package/core/auth/middleware.js +4 -2
  19. package/core/auth/oauth.js +5 -1
  20. package/core/auth/tokens.js +7 -2
  21. package/core/auth/totp.js +42 -6
  22. package/core/auth/user-agent.js +2 -0
  23. package/core/client/adapter/datastar.js +1401 -0
  24. package/core/client/api.js +1337 -0
  25. package/core/client/controller.js +1706 -0
  26. package/core/client/debug.js +367 -0
  27. package/core/client/devtool.js +1134 -0
  28. package/core/client/forms.js +1164 -0
  29. package/core/client/fragments.js +894 -0
  30. package/core/client/index.d.ts +59 -0
  31. package/core/client/index.js +391 -0
  32. package/core/client/lite.js +175 -0
  33. package/core/client/server-fragments.js +868 -0
  34. package/core/client/storage.js +339 -0
  35. package/core/client/utils.js +281 -0
  36. package/core/compression/middleware.js +277 -26
  37. package/core/context/app-context.js +25 -3
  38. package/core/context/request.js +32 -4
  39. package/core/errors/middleware.js +14 -0
  40. package/core/events/dispatcher.js +33 -0
  41. package/core/forms/flash.js +136 -102
  42. package/core/health/middleware.js +36 -6
  43. package/core/http/pipeline.js +45 -6
  44. package/core/index.js +25 -7
  45. package/core/kernel/view.js +41 -10
  46. package/core/metrics/middleware.js +30 -6
  47. package/core/metrics/registry.js +13 -5
  48. package/core/orm/cache/fingerprint.js +32 -11
  49. package/core/orm/cache/layer.js +19 -2
  50. package/core/orm/hidden.js +145 -0
  51. package/core/orm/model.js +48 -2
  52. package/core/orm/query-builder.js +343 -6
  53. package/core/orm/query-filters.js +14 -2
  54. package/core/orm/repository.js +64 -13
  55. package/core/orm/schema-helpers.js +9 -6
  56. package/core/orm/transaction.js +50 -6
  57. package/core/orm/types.js +4 -0
  58. package/core/queue/adapters/database.js +184 -2
  59. package/core/queue/adapters/memory.js +153 -5
  60. package/core/queue/adapters/redis.js +59 -4
  61. package/core/queue/job.js +14 -1
  62. package/core/queue/manager.js +115 -0
  63. package/core/resilience/circuit-breaker.js +27 -8
  64. package/core/services/builtins/exchange.js +174 -7
  65. package/core/services/builtins/file-manager.js +36 -0
  66. package/core/services/builtins/mail.js +27 -0
  67. package/core/services/builtins/queue.js +144 -0
  68. package/core/services/builtins/security.js +118 -0
  69. package/core/services/builtins/webhook.js +110 -0
  70. package/core/services/executor.js +38 -16
  71. package/core/services/index.js +4 -1
  72. package/core/sse/stream.js +28 -5
  73. package/core/utils/timeout.js +8 -1
  74. package/core/validation/compiler.js +10 -7
  75. package/index.d.ts +1320 -74
  76. package/index.js +128 -8
  77. package/package.json +75 -27
  78. package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
  79. package/plugins/admin-panel/index.js +19 -8
  80. package/plugins/csrf/index.js +3 -3
  81. package/plugins/data-exchange/export.js +214 -0
  82. package/plugins/data-exchange/import.js +48 -5
  83. package/plugins/data-exchange/index.js +70 -28
  84. package/plugins/data-exchange/preview.js +266 -0
  85. package/plugins/data-exchange/template.js +242 -0
  86. package/plugins/email/admin-component.js +783 -141
  87. package/plugins/email/api-handlers.js +51 -1
  88. package/plugins/email/index.js +5 -0
  89. package/plugins/email/service.js +48 -0
  90. package/plugins/file-manager/admin-component.js +1546 -70
  91. package/plugins/file-manager/api-handlers.js +166 -1
  92. package/plugins/file-manager/core.js +598 -8
  93. package/plugins/file-manager/index.js +8 -0
  94. package/plugins/index.js +7 -0
  95. package/plugins/mcp/auth.js +3 -3
  96. package/plugins/oauth/index.js +36 -3
  97. package/plugins/queue/admin-component.js +1092 -0
  98. package/plugins/queue/api-handlers.js +248 -0
  99. package/plugins/queue/index.js +69 -0
  100. package/plugins/rest-resources/index.js +7 -2
  101. package/plugins/security/admin-component.js +689 -0
  102. package/plugins/security/api-handlers.js +169 -0
  103. package/plugins/security/audit.js +153 -0
  104. package/plugins/security/bruteforce.js +244 -0
  105. package/plugins/security/firewall.js +459 -0
  106. package/plugins/security/headers.js +214 -0
  107. package/plugins/security/honeypot.js +234 -0
  108. package/plugins/security/incident-recorder.js +137 -0
  109. package/plugins/security/index.js +211 -0
  110. package/plugins/seo-checker/analyzer.js +20 -7
  111. package/plugins/upload/index.js +36 -0
  112. package/plugins/webhooks/admin-component.js +702 -175
  113. package/plugins/webhooks/api-handlers.js +75 -1
  114. package/plugins/webhooks/dispatcher.js +290 -11
  115. package/plugins/webhooks/index.js +37 -2
  116. package/plugins/webhooks/sender.js +56 -0
  117. package/plugins/xlsx/engine.js +19 -4
  118. package/src/api/api-loader.js +19 -1
  119. package/src/bundle/index.js +443 -17
  120. package/src/client-runtime/bootstrap-swup.js +9 -0
  121. package/src/client-runtime/mount.js +15 -20
  122. package/src/client-runtime/resolve.js +3 -2
  123. package/src/dev/api-typegen.js +1300 -0
  124. package/src/dev/banner.js +10 -1
  125. package/src/dev/colors.js +1 -1
  126. package/src/dev/index.js +7 -1
  127. package/src/dev/typegen.js +173 -17
  128. package/src/dev-reload/index.js +1 -1
  129. package/src/discovery/file-route-parser.js +17 -3
  130. package/src/discovery/scan-routes.js +4 -1
  131. package/src/file-router.js +253 -69
  132. package/src/helpers.js +46 -26
  133. package/src/njk-frontmatter.js +30 -4
  134. package/src/routing/cascading.js +26 -8
  135. package/src/routing/mount-discovered-routes.js +76 -0
  136. package/src/server.js +231 -70
  137. package/views/partials/webspresso-client-runtime.njk +1 -9
  138. package/.agents/ADMIN.md +0 -426
  139. package/.agents/AGENTS.md +0 -96
  140. package/.agents/ARCHITECTURE.md +0 -163
  141. package/.agents/AUTH.md +0 -581
  142. package/.agents/CACHE.md +0 -148
  143. package/.agents/CLI.md +0 -649
  144. package/.agents/COMPRESSION.md +0 -59
  145. package/.agents/CONTEXT.md +0 -152
  146. package/.agents/CONVENTIONS.md +0 -50
  147. package/.agents/EARLY_HINTS.md +0 -120
  148. package/.agents/EMAIL.md +0 -223
  149. package/.agents/ERRORS.md +0 -260
  150. package/.agents/EVENTS.md +0 -179
  151. package/.agents/FLAGS.md +0 -118
  152. package/.agents/HEALTH.md +0 -118
  153. package/.agents/LIMITS.md +0 -109
  154. package/.agents/LOGGING.md +0 -93
  155. package/.agents/MCP.md +0 -103
  156. package/.agents/METRICS.md +0 -127
  157. package/.agents/MIGRATION_JOBS.md +0 -95
  158. package/.agents/ORM.md +0 -700
  159. package/.agents/PLUGINS.md +0 -729
  160. package/.agents/QUEUE.md +0 -290
  161. package/.agents/RATE_LIMIT.md +0 -147
  162. package/.agents/REALTIME.md +0 -213
  163. package/.agents/RESILIENCE.md +0 -235
  164. package/.agents/ROUTING.md +0 -605
  165. package/.agents/SCALE_OUT.md +0 -109
  166. package/.agents/SECRETS.md +0 -117
  167. package/.agents/SERVICES.md +0 -341
  168. package/.agents/SHUTDOWN.md +0 -74
  169. package/.agents/STREAMING.md +0 -108
  170. package/.agents/WORKFLOW.md +0 -27
  171. package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
  172. package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
  173. package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
  174. package/.agents/skills/webspresso-framework/SKILL.md +0 -89
  175. package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
  176. package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
  177. package/.agents/skills/webspresso-services/SKILL.md +0 -134
  178. package/.cursorrules +0 -14
  179. package/AGENTS.md +0 -203
  180. package/CLAUDE.md +0 -54
  181. package/core/kernel/run-demo.js +0 -58
  182. package/plugins/admin-panel/styles.js +0 -9
  183. package/plugins/data-exchange/export-xlsx.js +0 -119
  184. package/src/client-runtime/bootstrap-alpine-swup.js +0 -34
@@ -0,0 +1,459 @@
1
+ /**
2
+ * IP Firewall, Blacklist, Whitelist, CIDR Matching & Auto-Ban Engine
3
+ * Zero-dependency native Node.js implementation.
4
+ * @module plugins/security/firewall
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ const EventEmitter = require('events');
10
+ const { extractClientIp, parseWindow } = require('../../core/rate-limit/utils');
11
+
12
+ /**
13
+ * Normalize IP address (strip IPv6 mapped IPv4 prefix, handle localhost)
14
+ * @param {string} ip
15
+ * @returns {string}
16
+ */
17
+ function normalizeIp(ip) {
18
+ if (!ip || typeof ip !== 'string') return '127.0.0.1';
19
+ let clean = ip.trim();
20
+
21
+ // Strip IPv4-mapped IPv6 addresses (e.g. ::ffff:192.168.1.1)
22
+ if (clean.startsWith('::ffff:')) {
23
+ clean = clean.slice(7);
24
+ }
25
+
26
+ // IPv6 localhost
27
+ if (clean === '::1') {
28
+ return '127.0.0.1';
29
+ }
30
+
31
+ return clean;
32
+ }
33
+
34
+ /**
35
+ * Convert IPv4 address to 32-bit unsigned integer
36
+ * @param {string} ip
37
+ * @returns {number}
38
+ */
39
+ function ipToLong(ip) {
40
+ return ip.split('.').reduce((acc, octet) => {
41
+ return ((acc << 8) + parseInt(octet, 10)) >>> 0;
42
+ }, 0);
43
+ }
44
+
45
+ /**
46
+ * Check if an IP matches a target IP or CIDR subnet (e.g. '192.168.1.0/24')
47
+ * @param {string} ip
48
+ * @param {string} pattern
49
+ * @returns {boolean}
50
+ */
51
+ function matchIpOrCidr(ip, pattern) {
52
+ const normIp = normalizeIp(ip);
53
+ const normPattern = normalizeIp(pattern);
54
+
55
+ if (!normPattern.includes('/')) {
56
+ return normIp === normPattern;
57
+ }
58
+
59
+ const [range, bitsStr] = normPattern.split('/');
60
+ const bits = parseInt(bitsStr, 10);
61
+
62
+ // Validate IPv4 CIDR
63
+ if (Number.isNaN(bits) || bits < 0 || bits > 32) {
64
+ return false;
65
+ }
66
+
67
+ // Exact 32 bits
68
+ if (bits === 32) {
69
+ return normIp === range;
70
+ }
71
+ if (bits === 0) {
72
+ return true;
73
+ }
74
+
75
+ const mask = bits === 0 ? 0 : (~((1 << (32 - bits)) - 1)) >>> 0;
76
+ const ipLong = ipToLong(normIp);
77
+ const rangeLong = ipToLong(range);
78
+
79
+ return ((ipLong & mask) >>> 0) === ((rangeLong & mask) >>> 0);
80
+ }
81
+
82
+ /**
83
+ * In-Memory Firewall & Ban Store
84
+ */
85
+ class MemoryFirewallStore {
86
+ constructor() {
87
+ this.banned = new Map(); // ip -> { ip, reason, bannedAt, expiresAt, isPermanent, violations, meta }
88
+ this.violations = new Map(); // ip -> [{ timestamp, type, meta }]
89
+ this.totalBansCount = 0;
90
+ this.totalViolationsCount = 0;
91
+ }
92
+
93
+ setBan(ip, record) {
94
+ this.banned.set(ip, record);
95
+ this.totalBansCount++;
96
+ }
97
+
98
+ removeBan(ip) {
99
+ return this.banned.delete(ip);
100
+ }
101
+
102
+ getBan(ip) {
103
+ const record = this.banned.get(ip);
104
+ if (!record) return null;
105
+
106
+ if (!record.isPermanent && record.expiresAt && Date.now() > record.expiresAt) {
107
+ this.banned.delete(ip);
108
+ return null;
109
+ }
110
+
111
+ return record;
112
+ }
113
+
114
+ getAllBans() {
115
+ const now = Date.now();
116
+ const active = [];
117
+ for (const [ip, record] of this.banned.entries()) {
118
+ if (!record.isPermanent && record.expiresAt && now > record.expiresAt) {
119
+ this.banned.delete(ip);
120
+ } else {
121
+ active.push(record);
122
+ }
123
+ }
124
+ return active;
125
+ }
126
+
127
+ clear() {
128
+ this.banned.clear();
129
+ this.violations.clear();
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Firewall & Auto-Ban Manager
135
+ */
136
+ class FirewallManager extends EventEmitter {
137
+ /**
138
+ * @param {Object} [options]
139
+ * @param {string[]} [options.whitelist=[]] - Whitelisted IPs or CIDRs
140
+ * @param {string[]} [options.blacklist=[]] - Static banned IPs or CIDRs
141
+ * @param {Object} [options.autoBan] - Auto-ban configuration
142
+ * @param {boolean} [options.autoBan.enabled=true]
143
+ * @param {number} [options.autoBan.threshold=5] - Number of violations to trigger ban
144
+ * @param {string|number} [options.autoBan.window='5m'] - Sliding window
145
+ * @param {string|number} [options.autoBan.duration='1h'] - Ban duration
146
+ */
147
+ constructor(options = {}) {
148
+ super();
149
+
150
+ this.whitelist = Array.isArray(options.whitelist) ? [...options.whitelist] : [];
151
+ this.blacklist = Array.isArray(options.blacklist) ? [...options.blacklist] : [];
152
+
153
+ const autoBanConfig = options.autoBan || {};
154
+ this.autoBanEnabled = autoBanConfig.enabled !== false;
155
+ this.autoBanThreshold = autoBanConfig.threshold || 5;
156
+ this.autoBanWindowMs = parseWindow(autoBanConfig.window || '5m');
157
+ this.autoBanDurationMs = parseWindow(autoBanConfig.duration || '1h');
158
+
159
+ this.store = new MemoryFirewallStore();
160
+
161
+ // Initialize static blacklist
162
+ for (const item of this.blacklist) {
163
+ if (!item.includes('/')) {
164
+ this.store.setBan(normalizeIp(item), {
165
+ ip: normalizeIp(item),
166
+ reason: 'static_blacklist',
167
+ bannedAt: Date.now(),
168
+ expiresAt: null,
169
+ isPermanent: true,
170
+ violations: 0,
171
+ });
172
+ }
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Check if an IP is whitelisted
178
+ * @param {string} ip
179
+ * @returns {boolean}
180
+ */
181
+ isWhitelisted(ip) {
182
+ const cleanIp = normalizeIp(ip);
183
+ for (const pattern of this.whitelist) {
184
+ if (matchIpOrCidr(cleanIp, pattern)) {
185
+ return true;
186
+ }
187
+ }
188
+ return false;
189
+ }
190
+
191
+ /**
192
+ * Check if an IP is banned (either static blacklist, CIDR or active dynamic ban)
193
+ * @param {string} ip
194
+ * @returns {{ banned: boolean, reason?: string, expiresAt?: number, isPermanent?: boolean, remainingMs?: number }}
195
+ */
196
+ isBanned(ip) {
197
+ const cleanIp = normalizeIp(ip);
198
+
199
+ // Whitelist takes absolute precedence
200
+ if (this.isWhitelisted(cleanIp)) {
201
+ return { banned: false };
202
+ }
203
+
204
+ // 1. Check static blacklist CIDR patterns
205
+ for (const pattern of this.blacklist) {
206
+ if (pattern.includes('/') && matchIpOrCidr(cleanIp, pattern)) {
207
+ return {
208
+ banned: true,
209
+ reason: 'static_blacklist_cidr',
210
+ isPermanent: true,
211
+ expiresAt: null,
212
+ };
213
+ }
214
+ }
215
+
216
+ // 2. Check dynamic or exact static ban store
217
+ const ban = this.store.getBan(cleanIp);
218
+ if (!ban) {
219
+ return { banned: false };
220
+ }
221
+
222
+ const remainingMs = ban.isPermanent ? null : Math.max(0, ban.expiresAt - Date.now());
223
+
224
+ return {
225
+ banned: true,
226
+ reason: ban.reason,
227
+ bannedAt: ban.bannedAt,
228
+ expiresAt: ban.expiresAt,
229
+ isPermanent: ban.isPermanent,
230
+ remainingMs,
231
+ violations: ban.violations,
232
+ meta: ban.meta,
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Manually or programmatically ban an IP
238
+ * @param {string} ip
239
+ * @param {Object} [options]
240
+ * @param {string} [options.reason='manual_ban']
241
+ * @param {string|number} [options.duration] - Duration string ('1h', '24h', 'permanent', 0)
242
+ * @param {Object} [options.meta]
243
+ * @returns {Object} Ban record
244
+ */
245
+ ban(ip, options = {}) {
246
+ const cleanIp = normalizeIp(ip);
247
+
248
+ if (this.isWhitelisted(cleanIp)) {
249
+ throw new Error(`Cannot ban whitelisted IP: ${cleanIp}`);
250
+ }
251
+
252
+ const duration = options.duration;
253
+ let expiresAt = null;
254
+ let isPermanent = false;
255
+
256
+ if (duration === 'permanent' || duration === 0 || duration === '0' || duration === null) {
257
+ isPermanent = true;
258
+ } else {
259
+ const ms = parseWindow(duration || this.autoBanDurationMs);
260
+ expiresAt = Date.now() + ms;
261
+ }
262
+
263
+ const record = {
264
+ ip: cleanIp,
265
+ reason: options.reason || 'manual_ban',
266
+ bannedAt: Date.now(),
267
+ expiresAt,
268
+ isPermanent,
269
+ violations: options.violations || 0,
270
+ meta: options.meta || {},
271
+ };
272
+
273
+ this.store.setBan(cleanIp, record);
274
+ this.emit('ip:banned', record);
275
+
276
+ return record;
277
+ }
278
+
279
+ /**
280
+ * Remove ban for an IP
281
+ * @param {string} ip
282
+ * @returns {boolean}
283
+ */
284
+ unban(ip) {
285
+ const cleanIp = normalizeIp(ip);
286
+ const removed = this.store.removeBan(cleanIp);
287
+
288
+ // Also remove from static blacklist array if present
289
+ const idx = this.blacklist.indexOf(cleanIp);
290
+ if (idx !== -1) {
291
+ this.blacklist.splice(idx, 1);
292
+ }
293
+
294
+ if (removed) {
295
+ this.emit('ip:unbanned', { ip: cleanIp });
296
+ }
297
+
298
+ return removed;
299
+ }
300
+
301
+ /**
302
+ * Record a security violation and check auto-ban threshold
303
+ * @param {string} ip
304
+ * @param {Object} violation
305
+ * @param {string} violation.type - 'honeypot'|'path_traversal'|'bad_bot'|'bruteforce'|'rate_limit'
306
+ * @param {number} [violation.weight=1]
307
+ * @param {string} [violation.path]
308
+ * @param {string} [violation.userAgent]
309
+ * @returns {{ banned: boolean, count: number, autoBanned: boolean }}
310
+ */
311
+ recordViolation(ip, violation = {}) {
312
+ const cleanIp = normalizeIp(ip);
313
+
314
+ if (this.isWhitelisted(cleanIp)) {
315
+ return { banned: false, count: 0, autoBanned: false };
316
+ }
317
+
318
+ this.store.totalViolationsCount++;
319
+ const now = Date.now();
320
+ const windowStart = now - this.autoBanWindowMs;
321
+
322
+ let history = this.store.violations.get(cleanIp) || [];
323
+ // Prune entries outside sliding window
324
+ history = history.filter(v => v.timestamp >= windowStart);
325
+
326
+ const weight = violation.weight || 1;
327
+ for (let i = 0; i < weight; i++) {
328
+ history.push({
329
+ timestamp: now,
330
+ type: violation.type || 'generic_violation',
331
+ path: violation.path,
332
+ userAgent: violation.userAgent,
333
+ });
334
+ }
335
+
336
+ this.store.violations.set(cleanIp, history);
337
+ const count = history.length;
338
+
339
+ let autoBanned = false;
340
+ if (this.autoBanEnabled && count >= this.autoBanThreshold) {
341
+ const banRecord = this.ban(cleanIp, {
342
+ reason: `auto_ban: threshold exceeded (${violation.type || 'violations'})`,
343
+ duration: this.autoBanDurationMs,
344
+ violations: count,
345
+ meta: {
346
+ lastPath: violation.path,
347
+ userAgent: violation.userAgent,
348
+ },
349
+ });
350
+ autoBanned = true;
351
+ this.emit('firewall:auto_ban', banRecord);
352
+ }
353
+
354
+ return {
355
+ banned: autoBanned || this.isBanned(cleanIp).banned,
356
+ count,
357
+ autoBanned,
358
+ };
359
+ }
360
+
361
+ /**
362
+ * List banned IPs with pagination and search
363
+ * @param {Object} [filter]
364
+ * @param {number} [filter.page=1]
365
+ * @param {number} [filter.limit=25]
366
+ * @param {string} [filter.search]
367
+ * @param {string} [filter.reason]
368
+ * @returns {Object}
369
+ */
370
+ listBanned(filter = {}) {
371
+ const page = Math.max(1, parseInt(filter.page, 10) || 1);
372
+ const limit = Math.max(1, Math.min(100, parseInt(filter.limit, 10) || 25));
373
+ const search = filter.search ? String(filter.search).trim().toLowerCase() : null;
374
+ const reasonFilter = filter.reason ? String(filter.reason).trim().toLowerCase() : null;
375
+
376
+ let items = this.store.getAllBans();
377
+
378
+ if (search) {
379
+ items = items.filter(b => b.ip.toLowerCase().includes(search) || (b.reason && b.reason.toLowerCase().includes(search)));
380
+ }
381
+
382
+ if (reasonFilter && reasonFilter !== 'all') {
383
+ items = items.filter(b => b.reason && b.reason.toLowerCase().includes(reasonFilter));
384
+ }
385
+
386
+ // Sort newest first
387
+ items.sort((a, b) => b.bannedAt - a.bannedAt);
388
+
389
+ const total = items.length;
390
+ const totalPages = Math.ceil(total / limit) || 1;
391
+ const offset = (page - 1) * limit;
392
+ const paginated = items.slice(offset, offset + limit);
393
+
394
+ return {
395
+ items: paginated,
396
+ total,
397
+ page,
398
+ limit,
399
+ totalPages,
400
+ };
401
+ }
402
+
403
+ /**
404
+ * Get overall firewall statistics
405
+ * @returns {Object}
406
+ */
407
+ getStats() {
408
+ const activeBans = this.store.getAllBans();
409
+ const now = Date.now();
410
+ const oneDayAgo = now - 24 * 60 * 60 * 1000;
411
+
412
+ const autoBans24h = activeBans.filter(b => b.bannedAt >= oneDayAgo && b.reason?.startsWith('auto_ban')).length;
413
+ const permanentBans = activeBans.filter(b => b.isPermanent).length;
414
+
415
+ return {
416
+ activeBans: activeBans.length,
417
+ permanentBans,
418
+ autoBans24h,
419
+ totalBans: this.store.totalBansCount,
420
+ totalViolations: this.store.totalViolationsCount,
421
+ whitelistCount: this.whitelist.length,
422
+ blacklistCount: this.blacklist.length,
423
+ };
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Create Express middleware for Firewall enforcement
429
+ * @param {FirewallManager} firewall
430
+ * @returns {Function}
431
+ */
432
+ function createFirewallMiddleware(firewall) {
433
+ return function firewallMiddleware(req, res, next) {
434
+ const clientIp = extractClientIp(req);
435
+ const banInfo = firewall.isBanned(clientIp);
436
+
437
+ if (banInfo.banned) {
438
+ firewall.emit('firewall:blocked', { ip: clientIp, path: req.originalUrl || req.url, reason: banInfo.reason });
439
+
440
+ res.status(403).json({
441
+ error: 'Forbidden',
442
+ message: 'Access denied by security firewall.',
443
+ reason: banInfo.reason,
444
+ });
445
+ return;
446
+ }
447
+
448
+ next();
449
+ };
450
+ }
451
+
452
+ module.exports = {
453
+ FirewallManager,
454
+ MemoryFirewallStore,
455
+ createFirewallMiddleware,
456
+ normalizeIp,
457
+ ipToLong,
458
+ matchIpOrCidr,
459
+ };
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Native Zero-Dependency HTTP Security Headers Engine
3
+ * Inspired by Helmet, built exclusively using Node.js native primitives.
4
+ * @module plugins/security/headers
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ const crypto = require('crypto');
10
+
11
+ /**
12
+ * Default Content Security Policy directives
13
+ */
14
+ const DEFAULT_CSP = {
15
+ 'default-src': ["'self'"],
16
+ 'base-uri': ["'self'"],
17
+ 'font-src': ["'self'", 'https:', 'data:'],
18
+ 'form-action': ["'self'"],
19
+ 'frame-ancestors': ["'self'"],
20
+ 'img-src': ["'self'", 'data:', 'https:', 'blob:'],
21
+ 'object-src': ["'none'"],
22
+ 'script-src': ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
23
+ 'script-src-attr': ["'none'"],
24
+ 'style-src': ["'self'", 'https:', "'unsafe-inline'"],
25
+ 'connect-src': ["'self'", 'https:', 'wss:', 'ws:'],
26
+ 'upgrade-insecure-requests': [],
27
+ };
28
+
29
+ /**
30
+ * Format CSP object to directive string
31
+ * @param {Record<string, string[]|boolean>} cspConfig
32
+ * @param {string} [nonce]
33
+ * @returns {string}
34
+ */
35
+ function buildCspHeader(cspConfig, nonce) {
36
+ if (!cspConfig || typeof cspConfig !== 'object') return '';
37
+
38
+ const directives = [];
39
+
40
+ for (const [key, rawValues] of Object.entries(cspConfig)) {
41
+ if (rawValues === false || rawValues === null || rawValues === undefined) {
42
+ continue;
43
+ }
44
+
45
+ if (Array.isArray(rawValues)) {
46
+ const values = [...rawValues];
47
+ if (nonce && (key === 'script-src' || key === 'style-src')) {
48
+ values.push(`'nonce-${nonce}'`);
49
+ }
50
+ directives.push(values.length > 0 ? `${key} ${values.join(' ')}` : key);
51
+ } else if (typeof rawValues === 'string') {
52
+ directives.push(`${key} ${rawValues}`);
53
+ } else if (rawValues === true) {
54
+ directives.push(key);
55
+ }
56
+ }
57
+
58
+ return directives.join('; ');
59
+ }
60
+
61
+ /**
62
+ * Create security headers middleware
63
+ *
64
+ * @param {Object} [options]
65
+ * @param {boolean|Object} [options.csp=true] - Content Security Policy config or boolean
66
+ * @param {boolean} [options.cspReportOnly=false] - Use Content-Security-Policy-Report-Only
67
+ * @param {boolean|Object} [options.hsts=true] - Strict-Transport-Security config
68
+ * @param {string|boolean} [options.frameGuard='SAMEORIGIN'] - X-Frame-Options ('DENY', 'SAMEORIGIN' or false)
69
+ * @param {boolean} [options.noSniff=true] - X-Content-Type-Options: nosniff
70
+ * @param {string|boolean} [options.referrerPolicy='strict-origin-when-cross-origin'] - Referrer-Policy
71
+ * @param {string|boolean} [options.permissionsPolicy=true] - Permissions-Policy
72
+ * @param {boolean} [options.xssFilter=true] - X-XSS-Protection (0 per OWASP)
73
+ * @param {boolean} [options.dnsPrefetchControl=true] - X-DNS-Prefetch-Control: off
74
+ * @param {string|boolean} [options.crossOriginOpenerPolicy='same-origin-allow-popups'] - Cross-Origin-Opener-Policy
75
+ * @param {string|boolean} [options.crossOriginResourcePolicy='same-origin'] - Cross-Origin-Resource-Policy
76
+ * @param {boolean} [options.hidePoweredBy=true] - Remove X-Powered-By
77
+ * @param {boolean} [options.generateNonce=false] - Generate crypto nonce on req/res.locals
78
+ * @returns {Function} Express/Connect middleware
79
+ */
80
+ function createSecurityHeadersMiddleware(options = {}) {
81
+ const {
82
+ csp = true,
83
+ cspReportOnly = false,
84
+ hsts = true,
85
+ frameGuard = 'SAMEORIGIN',
86
+ noSniff = true,
87
+ referrerPolicy = 'strict-origin-when-cross-origin',
88
+ permissionsPolicy = 'camera=(), microphone=(), geolocation=()',
89
+ xssFilter = true,
90
+ dnsPrefetchControl = true,
91
+ crossOriginOpenerPolicy = 'same-origin-allow-popups',
92
+ crossOriginResourcePolicy = 'same-origin',
93
+ hidePoweredBy = true,
94
+ generateNonce = false,
95
+ } = options;
96
+
97
+ // Normalized CSP directives
98
+ let cspDirectives = null;
99
+ if (csp === true) {
100
+ cspDirectives = { ...DEFAULT_CSP };
101
+ if (cspReportOnly) {
102
+ delete cspDirectives['upgrade-insecure-requests'];
103
+ }
104
+ } else if (typeof csp === 'object' && csp !== null) {
105
+ cspDirectives = { ...DEFAULT_CSP, ...csp };
106
+ if (cspReportOnly && !Object.prototype.hasOwnProperty.call(csp, 'upgrade-insecure-requests')) {
107
+ delete cspDirectives['upgrade-insecure-requests'];
108
+ }
109
+ }
110
+
111
+ // Normalized HSTS string
112
+ let hstsHeaderValue = null;
113
+ if (hsts === true) {
114
+ hstsHeaderValue = 'max-age=31536000; includeSubDomains; preload';
115
+ } else if (typeof hsts === 'object' && hsts !== null) {
116
+ const maxAge = hsts.maxAge !== undefined ? hsts.maxAge : 31536000;
117
+ const includeSubDomains = hsts.includeSubDomains !== false ? '; includeSubDomains' : '';
118
+ const preload = hsts.preload ? '; preload' : '';
119
+ hstsHeaderValue = `max-age=${maxAge}${includeSubDomains}${preload}`;
120
+ }
121
+
122
+ return function securityHeadersMiddleware(req, res, next) {
123
+ // 1. Hide X-Powered-By
124
+ if (hidePoweredBy) {
125
+ if (typeof res.removeHeader === 'function') {
126
+ res.removeHeader('X-Powered-By');
127
+ }
128
+ if (res.headers && res.headers['x-powered-by']) {
129
+ delete res.headers['x-powered-by'];
130
+ }
131
+ }
132
+
133
+ // 2. Generate CSP Nonce if requested
134
+ let nonce = null;
135
+ if (generateNonce) {
136
+ nonce = crypto.randomBytes(16).toString('base64');
137
+ req.cspNonce = nonce;
138
+ if (!res.locals) res.locals = {};
139
+ res.locals.cspNonce = nonce;
140
+ }
141
+
142
+ // 3. Content-Security-Policy
143
+ if (cspDirectives) {
144
+ const headerName = cspReportOnly ? 'Content-Security-Policy-Report-Only' : 'Content-Security-Policy';
145
+ const headerValue = buildCspHeader(cspDirectives, nonce);
146
+ if (headerValue && typeof res.setHeader === 'function') {
147
+ res.setHeader(headerName, headerValue);
148
+ }
149
+ }
150
+
151
+ // 4. Strict-Transport-Security (Apply if HTTPS or trust proxy indicates secure)
152
+ if (hstsHeaderValue) {
153
+ const isHttps = req.secure || req.headers?.['x-forwarded-proto'] === 'https' || req.protocol === 'https';
154
+ const forceHsts = typeof hsts === 'object' && hsts?.force === true;
155
+ if (isHttps || forceHsts) {
156
+ if (typeof res.setHeader === 'function') {
157
+ res.setHeader('Strict-Transport-Security', hstsHeaderValue);
158
+ }
159
+ }
160
+ }
161
+
162
+ // 5. X-Frame-Options
163
+ if (frameGuard && typeof res.setHeader === 'function') {
164
+ const val = typeof frameGuard === 'string' ? frameGuard.toUpperCase() : 'SAMEORIGIN';
165
+ res.setHeader('X-Frame-Options', val);
166
+ }
167
+
168
+ // 6. X-Content-Type-Options: nosniff
169
+ if (noSniff && typeof res.setHeader === 'function') {
170
+ res.setHeader('X-Content-Type-Options', 'nosniff');
171
+ }
172
+
173
+ // 7. Referrer-Policy
174
+ if (referrerPolicy && typeof res.setHeader === 'function') {
175
+ res.setHeader('Referrer-Policy', String(referrerPolicy));
176
+ }
177
+
178
+ // 8. Permissions-Policy
179
+ if (permissionsPolicy && typeof res.setHeader === 'function') {
180
+ const policyVal = typeof permissionsPolicy === 'string'
181
+ ? permissionsPolicy
182
+ : 'camera=(), microphone=(), geolocation=()';
183
+ res.setHeader('Permissions-Policy', policyVal);
184
+ }
185
+
186
+ // 9. X-XSS-Protection (0 disables buggy legacy XSS auditor per OWASP)
187
+ if (xssFilter && typeof res.setHeader === 'function') {
188
+ res.setHeader('X-XSS-Protection', '0');
189
+ }
190
+
191
+ // 10. X-DNS-Prefetch-Control: off
192
+ if (dnsPrefetchControl && typeof res.setHeader === 'function') {
193
+ res.setHeader('X-DNS-Prefetch-Control', 'off');
194
+ }
195
+
196
+ // 11. Cross-Origin-Opener-Policy
197
+ if (crossOriginOpenerPolicy && typeof res.setHeader === 'function') {
198
+ res.setHeader('Cross-Origin-Opener-Policy', String(crossOriginOpenerPolicy));
199
+ }
200
+
201
+ // 12. Cross-Origin-Resource-Policy
202
+ if (crossOriginResourcePolicy && typeof res.setHeader === 'function') {
203
+ res.setHeader('Cross-Origin-Resource-Policy', String(crossOriginResourcePolicy));
204
+ }
205
+
206
+ next();
207
+ };
208
+ }
209
+
210
+ module.exports = {
211
+ createSecurityHeadersMiddleware,
212
+ buildCspHeader,
213
+ DEFAULT_CSP,
214
+ };