@lethevimlet/sshift 1.9.8 → 2.0.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.
Files changed (33) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/plugins/claude-attention/index.js +42 -1
  4. package/plugins/claude-attention/package.json +1 -1
  5. package/plugins/opencode-attention/index.js +42 -1
  6. package/plugins/opencode-attention/package.json +1 -1
  7. package/src/server/endpoints/rest/auth.js +45 -32
  8. package/src/server/endpoints/rest/bookmarks.js +5 -1
  9. package/src/server/endpoints/rest/config.js +19 -35
  10. package/src/server/endpoints/rest/folders.js +15 -3
  11. package/src/server/endpoints/rest/speech-ai.js +35 -9
  12. package/src/server/endpoints/rest/system.js +40 -4
  13. package/src/server/endpoints/ws/index.js +6 -0
  14. package/src/server/endpoints/ws/sftp.js +70 -10
  15. package/src/server/endpoints/ws/ssh.js +13 -5
  16. package/src/server/endpoints/ws/tabs.js +4 -4
  17. package/src/server/index.js +87 -3
  18. package/src/server/plugins/plugin-manager.js +14 -1
  19. package/src/server/services/bookmarks.js +1 -1
  20. package/src/server/services/sftp-manager.js +80 -7
  21. package/src/server/services/ssh-manager.js +44 -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/index.html +28 -0
  31. package/src/webapp/js/app.js +356 -195
  32. package/src/webapp/js/mobile-terminal.js +436 -79
  33. package/sshift +23 -2
@@ -130,9 +130,8 @@ function registerSystemEndpoints(app, io) {
130
130
  // API: Get version
131
131
  app.get('/api/version', (req, res) => {
132
132
  try {
133
- const packagePath = path.join(__dirname, '../../../../package.json');
134
- const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
135
- res.json({ version: packageData.version });
133
+ // Same string the page was rendered with (dev builds add a suffix).
134
+ res.json({ version: require('../../utils/asset-version').getAssetVersion() });
136
135
  } catch (err) {
137
136
  console.error('Error reading version:', err);
138
137
  res.status(500).json({ error: 'Failed to read version' });
@@ -265,7 +264,14 @@ function registerSystemEndpoints(app, io) {
265
264
  });
266
265
 
267
266
  // API: Trigger update
267
+ // One update at a time: a second click (or a second browser) used to
268
+ // start a parallel `npm i -g` racing the first one.
269
+ let updateInProgress = false;
268
270
  app.post('/api/update', async (req, res) => {
271
+ if (updateInProgress) {
272
+ return res.status(409).json({ error: 'An update is already in progress' });
273
+ }
274
+ updateInProgress = true;
269
275
  try {
270
276
 
271
277
  const { spawn, execSync } = require('child_process');
@@ -302,6 +308,16 @@ function registerSystemEndpoints(app, io) {
302
308
  ghReq.setTimeout(10000, () => { ghReq.destroy(); reject(new Error('GitHub request timed out')); });
303
309
  ghReq.end();
304
310
  });
311
+ if (githubVersion && /^\d+\.\d+\.\d+$/.test(githubVersion) &&
312
+ compareVersions(currentPkg.version, githubVersion) >= 0) {
313
+ // GitHub main can lag npm, or this install can be ahead of it:
314
+ // "updating" would reinstall or downgrade.
315
+ return res.status(409).json({
316
+ error: 'Already up to date',
317
+ localVersion: currentPkg.version,
318
+ remoteVersion: githubVersion
319
+ });
320
+ }
305
321
  if (githubVersion && /^\d+\.\d+\.\d+$/.test(githubVersion)) {
306
322
  // Verify the version actually exists on the npm registry before pinning.
307
323
  // GitHub may show a version before npm propagation completes, which would
@@ -313,6 +329,7 @@ function registerSystemEndpoints(app, io) {
313
329
  method: 'GET',
314
330
  headers: { 'User-Agent': 'sshift-update-checker' }
315
331
  }, (npmRes) => {
332
+ npmRes.resume(); // free the socket (body not needed)
316
333
  resolve(npmRes.statusCode === 200);
317
334
  });
318
335
  npmReq.on('error', () => resolve(false));
@@ -687,6 +704,17 @@ fi
687
704
  spawnFailed = true;
688
705
  try { fs.unlinkSync(updateMarker); } catch (e) { /* ignore */ }
689
706
  });
707
+ // The update script runs for a while; exiting at once with an error
708
+ // means it never started (e.g. systemd-run refused by polkit for a
709
+ // non-root service user). Exiting the server then would leave it
710
+ // down: exit 0 does not trigger Restart=on-failure.
711
+ updateProcess.on('exit', (code, signal) => {
712
+ if (code !== 0 || signal) {
713
+ console.error('[UPDATE] Update process exited early (code', code, 'signal', signal + ')');
714
+ spawnFailed = true;
715
+ try { fs.unlinkSync(updateMarker); } catch (e) { /* ignore */ }
716
+ }
717
+ });
690
718
 
691
719
  updateProcess.unref();
692
720
 
@@ -699,14 +727,22 @@ fi
699
727
  setTimeout(() => {
700
728
  if (spawnFailed) {
701
729
  console.error('[UPDATE] Update process failed to start. Keeping server running.');
730
+ updateInProgress = false;
702
731
  return;
703
732
  }
704
733
  console.log('[UPDATE] Exiting for update...');
705
734
  process.exit(0);
706
735
  }, exitDelay);
707
736
  } catch (err) {
737
+ updateInProgress = false;
708
738
  console.error('Error triggering update:', err);
709
- res.status(500).json({ error: 'Failed to trigger update' });
739
+ // The success reply may already be out (it is sent before the
740
+ // background script starts); never answer twice.
741
+ if (!res.headersSent) res.status(500).json({ error: 'Failed to trigger update' });
742
+ } finally {
743
+ // Early returns (503, 500 above) and a failed spawn (server keeps
744
+ // running) must allow another attempt.
745
+ if (!res.headersSent || res.statusCode >= 400) updateInProgress = false;
710
746
  }
711
747
  });
