-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.ts
207 lines (179 loc) · 5.54 KB
/
handlers.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
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { RouterContext } from "https://deno.land/x/oak@v11.1.0/mod.ts";
import { timeoutMs } from "./constants.ts";
import { timeout } from "./utils.ts";
export const handleRun = async (context: RouterContext<"/run">) => {
let code = context.request.url.searchParams.get("code");
const stateString = context.request.url.searchParams.get("state");
let state: {
logPrefix?: string;
promptValues?: string[];
promptSkips?: number;
} | null = null;
if (stateString) {
try {
state = JSON.parse(stateString);
} catch (_error) {
context.response.status = 400;
context.response.body = JSON.stringify({
success: false,
message: "invalid state",
data: null,
});
return;
}
}
context.response.headers.set("content-type", "application/json");
if (!code && context.request.body.length < 1024 * 1024) {
try {
const body = context.request.body();
const value = await body.value;
code = decodeURIComponent(value?.code || "");
if (value?.state) {
state = value.state;
}
} catch (error) {
console.error(error);
}
}
if (!code) {
context.response.status = 400;
context.response.body = JSON.stringify({
success: false,
message: "missing property: code",
data: null,
});
return;
}
if (typeof code === "string" && code.includes("console.log")) {
let process: Deno.Process | undefined = undefined;
const dirname = new URL(".", import.meta.url).pathname;
const fileName = Math.floor(Math.random() * 1000000).toString();
const filePath = `${dirname}files/${fileName}.ts`;
try {
const file = await Deno.create(filePath);
const evalCode = `const ____promptValues____: any = [${state?.promptValues
?.reverse()
?.map((x) => `"${x}"`)
?.join(", ")}]; \
const ____promptCount____ = ${state?.promptSkips || 0}; \
let ____promptSkipped____ = ____promptCount____; \
globalThis.prompt = (title?: string) => { \
if (____promptSkipped____ <= 0) { \
console.log( \
JSON.stringify({ \
state: { \
prompt: { \
title, \
count: ____promptCount____ + 1, \
}, \
}, \
}), \
); \
Deno.exit(); \
} else { \
____promptSkipped____--; \
return ____promptValues____[____promptSkipped____]; \
} \
}; \
if ("${state?.logPrefix?.replaceAll("\n", "\\n").replaceAll("\r", "\\r") || ""}") { \
Deno.stdout.writeSync(new TextEncoder().encode(\`${state?.logPrefix
?.replaceAll("`", "\\`")
.replaceAll("\n", "\\n")
.replaceAll("\r", "\\r")}\`)); \
} \
Object.defineProperty(globalThis, "localStorage", { value: undefined });\n
const keys = Object.keys(Deno); \
keys.forEach((prop) => { \ if (prop == "exit") return;
Object.defineProperty(Deno, prop, { value: undefined }); });\n\
${code}`;
await file.write(new TextEncoder().encode(evalCode));
process = Deno.run({
cmd: [
"deno",
"run",
"--allow-net",
"--no-remote",
"--v8-flags=--max-old-space-size=10",
filePath,
],
env: {
NO_COLOR: "true",
},
stdout: "piped",
stderr: "piped",
});
const promise = new Promise((resolve, reject) => {
const tid = setTimeout(async () => {
clearTimeout(tid);
if (!process) {
reject(null);
return;
}
try {
const { code } = await process.status();
const rawOutput = await process.output();
if (code === 0) {
resolve(
new TextDecoder()
.decode(rawOutput)
.slice(0, -1)
.replace(/file:\/\/\/.+files/gi, ""),
);
} else {
const rawError = await process.stderrOutput();
reject(
new TextDecoder()
.decode(rawError)
.slice(0, -1)
.replace(/file:\/\/\/.+files/gi, ""),
);
}
} catch (error) {
reject(error);
}
}, 0);
});
const result = await Promise.race([promise, timeout(timeoutMs)]);
stopProcess(process);
await Deno.remove(filePath);
context.response.body = result as string;
return;
} catch (error) {
if (process) {
stopProcess(process);
}
try {
if (Deno.statSync(filePath).isFile) {
await Deno.remove(filePath);
}
} catch (_error) {
// no op
}
context.response.status = 500;
// console.error(error);
context.response.body = JSON.stringify({
success: false,
message: `${(error as Error)?.message ? (error as Error)?.message : error}`,
data: null,
});
return;
}
}
context.response.status = 400;
context.response.body = JSON.stringify({
success: false,
message: "invalid code. code must have at least one console.log statement",
data: null,
});
};
async function stopProcess(process: Deno.Process) {
if (typeof process !== "undefined") {
try {
process.kill("SIGTERM");
process.kill("SIGINT");
} catch (_error) {
// not interested
}
}
await Promise.resolve(true);
}