@lethevimlet/sshift 1.8.3 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,8 @@
12
12
  "webglRenderer": true,
13
13
  "imageAddonEnabled": true,
14
14
  "passwordHash": null,
15
+ "bookmarkEncryptionEnabled": false,
16
+ "bookmarkEncryptionSalt": null,
15
17
  "plugins": [
16
18
  {
17
19
  "name": "opencode-attention",
@@ -184,4 +186,4 @@
184
186
  ]
185
187
  }
186
188
  ]
187
- }
189
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.8.3",
3
+ "version": "1.9.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -1,7 +1,23 @@
1
- const { isPasswordSet, verifyPassword, setPassword, removePassword } = require('../../utils/config');
1
+ const {
2
+ hashPassword,
3
+ isPasswordSet,
4
+ loadConfig,
5
+ saveConfig,
6
+ verifyPasswordAsync
7
+ } = require('../../utils/config');
8
+ const {
9
+ clearBookmarkEncryptionKey,
10
+ decryptBookmarksWithPassword,
11
+ prepareEncryptedBookmarks,
12
+ setBookmarkEncryptionKey,
13
+ unlockBookmarkEncryption
14
+ } = require('../../utils/bookmark-encryption');
2
15
 
3
16
  const authTokens = new Map();
17
+ const loginAttempts = new Map();
4
18
  const TOKEN_TTL = 24 * 60 * 60 * 1000;
19
+ const LOGIN_WINDOW_MS = 60 * 1000;
20
+ const MAX_LOGIN_ATTEMPTS = 5;
5
21
 
6
22
  function generateToken() {
7
23
  const crypto = require('crypto');
@@ -15,12 +31,59 @@ function cleanExpiredTokens() {
15
31
  }
16
32
  }
17
33
 
