-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
520 lines (458 loc) · 15.7 KB
/
server.mjs
File metadata and controls
520 lines (458 loc) · 15.7 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
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, timingSafeEqual } 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;
const normalizedContainerId = String(containerId).trim().toLowerCase();
return perms.containerPerms.some(
(entry) =>
entry.canExec &&
String(entry.containerId).trim().toLowerCase() === normalizedContainerId
);
}
function getInternalRpcSecret() {
const secret = (process.env.INTERNAL_RPC_SECRET ?? "").trim();
if (!secret) return null;
if (secret.length < 32) return null;
return secret;
}
function normalizeSshHostFingerprint(value) {
const raw = String(value ?? "").trim();
if (!raw) return "";
const withoutPrefix = raw.replace(/^SHA256:/i, "");
if (!/^[A-Za-z0-9+/=]+$/.test(withoutPrefix)) {
throw new Error("SSH host fingerprint must be SHA256 base64 (optionally prefixed with 'SHA256:')");
}
return withoutPrefix;
}
function isSameFingerprint(actualHash, expectedHash) {
const a = Buffer.from(actualHash, "utf-8");
const b = Buffer.from(expectedHash, "utf-8");
return a.length === b.length && timingSafeEqual(a, b);
}
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;
}
async function loadSshRuntimeSettings() {
const dbSettings = await prisma.sshSettings.findUnique({ where: { id: "default" } });
if (dbSettings) {
return {
enabled: !!dbSettings.enabled,
host: dbSettings.host?.trim() ?? "",
username: dbSettings.username?.trim() ?? "",
port: Number(dbSettings.port ?? 22),
passwordEnc: dbSettings.passwordEnc?.trim() ?? "",
privateKeyEnc: dbSettings.privateKeyEnc?.trim() ?? "",
keyPassphraseEnc: dbSettings.keyPassphraseEnc?.trim() ?? "",
hostKeySha256: dbSettings.hostKeySha256?.trim() ?? "",
};
}
return {
enabled: String(process.env.SSH_ENABLED ?? "false").toLowerCase() === "true",
host: process.env.SSH_HOST?.trim() ?? "",
username: process.env.SSH_USERNAME?.trim() ?? "",
port: Number(process.env.SSH_PORT ?? "22"),
passwordEnc: process.env.SSH_PASSWORD_ENC?.trim() ?? "",
privateKeyEnc: process.env.SSH_PRIVATE_KEY_ENC?.trim() ?? "",
keyPassphraseEnc: process.env.SSH_KEY_PASSPHRASE_ENC?.trim() ?? "",
hostKeySha256: process.env.SSH_HOST_KEY_SHA256?.trim() ?? "",
};
}
function getSshPassword(encryptedPassword) {
const fallbackPassword = process.env.SSH_PASSWORD?.trim();
if (encryptedPassword) {
return decryptSecret(encryptedPassword);
}
return fallbackPassword ?? "";
}
function getSshPrivateKey(encryptedPrivateKey) {
if (!encryptedPrivateKey) return "";
return decryptSecret(encryptedPrivateKey);
}
function getSshKeyPassphrase(encryptedPassphrase) {
if (!encryptedPassphrase) return "";
return decryptSecret(encryptedPassphrase);
}
async function isSshBackendEnabled() {
const settings = await loadSshRuntimeSettings();
return settings.enabled;
}
async function getSshRuntimeConfig() {
const settings = await loadSshRuntimeSettings();
const host = settings.host;
const username = settings.username;
const password = getSshPassword(settings.passwordEnc);
const privateKey = getSshPrivateKey(settings.privateKeyEnc);
const passphrase = getSshKeyPassphrase(settings.keyPassphraseEnc);
const port = Number(settings.port ?? 22);
const hostKeySha256 = normalizeSshHostFingerprint(settings.hostKeySha256);
if (!host || !username || (!password && !privateKey)) {
throw new Error("SSH backend is enabled but host/username and private key or password are required");
}
if (!Number.isFinite(port) || port < 1 || port > 65535) {
throw new Error("SSH port must be between 1 and 65535");
}
return {
host,
username,
password: privateKey ? undefined : password,
privateKey: privateKey || undefined,
passphrase: privateKey ? passphrase || undefined : undefined,
port,
hostKeySha256: hostKeySha256 || undefined,
};
}
function decryptSecret(ciphertext) {
const keyHex = (process.env.ENCRYPTION_KEY ?? "").trim();
if (!/^[0-9a-fA-F]{64}$/.test(keyHex)) {
throw new Error("ENCRYPTION_KEY must be exactly 64 hex characters");
}
const parts = ciphertext.split(":");
const [ivHex, dataHex, tagHex] = parts;
if (!ivHex || !dataHex || !/^[0-9a-fA-F]+$/.test(ivHex) || !/^[0-9a-fA-F]+$/.test(dataHex)) {
throw new Error("Invalid SSH_PASSWORD_ENC format");
}
if (parts.length === 2) {
const legacyDecipher = createDecipheriv(
"aes-256-ctr",
Buffer.from(keyHex, "hex"),
Buffer.from(ivHex, "hex")
);
const legacyDecrypted = Buffer.concat([
legacyDecipher.update(Buffer.from(dataHex, "hex")),
legacyDecipher.final(),
]);
return legacyDecrypted.toString("utf-8");
}
if (!tagHex || !/^[0-9a-fA-F]+$/.test(tagHex)) {
throw new Error("Invalid SSH_PASSWORD_ENC authentication tag format");
}
const decipher = createDecipheriv(
"aes-256-gcm",
Buffer.from(keyHex, "hex"),
Buffer.from(ivHex, "hex")
);
decipher.setAuthTag(Buffer.from(tagHex, "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() {
const internalRpcSecret = getInternalRpcSecret();
if (!internalRpcSecret) {
return;
}
try {
await fetch(`http://127.0.0.1:${port}/api/internal/auto-update`, {
method: "POST",
headers: {
"x-internal-rpc-secret": internalRpcSecret,
},
});
} catch (error) {
console.error("[auto-update-runner]", error);
}
}
const autoUpdateTimer = setInterval(() => {
void triggerAutoUpdateCycle();
}, autoUpdateIntervalMs);
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", async (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;
}
userSessionCount.set(userId, current + 1);
const cwd = process.env.HOST_FS_MOUNT ?? "/host_system";
const useSshHostShell = mode === "host" && await isSshBackendEnabled();
let ptyProcess = null;
let sshConn = null;
let sshStream = null;
if (useSshHostShell) {
try {
const sshCfg = await getSshRuntimeConfig();
sshConn = new SSHClient();
sshConn.on("keyboard-interactive", (_name, _instructions, _lang, _prompts, finish) => {
finish([sshCfg.password ?? ""]);
});
sshConn.on("ready", () => {
if (readOnly) {
sshConn.exec(
"sh -lc 'tail -n 200 -f /var/log/syslog 2>/dev/null || tail -n 200 -f /var/log/messages 2>/dev/null || dmesg -w'",
(err, stream) => {
if (err) {
socket.emit("output", `\r\n\x1b[31mSSH log stream 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 log stream closed]\x1b[0m\r\n");
socket.disconnect();
});
}
);
return;
}
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,
tryKeyboard: !sshCfg.privateKey,
readyTimeout: 15000,
...(sshCfg.hostKeySha256
? {
hostHash: "sha256",
hostVerifier: (hashedKey) => isSameFingerprint(hashedKey, sshCfg.hostKeySha256),
}
: {}),
});
} 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 =
readOnly
? pty.spawn(
"docker",
[
"logs",
"-f",
"--tail",
"200",
mode === "container"
? containerId
: (process.env.SELF_CONTAINER_NAME?.trim() || process.env.HOSTNAME?.trim() || "servercommander"),
],
{
name: "xterm-256color",
cols: 80,
rows: 24,
cwd,
env: {
...process.env,
TERM: "xterm-256color",
COLORTERM: "truecolor",
},
}
)
: mode === "container"
? pty.spawn(
"docker",
["exec", "-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 () => {
clearInterval(autoUpdateTimer);
await prisma.$disconnect().catch(() => null);
process.exit(0);
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
});