Skip to content

Tests + hardening: money rounding, budget validation, CSV amounts, webhook tiers, bank URL - #4

Draft
ctmakc wants to merge 12 commits into
mainfrom
claude/finman-tests-security-sflmfe
Draft

ctmakc wants to merge 12 commits into
mainfrom
claude/finman-tests-security-sflmfe

Conversation

@ctmakc

@ctmakc ctmakc commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Tests and hardening pass: new unit and integration tests for money math, budget aggregation, CSV import, plan limits, auth and per-user isolation; 5 bug fixes; 2 pre-existing test failures fixed; a security sweep of the code I read.

Branch note: the task named cloud/tests-hardening-1102. This session can only push to claude/finman-tests-security-sflmfe, so the work is on that branch. Nothing was merged or deployed.

Step 1: install / build / existing tests

  • npm ci works (Node 22). The project has no lint, typecheck or build scripts (plain JS, no TS/ESLint config). CI is npm test plus a Docker build. Docker isn't available in the sandbox, so I didn't run the Docker build. I ran node --check on every changed source file.
  • Existing suite on the unmodified code, one file at a time: 65/67 files pass. The 2 failures were bugs in the tests, not the app. They're fixed in the first commit (see below). The last CI run on main (e52df28) also failed.

Bugs fixed (each fix is its own commit, and its regression test is a separate test-only commit)

