-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
75 lines (67 loc) · 2.45 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2023-latest the httpland authors. All rights reserved. MIT license.
// This module is browser compatible.
import { type Middleware, withHeader } from "./deps.ts";
import { CSPHeader, DEFAULT_DIRECTIVES } from "./constants.ts";
import { stringifyDirectives } from "./utils.ts";
import type { CamelCasingCSPDirectives, CSPDirectives } from "./types.ts";
/** Middleware options. */
export interface Options<
T extends CSPDirectives | CamelCasingCSPDirectives =
| CSPDirectives
| CamelCasingCSPDirectives,
> {
/** Content security policy directives name and values pair.
* @default {@link DEFAULT_DIRECTIVES}
*/
readonly directives?: T;
/** Whether header is report-only or not.
* Depending on the value, the header will be:
* - `true`: `Content-Security-Policy-Report-Only`
* - `false`: `Content-Security-Policy`
* @default false
*/
readonly reportOnly?: boolean;
}
/** Create `Content-Security-Policy` header field middleware.
*
* The default header is [Starter policy](https://content-security-policy.com/):
* ```http
* Content-Security-Policy: default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';base-uri 'self';form-action 'self'
* ```
*
* @example
* ```ts
* import {
* csp,
* type Handler,
* } from "https://deno.land/x/csp_middleware@$VERSION/mod.ts";
* import { assert } from "https://deno.land/std/testing/asserts.ts";
*
* declare const request: Request;
* declare const handler: Handler;
*
* const middleware = csp();
* const response = await middleware(request, handler);
*
* assert(response.headers.has("content-security-policy"));
* ```
*
* @throws {Error} If the serialized CSP is invalid [`<serialized-policy-list>`](https://w3c.github.io/webappsec-csp/#grammardef-serialized-policy-list) format.
*/
export function csp(options?: Options<CSPDirectives>): Middleware;
export function csp(options?: Options<CamelCasingCSPDirectives>): Middleware;
export function csp(options?: Options): Middleware {
const {
directives = DEFAULT_DIRECTIVES,
reportOnly = false,
} = options ?? {};
const fieldValue = stringifyDirectives({ ...directives });
const fieldName = reportOnly
? CSPHeader.ContentSecurityPolicyReportOnly
: CSPHeader.ContentSecurityPolicy;
return async (request, next) => {
const response = await next(request);
if (response.headers.has(fieldName)) return response;
return withHeader(response, fieldName, fieldValue);
};
}