diff --git a/pm-stack/aggregator/scripts/confirm-charges-surfaced.ts b/pm-stack/aggregator/scripts/confirm-charges-surfaced.ts index 7b97afd0f3..419298e11e 100644 --- a/pm-stack/aggregator/scripts/confirm-charges-surfaced.ts +++ b/pm-stack/aggregator/scripts/confirm-charges-surfaced.ts @@ -5,16 +5,41 @@ import { readFile, rename, unlink, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { join } from "node:path"; import { unmatchedKey } from "../src/charges-collect.ts"; +import type { UnmatchedCharge } from "../src/charges-match.ts"; +import { isFiniteNumber, isRecord } from "../src/validate.ts"; const feedPath = process.argv[2]; if (!feedPath) throw new Error("usage: confirm-charges-surfaced.ts "); const statePath = process.env.CHARGES_SURFACED_STATE_PATH ?? join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/charges-surfaced-state.json"); -const feed = JSON.parse(await readFile(feedPath, "utf8")); +const feed: unknown = JSON.parse(await readFile(feedPath, "utf8")); +// The feed arrives from disk after delivery, so it is untrusted input: +// a non-object top level (null, array, string, number) is an invalid +// feed, not something to dereference blindly or silently accept +// (#3681). +if (!isRecord(feed)) throw new Error("invalid feed: expected a JSON object"); if (feed.chargesAttention !== undefined && !Array.isArray(feed.chargesAttention)) throw new Error("invalid chargesAttention"); -const attention = feed.chargesAttention ?? []; +// An element is confirmable only when a surfaced key can actually be +// built from it: unmatchedKey needs a string normalized, a finite +// numeric amountUsd, and a string at. Anything else is dropped loudly +// instead of crashing confirmation (which would re-alert every +// already-delivered charge forever) or persisting a bogus +// "undefined|…" key (#3681). +type ConfirmableCharge = Pick; +function isConfirmableCharge(v: unknown): v is ConfirmableCharge { + if (!isRecord(v)) return false; + return typeof v.normalized === "string" && isFiniteNumber(v.amountUsd) && typeof v.at === "string"; +} +const attention: ConfirmableCharge[] = []; +let dropped = 0; +for (const element of feed.chargesAttention ?? []) { + if (isConfirmableCharge(element)) attention.push(element); + else dropped += 1; +} +if (dropped > 0) + console.error(`confirm-charges-surfaced: dropped ${dropped} malformed chargesAttention element(s)`); if (attention.length) { let state: { surfaced?: unknown } = {}; try { diff --git a/pm-stack/aggregator/src/charges-collect.ts b/pm-stack/aggregator/src/charges-collect.ts index c8d0dd35cb..3514a07a43 100644 --- a/pm-stack/aggregator/src/charges-collect.ts +++ b/pm-stack/aggregator/src/charges-collect.ts @@ -116,7 +116,7 @@ export function mergeChargeRows(autoRows: ChargeRow[], handFedRows: ChargeRow[]) } /** Stable identity of one unmatched charge for the surfaced-once state. */ -export function unmatchedKey(u: UnmatchedCharge): string { +export function unmatchedKey(u: Pick): string { return `${u.normalized}|${u.amountUsd.toFixed(2)}|${u.at}`; } diff --git a/pm-stack/aggregator/test/confirm-charges-surfaced-3681.test.ts b/pm-stack/aggregator/test/confirm-charges-surfaced-3681.test.ts new file mode 100644 index 0000000000..3c3c71990e --- /dev/null +++ b/pm-stack/aggregator/test/confirm-charges-surfaced-3681.test.ts @@ -0,0 +1,88 @@ +import { test, expect } from "bun:test"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// #3681: confirm-charges-surfaced.ts runs AFTER delivery, so a malformed +// chargesAttention element must never crash confirmation (delivered +// charges would re-alert forever) or persist a bogus key. Each case runs +// the real script as a subprocess against an isolated surfaced-state +// path, exactly like push-fleet-feed.sh invokes it. +const script = join(import.meta.dir, "../scripts/confirm-charges-surfaced.ts"); +const valid = { normalized: "acmeai", amountUsd: 12.5, at: "2026-10-30" }; +const validKey = "acmeai|12.50|2026-10-30"; + +async function runConfirm(feed: unknown) { + const dir = await mkdtemp(join(tmpdir(), "confirm-surfaced-3681-")); + const feedPath = join(dir, "feed.json"); + const statePath = join(dir, "state.json"); + try { + await writeFile(feedPath, typeof feed === "string" ? feed : JSON.stringify(feed)); + const proc = Bun.spawn([process.execPath, script, feedPath], { + env: { ...process.env, CHARGES_SURFACED_STATE_PATH: statePath }, + stdout: "pipe", + stderr: "pipe", + }); + const stderr = await new Response(proc.stderr).text(); + const code = await proc.exited; + let surfaced: string[] | null = null; + try { + surfaced = JSON.parse(await readFile(statePath, "utf8")).surfaced; + } catch { + surfaced = null; // no state file written + } + return { code, stderr, surfaced }; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +test("valid control: well-formed feed confirms exactly as before", async () => { + const r = await runConfirm({ chargesAttention: [valid] }); + expect(r.code).toBe(0); + expect(r.surfaced).toEqual([validKey]); +}, 30_000); + +test("null element: dropped loudly, no crash, no key persisted", async () => { + const r = await runConfirm({ chargesAttention: [null] }); + expect(r.code).toBe(0); + expect(r.stderr).toContain("dropped 1 malformed"); + expect(r.surfaced ?? []).toEqual([]); +}, 30_000); + +test("string amount: dropped loudly, no key persisted", async () => { + const r = await runConfirm({ chargesAttention: [{ ...valid, amountUsd: "12.50" }] }); + expect(r.code).toBe(0); + expect(r.stderr).toContain("dropped 1 malformed"); + expect(r.surfaced ?? []).toEqual([]); +}, 30_000); + +test("mixed valid + invalid: the valid sibling is still confirmed", async () => { + const r = await runConfirm({ chargesAttention: [valid, null] }); + expect(r.code).toBe(0); + expect(r.stderr).toContain("dropped 1 malformed"); + expect(r.surfaced).toEqual([validKey]); +}, 30_000); + +test("top-level null: clear invalid-feed error, never a raw TypeError", async () => { + const r = await runConfirm("null"); + expect(r.code).not.toBe(0); + expect(r.stderr).toContain("invalid feed"); + expect(r.stderr).not.toContain("TypeError"); +}, 30_000); + +test("top-level array: rejected instead of silently succeeding", async () => { + const r = await runConfirm([]); + expect(r.code).not.toBe(0); + expect(r.stderr).toContain("invalid feed"); + expect(r.stderr).not.toContain("TypeError"); +}, 30_000); + +test("missing normalized: dropped, and no undefined|… key can enter state", async () => { + const { normalized: _omit, ...noNormalized } = valid; + const r = await runConfirm({ chargesAttention: [noNormalized] }); + expect(r.code).toBe(0); + expect(r.stderr).toContain("dropped 1 malformed"); + expect(r.surfaced ?? []).toEqual([]); + expect((r.surfaced ?? []).some((k) => k.startsWith("undefined|"))).toBe(false); +}, 30_000);