1.1.0 • Published 6 months ago
securestate v1.1.0
Secure State - CSRF Protection Library
Secure State is a robust Node.js library designed to provide protection against Cross-Site Request Forgery (CSRF) attacks. It helps developers add CSRF security to their web applications easily by generating, validating, and managing CSRF tokens with built-in middleware.
Features
- Generate and validate CSRF tokens: Ensures safe requests by verifying tokens.
- Cookie-based token storage: Tokens are stored in secure cookies to prevent unauthorized access.
- Origin and expiration checks: Configurable to check the origin of requests and token expiration.
- Debugging support: Provides detailed debug information (disabled in production).
Table of Contents
Installation
Install Secure State via npm:
npm install securestate
Usage
Middleware
- secureStateMiddleware: This middleware generates and sets a CSRF token if not already set in the cookies. It should be used in routes where CSRF protection is needed.
const { secureStateMiddleware } = require('securestate');
// Use this middleware on routes that require CSRF protection
app.use(secureStateMiddleware);
- verifyCsrf: This middleware verifies that the CSRF token in the request matches the token stored in the cookies. It should be applied to routes that modify server-side state (e.g., POST, PUT, DELETE).
const { verifyCsrf } = require('securestate');
// Use this middleware to verify CSRF tokens before handling sensitive actions
app.use('/sensitive-route', verifyCsrf, (req, res) => {
// Handle the request if CSRF is valid
res.send('CSRF verified!');
});
CSRF Token Handling
- Generating a token: Use generateToken to manually generate a CSRF token.
const { generateToken } = require('securestate');
const token = generateToken(req, res);
console.log(token); // The CSRF token generated
- Validating a Token: Use validateToken to check if the incoming token is valid.
const { validateToken } = require('securestate');
const isValid = validateToken(incomingToken, storedToken);
console.log(isValid); // Returns true if valid, false if invalid
Configuration
The Secure State library is highly configurable via the config file.
Available Options:
const config = {
regenerateToken: false, // Whether to regenerate token on every request
tokenExpires: false, // Whether the token should expire
tokenExpiration: 0, // Token expiration time in seconds (0 = no expiration)
checkOrigin: false, // Whether to check the origin of requests
debug: false, // Enable debug logs (not recommended for production)
tokenLength: 32, // Length of the generated token
cookieOptions: {
cookieName: '_csrfToken', // Cookie name to store the CSRF token
httpOnly: true, // Prevent access via JavaScript
sameSite: 'Strict', // Restrict cross-site cookie sharing
secure: process.env.NODE_ENV === 'production', // Secure cookies in production
path: '/', // Cookie path (root of site)
domain: '', // Cookie domain
}
};
Example:
You can modify the configurations by using the setConfig() method.
const { setConfig } = require('securestate');
// Change the regenerateToken and checkOrigin configuration
setConfig({
regenerateToken: true,
checkOrigin: true,
});
API Documentation
generateToken(req, res, length)
- Generates a new CSRF token and stores it in the response cookie.
- Paramaters:
- req: The HTTP request object.
- res: The HTTP response object.
- length: Length of the token. Default is 32.
- Returns: The generated CSRF token string.
validateToken(incomingToken, storedToken, req)
- Validates the CSRF token sent by the client.
- Parameters:
- incomingToken: The token received in the request (usually in the x-csrf-token header).
- storedToken: The token stored in the cookie.
- req: The HTTP response object (optional).
- Returns: true if the token is valid, false otherwise.
secureStateMiddleware(req, res, next)
- Middleware that generates and sets a CSRF token for incoming requests.
- Parameters:
- req: The HTTP request object.
- res: The HTTP response object.
- next: The next middleware function.
verifyCsrf(req, res, next)
- Middleware to verify the CSRF token sent by the client.
- Parameters:
- req: The HTTP request object.
- res: The HTTP response object.
- next: The next middleware function.
License
This library is licensed under the GPL v3.0 license. See the LICENSE file for more details.
Created By: Sam Wilcox wilcox.sam@gmail.com