@lethevimlet/sshift 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1146 -0
  3. package/example.config.json +162 -0
  4. package/package.json +74 -0
  5. package/src/server/endpoints/index.js +12 -0
  6. package/src/server/endpoints/rest/bookmarks.js +106 -0
  7. package/src/server/endpoints/rest/config.js +65 -0
  8. package/src/server/endpoints/rest/folders.js +127 -0
  9. package/src/server/endpoints/rest/index.js +32 -0
  10. package/src/server/endpoints/rest/sessions.js +113 -0
  11. package/src/server/endpoints/rest/system.js +211 -0
  12. package/src/server/endpoints/ws/index.js +46 -0
  13. package/src/server/endpoints/ws/layout.js +43 -0
  14. package/src/server/endpoints/ws/sftp.js +156 -0
  15. package/src/server/endpoints/ws/ssh.js +180 -0
  16. package/src/server/endpoints/ws/tabs.js +211 -0
  17. package/src/server/index.js +127 -0
  18. package/src/server/services/index.js +12 -0
  19. package/src/server/services/sftp-manager.js +266 -0
  20. package/src/server/services/ssh-manager.js +527 -0
  21. package/src/server/utils/config.js +171 -0
  22. package/src/server/utils/env-loader.js +29 -0
  23. package/src/server/utils/index.js +14 -0
  24. package/src/server/utils/tab-manager.js +266 -0
  25. package/src/webapp/css/style.css +3819 -0
  26. package/src/webapp/index.html +1008 -0
  27. package/src/webapp/js/app.js +8308 -0
  28. package/src/webapp/layouts.json +128 -0
  29. package/src/webapp/libs/font-awesome/css/all.min.css +9 -0
  30. package/src/webapp/libs/font-awesome/webfonts/fa-brands-400.ttf +0 -0
  31. package/src/webapp/libs/font-awesome/webfonts/fa-brands-400.woff2 +0 -0
  32. package/src/webapp/libs/font-awesome/webfonts/fa-regular-400.ttf +0 -0
  33. package/src/webapp/libs/font-awesome/webfonts/fa-regular-400.woff2 +0 -0
  34. package/src/webapp/libs/font-awesome/webfonts/fa-solid-900.ttf +0 -0
  35. package/src/webapp/libs/font-awesome/webfonts/fa-solid-900.woff2 +0 -0
  36. package/src/webapp/libs/lucide/lucide.min.js +12 -0
  37. package/src/webapp/libs/xterm/xterm-addon-fit.js +2 -0
  38. package/src/webapp/libs/xterm/xterm-addon-search.js +2 -0
  39. package/src/webapp/libs/xterm/xterm-addon-serialize.js +2 -0
  40. package/src/webapp/libs/xterm/xterm-addon-web-links.js +2 -0
  41. package/src/webapp/libs/xterm/xterm.css +209 -0
  42. package/src/webapp/libs/xterm/xterm.js +2 -0
  43. package/sshift +269 -0