712
748
  }
@@ -20,6 +20,12 @@ function registerAllWSHandlers(socket, io) {
20
20
  registerTabHandlers(socket, io);
21
21
  registerLayoutHandlers(socket, io);
22
22
  registerBookmarkHandlers(socket, io);
23
+ // Liveness probe: after a laptop sleep or a network change the browser
24
+ // can hold a dead socket that still reports "connected" for over a
25
+ // minute. The client asks for an ack and reconnects when none arrives.
26
+ socket.on('sshift-ping', (ack) => {
27
+ if (typeof ack === 'function') ack({ t: Date.now() });
28
+ });
23
29
  }
24
30
 
25
31
  /**
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  const { loadConfig, getStickySetting } = require('../../utils/config');
6
- const { addTab, getTab, removeTab, addSocketToTab, removeSocketFromTab, clearCloseTimer, setCloseTimer } = require('../../utils/tab-manager');
6
+ const { wasRecentlyClosed, addTab, getTab, removeTab, addSocketToTab, removeSocketFromTab, clearCloseTimer, setCloseTimer } = require('../../utils/tab-manager');
7
7
  const { sftpManager } = require('../../services');
8
8
 
9
9
  /**
@@ -40,7 +40,8 @@ function registerSFTPHandlers(socket, io) {
40
40
  name: data.name || 'SFTP',
41
41
  type: 'sftp',
42
42
  connectionData: data,
43
- activeSockets: new Set([socket.id]),
43
+ // The socket may have gone away during the (up to 30 s) connect.
44
+ activeSockets: new Set(socket.connected ? [socket.id] : []),
44
45
  sticky: sticky
45
46
  });
46
47
 
@@ -48,7 +49,14 @@ function registerSFTPHandlers(socket, io) {
48
49
  sessionId,
49
50
  name: data.name || 'SFTP',
50
51
  type: 'sftp',
51
- connectionData: data
52
+ // Never broadcast secrets (password, key, passphrase) to other
53
+ // browsers; they join the running session by id.
54
+ connectionData: {
55
+ host: data.host,
56
+ port: data.port,
57
+ username: data.username,
58
+ name: data.name
59
+ }
52
60
  });
53
61
 
54
62
  io.emit('sessions-updated');
@@ -69,7 +77,7 @@ function registerSFTPHandlers(socket, io) {
69
77
  addSocketToTab(data.sessionId, socket.id);
70
78
  socket.emit('sftp-joined', { sessionId: data.sessionId });
71
79
  } else {
72
- socket.emit('sftp-error', { message: 'Session not found', sessionId: data.sessionId });
80
+ socket.emit('sftp-error', { message: 'Session not found', sessionId: data.sessionId, closed: wasRecentlyClosed(data.sessionId) });
73
81
  }
74
82
  });
75
83
 
@@ -136,13 +144,29 @@ function registerSFTPHandlers(socket, io) {
136
144
  });
137
145
 
138
146
  // SFTP download (streamed)
147
+ const activeDownloads = new Map(); // `${sessionId}\0${path}` -> read stream
148
+ socket.on('disconnect', () => {
149
+ for (const stream of activeDownloads.values()) {
150
+ try { stream.destroy(); } catch (_) {}
151
+ }
152
+ activeDownloads.clear();
153
+ });
154
+ socket.on('sftp-download-cancel', (data) => {
155
+ if (!data) return;
156
+ const key = `${data.sessionId}\0${data.path}`;
157
+ const stream = activeDownloads.get(key);
158
+ if (stream) {
159
+ activeDownloads.delete(key);
160
+ try { stream.destroy(); } catch (_) {}
161
+ }
162
+ });
139
163
  socket.on('sftp-download', async (data) => {
140
164
  try {
141
165
  const { sessionId, path } = data;
142
166
  const stats = await sftpManager.stat(sessionId, path);
143
167
 
144
168
  if (stats.isDirectory()) {
145
- socket.emit('sftp-error', { message: 'Cannot download a directory' });
169
+ socket.emit('sftp-error', { message: 'Cannot download a directory', sessionId, path, download: true });
146
170
  return;
147
171
  }
148
172
 
@@ -157,9 +181,28 @@ function registerSFTPHandlers(socket, io) {
157
181
 
158
182
  const stream = sftpManager.getReadStream(sessionId, path);
159
183
  const FLUSH_SIZE = 1024 * 1024;
184
+ // Backpressure: at most this many chunks queued for the browser.
185
+ // Without it a multi-GB file was read as fast as SSH delivers and
186
+ // piled up base64 chunks in memory for a slow (mobile) client.
187
+ const MAX_QUEUED_PACKETS = 4;
160
188
  let buffer = Buffer.alloc(0);
161
189
  let bytesDownloaded = 0;
162
190
 
191
+ // One download per (session, path) per socket; cancel and
192
+ // disconnect stop reading from the remote server.
193
+ const key = `${sessionId}\0${path}`;
194
+ const previous = activeDownloads.get(key);
195
+ if (previous) previous.destroy();
196
+ activeDownloads.set(key, stream);
197
+ const finish = () => {
198
+ if (activeDownloads.get(key) === stream) activeDownloads.delete(key);
199
+ if (socket.conn) socket.conn.off('drain', onDrain);
200
+ };
201
+ const onDrain = () => {
202
+ if (stream.isPaused && stream.isPaused()) stream.resume();
203
+ };
204
+ if (socket.conn) socket.conn.on('drain', onDrain);
205
+
163
206
  stream.on('data', (chunk) => {
164
207
  buffer = Buffer.concat([buffer, chunk]);
165
208
  bytesDownloaded += chunk.length;
@@ -173,8 +216,11 @@ function registerSFTPHandlers(socket, io) {
173
216
  totalBytes: stats.size
174
217
  });
175
218
  buffer = Buffer.alloc(0);
219
+ const queued = socket.conn && socket.conn.writeBuffer ? socket.conn.writeBuffer.length : 0;
220
+ if (queued >= MAX_QUEUED_PACKETS) stream.pause();
176
221
  }
177
222
  });
223
+ stream.on('close', finish);
178
224
 
179
225
  stream.on('end', () => {
180
226
  if (buffer.length > 0) {
@@ -195,7 +241,8 @@ function registerSFTPHandlers(socket, io) {
195
241
  });
196
242
 
197
243
  stream.on('error', (err) => {
198
- socket.emit('sftp-error', { message: `Download failed: ${err.message}` });
244
+ finish();
245
+ socket.emit('sftp-error', { message: `Download failed: ${err.message}`, sessionId, path, download: true });
199
246
  });
200
247
  } catch (err) {
201
248
  socket.emit('sftp-error', { message: err.message });
@@ -204,6 +251,8 @@ function registerSFTPHandlers(socket, io) {
204
251
 
205
252
  // SFTP upload (chunked)
206
253
  socket.on('sftp-upload-start', async (data, callback) => {
254
+ if (typeof callback !== 'function') callback = () => {};
255
+ data = data || {};
207
256
  try {
208
257
  const uploadId = sftpManager.uploadStart(
209
258
  data.sessionId,
@@ -218,6 +267,8 @@ function registerSFTPHandlers(socket, io) {
218
267
  });
219
268
 
220
269
  socket.on('sftp-upload-chunk', async (data, callback) => {
270
+ if (typeof callback !== 'function') callback = () => {};
271
+ data = data || {};
221
272
  try {
222
273
  const result = await sftpManager.uploadChunk(data.uploadId, data.data);
223
274
  callback(result);
@@ -227,6 +278,8 @@ function registerSFTPHandlers(socket, io) {
227
278
  });
228
279
 
229
280
  socket.on('sftp-upload-end', async (data, callback) => {
281
+ if (typeof callback !== 'function') callback = () => {};
282
+ data = data || {};
230
283
  try {
231
284
  const result = await sftpManager.uploadEnd(data.uploadId);
232
285
  callback(result);
@@ -251,26 +304,33 @@ function registerSFTPHandlers(socket, io) {
251
304
  });
252
305
 
253
306
  // SFTP delete
254
- socket.on('sftp-delete', async (data) => {
307
+ // With an ack callback the result (or error) goes only to the ack, so
308
+ // the requester can match it; without one (older pages) the broadcast
309
+ // result/error events are used as before.
310
+ socket.on('sftp-delete', async (data, ack) => {
255
311
  try {
256
312
  await sftpManager.delete(data.sessionId, data.path);
313
+ if (typeof ack === 'function') return ack({ success: true, path: data.path });
257
314
  socket.emit('sftp-delete-result', { path: data.path, success: true });
258
315
  } catch (err) {
259
- socket.emit('sftp-error', { message: err.message });
316
+ if (typeof ack === 'function') return ack({ success: false, error: err.message });
317
+ socket.emit('sftp-error', { message: err.message, sessionId: data.sessionId });
260
318
  }
261
319
  });
262
320
 
263
321
  // SFTP rename
264
- socket.on('sftp-rename', async (data) => {
322
+ socket.on('sftp-rename', async (data, ack) => {
265
323
  try {
266
324
  await sftpManager.rename(data.sessionId, data.oldPath, data.newPath);
325
+ if (typeof ack === 'function') return ack({ success: true, oldPath: data.oldPath, newPath: data.newPath });
267
326
  socket.emit('sftp-rename-result', {
268
327
  oldPath: data.oldPath,
269
328
  newPath: data.newPath,
270
329
  success: true
271
330
  });
272
331
  } catch (err) {
273
- socket.emit('sftp-error', { message: err.message });
332
+ if (typeof ack === 'function') return ack({ success: false, error: err.message });
333
+ socket.emit('sftp-error', { message: err.message, sessionId: data.sessionId });
274
334
  }
275
335
  });
276
336
 
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  const { loadConfig, getStickySetting, getScrollback } = require('../../utils/config');
6
- const { addTab, getTab, addSocketToTab, removeSocketFromTab, removeTab, getTabOrder, setCloseTimer, clearCloseTimer, getCloseTimer } = require('../../utils/tab-manager');
6
+ const { wasRecentlyClosed, addTab, getTab, addSocketToTab, removeSocketFromTab, removeTab, getTabOrder, setCloseTimer, clearCloseTimer, getCloseTimer } = require('../../utils/tab-manager');
7
7
  const { sshManager } = require('../../services');
8
8
  const pluginManager = require('../../plugins/plugin-manager');
9
9
 
@@ -64,7 +64,8 @@ function registerSSHHandlers(socket, io) {
64
64
  name: data.name || 'SSH',
65
65
  type: 'ssh',
66
66
  connectionData: data,
67
- activeSockets: new Set([socket.id]),
67
+ // The socket may have gone away during the (up to 30 s) connect.
68
+ activeSockets: new Set(socket.connected ? [socket.id] : []),
68
69
  sticky: sticky
69
70
  });
70
71
 
@@ -75,7 +76,14 @@ function registerSSHHandlers(socket, io) {
75
76
  sessionId,
76
77
  name: data.name || 'SSH',
77
78
  type: 'ssh',
78
- connectionData: data
79
+ // Never broadcast secrets (password, key, passphrase) to other
80
+ // browsers; they join the running session by id.
81
+ connectionData: {
82
+ host: data.host,
83
+ port: data.port,
84
+ username: data.username,
85
+ name: data.name
86
+ }
79
87
  });
80
88
 
81
89
  io.emit('sessions-updated');
@@ -96,7 +104,7 @@ function registerSSHHandlers(socket, io) {
96
104
  addSocketToTab(data.sessionId, socket.id);
97
105
  // Note: ssh-joined is emitted by joinSession() with noTerminalState flag
98
106
  } else {
99
- socket.emit('ssh-error', { message: 'Session not found', sessionId: data.sessionId });
107
+ socket.emit('ssh-error', { message: 'Session not found', sessionId: data.sessionId, closed: wasRecentlyClosed(data.sessionId) });
100
108
  }
101
109
  });
102
110
 
@@ -145,7 +153,7 @@ function registerSSHHandlers(socket, io) {
145
153
  advisory: true
146
154
  });
147
155
  } else {
148
- socket.emit('ssh-error', { message: 'Session not found', sessionId: data.sessionId });
156
+ socket.emit('ssh-error', { message: 'Session not found', sessionId: data.sessionId, closed: wasRecentlyClosed(data.sessionId) });
149
157
  }
150
158
  });
151
159
 
@@ -52,11 +52,11 @@ function registerTabHandlers(socket, io) {
52
52
 
53
53
  // Update tab order with panel assignments
54
54
  if (data.tabs && Array.isArray(data.tabs)) {
55
- setTabOrder(data.tabs.map(t => typeof t === 'string' ? t : t.sessionId));
55
+ setTabOrder(data.tabs.map(t => (t && typeof t === 'object') ? t.sessionId : t));
56
56
 
57
57
  // Update panel assignments in openTabs
58
58
  data.tabs.forEach(tabData => {
59
- if (typeof tabData === 'object' && tabData.sessionId && tabData.panelId) {
59
+ if (tabData && typeof tabData === 'object' && tabData.sessionId && tabData.panelId) {
60
60
  updateTabPanel(tabData.sessionId, tabData.panelId);
61
61
  }
62
62
  });
@@ -79,11 +79,11 @@ function registerTabHandlers(socket, io) {
79
79
 
80
80
  // Update tab order with panel assignments
81
81
  if (data.tabs && Array.isArray(data.tabs) && data.tabs.length > 0) {
82
- setTabOrder(data.tabs.map(t => typeof t === 'string' ? t : t.sessionId));
82
+ setTabOrder(data.tabs.map(t => (t && typeof t === 'object') ? t.sessionId : t));
83
83
 
84
84
  // Update panel assignments and active tabs in openTabs
85
85
  data.tabs.forEach(tabData => {
86
- if (typeof tabData === 'object' && tabData.sessionId && tabData.panelId) {
86
+ if (tabData && typeof tabData === 'object' && tabData.sessionId && tabData.panelId) {
87
87
  updateTabPanel(tabData.sessionId, tabData.panelId);
88
88
  // Track which tab is active per panel
89
89
  if (tabData.active) {
@@ -87,6 +87,48 @@ async function getSSLCredentials() {
87
87
  // Create Express app
88
88
  const app = express();
89
89
 
90
+ /**
91
+ * Cross-site guard shared by Socket.IO and state-changing REST calls.
92
+ * A browser always sends Origin on these requests: it must name this host
93
+ * (Host or X-Forwarded-Host) or an entry of config.allowedOrigins.
94
+ * Requests without Origin (curl, scripts, plugins) are not browsers'
95
+ * cross-site requests and pass.
96
+ */
97
+ function isSameOriginRequest(req) {
98
+ const origin = req.headers.origin;
99
+ if (!origin) return true;
100
+ let originHost = null;
101
+ try { originHost = new URL(origin).host.toLowerCase(); } catch (_) {}
102
+ const hosts = [req.headers['x-forwarded-host'], req.headers.host]
103
+ .filter(Boolean)
104
+ .map(h => String(h).split(',')[0].trim().toLowerCase());
105
+ let allowed = [];
106
+ try { allowed = loadConfig().allowedOrigins || []; } catch (_) {}
107
+ const ok = !!originHost && (
108
+ hosts.includes(originHost) ||
109
+ (Array.isArray(allowed) && allowed.some(a => String(a).toLowerCase() === origin.toLowerCase() || String(a).toLowerCase() === originHost))
110
+ );
111
+ if (!ok) {
112
+ console.warn(`[SECURITY] Rejected cross-site request from ${origin} (host ${hosts.join(', ') || 'none'}). Add it to "allowedOrigins" in config.json if it is yours.`);
113
+ }
114
+ return ok;
115
+ }
116
+ const { guardSocket, guardExpressApp, expressErrorHandler } = require('./utils/safe-handlers');
117
+ guardExpressApp(app);
118
+
119
+ // Last line of defence: one bad request or a library bug must not kill the
120
+ // process, because that ends every SSH session it hosts. Errors are logged.
121
+ // Startup failures (port in use, before listen) still exit so a supervisor
122
+ // can see them.
123
+ let serverListening = false;
124
+ process.on('unhandledRejection', (reason) => {
125
+ console.error('[PROCESS] Unhandled promise rejection:', reason && reason.stack ? reason.stack : reason);
126
+ });
127
+ process.on('uncaughtException', (err) => {
128
+ console.error('[PROCESS] Uncaught exception:', err && err.stack ? err.stack : err);
129
+ if (!serverListening || (err && err.code === 'EADDRINUSE')) process.exit(1);
130
+ });
131
+
90
132
  // Determine if HTTPS should be enabled
