@sayknow-cli/stats 0.7.10 → 0.7.12

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/stats",
4
- "version": "0.7.10",
4
+ "version": "0.7.12",
5
5
  "description": "Local observability dashboard for pi AI usage statistics",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -38,8 +38,8 @@
38
38
  "fmt": "biome format --write ."
39
39
  },
40
40
  "dependencies": {
41
- "@sayknow-cli/ai": "0.7.10",
42
- "@sayknow-cli/utils": "0.7.10",
41
+ "@sayknow-cli/ai": "0.7.12",
42
+ "@sayknow-cli/utils": "0.7.12",
43
43
  "@tailwindcss/node": "^4.2.4",
44
44
  "chart.js": "^4.5.1",
45
45
  "date-fns": "^4.1.0",
@@ -228,16 +228,18 @@ export function buildTopNByModelSeries<T extends ModelKeyedPoint, B>(
228
228
  const hasOther = points.some(p => !topKeys.has(`${p.model}::${p.provider}`));
229
229
  if (hasOther) seriesNames.push("Other");
230
230
 
231
- const dayMap = new Map<number, Record<string, B>>();
232
- for (const day of allDays) dayMap.set(day, {});
231
+ // Model labels are attacker-controlled strings. A plain object would treat
232
+ // "__proto__" as the inherited prototype and mutate Object.prototype.
233
+ const dayMap = new Map<number, Map<string, B>>();
234
+ for (const day of allDays) dayMap.set(day, new Map());
233
235
  for (const point of points) {
234
236
  const key = `${point.model}::${point.provider}`;
235
237
  const label = topKeys.has(key) ? (labelByKey.get(key) ?? point.model) : "Other";
236
238
  const row = dayMap.get(point.timestamp);
237
239
  if (!row) continue;
238
- const bucket = row[label] ?? initBucket();
240
+ const bucket = row.get(label) ?? initBucket();
239
241
  accumulate(bucket, point);
240
- row[label] = bucket;
242
+ row.set(label, bucket);
241
243
  }
242
244
 
243
245
  return {
@@ -245,7 +247,7 @@ export function buildTopNByModelSeries<T extends ModelKeyedPoint, B>(
245
247
  datasets: seriesNames.map(name => ({
246
248
  label: name,
247
249
  data: allDays.map(day => {
248
- const bucket = dayMap.get(day)?.[name];
250
+ const bucket = dayMap.get(day)?.get(name);
249
251
  return bucket ? bucketToValue(bucket) : 0;
250
252
  }),
251
253
  })),
package/src/index.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  import { parseArgs } from "node:util";
4
- import { formatDuration, formatNumber, formatPercent } from "@sayknow-cli/utils";
4
+ import { formatDuration, formatNumber, formatPercent, sanitizeDisplayLine } from "@sayknow-cli/utils";
5
5
  import { getDashboardStats, getTotalMessageCount, syncAllSessions } from "./aggregator";
6
6
  import { closeDb } from "./db";
7
7
  import { startServer } from "./server";
@@ -68,7 +68,7 @@ async function printStats(): Promise<void> {
68
68
  console.log("\nBy Model:");
69
69
  for (const m of byModel.slice(0, 10)) {
70
70
  console.log(
71
- ` ${m.model}: ${formatNumber(m.totalRequests)} reqs, ${formatCost(m.totalCost)}, ${formatPercent(m.cacheRate)} cache`,
71
+ ` ${sanitizeDisplayLine(m.model)}: ${formatNumber(m.totalRequests)} reqs, ${formatCost(m.totalCost)}, ${formatPercent(m.cacheRate)} cache`,
72
72
  );
73
73
  }
74
74
  }
@@ -76,7 +76,9 @@ async function printStats(): Promise<void> {
76
76
  if (byFolder.length > 0) {
77
77
  console.log("\nBy Folder:");
78
78
  for (const f of byFolder.slice(0, 10)) {
79
- console.log(` ${f.folder}: ${formatNumber(f.totalRequests)} reqs, ${formatCost(f.totalCost)}`);
79
+ console.log(
80
+ ` ${sanitizeDisplayLine(f.folder)}: ${formatNumber(f.totalRequests)} reqs, ${formatCost(f.totalCost)}`,
81
+ );
80
82
  }
81
83
  }
82
84
 
package/src/server.ts CHANGED
@@ -167,14 +167,16 @@ async function handleApi(req: Request, context: ApiContext): Promise<Response> {
167
167
  }
168
168
 
169
169
  if (path === "/api/stats/recent") {
170
- const limit = url.searchParams.get("limit");
171
- const stats = await getRecentRequests(limit ? parseInt(limit, 10) : undefined);
170
+ const limit = parseLimitParam(url.searchParams.get("limit"));
171
+ if (limit === null) return badRequest();
172
+ const stats = await getRecentRequests(limit);
172
173
  return Response.json(stats);
173
174
  }
174
175
 
175
176
  if (path === "/api/stats/errors") {
176
- const limit = url.searchParams.get("limit");
177
- const stats = await getRecentErrors(limit ? parseInt(limit, 10) : undefined);
177
+ const limit = parseLimitParam(url.searchParams.get("limit"));
178
+ if (limit === null) return badRequest();
179
+ const stats = await getRecentErrors(limit);
178
180
  return Response.json(stats);
179
181
  }
180
182
 
@@ -194,9 +196,9 @@ async function handleApi(req: Request, context: ApiContext): Promise<Response> {
194
196
  }
195
197
 
196
198
  if (path.startsWith("/api/request/")) {
197
- const id = path.split("/").pop();
198
- if (!id) return new Response("Bad Request", { status: 400 });
199
- const details = await getRequestDetails(parseInt(id, 10));
199
+ const id = parseIntegerParam(path.slice("/api/request/".length));
200
+ if (id === null) return badRequest();
201
+ const details = await getRequestDetails(id);
200
202
  if (!details) return new Response("Not Found", { status: 404 });
201
203
  return Response.json(details);
202
204
  }
@@ -218,6 +220,25 @@ async function handleApi(req: Request, context: ApiContext): Promise<Response> {
218
220
  return new Response("Not Found", { status: 404 });
219
221
  }
220
222
 
223
+ /**
224
+ * A request parameter that must be a whole decimal number. `parseInt` alone
225
+ * accepts "1abc" and "-1", and SQLite rejects NaN with a datatype mismatch and
226
+ * treats a negative LIMIT as unlimited, so anything but plain digits is refused.
227
+ */
228
+ function parseIntegerParam(value: string): number | null {
229
+ if (!/^\d{1,15}$/.test(value)) return null;
230
+ return Number(value);
231
+ }
232
+
233
+ /** `?limit=`: absent keeps the query's own default; present must be a whole number. */
234
+ function parseLimitParam(value: string | null): number | undefined | null {
235
+ return value === null ? undefined : parseIntegerParam(value);
236
+ }
237
+
238
+ function badRequest(): Response {
239
+ return new Response("Bad Request", { status: 400 });
240
+ }
241
+
221
242
  function forbidden(): Response {
222
243
  return new Response("Forbidden", { status: 403 });
223
244
  }