@lethevimlet/sshift 1.9.2 → 1.9.4

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 CHANGED
@@ -271,6 +271,19 @@ Add plugins to your `config.json`:
271
271
 
272
272
  See [Configuration > Plugins](docs/configuration.md#plugins) for full details.
273
273
 
274
+ ### Remote Control (local assistants)
275
+
276
+ The opt-in `remote-control` plugin exposes a **loopback-only, token-protected** HTTP API so a
277
+ local assistant (for example a voice assistant's MCP server) can list and switch tabs, open
278
+ bookmarks, read a terminal's screen as plain text, type text and press keys. Typing never
279
+ presses Enter; submitting is always a separate, explicit key request.
280
+
281
+ ```json
282
+ { "plugins": [{ "name": "remote-control", "enabled": true, "config": { "port": 8044 } }] }
283
+ ```
284
+
285
+ See [Configuration > Remote Control](docs/configuration.md#remote-control-plugin).
286
+
274
287
  ## 🛠️ Technology Stack
275
288
 
276
289
  **Backend:** Node.js, Express, Socket.IO, ssh2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.9.2",
3
+ "version": "1.9.4",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -0,0 +1,305 @@
1
+ /**
2
+ * remote-control Plugin
3
+ *
4
+ * A small HTTP API for LOCAL automation, e.g. a voice assistant's MCP
5
+ * server: list and switch tabs, open bookmarks, read a session's screen as
6
+ * plain text, type text and send named keys.
7
+ *
8
+ * Security model:
9
+ * - Binds to a loopback address only (non-loopback `host` is refused).
10
+ * - Every request needs `Authorization: Bearer <token>`. The token lives in
11
+ * `<dataDir>/remote-control.token` (mode 0600), generated on first start.
12
+ * Anyone who can read that file can type into your sessions.
13
+ * - Text input never contains control characters. Multi-line text is only
14
+ * accepted when the target application enabled bracketed paste, so a
15
+ * newline can never execute a shell line on its own. Enter is a separate,
16
+ * explicit key request — callers decide when to submit.
17
+ * - Credentials are never returned (bookmarks are listed by name/type).
18
+ *
19
+ * Config (config.json → plugins[] entry "remote-control"):
20
+ * { "port": 8044, "host": "127.0.0.1", "tokenFile": "<optional path>" }
21
+ *
22
+ * Endpoints (JSON):
23
+ * GET /v1/health
24
+ * GET /v1/tabs → { activeSessionId, tabs: [...] }
25
+ * GET /v1/bookmarks → { bookmarks: [{ id, name, type, folder }] }
26
+ * GET /v1/screen?sessionId=&history=N
27
+ * POST /v1/switch { sessionId }
28
+ * POST /v1/open { bookmarkId } → opens it on ONE connected browser
29
+ * POST /v1/type { sessionId?, text }
30
+ * POST /v1/key { sessionId?, key, repeat? }
31
+ * sessionId defaults to the focused tab.
32
+ */
33
+
34
+ const http = require('http');
35
+ const fs = require('fs');
36
+ const path = require('path');
37
+ const crypto = require('crypto');
38
+
39
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost']);
40
+ const MAX_BODY = 64 * 1024;
41
+ const MAX_TEXT = 8000;
42
+
43
+ // Named keys. Cursor keys depend on DECCKM (application cursor mode).
44
+ const KEYS = {
45
+ enter: '\r',
46
+ tab: '\t',
47
+ 'shift-tab': '\x1b[Z',
48
+ escape: '\x1b',
49
+ backspace: '\x7f',
50
+ delete: '\x1b[3~',
51
+ space: ' ',
52
+ 'ctrl-a': '\x01',
53
+ 'ctrl-c': '\x03',
54
+ 'ctrl-d': '\x04',
55
+ 'ctrl-e': '\x05',
56
+ 'ctrl-k': '\x0b',
57
+ 'ctrl-l': '\x0c',
58
+ 'ctrl-r': '\x12',
59
+ 'ctrl-u': '\x15',
60
+ 'ctrl-w': '\x17',
61
+ 'ctrl-z': '\x1a',
62
+ 'page-up': '\x1b[5~',
63
+ 'page-down': '\x1b[6~',
64
+ };
65
+ const CURSOR_KEYS = { up: 'A', down: 'B', right: 'C', left: 'D', home: 'H', end: 'F' };
66
+ const KEY_NAMES = [...Object.keys(KEYS), ...Object.keys(CURSOR_KEYS)];
67
+
68
+ // App hints so callers can find "the claude tab" or "the opencode tab".
69
+ // Case-sensitive wordmarks, mirroring the attention plugins' signatures.
70
+ const APP_PATTERNS = [
71
+ ['claude', /\? for shortcuts|esc to interrupt|⏵⏵|accept edits on|bypass permissions on|shift\+tab to cycle|Claude Code/],
72
+ ['opencode', /OpenCode|ctrl\+p commands/],
73
+ ];
74
+
75
+ function detectApp(text) {
76
+ if (!text) return null;
77
+ const tail = text.lines.slice(-30).join('\n');
78
+ for (const [app, pattern] of APP_PATTERNS) if (pattern.test(tail)) return app;
79
+ return text.alternateScreen ? 'fullscreen' : 'shell';
80
+ }
81
+
82
+ class HttpError extends Error {
83
+ constructor(status, message) { super(message); this.status = status; }
84
+ }
85
+
86
+ class RemoteControlPlugin {
87
+ constructor(ctx, config = {}) {
88
+ this.ctx = ctx;
89
+ this.config = config;
90
+ this.server = null;
91
+ }
92
+
93
+ init() {
94
+ const host = this.config.host || '127.0.0.1';
95
+ const port = Number(this.config.port) || 8044;
96
+ if (!LOOPBACK.has(host)) {
97
+ console.error(`[remote-control] Refusing non-loopback host "${host}"; plugin disabled.`);
98
+ return;
99
+ }
100
+ try {
101
+ this.token = this._loadToken();
102
+ } catch (err) {
103
+ console.error('[remote-control] Cannot prepare token file:', err.message);
104
+ return;
105
+ }
106
+ this.server = http.createServer((req, res) => this._handle(req, res));
107
+ this.server.on('error', err => console.error('[remote-control] Server error:', err.message));
108
+ this.server.listen(port, host, () => console.log(`[remote-control] Listening on http://${host}:${port}`));
109
+ }
110
+
111
+ destroy() {
112
+ if (this.server) this.server.close();
113
+ this.server = null;
114
+ }
115
+
116
+ _tokenFile() {
117
+ return this.config.tokenFile || path.join(this.ctx.getDataDir(), 'remote-control.token');
118
+ }
119
+
120
+ _loadToken() {
121
+ const file = this._tokenFile();
122
+ try {
123
+ const token = fs.readFileSync(file, 'utf8').trim();
124
+ if (token.length >= 32) return token;
125
+ } catch (err) {
126
+ if (err.code !== 'ENOENT') throw err;
127
+ }
128
+ const token = crypto.randomBytes(32).toString('hex');
129
+ fs.mkdirSync(path.dirname(file), { recursive: true });
130
+ fs.writeFileSync(file, token + '\n', { mode: 0o600 });
131
+ fs.chmodSync(file, 0o600);
132
+ console.log(`[remote-control] Generated access token in ${file}`);
133
+ return token;
134
+ }
135
+
136
+ _authorized(req) {
137
+ const header = req.headers.authorization || '';
138
+ const match = /^Bearer (\S+)$/.exec(header);
139
+ if (!match || !this.token) return false;
140
+ const a = Buffer.from(match[1]);
141
+ const b = Buffer.from(this.token);
142
+ return a.length === b.length && crypto.timingSafeEqual(a, b);
143
+ }
144
+
145
+ async _handle(req, res) {
146
+ const send = (status, body) => {
147
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
148
+ res.end(JSON.stringify(body));
149
+ };
150
+ try {
151
+ // Browsers must never drive this API (DNS rebinding / CSRF).
152
+ if (req.headers.origin) throw new HttpError(403, 'Browser requests are not allowed');
153
+ if (!this._authorized(req)) throw new HttpError(401, 'Unauthorized');
154
+ const url = new URL(req.url, 'http://localhost');
155
+ const route = `${req.method} ${url.pathname}`;
156
+ const body = req.method === 'POST' ? await this._readBody(req) : {};
157
+ switch (route) {
158
+ case 'GET /v1/health': return send(200, { ok: true });
159
+ case 'GET /v1/tabs': return send(200, this.tabs());
160
+ case 'GET /v1/bookmarks': return send(200, { bookmarks: this.ctx.getBookmarks() });
161
+ case 'GET /v1/screen': return send(200, this.screen(url.searchParams.get('sessionId'), url.searchParams.get('history')));
162
+ case 'POST /v1/switch': return send(200, this.switchTab(body.sessionId));
163
+ case 'POST /v1/open': return send(200, await this.open(body.bookmarkId));
164
+ case 'POST /v1/type': return send(200, await this.type(body.sessionId, body.text));
165
+ case 'POST /v1/key': return send(200, await this.key(body.sessionId, body.key, body.repeat));
166
+ default: throw new HttpError(404, 'Not found');
167
+ }
168
+ } catch (err) {
169
+ const status = err.status || 500;
170
+ if (status === 500) console.error('[remote-control] Request failed:', err.message);
171
+ send(status, { error: status === 500 ? 'Internal error' : err.message });
172
+ }
173
+ }
174
+
175
+ _readBody(req) {
176
+ return new Promise((resolve, reject) => {
177
+ let size = 0;
178
+ const chunks = [];
179
+ req.on('data', chunk => {
180
+ size += chunk.length;
181
+ if (size > MAX_BODY) { reject(new HttpError(413, 'Body too large')); req.destroy(); return; }
182
+ chunks.push(chunk);
183
+ });
184
+ req.on('end', () => {
185
+ if (!chunks.length) return resolve({});
186
+ try {
187
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
188
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error();
189
+ resolve(value);
190
+ } catch { reject(new HttpError(400, 'Invalid JSON body')); }
191
+ });
192
+ req.on('error', reject);
193
+ });
194
+ }
195
+
196
+ tabs() {
197
+ const { activeSessionId, tabs } = this.ctx.getTabs();
198
+ return {
199
+ activeSessionId,
200
+ tabs: tabs.map(tab => ({
201
+ ...tab,
202
+ focused: tab.sessionId === activeSessionId,
203
+ app: tab.type === 'ssh' && tab.connected ? detectApp(this.ctx.getTerminalText(tab.sessionId)) : null,
204
+ })),
205
+ };
206
+ }
207
+
208
+ _target(sessionId) {
209
+ const { activeSessionId, tabs } = this.ctx.getTabs();
210
+ let id = sessionId;
211
+ if (!id) {
212
+ const ssh = tabs.filter(t => t.type === 'ssh' && t.connected);
213
+ id = activeSessionId || (ssh.length === 1 ? ssh[0].sessionId : null);
214
+ if (!id) throw new HttpError(409, 'No focused tab; specify sessionId');
215
+ }
216
+ const tab = tabs.find(t => t.sessionId === id);
217
+ if (!tab) throw new HttpError(404, 'Tab not found');
218
+ if (tab.type !== 'ssh') throw new HttpError(409, 'Only SSH terminal tabs accept input');
219
+ if (!tab.connected) throw new HttpError(409, 'The tab is not connected');
220
+ return tab;
221
+ }
222
+
223
+ screen(sessionId, history) {
224
+ const tab = this._target(sessionId);
225
+ const text = this.ctx.getTerminalText(tab.sessionId, { history: Math.min(Number(history) || 0, 500) });
226
+ if (!text) throw new HttpError(409, 'Screen unavailable');
227
+ return { sessionId: tab.sessionId, name: tab.name, app: detectApp(text), ...text };
228
+ }
229
+
230
+ switchTab(sessionId) {
231
+ if (typeof sessionId !== 'string' || !sessionId) throw new HttpError(400, 'sessionId required');
232
+ if (!this.ctx.switchTab(sessionId)) throw new HttpError(404, 'Tab not found');
233
+ const tab = this.ctx.getTabs().tabs.find(t => t.sessionId === sessionId);
234
+ return { switched: true, sessionId, name: tab?.name || null };
235
+ }
236
+
237
+ async open(bookmarkId) {
238
+ const bookmark = this.ctx.getBookmarks().find(b => b.id === bookmarkId);
239
+ if (!bookmark) throw new HttpError(404, 'Bookmark not found');
240
+ if (!['ssh', 'sftp'].includes(bookmark.type)) throw new HttpError(409, 'Only SSH/SFTP bookmarks can be opened');
241
+ const before = new Set(this.ctx.getTabs().tabs.map(t => t.sessionId));
242
+ const claim = await this.ctx.requestClientAction('remote-open-bookmark', { bookmarkId });
243
+ if (!claim.claimed) {
244
+ throw new HttpError(409, 'No sshift browser page is open to connect the bookmark; open sshift first');
245
+ }
246
+ const deadline = Date.now() + 10000;
247
+ while (Date.now() < deadline) {
248
+ const tab = this.ctx.getTabs().tabs.find(t => !before.has(t.sessionId));
249
+ if (tab) {
250
+ // The opening client's tabs-save can arrive before the tab exists on
251
+ // the server, leaving no focused session; focus the new tab here.
252
+ this.ctx.switchTab(tab.sessionId);
253
+ return { opened: true, sessionId: tab.sessionId, name: tab.name, connected: tab.connected };
254
+ }
255
+ await new Promise(resolve => setTimeout(resolve, 200));
256
+ }
257
+ return { opened: true, sessionId: null, name: bookmark.name, pending: true };
258
+ }
259
+
260
+ async _inputLine(sessionId) {
261
+ await new Promise(resolve => setTimeout(resolve, 150));
262
+ const text = this.ctx.getTerminalText(sessionId);
263
+ if (!text) return null;
264
+ return (text.lines[text.cursorLine] || '').trimEnd().slice(-300);
265
+ }
266
+
267
+ async type(sessionId, text) {
268
+ if (typeof text !== 'string' || !text.length) throw new HttpError(400, 'text required');
269
+ if (text.length > MAX_TEXT) throw new HttpError(413, 'text too long');
270
+ const normalized = text.replace(/\r\n?/g, '\n');
271
+ if (/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(normalized)) {
272
+ throw new HttpError(400, 'text must not contain control characters; use /v1/key for keys');
273
+ }
274
+ const tab = this._target(sessionId);
275
+ const multiLine = normalized.includes('\n');
276
+ let data = normalized;
277
+ if (multiLine) {
278
+ const screen = this.ctx.getTerminalText(tab.sessionId);
279
+ if (!screen || !screen.bracketedPaste) {
280
+ throw new HttpError(409, 'This application does not accept pasted multi-line text; send one line at a time');
281
+ }
282
+ data = `\x1b[200~${normalized}\x1b[201~`;
283
+ }
284
+ this.ctx.sendInput(tab.sessionId, data);
285
+ return { typed: true, sessionId: tab.sessionId, name: tab.name, pasted: multiLine, submitted: false, inputLine: await this._inputLine(tab.sessionId) };
286
+ }
287
+
288
+ async key(sessionId, key, repeat = 1) {
289
+ if (!KEY_NAMES.includes(key)) throw new HttpError(400, `Unknown key; use one of: ${KEY_NAMES.join(', ')}`);
290
+ const times = Number.isInteger(repeat) ? repeat : 1;
291
+ if (times < 1 || times > 20) throw new HttpError(400, 'repeat must be 1-20');
292
+ const tab = this._target(sessionId);
293
+ let sequence = KEYS[key];
294
+ if (!sequence) {
295
+ const screen = this.ctx.getTerminalText(tab.sessionId);
296
+ sequence = (screen && screen.applicationCursorKeys ? '\x1bO' : '\x1b[') + CURSOR_KEYS[key];
297
+ }
298
+ this.ctx.sendInput(tab.sessionId, sequence.repeat(times));
299
+ return { sent: true, sessionId: tab.sessionId, name: tab.name, key, repeat: times, inputLine: await this._inputLine(tab.sessionId) };
300
+ }
301
+ }
302
+
303
+ RemoteControlPlugin.KEY_NAMES = KEY_NAMES;
304
+ RemoteControlPlugin.detectApp = detectApp;
305
+ module.exports = RemoteControlPlugin;
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "remote-control",
3
+ "version": "1.0.0",
4
+ "description": "Loopback, token-protected HTTP API for local assistants: list/switch tabs, open bookmarks, read the screen, type text and send keys",
5
+ "type": "sshift-plugin"
6
+ }
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  const { loadConfig, saveConfig } = require('../../utils/config');
6
+ const { saveBookmark } = require('../../services/bookmarks');
6
7
  const {
7
8
  BookmarkEncryptionLockedError,
8
9
  getDecryptedBookmarks,
@@ -10,6 +11,7 @@ const {
10
11
  } = require('../../utils/bookmark-encryption');
11
12
 
12
13
  function handleBookmarkError(res, err) {
14
+ if (err.status === 404) return res.status(404).json({ error: err.message });
13
15
  if (err instanceof BookmarkEncryptionLockedError) {
14
16
  return res.status(423).json({ error: 'Encrypted bookmarks are locked; sign in again' });
15
17
  }
@@ -35,38 +37,8 @@ function registerBookmarkEndpoints(app, io) {
35
37
 
36
38
  // API: Add bookmark
37
39
  app.post('/api/bookmarks', (req, res) => {
38
- const config = loadConfig();
39
- const bookmark = {
40
- id: Date.now().toString(),
41
- name: req.body.name,
42
- type: req.body.type || 'ssh'
43
- };
44
-
45
- // Add type-specific fields
46
- if (req.body.type === 'url') {
47
- bookmark.url = req.body.url;
48
- } else {
49
- bookmark.host = req.body.host;
50
- bookmark.port = req.body.port || 22;
51
- bookmark.username = req.body.username;
52
- }
53
-
54
- // Add optional fields
55
- if (req.body.password) bookmark.password = req.body.password;
56
- if (req.body.privateKey) bookmark.privateKey = req.body.privateKey;
57
- if (req.body.passphrase) bookmark.passphrase = req.body.passphrase;
58
- if (req.body.folderId) bookmark.folderId = req.body.folderId;
59
-
60
40
  try {
61
- const bookmarks = getDecryptedBookmarks(config);
62
- bookmarks.push(bookmark);
63
- storeBookmarks(config, bookmarks);
64
- if (!saveConfig(config)) {
65
- return res.status(500).json({ error: 'Failed to save bookmark' });
66
- }
67
- // Broadcast to all clients
68
- io.emit('bookmark-added', bookmark);
69
- res.json(bookmark);
41
+ res.json(saveBookmark(null, req.body, io));
70
42
  } catch (err) {
71
43
  handleBookmarkError(res, err);
72
44
  }
@@ -91,26 +63,8 @@ function registerBookmarkEndpoints(app, io) {
91
63
 
92
64
  // API: Update bookmark
93
65
  app.put('/api/bookmarks/:id', (req, res) => {
94
- const config = loadConfig();
95
66
  try {
96
- const bookmarks = getDecryptedBookmarks(config);
97
- const index = bookmarks.findIndex(b => b.id === req.params.id);
98
- if (index === -1) {
99
- return res.status(404).json({ error: 'Bookmark not found' });
100
- }
101
- bookmarks[index] = {
102
- ...bookmarks[index],
103
- ...req.body,
104
- id: req.params.id
105
- };
106
- delete bookmarks[index].encryptedConnection;
107
- storeBookmarks(config, bookmarks);
108
- if (!saveConfig(config)) {
109
- return res.status(500).json({ error: 'Failed to update bookmark' });
110
- }
111
- // Broadcast decrypted data only to authenticated, connected clients.
112
- io.emit('bookmark-updated', bookmarks[index]);
113
- res.json(bookmarks[index]);
67
+ res.json(saveBookmark(req.params.id, req.body, io));
114
68
  } catch (err) {
115
69
  handleBookmarkError(res, err);
116
70
  }
@@ -0,0 +1,26 @@
1
+ const { isPasswordSet } = require('../../utils/config');
2
+ const { isValidAuthToken } = require('../rest/auth');
3
+ const { BookmarkEncryptionLockedError } = require('../../utils/bookmark-encryption');
4
+ const { saveBookmark } = require('../../services/bookmarks');
5
+
6
+ function registerBookmarkHandlers(socket, io) {
7
+ socket.on('bookmark-save', (data, acknowledge) => {
8
+ if (typeof acknowledge !== 'function') return;
9
+ const token = socket.handshake.auth?.token || socket.handshake.query?.token;
10
+ if (isPasswordSet() && !isValidAuthToken(token)) {
11
+ return acknowledge({ error: 'Authentication required' });
12
+ }
13
+ if (!data || !data.bookmark || typeof data.bookmark !== 'object' || Array.isArray(data.bookmark)) {
14
+ return acknowledge({ error: 'Invalid bookmark' });
15
+ }
16
+ try {
17
+ acknowledge({ bookmark: saveBookmark(data.id, data.bookmark, io) });
18
+ } catch (err) {
19
+ acknowledge({ error: err instanceof BookmarkEncryptionLockedError
20
+ ? 'Encrypted bookmarks are locked; sign in again'
21
+ : err.status === 404 ? err.message : 'Failed to save bookmark' });
22
+ }
23
+ });
24
+ }
25
+
26
+ module.exports = { registerBookmarkHandlers };
@@ -7,6 +7,7 @@ const { registerSSHHandlers, handleSSHDisconnect } = require('./ssh');
7
7
  const { registerSFTPHandlers, handleSFTPDisconnect } = require('./sftp');
8
8
  const { registerTabHandlers, handleTabDisconnect } = require('./tabs');
9
9
  const { registerLayoutHandlers, getCurrentLayout, setCurrentLayout } = require('./layout');
10
+ const { registerBookmarkHandlers } = require('./bookmarks');
10
11
 
11
12
  /**
12
13
  * Register all WebSocket handlers
@@ -18,6 +19,7 @@ function registerAllWSHandlers(socket, io) {
18
19
  registerSFTPHandlers(socket, io);
19
20
  registerTabHandlers(socket, io);
20
21
  registerLayoutHandlers(socket, io);
22
+ registerBookmarkHandlers(socket, io);
21
23
  }
22
24
 
23
25
  /**
@@ -43,4 +45,4 @@ module.exports = {
43
45
  setCurrentLayout,
44
46
  registerAllWSHandlers,
45
47
  handleDisconnect
46
- };
48
+ };
@@ -262,7 +262,7 @@ function registerSSHHandlers(socket, io) {
262
262
  });
263
263
 
264
264
  // SSH disconnect — historically meant "I'm done with this session locally".
265
- // Treat it identically to tab-close: viewer-aware + sticky-aware teardown.
265
+ // Detach this viewer, unlike tab-close which explicitly ends the session.
266
266
  // Only destroy the underlying SSH stream when no other clients remain AND
267
267
  // the session is non-sticky. This lets the orchestrator close their view
268
268
  // without yanking the session out from under sticky observers (or shedding
@@ -335,4 +335,4 @@ function handleSSHDisconnect(socket, io) {
335
335
  };
336
336
  }
337
337
 
338
- module.exports = { registerSSHHandlers, handleSSHDisconnect };
338
+ module.exports = { registerSSHHandlers, handleSSHDisconnect };
@@ -26,70 +26,24 @@ const { sshManager, sftpManager } = require('../../services');
26
26
  * @param {Object} io - Socket.IO instance
27
27
  */
28
28
  function registerTabHandlers(socket, io) {
29
- // Tab close event (client-side tab close, not full disconnect)
29
+ // An explicit close ends the shared session. Socket disconnect/reload is
30
+ // handled separately below and retains sticky sessions/reconnect grace.
30
31
  socket.on('tab-close', (data) => {
31
32
  console.log('[TAB] Tab closed:', data.sessionId, 'by socket:', socket.id);
32
-
33
- // Remove this socket from the tab's active sockets
34
33
  const tab = getTab(data.sessionId);
34
+ clearCloseTimer(data.sessionId);
35
+ // Remove restoration state before disconnecting the stream, which can
36
+ // synchronously emit events. No reconnect should resurrect a closed tab.
37
+ removeTab(data.sessionId);
35
38
  if (tab) {
36
- removeSocketFromTab(data.sessionId, socket.id);
37
-
38
- // If other sockets are still viewing this tab, the originating
39
- // client's close must NOT tear down the session for them.
40
- // Just notify remaining viewers to refresh their sessions list.
41
- // The originating client already removed the tab locally via
42
- // closeTab() (app.js), so it does NOT need a tab-closed echo.
43
- if (tab.activeSockets.size > 0) {
44
- console.log('[TAB] Tab closed by', socket.id, 'but', tab.activeSockets.size, 'viewer(s) remain; keeping session:', data.sessionId);
45
- // SSH: drop this socket from the session room so it stops
46
- // receiving broadcasts from this session.
47
- if (tab.type === 'ssh') {
48
- sshManager.leaveSession(socket, data.sessionId);
49
- }
50
- // Tell remaining clients to refresh any open "manage sessions"
51
- // modal — they may want to reflect the new viewer count.
52
- io.emit('sessions-updated');
53
- return;
39
+ if (tab.type === 'ssh') {
40
+ sshManager.disconnect(data.sessionId);
41
+ } else if (tab.type === 'sftp') {
42
+ sftpManager.disconnect(data.sessionId);
54
43
  }
55
-
56
- // No more viewers left after this close. Honor the sticky flag:
57
- // sticky sessions stay alive on the server indefinitely (until
58
- // explicitly killed by another path or server restart). Non-
59
- // sticky sessions get the same 5s grace path used by
60
- // handleTabDisconnect, so a transient close-then-reopen round-
61
- // trip (e.g. closing and reloading a devtools session) doesn't
62
- // yank the SSH connection out from under the user.
63
- clearCloseTimer(data.sessionId);
64
- if (tab.sticky) {
65
- console.log('[TAB] Sticky session remains open on server (no viewers):', data.sessionId);
66
- io.emit('sessions-updated');
67
- return;
68
- }
69
-
70
- console.log('[TAB] Non-sticky session, scheduling close after grace period:', data.sessionId);
71
- const gracePeriod = 5000;
72
- setCloseTimer(data.sessionId, setTimeout(() => {
73
- const currentTab = getTab(data.sessionId);
74
- if (currentTab && currentTab.activeSockets.size === 0) {
75
- console.log('[TAB] Grace period expired, closing session:', data.sessionId);
76
- if (currentTab.type === 'ssh') {
77
- sshManager.disconnect(data.sessionId);
78
- } else if (currentTab.type === 'sftp') {
79
- sftpManager.disconnect(data.sessionId);
80
- }
81
- removeTab(data.sessionId);
82
- io.emit('tab-closed', { sessionId: data.sessionId });
83
- io.emit('sessions-updated');
84
- } else {
85
- console.log('[TAB] Session has new sockets, canceling close:', data.sessionId);
86
- }
87
- }, gracePeriod));
88
- } else {
89
- // No tab record — broadcast close so stale client UIs clear it.
90
- io.emit('tab-closed', { sessionId: data.sessionId });
91
- io.emit('sessions-updated');
92
44
  }
45
+ io.emit('tab-closed', { sessionId: data.sessionId });
46
+ io.emit('sessions-updated');
93
47
  });
94
48
 
95
49
  // Tab reorder event
@@ -336,6 +336,7 @@ async function initializeServer() {
336
336
 
337
337
  // Sync flash state for tabs that need attention
338
338
  pluginManager.syncFlashState(socket);
339
+ pluginManager.registerSocket(socket);
339
340
 
340
341
  // Register all WebSocket handlers
341
342
  ws.registerAllWSHandlers(socket, io);
@@ -22,6 +22,16 @@
22
22
  * - ctx.getTerminalViewport(sessionId) - Get the visible screen only (cheap)
23
23
  * - ctx.getActiveSessions() - Get list of active session IDs
24
24
  * - ctx.getConfig() - Get current server config
25
+ * - ctx.sendInput(sessionId, data) - Write input on the user's behalf (fires onUserInput)
26
+ * - ctx.getTerminalText(sessionId, options) - Plain-text screen (+ history) and input modes
27
+ * - ctx.getTabs() - Open tabs in order, with the focused session
28
+ * - ctx.switchTab(sessionId) - Focus a tab on every connected client
29
+ * - ctx.getBookmarks() - Bookmark names/types (never credentials)
30
+ * - ctx.requestClientAction(event, data, opts) - Ask exactly ONE connected client to act
31
+ * - ctx.getDataDir() - User data directory (private plugin state)
32
+ *
33
+ * Plugins that hold resources (servers, timers) should implement destroy();
34
+ * it is called before a reload replaces the instance.
25
35
  */
26
36
 
27
37
  const path = require('path');
@@ -44,6 +54,7 @@ class PluginManager {
44
54
  this.config = null;
45
55
  this._lineBuffers = new Map();
46
56
  this.flashingSessions = new Map(); // sessionId -> options
57
+ this.pendingClaims = new Map(); // requestId -> { resolve, timer }
47
58
  }
48
59
 
49
60
  discoverPlugins() {
@@ -87,6 +98,11 @@ class PluginManager {
87
98
 
88
99
  for (const [name, pluginEntry] of this.plugins.entries()) {
89
100
  const instance = pluginEntry.instance;
101
+ if (instance && typeof instance.destroy === 'function') {
102
+ try { instance.destroy(); } catch (e) {
103
+ console.error(`[PLUGINS] Error destroying plugin "${name}":`, e.message);
104
+ }
105
+ }
90
106
  if (instance && typeof instance.onSessionDisconnect === 'function') {
91
107
  for (const sessionId of this._lineBuffers.keys()) {
92
108
  try { instance.onSessionDisconnect(sessionId); } catch (e) { /* ignore */ }
@@ -255,9 +271,117 @@ class PluginManager {
255
271
  getPluginConfig() {
256
272
  return pluginConfig.config || {};
257
273
  },
274
+
275
+ sendInput(sessionId, data) {
276
+ if (!self.sshManager || !self.sshManager.hasSession(sessionId)) return false;
277
+ self.sshManager.write(sessionId, data);
278
+ self.onUserInput(sessionId, data);
279
+ return true;
280
+ },
281
+
282
+ getTerminalText(sessionId, options = {}) {
283
+ if (self.sshManager && typeof self.sshManager.getTerminalText === 'function') {
284
+ return self.sshManager.getTerminalText(sessionId, options);
285
+ }
286
+ return null;
287
+ },
288
+
289
+ getTabs() {
290
+ return self.getTabs();
291
+ },
292
+
293
+ switchTab(sessionId) {
294
+ const tm = self.tabManager;
295
+ if (!tm || !tm.getTab(sessionId)) return false;
296
+ tm.setActiveSession(sessionId);
297
+ const tab = tm.getTab(sessionId);
298
+ if (tab.panelId) tm.setActiveTab(tab.panelId, sessionId);
299
+ if (self.io) self.io.emit('remote-switch-tab', { sessionId });
300
+ return true;
301
+ },
302
+
303
+ getBookmarks() {
304
+ const { loadConfig } = require('../utils/config');
305
+ const config = loadConfig();
306
+ const folders = new Map((config.folders || []).map(f => [f.id, f.name]));
307
+ return (config.bookmarks || []).map(b => ({
308
+ id: b.id,
309
+ name: b.name,
310
+ type: b.type || 'ssh',
311
+ folder: b.folderId ? folders.get(b.folderId) || null : null,
312
+ }));
313
+ },
314
+
315
+ requestClientAction(event, data = {}, options = {}) {
316
+ return self.requestClientAction(event, data, options);
317
+ },
318
+
319
+ getDataDir() {
320
+ const { getDataDir } = require('../utils/config');
321
+ return getDataDir();
322
+ },
258
323
  };
259
324
  }
260
325
 
326
+ getTabs() {
327
+ const tm = this.tabManager;
328
+ if (!tm) return { activeSessionId: null, tabs: [] };
329
+ const openTabs = tm.getOpenTabs();
330
+ const order = tm.getTabOrder().filter(id => openTabs.has(id));
331
+ for (const id of openTabs.keys()) if (!order.includes(id)) order.push(id);
332
+ const activeByPanel = tm.getActiveTabsByPanel();
333
+ return {
334
+ activeSessionId: tm.getActiveSession(),
335
+ tabs: order.map((sessionId, index) => {
336
+ const tab = openTabs.get(sessionId);
337
+ return {
338
+ sessionId,
339
+ position: index + 1,
340
+ name: tab.name || tab.connectionData?.name || tab.connectionData?.host || 'Tab',
341
+ type: tab.type,
342
+ host: tab.connectionData?.host || null,
343
+ username: tab.connectionData?.username || null,
344
+ panelId: tab.panelId || 'panel-0',
345
+ activeInPanel: activeByPanel.get(tab.panelId || 'panel-0') === sessionId,
346
+ connected: tab.type === 'ssh' ? !!this.sshManager?.hasSession(sessionId) : true,
347
+ viewers: tab.activeSockets ? tab.activeSockets.size : 0,
348
+ };
349
+ }),
350
+ };
351
+ }
352
+
353
+ // Broadcast an action request and let exactly one client claim it (the
354
+ // first to answer). Clients answer quickly when visible and with a delay
355
+ // when hidden, so the device the user is looking at normally wins and an
356
+ // action like "open a tab" never runs once per open browser.
357
+ requestClientAction(event, data = {}, { timeoutMs = 4000 } = {}) {
358
+ if (!this.io || this.io.sockets.sockets.size === 0) {
359
+ return Promise.resolve({ claimed: false, reason: 'no-clients' });
360
+ }
361
+ const requestId = require('crypto').randomUUID();
362
+ return new Promise(resolve => {
363
+ const timer = setTimeout(() => {
364
+ this.pendingClaims.delete(requestId);
365
+ resolve({ claimed: false, reason: 'timeout', requestId });
366
+ }, timeoutMs);
367
+ this.pendingClaims.set(requestId, { resolve, timer });
368
+ this.io.emit(event, { ...data, requestId });
369
+ });
370
+ }
371
+
372
+ registerSocket(socket) {
373
+ socket.on('remote-action-claim', (data, ack) => {
374
+ const pending = data && this.pendingClaims.get(data.requestId);
375
+ const granted = !!pending;
376
+ if (pending) {
377
+ this.pendingClaims.delete(data.requestId);
378
+ clearTimeout(pending.timer);
379
+ pending.resolve({ claimed: true, requestId: data.requestId, socketId: socket.id });
380
+ }
381
+ if (typeof ack === 'function') ack({ granted });
382
+ });
383
+ }
384
+
261
385
  _processLineBuffer(sessionId, dataStr) {
262
386
  if (!this._lineBuffers.has(sessionId)) {
263
387
  this._lineBuffers.set(sessionId, '');
@@ -0,0 +1,39 @@
1
+ /** Shared bookmark writes for REST and authenticated WebSockets. */
2
+ const { loadConfig, saveConfig } = require('../utils/config');
3
+ const { getDecryptedBookmarks, storeBookmarks } = require('../utils/bookmark-encryption');
4
+
5
+ function saveBookmark(id, data, io) {
6
+ const config = loadConfig();
7
+ const bookmarks = getDecryptedBookmarks(config);
8
+ let bookmark;
9
+ if (id) {
10
+ const index = bookmarks.findIndex(b => b.id === id);
11
+ if (index === -1) {
12
+ const error = new Error('Bookmark not found');
13
+ error.status = 404;
14
+ throw error;
15
+ }
16
+ bookmark = { ...bookmarks[index], ...data, id };
17
+ delete bookmark.encryptedConnection;
18
+ bookmarks[index] = bookmark;
19
+ } else {
20
+ bookmark = { id: Date.now().toString(), name: data.name, type: data.type || 'ssh' };
21
+ if (bookmark.type === 'url') {
22
+ bookmark.url = data.url;
23
+ } else {
24
+ bookmark.host = data.host;
25
+ bookmark.port = data.port || 22;
26
+ bookmark.username = data.username;
27
+ }
28
+ for (const field of ['password', 'privateKey', 'passphrase', 'folderId']) {
29
+ if (data[field]) bookmark[field] = data[field];
30
+ }
31
+ bookmarks.push(bookmark);
32
+ }
33
+ storeBookmarks(config, bookmarks);
34
+ if (!saveConfig(config)) throw new Error('Failed to save bookmark');
35
+ io.emit(id ? 'bookmark-updated' : 'bookmark-added', bookmark);
36
+ return bookmark;
37
+ }
38
+
39
+ module.exports = { saveBookmark };
@@ -607,6 +607,41 @@ if (this.io) {
607
607
  return this.sessions.has(sessionId);
608
608
  }
609
609
 
610
+ // Plain-text view of the active buffer for remote-control/automation
611
+ // plugins: the visible screen plus up to `history` earlier lines, with
612
+ // the input modes a client needs to send correct key sequences. Reads the
613
+ // headless terminal directly — no ANSI serialization.
614
+ getTerminalText(sessionId, { history = 0 } = {}) {
615
+ const session = this.sessions.get(sessionId);
616
+ if (!session || !session.terminal) return null;
617
+ try {
618
+ const terminal = session.terminal;
619
+ const buffer = terminal.buffer.active;
620
+ const extra = Math.max(0, Math.min(Number(history) || 0, 2000));
621
+ const start = Math.max(0, buffer.baseY - extra);
622
+ const end = buffer.baseY + terminal.rows;
623
+ const lines = [];
624
+ for (let y = start; y < end; y++) {
625
+ const line = buffer.getLine(y);
626
+ lines.push(line ? line.translateToString(true) : '');
627
+ }
628
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
629
+ const modes = terminal.modes || {};
630
+ return {
631
+ lines,
632
+ cursorLine: buffer.baseY + buffer.cursorY - start,
633
+ alternateScreen: buffer.type === 'alternate',
634
+ bracketedPaste: !!modes.bracketedPasteMode,
635
+ applicationCursorKeys: !!modes.applicationCursorKeysMode,
636
+ cols: session.cols,
637
+ rows: session.rows
638
+ };
639
+ } catch (err) {
640
+ console.error(`[SSH] Error reading terminal text:`, err.message);
641
+ return null;
642
+ }
643
+ }
644
+
610
645
  // Serialize a session's screen for a client sync, shrinking the amount
611
646
  // of scrollback until the payload fits under `maxBytes`.
612
647
  //
@@ -240,12 +240,14 @@ function getActiveTabsByPanel() {
240
240
  return activeTabsByPanel;
241
241
  }
242
242
 
243
+ // Keep the id even if the tab is not registered yet: a client that opens a
244
+ // tab can report focus before its ssh-connect completes on the server.
243
245
  function setActiveSession(sessionId) {
244
- activeSessionId = sessionId && openTabs.has(sessionId) ? sessionId : null;
246
+ activeSessionId = sessionId || null;
245
247
  }
246
248
 
247
249
  function getActiveSession() {
248
- return activeSessionId;
250
+ return activeSessionId && openTabs.has(activeSessionId) ? activeSessionId : null;
249
251
  }
250
252
 
251
253
  /**
@@ -548,8 +548,8 @@
548
548
  </form>
549
549
  </div>
550
550
  <div class="modal-footer">
551
- <button class="btn" id="cancelBookmark">Cancel</button>
552
- <button class="btn btn-primary" id="saveBookmarkBtn">
551
+ <button type="button" class="btn" id="cancelBookmark">Cancel</button>
552
+ <button type="submit" form="bookmarkForm" class="btn btn-primary" id="saveBookmarkBtn">
553
553
  <i class="fas fa-save"></i> Save
554
554
  </button>
555
555
  </div>
@@ -5800,6 +5800,27 @@ const wheelHandler = (e) => {
5800
5800
  this.socket.on('tab-flash-stop', (data) => {
5801
5801
  this.stopTabFlash(data.sessionId);
5802
5802
  });
5803
+
5804
+ // Remote-control plugin requests (e.g. voice assistants). Switching is
5805
+ // applied by every client, like a tabs-sync. Opening a bookmark must
5806
+ // happen exactly once: clients claim the request (visible ones first)
5807
+ // and only the client the server grants it to connects.
5808
+ this.socket.on('remote-switch-tab', (data) => {
5809
+ if (data && data.sessionId && this.sessions.has(data.sessionId)) {
5810
+ this.switchTab(data.sessionId);
5811
+ }
5812
+ });
5813
+
5814
+ this.socket.on('remote-open-bookmark', (data) => {
5815
+ const bookmark = data && this.bookmarks.find(b => b.id === data.bookmarkId);
5816
+ if (!bookmark || !data.requestId) return;
5817
+ const delay = document.visibilityState === 'visible' ? 0 : 1500;
5818
+ setTimeout(() => {
5819
+ this.socket.emit('remote-action-claim', { requestId: data.requestId }, (response) => {
5820
+ if (response && response.granted) this.connectFromBookmark(bookmark);
5821
+ });
5822
+ }, delay);
5823
+ });
5803
5824
  }
5804
5825
 
5805
5826
  // Event Listeners
@@ -6053,7 +6074,8 @@ const wheelHandler = (e) => {
6053
6074
  this.closeModal('bookmarkModal');
6054
6075
  });
6055
6076
 
6056
- document.getElementById('saveBookmarkBtn').addEventListener('click', () => {
6077
+ document.getElementById('bookmarkForm').addEventListener('submit', (event) => {
6078
+ event.preventDefault();
6057
6079
  this.saveBookmark();
6058
6080
  });
6059
6081
 
@@ -11090,7 +11112,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11090
11112
 
11091
11113
  // Disconnect
11092
11114
  if (session.type === 'ssh') {
11093
- this.socket.emit('ssh-disconnect', { sessionId });
11094
11115
  // Clean up ResizeObserver
11095
11116
  if (session.resizeObserver) {
11096
11117
  session.resizeObserver.disconnect();
@@ -11152,7 +11173,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
11152
11173
  }
11153
11174
  this.sessions.delete(sessionId);
11154
11175
  } else {
11155
- this.socket.emit('sftp-disconnect', { sessionId });
11156
11176
  this.sftpSessions.delete(sessionId);
11157
11177
  }
11158
11178
 
@@ -13085,6 +13105,7 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13085
13105
  }
13086
13106
 
13087
13107
  async saveBookmark() {
13108
+ if (this._savingBookmark) return;
13088
13109
  const id = document.getElementById('bookmarkId').value;
13089
13110
  const name = document.getElementById('bookmarkName').value.trim();
13090
13111
  const type = document.getElementById('bookmarkType').value;
@@ -13124,33 +13145,38 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null,
13124
13145
  if (passphrase) bookmark.passphrase = passphrase;
13125
13146
  }
13126
13147
 
13148
+ this._savingBookmark = true;
13127
13149
  try {
13128
- let response;
13129
- if (id) {
13130
- response = await fetch(`/api/bookmarks/${id}`, {
13131
- method: 'PUT',
13132
- headers: { 'Content-Type': 'application/json' },
13133
- body: JSON.stringify(bookmark)
13134
- });
13150
+ let savedBookmark;
13151
+ // Reuse the authenticated terminal connection. A fresh HTTPS fetch can
13152
+ // fail when the browser's temporary certificate exception has expired,
13153
+ // even though this socket is still healthy. REST remains available when
13154
+ // the socket is offline; never retry an ambiguous create automatically.
13155
+ if (this.socket.connected) {
13156
+ const result = await this.socket.timeout(10000).emitWithAck('bookmark-save', { id, bookmark });
13157
+ if (result.error) throw new Error(result.error);
13158
+ savedBookmark = result.bookmark;
13135
13159
  } else {
13136
- response = await fetch('/api/bookmarks', {
13137
- method: 'POST',
13160
+ const response = await fetch(id ? `/api/bookmarks/${encodeURIComponent(id)}` : '/api/bookmarks', {
13161
+ method: id ? 'PUT' : 'POST',
13138
13162
  headers: { 'Content-Type': 'application/json' },
13139
13163
  body: JSON.stringify(bookmark)
13140
13164
  });
13141
- }
13142
-
13143
- if (response.ok) {
13144
- this.showToast(id ? 'Bookmark updated' : 'Bookmark added', 'success');
13145
- this.loadBookmarks();
13146
- this.closeModal('bookmarkModal');
13147
- } else {
13148
- throw new Error('Failed to save bookmark');
13149
- }
13165
+ const result = await response.json();
13166
+ if (!response.ok) throw new Error(result.error || 'Failed to save bookmark');
13167
+ savedBookmark = result;
13168
+ }
13169
+ if (!savedBookmark || !savedBookmark.id) throw new Error('Failed to save bookmark');
13170
+ const index = this.bookmarks.findIndex(b => b.id === savedBookmark.id);
13171
+ if (index === -1) this.bookmarks.push(savedBookmark);
13172
+ else this.bookmarks[index] = savedBookmark;
13173
+ this.renderBookmarks();
13174
+ this.showToast(id ? 'Bookmark updated' : 'Bookmark added', 'success');
13175
+ this.closeModal('bookmarkModal');
13150
13176
  } catch (err) {
13151
- if (!this.handleApiFetchError(err)) {
13152
- this.showToast(err.message, 'error');
13153
- }
13177
+ this.showToast(err.message, 'error');
13178
+ } finally {
13179
+ this._savingBookmark = false;
13154
13180
  }
13155
13181
  }
13156
13182