@lethevimlet/sshift 1.4.9 → 1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.4.9",
3
+ "version": "1.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": {
@@ -104,12 +104,19 @@ function registerSSHHandlers(socket, io) {
104
104
  console.log('[SSH] ssh-request-sync event received for session:', data.sessionId);
105
105
 
106
106
  // Rate-limit per session to prevent abuse / accidental DoS.
107
+ // NOTE: this emits an `ssh-error` with `advisory: true` so the
108
+ // client's ssh-error handler can distinguish a soft advisory from
109
+ // a hard connection failure (which would warrant closing the tab).
110
+ // Without the `advisory: true` flag, the client would
111
+ // `closeTab()` on every rate-limited sync — killing the very tab
112
+ // the user was trying to refresh.
107
113
  const now = Date.now();
108
114
  const last = _syncLastSent.get(data.sessionId) || 0;
109
115
  if ((now - last) < SYNC_RATE_LIMIT_MS) {
110
116
  socket.emit('ssh-error', {
111
117
  sessionId: data.sessionId,
112
- message: 'Sync rate limit reached, please wait'
118
+ message: 'Sync rate limit reached, please wait',
119
+ advisory: true
113
120
  });
114
121
  return;
115
122
  }
@@ -145,7 +152,8 @@ function registerSSHHandlers(socket, io) {
145
152
  console.warn(`[SSH] ssh-data: invalid payload type from socket ${socket.id}`);
146
153
  socket.emit('ssh-error', {
147
154
  sessionId: data.sessionId,
148
- message: 'Invalid input payload'
155
+ message: 'Invalid input payload',
156
+ advisory: true
149
157
  });
150
158
  return;
151
159
  }
@@ -155,7 +163,8 @@ function registerSSHHandlers(socket, io) {
155
163
  console.error(`[SSH] ssh-data: write failed for ${data.sessionId}:`, err.message);
156
164
  socket.emit('ssh-error', {
157
165
  sessionId: data.sessionId,
158
- message: 'Failed to write input: ' + err.message
166
+ message: 'Failed to write input: ' + err.message,
167
+ advisory: true
159
168
  });
160
169
  }
161
170
  });
@@ -203,7 +212,8 @@ function registerSSHHandlers(socket, io) {
203
212
  console.warn(`[SSH] ssh-resize: invalid dimensions (${data.cols}x${data.rows}) from socket ${socket.id}`);
204
213
  socket.emit('ssh-error', {
205
214
  sessionId: data.sessionId,
206
- message: `Invalid terminal dimensions: ${data.cols}x${data.rows}`
215
+ message: `Invalid terminal dimensions: ${data.cols}x${data.rows}`,
216
+ advisory: true
207
217
  });
208
218
  return;
209
219
  }
@@ -213,7 +223,8 @@ function registerSSHHandlers(socket, io) {
213
223
  console.error(`[SSH] ssh-resize: resize failed for ${data.sessionId}:`, err.message);
214
224
  socket.emit('ssh-error', {
215
225
  sessionId: data.sessionId,
216
- message: 'Failed to resize: ' + err.message
226
+ message: 'Failed to resize: ' + err.message,
227
+ advisory: true
217
228
  });
218
229
  return;
219
230
  }
