-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathchal.js
More file actions
95 lines (84 loc) · 2.54 KB
/
Copy pathchal.js
File metadata and controls
95 lines (84 loc) · 2.54 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
import * as parser from "@babel/parser";
import _traverse from "@babel/traverse";
import _generate from "@babel/generator";
import * as _minify from "babel-minify";
import readline from "readline";
const minify = _minify.default;
const traverse = _traverse.default;
class Jail {
constructor() {
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
this.promptForInput().then((input) => {
this.processInput(input);
this.rl.close();
});
}
promptForInput() {
return new Promise((resolve) => {
this.rl.question("Enter JavaScript code (one line): ", resolve);
});
}
processInput(input) {
try {
const unminifiedCode = input;
const parsedAst = this.parseCodeToAST(unminifiedCode);
const isSafe = this.noBadNodes(parsedAst);
if (!isSafe) {
throw new Error("Unsafe code detected!");
}
// I'll help you make smol code :)
const {
code: minifiedCode
} = this.minifyCode(unminifiedCode);
if (!minifiedCode || minifiedCode.length === 0) {
throw new Error("Minified code is empty");
}
const codeToEvaluate = this.chooseCode(unminifiedCode, minifiedCode);
if (codeToEvaluate.length > 23) {
console.log("not smol enough");
return;
}
try {
eval(codeToEvaluate);
} catch {
console.log("Error during evaluation");
}
} catch (error) {
console.log("Error:", error.message);
}
}
chooseCode(code1, code2) {
return code1.length < code2.length ? code1 : code2;
}
parseCodeToAST(code) {
return parser.parse(code, {
sourceType: "module",
plugins: [],
});
}
noBadNodes(ast) {
let hasBadNodes = false;
traverse(ast, {
"CallExpression|AssignmentExpression"(path) {
hasBadNodes = true;
path.stop();
},
});
return !hasBadNodes;
}
minifyCode(code) {
try {
const result = minify(code, {});
if (result.error) {
throw result.error;
}
return result;
} catch (error) {
throw new Error("Error during minification: " + error.message);
}
}
}
new Jail();