-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
112 lines (96 loc) · 2.15 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
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
import {
json,
serve,
validateRequest,
} from "https://deno.land/x/sift@0.4.0/mod.ts";
import { Rcon, RconConnectionException } from "./rcon.ts";
import { RconRequestDto } from "./types.ts";
const getHeaders = () => {
const headers = new Headers();
headers.set("Access-Control-Allow-Origin", "*");
headers.set("Access-Control-Allow-Methods", "POST");
headers.set("Access-Control-Allow-Headers", "Content-Type");
return headers;
};
serve({
"/": home,
404: notFound,
});
function notFound() {
return json({
statusCode: 404,
message: "Not found",
error: "Not Found",
});
}
async function home(req: Request) {
if (req.method.toUpperCase() === "OPTIONS") {
return new Response("OK", { status: 200, headers: getHeaders() });
}
let body: RconRequestDto;
try {
body = await validateBody(req);
} catch (err) {
if (err instanceof Response) {
return err;
}
throw err;
}
try {
const rcon = new Rcon(body.ip, body.port ?? 27015, body.password);
const response = await rcon.sendCmd(body.command);
return json(
{
statusCode: 200,
response,
},
{
headers: getHeaders(),
}
);
} catch (err) {
if (err instanceof RconConnectionException) {
return json(
{
statusCode: 400,
message: "Bad target IP",
error: "Bad Request",
},
{
headers: getHeaders(),
}
);
}
// actually something wrong internally
console.error(err);
return json(
{
statusCode: 400,
message: "Bad RCON details",
error: "Bad Request",
},
{
headers: getHeaders(),
}
);
}
}
async function validateBody(req: Request) {
try {
const { error, body } = await validateRequest(req, {
POST: {
body: ["ip", "password", "command"],
},
});
if (error) {
throw json({ error: error.message }, { status: error.status });
}
return body as unknown as RconRequestDto;
} catch (_err) {
throw json({
statusCode: 400,
message: "Body must be present",
error: "Bad Request",
});
}
}