@@ -571,12 +571,13 @@ class SSHManager {
571
571
  if (session.writeQueue.length >= 64) {
572
572
  console.warn(`[SSH] writeQueue overflow for ${sessionId}; dropping ${session.writeQueue.length} queued chunks`);
573
573
  session.writeQueue = [];
574
- if (this.io) {
575
- this.io.to(`session-${sessionId}`).emit('ssh-error', {
576
- sessionId,
577
- message: 'bufferFull'
578
- });
579
- }
574
+ if (this.io) {
575
+ this.io.to(`session-${sessionId}`).emit('ssh-error', {
576
+ sessionId,
577
+ message: 'bufferFull',
578
+ advisory: true
579
+ });
580
+ }
580
581
  return;
581
582
  }
582
583
  session.writeQueue.push(data);
@@ -2743,13 +2743,30 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2743
2743
  this.updateTerminalColorOverrideUI();
2744
2744
 
2745
2745
  // In sticky mode, the server is the single source of truth for tabs.
2746
- // Wait for the open-tabs event from the server instead of restoring from localStorage.
2747
- // Set a fallback timeout in case the server is unreachable.
2746
+ // We WAIT for the open-tabs event from the server instead of
2747
+ // restoring from localStorage. If the server is unreachable or
2748
+ // reports 0 active tabs (e.g. after a server restart), we treat it
2749
+ // as a fresh slate and DO NOT resurrect stale localStorage tabs —
2750
+ // the SSH sessions those tabs represented are GONE on the server,
2751
+ // so reopening them as fresh connections would silently spawn
2752
+ // duplicate sessions and confuse every other connected client.
2753
+ //
2754
+ // The 3s fallback below used to call restoreTabs() on timeout,
2755
+ // which auto-reconnected to all sessions in localStorage. That
2756
+ // behavior is removed: if the server doesn't respond within 3s we
2757
+ // just clear the stale localStorage cache so the next saveTabs()
2758
+ // doesn't re-broadcast it to other clients.
2748
2759
  if (this.sticky) {
2749
2760
  this._serverSyncTimeout = setTimeout(() => {
2750
2761
  if (!this._initialSyncDone) {
2751
- console.log('[SSHIFT] Server tabs not received within timeout, falling back to localStorage');
2752
- this.restoreTabs();
2762
+ console.warn('[SSHIFT] Server tabs not received within 3s timeout — starting with a fresh slate.');
2763
+ // Clear any stale localStorage tab cache so a future saveTabs
2764
+ // doesn't broadcast dead sessions to other clients.
2765
+ try { this.clearTabs(); } catch (_) {}
2766
+ // Drop the wait flag so any pending syncTabsFromServer busy-wait
2767
+ // doesn't block forever (it watches `this.isRestoring`).
2768
+ this.isRestoring = false;
2769
+ this._initialSyncDone = true;
2753
2770
  }
2754
2771
  }, 3000);
2755
2772
  }
@@ -2795,7 +2812,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2795
2812
  }
2796
2813
  this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel);
2797
2814
  } else {
2798
- this.restoreTabs();
2815
+ // Server has no tabs (e.g. right after restart). Treat it as a
2816
+ // fresh slate: clear stale localStorage and DO NOT resurrect
2817
+ // those sessions — they're gone on the server.
2818
+ if (pendingData.layout && !this.isMobile) {
2819
+ this.setLayoutFromServer(pendingData.layout);
2820
+ }
2821
+ try { this.clearTabs(); } catch (_) {}
2799
2822
  }
