@lethevimlet/sshift 1.9.7 → 1.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.
Files changed (32) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/plugins/claude-attention/index.js +11 -0
  4. package/plugins/opencode-attention/index.js +11 -0
  5. package/plugins/remote-control/index.js +13 -1
  6. package/src/server/endpoints/rest/auth.js +45 -32
  7. package/src/server/endpoints/rest/bookmarks.js +5 -1
  8. package/src/server/endpoints/rest/config.js +19 -35
  9. package/src/server/endpoints/rest/folders.js +15 -3
  10. package/src/server/endpoints/rest/speech-ai.js +35 -9
  11. package/src/server/endpoints/rest/system.js +40 -4
  12. package/src/server/endpoints/ws/index.js +6 -0
  13. package/src/server/endpoints/ws/sftp.js +70 -10
  14. package/src/server/endpoints/ws/ssh.js +13 -5
  15. package/src/server/endpoints/ws/tabs.js +4 -4
  16. package/src/server/index.js +87 -3
  17. package/src/server/plugins/plugin-manager.js +21 -1
  18. package/src/server/services/bookmarks.js +1 -1
  19. package/src/server/services/headless-open.js +91 -0
  20. package/src/server/services/sftp-manager.js +80 -7
  21. package/src/server/services/ssh-manager.js +48 -13
  22. package/src/server/utils/asset-version.js +26 -0
  23. package/src/server/utils/auth-tokens.js +254 -0
  24. package/src/server/utils/bookmark-encryption.js +5 -0
  25. package/src/server/utils/certs.js +3 -0
  26. package/src/server/utils/config.js +49 -6
  27. package/src/server/utils/key-converter.js +30 -5
  28. package/src/server/utils/safe-handlers.js +80 -0
  29. package/src/server/utils/tab-manager.js +41 -1
  30. package/src/webapp/js/app.js +296 -193
  31. package/src/webapp/js/mobile-terminal.js +436 -79
  32. package/sshift +23 -2
