@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
@@ -106,24 +106,62 @@ class SFTPManager {
106
106
  console.warn(`[SFTP] Could not resolve home directory: ${realpathErr?.message}`);
107
107
  }
108
108
 
109
+ // A client-chosen id can collide with a live session (two
110
+ // browsers recreating the same tab): retire the old connection
111
+ // so its late close event cannot tear down this one.
112
+ const previous = this.sessions.get(sessionId);
113
+ if (previous && previous !== session) {
114
+ console.warn(`[SFTP] Replacing existing session with the same id: ${sessionId}`);
115
+ previous.replaced = true;
116
+ try { previous.conn.end(); } catch (_) {}
117
+ }
109
118
  this.sessions.set(sessionId, session);
119
+ ownSession = session;
120
+ established = true;
121
+ // Every viewer (creator + sftp-join) hears errors/disconnects,
122
+ // not only the socket that created the session.
123
+ try { socket.join(`sftp-${sessionId}`); } catch (_) {}
110
124
  console.log(`[SFTP] SFTP session started: ${sessionId}`);
111
125
  resolve(sessionId);
112
126
  });
113
127
  });
114
128
  });
115
129
 
130
+ let established = false;
131
+ let ownSession = null;
132
+ const owns = () => {
133
+ const current = this.sessions.get(sessionId);
134
+ if (current && current.conn === conn) ownSession = current;
135
+ return !!current && current.conn === conn;
136
+ };
137
+ const notify = (event, payload) => {
138
+ if (established && socket.nsp) socket.nsp.to(`sftp-${sessionId}`).emit(event, payload);
139
+ else socket.emit(event, payload);
140
+ };
141
+
116
142
  conn.on('error', (err) => {
117
143
  console.error(`[SFTP] Connection error: ${err.message}`);
118
- socket.emit('sftp-error', { sessionId, message: err.message });
119
- this.sessions.delete(sessionId);
120
- removeTab(sessionId);
144
+ if (ownSession && ownSession.replaced) return reject(err);
145
+ notify('sftp-error', { sessionId, message: err.message });
146
+ if (owns()) {
147
+ this.sessions.delete(sessionId);
148
+ removeTab(sessionId);
149
+ } else if (!this.sessions.has(sessionId)) {
150
+ removeTab(sessionId);
151
+ }
121
152
  reject(err);
122
153
  });
123
154
 
124
155
  conn.on('close', () => {
125
156
  console.log(`[SFTP] Connection closed: ${sessionId}`);
126
- socket.emit('sftp-disconnected', { sessionId });
157
+ if (!owns()) {
158
+ // Replaced by a newer connection with the same id, or never
159
+ // established: leave the live session and its tab alone.
160
+ if (!established && !this.sessions.has(sessionId)) removeTab(sessionId);
161
+ reject(new Error('Connection closed'));
162
+ return;
163
+ }
164
+ notify('sftp-disconnected', { sessionId });
127
165
  this.sessions.delete(sessionId);
128
166
  removeTab(sessionId);
129
167
  });
@@ -233,6 +271,19 @@ try {
233
271
  return session.sftp.createReadStream(path);
234
272
  }
235
273
 
274
+ // An upload whose browser vanished (tab closed, network lost) never sends
275
+ // end/cancel: drop it after this long without a chunk, closing the
276
+ // remote file handle it holds.
277
+ _armUploadIdle(upload) {
278
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
279
+ upload.idleTimer = setTimeout(() => {
280
+ if (!this.activeUploads.has(upload.id)) return;
281
+ console.warn(`[SFTP] Upload ${upload.id} (${upload.path}) idle for 2 minutes, aborting`);
282
+ this.uploadCancel(upload.id);
283
+ }, 2 * 60 * 1000);
284
+ if (upload.idleTimer.unref) upload.idleTimer.unref();
285
+ }
286
+
236
287
  uploadStart(sessionId, path, fileName, fileSize) {
237
288
  const session = this.sessions.get(sessionId);
238
289
  if (!session) {
@@ -244,6 +295,7 @@ try {
244
295
 
245
296
  const upload = {
246
297
  id: uploadId,
298
+ sessionId,
247
299
  stream,
248
300
  bytesWritten: 0,
249
301
  totalBytes: fileSize,
@@ -261,10 +313,12 @@ try {
261
313
  upload.rejectEnd = null;
262
314
  upload.resolveEnd = null;
263
315
  }
316
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
264
317
  this.activeUploads.delete(uploadId);
265
318
  });
266
319
 
267
320
  stream.on('close', () => {
321
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
268
322
  if (upload.resolveEnd) {
269
323
  upload.resolveEnd({ path: upload.path, fileName: upload.fileName });
270
324
  upload.resolveEnd = null;
@@ -274,6 +328,7 @@ try {
274
328
  });
275
329
 
276
330
  this.activeUploads.set(uploadId, upload);
331
+ this._armUploadIdle(upload);
277
332
  return uploadId;
278
333
  }
279
334
 
@@ -289,9 +344,18 @@ try {
289
344
  return;
290
345
  }
291
346
 
347
+ if (typeof chunkBase64 !== 'string') {
348
+ reject(new Error('Invalid chunk'));
349
+ return;
350
+ }
351
+ this._armUploadIdle(upload);
292
352
  const chunkData = Buffer.from(chunkBase64, 'base64');
293
353
 
294
- upload.stream.write(chunkData, () => {
354
+ upload.stream.write(chunkData, (err) => {
355
+ if (err) {
356
+ reject(err);
357
+ return;
358
+ }
295
359
  upload.bytesWritten += chunkData.length;
296
360
  resolve({
297
361
  bytesWritten: upload.bytesWritten,
@@ -323,7 +387,13 @@ try {
323
387
  uploadCancel(uploadId) {
324
388
  const upload = this.activeUploads.get(uploadId);
325
389
  if (upload) {
326
- upload.stream.destroy();
390
+ if (upload.idleTimer) clearTimeout(upload.idleTimer);
391
+ try { upload.stream.destroy(); } catch (_) {}
392
+ if (upload.rejectEnd) {
393
+ upload.rejectEnd(new Error('Upload cancelled'));
394
+ upload.rejectEnd = null;
395
+ upload.resolveEnd = null;
396
+ }
327
397
  this.activeUploads.delete(uploadId);
328
398
  }
329
399
  }
@@ -436,6 +506,9 @@ try {
436
506
  disconnect(sessionId) {
437
507
  const session = this.sessions.get(sessionId);
438
508
  if (session) {
509
+ for (const upload of [...this.activeUploads.values()]) {
510
+ if (upload.sessionId === sessionId) this.uploadCancel(upload.id);
511
+ }
439
512
  if (session.conn) {
440
513
  session.conn.end();
441
514
  }
@@ -463,7 +536,7 @@ try {
463
536
  console.log(`[SFTP] Cannot join session ${sessionId}: session not found`);
464
537
  return false;
465
538
  }
466
-
539
+ try { socket.join(`sftp-${sessionId}`); } catch (_) {}
467
540
  return true;
468
541
  }
469
542
 
@@ -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,