2800
2823
  } finally {
2801
2824
  this.isSyncingTabs = wasSyncingTabs;
@@ -3653,113 +3676,30 @@ const wheelHandler = (e) => {
3653
3676
  }
3654
3677
 
3655
3678
  async restoreTabs() {
3656
- // If server tabs have already been synced, skip localStorage restore
3657
- // This prevents duplication when the server responded before the fallback timeout
3658
- if (this._initialSyncDone) {
3659
- console.log('[SSHIFT] Server tabs already synced, skipping localStorage restore');
3660
- return;
3661
- }
3662
-
3663
- const savedData = this.loadTabs();
3664
-
3665
- // Handle both old format (array) and new format (object with tabs and layout)
3666
- const savedTabs = Array.isArray(savedData) ? savedData : (savedData?.tabs || []);
3667
- const savedLayout = !Array.isArray(savedData) ? savedData?.layout : null;
3668
-
3669
- if (!savedTabs || savedTabs.length === 0) {
3670
- console.log('[SSHIFT] No tabs to restore');
3671
- return;
3672
- }
3673
-
3674
- console.log('[SSHIFT] Restoring', savedTabs.length, 'tabs');
3675
- console.log('[SSHIFT] sticky:', this.sticky, 'layout:', savedLayout);
3676
-
3677
- // Set restoring flag to prevent saving during restoration
3678
- this.isRestoring = true;
3679
-
3680
- // Wait for socket to be connected
3681
- if (!this.socket.connected) {
3682
- await new Promise(resolve => {
3683
- this.socket.once('connect', resolve);
3684
- setTimeout(resolve, 1000); // Timeout after 1s
3685
- });
3686
- }
3687
-
3688
- // Map old savedTab.sessionId -> freshly-created sessionId so the active
3689
- // highlight resolves against the new session id (not the pre-restart id
3690
- // which no longer exists on the server).
3691
- const savedToFresh = new Map();
3692
- let activeSavedId = null;
3693
-
3694
- // Restore each session
3695
- for (const savedTab of savedTabs) {
3696
- // Stop restoring if server tabs have been synced (open-tabs arrived while we were restoring)
3697
- if (this._initialSyncDone) {
3698
- console.log('[SSHIFT] Server tabs received during restore, stopping localStorage restore');
3699
- break;
3700
- }
3701
-
3702
- console.log('[SSHIFT] Restoring tab:', savedTab.name, savedTab.type);
3703
-
3704
- let freshSessionId = null;
3705
- // restoreTabs() is only called when the server has no active sessions
3706
- // (e.g. server restart), so we must create new connections, not join.
3707
- const restoreSessionId = null;
3708
-
3709
- if (savedTab.type === 'ssh') {
3710
- freshSessionId = this.createSSHTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3711
- } else if (savedTab.type === 'sftp') {
3712
- freshSessionId = this.createSFTPTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3713
- }
3714
-
3715
- if (freshSessionId) {
3716
- savedToFresh.set(savedTab.sessionId, freshSessionId);
3717
- }
3718
-
3719
- // Track the active saved id; resolve to the fresh id below
3720
- if (savedTab.active) {
3721
- activeSavedId = savedTab.sessionId;
3722
- }
3723
-
3724
- // Small delay between sessions
3725
- await new Promise(resolve => setTimeout(resolve, 100));
3726
- }
3727
-
3728
- // Restore active session using the freshly-minted sessionId
3729
- if (activeSavedId) {
3730
- const freshActiveId = savedToFresh.get(activeSavedId);
3731
- if (freshActiveId) {
3732
- setTimeout(() => {
3733
- console.log('[SSHIFT] Restoring active session (fresh id):', freshActiveId);
3734
- const savedTab = savedTabs.find(t => t.sessionId === activeSavedId);
3735
- const panelId = savedTab?.panelId || this.getPanelForSession(freshActiveId);
3736
- this.switchTab(freshActiveId, panelId);
3737
- }, 500);
3738
- }
3739
- }
3740
-
3741
- // Restore layout if saved, or use current layout
3742
- if (this.currentLayout) {
3743
- const layoutToApply = (savedLayout && this.layouts)
3744
- ? this.layouts.find(l => l.id === savedLayout) || this.currentLayout
3745
- : this.currentLayout;
3746
-
3747
- console.log('[SSHIFT] Applying layout after restoration:', layoutToApply.id);
3748
- // Pass savedTabs to applyLayout which will handle distribution
3749
- this.applyLayout(layoutToApply, savedTabs);
3750
- }
3751
-
3752
- // Update mobile tabs Dropdown after restoration
3753
- this.updateMobileTabsDropdown();
3754
-
3755
- // Apply any flash states that arrived before DOM elements existed
3756
- this.applyFlashStates();
3757
-
3758
- // Clear restoring flag after restoration is complete
3679
+ /**
3680
+ * DEPRECATED — server restart now produces a fresh slate with
3681
+ * 0 active sessions (no localStorage-based tab reconstruction).
3682
+ *
3683
+ * The previous behavior auto-SSH-connected to every tab the user
3684
+ * had open before the restart. Because the underlying SSH
3685
+ * sessions are GONE on the server, this silently spawned brand-
3686
+ * new SSH connections AND broadcast them to every other client
3687
+ * as if they were the original sessions — confusing sticky
3688
+ * state across devices. The user-visible contract is now: server
3689
+ * restart = blank client.
3690
+ *
3691
+ * Former call sites now invoke clearTabs() to drop the stale
3692
+ * localStorage cache and start empty. This method remains as a
3693
+ * no-op for any external callers (legacy extensions, plugins) so
3694
+ * they don't accidentally resurrect sessions.
3695
+ */
3696
+ console.log('[SSHIFT] restoreTabs() is deprecated — clearing stale localStorage cache.');
3697
+ try { this.clearTabs(); } catch (_) {}
3759
3698
  this.isRestoring = false;
3699
+ this._initialSyncDone = true;
3760
3700
  }
3761
3701
 
3762
- // Legacy method for backwards compatibility
3702
+ // Legacy method for backwards compatibility
3763
3703
  async restoreStickySessions() {
3764
3704
  return this.restoreTabs();
3765
3705
  }
@@ -3888,13 +3828,17 @@ const wheelHandler = (e) => {
3888
3828
  }
3889
3829
  this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel);
