/
index.ts
42 lines (36 loc) · 1019 Bytes
/
index.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
import { IncomingMessage, ServerResponse } from "http";
export interface CrossOriginOpenerPolicyOptions {
policy?: "same-origin" | "same-origin-allow-popups" | "unsafe-none";
}
const ALLOWED_POLICIES = new Set([
"same-origin",
"same-origin-allow-popups",
"unsafe-none",
]);
function getHeaderValueFromOptions({
policy = "same-origin",
}: Readonly<CrossOriginOpenerPolicyOptions>): string {
if (ALLOWED_POLICIES.has(policy)) {
return policy;
} else {
throw new Error(
`Cross-Origin-Opener-Policy does not support the ${JSON.stringify(
policy
)} policy`
);
}
}
function crossOriginOpenerPolicy(
options: Readonly<CrossOriginOpenerPolicyOptions> = {}
) {
const headerValue = getHeaderValueFromOptions(options);
return function crossOriginOpenerPolicyMiddleware(
_req: IncomingMessage,
res: ServerResponse,
next: () => void
) {
res.setHeader("Cross-Origin-Opener-Policy", headerValue);
next();
};
}
export default crossOriginOpenerPolicy;