@lethevimlet/sshift 1.9.8 → 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.
@@ -164,7 +164,21 @@ class SSHManager {
164
164
  }
165
165
 
166
166
  session.stream = stream;
167
+ // A client-chosen id can collide (two browsers recreating the
168
+ // same expired session after a restart). Retire the previous
169
+ // connection so it cannot keep feeding or tearing down this id.
170
+ const previous = this.sessions.get(sessionId);
171
+ if (previous && previous !== session) {
172
+ console.warn(`[SSH] Replacing existing session with the same id: ${sessionId}`);
173
+ previous.replaced = true;
174
+ if (previous.batchTimer) clearTimeout(previous.batchTimer);
175
+ if (previous.exitTimer) clearTimeout(previous.exitTimer);
176
+ try { previous.stream && previous.stream.destroy(); } catch (_) {}
177
+ try { previous.conn && previous.conn.end(); } catch (_) {}
178
+ try { previous.terminal && previous.terminal.dispose(); } catch (_) {}
179
+ }
167
180
  this.sessions.set(sessionId, session);
181
+ const isCurrent = () => this.sessions.get(sessionId) === session;
168
182
 
169
183
  // Join the session room to receive broadcasts
170
184
  socket.join(`session-${sessionId}`);
@@ -185,15 +199,16 @@ class SSHManager {
185
199
  // chunk boundaries (each .toString('utf8') would replace the
186
200
  // incomplete halves with U+FFFD).
187
201
  stream.on('data', (data) => {
188
- this.bufferData(sessionId, data);
202
+ if (isCurrent()) this.bufferData(sessionId, data);
189
203
  });
190
204
 
191
205
  stream.stderr.on('data', (data) => {
192
- this.bufferData(sessionId, data);
206
+ if (isCurrent()) this.bufferData(sessionId, data);
193
207
  });
194
208
 
195
209
  stream.on('close', () => {
196
210
  console.log(`[SSH] Stream closed: ${sessionId}`);
211
+ if (!isCurrent()) return;
197
212
  if (session.exitTimer) {
198
213
  clearTimeout(session.exitTimer);
199
214
  session.exitTimer = null;
@@ -210,6 +225,7 @@ class SSHManager {
210
225
 
211
226
  stream.on('exit', (code, signal) => {
212
227
  console.log(`[SSH] Stream exit: ${sessionId}, code: ${code}, signal: ${signal}`);
228
+ if (!isCurrent()) return;
213
229
  this.broadcastToSession(sessionId, 'ssh-exit', { sessionId, code, signal });
214
230
  // Remote process exited. The ssh2 channel normally fires
215
231
  // `close` shortly after, but if it doesn't (network drop,
@@ -237,27 +253,42 @@ class SSHManager {
237
253
  });
238
254
  });
239
255
 
240
- conn.on('error', (err) => {
241
- console.error(`[SSH] Connection error: ${err.message}`);
242
- socket.emit('ssh-error', { sessionId, message: err.message });
243
- this.sessions.delete(sessionId);
256
+ // ssh2 emits conn 'error' then 'close' BEFORE the channel's own
257
+ // 'close' on a network drop / keepalive timeout. Tear down through
258
+ // disconnect() (idempotent) so the headless terminal, line buffers
259
+ // and plugin state are released too, not just the map entry; and
260
+ // only when this connection still owns the id.
261
+ const teardown = () => {
262
+ if (this.sessions.get(sessionId) === session) {
263
+ this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
264
+ this.disconnect(sessionId);
265
+ } else if (session.replaced) {
266
+ return;
267
+ } else {
268
+ try { session.terminal && session.terminal.dispose(); } catch (_) {}
269
+ // Another live connection owns this id: leave its tab alone.
270
+ if (this.sessions.has(sessionId)) return;
271
+ }
244
272
  removeTab(sessionId);
245
273
  if (this.io) {
246
274
  this.io.emit('tab-closed', { sessionId });
247
275
  this.io.emit('sessions-updated');
248
276
  }
277
+ };
278
+
279
+ conn.on('error', (err) => {
280
+ console.error(`[SSH] Connection error: ${err.message}`);
281
+ if (!session.replaced) socket.emit('ssh-error', { sessionId, message: err.message });
282
+ teardown();
249
283
  reject(err);
250
284
  });
251
285
 
252
286
  conn.on('close', () => {
253
287
  console.log(`[SSH] Connection closed: ${sessionId}`);
254
- this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
255
- this.sessions.delete(sessionId);
256
- removeTab(sessionId);
257
- if (this.io) {
258
- this.io.emit('tab-closed', { sessionId });
259
- this.io.emit('sessions-updated');
260
- }
288
+ teardown();
289
+ // A connection that closes before the shell opened never settles
290
+ // otherwise (no error event), leaving ssh-connect hanging.
291
+ reject(new Error('Connection closed'));
261
292
  });
262
293
 
263
294
  try {
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Version string baked into index.html / sw.js (cache keys, ?v= URLs) and
3
+ * reported by /api/version for the stale-page check.
4
+ *
5
+ * In development (NODE_ENV=development, the --dev port) the package version
6
+ * does not change when files are edited, so the service worker kept serving
7
+ * the old JS/CSS from its version-keyed cache. There, every server start
8
+ * gets its own suffix: restart the dev server and pages pick up the edits
9
+ * (one automatic reload via the stale-page check).
10
+ */
11
+ const path = require('path');
12
+ const fs = require('fs');
13
+
14
+ const bootStamp = Date.now().toString(36);
15
+
16
+ function getPackageVersion() {
17
+ const pkgPath = path.join(__dirname, '../../../package.json');
18
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version;
19
+ }
20
+
21
+ function getAssetVersion() {
22
+ const version = getPackageVersion();
23
+ return process.env.NODE_ENV === 'development' ? `${version}-dev.${bootStamp}` : version;
24
+ }
25
+
26
+ module.exports = { getAssetVersion, getPackageVersion };
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Persistent login tokens ("remembered devices").
3
+ *
4
+ * Until v1.9.8 tokens lived only in a process-memory Map with a fixed 24 h
5
+ * lifetime, so every server restart (update, reboot, crash) and every day
6
+ * of uptime threw all browsers back to the password prompt. Tokens now
7
+ * survive restarts and never expire on their own. A token stops working
8
+ * only when:
9
+ * - the browser logs out (Settings → Logout revokes that one token), or
10
+ * - the password changes / is removed (all tokens are revoked), including
11
+ * a password hash changed outside the app: each token is bound to a
12
+ * fingerprint of the password hash it was issued under.
13
+ *
14
+ * Storage: <dataDir>/auth-tokens.json (mode 0600). Only SHA-256 hashes of
15
+ * tokens are stored, so the file alone cannot be used to log in.
16
+ *
17
+ * Encrypted bookmarks: the bookmark key is derived from the password and
18
+ * normally exists only in memory after a password login. To keep bookmarks
19
+ * usable after a restart without asking for the password again, each token
20
+ * record carries the bookmark key wrapped (AES-256-GCM) with a key derived
21
+ * from the raw token, which is never stored. Presenting the token after a
22
+ * restart unwraps it.
23
+ */
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const crypto = require('crypto');
27
+
28
+ const MAX_TOKENS = 100;
29
+ const LAST_USED_WRITE_INTERVAL_MS = 60 * 60 * 1000;
30
+
31
+ let storePath = null;
32
+ let store = null; // { version, tokens: { [hash]: record } }
33
+ // Raw tokens seen since this process started (needed to re-wrap the
34
+ // bookmark key for them when it changes). Never persisted.
35
+ const seenRawTokens = new Map(); // hash -> raw token
36
+
37
+ function defaultStorePath() {
38
+ // Unit tests must never touch the real data directory (a revokeAll there
39
+ // would log out the browsers of a live instance on the same machine).
40
+ if (process.env.JEST_WORKER_ID && !process.env.SSHIFT_DATA_DIR) {
41
+ return path.join(require('os').tmpdir(), `sshift-test-auth-tokens-${process.pid}.json`);
42
+ }
43
+ let dataDir = null;
44
+ try {
45
+ const config = require('./config');
46
+ if (typeof config.getDataDir === 'function') dataDir = config.getDataDir();
47
+ } catch (_) {}
48
+ if (!dataDir) {
49
+ dataDir = process.env.SSHIFT_DATA_DIR
50
+ ? path.resolve(process.env.SSHIFT_DATA_DIR)
51
+ : path.join(require('os').homedir(), '.local', 'share', 'sshift');
52
+ }
53
+ return path.join(dataDir, 'auth-tokens.json');
54
+ }
55
+
56
+ function hashToken(token) {
57
+ return crypto.createHash('sha256').update(String(token)).digest('hex');
58
+ }
59
+
60
+ function passwordFingerprint(passwordHash) {
61
+ if (!passwordHash) return null;
62
+ return crypto.createHash('sha256').update(String(passwordHash)).digest('hex');
63
+ }
64
+
65
+ function wrapKeyFor(token, salt) {
66
+ return crypto.hkdfSync('sha256', Buffer.from(String(token)), Buffer.from(String(salt || '')), 'sshift-bookmark-key-wrap', 32);
67
+ }
68
+
69
+ function wrapBookmarkKey(token, key, salt) {
70
+ const iv = crypto.randomBytes(12);
71
+ const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(wrapKeyFor(token, salt)), iv);
72
+ const ciphertext = Buffer.concat([cipher.update(key), cipher.final()]);
73
+ return {
74
+ salt,
75
+ iv: iv.toString('base64'),
76
+ tag: cipher.getAuthTag().toString('base64'),
77
+ ciphertext: ciphertext.toString('base64')
78
+ };
79
+ }
80
+
81
+ function unwrapBookmarkKey(token, wrapped) {
82
+ const decipher = crypto.createDecipheriv(
83
+ 'aes-256-gcm',
84
+ Buffer.from(wrapKeyFor(token, wrapped.salt)),
85
+ Buffer.from(wrapped.iv, 'base64')
86
+ );
87
+ decipher.setAuthTag(Buffer.from(wrapped.tag, 'base64'));
88
+ return Buffer.concat([
89
+ decipher.update(Buffer.from(wrapped.ciphertext, 'base64')),
90
+ decipher.final()
91
+ ]);
92
+ }
93
+
94
+ function load() {
95
+ if (store) return store;
96
+ if (!storePath) storePath = defaultStorePath();
97
+ store = { version: 1, tokens: {} };
98
+ try {
99
+ if (fs.existsSync(storePath)) {
100
+ const data = JSON.parse(fs.readFileSync(storePath, 'utf8'));
101
+ if (data && typeof data.tokens === 'object' && data.tokens) {
102
+ store.tokens = data.tokens;
103
+ }
104
+ }
105
+ } catch (err) {
106
+ console.error('[AUTH] Could not read token store, starting empty:', err.message);
107
+ }
108
+ return store;
109
+ }
110
+
111
+ function save() {
112
+ if (!store) return;
113
+ if (!storePath) storePath = defaultStorePath();
114
+ let tempPath = null;
115
+ try {
116
+ fs.mkdirSync(path.dirname(storePath), { recursive: true });
117
+ tempPath = `${storePath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
118
+ const fd = fs.openSync(tempPath, 'w', 0o600);
119
+ try {
120
+ fs.writeFileSync(fd, JSON.stringify(store, null, 2));
121
+ fs.fsyncSync(fd);
122
+ } finally {
123
+ fs.closeSync(fd);
124
+ }
125
+ fs.renameSync(tempPath, storePath);
126
+ } catch (err) {
127
+ console.error('[AUTH] Could not save token store:', err.message);
128
+ if (tempPath) {
129
+ try { fs.unlinkSync(tempPath); } catch (_) {}
130
+ }
131
+ }
132
+ }
133
+
134
+ function evictOldest() {
135
+ const entries = Object.entries(store.tokens);
136
+ if (entries.length <= MAX_TOKENS) return;
137
+ entries.sort((a, b) => (a[1].lastUsed || 0) - (b[1].lastUsed || 0));
138
+ for (const [hash] of entries.slice(0, entries.length - MAX_TOKENS)) {
139
+ delete store.tokens[hash];
140
+ seenRawTokens.delete(hash);
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Issue a new token bound to the current password hash.
146
+ * @param {string} passwordHash current config.passwordHash
147
+ * @param {{key: Buffer, salt: string}|null} bookmarkKey key to wrap, if bookmark encryption is on
148
+ */
149
+ function issueToken(passwordHash, bookmarkKey) {
150
+ load();
151
+ const token = crypto.randomBytes(32).toString('hex');
152
+ const hash = hashToken(token);
153
+ const now = Date.now();
154
+ const record = { created: now, lastUsed: now, pw: passwordFingerprint(passwordHash) };
155
+ if (bookmarkKey && bookmarkKey.key) {
156
+ record.bookmarkKey = wrapBookmarkKey(token, bookmarkKey.key, bookmarkKey.salt);
157
+ }
158
+ store.tokens[hash] = record;
159
+ seenRawTokens.set(hash, token);
160
+ evictOldest();
161
+ save();
162
+ return token;
163
+ }
164
+
165
+ /**
166
+ * Check a token. Returns the record (truthy) when valid, else null.
167
+ * Invalidates the token when it was issued under a different password.
168
+ */
169
+ function verifyToken(token, passwordHash) {
170
+ if (!token || typeof token !== 'string') return null;
171
+ load();
172
+ const hash = hashToken(token);
173
+ const record = store.tokens[hash];
174
+ if (!record) return null;
175
+ if (record.pw !== passwordFingerprint(passwordHash)) {
176
+ delete store.tokens[hash];
177
+ seenRawTokens.delete(hash);
178
+ save();
179
+ return null;
180
+ }
181
+ seenRawTokens.set(hash, token);
182
+ const now = Date.now();
183
+ if (now - (record.lastUsed || 0) > LAST_USED_WRITE_INTERVAL_MS) {
184
+ record.lastUsed = now;
185
+ save();
186
+ }
187
+ return record;
188
+ }
189
+
190
+ /**
191
+ * Bookmark key wrapped for this token, or null (none stored, stale salt,
192
+ * or unwrap failure).
193
+ */
194
+ function getBookmarkKeyForToken(token, salt) {
195
+ load();
196
+ const record = store.tokens[hashToken(token)];
197
+ if (!record || !record.bookmarkKey) return null;
198
+ if (salt && record.bookmarkKey.salt !== salt) return null;
199
+ try {
200
+ return unwrapBookmarkKey(token, record.bookmarkKey);
201
+ } catch (_) {
202
+ return null;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * The bookmark key changed (encryption toggled with the password): wrap the
208
+ * new key for every token whose raw value this process has seen, and drop
209
+ * the stale wrapped key from the others.
210
+ */
211
+ function rewrapBookmarkKey(key, salt) {
212
+ load();
213
+ for (const [hash, record] of Object.entries(store.tokens)) {
214
+ const raw = seenRawTokens.get(hash);
215
+ if (key && raw) record.bookmarkKey = wrapBookmarkKey(raw, key, salt);
216
+ else delete record.bookmarkKey;
217
+ }
218
+ save();
219
+ }
220
+
221
+ function revokeToken(token) {
222
+ if (!token) return;
223
+ load();
224
+ const hash = hashToken(token);
225
+ seenRawTokens.delete(hash);
226
+ if (store.tokens[hash]) {
227
+ delete store.tokens[hash];
228
+ save();
229
+ }
230
+ }
231
+
232
+ function revokeAll() {
233
+ load();
234
+ store.tokens = {};
235
+ seenRawTokens.clear();
236
+ save();
237
+ }
238
+
239
+ // Tests only.
240
+ function _setStorePath(p) {
241
+ storePath = p;
242
+ store = null;
243
+ seenRawTokens.clear();
244
+ }
245
+
246
+ module.exports = {
247
+ issueToken,
248
+ verifyToken,
249
+ getBookmarkKeyForToken,
250
+ rewrapBookmarkKey,
251
+ revokeToken,
252
+ revokeAll,
253
+ _setStorePath
254
+ };
@@ -135,6 +135,10 @@ function setBookmarkEncryptionKey(key) {
135
135
  bookmarkEncryptionKey = key ? Buffer.from(key) : null;
136
136
  }
137
137
 
138
+ function getBookmarkEncryptionKey() {
139
+ return bookmarkEncryptionKey;
140
+ }
141
+
138
142
  function clearBookmarkEncryptionKey() {
139
143
  if (bookmarkEncryptionKey) bookmarkEncryptionKey.fill(0);
140
144
  bookmarkEncryptionKey = null;
@@ -151,5 +155,6 @@ module.exports = {
151
155
  getDecryptedBookmarks,
152
156
  storeBookmarks,
153
157
  setBookmarkEncryptionKey,
158
+ getBookmarkEncryptionKey,
154
159
  clearBookmarkEncryptionKey
155
160
  };
@@ -230,6 +230,9 @@ function writePair(certPath, keyPath, pair) {
230
230
  // Certificates are public (they are served by /api/cert); keys are not.
231
231
  fs.writeFileSync(certPath, pair.cert, { mode: 0o644 });
232
232
  fs.writeFileSync(keyPath, pair.key, { mode: 0o600 });
233
+ // mode only applies when the file is created; an older key file may be
234
+ // group/world readable.
235
+ try { fs.chmodSync(keyPath, 0o600); } catch (_) {}
233
236
  }
234
237
 
235
238
  /**
@@ -125,17 +125,50 @@ function getConfigPath() {
125
125
  * Load configuration from file
126
126
  * @returns {Object} Configuration object
127
127
  */
128
+ // Last config that parsed, and whether the file on disk is currently
129
+ // unreadable. A config that exists but cannot be parsed (hand-edit typo,
130
+ // read racing a non-atomic external write) used to come back as the
131
+ // defaults: passwordHash null (authentication silently OFF) and empty
132
+ // bookmarks, which the next routine save then wrote over the real file.
133
+ let lastGoodConfig = null;
134
+ let configUnreadable = false;
135
+
128
136
  function loadConfig() {
137
+ let configPath;
129
138
  try {
130
- const configPath = getConfigPath();
131
- if (fs.existsSync(configPath)) {
132
- const data = fs.readFileSync(configPath, 'utf8');
133
- return JSON.parse(data);
139
+ configPath = getConfigPath();
140
+ if (!fs.existsSync(configPath)) {
141
+ configUnreadable = false;
142
+ return { ...defaultConfig };
134
143
  }
135
144
  } catch (err) {
136
- console.error('Error loading config:', err);
145
+ console.error('Error locating config:', err);
146
+ return { ...defaultConfig };
147
+ }
148
+ let lastErr = null;
149
+ // Two attempts: a concurrent external writer may have been mid-write.
150
+ for (let attempt = 0; attempt < 2; attempt++) {
151
+ try {
152
+ const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8'));
153
+ configUnreadable = false;
154
+ lastGoodConfig = parsed;
155
+ return JSON.parse(JSON.stringify(parsed));
156
+ } catch (err) {
157
+ lastErr = err;
158
+ }
137
159
  }
138
- return { ...defaultConfig };
160
+ if (!configUnreadable) {
161
+ console.error('[CONFIG] Cannot parse', configPath, '- keeping the last good config and refusing to save until it is fixed:', lastErr && lastErr.message);
162
+ }
163
+ configUnreadable = true;
164
+ if (lastGoodConfig) return JSON.parse(JSON.stringify(lastGoodConfig));
165
+ // Never parsed since start: fail closed (a password is required and
166
+ // nothing matches it) instead of opening the server.
167
+ return { ...defaultConfig, passwordHash: 'unreadable$config$' };
168
+ }
169
+
170
+ function isConfigUnreadable() {
171
+ return configUnreadable;
139
172
  }
140
173
 
141
174
  /**
@@ -145,6 +178,14 @@ function loadConfig() {
145
178
  */
146
179
  function saveConfig(config) {
147
180
  let tempPath = null;
181
+ if (configUnreadable) {
182
+ // Re-check: the file may have been fixed since.
183
+ loadConfig();
184
+ if (configUnreadable) {
185
+ console.error('[CONFIG] Not saving: the config file on disk is unreadable (fix or remove it first)');
186
+ return false;
187
+ }
188
+ }
148
189
  try {
149
190
  const configPath = getConfigPath();
150
191
  tempPath = `${configPath}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
@@ -426,6 +467,7 @@ function verifyPassword(password) {
426
467
  }
427
468
 
428
469
  function verifyPasswordAsync(password) {
470
+ if (typeof password !== 'string') return Promise.resolve(false);
429
471
  const config = loadConfig();
430
472
  if (!config.passwordHash) return Promise.resolve(true);
431
473
  if (!config.passwordHash.startsWith('scrypt$')) {
@@ -602,6 +644,7 @@ module.exports = {
602
644
  getCertPath,
603
645
  getKeyPath,
604
646
  getDataDir,
647
+ isConfigUnreadable,
605
648
  getLegacyDataDir,
606
649
  hashPassword,
607
650
  isPasswordSet,
@@ -96,7 +96,8 @@ function convertPPKViaPuttygen(ppkContent, passphrase) {
96
96
  });
97
97
  };
98
98
 
99
- fs.writeFile(inputFile, ppkContent, (writeErr) => {
99
+ // The PPK may hold an unencrypted private key: never world-readable.
100
+ fs.writeFile(inputFile, ppkContent, { mode: 0o600 }, (writeErr) => {
100
101
  if (writeErr) {
101
102
  try { fs.unlinkSync(inputFile); } catch (e) { /* ignore */ }
102
103
  return reject(new Error('Failed to write temporary PPK file: ' + writeErr.message));
@@ -483,14 +484,38 @@ async function convertPPKToOpenSSH(ppkContent, passphrase) {
483
484
  throw new Error('Not a PPK key');
484
485
  }
485
486
 
486
- // Try built-in converter first (works for v2 encrypted/unencrypted, no puttygen dependency)
487
+ if (!passphrase && /^Encryption:\s*(?!none)\S+/m.test(ppkContent)) {
488
+ throw new Error('This PPK key is encrypted: enter its passphrase');
489
+ }
490
+
491
+ // 1) ssh2's own PPK parser (PPK v2: ssh-rsa / ssh-dss, unencrypted or
492
+ // aes256-cbc). The hand-written v2 converter below rejected every
493
+ // real v2 key ("integrity check failed": wrong private-blob layout and
494
+ // key derivation), verified against ssh2's PPK fixtures.
495
+ let ssh2Error = null;
496
+ try {
497
+ const { utils } = require('ssh2');
498
+ const parsed = utils.parseKey(ppkContent, passphrase || undefined);
499
+ const key = Array.isArray(parsed) ? parsed[0] : parsed;
500
+ if (key && !(key instanceof Error) && typeof key.getPrivatePEM === 'function') {
501
+ const pem = key.getPrivatePEM();
502
+ if (pem && pem.includes('BEGIN')) return pem;
503
+ }
504
+ if (key instanceof Error) ssh2Error = key;
505
+ } catch (e) {
506
+ ssh2Error = e;
507
+ }
508
+ // A wrong passphrase is final: don't hide it behind fallback errors.
509
+ if (ssh2Error && /passphrase|decrypt|bad mac|integrity/i.test(ssh2Error.message) && passphrase !== undefined && /Encryption: aes256-cbc/.test(ppkContent) && /PuTTY-User-Key-File-2: ssh-(rsa|dss)/.test(ppkContent)) {
510
+ throw new Error('Could not decrypt the PPK key: wrong passphrase?');
511
+ }
512
+
513
+ // 2) Built-in converter (other v2 key types); its errors are not final.
487
514
  try {
488
515
  const result = convertPPKV2ToOpenSSH(ppkContent, passphrase);
489
516
  if (result) return result;
490
517
  } catch (e) {
491
- if (!e.message.includes('not supported by the built-in converter')) {
492
- throw e;
493
- }
518
+ // fall through to puttygen
494
519
  }
495
520
 
496
521
  // Fall back to puttygen (handles v3 and encryption types the built-in converter doesn't support)
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Crash guards for event and route handlers.
3
+ *
4
+ * socket.io 4.7 runs listeners from process.nextTick and Express 4 does not
5
+ * catch rejected promises, so a single malformed payload (`ssh-join` with no
6
+ * data, a numeric password) used to throw out of the event loop and take the
7
+ * whole server, and every SSH session in it, down. These wrappers log the
8
+ * error and keep the process alive.
9
+ */
10
+
11
+ function logHandlerError(where, err) {
12
+ console.error(`[SAFE] Handler error in ${where}:`, err && err.stack ? err.stack : err);
13
+ }
14
+
15
+ /**
16
+ * Make every listener registered with socket.on() exception-safe, including
17
+ * async listeners. Must run before any handler is registered on the socket.
18
+ */
19
+ function guardSocket(socket) {
20
+ if (!socket || socket.__sshiftGuarded) return socket;
21
+ socket.__sshiftGuarded = true;
22
+ const origOn = socket.on.bind(socket);
23
+ socket.on = (event, listener) => {
24
+ if (typeof listener !== 'function') return origOn(event, listener);
25
+ const wrapped = function (...args) {
26
+ try {
27
+ const result = listener.apply(this, args);
28
+ if (result && typeof result.catch === 'function') {
29
+ return result.catch((err) => logHandlerError(`socket event "${event}"`, err));
30
+ }
31
+ return result;
32
+ } catch (err) {
33
+ logHandlerError(`socket event "${event}"`, err);
34
+ return undefined;
35
+ }
36
+ };
37
+ return origOn(event, wrapped);
38
+ };
39
+ return socket;
40
+ }
41
+
42
+ /**
43
+ * Make app.get/post/put/patch/delete route handlers forward thrown errors
44
+ * and rejected promises to Express' error handling instead of crashing.
45
+ */
46
+ function guardExpressApp(app) {
47
+ if (!app || app.__sshiftGuarded) return app;
48
+ app.__sshiftGuarded = true;
49
+ for (const method of ['get', 'post', 'put', 'patch', 'delete']) {
50
+ if (typeof app[method] !== 'function') continue;
51
+ const orig = app[method].bind(app);
52
+ app[method] = (routePath, ...handlers) => {
53
+ // app.get('setting') is the settings getter, not a route.
54
+ if (handlers.length === 0) return orig(routePath);
55
+ const wrapped = handlers.map((h) => {
56
+ if (typeof h !== 'function' || h.length >= 4) return h;
57
+ return (req, res, next) => {
58
+ try {
59
+ const result = h(req, res, next);
60
+ if (result && typeof result.catch === 'function') return result.catch(next);
61
+ return result;
62
+ } catch (err) {
63
+ return next(err);
64
+ }
65
+ };
66
+ });
67
+ return orig(routePath, ...wrapped);
68
+ };
69
+ }
70
+ return app;
71
+ }
72
+
73
+ function expressErrorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
74
+ logHandlerError(`${req.method} ${req.path}`, err);
75
+ if (res.headersSent) return;
76
+ res.status(err && err.type === 'entity.parse.failed' ? 400 : 500)
77
+ .json({ error: err && err.type === 'entity.parse.failed' ? 'Invalid JSON' : 'Internal server error' });
78
+ }
79
+
80
+ module.exports = { guardSocket, guardExpressApp, expressErrorHandler, logHandlerError };