@lethevimlet/sshift 1.0.5 → 1.0.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -17,6 +17,8 @@ const UPDATE_MARKER_FILE = '.updating';
17
17
  */
18
18
  function registerSystemEndpoints(app, io) {
19
19
  // Clean up stale update marker from previous update attempt
20
+ // NOTE: Do NOT delete the update log here — the client needs to read it
21
+ // to detect errors. The log is cleaned up separately after a short delay.
20
22
  const dataDir = getDataDir();
21
23
  const staleUpdateMarker = path.join(dataDir, UPDATE_MARKER_FILE);
22
24
  const staleUpdateScript = path.join(dataDir, '.sshift-update.sh');
@@ -36,7 +38,10 @@ function registerSystemEndpoints(app, io) {
36
38
  if (fs.existsSync(staleUpdateLog)) {
37
39
  const logContent = fs.readFileSync(staleUpdateLog, 'utf8');
38
40
  console.log('[UPDATE] Previous update log:\n' + logContent);
39
- fs.unlinkSync(staleUpdateLog);
41
+ // Delay log deletion so the client can read error status
42
+ setTimeout(() => {
43
+ try { fs.unlinkSync(staleUpdateLog); } catch (e) { /* ignore */ }
44
+ }, 30000);
40
45
  }
41
46
  } catch (e) {
42
47
  console.error('[UPDATE] Failed to clean up marker file:', e.message);
@@ -156,12 +161,17 @@ function registerSystemEndpoints(app, io) {
156
161
 
157
162
  // Check for update error log
158
163
  let updateError = null;
164
+ let updateLog = null;
159
165
  if (!isUpdating && fs.existsSync(updateLogPath)) {
160
166
  try {
161
167
  const logContent = fs.readFileSync(updateLogPath, 'utf8');
162
168
  if (logContent.includes('npm install failed')) {
163
169
  updateError = 'Update failed: npm install exited with an error.';
164
170
  }
171
+ // Return the last 4KB of the log for debugging
172
+ const lastLines = logContent.slice(-4096);
173
+ const relevantLines = lastLines.split('\n').filter(l => l.trim()).slice(-10);
174
+ updateLog = relevantLines.join('\n');
165
175
  } catch (e) {
166
176
  // Ignore log read errors
167
177
  }
@@ -171,7 +181,8 @@ function registerSystemEndpoints(app, io) {
171
181
  version,
172
182
  updating: isUpdating,
173
183
  ready: !isUpdating,
174
- updateError
184
+ updateError,
185
+ updateLog
175
186
  });
176
187
  });
177
188
 
@@ -291,53 +302,88 @@ function registerSystemEndpoints(app, io) {
291
302
  const updateScriptPath = path.join(dataDir, '.sshift-update.sh');
292
303
  const updateLogPath = path.join(dataDir, '.sshift-update.log');
293
304
 
305
+ // Build PATH for the update script to ensure npm and node are findable
306
+ const pathDirs = [];
307
+ if (process.env.PATH) pathDirs.push(...process.env.PATH.split(':'));
308
+ const nodeDir = path.dirname(process.execPath);
309
+ if (!pathDirs.includes(nodeDir)) pathDirs.unshift(nodeDir);
310
+ ['/usr/local/bin', '/usr/bin', '/usr/sbin', '/bin', '/sbin'].forEach((d) => {
311
+ if (!pathDirs.includes(d)) pathDirs.push(d);
312
+ });
313
+ const scriptPath = pathDirs.join(':');
314
+
294
315
  // Send response immediately, then update in background
295
316
  res.json({ message: 'Update started. Server will restart automatically.' });
296
317
 
297
318
  if (platform === 'win32') {
298
319
  const sshiftCmd = sshiftBinPath.includes(' ') ? `& '${sshiftBinPath}'` : `sshift`;
299
320
  const psScript = `$ErrorActionPreference = 'Continue'
321
+ $MarkerPath = '${updateMarker}'
322
+ $LogPath = '${updateLogPath}'
323
+ $NodeExe = '${nodeExe}'
324
+ $SshiftBin = '${sshiftBinPath}'
325
+
300
326
  try {
301
- & npm install -g @lethevimlet/sshift@latest 2>&1 | Out-File -FilePath '${updateLogPath}' -Append
327
+ & npm install -g @lethevimlet/sshift@latest 2>&1 | Out-File -FilePath $LogPath -Append
302
328
  if ($LASTEXITCODE -ne 0) {
303
- Write-Output 'npm install failed with exit code ' + $LASTEXITCODE | Out-File -FilePath '${updateLogPath}' -Append
329
+ Write-Output "npm install failed with exit code $LASTEXITCODE" | Out-File -FilePath $LogPath -Append
330
+ Remove-Item -Path $MarkerPath -Force -ErrorAction SilentlyContinue
331
+ & $NodeExe $SshiftBin
304
332
  exit 1
305
333
  }
306
334
  } catch {
307
- Write-Output $_.Exception.Message | Out-File -FilePath '${updateLogPath}' -Append
335
+ Write-Output $_.Exception.Message | Out-File -FilePath $LogPath -Append
336
+ Remove-Item -Path $MarkerPath -Force -ErrorAction SilentlyContinue
337
+ & $NodeExe $SshiftBin
308
338
  exit 1
309
339
  }
310
- Remove-Item -Path '${updateMarker}' -Force -ErrorAction SilentlyContinue
311
- & '${nodeExe}' '${sshiftBinPath}'
340
+ Remove-Item -Path $MarkerPath -Force -ErrorAction SilentlyContinue
341
+ & $NodeExe $SshiftBin
312
342
  `;
313
343
  const psScriptPath = updateScriptPath.replace('.sh', '.ps1');
314
344
  fs.writeFileSync(psScriptPath, psScript, 'utf8');
315
345
  } else {
316
346
  const updateScript = `#!/bin/sh
317
- set -e
318
347
  LOG="${updateLogPath}"
319
- echo "$(date): Starting sshift update..." > "$LOG"
320
-
321
- # Try npm install
348
+ MARKER="${updateMarker}"
322
349
  NPM_BIN="${npmBinPath}"
323
- echo "$(date): Using npm at: $NPM_BIN" >> "$LOG"
350
+ SSHIFT_FALLBACK="${sshiftBinPath}"
351
+ NODE_BIN="${nodeExe}"
352
+ OLD_VERSION="${oldVersion}"
353
+
354
+ echo "$(date): Starting sshift update (from v${oldVersion})..." > "$LOG"
355
+ echo "$(date): npm path: $NPM_BIN" >> "$LOG"
356
+ echo "$(date): node path: $NODE_BIN" >> "$LOG"
357
+ echo "$(date): sshift fallback: $SSHIFT_FALLBACK" >> "$LOG"
324
358
 
359
+ # Find the current sshift binary before npm changes anything
360
+ CURRENT_SSHIFT="$(command -v sshift 2>/dev/null || which sshift 2>/dev/null || echo "$SSHIFT_FALLBACK")"
361
+
362
+ # Run npm install
363
+ echo "$(date): Running npm install..." >> "$LOG"
325
364
  if ! "$NPM_BIN" install -g @lethevimlet/sshift@latest >> "$LOG" 2>&1; then
326
- echo "$(date): npm install failed, removing update marker" >> "$LOG"
327
- rm -f "${updateMarker}"
328
- exit 1
365
+ echo "$(date): npm install failed" >> "$LOG"
366
+ echo "npm install failed" >> "$LOG"
367
+ rm -f "$MARKER"
368
+ # Always restart the server — the old version is still installed
369
+ echo "$(date): Restarting sshift (old version) from: $CURRENT_SSHIFT" >> "$LOG"
370
+ exec "$NODE_BIN" "$CURRENT_SSHIFT"
329
371
  fi
330
-
331
372
  echo "$(date): npm install completed successfully" >> "$LOG"
332
373
 
333
- # Remove the update marker before restart so the new instance sees a clean state
334
- rm -f "${updateMarker}"
374
+ # Remove the update marker before restart
375
+ rm -f "$MARKER"
335
376
 
336
377
  # Find the sshift binary — prefer PATH lookup since npm just updated it
337
- SSHIFT_BIN="$(command -v sshift 2>/dev/null || which sshift 2>/dev/null || echo "${sshiftBinPath}")"
378
+ SSHIFT_BIN="$(command -v sshift 2>/dev/null || which sshift 2>/dev/null || echo "$SSHIFT_FALLBACK")"
379
+ if [ ! -x "$SSHIFT_BIN" ]; then
380
+ echo "$(date): ERROR: sshift binary not found or not executable at: $SSHIFT_BIN" >> "$LOG"
381
+ echo "$(date): Attempting to restart with fallback path" >> "$LOG"
382
+ SSHIFT_BIN="$SSHIFT_FALLBACK"
383
+ fi
338
384
 
339
385
  echo "$(date): Restarting sshift from: $SSHIFT_BIN" >> "$LOG"
340
- exec "${nodeExe}" "$SSHIFT_BIN"
386
+ exec "$NODE_BIN" "$SSHIFT_BIN"
341
387
  `;
342
388
  fs.writeFileSync(updateScriptPath, updateScript, 'utf8');
343
389
  fs.chmodSync(updateScriptPath, 0o755);
@@ -358,11 +404,14 @@ exec "${nodeExe}" "$SSHIFT_BIN"
358
404
  spawnArgs = [updateScriptPath];
359
405
  }
360
406
 
407
+ const updateEnv = { ...process.env };
408
+ updateEnv.PATH = scriptPath;
409
+
361
410
  const updateProcess = spawn(spawnCommand, spawnArgs, {
362
411
  cwd: dataDir,
363
412
  detached: true,
364
413
  stdio: 'ignore',
365
- env: { ...process.env }
414
+ env: updateEnv
366
415
  });
367
416
 
368
417
  updateProcess.on('error', (err) => {
@@ -295,19 +295,18 @@ async function initializeServer() {
295
295
  next();
296
296
  });
297
297
 
298
- // Serve static files from the webapp directory
299
298
  const webappPath = path.join(__dirname, '../webapp');
300
- app.use(express.static(webappPath));
301
- app.use('/js', express.static(path.join(webappPath, 'js')));
302
- app.use('/css', express.static(path.join(webappPath, 'css')));
303
- app.use('/libs', express.static(path.join(webappPath, 'libs')));
304
- app.use('/tests', express.static(path.join(webappPath, 'tests')));
305
299
 
306
300
  // Service Worker script - must be served from root with proper headers
307
- // Version placeholder is replaced dynamically so the cache busts on each update
301
+ // MUST come before express.static so version placeholders are replaced
302
+ // and no-cache headers are set. Without this, express.static serves
303
+ // the raw file with __VERSION__ unreplaced and default cache headers,
304
+ // completely breaking cache busting on updates.
308
305
  app.get('/sw.js', (req, res) => {
309
306
  res.setHeader('Content-Type', 'application/javascript');
310
307
  res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
308
+ res.setHeader('Pragma', 'no-cache');
309
+ res.setHeader('Expires', '0');
311
310
  res.setHeader('Service-Worker-Allowed', '/');
312
311
  const swPath = path.join(webappPath, 'sw.js');
313
312
  fs.readFile(swPath, 'utf8', (err, data) => {
@@ -318,7 +317,9 @@ async function initializeServer() {
318
317
  });
319
318
 
320
319
  // Main route - no-cache so browser always checks for updates
321
- // Version placeholder is replaced dynamically for cache-busting
320
+ // MUST come before express.static so version placeholders are replaced
321
+ // and no-cache headers are set. Without this, express.static serves
322
+ // the raw index.html with __VERSION__ unreplaced.
322
323
  app.get('/', (req, res) => {
323
324
  res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
324
325
  res.setHeader('Pragma', 'no-cache');
@@ -331,6 +332,41 @@ async function initializeServer() {
331
332
  });
332
333
  });
333
334
 
335
+ // Serve static files from the webapp directory
336
+ // These come AFTER the custom / and /sw.js handlers so those routes
337
+ // can set proper cache headers and replace version placeholders.
338
+ app.use(express.static(webappPath, {
339
+ maxAge: '1d',
340
+ setHeaders: (res, filePath) => {
341
+ if (filePath.endsWith('.html')) {
342
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
343
+ res.setHeader('Pragma', 'no-cache');
344
+ res.setHeader('Expires', '0');
345
+ } else if (filePath.endsWith('.js') || filePath.endsWith('.css')) {
346
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
347
+ }
348
+ }
349
+ }));
350
+ app.use('/js', express.static(path.join(webappPath, 'js'), {
351
+ maxAge: '1d',
352
+ setHeaders: (res) => {
353
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
354
+ }
355
+ }));
356
+ app.use('/css', express.static(path.join(webappPath, 'css'), {
357
+ maxAge: '1d',
358
+ setHeaders: (res) => {
359
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
360
+ }
361
+ }));
362
+ app.use('/libs', express.static(path.join(webappPath, 'libs'), {
363
+ maxAge: '1d',
364
+ setHeaders: (res) => {
365
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
366
+ }
367
+ }));
368
+ app.use('/tests', express.static(path.join(webappPath, 'tests')));
369
+
334
370
  // Register REST endpoints
335
371
  rest.registerAllRestEndpoints(app, io);
336
372
 
@@ -10440,7 +10440,8 @@ async syncTabsFromServer(tabs) {
10440
10440
 
10441
10441
  // Check for update error from server
10442
10442
  if (data.updateError) {
10443
- this.handleUpdateError(data.updateError);
10443
+ const logMsg = data.updateLog ? '\n\n' + data.updateLog : '';
10444
+ this.handleUpdateError(data.updateError + logMsg);
10444
10445
  return;
10445
10446
  }
10446
10447
 
@@ -10476,9 +10477,8 @@ async syncTabsFromServer(tabs) {
10476
10477
  statusEl.textContent = `New version: ${data.version}`;
10477
10478
  }
10478
10479
 
10479
- // Reload page after a short delay
10480
10480
  setTimeout(() => {
10481
- window.location.reload();
10481
+ this.forceReloadAfterUpdate();
10482
10482
  }, 1000);
10483
10483
  } else if (data.ready && data.version === oldVersion) {
10484
10484
  // Server is back and ready. Same version could mean:
@@ -10498,7 +10498,7 @@ async syncTabsFromServer(tabs) {
10498
10498
  }
10499
10499
 
10500
10500
  setTimeout(() => {
10501
- window.location.reload();
10501
+ this.forceReloadAfterUpdate();
10502
10502
  }, 1000);
10503
10503
  } else {
10504
10504
  // Unexpected state
@@ -10549,6 +10549,19 @@ async syncTabsFromServer(tabs) {
10549
10549
  updateBtn.innerHTML = '<i class="fas fa-download"></i> Update';
10550
10550
  }
10551
10551
  }
10552
+
10553
+ forceReloadAfterUpdate() {
10554
+ const cleanup = [];
10555
+ if ('caches' in window) {
10556
+ cleanup.push(caches.keys().then((names) => Promise.all(names.map((name) => caches.delete(name)))));
10557
+ }
10558
+ if ('serviceWorker' in navigator) {
10559
+ cleanup.push(navigator.serviceWorker.getRegistrations().then((regs) => Promise.all(regs.map((r) => r.unregister()))));
10560
+ }
10561
+ Promise.all(cleanup).catch(() => {}).finally(() => {
10562
+ window.location.href = window.location.origin + window.location.pathname + '?v=' + Date.now();
10563
+ });
10564
+ }
10552
10565
  }
10553
10566
 
10554
10567
  // Initialize application
package/src/webapp/sw.js CHANGED
@@ -1,13 +1,16 @@
1
1
  const CACHE_NAME = 'sshift-__VERSION__';
2
+ const VERSION = '__VERSION__';
2
3
 
3
4
  const PRECACHE_URLS = [
4
- '/css/style.css',
5
- '/libs/xterm/xterm.css',
6
- '/libs/font-awesome/css/all.min.css',
7
- '/libs/lucide/lucide.min.js',
8
- '/manifest.json'
5
+ '/css/style.css?v=' + VERSION,
6
+ '/libs/xterm/xterm.css?v=' + VERSION,
7
+ '/libs/font-awesome/css/all.min.css?v=' + VERSION,
8
+ '/libs/lucide/lucide.min.js?v=' + VERSION,
9
+ '/manifest.json?v=' + VERSION
9
10
  ];
10
11
 
12
+ const NAV_CACHE = CACHE_NAME + '-nav';
13
+
11
14
  self.addEventListener('install', (event) => {
12
15
  event.waitUntil(
13
16
  caches.open(CACHE_NAME).then((cache) => {
@@ -28,7 +31,7 @@ self.addEventListener('activate', (event) => {
28
31
  caches.keys().then((cacheNames) =>
29
32
  Promise.all(
30
33
  cacheNames
31
- .filter((name) => name !== CACHE_NAME)
34
+ .filter((name) => name !== CACHE_NAME && name !== NAV_CACHE)
32
35
  .map((name) => caches.delete(name))
33
36
  )
34
37
  )
@@ -41,10 +44,11 @@ self.addEventListener('fetch', (event) => {
41
44
 
42
45
  const url = new URL(event.request.url);
43
46
 
44
- if (url.protocol === 'http:' || url.protocol === 'https:') {
45
- if (url.pathname.startsWith('/socket.io/')) return;
46
- if (url.pathname.startsWith('/api/')) return;
47
- }
47
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return;
48
+
49
+ if (url.pathname.startsWith('/socket.io/')) return;
50
+ if (url.pathname.startsWith('/api/')) return;
51
+ if (url.pathname === '/sw.js') return;
48
52
 
49
53
  const isNavigation = event.request.mode === 'navigate';
50
54
 
@@ -54,7 +58,7 @@ self.addEventListener('fetch', (event) => {
54
58
  .then((response) => {
55
59
  if (response && response.status === 200) {
56
60
  const clone = response.clone();
57
- caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
61
+ caches.open(NAV_CACHE).then((cache) => cache.put(event.request, clone));
58
62
  }
59
63
  return response;
60
64
  })
@@ -65,15 +69,26 @@ self.addEventListener('fetch', (event) => {
65
69
 
66
70
  event.respondWith(
67
71
  caches.match(event.request).then((cached) => {
68
- const fetched = fetch(event.request).then((response) => {
72
+ if (cached) {
73
+ return cached;
74
+ }
75
+ return fetch(event.request).then((response) => {
69
76
  if (response && response.status === 200 && response.type === 'basic') {
70
77
  const clone = response.clone();
71
78
  caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
72
79
  }
73
80
  return response;
74
- }).catch(() => cached);
75
-
76
- return cached || fetched;
81
+ });
77
82
  })
78
83
  );
84
+ });
85
+
86
+ self.addEventListener('message', (event) => {
87
+ if (event.data && event.data.type === 'CLEAR_CACHES') {
88
+ caches.keys().then((names) => {
89
+ for (const name of names) {
90
+ caches.delete(name);
91
+ }
92
+ });
93
+ }
79
94
  });