-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
177 lines (151 loc) · 4.37 KB
/
Copy pathmain.ts
File metadata and controls
177 lines (151 loc) · 4.37 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import "@std/dotenv/load";
import routes from "./routes.ts";
import { ReqLog } from "./lib/ReqLog.ts";
import { getBlockedIps } from "./data/blockedIPs.ts";
import about from "./handlers/about.ts";
export interface JSONObj {
[key: string]: string | number | string[] | number[] | JSONObj;
}
export type ResponseOptions = {
status?: number;
type?: "application/json" | "image/png" | "image/x-icon";
headers?: HeadersInit;
};
export type Payload = {
status: number;
data: JSONObj | Promise<JSONObj> | Uint8Array | Promise<Uint8Array>;
type: "application/json" | "image/png" | "image/x-icon";
headers: HeadersInit;
};
export type ResponseProps = {
respond: (data: JSONObj | Uint8Array, options?: ResponseOptions) => Payload;
};
export type Context = {
req: Request;
url: URL;
params: Record<string, string | number>;
data: JSONObj;
ip: string;
};
async function handler(
req: Request,
info: Deno.ServeHandlerInfo
): Promise<Response> {
const start = new Date();
const url = new URL(req.url);
const pathname = url.pathname;
const ip =
info.remoteAddr && info.remoteAddr.transport === "tcp"
? info.remoteAddr.hostname
: "unknown";
console.log("Client IP:", ip);
const reqLog = new ReqLog().start({ created_at: start, url, ip });
console.log("Request:", url.href);
if (req.method === "OPTIONS") {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
});
}
const staticEtag = Deno.env.get("STATIC_E_TAG");
const requestEtag = req.headers.get("If-None-Match");
if (requestEtag === staticEtag) {
return new Response(null, {
status: 304,
headers: {
ETag: staticEtag,
"Cache-Control": "public, max-age=604800",
},
});
}
const resp: ResponseProps = {
respond: (data: JSONObj | Uint8Array, options?: ResponseOptions) => {
return {
data,
status: options?.status || 200,
type: options?.type || "application/json",
headers: options?.headers || {},
};
},
};
let result: undefined | Payload;
if (blockedIps[ip]) {
result = about({ req, url, params: {}, data: {}, ip }, resp);
} else {
for (const route of routes) {
const match = pathname.match(route.pattern);
if (match) {
const params: Record<string, string | number> = {};
route.paramNames.forEach((name, idx) => {
let m: string | number = match[idx + 1];
const num = Number(m);
if (!isNaN(num)) {
m = num;
}
params[name] = m;
});
result = await route.handler({ req, url, params, data: {}, ip }, resp);
break;
}
}
}
if (!result) {
result = {
status: 404,
data: { error: "Not Found" },
type: "application/json",
headers: {},
};
}
if (result.data instanceof Promise) {
await result.data;
}
const blockedIp = (result.data as JSONObj).blocked as string;
if (blockedIp) {
blockedIps[blockedIp] = true;
delete (result.data as JSONObj).blocked;
await new Promise((resolve) => {
setTimeout(resolve, Number(Deno.env.get("BAD_TIMEOUT")) || 600000);
});
}
const processingTime = new Date().getTime() - start.getTime();
const headers = {
"Content-Type": result.type,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
...result.headers,
};
let payload: string | Uint8Array;
if (result.data instanceof Uint8Array) {
payload = result.data;
} else {
const meta: JSONObj = {
path: pathname,
search: url.search,
processingTime: `${processingTime}ms`,
status: result.status,
};
(result.data as JSONObj).meta = meta;
payload = JSON.stringify(result.data);
}
const response = new Response(payload, {
status: result.status,
headers,
});
reqLog.end({ time: processingTime, status: result.status });
return response;
}
const blockedIps = await getBlockedIps();
Deno.serve({
port: Number(Deno.env.get("PORT")) || undefined,
hostname: Deno.env.get("HOSTNAME") || undefined,
handler,
onListen({ port, hostname }) {
console.log(`Server started at http://[${hostname}]:${port}`);
},
});