claude-code-cost 0.12.1 → 0.13.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.
@@ -0,0 +1,267 @@
1
+ 'use strict';
2
+
3
+ // Network boundary for a local-only dev server.
4
+ //
5
+ // Binding loopback is necessary but not sufficient. Three distinct attackers:
6
+ //
7
+ // * LAN peer — http://192.168.1.42:3541/api/... The loopback bind stops this
8
+ // outright; the handshake never completes off-box.
9
+ // * DNS rebinding — the victim loads evil.com, the attacker re-resolves that
10
+ // name to 127.0.0.1, and the page fetches http://evil.com:3541/api/...
11
+ // The page's origin *is* evil.com:3541, so the request is same-origin and
12
+ // CORS never fires; the connection is to loopback, so the bind is satisfied.
13
+ // The only thing that differs from a legitimate request is the Host header,
14
+ // which script cannot forge. A Host allowlist is the entire defense.
15
+ // * Plain CSRF — evil.com POSTs straight at 127.0.0.1:3541. Host is a real
16
+ // allowlisted value, so hostGuard passes it; this needs a separate Origin /
17
+ // Sec-Fetch-Site check on state-changing methods.
18
+ //
19
+ // There is no authentication. Exposing this to a network means trusting everyone
20
+ // on it with the user's Claude Code history.
21
+ //
22
+ // CANONICAL COPY: scripts/security-lib/net-guard.js in the claude-code-hub repo.
23
+ // Run scripts/sync-security-lib.sh after editing.
24
+
25
+ const LOOPBACK_HOSTS = new Set([
26
+ 'localhost',
27
+ '127.0.0.1',
28
+ '::1',
29
+ '0:0:0:0:0:0:0:1',
30
+ '::ffff:127.0.0.1',
31
+ ]);
32
+
33
+ // Hoisted: parseHostHeader runs on every request, and neither the regex nor the
34
+ // predicate depends on the argument.
35
+ const PORT_RE = /^[0-9]{1,5}$/;
36
+ // The port is validated but not compared — the listen(0) fallbacks make the real
37
+ // port dynamic, so only the host is allowlisted.
38
+ const validPort = (p) => PORT_RE.test(p) && Number(p) >= 1 && Number(p) <= 65535;
39
+
40
+ function isLoopbackAddress(host) {
41
+ if (!host) return false;
42
+ const h = String(host).toLowerCase();
43
+ return LOOPBACK_HOSTS.has(h) || h.startsWith('127.');
44
+ }
45
+
46
+ // Hand-parsed rather than via new URL(), which is far more permissive than we
47
+ // want here and happily accepts things no real client sends. Returns the bare
48
+ // hostname, lowercased, or null if the header is malformed.
49
+ //
50
+ // The port is deliberately ignored: ports are dynamic in these apps because of
51
+ // the listen(0) fallback when the default is busy, so pinning one would break
52
+ // the fallback path.
53
+ function parseHostHeader(value) {
54
+ if (typeof value !== 'string') return null;
55
+ const raw = value.trim();
56
+ if (!raw || raw.length > 259) return null;
57
+
58
+ // Reject whitespace and control characters. Written as a code-point scan rather
59
+ // than a character class so it cannot be misread — a stray range in a regex
60
+ // here would silently reject legitimate hostnames containing a dash.
61
+ for (let i = 0; i < raw.length; i++) {
62
+ const code = raw.charCodeAt(i);
63
+ if (code <= 0x20 || code === 0x7f) return null;
64
+ }
65
+ if (raw.includes('@')) return null; // userinfo has no business in a Host header
66
+
67
+ let host;
68
+ if (raw.startsWith('[')) {
69
+ const end = raw.indexOf(']');
70
+ if (end === -1) return null;
71
+ host = raw.slice(1, end);
72
+ const rest = raw.slice(end + 1);
73
+ if (rest && !(rest.startsWith(':') && validPort(rest.slice(1)))) return null;
74
+ } else {
75
+ const parts = raw.split(':');
76
+ if (parts.length > 2) return null; // bare IPv6 without brackets, or garbage
77
+ host = parts[0];
78
+ if (parts.length === 2 && !validPort(parts[1])) return null;
79
+ }
80
+
81
+ if (!host) return null;
82
+ if (host.endsWith('.')) host = host.slice(0, -1); // one trailing root dot is legal
83
+ if (!host) return null;
84
+ return host.toLowerCase();
85
+ }
86
+
87
+ function parseList(value) {
88
+ return String(value || '')
89
+ .split(',')
90
+ .map((s) => s.trim().toLowerCase())
91
+ .filter(Boolean);
92
+ }
93
+
94
+ function getFlag(name) {
95
+ const idx = process.argv.findIndex((a) => a === `--${name}` || a.startsWith(`--${name}=`));
96
+ if (idx === -1) return null;
97
+ const arg = process.argv[idx];
98
+ if (arg.includes('=')) return arg.slice(arg.indexOf('=') + 1);
99
+ const next = process.argv[idx + 1];
100
+ return next && !next.startsWith('--') ? next : null;
101
+ }
102
+
103
+ /**
104
+ * @param {{appName?: string}} [config]
105
+ */
106
+ function createNetGuard(config = {}) {
107
+ const appName = config.appName || 'This app';
108
+
109
+ const BIND_HOST = getFlag('host') || process.env.HOST || '127.0.0.1';
110
+ const BIND_HOST_LC = BIND_HOST.toLowerCase();
111
+ const EXPOSED = !isLoopbackAddress(BIND_HOST);
112
+ // Resolved here and re-exported so the hub can forward the same value to its
113
+ // children rather than re-parsing the flag with its own argv scanner — a parent
114
+ // and child that disagree means the shell serves while every iframe 403s.
115
+ const ALLOWED_HOSTS = getFlag('allowed-hosts') || process.env.ALLOWED_HOSTS || '';
116
+ const extraHosts = new Set(parseList(ALLOWED_HOSTS));
117
+
118
+ // The hub frames each sub-app, so its origin must be accepted as an Origin and
119
+ // permitted as a framing ancestor.
120
+ let hubOrigin = null;
121
+ if (process.env.HUB_URL) {
122
+ try { hubOrigin = new URL(process.env.HUB_URL).origin; } catch { /* ignore a malformed HUB_URL */ }
123
+ }
124
+
125
+ // Resolved only once listen() succeeds — the requested port may have been busy.
126
+ let actualPort = null;
127
+
128
+ function hostAllowed(host) {
129
+ if (!host) return false;
130
+ if (isLoopbackAddress(host)) return true;
131
+ if (extraHosts.has(host)) return true;
132
+ // Binding a specific non-loopback address implies that address is a valid name for us.
133
+ if (EXPOSED && host === BIND_HOST_LC) return true;
134
+ return false;
135
+ }
136
+
137
+ function hostGuard(req, res, next) {
138
+ const host = parseHostHeader(req.headers.host);
139
+ if (hostAllowed(host)) return next();
140
+ res.status(403).type('text/plain').send(
141
+ `403 Forbidden - unrecognized Host header: ${req.headers.host || '(none)'}\n\n` +
142
+ `${appName} only answers requests addressed to localhost. This protects you\n` +
143
+ `from DNS rebinding, where a website you visit re-points its own hostname at\n` +
144
+ `127.0.0.1 in order to read your local data.\n\n` +
145
+ `If you meant to reach this from another machine, restart with:\n` +
146
+ ` --host 0.0.0.0 --allowed-hosts=${host || '<your-hostname>'}\n\n` +
147
+ `Only do that on a network you trust - there is no authentication.\n`
148
+ );
149
+ }
150
+
151
+ // true = allow, false = block, null = no Origin header, caller decides.
152
+ function originVerdict(origin) {
153
+ if (!origin || origin === 'null') return null;
154
+ let parsed;
155
+ try { parsed = new URL(origin); } catch { return false; }
156
+ if (hubOrigin && parsed.origin === hubOrigin) return true;
157
+ if (!isLoopbackAddress(parsed.hostname)) return false;
158
+ // Same port, any loopback spelling. A different local port is a different app
159
+ // and has no business driving this one.
160
+ if (actualPort && parsed.port && Number(parsed.port) !== Number(actualPort)) return false;
161
+ return true;
162
+ }
163
+
164
+ function originGuard(req, res, next) {
165
+ if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
166
+
167
+ const verdict = originVerdict(req.headers.origin);
168
+ if (verdict === true) return next();
169
+ if (verdict === false) {
170
+ return res.status(403).type('text/plain')
171
+ .send(`403 Forbidden - cross-origin ${req.method} from ${req.headers.origin} is not allowed.\n`);
172
+ }
173
+
174
+ // No Origin header: a non-browser client (curl, the CLI, the hub's own fetch).
175
+ // Trust it unless the browser explicitly tells us otherwise.
176
+ const site = req.headers['sec-fetch-site'];
177
+ if (site && site !== 'same-origin' && site !== 'none') {
178
+ return res.status(403).type('text/plain')
179
+ .send(`403 Forbidden - cross-site ${req.method} (Sec-Fetch-Site: ${site}) is not allowed.\n`);
180
+ }
181
+ return next();
182
+ }
183
+
184
+ // Constant for the life of the process, and frameGuard runs ahead of
185
+ // express.static — so this is built once rather than per asset fetch.
186
+ //
187
+ // Under the hub, X-Frame-Options is deliberately omitted: it has no multi-origin
188
+ // form, and sending SAMEORIGIN would break the hub's iframes.
189
+ //
190
+ // The port is wildcarded rather than pinned to HUB_URL's. The hub spawns its
191
+ // children before it binds, so if its own preferred port is busy it hands them a
192
+ // HUB_URL with the wrong port and every iframe would break. Any loopback port may
193
+ // frame us; that is not the threat being addressed here — a remote page still
194
+ // cannot, which is what matters.
195
+ //
196
+ // No IPv6 literal: Chrome rejects `http://[::1]:*` as a source expression and
197
+ // logs it on every framed load. The hub's own origin is added verbatim instead,
198
+ // which covers a hub reached over [::1].
199
+ let CSP;
200
+ if (hubOrigin) {
201
+ const ancestors = ["'self'", 'http://localhost:*', 'http://127.0.0.1:*'];
202
+ if (!/^http:\/\/(localhost|127\.0\.0\.1)(:|$)/.test(hubOrigin)) ancestors.push(hubOrigin);
203
+ CSP = `frame-ancestors ${ancestors.join(' ')}`;
204
+ } else {
205
+ CSP = "frame-ancestors 'none'";
206
+ }
207
+
208
+ function frameGuard(_req, res, next) {
209
+ res.setHeader('X-Content-Type-Options', 'nosniff');
210
+ res.setHeader('Referrer-Policy', 'no-referrer');
211
+ res.setHeader('Content-Security-Policy', CSP);
212
+ if (!hubOrigin) res.setHeader('X-Frame-Options', 'DENY');
213
+ next();
214
+ }
215
+
216
+ /**
217
+ * Bind BIND_HOST, then opportunistically serve the other loopback family on the
218
+ * same resolved port via a second server sharing the same request handler.
219
+ *
220
+ * That second bind is what keeps `http://localhost:<port>` working no matter how
221
+ * the OS resolver orders A/AAAA records - binding only 127.0.0.1 breaks hosts
222
+ * where `localhost` resolves to ::1, and vice versa. Doing it on the *resolved*
223
+ * port means every existing URL, startup banner and postMessage origin is
224
+ * unchanged. Failures are swallowed: it is an optimization, not a requirement.
225
+ *
226
+ * Returns the primary server, so callers keep attaching their own 'error'
227
+ * handler for the EADDRINUSE fallback.
228
+ *
229
+ * @param {any} app express app (or any http request handler)
230
+ * @param {number} port 0 selects a free port
231
+ * @param {(port: number) => void} [onReady]
232
+ * @param {{maxHeaderSize?: number}} [opts]
233
+ */
234
+ function listenLoopback(app, port, onReady, opts = {}) {
235
+ const http = require('http');
236
+ const serverOpts = opts.maxHeaderSize ? { maxHeaderSize: opts.maxHeaderSize } : {};
237
+ const makeServer = (handler) => http.createServer(serverOpts, handler);
238
+ const server = makeServer(app);
239
+ let secondary = null;
240
+
241
+ server.on('listening', () => {
242
+ actualPort = server.address().port;
243
+ if (!EXPOSED) {
244
+ const otherFamily = BIND_HOST.includes(':') ? '127.0.0.1' : '::1';
245
+ try {
246
+ secondary = makeServer(app);
247
+ secondary.on('error', () => {}); // that family may not exist on this host
248
+ secondary.listen({ host: otherFamily, port: actualPort, ipv6Only: otherFamily === '::1' });
249
+ } catch { /* best effort */ }
250
+ }
251
+ if (onReady) onReady(actualPort);
252
+ });
253
+ server.on('close', () => { try { if (secondary) secondary.close(); } catch { /* already gone */ } });
254
+
255
+ server.listen(port, BIND_HOST);
256
+ return server;
257
+ }
258
+
259
+ function exposureWarning() {
260
+ if (!EXPOSED) return null;
261
+ return `WARNING: listening on ${BIND_HOST} - reachable from your network, with no authentication.`;
262
+ }
263
+
264
+ return { BIND_HOST, ALLOWED_HOSTS, hostGuard, originGuard, frameGuard, listenLoopback, exposureWarning };
265
+ }
266
+
267
+ module.exports = { createNetGuard, parseHostHeader, isLoopbackAddress };
package/package.json CHANGED
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "claude-code-cost",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "Cost dashboard for Claude Code usage",
5
5
  "main": "server.js",
