@lethevimlet/sshift 0.3.1 → 0.5.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.
package/README.md CHANGED
@@ -22,6 +22,7 @@ A modern, responsive web-based SSH and SFTP terminal client built with Node.js,
22
22
  - 📁 **SFTP Browser** - File manager interface with upload/download
23
23
  - 🗂️ **Tabbed Interface** - Multiple concurrent sessions
24
24
  - 🔖 **Bookmarks** - Save connection details for quick access
25
+ - 🔒 **Password Protection** - Optional password lock for app access
25
26
  - ⌨️ **Mobile-Friendly** - Special keys popup for mobile devices
26
27
  - 🎨 **Modern UI** - GitHub-inspired dark theme, fully responsive
27
28
 
@@ -56,14 +57,14 @@ The recommended way to install sshift - automatically handles updates and autost
56
57
 
57
58
  **Linux/macOS:**
58
59
  ```bash
59
- curl -fsSL https://raw.githubusercontent.com/lethevimlet/sshift/main/install.sh | bash
60
+ curl -fsSL https://raw.githubusercontent.com/lethevimlet/sshift/main/sshift-install.sh | bash
60
61
  ```
61
62
 
62
63
  **Windows (PowerShell):**
63
64
 
64
65
  ```powershell
65
66
  Set-ExecutionPolicy Bypass -Scope Process
66
- Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/lethevimlet/sshift/main/install.ps1" -UseBasicParsing).Content
67
+ Invoke-Expression (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/lethevimlet/sshift/main/sshift-install.ps1" -UseBasicParsing).Content
67
68
  ```
68
69
 
69
70
  > **Note:** The Windows installer requires PowerShell to be run as Administrator for npm global installations.
@@ -6,6 +6,7 @@
6
6
  "sticky": true,
7
7
  "sshKeepaliveInterval": 15000,
8
8
  "sshKeepaliveCountMax": 500,
