-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop_detection_prevent_forwarded.ts
43 lines (40 loc) · 1.57 KB
/
loop_detection_prevent_forwarded.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 {
NextFunction,
RetHandler,
} from "https://cdn.jsdelivr.net/gh/masx200/[email protected]/src/Middleware.ts";
import { Context } from "https://cdn.jsdelivr.net/gh/masx200/[email protected]/src/Context.ts";
import { parse_forwarded_header } from "./parse_forwarded_header.ts";
import { JSONSTRINGIFYNULL4 } from "./JSONSTRINGIFYNULL4.ts";
/**
* 防止环路的产生的中间件forwarded
*/
export async function loop_detection_prevent_forwarded(
ctx: Context,
next: NextFunction,
): Promise<RetHandler> {
const req = ctx.request;
const Forwarded = req.headers.get("Forwarded");
const forwarded_map = parse_forwarded_header(Forwarded);
const hosts_forwarded = forwarded_map
.map((a) => a.get("host"))
.filter(Boolean);
const bys_forwarded = forwarded_map.map((a) => a.get("by")).filter(Boolean);
const fors_forwarded = forwarded_map
.map((a) => a.get("for"))
.filter(Boolean);
//预防循环转发的主机
//检查是否存在循环转发
if (
new Set(hosts_forwarded).size != hosts_forwarded.length ||
new Set(bys_forwarded).size != bys_forwarded.length ||
new Set(fors_forwarded).size != fors_forwarded.length
) {
const message = JSONSTRINGIFYNULL4({ forwarded: Forwarded }, null, 4);
console.error("loop detected", message);
return new Response("loop detected\n" + message, { status: 508 });
} else {
const res = await next();
// console.log("loop_detection_prevent_forwarded", res.body);
return res;
}
}