ccdeck 3.82.1 → 3.82.3

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 (30) hide show
  1. package/README.md +9 -1
  2. package/dist/web/assets/{BrowserWatchModal-5txXQWqr.js → BrowserWatchModal-BmRTh_xT.js} +1 -1
  3. package/dist/web/assets/{IntegrationModal-2caOGb1q.js → IntegrationModal-C_f526aV.js} +1 -1
  4. package/dist/web/assets/{RadioPanel-DuvwS-TT.js → RadioPanel-D2rkf9cg.js} +1 -1
  5. package/dist/web/assets/{TrafficRadar-BD_S2b0e.js → TrafficRadar-BOgVBLIN.js} +1 -1
  6. package/dist/web/assets/{UsageHistoryModal-CXDbKfIt.js → UsageHistoryModal-BJPTFwM9.js} +1 -1
  7. package/dist/web/assets/{app-CoVinTuS.js → app-DZdZoqJ6.js} +63 -63
  8. package/dist/web/assets/{index-DpfbtL3r.js → index-B4c5MZCc.js} +1 -1
  9. package/dist/web/index.html +2 -2
  10. package/package.json +1 -1
  11. package/release-notes.json +30 -0
  12. package/src/server/account-projects.mjs +42 -14
  13. package/src/server/boot-lock.mjs +6 -1
  14. package/src/server/ccusage-runner.mjs +4 -1
  15. package/src/server/codex-engine-rpc.mjs +1 -0
  16. package/src/server/exec-children.mjs +21 -6
  17. package/src/server/exec.mjs +46 -3
  18. package/src/server/http-io.mjs +3 -19
  19. package/src/server/integrations/store.mjs +12 -5
  20. package/src/server/lan-routes.mjs +13 -3
  21. package/src/server/lifecycle.mjs +13 -5
  22. package/src/server/metrics-history.mjs +17 -8
  23. package/src/server/quota-closes.mjs +5 -2
  24. package/src/server/quota-history.mjs +38 -15
  25. package/src/server/session-summary.mjs +34 -10
  26. package/src/server/swap-log.mjs +9 -4
  27. package/src/server/thermal-metrics.mjs +31 -3
  28. package/src/server/tool-audit.mjs +24 -12
  29. package/src/server/tui-machine.mjs +2 -2
  30. package/src/server/tui-network.mjs +3 -1
@@ -1 +1 @@
1
- import"./app-CoVinTuS.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
1
+ import"./app-DZdZoqJ6.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
@@ -77,8 +77,8 @@
77
77
  document.documentElement.setAttribute("data-density", density === "tightest" || density === "tighter" || density === "compact" || density === "comfortable" ? density : "default");
78
78
  })();
79
79
  </script>
80
- <script type="module" crossorigin src="/assets/index-DpfbtL3r.js"></script>
81
- <link rel="modulepreload" crossorigin href="/assets/app-CoVinTuS.js">
80
+ <script type="module" crossorigin src="/assets/index-B4c5MZCc.js"></script>
81
+ <link rel="modulepreload" crossorigin href="/assets/app-DZdZoqJ6.js">
82
82
  <link rel="stylesheet" crossorigin href="/assets/app-CbXmr9rC.css">
83
83
  </head>
84
84
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ccdeck",
3
- "version": "3.82.1",
3
+ "version": "3.82.3",
4
4
  "description": "Local dashboard for Claude Code and Codex CLI sessions: which Claude Code session needs input, every tool call and Claude Code subagent live, token cost and quota, several Claude accounts. Run npx ccdeck.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,4 +1,26 @@
