@lethevimlet/sshift 1.9.8 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/plugins/claude-attention/index.js +42 -1
  4. package/plugins/claude-attention/package.json +1 -1
  5. package/plugins/opencode-attention/index.js +42 -1
  6. package/plugins/opencode-attention/package.json +1 -1
  7. package/src/server/endpoints/rest/auth.js +45 -32
  8. package/src/server/endpoints/rest/bookmarks.js +5 -1
  9. package/src/server/endpoints/rest/config.js +19 -35
  10. package/src/server/endpoints/rest/folders.js +15 -3
  11. package/src/server/endpoints/rest/speech-ai.js +35 -9
  12. package/src/server/endpoints/rest/system.js +40 -4
  13. package/src/server/endpoints/ws/index.js +6 -0
  14. package/src/server/endpoints/ws/sftp.js +70 -10
  15. package/src/server/endpoints/ws/ssh.js +13 -5
  16. package/src/server/endpoints/ws/tabs.js +4 -4
  17. package/src/server/index.js +87 -3
  18. package/src/server/plugins/plugin-manager.js +14 -1
  19. package/src/server/services/bookmarks.js +1 -1
  20. package/src/server/services/sftp-manager.js +80 -7
  21. package/src/server/services/ssh-manager.js +44 -13
  22. package/src/server/utils/asset-version.js +26 -0
  23. package/src/server/utils/auth-tokens.js +254 -0
  24. package/src/server/utils/bookmark-encryption.js +5 -0
  25. package/src/server/utils/certs.js +3 -0
  26. package/src/server/utils/config.js +49 -6
  27. package/src/server/utils/key-converter.js +30 -5
  28. package/src/server/utils/safe-handlers.js +80 -0
  29. package/src/server/utils/tab-manager.js +41 -1
  30. package/src/webapp/index.html +28 -0
  31. package/src/webapp/js/app.js +356 -195
  32. package/src/webapp/js/mobile-terminal.js +436 -79
  33. package/sshift +23 -2
package/README.md CHANGED
@@ -233,11 +233,13 @@ SSHIFT includes built-in plugins that detect when AI coding tools are waiting fo
233
233
 
234
234
  ### OpenCode Attention
235
235
 
