cookie-to-guard
Version:
Library for protecting cookies from tampering
197 lines (152 loc) • 4.64 kB
Markdown
# CookieGuard - Cookie Tampering Protection Library
A client-side library for protecting cookies from unauthorized modification with signature mechanism and tampering response.
## Installation
### Via npm
```bash
npm install cookie-to-guard
```
### Direct browser inclusion
```html
<script src="https://www.npmjs.com/package/cookie-to-guard.min.js"></script>
```
## Quick Start
```javascript
// Initialization
const guard = new CookieGuard({
cookieName: 'auth_token',
redirectUrl: '/login?error=tampered'
});
// Set protected cookie
guard.setSecureCookie('user123_session');
// Get value
const token = guard.getSecureCookie();
// Delete
guard.deleteSecureCookie();
```
## Full Documentation
### Configuration
```javascript
const options = {
cookieName: 'session', // Required: cookie name to protect
redirectUrl: '/login', // Redirect URL when tampering detected
onDetect: () => {}, // Callback when tampering detected
autoReset: true, // Auto-reset tampered cookies (default: true)
domain: '.example.com', // Cookie domain
secure: true, // HTTPS only (default: false)
sameSite: 'Strict', // SameSite attribute (Lax|Strict|None)
secret: 'my-secret-key' // Custom signature secret
};
const guard = new CookieGuard(options);
```
### Core Methods
#### `setSecureCookie(value, options)`
Sets a protected cookie with signature.
```javascript
guard.setSecureCookie('data123', {
days: 30, // Lifetime in days (default: 365)
path: '/admin' // Cookie path (default: '/')
});
```
#### `getSecureCookie()`
Gets cookie value with signature verification. Returns `null` if tampered.
```javascript
const value = guard.getSecureCookie();
if (value) {
// Cookies are valid
} else {
// Tampering detected or cookies missing
}
```
#### `deleteSecureCookie()`
Completely removes the protected cookie and its signature.
```javascript
guard.deleteSecureCookie();
```
### Advanced Scenarios
#### Custom Tampering Handling
```javascript
new CookieGuard({
cookieName: 'cart',
onDetect: (tamperedValue) => {
console.warn(`Cookie tampering detected! Value: ${tamperedValue}`);
// Restore from localStorage or make server request
}
});
```
#### AJAX Integration
```javascript
// Automatic verification before each fetch request
fetch('/api/data')
.then(response => {
if (response.status === 403) {
// Server also detected mismatch
guard.deleteSecureCookie();
}
});
```
## How It Works
1. **When setting cookies**:
- Creates HMAC signature of the value
- Main cookie: `session=value`
- Signature cookie: `session_sig=signature`
2. **During verification**:
- Library compares current value with signature
- On mismatch:
- Triggers `onDetect`
- Clears cookies (if `autoReset: true`)
- Redirects to `redirectUrl`
3. **Fetch integration**:
- Intercepts all fetch requests
- Verifies cookies before sending
## Examples
### Authentication Protection
```javascript
// After successful login
function onLoginSuccess(token) {
const guard = new CookieGuard({
cookieName: 'auth',
secure: true,
sameSite: 'Strict'
});
guard.setSecureCookie(token);
}
// On page load
const guard = new CookieGuard({ cookieName: 'auth' });
const authToken = guard.getSecureCookie();
if (!authToken) {
window.location.href = '/login';
}
```
### Shopping Cart Protection
```javascript
const cartGuard = new CookieGuard({
cookieName: 'cart',
onDetect: () => {
// Restore from backup
const backup = localStorage.getItem('cartBackup');
if (backup) {
cartGuard.setSecureCookie(backup);
}
}
});
// Save data
function saveCart(items) {
cartGuard.setSecureCookie(JSON.stringify(items));
localStorage.setItem('cartBackup', JSON.stringify(items));
}
```
## FAQ
### How does tamper protection work?
The library creates cryptographic signatures for cookie values and stores them in separate cookies. Each access verifies the signature.
### What if JavaScript is disabled?
The library requires JS. For critical data always implement server-side validation.
### How to improve security?
1. Always use `secure: true` for HTTPS
2. Provide custom `secret` in configuration
3. Regularly rotate secret keys
## License
MIT License. Free for commercial and non-commercial use.
---
Author: Gennadiy
Version: 1.0.0
Date: 2025-08-07