-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
382 lines (332 loc) · 11.2 KB
/
server.mjs
File metadata and controls
382 lines (332 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { Server as SocketIOServer } from "socket.io";
import pty from "node-pty";
import { Client as SSHClient } from "ssh2";
import { jwtVerify } from "jose";
import { PrismaClient } from "@prisma/client";
import { createDecipheriv } from "crypto";
const dev = process.env.NODE_ENV !== "production";
const hostname = "0.0.0.0";
const port = parseInt(process.env.PORT ?? "3000", 10);
const prisma = new PrismaClient();
const autoUpdateIntervalMs = Math.max(60_000, parseInt(process.env.AUTO_UPDATE_RUN_INTERVAL_MS ?? "300000", 10));
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
// Track active terminal sessions per user
const userSessionCount = new Map();
function hasContainerExecPermission(perms, containerId) {
if (!perms || !containerId) return false;
if (perms.dockerViewAll && perms.terminalAccess) return true;
return perms.containerPerms.some(
(entry) =>
entry.canExec &&
(entry.containerId === containerId ||
containerId.startsWith(entry.containerId) ||
entry.containerId.startsWith(containerId))
);
}
function getJwtSecret() {
const secret = process.env.JWT_SECRET;
if (!secret || secret.length < 32) {
throw new Error("JWT_SECRET must be at least 32 characters");
}
return new TextEncoder().encode(secret);
}
function readCookie(name, cookieHeader = "") {
const parts = cookieHeader.split(";").map((p) => p.trim());
for (const part of parts) {
if (part.startsWith(name + "=")) {
return decodeURIComponent(part.slice(name.length + 1));
}
}
return null;
}
function isSshBackendEnabled() {
return String(process.env.SSH_ENABLED ?? "false").toLowerCase() === "true";
}
function getSshRuntimeConfig() {
const host = process.env.SSH_HOST?.trim();
const username = process.env.SSH_USERNAME?.trim();
const password = getSshPassword();
const privateKey = getSshPrivateKey();
const passphrase = getSshKeyPassphrase();
const port = Number(process.env.SSH_PORT ?? "22");
if (!host || !username || (!password && !privateKey)) {
throw new Error("SSH backend is enabled but SSH_HOST/SSH_USERNAME and SSH_PRIVATE_KEY_ENC or SSH_PASSWORD_ENC are required");
}
return { host, username, password: privateKey ? undefined : password, privateKey: privateKey || undefined, passphrase: privateKey ? passphrase || undefined : undefined, port };
}
function getSshPassword() {
const encryptedPassword = process.env.SSH_PASSWORD_ENC?.trim();
const fallbackPassword = process.env.SSH_PASSWORD?.trim();
if (encryptedPassword) {
return decryptSecret(encryptedPassword);
}
return fallbackPassword ?? "";
}
function getSshPrivateKey() {
const encryptedPrivateKey = process.env.SSH_PRIVATE_KEY_ENC?.trim();
if (!encryptedPrivateKey) return "";
return decryptSecret(encryptedPrivateKey);
}
function getSshKeyPassphrase() {
const encryptedPassphrase = process.env.SSH_KEY_PASSPHRASE_ENC?.trim();
if (!encryptedPassphrase) return "";
return decryptSecret(encryptedPassphrase);
}
function decryptSecret(ciphertext) {
const keyHex = (process.env.ENCRYPTION_KEY ?? "").trim();
if (!/^[0-9a-fA-F]{32}$/.test(keyHex) && !/^[0-9a-fA-F]{64}$/.test(keyHex)) {
throw new Error("ENCRYPTION_KEY must be 32 or 64 hex characters");
}
const [ivHex, dataHex] = ciphertext.split(":");
if (!ivHex || !dataHex || !/^[0-9a-fA-F]+$/.test(ivHex) || !/^[0-9a-fA-F]+$/.test(dataHex)) {
throw new Error("Invalid SSH_PASSWORD_ENC format");
}
const normalizedKeyHex = keyHex.padEnd(64, "0");
const decipher = createDecipheriv(
"aes-256-ctr",
Buffer.from(normalizedKeyHex, "hex"),
Buffer.from(ivHex, "hex")
);
const decrypted = Buffer.concat([
decipher.update(Buffer.from(dataHex, "hex")),
decipher.final(),
]);
return decrypted.toString("utf-8");
}
async function verifySessionToken(token) {
const { payload } = await jwtVerify(token, getJwtSecret());
const sessionId = String(payload.sessionId ?? "");
const userId = String(payload.userId ?? "");
const username = String(payload.username ?? "");
if (!sessionId || !userId) {
throw new Error("Invalid session payload");
}
const session = await prisma.session.findUnique({ where: { id: sessionId } });
if (!session || session.expiresAt < new Date()) {
throw new Error("Session expired or revoked");
}
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user || !user.isActive) {
throw new Error("User disabled or missing");
}
return { sessionId, userId, username };
}
app.prepare().then(() => {
const httpServer = createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
});
async function triggerAutoUpdateCycle() {
if (!process.env.JWT_SECRET) {
return;
}
try {
await fetch(`http://127.0.0.1:${port}/api/internal/auto-update`, {
method: "POST",
headers: {
"x-internal-audit-key": process.env.JWT_SECRET,
},
});
} catch (error) {
console.error("[auto-update-runner]", error);
}
}
const io = new SocketIOServer(httpServer, {
path: "/api/socket",
cors: { origin: false },
});
const terminalNs = io.of("/terminal");
terminalNs.use(async (socket, next) => {
const token =
socket.handshake.auth?.token ??
readCookie("sc_session", socket.request.headers?.cookie ?? "");
if (!token) return next(new Error("Unauthorized"));
try {
const session = await verifySessionToken(token);
const perms = await prisma.userPermission.findUnique({
where: { userId: session.userId },
include: {
containerPerms: true,
},
});
if (!perms || !perms.terminalAccess) {
return next(new Error("Terminal access denied"));
}
socket.data.userId = session.userId;
socket.data.username = session.username;
socket.data.readOnly = perms.terminalReadOnly;
socket.data.maxSessions = perms.terminalMaxSessions;
const mode = String(socket.handshake.query?.mode ?? "host");
const containerId = String(socket.handshake.query?.containerId ?? "");
if (mode === "container") {
if (!containerId) {
return next(new Error("Missing containerId"));
}
if (!hasContainerExecPermission(perms, containerId)) {
return next(new Error("Container exec denied"));
}
}
socket.data.mode = mode;
socket.data.containerId = containerId;
next();
} catch {
return next(new Error("Invalid session"));
}
});
terminalNs.on("connection", (socket) => {
const userId = socket.data.userId;
const readOnly = socket.data.readOnly;
const mode = socket.data.mode;
const containerId = socket.data.containerId;
// Enforce max sessions
const current = userSessionCount.get(userId) ?? 0;
const max = socket.data.maxSessions;
if (max > 0 && current >= max) {
socket.emit("output", "\r\n\x1b[31mMax terminal sessions reached.\x1b[0m\r\n");
socket.disconnect();
return;
}
setInterval(() => {
void triggerAutoUpdateCycle();
}, autoUpdateIntervalMs);
userSessionCount.set(userId, current + 1);
const cwd = process.env.HOST_FS_MOUNT ?? "/host_system";
const useSshHostShell = mode === "host" && isSshBackendEnabled();
let ptyProcess = null;
let sshConn = null;
let sshStream = null;
if (useSshHostShell) {
try {
const sshCfg = getSshRuntimeConfig();
sshConn = new SSHClient();
sshConn.on("ready", () => {
sshConn.shell(
{
term: "xterm-256color",
cols: 80,
rows: 24,
},
(err, stream) => {
if (err) {
socket.emit("output", `\r\n\x1b[31mSSH shell failed: ${err.message}\x1b[0m\r\n`);
socket.disconnect();
return;
}
sshStream = stream;
stream.on("data", (data) => socket.emit("output", data.toString("utf-8")));
stream.on("close", () => {
socket.emit("output", "\r\n\x1b[33m[SSH session closed]\x1b[0m\r\n");
socket.disconnect();
});
}
);
});
sshConn.on("error", (err) => {
socket.emit("output", `\r\n\x1b[31mSSH error: ${err.message}\x1b[0m\r\n`);
});
sshConn.connect({
host: sshCfg.host,
port: sshCfg.port,
username: sshCfg.username,
password: sshCfg.password,
privateKey: sshCfg.privateKey,
passphrase: sshCfg.passphrase,
readyTimeout: 15000,
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
socket.emit("output", `\r\n\x1b[31mSSH config error: ${message}\x1b[0m\r\n`);
socket.disconnect();
return;
}
} else {
ptyProcess =
mode === "container"
? pty.spawn(
"docker",
["exec", "-u", "0", "-it", containerId, "/bin/sh"],
{
name: "xterm-256color",
cols: 80,
rows: 24,
cwd,
env: {
...process.env,
TERM: "xterm-256color",
COLORTERM: "truecolor",
},
}
)
: pty.spawn(process.env.SHELL ?? "/bin/bash", [], {
name: "xterm-256color",
cols: 80,
rows: 24,
cwd,
env: {
...process.env,
TERM: "xterm-256color",
COLORTERM: "truecolor",
},
});
ptyProcess.onData((data) => socket.emit("output", data));
ptyProcess.onExit(() => {
socket.emit("output", "\r\n\x1b[33m[Process exited]\x1b[0m\r\n");
socket.disconnect();
});
}
socket.on("input", (data) => {
if (readOnly) return;
if (sshStream) {
sshStream.write(data);
return;
}
if (ptyProcess) {
ptyProcess.write(data);
}
});
socket.on("resize", ({ cols, rows }) => {
const safeCols = Math.max(1, cols);
const safeRows = Math.max(1, rows);
if (sshStream?.setWindow) {
sshStream.setWindow(safeRows, safeCols, 0, 0);
}
if (ptyProcess) {
ptyProcess.resize(safeCols, safeRows);
}
});
socket.on("disconnect", () => {
if (sshStream) {
try {
sshStream.end();
} catch {
// noop
}
}
if (sshConn) {
try {
sshConn.end();
} catch {
// noop
}
}
if (ptyProcess) {
ptyProcess.kill();
}
const cnt = userSessionCount.get(userId) ?? 1;
userSessionCount.set(userId, Math.max(0, cnt - 1));
});
});
httpServer.listen(port, hostname, () => {
console.log(`[ServerCommander OS] Ready on http://${hostname}:${port}`);
});
const shutdown = async () => {
await prisma.$disconnect().catch(() => null);
process.exit(0);
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
});