9
+ "passwordHash": null,
9
10
  "bookmarks": [
10
11
  {
11
12
  "id": "example1",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -0,0 +1,87 @@
1
+ const { isPasswordSet, verifyPassword, setPassword, removePassword } = require('../../utils/config');
2
+
3
+ const authTokens = new Map();
4
+ const TOKEN_TTL = 24 * 60 * 60 * 1000;
5
+
6
+ function generateToken() {
7
+ const crypto = require('crypto');
8
+ return crypto.randomBytes(32).toString('hex');
9
+ }
10
+
11
+ function cleanExpiredTokens() {
12
+ const now = Date.now();
13
+ for (const [token, expiry] of authTokens) {
14
+ if (expiry < now) authTokens.delete(token);
15
+ }
16
+ }
17
+
18
+ function registerAuthEndpoints(app, io) {
19
+ app.get('/api/auth/status', (req, res) => {
20
+ res.json({ passwordEnabled: isPasswordSet() });
21
+ });
22
+
23
+ app.post('/api/auth/login', (req, res) => {
24
+ const { password } = req.body;
25
+ if (!isPasswordSet()) {
26
+ return res.json({ success: true, authenticated: true });
27
+ }
28
+ if (!password) {
29
+ return res.status(400).json({ error: 'Password required' });
30
+ }
31
+ if (!verifyPassword(password)) {
32
+ return res.status(401).json({ error: 'Invalid password' });
33
+ }
34
+ const token = generateToken();
35
+ authTokens.set(token, Date.now() + TOKEN_TTL);
36
+ cleanExpiredTokens();
37
+ res.json({ success: true, token });
38
+ });
39
+
40
+ app.post('/api/auth/set-password', (req, res) => {
41
+ const { currentPassword, newPassword } = req.body;
42
+ if (isPasswordSet()) {
43
+ if (!currentPassword || !verifyPassword(currentPassword)) {
44
+ return res.status(401).json({ error: 'Current password is incorrect' });
45
+ }
46
+ }
47
+ if (!newPassword || newPassword.length < 1) {
48
+ return res.status(400).json({ error: 'Password cannot be empty' });
49
+ }
50
+ const result = setPassword(newPassword);
51
+ if (result) {
52
+ res.json({ success: true });
53
+ } else {
54
+ res.status(500).json({ error: 'Failed to save password' });
55
+ }
56
+ });
57
+
58
+ app.post('/api/auth/remove-password', (req, res) => {
59
+ const { currentPassword } = req.body;
60
+ if (!isPasswordSet()) {
61
+ return res.json({ success: true });
62
+ }
63
+ if (!currentPassword || !verifyPassword(currentPassword)) {
64
+ return res.status(401).json({ error: 'Current password is incorrect' });
65
+ }
66
+ const result = removePassword();
67
+ if (result) {
68
+ res.json({ success: true });
69
+ } else {
70
+ res.status(500).json({ error: 'Failed to remove password' });
71
+ }
72
+ });
73
+ }
74
+
75
+ function isValidAuthToken(token) {
76
+ if (!token) return false;
77
+ cleanExpiredTokens();
78
+ const expiry = authTokens.get(token);
79
+ if (!expiry) return false;
80
+ if (expiry < Date.now()) {
81
+ authTokens.delete(token);
82
+ return false;
83
+ }
84
+ return true;
85
+ }
86
+
87
+ module.exports = { registerAuthEndpoints, isValidAuthToken };
@@ -4,22 +4,22 @@
4
4
 
5
5
  const { loadConfig, saveConfig } = require('../../utils/config');
6
6
 
7
- /**
8
- * Register config endpoints
9
- * @param {Object} app - Express app
10
- * @param {Object} io - Socket.IO instance
11
- */
7
+ const AUTH_WHITELIST = [
8
+ '/api/auth/status',
9
+ '/api/auth/login'
10
+ ];
11
+
12
12
  function registerConfigEndpoints(app, io) {
13
- // API: Get config (for sticky sessions and SSH keepalive)
14
13
  app.get('/api/config', (req, res) => {
15
14
  const config = loadConfig();
16
15
  res.json({
17
- sticky: config.sticky !== false, // Default to true
18
- takeControlDefault: config.takeControlDefault !== false, // Default to true
16
+ sticky: config.sticky !== false,
17
+ takeControlDefault: config.takeControlDefault !== false,
19
18
  sshKeepaliveInterval: config.sshKeepaliveInterval || 10000,
20
19
  sshKeepaliveCountMax: config.sshKeepaliveCountMax || 1000,
21
- mobileKeysBarEnabled: config.mobileKeysBarEnabled !== false, // Default to true
22
- layouts: config.layouts || null // Include layouts if defined in config
20
+ mobileKeysBarEnabled: config.mobileKeysBarEnabled !== false,
21
+ layouts: config.layouts || null,
22
+ passwordEnabled: !!config.passwordHash
23
23
  });
24
24
  });
25
25
 
@@ -8,18 +8,17 @@ const { registerConfigEndpoints } = require('./config');
8
8
  const { registerFolderEndpoints } = require('./folders');
9
9
  const { registerSessionsEndpoints } = require('./sessions');
10
10
  const { registerSystemEndpoints } = require('./system');
11
+ const { registerUtilsEndpoints } = require('./utils');
12
+ const { registerAuthEndpoints, isValidAuthToken } = require('./auth');
11
13
 
12
- /**
13
- * Register all REST endpoints
14
- * @param {Object} app - Express app
15
- * @param {Object} io - Socket.IO instance
16
- */
17
14
  function registerAllRestEndpoints(app, io) {
15
+ registerAuthEndpoints(app, io);
18
16
  registerBookmarkEndpoints(app, io);
19
17
  registerConfigEndpoints(app, io);
20
18
  registerFolderEndpoints(app, io);
21
19
  registerSessionsEndpoints(app, io);
22
20
  registerSystemEndpoints(app, io);
21
+ registerUtilsEndpoints(app, io);
23
22
  }
24
23
 
25
24
  module.exports = {
@@ -28,5 +27,8 @@ module.exports = {
28
27
  registerFolderEndpoints,
29
28
  registerSessionsEndpoints,
30
29
  registerSystemEndpoints,
30
+ registerUtilsEndpoints,
31
+ registerAuthEndpoints,
32
+ isValidAuthToken,
31
33
  registerAllRestEndpoints
32
34
  };
@@ -0,0 +1,36 @@
1
+ const { detectKeyFormat, convertPPKToOpenSSH } = require('../../utils/key-converter');
2
+
3
+ function registerUtilsEndpoints(app, io) {
4
+ app.post('/api/utils/detect-key', (req, res) => {
5
+ const { content } = req.body;
6
+ if (!content || !content.trim()) {
7
+ return res.json({ format: 'unknown', type: 'unknown', encrypted: false });
8
+ }
9
+ try {
10
+ const info = detectKeyFormat(content);
11
+ res.json(info);
12
+ } catch (e) {
13
+ res.json({ format: 'unknown', type: 'unknown', encrypted: false, error: e.message });
14
+ }
15
+ });
16
+
17
+ app.post('/api/utils/convert-key', async (req, res) => {
18
+ const { content } = req.body;
19
+ if (!content || !content.trim()) {
20
+ return res.status(400).json({ error: 'No key content provided' });
21
+ }
22
+ const info = detectKeyFormat(content);
23
+ if (info.format === 'ppk') {
24
+ try {
25
+ const converted = await convertPPKToOpenSSH(content);
26
+ res.json({ success: true, key: converted, format: 'openssh' });
27
+ } catch (e) {
28
+ res.status(400).json({ error: e.message });
29
+ }
30
+ } else {
31
+ res.json({ success: true, key: content, format: info.format });
32
+ }
33
+ });
34
+ }
35
+
36
+ module.exports = { registerUtilsEndpoints };
@@ -12,12 +12,13 @@ require('./utils/env-loader');
12
12
  const express = require('express');
13
13
  const http = require('http');
14
14
  const https = require('https');
15
+ const fs = require('fs');
15
16
  const path = require('path');
16
17
  const socketIO = require('socket.io');
17
18
  const selfsigned = require('selfsigned');
18
19
 
19
20
  // Import utilities
20
- const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps } = require('./utils/config');
21
+ const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getDataDir, isPasswordSet } = require('./utils/config');
21
22
 
22
23
  // Import services
23
24
  const { sshManager, sftpManager } = require('./services');
@@ -25,8 +26,49 @@ const { sshManager, sftpManager } = require('./services');
25
26
  // Import endpoints
26
27
  const { rest, ws } = require('./endpoints');
27
28
 
29
+ const SSL_CERT_FILE = 'ssl-cert.pem';
30
+ const SSL_KEY_FILE = 'ssl-key.pem';
31
+
28
32
  /**
29
- * Generate self-signed SSL certificates in memory using selfsigned package (pure JS, no OpenSSL dependency)
33
+ * Get SSL credentials, reusing persisted certificates if available.
34
+ * Generates new self-signed certificates only if no persisted ones exist.
35
+ * @returns {Promise<Object>} Certificate and private key
36
+ */
37
+ async function getSSLCredentials() {
38
+ const dataDir = getDataDir();
39
+ const certPath = path.join(dataDir, SSL_CERT_FILE);
40
+ const keyPath = path.join(dataDir, SSL_KEY_FILE);
41
+
42
+ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
43
+ console.log('[HTTPS] Reusing persisted SSL certificate from', dataDir);
44
+ try {
45
+ return {
46
+ cert: fs.readFileSync(certPath, 'utf8'),
47
+ key: fs.readFileSync(keyPath, 'utf8')
48
+ };
49
+ } catch (err) {
50
+ console.warn('[HTTPS] Failed to read persisted certificate, regenerating:', err.message);
51
+ }
52
+ }
53
+
54
+ const creds = await generateSelfSignedCert();
55
+
56
+ try {
57
+ if (!fs.existsSync(dataDir)) {
58
+ fs.mkdirSync(dataDir, { recursive: true });
59
+ }
60
+ fs.writeFileSync(certPath, creds.cert, { mode: 0o600 });
61
+ fs.writeFileSync(keyPath, creds.key, { mode: 0o600 });
62
+ console.log('[HTTPS] SSL certificate persisted to', dataDir);
63
+ } catch (err) {
64
+ console.warn('[HTTPS] Failed to persist certificate:', err.message);
65
+ }
66
+
67
+ return creds;
68
+ }
69
+
70
+ /**
71
+ * Generate self-signed SSL certificates using selfsigned package (pure JS, no OpenSSL dependency)
30
72
  * @returns {Promise<Object>} Certificate and private key
31
73
  */
32
74
  async function generateSelfSignedCert() {
@@ -34,11 +76,9 @@ async function generateSelfSignedCert() {
34
76
 
35
77
  const os = require('os');
36
78
 
37
- // Get local IP addresses for SAN
38
79
  const interfaces = os.networkInterfaces();
39
80
  const localIPs = ['127.0.0.1'];
40
81
 
41
- // Extract all IPv4 addresses from network interfaces
42
82
  Object.values(interfaces).forEach(iface => {
43
83
  iface.forEach(addr => {
44
84
  if (addr.family === 'IPv4' && !addr.internal) {
@@ -47,12 +87,10 @@ async function generateSelfSignedCert() {
47
87
  });
48
88
  });
49
89
 
50
- // Get hostname
51
90
  const hostname = os.hostname() || 'localhost';
52
91
 
53
92
  console.log('[HTTPS] Certificate will be valid for:', localIPs.join(', '), 'and hostname:', hostname);
54
93
 
55
- // Build Subject Alternative Names
56
94
  const altNames = [
57
95
  { type: 2, value: 'localhost' },
58
96
  { type: 2, value: hostname },
@@ -97,7 +135,7 @@ async function initializeServer() {
97
135
 
98
136
  if (enableHttps) {
99
137
  try {
100
- sslCredentials = await generateSelfSignedCert();
138
+ sslCredentials = await getSSLCredentials();
101
139
  server = https.createServer({
102
140
  key: sslCredentials.key,
103
141
  cert: sslCredentials.cert
@@ -117,10 +155,16 @@ async function initializeServer() {
117
155
  origin: "*",
118
156
  methods: ["GET", "POST"]
119
157
  },
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)
158
+ pingTimeout: 60000,
159
+ pingInterval: 25000
160
+ });
161
+
162
+ // Socket.IO auth middleware
163
+ io.use((socket, next) => {
164
+ if (!isPasswordSet()) return next();
165
+ const token = socket.handshake.auth.token || socket.handshake.query.token;
166
+ if (isValidAuthToken(token)) return next();
167
+ next(new Error('Authentication required'));
124
168
  });
125
169
 
126
170
  // Set the socket.io instance for services that need it
@@ -129,6 +173,23 @@ async function initializeServer() {
129
173
  // Middleware
130
174
  app.use(express.json());
131
175
 
176
+ // Auth middleware - block API endpoints when password is set
177
+ const { isValidAuthToken } = require('./endpoints/rest/auth');
178
+ const AUTH_WHITELIST = ['/auth/status', '/auth/login'];
179
+
180
+ app.use('/api', (req, res, next) => {
181
+ if (AUTH_WHITELIST.some(p => req.path === p)) return next();
182
+ if (!isPasswordSet()) return next();
183
+ const token = req.headers.authorization?.replace('Bearer ', '') || req.query.token;
184
+ if (isValidAuthToken(token)) return next();
185
+ res.status(401).json({ error: 'Authentication required' });
186
+ });
187
+
188
+ app.use((req, res, next) => {
189
+ if (req.path.startsWith('/api/') || req.path.startsWith('/socket.io/')) return next();
190
+ next();
191
+ });
192
+
132
193
  // Serve static files from the webapp directory
133
194
  const webappPath = path.join(__dirname, '../webapp');
134
195
  app.use(express.static(webappPath));
@@ -28,11 +28,13 @@ class SFTPManager {
28
28
  config.password = options.password;
29
29
  console.log('[SFTP] Using password authentication');
30
30
  } else if (options.privateKey && options.privateKey.length > 0) {
31
+ // Handle private key - supports OpenSSH, PEM, PKCS8, and base64-encoded formats
31
32
  try {
32
33
  if (options.privateKey.includes('BEGIN')) {
33
34
  config.privateKey = options.privateKey;
34
35
  } else {
35
- config.privateKey = Buffer.from(options.privateKey, 'base64').toString('utf8');
36
+ const decoded = Buffer.from(options.privateKey, 'base64').toString('utf8');
37
+ config.privateKey = decoded;
36
38
  }
37
39
  } catch (e) {
38
40
  config.privateKey = options.privateKey;
@@ -76,14 +76,13 @@ class SSHManager {
76
76
  config.password = options.password;
77
77
  console.log('[SSH] Using password authentication');
78
78
  } else if (options.privateKey && options.privateKey.length > 0) {
79
- // Handle private key - can be string or buffer
79
+ // Handle private key - supports OpenSSH, PEM, PKCS8, and base64-encoded formats
80
80
  try {
81
- // If it's a base64 encoded key, decode it
82
81
  if (options.privateKey.includes('BEGIN')) {
83
82
  config.privateKey = options.privateKey;
84
83
  } else {
85
- // Try to decode base64
86
- config.privateKey = Buffer.from(options.privateKey, 'base64').toString('utf8');
84
+ const decoded = Buffer.from(options.privateKey, 'base64').toString('utf8');
85
+ config.privateKey = decoded;
87
86
  }
88
87
  } catch (e) {
89
88
  config.privateKey = options.privateKey;
@@ -6,6 +6,7 @@
6
6
  const path = require('path');
7
7
  const fs = require('fs');
8
8
  const os = require('os');
9
+ const crypto = require('crypto');
9
10
 
10
11
  // Get user's home directory
11
12
  const HOME_DIR = os.homedir();
@@ -39,7 +40,8 @@ const defaultConfig = {
39
40
  sshKeepaliveInterval: 15000,
40
41
  sshKeepaliveCountMax: 500,
41
42
  bookmarks: [],
42
- folders: []
43
+ folders: [],
44
+ passwordHash: null
43
45
  };
44
46
 
45
47
  /**
@@ -220,6 +222,50 @@ function getEnableHttps() {
220
222
  return config.enableHttps !== false; // Default to true
221
223
  }
222
224
 
225
+ /**
226
+ * Get the data directory for persistent storage (SSL certs, etc.)
227
+ * Searches the same paths as config to find a writable data directory.
228
+ * @returns {string} Path to data directory
229
+ */
230
+ function getDataDir() {
231
+ const configPath = getConfigPath();
232
+ const configDir = path.dirname(configPath);
233
+
234
+ // If config is in a .env subdirectory, use parent
235
+ if (path.basename(configDir) === '.env') {
236
+ return path.dirname(configDir);
237
+ }
238
+
239
+ return configDir;
240
+ }
241
+
242
+ function hashPassword(password) {
243
+ return crypto.createHash('sha3-256').update(password).digest('hex');
244
+ }
245
+
246
+ function isPasswordSet() {
247
+ const config = loadConfig();
248
+ return !!config.passwordHash;
249
+ }
250
+
251
+ function verifyPassword(password) {
252
+ const config = loadConfig();
253
+ if (!config.passwordHash) return true;
254
+ return hashPassword(password) === config.passwordHash;
255
+ }
256
+
257
+ function setPassword(password) {
258
+ const config = loadConfig();
259
+ config.passwordHash = hashPassword(password);
260
+ return saveConfig(config);
261
+ }
262
+
263
+ function removePassword() {
264
+ const config = loadConfig();
265
+ config.passwordHash = null;
266
+ return saveConfig(config);
267
+ }
268
+
223
269
  module.exports = {
224
270
  defaultConfig,
225
271
  ensureConfig,
@@ -233,5 +279,11 @@ module.exports = {
233
279
  getTakeControlDefault,
234
280
  getMobileKeysBarEnabled,
235
281
  getLayouts,
236
- getEnableHttps
282
+ getEnableHttps,
283
+ getDataDir,
284
+ hashPassword,
285
+ isPasswordSet,
286
+ verifyPassword,
287
+ setPassword,
288
+ removePassword
237
289
  };