@lethevimlet/sshift 0.9.8 → 1.0.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
@@ -143,27 +143,46 @@ See [Configuration](docs/configuration.md) for details.
143
143
 
144
144
  ## 🔒 HTTPS on Local Network (PWA / "Not Secure" Warnings)
145
145
 
146
- When accessing sshift from a LAN IP (e.g., `https://192.168.1.50:8022`), browsers show "Not Secure" warnings because the self-signed certificate is untrusted. This also blocks PWA installation.
146
+ When accessing sshift from a LAN IP (e.g., `https://192.168.1.50:8022`), browsers show "Not Secure" warnings because the self-signed certificate is not trusted. This also blocks PWA installation, which requires a trusted secure context.
147
147
 
148
- ### Quick Fix: Chrome Flag
148
+ ### Recommended: Trust the Auto-Generated Certificate
149
149
 
150
- 1. Go to `chrome://flags/#unsafely-treat-insecure-origin-as-secure`
151
- 2. Enter your LAN URL: `https://192.168.1.50:8022`
152
- 3. Set to **Enabled** → **Relaunch**
150
+ sshift automatically generates a self-signed TLS certificate on first run. The simplest fix is to add this certificate to your device's trusted root store:
153
151
 
154
- ### Permanent: Custom Trusted Certificate
152
+ 1. **Download the certificate** — visit `https://<your-sshift-host>:8022/api/cert` in your browser, or find it at `~/.local/share/sshift/ssl-cert.pem` on the server
153
+ 2. **Add it to your device's trusted root store:**
154
+ - **Windows:** Double-click the file → Install Certificate → Local Machine → Trusted Root Certification Authorities
155
+ - **macOS:** Double-click the file → Add to Keychain → Set "Always Trust" in Keychain Access
156
+ - **Linux:** Copy to `/usr/local/share/ca-certificates/` and run `sudo update-ca-certificates`
157
+ - **Android:** Settings → Security → Install from storage
158
+ - **iOS:** Send via AirDrop/email → Open → Install profile → Settings → General → About → Certificate Trust Settings → Enable full trust
155
159
 
156
- Generate a cert for your LAN IP and configure sshift to use it:
160
+ After trusting the certificate, the "Not Secure" warning will disappear and PWA installation will work.
161
+
162
+ ### Using Your Own Certificate
163
+
164
+ You can provide your own TLS certificate via `config.json`:
157
165
 
158
166
  ```json
159
167
  {
160
168
  "enableHttps": true,
161
- "certPath": "/path/to/sshift-lan-cert.pem",
162
- "keyPath": "/path/to/sshift-lan-key.pem"
169
+ "certPath": "/path/to/your/certificate.pem",
170
+ "keyPath": "/path/to/your/private-key.pem"
163
171
  }
164
172
  ```
165
173
 
166
- Then add the certificate to your device's trusted root store. See [Configuration > HTTPS on Local Network](docs/configuration.md) for full instructions including nginx reverse proxy and mDNS options.
174
+ Both `certPath` and `keyPath` must be set together. See [Configuration > HTTPS on Local Network](docs/configuration.md) for full instructions including nginx reverse proxy and mDNS options.
175
+
176
+ ### HTTP → HTTPS Redirect
177
+
178
+ By default, sshift automatically redirects any plain HTTP requests to HTTPS on the same port — so visiting `http://192.168.1.50:8022` seamlessly upgrades to `https://`. This is controlled by the `httpRedirect` setting (enabled by default). To disable it:
179
+
180
+ ```json
181
+ {
182
+ "enableHttps": true,
183
+ "httpRedirect": false
184
+ }
185
+ ```
167
186
 
168
187
  ## 🤖 AI Attention Plugins
169
188
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "0.9.8",
3
+ "version": "1.0.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -8,6 +8,8 @@ const { getDataDir } = require('../../utils/config');
8
8
 
