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

aegis-security

v1.0.0

Published

Deterministic guardian for AI-generated code - detect and fix security vulnerabilities

Readme

🛡️ Aegis.js

Guardian determinístico para código gerado por IA

npm version License: MIT TypeScript Zero Dependencies

Aegis.js é uma biblioteca zero-dependency de análise estática de segurança que detecta e corrige automaticamente vulnerabilidades em código JavaScript gerado por ferramentas de IA como GitHub Copilot, ChatGPT, Claude, e outras.

✨ Características

  • 🔍 Detecção Determinística: Algoritmos precisos, não baseados em IA
  • Ultra-Rápido: < 5ms por arquivo (1000 linhas)
  • 🔧 Auto-Fix Inteligente: Corrige vulnerabilidades automaticamente quando seguro
  • 📦 Zero Dependências: Nenhuma dependência externa
  • 🎯 Alta Precisão: > 95% detection rate, < 5% false positives
  • 🛡️ 6 Vulnerabilidades Críticas: eval(), SQL Injection, Secrets, Command Injection, XSS, Path Traversal
  • 💪 TypeScript First: Tipos completos incluídos
  • 🚀 Leve: < 50KB minified + gzipped

📦 Instalação

npm install aegis.js

🚀 Uso Rápido

API Simples (Guard)

import { guard } from 'aegis.js';

// Auto-detecta e auto-corrige vulnerabilidades
const aiGeneratedCode = `eval('{"x": 1}');`;
const safeCode = await guard(aiGeneratedCode);
// Resultado: JSON.parse('{"x": 1}');

API Detalhada (Validate)

import { validate } from 'aegis.js';

const code = `
const apiKey = "sk-1234567890abcdef1234567890abcdef";
db.query(\`SELECT * FROM users WHERE id = \${userId}\`);
`;

const result = await validate(code, { autoFix: true });

console.log(result);
// {
//   safe: false,
//   issues: [
//     {
//       type: 'CRITICAL',
//       rule: 'no-hardcoded-secrets',
//       message: 'Hardcoded secret detected...',
//       line: 2,
//       autoFixable: true,
//       fix: 'Move to environment variables: process.env.API_KEY'
//     },
//     {
//       type: 'CRITICAL',
//       rule: 'no-sql-injection',
//       message: 'SQL Injection risk...',
//       line: 3,
//       autoFixable: true,
//       fix: 'Use parameterized queries'
//     }
//   ],
//   fixed: "const apiKey = process.env.API_KEY;\ndb.query('SELECT * FROM users WHERE id = ?', [userId]);",
//   autoFixed: true,
//   stats: {
//     linesScanned: 4,
//     issuesFound: 2,
//     issuesFixed: 2,
//     criticalIssues: 2
//   }
// }

🎯 Vulnerabilidades Detectadas

| Vulnerabilidade | CWE | Auto-Fix | Severidade | |----------------|-----|----------|------------| | eval() / Code Execution | CWE-95 | ✅ | CRITICAL | | SQL Injection | CWE-89 | ✅ | CRITICAL | | Hardcoded Secrets | CWE-798 | ✅ | CRITICAL | | Command Injection | CWE-78 | ⚠️ | CRITICAL | | Cross-Site Scripting (XSS) | CWE-79 | ❌ | HIGH | | Path Traversal | CWE-22 | ❌ | HIGH |

🔧 Exemplos de Auto-Fix

1. eval() → JSON.parse()

// ❌ Antes (Vulnerável)
eval('{"x": 1}');

// ✅ Depois (Seguro)
JSON.parse('{"x": 1}');

2. SQL Injection → Parameterized Query

// ❌ Antes (Vulnerável)
db.query(`SELECT * FROM users WHERE id = ${userId}`);

// ✅ Depois (Seguro)
db.query('SELECT * FROM users WHERE id = ?', [userId]);

3. Hardcoded Secret → Environment Variable

// ❌ Antes (Vulnerável)
const apiKey = "sk-1234567890abcdef1234567890abcdef";

// ✅ Depois (Seguro)
const apiKey = process.env.API_KEY;

4. Command Injection → execFile()

// ❌ Antes (Vulnerável)
exec(`rm ${filename}`);

// ✅ Depois (Seguro)
execFile('rm', [filename]);

📚 Casos de Uso

🤖 Validar Sugestões do GitHub Copilot

import { validate } from 'aegis.js';

// Integração com editor/IDE
editor.onCopilotSuggestion(async (suggestion) => {
    const result = await validate(suggestion.code);
    
    if (result.stats.criticalIssues > 0) {
        showWarning('⚠️ Código sugerido contém vulnerabilidades!');
        showQuickFix(result.issues);
    }
});

🔄 CI/CD Pipeline

# .github/workflows/security.yml
name: Security Scan
on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
      - run: npm install aegis.js
      - run: node security-scan.js
