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

sft-token

v1.0.10

Published

Secure Flex Token (SFT) - Custom authentication solution with AES and HMAC security

Readme

Secure Function Token (SFT)

Node.js Security License

Uma implementação robusta e segura para criação e verificação de tokens criptográficos utilizando AES-256-GCM e HMAC-SHA256.

🚀 Características

  • 🔒 Criptografia Forte: AES-256-GCM para dados privados
  • 📝 Assinatura Segura: HMAC-SHA256 para integridade
  • 🔑 Derivação de Chaves: PBKDF2 com dois fatores
  • ⚡ Múltiplos Níveis de Segurança: Low, Medium e High
  • ⏰ Expiração Controlada: TTL personalizável
  • 🌐 Base64 URL-safe: Compatível com URLs e HTTP
  • 🛡️ Resistente a Timing Attacks: Verificação segura de assinaturas

📦 Instalação

npm install

🎯 Uso Rápido

const SFT = require('./sft');

// Configuração
const data = {
    private: { user_id: 123, role: 'admin' },
    public: { name: 'John Doe' },
    scope: 'read:write'
};

const password1 = "secure_password_1";
const password2 = "secure_password_2";
const contextSalt = Buffer.from("my_app_context");

// Criar e verificar token
async function exemplo() {
    try {
        // Criar token
        const token = await SFT.createToken(
            data, 
            password1, 
            password2, 
            contextSalt, 
            'high',
            1800 // 30 minutos
        );
        
        console.log('🔐 Token:', token);

        // Verificar token
        const verified = await SFT.verifyToken(
            token,
            password1,
            password2,
            contextSalt,
            'high'
        );
        
        console.log('✅ Dados verificados:', verified);
        
    } catch (error) {
        console.error('❌ Erro:', error.message);
    }
}

exemplo();

📖 Documentação

SFT.createToken(data, password1, password2, [contextSalt], [securityLevel], [ttl])

Cria um novo token seguro.

Parâmetros:

  • data (Object): Dados do token
    • private (Object): Dados criptografados
    • public (Object): Dados públicos
    • scope (String): Escopo do token
  • password1, password2 (String): Passwords para derivação de chaves
  • contextSalt (Buffer): Salt contextual (opcional)
  • securityLevel (String): "low", "medium" ou "high" (padrão: "medium")
  • ttl (Number): Time-to-live em segundos (padrão: 30)

Retorna: Promise<string> - Token SFT

SFT.verifyToken(token, password1, password2, [contextSalt], [securityLevel])

Verifica e decodifica um token.

Parâmetros:

  • token (String): Token SFT a ser verificado
  • password1, password2 (String): Passwords usados na criação
  • contextSalt (Buffer): Salt contextual (opcional)
  • securityLevel (String): Nível de segurança (padrão: "medium")

Retorna: Promise<Object> - Dados decodificados

SFT.deriveKeys(password1, password2, securityLevel, [contextSalt])

Deriva chaves de criptografia e HMAC.

Parâmetros:

  • password1, password2 (String): Passwords de entrada
  • securityLevel (String): Nível de segurança
  • contextSalt (Buffer): Salt adicional (opcional)

Retorna: Promise<Object> - { encryptionKey, hmacKey }

🛡️ Níveis de Segurança

| Nível | Algoritmo | Iterações | Casos de Uso | |-------|-----------|-----------|-------------| | low | SHA-256 | 10,000 | Desenvolvimento, testes | | medium | SHA-256 | 100,000 | Produção geral | | high | SHA-512 | 1,000,000 | Dados sensíveis, financeiro |

🔧 Estrutura do Token

O token SFT possui 6 componentes:

iv.encryptedData.authTag.publicData.nonce.signature
  • iv (12 bytes): Vector de inicialização para AES-GCM
  • encryptedData: Dados privados criptografados
  • authTag (16 bytes): Tag de autenticação GCM
  • publicData: Dados públicos em JSON (base64 URL-safe)
  • nonce: Identificador único da sessão
  • signature: Assinatura HMAC-SHA256

📋 Exemplos Avançados

Exemplo 1: Token com Dados Complexos

const complexData = {
    private: {
        user_id: 12345,
        permissions: ['read', 'write', 'delete'],
        session_data: { login_time: Date.now() }
    },
    public: {
        username: 'johndoe',
        email: '[email protected]',
        avatar: 'https://example.com/avatar.jpg'
    },
    scope: 'user:admin'
};

const token = await SFT.createToken(complexData, pwd1, pwd2, salt, 'high', 3600);

Exemplo 2: Verificação com Tratamento de Erros

async function verifyUserToken(token) {
    try {
        const data = await SFT.verifyToken(
            token,
            process.env.PASSWORD1,
            process.env.PASSWORD2,
            Buffer.from(process.env.CONTEXT_SALT),
            'medium'
        );
        
        return {
            success: true,
            data: data,
            user: data.public.username
        };
        
    } catch (error) {
        return {
            success: false,
            error: error.message,
            expired: error.message.includes('expired'),
            invalid: error.message.includes('Invalid signature')
        };
    }
}

Exemplo 3: Benchmark de Performance

// Executar benchmark (100 iterações)
node sft.js

Saída esperada:

Benchmark Results (100 iterations):
Token Creation:
  Average: 45.234 ms
  Min: 42.123 ms
  Max: 52.456 ms

Token Verification:
  Average: 23.567 ms
  Min: 21.890 ms
  Max: 28.901 ms

🔐 Melhores Práticas

1. Gerenciamento de Secrets

// Use variáveis de ambiente
const password1 = process.env.SFT_PASSWORD1;
const password2 = process.env.SFT_PASSWORD2;
const contextSalt = Buffer.from(process.env.SFT_CONTEXT_SALT);

2. Escolha do Nível de Segurança

// Desenvolvimento
const devLevel = 'low';

// Produção geral
const prodLevel = 'medium';

// Dados críticos
const criticalLevel = 'high';

3. Validação de Input

function validateTokenData(data) {
    if (!data.private || typeof data.private !== 'object') {
        throw new Error('Dados privados inválidos');
    }
    if (!data.scope || typeof data.scope !== 'string') {
        throw new Error('Escopo inválido');
    }
}

🚨 Tratamento de Erros

| Erro | Causa | Solução | |------|-------|---------| | Invalid token format | Token malformado | Verificar estrutura | | Invalid signature | Assinatura inválida | Verificar passwords | | Token expired | TTL expirado | Renovar token | | Invalid security level | Nível não suportado | Usar 'low', 'medium' ou 'high' |

📊 Performance

O módulo inclui sistema de benchmarking integrado. Execute para testar performance no seu ambiente:

node sft.js

🤝 Contribuição

  1. Fork o projeto
  2. Crie uma branch para sua feature (git checkout -b feature/AmazingFeature)
  3. Commit suas mudanças (git commit -m 'Add some AmazingFeature')
  4. Push para a branch (git push origin feature/AmazingFeature)
  5. Abra um Pull Request

📄 Licença

Distribuído sob licença MIT. Veja LICENSE para mais informações.

⚠️ Avisos de Segurança

  • NUNCA comite passwords ou salts no código
  • Use sempre variáveis de ambiente para dados sensíveis
  • Rotacione passwords periodicamente em produção
  • Valide sempre os dados de entrada
  • Use o nível de segurança apropriado para seu caso de uso

Desenvolvido com ❤️ para aplicações seguras