npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

tl-shared-security

v1.0.1

Published

Enterprise-grade security module for frontend and backend applications with comprehensive protection against XSS, CSRF, SQL injection, and other security vulnerabilities

Readme

TL Shared Security

npm version License: MIT TypeScript

Enterprise-grade security module for both frontend and backend applications. Provides comprehensive protection against XSS, CSRF, SQL injection, and other security vulnerabilities.

📦 Installation

npm install tl-shared-security

🚀 Quick Start

Backend (NestJS)

// app.module.ts
import { Module } from '@nestjs/common';
import { SecurityModule } from 'tl-shared-security/backend';

@Module({
  imports: [
    SecurityModule.forRoot({
      enableHelmet: true,
      enableXssSanitization: true,
      enableCsrf: true,
      enableRbac: true,
      enableRateLimiter: true,
      enableSecurityMonitoring: true,
    }),
  ],
})
export class AppModule {}

Frontend (React)

// App.tsx
import React from 'react';
import { sanitizeInput, secureStorage } from 'tl-shared-security/frontend';

function App() {
  const [userInput, setUserInput] = React.useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const sanitized = sanitizeInput(userInput);
    secureStorage.setItem('userInput', sanitized);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={userInput}
        onChange={(e) => setUserInput(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

📚 Complete Usage Guide

1. Backend Security Setup

Basic Security Module Configuration

// app.module.ts
import { SecurityModule } from 'tl-shared-security/backend';

@Module({
  imports: [
    SecurityModule.forRoot({
      // Core Security Features
      enableHelmet: true,                    // Security headers
      enableXssSanitization: true,          // XSS protection
      enableCsrf: true,                     // CSRF protection
      enableRbac: true,                     // Role-based access control
      enableRateLimiter: true,              // Rate limiting
      enableValidation: true,               // Input validation
      enableLogging: true,                  // Request logging
      enableApiSecurity: true,              // API security
      enableCors: true,                     // CORS protection
      enableAuditLog: true,                 // Audit logging
      enableSqlInjectionProtection: true,   // SQL injection protection
      enableSsrfProtection: true,           // SSRF protection
      enableSecurityMonitoring: true,       // Security monitoring
      enableSessionSecurity: true,          // Session management
      enableSecretsManager: true,           // Secrets validation
      enableSecurityHealth: true,           // Health monitoring
      
      // Rate Limiting Configuration
      rateLimiterOptions: {
        windowMs: 15 * 60 * 1000,          // 15 minutes
        max: 100,                          // 100 requests per window
        standardHeaders: true,
        legacyHeaders: false,
      },
      
      // CORS Configuration
      corsOptions: {
        origin: ['http://localhost:3000', 'https://yourdomain.com'],
        methods: ['GET', 'POST', 'PUT', 'DELETE'],
        allowedHeaders: ['Content-Type', 'Authorization'],
        credentials: true,
      },
    }),
  ],
})
export class AppModule {}

Role-Based Access Control (RBAC)

// users.controller.ts
import { Controller, Get, Post, UseGuards } from '@nestjs/common';
import { RolesGuard, Roles } from 'tl-shared-security/backend';

@Controller('users')
@UseGuards(RolesGuard)
export class UsersController {
  @Get('admin')
  @Roles('admin')
  getAdminData() {
    return { message: 'Admin-only data' };
  }

  @Get('profile')
  @Roles('user', 'admin')
  getUserProfile() {
    return { message: 'User profile data' };
  }

  @Post('create')
  @Roles('admin', 'moderator')
  createUser() {
    return { message: 'User created' };
  }
}

Multi-Factor Authentication (MFA)

// auth.controller.ts
import { Controller, Post, Body, Get, Param } from '@nestjs/common';
import { MfaService } from 'tl-shared-security/backend';

@Controller('auth')
export class AuthController {
  constructor(private mfaService: MfaService) {}

  @Post('mfa/setup')
  async setupMfa(@Body('userId') userId: string) {
    const result = await this.mfaService.generateSecret(userId);
    return {
      secret: result.secret.base32,
      qrCode: result.qrCodeDataUrl,
      backupCodes: result.secret.backupCodes,
    };
  }

  @Post('mfa/verify')
  async verifyMfa(@Body() body: { userId: string; token: string }) {
    const isValid = this.mfaService.verifyToken(body.userId, body.token);
    return { valid: isValid };
  }

  @Post('mfa/verify-backup')
  async verifyBackupCode(@Body() body: { backupCodes: string[]; code: string }) {
    const result = this.mfaService.verifyBackupCode(body.backupCodes, body.code);
    return result;
  }
}

Security Monitoring

// security.controller.ts
import { Controller, Get, Post, Param } from '@nestjs/common';
import { SecurityMonitoringService } from 'tl-shared-security/backend';

@Controller('security')
export class SecurityController {
  constructor(private securityMonitoring: SecurityMonitoringService) {}

  @Get('metrics')
  getSecurityMetrics() {
    return this.securityMonitoring.getSecurityMetrics();
  }

  @Get('events')
  getSecurityEvents() {
    return this.securityMonitoring.getUnresolvedEvents();
  }

  @Post('events/:eventId/resolve')
  resolveSecurityEvent(@Param('eventId') eventId: string) {
    const resolved = this.securityMonitoring.resolveEvent(eventId);
    return { resolved, eventId };
  }

  @Get('health')
  getSecurityHealth() {
    return this.securityMonitoring.getHealthStatus();
  }
}

2. Frontend Security Setup

XSS Protection

// components/UserInput.tsx
import React, { useState } from 'react';
import { sanitizeInput, sanitizeRecursive } from 'tl-shared-security/frontend';

export const UserInput: React.FC = () => {
  const [input, setInput] = useState('');
  const [sanitizedOutput, setSanitizedOutput] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Sanitize single input
    const sanitized = sanitizeInput(input);
    setSanitizedOutput(sanitized);
    
    // For complex objects
    const complexData = { name: input, description: '<script>alert("xss")</script>' };
    const sanitizedData = sanitizeRecursive(complexData);
    console.log('Sanitized data:', sanitizedData);
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Enter content (HTML will be sanitized)"
        />
        <button type="submit">Sanitize</button>
      </form>
      
      <div>
        <h3>Sanitized Output:</h3>
        <div dangerouslySetInnerHTML={{ __html: sanitizedOutput }} />
      </div>
    </div>
  );
};

Secure Storage

// utils/storage.ts
import { secureStorage } from 'tl-shared-security/frontend';

// Store data with encryption
secureStorage.setItem('userToken', 'jwt-token-here', 3600); // 1 hour expiry
secureStorage.setItem('userPreferences', { theme: 'dark', lang: 'en' });

// Retrieve data
const token = secureStorage.getItem('userToken');
const preferences = secureStorage.getItem('userPreferences', { theme: 'light' });

// Remove data
secureStorage.removeItem('userToken');

// Clear all data
secureStorage.clear();

// Check if item exists and is not expired
const hasValidToken = secureStorage.getItem('userToken') !== null;

Content Security Policy (CSP)

// utils/csp.ts
import { cspConfig } from 'tl-shared-security/frontend';

// Configure CSP for your application
const csp = cspConfig.generateCSP({
  defaultSrc: ["'self'"],
  scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.example.com"],
  styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
  imgSrc: ["'self'", "data:", "https:"],
  connectSrc: ["'self'", "https://api.example.com"],
  fontSrc: ["'self'", "https://fonts.gstatic.com"],
});

// Apply CSP to document
cspConfig.applyCSP(csp);

Security Scanner

// components/SecurityScanner.tsx
import React, { useState } from 'react';
import { SecurityScanner } from 'tl-shared-security/frontend';

export const ContentScanner: React.FC = () => {
  const [content, setContent] = useState('');
  const [scanResults, setScanResults] = useState<any>(null);

  const scanner = new SecurityScanner();

  const handleScan = () => {
    const results = scanner.scanContent(content);
    setScanResults(results);
  };

  return (
    <div>
      <textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        placeholder="Enter content to scan for security issues"
      />
      <button onClick={handleScan}>Scan Content</button>
      
      {scanResults && (
        <div>
          <h3>Scan Results:</h3>
          <p>Threats Found: {scanResults.threatsFound}</p>
          <p>Risk Level: {scanResults.riskLevel}</p>
          <ul>
            {scanResults.issues.map((issue: any, index: number) => (
              <li key={index}>{issue.type}: {issue.description}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

3. Cryptographic Operations

Basic Encryption/Decryption

// utils/crypto.ts
import { cryptoService } from 'tl-shared-security/crypto';

// Encrypt sensitive data
const sensitiveData = 'user-credit-card-info';
const password = 'strong-encryption-password';
const encrypted = cryptoService.encrypt(sensitiveData, password);

// Decrypt data
const decrypted = cryptoService.decrypt(encrypted, password);

// Generate secure tokens
const apiToken = cryptoService.generateToken(32); // 32 bytes = 64 hex chars
const sessionId = cryptoService.generateUUID();

Password Management

// services/auth.service.ts
import { cryptoService, passwordPolicyService } from 'tl-shared-security/crypto';

export class AuthService {
  async registerUser(email: string, password: string) {
    // Validate password strength
    const validation = passwordPolicyService.validate(password, {
      minLength: 8,
      requireUppercase: true,
      requireLowercase: true,
      requireNumbers: true,
      requireSpecialChars: true,
    });

    if (!validation.isValid) {
      throw new Error(`Password validation failed: ${validation.errors.join(', ')}`);
    }

    // Hash password securely
    const hashedPassword = await cryptoService.hashPasswordAsync(password);
    
    // Store user with hashed password
    return { email, hashedPassword };
  }

  async loginUser(email: string, password: string, hashedPassword: string) {
    // Verify password
    const isValid = await cryptoService.verifyPasswordAsync(password, hashedPassword);
    
    if (!isValid) {
      throw new Error('Invalid credentials');
    }

    return { success: true };
  }
}

JWT Token Management

// services/jwt.service.ts
import { jwtService } from 'tl-shared-security/crypto';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// Generate JWT token
const payload = { userId: 123, email: '[email protected]', roles: ['user'] };
const token = jwtService.sign(payload, JWT_SECRET, { expiresIn: '1h' });

// Verify JWT token
try {
  const decoded = jwtService.verify(token, JWT_SECRET);
  console.log('Token valid:', decoded);
} catch (error) {
  console.error('Token invalid:', error.message);
}

// Decode without verification (for debugging)
const { header, payload: decodedPayload } = jwtService.decode(token);

HMAC Signing

// utils/signing.ts
import { cryptoService } from 'tl-shared-security/crypto';

const secret = 'webhook-secret-key';
const data = JSON.stringify({ event: 'user.created', userId: 123 });

// Sign data
const signature = cryptoService.sign(data, secret);

// Verify signature
const isValid = cryptoService.verifySignature(data, signature, secret);

// For webhook verification
export function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
  return cryptoService.verifySignature(payload, signature, secret);
}

4. Advanced Security Features

Custom Security Guards

// guards/api-key.guard.ts
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { cryptoService } from 'tl-shared-security/crypto';

@Injectable()
export class ApiKeyGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const apiKey = request.headers['x-api-key'];
    
    if (!apiKey) {
      throw new UnauthorizedException('API key required');
    }

    // Verify API key using HMAC
    const expectedSignature = cryptoService.sign('api-access', process.env.API_SECRET!);
    const isValid = cryptoService.verifySignature('api-access', apiKey, process.env.API_SECRET!);
    
    if (!isValid) {
      throw new UnauthorizedException('Invalid API key');
    }

    return true;
  }
}

Environment Secrets Validation

// services/config.service.ts
import { SecretsManagerService } from 'tl-shared-security/backend';

export class ConfigService {
  constructor(private secretsManager: SecretsManagerService) {}

  validateEnvironment() {
    const validation = this.secretsManager.validateSecrets();
    
    if (!validation.valid) {
      console.error('Environment validation failed:', validation.issues);
      process.exit(1);
    }

    console.log('Environment validation passed');
  }

  getSecureConfig() {
    return {
      jwtSecret: this.secretsManager.getSecret('JWT_SECRET'),
      dbPassword: this.secretsManager.getSecret('DB_PASSWORD'),
      apiKey: this.secretsManager.getSecret('API_KEY'),
    };
  }
}

🔧 Configuration Options

SecurityModule Configuration

interface SecurityModuleOptions {
  enableHelmet?: boolean;                    // Default: true
  enableXssSanitization?: boolean;          // Default: true
  enableCsrf?: boolean;                     // Default: true
  enableRbac?: boolean;                     // Default: true
  enableRateLimiter?: boolean;              // Default: true
  enableValidation?: boolean;               // Default: true
  enableLogging?: boolean;                  // Default: true
  enableApiSecurity?: boolean;              // Default: true
  enableCors?: boolean;                     // Default: true
  enableAuditLog?: boolean;                 // Default: true
  enableSqlInjectionProtection?: boolean;   // Default: true
  enableSsrfProtection?: boolean;           // Default: true
  enableSecurityMonitoring?: boolean;       // Default: true
  enableSessionSecurity?: boolean;          // Default: true
  enableSecretsManager?: boolean;           // Default: true
  enableSecurityHealth?: boolean;           // Default: true
}

🔒 Security Best Practices

  1. Always use HTTPS in production
  2. Enable all security features by default
  3. Regularly update the package
  4. Monitor security events in real-time
  5. Use strong passwords and MFA
  6. Validate all inputs on both client and server
  7. Implement proper error handling
  8. Use secure storage for sensitive data
  9. Regular security audits
  10. Keep dependencies updated

📊 Security Compliance

This module helps achieve compliance with:

  • OWASP Top 10 - Protection against all major web vulnerabilities
  • GDPR - Data protection and privacy features
  • SOC 2 - Security monitoring and audit logging
  • PCI DSS - Cryptographic standards and secure data handling
  • NIST - Security framework compliance

🧪 Testing

# Install the package
npm install tl-shared-security

# Test backend integration
npm install @nestjs/common @nestjs/core

# Test frontend integration  
npm install react @types/react

# Run your application tests
npm test

📄 License

MIT License - see LICENSE file for details.

🆘 Support

For issues and questions:


⚠️ Security Notice: Always keep this package updated to the latest version for the most recent security patches and improvements.