@lethevimlet/sshift 1.9.2 → 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.2",
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>
@@ -6053,7 +6053,8 @@ const wheelHandler = (e) => {
6053
6053
  this.closeModal('bookmarkModal');
6054
6054
  });
6055
6055
 
6056
- document.getElementById('saveBookmarkBtn').addEventListener('click', () => {
6056
+ document.getElementById('bookmarkForm').addEventListener('submit', (event) => {
6057
+ event.preventDefault();
6057
6058
  this.saveBookmark();
6058
6059
  });
6059
6060
 
@@ -11090,7 +11091,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11090
11091
 
11091
11092
  // Disconnect
11092
11093
  if (session.type === 'ssh') {
11093
- this.socket.emit('ssh-disconnect', { sessionId });
11094
11094
  // Clean up ResizeObserver
11095
11095
  if (session.resizeObserver) {
11096
11096
  session.resizeObserver.disconnect();
@@ -11152,7 +11152,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11152
11152
  }
11153
11153
  this.sessions.delete(sessionId);
11154
11154
  } else {
11155
- this.socket.emit('sftp-disconnect', { sessionId });
11156
11155
  this.sftpSessions.delete(sessionId);
11157
11156
  }
11158
11157
 
@@ -13085,6 +13084,7 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13085
13084
  }
13086
13085
 
13087
13086
  async saveBookmark() {
13087
+ if (this._savingBookmark) return;
13088
13088
  const id = document.getElementById('bookmarkId').value;
13089
13089
  const name = document.getElementById('bookmarkName').value.trim();
13090
13090
  const type = document.getElementById('bookmarkType').value;
@@ -13124,33 +13124,38 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13124
13124
  if (passphrase) bookmark.passphrase = passphrase;
13125
13125
  }
13126
13126
 
13127
+ this._savingBookmark = true;
13127
13128
  try {
13128
- let response;
13129
- if (id) {
13130
- response = await fetch(`/api/bookmarks/${id}`, {
13131
- method: 'PUT',
13132
- headers: { 'Content-Type': 'application/json' },
13133
- body: JSON.stringify(bookmark)
13134
- });
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;
13135
13138
  } else {
13136
- response = await fetch('/api/bookmarks', {
13137
- method: 'POST',
13139
+ const response = await fetch(id ? `/api/bookmarks/${encodeURIComponent(id)}` : '/api/bookmarks', {
13140
+ method: id ? 'PUT' : 'POST',
13138
13141
  headers: { 'Content-Type': 'application/json' },
13139
13142
  body: JSON.stringify(bookmark)
13140
13143
  });
13141
- }
13142
-
13143
- if (response.ok) {
13144
- this.showToast(id ? 'Bookmark updated' : 'Bookmark added', 'success');
13145
- this.loadBookmarks();
13146
- this.closeModal('bookmarkModal');
13147
- } else {
13148
- throw new Error('Failed to save bookmark');
13149
- }
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');
13150
13155
  } catch (err) {
13151
- if (!this.handleApiFetchError(err)) {
13152
- this.showToast(err.message, 'error');
13153
- }
13156
+ this.showToast(err.message, 'error');
13157
+ } finally {
13158
+ this._savingBookmark = false;
13154
13159
  }
13155
13160
  }
13156
13161