@lethevimlet/sshift 0.2.0 → 0.3.1

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.1",
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,7 @@
24
24
  "dotenv": "^17.4.0",
25
25
  "express": "^4.18.2",
26
26
  "lucide": "^1.7.0",
27
+ "selfsigned": "^5.5.0",
27
28
  "socket.io": "^4.7.2",
28
29
  "ssh2": "^1.15.0",
29
30
  "uuid": "^9.0.0"
@@ -11,11 +11,13 @@ 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');
16
18
 
17
19
  // Import utilities
18
- const { loadConfig, getPort, getBindAddress } = require('./utils/config');
20
+ const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps } = require('./utils/config');
19
21
 
20
22
  // Import services
21
23
  const { sshManager, sftpManager } = require('./services');
@@ -23,104 +25,201 @@ const { sshManager, sftpManager } = require('./services');
23
25
  // Import endpoints
24
26
  const { rest, ws } = require('./endpoints');
25
27
 
26
- // Create Express app and HTTP server
28
+ /**
29
+ * Generate self-signed SSL certificates in memory using selfsigned package (pure JS, no OpenSSL dependency)
30
+ * @returns {Promise<Object>} Certificate and private key
31
+ */
32
+ async function generateSelfSignedCert() {
33
+ console.log('[HTTPS] Generating self-signed certificate...');
34
+
35
+ const os = require('os');
36
+
37
+ // Get local IP addresses for SAN
38
+ const interfaces = os.networkInterfaces();
39
+ const localIPs = ['127.0.0.1'];
40
+
41
+ // Extract all IPv4 addresses from network interfaces
42
+ Object.values(interfaces).forEach(iface => {
43
+ iface.forEach(addr => {
44
+ if (addr.family === 'IPv4' && !addr.internal) {
45
+ localIPs.push(addr.address);
46
+ }
47
+ });
48
+ });
49
+
50
+ // Get hostname
51
+ const hostname = os.hostname() || 'localhost';
52
+
53
+ console.log('[HTTPS] Certificate will be valid for:', localIPs.join(', '), 'and hostname:', hostname);
54
+
55
+ // Build Subject Alternative Names
56
+ const altNames = [
57
+ { type: 2, value: 'localhost' },
58
+ { type: 2, value: hostname },
59
+ ...localIPs.map(ip => ({ type: 7, ip }))
60
+ ];
61
+
62
+ try {
63
+ const attrs = [{ name: 'commonName', value: hostname }];
64
+ const pems = await selfsigned.generate(attrs, {
65
+ days: 365,
66
+ keySize: 2048,
67
+ algorithm: 'sha256',
68
+ extensions: [{
69
+ name: 'subjectAltName',
70
+ altNames
71
+ }]
72
+ });
73
+
74
+ console.log('[HTTPS] Self-signed certificate generated successfully');
75
+ return {
76
+ cert: pems.cert,
77
+ key: pems.private
78
+ };
79
+ } catch (err) {
80
+ console.error('[HTTPS] Error generating certificate:', err);
81
+ throw err;
82
+ }
83
+ }
84
+
85
+ // Create Express app
27
86
  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
-
40
- // Set the socket.io instance for services that need it
41
- sshManager.setIO(io);
42
87
 
