@lethevimlet/sshift 1.2.0 → 1.2.2

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.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -60,6 +60,19 @@ function registerSFTPHandlers(socket, io) {
60
60
  }
61
61
  });
62
62
 
63
+ // SFTP join existing session
64
+ socket.on('sftp-join', (data) => {
65
+ console.log('[SFTP] sftp-join event received for session:', data.sessionId);
66
+ const success = sftpManager.joinSession(socket, data.sessionId);
67
+ if (success) {
68
+ // Add this socket to the tab's active sockets
69
+ addSocketToTab(data.sessionId, socket.id);
70
+ socket.emit('sftp-joined', { sessionId: data.sessionId });
71
+ } else {
72
+ socket.emit('sftp-error', { message: 'Session not found', sessionId: data.sessionId });
73
+ }
74
+ });
75
+
63
76
  // SFTP list directory
64
77
  socket.on('sftp-list', async (data) => {
65
78
  try {
@@ -400,6 +400,24 @@ class SFTPManager {
400
400
  getActiveSessions() {
401
401
  return this.sessions;
402
402
  }
403
+
404
+ // Join an existing SFTP session (for multi-client viewing)
405
+ joinSession(socket, sessionId) {
406
+ const session = this.sessions.get(sessionId);
407
+ if (!session) {
408
+ console.log(`[SFTP] Cannot join session ${sessionId}: session not found`);
409
+ return false;
410
+ }
411
+
412
+ return true;
413
+ }
414
+
415
+ // Leave an SFTP session (just removes the socket, doesn't disconnect)
416
+ leaveSession(socket, sessionId) {
417
+ // SFTP sessions don't track per-socket membership like SSH does
418
+ // The session stays alive as long as the SSH connection is active
419
+ console.log(`[SFTP] Socket ${socket.id} left session ${sessionId}`);
420
+ }
403
421
  }
404
422
 
405
423
  module.exports = new SFTPManager();
@@ -31,6 +31,8 @@ class SSHIFTClient {
31
31
  this.savedTabs = []; // Store tab information
32
32
  this.isRestoring = false; // Flag to prevent saving during restoration
33
33
  this.isSyncingTabs = false; // Flag to prevent saveTabs emission during tabs-sync
34
+ this._initialSyncDone = false; // Whether initial open-tabs sync from server has completed
35
+ this._serverSyncTimeout = null; // Timeout for fallback to localStorage restore
34
36
  this.sftpClipboard = null; // For cut/copy/paste: { action: 'cut'|'copy', path: string, name: string, sessionId: string }
35
37
  this.terminalClipboardContent = null; // Pre-read clipboard content for context menu paste
36
38
  this.osc52Buffer = null; // Buffered OSC 52 clipboard content pending write
@@ -2389,9 +2391,16 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2389
2391
  // Update terminal color UI to reflect loaded settings
2390
2392
  this.updateTerminalColorOverrideUI();
2391
2393
 
2392
- // Restore tabs if sticky is enabled
2394
+ // In sticky mode, the server is the single source of truth for tabs.
2395
+ // Wait for the open-tabs event from the server instead of restoring from localStorage.
2396
+ // Set a fallback timeout in case the server is unreachable.
2393
2397
  if (this.sticky) {
2394
- await this.restoreTabs();
2398
+ this._serverSyncTimeout = setTimeout(() => {
2399
+ if (!this._initialSyncDone) {
2400
+ console.log('[SSHIFT] Server tabs not received within timeout, falling back to localStorage');
2401
+ this.restoreTabs();
2402
+ }
2403
+ }, 3000);
2395
2404
  }
2396
2405
 
2397
2406
  // Initialize mobile tabs dropdown
@@ -3255,6 +3264,13 @@ const wheelHandler = (e) => {
3255
3264
  }
3256
3265
 
3257
3266
  async restoreTabs() {
3267
+ // If server tabs have already been synced, skip localStorage restore
3268
+ // This prevents duplication when the server responded before the fallback timeout
3269
+ if (this._initialSyncDone) {
3270
+ console.log('[SSHIFT] Server tabs already synced, skipping localStorage restore');
3271
+ return;
3272
+ }
3273
+
3258
3274
  const savedData = this.loadTabs();
3259
3275
 
3260
3276
  // Handle both old format (array) and new format (object with tabs and layout)
@@ -3284,6 +3300,12 @@ const wheelHandler = (e) => {
3284
3300
 
3285
3301
  // Restore each session
3286
3302
  for (const savedTab of savedTabs) {
3303
+ // Stop restoring if server tabs have been synced (open-tabs arrived while we were restoring)
3304
+ if (this._initialSyncDone) {
3305
+ console.log('[SSHIFT] Server tabs received during restore, stopping localStorage restore');
3306
+ break;
3307
+ }
3308
+
3287
3309
  console.log('[SSHIFT] Restoring tab:', savedTab.name, savedTab.type);
3288
3310
 
3289
3311
  let sessionId;
@@ -3385,6 +3407,12 @@ const wheelHandler = (e) => {
3385
3407
  // Handle receiving open tabs from server (for cross-tab sync)
3386
3408
  this.socket.on('open-tabs', (data) => {
3387
3409
  console.log('[SSHIFT] Received open tabs from server:', data.tabs.length);
3410
+
3411
+ // Clear fallback timeout - server has responded
3412
+ if (this._serverSyncTimeout) {
3413
+ clearTimeout(this._serverSyncTimeout);
3414
+ this._serverSyncTimeout = null;
3415
+ }
3388
3416
 
3389
3417
  // Sync theme and accent from server
3390
3418
  if (data.theme) {
@@ -3411,8 +3439,19 @@ const wheelHandler = (e) => {
3411
3439
  }
3412
3440
 
3413
3441
  // Only sync if sticky is enabled
3414
- if (this.sticky && data.tabs.length > 0) {
3415
- this.syncTabsFromServer(data.tabs);
3442
+ // Server is the single source of truth for tabs in sticky mode.
3443
+ // On initial sync, reconcile local state to match server state.
3444
+ // On reconnection, only add missing tabs to avoid disrupting locally-created tabs.
3445
+ if (this.sticky) {
3446
+ if (data.tabs.length > 0) {
3447
+ const isInitialSync = !this._initialSyncDone;
3448
+ this.syncTabsFromServer(data.tabs, isInitialSync);
3449
+ } else if (!this._initialSyncDone) {
3450
+ // Server has no tabs and this is the first sync (e.g. server restart).
3451
+ // Fall back to localStorage restore to reconnect sessions.
3452
+ this.restoreTabs();
3453
+ }
3454
+ this._initialSyncDone = true;
3416
3455
  }
3417
3456
  // Sync layout if provided (but not on mobile - mobile always uses single panel)
3418
3457
  if (data.layout && this.sticky && !this.isMobile) {
@@ -3929,7 +3968,6 @@ const wheelHandler = (e) => {
3929
3968
 
3930
3969
  this.socket.on('ssh-error', (data) => {
3931
3970
  console.error('[SSHIFT] SSH Error:', data.message, 'sessionId:', data.sessionId);
3932
- this.showToast(data.message, 'error');
3933
3971
 
3934
3972
  // If session not found and we're restoring, try to reconnect
3935
3973
  if (data.sessionId && data.message === 'Session not found') {
@@ -3937,28 +3975,61 @@ const wheelHandler = (e) => {
3937
3975
  console.log('[SSHIFT] Session found:', !!session, 'isRestoring:', session?.isRestoring);
3938
3976
 
3939
3977
  if (session && session.isRestoring && session.connectionData) {
3940
- console.log('[SSHIFT] Session not found on server, reconnecting with new connection...');
3941
- session.isRestoring = false;
3942
- session.connecting = true;
3943
- session.connected = false;
3944
-
3945
- // Clear the terminal and show reconnecting message
3946
- if (session.terminal) {
3947
- session.terminal.clear();
3948
- session.terminal.writeln('\x1b[33m⚠ Session expired, reconnecting...\x1b[0m');
3949
- session.terminal.writeln('');
3978
+ // Only attempt reconnection if we have auth credentials.
3979
+ // When syncing from the server, password/privateKey are stripped,
3980
+ // so reconnecting without them would fail with a misleading auth error.
3981
+ const hasCredentials = session.connectionData.password || session.connectionData.privateKey;
3982
+ if (hasCredentials) {
3983
+ console.log('[SSHIFT] Session not found on server, reconnecting with new connection...');
3984
+ this.showToast('Session expired, reconnecting...', 'warning');
3985
+ session.isRestoring = false;
3986
+ session.connecting = true;
3987
+ session.connected = false;
3988
+
3989
+ // Clear the terminal and show reconnecting message
3990
+ if (session.terminal) {
3991
+ session.terminal.clear();
3992
+ session.terminal.writeln('\x1b[33m⚠ Session expired, reconnecting...\x1b[0m');
3993
+ session.terminal.writeln('');
3994
+ }
3995
+
3996
+ // Emit ssh-connect to create a new connection
3997
+ console.log('[SSHIFT] Emitting ssh-connect for reconnection with sessionId:', data.sessionId);
3998
+ this.socket.emit('ssh-connect', { ...session.connectionData, sessionId: data.sessionId });
3999
+ return; // Don't close the tab
4000
+ } else {
4001
+ // No credentials available - show a user-friendly message
4002
+ console.log('[SSHIFT] Session expired and no credentials available for reconnection');
4003
+ this.showToast('Session expired. Please reconnect manually.', 'warning');
4004
+ if (session.terminal) {
4005
+ session.terminal.writeln('\x1b[33m⚠ Session expired. Please close this tab and reconnect.\x1b[0m');
4006
+ }
4007
+ // Don't close the tab - let the user see the message
4008
+ if (session.terminal) {
4009
+ session.connecting = false;
4010
+ }
4011
+ return;
3950
4012
  }
3951
-
3952
- // Emit ssh-connect to create a new connection
3953
- console.log('[SSHIFT] Emitting ssh-connect for reconnection with sessionId:', data.sessionId);
3954
- this.socket.emit('ssh-connect', { ...session.connectionData, sessionId: data.sessionId });
3955
- return; // Don't close the tab
3956
4013
  } else {
3957
4014
  console.log('[SSHIFT] Session not eligible for reconnection, closing tab');
3958
4015
  }
3959
4016
  }
3960
4017
 
3961
- if (data.sessionId) {
4018
+ // Show error toast for genuine errors (not auth failures from stripped credentials)
4019
+ const isStrippedAuthError = data.message && data.message.includes('authentication methods failed');
4020
+ if (isStrippedAuthError) {
4021
+ const session = data.sessionId ? this.sessions.get(data.sessionId) : null;
4022
+ // Suppress the auth error toast if this is a restoring/joined session without credentials
4023
+ if (session && session.isRestoring) {
4024
+ console.log('[SSHIFT] Suppressing auth error toast for restoring session without credentials');
4025
+ } else {
4026
+ this.showToast(data.message, 'error');
4027
+ }
4028
+ } else {
4029
+ this.showToast(data.message, 'error');
4030
+ }
4031
+
4032
+ if (data.sessionId && data.message !== 'Session not found') {
3962
4033
  this.closeTab(data.sessionId);
3963
4034
  }
3964
4035
  });
@@ -3979,6 +4050,18 @@ const wheelHandler = (e) => {
3979
4050
  this.onSFTPConnected(data);
3980
4051
  });
3981
4052
 
4053
+ this.socket.on('sftp-joined', (data) => {
4054
+ console.log('[SSHIFT] SFTP Joined session:', data.sessionId);
4055
+ const session = this.sftpSessions.get(data.sessionId);
4056
+ if (session) {
4057
+ session.connecting = false;
4058
+ session.isRestoring = false;
4059
+ // Navigate to the stored path or root to show the session is active
4060
+ const path = session.currentPath || '/';
4061
+ this.socket.emit('sftp-list', { sessionId: data.sessionId, path });
4062
+ }
4063
+ });
4064
+
3982
4065
  this.socket.on('sftp-list-result', (data) => {
3983
4066
  console.log('[SSHIFT] sftp-list-result received:', data);
3984
4067
  console.log('[SSHIFT] sessionId from server:', data.sessionId);
@@ -3988,7 +4071,45 @@ const wheelHandler = (e) => {
3988
4071
  });
3989
4072
 
3990
4073
  this.socket.on('sftp-error', (data) => {
3991
- this.showToast(data.message, 'error');
4074
+ console.error('[SSHIFT] SFTP Error:', data.message, 'sessionId:', data?.sessionId);
4075
+
4076
+ // If session not found and we're restoring, try to reconnect
4077
+ if (data?.sessionId && data.message === 'Session not found') {
4078
+ const session = this.sftpSessions.get(data.sessionId);
4079
+
4080
+ if (session && session.isRestoring && session.connectionData) {
4081
+ // Only attempt reconnection if we have auth credentials
4082
+ const hasCredentials = session.connectionData.password || session.connectionData.privateKey;
4083
+ if (hasCredentials) {
4084
+ console.log('[SFTP] Session not found on server, reconnecting...');
4085
+ this.showToast('SFTP session expired, reconnecting...', 'warning');
4086
+ session.isRestoring = false;
4087
+ session.connecting = true;
4088
+ this.socket.emit('sftp-connect', { ...session.connectionData, sessionId: data.sessionId });
4089
+ return;
4090
+ } else {
4091
+ // No credentials available - show a user-friendly message
4092
+ console.log('[SFTP] Session expired and no credentials available for reconnection');
4093
+ this.showToast('SFTP session expired. Please reconnect manually.', 'warning');
4094
+ session.connecting = false;
4095
+ return;
4096
+ }
4097
+ }
4098
+ }
4099
+
4100
+ // Suppress auth error toast for restoring sessions without credentials
4101
+ const isStrippedAuthError = data.message && data.message.includes('authentication methods failed');
4102
+ if (isStrippedAuthError) {
4103
+ const session = data?.sessionId ? this.sftpSessions.get(data.sessionId) : null;
4104
+ if (session && session.isRestoring) {
4105
+ console.log('[SSHIFT] Suppressing auth error toast for restoring SFTP session without credentials');
4106
+ } else {
4107
+ this.showToast(data.message, 'error');
4108
+ }
4109
+ } else {
4110
+ this.showToast(data.message, 'error');
4111
+ }
4112
+
3992
4113
  if (this._activeDownload) {
3993
4114
  this.hideTransferProgress(this._activeDownload.sessionId);
3994
4115
  this._activeDownload = null;
@@ -7456,7 +7577,9 @@ const wheelHandler = (e) => {
7456
7577
  type: 'sftp',
7457
7578
  currentPath: '/',
7458
7579
  connectionData, // Store for sticky sessions
7459
- fontSize: this.terminalFontSize // Initialize with default font size
7580
+ fontSize: this.terminalFontSize, // Initialize with default font size
7581
+ isRestoring: !!restoreSessionId, // Flag to indicate if this is a restored session
7582
+ connecting: !restoreSessionId, // Only show connecting state for new connections
7460
7583
  });
7461
7584
 
7462
7585
  console.log('[SSHIFT] Switching to SFTP tab:', sessionId);
@@ -7473,9 +7596,15 @@ const wheelHandler = (e) => {
7473
7596
  const sftpContainer = document.getElementById(`sftp-${sessionId}`);
7474
7597
  console.log('[SSHIFT] SFTP container found:', !!sftpContainer);
7475
7598
 
7476
- // Connect via socket
7477
- console.log('[SSHIFT] Emitting sftp-connect for session:', sessionId);
7478
- this.socket.emit('sftp-connect', { ...connectionData, sessionId });
7599
+ // If restoring a session, try to join it first (no new SSH connection needed)
7600
+ if (restoreSessionId) {
7601
+ console.log('[SSHIFT] Attempting to join existing SFTP session:', restoreSessionId);
7602
+ this.socket.emit('sftp-join', { sessionId: restoreSessionId });
7603
+ } else {
7604
+ // Connect via socket for new sessions
7605
+ console.log('[SSHIFT] Emitting sftp-connect for session:', sessionId);
7606
+ this.socket.emit('sftp-connect', { ...connectionData, sessionId });
7607
+ }
7479
7608
 
7480
7609
  // Save tabs
7481
7610
  this.saveTabs();
@@ -8276,6 +8405,84 @@ const wheelHandler = (e) => {
8276
8405
  this.saveTabs();
8277
8406
  }
8278
8407
 
8408
+ // Remove a tab locally without notifying the server.
8409
+ // Used during initial sync to remove stale tabs from localStorage
8410
+ // that don't exist on the server (prevents cross-device duplication).
8411
+ removeTabLocally(sessionId) {
8412
+ const session = this.sessions.get(sessionId) || this.sftpSessions.get(sessionId);
8413
+ if (!session) return;
8414
+
8415
+ console.log('[SSHIFT] Removing tab locally:', sessionId);
8416
+
8417
+ const panelId = this.getPanelForSession(sessionId);
8418
+
8419
+ // Disconnect from server session (without emitting tab-close)
8420
+ if (session.type === 'ssh') {
8421
+ this.socket.emit('ssh-disconnect', { sessionId });
8422
+ if (session.writeRAF) cancelAnimationFrame(session.writeRAF);
8423
+ if (session.scrollbackRestoreTimer) clearTimeout(session.scrollbackRestoreTimer);
8424
+ if (session.originalScrollback && session.terminal) {
8425
+ session.terminal.options.scrollback = session.originalScrollback;
8426
+ }
8427
+ if (session.resizeObserver) {
8428
+ session.resizeObserver.disconnect();
8429
+ session.resizeObserver = null;
8430
+ }
8431
+ if (session.resizeTimeout) {
8432
+ clearTimeout(session.resizeTimeout);
8433
+ session.resizeTimeout = null;
8434
+ }
8435
+ if (session.wheelHandler && session.wheelElement) {
8436
+ session.wheelElement.removeEventListener('wheel', session.wheelHandler);
8437
+ }
8438
+ if (session.osc52FlushListener) {
8439
+ document.removeEventListener('click', session.osc52FlushListener, true);
8440
+ document.removeEventListener('keydown', session.osc52FlushListener, true);
8441
+ document.removeEventListener('touchstart', session.osc52FlushListener, true);
8442
+ }
8443
+ if (session.terminal) session.terminal.dispose();
8444
+ if (session.mobileHandler) {
8445
+ session.mobileHandler.destroy();
8446
+ session.mobileHandler = null;
8447
+ }
8448
+ this.sessions.delete(sessionId);
8449
+ } else {
8450
+ this.socket.emit('sftp-disconnect', { sessionId });
8451
+ this.sftpSessions.delete(sessionId);
8452
+ }
8453
+
8454
+ // Remove from DOM
8455
+ const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
8456
+ const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
8457
+ if (tab) tab.remove();
8458
+ if (wrapper) wrapper.remove();
8459
+
8460
+ // Update scroll arrows
8461
+ this.updateTabsScrollArrows();
8462
+
8463
+ // Check if this was the active session
8464
+ if (this.activeSessionId === sessionId) {
8465
+ const remainingSessions = [...Array.from(this.sessions.keys()), ...Array.from(this.sftpSessions.keys())];
8466
+ if (remainingSessions.length > 0) {
8467
+ this.switchTab(remainingSessions[0]);
8468
+ } else {
8469
+ this.activeSessionId = null;
8470
+ this.updateMobileKeysBar();
8471
+ }
8472
+ }
8473
+
8474
+ // Check if this was the active session in its panel
8475
+ const activeInPanel = this.activeSessionsByPanel.get(panelId);
8476
+ if (activeInPanel === sessionId) {
8477
+ this.activeSessionsByPanel.delete(panelId);
8478
+ const tabsContainer = this.getTabsContainer(panelId);
8479
+ const remainingInPanel = tabsContainer ? Array.from(tabsContainer.children) : [];
8480
+ if (remainingInPanel.length === 0) {
8481
+ this.showEmptyState(panelId);
8482
+ }
8483
+ }
8484
+ }
8485
+
8279
8486
  // Handle tab opened by another client
8280
8487
  handleTabOpened(data) {
8281
8488
  // Check if we already have this session
@@ -8376,7 +8583,7 @@ const wheelHandler = (e) => {
8376
8583
  }
8377
8584
 
8378
8585
  // Sync tabs from server (called on connect when sticky is enabled)
8379
- async syncTabsFromServer(tabs) {
8586
+ async syncTabsFromServer(tabs, isInitialSync = false) {
8380
8587
  // Wait for any in-progress restoration to complete before syncing
8381
8588
  // This prevents the race condition where restoreTabs starts first,
8382
8589
  // sets isRestoring=true, and then this function returns early, missing
@@ -8387,9 +8594,27 @@ async syncTabsFromServer(tabs) {
8387
8594
  waitCount++;
8388
8595
  }
8389
8596
 
8390
- console.log('[SSHIFT] Syncing tabs from server:', tabs.length);
8597
+ console.log('[SSHIFT] Syncing tabs from server:', tabs.length, 'isInitialSync:', isInitialSync);
8391
8598
  this.isRestoring = true;
8392
8599
 
8600
+ // On initial sync, remove any client-side tabs that don't exist on the server.
8601
+ // This ensures the server is the single source of truth and prevents duplicates
8602
+ // from stale localStorage caches (e.g. when switching between devices).
8603
+ if (isInitialSync) {
8604
+ const serverSessionIds = new Set(tabs.map(t => t.sessionId));
8605
+ const clientSessionIds = [
8606
+ ...Array.from(this.sessions.keys()),
8607
+ ...Array.from(this.sftpSessions.keys())
8608
+ ];
8609
+
8610
+ for (const sessionId of clientSessionIds) {
8611
+ if (!serverSessionIds.has(sessionId)) {
8612
+ console.log('[SSHIFT] Removing local tab not on server during initial sync:', sessionId);
8613
+ this.removeTabLocally(sessionId);
8614
+ }
8615
+ }
8616
+ }
8617
+
8393
8618
  for (const tab of tabs) {
8394
8619
  // Check if we already have this session
8395
8620
  if (this.sessions.has(tab.sessionId) || this.sftpSessions.has(tab.sessionId)) {
@@ -8426,6 +8651,9 @@ async syncTabsFromServer(tabs) {
8426
8651
  this.applyFlashStates();
8427
8652
 
8428
8653
  this.isRestoring = false;
8654
+
8655
+ // Save the final tab state to localStorage after sync completes
8656
+ this.saveTabs();
8429
8657
  }
8430
8658
 
8431
8659
  // Special Keys