// security-scan.js
import { validate } from 'aegis.js';
import * as fs from 'fs';
import * as glob from 'glob';

const files = glob.sync('src/**/*.{js,ts}');
let hasIssues = false;

for (const file of files) {
    const code = fs.readFileSync(file, 'utf-8');
    const result = await validate(code);
    
    if (result.stats.criticalIssues > 0) {
        console.error(`❌ ${file}: ${result.stats.criticalIssues} critical issue(s)`);
        hasIssues = true;
    }
}

if (hasIssues) {
    process.exit(1);
}

📝 Pre-commit Hook

# .husky/pre-commit
#!/bin/sh
node pre-commit-check.js
// pre-commit-check.js
import { validate } from 'aegis.js';
import { execSync } from 'child_process';
import * as fs from 'fs';

const stagedFiles = execSync('git diff --cached --name-only --diff-filter=ACM')
    .toString()
    .split('\n')
    .filter(f => f.endsWith('.js') || f.endsWith('.ts'));

for (const file of stagedFiles) {
    const code = fs.readFileSync(file, 'utf-8');
    const result = await validate(code, { autoFix: true });
    
    if (result.autoFixed) {
        fs.writeFileSync(file, result.fixed);
        execSync(`git add ${file}`);
        console.log(`✅ ${file} auto-fixed`);
    }
    
    if (result.stats.criticalIssues > 0) {
        console.error(`❌ ${file} still has critical issues`);
        process.exit(1);
    }
}

🎯 VS Code Extension

import { validate } from 'aegis.js';

// Validação em tempo real
vscode.workspace.onDidSaveTextDocument(async (document) => {
    if (document.languageId === 'javascript' || document.languageId === 'typescript') {
        const result = await validate(document.getText());
        
        // Mostra diagnostics no editor
        diagnosticCollection.set(document.uri, 
            result.issues.map(issue => new vscode.Diagnostic(
                new vscode.Range(issue.line - 1, issue.column, issue.line - 1, 100),
                issue.message,
                vscode.DiagnosticSeverity.Error
            ))
        );
    }
});

⚙️ Configuração Avançada

Regras Customizadas

const result = await validate(code, {
    rules: {
        noEval: 'error',              // Bloqueia eval()
        noSqlInjection: 'error',      // Bloqueia SQL injection
        noHardcodedSecrets: 'error',  // Bloqueia secrets
        noCommandInjection: 'warn',   // Apenas avisa
        noXSS: 'warn',                // Apenas avisa
        noPathTraversal: 'off'        // Desabilita
    },
    autoFix: true,
    strict: false,
    throwOnError: true
});

Opções Disponíveis

interface GuardOptions {
    rules?: {
        noEval?: 'error' | 'warn' | 'off';
        noSqlInjection?: 'error' | 'warn' | 'off';
        noHardcodedSecrets?: 'error' | 'warn' | 'off';
        noCommandInjection?: 'error' | 'warn' | 'off';
        noXSS?: 'error' | 'warn' | 'off';
        noPathTraversal?: 'error' | 'warn' | 'off';
    };
    autoFix?: boolean;      // Aplica correções automáticas (padrão: true)
    strict?: boolean;       // Para no primeiro erro crítico (padrão: false)
    throwOnError?: boolean; // Lança exceção em erros críticos (padrão: true)
}

📊 Performance

  • < 5ms por arquivo de 1000 linhas
  • 💾 < 10MB de uso de memória
  • 📦 < 50KB bundle size (minified + gzipped)
  • 🚫 Zero dependências externas

Benchmark

npm run benchmark
🚀 Aegis.js Performance Benchmark
============================================================

📊 Test 1: Small code (~5 lines, clean)
  Average: 0.42ms
  Throughput: 11 lines/ms
  ✅ Target: <5ms (PASS)

📊 Test 2: Medium code (~500 lines, clean)
  Average: 3.21ms
  Throughput: 155 lines/ms
  ✅ Target: <50ms (PASS)

📊 Test 3: Large code (~5000 lines, clean)
  Average: 28.45ms
  Throughput: 175 lines/ms
  ✅ Target: <500ms (PASS)

🧪 Testes

# Executar testes
npm test

# Executar benchmark
npm run benchmark

# Build
npm run build

📖 Documentação

🤝 Contribuindo

Contribuições são bem-vindas! Por favor:

  1. Fork o repositório
  2. Crie uma branch para sua feature (git checkout -b feature/nova-feature)
  3. Commit suas mudanças (git commit -am 'Adiciona nova feature')
  4. Push para a branch (git push origin feature/nova-feature)
  5. Abra um Pull Request

📝 Licença

MIT © [Seu Nome]

🙏 Agradecimentos

  • Inspirado pela necessidade de segurança em código gerado por IA
  • Baseado em padrões do OWASP e CWE
  • Desenvolvido com ❤️ para a comunidade

🔗 Links


Aegis.js - Protegendo seu código gerado por IA 🛡️