Penjaro AI-powered proxy middleware for preventive cybersecurity
npm install penjaro-network-security-library-javascript

Penjaro provides intelligent, proactive network security for your web applications and APIs. It acts as a smart shield between your application and potential threats, analyzing incoming requests and outgoing responses using a sophisticated combination of:
- Rule-based detection
- Threat intelligence feeds
- AI-powered analysis (optional)
- Framework-specific hardening techniques
Stop attacks before they reach your application logic. Penjaro integrates seamlessly as middleware or a standalone proxy, offering a powerful layer of defense against common and sophisticated threats.
- Proactive Defense: Identifies and blocks threats like SQL injection, XSS, command injection, malicious bots, DoS attempts, and more at the edge
- AI-Powered Intelligence: Leverage TensorFlow.js models to detect novel and complex attack patterns that signature-based methods might miss
- Threat Feed Integration: Stay ahead of attackers by automatically blocking IPs known for malicious activity (malware C&C, scanners, Tor exits, etc.)
- Response Security: Prevent accidental leaks of sensitive data (API keys, PII) or verbose error messages in responses
- Framework Native: Easy integration with popular Node.js frameworks (Express, NestJS, Koa, Fastify, Hapi)
- Highly Configurable: Fine-tune security policies to match your application's specific needs and risk profile
- Distributed Ready: Use Redis to share rate limiting and threat intelligence state across multiple instances
tf.js modelsIn addition to the core security features, Penjaro provides several advanced security mechanisms to enhance your application's protection:
Content Security Policy is one of the most powerful browser security features, restricting which resources can be loaded and executed by the browser. Penjaro provides comprehensive CSP support with violation reporting:
- Configure and apply CSP headers with sensible defaults
- Set up CSP violation reporting endpoints
- Store, analyze, and respond to CSP violation reports
- Multiple storage options (in-memory, file, callback)
- Notification hooks for real-time alerts
``javascript`
const penjaroMiddleware = await createPenjaroProxy({
apiKey: 'your-api-key',
securityHeaders: {
contentSecurityPolicy: {
enableReporting: true,
reportingPath: '/csp-report',
directives: {
'default-src': ["'self'"],
'script-src': ["'self'", "https://trusted-cdn.com"]
}
}
}
});
HTTP security headers provide critical browser-level protections against common web vulnerabilities. Penjaro offers a comprehensive set of security headers with sensible defaults:
- Content-Security-Policy (CSP)
- Strict-Transport-Security (HSTS)
- X-Frame-Options
- X-Content-Type-Options
- Referrer-Policy
- Permissions-Policy
- Cross-Origin headers (Opener, Embedder, Resource Policy)
`javascript`
const penjaroMiddleware = await createPenjaroProxy({
apiKey: 'your-api-key',
securityHeaders: {
frameOptions: 'DENY',
hsts: 'max-age=31536000; includeSubDomains; preload',
referrerPolicy: 'strict-origin-when-cross-origin',
permissionsPolicy: 'camera=(), microphone=(), geolocation=()'
}
});
Cookies often store sensitive session data that needs protection. Penjaro's encrypted cookies feature provides transparent encryption and decryption:
- AES-GCM encryption for cookie values
- Automatic encryption/decryption
- Cookie-specific encryption targeting
- Configurable cookie options (httpOnly, secure, SameSite)
- Convenience methods for setting/getting encrypted cookies
`javascript
const penjaroMiddleware = await createPenjaroProxy({
apiKey: 'your-api-key',
encryptedCookies: {
secretKey: 'at-least-32-characters-long-secret-key',
cookieNames: ['session', 'auth', 'token'],
defaultCookieOptions: {
httpOnly: true,
secure: true,
sameSite: 'strict'
}
}
});
// In your route handlers
app.get('/profile', (req, res) => {
// Access decrypted cookie
const sessionData = req.getDecryptedCookie('session');
// Set encrypted cookie
res.setEncryptedCookie('session', JSON.stringify({ userId: 123 }));
});
`
Ensure resources loaded from external sources (like CDNs) haven't been tampered with:
- Generate integrity hashes for scripts and stylesheets
- Verify resource integrity
- Cache generated hashes for performance
- Generate SRI-enabled HTML tags
`javascript
const { createSRIManager } = require('penjaro-network-security-library-javascript');
// Setup SRI
const sriManager = createSRIManager({
algorithms: ['sha384'],
cacheDir: '.sri-cache'
});
// Generate integrity hash
const integrity = await sriManager.generateIntegrity('https://cdn.example.com/script.js');
console.log(integrity.integrity); // outputs: "sha384-a1b2c3d4..."
// Generate script tag with integrity
const scriptTag = await sriManager.generateScriptTag('https://cdn.example.com/script.js');
`
Detect and block malicious bots, scrapers, and automated tools:
- User-Agent pattern detection
- Browser fingerprinting
- Behavioral analysis
- Challenge-based verification
- Whitelist trusted crawlers (Google, Bing, etc.)
- Customizable challenge pages
`javascript`
const penjaroMiddleware = await createPenjaroProxy({
apiKey: 'your-api-key',
botProtection: {
enableChallenges: true,
enableFingerprinting: true,
enableBehavioralAnalysis: true,
cookieName: '_bot_verify',
excludePatterns: [/^\/api\/public/, /\.(jpg|png|gif)$/],
trustedBotPatterns: [/Googlebot/i, /bingbot/i]
}
});
`bashInstall the core package
npm install penjaro-network-security-library-javascript
Core Concept: Operating Modes
Penjaro can operate in two distinct modes, determined by the presence of the
targetServer option:$3
- Integrates directly into your framework's middleware chain
- Analyzes incoming requests only
- Blocks malicious requests or passes legitimate ones to your application logic
- Ideal for securing existing applications without changing infrastructure$3
- Acts as a reverse proxy
- Analyzes both incoming requests and outgoing responses
- Forwards valid requests to your target server
- Provides comprehensive protection including data leak prevention
- Requires Penjaro to run as a separate process or containerQuick Start Examples
$3
`typescript
import express from 'express';
import { createPenjaroProxy, PenjaroConfigOptions } from 'penjaro-network-security-library-javascript';const app = express();
const penjaroOptions: PenjaroConfigOptions = {
apiKey: process.env.PENJARO_API_KEY,
enableRateLimit: true,
enableThreatIntelCheck: true,
includeDefaultFireholFeed: true,
};
async function startServer() {
try {
// Initialize Penjaro middleware
const penjaroMiddleware = await createPenjaroProxy(penjaroOptions);
// Apply Penjaro middleware BEFORE other routes/middleware
app.use(penjaroMiddleware);
// Your application routes
app.get('/', (req, res) => {
res.send('Hello World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(
Server running with Penjaro protection on port ${PORT});
});
} catch (error) {
console.error("Failed to initialize Penjaro or start server:", error);
process.exit(1);
}
}startServer();
`$3
`typescript
import express from 'express';
import { createPenjaroProxy, PenjaroConfigOptions } from 'penjaro-network-security-library-javascript';async function startProxy() {
try {
const penjaroOptions: PenjaroConfigOptions = {
apiKey: process.env.PENJARO_API_KEY,
targetServer: 'http://localhost:8080', // Your actual application server
enableRateLimit: true,
enableResponseAnalysis: true, // Enable response analysis
enableDataLeakChecks: true,
enableVerboseErrorChecks: true,
};
// Initialize Penjaro proxy
const penjaroProxy = await createPenjaroProxy(penjaroOptions);
// Create an Express app that just uses the proxy
const app = express();
app.use(penjaroProxy);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(
Penjaro proxy running on port ${PORT}, forwarding to ${penjaroOptions.targetServer});
});
} catch (error) {
console.error("Failed to initialize Penjaro proxy:", error);
process.exit(1);
}
}startProxy();
`Express 5.x Compatibility
Penjaro now includes built-in support for both Express 4.x and Express 5.x. The library has been updated to handle the middleware changes in Express 5, including:
- Handling of async/await middleware functions
- Support for Express 5's promise-based middleware chain
- Compatibility with Express 5's updated response object
$3
For the best compatibility with Express 5.x, use the dedicated Express adapter:
`typescript
import express from 'express';
import { createExpressMiddleware } from 'penjaro-network-security-library-javascript';const app = express();
async function startServer() {
try {
// Use the Express-specific adapter for best compatibility
const penjaroMiddleware = await createExpressMiddleware({
apiKey: process.env.PENJARO_API_KEY,
enableRateLimit: true,
// ... other options
});
// Apply Penjaro middleware
app.use(penjaroMiddleware);
// Your Express 5.x routes
app.get('/', async (req, res) => {
// Express 5.x allows async route handlers
const data = await fetchSomeData();
res.send(data);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(
Express 5.x server running with Penjaro protection on port ${PORT});
});
} catch (error) {
console.error("Failed to initialize Penjaro:", error);
process.exit(1);
}
}startServer();
`$3
Penjaro now supports a wider range of dependency versions:
- Express:
^4.17.1 || ^5.0.0
- NestJS: ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0
- Koa: ^2.13.0 || ^3.0.0
- Fastify: ^4.0.0 || ^5.0.0
- Redis: ^4.0.0 || ^5.0.0
- And more...This makes it easier to integrate Penjaro into projects using different versions of these frameworks and libraries.
Framework Integration Examples
$3
NestJS integration is easy and clean with Penjaro's dedicated adapter. Here's a complete example:
#### 1. Create a Penjaro Module
`typescript
// src/penjaro/penjaro.module.ts
import { Module, DynamicModule } from '@nestjs/common';
import { PenjaroService } from './penjaro.service';
import { PenjaroConfigOptions } from 'penjaro-network-security-library-javascript';@Module({})
export class PenjaroModule {
static register(options: PenjaroConfigOptions): DynamicModule {
return {
module: PenjaroModule,
providers: [
{
provide: 'PENJARO_OPTIONS',
useValue: options,
},
PenjaroService,
],
exports: [PenjaroService],
};
}
}
`#### 2. Create a Penjaro Service
`typescript
// src/penjaro/penjaro.service.ts
import { Injectable, Inject, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { createPenjaroProxy, PenjaroConfigOptions } from 'penjaro-network-security-library-javascript';
import { RequestHandler } from 'express';@Injectable()
export class PenjaroService implements OnModuleInit, OnModuleDestroy {
private middleware: RequestHandler | null = null;
private redisClient: unknown | null = null;
private readonly logger = new Logger(PenjaroService.name);
private initializationPromise: Promise | null = null;
constructor(
@Inject('PENJARO_OPTIONS') private readonly options: PenjaroConfigOptions,
) {}
async onModuleInit() {
this.initializationPromise = this.initialize();
await this.initializationPromise;
}
private async initialize() {
try {
this.logger.log('Initializing Penjaro middleware...');
this.middleware = (await createPenjaroProxy(
this.options,
)) as unknown as RequestHandler;
// Store redis client reference if it exists
if (this.options.redisClient) {
this.redisClient = this.options.redisClient;
}
this.logger.log('Penjaro middleware initialized successfully');
} catch (error) {
this.logger.error(
Failed to initialize Penjaro middleware: ${error.message});
throw error;
}
} async onModuleDestroy() {
// Clean up redis connection if needed
if (
this.redisClient &&
typeof (this.redisClient as any).disconnect === 'function'
) {
try {
await (this.redisClient as any).disconnect();
this.logger.log('Redis client disconnected successfully');
} catch (error) {
this.logger.error(
Error disconnecting Redis client: ${error.message});
}
}
} getMiddleware(): RequestHandler {
if (!this.middleware) {
throw new Error('Penjaro middleware not initialized');
}
return this.middleware;
}
}
`#### 3. Create a Penjaro Middleware
`typescript
// src/penjaro/penjaro.middleware.ts
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { PenjaroService } from './penjaro.service';@Injectable()
export class PenjaroMiddleware implements NestMiddleware {
private readonly logger = new Logger(PenjaroMiddleware.name);
constructor(private readonly penjaroService: PenjaroService) {}
use(req: Request, res: Response, next: NextFunction) {
try {
const middleware = this.penjaroService.getMiddleware();
middleware(req, res, (err?: any) => {
if (err) {
this.logger.error(
Penjaro middleware error: ${err.message});
return next(err);
}
next();
});
} catch (error) {
this.logger.error(Failed to get Penjaro middleware: ${error.message});
next(error);
}
}
}
`#### 4. Use in App Module
`typescript
// src/app.module.ts
import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PenjaroModule } from './penjaro/penjaro.module';
import { PenjaroMiddleware } from './penjaro/penjaro.middleware';@Module({
imports: [
PenjaroModule.register({
apiKey: process.env.PENJARO_API_KEY,
enableRateLimit: true,
rateLimitPoints: 5,
rateLimitDuration: 10, // 10 seconds
enableResponseAnalysis: true,
enableDataLeakChecks: true,
enableVerboseErrorChecks: true,
// Example custom rules
customRequestRulePatterns: {
xss: [/