From 6483b5e7fec9c5cf432798c9b9bbbcb0c635665e Mon Sep 17 00:00:00 2001
From: catloversg <152669316+catloversg@users.noreply.github.com>
Date: Fri, 2 Aug 2024 13:09:49 +0700
Subject: [PATCH] BUGFIX: Crash when accessing nonexist files with file
protocol (#1529)
---
electron/fileError.html | 30 ------------------------------
electron/main.js | 28 ++++++++++++++++++++--------
2 files changed, 20 insertions(+), 38 deletions(-)
delete mode 100644 electron/fileError.html
diff --git a/electron/fileError.html b/electron/fileError.html
deleted file mode 100644
index 7a119b5f0..000000000
--- a/electron/fileError.html
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
- Bitburner
-
-
-
-
-
Attempts to access local files outside the normal game environment will be directed to this file.
-
-
-
diff --git a/electron/main.js b/electron/main.js
index 02c937443..07b17b78e 100644
--- a/electron/main.js
+++ b/electron/main.js
@@ -201,19 +201,31 @@ global.app_handlers = {
app.on("ready", async () => {
// Intercept file protocol requests and only let valid requests through
protocol.interceptFileProtocol("file", ({ url, method }, callback) => {
- const filePath = fileURLToPath(url);
- const realPath = realpathSync(filePath);
- const relativePath = path.relative(__dirname, realPath);
- // Only allow access to files in "dist" folder or html files in the same directory
- if (method === "GET" && (relativePath.startsWith("dist") || relativePath.match(/^[a-zA-Z-_]*\.html/))) {
- callback(realPath);
- return;
+ let filePath;
+ let realPath;
+ let relativePath;
+ /**
+ * "realpathSync" will throw an error if "filePath" points to a non-existent file. If an error is thrown here, the
+ * electron app will crash immediately. We can use fs.existsSync to check "filePath" before using it, but it's best
+ * to try-catch the entire code block and avoid unexpected issues.
+ */
+ try {
+ filePath = fileURLToPath(url);
+ realPath = realpathSync(filePath);
+ relativePath = path.relative(__dirname, realPath);
+ // Only allow access to files in "dist" folder or html files in the same directory
+ if (method === "GET" && (relativePath.startsWith("dist") || relativePath.match(/^[a-zA-Z-_]*\.html/))) {
+ callback(realPath);
+ return;
+ }
+ } catch (error) {
+ log.error(error);
}
log.error(
`Tried to access a page outside the sandbox. Url: ${url}. FilePath: ${filePath}. RealPath: ${realPath}.` +
` __dirname: ${__dirname}. RelativePath: ${relativePath}. Method: ${method}.`,
);
- callback(path.join(__dirname, "fileError.html"));
+ callback({ statusCode: 403 });
});
log.info("Application is ready!");