bitburner-src/electron/api-server.js

200 lines
4.5 KiB
JavaScript
Raw Normal View History

/* eslint-disable @typescript-eslint/no-var-requires */
const http = require("http");
const crypto = require("crypto");
const log = require("electron-log");
const Config = require("electron-config");
const config = new Config();
let server;
let window;
async function initialize(win) {
window = win;
server = http.createServer(async function (req, res) {
let body = "";
2022-04-07 01:30:08 +02:00
res.setHeader("Content-Type", "application/json");
req.on("data", (chunk) => {
body += chunk.toString(); // convert Buffer to string
});
req.on("end", async () => {
2022-04-07 01:30:08 +02:00
const providedToken = req.headers?.authorization?.replace("Bearer ", "") ?? "";
const isValid = providedToken === getAuthenticationToken();
if (isValid) {
2022-04-07 01:30:08 +02:00
log.debug("Valid authentication token");
} else {
2022-04-07 01:30:08 +02:00
log.log("Invalid authentication token");
res.writeHead(401);
2022-04-07 01:30:08 +02:00
res.end(
JSON.stringify({
success: false,
msg: "Invalid authentication token",
}),
);
return;
}
let data;
try {
data = JSON.parse(body);
} catch (error) {
log.warn(`Invalid body data`);
res.writeHead(400);
2022-04-07 01:30:08 +02:00
res.end(
JSON.stringify({
success: false,
msg: "Invalid body data",
}),
);
return;
}
let result;
2022-04-07 01:30:08 +02:00
switch (req.method) {
// Request files
case "GET":
2022-01-20 18:39:50 +01:00
result = await window.webContents.executeJavaScript(`document.getFiles()`);
break;
// Create or update files
// Support POST for VScode implementation
case "POST":
case "PUT":
if (!data) {
log.warn(`Invalid script update request - No data`);
res.writeHead(400);
2022-04-07 01:30:08 +02:00
res.end(
JSON.stringify({
success: false,
msg: "Invalid script update request - No data",
}),
);
return;
}
result = await window.webContents.executeJavaScript(`document.saveFile("${data.filename}", "${data.code}")`);
break;
// Delete files
case "DELETE":
2022-01-21 17:52:53 +01:00
result = await window.webContents.executeJavaScript(`document.deleteFile("${data.filename}")`);
break;
}
if (!result.res) {
//We've encountered an error
res.writeHead(400);
log.warn(`Api Server Error`, result.msg);
}
2022-04-07 01:30:08 +02:00
res.end(
JSON.stringify({
success: result.res,
msg: result.msg,
data: result.data,
}),
);
});
});
2022-04-07 01:30:08 +02:00
const autostart = config.get("autostart", false);
if (autostart) {
try {
2022-04-07 01:30:08 +02:00
await enable();
} catch (error) {
return Promise.reject(error);
}
}
return Promise.resolve();
}
function enable() {
if (isListening()) {
2022-04-07 01:30:08 +02:00
log.warn("API server already listening");
return Promise.resolve();
}
2022-04-07 01:30:08 +02:00
const port = config.get("port", 9990);
const host = config.get("host", "127.0.0.1");
log.log(`Starting http server on port ${port} - listening on ${host}`);
// https://stackoverflow.com/a/62289870
let startFinished = false;
return new Promise((resolve, reject) => {
server.listen(port, host, () => {
if (!startFinished) {
startFinished = true;
resolve();
}
});
2022-04-07 01:30:08 +02:00
server.once("error", (err) => {
if (!startFinished) {
startFinished = true;
2022-04-07 01:30:08 +02:00
console.log("There was an error starting the server in the error listener:", err);
reject(err);
}
});
});
}
function disable() {
if (!isListening()) {
2022-04-07 01:30:08 +02:00
log.warn("API server not listening");
return Promise.resolve();
}
2022-04-07 01:30:08 +02:00
log.log("Stopping http server");
return server.close();
}
function toggleServer() {
if (isListening()) {
return disable();
} else {
return enable();
}
}
function isListening() {
return server?.listening ?? false;
}
function toggleAutostart() {
const newValue = !isAutostart();
2022-04-07 01:30:08 +02:00
config.set("autostart", newValue);
log.log(`New autostart value is '${newValue}'`);
}
function isAutostart() {
2022-04-07 01:30:08 +02:00
return config.get("autostart");
}
function getAuthenticationToken() {
2022-04-07 01:30:08 +02:00
const token = config.get("token");
if (token) return token;
const newToken = generateToken();
2022-04-07 01:30:08 +02:00
config.set("token", newToken);
return newToken;
}
function generateToken() {
const buffer = crypto.randomBytes(48);
2022-04-07 01:30:08 +02:00
return buffer.toString("base64");
}
module.exports = {
initialize,
2022-04-07 01:30:08 +02:00
enable,
disable,
toggleServer,
toggleAutostart,
isAutostart,
getAuthenticationToken,
isListening,
};