236
- Detects when [OpenCode](https://opencode.ai) is waiting for input by tracking its spinner characters (⬝ ■ ▣) and prompt patterns. When the spinner stops or a prompt appears, the tab flashes.
236
+ Detects when [OpenCode](https://opencode.ai) finishes working (its spinner and "esc interrupt" hint disappear) and flashes the tab.
237
237
 
238
238
  ### Claude Attention
239
239
 
240
- Detects when [Claude Code](https://claude.ai) is waiting for input by tracking its spinner characters (⠋⠙⠹ braille patterns, ·✢✳✶✻✽) and prompt patterns like "❯", "Do you want", "Allow", and "Esc to cancel".
240
+ Detects when [Claude Code](https://claude.ai) finishes working or shows a permission dialog ("esc to interrupt" and the spinner disappear) and flashes the tab.
241
+
242
+ A flash stops as soon as you look at the tab and does not come back until you send the next prompt in that session. Turn each one on or off in **Settings → Sessions** (or **Settings → Plugins**).
241
243
 
242
244
  ### Enabling Plugins
243
245
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.9.8",
3
+ "version": "2.0.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -209,6 +209,12 @@ class ClaudeAttentionPlugin {
209
209
  agentBytes: 0, // agent-driven bytes in the rolling window
210
210
  agentWindowStart: 0,
211
211
  cooldownUntil: 0,
212
+ // Flashing is allowed only after a prompt. Seeing a flash disarms
213
+ // it; the next real keystroke in the session re-arms it. Without
214
+ // this, a TUI repaint (resize, tab switch, status refresh) looked
215
+ // like a new working episode and the tab flashed again although
216
+ // nothing was asked.
217
+ armed: true,
212
218
  });
213
219
  }
214
220
  return this._sessionState.get(sessionId);
@@ -266,6 +272,11 @@ class ClaudeAttentionPlugin {
266
272
  _startFlash(sessionId, { force = false } = {}) {
267
273
  const s = this._getSessionState(sessionId);
268
274
  const now = Date.now();
275
+ // Already seen since the last prompt: nothing new to announce.
276
+ if (!s.armed) {
277
+ s.pendingAttention = false;
278
+ return;
279
+ }
269
280
  // Suppressed for now — pendingAttention keeps it queued for a retry
270
281
  // instead of dropping the event on the floor.
271
282
  if (now < s.cooldownUntil) return;
@@ -447,8 +458,22 @@ class ClaudeAttentionPlugin {
447
458
  this._scheduleEvaluate(sessionId);
448
459
  }
449
460
 
450
- onUserInput(sessionId /*, data */) {
461
+ // True for input the user actually typed. Terminal-generated reports
462
+ // (focus in/out when the tab gains or loses focus, mouse wheel/click
463
+ // reports) are not a prompt and must not re-arm the flash.
464
+ _isTypedInput(data) {
465
+ if (typeof data !== 'string') return !!data;
466
+ const rest = data
467
+ .replace(/\x1b\[[IO]/g, '')
468
+ .replace(/\x1b\[<\d+;\d+;\d+[Mm]/g, '')
469
+ .replace(/\x1b\[M[\s\S]{3}/g, '');
470
+ return rest.length > 0;
471
+ }
472
+
473
+ onUserInput(sessionId, data) {
451
474
  const s = this._getSessionState(sessionId);
475
+ if (data !== undefined && !this._isTypedInput(data)) return;
476
+ s.armed = true;
452
477
  s.lastUserInputAt = Date.now();
453
478
  // The user is here — stop flashing and hold off for a while. The
454
479
  // current episode is dropped as well: if the agent really is working,
@@ -461,7 +486,12 @@ class ClaudeAttentionPlugin {
461
486
  }
462
487
 
463
488
  // A client reported the user is looking at this tab.
489
+ // Once the result has been seen, stay quiet until the next prompt. A tab
490
+ // viewed while the agent is still working stays armed so the finish of
491
+ // that run is still announced.
464
492
  onSessionFocus(sessionId) {
493
+ const s = this._getSessionState(sessionId);
494
+ if (!s.workEpisode) s.armed = false;
465
495
  this._stopFlash(sessionId, { cooldown: true });
466
496
  }
467
497
 
@@ -484,6 +514,17 @@ class ClaudeAttentionPlugin {
484
514
  this._checkTimers.set(sessionId, timer);
485
515
  }
486
516
 
517
+ // Plugin reload/disable: stop every timer of this instance.
518
+ destroy() {
519
+ for (const t of this._checkTimers.values()) clearInterval(t);
520
+ for (const map of [this._dataTimers, this._idleTimers]) {
521
+ for (const t of map.values()) clearTimeout(t);
522
+ }
523
+ this._checkTimers.clear();
524
+ this._dataTimers.clear();
525
+ this._idleTimers.clear();
526
+ }
527
+
487
528
  onSessionDisconnect(sessionId) {
488
529
  this._resetSession(sessionId);
489
530
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-attention",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Flashes SSH tabs when Claude Code finishes working and is waiting for you (state-transition detection, no brittle prompt patterns)",
5
5
  "type": "sshift-plugin"
6
6
  }
@@ -193,6 +193,12 @@ class OpenCodeAttentionPlugin {
193
193
  agentBytes: 0, // agent-driven bytes in the rolling window
194
194
  agentWindowStart: 0,
195
195
  cooldownUntil: 0,
196
+ // Flashing is allowed only after a prompt. Seeing a flash disarms
197
+ // it; the next real keystroke in the session re-arms it. Without
198
+ // this, a TUI repaint (resize, tab switch, status refresh) looked
199
+ // like a new working episode and the tab flashed again although
200
+ // nothing was asked.
201
+ armed: true,
196
202
  });
197
203
  }
198
204
  return this._sessionState.get(sessionId);
@@ -250,6 +256,11 @@ class OpenCodeAttentionPlugin {
250
256
  _startFlash(sessionId, { force = false } = {}) {
251
257
  const s = this._getSessionState(sessionId);
252
258
  const now = Date.now();
259
+ // Already seen since the last prompt: nothing new to announce.
260
+ if (!s.armed) {
261
+ s.pendingAttention = false;
262
+ return;
263
+ }
253
264
  // Suppressed for now — pendingAttention keeps it queued for a retry
254
265
  // instead of dropping the event on the floor.
255
266
  if (now < s.cooldownUntil) return;
@@ -431,8 +442,22 @@ class OpenCodeAttentionPlugin {
431
442
  this._scheduleEvaluate(sessionId);
432
443
  }
433
444
 
434
- onUserInput(sessionId /*, data */) {
445
+ // True for input the user actually typed. Terminal-generated reports
446
+ // (focus in/out when the tab gains or loses focus, mouse wheel/click
447
+ // reports) are not a prompt and must not re-arm the flash.
448
+ _isTypedInput(data) {
449
+ if (typeof data !== 'string') return !!data;
450
+ const rest = data
451
+ .replace(/\x1b\[[IO]/g, '')
452
+ .replace(/\x1b\[<\d+;\d+;\d+[Mm]/g, '')
453
+ .replace(/\x1b\[M[\s\S]{3}/g, '');
454
+ return rest.length > 0;
455
+ }
456
+
457
+ onUserInput(sessionId, data) {
435
458
  const s = this._getSessionState(sessionId);
459
+ if (data !== undefined && !this._isTypedInput(data)) return;
460
+ s.armed = true;
436
461
  s.lastUserInputAt = Date.now();
437
462
  // The user is here — stop flashing and hold off for a while. The
438
463
  // current episode is dropped as well: if the agent really is working,
@@ -445,7 +470,12 @@ class OpenCodeAttentionPlugin {
445
470
  }
446
471
 
447
472
  // A client reported the user is looking at this tab.
473
+ // Once the result has been seen, stay quiet until the next prompt. A tab
474
+ // viewed while the agent is still working stays armed so the finish of
475
+ // that run is still announced.
448
476
  onSessionFocus(sessionId) {
477
+ const s = this._getSessionState(sessionId);
478
+ if (!s.workEpisode) s.armed = false;
449
479
  this._stopFlash(sessionId, { cooldown: true });
450
480
  }
451
481
 
@@ -468,6 +498,17 @@ class OpenCodeAttentionPlugin {
468
498
  this._checkTimers.set(sessionId, timer);
469
499
  }
470
500
 
501
+ // Plugin reload/disable: stop every timer of this instance.
502
+ destroy() {
503
+ for (const t of this._checkTimers.values()) clearInterval(t);
504
+ for (const map of [this._dataTimers, this._idleTimers]) {
505
+ for (const t of map.values()) clearTimeout(t);
506
+ }
507
+ this._checkTimers.clear();
508
+ this._dataTimers.clear();
509
+ this._idleTimers.clear();
510
+ }
511
+
471
512
  onSessionDisconnect(sessionId) {
472
513
  this._resetSession(sessionId);
473
514
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-attention",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Flashes SSH tabs when OpenCode finishes working and is waiting for you (state-transition detection, no brittle prompt patterns)",
5
5
  "type": "sshift-plugin"
6
6
  }
@@ -8,27 +8,21 @@ const {
8
8
  const {
9
9
  clearBookmarkEncryptionKey,
10
10
  decryptBookmarksWithPassword,
11
+ getBookmarkEncryptionKey,
11
12
  prepareEncryptedBookmarks,
12
13
  setBookmarkEncryptionKey,
13
14
  unlockBookmarkEncryption
14
15
  } = require('../../utils/bookmark-encryption');
15
16
 
16
- const authTokens = new Map();
17
+ const authTokens = require('../../utils/auth-tokens');
17
18
  const loginAttempts = new Map();
18
- const TOKEN_TTL = 24 * 60 * 60 * 1000;
19
19
  const LOGIN_WINDOW_MS = 60 * 1000;
20
20
  const MAX_LOGIN_ATTEMPTS = 5;
21
21
 
22
- function generateToken() {
23
- const crypto = require('crypto');
24
- return crypto.randomBytes(32).toString('hex');
25
- }
26
-
27
- function cleanExpiredTokens() {
28
- const now = Date.now();
29
- for (const [token, expiry] of authTokens) {
30
- if (expiry < now) authTokens.delete(token);
31
- }
22
+ function currentBookmarkKey(config) {
23
+ const key = getBookmarkEncryptionKey();
24
+ if (!config.bookmarkEncryptionEnabled || !key) return null;
25
+ return { key, salt: config.bookmarkEncryptionSalt };
32
26
  }
33
27
 
34
28
  function getLoginAttemptKey(req) {
@@ -68,12 +62,14 @@ function notifyAuthState(io, passwordEnabled) {
68
62
  }
69
63
 
70
64
  function revokeAuthenticatedClients(io) {
71
- authTokens.clear();
65
+ authTokens.revokeAll();
72
66
  if (io && typeof io.disconnectSockets === 'function') {
73
67
  setTimeout(() => io.disconnectSockets(true), 50);
74
68
  }
75
69
  }
76
70
 
71
+ const isNonEmptyString = (v) => typeof v === 'string' && v.length > 0;
72
+
77
73
  function registerAuthEndpoints(app, io) {
78
74
  app.get('/api/auth/status', (req, res) => {
79
75
  const config = loadConfig();
@@ -84,11 +80,11 @@ function registerAuthEndpoints(app, io) {
84
80
  });
85
81
 
86
82
  app.post('/api/auth/login', async (req, res) => {
87
- const { password } = req.body;
83
+ const { password } = req.body || {};
88
84
  if (!isPasswordSet()) {
89
85
  return res.json({ success: true, authenticated: true });
90
86
  }
91
- if (!password) {
87
+ if (!isNonEmptyString(password)) {
92
88
  return res.status(400).json({ error: 'Password required' });
93
89
  }
94
90
  if (isLoginRateLimited(req)) {
@@ -107,20 +103,19 @@ function registerAuthEndpoints(app, io) {
107
103
  console.error('[AUTH] Failed to unlock encrypted bookmarks:', err.message);
108
104
  return res.status(500).json({ error: 'Encrypted bookmarks could not be unlocked' });
109
105
  }
110
- const token = generateToken();
111
- authTokens.set(token, Date.now() + TOKEN_TTL);
112
- cleanExpiredTokens();
106
+ const config = loadConfig();
107
+ const token = authTokens.issueToken(config.passwordHash, currentBookmarkKey(config));
113
108
  res.json({ success: true, token });
114
109
  });
115
110
 
116
111
  app.post('/api/auth/set-password', async (req, res) => {
117
- const { currentPassword, newPassword } = req.body;
112
+ const { currentPassword, newPassword } = req.body || {};
118
113
  if (isPasswordSet()) {
119
- if (!currentPassword || !await verifyPasswordAsync(currentPassword)) {
114
+ if (!isNonEmptyString(currentPassword) || !await verifyPasswordAsync(currentPassword)) {
120
115
  return res.status(401).json({ error: 'Current password is incorrect' });
121
116
  }
122
117
  }
123
- if (!newPassword || newPassword.length < 1) {
118
+ if (!isNonEmptyString(newPassword)) {
124
119
  return res.status(400).json({ error: 'Password cannot be empty' });
125
120
  }
126
121
  const config = loadConfig();
@@ -163,11 +158,11 @@ function registerAuthEndpoints(app, io) {
163
158
  });
164
159
 
165
160
  app.post('/api/auth/remove-password', async (req, res) => {
166
- const { currentPassword } = req.body;
161
+ const { currentPassword } = req.body || {};
167
162
  if (!isPasswordSet()) {
168
163
  return res.json({ success: true });
169
164
  }
170
- if (!currentPassword || !await verifyPasswordAsync(currentPassword)) {
165
+ if (!isNonEmptyString(currentPassword) || !await verifyPasswordAsync(currentPassword)) {
171
166
  return res.status(401).json({ error: 'Current password is incorrect' });
172
167
  }
173
168
  const config = loadConfig();
@@ -193,11 +188,11 @@ function registerAuthEndpoints(app, io) {
193
188
  });
194
189
 
195
190
  app.post('/api/auth/bookmark-encryption', async (req, res) => {
196
- const { currentPassword, enabled } = req.body;
191
+ const { currentPassword, enabled } = req.body || {};
197
192
  if (!isPasswordSet()) {
198
193
  return res.status(400).json({ error: 'Password protection must be enabled first' });
199
194
  }
200
- if (!currentPassword || !await verifyPasswordAsync(currentPassword)) {
195
+ if (!isNonEmptyString(currentPassword) || !await verifyPasswordAsync(currentPassword)) {
201
196
  return res.status(401).json({ error: 'Current password is incorrect' });
202
197
  }
203
198
 
@@ -226,6 +221,11 @@ function registerAuthEndpoints(app, io) {
226
221
  }
227
222
  clearBookmarkEncryptionKey();
228
223
  }
224
+ // Keep remembered browsers able to unlock bookmarks after a restart.
225
+ authTokens.rewrapBookmarkKey(
226
+ enabled ? getBookmarkEncryptionKey() : null,
227
+ enabled ? loadConfig().bookmarkEncryptionSalt : null
228
+ );
229
229
  notifyEncryptionState(io, enabled === true);
230
230
  res.json({ success: true, bookmarkEncryptionEnabled: enabled === true });
231
231
  } catch (err) {
@@ -236,19 +236,32 @@ function registerAuthEndpoints(app, io) {
236
236
 
237
237
  app.post('/api/auth/logout', (req, res) => {
238
238
  const token = req.headers.authorization?.replace('Bearer ', '');
239
- if (token) authTokens.delete(token);
239
+ if (token) {
240
+ authTokens.revokeToken(token);
241
+ // Sockets opened with this token keep their session otherwise.
242
+ if (io && io.sockets && io.sockets.sockets) {
243
+ for (const socket of io.sockets.sockets.values()) {
244
+ const t = socket.handshake && socket.handshake.auth && socket.handshake.auth.token;
245
+ if (t === token) socket.disconnect(true);
246
+ }
247
+ }
248
+ }
240
249
  res.json({ success: true });
241
250
  });
242
251
  }
243
252
 
244
253
  function isValidAuthToken(token) {
245
254
  if (!token) return false;
246
- cleanExpiredTokens();
247
- const expiry = authTokens.get(token);
248
- if (!expiry) return false;
249
- if (expiry < Date.now()) {
250
- authTokens.delete(token);
251
- return false;
255
+ const config = loadConfig();
256
+ if (!authTokens.verifyToken(token, config.passwordHash)) return false;
257
+ // After a restart the bookmark key is gone from memory; a remembered
258
+ // browser carries what is needed to restore it.
259
+ if (config.bookmarkEncryptionEnabled && !getBookmarkEncryptionKey()) {
260
+ const key = authTokens.getBookmarkKeyForToken(token, config.bookmarkEncryptionSalt);
261
+ if (key) {
262
+ setBookmarkEncryptionKey(key);
263
+ key.fill(0);
264
+ }
252
265
  }
253
266
  return true;
254
267
  }
@@ -72,8 +72,12 @@ function registerBookmarkEndpoints(app, io) {
72
72
 
73
73
  // API: Save bookmark order
74
74
  app.post('/api/bookmarks/order', (req, res) => {
75
+ const order = req.body && req.body.order;
76
+ if (!Array.isArray(order) || order.some(id => typeof id !== 'string' && typeof id !== 'number')) {
77
+ return res.status(400).json({ error: 'order must be an array of ids' });
78
+ }
75
79
  const config = loadConfig();
76
- config.bookmarkOrder = req.body.order;
80
+ config.bookmarkOrder = order;
77
81
  if (saveConfig(config)) {
78
82
  res.json({ success: true });
79
83
  } else {
@@ -30,44 +30,28 @@ function registerConfigEndpoints(app, io) {
30
30
  // API: Update config
31
31
  app.post('/api/config', (req, res) => {
32
32
  const config = loadConfig();
33
-
34
- // Update sticky setting if provided
35
- if (req.body.hasOwnProperty('sticky')) {
36
- config.sticky = req.body.sticky;
37
- }
38
-
39
- // Update takeControlDefault setting if provided
40
- if (req.body.hasOwnProperty('takeControlDefault')) {
41
- config.takeControlDefault = req.body.takeControlDefault;
42
- }
43
-
44
- // Update SSH keepalive settings if provided
45
- if (req.body.hasOwnProperty('sshKeepaliveInterval')) {
46
- config.sshKeepaliveInterval = parseInt(req.body.sshKeepaliveInterval) || 10000;
47
- }
48
-
49
- if (req.body.hasOwnProperty('sshKeepaliveCountMax')) {
50
- config.sshKeepaliveCountMax = parseInt(req.body.sshKeepaliveCountMax) || 1000;
51
- }
52
-
53
- // Update mobile keys bar setting if provided
54
- if (req.body.hasOwnProperty('mobileKeysBarEnabled')) {
55
- config.mobileKeysBarEnabled = req.body.mobileKeysBarEnabled;
33
+ const body = (req.body && typeof req.body === 'object') ? req.body : {};
34
+ const has = (k) => Object.prototype.hasOwnProperty.call(body, k);
35
+ // Booleans must be booleans: the string "false" used to be stored and
36
+ // then read as enabled.
37
+ const bool = (v) => v === true || v === 'true';
38
+ const int = (v, min, max, fallback) => {
39
+ const n = parseInt(v, 10);
40
+ return Number.isFinite(n) && n >= min && n <= max ? n : fallback;
41
+ };
42
+
43
+ for (const key of ['sticky', 'takeControlDefault', 'mobileKeysBarEnabled', 'webglRenderer', 'imageAddonEnabled']) {
44
+ if (has(key)) config[key] = bool(body[key]);
56
45
  }
57
-
58
- // Update WebGL renderer setting if provided
59
- if (req.body.hasOwnProperty('webglRenderer')) {
60
- config.webglRenderer = req.body.webglRenderer;
46
+ // 1 s .. 10 min between SSH keepalives; 1 .. 10000 unanswered ones.
47
+ if (has('sshKeepaliveInterval')) {
48
+ config.sshKeepaliveInterval = int(body.sshKeepaliveInterval, 1000, 600000, 10000);
61
49
  }
62
-
63
- // Update image addon setting if provided
64
- if (req.body.hasOwnProperty('imageAddonEnabled')) {
65
- config.imageAddonEnabled = req.body.imageAddonEnabled;
50
+ if (has('sshKeepaliveCountMax')) {
51
+ config.sshKeepaliveCountMax = int(body.sshKeepaliveCountMax, 1, 10000, 1000);
66
52
  }
67
-
68
- if (req.body.hasOwnProperty('scrollback')) {
69
- const val = parseInt(req.body.scrollback);
70
- config.scrollback = (val >= 0 && val <= 100000) ? val : 10000;
53
+ if (has('scrollback')) {
54
+ config.scrollback = int(body.scrollback, 0, 100000, 10000);
71
55
  }
72
56
 
73
57
  // Save config
@@ -20,7 +20,7 @@ function registerFolderEndpoints(app, io) {
20
20
  app.post('/api/folders', (req, res) => {
21
21
  const config = loadConfig();
22
22
  const folder = {
23
- id: Date.now().toString(),
23
+ id: require('crypto').randomUUID(),
24
24
  name: req.body.name,
25
25
  icon: req.body.icon || 'folder',
26
26
  expanded: true
@@ -90,7 +90,11 @@ function registerFolderEndpoints(app, io) {
90
90
  // API: Save folder order
91
91
  app.post('/api/folders/order', (req, res) => {
92
92
  const config = loadConfig();
93
- config.folderOrder = req.body.order;
93
+ const order = req.body && req.body.order;
94
+ if (!Array.isArray(order) || order.some(id => typeof id !== 'string' && typeof id !== 'number')) {
95
+ return res.status(400).json({ error: 'order must be an array of ids' });
96
+ }
97
+ config.folderOrder = order;
94
98
  if (saveConfig(config)) {
95
99
  res.json({ success: true });
96
100
  } else {
@@ -107,7 +111,15 @@ function registerFolderEndpoints(app, io) {
107
111
  // API: Save folder expanded states
108
112
  app.post('/api/folders/expanded', (req, res) => {
109
113
  const config = loadConfig();
110
- config.folderExpandedStates = req.body.states;
114
+ const states = req.body && req.body.states;
115
+ if (!states || typeof states !== 'object' || Array.isArray(states)) {
116
+ return res.status(400).json({ error: 'states must be an object' });
117
+ }
118
+ config.folderExpandedStates = Object.fromEntries(
119
+ Object.entries(states)
120
+ .filter(([k]) => k !== '__proto__' && k !== 'constructor' && k !== 'prototype')
121
+ .map(([k, v]) => [k, v === true])
122
+ );
111
123
  if (saveConfig(config)) {
112
124
  // Broadcast to all clients
113
125
  io.emit('folder-expanded-states', { states: req.body.states });
@@ -168,6 +168,7 @@ function registerSpeechAiEndpoints(app, io) {
168
168
  app.post('/api/speech-ai/stt', (req, res) => {
169
169
  handleSttProxy(req, res).catch(err => {
170
170
  console.error('[SPEECH-AI] STT proxy error:', err);
171
+ if (res.headersSent) return;
171
172
  res.status(502).json({ error: 'Speech-to-text proxy failed', detail: String(err.message || err) });
172
173
  });
173
174
  });
@@ -178,6 +179,7 @@ function registerSpeechAiEndpoints(app, io) {
178
179
  app.post('/api/speech-ai/wand', (req, res) => {
179
180
  handleWandProxy(req, res).catch(err => {
180
181
  console.error('[SPEECH-AI] Wand proxy error:', err);
182
+ if (res.headersSent) return;
181
183
  res.status(502).json({ error: 'LLM wand proxy failed', detail: String(err.message || err) });
182
184
  });
183
185
  });
@@ -189,6 +191,8 @@ function sanitizeProfileName(raw) {
189
191
  if (typeof raw !== 'string') return null;
190
192
  const name = raw.trim();
191
193
  if (!name || name.length > 64) return null;
194
+ // Names are object keys in config.json.
195
+ if (name === '__proto__' || name === 'constructor' || name === 'prototype') return null;
192
196
  return name;
193
197
  }
194
198
 
@@ -227,20 +231,38 @@ async function handleSttProxy(req, res) {
227
231
  if (!cfg.sttEndpoint) return res.status(400).json({ error: 'STT endpoint not configured' });
228
232
  if (!cfg.sttAuthKey) return res.status(400).json({ error: 'STT auth key not configured' });
229
233
 
230
- // Collect raw body bytes.
234
+ // Collect raw body bytes (bounded). A body express.json already
235
+ // consumed (JSON content type) never emits 'end' again: reject it
236
+ // instead of hanging the request forever.
237
+ if (req.readableEnded || req._body) {
238
+ return res.status(400).json({ error: 'Send the audio as the raw request body' });
239
+ }
240
+ const MAX_AUDIO_BYTES = 25 * 1024 * 1024;
231
241
  const chunks = [];
232
- await new Promise((resolve, reject) => {
233
- req.on('data', c => chunks.push(c));
234
- req.on('end', resolve);
242
+ let total = 0;
243
+ const tooLarge = await new Promise((resolve, reject) => {
244
+ req.on('data', (c) => {
245
+ total += c.length;
246
+ if (total > MAX_AUDIO_BYTES) {
247
+ req.removeAllListeners('data');
248
+ req.resume();
249
+ return resolve(true);
250
+ }
251
+ chunks.push(c);
252
+ });
253
+ req.on('end', () => resolve(false));
235
254
  req.on('error', reject);
236
255
  });
256
+ if (tooLarge) return res.status(413).json({ error: 'Recording too large' });
237
257
  const audioBuffer = Buffer.concat(chunks);
238
258
  if (!audioBuffer.length) return res.status(400).json({ error: 'No audio received' });
239
259
 
240
260
  // Build multipart/form-data manually — we deliberately avoid adding
241
261
  // multer/formidable as dependencies just for one endpoint.
242
262
  const boundary = 'sshift-' + Math.random().toString(16).slice(2) + '-' + Date.now().toString(16);
243
- const filename = req.headers['x-audio-filename'] || `recording-${Date.now()}.webm`;
263
+ // Header values end up inside the multipart headers: keep them plain.
264
+ const filename = String(req.headers['x-audio-filename'] || `recording-${Date.now()}.webm`)
265
+ .replace(/[^\w.\-]/g, '_').slice(0, 100);
244
266
  const mime = (req.headers['content-type'] && !req.headers['content-type'].includes('application/json'))
245
267
  ? req.headers['content-type']
246
268
  : 'audio/webm';
@@ -270,13 +292,15 @@ async function handleSttProxy(req, res) {
270
292
  'Authorization': `Bearer ${cfg.sttAuthKey}`,
271
293
  'Content-Type': `multipart/form-data; boundary=${boundary}`
272
294
  },
273
- body
295
+ body,
296
+ signal: AbortSignal.timeout(120000)
274
297
  });
275
298
 
276
299
  const text = await upstream.text();
277
300
  if (!upstream.ok) {
278
301
  console.error('[SPEECH-AI] STT upstream error', upstream.status, text);
279
- return res.status(upstream.status).json({ error: 'STT upstream error', detail: text });
302
+ return res.status(upstream.status === 401 || upstream.status === 403 ? 502 : upstream.status)
303
+ .json({ error: 'STT upstream error', upstreamStatus: upstream.status, detail: text.slice(0, 2000) });
280
304
  }
281
305
 
282
306
  // OpenAI-compatible transcription returns { text: "..." }
@@ -310,13 +334,15 @@ async function handleWandProxy(req, res) {
310
334
  ],
311
335
  temperature: 0.2,
312
336
  max_tokens: Math.min(2048, Math.max(64, Math.ceil(userText.length / 2)))
313
- })
337
+ }),
338
+ signal: AbortSignal.timeout(120000)
314
339
  });
315
340
 
316
341
  const text = await upstream.text();
317
342
  if (!upstream.ok) {
318
343
  console.error('[SPEECH-AI] LLM upstream error', upstream.status, text);
319
- return res.status(upstream.status).json({ error: 'LLM upstream error', detail: text });
344
+ return res.status(upstream.status === 401 || upstream.status === 403 ? 502 : upstream.status)
345
+ .json({ error: 'LLM upstream error', upstreamStatus: upstream.status, detail: text.slice(0, 2000) });
320
346
  }
321
347
  let parsed;
322
348
  try { parsed = JSON.parse(text); }