Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion apps/server/src/engine/finance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,19 @@ export function analyzeSpending(csv: string) {
cell += '"';
i++;
} else if (!quoted && cell.length) throw new Error("Invalid quoted CSV field");
else quoted = !quoted;
else {
quoted = !quoted;
if (!quoted) {
const next = csv[i + 1];
if (
next !== undefined &&
next !== "," &&
next !== "\n" &&
!(next === "\r" && (csv[i + 2] === "\n" || csv[i + 2] === undefined))
)
throw new Error("Invalid quoted CSV field");
}
}
} else if (!quoted && (c === "," || c === "\n" || c === undefined)) {
row.push(cell.replace(/\r$/, ""));
cell = "";
Expand Down
32 changes: 32 additions & 0 deletions tests/finance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { analyzeSpending } from "../apps/server/src/engine/finance.ts";

test("transaction imports reject characters after a closing CSV quote", () => {
for (const amount of ['"10"0', '""10', '"10".00', '"10" ']) {
assert.throws(
() => analyzeSpending(`date,description,amount,category\n2026-09-01,Coffee,${amount},Food`),
/Invalid quoted CSV field/,
`must not silently interpret ${amount} as a transaction amount`,
);
}
assert.throws(
() => analyzeSpending('date,description,amount,category\n2026-09-01,"Coffee"shop,10,Food'),
/Invalid quoted CSV field/,
);
});

test("transaction imports preserve valid quoted fields at CSV boundaries", () => {
for (const ending of ["", "\n", "\r\n", "\r"]) {
const report = analyzeSpending(
'"date","description","amount","category"\r\n' +
'"2026-09-01","Coffee, ""local""\nshop","10.10","Food"\r\n' +
`"2026-09-02","","20.20",""${ending}`,
);
assert.equal(report.count, 2);
assert.equal(report.spending, 30.3);
assert.equal(report.transactions[0].description, 'Coffee, "local"\nshop');
assert.equal(report.transactions[1].description, "");
assert.equal(report.transactions[1].category, "Uncategorized");
}
});
Loading