34
+ function getLoginAttemptKey(req) {
35
+ return req.ip || req.socket?.remoteAddress || 'unknown';
36
+ }
37
+
38
+ function isLoginRateLimited(req) {
39
+ const key = getLoginAttemptKey(req);
40
+ const now = Date.now();
41
+ const attempts = (loginAttempts.get(key) || []).filter(time => now - time < LOGIN_WINDOW_MS);
42
+ if (attempts.length === 0) loginAttempts.delete(key);
43
+ else loginAttempts.set(key, attempts);
44
+ return attempts.length >= MAX_LOGIN_ATTEMPTS;
45
+ }
46
+
47
+ function reserveLoginAttempt(req) {
48
+ const key = getLoginAttemptKey(req);
49
+ const attempts = loginAttempts.get(key) || [];
50
+ attempts.push(Date.now());
51
+ loginAttempts.set(key, attempts);
52
+ }
53
+
54
+ function clearFailedLogins(req) {
55
+ loginAttempts.delete(getLoginAttemptKey(req));
56
+ }
57
+
58
+ function notifyEncryptionState(io, enabled) {
59
+ if (io && typeof io.emit === 'function') {
60
+ io.emit('bookmark-encryption-changed', { enabled });
61
+ }
62
+ }
63
+
64
+ function notifyAuthState(io, passwordEnabled) {
65
+ if (io && typeof io.emit === 'function') {
66
+ io.emit('auth-state-changed', { passwordEnabled });
67
+ }
68
+ }
69
+
70
+ function revokeAuthenticatedClients(io) {
71
+ authTokens.clear();
72
+ if (io && typeof io.disconnectSockets === 'function') {
73
+ setTimeout(() => io.disconnectSockets(true), 50);
74
+ }
75
+ }
76
+
18
77
  function registerAuthEndpoints(app, io) {
19
78
  app.get('/api/auth/status', (req, res) => {
20
- res.json({ passwordEnabled: isPasswordSet() });
79
+ const config = loadConfig();
80
+ res.json({
81
+ passwordEnabled: !!config.passwordHash,
82
+ bookmarkEncryptionEnabled: config.bookmarkEncryptionEnabled === true
83
+ });
21
84
  });
22
85
 
23
- app.post('/api/auth/login', (req, res) => {
86
+ app.post('/api/auth/login', async (req, res) => {
24
87
  const { password } = req.body;
25
88
  if (!isPasswordSet()) {
26
89
  return res.json({ success: true, authenticated: true });
@@ -28,48 +91,154 @@ function registerAuthEndpoints(app, io) {
28
91
  if (!password) {
29
92
  return res.status(400).json({ error: 'Password required' });
30
93
  }
31
- if (!verifyPassword(password)) {
94
+ if (isLoginRateLimited(req)) {
95
+ return res.status(429).json({ error: 'Too many login attempts; try again shortly' });
96
+ }
97
+ // Reserve a slot before starting scrypt so concurrent bursts cannot all
98
+ // pass the limit while earlier password checks are still in flight.
99
+ reserveLoginAttempt(req);
100
+ if (!await verifyPasswordAsync(password)) {
32
101
  return res.status(401).json({ error: 'Invalid password' });
33
102
  }
103
+ clearFailedLogins(req);
104
+ try {
105
+ unlockBookmarkEncryption(loadConfig(), password);
106
+ } catch (err) {
107
+ console.error('[AUTH] Failed to unlock encrypted bookmarks:', err.message);
108
+ return res.status(500).json({ error: 'Encrypted bookmarks could not be unlocked' });
109
+ }
34
110
  const token = generateToken();
35
111
  authTokens.set(token, Date.now() + TOKEN_TTL);
36
112
  cleanExpiredTokens();
37
113
  res.json({ success: true, token });
38
114
  });
39
115
 
40
- app.post('/api/auth/set-password', (req, res) => {
116
+ app.post('/api/auth/set-password', async (req, res) => {
41
117
  const { currentPassword, newPassword } = req.body;
42
118
  if (isPasswordSet()) {
43
- if (!currentPassword || !verifyPassword(currentPassword)) {
119
+ if (!currentPassword || !await verifyPasswordAsync(currentPassword)) {
44
120
  return res.status(401).json({ error: 'Current password is incorrect' });
45
121
  }
46
122
  }
47
123
  if (!newPassword || newPassword.length < 1) {
48
124
  return res.status(400).json({ error: 'Password cannot be empty' });
49
125
  }
50
- const result = setPassword(newPassword);
51
- if (result) {
126
+ const config = loadConfig();
127
+ const encryptionRequested = req.body.encryptBookmarks === undefined
128
+ ? config.bookmarkEncryptionEnabled === true
129
+ : req.body.encryptBookmarks === true;
130
+
131
+ try {
132
+ let bookmarks = config.bookmarks || [];
133
+ if (config.bookmarkEncryptionEnabled) {
134
+ bookmarks = decryptBookmarksWithPassword(config, currentPassword).bookmarks;
135
+ }
136
+
137
+ let nextKey = null;
138
+ if (encryptionRequested) {
139
+ const encrypted = prepareEncryptedBookmarks(bookmarks, newPassword);
140
+ config.bookmarks = encrypted.bookmarks;
141
+ config.bookmarkEncryptionEnabled = true;
142
+ config.bookmarkEncryptionSalt = encrypted.salt;
143
+ nextKey = encrypted.key;
144
+ } else {
145
+ config.bookmarks = bookmarks;
146
+ config.bookmarkEncryptionEnabled = false;
147
+ config.bookmarkEncryptionSalt = null;
148
+ }
149
+ config.passwordHash = hashPassword(newPassword);
150
+
151
+ if (!saveConfig(config)) {
152
+ return res.status(500).json({ error: 'Failed to save password' });
153
+ }
154
+ setBookmarkEncryptionKey(nextKey);
155
+ notifyEncryptionState(io, encryptionRequested);
156
+ notifyAuthState(io, true);
157
+ revokeAuthenticatedClients(io);
52
158
  res.json({ success: true });
53
- } else {
54
- res.status(500).json({ error: 'Failed to save password' });
159
+ } catch (err) {
160
+ console.error('[AUTH] Failed to configure password protection:', err.message);
161
+ res.status(500).json({ error: 'Failed to configure bookmark encryption' });
55
162
  }
56
163
  });
57
164
 
58
- app.post('/api/auth/remove-password', (req, res) => {
165
+ app.post('/api/auth/remove-password', async (req, res) => {
59
166
  const { currentPassword } = req.body;
60
167
  if (!isPasswordSet()) {
61
168
  return res.json({ success: true });
62
169
  }
63
- if (!currentPassword || !verifyPassword(currentPassword)) {
170
+ if (!currentPassword || !await verifyPasswordAsync(currentPassword)) {
64
171
  return res.status(401).json({ error: 'Current password is incorrect' });
65
172
  }
66
- const result = removePassword();
67
- if (result) {
173
+ const config = loadConfig();
174
+ try {
175
+ if (config.bookmarkEncryptionEnabled) {
176
+ config.bookmarks = decryptBookmarksWithPassword(config, currentPassword).bookmarks;
177
+ config.bookmarkEncryptionEnabled = false;
178
+ config.bookmarkEncryptionSalt = null;
179
+ }
180
+ config.passwordHash = null;
181
+ if (!saveConfig(config)) {
182
+ return res.status(500).json({ error: 'Failed to remove password' });
183
+ }
184
+ clearBookmarkEncryptionKey();
185
+ notifyEncryptionState(io, false);
186
+ notifyAuthState(io, false);
187
+ revokeAuthenticatedClients(io);
68
188
  res.json({ success: true });
69
- } else {
70
- res.status(500).json({ error: 'Failed to remove password' });
189
+ } catch (err) {
190
+ console.error('[AUTH] Failed to disable password protection:', err.message);
191
+ res.status(500).json({ error: 'Failed to decrypt bookmarks before removing password' });
71
192
  }
72
193
  });
194
+
195
+ app.post('/api/auth/bookmark-encryption', async (req, res) => {
196
+ const { currentPassword, enabled } = req.body;
197
+ if (!isPasswordSet()) {
198
+ return res.status(400).json({ error: 'Password protection must be enabled first' });
199
+ }
200
+ if (!currentPassword || !await verifyPasswordAsync(currentPassword)) {
201
+ return res.status(401).json({ error: 'Current password is incorrect' });
202
+ }
203
+
204
+ const config = loadConfig();
205
+ try {
206
+ if (enabled) {
207
+ if (!config.bookmarkEncryptionEnabled) {
208
+ const encrypted = prepareEncryptedBookmarks(config.bookmarks || [], currentPassword);
209
+ config.bookmarks = encrypted.bookmarks;
210
+ config.bookmarkEncryptionEnabled = true;
211
+ config.bookmarkEncryptionSalt = encrypted.salt;
212
+ if (!saveConfig(config)) {
213
+ return res.status(500).json({ error: 'Failed to enable bookmark encryption' });
214
+ }
215
+ setBookmarkEncryptionKey(encrypted.key);
216
+ } else {
217
+ unlockBookmarkEncryption(config, currentPassword);
218
+ }
219
+ } else if (config.bookmarkEncryptionEnabled) {
220
+ const decrypted = decryptBookmarksWithPassword(config, currentPassword);
221
+ config.bookmarks = decrypted.bookmarks;
222
+ config.bookmarkEncryptionEnabled = false;
223
+ config.bookmarkEncryptionSalt = null;
224
+ if (!saveConfig(config)) {
225
+ return res.status(500).json({ error: 'Failed to disable bookmark encryption' });
226
+ }
227
+ clearBookmarkEncryptionKey();
228
+ }
229
+ notifyEncryptionState(io, enabled === true);
230
+ res.json({ success: true, bookmarkEncryptionEnabled: enabled === true });
231
+ } catch (err) {
232
+ console.error('[AUTH] Failed to update bookmark encryption:', err.message);
233
+ res.status(500).json({ error: 'Failed to update bookmark encryption' });
234
+ }
235
+ });
236
+
237
+ app.post('/api/auth/logout', (req, res) => {
238
+ const token = req.headers.authorization?.replace('Bearer ', '');
239
+ if (token) authTokens.delete(token);
240
+ res.json({ success: true });
241
+ });
73
242
  }
74
243
 
75
244
  function isValidAuthToken(token) {
@@ -84,4 +253,4 @@ function isValidAuthToken(token) {
84
253
  return true;
85
254
  }
86
255
 
87
- module.exports = { registerAuthEndpoints, isValidAuthToken };
256
+ module.exports = { registerAuthEndpoints, isValidAuthToken };
@@ -3,6 +3,19 @@
3
3
  */
4
4
 
5
5
  const { loadConfig, saveConfig } = require('../../utils/config');
6
+ const {
7
+ BookmarkEncryptionLockedError,
8
+ getDecryptedBookmarks,
9
+ storeBookmarks
10
+ } = require('../../utils/bookmark-encryption');
11
+
12
+ function handleBookmarkError(res, err) {
13
+ if (err instanceof BookmarkEncryptionLockedError) {
14
+ return res.status(423).json({ error: 'Encrypted bookmarks are locked; sign in again' });
15
+ }
16
+ console.error('[BOOKMARKS] Failed to process bookmarks:', err.message);
17
+ return res.status(500).json({ error: 'Failed to process bookmarks' });
18
+ }
6
19
 
7
20
  /**
8
21
  * Register bookmark endpoints
@@ -12,8 +25,12 @@ const { loadConfig, saveConfig } = require('../../utils/config');
12
25
  function registerBookmarkEndpoints(app, io) {
13
26
  // API: Get bookmarks
14
27
  app.get('/api/bookmarks', (req, res) => {
15
- const config = loadConfig();
16
- res.json(config.bookmarks);
28
+ try {
29
+ const config = loadConfig();
30
+ res.json(getDecryptedBookmarks(config));
31
+ } catch (err) {
32
+ handleBookmarkError(res, err);
33
+ }
17
34
  });
18
35
 
19
36
  // API: Add bookmark
@@ -40,48 +57,62 @@ function registerBookmarkEndpoints(app, io) {
40
57
  if (req.body.passphrase) bookmark.passphrase = req.body.passphrase;
41
58
  if (req.body.folderId) bookmark.folderId = req.body.folderId;
42
59
 
43
- config.bookmarks.push(bookmark);
44
- if (saveConfig(config)) {
60
+ 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
+ }
45
67
  // Broadcast to all clients
46
68
  io.emit('bookmark-added', bookmark);
47
69
  res.json(bookmark);
48
- } else {
49
- res.status(500).json({ error: 'Failed to save bookmark' });
70
+ } catch (err) {
71
+ handleBookmarkError(res, err);
50
72
  }
51
73
  });
52
74
 
53
75
  // API: Delete bookmark
54
76
  app.delete('/api/bookmarks/:id', (req, res) => {
55
77
  const config = loadConfig();
56
- config.bookmarks = config.bookmarks.filter(b => b.id !== req.params.id);
57
- if (saveConfig(config)) {
78
+ try {
79
+ const bookmarks = getDecryptedBookmarks(config).filter(b => b.id !== req.params.id);
80
+ storeBookmarks(config, bookmarks);
81
+ if (!saveConfig(config)) {
82
+ return res.status(500).json({ error: 'Failed to delete bookmark' });
83
+ }
58
84
  // Broadcast to all clients
59
85
  io.emit('bookmark-deleted', { id: req.params.id });
60
86
  res.json({ success: true });
61
- } else {
62
- res.status(500).json({ error: 'Failed to delete bookmark' });
87
+ } catch (err) {
88
+ handleBookmarkError(res, err);
63
89
  }
64
90
  });
65
91
 
66
92
  // API: Update bookmark
67
93
  app.put('/api/bookmarks/:id', (req, res) => {
68
94
  const config = loadConfig();
69
- const index = config.bookmarks.findIndex(b => b.id === req.params.id);
70
- if (index !== -1) {
71
- config.bookmarks[index] = {
72
- ...config.bookmarks[index],
95
+ 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],
73
103
  ...req.body,
74
104
  id: req.params.id
75
105
  };
76
- if (saveConfig(config)) {
77
- // Broadcast to all clients
78
- io.emit('bookmark-updated', config.bookmarks[index]);
79
- res.json(config.bookmarks[index]);
80
- } else {
81
- res.status(500).json({ error: 'Failed to update bookmark' });
106
+ delete bookmarks[index].encryptedConnection;
107
+ storeBookmarks(config, bookmarks);
108
+ if (!saveConfig(config)) {
109
+ return res.status(500).json({ error: 'Failed to update bookmark' });
82
110
  }
83
- } else {
84
- res.status(404).json({ error: 'Bookmark not found' });
111
+ // Broadcast decrypted data only to authenticated, connected clients.
112
+ io.emit('bookmark-updated', bookmarks[index]);
113
+ res.json(bookmarks[index]);
114
+ } catch (err) {
115
+ handleBookmarkError(res, err);
85
116
  }
86
117
  });
87
118
 
@@ -103,4 +134,4 @@ function registerBookmarkEndpoints(app, io) {
103
134
  });
104
135
  }
105
136
 
106
- module.exports = { registerBookmarkEndpoints };
137
+ module.exports = { registerBookmarkEndpoints };
@@ -22,7 +22,8 @@ function registerConfigEndpoints(app, io) {
22
22
  webglRenderer: config.webglRenderer !== false,
23
23
  imageAddonEnabled: config.imageAddonEnabled !== false,
24
24
  layouts: config.layouts || null,
25
- passwordEnabled: !!config.passwordHash
25
+ passwordEnabled: !!config.passwordHash,
26
+ bookmarkEncryptionEnabled: config.bookmarkEncryptionEnabled === true
26
27
  });
27
28
  });
28
29
 
@@ -89,4 +90,4 @@ function registerConfigEndpoints(app, io) {
89
90
  });
90
91
  }
91
92
 
92
- module.exports = { registerConfigEndpoints };
93
+ module.exports = { registerConfigEndpoints };
@@ -15,6 +15,7 @@ const {
15
15
  updateTabName,
16
16
  updateTabPanel,
17
17
  setActiveTab,
18
+ setActiveSession,
18
19
  getOpenTabs
19
20
  } = require('../../utils/tab-manager');
20
21
  const { sshManager, sftpManager } = require('../../services');
@@ -136,6 +137,7 @@ function registerTabHandlers(socket, io) {
136
137
  }
137
138
  }
138
139
  });
140
+ setActiveSession(data.activeSessionId);
139
141
  }
140
142
  // Don't update tab order for empty tab lists — a new client syncing
141
143
  // before receiving server tabs would wipe the server-side tab order.
@@ -146,7 +148,8 @@ function registerTabHandlers(socket, io) {
146
148
  if (data.tabs && data.tabs.length > 0) {
147
149
  socket.broadcast.emit('tabs-sync', {
148
150
  tabs: data.tabs,
149
- layout: data.layout
151
+ layout: data.layout,
152
+ activeSessionId: data.activeSessionId
150
153
  });
151
154
  }
152
155
  });
@@ -225,4 +228,4 @@ function handleTabDisconnect(socket, io) {
225
228
  };
226
229
  }
227
230
 
228
- module.exports = { registerTabHandlers, handleTabDisconnect };
231
+ module.exports = { registerTabHandlers, handleTabDisconnect };
@@ -282,7 +282,7 @@ async function initializeServer() {
282
282
  // localStorage (they survive server restarts and can differ per
283
283
  // device). Broadcasting them here used to clobber every new client's
284
284
  // own preference with the server's in-memory copy.
285
- const { getOpenTabs, getTabOrder, getActiveTabsByPanel } = require('./utils/tab-manager');
285
+ const { getOpenTabs, getTabOrder, getActiveTabsByPanel, getActiveSession } = require('./utils/tab-manager');
286
286
 
287
287
  const openTabs = getOpenTabs();
288
288
  const tabOrder = getTabOrder();
@@ -330,7 +330,8 @@ async function initializeServer() {
330
330
 
331
331
  socket.emit('open-tabs', {
332
332
  tabs: orderedTabs,
333
- activeTabsByPanel
333
+ activeTabsByPanel,
334
+ activeSessionId: getActiveSession()
334
335
  });
335
336
 
336
337
  // Sync flash state for tabs that need attention
@@ -371,4 +372,4 @@ initializeServer().catch(err => {
371
372
  });
372
373
 
373
374
  // Export for testing
374
- module.exports = { app, server, io };
375
+ module.exports = { app, server, io };
@@ -0,0 +1,155 @@
1
+ const crypto = require('crypto');
2
+
3
+ const SENSITIVE_FIELDS = [
4
+ 'host',
5
+ 'port',
6
+ 'username',
7
+ 'password',
8
+ 'privateKey',
9
+ 'passphrase',
10
+ 'url'
11
+ ];
12
+
13
+ let bookmarkEncryptionKey = null;
14
+
15
+ class BookmarkEncryptionLockedError extends Error {
16
+ constructor(message = 'Encrypted bookmarks are locked') {
17
+ super(message);
18
+ this.name = 'BookmarkEncryptionLockedError';
19
+ this.code = 'BOOKMARKS_LOCKED';
20
+ }
21
+ }
22
+
23
+ function deriveKey(password, salt) {
24
+ return crypto.scryptSync(password, Buffer.from(salt, 'base64'), 32);
25
+ }
26
+
27
+ function encryptConnectionData(data, key, bookmarkId) {
28
+ const iv = crypto.randomBytes(12);
29
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
30
+ cipher.setAAD(Buffer.from(String(bookmarkId)));
31
+ const ciphertext = Buffer.concat([
32
+ cipher.update(JSON.stringify(data), 'utf8'),
33
+ cipher.final()
34
+ ]);
35
+ return {
36
+ version: 1,
37
+ iv: iv.toString('base64'),
38
+ tag: cipher.getAuthTag().toString('base64'),
39
+ ciphertext: ciphertext.toString('base64')
40
+ };
41
+ }
42
+
43
+ function decryptConnectionData(payload, key, bookmarkId) {
44
+ if (!payload || payload.version !== 1) {
45
+ throw new Error('Unsupported encrypted bookmark format');
46
+ }
47
+ const decipher = crypto.createDecipheriv(
48
+ 'aes-256-gcm',
49
+ key,
50
+ Buffer.from(payload.iv, 'base64')
51
+ );
52
+ decipher.setAAD(Buffer.from(String(bookmarkId)));
53
+ decipher.setAuthTag(Buffer.from(payload.tag, 'base64'));
54
+ const plaintext = Buffer.concat([
55
+ decipher.update(Buffer.from(payload.ciphertext, 'base64')),
56
+ decipher.final()
57
+ ]);
58
+ return JSON.parse(plaintext.toString('utf8'));
59
+ }
60
+
61
+ function encryptBookmark(bookmark, key) {
62
+ const stored = { ...bookmark };
63
+ const connectionData = {};
64
+ for (const field of SENSITIVE_FIELDS) {
65
+ if (Object.prototype.hasOwnProperty.call(stored, field)) {
66
+ connectionData[field] = stored[field];
67
+ delete stored[field];
68
+ }
69
+ }
70
+ delete stored.encryptedConnection;
71
+ stored.encryptedConnection = encryptConnectionData(connectionData, key, stored.id);
72
+ return stored;
73
+ }
74
+
75
+ function decryptBookmark(bookmark, key) {
76
+ if (!bookmark.encryptedConnection) return { ...bookmark };
77
+ const stored = { ...bookmark };
78
+ const connectionData = decryptConnectionData(stored.encryptedConnection, key, stored.id);
79
+ delete stored.encryptedConnection;
80
+ return { ...stored, ...connectionData };
81
+ }
82
+
83
+ function encryptBookmarks(bookmarks, key) {
84
+ return (bookmarks || []).map(bookmark => encryptBookmark(bookmark, key));
85
+ }
86
+
87
+ function decryptBookmarks(bookmarks, key) {
88
+ return (bookmarks || []).map(bookmark => decryptBookmark(bookmark, key));
89
+ }
90
+
91
+ function prepareEncryptedBookmarks(bookmarks, password, salt = crypto.randomBytes(16).toString('base64')) {
92
+ const key = deriveKey(password, salt);
93
+ return { salt, key, bookmarks: encryptBookmarks(bookmarks, key) };
94
+ }
95
+
96
+ function decryptBookmarksWithPassword(config, password) {
97
+ if (!config.bookmarkEncryptionSalt) {
98
+ throw new Error('Bookmark encryption salt is missing');
99
+ }
100
+ const key = deriveKey(password, config.bookmarkEncryptionSalt);
101
+ return { key, bookmarks: decryptBookmarks(config.bookmarks, key) };
102
+ }
103
+
104
+ function unlockBookmarkEncryption(config, password) {
105
+ if (!config.bookmarkEncryptionEnabled) {
106
+ clearBookmarkEncryptionKey();
107
+ return;
108
+ }
109
+ if (!config.bookmarkEncryptionSalt) {
110
+ throw new Error('Bookmark encryption salt is missing');
111
+ }
112
+ // Password verification happens before this call. Keep login available
113
+ // even if one bookmark payload is corrupt; decryption errors remain scoped
114
+ // to bookmark access instead of locking the user out of the whole app.
115
+ setBookmarkEncryptionKey(deriveKey(password, config.bookmarkEncryptionSalt));
116
+ }
117
+
118
+ function getDecryptedBookmarks(config) {
119
+ if (!config.bookmarkEncryptionEnabled) return config.bookmarks || [];
120
+ if (!bookmarkEncryptionKey) throw new BookmarkEncryptionLockedError();
121
+ return decryptBookmarks(config.bookmarks, bookmarkEncryptionKey);
122
+ }
123
+
124
+ function storeBookmarks(config, bookmarks) {
125
+ if (!config.bookmarkEncryptionEnabled) {
126
+ config.bookmarks = bookmarks;
127
+ return;
128
+ }
129
+ if (!bookmarkEncryptionKey) throw new BookmarkEncryptionLockedError();
130
+ config.bookmarks = encryptBookmarks(bookmarks, bookmarkEncryptionKey);
131
+ }
132
+
133
+ function setBookmarkEncryptionKey(key) {
134
+ if (bookmarkEncryptionKey) bookmarkEncryptionKey.fill(0);
135
+ bookmarkEncryptionKey = key ? Buffer.from(key) : null;
136
+ }
137
+
138
+ function clearBookmarkEncryptionKey() {
139
+ if (bookmarkEncryptionKey) bookmarkEncryptionKey.fill(0);
140
+ bookmarkEncryptionKey = null;
141
+ }
142
+
143
+ module.exports = {
144
+ BookmarkEncryptionLockedError,
145
+ deriveKey,
146
+ encryptBookmarks,
147
+ decryptBookmarks,
148
+ prepareEncryptedBookmarks,
149
+ decryptBookmarksWithPassword,
150
+ unlockBookmarkEncryption,
151
+ getDecryptedBookmarks,
152
+ storeBookmarks,
153
+ setBookmarkEncryptionKey,
154
+ clearBookmarkEncryptionKey
155
+ };
@@ -47,6 +47,8 @@ const defaultConfig = {
47
47
  bookmarks: [],
48
48
  folders: [],
49
49
  passwordHash: null,
50
+ bookmarkEncryptionEnabled: false,
51
+ bookmarkEncryptionSalt: null,
50
52
  scrollback: 10000,
51
53
  webglRenderer: true,
52
54
  imageAddonEnabled: true,
@@ -142,12 +144,24 @@ function loadConfig() {
142
144
  * @returns {boolean} Success status
143
145
  */
144
146
  function saveConfig(config) {
147
+ let tempPath = null;
145
148
  try {
146
149
  const configPath = getConfigPath();
147
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
150
+ tempPath = `${configPath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
151
+ const fd = fs.openSync(tempPath, 'w', 0o600);
152
+ try {
153
+ fs.writeFileSync(fd, JSON.stringify(config, null, 2));
154
+ fs.fsyncSync(fd);
155
+ } finally {
156
+ fs.closeSync(fd);
157
+ }
158
+ fs.renameSync(tempPath, configPath);
148
159
  return true;
149
160
  } catch (err) {
150
161
  console.error('Error saving config:', err);
162
+ if (tempPath) {
163
+ try { fs.unlinkSync(tempPath); } catch (_) {}
164
+ }
151
165
  return false;
152
166
  }
153
167
  }
@@ -379,7 +393,9 @@ function getLegacyDataDir() {
379
393
  }
380
394
 
381
395
  function hashPassword(password) {
382
- return crypto.createHash('sha3-256').update(password).digest('hex');
396
+ const salt = crypto.randomBytes(16);
397
+ const hash = crypto.scryptSync(password, salt, 32);
398
+ return `scrypt$${salt.toString('base64')}$${hash.toString('base64')}`;
383
399
  }
384
400
 
385
401
  function isPasswordSet() {
@@ -390,7 +406,45 @@ function isPasswordSet() {
390
406
  function verifyPassword(password) {
391
407
  const config = loadConfig();
392
408
  if (!config.passwordHash) return true;
393
- return hashPassword(password) === config.passwordHash;
409
+ if (config.passwordHash.startsWith('scrypt$')) {
410
+ const parts = config.passwordHash.split('$');
411
+ if (parts.length !== 3) return false;
412
+ try {
413
+ const expected = Buffer.from(parts[2], 'base64');
414
+ const actual = crypto.scryptSync(password, Buffer.from(parts[1], 'base64'), expected.length);
415
+ return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
416
+ } catch (_) {
417
+ return false;
418
+ }
419
+ }
420
+ // Legacy password hashes used unsalted SHA3-256. They remain valid until
421
+ // the password is changed, at which point setPassword writes scrypt.
422
+ const legacyHash = crypto.createHash('sha3-256').update(password).digest('hex');
423
+ const expected = Buffer.from(config.passwordHash, 'hex');
424
+ const actual = Buffer.from(legacyHash, 'hex');
425
+ return expected.length === actual.length && crypto.timingSafeEqual(expected, actual);
426
+ }
427
+
428
+ function verifyPasswordAsync(password) {
429
+ const config = loadConfig();
430
+ if (!config.passwordHash) return Promise.resolve(true);
431
+ if (!config.passwordHash.startsWith('scrypt$')) {
432
+ return Promise.resolve(verifyPassword(password));
433
+ }
434
+ const parts = config.passwordHash.split('$');
435
+ if (parts.length !== 3) return Promise.resolve(false);
436
+ try {
437
+ const expected = Buffer.from(parts[2], 'base64');
438
+ const salt = Buffer.from(parts[1], 'base64');
439
+ return new Promise(resolve => {
440
+ crypto.scrypt(password, salt, expected.length, (err, actual) => {
441
+ if (err || expected.length !== actual.length) return resolve(false);
442
+ resolve(crypto.timingSafeEqual(expected, actual));
443
+ });
444
+ });
445
+ } catch (_) {
446
+ return Promise.resolve(false);
447
+ }
394
448
  }
395
449
 
396
450
  function setPassword(password) {
@@ -552,6 +606,7 @@ module.exports = {
552
606
  hashPassword,
553
607
  isPasswordSet,
554
608
  verifyPassword,
609
+ verifyPasswordAsync,
555
610
  setPassword,
556
611
  removePassword,
557
612
  getSpeechAiPublicConfig,
@@ -562,4 +617,4 @@ module.exports = {
562
617
  loadSpeechAiProfile,
563
618
  deleteSpeechAiProfile,
564
619
  USER_INSTALL_DIR
565
- };
620
+ };
@@ -13,6 +13,9 @@ let tabOrder = [];
13
13
  // Active tab per panel: Map<panelId, sessionId>
14
14
  const activeTabsByPanel = new Map();
15
15
 
16
+ // Most recently focused tab on the client that last saved tab state.
17
+ let activeSessionId = null;
18
+
16
19
  // Current layout for sync
17
20
  let currentLayout = 'single';
18
21
 
@@ -104,6 +107,7 @@ function removeTab(sessionId) {
104
107
  activeTabsByPanel.delete(panelId);
105
108
  }
106
109
  }
110
+ if (activeSessionId === sessionId) activeSessionId = null;
107
111
  }
108
112
 
109
113
  /**
@@ -236,6 +240,14 @@ function getActiveTabsByPanel() {
236
240
  return activeTabsByPanel;
237
241
  }
238
242
 
243
+ function setActiveSession(sessionId) {
244
+ activeSessionId = sessionId && openTabs.has(sessionId) ? sessionId : null;
245
+ }
246
+
247
+ function getActiveSession() {
248
+ return activeSessionId;
249
+ }
250
+
239
251
  /**
240
252
  * Get current theme
241
253
  * @returns {string} Current theme
@@ -298,9 +310,11 @@ module.exports = {
298
310
  setActiveTab,
299
311
  getActiveTab,
300
312
  getActiveTabsByPanel,
313
+ setActiveSession,
314
+ getActiveSession,
301
315
  getCurrentTheme,
302
316
  setCurrentTheme,
303
317
  getCurrentAccent,
304
318
  setCurrentAccent,
305
319
  forEachTab
306
- };
320
+ };
@@ -1013,6 +1013,20 @@
1013
1013
  </button>
1014
1014
  </div>
1015
1015
  </div>
1016
+ <div class="setting-item">
1017
+ <label class="setting-label">
1018
+ <i class="fas fa-key"></i> Bookmark Connection Encryption
1019
+ </label>
1020
+ <div class="setting-description">
1021
+ Encrypt bookmark hosts, usernames, passwords, private keys, passphrases, ports, and URLs using your app password. Decrypted values are kept only in memory. If you lose the password, this connection data cannot be recovered.
1022
+ </div>
1023
+ <div class="setting-control">
1024
+ <label class="toggle-switch">
1025
+ <input type="checkbox" id="bookmarkEncryptionToggle" disabled>
1026
+ <span class="toggle-slider"></span>
1027
+ </label>
1028
+ </div>
1029
+ </div>
1016
1030
  </div>
1017
1031
 
1018
1032
  <div class="settings-category" id="settings-category-system" style="display:none;">
@@ -1251,8 +1265,18 @@
1251
1265
  <label class="setting-label" style="margin-bottom: 8px;">Confirm Password</label>
1252
1266
  <input type="password" id="passwordModalConfirmInput" class="setting-input" placeholder="Confirm password" autocomplete="off" style="width:100%;">
1253
1267
  </div>
1268
+ <div id="passwordModalEncryptionGroup" style="display: none; margin-top: 16px;">
1269
+ <label class="setting-label" style="display:flex; align-items:center; gap:10px;">
1270
+ <input type="checkbox" id="passwordModalEncryptionToggle">
1271
+ Encrypt bookmark connection data
1272
+ </label>
1273
+ <div class="setting-description" style="margin-top:8px;">
1274
+ If you lose this password, encrypted connection data cannot be recovered.
1275
+ </div>
1276
+ </div>
1254
1277
  </div>
1255
1278
  </div>
1279
+ <p id="passwordModalMessage" class="setting-description" style="display:none; margin-top:8px;"></p>
1256
1280
  <p class="password-modal-error" id="passwordModalError" style="display: none; color: var(--accent-danger); font-size: 13px; margin-top: 8px;"></p>
1257
1281
  </div>
1258
1282
  <div class="modal-footer">
@@ -1642,4 +1666,4 @@
1642
1666
  }
1643
1667
  </script>
1644
1668
  </body>
1645
- </html>
1669
+ </html>
@@ -79,6 +79,7 @@ class SSHIFTClient {
79
79
 
80
80
  // Password protection state
81
81
  this.passwordEnabled = false;
82
+ this.bookmarkEncryptionEnabled = false;
82
83
  this.authToken = localStorage.getItem('sshift_auth_token') || null;
83
84
 
84
85
  this._origFetch = window.fetch.bind(window);
@@ -158,6 +159,7 @@ class SSHIFTClient {
158
159
  this.imageAddonEnabled = config.imageAddonEnabled !== undefined ? config.imageAddonEnabled : true;
159
160
  this.scrollback = config.scrollback || 10000;
160
161
  this.passwordEnabled = config.passwordEnabled || false;
162
+ this.bookmarkEncryptionEnabled = config.bookmarkEncryptionEnabled === true;
161
163
  console.log('[SSHIFT] Loaded from server - Sticky:', this.sticky ? 'enabled' : 'disabled',
162
164
  'Take Control Default:', this.takeControlDefault ? 'enabled' : 'disabled',
163
165
  'Keepalive Interval:', this.sshKeepaliveInterval,
@@ -188,6 +190,8 @@ class SSHIFTClient {
188
190
  const response = await this._origFetch('/api/auth/status');
189
191
  const data = await response.json();
190
192
  this.passwordEnabled = data.passwordEnabled;
193
+ this.bookmarkEncryptionEnabled = data.bookmarkEncryptionEnabled === true;
194
+ if (this.bookmarkEncryptionEnabled) this.clearSensitiveTabStorage();
191
195
 
192
196
  if (!this.passwordEnabled) {
193
197
  if (lockScreen) lockScreen.style.display = 'none';
@@ -257,6 +261,7 @@ class SSHIFTClient {
257
261
  this.updateSocketAuth();
258
262
  lockScreen.style.display = 'none';
259
263
  this.passwordEnabled = true;
264
+ if (this.bookmarkEncryptionEnabled) this.clearSensitiveTabStorage();
260
265
  lockScreenForm.removeEventListener('submit', submitHandler);
261
266
  resolve();
262
267
  } else {
@@ -291,7 +296,10 @@ class SSHIFTClient {
291
296
  title: 'Disable Password Protection',
292
297
  label: 'Enter current password',
293
298
  confirmText: 'Disable',
294
- requireConfirm: false
299
+ requireConfirm: false,
300
+ message: this.bookmarkEncryptionEnabled
301
+ ? 'Bookmark connection data will be decrypted and stored in plaintext before password protection is disabled.'
302
+ : ''
295
303
  }, async (password) => {
296
304
  try {
297
305
  const resp = await fetch('/api/auth/remove-password', {
@@ -316,16 +324,21 @@ class SSHIFTClient {
316
324
  title: 'Enable Password Protection',
317
325
  label: 'Set a password',
318
326
  confirmText: 'Enable',
319
- requireConfirm: true
320
- }, async (password) => {
327
+ requireConfirm: true,
328
+ showEncryptionOption: true
329
+ }, async (password, options) => {
321
330
  try {
322
331
  const resp = await fetch('/api/auth/set-password', {
323
332
  method: 'POST',
324
333
  headers: { 'Content-Type': 'application/json' },
325
- body: JSON.stringify({ newPassword: password })
334
+ body: JSON.stringify({
335
+ newPassword: password,
336
+ encryptBookmarks: options.encryptBookmarks
337
+ })
326
338
  });
327
339
 
328
340
  if (resp.ok) {
341
+ if (options.encryptBookmarks) this.clearSensitiveTabStorage();
329
342
  location.reload();
330
343
  } else {
331
344
  const data = await resp.json();
@@ -346,6 +359,9 @@ class SSHIFTClient {
346
359
  const confirmInput = document.getElementById('passwordModalConfirmInput');
347
360
  const confirmGroup = document.getElementById('confirmPasswordGroup');
348
361
  const errorEl = document.getElementById('passwordModalError');
362
+ const messageEl = document.getElementById('passwordModalMessage');
363
+ const encryptionGroup = document.getElementById('passwordModalEncryptionGroup');
364
+ const encryptionToggle = document.getElementById('passwordModalEncryptionToggle');
349
365
  const submitBtn = document.getElementById('passwordModalSubmit');
350
366
  const cancelBtn = document.getElementById('passwordModalCancel');
351
367
  const closeBtn = document.getElementById('closePasswordModal');
@@ -356,6 +372,14 @@ class SSHIFTClient {
356
372
  input.value = '';
357
373
  confirmInput.value = '';
358
374
  errorEl.style.display = 'none';
375
+ if (messageEl) {
376
+ messageEl.textContent = options.message || '';
377
+ messageEl.style.display = options.message ? 'block' : 'none';
378
+ }
379
+ if (encryptionGroup) {
380
+ encryptionGroup.style.display = options.showEncryptionOption ? 'block' : 'none';
381
+ }
382
+ if (encryptionToggle) encryptionToggle.checked = false;
359
383
 
360
384
  if (options.requireConfirm) {
361
385
  confirmGroup.style.display = 'block';
@@ -385,7 +409,9 @@ class SSHIFTClient {
385
409
  return;
386
410
  }
387
411
  cleanup();
388
- await onSubmit(password);
412
+ await onSubmit(password, {
413
+ encryptBookmarks: !!(encryptionToggle && encryptionToggle.checked)
414
+ });
389
415
  };
390
416
 
391
417
  const handleCancel = () => { cleanup(); if (onCancel) onCancel(); };
@@ -414,6 +440,11 @@ class SSHIFTClient {
414
440
  label.textContent = 'Enable Password';
415
441
  }
416
442
  }
443
+ const encryptionToggle = document.getElementById('bookmarkEncryptionToggle');
444
+ if (encryptionToggle) {
445
+ encryptionToggle.checked = this.bookmarkEncryptionEnabled;
446
+ encryptionToggle.disabled = !this.passwordEnabled;
447
+ }
417
448
  }
418
449
 
419
450
  // Update sticky checkbox to reflect loaded value
@@ -490,7 +521,9 @@ class SSHIFTClient {
490
521
  sessionId,
491
522
  name: session.name,
492
523
  type: session.type,
493
- connectionData: session.connectionData,
524
+ // When bookmark encryption is enabled, do not create a second
525
+ // plaintext-at-rest copy in this browser's sticky-tab cache.
526
+ connectionData: this.bookmarkEncryptionEnabled ? {} : session.connectionData,
494
527
  active: sessionId === activeInThisPanel, // Active in this specific panel
495
528
  panelId: effectivePanelId
496
529
  });
@@ -506,7 +539,8 @@ class SSHIFTClient {
506
539
  : (this.currentLayout?.id || 'single');
507
540
  const tabsData = {
508
541
  tabs,
509
- layout: savedLayout
542
+ layout: savedLayout,
543
+ activeSessionId: this.activeSessionId
510
544
  };
511
545
 
512
546
  // Debounce + dedup: collapse rapid-fire saveTabs calls into one
@@ -544,6 +578,27 @@ class SSHIFTClient {
544
578
  }
545
579
  }
546
580
 
581
+ clearSensitiveTabStorage() {
582
+ try {
583
+ if (this._saveTabsTimer) {
584
+ clearTimeout(this._saveTabsTimer);
585
+ this._saveTabsTimer = null;
586
+ }
587
+ this._saveTabsSignature = null;
588
+ const saved = localStorage.getItem('openTabs');
589
+ if (!saved) return;
590
+ const data = JSON.parse(saved);
591
+ const tabs = Array.isArray(data) ? data : data.tabs;
592
+ if (!Array.isArray(tabs)) return;
593
+ tabs.forEach(tab => {
594
+ if (tab && tab.connectionData) tab.connectionData = {};
595
+ });
596
+ localStorage.setItem('openTabs', JSON.stringify(data));
597
+ } catch (err) {
598
+ console.warn('[SSHIFT] Failed to scrub sensitive sticky-tab data:', err);
599
+ }
600
+ }
601
+
547
602
  clearTabs() {
548
603
  localStorage.removeItem('openTabs');
549
604
  }
@@ -631,7 +686,7 @@ class SSHIFTClient {
631
686
  }
632
687
 
633
688
  // Distribute tabs across panels when layout changes
634
- distributeTabsToPanels(syncedTabs = null) {
689
+ distributeTabsToPanels(syncedTabs = null, preferredActiveSessionId = null) {
635
690
  // Get all sessions
636
691
  const allSessions = [...this.sessions.keys(), ...this.sftpSessions.keys()];
637
692
  if (allSessions.length === 0) return;
@@ -665,12 +720,26 @@ class SSHIFTClient {
665
720
  });
666
721
  });
667
722
 
668
- // Restore active sessions per panel - only activate the first active tab in each panel
723
+ // Restore active sessions per local panel. Synced desktop panel IDs do
724
+ // not exist on mobile, so map them to the same fallback used above.
669
725
  const activatedPanels = new Set();
726
+ if (preferredActiveSessionId) {
727
+ const preferredTab = syncedTabs.find(tabData => tabData.sessionId === preferredActiveSessionId);
728
+ if (preferredTab) {
729
+ const targetPanel = preferredTab.panelId && panels.includes(preferredTab.panelId)
730
+ ? preferredTab.panelId
731
+ : clockwisePanels[0];
732
+ this.switchTab(preferredTab.sessionId, targetPanel);
733
+ activatedPanels.add(targetPanel);
734
+ }
735
+ }
670
736
  syncedTabs.forEach(tabData => {
671
- if (tabData.active && !activatedPanels.has(tabData.panelId)) {
672
- this.switchTab(tabData.sessionId, tabData.panelId);
673
- activatedPanels.add(tabData.panelId);
737
+ const targetPanel = tabData.panelId && panels.includes(tabData.panelId)
738
+ ? tabData.panelId
739
+ : clockwisePanels[0];
740
+ if (tabData.active && !activatedPanels.has(targetPanel)) {
741
+ this.switchTab(tabData.sessionId, targetPanel);
742
+ activatedPanels.add(targetPanel);
674
743
  }
675
744
  });
676
745
  } else {
@@ -3340,25 +3409,19 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3340
3409
  const savedLayoutId = this.loadCurrentLayout();
3341
3410
  const layout = this.layouts.find(l => l.id === savedLayoutId) || this.layouts[0];
3342
3411
 
3343
- // Check if we should defer layout application (sticky mode with saved tabs)
3344
- const savedData = this.loadTabs();
3345
- const savedTabs = Array.isArray(savedData) ? savedData : (savedData?.tabs || []);
3346
- const shouldDeferLayout = this.sticky && savedTabs.length > 0;
3347
-
3348
3412
  if (layout) {
3349
3413
  this.currentLayout = layout;
3350
3414
  this.updateLayoutActiveState(layout.id);
3351
-
3352
- // Only apply layout if not deferring to restoreTabs()
3353
- if (!shouldDeferLayout) {
3354
- this.applyLayout(layout);
3355
- // Resize terminals after initial layout (with delay for DOM to settle)
3356
- setTimeout(() => this.handleResize(), 100);
3357
- }
3415
+
3416
+ // Layout is a per-device preference and must be rendered before tabs
3417
+ // arrive from the server. Tab restoration no longer applies a deferred
3418
+ // layout, so deferring here leaves the DOM in its default single panel.
3419
+ this.applyLayout(layout);
3420
+ // Resize terminals after initial layout (with delay for DOM to settle)
3421
+ setTimeout(() => this.handleResize(), 100);
3358
3422
  }
3359
3423
 
3360
- console.log('[SSHIFT] Layout system initialized with layout:', layout?.name,
3361
- shouldDeferLayout ? '(deferred to restoreTabs)' : '');
3424
+ console.log('[SSHIFT] Layout system initialized with layout:', layout?.name);
3362
3425
  }
3363
3426
 
3364
3427
  async loadBookmarkOrder() {
@@ -3497,7 +3560,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3497
3560
  // The local layout (per-device, applied by initLayoutSystem)
3498
3561
  // already created the panels — just distribute the synced tabs
3499
3562
  // into them.
3500
- this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel);
3563
+ this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel, pendingData.activeSessionId);
3501
3564
  } else {
3502
3565
  // Server has no tabs (e.g. right after restart). Treat it as a
3503
3566
  // fresh slate: clear stale localStorage and DO NOT resurrect
@@ -4745,7 +4808,7 @@ const wheelHandler = (e) => {
4745
4808
  const isInitialSync = !this._initialSyncDone;
4746
4809
  // The local per-device layout (initLayoutSystem) has already
4747
4810
  // created the panels — distribute the synced tabs into them.
4748
- this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel);
4811
+ this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel, data.activeSessionId);
4749
4812
  } else if (!this._initialSyncDone) {
4750
4813
  // Server has no tabs and this is the first sync. This is the
4751
4814
  // post-restart / fresh-install / single-client-with-no-sessions
@@ -4821,6 +4884,20 @@ const wheelHandler = (e) => {
4821
4884
  }
4822
4885
  });
4823
4886
 
4887
+ this.socket.on('bookmark-encryption-changed', (data) => {
4888
+ this.bookmarkEncryptionEnabled = data.enabled === true;
4889
+ if (this.bookmarkEncryptionEnabled) this.clearSensitiveTabStorage();
4890
+ this.updatePasswordToggleUI();
4891
+ });
4892
+
4893
+ this.socket.on('auth-state-changed', () => {
4894
+ // A password was enabled, changed, or removed. Reloading clears all
4895
+ // decrypted bookmarks, connection credentials, and terminal history
4896
+ // from this page's memory before applying the new auth state.
4897
+ localStorage.removeItem('sshift_auth_token');
4898
+ location.reload();
4899
+ });
4900
+
4824
4901
  // layout-changed / theme-changed / accent-changed handlers removed:
4825
4902
  // layout, theme and accent are per-device preferences (localStorage)
4826
4903
  // and are no longer broadcast between clients through the server.
@@ -4846,7 +4923,10 @@ const wheelHandler = (e) => {
4846
4923
  // Tabs whose panelId doesn't exist in this device's layout fall
4847
4924
  // back to the first panel (distributeTabsToPanels).
4848
4925
  if (data.tabs && Array.isArray(data.tabs)) {
4849
- this.distributeTabsToPanels(data.tabs);
4926
+ if (this.isMobile) {
4927
+ this.reorderTabsInDOM(data.tabs.map(tab => tab.sessionId));
4928
+ }
4929
+ this.distributeTabsToPanels(data.tabs, data.activeSessionId);
4850
4930
  }
4851
4931
  } finally {
4852
4932
  // Clear flag after processing
@@ -7245,10 +7325,47 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7245
7325
  this.togglePasswordProtection();
7246
7326
  });
7247
7327
  }
7328
+ const encryptionToggle = document.getElementById('bookmarkEncryptionToggle');
7329
+ if (encryptionToggle) {
7330
+ encryptionToggle.addEventListener('change', () => {
7331
+ const enabled = encryptionToggle.checked;
7332
+ encryptionToggle.checked = this.bookmarkEncryptionEnabled;
7333
+ this._showPasswordModal({
7334
+ title: enabled ? 'Encrypt Bookmark Connections' : 'Disable Bookmark Encryption',
7335
+ label: 'Enter current password',
7336
+ confirmText: enabled ? 'Encrypt' : 'Decrypt',
7337
+ requireConfirm: false,
7338
+ message: enabled
7339
+ ? 'Hostnames, usernames, passwords, keys, passphrases, ports, and URLs will be encrypted. If you lose this password, the connection data cannot be recovered.'
7340
+ : 'Connection data will be decrypted and stored in plaintext in the configuration file.'
7341
+ }, async (password) => {
7342
+ try {
7343
+ const response = await fetch('/api/auth/bookmark-encryption', {
7344
+ method: 'POST',
7345
+ headers: { 'Content-Type': 'application/json' },
7346
+ body: JSON.stringify({ currentPassword: password, enabled })
7347
+ });
7348
+ const data = await response.json();
7349
+ if (!response.ok) throw new Error(data.error || 'Failed to update bookmark encryption');
7350
+ this.bookmarkEncryptionEnabled = data.bookmarkEncryptionEnabled;
7351
+ if (this.bookmarkEncryptionEnabled) this.clearSensitiveTabStorage();
7352
+ this.updatePasswordToggleUI();
7353
+ await this.loadBookmarks();
7354
+ this.showToast(enabled ? 'Bookmark connections encrypted' : 'Bookmark encryption disabled', 'success');
7355
+ } catch (err) {
7356
+ this.updatePasswordToggleUI();
7357
+ this.showToast(err.message, 'error');
7358
+ }
7359
+ });
7360
+ });
7361
+ }
7248
7362
  const logoutBtn = document.getElementById('logoutBtn');
7249
7363
  if (logoutBtn) {
7250
7364
  if (this.passwordEnabled) logoutBtn.style.display = '';
7251
- logoutBtn.addEventListener('click', () => {
7365
+ logoutBtn.addEventListener('click', async () => {
7366
+ try {
7367
+ await fetch('/api/auth/logout', { method: 'POST' });
7368
+ } catch (_) {}
7252
7369
  localStorage.removeItem('sshift_auth_token');
7253
7370
  location.reload();
7254
7371
  });
@@ -11269,7 +11386,7 @@ handleTabOpened(data) {
11269
11386
  }
11270
11387
 
11271
11388
  // Sync tabs from server (called on connect when sticky is enabled)
11272
- async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null) {
11389
+ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null, activeSessionId = null) {
11273
11390
  // Wait for any in-progress restoration to complete before syncing
11274
11391
  // This prevents the race condition where restoreTabs starts first,
11275
11392
  // sets isRestoring=true, and then this function returns early, missing
@@ -11376,10 +11493,13 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
11376
11493
  }
11377
11494
  }
11378
11495
  } else if (activeTabsByPanel) {
11379
- // Mobile: use the first active tab from any panel
11380
- const firstActive = Object.values(activeTabsByPanel).find(id => this.sessions.has(id) || this.sftpSessions.has(id));
11381
- if (firstActive) {
11382
- this.switchTab(firstActive);
11496
+ // Mobile has one local panel. Prefer the source device's focused tab;
11497
+ // otherwise fall back to an active tab from any source panel.
11498
+ const mobileActive = (activeSessionId && (this.sessions.has(activeSessionId) || this.sftpSessions.has(activeSessionId)))
11499
+ ? activeSessionId
11500
+ : Object.values(activeTabsByPanel).find(id => this.sessions.has(id) || this.sftpSessions.has(id));
11501
+ if (mobileActive) {
11502
+ this.switchTab(mobileActive, 'panel-0');
11383
11503
  }
11384
11504
  } else if (tabs.length > 0) {
11385
11505
  // No active tab info from server — default to first tab
@@ -11459,6 +11579,10 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
11459
11579
  async loadBookmarks() {
11460
11580
  try {
11461
11581
  const response = await fetch('/api/bookmarks');
11582
+ if (!response.ok) {
11583
+ const data = await response.json().catch(() => ({}));
11584
+ throw new Error(data.error || 'Failed to load bookmarks');
11585
+ }
11462
11586
  let bookmarks = await response.json();
11463
11587
 
11464
11588
  // Apply saved order if exists
@@ -14043,4 +14167,4 @@ document.addEventListener('DOMContentLoaded', () => {
14043
14167
  if (typeof lucide !== 'undefined') {
14044
14168
  lucide.createIcons();
14045
14169
  }
14046
- });
14170
+ });