43
- // Middleware
44
- app.use(express.json());
88
+ // Determine if HTTPS should be enabled
89
+ const enableHttps = getEnableHttps();
90
+ let server;
91
+ let io; // Declare io at module level for exports
92
+ let sslCredentials = null;
93
+
94
+ // Async initialization function
95
+ async function initializeServer() {
96
+ ensureConfig();
97
+
98
+ if (enableHttps) {
99
+ try {
100
+ sslCredentials = await generateSelfSignedCert();
101
+ server = https.createServer({
102
+ key: sslCredentials.key,
103
+ cert: sslCredentials.cert
104
+ }, app);
105
+ console.log('[HTTPS] HTTPS server created with self-signed certificate');
106
+ } catch (err) {
107
+ console.error('[HTTPS] Failed to create HTTPS server, falling back to HTTP:', err.message);
108
+ server = http.createServer(app);
109
+ }
110
+ } else {
111
+ server = http.createServer(app);
112
+ console.log('[HTTP] HTTP server created (HTTPS disabled)');
113
+ }
114
+
115
+ io = socketIO(server, {
116
+ cors: {
117
+ origin: "*",
118
+ methods: ["GET", "POST"]
119
+ },
120
+ // Increase ping timeout for sticky sessions
121
+ // This prevents disconnection during temporary network issues
122
+ pingTimeout: 60000, // 60 seconds (default 20s)
123
+ pingInterval: 25000 // 25 seconds (default)
124
+ });
45
125
 
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')));
126
+ // Set the socket.io instance for services that need it
127
+ sshManager.setIO(io);
53
128
 
54
- // Main route
55
- app.get('/', (req, res) => {
56
- res.sendFile(path.join(webappPath, 'index.html'));
57
- });
129
+ // Middleware
130
+ app.use(express.json());
58
131
 
59
- // Register REST endpoints
60
- rest.registerAllRestEndpoints(app, io);
132
+ // Serve static files from the webapp directory
133
+ const webappPath = path.join(__dirname, '../webapp');
134
+ app.use(express.static(webappPath));
135
+ app.use('/js', express.static(path.join(webappPath, 'js')));
136
+ app.use('/css', express.static(path.join(webappPath, 'css')));
137
+ app.use('/libs', express.static(path.join(webappPath, 'libs')));
138
+ app.use('/tests', express.static(path.join(webappPath, 'tests')));
61
139
 
62
- // Socket.IO connection handling
63
- io.on('connection', (socket) => {
64
- console.log('Client connected:', socket.id);
140
+ // Main route
141
+ app.get('/', (req, res) => {
142
+ res.sendFile(path.join(webappPath, 'index.html'));
143
+ });
65
144
 
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
- };
145
+ // Register REST endpoints
146
+ rest.registerAllRestEndpoints(app, io);
147
+
148
+ // Socket.IO connection handling
149
+ io.on('connection', (socket) => {
150
+ console.log('Client connected:', socket.id);
151
+
152
+ // Send current open tabs to new client
153
+ const { getOpenTabs, getTabOrder, getCurrentTheme, getCurrentAccent } = require('./utils/tab-manager');
154
+ const { getCurrentLayout } = require('./endpoints/ws/layout');
155
+
156
+ const openTabs = getOpenTabs();
157
+ const tabOrder = getTabOrder();
158
+ const currentLayout = getCurrentLayout();
159
+ const currentTheme = getCurrentTheme();
160
+ const currentAccent = getCurrentAccent();
161
+
162
+ // Exclude activeSockets (Set object) to avoid Socket.IO serialization issues
163
+ const orderedTabs = tabOrder
164
+ .filter(sessionId => openTabs.has(sessionId))
165
+ .map(sessionId => {
166
+ const tab = openTabs.get(sessionId);
167
+ return {
168
+ sessionId,
169
+ name: tab.name,
170
+ type: tab.type,
171
+ connectionData: {
172
+ host: tab.connectionData?.host,
173
+ port: tab.connectionData?.port,
174
+ username: tab.connectionData?.username,
175
+ name: tab.connectionData?.name
176
+ // Exclude password, privateKey, and other sensitive data
177
+ },
178
+ sticky: tab.sticky,
179
+ panelId: tab.panelId || 'panel-0' // Include panel assignment
180
+ // Exclude activeSockets (Set) to avoid serialization issues
181
+ };
182
+ });
183
+
184
+ socket.emit('open-tabs', {
185
+ tabs: orderedTabs,
186
+ layout: currentLayout,
187
+ theme: currentTheme,
188
+ accent: currentAccent
96
189
  });
97
-
98
- socket.emit('open-tabs', {
99
- tabs: orderedTabs,
100
- layout: currentLayout,
101
- theme: currentTheme,
102
- accent: currentAccent
103
- });
104
190
 
105
- // Register all WebSocket handlers
106
- ws.registerAllWSHandlers(socket, io);
191
+ // Register all WebSocket handlers
192
+ ws.registerAllWSHandlers(socket, io);
107
193
 
108
- // Handle disconnect
109
- socket.on('disconnect', () => {
110
- ws.handleDisconnect(socket, io);
194
+ // Handle disconnect
195
+ socket.on('disconnect', () => {
196
+ ws.handleDisconnect(socket, io);
197
+ });
111
198
  });
112
- });
113
199
 
114
- // Start server
115
- const PORT = getPort();
116
- const BIND = getBindAddress();
200
+ // Start server
201
+ const PORT = getPort();
202
+ const BIND = getBindAddress();
203
+
204
+ server.listen(PORT, BIND, () => {
205
+ const address = BIND === '0.0.0.0' || BIND === '::' ? 'localhost' : BIND;
206
+ const protocol = enableHttps ? 'https' : 'http';
207
+ console.log(`Web SSH/SFTP Client running at ${protocol}://${address}:${PORT}`);
208
+ // OSC 8 hyperlink: ESC ] 8 ; ; URL BEL text ESC ] 8 ; ; BEL
209
+ const ESC = '\x1b';
210
+ console.log(`${ESC}]8;;${protocol}://${address}:${PORT}${ESC}\\Open in browser${ESC}]8;;${ESC}\\`);
211
+
212
+ if (enableHttps) {
213
+ console.log('[HTTPS] Note: Using self-signed certificate. Your browser may show a security warning.');
214
+ console.log('[HTTPS] For mobile devices, you may need to accept the certificate warning to use native text selection.');
215
+ }
216
+ });
217
+ }
117
218
 
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}\\`);
219
+ // Start the server
220
+ initializeServer().catch(err => {
221
+ console.error('Failed to initialize server:', err);
222
+ process.exit(1);
124
223
  });
125
224
 
126
225
  // 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 => {