@lethevimlet/sshift 1.9.3 → 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 +13 -0
- package/package.json +1 -1
- package/plugins/remote-control/index.js +305 -0
- package/plugins/remote-control/package.json +6 -0
- package/src/server/index.js +1 -0
- package/src/server/plugins/plugin-manager.js +124 -0
- package/src/server/services/ssh-manager.js +35 -0
- package/src/server/utils/tab-manager.js +4 -2
- package/src/webapp/js/app.js +21 -0
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
|
@@ -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;
|
package/src/server/index.js
CHANGED
|
@@ -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, '');
|
|
@@ -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
|
|
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
|
/**
|
package/src/webapp/js/app.js
CHANGED
|
@@ -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
|