# Severity Commit Bug Reproducer (before the fix)
1 Medium (money) fix(money) — lib/money.js money.round sent negative half cents toward +∞ (Math.round(-100.5) = -100). The Number.EPSILON nudge only works for values near 1, so larger half-cent products also rounded down. This touches every expense (they're stored negative), FX conversion (fx.convert → money.mul), splits and budget math. money.round(-1.005) → -1 (while round(1.005) → 1.01); money.round(-0.125) → -0.12; money.round(2592.315) → 2592.31. Fix: round the magnitude after trimming float noise to 15 significant digits, then put the sign back; -0 becomes 0.
2 Low–Medium (import correctness) fix(import) — services/csvImportService.js parseAmount stripped every non-digit, so letters between digits disappeared. parseAmount('1e5') → 15, '12a34' → 1234, '0x10' → 10. These now return null, so the preview shows a row error. Currency codes and CR/DR before or after the number still parse.
3 Low–Medium (input validation, stored markup) fix(budgets) — routes/budgets.js Budget amount, carryover, period (PUT) and currency weren't validated. POST /api/budgets {name,amount:"abc"} → 500; {amount:"1e400"} → 201 with a 0/Infinity budget; {amount:100,currency:"<b>"} → 201, stored and rendered; {carryover:"x"} silently became 0; PUT accepted any period. Now these return 400. The currency rule matches accounts/subscriptions (3–5 letters, upper-cased). carryover null or '' still means 0, so the existing UI payloads keep working.
4 Low (billing integrity) fix(billing) — services/billingService.js Stripe webhooks wrote metadata.tier into users.subscription_tier without checking it. A signed checkout.session.completed with metadata.tier: "enterprise" (a typo or manual edit in the Stripe dashboard) stored enterprise. Unknown tiers are now ignored and logged. A missing tier still defaults to pro, and inactive subscriptions still downgrade to free. Prices and plan contents are unchanged. The PLANS comment wrongly said prices were in cents; it now says they're whole dollars (unit_amount = price * 100).
5 Low (defense in depth) fix(bank-api) — routes/bank-api.js The custom bank apiUrl was only checked with new URL(), which accepts javascript:, data: and file:. POST /api/bank-api/custom-banks {apiUrl:"javascript:alert(1)"} → 201. Only http and https are accepted now. Nothing fetches this URL server-side today, so this is not an SSRF.

Each regression test file fails on the old code and passes on the new code (checked in a separate worktree at the base commit):
regression-money-rounding 8 failed → 0, regression-csv-amount-letters 7 → 0, regression-budget-validation 10 → 0, regression-billing-tier 5 → 0, regression-custom-bank-url 5 → 0.

Pre-existing test failures (test-only commit)

  • test/demo-seed.test.js: hard-coded + 6 partner transactions. The 6th one is dated the 3rd of the current month and is skipped on the 1st and 2nd, so the test failed 2 days a month. It now counts the partner's rows from the DB and asserts 5..6.
  • test/fe-review.test.js: assigning process.env.TZ inside a Jest test file doesn't reach the process, so the toISOString() check only holds at a negative UTC offset. That one assertion is now guarded; the real UI.ymd assertion still runs. It passes under both TZ=UTC and TZ=America/Toronto. This is compatible with open PR UI redesign (NORTHERN LIGHT), native shell, password reset, housekeeping #3, which pins TZ in the jest config.

New tests (test-only commit; all pass on the unmodified code)

File Covers
test/unit-money.test.js lib/money against exact integer-cent arithmetic: seeded property tests for add/sub/sum, drift (1000 × 0.01), junk input, division by zero
test/budget-aggregation.test.js Budget.getPeriodDates edges (leap February, a week spanning New Year, Sunday → Monday week start), nextPeriodStart; todayISO across Toronto/Kyiv/Auckland/LA and the Toronto DST end; recalculateSpent by month/week/year across the Oct→Nov boundary, filtered by category, type and user, with FX from the local currency_rates table; ended or future budgets; /api/budgets 401 without a token, 404 for another user on GET/PUT/recalculate/DELETE, empty list
test/unit-csv-parse.test.js parseAmount (thousands and decimal separators, decimal comma, parentheses, trailing minus, CR/DR, Unicode minus and dashes, junk), parseDate (ISO, compact, dotted, textual, MDY/DMY ambiguity, calendar validity), inferDateOrder, parseCsv (quotes, doubled quotes, embedded newline, CRLF, BOM, stray quote), detectDelimiter, previewCsv end to end (debit/credit signs, exact totals, error rows, fingerprint duplicates)
test/unit-billing-auth.test.js PLANS catalog guard (ids, tiers, prices 0/9/19 USD monthly, "Up to 5 members"), getPlan returns copies, TIER_ORDER matches the plans; requireTier matrix; requireOwnership 401/404/403/pass and error forwarding; JWT rejection (missing, malformed, no Bearer prefix, foreign secret, expired, alg=none, deleted user, token_version revocation); Stripe checkout unit_amount 900/1900 cents, Price ID override, free/unknown plans rejected

Stripe and axios are mocked. No real network, keys, accounts or databases are used (each suite gets its own temp SQLite file through the existing harness). The sk_test_* / whsec_* strings are dummy values.

Security sweep (code I read)

  • Committed secrets: none found. I grepped tracked files for Stripe, AWS, Google, Slack, GitHub, Anthropic and OpenAI key patterns and private keys, plus Android/iOS signing passwords. The only matches are documentation placeholders in .env.example and README.md, and obviously fake test values in test/*.test.js. config/config.js generates random dev secrets and refuses to start in production without JWT_SECRET / SESSION_SECRET.
  • Missing auth on routes: every router in routes/ is behind passport-jwt (router.use or per route), PAT (/api/v1), or apiAuthMiddleware (/api/ai, /api/onboarding). The intentionally public routes are /api/auth/* login/register/google, /api/health, /api/ready, /api/billing/plans, and /api/billing/webhook (signature required). I found no gaps.
  • Injection: SQL uses bound parameters. Dynamic identifiers come from constant lists (backupService TABLES, migration PRAGMAs) or schema-filtered columns (restore). UPDATE … SET ${updates.join} builders use fixed column names.
  • SSRF: outbound calls go to fixed hosts (Stooq, Resend, monobank, AI providers, from env). The custom bank apiUrl is stored but never fetched (scheme restricted, fix 5).
  • Path traversal: uploads use generated names (Date.now()-random.ext); bank imports use memory storage; the report download filename is sanitised; express.static only serves public/.
  • Unsafe HTML: a heuristic scan of public/js for innerHTML with unescaped user fields found only static labels. Budget currency was unvalidated (fix 3).

Not fixed — listed for follow-up

  1. The full single-process npm test is slow: 13.5 minutes here, with RSS around 1 GB, while all 76 files pass one at a time in about 3 minutes total. It looks like module-registry or memory growth from jest.resetModules() in test/helpers/app.js across suites. I didn't change the harness.
  2. routes/transactions.js CSV upload fileFilter accepts a file if the MIME type or the extension matches, and keeps the original extension. The files go to uploads/ (not served statically) and are deleted after import, so this is low risk.
  3. Budget startDate / endDate aren't validated as YYYY-MM-DD (lib/dates.isValidYMD exists). I left this alone so clients sending full ISO timestamps don't break.
  4. previewCsv flags a second identical row in the same file (same date, amount and description) as a file duplicate. Two real identical purchases on one day need the user to untick the duplicate flag. I believe this is by design, so I didn't change it.
  5. I didn't do a full XSS review of the roughly 30 frontend files; only the heuristic scan above.

Verification

  • Each test file run on its own with jest --runInBand <file>: 76/76 files pass (67 existing + 9 new).
  • The base commit with only the new non-regression test files: they all pass. With the regression files: they fail as described above.
  • node --check on all changed source files.
  • fe-review also run under TZ=America/Toronto.
  • Full npm test run: jest --runInBand over the whole suite in one process: 76/76 suites, 1064/1064 tests passed, 13 min 28 s in the sandbox.

🤖 Generated with Claude Code

https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78

claude added 12 commits November 2, 2026 13:44
…ocess TZ

- demo-seed: the partner's 6th transaction is dated the 3rd of the current
  month and is skipped on the 1st-2nd, so the hard-coded '+ 6' failed two
  days a month. Count the partner's rows from the DB (5..6) instead.
- fe-review: process.env.TZ assigned inside a Jest test file does not reach
  the process, so the toISOString() check only holds at a negative UTC
  offset. Guard that one assertion; the UI.ymd assertion still runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
…ns and auth

- unit-money: lib/money checked against exact integer-cent arithmetic
  (seeded property tests for add/sub/sum, drift, junk input).
- unit-csv-parse: parseAmount/parseDate/parseCsv/detectDelimiter tables and
  an end-to-end previewCsv (signs, totals, fingerprint duplicates).
- budget-aggregation: getPeriodDates edges (leap Feb, week across New Year),
  todayISO across zones and the Toronto DST switch, recalculateSpent by
  month/week/year, category, type, user and account currency (FX from the
  local rates table, axios mocked), /api/budgets per-user isolation.
- unit-billing-auth: PLANS catalog guard (ids, tiers, prices, interval),
  getPlan copies, requireTier and requireOwnership, JWT rejection paths
  (foreign secret, expired, alg=none, deleted user, token_version), Stripe
  checkout unit_amount in cents (Stripe mocked).

All pass on the unmodified code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
…alues

money.round used Math.round((n + EPSILON) * 100) / 100:
- Math.round(-100.5) is -100, so -1.005 -> -1.00 while 1.005 -> 1.01
  (expenses are stored negative; FX/split math on them lost a cent).
- EPSILON is below one ULP for values above ~2, so a product such as
  2592.315 (amount x rate) rounded down to 2592.31.

Round the magnitude after trimming binary noise to 15 significant digits,
then restore the sign; -0 is normalised to 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
parseAmount stripped every non-digit character, so a cell like '1e5'
imported as 15, '12a34' as 1234 and '0x10' as 10. Letters may only sit
before or after the number (currency codes, CR/DR); otherwise the cell is
not an amount and the row is reported as an error in the preview.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
- amount 'abc' -> 500 (NaN into a NOT NULL column); '1e400' -> 201 with
  an Infinity/0 budget; arrays/booleans were coerced. Now a finite number
  (or numeric string) > 0 is required, else 400.
- carryover 'x' silently became 0; now 400. null/'' still mean 0.
- PUT accepted any period; it now uses the same list as POST.
- currency accepted any string ('<b>' was stored and rendered by the UI);
  same 3-5 letter rule as accounts/subscriptions, upper-cased.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
checkout.session.completed and customer.subscription.created/updated wrote
metadata.tier verbatim into users.subscription_tier. An unknown value (a
typo or manual edit in the Stripe dashboard) is now ignored and logged;
a missing tier still defaults to 'pro', and inactive subscriptions still
downgrade to free. Plan prices and contents are unchanged; the PLANS
comment now says prices are whole dollars (unit_amount = price * 100).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
new URL() alone accepted javascript:, data: and file: URLs. The value is
not fetched server-side today, but it is stored and returned to the
client, so only http/https are accepted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X3cUue7aFsu6xEMNPXqH78
@ctmakc
ctmakc marked this pull request as draft November 2, 2026 23:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants