Application security middleware for Express.js providing CSRF protection, CSP headers, and comprehensive web security features.
npx @tessl/cli install tessl/npm-lusca@1.7.00
# Lusca
1
2
Lusca is a comprehensive web application security middleware for Express.js applications that provides essential security features including Cross-Site Request Forgery (CSRF) protection, Content Security Policy (CSP) headers, X-Frame-Options for clickjacking prevention, HTTP Strict Transport Security (HSTS), X-XSS-Protection headers, X-Content-Type-Options for MIME-sniffing prevention, Platform for Privacy Preferences (P3P) headers, and Referrer-Policy control.
3
4
## Package Information
5
6
- **Package Name**: lusca
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lusca`
10
11
## Core Imports
12
13
```javascript
14
const lusca = require('lusca');
15
```
16
17
For individual security modules:
18
19
```javascript
20
const lusca = require('lusca');
21
// Access individual modules as properties
22
// lusca.csrf, lusca.csp, lusca.hsts, lusca.p3p,
23
// lusca.xframe, lusca.xssProtection, lusca.nosniff, lusca.referrerPolicy
24
```
25
26
## Basic Usage
27
28
### Unified Configuration
29
30
```javascript
31
const express = require('express');
32
const session = require('express-session');
33
const lusca = require('lusca');
34
35
const app = express();
36
37
// Session middleware required for CSRF
38
app.use(session({
39
secret: 'your-secret-key',
40
resave: true,
41
saveUninitialized: true
42
}));
43
44
// Apply all security features at once
45
app.use(lusca({
46
csrf: true,
47
csp: { policy: { 'default-src': "'self'" } },
48
xframe: 'SAMEORIGIN',
49
p3p: 'ABCDEF',
50
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
51
xssProtection: true,
52
nosniff: true,
53
referrerPolicy: 'same-origin'
54
}));
55
```
56
57
### Individual Module Usage
58
59
```javascript
60
// Apply security features individually
61
app.use(lusca.csrf());
62
app.use(lusca.csp({ policy: { 'default-src': "'self'" } }));
63
app.use(lusca.xframe('SAMEORIGIN'));
64
app.use(lusca.p3p('ABCDEF'));
65
app.use(lusca.hsts({ maxAge: 31536000 }));
66
app.use(lusca.xssProtection(true));
67
app.use(lusca.nosniff());
68
app.use(lusca.referrerPolicy('same-origin'));
69
```
70
71
## Architecture
72
73
Lusca is built around a modular security middleware architecture:
74
75
- **Main Function**: Unified configuration that applies multiple security features
76
- **Individual Modules**: Standalone middleware functions for specific security headers
77
- **Session Integration**: CSRF protection requires Express session middleware
78
- **Nonce Support**: Automatic nonce generation for CSP when styleNonce or scriptNonce is enabled
79
80
## Capabilities
81
82
### Main Lusca Function
83
84
Configures and applies multiple security features based on provided options.
85
86
```javascript { .api }
87
/**
88
* Main lusca middleware function that applies multiple security features
89
* @param {Object} options - Configuration object with security feature options
90
* @returns {Function} Express middleware function
91
*/
92
function lusca(options);
93
```
94
95
**Options Properties:**
96
- `csrf` - CSRF protection configuration (boolean or object)
97
- `csp` - Content Security Policy configuration (object)
98
- `xframe` - X-Frame-Options value (string)
99
- `p3p` - P3P compact privacy policy (string)
100
- `hsts` - HTTP Strict Transport Security configuration (object)
101
- `xssProtection` - X-XSS-Protection configuration (boolean or object)
102
- `nosniff` - X-Content-Type-Options configuration (boolean)
103
- `referrerPolicy` - Referrer-Policy value (string)
104
105
### CSRF Protection
106
107
Provides Cross-Site Request Forgery protection with token-based validation.
108
109
```javascript { .api }
110
/**
111
* CSRF protection middleware
112
* @param {Object} options - CSRF configuration options
113
* @returns {Function} Express middleware function that validates CSRF tokens
114
*/
115
function csrf(options);
116
117
interface CSRFOptions {
118
/** The name of the CSRF token in the model. Default "_csrf" */
119
key?: string;
120
/** The key to place on the session object for server side token. Default "_csrfSecret" */
121
secret?: string;
122
/** Custom implementation to generate a token */
123
impl?: TokenImplementation;
124
/** The name of the response header containing CSRF token. Default "x-csrf-token" */
125
header?: string;
126
/** Cookie configuration for CSRF token */
127
cookie?: string | {
128
name: string;
129
options?: CookieOptions;
130
};
131
/** Shorthand setting for AngularJS CSRF defaults */
132
angular?: boolean;
133
/** Routes that will not have CSRF protection */
134
blocklist?: string | Array<string | { path: string; type: 'exact' | 'startsWith' }>;
135
/** Routes that will have CSRF protection (all others will not) */
136
allowlist?: string | Array<string | { path: string; type: 'exact' | 'startsWith' }>;
137
}
138
139
interface TokenImplementation {
140
create(req: Request, secret: string): {
141
token: string;
142
secret: string;
143
validate: (req: Request, token: string) => boolean;
144
};
145
}
146
```
147
148
**Adds to Request:**
149
```javascript { .api }
150
/**
151
* Function added to req object for getting CSRF token
152
* @returns {string} Current CSRF token
153
*/
154
req.csrfToken(): string;
155
```
156
157
### Content Security Policy
158
159
Enables Content Security Policy headers to prevent XSS attacks.
160
161
```javascript { .api }
162
/**
163
* Content Security Policy middleware
164
* @param {Object} options - CSP configuration options
165
* @returns {Function} Express middleware function that sets CSP headers
166
*/
167
function csp(options);
168
169
interface CSPOptions {
170
/** CSP policy definition */
171
policy?: string | Object | Array<string | Object>;
172
/** Enable report-only mode */
173
reportOnly?: boolean;
174
/** URI where to send violation reports */
175
reportUri?: string;
176
/** Enable nonce for inline style-src, access from res.locals.nonce */
177
styleNonce?: boolean;
178
/** Enable nonce for inline script-src, access from res.locals.nonce */
179
scriptNonce?: boolean;
180
}
181
182
/**
183
* Utility function to create policy strings from various formats
184
* @param {string|Object|Array} policy - Policy definition
185
* @returns {string} Formatted policy string
186
*/
187
function createPolicyString(policy): string;
188
```
189
190
### HTTP Strict Transport Security
191
192
Enables HSTS headers to enforce HTTPS connections.
193
194
```javascript { .api }
195
/**
196
* HSTS middleware
197
* @param {Object} options - HSTS configuration options
198
* @returns {Function} Express middleware function that sets HSTS headers
199
*/
200
function hsts(options);
201
202
interface HSTSOptions {
203
/** Number of seconds HSTS is in effect. Required */
204
maxAge?: number;
205
/** Applies HSTS to all subdomains of the host */
206
includeSubDomains?: boolean;
207
/** Adds preload flag for Chrome's HSTS preload list */
208
preload?: boolean;
209
}
210
```
211
212
### Platform for Privacy Preferences
213
214
Enables P3P headers for legacy Internet Explorer privacy policies.
215
216
```javascript { .api }
217
/**
218
* P3P middleware
219
* @param {string} value - The P3P compact privacy policy value
220
* @returns {Function} Express middleware function that sets P3P headers
221
*/
222
function p3p(value);
223
```
224
225
### X-Frame-Options
226
227
Enables X-Frame-Options headers to prevent clickjacking attacks.
228
229
```javascript { .api }
230
/**
231
* X-Frame-Options middleware
232
* @param {string} value - Frame options value (DENY, SAMEORIGIN, ALLOW-FROM uri)
233
* @returns {Function} Express middleware function that sets X-Frame-Options headers
234
*/
235
function xframe(value);
236
```
237
238
### XSS Protection
239
240
Enables X-XSS-Protection headers for legacy XSS filtering in older browsers.
241
242
```javascript { .api }
243
/**
244
* X-XSS-Protection middleware
245
* @param {Object|boolean} options - XSS protection configuration
246
* @returns {Function} Express middleware function that sets X-XSS-Protection headers
247
*/
248
function xssProtection(options);
249
250
interface XSSProtectionOptions {
251
/** Enable XSS protection (0 or 1). Default 1 */
252
enabled?: number | boolean;
253
/** Protection mode. Default "block" */
254
mode?: string;
255
}
256
```
257
258
### MIME Sniffing Protection
259
260
Enables X-Content-Type-Options headers to prevent MIME-sniffing attacks.
261
262
```javascript { .api }
263
/**
264
* X-Content-Type-Options middleware
265
* @returns {Function} Express middleware function that sets X-Content-Type-Options headers
266
*/
267
function nosniff();
268
```
269
270
### Referrer Policy
271
272
Enables Referrer-Policy headers to control referrer information.
273
274
```javascript { .api }
275
/**
276
* Referrer-Policy middleware
277
* @param {string} value - Referrer policy value
278
* @returns {Function} Express middleware function that sets Referrer-Policy headers
279
*/
280
function referrerPolicy(value);
281
```
282
283
**Supported Values:**
284
- `''` (empty string)
285
- `'no-referrer'`
286
- `'no-referrer-when-downgrade'`
287
- `'same-origin'`
288
- `'origin'`
289
- `'strict-origin'`
290
- `'origin-when-cross-origin'`
291
- `'strict-origin-when-cross-origin'`
292
- `'unsafe-url'`
293
294
## Error Handling
295
296
- **CSRF**: Returns 403 Forbidden for missing or invalid CSRF tokens
297
- **CSP**: Throws Error for invalid policy objects
298
- **Referrer Policy**: Throws Error for unsupported values (non-production only)
299
- **Session Requirement**: CSRF functionality requires Express session middleware
300
301
## Advanced Usage Examples
302
303
### CSRF with Custom Token Implementation
304
305
```javascript
306
const customToken = {
307
create: function(req, secret) {
308
// Custom token generation logic
309
return {
310
token: 'custom-token',
311
secret: secret,
312
validate: function(req, token) {
313
// Custom validation logic
314
return token === 'custom-token';
315
}
316
};
317
}
318
};
319
320
app.use(lusca.csrf({
321
impl: customToken,
322
key: '_customCsrf',
323
header: 'x-custom-csrf-token'
324
}));
325
```
326
327
### Complex CSP Configuration
328
329
```javascript
330
app.use(lusca.csp({
331
policy: {
332
'default-src': "'self'",
333
'script-src': "'self' 'unsafe-inline'",
334
'style-src': "'self' 'unsafe-inline'",
335
'img-src': "'self' data: https:",
336
'font-src': "'self' https://fonts.gstatic.com"
337
},
338
reportOnly: false,
339
reportUri: '/csp-violation-report',
340
styleNonce: true,
341
scriptNonce: true
342
}));
343
```
344
345
### CSRF with Path Allowlist/Blocklist
346
347
```javascript
348
app.use(lusca.csrf({
349
// Exact path matching
350
blocklist: [
351
{ path: '/api/webhook', type: 'exact' },
352
{ path: '/public', type: 'startsWith' }
353
],
354
// Or string format (uses startsWith matching)
355
blocklist: ['/api/webhook', '/public']
356
}));
357
```