@@ -0,0 +1,527 @@
1
+ const { Client } = require('ssh2');
2
+ const { Terminal } = require('@xterm/headless');
3
+ const { SerializeAddon } = require('@xterm/addon-serialize');
4
+
5
+ class SSHManager {
6
+ constructor() {
7
+ this.sessions = new Map();
8
+ // Data batching configuration
9
+ this.batchInterval = 16; // ~60fps - batch data for this many ms before sending
10
+ this.batchMaxSize = 64 * 1024; // 64KB max batch size - send immediately if exceeded
11
+ // Socket.io instance (set via setIO method)
12
+ this.io = null;
13
+ }
14
+
15
+ // Set the socket.io instance (called from server initialization)
16
+ setIO(io) {
17
+ this.io = io;
18
+ }
19
+
20
+ connect(socket, options) {
21
+ return new Promise((resolve, reject) => {
22
+ const conn = new Client();
23
+ const sessionId = options.sessionId || require('uuid').v4();
24
+
25
+ console.log(`[SSH] Attempting connection to ${options.username}@${options.host}:${options.port || 22}`);
26
+
27
+ const cols = options.cols || 80;
28
+ const rows = options.rows || 24;
29
+
30
+ // Create a headless terminal to maintain state
31
+ const terminal = new Terminal({
32
+ cols: cols,
33
+ rows: rows,
34
+ allowProposedApi: true
35
+ });
36
+
37
+ // Create serialize addon for terminal state
38
+ const serializeAddon = new SerializeAddon();
39
+ terminal.loadAddon(serializeAddon);
40
+
41
+ const session = {
42
+ id: sessionId,
43
+ conn: conn,
44
+ stream: null,
45
+ socket: socket,
46
+ sockets: new Set([socket.id]), // Track all connected sockets for this session
47
+ controllerSocket: socket.id, // The socket that has control (first client gets control)
48
+ cols: cols,
49
+ rows: rows,
50
+ terminal: terminal, // Headless terminal for state management
51
+ serializeAddon: serializeAddon, // Serialize addon for syncing state
52
+ // Connection info for sessions API
53
+ host: options.host,
54
+ port: options.port || 22,
55
+ username: options.username,
56
+ connectedAt: Date.now(),
57
+ // Data batching state
58
+ dataBuffer: '', // Buffer for outgoing data
59
+ batchTimer: null, // Timer for batched sends
60
+ lastDataTime: 0 // Timestamp of last data received
61
+ };
62
+
63
+ const config = {
64
+ host: options.host,
65
+ port: options.port || 22,
66
+ username: options.username,
67
+ readyTimeout: 30000,
68
+ // Keep SSH connection alive for sticky sessions
69
+ // These values can be configured via config.json
70
+ keepaliveInterval: options.sshKeepaliveInterval || 10000,
71
+ keepaliveCountMax: options.sshKeepaliveCountMax || 1000
72
+ };
73
+
74
+ // Authentication method
75
+ if (options.password && options.password.length > 0) {
76
+ config.password = options.password;
77
+ console.log('[SSH] Using password authentication');
78
+ } else if (options.privateKey && options.privateKey.length > 0) {
79
+ // Handle private key - can be string or buffer
80
+ try {
81
+ // If it's a base64 encoded key, decode it
82
+ if (options.privateKey.includes('BEGIN')) {
83
+ config.privateKey = options.privateKey;
84
+ } else {
85
+ // Try to decode base64
86
+ config.privateKey = Buffer.from(options.privateKey, 'base64').toString('utf8');
87
+ }
88
+ } catch (e) {
89
+ config.privateKey = options.privateKey;
90
+ }
91
+ if (options.passphrase && options.passphrase.length > 0) {
92
+ config.passphrase = options.passphrase;
93
+ }
94
+ console.log('[SSH] Using private key authentication');
95
+ } else {
96
+ // Try keyboard-interactive for servers that require it
97
+ config.tryKeyboard = true;
98
+ console.log('[SSH] No auth provided, trying keyboard-interactive');
99
+ }
100
+
101
+ // Handle keyboard-interactive authentication
102
+ conn.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => {
103
+ console.log('[SSH] Keyboard-interactive auth requested');
104
+ // For password-based keyboard-interactive, send the password
105
+ if (prompts.length > 0 && options.password) {
106
+ finish([options.password]);
107
+ } else {
108
+ finish([]);
109
+ }
110
+ });
111
+
112
+ conn.on('ready', () => {
113
+ console.log(`[SSH] Connection ready: ${sessionId}`);
114
+
115
+ // Start shell with proper PTY
116
+ conn.shell({
117
+ term: 'xterm-256color',
118
+ cols: session.cols,
119
+ rows: session.rows
120
+ }, (err, stream) => {
121
+ if (err) {
122
+ console.error(`[SSH] Shell error: ${err.message}`);
123
+ socket.emit('ssh-error', { sessionId, message: err.message });
124
+ conn.end();
125
+ reject(err);
126
+ return;
127
+ }
128
+
129
+ session.stream = stream;
130
+ this.sessions.set(sessionId, session);
131
+
132
+ // Join the session room to receive broadcasts
133
+ socket.join(`session-${sessionId}`);
134
+ console.log(`[SSH] Shell started: ${sessionId}`);
135
+
136
+ // Handle stream data with batching to reduce socket events
137
+ // This prevents performance issues when multiple clients are connected
138
+ stream.on('data', (data) => {
139
+ const dataStr = data.toString('utf8');
140
+
141
+ // Write to headless terminal to maintain state (immediate)
142
+ session.terminal.write(dataStr);
143
+
144
+ // Buffer data for batched broadcast
145
+ this.bufferData(sessionId, dataStr);
146
+ });
147
+
148
+ stream.stderr.on('data', (data) => {
149
+ const dataStr = data.toString('utf8');
150
+
151
+ // Write to headless terminal (immediate)
152
+ session.terminal.write(dataStr);
153
+
154
+ // Buffer data for batched broadcast
155
+ this.bufferData(sessionId, dataStr);
156
+ });
157
+
158
+ stream.on('close', () => {
159
+ console.log(`[SSH] Stream closed: ${sessionId}`);
160
+ // Flush any remaining buffered data before disconnect
161
+ this.flushData(sessionId);
162
+ this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
163
+ this.disconnect(sessionId);
164
+ });
165
+
166
+ stream.on('exit', (code, signal) => {
167
+ console.log(`[SSH] Stream exit: ${sessionId}, code: ${code}, signal: ${signal}`);
168
+ this.broadcastToSession(sessionId, 'ssh-exit', { sessionId, code, signal });
169
+ });
170
+
171
+ stream.on('error', (err) => {
172
+ console.error(`[SSH] Stream error: ${sessionId}`, err);
173
+ this.broadcastToSession(sessionId, 'ssh-error', { sessionId, message: err.message });
174
+ });
175
+
176
+ resolve(sessionId);
177
+ });
178
+ });
179
+
180
+ conn.on('error', (err) => {
181
+ console.error(`[SSH] Connection error: ${err.message}`);
182
+ socket.emit('ssh-error', { sessionId, message: err.message });
183
+ this.sessions.delete(sessionId);
184
+ reject(err);
185
+ });
186
+
187
+ conn.on('close', () => {
188
+ console.log(`[SSH] Connection closed: ${sessionId}`);
189
+ this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
190
+ this.sessions.delete(sessionId);
191
+ });
192
+
193
+ try {
194
+ conn.connect(config);
195
+ } catch (err) {
196
+ console.error(`[SSH] Connect exception: ${err.message}`);
197
+ reject(err);
198
+ }
199
+ });
200
+ }
201
+
202
+ // Broadcast data to all sockets connected to a session
203
+ broadcastToSession(sessionId, event, data) {
204
+ const session = this.sessions.get(sessionId);
205
+ if (!session) return;
206
+
207
+ // Use the socket.io instance set during initialization
208
+ if (!this.io) return;
209
+
210
+ // Emit to all sockets in the session room
211
+ this.io.to(`session-${sessionId}`).emit(event, data);
212
+ }
213
+
214
+ // Buffer data for batched broadcast to reduce socket events
215
+ // This improves performance when multiple clients are connected
216
+ bufferData(sessionId, dataStr) {
217
+ const session = this.sessions.get(sessionId);
218
+ if (!session) return;
219
+
220
+ // Add data to buffer
221
+ session.dataBuffer += dataStr;
222
+ session.lastDataTime = Date.now();
223
+
224
+ // If buffer exceeds max size, flush immediately
225
+ if (session.dataBuffer.length >= this.batchMaxSize) {
226
+ this.flushData(sessionId);
227
+ return;
228
+ }
229
+
230
+ // If no timer is running, start one
231
+ if (!session.batchTimer) {
232
+ session.batchTimer = setTimeout(() => {
233
+ this.flushData(sessionId);
234
+ }, this.batchInterval);
235
+ }
236
+ }
237
+
238
+ // Flush buffered data to all connected clients
239
+ flushData(sessionId) {
240
+ const session = this.sessions.get(sessionId);
241
+ if (!session) return;
242
+
243
+ // Clear any pending timer
244
+ if (session.batchTimer) {
245
+ clearTimeout(session.batchTimer);
246
+ session.batchTimer = null;
247
+ }
248
+
249
+ // If there's data to send, broadcast it
250
+ if (session.dataBuffer.length > 0) {
251
+ this.broadcastToSession(sessionId, 'ssh-data', {
252
+ sessionId,
253
+ data: session.dataBuffer
254
+ });
255
+ session.dataBuffer = '';
256
+ }
257
+ }
258
+
259
+ // Join a session (for receiving updates)
260
+ joinSession(socket, sessionId) {
261
+ const session = this.sessions.get(sessionId);
262
+ if (!session) {
263
+ console.log(`[SSH] Cannot join session ${sessionId}: session not found`);
264
+ return false;
265
+ }
266
+
267
+ // Check if we have a terminal state to send
268
+ let hasTerminalState = false;
269
+
270
+ // Send current terminal state to the joining socket BEFORE joining the room
271
+ // This ensures the client gets the full state before receiving any new data
272
+ // This provides the complete screen state for TUIs
273
+ if (session.terminal && session.serializeAddon) {
274
+ try {
275
+ // Serialize only the current viewport to avoid large payloads
276
+ // 'all' mode can cause stack overflow with large scrollback buffers
277
+ let serializedState = session.serializeAddon.serialize({
278
+ mode: 'normal' // Only current viewport, not full scrollback
279
+ });
280
+
281
+ // Ensure it's a string (not a complex object)
282
+ if (typeof serializedState !== 'string') {
283
+ serializedState = String(serializedState);
284
+ }
285
+
286
+ // Validate the serialized state is not too large
287
+ // Use a conservative limit to avoid Socket.IO stack overflow
288
+ const maxSize = 50 * 1024; // 50KB max (reduced to be safe)
289
+ if (serializedState.length > maxSize) {
290
+ console.warn(`[SSH] Terminal state too large (${serializedState.length} bytes), skipping sync`);
291
+ } else {
292
+ console.log(`[SSH] Sending serialized terminal state to socket ${socket.id}, size: ${serializedState.length}`);
293
+
294
+ // Use base64 encoding to avoid Socket.IO's binary detection
295
+ // which can cause stack overflow with large strings
296
+ const base64State = Buffer.from(serializedState, 'utf-8').toString('base64');
297
+
298
+ // Send the serialized state to the joining client
299
+ // Use a plain object with primitive values only
300
+ socket.emit('ssh-screen-sync', {
301
+ sessionId: sessionId,
302
+ state: base64State,
303
+ cols: session.cols,
304
+ rows: session.rows,
305
+ encoded: true // Flag to indicate base64 encoding
306
+ });
307
+
308
+ hasTerminalState = true;
309
+ }
310
+ } catch (err) {
311
+ console.error(`[SSH] Error serializing terminal state:`, err.message);
312
+ }
313
+ }
314
+
315
+ // Now join the session room to receive future updates
316
+ socket.join(`session-${sessionId}`);
317
+ session.sockets.add(socket.id);
318
+ console.log(`[SSH] Socket ${socket.id} joined session ${sessionId}`);
319
+
320
+ // Notify client that they've joined, including whether terminal state was sent
321
+ // and who is the current controller
322
+ socket.emit('ssh-joined', {
323
+ sessionId: sessionId,
324
+ noTerminalState: !hasTerminalState,
325
+ controllerSocket: session.controllerSocket, // Tell client who is in control
326
+ isController: session.controllerSocket === socket.id, // Tell client if they are in control
327
+ socketCount: session.sockets.size // Tell client how many sockets are connected
328
+ });
329
+
330
+ return true;
331
+ }
332
+
333
+ // Leave a session
334
+ leaveSession(socket, sessionId) {
335
+ const session = this.sessions.get(sessionId);
336
+ if (!session) return;
337
+
338
+ const wasController = session.controllerSocket === socket.id;
339
+ session.sockets.delete(socket.id);
340
+ socket.leave(`session-${sessionId}`);
341
+ console.log(`[SSH] Socket ${socket.id} left session ${sessionId}`);
342
+
343
+ // If the controller left, assign control to another socket
344
+ if (wasController) {
345
+ const remainingSockets = Array.from(session.sockets);
346
+ if (remainingSockets.length > 0) {
347
+ // Assign control to the first remaining socket
348
+ session.controllerSocket = remainingSockets[0];
349
+ console.log(`[SSH] Controller left, reassigning control to ${session.controllerSocket}`);
350
+
351
+ // Notify the new controller and remaining clients about the new controller
352
+ // Include terminal dimensions so the new controller can resize if needed
353
+ if (this.io) {
354
+ // Broadcast to all clients in the session about the new controller
355
+ this.io.to(`session-${sessionId}`).emit('ssh-control-taken', {
356
+ sessionId,
357
+ controllerSocket: session.controllerSocket,
358
+ cols: session.cols,
359
+ rows: session.rows
360
+ });
361
+ }
362
+ } else {
363
+ session.controllerSocket = null;
364
+ }
365
+ }
366
+ }
367
+
368
+ // Take control of a session
369
+ takeControl(socket, sessionId) {
370
+ const session = this.sessions.get(sessionId);
371
+ if (!session) {
372
+ console.log(`[SSH] Cannot take control: session ${sessionId} not found`);
373
+ return { success: false, error: 'Session not found' };
374
+ }
375
+
376
+ // Prevent rapid control transfers (cooldown of 1 second)
377
+ // This prevents "control wars" where multiple clients keep taking control
378
+ const now = Date.now();
379
+ if (session.lastControlTransfer && (now - session.lastControlTransfer) < 1000) {
380
+ console.log(`[SSH] Control transfer cooldown active for session ${sessionId}`);
381
+ return { success: false, error: 'Please wait before taking control again' };
382
+ }
383
+
384
+ const previousController = session.controllerSocket;
385
+ session.controllerSocket = socket.id;
386
+ session.lastControlTransfer = now;
387
+ console.log(`[SSH] Socket ${socket.id} took control of session ${sessionId} (was ${previousController})`);
388
+
389
+ // Notify other clients that control was taken
390
+ if (this.io) {
391
+ // Broadcast to all OTHER clients that control was taken
392
+ socket.to(`session-${sessionId}`).emit('ssh-control-taken', {
393
+ sessionId,
394
+ controllerSocket: socket.id
395
+ });
396
+ }
397
+
398
+ return {
399
+ success: true,
400
+ cols: session.cols,
401
+ rows: session.rows,
402
+ previousController: previousController
403
+ };
404
+ }
405
+
406
+ // Release control of a session (become observer)
407
+ releaseControl(socket, sessionId) {
408
+ const session = this.sessions.get(sessionId);
409
+ if (!session) {
410
+ return { success: false, error: 'Session not found' };
411
+ }
412
+
413
+ if (session.controllerSocket !== socket.id) {
414
+ return { success: false, error: 'Not the controller' };
415
+ }
416
+
417
+ // Find another socket to give control to
418
+ const remainingSockets = Array.from(session.sockets).filter(id => id !== socket.id);
419
+ if (remainingSockets.length > 0) {
420
+ session.controllerSocket = remainingSockets[0];
421
+ console.log(`[SSH] Socket ${socket.id} released control, new controller: ${session.controllerSocket}`);
422
+
423
+ if (this.io) {
424
+ this.io.to(`session-${sessionId}`).emit('ssh-control-released', {
425
+ sessionId,
426
+ controllerSocket: session.controllerSocket
427
+ });
428
+ }
429
+ } else {
430
+ session.controllerSocket = null;
431
+ }
432
+
433
+ return { success: true };
434
+ }
435
+
436
+ // Check if a socket is the controller
437
+ isController(socketId, sessionId) {
438
+ const session = this.sessions.get(sessionId);
439
+ return session && session.controllerSocket === socketId;
440
+ }
441
+
442
+ write(sessionId, data) {
443
+ const session = this.sessions.get(sessionId);
444
+ if (session && session.stream) {
445
+ session.stream.write(data);
446
+ }
447
+ }
448
+
449
+ resize(sessionId, cols, rows) {
450
+ const session = this.sessions.get(sessionId);
451
+ if (session && session.stream) {
452
+ session.stream.setWindow(rows, cols);
453
+ session.cols = cols;
454
+ session.rows = rows;
455
+
456
+ // Also resize the headless terminal
457
+ if (session.terminal) {
458
+ session.terminal.resize(cols, rows);
459
+ }
460
+ }
461
+ }
462
+
463
+ // Get current terminal state for a session
464
+ getTerminalState(sessionId) {
465
+ const session = this.sessions.get(sessionId);
466
+ if (!session || !session.terminal || !session.serializeAddon) {
467
+ return null;
468
+ }
469
+
470
+ try {
471
+ // Use 'normal' mode to avoid stack overflow with large scrollback buffers
472
+ const serializedState = session.serializeAddon.serialize({ mode: 'normal' });
473
+
474
+ // Validate size
475
+ const maxSize = 1024 * 1024; // 1MB max
476
+ if (serializedState.length > maxSize) {
477
+ console.warn(`[SSH] Terminal state too large (${serializedState.length} bytes), returning null`);
478
+ return null;
479
+ }
480
+
481
+ return {
482
+ state: serializedState,
483
+ cols: session.cols,
484
+ rows: session.rows
485
+ };
486
+ } catch (err) {
487
+ console.error(`[SSH] Error getting terminal state:`, err.message);
488
+ return null;
489
+ }
490
+ }
491
+
492
+ disconnect(sessionId) {
493
+ const session = this.sessions.get(sessionId);
494
+ if (session) {
495
+ // Clear any pending batch timer
496
+ if (session.batchTimer) {
497
+ clearTimeout(session.batchTimer);
498
+ session.batchTimer = null;
499
+ }
500
+ if (session.stream) {
501
+ session.stream.end();
502
+ }
503
+ if (session.conn) {
504
+ session.conn.end();
505
+ }
506
+ // Dispose of the headless terminal
507
+ if (session.terminal) {
508
+ session.terminal.dispose();
509
+ }
510
+ this.sessions.delete(sessionId);
511
+ }
512
+ }
513
+
514
+ disconnectAll(socketId) {
515
+ for (const [sessionId, session] of this.sessions) {
516
+ if (session.socket.id === socketId) {
517
+ this.disconnect(sessionId);
518
+ }
519
+ }
520
+ }
521
+
522
+ getActiveSessions() {
523
+ return this.sessions;
524
+ }
525
+ }
526
+
527
+ module.exports = new SSHManager();
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Configuration management utility
3
+ * Handles loading, saving, and accessing configuration
4
+ */
5
+
6
+ const path = require('path');
7
+ const fs = require('fs');
8
+
9
+ // Config paths - try .env/config.json first, then fall back to root config.json
10
+ const ENV_CONFIG_PATH = path.join(__dirname, '..', '..', '..', '.env', 'config.json');
11
+ const ROOT_CONFIG_PATH = path.join(__dirname, '..', '..', '..', 'config.json');
12
+
13
+ // Default config structure
14
+ const defaultConfig = {
15
+ port: 8022,
16
+ devPort: 3000,
17
+ bind: '0.0.0.0',
18
+ sticky: true,
19
+ sshKeepaliveInterval: 10000,
20
+ sshKeepaliveCountMax: 1000,
21
+ bookmarks: [],
22
+ folders: []
23
+ };
24
+
25
+ /**
26
+ * Get config path (prioritize .env/config.json)
27
+ * @returns {string} Path to config file
28
+ */
29
+ function getConfigPath() {
30
+ if (fs.existsSync(ENV_CONFIG_PATH)) {
31
+ console.log('[CONFIG] Using .env/config.json');
32
+ return ENV_CONFIG_PATH;
33
+ }
34
+ console.log('[CONFIG] Using root config.json');
35
+ return ROOT_CONFIG_PATH;
36
+ }
37
+
38
+ /**
39
+ * Load configuration from file
40
+ * @returns {Object} Configuration object
41
+ */
42
+ function loadConfig() {
43
+ try {
44
+ const configPath = getConfigPath();
45
+ if (fs.existsSync(configPath)) {
46
+ const data = fs.readFileSync(configPath, 'utf8');
47
+ return JSON.parse(data);
48
+ }
49
+ } catch (err) {
50
+ console.error('Error loading config:', err);
51
+ }
52
+ return { ...defaultConfig };
53
+ }
54
+
55
+ /**
56
+ * Save configuration to file
57
+ * @param {Object} config - Configuration object to save
58
+ * @returns {boolean} Success status
59
+ */
60
+ function saveConfig(config) {
61
+ try {
62
+ const configPath = getConfigPath();
63
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
64
+ return true;
65
+ } catch (err) {
66
+ console.error('Error saving config:', err);
67
+ return false;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Determine port with priority: PORT env var > config > defaults
73
+ * @returns {number} Port number
74
+ */
75
+ function getPort() {
76
+ // Priority 1: PORT environment variable (highest priority)
77
+ if (process.env.PORT) {
78
+ return parseInt(process.env.PORT, 10);
79
+ }
80
+
81
+ // Priority 2: Check if running in dev mode
82
+ const isDev = process.env.NODE_ENV === 'development' || process.argv.includes('dev');
83
+
84
+ // Priority 3: Load from config
85
+ const config = loadConfig();
86
+
87
+ if (isDev) {
88
+ return config.devPort || 3000;
89
+ }
90
+
91
+ return config.port || 8022;
92
+ }
93
+
94
+ /**
95
+ * Determine bind address with priority: BIND env var > config > defaults
96
+ * @returns {string} Bind address
97
+ */
98
+ function getBindAddress() {
99
+ // Priority 1: BIND environment variable (highest priority)
100
+ if (process.env.BIND) {
101
+ return process.env.BIND;
102
+ }
103
+
104
+ // Priority 2: Load from config
105
+ const config = loadConfig();
106
+
107
+ // Priority 3: Default
108
+ return config.bind || '0.0.0.0';
109
+ }
110
+
111
+ /**
112
+ * Get SSH keepalive settings from config
113
+ * @returns {Object} Keepalive settings
114
+ */
115
+ function getSSHKeepaliveSettings() {
116
+ const config = loadConfig();
117
+ return {
118
+ sshKeepaliveInterval: config.sshKeepaliveInterval || 10000,
119
+ sshKeepaliveCountMax: config.sshKeepaliveCountMax || 1000
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Get sticky sessions setting from config
125
+ * @returns {boolean} Sticky setting
126
+ */
127
+ function getStickySetting() {
128
+ const config = loadConfig();
129
+ return config.sticky !== false; // Default to true
130
+ }
131
+
132
+ /**
133
+ * Get take control default setting from config
134
+ * @returns {boolean} Take control default setting
135
+ */
136
+ function getTakeControlDefault() {
137
+ const config = loadConfig();
138
+ return config.takeControlDefault !== false; // Default to true
139
+ }
140
+
141
+ /**
142
+ * Get mobile keys bar setting from config
143
+ * @returns {boolean} Mobile keys bar setting
144
+ */
145
+ function getMobileKeysBarEnabled() {
146
+ const config = loadConfig();
147
+ return config.mobileKeysBarEnabled !== false; // Default to true
148
+ }
149
+
150
+ /**
151
+ * Get layouts from config
152
+ * @returns {Object|null} Layouts object or null
153
+ */
154
+ function getLayouts() {
155
+ const config = loadConfig();
156
+ return config.layouts || null;
157
+ }
158
+
159
+ module.exports = {
160
+ defaultConfig,
161
+ getConfigPath,
162
+ loadConfig,
163
+ saveConfig,
164
+ getPort,
165
+ getBindAddress,
166
+ getSSHKeepaliveSettings,
167
+ getStickySetting,
168
+ getTakeControlDefault,
169
+ getMobileKeysBarEnabled,
170
+ getLayouts
171
+ };