1
1
  {
2
+ "3.82.3": [
3
+ {
4
+ "title": "🖥️ Windows CPU performance limits",
5
+ "body": "Machine now shows CPU performance limits reported by Windows, even when no CPU temperature sensor is available.",
6
+ "priority": "highlight",
7
+ "notice": "The reading includes power-policy and firmware limits. It does not identify overheating or rule out every hardware thermal restriction."
8
+ },
9
+ {
10
+ "title": "🎯 More reliable session status",
11
+ "body": "Failed turns stop appearing active, and background scans no longer create phantom sessions.",
12
+ "priority": "highlight"
13
+ },
14
+ {
15
+ "title": "🔁 Usage history recovers from temporary errors",
16
+ "body": "Project usage, quota history and tool history recover more reliably after temporary read or save failures.",
17
+ "priority": "highlight"
18
+ },
19
+ {
20
+ "title": "🧹 No hook errors in Claude Code after uninstalling the desktop app",
21
+ "body": "From this version on, the hook the desktop app leaves in Claude Code's settings ends quietly once the app is uninstalled, instead of showing an error on every tool call."
22
+ }
23
+ ],
2
24
  "//": [
3
25
  "What a user would NOTICE. One key per version that has something to say,",
4
26
  "and no key at all for a version that has nothing — which is most of them.",
@@ -84,6 +106,8 @@
84
106
  "without one."
85
107
  ],
86
108
  "//summaries": {
109
+ "3.82.3": "Windows CPU limits and more reliable session and usage history",
110
+ "3.82.2": "Arrow keys show the selected row on ccdeck tui's Network tab",
87
111
  "3.82.1": "Clearer network shortcuts, accurate account capacity and Codex recovery fixes",
88
112
  "3.82.0": "Steadier Codex switching, and uninstall cleans up Codex's terminal selection",
89
113
  "3.81.4": "Codex account switching works with Windows sandbox logins",
@@ -142,6 +166,12 @@
142
166
  "3.53.1",
143
167
  "3.53.3"
144
168
  ],
169
+ "3.82.2": [
170
+ {
171
+ "title": "⌨️ Arrow keys show where you are on ccdeck tui's Network tab",
172
+ "body": "In ccdeck tui, ↑ and ↓ on the Network tab now highlight the row you are on and scroll the list to it."
173
+ }
174
+ ],
145
175
  "3.82.1": [
146
176
  {
147
177
  "title": "Local network controls, easier to find",
@@ -23,7 +23,7 @@
23
23
  // of a small on-disk tally rather than a walk of every transcript.
24
24
  import { open, stat, readdir, readFile, writeFile, mkdir } from "node:fs/promises";
25
25
  import { homedir } from "node:os";
26
- import { join, resolve, basename, dirname, relative } from "node:path";
26
+ import { join, resolve, basename, dirname, relative, isAbsolute, sep } from "node:path";
27
27
  import { StringDecoder } from "node:string_decoder";
28
28
  import { renameWithRetry } from "./atomic-write.mjs";
29
29
  import { ccProjectSlug, claudeConfigDir } from "./claude-dir.mjs";
@@ -361,10 +361,12 @@ async function foldAppended(fh, start, size, onLine) {
361
361
  async function listTranscripts(roots) {
362
362
  const found = [];
363
363
  const seen = new Set();
364
+ const scanned = new Set();
364
365
  for (const root of roots) {
365
366
  let ents = null;
366
367
  try { ents = await readdir(root, { recursive: true, withFileTypes: true }); }
367
368
  catch { continue; }
369
+ scanned.add(root);
368
370
  for (const e of ents) {
369
371
  if (!e.isFile() || !e.name.endsWith(".jsonl")) continue;
370
372
  const dir = e.parentPath ?? e.path ?? root;
@@ -376,7 +378,15 @@ async function listTranscripts(roots) {
376
378
  }
377
379
  }
378
380
  found.sort((a, b) => a.depth - b.depth);
379
- return new Map(found.map(f => [f.path, f]));
381
+ return { files: new Map(found.map(f => [f.path, f])), scanned };
382
+ }
383
+
384
+ /** Only a completed inventory proves a missing transcript was deleted.
385
+ * Path components matter: a sibling named `projects-other` is not inside
386
+ * `projects`, and a recursive scan failure says nothing about its files. */
387
+ function insideRoot(path, root) {
388
+ const from = relative(root, path);
389
+ return from !== "" && from !== ".." && !from.startsWith(`..${sep}`) && !isAbsolute(from);
380
390
  }
381
391
 
382
392
  /** Drop day buckets older than the retention window and prune the empty
@@ -573,6 +583,16 @@ export function createProjectRollup({
573
583
  } catch { /* a failed persist just re-folds next time; cursors stay in memory */ }
574
584
  }
575
585
 
586
+ // Liveness is independent of transcript progress: a failed timeline read
587
+ // must not make a process that is still ticking look like it was shut down.
588
+ async function heartbeat(nowMs) {
589
+ if (dirty || !state.lastAlive || nowMs - state.lastAlive > HEARTBEAT_MS) {
590
+ state.lastAlive = nowMs;
591
+ dirty = true;
592
+ }
593
+ await persist();
594
+ }
595
+
576
596
  async function foldFile(path, slug, timeline, root) {
577
597
  let st = null;
578
598
  try { st = await stat(path); } catch { return; }
@@ -601,6 +621,17 @@ export function createProjectRollup({
601
621
  try {
602
622
  await load();
603
623
  const nowMs = now();
624
+ const defer = async () => {
625
+ // An old heartbeat already proving a gap must survive until the log
626
+ // can be read and its stop fence written. In particular, the first
627
+ // pass after a real restart may itself encounter an unreadable log.
628
+ if (!state.lastAlive || nowMs - state.lastAlive <= GAP_MS) await heartbeat(nowMs);
629
+ };
630
+ // A failed read is not evidence that nobody owned the new usage. Check
631
+ // before writing gap/seed entries, and again after those writes, so no
632
+ // transcript bytes are consumed from a fabricated empty timeline.
633
+ try { await readSwapLog(swapLog, { strict: true }); }
634
+ catch { await defer(); return; } // scheduled passes must defer without rejecting
604
635
  // The deck was down between the last heartbeat and this boot. Fence that
605
636
  // stretch off so work timestamped inside it is unattributed rather than
606
637
  // charged to whoever was active when the deck closed — the user may have
@@ -610,8 +641,10 @@ export function createProjectRollup({
610
641
  for (const root of gapRoots) await markGap(state.lastAlive + 1, swapLog, root);
611
642
  }
612
643
  await seedActive({ now, path: swapLog, root: storeRoot, projectsRoot: canonicalRoots[0] }); // anchor the current account, once, deduped
613
- const timeline = await readSwapLog(swapLog);
614
- const files = await listTranscripts(canonicalRoots);
644
+ let timeline;
645
+ try { timeline = await readSwapLog(swapLog, { strict: true }); }
646
+ catch { await defer(); return; }
647
+ const { files, scanned } = await listTranscripts(canonicalRoots);
615
648
  // Each root is attributed only by the entries that speak for it; an
616
649
  // unscoped legacy entry speaks for none unless its root is unambiguous
617
650
  // (timelineFor).
@@ -620,21 +653,16 @@ export function createProjectRollup({
620
653
  // Forget the cursors and request ledgers of files that are gone, and
621
654
  // the folders of project directories with no transcript left, so none of
622
655
  // the three maps grows forever.
623
- for (const p of Object.keys(state.cursors)) if (!files.has(p)) { delete state.cursors[p]; dirty = true; }
624
- for (const p of Object.keys(state.requests)) if (!files.has(p)) { delete state.requests[p]; dirty = true; }
656
+ const gone = p => !files.has(p) && [...scanned].some(root => insideRoot(p, root));
657
+ for (const p of Object.keys(state.cursors)) if (gone(p)) { delete state.cursors[p]; dirty = true; }
658
+ for (const p of Object.keys(state.requests)) if (gone(p)) { delete state.requests[p]; dirty = true; }
625
659
  for (const root of Object.keys(state.folders)) {
660
+ if (!scanned.has(root)) continue;
626
661
  const slugs = new Set([...files.values()].filter(f => f.root === root).map(f => f.slug));
627
662
  for (const s of Object.keys(state.folders[root])) if (!slugs.has(s)) { delete state.folders[root][s]; dirty = true; }
628
663
  if (!slugs.size) delete state.folders[root];
629
664
  }
630
- // Heartbeat: record that the deck was alive now, so a later boot can see
631
- // how long it was down. Cheap when nothing else changed — only bumped
632
- // (and so only persisted) once every HEARTBEAT_MS while idle.
633
- if (dirty || !state.lastAlive || nowMs - state.lastAlive > HEARTBEAT_MS) {
634
- state.lastAlive = nowMs;
635
- dirty = true;
636
- }
637
- await persist();
665
+ await heartbeat(nowMs);
638
666
  } finally { running = false; }
639
667
  }
640
668
 
@@ -128,7 +128,12 @@ export async function takeBootLock({
128
128
  }
129
129
  const holder = readHolder(file, fs);
130
130
  if (holderIsGone(holder, { now: now(), alive, staleMs, mtime: modifiedAt(file, fs), self: pid })) {
131
- try { fs.unlinkSync(file); } catch { /* another start cleared it first */ }
131
+ try { fs.unlinkSync(file); }
132
+ catch (err) {
133
+ // A competing start may have cleared it. Other refusals cannot be
134
+ // fixed by retrying synchronously: let startup proceed unguarded.
135
+ if (err?.code !== "ENOENT") return { held: false, waited, reason: err?.code ?? "unlink_failed", release: () => false };
136
+ }
132
137
  continue;
133
138
  }
134
139
  waited = true;
@@ -10,6 +10,7 @@ import { createRequire } from "node:module";
10
10
  import { spawn } from "node:child_process";
11
11
  import { existsSync } from "node:fs";
12
12
  import { killTree, pathLookup, spawnSpec } from "./exec.mjs";
13
+ import { watchChild } from "./exec-children.mjs";
13
14
  import { note, stamp, tagged } from "./ccusage-failure.mjs";
14
15
  import {
15
16
  discardDamagedInstall, installsDisabled, lastInstallError, maybeBackgroundUpdate, npmAvailable,
@@ -232,7 +233,9 @@ function runOnce(runner, args) {
232
233
  ? userSpec(runner.file, args)
233
234
  : fallbackSpec(args);
234
235
  return new Promise((resolve, reject) => {
235
- const child = spawn(file, full, { windowsHide: true, ...opts });
236
+ const processGroup = process.platform !== "win32";
237
+ const child = watchChild(spawn(file, full, { windowsHide: true, ...opts,
238
+ ...(processGroup ? { detached: true } : {}) }), { processGroup });
236
239
  let out = "", err = "";
237
240
  const timer = setTimeout(() => {
238
241
  // The npx fallback goes through cmd.exe on Windows, so `child` is the
@@ -49,6 +49,7 @@ export function startEngineRpc(executable, args, home, { env = process.env, onMe
49
49
  if (!line.trim()) continue;
50
50
  let message;
51
51
  try { message = JSON.parse(line); } catch { protocolError('json'); return; }
52
+ if (!message || typeof message !== 'object' || Array.isArray(message)) { protocolError('envelope'); return; }
52
53
  const call = pending.get(message.id);
53
54
  if (call && !message.method) {
54
55
  clearTimeout(call.timer); pending.delete(message.id);
@@ -14,8 +14,12 @@ import { spawn } from "node:child_process";
14
14
  /**
15
15
  * Stop a child AND everything it started.
16
16
  *
17
- * On POSIX the child is the tool, so a signal to it is the whole job and this
18
- * is exactly the `child.kill()` it replaces. On Windows a .cmd or .bat runs
17
+ * On POSIX an explicitly owned process group receives the signal as a group:
18
+ * wrappers can start ordinary descendants which outlive a signal to the
19
+ * wrapper alone. Only callers that spawned with `detached: true` may mark that
20
+ * ownership in watchChild; an arbitrary child's inherited group could include
21
+ * the deck and the user's shell. Unmarked children keep the plain kill.
22
+ * On Windows a .cmd or .bat runs
19
23
  * THROUGH cmd.exe (see viaCmd), so the tool — node, for the claude and npm
20
24
  * shims — is a grandchild, and a kill is one TerminateProcess against the
21
25
  * wrapper. Windows terminates no descendants and libuv's job object lets them
@@ -37,7 +41,13 @@ import { spawn } from "node:child_process";
37
41
  */
38
42
  export function killTree(child, signal) {
39
43
  const plain = () => { try { child?.kill(signal); } catch { /* already gone */ } };
40
- if (process.platform !== "win32" || !child?.pid) return plain();
44
+ if (process.platform !== "win32") {
45
+ if (ownedGroups.has(child) && Number.isInteger(child.pid) && child.pid > 1 && child.pid !== process.pid) {
46
+ try { process.kill(-child.pid, signal); return; } catch { /* gone, or no group: try the child */ }
47
+ }
48
+ return plain();
49
+ }
50
+ if (!child?.pid) return plain();
41
51
  try {
42
52
  const root = process.env.SystemRoot || process.env.systemroot;
43
53
  const exe = root ? `${root}\\System32\\taskkill.exe` : "taskkill";
@@ -84,12 +94,17 @@ export function killTree(child, signal) {
84
94
  * purpose. Killing those on the way out would be this set overreaching.
85
95
  */
86
96
  const live = new Set();
97
+ const ownedGroups = new WeakSet();
87
98
 
88
- /** Track one child until it ends. Returns it, so it can wrap a spawn inline. */
89
- export function watchChild(cp) {
99
+ /** Track one child until it ends. `processGroup` may only be true when this
100
+ * caller just spawned a dedicated POSIX group with `detached: true`.
101
+ * Tracking alone (e.g. a native account probe) never grants group ownership. */
102
+ export function watchChild(cp, { processGroup = false } = {}) {
90
103
  if (!cp) return cp;
104
+ if (processGroup && process.platform !== "win32") ownedGroups.add(cp);
91
105
  live.add(cp);
92
- const forget = () => { live.delete(cp); };
106
+ // A stale ChildProcess must never signal a later process reusing its PID.
107
+ const forget = () => { live.delete(cp); ownedGroups.delete(cp); };
93
108
  cp.once?.("close", forget);
94
109
  cp.once?.("error", forget);
95
110
  return cp;
@@ -26,6 +26,7 @@
26
26
  // launched by its full path where one can be found; see shimPath and
27
27
  // candidateSpec.
28
28
  import { execFile, spawn } from "node:child_process";
29
+ import { StringDecoder } from "node:string_decoder";
29
30
  // Which spelling of a command to try, whether it goes through cmd.exe, and the
30
31
  // exact file, argv and options spawn is handed for it — all of it decided
31
32
  // before anything is spawned, and all of it platform-parameterised so the
@@ -81,6 +82,46 @@ export const tryNext = (err) =>
81
82
  // where a tool puts the line that explains itself.
82
83
  const TIMEOUT_TAIL = 8 << 10;
83
84
 
85
+ /** execFile does not forward `detached` to spawn. POSIX buffered commands
86
+ * therefore need their own spawn to establish a private group. Keep the
87
+ * execFile contract: UTF-8 output, separate byte limits, and one callback
88
+ * after both pipes close. Windows keeps its existing execFile path. */
89
+ function execCommand(file, args, opts, callback) {
90
+ if (process.platform === "win32") return watchChild(execFile(file, args, opts, callback));
91
+ const cp = watchChild(spawn(file, args, { ...opts, detached: true }), { processGroup: true });
92
+ const output = { stdout: "", stderr: "" };
93
+ const bytes = { stdout: 0, stderr: 0 };
94
+ let error = null, finished = false;
95
+ const finish = (err) => {
96
+ if (finished) return;
97
+ finished = true;
98
+ callback(err, output.stdout, output.stderr);
99
+ };
100
+ for (const name of ["stdout", "stderr"]) {
101
+ cp[name].setEncoding?.("utf8");
102
+ cp[name].on("data", text => {
103
+ if (error) return;
104
+ const size = Buffer.byteLength(text);
105
+ const remaining = Math.max(0, opts.maxBuffer - bytes[name]);
106
+ output[name] += size > remaining
107
+ ? new StringDecoder("utf8").write(Buffer.from(text).subarray(0, remaining)) : text;
108
+ bytes[name] += size;
109
+ if (bytes[name] > opts.maxBuffer) {
110
+ error = Object.assign(new Error(`${name} maxBuffer length exceeded`), {
111
+ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER", killed: true,
112
+ });
113
+ killTree(cp);
114
+ }
115
+ });
116
+ cp[name].on("error", err => { error ??= err; killTree(cp); });
117
+ }
118
+ cp.on("error", finish);
119
+ cp.on("close", (code, signal) => finish(error ?? (code === 0 ? null : {
120
+ code, signal, killed: Boolean(signal),
121
+ })));
122
+ return cp;
123
+ }
124
+
84
125
  /**
85
126
  * Run a command and collect its output. Never rejects, and never throws —
86
127
  * failures come back as `{ ok: false }`, because every caller here is a poll or
@@ -169,8 +210,8 @@ export function run(cmd, args, { timeout = 20_000, maxBuffer = 4 << 20, env, cwd
169
210
  // watchChild: this run's deadline lives in the timer below, in THIS
170
211
  // process, so a shutdown that does not reap it leaves the child with
171
212
  // no deadline at all. See `live` in exec-children.mjs, and #1012.
172
- const cp = watchChild(execFile(file, argv,
173
- { timeout: 0, shell: false, windowsHide: true, maxBuffer, ...(env ? { env } : {}), ...(cwd ? { cwd } : {}), ...opts }, done));
213
+ const cp = execCommand(file, argv,
214
+ { timeout: 0, shell: false, windowsHide: true, maxBuffer, ...(env ? { env } : {}), ...(cwd ? { cwd } : {}), ...opts }, done);
174
215
  // Give the child EOF on stdin straight away, which is what this
175
216
  // function's contract has always claimed ("run closes stdin", says
176
217
  // runInteractive's header) and what execFile does not do: it leaves the
@@ -314,7 +355,9 @@ export function runInteractive(cmd, args, { timeout = 300_000, maxOutput = 256 <
314
355
  // this one's deadline is five minutes and it is a `claude auth login`
315
356
  // blocked on a stdin pipe only this process holds. See `live` in
316
357
  // exec-children.mjs.
317
- proc = watchChild(spawn(file, argv, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...opts }));
358
+ const processGroup = process.platform !== "win32";
359
+ proc = watchChild(spawn(file, argv, { stdio: ["pipe", "pipe", "pipe"], shell: false, windowsHide: true, ...opts,
360
+ ...(processGroup ? { detached: true } : {}) }), { processGroup });
318
361
  } catch (err) {
319
362
  return tryNext(err) ? attempt(i + 1) : finish(-1, err);
320
363
  }
@@ -37,7 +37,8 @@ export function send(res, status, body, headers = {}) {
37
37
  export const OVERSIZE_DRAIN_MS = 10_000;
38
38
 
39
39
  /**
40
- * Collect a request body as a string, capped so a bad client can't fill memory.
40
+ * Collect a request body as a string, capped in wire bytes before UTF-8
41
+ * decoding so the same limit applies to every language.
41
42
  *
42
43
  * IT ANSWERS BEFORE IT HANGS UP, which it did not. `req.destroy()` ran ahead of
43
44
  * the reject, so the caller's own `send(res, 400, ...)` had no socket left to
@@ -63,24 +64,7 @@ export const OVERSIZE_DRAIN_MS = 10_000;
63
64
  * gone out.
64
65
  */
65
66
  export function readBody(req, res = null, limit = 64_000) {
66
- return new Promise((resolve, reject) => {
67
- let body = "";
68
- let refused = false;
69
- req.setEncoding("utf8");
70
- req.on("data", c => {
71
- if (refused) return;
72
- body += c;
73
- if (body.length > limit) {
74
- refused = true;
75
- body = "";
76
- if (res) send(res, 413, { error: "body too large" });
77
- drainRefused(req);
78
- reject(new Error("body too large"));
79
- }
80
- });
81
- req.on("end", () => { if (!refused) resolve(body); });
82
- req.on("error", reject);
83
- });
67
+ return readBytes(req, res, limit).then(body => body.toString("utf8"));
84
68
  }
85
69
 
86
70
  /** Keep reading a refused upload and throw it away, for a bounded while — see readBody. */
@@ -71,7 +71,8 @@ function normaliseConnection(raw) {
71
71
  * @param {(msg: string) => void} [opts.warn]
72
72
  */
73
73
  export function createIntegrationsStore({ dir = () => join(deckDataDir(), STORE_DIR), warn = msg => console.warn(msg) } = {}) {
74
- /** Every write, one at a time, so two pages saving at once cannot lose one. */
74
+ /** Loads can quarantine damaged files, so serialize them with mutations too:
75
+ * a reader's stale parse must never move aside a freshly saved file. */
75
76
  let chain = Promise.resolve();
76
77
  const queued = job => {
77
78
  const run = chain.then(job, job);
@@ -92,7 +93,13 @@ export function createIntegrationsStore({ dir = () => join(deckDataDir(), STORE_
92
93
  // the user's tokens, and the next save would otherwise replace it with
93
94
  // an empty one. Its contents are never logged.
94
95
  const aside = `${path}.corrupt-${Date.now()}`;
95
- await rename(path, aside).catch(() => {});
96
+ try { await rename(path, aside); }
97
+ catch (err) {
98
+ // Another reader may already have moved it. Any other refusal must
99
+ // stop the load: a later save must not overwrite unpreserved bytes.
100
+ if (err?.code === "ENOENT") return null;
101
+ throw err;
102
+ }
96
103
  warn(`${PRODUCT}: ${label} could not be read as JSON and was moved aside to ${aside}.`);
97
104
  return null;
98
105
  }
@@ -172,13 +179,13 @@ export function createIntegrationsStore({ dir = () => join(deckDataDir(), STORE_
172
179
  * answers the connection to list: the routes take that secret out of what
173
180
  * an earlier build kept (routes.mjs). */
174
181
  async list({ own } = {}) {
175
- const { connections, secrets } = await load();
182
+ const { connections, secrets } = await queued(load);
176
183
  return connections.map(c => publicOf(own && secrets.has(c.id) ? own(c, secrets.get(c.id)) : c, secrets));
177
184
  },
178
185
 
179
186
  /** One connection, as a page may see it, or null. */
180
187
  async get(id) {
181
- const { connections, secrets } = await load();
188
+ const { connections, secrets } = await queued(load);
182
189
  const conn = connections.find(c => c.id === id);
183
190
  return conn ? publicOf(conn, secrets) : null;
184
191
  },
@@ -186,7 +193,7 @@ export function createIntegrationsStore({ dir = () => join(deckDataDir(), STORE_
186
193
  /** The opaque secret for one connection, or null. The ONE read of the
187
194
  * secrets file, and its only caller is the proxy that signs requests. */
188
195
  async secret(id) {
189
- const { secrets } = await load();
196
+ const { secrets } = await queued(load);
190
197
  return secrets.get(id) ?? null;
191
198
  },
192
199
 
@@ -133,9 +133,19 @@ export async function handleLanPeer(req, res) {
133
133
  * than reporting a round that asked nobody. */
134
134
  export async function handleLanSync(req, res) {
135
135
  const raw = await readBody(req, res).catch(() => null);
136
- let body = null;
137
- try { body = JSON.parse(raw ?? ""); } catch { /* the whole-list press sends nothing to read */ }
138
- const fp = body && typeof body.fp === "string" ? body.fp : null;
136
+ // A refused upload has already been answered. It must not become the empty
137
+ // request that deliberately asks every peer to sync.
138
+ if (raw == null) return;
139
+ let body = {};
140
+ if (raw !== "") {
141
+ try { body = JSON.parse(raw); }
142
+ catch { return send(res, 400, { ok: false, reason: "bad_request" }); }
143
+ }
144
+ if (!body || typeof body !== "object" || Array.isArray(body)
145
+ || ("fp" in body && (typeof body.fp !== "string" || !body.fp))) {
146
+ return send(res, 400, { ok: false, reason: "bad_request" });
147
+ }
148
+ const fp = body.fp;
139
149
  if (fp) {
140
150
  const done = await lanEngine.roundOne(fp);
141
151
  if (done == null) return send(res, 409, { ok: false, reason: "no_address" });
@@ -208,11 +208,19 @@ async function handleRestart(req, res) {
208
208
  let whenIdle = false;
209
209
  if (req.method === "POST") {
210
210
  const body = await readBody(req, res).catch(() => null);
211
- try {
212
- const ask = JSON.parse(body ?? "");
213
- wantUpgrade = ask?.upgrade === true;
214
- whenIdle = ask?.whenIdle === true;
215
- } catch { /* a plain restart */ }
211
+ if (body == null) return;
212
+ let ask = {};
213
+ if (body !== "") {
214
+ try { ask = JSON.parse(body); }
215
+ catch { return send(res, 400, { ok: false, reason: "bad_request" }); }
216
+ }
217
+ if (!ask || typeof ask !== "object" || Array.isArray(ask)
218
+ || ("upgrade" in ask && typeof ask.upgrade !== "boolean")
219
+ || ("whenIdle" in ask && typeof ask.whenIdle !== "boolean")) {
220
+ return send(res, 400, { ok: false, reason: "bad_request" });
221
+ }
222
+ wantUpgrade = ask.upgrade === true;
223
+ whenIdle = ask.whenIdle === true;
216
224
  }
217
225
  let mode = null;
218
226
  if (wantUpgrade) {
@@ -47,16 +47,25 @@ export const BUCKET_MS = 60_000;
47
47
  * should be.
48
48
  */
49
49
  export function record(key, value, nowMs = Date.now()) {
50
- if (!Number.isFinite(value)) return;
50
+ if (!Number.isFinite(value) || !Number.isFinite(nowMs)) return;
51
51
  const minute = Math.floor(nowMs / BUCKET_MS);
52
- let last = history[history.length - 1];
53
- if (!last || last.m !== minute) {
54
- last = { m: minute, v: {} };
55
- history.push(last);
56
- while (history.length > HISTORY_MINUTES) history.shift();
52
+ let bucket = history[history.length - 1];
53
+ if (!bucket || bucket.m < minute) {
54
+ bucket = { m: minute, v: {} };
55
+ history.push(bucket);
56
+ } else if (bucket.m > minute) {
57
+ // A clock correction can revisit an existing minute or a gap. Keep one
58
+ // maximum per minute, in time order, without evicting newer data for it.
59
+ const index = history.findIndex(b => b.m >= minute);
60
+ bucket = history[index];
61
+ if (bucket.m !== minute) {
62
+ bucket = { m: minute, v: {} };
63
+ history.splice(index, 0, bucket);
64
+ }
57
65
  }
58
- const prev = last.v[key];
59
- last.v[key] = prev == null ? value : Math.max(prev, value);
66
+ while (history.length > HISTORY_MINUTES) history.shift();
67
+ const prev = bucket.v[key];
68
+ bucket.v[key] = prev == null ? value : Math.max(prev, value);
60
69
  }
61
70
 
62
71
  /** Every reading recorded under `key`, oldest first, one point per minute that
@@ -79,8 +79,11 @@ export function createQuotaCloses({ load = async () => null, save = async () =>
79
79
  const flush = async () => {
80
80
  prune(state, now());
81
81
  if (!dirty) return;
82
- dirty = false;
83
- try { await save({ v: 1, open: state.open, closed: state.closed }); storageOk = true; }
82
+ try {
83
+ await save({ v: 1, open: state.open, closed: state.closed });
84
+ dirty = false;
85
+ storageOk = true;
86
+ }
84
87
  catch { storageOk = false; } // the record cannot fail a quota read
85
88
  };
86
89
  const run = fn => (queue = queue.then(async () => { await ready(); await fn(); await flush(); }).catch(() => { storageOk = false; }));
@@ -64,14 +64,44 @@ export function normalizeHistory(raw, now) {
64
64
  return prune(out, now);
65
65
  }
66
66
 
67
+ /** Keep observations collected during a read failure when the file recovers.
68
+ * The same window match and reset tolerance as record(), without replacing
69
+ * points that were already persisted at the same timestamp. */
70
+ function mergeBufferedHistory(stored, buffered, now) {
71
+ for (const pending of buffered) {
72
+ const row = stored.find(s => s.provider === pending.provider && s.account === pending.account
73
+ && s.id === pending.id && s.windowSec === pending.windowSec && Math.abs(s.resetAt - pending.resetAt) <= 120);
74
+ if (!row) { stored.push(pending); continue; }
75
+ row.resetAt = Math.max(row.resetAt, pending.resetAt);
76
+ const points = new Map([...pending.points, ...row.points].map(p => [p.t, p]));
77
+ row.points = [...points.values()].sort((a, b) => a.t - b.t);
78
+ }
79
+ return prune(stored, now);
80
+ }
81
+
67
82
  export function createQuotaHistory({ load = async () => null, save = async () => {}, now = Date.now } = {}) {
68
- let series = [], loading = null, storageOk = true;
83
+ let series = [], loaded = false, storageOk = true, dirty = false;
69
84
  const active = new Map();
70
85
  let queue = Promise.resolve();
71
- const ready = () => loading ??= (async () => {
72
- try { series = normalizeHistory(await load(), now()); }
86
+ // Every read and write runs in the queue. A failed load is retried by the
87
+ // next operation; buffered readings never authorize replacing unread data.
88
+ const ready = async () => {
89
+ if (loaded) return;
90
+ try {
91
+ const stored = normalizeHistory(await load(), now());
92
+ series = mergeBufferedHistory(stored, series, now());
93
+ loaded = true;
94
+ storageOk = true;
95
+ }
73
96
  catch { storageOk = false; }
74
- })();
97
+ };
98
+ const flush = async () => {
99
+ if (!loaded || !dirty) return;
100
+ try { await save({ v: 1, series }); dirty = false; storageOk = true; }
101
+ catch { storageOk = false; } // history cannot fail a quota request
102
+ };
103
+ const run = fn => (queue = queue.then(async () => { await ready(); await fn(); await flush(); })
104
+ .catch(() => { storageOk = false; }));
75
105
  return {
76
106
  activate(provider, account) {
77
107
  if (!providers.has(provider)) return null;
@@ -80,8 +110,7 @@ export function createQuotaHistory({ load = async () => null, save = async () =>
80
110
  return key;
81
111
  },
82
112
  record(provider, account, reading) {
83
- queue = queue.then(async () => {
84
- await ready();
113
+ return run(() => {
85
114
  if (!providers.has(provider) || !/^[a-f0-9]{64}$/.test(account ?? "") || !reading?.ok || reading.stale
86
115
  || !finite(reading.fetchedAt) || reading.fetchedAt > now() + 60_000) return;
87
116
  let changed = false;
@@ -105,20 +134,14 @@ export function createQuotaHistory({ load = async () => null, save = async () =>
105
134
  changed = true;
106
135
  }
107
136
  series = prune(series, now());
108
- if (changed) {
109
- try { await save({ v: 1, series }); storageOk = true; }
110
- catch { storageOk = false; } // history cannot fail a quota request
111
- }
112
- }).catch(() => { storageOk = false; });
113
- return queue;
137
+ if (changed) dirty = true;
138
+ });
114
139
  },
115
140
  async report(provider, account) {
116
- await queue;
117
- await ready();
141
+ await run(() => { series = prune(series, now()); });
118
142
  // A delayed request for an account that was switched away from cannot
119
143
  // display its history beside the new account's current quota.
120
144
  if (!account || active.get(provider) !== account) return { ok: true, account: null, series: [], storageOk };
121
- series = prune(series, now());
122
145
  return { ok: true, account, storageOk, series: series.filter(s => s.provider === provider && s.account === account)
123
146
  .map(({ account: _account, provider: _provider, ...s }) => ({ ...s, points: s.points.map(p => ({ ...p })) })) };
124
147
  },