3890
3830
  } else if (!this._initialSyncDone) {
3891
- // Server has no tabs and this is the first sync (e.g. server restart).
3892
- // Still apply layout from server even with no tabs.
3831
+ // Server has no tabs and this is the first sync. This is the
3832
+ // post-restart / fresh-install / single-client-with-no-sessions
3833
+ // case. Per the user contract, a server restart = new slate:
3834
+ // we do NOT auto-reconnect stale localStorage tabs (those SSH
3835
+ // sessions are gone on the server, recreating them as new
3836
+ // connections silently spawns duplicates and confuses other
3837
+ // clients). Drop the stale cache and start fresh.
3893
3838
  if (data.layout && !this.isMobile) {
3894
3839
  this.setLayoutFromServer(data.layout);
3895
3840
  }
3896
- // Fall back to localStorage restore to reconnect sessions.
3897
- this.restoreTabs();
3841
+ try { this.clearTabs(); } catch (_) {}
3898
3842
  } else if (data.layout && !this.isMobile) {
3899
3843
  // No tabs change, but layout may have changed
3900
3844
  this.setLayoutFromServer(data.layout);
@@ -4516,11 +4460,25 @@ const wheelHandler = (e) => {
4516
4460
  } else {
4517
4461
  this.showToast(data.message, 'error');
4518
4462
  }
4463
+ } else if (data.advisory) {
4464
+ // Advisory errors (rate-limit, invalid payload, bufferFull, etc.)
4465
+ // are non-fatal — warn via toast but DO NOT close the tab. Closing
4466
+ // the tab on every rate-limited ssh-request-sync would kill the
4467
+ // very session the user was trying to refresh / switch to.
4468
+ console.warn('[SSHIFT] Advisory ssh-error (tab kept open):', data.message);
4469
+ this.showToast(data.message, 'warning');
4519
4470
  } else {
4520
4471
  this.showToast(data.message, 'error');
4521
4472
  }
4522
-
4523
- if (data.sessionId && data.message !== 'Session not found') {
4473
+
4474
+ // Only close the tab for hard errors that actually break the session.
4475
+ // `advisory: true` errors (rate-limit, invalid payload, bufferFull) are
4476
+ // operational warnings and must NOT close the tab. Previously a single
4477
+ // mobile dropdown tab switch would close every tab because switchTab
4478
+ // triggers ssh-request-sync, which hit the Phase-3 rate-limit and
4479
+ // emitted an advisory ssh-error; the old closeTab-on-any-error path
4480
+ // then chained the close into server-side teardown cascades.
4481
+ if (data.sessionId && data.message !== 'Session not found' && !data.advisory) {
4524
4482
  this.closeTab(data.sessionId);
4525
4483
  }
4526
4484
  });