@lethevimlet/sshift 1.9.8 → 1.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 {
@@ -106,24 +106,62 @@ class SFTPManager {
106
106
  console.warn(`[SFTP] Could not resolve home directory: ${realpathErr?.message}`);
107
107
  }
108
108
 
109
+ // A client-chosen id can collide with a live session (two
110
+ // browsers recreating the same tab): retire the old connection
111
+ // so its late close event cannot tear down this one.
112
+ const previous = this.sessions.get(sessionId);
113
+ if (previous && previous !== session) {
114
+ console.warn(`[SFTP] Replacing existing session with the same id: ${sessionId}`);
115
+ previous.replaced = true;
116
+ try { previous.conn.end(); } catch (_) {}
117
+ }
109
118
  this.sessions.set(sessionId, session);
119
+ ownSession = session;
120
+ established = true;
121
+ // Every viewer (creator + sftp-join) hears errors/disconnects,
122
+ // not only the socket that created the session.
123
+ try { socket.join(`sftp-${sessionId}`); } catch (_) {}
110
124
  console.log(`[SFTP] SFTP session started: ${sessionId}`);
111
125
  resolve(sessionId);
112
126
  });
113
127
  });
114
128
  });
115
129
 
130
+ let established = false;
131
+ let ownSession = null;
132
+ const owns = () => {
133
+ const current = this.sessions.get(sessionId);
134
+ if (current && current.conn === conn) ownSession = current;
135
+ return !!current && current.conn === conn;
136
+ };
137
+ const notify = (event, payload) => {
138
+ if (established && socket.nsp) socket.nsp.to(`sftp-${sessionId}`).emit(event, payload);
139
+ else socket.emit(event, payload);
140
+ };
141
+
116
142
  conn.on('error', (err) => {
117
143
  console.error(`[SFTP] Connection error: ${err.message}`);
118
- socket.emit('sftp-error', { sessionId, message: err.message });
119
- this.sessions.delete(sessionId);
120
- removeTab(sessionId);
144
+ if (ownSession && ownSession.replaced) return reject(err);
145
+ notify('sftp-error', { sessionId, message: err.message });
146
+ if (owns()) {
147
+ this.sessions.delete(sessionId);
148
+ removeTab(sessionId);
149
+ } else if (!this.sessions.has(sessionId)) {
150
+ removeTab(sessionId);
151
+ }
121
152
  reject(err);
122
153
  });
123
154
 
124
155
  conn.on('close', () => {
125
156
  console.log(`[SFTP] Connection closed: ${sessionId}`);
126
- socket.emit('sftp-disconnected', { sessionId });
157
+ if (!owns()) {
158
+ // Replaced by a newer connection with the same id, or never
159
+ // established: leave the live session and its tab alone.
160
+ if (!established && !this.sessions.has(sessionId)) removeTab(sessionId);
161
+ reject(new Error('Connection closed'));
162
+ return;
163
+ }
164
+ notify('sftp-disconnected', { sessionId });
127
165
  this.sessions.delete(sessionId);
128
166
  removeTab(sessionId);
129
167
  });
@@ -233,6 +271,19 @@ try {
233
271
  return session.sftp.createReadStream(path);
234
272
  }
235
273
 
274
+ // An upload whose browser vanished (tab closed, network lost) never sends
275
+ // end/cancel: drop it after this long without a chunk, closing the
276
+ // remote file handle it holds.
277
+ _armUploadIdle(upload) {
278
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
279
+ upload.idleTimer = setTimeout(() => {
280
+ if (!this.activeUploads.has(upload.id)) return;
281
+ console.warn(`[SFTP] Upload ${upload.id} (${upload.path}) idle for 2 minutes, aborting`);
282
+ this.uploadCancel(upload.id);
283
+ }, 2 * 60 * 1000);
284
+ if (upload.idleTimer.unref) upload.idleTimer.unref();
285
+ }
286
+
236
287
  uploadStart(sessionId, path, fileName, fileSize) {
237
288
  const session = this.sessions.get(sessionId);
238
289
  if (!session) {
@@ -244,6 +295,7 @@ try {
244
295
 
245
296
  const upload = {
246
297
  id: uploadId,
298
+ sessionId,
247
299
  stream,
248
300
  bytesWritten: 0,
249
301
  totalBytes: fileSize,
@@ -261,10 +313,12 @@ try {
261
313
  upload.rejectEnd = null;
262
314
  upload.resolveEnd = null;
263
315
  }
316
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
264
317
  this.activeUploads.delete(uploadId);
265
318
  });
266
319
 
267
320
  stream.on('close', () => {
321
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
268
322
  if (upload.resolveEnd) {
269
323
  upload.resolveEnd({ path: upload.path, fileName: upload.fileName });
270
324
  upload.resolveEnd = null;
@@ -274,6 +328,7 @@ try {
274
328
  });
275
329
 
276
330
  this.activeUploads.set(uploadId, upload);
331
+ this._armUploadIdle(upload);
277
332
  return uploadId;
278
333
  }
279
334
 
@@ -289,9 +344,18 @@ try {
289
344
  return;
290
345
  }
291
346
 
347
+ if (typeof chunkBase64 !== 'string') {
348
+ reject(new Error('Invalid chunk'));
349
+ return;
350
+ }
351
+ this._armUploadIdle(upload);
292
352
  const chunkData = Buffer.from(chunkBase64, 'base64');
293
353
 
294
- upload.stream.write(chunkData, () => {
354
+ upload.stream.write(chunkData, (err) => {
355
+ if (err) {
356
+ reject(err);
357
+ return;
358
+ }
295
359
  upload.bytesWritten += chunkData.length;
296
360
  resolve({
297
361
  bytesWritten: upload.bytesWritten,
@@ -323,7 +387,13 @@ try {
323
387
  uploadCancel(uploadId) {
324
388
  const upload = this.activeUploads.get(uploadId);
325
389
  if (upload) {
326
- upload.stream.destroy();
390
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
391
+ try { upload.stream.destroy(); } catch (_) {}
392
+ if (upload.rejectEnd) {
393
+ upload.rejectEnd(new Error('Upload cancelled'));
394
+ upload.rejectEnd = null;
395
+ upload.resolveEnd = null;
396
+ }
327
397
  this.activeUploads.delete(uploadId);
328
398
  }
329
399
  }
@@ -436,6 +506,9 @@ try {
436
506
  disconnect(sessionId) {
437
507
  const session = this.sessions.get(sessionId);
438
508
  if (session) {
509
+ for (const upload of [...this.activeUploads.values()]) {
510
+ if (upload.sessionId === sessionId) this.uploadCancel(upload.id);
511
+ }
439
512
  if (session.conn) {
440
513
  session.conn.end();
441
514
  }
@@ -463,7 +536,7 @@ try {
463
536
  console.log(`[SFTP] Cannot join session ${sessionId}: session not found`);
464
537
  return false;
465
538
  }
466
-
539
+ try { socket.join(`sftp-${sessionId}`); } catch (_) {}
467
540
  return true;
468
541
  }
469
542