-
Notifications
You must be signed in to change notification settings - Fork 368
/
index.ts
43 lines (37 loc) · 1.22 KB
/
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
43
import { IncomingMessage, ServerResponse } from "http";
export interface XFrameOptionsOptions {
action?: "deny" | "sameorigin";
}
function getHeaderValueFromOptions({
action = "sameorigin",
}: Readonly<XFrameOptionsOptions>): string {
const normalizedAction =
typeof action === "string" ? action.toUpperCase() : action;
switch (normalizedAction) {
case "SAME-ORIGIN":
return "SAMEORIGIN";
case "DENY":
case "SAMEORIGIN":
return normalizedAction;
case "ALLOW-FROM":
throw new Error(
"X-Frame-Options no longer supports `ALLOW-FROM` due to poor browser support. See <https://github.com/helmetjs/helmet/wiki/How-to-use-X%E2%80%93Frame%E2%80%93Options's-%60ALLOW%E2%80%93FROM%60-directive> for more info."
);
default:
throw new Error(
`X-Frame-Options received an invalid action ${JSON.stringify(action)}`
);
}
}
function xFrameOptions(options: Readonly<XFrameOptionsOptions> = {}) {
const headerValue = getHeaderValueFromOptions(options);
return function xFrameOptionsMiddleware(
_req: IncomingMessage,
res: ServerResponse,
next: () => void
) {
res.setHeader("X-Frame-Options", headerValue);
next();
};
}
export default xFrameOptions;