@lethevimlet/sshift 1.9.7 → 1.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/plugins/claude-attention/index.js +11 -0
  4. package/plugins/opencode-attention/index.js +11 -0
  5. package/plugins/remote-control/index.js +13 -1
  6. package/src/server/endpoints/rest/auth.js +45 -32
  7. package/src/server/endpoints/rest/bookmarks.js +5 -1
  8. package/src/server/endpoints/rest/config.js +19 -35
  9. package/src/server/endpoints/rest/folders.js +15 -3
  10. package/src/server/endpoints/rest/speech-ai.js +35 -9
  11. package/src/server/endpoints/rest/system.js +40 -4
  12. package/src/server/endpoints/ws/index.js +6 -0
  13. package/src/server/endpoints/ws/sftp.js +70 -10
  14. package/src/server/endpoints/ws/ssh.js +13 -5
  15. package/src/server/endpoints/ws/tabs.js +4 -4
  16. package/src/server/index.js +87 -3
  17. package/src/server/plugins/plugin-manager.js +21 -1
  18. package/src/server/services/bookmarks.js +1 -1
  19. package/src/server/services/headless-open.js +91 -0
  20. package/src/server/services/sftp-manager.js +80 -7
  21. package/src/server/services/ssh-manager.js +48 -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/js/app.js +296 -193
  31. package/src/webapp/js/mobile-terminal.js +436 -79
  32. package/sshift +23 -2
