@seckav/security-sdk
Version:
Lightweight API Security SDK for Enterprises - One-click protection with rate limiting, threat detection, security analytics, and real-time monitoring for Express.js and Next.js applications
260 lines • 10 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecKavSDK = void 0;
exports.createSecKavMiddleware = createSecKavMiddleware;
exports.createSecKavNextMiddleware = createSecKavNextMiddleware;
const RateLimit_1 = require("../modules/RateLimit");
const Security_1 = require("../modules/Security");
const EncryptionModule_1 = require("../modules/EncryptionModule");
const MisconfigurationScanner_1 = require("../modules/MisconfigurationScanner");
/**
* SecKav Security SDK - Lightweight Client SDK for API Protection
*
* Core Features:
* - Rate Limiting with DDoS protection
* - API Firewall (WAF-lite) with threat detection
* - Encryption Gateway with TLS enforcement
* - Misconfiguration Scanner for security assessment
* - Basic Analytics (sends data to dashboard)
*
* What this SDK does NOT do (handled by dashboard):
* - User authentication/registration
* - Organization management
* - Compliance reporting
* - Git integration
*/
class SecKavSDK {
constructor(config) {
// Validate required configuration
if (!config.apiKey) {
throw new Error('SecKav SDK: API key is required. Get your API key from https://dashboard.seckav.com');
}
if (!config.organizationId) {
throw new Error('SecKav SDK: Organization ID is required. Find it in your dashboard settings.');
}
this.config = {
timeout: 5000,
features: {
rateLimit: true,
security: true,
encryption: false,
misconfigurationScanning: false,
analytics: true
},
debug: false,
...config,
apiUrl: config.apiUrl || 'https://api.seckav.com', // Production API URL
};
// Initialize core security modules
this.initializeModules();
// Log SDK initialization
if (this.config.debug) {
console.log('SecKav SDK v3.0.0 initialized for organization:', this.config.organizationId);
console.log('Enabled features:', this.getEnabledFeatures());
}
}
initializeModules() {
// Rate Limiting (core feature)
if (this.config.features?.rateLimit) {
this.rateLimit = new RateLimit_1.RateLimitModule({
apiUrl: this.config.apiUrl,
organizationId: this.config.organizationId,
apiKey: this.config.apiKey,
timeout: this.config.timeout,
onError: this.config.onError,
});
}
// Security Module (IP filtering, threat detection, etc.)
if (this.config.features?.security) {
this.security = new Security_1.SecurityModule({
apiUrl: this.config.apiUrl,
timeout: this.config.timeout,
onError: this.config.onError,
});
}
// Encryption Module (optional)
if (this.config.features?.encryption) {
this.encryption = new EncryptionModule_1.EncryptionModule({
apiUrl: this.config.apiUrl,
organizationId: this.config.organizationId,
timeout: this.config.timeout,
onError: this.config.onError,
});
}
// Misconfiguration Scanner (optional)
if (this.config.features?.misconfigurationScanning) {
this.misconfigurationScanner = new MisconfigurationScanner_1.MisconfigurationScannerModule({
apiUrl: this.config.apiUrl,
organizationId: this.config.organizationId,
timeout: this.config.timeout,
onError: this.config.onError,
});
}
}
/**
* Get Express.js middleware with all enabled security features
* This is the main integration point for most users
*/
getExpressMiddleware() {
return async (req, res, next) => {
try {
// 1. Rate limiting check (if enabled)
if (this.config.features?.rateLimit && this.rateLimit) {
const rateLimitResult = await this.rateLimit.checkRequest(req);
if (!rateLimitResult.allowed) {
return this.rateLimit.handleRateLimitResponse(res, rateLimitResult);
}
// Set rate limit headers
Object.entries(rateLimitResult.headers || {}).forEach(([key, value]) => {
res.setHeader(key, value);
});
}
// 2. Basic security validation (placeholder for future implementation)
// Security module methods require tokens, so we skip for now
// This would integrate with backend API firewall for request validation
// 3. Encryption validation (placeholder for future implementation)
// Encryption module methods require tokens, so we skip for now
// 4. Send analytics data to dashboard (if enabled)
if (this.config.features?.analytics) {
this.sendAnalytics(req).catch(err => {
if (this.config.debug) {
console.warn('Failed to send analytics:', err.message);
}
});
}
next();
}
catch (error) {
if (this.config.onError) {
this.config.onError(error);
}
// Fail open - allow request to continue in case of SDK errors
if (this.config.debug) {
console.error('SecKav middleware error:', error);
}
next();
}
};
}
/**
* Get Next.js middleware
*/
getNextMiddleware() {
return async (req) => {
try {
// Similar logic to Express middleware but for Next.js
if (this.config.features?.rateLimit && this.rateLimit) {
const rateLimitResult = await this.rateLimit.checkRequest(req);
if (!rateLimitResult.allowed) {
return new Response(JSON.stringify({
error: 'Rate limited',
retryAfter: rateLimitResult.retryAfter,
}), {
status: 429,
headers: {
'Content-Type': 'application/json',
...rateLimitResult.headers,
},
});
}
}
// Send analytics for Next.js
if (this.config.features?.analytics) {
this.sendAnalytics(req).catch(() => { });
}
return null; // Allow request to continue
}
catch (error) {
if (this.config.onError) {
this.config.onError(error);
}
return null; // Fail open
}
};
}
/**
* Manual rate limit check (for custom implementations)
*/
async checkRateLimit(endpoint, method, clientId) {
if (!this.rateLimit) {
throw new Error('Rate limiting not enabled');
}
// Create a mock request object to use existing checkRequest method
const mockReq = {
path: endpoint,
method: method,
headers: { 'x-client-id': clientId },
ip: 'unknown'
};
return this.rateLimit.checkRequest(mockReq);
}
/**
* Get security settings (requires authentication token)
*/
async getSecuritySettings(token) {
if (!this.security) {
throw new Error('Security module not enabled');
}
return this.security.getSecuritySettings(token);
}
/**
* Scan for misconfigurations (requires backend API)
* This would typically be called from dashboard, not client SDK
*/
async scanMisconfigurations(token, files) {
if (!this.misconfigurationScanner) {
throw new Error('Misconfiguration scanner not enabled');
}
// This would call backend API with files
throw new Error('Misconfiguration scanning should be done via dashboard');
}
/**
* Get SDK information and enabled features
*/
getInfo() {
return {
version: '3.0.0',
organizationId: this.config.organizationId,
apiUrl: this.config.apiUrl,
enabledFeatures: this.getEnabledFeatures(),
availableFeatures: [
'rateLimit',
'security',
'encryption',
'misconfigurationScanning',
'analytics'
]
};
}
getEnabledFeatures() {
return Object.entries(this.config.features || {})
.filter(([, enabled]) => enabled)
.map(([feature]) => feature);
}
/**
* Send analytics data to dashboard (private method)
*/
async sendAnalytics(req) {
// This would send usage data to the dashboard
// Implementation depends on your analytics requirements
// Keep it lightweight and non-blocking
}
/**
* Update configuration at runtime
*/
updateConfig(newConfig) {
this.config = { ...this.config, ...newConfig };
this.initializeModules(); // Reinitialize modules with new config
}
}
exports.SecKavSDK = SecKavSDK;
// Convenience functions for one-line integration
function createSecKavMiddleware(config) {
const sdk = new SecKavSDK(config);
return sdk.getExpressMiddleware();
}
function createSecKavNextMiddleware(config) {
const sdk = new SecKavSDK(config);
return sdk.getNextMiddleware();
}
//# sourceMappingURL=SecKavSDK.js.map