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

serverless-crypto-utils

v1.4.0

Published

Complete crypto toolkit for serverless & Edge platforms: password hashing, secure access tokens, ID generation. Zero dependencies, Web Crypto API only.

Readme

🔒 Serverless Crypto Utilities

🇺🇸 English | 🇧🇷 Português

npm npm downloads Build License: MIT

Serverless Crypto Utilities é um pacote minimalista para operações criptográficas rápidas e seguras na Edge.

O pacote fornece funções para hashing, criptografia, geração de tokens e outras operações criptográficas, projetadas para máxima performance, baixo bundle size e segurança nativa.

Todas as funções utilizam exclusivamente a Web Crypto API, sem dependências externas.

🔹 Estrutura do Pacote

O pacote é dividido em categorias de funções:

| Categoria | Descrição | Exemplos de Funções | | :-------------------------------------------------------- | :---------------------------------------------------------------------------------- | :------------------------------------------- | | password-hashing README | Funções para gerar e verificar hashes de senhas (PBKDF2-HMAC-SHA256) | hashPassword, verifyPassword | | access-token README | Funções para criar e verificar tokens de acesso seguros (AES-256-GCM + HMAC-SHA256) | createAccessToken, verifyAccessTokenSafe | | id-generation README | Funções para gerar IDs únicos | uuidV4, ulid | | encryption README | Funções para criptografia e descriptografia simétrica (AES-256-GCM) | encrypt, decrypt, encryptObject |

Atualmente o pacote inclui módulos para hashing de senhas, tokens de acesso seguros, geração de IDs e criptografia de dados. Novos módulos serão adicionados progressivamente.


✅ Por Que Usar?

  • Velocidade na Edge: Utiliza a API nativa do runtime, otimizada para o serverless.
  • Portabilidade: Funciona em qualquer plataforma que suporte o runtime Web Crypto (Cloudflare, Deno, etc.).
  • Segurança: Implementa algoritmos padrão do setor para autenticação e hashing de senhas.

⚡ Instalação

npm install serverless-crypto-utils
# ou
yarn add serverless-crypto-utils
# ou
pnpm add serverless-crypto-utils

📦 Bundle Size Optimization

Importação Modular vs Completa

| Módulo | Size (ESM) | Size (CJS) | Use Case | | :----------------- | :--------- | :--------- | :------------------------ | | password-hashing | 117 B | 3.45 KB | Apenas autenticação | | access-token | 219 B | 9.43 KB | Apenas tokens seguros | | id-generation | 85 B | 1.64 KB | Apenas geração de IDs | | encryption | 165 B | 4.21 KB | Apenas criptografia | | Full package | 564 B | 16.74 KB | Múltiplas funcionalidades |

Exemplo de Otimização

// ❌ Bundle maior (16.74 KB)
import { hashPassword } from "serverless-crypto-utils";

// ✅ Bundle menor (3.45 KB)
import { hashPassword } from "serverless-crypto-utils/password-hashing";

Redução de até 79% no bundle size usando imports modulares! 🚀

Para reduzir o bundle size, você pode importar apenas as funções que precisa:

// Apenas password hashing
import {
  hashPassword,
  verifyPassword,
} from "serverless-crypto-utils/password-hashing";

// Apenas access tokens
import {
  createAccessToken,
  verifyAccessTokenSafe,
} from "serverless-crypto-utils/access-token";

// Apenas ID generation
import { uuidV4, ulid } from "serverless-crypto-utils/id-generation";

// Apenas criptografia
import {
  encrypt,
  decrypt,
  encryptObject,
  decryptObject,
} from "serverless-crypto-utils/encryption";

📦 Import Completo

Ou importe tudo de uma vez:

import {
  hashPassword,
  verifyPassword,
  createAccessToken,
  verifyAccessTokenSafe,
  uuidV4,
  ulid,
  encrypt,
  decrypt,
  encryptObject,
  decryptObject,
} from "serverless-crypto-utils";

