@lethevimlet/sshift 0.9.7 → 0.9.9

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.7",
3
+ "version": "0.9.9",
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();
@@ -45,7 +45,8 @@ const defaultConfig = {
45
45
 
46
46
  /**
47
47
  * Ensure a config file exists. If no config is found in any search path,
48
- * create config.json in the package root using env var overrides or defaults.
48
+ * create config.json at the user install directory (~/.local/share/sshift/.env/config.json)
49
+ * so it survives npm updates (which replace the package directory).
49
50
  * This mirrors the installer create_config behavior.
50
51
  */
51
52
  function ensureConfig() {
@@ -55,7 +56,11 @@ function ensureConfig() {
55
56
  }
56
57
  }
57
58
 
58
- const configPath = path.join(PACKAGE_DIR, 'config.json');
59
+ const configDir = path.join(USER_INSTALL_DIR, '.env');
60
+ if (!fs.existsSync(configDir)) {
61
+ fs.mkdirSync(configDir, { recursive: true });
62
+ }
63
+ const configPath = path.join(configDir, 'config.json');
59
64
  const config = { ...defaultConfig };
60
65
 
61
66
  if (process.env.PORT) {
@@ -85,8 +90,8 @@ function getConfigPath() {
85
90
  }
86
91
  }
87
92
 
88
- // Return default path (first user install directory)
89
- const defaultPath = ENV_CONFIG_PATHS[0];
93
+ // Return default path (user install directory, survives npm updates)
94
+ const defaultPath = path.join(USER_INSTALL_DIR, '.env', 'config.json');
90
95
  console.log('[CONFIG] Using default path:', defaultPath);
91
96
  return defaultPath;
92
97
  }
