dsql-admin/dsql-app/utils/socket.js

126 lines
4.3 KiB
JavaScript
Raw Permalink Normal View History

2024-11-05 11:12:42 +00:00
// @ts-check
const http = require("http");
const path = require("path");
const fs = require("fs");
const { Server } = require("socket.io");
const { parse } = require("url");
2024-12-05 07:03:33 +00:00
const parseCookies = require("@moduletrace/datasquirel/utils/functions/parseCookies");
2024-11-05 11:12:42 +00:00
const suSocketAuth = require("../package-shared/functions/backend/suSocketAuth");
const pty = require("node-pty");
/**
*
* @param {http.Server} server
*/
module.exports = async function serverSocket(server) {
const io = new Server(server);
io.on("connection", async (socket) => {
const req = socket.request;
const parsedUrl = parse(req.url || "", true);
const { pathname, query, href, search } = parsedUrl;
const cookie = req.headers.cookie;
const paradigm = req.headers["x-socket-paradigm"];
const parsedCookies = parseCookies({ request: req });
const suAdminUser = await suSocketAuth(req);
const logPath = path.resolve(__dirname, "../log.log");
if (!suAdminUser) return;
switch (paradigm) {
case "Console":
try {
socket.emit("console", "Welcome");
process.stdin.on("data", (data) => {
console.log("STDOUT data =>", data.toString("utf8"));
});
const originalConsoleLog = console.log;
console.log = function (...args) {
const logMessage = args
.map((arg) =>
typeof arg === "object"
? JSON.stringify(arg)
: arg
)
.join(" ");
socket.emit("console", logMessage + "\n\r");
originalConsoleLog.apply(console, args);
};
socket.on("log", (log) => {
console.log(log);
});
socket.on("get-log", (log) => {
if (fs.existsSync(logPath)) {
socket.emit(
"console-log",
fs.readFileSync(logPath, "utf-8")
);
}
});
//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////
if (process.env.NEXT_PUBLIC_DSQL_LOCAL) {
const PAUSE = "\x13";
const CANCEL = "\x03";
const RESUME = "\x11";
const ptyProcess = pty.spawn("bash", [], {
name: "xterm-color",
});
socket.on("shell", (message) => {
ptyProcess.write(message);
});
ptyProcess.onData((data) => {
socket.emit("shell", data);
});
socket.on("disconnect", () => {
ptyProcess.kill("SIGTERM");
});
}
socket.on("clear-log", (message) => {
if (fs.existsSync(logPath))
fs.writeFileSync(logPath, "", "utf-8");
});
//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////
} catch (/** @type {any} */ error) {
//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////
console.log("Error in Console socket =>", error.message);
}
break;
//////////////////////////////////////////
//////////////////////////////////////////
//////////////////////////////////////////
default:
break;
}
});
io.on("error", (err) => {
console.log("Socket Server Error =>", err);
});
};