9
9
  const SSL_CERT_FILE = 'ssl-cert.pem';
10
10
  const SSL_KEY_FILE = 'ssl-key.pem';
11
+ const UPDATE_MARKER_FILE = '.updating';
12
+ const RESTART_MARKER_FILE = '.restart-after-update';
11
13
 
12
14
  /**
13
15
  * Register system endpoints
@@ -15,6 +17,23 @@ const SSL_KEY_FILE = 'ssl-key.pem';
15
17
  * @param {Object} io - Socket.IO instance
16
18
  */
17
19
  function registerSystemEndpoints(app, io) {
20
+ // Clean up stale update marker files from previous update attempts
21
+ const dataDir = getDataDir();
22
+ const staleUpdateMarker = path.join(dataDir, UPDATE_MARKER_FILE);
23
+ const staleRestartMarker = path.join(dataDir, RESTART_MARKER_FILE);
24
+ try {
25
+ if (fs.existsSync(staleUpdateMarker)) {
26
+ fs.unlinkSync(staleUpdateMarker);
27
+ console.log('[UPDATE] Cleaned up stale update marker');
28
+ }
29
+ if (fs.existsSync(staleRestartMarker)) {
30
+ fs.unlinkSync(staleRestartMarker);
31
+ console.log('[UPDATE] Cleaned up stale restart marker');
32
+ }
33
+ } catch (e) {
34
+ console.error('[UPDATE] Failed to clean up marker files:', e.message);
35
+ }
36
+
18
37
  // API: Get version
19
38
  app.get('/api/version', (req, res) => {
20
39
  try {
@@ -110,8 +129,9 @@ function registerSystemEndpoints(app, io) {
110
129
 
111
130
  // API: Get update status
112
131
  app.get('/api/update-status', (req, res) => {
113
- const updateMarker = path.join(__dirname, '../../../../.updating');
114
- const restartMarker = path.join(__dirname, '../../../../.restart-after-update');
132
+ const dataDir = getDataDir();
133
+ const updateMarker = path.join(dataDir, UPDATE_MARKER_FILE);
134
+ const restartMarker = path.join(dataDir, RESTART_MARKER_FILE);
115
135
 
116
136
  // Read package.json for current version
117
137
  let version = 'unknown';
@@ -172,6 +192,7 @@ function registerSystemEndpoints(app, io) {
172
192
  try {
173
193
  const { spawn } = require('child_process');
174
194
  const platform = process.platform;
195
+ const dataDir = getDataDir();
175
196
 
176
197
  // Determine the install script based on platform
177
198
  let installScript;
@@ -188,9 +209,10 @@ function registerSystemEndpoints(app, io) {
188
209
  }
189
210
 
190
211
  // Write update marker to indicate update in progress
191
- const updateMarker = path.join(__dirname, '../../../../.updating');
212
+ const updateMarker = path.join(dataDir, UPDATE_MARKER_FILE);
192
213
  try {
193
214
  const pkg = require('../../../../package.json');
215
+ fs.mkdirSync(dataDir, { recursive: true });
194
216
  fs.writeFileSync(updateMarker, JSON.stringify({
195
217
  startTime: Date.now(),
196
218
  oldVersion: pkg.version
@@ -200,7 +222,7 @@ function registerSystemEndpoints(app, io) {
200
222
  }
201
223
 
202
224
  // Write a restart marker file to indicate we want to restart after update
203
- const restartMarker = path.join(__dirname, '../../../../.restart-after-update');
225
+ const restartMarker = path.join(dataDir, RESTART_MARKER_FILE);
204
226
  try {
205
227
  fs.writeFileSync(restartMarker, 'true');
206
228
  } catch (e) {
@@ -211,10 +233,13 @@ function registerSystemEndpoints(app, io) {
211
233
  res.json({ message: 'Update started. Server will restart automatically.' });
212
234
 
213
235
  // Execute update script with --update flag (detached from parent process)
236
+ // Set SSHIFT_NO_SUDO=1 to prevent sudo prompts which won't work in detached mode
214
237
  const updateCommand = platform === 'win32'
215
238
  ? `powershell.exe -ExecutionPolicy Bypass -File "${installScript}" --update`
216
239
  : `"${installScript}" --update`;
217
240
 
241
+ const updateEnv = { ...process.env, SSHIFT_NO_SUDO: '1' };
242
+
218
243
  console.log('[UPDATE] Starting update process...');
219
244
 
220
245
  // Wait for response to be sent before spawning update process
@@ -224,7 +249,8 @@ function registerSystemEndpoints(app, io) {
224
249
  cwd: path.join(__dirname, '../../../..'),
225
250
  shell: true,
226
251
  detached: true,
227
- stdio: 'ignore'
252
+ stdio: 'ignore',
253
+ env: updateEnv
228
254
  });
229
255
 
230
256
  // Unref the child process so the parent can exit without waiting for it
@@ -19,7 +19,7 @@ const selfsigned = require('selfsigned');
19
19
  const httpolyglot = require('httpolyglot');
20
20
 
21
21
  // Import utilities
22
- const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getHttpRedirect, getCertPath, getKeyPath, getDataDir, isPasswordSet } = require('./utils/config');
22
+ const { ensureConfig, loadConfig, getPort, getBindAddress, getEnableHttps, getHttpRedirect, getCertPath, getKeyPath, getDataDir, getLegacyDataDir, isPasswordSet, USER_INSTALL_DIR } = require('./utils/config');
23
23
 
24
24
  // Import services
25
25
  const { sshManager, sftpManager } = require('./services');
@@ -39,6 +39,7 @@ const SSL_KEY_FILE = 'ssl-key.pem';
39
39
  /**
40
40
  * Get SSL credentials, reusing persisted certificates if available.
41
41
  * Generates new self-signed certificates only if no persisted ones exist.
42
+ * Migrates certs from package directory to user-space directory if needed.
42
43
  * @returns {Promise<Object>} Certificate and private key
43
44
  */
44
45
  async function getSSLCredentials() {
@@ -69,13 +70,42 @@ async function getSSLCredentials() {
69
70
  if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
70
71
  console.log('[HTTPS] Reusing persisted SSL certificate from', dataDir);
71
72
  try {
72
- return {
73
- cert: fs.readFileSync(certPath, 'utf8'),
74
- key: fs.readFileSync(keyPath, 'utf8')
75
- };
73
+ const cert = fs.readFileSync(certPath, 'utf8');
74
+ const key = fs.readFileSync(keyPath, 'utf8');
75
+ if (!certIncludesOrg(cert)) {
76
+ console.log('[HTTPS] Existing certificate lacks organizationName, regenerating...');
77
+ } else {
78
+ return { cert, key };
79
+ }
76
80
  } catch (err) {
77
81
  console.warn('[HTTPS] Failed to read persisted certificate, regenerating:', err.message);
78
82
  }
83
+ } else {
84
+ // Migrate from legacy (package) directory if certs exist there
85
+ const legacyDir = getLegacyDataDir();
86
+ if (legacyDir) {
87
+ const legacyCert = path.join(legacyDir, SSL_CERT_FILE);
88
+ const legacyKey = path.join(legacyDir, SSL_KEY_FILE);
89
+ if (fs.existsSync(legacyCert) && fs.existsSync(legacyKey)) {
90
+ console.log('[HTTPS] Migrating SSL certificate from', legacyDir, 'to', dataDir);
91
+ try {
92
+ if (!fs.existsSync(dataDir)) {
93
+ fs.mkdirSync(dataDir, { recursive: true });
94
+ }
95
+ const certData = fs.readFileSync(legacyCert, 'utf8');
96
+ const keyData = fs.readFileSync(legacyKey, 'utf8');
97
+ fs.writeFileSync(certPath, certData, { mode: 0o600 });
98
+ fs.writeFileSync(keyPath, keyData, { mode: 0o600 });
99
+ console.log('[HTTPS] SSL certificate migrated to user-space directory');
100
+ if (certIncludesOrg(certData)) {
101
+ return { cert: certData, key: keyData };
102
+ }
103
+ console.log('[HTTPS] Migrated certificate lacks organizationName, regenerating...');
104
+ } catch (err) {
105
+ console.warn('[HTTPS] Failed to migrate certificate:', err.message);
106
+ }
107
+ }
108
+ }
79
109
  }
80
110
 
81
111
  const creds = await generateSelfSignedCert();
@@ -94,6 +124,21 @@ async function getSSLCredentials() {
94
124
  return creds;
95
125
  }
96
126
 
127
+ /**
128
+ * Check if a PEM certificate includes an organizationName (O=) attribute.
129
+ * @param {string} certPem - PEM-encoded certificate
130
+ * @returns {boolean} True if O=sshift is present
131
+ */
132
+ function certIncludesOrg(certPem) {
133
+ try {
134
+ const { X509Certificate } = require('crypto');
135
+ const x509 = new X509Certificate(certPem);
136
+ return /O=sshift/i.test(x509.subject);
137
+ } catch {
138
+ return false;
139
+ }
140
+ }
141
+
97
142
  /**
98
143
  * Generate self-signed SSL certificates using selfsigned package (pure JS, no OpenSSL dependency)
99
144
  * @returns {Promise<Object>} Certificate and private key
@@ -125,7 +170,10 @@ async function generateSelfSignedCert() {
125
170
  ];
126
171
 
127
172
  try {
128
- const attrs = [{ name: 'commonName', value: hostname }];
173
+ const attrs = [
174
+ { name: 'commonName', value: hostname },
175
+ { name: 'organizationName', value: 'sshift' }
176
+ ];
129
177
  const pems = await selfsigned.generate(attrs, {
130
178
  days: 365,
131
179
  keySize: 2048,
@@ -232,7 +280,7 @@ async function initializeServer() {
232
280
 
233
281
  // Auth middleware - block API endpoints when password is set
234
282
  const { isValidAuthToken } = require('./endpoints/rest/auth');
235
- const AUTH_WHITELIST = ['/auth/status', '/auth/login', '/cert', '/security-info'];
283
+ const AUTH_WHITELIST = ['/auth/status', '/auth/login', '/cert', '/security-info', '/version', '/update-status'];
236
284
 
237
285
  app.use('/api', (req, res, next) => {
238
286
  if (AUTH_WHITELIST.some(p => req.path === p)) return next();
@@ -274,19 +274,32 @@ function getKeyPath() {
274
274
 
275
275
  /**
276
276
  * Get the data directory for persistent storage (SSL certs, etc.)
277
- * Searches the same paths as config to find a writable data directory.
277
+ * Always returns the user-space directory so certs survive npm updates.
278
278
  * @returns {string} Path to data directory
279
279
  */
280
280
  function getDataDir() {
281
+ return USER_INSTALL_DIR;
282
+ }
283
+
284
+ /**
285
+ * Get the legacy data directory (package directory) used before
286
+ * certs were moved to user space. Used for migration only.
287
+ * @returns {string|null} Path to legacy data directory, or null if N/A
288
+ */
289
+ function getLegacyDataDir() {
281
290
  const configPath = getConfigPath();
282
291
  const configDir = path.dirname(configPath);
283
-
284
- // If config is in a .env subdirectory, use parent
292
+
285
293
  if (path.basename(configDir) === '.env') {
286
- return path.dirname(configDir);
294
+ const pkgDataDir = path.dirname(configDir);
295
+ if (pkgDataDir !== USER_INSTALL_DIR) {
296
+ return pkgDataDir;
297
+ }
298
+ } else if (configDir !== USER_INSTALL_DIR) {
299
+ return configDir;
287
300
  }
288
-
289
- return configDir;
301
+
302
+ return null;
290
303
  }
291
304
 
292
305
  function hashPassword(password) {
@@ -336,9 +349,11 @@ module.exports = {
336
349
  getCertPath,
337
350
  getKeyPath,
338
351
  getDataDir,
352
+ getLegacyDataDir,
339
353
  hashPassword,
340
354
  isPasswordSet,
341
355
  verifyPassword,
342
356
  setPassword,
343
- removePassword
357
+ removePassword,
358
+ USER_INSTALL_DIR
344
359
  };
@@ -494,6 +494,7 @@ function Install-Sshift {
494
494
 
495
495
  if ($LASTEXITCODE -eq 0) {
496
496
  Write-Success "sshift installed successfully"
497
+ $script:installSucceeded = $true
497
498
  } else {
498
499
  Write-Host ""
499
500
  Write-Host "[ERROR] Failed to install sshift" -ForegroundColor Red
@@ -504,9 +505,7 @@ function Install-Sshift {
504
505
  Write-Host " 3. Try: npm cache clean --force" -ForegroundColor Cyan
505
506
  Write-Host " 4. Check npm logs for details" -ForegroundColor Cyan
506
507
  Write-Host ""
507
- Write-Host "Press any key to exit..."
508
- $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
509
- exit 1
508
+ $script:installSucceeded = $false
510
509
  }
511
510
  }
512
511
 
@@ -515,6 +514,7 @@ function Update-Sshift {
515
514
  Write-Info "Updating sshift..."
516
515
 
517
516
  # Stop running instance before updating
517
+ $script:updateSucceeded = $false
518
518
  $wasRunning = $false
519
519
  if (Test-IsRunning) {
520
520
  $wasRunning = $true
@@ -533,6 +533,7 @@ function Update-Sshift {
533
533
 
534
534
  if ($LASTEXITCODE -eq 0) {
535
535
  Write-Success "sshift updated successfully"
536
+ $script:updateSucceeded = $true
536
537
  } else {
537
538
  Write-Host ""
538
539
  Write-Host "[ERROR] Failed to update sshift" -ForegroundColor Red
@@ -544,9 +545,7 @@ function Update-Sshift {
544
545
  Write-Host " 4. Check npm logs for details" -ForegroundColor Cyan
545
546
  Write-Host " 5. If sshift was running, stop it first: ./sshift-install.ps1 -stop" -ForegroundColor Cyan
546
547
  Write-Host ""
547
- Write-Host "Press any key to exit..."
548
- $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
549
- exit 1
548
+ $script:updateSucceeded = $false
550
549
  }
551
550
  }
552
551
 
@@ -1025,6 +1024,23 @@ function Main {
1025
1024
 
1026
1025
  Update-Sshift
1027
1026
 
1027
+ # Restart the app if .restart-after-update marker exists (triggered from UI)
1028
+ # Always check markers regardless of update result to ensure cleanup
1029
+ $restartMarker = Join-Path $installDir ".restart-after-update"
1030
+ $updateMarker = Join-Path $installDir ".updating"
1031
+ if (Test-Path $restartMarker) {
1032
+ Remove-Item -Force $restartMarker -ErrorAction SilentlyContinue
1033
+ Remove-Item -Force $updateMarker -ErrorAction SilentlyContinue
1034
+ if ($script:updateSucceeded) {
1035
+ Write-Info "Restarting sshift..."
1036
+ } else {
1037
+ Write-Warning "Update failed, restarting with previous version..."
1038
+ }
1039
+ Start-App
1040
+ } elseif (Test-Path $updateMarker) {
1041
+ Remove-Item -Force $updateMarker -ErrorAction SilentlyContinue
1042
+ }
1043
+
1028
1044
  Show-Summary
1029
1045
 
1030
1046
  Write-Host ""
package/sshift-install.sh CHANGED
@@ -368,18 +368,24 @@ install_nodejs() {
368
368
  install_sshift() {
369
369
  info "Installing sshift via npm..."
370
370
 
371
+ local install_rc=0
371
372
  if [ "$(id -u)" -eq 0 ]; then
372
- npm install -g @lethevimlet/sshift
373
+ npm install -g @lethevimlet/sshift || install_rc=$?
373
374
  elif [ -w /usr/lib/node_modules ] 2>/dev/null || [ -w /usr/local/lib/node_modules ] 2>/dev/null; then
374
- npm install -g @lethevimlet/sshift
375
+ npm install -g @lethevimlet/sshift || install_rc=$?
376
+ elif [ -n "$SSHIFT_NO_SUDO" ] && [ "$SSHIFT_NO_SUDO" = "1" ]; then
377
+ warn "Cannot install without sudo (running in non-interactive mode)."
378
+ warn "Run 'sshift-install.sh' from a terminal to install."
379
+ install_rc=1
375
380
  else
376
- sudo npm install -g @lethevimlet/sshift
381
+ sudo npm install -g @lethevimlet/sshift || install_rc=$?
377
382
  fi
378
383
 
379
- if [ $? -eq 0 ]; then
384
+ if [ $install_rc -eq 0 ]; then
380
385
  success "sshift installed successfully"
381
386
  else
382
387
  error "Failed to install sshift"
388
+ return 1
383
389
  fi
384
390
  }
385
391
 
@@ -390,18 +396,24 @@ update_sshift() {
390
396
  stop_app
391
397
  fi
392
398
 
399
+ local update_rc=0
393
400
  if [ "$(id -u)" -eq 0 ]; then
394
- npm update -g @lethevimlet/sshift
401
+ npm update -g @lethevimlet/sshift || update_rc=$?
395
402
  elif [ -w /usr/lib/node_modules ] 2>/dev/null || [ -w /usr/local/lib/node_modules ] 2>/dev/null; then
396
- npm update -g @lethevimlet/sshift
403
+ npm update -g @lethevimlet/sshift || update_rc=$?
404
+ elif [ -n "$SSHIFT_NO_SUDO" ] && [ "$SSHIFT_NO_SUDO" = "1" ]; then
405
+ warn "Cannot update without sudo (running in non-interactive mode)."
406
+ warn "Run 'sshift-install.sh --update' from a terminal to update."
407
+ update_rc=1
397
408
  else
398
- sudo npm update -g @lethevimlet/sshift
409
+ sudo npm update -g @lethevimlet/sshift || update_rc=$?
399
410
  fi
400
411
 
401
- if [ $? -eq 0 ]; then
412
+ if [ $update_rc -eq 0 ]; then
402
413
  success "sshift updated successfully"
403
414
  else
404
415
  error "Failed to update sshift"
416
+ return 1
405
417
  fi
406
418
  }
407
419
 
@@ -907,6 +919,24 @@ main() {
907
919
 
908
920
  info "Updating sshift..."
909
921
  update_sshift
922
+ update_result=$?
923
+
924
+ # Restart the app if .restart-after-update marker exists (triggered from UI)
925
+ # Always check markers regardless of update result to ensure cleanup
926
+ if [ -f "$INSTALL_DIR/.restart-after-update" ]; then
927
+ rm -f "$INSTALL_DIR/.restart-after-update"
928
+ rm -f "$INSTALL_DIR/.updating"
929
+ if [ $update_result -eq 0 ]; then
930
+ info "Restarting sshift..."
931
+ start_app
932
+ else
933
+ warn "Update failed, restarting with previous version..."
934
+ start_app
935
+ fi
936
+ elif [ -f "$INSTALL_DIR/.updating" ]; then
937
+ rm -f "$INSTALL_DIR/.updating"
938
+ fi
939
+
910
940
  print_summary
911
941
  exit 0
912
942
  ;;