@@ -29,6 +29,9 @@ class SSHIFTClient {
29
29
  this._disconnectToastTimer = null;
30
30
  this._disconnectToastShown = false;
31
31
  this.DISCONNECT_TOAST_GRACE_MS = 2500;
32
+ this.WAKE_GAP_MS = 15000; // timer gap that means the machine slept
33
+ this.PROBE_TIMEOUT_MS = 4000; // ack deadline for the liveness probe
34
+ this._authRejected = false;
32
35
  this._staleReloadFor = null;
33
36
  this._initReady = false; // Set true once init() completes
34
37
  this._pendingOpenTabs = null; // Deferred open-tabs data
@@ -108,7 +111,9 @@ class SSHIFTClient {
108
111
 
109
112
  console.log('[SSHIFT] Mobile detection - isMobile:', this.isMobile, 'window width:', window.innerWidth);
110
113
 
111
- this.init();
114
+ Promise.resolve(this.init()).catch((err) => {
115
+ console.error('[SSHIFT] Initialization failed:', err);
116
+ });
112
117
  }
113
118
 
114
119
  async loadStickyConfig() {
@@ -124,13 +129,15 @@ class SSHIFTClient {
124
129
 
125
130
  // If we have localStorage values, use them
126
131
  if (localSticky !== null) {
127
- this.sticky = JSON.parse(localSticky);
128
- this.takeControlDefault = localTakeControl !== null ? JSON.parse(localTakeControl) : true;
132
+ // A corrupt stored value must not stop the app from starting.
133
+ const parse = (v, fallback) => { try { return v === null ? fallback : JSON.parse(v); } catch (_) { return fallback; } };
134
+ this.sticky = parse(localSticky, true);
135
+ this.takeControlDefault = parse(localTakeControl, true);
129
136
  this.sshKeepaliveInterval = localKeepaliveInterval !== null ? parseInt(localKeepaliveInterval) : 10000;
130
137
  this.sshKeepaliveCountMax = localKeepaliveCountMax !== null ? parseInt(localKeepaliveCountMax) : 1000;
131
- this.mobileKeysBarEnabled = localMobileKeysBar !== null ? JSON.parse(localMobileKeysBar) : true;
132
- this.webglRenderer = localWebglRenderer !== null ? JSON.parse(localWebglRenderer) : true;
133
- this.imageAddonEnabled = localImageAddonEnabled !== null ? JSON.parse(localImageAddonEnabled) : true;
138
+ this.mobileKeysBarEnabled = parse(localMobileKeysBar, true);
139
+ this.webglRenderer = parse(localWebglRenderer, true);
140
+ this.imageAddonEnabled = parse(localImageAddonEnabled, true);
134
141
  this.scrollback = localScrollback !== null ? parseInt(localScrollback) : 10000;
135
142
  console.log('[SSHIFT] Loaded from localStorage - Sticky:', this.sticky ? 'enabled' : 'disabled',
136
143
  'Take Control Default:', this.takeControlDefault ? 'enabled' : 'disabled',
@@ -205,13 +212,21 @@ class SSHIFTClient {
205
212
  const verifyResp = await this._origFetch('/api/config', {
206
213
  headers: { 'Authorization': `Bearer ${storedToken}` }
207
214
  });
208
- if (verifyResp.ok) {
215
+ // Only a definite rejection forgets the remembered login. A
216
+ // server that is restarting, a proxy error or a network blip
217
+ // must not throw the user back to the password prompt.
218
+ if (verifyResp.status !== 401) {
209
219
  this.authToken = storedToken;
210
220
  this.updateSocketAuth();
211
221
  if (lockScreen) lockScreen.style.display = 'none';
212
222
  return;
213
223
  }
214
- } catch (e) {}
224
+ } catch (e) {
225
+ this.authToken = storedToken;
226
+ this.updateSocketAuth();
227
+ if (lockScreen) lockScreen.style.display = 'none';
228
+ return;
229
+ }
215
230
  localStorage.removeItem('sshift_auth_token');
216
231
  this.authToken = null;
217
232
  }
@@ -224,7 +239,10 @@ class SSHIFTClient {
224
239
  }
225
240
 
226
241
  showLockScreen() {
227
- return new Promise((resolve) => {
242
+ // connect_error and checkAuthStatus can both ask for the lock screen;
243
+ // one prompt (and one submit handler) at a time.
244
+ if (this._lockScreenPromise) return this._lockScreenPromise;
245
+ this._lockScreenPromise = new Promise((resolve) => {
228
246
  const lockScreen = document.getElementById('lockScreen');
229
247
  const lockScreenForm = document.getElementById('lockScreenForm');
230
248
  const lockScreenPassword = document.getElementById('lockScreenPassword');
@@ -264,6 +282,7 @@ class SSHIFTClient {
264
282
  this.passwordEnabled = true;
265
283
  if (this.bookmarkEncryptionEnabled) this.clearSensitiveTabStorage();
266
284
  lockScreenForm.removeEventListener('submit', submitHandler);
285
+ this._lockScreenPromise = null;
267
286
  resolve();
268
287
  } else {
269
288
  const data = await resp.json();
@@ -280,10 +299,14 @@ class SSHIFTClient {
280
299
 
281
300
  lockScreenForm.addEventListener('submit', submitHandler);
282
301
  });
302
+ return this._lockScreenPromise;
283
303
  }
284
304
 
285
305
  updateSocketAuth() {
286
306
  if (this.socket && this.authToken) {
307
+ // Already connected with this token (the socket is created with the
308
+ // stored token): nothing to swap, don't drop the connection.
309
+ if (this.socket.connected && this.socket.auth && this.socket.auth.token === this.authToken) return;
287
310
  this.socket.auth = { token: this.authToken };
288
311
  // Deliberate reconnect: no Disconnected/Reconnected toasts for it.
289
312
  this._silentReconnect = true;
@@ -550,6 +573,11 @@ class SSHIFTClient {
550
573
  // fire saveTabs in tight succession with identical payloads; that
551
574
  // amplified duplicates across clients and spammed the server.
552
575
  const signature = JSON.stringify(tabsData);
576
+ // Decided now, not when the timer fires: by then the sync flags have
577
+ // long been reset.
578
+ if (!this.isSyncingTabs && !(this._tabSyncDepth > 0)) {
579
+ this._saveTabsLocalChange = true;
580
+ }
553
581
  if (this._saveTabsTimer) clearTimeout(this._saveTabsTimer);
554
582
  this._saveTabsTimer = setTimeout(() => {
555
583
  this._saveTabsTimer = null;
@@ -563,7 +591,9 @@ class SSHIFTClient {
563
591
 
564
592
  // Sync to server for cross-tab sync
565
593
  // Don't emit if we're currently syncing from another client to prevent loops
566
- if (this.socket && this.socket.connected && !this.isSyncingTabs) {
594
+ const localChange = !!this._saveTabsLocalChange;
595
+ this._saveTabsLocalChange = false;
596
+ if (this.socket && this.socket.connected && localChange) {
567
597
  this.socket.emit('tabs-save', tabsData);
568
598
  }
569
599
  }, 150);
@@ -919,8 +949,11 @@ class SSHIFTClient {
919
949
 
920
950
  // Fallback to execCommand (also requires user gesture in modern browsers)
921
951
  try {
952
+ const previousFocus = document.activeElement;
922
953
  const textarea = document.createElement('textarea');
923
954
  textarea.value = text;
955
+ // readonly: selecting it must not pop the phone keyboard
956
+ textarea.setAttribute('readonly', '');
924
957
  textarea.style.position = 'fixed';
925
958
  textarea.style.left = '-9999px';
926
959
  textarea.style.top = '-9999px';
@@ -928,8 +961,12 @@ class SSHIFTClient {
928
961
  document.body.appendChild(textarea);
929
962
  textarea.focus();
930
963
  textarea.select();
964
+ try { textarea.setSelectionRange(0, text.length); } catch (_) {} // iOS
931
965
  const success = document.execCommand('copy');
932
966
  document.body.removeChild(textarea);
967
+ if (previousFocus && previousFocus !== document.body && typeof previousFocus.focus === 'function') {
968
+ try { previousFocus.focus({ preventScroll: true }); } catch (_) {}
969
+ }
933
970
  if (success) {
934
971
  console.log('[SSHIFT] execCommand copy succeeded, length:', text.length);
935
972
  } else {
@@ -3438,8 +3475,12 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3438
3475
  console.error('Failed to load bookmark order from server:', err);
3439
3476
  }
3440
3477
  // Fall back to localStorage
3441
- const saved = localStorage.getItem('bookmarkOrder');
3442
- return saved ? JSON.parse(saved) : null;
3478
+ try {
3479
+ const saved = localStorage.getItem('bookmarkOrder');
3480
+ return saved ? JSON.parse(saved) : null;
3481
+ } catch (_) {
3482
+ return null;
3483
+ }
3443
3484
  }
3444
3485
 
3445
3486
  async saveBookmarkOrder() {
@@ -4704,6 +4745,7 @@ const wheelHandler = (e) => {
4704
4745
  const wasDisconnected = this._wasDisconnected;
4705
4746
  this._wasDisconnected = false;
4706
4747
  this._silentReconnect = false;
4748
+ this._authRejected = false;
4707
4749
  this._cancelDisconnectToast();
4708
4750
  if (wasDisconnected) {
4709
4751
  // Only announce the recovery of an outage that was announced.
@@ -4723,13 +4765,18 @@ const wheelHandler = (e) => {
4723
4765
  console.log('[SSHIFT] Disconnected from server:', reason);
4724
4766
  this._wasDisconnected = true;
4725
4767
  if (reason === 'io server disconnect') {
4726
- // Server intentionally disconnected us (e.g. auth failure) — don't auto-reconnect
4727
- // Socket.IO won't retry after server-initiated disconnect anyway
4768
+ // The server dropped us on purpose (credentials revoked). Socket.IO
4769
+ // never retries this by itself; try once more shortly so the page
4770
+ // either comes back or shows the lock screen instead of sitting
4771
+ // dead until F5.
4772
+ setTimeout(() => this._ensureConnection('server disconnect'), 1000);
4728
4773
  } else if (!this.isUpdating && !this._silentReconnect) {
4729
4774
  this._armDisconnectToast();
4730
4775
  }
4731
4776
  });
4732
4777
 
4778
+ this._installConnectionWatchdog();
4779
+
4733
4780
  // When the tab becomes visible again, reconnect the socket if needed
4734
4781
  // and refresh WebGL terminal renderers (the browser may reclaim GPU
4735
4782
  // memory from background tabs, invalidating the glyph texture atlas).
@@ -4737,10 +4784,9 @@ const wheelHandler = (e) => {
4737
4784
  if (document.hidden) return;
4738
4785
  if (!this.socket.connected) {
4739
4786
  console.log('[SSHIFT] Tab visible and socket disconnected, triggering reconnect');
4740
- this.socket.connect();
4741
- // Give the reconnect the same grace period before complaining.
4742
- this._armDisconnectToast();
4787
+ this._ensureConnection('visible');
4743
4788
  } else {
4789
+ this._ensureConnection('visible');
4744
4790
  this._checkServerVersion();
4745
4791
  }
4746
4792
  this.clearFlashesForVisibleSessions();
@@ -4760,6 +4806,7 @@ const wheelHandler = (e) => {
4760
4806
  this.socket.on('connect_error', (error) => {
4761
4807
  console.error('[SSHIFT] Connection error:', error);
4762
4808
  if (error.message === 'Authentication required') {
4809
+ this._authRejected = true;
4763
4810
  this.authToken = null;
4764
4811
  localStorage.removeItem('sshift_auth_token');
4765
4812
  this.showLockScreen();
@@ -5460,6 +5507,14 @@ const wheelHandler = (e) => {
5460
5507
  console.error('[SSHIFT] SSH Error:', data.message, 'sessionId:', data.sessionId);
5461
5508
  this._dismissConnectingToasts();
5462
5509
 
5510
+ // The session ended on the server while this page was away (closed
5511
+ // on another device, remote exit): drop the tab instead of
5512
+ // recreating the connection from stored credentials.
5513
+ if (data.sessionId && data.message === 'Session not found' && data.closed) {
5514
+ console.log('[SSHIFT] Session was closed while disconnected, removing tab:', data.sessionId);
5515
+ this.handleTabClosed(data.sessionId);
5516
+ return;
5517
+ }
5463
5518
  // If session not found and we're restoring, try to reconnect
5464
5519
  if (data.sessionId && data.message === 'Session not found') {
5465
5520
  const session = this.sessions.get(data.sessionId);
@@ -5616,6 +5671,11 @@ const wheelHandler = (e) => {
5616
5671
  this._dismissConnectingToasts();
5617
5672
  console.error('[SSHIFT] SFTP Error:', data.message, 'sessionId:', data?.sessionId);
5618
5673
 
5674
+ if (data?.sessionId && data.message === 'Session not found' && data.closed) {
5675
+ console.log('[SFTP] Session was closed while disconnected, removing tab:', data.sessionId);
5676
+ this.handleTabClosed(data.sessionId);
5677
+ return;
5678
+ }
5619
5679
  // If session not found and we're restoring, try to reconnect
5620
5680
  if (data?.sessionId && data.message === 'Session not found') {
5621
5681
  const session = this.sftpSessions.get(data.sessionId);
@@ -5669,8 +5729,13 @@ const wheelHandler = (e) => {
5669
5729
  this.showToast(data.message, 'error');
5670
5730
  }
5671
5731
 
5672
- if (this._activeDownload) {
5673
- this.hideTransferProgress(this._activeDownload.sessionId);
5732
+ // Only an error about the download itself aborts it (errors from
5733
+ // other SFTP tabs or a failed listing used to drop it silently while
5734
+ // the server kept streaming).
5735
+ const dl = this._activeDownload;
5736
+ if (dl && data && data.download && data.sessionId === dl.sessionId &&
5737
+ (!data.path || data.path === dl.path)) {
5738
+ this.hideTransferProgress(dl.sessionId);
5674
5739
  this._activeDownload = null;
5675
5740
  }
5676
5741
  });
@@ -5689,7 +5754,7 @@ const wheelHandler = (e) => {
5689
5754
 
5690
5755
  this.socket.on('sftp-download-chunk', (data) => {
5691
5756
  const dl = this._activeDownload;
5692
- if (dl && dl.path === data.path) {
5757
+ if (dl && dl.path === data.path && dl.sessionId === data.sessionId) {
5693
5758
  const binaryStr = atob(data.data);
5694
5759
  const bytes = new Uint8Array(binaryStr.length);
5695
5760
  for (let i = 0; i < binaryStr.length; i++) {
@@ -5712,7 +5777,7 @@ const wheelHandler = (e) => {
5712
5777
 
5713
5778
  this.socket.on('sftp-download-end', (data) => {
5714
5779
  const dl = this._activeDownload;
5715
- if (dl && dl.path === data.path) {
5780
+ if (dl && dl.path === data.path && dl.sessionId === data.sessionId) {
5716
5781
  if (data.success) {
5717
5782
  const blob = new Blob(dl.chunks, { type: 'application/octet-stream' });
5718
5783
  const url = URL.createObjectURL(blob);
@@ -5720,7 +5785,8 @@ const wheelHandler = (e) => {
5720
5785
  a.href = url;
5721
5786
  a.download = dl.fileName;
5722
5787
  a.click();
5723
- URL.revokeObjectURL(url);
5788
+ // Revoking synchronously can abort the save in some browsers.
5789
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
5724
5790
  this.showToast(`Downloaded: ${dl.fileName}`, 'success');
5725
5791
  }
5726
5792
  this.hideTransferProgress(dl.sessionId);
@@ -7667,7 +7733,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7667
7733
  }
7668
7734
  option.innerHTML = `
7669
7735
  <i class="fas ${icon} tab-icon ${iconClass}"></i>
7670
- <span class="tab-name">${displayName}</span>
7736
+ <span class="tab-name">${this.escapeHtml(displayName)}</span>
7671
7737
  <button class="tab-rename" data-session-id="${sessionId}" title="Rename">
7672
7738
  <i class="fas fa-pen"></i>
7673
7739
  </button>
@@ -7786,7 +7852,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7786
7852
  : '';
7787
7853
  option.innerHTML = `
7788
7854
  <i class="fas ${icon} tab-icon ${iconClass}"></i>
7789
- <span class="tab-name">${name}</span>
7855
+ <span class="tab-name">${this.escapeHtml(name)}</span>
7790
7856
  ${panelIndicator}
7791
7857
  <button class="tab-rename" data-session-id="${sessionId}" title="Rename">
7792
7858
  <i class="fas fa-pen"></i>
@@ -10447,15 +10513,9 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10447
10513
  }
10448
10514
  }
10449
10515
 
10450
- // Method 3: Find active wrapper, then container
10451
- if (!container) {
10452
- const activeWrapper = document.querySelector('.terminal-wrapper.active');
10453
- console.log('[SSHIFT] Active wrapper found:', !!activeWrapper);
10454
- if (activeWrapper) {
10455
- container = activeWrapper.querySelector('.sftp-file-list');
10456
- console.log('[SSHIFT] Method 3 (via active wrapper):', !!container);
10457
- }
10458
- }
10516
+ // No "active wrapper" fallback: a late result for a closed or not yet
10517
+ // built tab used to render into whatever SFTP pane was active, where
10518
+ // every click then acted on the other session.
10459
10519
 
10460
10520
  if (!container) {
10461
10521
  console.error('[SSHIFT] SFTP file list container not found');
@@ -10775,6 +10835,8 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10775
10835
  const download = this._activeDownload;
10776
10836
  if (download && download.sessionId === sessionId) {
10777
10837
  this._activeDownload = null;
10838
+ // Stop the server reading the rest of the file.
10839
+ this.socket.emit('sftp-download-cancel', { sessionId, path: download.path });
10778
10840
  }
10779
10841
 
10780
10842
  this.hideTransferProgress(sessionId);
@@ -11097,6 +11159,54 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11097
11159
  this.saveTabs();
11098
11160
  }
11099
11161
 
11162
+ /**
11163
+ * Release everything a terminal session holds in this page: observers,
11164
+ * timers, frame callbacks, the mobile touch/keyboard handler (window and
11165
+ * document listeners), wheel and OSC 52 listeners, and the xterm
11166
+ * instance. Shared by closeTab, removeTabLocally and handleTabClosed:
11167
+ * the last two used to skip most of it, so every tab closed from another
11168
+ * device left listeners and timers running against a disposed terminal.
11169
+ * Idempotent.
11170
+ */
11171
+ _releaseSessionResources(session) {
11172
+ if (!session || session._released) return;
11173
+ session._released = true;
11174
+ if (session.type !== 'ssh') return;
11175
+ const clear = (key, fn) => {
11176
+ if (session[key]) {
11177
+ try { fn(session[key]); } catch (_) {}
11178
+ session[key] = null;
11179
+ }
11180
+ };
11181
+ clear('resizeObserver', (o) => o.disconnect());
11182
+ clear('_scrollbarObserver', (o) => o.disconnect());
11183
+ for (const key of ['resizeTimeout', 'roFitTimeout', 'scrollbackRestoreTimer', 'settleRefreshTimer', 'syncTimeout', 'overlayUpdateTimeout', 'scrollTimeout']) {
11184
+ clear(key, clearTimeout);
11185
+ }
11186
+ for (const key of ['writeRAF', 'scrollRAF', 'scrollApplyRAF', 'momentumRAF']) {
11187
+ clear(key, cancelAnimationFrame);
11188
+ }
11189
+ if (session.originalScrollback && session.terminal) {
11190
+ try { session.terminal.options.scrollback = session.originalScrollback; } catch (_) {}
11191
+ }
11192
+ clear('mobileHandler', (h) => h.destroy());
11193
+ if (session.wheelHandler && session.wheelElement) {
11194
+ session.wheelElement.removeEventListener('wheel', session.wheelHandler);
11195
+ }
11196
+ session.wheelHandler = null;
11197
+ session.wheelElement = null;
11198
+ if (session.osc52FlushListener) {
11199
+ document.removeEventListener('click', session.osc52FlushListener, true);
11200
+ document.removeEventListener('keydown', session.osc52FlushListener, true);
11201
+ document.removeEventListener('touchstart', session.osc52FlushListener, true);
11202
+ session.osc52FlushListener = null;
11203
+ }
11204
+ // Keep the (disposed) reference: late callbacks test session.terminal.
11205
+ if (session.terminal) {
11206
+ try { session.terminal.dispose(); } catch (_) {}
11207
+ }
11208
+ }
11209
+
11100
11210
  closeTab(sessionId) {
11101
11211
  const session = this.sessions.get(sessionId) || this.sftpSessions.get(sessionId);
11102
11212
  if (!session) return;
@@ -11111,66 +11221,8 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11111
11221
  this.socket.emit('tab-close', { sessionId });
11112
11222
 
11113
11223
  // Disconnect
11224
+ this._releaseSessionResources(session);
11114
11225
  if (session.type === 'ssh') {
11115
- // Clean up ResizeObserver
11116
- if (session.resizeObserver) {
11117
- session.resizeObserver.disconnect();
11118
- session.resizeObserver = null;
11119
- }
11120
- // Clean up resize timeouts (emit debounce + ResizeObserver fit debounce)
11121
- if (session.resizeTimeout) {
11122
- clearTimeout(session.resizeTimeout);
11123
- session.resizeTimeout = null;
11124
- }
11125
- if (session.roFitTimeout) {
11126
- clearTimeout(session.roFitTimeout);
11127
- session.roFitTimeout = null;
11128
- }
11129
- // Clean up scrollbar MutationObserver (mobile-only)
11130
- if (session._scrollbarObserver) {
11131
- session._scrollbarObserver.disconnect();
11132
- session._scrollbarObserver = null;
11133
- }
11134
- // Clean up write buffer RAF
11135
- if (session.writeRAF) {
11136
- cancelAnimationFrame(session.writeRAF);
11137
- session.writeRAF = null;
11138
- }
11139
- // Clean up scrollback restore timer
11140
- if (session.scrollbackRestoreTimer) {
11141
- clearTimeout(session.scrollbackRestoreTimer);
11142
- session.scrollbackRestoreTimer = null;
11143
- }
11144
- // Clean up settle-refresh timer
11145
- if (session.settleRefreshTimer) {
11146
- clearTimeout(session.settleRefreshTimer);
11147
- session.settleRefreshTimer = null;
11148
- }
11149
- // Restore scrollback if it was dynamically reduced
11150
- if (session.originalScrollback && session.terminal) {
11151
- session.terminal.options.scrollback = session.originalScrollback;
11152
- }
11153
- // Clean up mobile handler
11154
- if (session.mobileHandler) {
11155
- session.mobileHandler.destroy();
11156
- session.mobileHandler = null;
11157
- }
11158
- // Clean up wheel handler
11159
- if (session.wheelHandler && session.wheelElement) {
11160
- session.wheelElement.removeEventListener('wheel', session.wheelHandler);
11161
- session.wheelHandler = null;
11162
- session.wheelElement = null;
11163
- }
11164
- // Clean up OSC 52 clipboard flush listeners
11165
- if (session.osc52FlushListener) {
11166
- document.removeEventListener('click', session.osc52FlushListener, true);
11167
- document.removeEventListener('keydown', session.osc52FlushListener, true);
11168
- document.removeEventListener('touchstart', session.osc52FlushListener, true);
11169
- session.osc52FlushListener = null;
11170
- }
11171
- if (session.terminal) {
11172
- session.terminal.dispose();
11173
- }
11174
11226
  this.sessions.delete(sessionId);
11175
11227
  } else {
11176
11228
  this.sftpSessions.delete(sessionId);
@@ -11242,37 +11294,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11242
11294
  // Disconnect from server session (without emitting tab-close)
11243
11295
  if (session.type === 'ssh') {
11244
11296
  this.socket.emit('ssh-disconnect', { sessionId });
11245
- if (session.writeRAF) cancelAnimationFrame(session.writeRAF);
11246
- if (session.scrollbackRestoreTimer) clearTimeout(session.scrollbackRestoreTimer);
11247
- if (session.settleRefreshTimer) clearTimeout(session.settleRefreshTimer);
11248
- if (session.originalScrollback && session.terminal) {
11249
- session.terminal.options.scrollback = session.originalScrollback;
11250
- }
11251
- if (session.resizeObserver) {
11252
- session.resizeObserver.disconnect();
11253
- session.resizeObserver = null;
11254
- }
11255
- if (session.resizeTimeout) {
11256
- clearTimeout(session.resizeTimeout);
11257
- session.resizeTimeout = null;
11258
- }
11259
- if (session.roFitTimeout) {
11260
- clearTimeout(session.roFitTimeout);
11261
- session.roFitTimeout = null;
11262
- }
11263
- if (session.wheelHandler && session.wheelElement) {
11264
- session.wheelElement.removeEventListener('wheel', session.wheelHandler);
11265
- }
11266
- if (session.osc52FlushListener) {
11267
- document.removeEventListener('click', session.osc52FlushListener, true);
11268
- document.removeEventListener('keydown', session.osc52FlushListener, true);
11269
- document.removeEventListener('touchstart', session.osc52FlushListener, true);
11270
- }
11271
- if (session.terminal) session.terminal.dispose();
11272
- if (session.mobileHandler) {
11273
- session.mobileHandler.destroy();
11274
- session.mobileHandler = null;
11275
- }
11297
+ this._releaseSessionResources(session);
11276
11298
  this.sessions.delete(sessionId);
11277
11299
  } else {
11278
11300
  this.socket.emit('sftp-disconnect', { sessionId });
@@ -11361,28 +11383,12 @@ handleTabOpened(data) {
11361
11383
  const panelId = this.getPanelForSession(sessionId);
11362
11384
 
11363
11385
  // Clean up the session locally (don't emit tab-close again)
11386
+ this._serverPanelMap.delete(sessionId);
11387
+ if (this.activeSessionsByPanel.get(panelId) === sessionId) {
11388
+ this.activeSessionsByPanel.delete(panelId);
11389
+ }
11390
+ this._releaseSessionResources(session);
11364
11391
  if (session.type === 'ssh') {
11365
- if (session.writeRAF) {
11366
- cancelAnimationFrame(session.writeRAF);
11367
- }
11368
- if (session.scrollbackRestoreTimer) {
11369
- clearTimeout(session.scrollbackRestoreTimer);
11370
- }
11371
- if (session.originalScrollback && session.terminal) {
11372
- session.terminal.options.scrollback = session.originalScrollback;
11373
- }
11374
- if (session.wheelHandler && session.wheelElement) {
11375
- session.wheelElement.removeEventListener('wheel', session.wheelHandler);
11376
- }
11377
- if (session.osc52FlushListener) {
11378
- document.removeEventListener('click', session.osc52FlushListener, true);
11379
- document.removeEventListener('keydown', session.osc52FlushListener, true);
11380
- document.removeEventListener('touchstart', session.osc52FlushListener, true);
11381
- session.osc52FlushListener = null;
11382
- }
11383
- if (session.terminal) {
11384
- session.terminal.dispose();
11385
- }
11386
11392
  this.sessions.delete(sessionId);
11387
11393
  } else {
11388
11394
  this.sftpSessions.delete(sessionId);
@@ -11423,7 +11429,20 @@ handleTabOpened(data) {
11423
11429
  }
11424
11430
 
11425
11431
  // Sync tabs from server (called on connect when sticky is enabled)
11426
- async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null, activeSessionId = null) {
11432
+ async syncTabsFromServer(...args) {
11433
+ // Held across all awaits of the sync: saveTabs calls made while
11434
+ // applying server state must not be broadcast back (echo loops
11435
+ // between clients). The callers' isSyncingTabs flag is reset
11436
+ // synchronously, long before this async body finishes.
11437
+ this._tabSyncDepth = (this._tabSyncDepth || 0) + 1;
11438
+ try {
11439
+ return await this._syncTabsFromServerImpl(...args);
11440
+ } finally {
11441
+ this._tabSyncDepth--;
11442
+ }
11443
+ }
11444
+
11445
+ async _syncTabsFromServerImpl(tabs, isInitialSync = false, activeTabsByPanel = null, activeSessionId = null) {
11427
11446
  // Wait for any in-progress restoration to complete before syncing
11428
11447
  // This prevents the race condition where restoreTabs starts first,
11429
11448
  // sets isRestoring=true, and then this function returns early, missing
@@ -11846,19 +11865,19 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
11846
11865
  let iconClass, details;
11847
11866
  if (bookmark.type === 'url') {
11848
11867
  iconClass = 'fa-globe';
11849
- details = bookmark.url || '';
11868
+ details = this.escapeHtml(bookmark.url || '');
11850
11869
  } else if (bookmark.type === 'sftp') {
11851
11870
  iconClass = 'fa-folder-open';
11852
- details = `${this.escapeHtml(bookmark.username)}@${this.escapeHtml(bookmark.host)}:${bookmark.port}`;
11871
+ details = `${this.escapeHtml(bookmark.username)}@${this.escapeHtml(bookmark.host)}:${this.escapeHtml(bookmark.port)}`;
11853
11872
  } else {
11854
11873
  iconClass = 'fa-terminal';
11855
- details = `${this.escapeHtml(bookmark.username)}@${this.escapeHtml(bookmark.host)}:${bookmark.port}`;
11874
+ details = `${this.escapeHtml(bookmark.username)}@${this.escapeHtml(bookmark.host)}:${this.escapeHtml(bookmark.port)}`;
11856
11875
  }
11857
11876
 
11858
11877
  item.innerHTML = `
11859
11878
  <div class="bookmark-icon ${bookmark.type}">
11860
11879
  <i class="fas ${iconClass}"></i>
11861
- <span class="bookmark-letter">${firstLetter}</span>
11880
+ <span class="bookmark-letter">${this.escapeHtml(firstLetter)}</span>
11862
11881
  </div>
11863
11882
  <div class="bookmark-info">
11864
11883
  <div class="bookmark-name">${this.escapeHtml(bookmark.name)}</div>
@@ -12460,26 +12479,30 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
12460
12479
  pathParts.pop();
12461
12480
  const newPath = pathParts.join('/') + '/' + newName;
12462
12481
 
12463
- this.socket.emit('sftp-rename', {
12464
- sessionId,
12465
- oldPath: oldPath,
12466
- newPath: newPath
12467
- });
12468
-
12469
- // Listen for result
12470
- this.socket.once('sftp-rename-result', (data) => {
12482
+ this._sftpRequest('sftp-rename', { sessionId, oldPath, newPath }).then((data) => {
12471
12483
  if (data.success) {
12472
- // Get current path and refresh
12473
12484
  const sftpSession = this.sftpSessions.get(sessionId);
12474
12485
  if (sftpSession) {
12475
12486
  this.navigateSFTPPath(sftpSession.currentPath, sessionId);
12476
12487
  }
12488
+ } else {
12489
+ this.showToast('Error renaming: ' + data.error, 'error');
12477
12490
  }
12478
12491
  });
12492
+ }
12479
12493
 
12480
- // Listen for errors
12481
- this.socket.once('sftp-error', (data) => {
12482
- alert('Error renaming: ' + data.message);
12494
+ /**
12495
+ * SFTP request answered through a Socket.IO ack, so the reply belongs to
12496
+ * this request only. (The previous once('sftp-error') listeners stayed
12497
+ * registered after a success and later fired for unrelated errors from
12498
+ * any SFTP tab.) Resolves to { success, error? }.
12499
+ */
12500
+ _sftpRequest(event, payload, timeoutMs = 60000) {
12501
+ return new Promise((resolve) => {
12502
+ this.socket.timeout(timeoutMs).emit(event, payload, (err, data) => {
12503
+ if (err) return resolve({ success: false, error: 'No response from server' });
12504
+ resolve(data || { success: false, error: 'Empty response' });
12505
+ });
12483
12506
  });
12484
12507
  }
12485
12508
 
@@ -12921,26 +12944,16 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
12921
12944
 
12922
12945
  if (!confirm(confirmMsg)) return;
12923
12946
 
12924
- this.socket.emit('sftp-delete', {
12925
- sessionId,
12926
- path: filePath
12927
- });
12928
-
12929
- // Listen for result
12930
- this.socket.once('sftp-delete-result', (data) => {
12947
+ this._sftpRequest('sftp-delete', { sessionId, path: filePath }).then((data) => {
12931
12948
  if (data.success) {
12932
- // Get current path and refresh
12933
12949
  const sftpSession = this.sftpSessions.get(sessionId);
12934
12950
  if (sftpSession) {
12935
12951
  this.navigateSFTPPath(sftpSession.currentPath, sessionId);
12936
12952
  }
12953
+ } else {
12954
+ this.showToast('Error deleting: ' + data.error, 'error');
12937
12955
  }
12938
12956
  });
12939
-
12940
- // Listen for errors
12941
- this.socket.once('sftp-error', (data) => {
12942
- alert('Error deleting: ' + data.message);
12943
- });
12944
12957
  }
12945
12958
 
12946
12959
  cutSFTPItem(fileName, filePath, sessionId) {
@@ -12996,24 +13009,16 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
12996
13009
 
12997
13010
  if (this.sftpClipboard.action === 'cut') {
12998
13011
  // Move (rename) the file
12999
- this.socket.emit('sftp-rename', {
13000
- sessionId,
13001
- oldPath: sourcePath,
13002
- newPath: destPath
13003
- });
13004
-
13005
- this.socket.once('sftp-rename-result', (data) => {
13012
+ this._sftpRequest('sftp-rename', { sessionId, oldPath: sourcePath, newPath: destPath }).then((data) => {
13006
13013
  if (data.success) {
13007
13014
  this.showToast(`Moved ${sourceName}`, 'success');
13008
13015
  this.navigateSFTPPath(currentPath, sessionId);
13009
13016
  // Clear clipboard after successful cut
13010
13017
  this.sftpClipboard = null;
13018
+ } else {
13019
+ this.showToast('Error moving: ' + data.error, 'error');
13011
13020
  }
13012
13021
  });
13013
-
13014
- this.socket.once('sftp-error', (data) => {
13015
- this.showToast('Error moving: ' + data.message, 'error');
13016
- });
13017
13022
  } else {
13018
13023
  // Copy operation - need to download and re-upload
13019
13024
  this.showToast('Copy operation requires download/re-upload. Use download button instead.', 'info');
@@ -13272,7 +13277,15 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13272
13277
  // Handle URL type - open in new tab
13273
13278
  if (bookmark.type === 'url') {
13274
13279
  if (bookmark.url) {
13275
- window.open(bookmark.url, '_blank');
13280
+ // Only web links, and without handing the opened page a handle
13281
+ // on this window (window.opener).
13282
+ let parsed = null;
13283
+ try { parsed = new URL(bookmark.url, window.location.href); } catch (_) {}
13284
+ if (parsed && (parsed.protocol === 'http:' || parsed.protocol === 'https:')) {
13285
+ window.open(parsed.href, '_blank', 'noopener,noreferrer');
13286
+ } else {
13287
+ this.showToast('Only http(s) links can be opened', 'error');
13288
+ }
13276
13289
  }
13277
13290
  return;
13278
13291
  }
@@ -13405,8 +13418,12 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13405
13418
  console.error('Failed to load folder order from server:', err);
13406
13419
  }
13407
13420
  // Fall back to localStorage
13408
- const saved = localStorage.getItem('folderOrder');
13409
- return saved ? JSON.parse(saved) : null;
13421
+ try {
13422
+ const saved = localStorage.getItem('folderOrder');
13423
+ return saved ? JSON.parse(saved) : null;
13424
+ } catch (_) {
13425
+ return null;
13426
+ }
13410
13427
  }
13411
13428
 
13412
13429
  async saveFolderOrder() {
@@ -13438,8 +13455,12 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13438
13455
  console.error('Failed to load folder expanded states from server:', err);
13439
13456
  }
13440
13457
  // Fall back to localStorage
13441
- const saved = localStorage.getItem('folderExpandedStates');
13442
- return saved ? JSON.parse(saved) : {};
13458
+ try {
13459
+ const saved = localStorage.getItem('folderExpandedStates');
13460
+ return saved ? JSON.parse(saved) : {};
13461
+ } catch (_) {
13462
+ return {};
13463
+ }
13443
13464
  }
13444
13465
 
13445
13466
  async saveFolderExpandedStates() {
@@ -13706,6 +13727,84 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13706
13727
  }, this.DISCONNECT_TOAST_GRACE_MS);
13707
13728
  }
13708
13729
 
13730
+ /**
13731
+ * Keep the socket alive across laptop sleep, network changes and
13732
+ * background freezes (v1.9.9). Socket.IO alone recovers too slowly:
13733
+ * - a socket that died while the machine slept still reports
13734
+ * "connected" until its 85 s heartbeat timer fires, and timers do
13735
+ * not advance during suspend, so that can be well over a minute
13736
+ * after the lid opens (or minutes when the network changed and no
13737
+ * TCP reset ever arrives);
13738
+ * - while disconnected, socket.connect() does not cut short a pending
13739
+ * reconnect backoff (up to 30 s), so the old visibilitychange kick
13740
+ * did nothing.
13741
+ * Wake-ups are detected by a timer gap, `online`, `pageshow`, focus and
13742
+ * visibility; each one probes a connected socket with an acked ping and
13743
+ * forces a fresh connection when the probe fails, and makes a
13744
+ * disconnected socket retry immediately.
13745
+ */
13746
+ _installConnectionWatchdog() {
13747
+ if (this._connectionWatchdogInstalled) return;
13748
+ this._connectionWatchdogInstalled = true;
13749
+ this._lastWatchdogTick = Date.now();
13750
+ const timer = setInterval(() => {
13751
+ const now = Date.now();
13752
+ const gap = now - this._lastWatchdogTick;
13753
+ this._lastWatchdogTick = now;
13754
+ if (gap > this.WAKE_GAP_MS) {
13755
+ console.log('[SSHIFT] Resumed after', Math.round(gap / 1000), 's pause, checking connection');
13756
+ this._ensureConnection('wake', { force: true });
13757
+ } else if (!this.socket.connected && !this.socket.active && !this._authRejected) {
13758
+ // Nothing is retrying (server-side disconnect, manual close):
13759
+ // keep trying in the background.
13760
+ this._ensureConnection('idle');
13761
+ }
13762
+ }, 5000);
13763
+ // Node (unit tests) only: don't keep the process alive.
13764
+ if (timer && typeof timer.unref === 'function') timer.unref();
13765
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return;
13766
+ window.addEventListener('online', () => this._ensureConnection('online', { force: true }));
13767
+ window.addEventListener('pageshow', (e) => {
13768
+ if (e.persisted) this._ensureConnection('pageshow', { force: true });
13769
+ });
13770
+ window.addEventListener('focus', () => this._ensureConnection('focus'));
13771
+ }
13772
+
13773
+ _ensureConnection(reason, opts) {
13774
+ const socket = this.socket;
13775
+ if (!socket || this.isUpdating || this._authRejected || this._lockScreenPromise) return;
13776
+ const force = !!(opts && opts.force);
13777
+ if (!socket.connected) {
13778
+ // Skip a pending backoff and dial now. disconnect() resets the
13779
+ // manager (and its backoff); connect() opens a new transport, and
13780
+ // a failure there resumes the normal automatic retries.
13781
+ const now = Date.now();
13782
+ if (!force && this._lastKickAt && now - this._lastKickAt < 3000) return;
13783
+ this._lastKickAt = now;
13784
+ console.log('[SSHIFT] Reconnecting now (' + reason + ')');
13785
+ socket.disconnect();
13786
+ socket.connect();
13787
+ this._armDisconnectToast();
13788
+ return;
13789
+ }
13790
+ // Connected on paper: prove it. Throttled unless this is a real wake.
13791
+ const now = Date.now();
13792
+ if (this._probeInFlight) return;
13793
+ if (!force && this._lastProbeAt && now - this._lastProbeAt < 15000) return;
13794
+ this._lastProbeAt = now;
13795
+ this._probeInFlight = true;
13796
+ const engine = socket.io && socket.io.engine;
13797
+ socket.timeout(this.PROBE_TIMEOUT_MS).emit('sshift-ping', (err) => {
13798
+ this._probeInFlight = false;
13799
+ if (!err) return;
13800
+ // Only tear down the transport the probe was sent on.
13801
+ if (socket.connected && socket.io && socket.io.engine === engine) {
13802
+ console.warn('[SSHIFT] Connection probe timed out (' + reason + '), reconnecting');
13803
+ try { engine.close(); } catch (_) {}
13804
+ }
13805
+ });
13806
+ }
13807
+
13709
13808
  _cancelDisconnectToast() {
13710
13809
  if (this._disconnectToastTimer) {
13711
13810
  clearTimeout(this._disconnectToastTimer);
@@ -13832,9 +13931,13 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13832
13931
 
13833
13932
  // Utility Functions
13834
13933
  escapeHtml(text) {
13835
- const div = document.createElement('div');
13836
- div.textContent = text;
13837
- return div.innerHTML;
13934
+ // Also safe inside quoted attributes (tab names, URLs, ids).
13935
+ return String(text == null ? '' : text)
13936
+ .replace(/&/g, '&amp;')
13937
+ .replace(/</g, '&lt;')
13938
+ .replace(/>/g, '&gt;')
13939
+ .replace(/"/g, '&quot;')
13940
+ .replace(/'/g, '&#39;');
13838
13941
  }
13839
13942
 
13840
13943
  formatSize(bytes) {