@lethevimlet/sshift 0.2.0 → 0.3.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.
@@ -2,6 +2,7 @@
2
2
  "port": 8022,
3
3
  "devPort": 3000,
4
4
  "bind": "0.0.0.0",
5
+ "enableHttps": true,
5
6
  "sticky": true,
6
7
  "sshKeepaliveInterval": 15000,
7
8
  "sshKeepaliveCountMax": 500,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -24,6 +24,8 @@
24
24
  "dotenv": "^17.4.0",
25
25
  "express": "^4.18.2",
26
26
  "lucide": "^1.7.0",
27
+ "pem": "^1.14.8",
28
+ "selfsigned": "^5.5.0",
27
29
  "socket.io": "^4.7.2",
28
30
  "ssh2": "^1.15.0",
29
31
  "uuid": "^9.0.0"
@@ -11,11 +11,14 @@ require('./utils/env-loader');
11
11
 
12
12
  const express = require('express');
13
13
  const http = require('http');
14
+ const https = require('https');
14
15
  const path = require('path');
15
16
  const socketIO = require('socket.io');
17
+ const selfsigned = require('selfsigned');
18
+ const pem = require('pem');
16
19
 
17
20
  // Import utilities
18
- const { loadConfig, getPort, getBindAddress } = require('./utils/config');
21
+ const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps } = require('./utils/config');
19
22
 
20
23
  // Import services
21
24
  const { sshManager, sftpManager } = require('./services');
@@ -23,104 +26,196 @@ const { sshManager, sftpManager } = require('./services');
23
26
  // Import endpoints
24
27
  const { rest, ws } = require('./endpoints');
25
28
 
26
- // Create Express app and HTTP server
29
+ /**
30
+ * Generate self-signed SSL certificates in memory using pem package
31
+ * @returns {Promise<Object>} Certificate and private key
32
+ */
33
+ function generateSelfSignedCert() {
34
+ return new Promise((resolve, reject) => {
35
+ console.log('[HTTPS] Generating self-signed certificate...');
36
+
37
+ const os = require('os');
38
+
39
+ // Get local IP addresses for SAN
40
+ const interfaces = os.networkInterfaces();
41
+ const localIPs = ['127.0.0.1'];
42
+
43
+ // Extract all IPv4 addresses from network interfaces
44
+ Object.values(interfaces).forEach(iface => {
45
+ iface.forEach(addr => {
46
+ if (addr.family === 'IPv4' && !addr.internal) {
47
+ localIPs.push(addr.address);
48
+ }
49
+ });
50
+ });
51
+
52
+ // Get hostname
53
+ const hostname = os.hostname();
54
+
55
+ console.log('[HTTPS] Certificate will be valid for:', localIPs.join(', '), 'and hostname:', hostname);
56
+
57
+ // Build alt names array
58
+ const altNames = ['localhost', hostname || 'localhost', ...localIPs];
59
+
60
+ pem.createCertificate({
61
+ days: 365,
62
+ selfSigned: true,
63
+ commonName: hostname || 'localhost',
64
+ altNames: altNames
65
+ }, (err, keys) => {
66
+ if (err) {
67
+ console.error('[HTTPS] Error generating certificate:', err);
68
+ reject(err);
69
+ return;
70
+ }
71
+
72
+ console.log('[HTTPS] Self-signed certificate generated successfully');
73
+ resolve({
74
+ cert: keys.certificate,
75
+ key: keys.serviceKey
76
+ });
77
+ });
78
+ });
79
+ }
80
+
81
+ // Create Express app
27
82
  const app = express();
28
- const server = http.createServer(app);
29
- const io = socketIO(server, {
30
- cors: {
31
- origin: "*",
32
- methods: ["GET", "POST"]
33
- },
34
- // Increase ping timeout for sticky sessions
35
- // This prevents disconnection during temporary network issues
36
- pingTimeout: 60000, // 60 seconds (default 20s)
37
- pingInterval: 25000 // 25 seconds (default)
38
- });
39
83
 