🚀 Uso Básico

Password Hashing

import {
  hashPassword,
  verifyPassword,
} from "serverless-crypto-utils/password-hashing";

const pepper = process.env.PEPPER || "secretGlobalPepper";

const hash = await hashPassword("superSenha123", { pepper });
const isValid = await verifyPassword("superSenha123", hash, { pepper });

console.log("Hash:", hash);
console.log("Senha correta?", isValid);

Access Token

import {
  createAccessToken,
  verifyAccessTokenSafe,
  TokenErrorCode,
} from "serverless-crypto-utils/access-token";

// Criar token
const token = await createAccessToken({
  encryptionSecret: process.env.TOKEN_ENCRYPTION_SECRET,
  signingSecret: process.env.TOKEN_SIGNING_SECRET,
  payload: { userId: 123, role: "admin" },
  expiresInSeconds: 900, // 15 minutos
});

// Verificar token
const result = await verifyAccessTokenSafe({
  encryptionSecret: process.env.TOKEN_ENCRYPTION_SECRET,
  signingSecret: process.env.TOKEN_SIGNING_SECRET,
  accessToken: token,
});

if (result.success) {
  const user = JSON.parse(result.data);
  console.log("Acesso autorizado:", user.userId);
} else {
  console.log("Acesso negado:", result.error.message);
}

Criptografia de Dados

import {
  encrypt,
  decrypt,
  encryptObject,
  decryptObject,
} from "serverless-crypto-utils/encryption";

const secret = process.env.ENCRYPTION_SECRET || "minhaChaveSecreta";

// Criptografar string sensível
const encrypted = await encrypt("dados sensíveis", secret);
console.log("Criptografado:", encrypted); // "ivBase64.encryptedDataBase64"

// Descriptografar de volta ao original
const decrypted = await decrypt(encrypted, secret);
console.log("Descriptografado:", decrypted); // "dados sensíveis"

// Criptografar objetos
const usuario = { id: 123, email: "[email protected]" };
const usuarioCriptografado = await encryptObject(usuario, secret);
const usuarioDescriptografado = await decryptObject(
  usuarioCriptografado,
  secret
);
console.log("Usuário:", usuarioDescriptografado); // { id: 123, email: "[email protected]" }

ID Generation

import { uuidV4, ulid } from "serverless-crypto-utils/id-generation";

// Gerar UUID v4
const uuid = uuidV4();
console.log("UUID:", uuid); // e.g. "3b12f1df-5232-4f0c-8b1d-3f3f9f1b5ec1"

// Gerar ULID (lexicograficamente ordenável)
const ulidId = ulid();
console.log("ULID:", ulidId); // e.g. "01F8MECHZX3TBDSZ7EXAMPLE"

Para detalhes completos, consulte:

🔒 Segurança

Todos os algoritmos usam a Web Crypto API nativa, garantindo segurança nativa e compatibilidade com Workers.

  • Password Hashing: Salt aleatório e pepper opcional para proteção adicional.
  • Access Tokens: Criptografia AES-256-GCM + assinatura HMAC-SHA256 com expiração automática.
  • Comparações timing-safe para evitar ataques de tempo.
  • Zero dependências externas para minimizar superfície de ataque.

📌 Roadmap

| # | Funcionalidade | Status | | --- | ----------------------------------------- | --------- | | ✅ | Password hashing (PBKDF2-HMAC-SHA256) | Concluído | | ✅ | Access tokens (AES-256-GCM + HMAC-SHA256) | Concluído | | ✅ | Geração de IDs únicos (UUID, ULID) | Concluído | | ✅ | Criptografia de dados (AES-256-GCM) | Concluído | | 🔄 | Hashing genérico (SHA-256, SHA-512) | Planejado | | 🔄 | Helpers para JWT | Planejado |

🤝 Contribuição

Contribuições, sugestões e correções são bem-vindas! Abra issues ou PRs no GitHub para colaborar.