-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapp.js
81 lines (68 loc) · 1.87 KB
/
app.js
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
// Import Aikido Firewall
const Zen = require("@aikidosec/firewall");
const { createConnection } = require("./db");
const fastify = require("fastify");
const Cats = require("./Cats");
// Prevent Prototype Pollution
require("@aikidosec/firewall/nopp");
/**
* Get the HTML body of the root page
*/
function getHTMLBody(cats) {
return `
<html lang="en">
<bod>
<p>All cats : ${cats.join(", ")}</p>
<form action="/" method="GET">
<label for="search">Add a new cat</label>
<input type="text" name="petname">
<input type="submit" value="Add" />
</form>
<a href="http://localhost:4000/?petname=Kitty'); DELETE FROM cats;-- H">Test injection</a> / <a href="http://localhost:4000/clear">Clear table</a>
</body>
</html>`;
}
// Async main function that starts the Fastify server
(async () => {
const db = await createConnection();
const cats = new Cats(db);
const app = fastify({
logger: true,
});
Zen.addFastifyHook(app);
// Handle GET requests to the root URL
app.get("/", async (request, reply) => {
if (request.query["petname"]) {
await cats.add(request.query["petname"]);
}
const html = getHTMLBody(await cats.getAll());
reply.header("Content-Type", "text/html").send(html);
});
app.route({
method: "GET",
url: "/cats",
handler: async (request, reply) => {
reply.send(await cats.getAll());
},
});
// Handle GET requests to /clear
app.get("/clear", async (request, reply) => {
await db.execute("DELETE FROM cats;");
reply.redirect("/");
});
// Start the server
try {
await app.listen({ port: getPort() });
} catch (err) {
app.log.error(err);
process.exit(1);
}
})();
function getPort() {
const port = parseInt(process.argv[2], 10) || 4000;
if (isNaN(port)) {
console.error("Invalid port");
process.exit(1);
}
return port;
}