securend
v1.0.3
Published
a light fastify api endpoint with basic authentication
Downloads
301
Readme
secury
Production-grade REST API factory with JWE & HMAC encryption for Node.js
secury is a lightweight, secure REST API framework built on top of Fastify. It provides enterprise-grade security features including JWE (JSON Web Encryption) decryption, HMAC signature verification, Bearer/Basic authentication, and built-in production hardening via Helmet and CORS — all with zero configuration required.
Features
- 🔐 JWE Decryption - Automatically decrypt RSA-OAEP-256 encrypted payloads
- 🛡️ HMAC Integrity - SHA-256 request signature verification
- 🔑 Authentication - Built-in Bearer token and Basic auth support
- 🚀 Fastify Powered - High-performance HTTP handling
- 🏢 Production Ready - Helmet security headers, CORS, graceful shutdown
- 📦 Zero Config - Sensible defaults, fully extensible
Installation
npm install securyQuick Start
const secury = require('secury');
const app = secury({
bearer: 'my-secret-token',
verbose: true
});
// Define routes
app.get('/hello', async (ctx, res) => {
return res({ message: 'Hello, World!' });
});
app.listen({ port: 3000 }, (err) => {
if (err) throw err;
console.log('Server running on http://localhost:3000');
});API Reference
secury(options)
Creates and returns a Fastify instance with enhanced security middleware.
Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| bearer | string | null | Static Bearer token for authentication |
| basic | object | null | Basic auth credentials { user, pass } |
| security | object | {} | Encryption settings (see below) |
| verbose | boolean\\|function | false | Enable logging or provide custom logger |
| cors | boolean\\|object | true | Enable CORS (pass object for custom config) |
| limit | string | '1mb' | Request body size limit |
| trustProxy | boolean | true | Trust proxy headers |
Security Options
{
security: {
jwePrivateKey: '-----BEGIN PRIVATE KEY-----...', // RSA private key for JWE decryption
hmacSecret: 'your-hmac-secret-key' // Secret for HMAC signature verification
}
}Route Methods
Pass route definitions in the options object:
get- GET routespost- POST routesput- PUT routesdelete- DELETE routespatch- PATCH routes
Usage Examples
Basic Authentication
const app = secury({
basic: { user: 'admin', pass: 'secret123' }
});Bearer Token Authentication
const app = secury({
bearer: process.env.API_TOKEN
});JWE Decryption
Automatically decrypts JWE compact serialization payloads:
const app = secury({
security: {
jwePrivateKey: process.env.RSA_PRIVATE_KEY
}
});
// POST with JWE encrypted body will be automatically decrypted
app.post('/secure', async (ctx, res) => {
// ctx.body is the decrypted JSON payload
return res({ received: ctx.body });
});HMAC Signature Verification
Verifies request integrity using SHA-256 HMAC:
const app = secury({
security: {
hmacSecret: 'your-webhook-secret'
}
});
// Client must include: X-Signature: sha256=<hex_digest>
app.post('/webhook', async (ctx, res) => {
return res({ verified: true });
});Combined Security
const app = secury({
bearer: process.env.API_TOKEN,
security: {
jwePrivateKey: process.env.RSA_PRIVATE_KEY,
hmacSecret: process.env.HMAC_SECRET
},
cors: { origin: 'https://trusted-domain.com' },
verbose: true
});Route Configuration with Schema
const app = secury({
post: {
'/users': {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
},
required: ['name', 'email']
}
},
handler: async (ctx, res) => {
const { name, email } = ctx.body;
// Create user...
return res({ id: 1, name, email }, 201);
}
}
}
});Handler Context
Each handler receives:
async (ctx, res) => {
ctx.query // Query parameters
ctx.params // URL parameters
ctx.body // Request body (decrypted if JWE enabled)
ctx.headers // Request headers
ctx.ip // Client IP
ctx.req // Raw Fastify request object
// Response helpers
res(data) // Send response
res(data, 201) // Send with status code
res.status(201).send(data) // Chain status
}Error Handling
secury automatically handles errors and returns appropriate HTTP responses:
- 401 Unauthorized - Invalid or missing authentication
- 403 Forbidden - Invalid HMAC signature
- 400 Bad Request - JWE decryption failed
- 500 Internal Server Error - Unexpected errors (with stack trace in verbose mode)
Dependencies
- fastify - Fast and low overhead web framework
- @fastify/helmet - Security headers
- @fastify/cors - CORS handling
- jose - JWE/JWS/JWT implementation
Requirements
- Node.js >= 14.0.0
License
MIT © littlejustnode
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
For bugs and feature requests, please open an issue.
