@lethevimlet/sshift 1.9.1 → 1.9.3

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.9.1",
3
+ "version": "1.9.3",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  const { loadConfig, saveConfig } = require('../../utils/config');
6
+ const { saveBookmark } = require('../../services/bookmarks');
6
7
  const {
7
8
  BookmarkEncryptionLockedError,
8
9
  getDecryptedBookmarks,
@@ -10,6 +11,7 @@ const {
10
11
  } = require('../../utils/bookmark-encryption');
11
12
 
12
13
  function handleBookmarkError(res, err) {
14
+ if (err.status === 404) return res.status(404).json({ error: err.message });
13
15
  if (err instanceof BookmarkEncryptionLockedError) {
14
16
  return res.status(423).json({ error: 'Encrypted bookmarks are locked; sign in again' });
15
17
  }
@@ -35,38 +37,8 @@ function registerBookmarkEndpoints(app, io) {
35
37
 
36
38
  // API: Add bookmark
37
39
  app.post('/api/bookmarks', (req, res) => {
38
- const config = loadConfig();
39
- const bookmark = {
40
- id: Date.now().toString(),
41
- name: req.body.name,
42
- type: req.body.type || 'ssh'
43
- };
44
-
45
- // Add type-specific fields
46
- if (req.body.type === 'url') {
47
- bookmark.url = req.body.url;
48
- } else {
49
- bookmark.host = req.body.host;
50
- bookmark.port = req.body.port || 22;
51
- bookmark.username = req.body.username;
52
- }
53
-
54
- // Add optional fields
55
- if (req.body.password) bookmark.password = req.body.password;
56
- if (req.body.privateKey) bookmark.privateKey = req.body.privateKey;
57
- if (req.body.passphrase) bookmark.passphrase = req.body.passphrase;
58
- if (req.body.folderId) bookmark.folderId = req.body.folderId;
59
-
60
40
  try {
61
- const bookmarks = getDecryptedBookmarks(config);
62
- bookmarks.push(bookmark);
63
- storeBookmarks(config, bookmarks);
64
- if (!saveConfig(config)) {
65
- return res.status(500).json({ error: 'Failed to save bookmark' });
66
- }
67
- // Broadcast to all clients
68
- io.emit('bookmark-added', bookmark);
69
- res.json(bookmark);
41
+ res.json(saveBookmark(null, req.body, io));
70
42
  } catch (err) {
71
43
  handleBookmarkError(res, err);
72
44
  }
@@ -91,26 +63,8 @@ function registerBookmarkEndpoints(app, io) {
91
63
 
92
64
  // API: Update bookmark
93
65
  app.put('/api/bookmarks/:id', (req, res) => {
94
- const config = loadConfig();
95
66
  try {
96
- const bookmarks = getDecryptedBookmarks(config);
97
- const index = bookmarks.findIndex(b => b.id === req.params.id);
98
- if (index === -1) {
99
- return res.status(404).json({ error: 'Bookmark not found' });
100
- }
101
- bookmarks[index] = {
102
- ...bookmarks[index],
103
- ...req.body,
104
- id: req.params.id
105
- };
106
- delete bookmarks[index].encryptedConnection;
107
- storeBookmarks(config, bookmarks);
108
- if (!saveConfig(config)) {
109
- return res.status(500).json({ error: 'Failed to update bookmark' });
110
- }
111
- // Broadcast decrypted data only to authenticated, connected clients.
112
- io.emit('bookmark-updated', bookmarks[index]);
113
- res.json(bookmarks[index]);
67
+ res.json(saveBookmark(req.params.id, req.body, io));
114
68
  } catch (err) {
115
69
  handleBookmarkError(res, err);
116
70
  }
@@ -0,0 +1,26 @@
1
+ const { isPasswordSet } = require('../../utils/config');
2
+ const { isValidAuthToken } = require('../rest/auth');
3
+ const { BookmarkEncryptionLockedError } = require('../../utils/bookmark-encryption');
4
+ const { saveBookmark } = require('../../services/bookmarks');
5
+
6
+ function registerBookmarkHandlers(socket, io) {
7
+ socket.on('bookmark-save', (data, acknowledge) => {
8
+ if (typeof acknowledge !== 'function') return;
9
+ const token = socket.handshake.auth?.token || socket.handshake.query?.token;
10
+ if (isPasswordSet() && !isValidAuthToken(token)) {
11
+ return acknowledge({ error: 'Authentication required' });
12
+ }
13
+ if (!data || !data.bookmark || typeof data.bookmark !== 'object' || Array.isArray(data.bookmark)) {
14
+ return acknowledge({ error: 'Invalid bookmark' });
15
+ }
16
+ try {
17
+ acknowledge({ bookmark: saveBookmark(data.id, data.bookmark, io) });
18
+ } catch (err) {
19
+ acknowledge({ error: err instanceof BookmarkEncryptionLockedError
20
+ ? 'Encrypted bookmarks are locked; sign in again'
21
+ : err.status === 404 ? err.message : 'Failed to save bookmark' });
22
+ }
23
+ });
24
+ }
25
+
26
+ module.exports = { registerBookmarkHandlers };
@@ -7,6 +7,7 @@ const { registerSSHHandlers, handleSSHDisconnect } = require('./ssh');
7
7
  const { registerSFTPHandlers, handleSFTPDisconnect } = require('./sftp');
8
8
  const { registerTabHandlers, handleTabDisconnect } = require('./tabs');
9
9
  const { registerLayoutHandlers, getCurrentLayout, setCurrentLayout } = require('./layout');
10
+ const { registerBookmarkHandlers } = require('./bookmarks');
10
11
 
11
12
  /**
12
13
  * Register all WebSocket handlers
@@ -18,6 +19,7 @@ function registerAllWSHandlers(socket, io) {
18
19
  registerSFTPHandlers(socket, io);
19
20
  registerTabHandlers(socket, io);
20
21
  registerLayoutHandlers(socket, io);
22
+ registerBookmarkHandlers(socket, io);
21
23
  }
22
24
 
23
25
  /**
@@ -43,4 +45,4 @@ module.exports = {
43
45
  setCurrentLayout,
44
46
  registerAllWSHandlers,
45
47
  handleDisconnect
46
- };
48
+ };
@@ -262,7 +262,7 @@ function registerSSHHandlers(socket, io) {
262
262
  });
263
263
 
264
264
  // SSH disconnect — historically meant "I'm done with this session locally".
265
- // Treat it identically to tab-close: viewer-aware + sticky-aware teardown.
265
+ // Detach this viewer, unlike tab-close which explicitly ends the session.
266
266
  // Only destroy the underlying SSH stream when no other clients remain AND
267
267
  // the session is non-sticky. This lets the orchestrator close their view
268
268
  // without yanking the session out from under sticky observers (or shedding
@@ -335,4 +335,4 @@ function handleSSHDisconnect(socket, io) {
335
335
  };
336
336
  }
337
337
 
338
- module.exports = { registerSSHHandlers, handleSSHDisconnect };
338
+ module.exports = { registerSSHHandlers, handleSSHDisconnect };
@@ -26,70 +26,24 @@ const { sshManager, sftpManager } = require('../../services');
26
26
  * @param {Object} io - Socket.IO instance
27
27
  */
28
28
  function registerTabHandlers(socket, io) {
29
- // Tab close event (client-side tab close, not full disconnect)
29
+ // An explicit close ends the shared session. Socket disconnect/reload is
30
+ // handled separately below and retains sticky sessions/reconnect grace.
30
31
  socket.on('tab-close', (data) => {
31
32
  console.log('[TAB] Tab closed:', data.sessionId, 'by socket:', socket.id);
32
-
33
- // Remove this socket from the tab's active sockets
34
33
  const tab = getTab(data.sessionId);
34
+ clearCloseTimer(data.sessionId);
35
+ // Remove restoration state before disconnecting the stream, which can
36
+ // synchronously emit events. No reconnect should resurrect a closed tab.
37
+ removeTab(data.sessionId);
35
38
  if (tab) {
36
- removeSocketFromTab(data.sessionId, socket.id);
37
-
38
- // If other sockets are still viewing this tab, the originating
39
- // client's close must NOT tear down the session for them.
40
- // Just notify remaining viewers to refresh their sessions list.
41
- // The originating client already removed the tab locally via
42
- // closeTab() (app.js), so it does NOT need a tab-closed echo.
43
- if (tab.activeSockets.size > 0) {
44
- console.log('[TAB] Tab closed by', socket.id, 'but', tab.activeSockets.size, 'viewer(s) remain; keeping session:', data.sessionId);
45
- // SSH: drop this socket from the session room so it stops
46
- // receiving broadcasts from this session.
47
- if (tab.type === 'ssh') {
48
- sshManager.leaveSession(socket, data.sessionId);
49
- }
50
- // Tell remaining clients to refresh any open "manage sessions"
51
- // modal — they may want to reflect the new viewer count.
52
- io.emit('sessions-updated');
53
- return;
39
+ if (tab.type === 'ssh') {
40
+ sshManager.disconnect(data.sessionId);
41
+ } else if (tab.type === 'sftp') {
42
+ sftpManager.disconnect(data.sessionId);
54
43
  }
55
-
56
- // No more viewers left after this close. Honor the sticky flag:
57
- // sticky sessions stay alive on the server indefinitely (until
58
- // explicitly killed by another path or server restart). Non-
59
- // sticky sessions get the same 5s grace path used by
60
- // handleTabDisconnect, so a transient close-then-reopen round-
61
- // trip (e.g. closing and reloading a devtools session) doesn't
62
- // yank the SSH connection out from under the user.
63
- clearCloseTimer(data.sessionId);
64
- if (tab.sticky) {
65
- console.log('[TAB] Sticky session remains open on server (no viewers):', data.sessionId);
66
- io.emit('sessions-updated');
67
- return;
68
- }
69
-
70
- console.log('[TAB] Non-sticky session, scheduling close after grace period:', data.sessionId);
71
- const gracePeriod = 5000;
72
- setCloseTimer(data.sessionId, setTimeout(() => {
73
- const currentTab = getTab(data.sessionId);
74
- if (currentTab && currentTab.activeSockets.size === 0) {
75
- console.log('[TAB] Grace period expired, closing session:', data.sessionId);
76
- if (currentTab.type === 'ssh') {
77
- sshManager.disconnect(data.sessionId);
78
- } else if (currentTab.type === 'sftp') {
79
- sftpManager.disconnect(data.sessionId);
80
- }
81
- removeTab(data.sessionId);
82
- io.emit('tab-closed', { sessionId: data.sessionId });
83
- io.emit('sessions-updated');
84
- } else {
85
- console.log('[TAB] Session has new sockets, canceling close:', data.sessionId);
86
- }
87
- }, gracePeriod));
88
- } else {
89
- // No tab record — broadcast close so stale client UIs clear it.
90
- io.emit('tab-closed', { sessionId: data.sessionId });
91
- io.emit('sessions-updated');
92
44
  }
45
+ io.emit('tab-closed', { sessionId: data.sessionId });
46
+ io.emit('sessions-updated');
93
47
  });
94
48
 
95
49
  // Tab reorder event
@@ -0,0 +1,39 @@
1
+ /** Shared bookmark writes for REST and authenticated WebSockets. */
2
+ const { loadConfig, saveConfig } = require('../utils/config');
3
+ const { getDecryptedBookmarks, storeBookmarks } = require('../utils/bookmark-encryption');
4
+
5
+ function saveBookmark(id, data, io) {
6
+ const config = loadConfig();
7
+ const bookmarks = getDecryptedBookmarks(config);
8
+ let bookmark;
9
+ if (id) {
10
+ const index = bookmarks.findIndex(b => b.id === id);
11
+ if (index === -1) {
12
+ const error = new Error('Bookmark not found');
13
+ error.status = 404;
14
+ throw error;
15
+ }
16
+ bookmark = { ...bookmarks[index], ...data, id };
17
+ delete bookmark.encryptedConnection;
18
+ bookmarks[index] = bookmark;
19
+ } else {
20
+ bookmark = { id: Date.now().toString(), name: data.name, type: data.type || 'ssh' };
21
+ if (bookmark.type === 'url') {
22
+ bookmark.url = data.url;
23
+ } else {
24
+ bookmark.host = data.host;
25
+ bookmark.port = data.port || 22;
26
+ bookmark.username = data.username;
27
+ }
28
+ for (const field of ['password', 'privateKey', 'passphrase', 'folderId']) {
29
+ if (data[field]) bookmark[field] = data[field];
30
+ }
31
+ bookmarks.push(bookmark);
32
+ }
33
+ storeBookmarks(config, bookmarks);
34
+ if (!saveConfig(config)) throw new Error('Failed to save bookmark');
35
+ io.emit(id ? 'bookmark-updated' : 'bookmark-added', bookmark);
36
+ return bookmark;
37
+ }
38
+
39
+ module.exports = { saveBookmark };
@@ -548,8 +548,8 @@
548
548
  </form>
549
549
  </div>
550
550
  <div class="modal-footer">
551
- <button class="btn" id="cancelBookmark">Cancel</button>
552
- <button class="btn btn-primary" id="saveBookmarkBtn">
551
+ <button type="button" class="btn" id="cancelBookmark">Cancel</button>
552
+ <button type="submit" form="bookmarkForm" class="btn btn-primary" id="saveBookmarkBtn">
553
553
  <i class="fas fa-save"></i> Save
554
554
  </button>
555
555
  </div>
@@ -1315,9 +1315,15 @@
1315
1315
  <div id="customCertWarning" class="sw-custom-cert-warning" style="display: none; margin-top: 8px;">
1316
1316
  <i class="fas fa-exclamation-circle"></i> A custom certificate is configured. Download the certificate from your administrator.
1317
1317
  </div>
1318
- <button class="btn btn-secondary" id="downloadCertBtn" style="margin-top: 8px;">
1319
- <i class="fas fa-download"></i> Download CA Certificate
1320
- </button>
1318
+ <button class="btn btn-secondary" id="downloadCertBtn" style="margin-top: 8px;">
1319
+ <i class="fas fa-download"></i> Download CA Certificate
1320
+ </button>
1321
+ <a class="btn btn-secondary" id="acceptCertBtn" href="/api/version" target="_blank" rel="noopener noreferrer" style="margin-top: 8px;">
1322
+ <i class="fas fa-external-link-alt"></i> Re-accept Certificate
1323
+ </a>
1324
+ <div class="setting-description" style="margin-top: 8px;">
1325
+ If the app loaded but API requests fail, open this link, choose <strong>Advanced → Proceed</strong>, then return and reload SSHIFT. This exception is temporary; installing the CA is optional but permanent.
1326
+ </div>
1321
1327
  </div>
1322
1328
  </div>
1323
1329
  </div>
@@ -81,6 +81,7 @@ class SSHIFTClient {
81
81
  this.passwordEnabled = false;
82
82
  this.bookmarkEncryptionEnabled = false;
83
83
  this.authToken = localStorage.getItem('sshift_auth_token') || null;
84
+ this._certificateAcceptanceRequired = false;
84
85
 
85
86
  this._origFetch = window.fetch.bind(window);
86
87
  window.fetch = (url, options = {}) => {
@@ -6052,7 +6053,8 @@ const wheelHandler = (e) => {
6052
6053
  this.closeModal('bookmarkModal');
6053
6054
  });
6054
6055
 
6055
- document.getElementById('saveBookmarkBtn').addEventListener('click', () => {
6056
+ document.getElementById('bookmarkForm').addEventListener('submit', (event) => {
6057
+ event.preventDefault();
6056
6058
  this.saveBookmark();
6057
6059
  });
6058
6060
 
@@ -7061,7 +7063,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7061
7063
  const swStatusContainer = document.getElementById('swStatusContainer');
7062
7064
 
7063
7065
  let swStatus = window._swStatus;
7064
- if (navigator.serviceWorker && navigator.serviceWorker.controller) {
7066
+ if (!this._certificateAcceptanceRequired && navigator.serviceWorker && navigator.serviceWorker.controller) {
7065
7067
  swStatus = 'active';
7066
7068
  window._swStatus = 'active';
7067
7069
  }
@@ -7090,7 +7092,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7090
7092
  '<li><i class="fas fa-times"></i> Installable as app (PWA)</li>' +
7091
7093
  '<li><i class="fas fa-times"></i> Clipboard API access</li>' +
7092
7094
  '</ul>' +
7093
- '<p class="sw-hint">Trust the HTTPS certificate to enable all features.</p>';
7095
+ '<p class="sw-hint">Re-accept the certificate to continue without installing it, or trust the local CA to enable all features.</p>';
7094
7096
  } else if (swStatus === 'redundant') {
7095
7097
  swStatusContainer.classList.add('sw-status-failed');
7096
7098
  swStatusIcon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
@@ -7126,6 +7128,22 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7126
7128
  this.openModal('securityInfoModal');
7127
7129
  }
7128
7130
 
7131
+ handleApiFetchError(err) {
7132
+ const swError = String(window._swError || '').toLowerCase();
7133
+ const certificateFailure = window.location.protocol === 'https:' &&
7134
+ err instanceof TypeError &&
7135
+ window._swStatus === 'failed' &&
7136
+ (swError.includes('ssl') || swError.includes('certificate'));
7137
+
7138
+ if (!certificateFailure) return false;
7139
+
7140
+ this._certificateAcceptanceRequired = true;
7141
+ window._swError = 'The browser no longer accepts this HTTPS certificate. Re-accept it to continue, or install the local CA for permanent trust.';
7142
+ this.showToast('HTTPS certificate approval required', 'error');
7143
+ this.openSecurityInfoDialog();
7144
+ return true;
7145
+ }
7146
+
7129
7147
  // Debug Info Dialog
7130
7148
  initDebugInfoDialog() {
7131
7149
  const showBtn = document.getElementById('showDebugInfoBtn');
@@ -11073,7 +11091,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11073
11091
 
11074
11092
  // Disconnect
11075
11093
  if (session.type === 'ssh') {
11076
- this.socket.emit('ssh-disconnect', { sessionId });
11077
11094
  // Clean up ResizeObserver
11078
11095
  if (session.resizeObserver) {
11079
11096
  session.resizeObserver.disconnect();
@@ -11135,7 +11152,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11135
11152
  }
11136
11153
  this.sessions.delete(sessionId);
11137
11154
  } else {
11138
- this.socket.emit('sftp-disconnect', { sessionId });
11139
11155
  this.sftpSessions.delete(sessionId);
11140
11156
  }
11141
11157
 
@@ -13068,6 +13084,7 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13068
13084
  }
13069
13085
 
13070
13086
  async saveBookmark() {
13087
+ if (this._savingBookmark) return;
13071
13088
  const id = document.getElementById('bookmarkId').value;
13072
13089
  const name = document.getElementById('bookmarkName').value.trim();
13073
13090
  const type = document.getElementById('bookmarkType').value;
@@ -13107,31 +13124,38 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13107
13124
  if (passphrase) bookmark.passphrase = passphrase;
13108
13125
  }
13109
13126
 
13127
+ this._savingBookmark = true;
13110
13128
  try {
13111
- let response;
13112
- if (id) {
13113
- response = await fetch(`/api/bookmarks/${id}`, {
13114
- method: 'PUT',
13115
- headers: { 'Content-Type': 'application/json' },
13116
- body: JSON.stringify(bookmark)
13117
- });
13129
+ let savedBookmark;
13130
+ // Reuse the authenticated terminal connection. A fresh HTTPS fetch can
13131
+ // fail when the browser's temporary certificate exception has expired,
13132
+ // even though this socket is still healthy. REST remains available when
13133
+ // the socket is offline; never retry an ambiguous create automatically.
13134
+ if (this.socket.connected) {
13135
+ const result = await this.socket.timeout(10000).emitWithAck('bookmark-save', { id, bookmark });
13136
+ if (result.error) throw new Error(result.error);
13137
+ savedBookmark = result.bookmark;
13118
13138
  } else {
13119
- response = await fetch('/api/bookmarks', {
13120
- method: 'POST',
13139
+ const response = await fetch(id ? `/api/bookmarks/${encodeURIComponent(id)}` : '/api/bookmarks', {
13140
+ method: id ? 'PUT' : 'POST',
13121
13141
  headers: { 'Content-Type': 'application/json' },
13122
13142
  body: JSON.stringify(bookmark)
13123
13143
  });
13124
- }
13125
-
13126
- if (response.ok) {
13127
- this.showToast(id ? 'Bookmark updated' : 'Bookmark added', 'success');
13128
- this.loadBookmarks();
13129
- this.closeModal('bookmarkModal');
13130
- } else {
13131
- throw new Error('Failed to save bookmark');
13132
- }
13144
+ const result = await response.json();
13145
+ if (!response.ok) throw new Error(result.error || 'Failed to save bookmark');
13146
+ savedBookmark = result;
13147
+ }
13148
+ if (!savedBookmark || !savedBookmark.id) throw new Error('Failed to save bookmark');
13149
+ const index = this.bookmarks.findIndex(b => b.id === savedBookmark.id);
13150
+ if (index === -1) this.bookmarks.push(savedBookmark);
13151
+ else this.bookmarks[index] = savedBookmark;
13152
+ this.renderBookmarks();
13153
+ this.showToast(id ? 'Bookmark updated' : 'Bookmark added', 'success');
13154
+ this.closeModal('bookmarkModal');
13133
13155
  } catch (err) {
13134
13156
  this.showToast(err.message, 'error');
13157
+ } finally {
13158
+ this._savingBookmark = false;
13135
13159
  }
13136
13160
  }
13137
13161