@@ -269,19 +274,32 @@ function getKeyPath() {
269
274
 
270
275
  /**
271
276
  * Get the data directory for persistent storage (SSL certs, etc.)
272
- * Searches the same paths as config to find a writable data directory.
277
+ * Always returns the user-space directory so certs survive npm updates.
273
278
  * @returns {string} Path to data directory
274
279
  */
275
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() {
276
290
  const configPath = getConfigPath();
277
291
  const configDir = path.dirname(configPath);
278
-
279
- // If config is in a .env subdirectory, use parent
292
+
280
293
  if (path.basename(configDir) === '.env') {
281
- 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;
282
300
  }
283
-
284
- return configDir;
301
+
302
+ return null;
285
303
  }
286
304
 
287
305
  function hashPassword(password) {
@@ -331,9 +349,11 @@ module.exports = {
331
349
  getCertPath,
332
350
  getKeyPath,
333
351
  getDataDir,
352
+ getLegacyDataDir,
334
353
  hashPassword,
335
354
  isPasswordSet,
336
355
  verifyPassword,
337
356
  setPassword,
338
- removePassword
357
+ removePassword,
358
+ USER_INSTALL_DIR
339
359
  };
@@ -3540,8 +3540,11 @@ const wheelHandler = (e) => {
3540
3540
  let state = data.state;
3541
3541
  if (data.encoded) {
3542
3542
  try {
3543
- // Decode base64 to utf-8 string
3544
- state = atob(data.state);
3543
+ // Decode base64 to UTF-8 string (atob produces Latin-1 binary;
3544
+ // we must re-decode as UTF-8 to preserve multi-byte characters)
3545
+ const binaryString = atob(data.state);
3546
+ const bytes = Uint8Array.from(binaryString, c => c.charCodeAt(0));
3547
+ state = new TextDecoder().decode(bytes);
3545
3548
  console.log('[SSHIFT] Decoded base64 state, size:', state.length);
3546
3549
  } catch (e) {
3547
3550
  console.error('[SSHIFT] Error decoding base64 state:', e);
@@ -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
 
@@ -562,40 +561,60 @@ function New-Config {
562
561
  $configFile = Join-Path $envDir "config.json"
563
562
  $port = if ($ServerPort -ne "") { $ServerPort } else { "8022" }
564
563
 
565
- $configContent = @"
566
- {
567
- "port": $port,
568
- "devPort": 3000,
569
- "bind": "0.0.0.0",
570
- "enableHttps": true,
571
- "sticky": true,
572
- "sshKeepaliveInterval": 15000,
573
- "sshKeepaliveCountMax": 500,
574
- "bookmarks": [],
575
- "folders": []
576
- }
577
- "@
578
-
579
- # Write config to user install directory (preferred by updated config loader)
580
- $configContent | Out-File -FilePath $configFile -Encoding ASCII
564
+ # Merge default values into existing config:
565
+ # - Preserves user's existing values
566
+ # - Adds new default properties from newer versions
567
+ # - If -port was explicitly set, overrides the port value
568
+ $defaults = @{
569
+ port = [int]$port
570
+ devPort = 3000
571
+ bind = "0.0.0.0"
572
+ enableHttps = $true
573
+ sticky = $true
574
+ sshKeepaliveInterval = 15000
575
+ sshKeepaliveCountMax = 500
576
+ bookmarks = @()
577
+ folders = @()
578
+ }
581
579
 
582
- # Also write config to the npm package directory so the older config loader finds it
583
- $sshiftPath = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
584
- if ($sshiftPath) {
585
- # sshift is typically at <npm_prefix>\sshift.cmd, package dir is <npm_prefix>\node_modules\@lethevimlet\sshift
586
- $npmPrefix = npm config get prefix 2>$null
587
- if ($npmPrefix) {
588
- $pkgDir = Join-Path $npmPrefix "node_modules\@lethevimlet\sshift"
589
- if (Test-Path $pkgDir) {
590
- $pkgEnvDir = Join-Path $pkgDir ".env"
591
- New-Item -ItemType Directory -Force -Path $pkgEnvDir | Out-Null
592
- $configContent | Out-File -FilePath (Join-Path $pkgEnvDir "config.json") -Encoding ASCII
593
- $configContent | Out-File -FilePath (Join-Path $pkgDir "config.json") -Encoding ASCII
594
- }
580
+ $wasNew = $true
581
+ if (Test-Path $configFile) {
582
+ try {
583
+ $existing = Get-Content $configFile -Raw | ConvertFrom-Json
584
+ $wasNew = $false
585
+ } catch {
586
+ Write-Warning "Could not parse existing config, using defaults"
587
+ $existing = [PSCustomObject]@{}
595
588
  }
589
+ } else {
590
+ $existing = [PSCustomObject]@{}
591
+ }
592
+
593
+ # Build merged config: start with defaults, overlay existing values
594
+ $merged = [PSCustomObject]@{}
595
+ foreach ($key in $defaults.Keys) {
596
+ $merged | Add-Member -NotePropertyName $key -NotePropertyValue $defaults[$key] -Force
597
+ }
598
+ foreach ($prop in $existing.PSObject.Properties) {
599
+ $merged | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $prop.Value -Force
600
+ }
601
+
602
+ # If -port was explicitly set, override the port value
603
+ if ($ServerPort -ne "") {
604
+ $merged.port = [int]$ServerPort
596
605
  }
597
606
 
598
- Write-Success "Configuration created with HTTPS enabled on port $port"
607
+ # Write merged config
608
+ $merged | ConvertTo-Json -Depth 10 | Set-Content -Path $configFile -Encoding ASCII
609
+
610
+ if ($wasNew) {
611
+ Write-Info "Configuration created at $configFile"
612
+ } else {
613
+ Write-Info "Existing configuration merged with defaults at $configFile"
614
+ }
615
+
616
+ $effectivePort = $merged.port
617
+ Write-Success "Configuration created with HTTPS enabled on port $effectivePort"
599
618
  }
600
619
 
601
620
  # Add to PATH
@@ -1005,6 +1024,23 @@ function Main {
1005
1024
 
1006
1025
  Update-Sshift
1007
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
+
1008
1044
  Show-Summary
1009
1045
 
1010
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
 
@@ -411,49 +423,44 @@ create_config() {
411
423
  mkdir -p "$INSTALL_DIR/.env"
412
424
 
413
425
  local port="${SERVER_PORT:-8022}"
414
- local config_content="{
415
- \"port\": $port,
416
- \"devPort\": 3000,
417
- \"bind\": \"0.0.0.0\",
418
- \"enableHttps\": true,
419
- \"sticky\": true,
420
- \"sshKeepaliveInterval\": 15000,
421
- \"sshKeepaliveCountMax\": 500,
422
- \"bookmarks\": [],
423
- \"folders\": []
424
- }"
425
-
426
- # Write config to user install directory (preferred by updated config loader)
427
- echo "$config_content" > "$INSTALL_DIR/.env/config.json"
428
-
429
- # Also write config to the npm package directory so the older config loader finds it
430
- local sshift_bin_path=$(which sshift 2>/dev/null)
431
- if [ -n "$sshift_bin_path" ]; then
432
- local real_path="$sshift_bin_path"
433
- # Resolve symlinks portably (readlink -f is not available on macOS BSD)
434
- while [ -L "$real_path" ]; do
435
- local target=$(readlink "$real_path" 2>/dev/null)
436
- if [ -z "$target" ]; then break; fi
437
- # Handle relative symlinks
438
- case "$target" in
439
- /*) real_path="$target" ;;
440
- *) real_path="$(dirname "$real_path")/$target" ;;
441
- esac
442
- done
443
- local pkg_dir=$(dirname "$real_path")
444
- if [ -d "$pkg_dir" ]; then
445
- if mkdir -p "$pkg_dir/.env" 2>/dev/null; then
446
- echo "$config_content" > "$pkg_dir/.env/config.json"
447
- echo "$config_content" > "$pkg_dir/config.json"
448
- else
449
- # Package directory may be root-owned (e.g. Homebrew npm global installs on macOS)
450
- # The user-space config at INSTALL_DIR is already written, so this is just a
451
- # backwards-compat fallback — skip silently if we lack permissions.
452
- warn "Cannot write to package directory $pkg_dir (permission denied). Using config at $INSTALL_DIR/.env/config.json instead."
453
- fi
454
- fi
426
+ local config_file="$INSTALL_DIR/.env/config.json"
427
+
428
+ # Merge default values into existing config:
429
+ # - Preserves user's existing values
430
+ # - Adds new default properties from newer versions
431
+ # - If --port was explicitly set, overrides the port value
432
+ local port_override=""
433
+ if [ -n "$SERVER_PORT" ]; then
434
+ port_override="$SERVER_PORT"
435
+ fi
436
+
437
+ local config_action
438
+ config_action=$(node -e "
439
+ const fs = require('fs');
440
+ const defaults = {port: $port, devPort: 3000, bind: '0.0.0.0', enableHttps: true, sticky: true, sshKeepaliveInterval: 15000, sshKeepaliveCountMax: 500, bookmarks: [], folders: []};
441
+ const configPath = '$config_file';
442
+ let existing = {};
443
+ let wasNew = true;
444
+ if (fs.existsSync(configPath)) {
445
+ try { existing = JSON.parse(fs.readFileSync(configPath, 'utf8')); wasNew = false; } catch(e) { process.stderr.write('Warning: Could not parse existing config, using defaults\n'); }
446
+ }
447
+ const merged = Object.assign({}, defaults, existing);
448
+ const portOverride = '$port_override';
449
+ if (portOverride) { merged.port = parseInt(portOverride); }
450
+ fs.writeFileSync(configPath, JSON.stringify(merged, null, 2) + '\n');
451
+ process.stdout.write(wasNew ? 'created' : 'merged');
452
+ " 2>&1) || config_action="created"
453
+
454
+ if [ "$config_action" = "merged" ]; then
455
+ info "Existing configuration merged with defaults at $config_file"
456
+ else
457
+ info "Configuration created at $config_file"
455
458
  fi
456
459
 
460
+ local effective_port=$(grep -oP '"port"\s*:\s*\K[0-9]+' "$config_file" 2>/dev/null | head -1)
461
+ if [ -n "$effective_port" ]; then
462
+ port="$effective_port"
463
+ fi
457
464
  success "Configuration created with HTTPS enabled on port $port"
458
465
  }
459
466
 
@@ -912,6 +919,24 @@ main() {
912
919
 
913
920
  info "Updating sshift..."
914
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
+
915
940
  print_summary
916
941
  exit 0
917
942
  ;;