npm-package-nodejs-utils-lda
v1.0.60
Published
Este projeto tem como fins de criar e abstrair módulos basicos e utilidades para o node js
Readme
npm-package-nodejs-utils
Este projeto tem como fins de criar e abstrair módulos basicos e utilidades para o node js
requires .env file config.json file data folder
automatic create requires folders and files. automatic generation of AES + RSA KEYS FOR ENCRYPTION
Functions
self-hosted status dashboard
The dashboard uses the /status route, automatically created with the function StatusDashboard(app). This means you can also use the endpoint, but don't overwrite it.
// PT-BR
O dashboard utiliza a rota /status, criado automaticamente com function StatusDashboard(app), isso significa que voce tambem pode usar o endpoint mas não o sobrescreva

Este arquivo implementa um canal criptográfico seguro no nível da aplicação, funcionando como um mini-TLS customizado, porém controlado totalmente por código. Usa padrões modernos e seguros
RSA-OAEP com SHA-256 (correto)
AES-256-GCM (estado da arte)
Proteção contra replay
Separação clara de responsabilidades
Casos de uso reais
APIs seguras entre servidores
Comunicação cliente ↔ backend sensível
Sistemas financeiros
Troca de credenciais
Licenciamento de software
Autenticação forte sem TLS customizado
Comunicação entre containers isolados
usage
import express from 'express';
import { encryptedPayloadMiddleware } from 'npm-package-nodejs-utils-lda';
const app = express();
app.use(express.json());
app.post('/secure-endpoint', encryptedPayloadMiddleware, (req, res) => {
res.json({ received: req.decryptedBody });
});
app.listen(3000, () => console.log('Servidor rodando na porta 3000'));client mode
🔑 Crypto Client Implementation (Front-end/Node.js) Para que o cliente (browser, React, ou outro servidor) possa se comunicar com segurança, ele deve:
Buscar a chave RSA pública do servidor (/public-keys/public_key.pem).
Gerar uma chave AES efêmera.
Criptografar a chave AES com a chave RSA pública (Key Exchange).
Criptografar o payload da mensagem com a chave AES (Data Encryption).
Enviar o pacote completo (AES key, IV, AuthTag, Timestamp, Nonce) ao endpoint seguro.
Exemplo de Código do Lado do Cliente (Browser/Web Crypto API)
// crypto_client.js (Implementação de referência)
// 1. Defina a URL da chave pública (deve ser a rota que você expôs)
const PUBLIC_KEY_URL = '/public-keys/public_key.pem';
const API_URL = '/secure-endpoint';
/**
* Converte um buffer para string Base64 (Web-Safe)
* @param {ArrayBuffer} buffer
* @returns {string} Base64 Web-Safe string.
*/
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}
/**
* Busca e importa a chave RSA pública do servidor.
* @returns {Promise<CryptoKey>} Chave RSA importada.
*/
async function getPublicKey() {
const response = await fetch(PUBLIC_KEY_URL);
if (!response.ok) throw new Error('Falha ao buscar chave pública do servidor.');
const pem = await response.text();
// Remove cabeçalho e rodapé PEM e trata Base64
const base64 = pem
.replace('-----BEGIN PUBLIC KEY-----', '')
.replace('-----END PUBLIC KEY-----', '')
.replace(/\s/g, '');
const binaryDer = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
// Importa a chave pública para a Web Crypto API
return crypto.subtle.importKey(
'spki',
binaryDer,
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["wrapKey"]
);
}
/**
* Criptografa o payload para ser enviado ao servidor.
* @param {object} data - O objeto JSON a ser criptografado.
* @returns {Promise<object>} O payload criptografado pronto para envio.
*/
export async function encryptAndSend(data) {
const rsaPublicKey = await getPublicKey();
// 1. Gerar Chave AES-256-GCM (Chave Secreta Efêmera)
const aesKey = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt", "wrapKey", "unwrapKey"]
);
// 2. Criptografar (Wrap) a Chave AES com a Chave RSA Pública (RSA-OAEP)
const encryptedKeyBuffer = await crypto.subtle.wrapKey(
"raw",
aesKey,
rsaPublicKey,
{ name: "RSA-OAEP" }
);
// 3. Criptografar o Payload (AES-256-GCM)
const iv = crypto.getRandomValues(new Uint8Array(12)); // Initialization Vector (IV)
const plaintext = JSON.stringify(data);
const encodedData = new TextEncoder().encode(plaintext);
const cipherBuffer = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
aesKey,
encodedData
);
// O AES-GCM anexa o AuthTag ao final do ciphertext
const authTagLength = 16; // 16 bytes para GCM
const encryptedDataBuffer = cipherBuffer.slice(0, cipherBuffer.byteLength - authTagLength);
const authTagBuffer = cipherBuffer.slice(cipherBuffer.byteLength - authTagLength);
// Gerar Timestamp e Nonce para Proteção Anti-Replay
const timestamp = Date.now();
const nonce = arrayBufferToBase64(crypto.getRandomValues(new Uint8Array(16)));
// 4. Preparar o Pacote Final
const payload = {
encryptedData: arrayBufferToBase64(encryptedDataBuffer),
encryptedKey: arrayBufferToBase64(encryptedKeyBuffer),
iv: arrayBufferToBase64(iv.buffer),
authTag: arrayBufferToBase64(authTagBuffer),
timestamp: timestamp,
nonce: nonce
};
// 5. Enviar para o Servidor
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
return response.json();
}
// Exemplo de uso:
/*
encryptAndSend({ nome: "Luis das Artimanhas", valor: 500.00 })
.then(res => console.log("Resposta do Servidor:", res))
.catch(err => console.error("Erro na comunicação segura:", err));
*/user system
insertUser(name,userdata);
return userdata saved
selectUser(ID);
return userdata
usersList();
return users ID,name
deleteUser(ID);
alterUser(ID, name, newUserData);
disableUser(ID);
reactivateUser(ID);STORAGE
Express (ESM)
import express from "express";
import { saveFile, saveBot } from "npm-package-nodejs-utils-lda";
const app = express();
app.post("/upload/page", saveFile.single("file"), (req, res) => {
res.json({ ok: true, file: req.file });
});
app.post("/upload/bot", saveBot.single("file"), (req, res) => {
res.json({ ok: true, file: req.file });
});mongo DB
mongoConnect(connectionString)
// SET 'MONGO_CONNECTION_STRING' VARIABLE IN .ENV FILE FOR SECURE AND AUTOMATIC CONNECTION
mongoConnect()
// connection = await mongoConnect(connectionString);
select(connection, database, table)
return all data of selected table
insert(connection, database, table, data)
return mongoClient or connectionAUTH
const { requestAuthCode } = require("npm-package-nodejs-utils-lda");
/**
* POST /api/auth/request-code
* Body: { email: string }
*/
router.post("/request-code", async (req, res) => {
try {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: "Email é obrigatório" });
}
await requestAuthCode(email);
return res.status(200).json({
success: true,
message: "Código enviado para o email",
});
} catch (err) {
console.error(err);
return res.status(500).json({
error: "Erro ao enviar código",
});
}
});
module.exports = router;verify codes
const { verifyAuthCode } = require("npm-package-nodejs-utils-lda");
app.post("/api/auth/verify-code", async (req, res) => {
try {
const { email, code } = req.body;
await verifyAuthCode(email, code);
res.json({ success: true });
} catch (err) {
res.status(401).json({ error: err.message });
}
});Generals Usage
import { fopen, fwrite, generateToken, fetchGet } from "npm-package-nodejs-utils-lda";
const filePath = "database.json"
// Usando as funções
const data = fopen(filePath);
data.push("X");
fwrite(filePath, data);
const token = generateToken();
fetchGet("https://example.com",null, (onError,data)=>{
if(onError){
res.send(error);
}
res.send(data);
});
app.get("/baixar", (req, res) => {
const fileUrl = "https://exemplo.com/arquivo.zip"; // URL do arquivo
fetchDownloadStream(fileUrl, (err, fileStream) => {
if (err) {
return res.status(500).send("Erro ao baixar o arquivo.");
}
// Define o cabeçalho para download
res.setHeader("Content-Disposition", 'attachment; filename="arquivo.zip"');
res.setHeader("Content-Type", "application/octet-stream");
// Envia o stream do arquivo para o cliente
fileStream.pipe(res);
});
});
# WSChat
## With Express (recommended)
If you already have an Express server, just pass the app instance to WSChat:
````js
import express from "express";
import WSChat from "./WSchat.lib.mjs"; // or require() for CommonJS
const app = express();
const server = WSChat(app, {
welcomeMessage: "Hello! Welcome to the chat."
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});This creates the HTTP + WebSocket server using the same Express server.
Without Express (standalone WebSocket server)
If you want to run WSChat alone, without Express:
import WSChat from "./WSchat.lib.mjs";
WSChat(null, { port: 8080 }); // starts HTTP + WS server on port 8080Options
The second argument is an optional object with the following properties:
{
port: 8080, // Number - Port to listen on if WSChat creates its own HTTP server (default 8080)
welcomeMessage: "Welcome to WSChat!" // String - Message sent to clients immediately after connection
}