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

@jsbytecore/jsbyte-crypto

v1.1.0

Published

Security toolkit for Node.js: password hashing (PBKDF2) and signed token system (JWT-like) using native crypto.

Readme


📄 README.md COMPLETO (Hash + Token)

# @jsbytecore/jsbyte-crypto

🔐 Módulo de segurança para Node.js sem dependências externas.

Inclui:

- Hash seguro de senha (PBKDF2 + SHA-256)
- Sistema de token assinado estilo JWT próprio (HS256)
- Comparação segura contra timing attacks
- Zero dependências externas (usa apenas `crypto` nativo do Node.js)

---

## 🚀 Instalação

```bash
npm install @jsbytecore/jsbyte-crypto

🔐 Parte 1 — Hash de Senha

✨ Features

  • PBKDF2 + SHA-256
  • Salt criptograficamente seguro
  • 120.000 iterações
  • Formato auto-contido
  • Proteção contra timing attacks

📦 Uso Básico

const {
  hashPassword,
  verifyPassword,
  config,
} = require("@jsbytecore/jsbyte-crypto");

const senha = "minhaSenhaUltraSecreta";

// Criar hash
const hash = hashPassword(senha);
console.log(hash);

// Verificar senha
const ok = verifyPassword("minhaSenhaUltraSecreta", hash);
console.log(ok); // true

🧠 Formato do Hash

Formato armazenado no banco:

pbkdf2$sha256$120000$64$saltHex$hashHex

Isso permite:

  • Migrar parâmetros futuramente
  • Manter compatibilidade
  • Armazenar tudo em um único campo

🧩 API — Hash

hashPassword(password: string): string

Gera hash seguro.

verifyPassword(password: string, storedHash: string): boolean

Valida senha contra hash salvo.

config

Retorna configuração padrão:

{
  ITERATIONS: 120000,
  KEYLEN: 64,
  DIGEST: "sha256",
  SALT_BYTES: 16
}

🎫 Parte 2 — Sistema de Token Assinado (JWT-like)

Este módulo inclui um sistema próprio de token assinado no formato:

header.payload.signature

Compatível com padrão JWT (HS256), mas implementado manualmente usando crypto.


🔐 Criar Token

const { JsByteToken } = require("@jsbytecore/jsbyte-crypto");

const tokenService = new JsByteToken({
  secret: "minha-chave-super-secreta"
});

const token = tokenService.sign(
  {
    userId: 123,
    email: "[email protected]"
  },
  {
    expiresIn: 60 * 60 // 1 hora
  }
);

console.log(token);

✅ Verificar Token

const result = tokenService.verify(token);

if (result.valid) {
  console.log("Payload:", result.payload);
} else {
  console.log("Erro:", result.reason);
}

🧩 API — Token

new JsByteToken({ secret })

Cria serviço de token.

sign(payload, { expiresIn })

Cria token assinado.

verify(token)

Retorna:

{
  valid: boolean,
  payload?: object,
  reason?: string
}

Possíveis erros:

  • INVALID_FORMAT
  • INVALID_SIGNATURE
  • TOKEN_EXPIRED
  • INVALID_PAYLOAD

🧱 Exemplo Completo — Login com Token

Registro

const { hashPassword } = require("@jsbytecore/jsbyte-crypto");

async function registerUser(db, { name, email, password }) {
  const password_hash = hashPassword(password);

  await db.insert("users", {
    name,
    email,
    password_hash,
    created_at: new Date().toISOString(),
  });
}

Login

const {
  verifyPassword,
  JsByteToken
} = require("@jsbytecore/jsbyte-crypto");

const tokenService = new JsByteToken({
  secret: process.env.JWT_SECRET || "dev-secret"
});

async function loginUser(db, { email, password }) {
  const users = await db.find("users", { email });
  const user = users?.[0];

  if (!user) {
    return { ok: false };
  }

  const valid = verifyPassword(password, user.password_hash);

  if (!valid) {
    return { ok: false };
  }

  const token = tokenService.sign(
    {
      sub: user.id,
      email: user.email
    },
    {
      expiresIn: 3600
    }
  );

  return {
    ok: true,
    token
  };
}

🛡 Middleware de Proteção

function authMiddleware(tokenService) {
  return (req, res, next) => {
    const auth = req.headers.authorization;

    if (!auth || !auth.startsWith("Bearer ")) {
      return res.status(401).json({ error: "NO_TOKEN" });
    }

    const token = auth.slice(7);

    const result = tokenService.verify(token);

    if (!result.valid) {
      return res.status(401).json({ error: result.reason });
    }

    req.user = result.payload;
    next();
  };
}

⚠️ Boas Práticas

  • Sempre use HTTPS
  • Use segredo forte em produção
  • Armazene segredo em .env
  • Implemente rate limit
  • Nunca exponha secret no frontend

🔥 Arquitetura Recomendada

Use:

  • Hash para armazenamento de senha
  • Token para autenticação stateless
  • Middleware para proteção de rotas

📜 Licença

MIT License Desenvolvido por Jean Gomes (@jsbytecore)