40
- // Set the socket.io instance for services that need it
41
- sshManager.setIO(io);
84
+ // Determine if HTTPS should be enabled
85
+ const enableHttps = getEnableHttps();
86
+ let server;
87
+ let io; // Declare io at module level for exports
88
+ let sslCredentials = null;
89
+
90
+ // Async initialization function
91
+ async function initializeServer() {
92
+ ensureConfig();
93
+
94
+ if (enableHttps) {
95
+ try {
96
+ sslCredentials = await generateSelfSignedCert();
97
+ server = https.createServer({
98
+ key: sslCredentials.key,
99
+ cert: sslCredentials.cert
100
+ }, app);
101
+ console.log('[HTTPS] HTTPS server created with self-signed certificate');
102
+ } catch (err) {
103
+ console.error('[HTTPS] Failed to create HTTPS server, falling back to HTTP:', err.message);
104
+ server = http.createServer(app);
105
+ }
106
+ } else {
107
+ server = http.createServer(app);
108
+ console.log('[HTTP] HTTP server created (HTTPS disabled)');
109
+ }
110
+
111
+ io = socketIO(server, {
112
+ cors: {
113
+ origin: "*",
114
+ methods: ["GET", "POST"]
115
+ },
116
+ // Increase ping timeout for sticky sessions
117
+ // This prevents disconnection during temporary network issues
118
+ pingTimeout: 60000, // 60 seconds (default 20s)
119
+ pingInterval: 25000 // 25 seconds (default)
120
+ });
42
121
 
43
- // Middleware
44
- app.use(express.json());
122
+ // Set the socket.io instance for services that need it
123
+ sshManager.setIO(io);
45
124
 
46
- // Serve static files from the webapp directory
47
- const webappPath = path.join(__dirname, '../webapp');
48
- app.use(express.static(webappPath));
49
- app.use('/js', express.static(path.join(webappPath, 'js')));
50
- app.use('/css', express.static(path.join(webappPath, 'css')));
51
- app.use('/libs', express.static(path.join(webappPath, 'libs')));
52
- app.use('/tests', express.static(path.join(webappPath, 'tests')));
125
+ // Middleware
126
+ app.use(express.json());
53
127
 
54
- // Main route
55
- app.get('/', (req, res) => {
56
- res.sendFile(path.join(webappPath, 'index.html'));
57
- });
128
+ // Serve static files from the webapp directory
129
+ const webappPath = path.join(__dirname, '../webapp');
130
+ app.use(express.static(webappPath));
131
+ app.use('/js', express.static(path.join(webappPath, 'js')));
132
+ app.use('/css', express.static(path.join(webappPath, 'css')));
133
+ app.use('/libs', express.static(path.join(webappPath, 'libs')));
134
+ app.use('/tests', express.static(path.join(webappPath, 'tests')));
58
135
 
59
- // Register REST endpoints
60
- rest.registerAllRestEndpoints(app, io);
61
-
62
- // Socket.IO connection handling
63
- io.on('connection', (socket) => {
64
- console.log('Client connected:', socket.id);
65
-
66
- // Send current open tabs to new client
67
- const { getOpenTabs, getTabOrder, getCurrentTheme, getCurrentAccent } = require('./utils/tab-manager');
68
- const { getCurrentLayout } = require('./endpoints/ws/layout');
69
-
70
- const openTabs = getOpenTabs();
71
- const tabOrder = getTabOrder();
72
- const currentLayout = getCurrentLayout();
73
- const currentTheme = getCurrentTheme();
74
- const currentAccent = getCurrentAccent();
75
-
76
- // Exclude activeSockets (Set object) to avoid Socket.IO serialization issues
77
- const orderedTabs = tabOrder
78
- .filter(sessionId => openTabs.has(sessionId))
79
- .map(sessionId => {
80
- const tab = openTabs.get(sessionId);
81
- return {
82
- sessionId,
83
- name: tab.name,
84
- type: tab.type,
85
- connectionData: {
86
- host: tab.connectionData?.host,
87
- port: tab.connectionData?.port,
88
- username: tab.connectionData?.username,
89
- name: tab.connectionData?.name
90
- // Exclude password, privateKey, and other sensitive data
91
- },
92
- sticky: tab.sticky,
93
- panelId: tab.panelId || 'panel-0' // Include panel assignment
94
- // Exclude activeSockets (Set) to avoid serialization issues
95
- };
96
- });
97
-
98
- socket.emit('open-tabs', {
99
- tabs: orderedTabs,
100
- layout: currentLayout,
101
- theme: currentTheme,
102
- accent: currentAccent
136
+ // Main route
137
+ app.get('/', (req, res) => {
138
+ res.sendFile(path.join(webappPath, 'index.html'));
103
139
  });
104
140
 
105
- // Register all WebSocket handlers
106
- ws.registerAllWSHandlers(socket, io);
141
+ // Register REST endpoints
142
+ rest.registerAllRestEndpoints(app, io);
143
+
144
+ // Socket.IO connection handling
145
+ io.on('connection', (socket) => {
146
+ console.log('Client connected:', socket.id);
147
+
148
+ // Send current open tabs to new client
149
+ const { getOpenTabs, getTabOrder, getCurrentTheme, getCurrentAccent } = require('./utils/tab-manager');
150
+ const { getCurrentLayout } = require('./endpoints/ws/layout');
151
+
152
+ const openTabs = getOpenTabs();
153
+ const tabOrder = getTabOrder();
154
+ const currentLayout = getCurrentLayout();
155
+ const currentTheme = getCurrentTheme();
156
+ const currentAccent = getCurrentAccent();
157
+
158
+ // Exclude activeSockets (Set object) to avoid Socket.IO serialization issues
159
+ const orderedTabs = tabOrder
160
+ .filter(sessionId => openTabs.has(sessionId))
161
+ .map(sessionId => {
162
+ const tab = openTabs.get(sessionId);
163
+ return {
164
+ sessionId,
165
+ name: tab.name,
166
+ type: tab.type,
167
+ connectionData: {
168
+ host: tab.connectionData?.host,
169
+ port: tab.connectionData?.port,
170
+ username: tab.connectionData?.username,
171
+ name: tab.connectionData?.name
172
+ // Exclude password, privateKey, and other sensitive data
173
+ },
174
+ sticky: tab.sticky,
175
+ panelId: tab.panelId || 'panel-0' // Include panel assignment
176
+ // Exclude activeSockets (Set) to avoid serialization issues
177
+ };
178
+ });
179
+
180
+ socket.emit('open-tabs', {
181
+ tabs: orderedTabs,
182
+ layout: currentLayout,
183
+ theme: currentTheme,
184
+ accent: currentAccent
185
+ });
186
+
187
+ // Register all WebSocket handlers
188
+ ws.registerAllWSHandlers(socket, io);
107
189
 
108
- // Handle disconnect
109
- socket.on('disconnect', () => {
110
- ws.handleDisconnect(socket, io);
190
+ // Handle disconnect
191
+ socket.on('disconnect', () => {
192
+ ws.handleDisconnect(socket, io);
193
+ });
111
194
  });
112
- });
113
195
 
114
- // Start server
115
- const PORT = getPort();
116
- const BIND = getBindAddress();
196
+ // Start server
197
+ const PORT = getPort();
198
+ const BIND = getBindAddress();
199
+
200
+ server.listen(PORT, BIND, () => {
201
+ const address = BIND === '0.0.0.0' || BIND === '::' ? 'localhost' : BIND;
202
+ const protocol = enableHttps ? 'https' : 'http';
203
+ console.log(`Web SSH/SFTP Client running at ${protocol}://${address}:${PORT}`);
204
+ // OSC 8 hyperlink: ESC ] 8 ; ; URL BEL text ESC ] 8 ; ; BEL
205
+ const ESC = '\x1b';
206
+ console.log(`${ESC}]8;;${protocol}://${address}:${PORT}${ESC}\\Open in browser${ESC}]8;;${ESC}\\`);
207
+
208
+ if (enableHttps) {
209
+ console.log('[HTTPS] Note: Using self-signed certificate. Your browser may show a security warning.');
210
+ console.log('[HTTPS] For mobile devices, you may need to accept the certificate warning to use native text selection.');
211
+ }
212
+ });
213
+ }
117
214
 
118
- server.listen(PORT, BIND, () => {
119
- const address = BIND === '0.0.0.0' || BIND === '::' ? 'localhost' : BIND;
120
- console.log(`Web SSH/SFTP Client running at http://${address}:${PORT}`);
121
- // OSC 8 hyperlink: ESC ] 8 ; ; URL BEL text ESC ] 8 ; ; BEL
122
- const ESC = '\x1b';
123
- console.log(`${ESC}]8;;http://${address}:${PORT}${ESC}\\Open in browser${ESC}]8;;${ESC}\\`);
215
+ // Start the server
216
+ initializeServer().catch(err => {
217
+ console.error('Failed to initialize server:', err);
218
+ process.exit(1);
124
219
  });
125
220
 
126
221
  // Export for testing
@@ -5,34 +5,89 @@
5
5
 
6
6
  const path = require('path');
7
7
  const fs = require('fs');
8
+ const os = require('os');
8
9
 
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');
10
+ // Get user's home directory
11
+ const HOME_DIR = os.homedir();
12
+
13
+ // Default install directories for config (platform-specific)
14
+ const DEFAULT_INSTALL_DIRS = [
15
+ // Linux/macOS
16
+ path.join(HOME_DIR, '.local', 'share', 'sshift'),
17
+ // Windows
18
+ path.join(HOME_DIR, '.local', 'share', 'sshift'),
19
+ // Alternative locations
20
+ path.join(HOME_DIR, '.local', 'share', 'bin'),
21
+ ];
22
+
23
+ // Config paths - prioritize user install directory, then fall back to package directory
24
+ const PACKAGE_DIR = path.join(__dirname, '..', '..', '..');
25
+ const ENV_CONFIG_PATHS = [
26
+ ...DEFAULT_INSTALL_DIRS.map(dir => path.join(dir, '.env', 'config.json')),
27
+ ...DEFAULT_INSTALL_DIRS.map(dir => path.join(dir, 'config.json')),
28
+ path.join(PACKAGE_DIR, '.env', 'config.json'),
29
+ path.join(PACKAGE_DIR, 'config.json'),
30
+ ];
12
31
 
13
32
  // Default config structure
14
33
  const defaultConfig = {
15
34
  port: 8022,
16
35
  devPort: 3000,
17
36
  bind: '0.0.0.0',
37
+ enableHttps: true,
18
38
  sticky: true,
19
- sshKeepaliveInterval: 10000,
20
- sshKeepaliveCountMax: 1000,
39
+ sshKeepaliveInterval: 15000,
40
+ sshKeepaliveCountMax: 500,
21
41
  bookmarks: [],
22
42
  folders: []
23
43
  };
24
44
 
25
45
  /**
26
- * Get config path (prioritize .env/config.json)
46
+ * Ensure a config file exists. If no config is found in any search path,
47
+ * create config.json in the package root using env var overrides or defaults.
48
+ * This mirrors the installer create_config behavior.
49
+ */
50
+ function ensureConfig() {
51
+ for (const configPath of ENV_CONFIG_PATHS) {
52
+ if (fs.existsSync(configPath)) {
53
+ return;
54
+ }
55
+ }
56
+
57
+ const configPath = path.join(PACKAGE_DIR, 'config.json');
58
+ const config = { ...defaultConfig };
59
+
60
+ if (process.env.PORT) {
61
+ const port = parseInt(process.env.PORT, 10);
62
+ if (!isNaN(port)) {
63
+ config.port = port;
64
+ }
65
+ }
66
+
67
+ if (process.env.BIND) {
68
+ config.bind = process.env.BIND;
69
+ }
70
+
71
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
72
+ console.log('[CONFIG] Created default config at', configPath);
73
+ }
74
+
75
+ /**
76
+ * Get config path (prioritize user install directory)
27
77
  * @returns {string} Path to config file
28
78
  */
29
79
  function getConfigPath() {
30
- if (fs.existsSync(ENV_CONFIG_PATH)) {
31
- console.log('[CONFIG] Using .env/config.json');
32
- return ENV_CONFIG_PATH;
80
+ for (const configPath of ENV_CONFIG_PATHS) {
81
+ if (fs.existsSync(configPath)) {
82
+ console.log('[CONFIG] Using', configPath);
83
+ return configPath;
84
+ }
33
85
  }
34
- console.log('[CONFIG] Using root config.json');
35
- return ROOT_CONFIG_PATH;
86
+
87
+ // Return default path (first user install directory)
88
+ const defaultPath = ENV_CONFIG_PATHS[0];
89
+ console.log('[CONFIG] Using default path:', defaultPath);
90
+ return defaultPath;
36
91
  }
37
92
 
38
93
  /**
@@ -85,10 +140,10 @@ function getPort() {
85
140
  const config = loadConfig();
86
141
 
87
142
  if (isDev) {
88
- return config.devPort || 3000;
143
+ return config.devPort || defaultConfig.devPort;
89
144
  }
90
145
 
91
- return config.port || 8022;
146
+ return config.port || defaultConfig.port;
92
147
  }
93
148
 
94
149
  /**
@@ -105,7 +160,7 @@ function getBindAddress() {
105
160
  const config = loadConfig();
106
161
 
107
162
  // Priority 3: Default
108
- return config.bind || '0.0.0.0';
163
+ return config.bind || defaultConfig.bind;
109
164
  }
110
165
 
111
166
  /**
@@ -115,8 +170,8 @@ function getBindAddress() {
115
170
  function getSSHKeepaliveSettings() {
116
171
  const config = loadConfig();
117
172
  return {
118
- sshKeepaliveInterval: config.sshKeepaliveInterval || 10000,
119
- sshKeepaliveCountMax: config.sshKeepaliveCountMax || 1000
173
+ sshKeepaliveInterval: config.sshKeepaliveInterval || defaultConfig.sshKeepaliveInterval,
174
+ sshKeepaliveCountMax: config.sshKeepaliveCountMax || defaultConfig.sshKeepaliveCountMax
120
175
  };
121
176
  }
122
177
 
@@ -156,8 +211,18 @@ function getLayouts() {
156
211
  return config.layouts || null;
157
212
  }
158
213
 
214
+ /**
215
+ * Get HTTPS setting from config
216
+ * @returns {boolean} Enable HTTPS setting
217
+ */
218
+ function getEnableHttps() {
219
+ const config = loadConfig();
220
+ return config.enableHttps !== false; // Default to true
221
+ }
222
+
159
223
  module.exports = {
160
224
  defaultConfig,
225
+ ensureConfig,
161
226
  getConfigPath,
162
227
  loadConfig,
163
228
  saveConfig,
@@ -167,5 +232,6 @@ module.exports = {
167
232
  getStickySetting,
168
233
  getTakeControlDefault,
169
234
  getMobileKeysBarEnabled,
170
- getLayouts
235
+ getLayouts,
236
+ getEnableHttps
171
237
  };
@@ -5,18 +5,39 @@
5
5
 
6
6
  const path = require('path');
7
7
  const fs = require('fs');
8
+ const os = require('os');
8
9
 
9
10
  /**
10
11
  * Load .env files in priority order
11
12
  * Priority: .env/.env.local > .env.local > .env/.env > .env
12
13
  */
13
14
  function loadEnvFiles() {
14
- // Paths are relative to project root (parent of src/server)
15
+ // Get user's home directory
16
+ const HOME_DIR = os.homedir();
17
+
18
+ // Default install directories for config (platform-specific)
19
+ const DEFAULT_INSTALL_DIRS = [
20
+ // Linux/macOS
21
+ path.join(HOME_DIR, '.local', 'share', 'sshift'),
22
+ // Windows
23
+ path.join(HOME_DIR, '.local', 'share', 'sshift'),
24
+ // Alternative locations
25
+ path.join(HOME_DIR, '.local', 'share', 'bin'),
26
+ ];
27
+
28
+ // Package directory (for development)
29
+ const PACKAGE_DIR = path.join(__dirname, '..', '..', '..');
30
+
31
+ // Build env paths - prioritize user install directory, then package directory
15
32
  const envPaths = [
16
- path.join(__dirname, '..', '..', '..', '.env', '.env.local'),
17
- path.join(__dirname, '..', '..', '..', '.env.local'),
18
- path.join(__dirname, '..', '..', '..', '.env', '.env'),
19
- path.join(__dirname, '..', '..', '..', '.env')
33
+ ...DEFAULT_INSTALL_DIRS.map(dir => path.join(dir, '.env', '.env.local')),
34
+ ...DEFAULT_INSTALL_DIRS.map(dir => path.join(dir, '.env.local')),
35
+ ...DEFAULT_INSTALL_DIRS.map(dir => path.join(dir, '.env', '.env')),
36
+ ...DEFAULT_INSTALL_DIRS.map(dir => path.join(dir, '.env')),
37
+ path.join(PACKAGE_DIR, '.env', '.env.local'),
38
+ path.join(PACKAGE_DIR, '.env.local'),
39
+ path.join(PACKAGE_DIR, '.env', '.env'),
40
+ path.join(PACKAGE_DIR, '.env')
20
41
  ];
21
42
 
22
43
  envPaths.forEach(envPath => {