package/README.md CHANGED
@@ -276,7 +276,8 @@ See [Configuration > Plugins](docs/configuration.md#plugins) for full details.
276
276
  The opt-in `remote-control` plugin exposes a **loopback-only, token-protected** HTTP API so a
277
277
  local assistant (for example a voice assistant's MCP server) can list, switch and rename tabs, open
278
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.
279
+ presses Enter; submitting is always a separate, explicit key request. It works with no sshift
280
+ page open: SSH bookmarks are connected by the server itself, and pages show those tabs when opened.
280
281
 
281
282
  ```json
282
283
  { "plugins": [{ "name": "remote-control", "enabled": true, "config": { "port": 8044 } }] }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.9.7",
3
+ "version": "1.9.9",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -484,6 +484,17 @@ class ClaudeAttentionPlugin {
484
484
  this._checkTimers.set(sessionId, timer);
485
485
  }
486
486
 
487
+ // Plugin reload/disable: stop every timer of this instance.
488
+ destroy() {
489
+ for (const t of this._checkTimers.values()) clearInterval(t);
490
+ for (const map of [this._dataTimers, this._idleTimers]) {
491
+ for (const t of map.values()) clearTimeout(t);
492
+ }
493
+ this._checkTimers.clear();
494
+ this._dataTimers.clear();
495
+ this._idleTimers.clear();
496
+ }
497
+
487
498
  onSessionDisconnect(sessionId) {
488
499
  this._resetSession(sessionId);
489
500
 
@@ -468,6 +468,17 @@ class OpenCodeAttentionPlugin {
468
468
  this._checkTimers.set(sessionId, timer);
469
469
  }
470
470
 
471
+ // Plugin reload/disable: stop every timer of this instance.
472
+ destroy() {
473
+ for (const t of this._checkTimers.values()) clearInterval(t);
474
+ for (const map of [this._dataTimers, this._idleTimers]) {
475
+ for (const t of map.values()) clearTimeout(t);
476
+ }
477
+ this._checkTimers.clear();
478
+ this._dataTimers.clear();
479
+ this._idleTimers.clear();
480
+ }
481
+
471
482
  onSessionDisconnect(sessionId) {
472
483
  this._resetSession(sessionId);
473
484
 
@@ -27,7 +27,8 @@
27
27
  * POST /v1/switch { sessionId }
28
28
  * POST /v1/rename { sessionId, name } → renames the tab on every browser
29
29
  * POST /v1/close { sessionId } → closes the tab (ends its SSH session) everywhere
30
- * POST /v1/open { bookmarkId } → opens it on ONE connected browser
30
+ * POST /v1/open { bookmarkId } → SSH: the server connects it (no browser needed) and every
31
+ * open page attaches; SFTP: opened by ONE connected browser
31
32
  * POST /v1/type { sessionId?, text }
32
33
  * POST /v1/key { sessionId?, key, repeat? }
33
34
  * sessionId defaults to the focused tab.
@@ -260,6 +261,17 @@ class RemoteControlPlugin {
260
261
  const bookmark = this.ctx.getBookmarks().find(b => b.id === bookmarkId);
261
262
  if (!bookmark) throw new HttpError(404, 'Bookmark not found');
262
263
  if (!['ssh', 'sftp'].includes(bookmark.type)) throw new HttpError(409, 'Only SSH/SFTP bookmarks can be opened');
264
+ // SSH: the server connects it itself — works with no browser open; open pages attach to the tab.
265
+ if (bookmark.type === 'ssh' && typeof this.ctx.openBookmark === 'function') {
266
+ let opened;
267
+ try {
268
+ opened = await this.ctx.openBookmark(bookmarkId);
269
+ } catch (err) {
270
+ throw new HttpError(err.status || 502, err.message);
271
+ }
272
+ this.ctx.switchTab(opened.sessionId);
273
+ return { opened: true, sessionId: opened.sessionId, name: opened.name, connected: true, headless: true };
274
+ }
263
275
  const before = new Set(this.ctx.getTabs().tabs.map(t => t.sessionId));
264
276
  const claim = await this.ctx.requestClientAction('remote-open-bookmark', { bookmarkId });
265
277
  if (!claim.claimed) {
@@ -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); }
@@ -130,9 +130,8 @@ function registerSystemEndpoints(app, io) {
130
130
  // API: Get version
131
131
  app.get('/api/version', (req, res) => {
132
132
  try {
133
- const packagePath = path.join(__dirname, '../../../../package.json');
134
- const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
135
- res.json({ version: packageData.version });
133
+ // Same string the page was rendered with (dev builds add a suffix).
134
+ res.json({ version: require('../../utils/asset-version').getAssetVersion() });
136
135
  } catch (err) {
137
136
  console.error('Error reading version:', err);
138
137
  res.status(500).json({ error: 'Failed to read version' });
@@ -265,7 +264,14 @@ function registerSystemEndpoints(app, io) {
265
264
  });
266
265
 
267
266
  // API: Trigger update
267
+ // One update at a time: a second click (or a second browser) used to
268
+ // start a parallel `npm i -g` racing the first one.
269
+ let updateInProgress = false;
268
270
  app.post('/api/update', async (req, res) => {
271
+ if (updateInProgress) {
272
+ return res.status(409).json({ error: 'An update is already in progress' });
273
+ }
274
+ updateInProgress = true;
269
275
  try {
270
276
 
271
277
  const { spawn, execSync } = require('child_process');
@@ -302,6 +308,16 @@ function registerSystemEndpoints(app, io) {
302
308
  ghReq.setTimeout(10000, () => { ghReq.destroy(); reject(new Error('GitHub request timed out')); });
303
309
  ghReq.end();
304
310
  });
311
+ if (githubVersion && /^\d+\.\d+\.\d+$/.test(githubVersion) &&
312
+ compareVersions(currentPkg.version, githubVersion) >= 0) {
313
+ // GitHub main can lag npm, or this install can be ahead of it:
314
+ // "updating" would reinstall or downgrade.
315
+ return res.status(409).json({
316
+ error: 'Already up to date',
317
+ localVersion: currentPkg.version,
318
+ remoteVersion: githubVersion
319
+ });
320
+ }
305
321
  if (githubVersion && /^\d+\.\d+\.\d+$/.test(githubVersion)) {
306
322
  // Verify the version actually exists on the npm registry before pinning.
307
323
  // GitHub may show a version before npm propagation completes, which would
@@ -313,6 +329,7 @@ function registerSystemEndpoints(app, io) {
313
329
  method: 'GET',
314
330
  headers: { 'User-Agent': 'sshift-update-checker' }
315
331
  }, (npmRes) => {
332
+ npmRes.resume(); // free the socket (body not needed)
316
333
  resolve(npmRes.statusCode === 200);
317
334
  });
318
335
  npmReq.on('error', () => resolve(false));
@@ -687,6 +704,17 @@ fi
687
704
  spawnFailed = true;
688
705
  try { fs.unlinkSync(updateMarker); } catch (e) { /* ignore */ }
689
706
  });
707
+ // The update script runs for a while; exiting at once with an error
708
+ // means it never started (e.g. systemd-run refused by polkit for a
709
+ // non-root service user). Exiting the server then would leave it
710
+ // down: exit 0 does not trigger Restart=on-failure.
711
+ updateProcess.on('exit', (code, signal) => {
712
+ if (code !== 0 || signal) {
713
+ console.error('[UPDATE] Update process exited early (code', code, 'signal', signal + ')');
714
+ spawnFailed = true;
715
+ try { fs.unlinkSync(updateMarker); } catch (e) { /* ignore */ }
716
+ }
717
+ });
690
718
 
691
719
  updateProcess.unref();
692
720
 
@@ -699,14 +727,22 @@ fi
699
727
  setTimeout(() => {
700
728
  if (spawnFailed) {
701
729
  console.error('[UPDATE] Update process failed to start. Keeping server running.');
730
+ updateInProgress = false;
702
731
  return;
703
732
  }
704
733
  console.log('[UPDATE] Exiting for update...');
705
734
  process.exit(0);
706
735
  }, exitDelay);
707
736
  } catch (err) {
737
+ updateInProgress = false;
708
738
  console.error('Error triggering update:', err);
709
- res.status(500).json({ error: 'Failed to trigger update' });
739
+ // The success reply may already be out (it is sent before the
740
+ // background script starts); never answer twice.
741
+ if (!res.headersSent) res.status(500).json({ error: 'Failed to trigger update' });
742
+ } finally {
743
+ // Early returns (503, 500 above) and a failed spawn (server keeps
744
+ // running) must allow another attempt.
745
+ if (!res.headersSent || res.statusCode >= 400) updateInProgress = false;
710
746
  }
711
747
  });
712
748
  }
@@ -20,6 +20,12 @@ function registerAllWSHandlers(socket, io) {
20
20
  registerTabHandlers(socket, io);
21
21
  registerLayoutHandlers(socket, io);
22
22
  registerBookmarkHandlers(socket, io);
23
+ // Liveness probe: after a laptop sleep or a network change the browser
24
+ // can hold a dead socket that still reports "connected" for over a
25
+ // minute. The client asks for an ack and reconnects when none arrives.
26
+ socket.on('sshift-ping', (ack) => {
27
+ if (typeof ack === 'function') ack({ t: Date.now() });
28
+ });
23
29
  }
24
30
 
25
31
  /**