91
133
  const enableHttps = getEnableHttps();
92
134
  const enableHttpRedirect = enableHttps && getHttpRedirect();
@@ -139,7 +181,17 @@ async function initializeServer() {
139
181
  },
140
182
  pingTimeout: 60000,
141
183
  pingInterval: 25000,
142
- maxHttpBufferSize: 5e6
184
+ maxHttpBufferSize: 5e6,
185
+ // Cross-site WebSocket hijacking guard. WebSockets ignore CORS, so
186
+ // without a password any web page open in the user's browser could
187
+ // connect to this server and type into their terminals. A browser
188
+ // always sends Origin: it must name this same host (or one listed in
189
+ // config.allowedOrigins). Non-browser clients send no Origin. With a
190
+ // password set the auth token already blocks foreign pages.
191
+ allowRequest: (req, callback) => {
192
+ if (isPasswordSet()) return callback(null, true);
193
+ callback(null, isSameOriginRequest(req));
194
+ }
143
195
  });
144
196
 
145
197
  // Socket.IO auth middleware
@@ -184,6 +236,15 @@ async function initializeServer() {
184
236
  const { isValidAuthToken } = require('./endpoints/rest/auth');
185
237
  const AUTH_WHITELIST = ['/auth/status', '/auth/login', '/cert', '/security-info', '/version', '/update-status'];
186
238
 
239
+ // CSRF: a foreign page can auto-submit a form POST (no preflight) to
240
+ // /api/update or /api/sessions/close-all. Reject state-changing calls
241
+ // whose Origin is another site.
242
+ app.use('/api', (req, res, next) => {
243
+ if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
244
+ if (isSameOriginRequest(req)) return next();
245
+ res.status(403).json({ error: 'Cross-site request rejected' });
246
+ });
247
+
187
248
  app.use('/api', (req, res, next) => {
188
249
  if (AUTH_WHITELIST.some(p => req.path === p)) return next();
189
250
  if (!isPasswordSet()) return next();
@@ -213,7 +274,7 @@ async function initializeServer() {
213
274
  const swPath = path.join(webappPath, 'sw.js');
214
275
  fs.readFile(swPath, 'utf8', (err, data) => {
215
276
  if (err) return res.status(500).send('/* SW load error */');
216
- const version = require(path.join(__dirname, '../../package.json')).version;
277
+ const version = require('./utils/asset-version').getAssetVersion();
217
278
  res.send(data.replace(/__VERSION__/g, version));
218
279
  });
219
280
  });
@@ -229,7 +290,7 @@ async function initializeServer() {
229
290
  const htmlPath = path.join(webappPath, 'index.html');
230
291
  fs.readFile(htmlPath, 'utf8', (err, data) => {
231
292
  if (err) return res.status(500).send('Error loading page');
232
- const version = require(path.join(__dirname, '../../package.json')).version;
293
+ const version = require('./utils/asset-version').getAssetVersion();
233
294
  res.send(data.replace(/__VERSION__/g, version));
234
295
  });
235
296
  });
@@ -271,9 +332,11 @@ async function initializeServer() {
271
332
 
272
333
  // Register REST endpoints
273
334
  rest.registerAllRestEndpoints(app, io);
335
+ app.use(expressErrorHandler);
274
336
 
275
337
  // Socket.IO connection handling
276
338
  io.on('connection', (socket) => {
339
+ guardSocket(socket);
277
340
  console.log('Client connected:', socket.id);
278
341
 
279
342
  // Send current open tabs to new client.
@@ -351,7 +414,28 @@ async function initializeServer() {
351
414
  const PORT = getPort();
352
415
  const BIND = getBindAddress();
353
416
 
417
+ // Certificates were only checked at startup: a server running for months
418
+ // kept serving a certificate past its expiry, or without the machine's
419
+ // new IP address. Re-check daily and swap the new one into the running
420
+ // server (existing connections keep working; new ones get the new cert).
421
+ if (actuallyHttps && typeof server.setSecureContext === 'function') {
422
+ const timer = setInterval(async () => {
423
+ try {
424
+ const fresh = await getSSLCredentials();
425
+ if (fresh && sslCredentials && (fresh.cert !== sslCredentials.cert || fresh.key !== sslCredentials.key)) {
426
+ server.setSecureContext({ key: fresh.key, cert: fresh.cert });
427
+ sslCredentials = fresh;
428
+ console.log('[HTTPS] Certificate renewed without a restart');
429
+ }
430
+ } catch (err) {
431
+ console.error('[HTTPS] Daily certificate check failed:', err.message);
432
+ }
433
+ }, 24 * 60 * 60 * 1000);
434
+ if (timer.unref) timer.unref();
435
+ }
436
+
354
437
  server.listen(PORT, BIND, () => {
438
+ serverListening = true;
355
439
  const address = BIND === '0.0.0.0' || BIND === '::' ? 'localhost' : BIND;
356
440
  const protocol = actuallyHttps ? 'https' : 'http';
357
441
  console.log(`Web SSH/SFTP Client running at ${protocol}://${address}:${PORT}`);
@@ -107,7 +107,12 @@ class PluginManager {
107
107
  }
108
108
  }
109
109
  if (instance && typeof instance.onSessionDisconnect === 'function') {
110
- for (const sessionId of this._lineBuffers.keys()) {
110
+ const ids = new Set(this._lineBuffers.keys());
111
+ const live = this.sshManager && this.sshManager.sessions;
112
+ if (live && typeof live.keys === 'function') {
113
+ for (const id of live.keys()) ids.add(id);
114
+ }
115
+ for (const sessionId of ids) {
111
116
  try { instance.onSessionDisconnect(sessionId); } catch (e) { /* ignore */ }
112
117
  }
113
118
  }
@@ -415,6 +420,12 @@ class PluginManager {
415
420
  }
416
421
 
417
422
  _processLineBuffer(sessionId, dataStr) {
423
+ // Nobody listens for lines: don't accumulate (full-screen apps that
424
+ // never print a newline grew this buffer without bound).
425
+ if (!this.hooks.onTerminalLine || this.hooks.onTerminalLine.length === 0) {
426
+ this._lineBuffers.delete(sessionId);
427
+ return;
428
+ }
418
429
  if (!this._lineBuffers.has(sessionId)) {
419
430
  this._lineBuffers.set(sessionId, '');
420
431
  }
@@ -428,6 +439,8 @@ class PluginManager {
428
439
  const split = rawLines.split('\n');
429
440
  lines.push(...split);
430
441
  }
442
+ // Cap an unterminated line at 64 KB (keep the newest output).
443
+ if (buffer.length > 65536) buffer = buffer.slice(-65536);
431
444
  this._lineBuffers.set(sessionId, buffer);
432
445
 
433
446
  for (const line of lines) {
@@ -17,7 +17,7 @@ function saveBookmark(id, data, io) {
17
17
  delete bookmark.encryptedConnection;
18
18
  bookmarks[index] = bookmark;
19
19
  } else {
20
- bookmark = { id: Date.now().toString(), name: data.name, type: data.type || 'ssh' };
20
+ bookmark = { id: require('crypto').randomUUID(), name: data.name, type: data.type || 'ssh' };
21
21
  if (bookmark.type === 'url') {
22
22
  bookmark.url = data.url;
23
23
  } else {