Compare commits

..

1 Commits

Author SHA1 Message Date
Zimeng Xiong bb42187ba8 make async database integrity check 2025-11-22 21:59:18 -08:00
2 changed files with 44 additions and 55 deletions
+24 -53
View File
@@ -5,6 +5,7 @@ import path from "path";
import fs from "fs"; import fs from "fs";
import { createServer } from "http"; import { createServer } from "http";
import { Server } from "socket.io"; import { Server } from "socket.io";
import { Worker } from "worker_threads";
import multer from "multer"; import multer from "multer";
import archiver from "archiver"; import archiver from "archiver";
import Database from "better-sqlite3"; import Database from "better-sqlite3";
@@ -125,61 +126,31 @@ const respondWithValidationErrors = (
}); });
}; };
const validateSqliteHeader = (filePath: string): boolean => { // Non-blocking CPU check using worker threads
try { const verifyDatabaseIntegrityAsync = (filePath: string): Promise<boolean> => {
const buffer = Buffer.alloc(16); return new Promise((resolve) => {
const fd = fs.openSync(filePath, "r"); const worker = new Worker(
const bytesRead = fs.readSync(fd, buffer, 0, 16, 0); path.resolve(__dirname, "./workers/db-verify.js"),
fs.closeSync(fd); {
workerData: { filePath },
if (bytesRead < 16) {
console.warn("File too small to be a valid SQLite database");
return false;
} }
);
// SQLite format 3 header: "SQLite format 3\0" (16 bytes) worker.on("message", (isValid: boolean) => resolve(isValid));
// Hex: 53 51 4c 69 74 65 20 66 6f 72 6d 61 74 20 33 00 worker.on("error", (err) => {
const expectedHeader = Buffer.from([ console.error("Worker error:", err);
0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, resolve(false);
0x74, 0x20, 0x33, 0x00,
]);
const isValid = buffer.equals(expectedHeader);
if (!isValid) {
console.warn("Invalid SQLite file header detected", {
filePath,
header: buffer.toString("hex"),
expected: expectedHeader.toString("hex"),
}); });
} worker.on("exit", (code) => {
if (code !== 0) resolve(false);
return isValid; });
} catch (error) {
console.error("Failed to validate SQLite header:", error); // Kill worker if it takes too long (DoS protection)
return false; setTimeout(() => {
} worker.terminate();
}; resolve(false);
}, 10000); // 10 second timeout
const runIntegrityCheck = (filePath: string): boolean => {
// First validate the file header to prevent RCE attacks
if (!validateSqliteHeader(filePath)) {
return false;
}
let dbInstance: Database.Database | undefined;
try {
dbInstance = new Database(filePath, {
readonly: true,
fileMustExist: true,
}); });
const result = dbInstance.prepare("PRAGMA integrity_check;").get();
return result?.integrity_check === "ok";
} catch (error) {
console.error("Integrity check failed:", error);
return false;
} finally {
dbInstance?.close();
}
}; };
const removeFileIfExists = (filePath?: string) => { const removeFileIfExists = (filePath?: string) => {
@@ -685,7 +656,7 @@ app.post("/import/sqlite/verify", upload.single("db"), async (req, res) => {
} }
const stagedPath = req.file.path; const stagedPath = req.file.path;
const isValid = runIntegrityCheck(stagedPath); const isValid = await verifyDatabaseIntegrityAsync(stagedPath);
removeFileIfExists(stagedPath); removeFileIfExists(stagedPath);
if (!isValid) { if (!isValid) {
@@ -724,7 +695,7 @@ app.post("/import/sqlite", upload.single("db"), async (req, res) => {
return res.status(500).json({ error: "Failed to stage uploaded file" }); return res.status(500).json({ error: "Failed to stage uploaded file" });
} }
const isValid = runIntegrityCheck(stagedPath); const isValid = await verifyDatabaseIntegrityAsync(stagedPath);
if (!isValid) { if (!isValid) {
removeFileIfExists(stagedPath); removeFileIfExists(stagedPath);
return res return res
+18
View File
@@ -0,0 +1,18 @@
const { parentPort, workerData } = require('worker_threads');
const Database = require('better-sqlite3');
if (!parentPort) throw new Error("Must be run in a worker thread");
try {
const { filePath } = workerData;
const db = new Database(filePath, { readonly: true, fileMustExist: true });
// This is the CPU-heavy operation
const result = db.prepare("PRAGMA integrity_check;").get();
db.close();
parentPort.postMessage(result.integrity_check === "ok");
} catch (error) {
// Any error means invalid or corrupt DB
parentPort.postMessage(false);
}