Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2190 lines (1961 loc) · 76.2 KB
/
Copy pathserver.js
File metadata and controls
2190 lines (1961 loc) · 76.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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createServer } from 'http';
import { parse } from 'url';
import next from 'next';
import { WebSocketServer } from 'ws';
import { spawn } from 'child_process';
import { existsSync } from 'fs';
import { join, resolve } from 'path';
import stripAnsi from 'strip-ansi';
import { spawn as ptySpawn } from 'node-pty';
import { getSSHExecutionService } from './src/server/ssh-execution-service.js';
import { NEWT_COLORS_EXPORT } from './src/server/newt-colors.js';
import { getDatabase } from './src/server/database-prisma.js';
import { getAuthConfig, verifyToken, decodeToken } from './src/lib/auth.js';
import dotenv from 'dotenv';
// Dynamic import for auto sync init to avoid tsx caching issues
/** @type {any} */
let autoSyncModule = null;
// Load environment variables from .env file
dotenv.config();
// Fallback minimal global error handlers for Node runtime (avoid TS import)
function registerGlobalErrorHandlers() {
if (registerGlobalErrorHandlers._registered) return;
registerGlobalErrorHandlers._registered = true;
process.on('uncaughtException', (err) => {
console.error('uncaught_exception', err);
});
process.on('unhandledRejection', (reason) => {
console.error('unhandled_rejection', reason);
});
}
registerGlobalErrorHandlers._registered = false;
// JWT `exp` claim is a UNIX timestamp in seconds; Date.now() is milliseconds.
const JWT_EXP_MS_FACTOR = 1000;
// Maximum number of characters retained in the output buffer per execution.
const OUTPUT_BUFFER_MAX_LENGTH = 1000;
// Delay (ms) between backup completion and update start.
const BACKUP_UPDATE_DELAY_MS = 1000;
// Proxmox VMIDs are always purely numeric (typically 100-999999999).
const CONTAINER_ID_PATTERN = /^\d+$/;
// Proxmox storage identifiers only contain alphanumerics, underscore, hyphen, dot.
const STORAGE_ID_PATTERN = /^[a-zA-Z0-9_.-]+$/;
// Conservative hostname pattern (labels of alphanumerics/hyphens, dot-separated).
const HOSTNAME_PATTERN =
/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
const MAX_CLONE_COUNT = 50;
/**
* Validate the subset of a WebSocket "start" message that ends up interpolated
* directly into shell commands executed on the Proxmox host (pct/qm/vzdump).
* These values normally come from trusted UI dropdowns/DB records, but the
* WebSocket endpoint itself has no other request-shape enforcement, so a
* malformed or malicious client could otherwise inject arbitrary shell syntax.
* @param {WebSocketMessage} message
* @returns {string | null} an error message if invalid, otherwise null
*/
function validateExecutionParams(message) {
const { containerId, storage, backupStorage, hostnames, containerType, cloneCount } = message;
if (containerId !== undefined && !CONTAINER_ID_PATTERN.test(String(containerId))) {
return `Invalid containerId: ${containerId}`;
}
if (storage !== undefined && !STORAGE_ID_PATTERN.test(String(storage))) {
return `Invalid storage identifier: ${storage}`;
}
if (backupStorage !== undefined && !STORAGE_ID_PATTERN.test(String(backupStorage))) {
return `Invalid backup storage identifier: ${backupStorage}`;
}
if (containerType !== undefined && containerType !== 'lxc' && containerType !== 'vm') {
return `Invalid containerType: ${containerType}`;
}
if (cloneCount !== undefined) {
const n = Number(cloneCount);
if (!Number.isInteger(n) || n < 1 || n > MAX_CLONE_COUNT) {
return `Invalid cloneCount: ${cloneCount}`;
}
}
if (hostnames !== undefined) {
if (!Array.isArray(hostnames) || !hostnames.every((h) => typeof h === 'string' && HOSTNAME_PATTERN.test(h))) {
return 'Invalid hostnames';
}
}
return null;
}
const dev = process.env.NODE_ENV !== 'production';
const hostname = '::';
const port = parseInt(process.env.PORT || '3000', 10);
const app = next({ dev, hostname, port });
// Register global handlers once at bootstrap
registerGlobalErrorHandlers();
const handle = app.getRequestHandler();
/**
* Extract a cookie value from request cookie header.
* @param {import('http').IncomingMessage} request
* @param {string} cookieName
* @returns {string | null}
*/
function getCookieValue(request, cookieName) {
const rawCookieHeader = request.headers.cookie;
if (!rawCookieHeader) return null;
const cookies = rawCookieHeader.split(';');
for (const cookie of cookies) {
const [name, ...rest] = cookie.trim().split('=');
if (name === cookieName) {
return decodeURIComponent(rest.join('='));
}
}
return null;
}
/**
* Validate auth for WebSocket upgrades when authentication is enabled.
* @param {import('http').IncomingMessage} request
* @returns {boolean}
*/
function isWebSocketUpgradeAuthorized(request) {
const authConfig = getAuthConfig();
// Preserve current behavior if auth is disabled / not set up.
if (!authConfig.enabled || !authConfig.setupCompleted) {
return true;
}
const token = getCookieValue(request, 'auth-token');
if (!token) {
console.warn('ws_auth_rejected: missing auth-token cookie');
return false;
}
const decoded = decodeToken(token);
if (decoded && typeof decoded.exp === 'number' && decoded.exp * JWT_EXP_MS_FACTOR < Date.now()) {
console.warn('ws_auth_rejected: token expired');
return false;
}
const verified = verifyToken(token);
if (!verified) {
console.warn('ws_auth_rejected: token verification failed');
return false;
}
return true;
}
// WebSocket handler for script execution
/**
* @typedef {import('ws').WebSocket & {connectionTime?: number, clientIP?: string}} ExtendedWebSocket
*/
/**
* @typedef {Object} Execution
* @property {any} process
* @property {ExtendedWebSocket} ws
*/
/**
* @typedef {Object} ServerInfo
* @property {string} name
* @property {string} ip
* @property {string} user
* @property {string} password
* @property {number} [id]
* @property {string} [auth_type]
* @property {string} [ssh_key_path]
*/
/**
* @typedef {Object} ExecutionResult
* @property {any} process
* @property {Function} kill
*/
/**
* @typedef {Object} WebSocketMessage
* @property {string} action
* @property {string} [scriptPath]
* @property {string} [executionId]
* @property {string} [input]
* @property {string} [mode]
* @property {ServerInfo} [server]
* @property {boolean} [isUpdate]
* @property {boolean} [isShell]
* @property {boolean} [isBackup]
* @property {boolean} [isClone]
* @property {boolean} [executeInContainer]
* @property {string} [containerId]
* @property {string} [storage]
* @property {string} [backupStorage]
* @property {number} [cloneCount]
* @property {string[]} [hostnames]
* @property {'lxc'|'vm'} [containerType]
* @property {Record<string, string|number|boolean>} [envVars]
* @property {number} [cols]
* @property {number} [rows]
* @property {number} [installedScriptId]
*/
class ScriptExecutionHandler {
/**
* @param {import('http').Server} server
*/
constructor(server) {
// Create WebSocketServer without attaching to server
// We'll handle upgrades manually to avoid interfering with Next.js HMR
this.wss = new WebSocketServer({
noServer: true
});
this.activeExecutions = new Map();
this.db = getDatabase();
this.setupWebSocket();
}
/**
* Handle WebSocket upgrade for our endpoint
* @param {import('http').IncomingMessage} request
* @param {import('stream').Duplex} socket
* @param {Buffer} head
*/
handleUpgrade(request, socket, head) {
this.wss.handleUpgrade(request, socket, head, (ws) => {
this.wss.emit('connection', ws, request);
});
}
/**
* Parse Container ID from terminal output
* @param {string} output - Terminal output to parse
* @returns {string|null} - Container ID if found, null otherwise
*/
parseContainerId(output) {
// First, strip ANSI color codes to make pattern matching more reliable
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
// Look for various patterns that Proxmox scripts might use
const patterns = [
// Primary pattern - the exact format from the output
/🆔\s+Container\s+ID:\s+(\d+)/i,
// Standard patterns with flexible spacing
/🆔\s*Container\s*ID:\s*(\d+)/i,
/Container\s*ID:\s*(\d+)/i,
/CT\s*ID:\s*(\d+)/i,
/Container\s*(\d+)/i,
// Alternative patterns
/CT\s*(\d+)/i,
/Container\s*created\s*with\s*ID\s*(\d+)/i,
/Created\s*container\s*(\d+)/i,
/Container\s*(\d+)\s*created/i,
/ID:\s*(\d+)/i,
// Patterns with different spacing and punctuation
/Container\s*ID\s*:\s*(\d+)/i,
/CT\s*ID\s*:\s*(\d+)/i,
/Container\s*#\s*(\d+)/i,
/CT\s*#\s*(\d+)/i,
// Patterns that might appear in success messages
/Successfully\s*created\s*container\s*(\d+)/i,
/Container\s*(\d+)\s*is\s*ready/i,
/Container\s*(\d+)\s*started/i,
// Deliberately no generic bare-number fallback here: a stray 3-4 digit
// number in unrelated output (port, percentage, byte count) would be
// misdetected as the container ID and could overwrite a correct one.
];
// Try patterns on both original and cleaned output
const outputsToTry = [output, cleanOutput];
for (const testOutput of outputsToTry) {
for (const pattern of patterns) {
const match = testOutput.match(pattern);
if (match && match[1]) {
const containerId = match[1];
// Additional validation: container IDs are typically 3-4 digits
if (containerId.length >= 3 && containerId.length <= 4) {
return containerId;
}
}
}
}
return null;
}
/**
* Parse Web UI URL from terminal output
* @param {string} output - Terminal output to parse
* @returns {{ip: string, port: number}|null} - Object with ip and port if found, null otherwise
*/
parseWebUIUrl(output) {
// First, strip ANSI color codes to make pattern matching more reliable
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
// Look for URL patterns with any valid IP address (private or public)
const patterns = [
// HTTP/HTTPS URLs with IP and port
/https?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)/gi,
// URLs without explicit port (assume default ports)
/https?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\/|$|\s)/gi,
// URLs with trailing slash and port
/https?:\/\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)\//gi,
// URLs with just IP and port (no protocol)
/(?:^|\s)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)(?:\s|$)/gi,
// Deliberately no bare-IP-only fallback (no protocol, no port): a
// netmask, DNS resolver IP, or unrelated dotted-quad printed by the
// script would be misdetected as the web UI address.
];
// Try patterns on both original and cleaned output
const outputsToTry = [output, cleanOutput];
for (const testOutput of outputsToTry) {
for (const pattern of patterns) {
const matches = [...testOutput.matchAll(pattern)];
for (const match of matches) {
if (match[1]) {
const ip = match[1];
const port = match[2] || (match[0].startsWith('https') ? '443' : '80');
// Validate IP address format
if (ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)) {
return {
ip: ip,
port: parseInt(port, 10)
};
}
}
}
}
}
return null;
}
/**
* Create installation record
* @param {string} scriptName - Name of the script
* @param {string} scriptPath - Path to the script
* @param {string} executionMode - 'local' or 'ssh'
* @param {number|null} serverId - Server ID for SSH executions
* @param {string|number|null} [containerId] - Container ID, when already known at start time
* @returns {Promise<number|null>} - Installation record ID
*/
async createInstallationRecord(scriptName, scriptPath, executionMode, serverId = null, containerId = null) {
try {
const result = await this.db.createInstalledScript({
script_name: scriptName,
script_path: scriptPath,
container_id: containerId != null ? String(containerId) : undefined,
server_id: serverId ?? undefined,
execution_mode: executionMode,
status: 'in_progress',
output_log: ''
});
return Number(result.id);
} catch (error) {
console.error('Error creating installation record:', error);
return null;
}
}
/**
* Update installation record
* @param {number} installationId - Installation record ID
* @param {Object} updateData - Data to update
*/
async updateInstallationRecord(installationId, updateData) {
try {
await this.db.updateInstalledScript(installationId, updateData);
} catch (error) {
console.error('Error updating installation record:', error);
}
}
setupWebSocket() {
this.wss.on('connection', (ws, request) => {
// Set connection metadata
/** @type {ExtendedWebSocket} */ (ws).connectionTime = Date.now();
/** @type {ExtendedWebSocket} */ (ws).clientIP = request.socket.remoteAddress || 'unknown';
ws.on('message', (data) => {
try {
const rawMessage = data.toString();
const message = JSON.parse(rawMessage);
this.handleMessage(/** @type {ExtendedWebSocket} */(ws), message);
} catch (error) {
console.error('Error parsing WebSocket message:', error);
this.sendMessage(ws, {
type: 'error',
data: 'Invalid message format',
timestamp: Date.now()
});
}
});
ws.on('close', (code, reason) => {
this.cleanupActiveExecutions(/** @type {ExtendedWebSocket} */(ws));
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
this.cleanupActiveExecutions(/** @type {ExtendedWebSocket} */(ws));
});
});
}
/**
* Resolve full server from DB when client sends a redacted server payload.
* Since v1.1.2 server API responses redact secrets, SSH execution must always
* rehydrate credentials (password/key/passphrase/path) by server id.
* @param {ServerInfo|null} server - Server from WebSocket message
* @returns {Promise<ServerInfo|null>} Same server or full server from DB
*/
async resolveServerForSSH(server) {
if (!server?.id) return server;
const serverId = Number(server.id);
if (!Number.isFinite(serverId) || serverId <= 0) {
return server;
}
const full = await this.db.getServerById(serverId);
if (!full) {
return server;
}
return /** @type {ServerInfo|null} */ ({ ...server, ...full });
}
/**
* @param {ExtendedWebSocket} ws
* @param {WebSocketMessage} message
*/
async handleMessage(ws, message) {
const { action, scriptPath, executionId, input, mode, server, isUpdate, isShell, isBackup, isClone, executeInContainer, containerId, storage, backupStorage, cloneCount, hostnames, containerType, envVars, cols, rows, installedScriptId } = message;
switch (action) {
case 'start': {
const validationError = validateExecutionParams(message);
if (validationError) {
this.sendMessage(ws, {
type: 'error',
data: validationError,
timestamp: Date.now()
});
break;
}
if (scriptPath && executionId) {
let serverToUse = server;
if (serverToUse?.id) {
serverToUse = await this.resolveServerForSSH(serverToUse) ?? serverToUse;
}
const resolved = serverToUse ?? server;
// Fall back to reasonably large defaults if the client didn't report
// its actual terminal size — better than the old hardcoded 80x24/120x30
// which made whiptail/ncurses dialogs draw off-center in real usage.
const effectiveCols = typeof cols === 'number' && cols > 0 ? cols : 220;
const effectiveRows = typeof rows === 'number' && rows > 0 ? rows : 50;
if (isClone && containerId && storage && server && cloneCount && hostnames && containerType) {
await this.startSSHCloneExecution(ws, containerId, executionId, storage, /** @type {ServerInfo} */(resolved), containerType, cloneCount, hostnames, effectiveCols, effectiveRows);
} else if (isBackup && containerId && storage) {
await this.startBackupExecution(ws, containerId, executionId, storage, mode, resolved, effectiveCols, effectiveRows);
} else if (isUpdate && containerId) {
await this.startUpdateExecution(ws, containerId, executionId, mode, resolved, backupStorage, envVars, installedScriptId, effectiveCols, effectiveRows);
} else if (isShell && containerId) {
await this.startShellExecution(ws, containerId, executionId, mode, resolved, containerType, effectiveCols, effectiveRows);
} else if (executeInContainer && containerId) {
await this.startInContainerScriptExecution(ws, scriptPath, executionId, mode, resolved, envVars, containerId, containerType ?? 'lxc', effectiveCols, effectiveRows);
} else {
await this.startScriptExecution(ws, scriptPath, executionId, mode, resolved, envVars, effectiveCols, effectiveRows);
}
} else {
this.sendMessage(ws, {
type: 'error',
data: 'Missing scriptPath or executionId',
timestamp: Date.now()
});
}
break;
}
case 'stop':
if (executionId) {
this.stopScriptExecution(executionId);
}
break;
case 'input':
if (executionId && input !== undefined) {
this.sendInputToProcess(executionId, input);
}
break;
case 'resize':
if (executionId && typeof cols === 'number' && typeof rows === 'number') {
this.resizeProcess(executionId, cols, rows);
}
break;
default:
this.sendMessage(ws, {
type: 'error',
data: 'Unknown action',
timestamp: Date.now()
});
}
}
/**
* @param {ExtendedWebSocket} ws
* @param {string} scriptPath
* @param {string} executionId
* @param {string} mode
* @param {ServerInfo|null} server
* @param {Object} [envVars] - Optional environment variables to pass to the script
*/
async startScriptExecution(ws, scriptPath, executionId, mode = 'local', server = null, envVars = {}, cols = 220, rows = 50) {
/** @type {number|null} */
let installationId = null;
try {
// Check if execution is already running
if (this.activeExecutions.has(executionId)) {
this.sendMessage(ws, {
type: 'error',
data: 'Script execution already running',
timestamp: Date.now()
});
return;
}
// Extract script name from path
const scriptName = scriptPath.split('/').pop() ?? scriptPath.split('\\').pop() ?? 'Unknown Script';
// Create installation record
const serverId = server ? (server.id ?? null) : null;
installationId = await this.createInstallationRecord(scriptName, scriptPath, mode, serverId);
if (!installationId) {
console.error('Failed to create installation record');
}
// Handle SSH execution
if (mode === 'ssh' && server) {
await this.startSSHScriptExecution(ws, scriptPath, executionId, server, installationId, envVars, cols, rows);
return;
}
if (mode === 'ssh' && !server) {
// SSH mode requested but no server provided, falling back to local execution
}
// Basic validation for local execution
const scriptsDir = join(process.cwd(), 'scripts');
const resolvedPath = resolve(scriptPath);
if (!resolvedPath.startsWith(resolve(scriptsDir))) {
this.sendMessage(ws, {
type: 'error',
data: 'Script path is not within the allowed scripts directory',
timestamp: Date.now()
});
// Update installation record with failure
if (installationId) {
await this.updateInstallationRecord(installationId, { status: 'failed' });
}
return;
}
// Format environment variables for local execution
// Convert envVars object to environment variables
const envWithVars = {
...process.env,
TERM: 'xterm-256color', // Enable proper terminal support
FORCE_ANSI: 'true', // Allow ANSI codes for proper display
COLUMNS: '80', // Set terminal width
LINES: '24' // Set terminal height
};
// Add envVars to environment
if (envVars && typeof envVars === 'object') {
for (const [key, value] of Object.entries(envVars)) {
/** @type {Record<string, string>} */
const envRecord = envWithVars;
envRecord[key] = String(value);
}
}
// Start script execution with pty for proper TTY support
const childProcess = ptySpawn('bash', [resolvedPath], {
cwd: scriptsDir,
name: 'xterm-256color',
cols,
rows,
env: envWithVars
});
// pty handles encoding automatically
// Store the execution with installation ID
this.activeExecutions.set(executionId, {
process: childProcess,
ws,
installationId,
outputBuffer: ''
});
// Send start message
this.sendMessage(ws, {
type: 'start',
data: `Starting execution of ${scriptPath}`,
timestamp: Date.now()
});
// Handle pty data (both stdout and stderr combined)
childProcess.onData(async (data) => {
const output = data.toString();
// Store output in buffer for logging
const execution = this.activeExecutions.get(executionId);
if (execution) {
execution.outputBuffer += output;
// Trim buffer to maximum allowed length to avoid memory issues
if (execution.outputBuffer.length > OUTPUT_BUFFER_MAX_LENGTH) {
execution.outputBuffer = execution.outputBuffer.slice(-OUTPUT_BUFFER_MAX_LENGTH);
}
}
// Parse for Container ID
const containerId = this.parseContainerId(output);
if (containerId && installationId) {
await this.updateInstallationRecord(installationId, { container_id: containerId });
}
// Parse for Web UI URL
const webUIUrl = this.parseWebUIUrl(output);
if (webUIUrl && installationId) {
const { ip, port } = webUIUrl;
if (ip && port) {
await this.updateInstallationRecord(installationId, {
web_ui_ip: ip,
web_ui_port: port
});
}
}
this.sendMessage(ws, {
type: 'output',
data: output,
timestamp: Date.now()
});
});
// Handle process exit
childProcess.onExit((e) => {
const execution = this.activeExecutions.get(executionId);
const isSuccess = e.exitCode === 0;
// Update installation record with final status and output
if (installationId && execution) {
this.updateInstallationRecord(installationId, {
status: isSuccess ? 'success' : 'failed',
output_log: execution.outputBuffer
});
}
this.sendMessage(ws, {
type: 'end',
data: `Script execution finished with code: ${e.exitCode}, signal: ${e.signal}`,
timestamp: Date.now()
});
// Clean up
this.activeExecutions.delete(executionId);
});
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start script: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});
// Update installation record with failure
if (installationId) {
await this.updateInstallationRecord(installationId, { status: 'failed' });
}
}
}
/**
* Execute a script INSIDE a container via `pct exec` (LXC) or `qm guest exec` (VM).
* For SSH mode the scripts folder is already transferred to /tmp/scripts on the PVE host by
* startSSHScriptExecution; we re-use that mechanism and then run the script inside the CT.
* For local mode we pipe the script through `pct exec`.
*
* @param {ExtendedWebSocket} ws
* @param {string} scriptPath
* @param {string} executionId
* @param {string} mode
* @param {ServerInfo|null} server
* @param {Object} envVars
* @param {string} containerId
* @param {'lxc'|'vm'} containerType
*/
async startInContainerScriptExecution(ws, scriptPath, executionId, mode = 'local', server = null, envVars = {}, containerId, containerType = 'lxc', cols = 220, rows = 50) {
/** @type {number|null} */
let installationId = null;
try {
if (this.activeExecutions.has(executionId)) {
this.sendMessage(ws, { type: 'error', data: 'Script execution already running', timestamp: Date.now() });
return;
}
// Guard against path traversal — every script must resolve inside the
// scripts directory, regardless of execution mode (local or SSH).
const guardScriptsDir = join(process.cwd(), 'scripts');
const resolvedScriptPath = resolve(scriptPath);
if (!resolvedScriptPath.startsWith(resolve(guardScriptsDir))) {
this.sendMessage(ws, { type: 'error', data: 'Script path outside scripts directory', timestamp: Date.now() });
return;
}
const scriptName = scriptPath.split('/').pop() ?? scriptPath.split('\\').pop() ?? 'Unknown Script';
const serverId = server ? (server.id ?? null) : null;
installationId = await this.createInstallationRecord(scriptName, scriptPath, mode, serverId, containerId ?? null);
// Build env-var export prefix
const envExports = Object.entries(envVars ?? {})
.filter(([k]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(k))
.map(([k, v]) => `export ${k}=${JSON.stringify(String(v))}`)
.join('; ');
const envPrefix = `${NEWT_COLORS_EXPORT}; ${envExports ? `${envExports}; ` : ''}`;
if (mode === 'ssh' && server) {
// Transfer scripts folder to PVE host, then exec inside container
const sshService = getSSHExecutionService();
this.sendMessage(ws, { type: 'start', data: `Connecting to ${server.ip}…`, timestamp: Date.now() });
const relScript = scriptPath.replace(/^scripts[/\\]/, '');
const remoteScript = `/tmp/scripts/${relScript}`;
// Transfer scripts folder silently — suppress verbose rsync file listing
this.sendMessage(ws, { type: 'output', data: 'Syncing scripts…\r\n', timestamp: Date.now() });
await sshService.transferScriptsFolder(server,
() => { }, // suppress rsync stdout (verbose file listing)
(/** @type {string} */ err) => {
// Ignore harmless SSH host-key / known-hosts notices from rsync stderr
if (!err.includes('Warning:') && !err.includes('Permanently added')) {
this.sendMessage(ws, { type: 'error', data: err, timestamp: Date.now() });
}
}
);
let inContainerCmd;
if (containerType === 'lxc') {
// For LXC we must copy the script from host (/tmp/scripts/...) into the container first.
// Otherwise pct exec tries to run a host path that does not exist inside the CT.
const remoteTarget = `/tmp/${scriptName}`;
const pushCmd = `pct push ${containerId} ${remoteScript} ${remoteTarget}`;
// Run pct push silently (no terminal output needed for this bookkeeping step)
await new Promise((resolve, reject) => {
sshService.executeCommand(server, pushCmd,
() => { }, // suppress push output
() => { }, // suppress push stderr
(/** @type {number} */ code) => {
if (code === 0) resolve(true);
else reject(new Error(`pct push failed with exit code ${code}`));
},
);
});
inContainerCmd = `pct exec ${containerId} -- bash -c "chmod +x ${remoteTarget}; ${envPrefix}bash ${remoteTarget}"`;
} else {
// VM execution currently relies on guest exec and assumes script path exists in guest context.
inContainerCmd = `qm guest exec ${containerId} -- bash -c "${envPrefix}bash ${remoteScript}"`;
}
this.activeExecutions.set(executionId, { process: null, ws, installationId, outputBuffer: '' });
// executeCommand resolves immediately with the PTY process — store it so
// interactive input (y/n prompts etc.) can be forwarded via sendInputToProcess.
const execResult = await sshService.executeCommand(server, inContainerCmd,
(/** @type {string} */ data) => {
const execution = this.activeExecutions.get(executionId);
if (execution) execution.outputBuffer += data;
this.sendMessage(ws, { type: 'output', data, timestamp: Date.now() });
},
(/** @type {string} */ err) => {
this.sendMessage(ws, { type: 'error', data: err, timestamp: Date.now() });
},
async (/** @type {number} */ exitCode) => {
const execution = this.activeExecutions.get(executionId);
if (installationId && execution) {
await this.updateInstallationRecord(installationId, {
status: exitCode === 0 ? 'success' : 'failed',
output_log: execution.outputBuffer
});
}
this.sendMessage(ws, { type: 'end', data: `Finished with code: ${exitCode}`, timestamp: Date.now() });
this.activeExecutions.delete(executionId);
},
cols,
rows
);
// Attach the real PTY process so keyboard input can reach interactive prompts
const storedExec = this.activeExecutions.get(executionId);
if (storedExec && execResult && /** @type {any} */(execResult).process) {
storedExec.process = /** @type {any} */(execResult).process;
}
return;
}
// Local mode: pipe the script content into `pct exec <ctid> -- bash`
const scriptsDir = join(process.cwd(), 'scripts');
const resolvedPath = resolve(scriptPath);
if (!resolvedPath.startsWith(resolve(scriptsDir))) {
this.sendMessage(ws, { type: 'error', data: 'Script path outside scripts directory', timestamp: Date.now() });
if (installationId) await this.updateInstallationRecord(installationId, { status: 'failed' });
return;
}
const bashCmd = `${envPrefix}bash ${resolvedPath}`;
const args = containerType === 'lxc'
? ['exec', containerId, '--', 'bash', '-c', bashCmd]
: ['guest', 'exec', containerId, '--', 'bash', '-c', bashCmd];
const cmd = containerType === 'lxc' ? 'pct' : 'qm';
const childProcess = ptySpawn(cmd, args, {
cwd: scriptsDir,
name: 'xterm-256color',
cols,
rows,
env: { ...process.env, TERM: 'xterm-256color' }
});
this.activeExecutions.set(executionId, { process: childProcess, ws, installationId, outputBuffer: '' });
this.sendMessage(ws, { type: 'start', data: `Executing inside container ${containerId}…`, timestamp: Date.now() });
childProcess.onData((data) => {
const execution = this.activeExecutions.get(executionId);
if (execution) execution.outputBuffer += data;
this.sendMessage(ws, { type: 'output', data, timestamp: Date.now() });
});
childProcess.onExit(async (e) => {
const execution = this.activeExecutions.get(executionId);
if (installationId && execution) {
await this.updateInstallationRecord(installationId, {
status: e.exitCode === 0 ? 'success' : 'failed',
output_log: execution.outputBuffer
});
}
this.sendMessage(ws, { type: 'end', data: `Script finished with code: ${e.exitCode}`, timestamp: Date.now() });
this.activeExecutions.delete(executionId);
});
} catch (error) {
this.sendMessage(ws, { type: 'error', data: `Failed to start in-container script: ${error instanceof Error ? error.message : String(error)}`, timestamp: Date.now() });
if (installationId) await this.updateInstallationRecord(installationId, { status: 'failed' });
}
}
/**
* Start SSH script execution
* @param {ExtendedWebSocket} ws
* @param {string} scriptPath
* @param {string} executionId
* @param {ServerInfo} server
* @param {number|null} installationId
* @param {Object} [envVars] - Optional environment variables to pass to the script
*/
async startSSHScriptExecution(ws, scriptPath, executionId, server, installationId = null, envVars = {}, cols = 220, rows = 50) {
const sshService = getSSHExecutionService();
// Send start message
this.sendMessage(ws, {
type: 'start',
data: `Starting SSH execution of ${scriptPath} on ${server.name} (${server.ip})`,
timestamp: Date.now()
});
try {
const execution = /** @type {ExecutionResult} */ (await sshService.executeScript(
server,
scriptPath,
/** @param {string} data */ async (data) => {
// Store output in buffer for logging
const exec = this.activeExecutions.get(executionId);
if (exec) {
exec.outputBuffer += data;
// Trim buffer to maximum allowed length to avoid memory issues
if (exec.outputBuffer.length > OUTPUT_BUFFER_MAX_LENGTH) {
exec.outputBuffer = exec.outputBuffer.slice(-OUTPUT_BUFFER_MAX_LENGTH);
}
}
// Parse for Container ID
const containerId = this.parseContainerId(data);
if (containerId && installationId) {
await this.updateInstallationRecord(installationId, { container_id: containerId });
}
// Parse for Web UI URL
const webUIUrl = this.parseWebUIUrl(data);
if (webUIUrl && installationId) {
const { ip, port } = webUIUrl;
if (ip && port) {
await this.updateInstallationRecord(installationId, {
web_ui_ip: ip,
web_ui_port: port
});
}
}
// Handle data output
this.sendMessage(ws, {
type: 'output',
data: data,
timestamp: Date.now()
});
},
/** @param {string} error */(error) => {
// Store error in buffer for logging
const exec = this.activeExecutions.get(executionId);
if (exec) {
exec.outputBuffer += error;
// Trim buffer to maximum allowed length to avoid memory issues
if (exec.outputBuffer.length > OUTPUT_BUFFER_MAX_LENGTH) {
exec.outputBuffer = exec.outputBuffer.slice(-OUTPUT_BUFFER_MAX_LENGTH);
}
}
// Handle errors
this.sendMessage(ws, {
type: 'error',
data: error,
timestamp: Date.now()
});
},
/** @param {number} code */ async (code) => {
const exec = this.activeExecutions.get(executionId);
const isSuccess = code === 0;
// Update installation record with final status and output
if (installationId && exec) {
await this.updateInstallationRecord(installationId, {
status: isSuccess ? 'success' : 'failed',
output_log: exec.outputBuffer
});
}
// Handle process exit
this.sendMessage(ws, {
type: 'end',
data: `SSH script execution finished with code: ${code}`,
timestamp: Date.now()
});
// Clean up
this.activeExecutions.delete(executionId);
},
envVars,
cols,
rows
));
// Store the execution with installation ID
this.activeExecutions.set(executionId, {
process: execution.process,
ws,
installationId,
outputBuffer: ''
});
} catch (error) {
this.sendMessage(ws, {
type: 'error',
data: `Failed to start SSH execution: ${error instanceof Error ? error.message : String(error)}`,
timestamp: Date.now()
});