6
6
  "bin": {
7
- "claude-code-cost": "./server.js"
7
+ "claude-code-cost": "server.js"
8
8
  },
9
9
  "scripts": {
10
10
  "start": "node server.js",
11
11
  "dev": "node server.js --open",
12
- "prepare": "husky || true"
12
+ "prepare": "husky || true",
13
+ "test": "node --test test/*.test.js"
13
14
  },
14
15
  "engines": {
15
16
  "node": ">=20.0.0"
@@ -43,6 +44,7 @@
43
44
  "license": "MIT",
44
45
  "files": [
45
46
  "server.js",
47
+ "lib/",
46
48
  "public/",
47
49
  "README.md",
48
50
  "LICENSE"
package/public/app.js CHANGED
@@ -33,10 +33,27 @@ let navCounter = 0;
33
33
 
34
34
  // #region UTILS
35
35
 
36
+ // The div.textContent -> innerHTML trick escapes only & < > : innerHTML serializes
37
+ // for *text* context, where quotes are correctly left raw. That made every
38
+ // attribute interpolation breakable with a bare " . It cannot be patched, so the
39
+ // escaping is explicit here.
40
+ const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '`': '&#96;' };
41
+
36
42
  function esc(str) {
37
- const d = document.createElement('div');
38
- d.textContent = str;
39
- return d.innerHTML;
43
+ if (str == null) return '';
44
+ return String(str).replace(/[&<>"'`]/g, (c) => HTML_ESCAPES[c]);
45
+ }
46
+
47
+ // For a value landing inside a quoted JS string inside an HTML attribute —
48
+ // onclick="fn('${escAttrJs(x)}')". The browser HTML-decodes the attribute before
49
+ // the JS parser sees it, so the JS escape must happen first and be escaped in turn.
50
+ function escAttrJs(value) {
51
+ const js = String(value == null ? '' : value)
52
+ .replace(/\\/g, '\\\\')
53
+ .replace(/'/g, "\\'")
54
+ .replace(/\r/g, '\\r')
55
+ .replace(/\n/g, '\\n');
56
+ return esc(js);
40
57
  }
41
58
 
42
59
  function formatCost(usd) {
@@ -459,7 +476,7 @@ function renderOverview() {
459
476
  .sort((a, b) => sortCompare(a, b, viewSort.overview.field, viewSort.overview.order))
460
477
  .map(
461
478
  (p) => `
462
- <tr data-clickable onclick="navigateToSessions('${esc(p.encodedPath)}', '${esc(p.name)}')">
479
+ <tr data-clickable onclick="navigateToSessions('${escAttrJs(p.encodedPath)}', '${escAttrJs(p.name)}')">
463
480
  <td>${esc(p.name)}</td>
464
481
  <td class="cost-cell">${formatCost(p.totalCost)}</td>
465
482
  <td>${p.sessionCount}</td>
@@ -529,7 +546,7 @@ function renderProjects() {
529
546
  ${sorted
530
547
  .map(
531
548
  (p) => `
532
- <tr data-clickable onclick="navigateToSessions('${esc(p.encodedPath)}', '${esc(p.name)}')">
549
+ <tr data-clickable onclick="navigateToSessions('${escAttrJs(p.encodedPath)}', '${escAttrJs(p.name)}')">
533
550
  <td>${esc(p.name)}</td>
534
551
  <td class="cost-cell">${formatCost(p.totalCost)}</td>
535
552
  <td>${p.sessionCount}</td>
@@ -609,7 +626,7 @@ function renderSessions() {
609
626
  .sort((a, b) => sortCompare(a, b, viewSort.sessions.field, viewSort.sessions.order))
610
627
  .map(
611
628
  (s) => `
612
- <tr data-clickable onclick="navigateToDetail('${esc(s.sessionId)}')">
629
+ <tr data-clickable onclick="navigateToDetail('${escAttrJs(s.sessionId)}')">
613
630
  <td class="truncate" title="${esc(s.customTitle || s.firstPrompt || s.sessionId)}">${esc(s.customTitle || s.firstPrompt || s.sessionId)}</td>
614
631
  <td class="cost-cell">${formatCost(s.totalCost)}</td>
615
632
  <td>${formatTokens(s.totalTokens)}</td>
@@ -652,7 +669,7 @@ function renderDetail() {
652
669
  <div class="breadcrumb">
653
670
  ${parentBreadcrumb()}
654
671
  <span class="sep">/</span>
655
- <a onclick="navigateToSessions('${esc(d.encodedProjectPath)}', '${esc(d.projectPath)}')">${esc(d.projectPath)}</a>
672
+ <a onclick="navigateToSessions('${escAttrJs(d.encodedProjectPath)}', '${escAttrJs(d.projectPath)}')">${esc(d.projectPath)}</a>
656
673
  <span class="sep">/</span>
657
674
  <span class="current">${esc(d.customTitle || d.firstPrompt || d.sessionId)}</span>
658
675
  </div>
@@ -1551,7 +1568,7 @@ async function refreshIfStale() {
1551
1568
  document.addEventListener('keydown', (e) => {
1552
1569
  const fwd = (key) => {
1553
1570
  e.preventDefault();
1554
- window.parent?.postMessage({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey }, '*');
1571
+ hubPost({ type: 'hub:keydown', key, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey });
1555
1572
  };
1556
1573
  if (e.ctrlKey && e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
1557
1574
  fwd(e.key);
@@ -1569,9 +1586,16 @@ async function refreshIfStale() {
1569
1586
  // Hoisted out of initHubTheme so initHubProject can share it.
1570
1587
  const hubOrigin = () => (window.__HUB__?.url ? new URL(window.__HUB__.url).origin : null);
1571
1588
 
1589
+ // Every send is addressed to the hub explicitly. With targetOrigin '*' any page that
1590
+ // framed this app also received the forwarded keystrokes and navigation intents.
1591
+ function hubPost(message) {
1592
+ const origin = hubOrigin();
1593
+ if (origin) window.parent?.postMessage(message, origin);
1594
+ }
1595
+
1572
1596
  window.hubNavigate = function hubNavigate(app, url) {
1573
1597
  if (!window.__HUB__?.enabled) return;
1574
- window.parent?.postMessage({ type: 'hub:navigate', app, url }, '*');
1598
+ hubPost({ type: 'hub:navigate', app, url });
1575
1599
  };
1576
1600
 
1577
1601
  (function initHubTheme() {
@@ -1599,8 +1623,7 @@ window.hubNavigate = function hubNavigate(app, url) {
1599
1623
  if (t === lastTheme && ct === lastColorTheme) return;
1600
1624
  lastTheme = t;
1601
1625
  lastColorTheme = ct;
1602
- const origin = hubOrigin();
1603
- if (origin) window.parent.postMessage({ type: 'hub:theme', theme: t, colorTheme: ct }, origin);
1626
+ hubPost({ type: 'hub:theme', theme: t, colorTheme: ct });
1604
1627
  }).observe(document.body, {
1605
1628
  attributes: true,
1606
1629
  attributeFilter: ['class', 'data-color-theme'],
package/server.js CHANGED
@@ -7,6 +7,7 @@ const fs = require('fs');
7
7
  const { createReadStream } = require('fs');
8
8
  const { createInterface } = require('readline');
9
9
  const os = require('os');
10
+ const { createNetGuard } = require('./lib/net-guard');
10
11
 
11
12
  // #region CLI_ARGS
12
13
 
@@ -780,6 +781,13 @@ async function getSessionDetailData(sessionId) {
780
781
  // #region EXPRESS
781
782
 
782
783
  const app = express();
784
+
785
+ // Mounted before express.json() so a rejected request never buffers a body.
786
+ const net = createNetGuard({ appName: 'Claude Code Cost Dashboard' });
787
+ app.use(net.hostGuard);
788
+ app.use(net.frameGuard);
789
+ app.use(net.originGuard);
790
+
783
791
  app.use(express.json());
784
792
  app.use(express.static(path.join(__dirname, 'public')));
785
793
 
@@ -878,25 +886,22 @@ app.post('/api/refresh', (_req, res) => {
878
886
 
879
887
  // #region STARTUP
880
888
 
881
- const server = app.listen(PORT, () => {
882
- const actualPort = server.address().port;
889
+ const onReady = (actualPort) => {
883
890
  console.log(`Claude Code Cost Dashboard running at http://localhost:${actualPort}`);
891
+ const warning = net.exposureWarning();
892
+ if (warning) console.log(warning);
884
893
 
885
894
  if (process.argv.includes('--open')) {
886
895
  import('open').then(mod => mod.default(`http://localhost:${actualPort}`));
887
896
  }
888
- });
897
+ };
898
+
899
+ const server = net.listenLoopback(app, PORT, onReady);
889
900
 
890
901
  server.on('error', (err) => {
891
902
  if (err.code === 'EADDRINUSE') {
892
903
  console.log(`Port ${PORT} in use, trying random port...`);
893
- const fallback = app.listen(0, () => {
894
- const p = fallback.address().port;
895
- console.log(`Claude Code Cost Dashboard running at http://localhost:${p}`);
896
- if (process.argv.includes('--open')) {
897
- import('open').then(mod => mod.default(`http://localhost:${p}`));
898
- }
899
- });
904
+ net.listenLoopback(app, 0, onReady);
900
905
  } else {
901
906
  throw err;
902
907
  }