0
# Koa Helmet
1
2
Koa Helmet is a wrapper for Helmet.js that provides security header middleware collection for Koa applications. It converts Helmet's Express-style middleware into Koa-compatible middleware, applying essential security headers to protect web applications from common vulnerabilities.
3
4
## Package Information
5
6
- **Package Name**: koa-helmet
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install koa-helmet helmet`
10
- **Peer Dependencies**: `helmet >= 6`
11
12
## Core Imports
13
14
```javascript
15
import helmet from "koa-helmet";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const helmet = require("koa-helmet");
22
```
23
24
## Basic Usage
25
26
```javascript
27
import Koa from "koa";
28
import helmet from "koa-helmet";
29
30
const app = new Koa();
31
32
// Apply all security headers (recommended)
33
app.use(helmet());
34
35
// Or use individual middleware
36
app.use(helmet.contentSecurityPolicy());
37
app.use(helmet.hsts());
38
app.use(helmet.frameguard());
39
40
app.use((ctx) => {
41
ctx.body = "Hello World";
42
});
43
44
app.listen(4000);
45
```
46
47
## Architecture
48
49
Koa Helmet works by dynamically wrapping all Helmet.js middleware methods:
50
51
- **Dynamic Wrapping**: Automatically detects and wraps all Helmet middleware using `Object.keys(helmet)`
52
- **Promise-based Conversion**: Uses Node.js `promisify` to convert Express-style middleware to Koa's promise-based pattern
53
- **Context Bridging**: Maps Koa's `ctx.req` and `ctx.res` to work with Helmet's Express-style middleware
54
- **Method Preservation**: Maintains all static properties and methods from the original Helmet middleware
55
56
## Capabilities
57
58
### Main Security Middleware
59
60
The primary function that applies all recommended security headers.
61
62
```javascript { .api }
63
/**
64
* Apply all Helmet security headers with default settings
65
* @param options - Optional Helmet configuration options
66
* @returns Koa middleware function
67
*/
68
function helmet(options?: HelmetOptions): Middleware;
69
```
70
71
**Usage Example:**
72
73
```javascript
74
import helmet from "koa-helmet";
75
76
// Apply all security headers with defaults
77
app.use(helmet());
78
79
// Apply with custom options
80
app.use(helmet({
81
contentSecurityPolicy: {
82
directives: {
83
defaultSrc: ["'self'"],
84
scriptSrc: ["'self'", "'unsafe-inline'"]
85
}
86
}
87
}));
88
```
89
90
### Content Security Policy
91
92
Sets Content-Security-Policy headers to mitigate XSS attacks and control resource loading.
93
94
```javascript { .api }
95
/**
96
* Configure Content Security Policy headers
97
* @param options - CSP configuration options
98
* @returns Koa middleware function
99
*/
100
function contentSecurityPolicy(options?: CSPOptions): Middleware;
101
102
// Static methods available on contentSecurityPolicy
103
contentSecurityPolicy.getDefaultDirectives(): CSPDirectives;
104
contentSecurityPolicy.dangerouslyDisableDefaultSrc(directives: CSPDirectives): CSPDirectives;
105
```
106
107
**Usage Example:**
108
109
```javascript
110
app.use(helmet.contentSecurityPolicy({
111
directives: {
112
defaultSrc: ["'self'"],
113
scriptSrc: ["'self'", "'unsafe-inline'"],
114
styleSrc: ["'self'", "'unsafe-inline'"],
115
imgSrc: ["'self'", "data:", "https:"]
116
}
117
}));
118
```
119
120
### Cross-Origin Policies
121
122
Controls cross-origin resource access and embedding policies.
123
124
```javascript { .api }
125
/**
126
* Set Cross-Origin-Embedder-Policy header
127
* @param options - COEP configuration options
128
* @returns Koa middleware function
129
*/
130
function crossOriginEmbedderPolicy(options?: COEPOptions): Middleware;
131
132
/**
133
* Set Cross-Origin-Opener-Policy header
134
* @param options - COOP configuration options
135
* @returns Koa middleware function
136
*/
137
function crossOriginOpenerPolicy(options?: COOPOptions): Middleware;
138
139
/**
140
* Set Cross-Origin-Resource-Policy header
141
* @param options - CORP configuration options
142
* @returns Koa middleware function
143
*/
144
function crossOriginResourcePolicy(options?: CORPOptions): Middleware;
145
```
146
147
### DNS and Prefetch Control
148
149
Controls DNS prefetching behavior for performance and privacy.
150
151
```javascript { .api }
152
/**
153
* Control DNS prefetching via X-DNS-Prefetch-Control header
154
* @param options - DNS prefetch configuration
155
* @returns Koa middleware function
156
*/
157
function dnsPrefetchControl(options?: { allow?: boolean }): Middleware;
158
```
159
160
**Usage Example:**
161
162
```javascript
163
// Disable DNS prefetching (default)
164
app.use(helmet.dnsPrefetchControl());
165
166
// Enable DNS prefetching
167
app.use(helmet.dnsPrefetchControl({ allow: true }));
168
```
169
170
### Frame Protection
171
172
Prevents clickjacking attacks by controlling frame embedding.
173
174
```javascript { .api }
175
/**
176
* Set X-Frame-Options header to prevent clickjacking
177
* @param options - Frame guard configuration
178
* @returns Koa middleware function
179
*/
180
function frameguard(options?: FrameguardOptions): Middleware;
181
```
182
183
**Usage Example:**
184
185
```javascript
186
// Default: SAMEORIGIN
187
app.use(helmet.frameguard());
188
189
// Deny all framing
190
app.use(helmet.frameguard({ action: "deny" }));
191
192
// Allow from specific origin
193
app.use(helmet.frameguard({
194
action: "allow-from",
195
domain: "https://example.com"
196
}));
197
```
198
199
### Server Identity Protection
200
201
Removes server technology information from responses.
202
203
```javascript { .api }
204
/**
205
* Remove X-Powered-By header to hide server technology
206
* @returns Koa middleware function
207
*/
208
function hidePoweredBy(): Middleware;
209
```
210
211
### HTTPS Enforcement
212
213
Enforces secure HTTPS connections via Strict Transport Security.
214
215
```javascript { .api }
216
/**
217
* Set Strict-Transport-Security header to enforce HTTPS
218
* @param options - HSTS configuration options
219
* @returns Koa middleware function
220
*/
221
function hsts(options?: HSTSOptions): Middleware;
222
```
223
224
**Usage Example:**
225
226
```javascript
227
// Default: max-age=15552000; includeSubDomains
228
app.use(helmet.hsts());
229
230
// Custom configuration
231
app.use(helmet.hsts({
232
maxAge: 31536000, // 1 year in seconds
233
includeSubDomains: true,
234
preload: true
235
}));
236
```
237
238
### IE Security Features
239
240
Configures Internet Explorer-specific security features.
241
242
```javascript { .api }
243
/**
244
* Set X-Download-Options header to prevent IE from executing downloads
245
* @returns Koa middleware function
246
*/
247
function ieNoOpen(): Middleware;
248
```
249
250
### MIME Type Protection
251
252
Prevents MIME type sniffing attacks.
253
254
```javascript { .api }
255
/**
256
* Set X-Content-Type-Options header to prevent MIME type sniffing
257
* @returns Koa middleware function
258
*/
259
function noSniff(): Middleware;
260
```
261
262
### Origin Agent Cluster
263
264
Provides origin-based process isolation for better security.
265
266
```javascript { .api }
267
/**
268
* Set Origin-Agent-Cluster header for process isolation
269
* @returns Koa middleware function
270
*/
271
function originAgentCluster(): Middleware;
272
```
273
274
### Cross-Domain Policies
275
276
Controls Adobe Flash and Silverlight cross-domain access policies.
277
278
```javascript { .api }
279
/**
280
* Set X-Permitted-Cross-Domain-Policies header
281
* @param options - Cross-domain policy configuration
282
* @returns Koa middleware function
283
*/
284
function permittedCrossDomainPolicies(options?: PermittedPoliciesOptions): Middleware;
285
```
286
287
### Referrer Policy
288
289
Controls referrer information sent with requests.
290
291
```javascript { .api }
292
/**
293
* Set Referrer-Policy header to control referrer information
294
* @param options - Referrer policy configuration
295
* @returns Koa middleware function
296
*/
297
function referrerPolicy(options?: ReferrerPolicyOptions): Middleware;
298
```
299
300
**Usage Example:**
301
302
```javascript
303
// Default: no-referrer
304
app.use(helmet.referrerPolicy());
305
306
// Custom policy
307
app.use(helmet.referrerPolicy({ policy: "same-origin" }));
308
```
309
310
### XSS Protection
311
312
Controls legacy XSS protection features (mostly deprecated).
313
314
```javascript { .api }
315
/**
316
* Set X-XSS-Protection header (legacy, mostly disabled by default)
317
* @param options - XSS filter configuration
318
* @returns Koa middleware function
319
*/
320
function xssFilter(options?: XSSFilterOptions): Middleware;
321
```
322
323
## Method Aliases
324
325
Koa Helmet provides several method aliases for compatibility:
326
327
```javascript { .api }
328
// HSTS aliases
329
function strictTransportSecurity(options?: HSTSOptions): Middleware;
330
331
// Content type aliases
332
function xContentTypeOptions(): Middleware;
333
334
// DNS prefetch aliases
335
function xDnsPrefetchControl(options?: { allow?: boolean }): Middleware;
336
337
// Download options aliases
338
function xDownloadOptions(): Middleware;
339
340
// Frame options aliases
341
function xFrameOptions(options?: FrameguardOptions): Middleware;
342
343
// Cross-domain policies aliases
344
function xPermittedCrossDomainPolicies(options?: PermittedPoliciesOptions): Middleware;
345
346
// Powered-by aliases
347
function xPoweredBy(): Middleware;
348
349
// XSS protection aliases
350
function xXssProtection(options?: XSSFilterOptions): Middleware;
351
```
352
353
## Types
354
355
```typescript { .api }
356
import { Middleware } from "koa";
357
import { HelmetOptions } from "helmet";
358
359
interface KoaHelmet {
360
// Main function
361
(options?: HelmetOptions): Middleware;
362
363
// Individual middleware methods
364
contentSecurityPolicy(options?: CSPOptions): Middleware;
365
crossOriginEmbedderPolicy(options?: COEPOptions): Middleware;
366
crossOriginOpenerPolicy(options?: COOPOptions): Middleware;
367
crossOriginResourcePolicy(options?: CORPOptions): Middleware;
368
dnsPrefetchControl(options?: { allow?: boolean }): Middleware;
369
frameguard(options?: FrameguardOptions): Middleware;
370
hidePoweredBy(): Middleware;
371
hsts(options?: HSTSOptions): Middleware;
372
ieNoOpen(): Middleware;
373
noSniff(): Middleware;
374
originAgentCluster(): Middleware;
375
permittedCrossDomainPolicies(options?: PermittedPoliciesOptions): Middleware;
376
referrerPolicy(options?: ReferrerPolicyOptions): Middleware;
377
xssFilter(options?: XSSFilterOptions): Middleware;
378
379
// Method aliases (x-prefixed variants)
380
strictTransportSecurity(options?: HSTSOptions): Middleware;
381
xContentTypeOptions(): Middleware;
382
xDnsPrefetchControl(options?: { allow?: boolean }): Middleware;
383
xDownloadOptions(): Middleware;
384
xFrameOptions(options?: FrameguardOptions): Middleware;
385
xPermittedCrossDomainPolicies(options?: PermittedPoliciesOptions): Middleware;
386
xPoweredBy(): Middleware;
387
xXssProtection(options?: XSSFilterOptions): Middleware;
388
}
389
390
interface FrameguardOptions {
391
action?: "deny" | "sameorigin" | "allow-from";
392
domain?: string;
393
}
394
395
interface HSTSOptions {
396
maxAge?: number;
397
includeSubDomains?: boolean;
398
preload?: boolean;
399
}
400
401
interface ReferrerPolicyOptions {
402
policy?: "no-referrer" | "no-referrer-when-downgrade" | "origin" |
403
"origin-when-cross-origin" | "same-origin" | "strict-origin" |
404
"strict-origin-when-cross-origin" | "unsafe-url";
405
}
406
407
interface CSPDirectives {
408
[directive: string]: string | string[];
409
}
410
411
interface CSPOptions {
412
directives?: CSPDirectives;
413
reportOnly?: boolean;
414
useDefaults?: boolean;
415
}
416
417
interface COEPOptions {
418
policy?: "require-corp" | "credentialless";
419
}
420
421
interface COOPOptions {
422
policy?: "same-origin" | "same-origin-allow-popups" | "unsafe-none";
423
}
424
425
interface CORPOptions {
426
policy?: "same-origin" | "same-site" | "cross-origin";
427
}
428
429
interface PermittedPoliciesOptions {
430
permittedPolicies?: "none" | "master-only" | "by-content-type" | "by-ftp-filename" | "all";
431
}
432
433
interface XSSFilterOptions {
434
mode?: "block" | null;
435
}
436
```
437
438
## Security Headers Produced
439
440
When using `helmet()` with default settings, the following headers are set:
441
442
- **Content-Security-Policy**: `default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests`
443
- **Cross-Origin-Opener-Policy**: `same-origin`
444
- **Cross-Origin-Resource-Policy**: `same-origin`
445
- **X-DNS-Prefetch-Control**: `off`
446
- **X-Frame-Options**: `SAMEORIGIN`
447
- **Strict-Transport-Security**: `max-age=15552000; includeSubDomains`
448
- **X-Download-Options**: `noopen`
449
- **X-Content-Type-Options**: `nosniff`
450
- **Referrer-Policy**: `no-referrer`
451
- **X-Permitted-Cross-Domain-Policies**: `none`
452
- **X-XSS-Protection**: `0`
453
454
## Error Handling
455
456
Koa Helmet preserves Helmet's error handling behavior:
457
458
- **Configuration Errors**: Invalid options throw errors during middleware setup
459
- **Runtime Errors**: Middleware errors are passed through Koa's error handling system
460
- **Promise Handling**: All middleware is properly promisified for Koa's async pattern
461
462
```javascript
463
// Error handling example
464
app.use(async (ctx, next) => {
465
try {
466
await next();
467
} catch (err) {
468
console.error('Helmet middleware error:', err);
469
ctx.status = 500;
470
ctx.body = 'Internal Server Error';
471
}
472
});
473
474
app.use(helmet());
475
```