mirror of
https://github.com/louislam/dockge.git
synced 2025-08-19 07:22:18 +02:00
wip
This commit is contained in:
@@ -20,27 +20,20 @@ import { R } from "redbean-node";
|
||||
import { genSecret, isDev } from "./util-common";
|
||||
import { generatePasswordHash } from "./password-hash";
|
||||
import { Bean } from "redbean-node/dist/bean";
|
||||
import { DockgeSocket } from "./util-server";
|
||||
import { Arguments, Config, DockgeSocket } from "./util-server";
|
||||
import { DockerSocketHandler } from "./socket-handlers/docker-socket-handler";
|
||||
import { Terminal } from "./terminal";
|
||||
|
||||
export interface Arguments {
|
||||
sslKey? : string;
|
||||
sslCert? : string;
|
||||
sslKeyPassphrase? : string;
|
||||
port? : number;
|
||||
hostname? : string;
|
||||
dataDir? : string;
|
||||
}
|
||||
import expressStaticGzip from "express-static-gzip";
|
||||
import path from "path";
|
||||
import { TerminalSocketHandler } from "./socket-handlers/terminal-socket-handler";
|
||||
import { Stack } from "./stack";
|
||||
|
||||
export class DockgeServer {
|
||||
app : Express;
|
||||
httpServer : http.Server;
|
||||
packageJSON : PackageJson;
|
||||
io : socketIO.Server;
|
||||
config : Arguments;
|
||||
indexHTML : string;
|
||||
terminal : Terminal;
|
||||
config : Config;
|
||||
indexHTML : string = "";
|
||||
|
||||
/**
|
||||
* List of express routers
|
||||
@@ -55,6 +48,7 @@ export class DockgeServer {
|
||||
socketHandlerList : SocketHandler[] = [
|
||||
new MainSocketHandler(),
|
||||
new DockerSocketHandler(),
|
||||
new TerminalSocketHandler(),
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -64,10 +58,20 @@ export class DockgeServer {
|
||||
|
||||
jwtSecret? : string;
|
||||
|
||||
stacksDir : string = "";
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
constructor() {
|
||||
// Catch unexpected errors here
|
||||
let unexpectedErrorHandler = (error : unknown) => {
|
||||
console.trace(error);
|
||||
console.error("If you keep encountering errors, please report to https://github.com/louislam/uptime-kuma/issues");
|
||||
};
|
||||
process.addListener("unhandledRejection", unexpectedErrorHandler);
|
||||
process.addListener("uncaughtException", unexpectedErrorHandler);
|
||||
|
||||
if (!process.env.NODE_ENV) {
|
||||
process.env.NODE_ENV = "production";
|
||||
}
|
||||
@@ -75,8 +79,8 @@ export class DockgeServer {
|
||||
// Log NODE ENV
|
||||
log.info("server", "NODE_ENV: " + process.env.NODE_ENV);
|
||||
|
||||
// Load arguments
|
||||
const args = this.config = parse<Arguments>({
|
||||
// Define all possible arguments
|
||||
let args = parse<Arguments>({
|
||||
sslKey: {
|
||||
type: String,
|
||||
optional: true,
|
||||
@@ -103,21 +107,101 @@ export class DockgeServer {
|
||||
}
|
||||
});
|
||||
|
||||
// Load from environment variables or default values if args are not set
|
||||
args.sslKey = args.sslKey || process.env.DOCKGE_SSL_KEY || undefined;
|
||||
args.sslCert = args.sslCert || process.env.DOCKGE_SSL_CERT || undefined;
|
||||
args.sslKeyPassphrase = args.sslKeyPassphrase || process.env.DOCKGE_SSL_KEY_PASSPHRASE || undefined;
|
||||
args.port = args.port || parseInt(process.env.DOCKGE_PORT) || 5001;
|
||||
args.hostname = args.hostname || process.env.DOCKGE_HOSTNAME || undefined;
|
||||
args.dataDir = args.dataDir || process.env.DOCKGE_DATA_DIR || "./data/";
|
||||
this.config = args as Config;
|
||||
|
||||
log.debug("server", args);
|
||||
// Load from environment variables or default values if args are not set
|
||||
this.config.sslKey = args.sslKey || process.env.DOCKGE_SSL_KEY || undefined;
|
||||
this.config.sslCert = args.sslCert || process.env.DOCKGE_SSL_CERT || undefined;
|
||||
this.config.sslKeyPassphrase = args.sslKeyPassphrase || process.env.DOCKGE_SSL_KEY_PASSPHRASE || undefined;
|
||||
this.config.port = args.port || parseInt(process.env.DOCKGE_PORT) || 5001;
|
||||
this.config.hostname = args.hostname || process.env.DOCKGE_HOSTNAME || undefined;
|
||||
this.config.dataDir = args.dataDir || process.env.DOCKGE_DATA_DIR || "./data/";
|
||||
|
||||
log.debug("server", this.config);
|
||||
|
||||
this.packageJSON = packageJSON as PackageJson;
|
||||
|
||||
try {
|
||||
this.indexHTML = fs.readFileSync("./frontend-dist/index.html").toString();
|
||||
} catch (e) {
|
||||
// "dist/index.html" is not necessary for development
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
log.error("server", "Error: Cannot find 'frontend-dist/index.html', did you install correctly?");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Create all the necessary directories
|
||||
this.initDataDir();
|
||||
|
||||
this.terminal = new Terminal(this);
|
||||
// Create express
|
||||
this.app = express();
|
||||
|
||||
// Create HTTP server
|
||||
if (this.config.sslKey && this.config.sslCert) {
|
||||
log.info("server", "Server Type: HTTPS");
|
||||
this.httpServer = https.createServer({
|
||||
key: fs.readFileSync(this.config.sslKey),
|
||||
cert: fs.readFileSync(this.config.sslCert),
|
||||
passphrase: this.config.sslKeyPassphrase,
|
||||
}, this.app);
|
||||
} else {
|
||||
log.info("server", "Server Type: HTTP");
|
||||
this.httpServer = http.createServer(this.app);
|
||||
}
|
||||
|
||||
// Binding Routers
|
||||
for (const router of this.routerList) {
|
||||
this.app.use(router.create(this.app, this));
|
||||
}
|
||||
|
||||
// Static files
|
||||
this.app.use("/", expressStaticGzip("frontend-dist", {
|
||||
enableBrotli: true,
|
||||
}));
|
||||
|
||||
// Universal Route Handler, must be at the end of all express routes.
|
||||
this.app.get("*", async (_request, response) => {
|
||||
response.send(this.indexHTML);
|
||||
});
|
||||
|
||||
// Allow all CORS origins in development
|
||||
let cors = undefined;
|
||||
if (isDev) {
|
||||
cors = {
|
||||
origin: "*",
|
||||
};
|
||||
}
|
||||
|
||||
// Create Socket.io
|
||||
this.io = new socketIO.Server(this.httpServer, {
|
||||
cors,
|
||||
});
|
||||
|
||||
this.io.on("connection", (socket: Socket) => {
|
||||
log.info("server", "Socket connected!");
|
||||
|
||||
this.sendInfo(socket, true);
|
||||
|
||||
if (this.needSetup) {
|
||||
log.info("server", "Redirect to setup page");
|
||||
socket.emit("setup");
|
||||
}
|
||||
|
||||
// Create socket handlers
|
||||
for (const socketHandler of this.socketHandlerList) {
|
||||
socketHandler.create(socket as DockgeSocket, this);
|
||||
}
|
||||
});
|
||||
|
||||
this.io.on("disconnect", () => {
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
prepareServer() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -157,64 +241,6 @@ export class DockgeServer {
|
||||
this.needSetup = true;
|
||||
}
|
||||
|
||||
// Create express
|
||||
this.app = express();
|
||||
|
||||
if (this.config.sslKey && this.config.sslCert) {
|
||||
log.info("server", "Server Type: HTTPS");
|
||||
this.httpServer = https.createServer({
|
||||
key: fs.readFileSync(this.config.sslKey),
|
||||
cert: fs.readFileSync(this.config.sslCert),
|
||||
passphrase: this.config.sslKeyPassphrase,
|
||||
}, this.app);
|
||||
} else {
|
||||
log.info("server", "Server Type: HTTP");
|
||||
this.httpServer = http.createServer(this.app);
|
||||
}
|
||||
|
||||
try {
|
||||
this.indexHTML = fs.readFileSync("./dist/index.html").toString();
|
||||
} catch (e) {
|
||||
// "dist/index.html" is not necessary for development
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
log.error("server", "Error: Cannot find 'dist/index.html', did you install correctly?");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
for (const router of this.routerList) {
|
||||
this.app.use(router.create(this.app, this));
|
||||
}
|
||||
|
||||
let cors = undefined;
|
||||
|
||||
if (isDev) {
|
||||
cors = {
|
||||
origin: "*",
|
||||
};
|
||||
}
|
||||
|
||||
// Create Socket.io
|
||||
this.io = new socketIO.Server(this.httpServer, {
|
||||
cors,
|
||||
});
|
||||
|
||||
this.io.on("connection", (socket: Socket) => {
|
||||
log.info("server", "Socket connected!");
|
||||
|
||||
this.sendInfo(socket, true);
|
||||
|
||||
if (this.needSetup) {
|
||||
log.info("server", "Redirect to setup page");
|
||||
socket.emit("setup");
|
||||
}
|
||||
|
||||
// Create socket handlers
|
||||
for (const socketHandler of this.socketHandlerList) {
|
||||
socketHandler.create(socket as DockgeSocket, this);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen
|
||||
this.httpServer.listen(5001, this.config.hostname, () => {
|
||||
if (this.config.hostname) {
|
||||
@@ -349,14 +375,21 @@ export class DockgeServer {
|
||||
* Initialize the data directory
|
||||
*/
|
||||
initDataDir() {
|
||||
if (! fs.existsSync(this.config.dataDir)) {
|
||||
fs.mkdirSync(this.config.dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Check if a directory
|
||||
if (!fs.lstatSync(this.config.dataDir).isDirectory()) {
|
||||
throw new Error(`Fatal error: ${this.config.dataDir} is not a directory`);
|
||||
}
|
||||
|
||||
if (! fs.existsSync(this.config.dataDir)) {
|
||||
fs.mkdirSync(this.config.dataDir, { recursive: true });
|
||||
// Create data/stacks directory
|
||||
this.stacksDir = path.join(this.config.dataDir, "stacks");
|
||||
if (!fs.existsSync(this.stacksDir)) {
|
||||
fs.mkdirSync(this.stacksDir, { recursive: true });
|
||||
}
|
||||
|
||||
log.info("server", `Data Dir: ${this.config.dataDir}`);
|
||||
}
|
||||
|
||||
@@ -378,4 +411,19 @@ export class DockgeServer {
|
||||
await R.store(jwtSecretBean);
|
||||
return jwtSecretBean;
|
||||
}
|
||||
|
||||
sendStackList(socket : DockgeSocket) {
|
||||
let room = socket.userID.toString();
|
||||
let stackList = Stack.getStackList(this);
|
||||
let list = {};
|
||||
|
||||
for (let stack of stackList) {
|
||||
list[stack.name] = stack.toSimpleJSON();
|
||||
}
|
||||
|
||||
this.io.to(room).emit("stackList", {
|
||||
ok: true,
|
||||
stackList: list,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ export class MainRouter extends Router {
|
||||
const router = express.Router();
|
||||
|
||||
router.get("/", (req, res) => {
|
||||
|
||||
res.send(server.indexHTML);
|
||||
});
|
||||
|
||||
return router;
|
||||
|
@@ -1,61 +1,84 @@
|
||||
import { SocketHandler } from "../socket-handler.js";
|
||||
import { DockgeServer } from "../dockge-server";
|
||||
import { checkLogin, DockgeSocket } from "../util-server";
|
||||
import { callbackError, checkLogin, DockgeSocket, ValidationError } from "../util-server";
|
||||
import { log } from "../log";
|
||||
|
||||
const allowedCommandList : string[] = [
|
||||
"docker",
|
||||
];
|
||||
import yaml from "yaml";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import {
|
||||
allowedCommandList,
|
||||
allowedRawKeys,
|
||||
getComposeTerminalName,
|
||||
isDev,
|
||||
PROGRESS_TERMINAL_ROWS
|
||||
} from "../util-common";
|
||||
import { Terminal } from "../terminal";
|
||||
import { Stack } from "../stack";
|
||||
|
||||
export class DockerSocketHandler extends SocketHandler {
|
||||
create(socket : DockgeSocket, server : DockgeServer) {
|
||||
|
||||
socket.on("composeUp", async (compose, callback) => {
|
||||
|
||||
});
|
||||
|
||||
socket.on("terminalInput", async (cmd : unknown, errorCallback) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
|
||||
if (typeof(cmd) !== "string") {
|
||||
throw new Error("Command must be a string.");
|
||||
}
|
||||
|
||||
// Check if the command is allowed
|
||||
const cmdParts = cmd.split(" ");
|
||||
const executable = cmdParts[0].trim();
|
||||
log.debug("console", "Executable: " + executable);
|
||||
log.debug("console", "Executable length: " + executable.length);
|
||||
|
||||
if (!allowedCommandList.includes(executable)) {
|
||||
throw new Error("Command not allowed.");
|
||||
}
|
||||
|
||||
server.terminal.write(cmd);
|
||||
} catch (e) {
|
||||
errorCallback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Setup
|
||||
socket.on("getTerminalBuffer", async (callback) => {
|
||||
socket.on("deployStack", async (name : unknown, composeYAML : unknown, isAdd : unknown, callback) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
const stack = this.saveStack(socket, server, name, composeYAML, isAdd);
|
||||
await stack.deploy(socket);
|
||||
callback({
|
||||
ok: true,
|
||||
buffer: server.terminal.getBuffer(),
|
||||
});
|
||||
} catch (e) {
|
||||
callback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
});
|
||||
callbackError(e, callback);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("saveStack", async (name : unknown, composeYAML : unknown, isAdd : unknown, callback) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
this.saveStack(socket, server, name, composeYAML, isAdd);
|
||||
callback({
|
||||
ok: true,
|
||||
"msg": "Saved"
|
||||
});
|
||||
server.sendStackList(socket);
|
||||
} catch (e) {
|
||||
callbackError(e, callback);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("getStack", (stackName : unknown, callback) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
|
||||
if (typeof(stackName) !== "string") {
|
||||
throw new ValidationError("Stack name must be a string");
|
||||
}
|
||||
|
||||
const stack = Stack.getStack(server, stackName);
|
||||
callback({
|
||||
ok: true,
|
||||
stack: stack.toJSON(),
|
||||
});
|
||||
} catch (e) {
|
||||
callbackError(e, callback);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
saveStack(socket : DockgeSocket, server : DockgeServer, name : unknown, composeYAML : unknown, isAdd : unknown) : Stack {
|
||||
// Check types
|
||||
if (typeof(name) !== "string") {
|
||||
throw new ValidationError("Name must be a string");
|
||||
}
|
||||
if (typeof(composeYAML) !== "string") {
|
||||
throw new ValidationError("Compose YAML must be a string");
|
||||
}
|
||||
if (typeof(isAdd) !== "boolean") {
|
||||
throw new ValidationError("isAdd must be a boolean");
|
||||
}
|
||||
|
||||
const stack = new Stack(server, name, composeYAML);
|
||||
stack.save(isAdd);
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -71,7 +71,7 @@ export class MainSocketHandler extends SocketHandler {
|
||||
}
|
||||
|
||||
log.debug("auth", "afterLogin");
|
||||
await this.afterLogin(socket, user);
|
||||
await this.afterLogin(server, socket, user);
|
||||
log.debug("auth", "afterLogin ok");
|
||||
|
||||
log.info("auth", `Successfully logged in user ${decoded.username}. IP=${clientIP}`);
|
||||
@@ -128,7 +128,7 @@ export class MainSocketHandler extends SocketHandler {
|
||||
|
||||
if (user) {
|
||||
if (user.twofa_status === 0) {
|
||||
this.afterLogin(socket, user);
|
||||
this.afterLogin(server, socket, user);
|
||||
|
||||
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
||||
|
||||
@@ -151,7 +151,7 @@ export class MainSocketHandler extends SocketHandler {
|
||||
const verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions);
|
||||
|
||||
if (user.twofa_last_token !== data.token && verify) {
|
||||
this.afterLogin(socket, user);
|
||||
this.afterLogin(server, socket, user);
|
||||
|
||||
await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [
|
||||
data.token,
|
||||
@@ -189,10 +189,15 @@ export class MainSocketHandler extends SocketHandler {
|
||||
});
|
||||
}
|
||||
|
||||
async afterLogin(socket : DockgeSocket, user : User) {
|
||||
async afterLogin(server: DockgeServer, socket : DockgeSocket, user : User) {
|
||||
socket.userID = user.id;
|
||||
socket.join(user.id + "");
|
||||
socket.join("terminal");
|
||||
socket.join(user.id.toString());
|
||||
|
||||
try {
|
||||
server.sendStackList(socket);
|
||||
} catch (e) {
|
||||
log.error("server", e);
|
||||
}
|
||||
}
|
||||
|
||||
async login(username : string, password : string) {
|
||||
|
111
backend/socket-handlers/terminal-socket-handler.ts
Normal file
111
backend/socket-handlers/terminal-socket-handler.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
import { SocketHandler } from "../socket-handler.js";
|
||||
import { DockgeServer } from "../dockge-server";
|
||||
import { callbackError, checkLogin, DockgeSocket, ValidationError } from "../util-server";
|
||||
import { log } from "../log";
|
||||
import yaml from "yaml";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import { allowedCommandList, allowedRawKeys, isDev } from "../util-common";
|
||||
import { Terminal } from "../terminal";
|
||||
|
||||
export class TerminalSocketHandler extends SocketHandler {
|
||||
create(socket : DockgeSocket, server : DockgeServer) {
|
||||
|
||||
socket.on("terminalInputRaw", async (key : unknown) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
|
||||
if (typeof(key) !== "string") {
|
||||
throw new Error("Key must be a string.");
|
||||
}
|
||||
|
||||
if (allowedRawKeys.includes(key)) {
|
||||
server.terminal.write(key);
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("terminalInput", async (terminalName : unknown, cmd : unknown, errorCallback : unknown) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
|
||||
if (typeof(cmd) !== "string") {
|
||||
throw new Error("Command must be a string.");
|
||||
}
|
||||
|
||||
// Check if the command is allowed
|
||||
const cmdParts = cmd.split(" ");
|
||||
const executable = cmdParts[0].trim();
|
||||
log.debug("console", "Executable: " + executable);
|
||||
log.debug("console", "Executable length: " + executable.length);
|
||||
|
||||
if (!allowedCommandList.includes(executable)) {
|
||||
throw new Error("Command not allowed.");
|
||||
}
|
||||
|
||||
server.terminal.write(cmd);
|
||||
} catch (e) {
|
||||
if (typeof(errorCallback) === "function") {
|
||||
errorCallback({
|
||||
ok: false,
|
||||
msg: e.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Create Terminal
|
||||
socket.on("terminalCreate", async (terminalName : unknown, callback : unknown) => {
|
||||
|
||||
});
|
||||
|
||||
// Join Terminal
|
||||
socket.on("terminalJoin", async (terminalName : unknown, callback : unknown) => {
|
||||
if (typeof(callback) !== "function") {
|
||||
log.debug("console", "Callback is not a function.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
checkLogin(socket);
|
||||
if (typeof(terminalName) !== "string") {
|
||||
throw new ValidationError("Terminal name must be a string.");
|
||||
}
|
||||
|
||||
let buffer : string = Terminal.getTerminal(terminalName)?.getBuffer() ?? "";
|
||||
|
||||
if (!buffer) {
|
||||
log.debug("console", "No buffer found.");
|
||||
}
|
||||
|
||||
callback({
|
||||
ok: true,
|
||||
buffer,
|
||||
});
|
||||
} catch (e) {
|
||||
callbackError(e, callback);
|
||||
}
|
||||
});
|
||||
|
||||
// Close Terminal
|
||||
socket.on("terminalClose", async (terminalName : unknown, callback : unknown) => {
|
||||
|
||||
});
|
||||
|
||||
// Resize Terminal
|
||||
socket.on("terminalResize", async (rows : unknown) => {
|
||||
try {
|
||||
checkLogin(socket);
|
||||
if (typeof(rows) !== "number") {
|
||||
throw new Error("Rows must be a number.");
|
||||
}
|
||||
log.debug("console", "Resize terminal to " + rows + " rows.");
|
||||
server.terminal.resize(rows);
|
||||
} catch (e) {
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
158
backend/stack.ts
Normal file
158
backend/stack.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { DockgeServer } from "./dockge-server";
|
||||
import fs from "fs";
|
||||
import { log } from "./log";
|
||||
import yaml from "yaml";
|
||||
import { DockgeSocket, ValidationError } from "./util-server";
|
||||
import path from "path";
|
||||
import { getComposeTerminalName, PROGRESS_TERMINAL_ROWS } from "./util-common";
|
||||
import { Terminal } from "./terminal";
|
||||
|
||||
export class Stack {
|
||||
|
||||
name: string;
|
||||
protected _composeYAML?: string;
|
||||
protected server: DockgeServer;
|
||||
|
||||
constructor(server : DockgeServer, name : string, composeYAML? : string) {
|
||||
this.name = name;
|
||||
this.server = server;
|
||||
this._composeYAML = composeYAML;
|
||||
}
|
||||
|
||||
toJSON() : object {
|
||||
let obj = this.toSimpleJSON();
|
||||
return {
|
||||
...obj,
|
||||
composeYAML: this.composeYAML,
|
||||
};
|
||||
}
|
||||
|
||||
toSimpleJSON() : object {
|
||||
return {
|
||||
name: this.name,
|
||||
tags: [],
|
||||
};
|
||||
}
|
||||
|
||||
validate() {
|
||||
// Check name, allows [a-z][A-Z][0-9] _ - only
|
||||
if (!this.name.match(/^[a-zA-Z0-9_-]+$/)) {
|
||||
throw new ValidationError("Stack name can only contain [a-z][A-Z][0-9] _ - only");
|
||||
}
|
||||
|
||||
// Check YAML format
|
||||
yaml.parse(this.composeYAML);
|
||||
}
|
||||
|
||||
get composeYAML() : string {
|
||||
if (this._composeYAML === undefined) {
|
||||
try {
|
||||
this._composeYAML = fs.readFileSync(path.join(this.path, "compose.yaml"), "utf-8");
|
||||
} catch (e) {
|
||||
this._composeYAML = "";
|
||||
}
|
||||
}
|
||||
return this._composeYAML;
|
||||
}
|
||||
|
||||
get path() : string {
|
||||
return path.join(this.server.stacksDir, this.name);
|
||||
}
|
||||
|
||||
get fullPath() : string {
|
||||
let dir = this.path;
|
||||
|
||||
// Compose up via node-pty
|
||||
let fullPathDir;
|
||||
|
||||
// if dir is relative, make it absolute
|
||||
if (!path.isAbsolute(dir)) {
|
||||
fullPathDir = path.join(process.cwd(), dir);
|
||||
} else {
|
||||
fullPathDir = dir;
|
||||
}
|
||||
return fullPathDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the stack to the disk
|
||||
* @param isAdd
|
||||
*/
|
||||
save(isAdd : boolean) {
|
||||
this.validate();
|
||||
|
||||
let dir = this.path;
|
||||
|
||||
// Check if the name is used if isAdd
|
||||
if (isAdd) {
|
||||
if (fs.existsSync(dir)) {
|
||||
throw new ValidationError("Stack name already exists");
|
||||
}
|
||||
|
||||
// Create the stack folder
|
||||
fs.mkdirSync(dir);
|
||||
} else {
|
||||
if (!fs.existsSync(dir)) {
|
||||
throw new ValidationError("Stack not found");
|
||||
}
|
||||
}
|
||||
|
||||
// Write or overwrite the compose.yaml
|
||||
fs.writeFileSync(path.join(dir, "compose.yaml"), this.composeYAML);
|
||||
}
|
||||
|
||||
async deploy(socket? : DockgeSocket) : Promise<number> {
|
||||
const terminalName = getComposeTerminalName(this.name);
|
||||
log.debug("deployStack", "Terminal name: " + terminalName);
|
||||
|
||||
const terminal = new Terminal(this.server, terminalName, "docker-compose", [ "up", "-d" ], this.path);
|
||||
log.debug("deployStack", "Terminal created");
|
||||
|
||||
terminal.rows = PROGRESS_TERMINAL_ROWS;
|
||||
|
||||
if (socket) {
|
||||
terminal.join(socket);
|
||||
log.debug("deployStack", "Terminal joined");
|
||||
} else {
|
||||
log.debug("deployStack", "No socket, not joining");
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
terminal.onExit((exitCode : number) => {
|
||||
if (exitCode === 0) {
|
||||
resolve(exitCode);
|
||||
} else {
|
||||
reject(new Error("Failed to deploy, please check the terminal output for more information."));
|
||||
}
|
||||
});
|
||||
terminal.start();
|
||||
});
|
||||
}
|
||||
|
||||
static getStackList(server : DockgeServer) : Stack[] {
|
||||
let stacksDir = server.stacksDir;
|
||||
let stackList : Stack[] = [];
|
||||
|
||||
// Scan the stacks directory, and get the stack list
|
||||
let filenameList = fs.readdirSync(stacksDir);
|
||||
|
||||
log.debug("stack", filenameList);
|
||||
|
||||
for (let filename of filenameList) {
|
||||
let relativePath = path.join(stacksDir, filename);
|
||||
if (fs.statSync(relativePath).isDirectory()) {
|
||||
let stack = new Stack(server, filename);
|
||||
stackList.push(stack);
|
||||
}
|
||||
}
|
||||
return stackList;
|
||||
}
|
||||
|
||||
static getStack(server: DockgeServer, stackName: string) : Stack {
|
||||
let dir = path.join(server.stacksDir, stackName);
|
||||
if (!fs.existsSync(dir)) {
|
||||
throw new ValidationError("Stack not found");
|
||||
}
|
||||
return new Stack(server, stackName);
|
||||
}
|
||||
}
|
@@ -1,43 +1,151 @@
|
||||
import { DockgeServer } from "./dockge-server";
|
||||
import * as os from "node:os";
|
||||
import * as pty from "node-pty";
|
||||
import * as pty from "@homebridge/node-pty-prebuilt-multiarch";
|
||||
import { LimitQueue } from "./utils/limit-queue";
|
||||
import { DockgeSocket } from "./util-server";
|
||||
import { getCryptoRandomInt, TERMINAL_COLS, TERMINAL_ROWS } from "./util-common";
|
||||
import { sync as commandExistsSync } from "command-exists";
|
||||
import { log } from "./log";
|
||||
|
||||
const shell = os.platform() === "win32" ? "pwsh.exe" : "bash";
|
||||
|
||||
/**
|
||||
* Terminal for running commands, no user interaction
|
||||
*/
|
||||
export class Terminal {
|
||||
|
||||
ptyProcess;
|
||||
private server : DockgeServer;
|
||||
private buffer : LimitQueue<string> = new LimitQueue(100);
|
||||
protected static terminalMap : Map<string, Terminal> = new Map();
|
||||
|
||||
constructor(server : DockgeServer) {
|
||||
protected _ptyProcess? : pty.IPty;
|
||||
protected server : DockgeServer;
|
||||
protected buffer : LimitQueue<string> = new LimitQueue(100);
|
||||
protected _name : string;
|
||||
|
||||
protected file : string;
|
||||
protected args : string | string[];
|
||||
protected cwd : string;
|
||||
protected callback? : (exitCode : number) => void;
|
||||
|
||||
protected _rows : number = TERMINAL_ROWS;
|
||||
|
||||
constructor(server : DockgeServer, name : string, file : string, args : string | string[], cwd : string) {
|
||||
this.server = server;
|
||||
this._name = name;
|
||||
//this._name = "terminal-" + Date.now() + "-" + getCryptoRandomInt(0, 1000000);
|
||||
this.file = file;
|
||||
this.args = args;
|
||||
this.cwd = cwd;
|
||||
|
||||
this.ptyProcess = pty.spawn(shell, [], {
|
||||
name: "dockge-terminal",
|
||||
cwd: "./tmp",
|
||||
});
|
||||
|
||||
// this.ptyProcess.write("npm remove lodash\r");
|
||||
//this.ptyProcess.write("npm install lodash\r");
|
||||
|
||||
this.ptyProcess.onData((data) => {
|
||||
this.buffer.push(data);
|
||||
this.server.io.to("terminal").emit("commandOutput", data);
|
||||
});
|
||||
|
||||
Terminal.terminalMap.set(this.name, this);
|
||||
}
|
||||
|
||||
write(input : string) {
|
||||
this.ptyProcess.write(input);
|
||||
get rows() {
|
||||
return this._rows;
|
||||
}
|
||||
|
||||
set rows(rows : number) {
|
||||
this._rows = rows;
|
||||
this.ptyProcess?.resize(TERMINAL_COLS, rows);
|
||||
}
|
||||
|
||||
public start() {
|
||||
this._ptyProcess = pty.spawn(this.file, this.args, {
|
||||
name: this.name,
|
||||
cwd: this.cwd,
|
||||
cols: TERMINAL_COLS,
|
||||
rows: this.rows,
|
||||
});
|
||||
|
||||
// On Data
|
||||
this._ptyProcess.onData((data) => {
|
||||
this.buffer.push(data);
|
||||
if (this.server.io) {
|
||||
this.server.io.to(this.name).emit("terminalWrite", this.name, data);
|
||||
}
|
||||
});
|
||||
|
||||
// On Exit
|
||||
this._ptyProcess.onExit((res) => {
|
||||
this.server.io.to(this.name).emit("terminalExit", this.name, res.exitCode);
|
||||
|
||||
// Remove room
|
||||
this.server.io.in(this.name).socketsLeave(this.name);
|
||||
|
||||
if (this.callback) {
|
||||
this.callback(res.exitCode);
|
||||
}
|
||||
|
||||
Terminal.terminalMap.delete(this.name);
|
||||
log.debug("Terminal", "Terminal " + this.name + " exited with code " + res.exitCode);
|
||||
});
|
||||
}
|
||||
|
||||
public onExit(callback : (exitCode : number) => void) {
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
public join(socket : DockgeSocket) {
|
||||
socket.join(this.name);
|
||||
}
|
||||
|
||||
public leave(socket : DockgeSocket) {
|
||||
socket.leave(this.name);
|
||||
}
|
||||
|
||||
public get ptyProcess() {
|
||||
return this._ptyProcess;
|
||||
}
|
||||
|
||||
public get name() {
|
||||
return this._name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the terminal output string for re-connecting
|
||||
* Get the terminal output string
|
||||
*/
|
||||
getBuffer() : string {
|
||||
if (this.buffer.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return this.buffer.join("");
|
||||
}
|
||||
|
||||
close() {
|
||||
this._ptyProcess?.kill();
|
||||
}
|
||||
|
||||
public static getTerminal(name : string) : Terminal | undefined {
|
||||
return Terminal.terminalMap.get(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interactive terminal
|
||||
* Mainly used for container exec
|
||||
*/
|
||||
export class InteractiveTerminal extends Terminal {
|
||||
public write(input : string) {
|
||||
this.ptyProcess?.write(input);
|
||||
}
|
||||
|
||||
resetCWD() {
|
||||
const cwd = process.cwd();
|
||||
this.ptyProcess?.write(`cd "${cwd}"\r`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* User interactive terminal that use bash or powershell with limited commands such as docker, ls, cd, dir
|
||||
*/
|
||||
export class MainTerminal extends InteractiveTerminal {
|
||||
constructor(server : DockgeServer, name : string, cwd : string = "./") {
|
||||
let shell;
|
||||
|
||||
if (commandExistsSync("pwsh")) {
|
||||
shell = "pwsh";
|
||||
} else if (os.platform() === "win32") {
|
||||
shell = "powershell.exe";
|
||||
} else {
|
||||
shell = "bash";
|
||||
}
|
||||
super(server, name, shell, [], cwd);
|
||||
}
|
||||
}
|
||||
|
@@ -1,12 +1,38 @@
|
||||
import dayjs from "dayjs";
|
||||
|
||||
// For loading dayjs plugins, don't remove event though it is not used in this file
|
||||
import dayjs from "dayjs";
|
||||
import timezone from "dayjs/plugin/timezone";
|
||||
import utc from "dayjs/plugin/utc";
|
||||
|
||||
import { randomBytes } from "crypto";
|
||||
let randomBytes : (numBytes: number) => Uint8Array;
|
||||
|
||||
if (typeof window !== "undefined" && window.crypto) {
|
||||
randomBytes = function randomBytes(numBytes: number) {
|
||||
const bytes = new Uint8Array(numBytes);
|
||||
for (let i = 0; i < numBytes; i += 65536) {
|
||||
window.crypto.getRandomValues(bytes.subarray(i, i + Math.min(numBytes - i, 65536)));
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
} else {
|
||||
randomBytes = (await import("node:crypto")).randomBytes;
|
||||
}
|
||||
|
||||
export const isDev = process.env.NODE_ENV === "development";
|
||||
export const TERMINAL_COLS = 80;
|
||||
export const TERMINAL_ROWS = 10;
|
||||
export const PROGRESS_TERMINAL_ROWS = 8;
|
||||
|
||||
export const ERROR_TYPE_VALIDATION = 1;
|
||||
|
||||
export const allowedCommandList : string[] = [
|
||||
"docker",
|
||||
"ls",
|
||||
"cd",
|
||||
"dir",
|
||||
];
|
||||
export const allowedRawKeys = [
|
||||
"\u0003", // Ctrl + C
|
||||
];
|
||||
|
||||
/**
|
||||
* Generate a decimal integer number from a string
|
||||
@@ -54,7 +80,6 @@ export function genSecret(length = 64) {
|
||||
* @returns Cryptographically suitable random integer
|
||||
*/
|
||||
export function getCryptoRandomInt(min: number, max: number):number {
|
||||
|
||||
// synchronous version of: https://github.com/joepie91/node-random-number-csprng
|
||||
|
||||
const range = max - min;
|
||||
@@ -76,11 +101,11 @@ export function getCryptoRandomInt(min: number, max: number):number {
|
||||
tmpRange = tmpRange >>> 1;
|
||||
}
|
||||
|
||||
const randomBytes = getRandomBytes(bytesNeeded);
|
||||
const bytes = randomBytes(bytesNeeded);
|
||||
let randomValue = 0;
|
||||
|
||||
for (let i = 0; i < bytesNeeded; i++) {
|
||||
randomValue |= randomBytes[i] << 8 * i;
|
||||
randomValue |= bytes[i] << 8 * i;
|
||||
}
|
||||
|
||||
randomValue = randomValue & mask;
|
||||
@@ -92,27 +117,15 @@ export function getCryptoRandomInt(min: number, max: number):number {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns either the NodeJS crypto.randomBytes() function or its
|
||||
* browser equivalent implemented via window.crypto.getRandomValues()
|
||||
*/
|
||||
const getRandomBytes = (
|
||||
(typeof window !== "undefined" && window.crypto)
|
||||
export function getComposeTerminalName(stack : string) {
|
||||
return "compose-" + stack;
|
||||
}
|
||||
|
||||
// Browsers
|
||||
? function () {
|
||||
return (numBytes: number) => {
|
||||
const randomBytes = new Uint8Array(numBytes);
|
||||
for (let i = 0; i < numBytes; i += 65536) {
|
||||
window.crypto.getRandomValues(randomBytes.subarray(i, i + Math.min(numBytes - i, 65536)));
|
||||
}
|
||||
return randomBytes;
|
||||
};
|
||||
}
|
||||
export function getContainerTerminalName(container : string) {
|
||||
return "container-" + container;
|
||||
}
|
||||
|
||||
export function getContainerExecTerminalName(container : string, index : number) {
|
||||
return "container-exec-" + container + "-" + index;
|
||||
}
|
||||
|
||||
// Node
|
||||
: function () {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
return randomBytes;
|
||||
}
|
||||
)();
|
||||
|
@@ -1,7 +1,27 @@
|
||||
import { Socket } from "socket.io";
|
||||
import { Terminal } from "./terminal";
|
||||
import { randomBytes } from "crypto";
|
||||
import { log } from "./log";
|
||||
import { ERROR_TYPE_VALIDATION } from "./util-common";
|
||||
|
||||
export interface DockgeSocket extends Socket {
|
||||
userID: number;
|
||||
consoleTerminal? : Terminal;
|
||||
}
|
||||
|
||||
// For command line arguments, so they are nullable
|
||||
export interface Arguments {
|
||||
sslKey? : string;
|
||||
sslCert? : string;
|
||||
sslKeyPassphrase? : string;
|
||||
port? : number;
|
||||
hostname? : string;
|
||||
dataDir? : string;
|
||||
}
|
||||
|
||||
// Some config values are required
|
||||
export interface Config extends Arguments {
|
||||
dataDir : string;
|
||||
}
|
||||
|
||||
export function checkLogin(socket : DockgeSocket) {
|
||||
@@ -9,3 +29,31 @@ export function checkLogin(socket : DockgeSocket) {
|
||||
throw new Error("You are not logged in.");
|
||||
}
|
||||
}
|
||||
|
||||
export class ValidationError extends Error {
|
||||
constructor(message : string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function callbackError(error : unknown, callback : unknown) {
|
||||
if (typeof(callback) !== "function") {
|
||||
log.error("console", "Callback is not a function");
|
||||
return;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
callback({
|
||||
ok: false,
|
||||
msg: error.message,
|
||||
});
|
||||
} else if (error instanceof ValidationError) {
|
||||
callback({
|
||||
ok: false,
|
||||
type: ERROR_TYPE_VALIDATION,
|
||||
msg: error.message,
|
||||
});
|
||||
} else {
|
||||
log.debug("console", "Unknown error: " + error);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user