api-security-shield 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,385 @@
1
+ # API Security Shield - Core ๐Ÿ›ก๏ธ
2
+
3
+ [![npm version](https://img.shields.io/npm/v/api-security-shield-core.svg)](https://www.npmjs.com/package/api-security-shield-core)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.5+-blue.svg)](https://www.typescriptlang.org/)
6
+ [![Node.js](https://img.shields.io/badge/Node.js-20.11+-green.svg)](https://nodejs.org/)
7
+
8
+ **Core security engine for intelligent API protection in Node.js applications.**
9
+
10
+ The core module of API Security Shield provides the foundation for protecting your APIs from automated threats, brute force attacks, and malicious traffic. Built with TypeScript and a plugin-first architecture, it enables real-time threat detection and adaptive responses.
11
+
12
+ ## ๐Ÿ“ฆ What's Included
13
+
14
+ - **Threat Detection Engine**: Multi-layered detection for SQL injection, XSS, and common attack patterns
15
+ - **Adaptive Rate Limiting**: Intelligent request throttling based on threat assessment
16
+ - **Bot Detection**: Advanced fingerprinting and behavioral analysis
17
+ - **Event System**: Real-time event bus for security events
18
+ - **Extensible Architecture**: Plugin system for custom detectors and analyzers
19
+ - **Storage Adapters**: Memory and Redis support for distributed deployments
20
+ - **Middleware Integration**: Express, Fastify, and NestJS compatible
21
+
22
+ ## ๐Ÿš€ Quick Start
23
+
24
+ ### Installation
25
+
26
+ ```bash
27
+ npm install api-security-shield
28
+ # or
29
+ pnpm add api-security-shield
30
+ # or
31
+ yarn add api-security-shield
32
+ ```
33
+
34
+ ### Basic Usage
35
+
36
+ ```typescript
37
+ import { SecurityShield } from 'api-security-shield-core';
38
+ import express from 'express';
39
+
40
+ const app = express();
41
+ const shield = new SecurityShield({
42
+ rateLimit: {
43
+ windowMs: 60000, // 1 minute
44
+ max: 100 // 100 requests per window
45
+ },
46
+ botDetection: {
47
+ enabled: true,
48
+ sensitivity: 'high' // low | medium | high
49
+ }
50
+ });
51
+
52
+ // Apply middleware
53
+ app.use(shield.middleware());
54
+
55
+ app.get('/api/data', (req, res) => {
56
+ res.json({ message: 'Protected endpoint' });
57
+ });
58
+
59
+ app.listen(3000, () => {
60
+ console.log('Server running on port 3000 with Shield protection');
61
+ });
62
+ ```
63
+
64
+ ## ๐Ÿ”ง Configuration
65
+
66
+ ### Core Options
67
+
68
+ ```typescript
69
+ interface ShieldConfig {
70
+ // Rate limiting
71
+ rateLimit?: {
72
+ windowMs: number; // Time window in ms
73
+ max: number; // Max requests per window
74
+ message?: string; // Custom rate limit message
75
+ };
76
+
77
+ // Bot detection
78
+ botDetection?: {
79
+ enabled: boolean;
80
+ sensitivity: 'low' | 'medium' | 'high';
81
+ threshold?: number; // 0-100 score threshold
82
+ };
83
+
84
+ // Threat detection
85
+ threatDetection?: {
86
+ sqlInjection: boolean;
87
+ xss: boolean;
88
+ customPatterns?: RegExp[];
89
+ };
90
+
91
+ // Storage adapter (memory or redis)
92
+ storage?: StorageAdapter;
93
+
94
+ // Event handlers
95
+ onThreat?: (event: ThreatEvent) => void;
96
+ onRateLimit?: (event: RateLimitEvent) => void;
97
+ }
98
+ ```
99
+
100
+ ## ๐Ÿ“Š Event System
101
+
102
+ Listen to security events in real-time:
103
+
104
+ ```typescript
105
+ shield.on('threat', (event) => {
106
+ console.log(`Threat detected: ${event.type}`, {
107
+ source: event.ip,
108
+ severity: event.severity,
109
+ timestamp: event.timestamp
110
+ });
111
+ });
112
+
113
+ shield.on('rate-limit', (event) => {
114
+ console.log(`Rate limit exceeded for ${event.ip}`);
115
+ });
116
+
117
+ shield.on('bot', (event) => {
118
+ console.log(`Bot detected with score: ${event.score}`);
119
+ });
120
+ ```
121
+
122
+ ## ๐Ÿ”Œ Storage Adapters
123
+
124
+ ### Memory Adapter (Default)
125
+
126
+ ```typescript
127
+ import { MemoryStorageAdapter } from 'api-security-shield-core';
128
+
129
+ const shield = new SecurityShield({
130
+ storage: new MemoryStorageAdapter()
131
+ });
132
+ ```
133
+
134
+ ### Redis Adapter
135
+
136
+ ```typescript
137
+ import { RedisStorageAdapter } from '@api-security-shield/redis';
138
+ import Redis from 'ioredis';
139
+
140
+ const redis = new Redis({
141
+ host: 'localhost',
142
+ port: 6379
143
+ });
144
+
145
+ const shield = new SecurityShield({
146
+ storage: new RedisStorageAdapter(redis)
147
+ });
148
+ ```
149
+
150
+ ## ๐ŸŽฏ Advanced Features
151
+
152
+ ### Custom Threat Detectors
153
+
154
+ ```typescript
155
+ import { CustomDetector } from 'api-security-shield-core';
156
+
157
+ class MyCustomDetector extends CustomDetector {
158
+ detect(request) {
159
+ // Your detection logic
160
+ return {
161
+ detected: false,
162
+ score: 0,
163
+ message: 'Custom check passed'
164
+ };
165
+ }
166
+ }
167
+
168
+ shield.registerDetector(new MyCustomDetector());
169
+ ```
170
+
171
+ ### Threat Scoring
172
+
173
+ The shield assigns threat scores (0-100) based on multiple factors:
174
+
175
+ | Score Range | Level | Action |
176
+ |------------|-------|--------|
177
+ | 0-20 | Low | Allow request |
178
+ | 21-50 | Medium | Monitor & log |
179
+ | 51-80 | High | Rate limit |
180
+ | 81-100 | Critical | Block immediately |
181
+
182
+ ### Request Context
183
+
184
+ Access security context in your handlers:
185
+
186
+ ```typescript
187
+ app.get('/api/data', (req: any, res) => {
188
+ const shieldContext = req.shieldContext;
189
+
190
+ console.log({
191
+ threatScore: shieldContext.threatScore,
192
+ isBot: shieldContext.isBot,
193
+ fingerprint: shieldContext.fingerprint,
194
+ violations: shieldContext.violations
195
+ });
196
+
197
+ res.json({ data: 'sensitive' });
198
+ });
199
+ ```
200
+
201
+ ## ๐Ÿ” Security Best Practices
202
+
203
+ 1. **Always validate input** - Shield complements but doesn't replace input validation
204
+ 2. **Use HTTPS** - Always run in production with TLS/SSL
205
+ 3. **Monitor events** - Set up alerts for high threat scores
206
+ 4. **Update regularly** - Keep Shield and dependencies updated
207
+ 5. **Test configuration** - Thoroughly test rate limits and detection rules
208
+ 6. **Use Redis for distributed** - In production with multiple servers, use Redis adapter
209
+
210
+ ## ๐Ÿ“š Middleware Integration
211
+
212
+ ### Express
213
+
214
+ ```typescript
215
+ import express from 'express';
216
+ import { SecurityShield } from 'api-security-shield-core';
217
+
218
+ const app = express();
219
+ const shield = new SecurityShield(config);
220
+ app.use(shield.middleware());
221
+ ```
222
+
223
+ ### Fastify
224
+
225
+ Install the Fastify adapter:
226
+ ```bash
227
+ npm install @api-security-shield/fastify
228
+ ```
229
+
230
+ ```typescript
231
+ import Fastify from 'fastify';
232
+ import { fastifyShield } from '@api-security-shield/fastify';
233
+
234
+ const fastify = Fastify();
235
+ await fastify.register(fastifyShield, config);
236
+ ```
237
+
238
+ ### NestJS
239
+
240
+ Install the NestJS adapter:
241
+ ```bash
242
+ npm install @api-security-shield/nestjs
243
+ ```
244
+
245
+ ```typescript
246
+ import { Module } from '@nestjs/common';
247
+ import { ShieldModule } from '@api-security-shield/nestjs';
248
+
249
+ @Module({
250
+ imports: [ShieldModule.forRoot(config)]
251
+ })
252
+ export class AppModule {}
253
+ ```
254
+
255
+ ## ๐Ÿšจ Error Handling
256
+
257
+ ```typescript
258
+ shield.on('error', (error) => {
259
+ console.error('Shield error:', error);
260
+ // Handle errors gracefully
261
+ });
262
+
263
+ // Custom error responses
264
+ app.use((err: any, req: any, res: any, next: any) => {
265
+ if (err.code === 'RATE_LIMIT_EXCEEDED') {
266
+ return res.status(429).json({
267
+ error: 'Too many requests',
268
+ retryAfter: err.retryAfter
269
+ });
270
+ }
271
+
272
+ if (err.code === 'THREAT_DETECTED') {
273
+ return res.status(403).json({
274
+ error: 'Request blocked',
275
+ reason: err.reason
276
+ });
277
+ }
278
+
279
+ next(err);
280
+ });
281
+ ```
282
+
283
+ ## ๐Ÿ“Š Monitoring & Metrics
284
+
285
+ Access real-time metrics:
286
+
287
+ ```typescript
288
+ const metrics = shield.getMetrics();
289
+
290
+ console.log({
291
+ totalRequests: metrics.totalRequests,
292
+ blockedRequests: metrics.blockedRequests,
293
+ threatsDetected: metrics.threatsDetected,
294
+ averageThreatScore: metrics.averageThreatScore,
295
+ botsDetected: metrics.botsDetected
296
+ });
297
+ ```
298
+
299
+ ## ๐Ÿ”— Webhook Integration
300
+
301
+ Send security events to external services:
302
+
303
+ ```bash
304
+ npm install @api-security-shield/webhook
305
+ ```
306
+
307
+ ```typescript
308
+ import { WebhookAdapter } from '@api-security-shield/webhook';
309
+
310
+ const webhook = new WebhookAdapter({
311
+ url: 'https://your-service.com/security-events',
312
+ events: ['threat', 'bot', 'rate-limit'],
313
+ retries: 3
314
+ });
315
+
316
+ shield.registerAdapter(webhook);
317
+ ```
318
+
319
+ ## ๐Ÿงช Testing
320
+
321
+ ```typescript
322
+ import { createTestShield } from 'api-security-shield-core';
323
+
324
+ const shield = createTestShield({
325
+ rateLimit: { windowMs: 1000, max: 5 }
326
+ });
327
+
328
+ // Simulate requests
329
+ const result = await shield.check({
330
+ ip: '192.168.1.1',
331
+ path: '/api/test',
332
+ method: 'POST'
333
+ });
334
+
335
+ expect(result.threatScore).toBeLessThan(50);
336
+ ```
337
+
338
+ ## ๐Ÿ› Debugging
339
+
340
+ Enable debug mode to see detailed logs:
341
+
342
+ ```typescript
343
+ const shield = new SecurityShield(config, {
344
+ debug: true,
345
+ logLevel: 'verbose'
346
+ });
347
+
348
+ // Or use environment variable
349
+ // DEBUG=api-security-shield:* node app.js
350
+ ```
351
+
352
+ ## ๐Ÿ“– Documentation
353
+
354
+ - [Full API Reference](https://github.com/akramhossain-dev/API-Security-Shield/blob/main/docs/API_REFERENCE.md)
355
+ - [Architecture Guide](https://github.com/akramhossain-dev/API-Security-Shield/blob/main/docs/ARCHITECTURE.md)
356
+ - [Plugin Development](https://github.com/akramhossain-dev/API-Security-Shield/blob/main/docs/CONTRIBUTING.md)
357
+ - [Examples](https://github.com/akramhossain-dev/API-Security-Shield/tree/main/examples)
358
+
359
+ ## ๐Ÿ”— Related Packages
360
+
361
+ - [@api-security-shield/express](https://www.npmjs.com/package/@api-security-shield/express) - Express integration
362
+ - [@api-security-shield/fastify](https://www.npmjs.com/package/@api-security-shield/fastify) - Fastify integration
363
+ - [@api-security-shield/redis](https://www.npmjs.com/package/@api-security-shield/redis) - Redis adapter
364
+ - [@api-security-shield/webhook](https://www.npmjs.com/package/@api-security-shield/webhook) - Webhook notifications
365
+
366
+ ## ๐Ÿ“œ License
367
+
368
+ MIT ยฉ 2024 [Akram Hossain](https://github.com/akramhossain-dev)
369
+
370
+ ## ๐Ÿค Contributing
371
+
372
+ Contributions are welcome! Please see [CONTRIBUTING.md](https://github.com/akramhossain-dev/API-Security-Shield/blob/main/docs/CONTRIBUTING.md) for guidelines.
373
+
374
+ ## ๐Ÿ› Report Issues
375
+
376
+ Found a bug? Please report it on [GitHub Issues](https://github.com/akramhossain-dev/API-Security-Shield/issues)
377
+
378
+ ## ๐Ÿ“ž Support
379
+
380
+ - GitHub Discussions: [Discussion Board](https://github.com/akramhossain-dev/API-Security-Shield/discussions)
381
+ - Email: md.akramhossainjisan@gmail.com
382
+
383
+ ---
384
+
385
+ **Made with โค๏ธ by the API Security Shield team**