@lethevimlet/sshift 1.9.7 → 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.
- package/README.md +2 -1
- package/package.json +1 -1
- package/plugins/claude-attention/index.js +11 -0
- package/plugins/opencode-attention/index.js +11 -0
- package/plugins/remote-control/index.js +13 -1
- package/src/server/endpoints/rest/auth.js +45 -32
- package/src/server/endpoints/rest/bookmarks.js +5 -1
- package/src/server/endpoints/rest/config.js +19 -35
- package/src/server/endpoints/rest/folders.js +15 -3
- package/src/server/endpoints/rest/speech-ai.js +35 -9
- package/src/server/endpoints/rest/system.js +40 -4
- package/src/server/endpoints/ws/index.js +6 -0
- package/src/server/endpoints/ws/sftp.js +70 -10
- package/src/server/endpoints/ws/ssh.js +13 -5
- package/src/server/endpoints/ws/tabs.js +4 -4
- package/src/server/index.js +87 -3
- package/src/server/plugins/plugin-manager.js +21 -1
- package/src/server/services/bookmarks.js +1 -1
- package/src/server/services/headless-open.js +91 -0
- package/src/server/services/sftp-manager.js +80 -7
- package/src/server/services/ssh-manager.js +48 -13
- package/src/server/utils/asset-version.js +26 -0
- package/src/server/utils/auth-tokens.js +254 -0
- package/src/server/utils/bookmark-encryption.js +5 -0
- package/src/server/utils/certs.js +3 -0
- package/src/server/utils/config.js +49 -6
- package/src/server/utils/key-converter.js +30 -5
- package/src/server/utils/safe-handlers.js +80 -0
- package/src/server/utils/tab-manager.js +41 -1
- package/src/webapp/js/app.js +296 -193
- package/src/webapp/js/mobile-terminal.js +436 -79
- package/sshift +23 -2
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 === '
|
|
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 === '
|
|
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) {
|
package/src/server/index.js
CHANGED
|
@@ -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(
|
|
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(
|
|
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}`);
|
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
* - ctx.closeTab(sessionId) - Close a tab (ends its session) everywhere
|
|
31
31
|
* - ctx.getBookmarks() - Bookmark names/types (never credentials)
|
|
32
32
|
* - ctx.requestClientAction(event, data, opts) - Ask exactly ONE connected client to act
|
|
33
|
+
* - ctx.openBookmark(bookmarkId) - Connect an SSH bookmark on the server (no browser needed)
|
|
33
34
|
* - ctx.getDataDir() - User data directory (private plugin state)
|
|
34
35
|
*
|
|
35
36
|
* Plugins that hold resources (servers, timers) should implement destroy();
|
|
@@ -106,7 +107,12 @@ class PluginManager {
|
|
|
106
107
|
}
|
|
107
108
|
}
|
|
108
109
|
if (instance && typeof instance.onSessionDisconnect === 'function') {
|
|
109
|
-
|
|
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) {
|
|
110
116
|
try { instance.onSessionDisconnect(sessionId); } catch (e) { /* ignore */ }
|
|
111
117
|
}
|
|
112
118
|
}
|
|
@@ -341,6 +347,12 @@ class PluginManager {
|
|
|
341
347
|
return self.requestClientAction(event, data, options);
|
|
342
348
|
},
|
|
343
349
|
|
|
350
|
+
// Connect an SSH bookmark on the server (no browser needed); browsers attach via tab-opened.
|
|
351
|
+
async openBookmark(bookmarkId, options = {}) {
|
|
352
|
+
const { openBookmarkHeadless } = require('../services/headless-open');
|
|
353
|
+
return openBookmarkHeadless(self.io, bookmarkId, options);
|
|
354
|
+
},
|
|
355
|
+
|
|
344
356
|
getDataDir() {
|
|
345
357
|
const { getDataDir } = require('../utils/config');
|
|
346
358
|
return getDataDir();
|
|
@@ -408,6 +420,12 @@ class PluginManager {
|
|
|
408
420
|
}
|
|
409
421
|
|
|
410
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
|
+
}
|
|
411
429
|
if (!this._lineBuffers.has(sessionId)) {
|
|
412
430
|
this._lineBuffers.set(sessionId, '');
|
|
413
431
|
}
|
|
@@ -421,6 +439,8 @@ class PluginManager {
|
|
|
421
439
|
const split = rawLines.split('\n');
|
|
422
440
|
lines.push(...split);
|
|
423
441
|
}
|
|
442
|
+
// Cap an unterminated line at 64 KB (keep the newest output).
|
|
443
|
+
if (buffer.length > 65536) buffer = buffer.slice(-65536);
|
|
424
444
|
this._lineBuffers.set(sessionId, buffer);
|
|
425
445
|
|
|
426
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:
|
|
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 {
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Open an SSH bookmark on the SERVER, without any browser page.
|
|
3
|
+
*
|
|
4
|
+
* Used by automation (the remote-control plugin → voice assistants): the
|
|
5
|
+
* server connects the bookmark itself with a stand-in socket, registers the
|
|
6
|
+
* tab, and tells every connected browser through the normal `tab-opened`
|
|
7
|
+
* broadcast, so open pages attach exactly as they do for a tab opened on
|
|
8
|
+
* another device. Pages opened later get it through `open-tabs`.
|
|
9
|
+
*
|
|
10
|
+
* Credentials are read from the stored bookmark on the server; they are never
|
|
11
|
+
* broadcast (the browsers only receive name/host/port/username). Encrypted
|
|
12
|
+
* bookmarks work only while the server holds the unlock key (after a login).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const crypto = require('crypto');
|
|
16
|
+
const { loadConfig, getStickySetting, getScrollback } = require('../utils/config');
|
|
17
|
+
const { getDecryptedBookmarks } = require('../utils/bookmark-encryption');
|
|
18
|
+
const tabManager = require('../utils/tab-manager');
|
|
19
|
+
const sshManager = require('./ssh-manager');
|
|
20
|
+
|
|
21
|
+
// Size of the server-side terminal until a browser attaches and resizes it.
|
|
22
|
+
// Wider than the 80x24 default so coding agents (Claude Code, opencode) and
|
|
23
|
+
// screen reads by the assistant are not cramped.
|
|
24
|
+
const HEADLESS_COLS = 120;
|
|
25
|
+
const HEADLESS_ROWS = 36;
|
|
26
|
+
|
|
27
|
+
class HeadlessOpenError extends Error {
|
|
28
|
+
constructor(status, message) { super(message); this.status = status; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// A Socket.IO-shaped object that receives nothing: the session's output goes to
|
|
32
|
+
// the `session-<id>` room (browsers that join later) and to the headless terminal.
|
|
33
|
+
function standInSocket() {
|
|
34
|
+
const noop = () => {};
|
|
35
|
+
return { id: `headless-${crypto.randomUUID()}`, emit: noop, join: noop, leave: noop, to: () => ({ emit: noop }) };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function openBookmarkHeadless(io, bookmarkId, { cols = HEADLESS_COLS, rows = HEADLESS_ROWS } = {}) {
|
|
39
|
+
const config = loadConfig();
|
|
40
|
+
let bookmarks;
|
|
41
|
+
try {
|
|
42
|
+
bookmarks = getDecryptedBookmarks(config);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (err.code === 'BOOKMARKS_LOCKED') throw new HeadlessOpenError(409, 'Bookmarks are encrypted and locked; log in to sshift once to unlock them');
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
const bookmark = bookmarks.find(b => b.id === bookmarkId);
|
|
48
|
+
if (!bookmark) throw new HeadlessOpenError(404, 'Bookmark not found');
|
|
49
|
+
if ((bookmark.type || 'ssh') !== 'ssh') throw new HeadlessOpenError(409, 'Only SSH bookmarks can be opened without a browser');
|
|
50
|
+
|
|
51
|
+
const name = bookmark.name || bookmark.host || 'SSH';
|
|
52
|
+
const publicData = { name, host: bookmark.host, port: bookmark.port || 22, username: bookmark.username };
|
|
53
|
+
const socket = standInSocket();
|
|
54
|
+
let sessionId;
|
|
55
|
+
try {
|
|
56
|
+
sessionId = await sshManager.connect(socket, {
|
|
57
|
+
...publicData,
|
|
58
|
+
password: bookmark.password || '',
|
|
59
|
+
privateKey: bookmark.privateKey || '',
|
|
60
|
+
passphrase: bookmark.passphrase || '',
|
|
61
|
+
cols, rows,
|
|
62
|
+
sshKeepaliveInterval: config.sshKeepaliveInterval || 10000,
|
|
63
|
+
sshKeepaliveCountMax: config.sshKeepaliveCountMax || 1000,
|
|
64
|
+
scrollback: getScrollback()
|
|
65
|
+
});
|
|
66
|
+
} catch (err) {
|
|
67
|
+
throw new HeadlessOpenError(502, `Could not connect ${name}: ${err.message}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Nobody is attached: no controller, so the first browser that joins gets control.
|
|
71
|
+
const session = sshManager.sessions.get(sessionId);
|
|
72
|
+
if (session) {
|
|
73
|
+
session.sockets.delete(socket.id);
|
|
74
|
+
if (session.controllerSocket === socket.id) session.controllerSocket = null;
|
|
75
|
+
}
|
|
76
|
+
tabManager.addTab(sessionId, {
|
|
77
|
+
name,
|
|
78
|
+
type: 'ssh',
|
|
79
|
+
connectionData: publicData,
|
|
80
|
+
activeSockets: new Set(),
|
|
81
|
+
sticky: getStickySetting(),
|
|
82
|
+
openedHeadless: true
|
|
83
|
+
});
|
|
84
|
+
if (io) {
|
|
85
|
+
io.emit('tab-opened', { sessionId, name, type: 'ssh', connectionData: publicData });
|
|
86
|
+
io.emit('sessions-updated');
|
|
87
|
+
}
|
|
88
|
+
return { sessionId, name };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { openBookmarkHeadless, HeadlessOpenError, HEADLESS_COLS, HEADLESS_ROWS };
|