budget-app / docs /code_review.md
elvigar
Claude Sonnet 5
fix: resolve code review findings — AI context bugs, buffer consistency, rate limiting
b58a128
|
Raw History Blame Contribute Delete
12.6 kB
# Code Review — Budget Blueprint
**Scope:** full repository (`src/`, config, and project root). There is no git repository
initialized here, so this review reads the whole tree as a single change rather than a diff.
**Method:** manual review of every source file + an automated high-effort pass, cross-checked
against the actual `node_modules/ai` and `node_modules/@ai-sdk/react` source to confirm library
behavior before reporting anything as a bug.
**Health check:** `tsc --noEmit` passes with zero errors; `eslint .` passes with a single
pre-existing warning (`button.tsx:58`, fast-refresh only-export-components). The code is
generally clean and well-organized — the issues below are specific and mostly isolated.
> **Status: Resolved (2026-08-11).** Every item in the action checklist (§4) has been addressed
> except §2.1 (rotate the `OLLAMA_API_KEY`), which requires action outside this codebase, and
> §2.3 (prompt-injection hardening), which was left as-is per the original low-severity note.
> Shared helpers for the recurring budget math now live in `src/lib/budget-math.ts`
> (`computeUnallocated`, `requiredMonthlyContribution`, `formatMoneyBySymbol`), a rate limiter
> lives in `src/lib/rate-limit.server.ts`, both have Vitest coverage (`bun run test`), and
> `bun run typecheck` was added alongside the existing `lint`/`format` scripts. The project root
> is now a git repository. The findings below are kept as-written for the historical record.
---
## 1. Correctness bugs
### 1.1 Adviser chat silently uses stale budget data after the first message (High)
**File:** `src/components/AdviserChat.tsx:42`
```ts
const transport = useMemo(
() => new DefaultChatTransport({ api: "/api/chat", prepareSendMessagesRequest: ... }),
[context],
);
const { messages, sendMessage, ... } = useChat({ transport, ... });
```
`useChat` (in `@ai-sdk/react`) stores its `Chat` instance in a `useRef` that is only replaced when
an explicit `chat` or `id` option changes:
```js
// node_modules/@ai-sdk/react/dist/index.js:179-185
const chatRef = useRef("chat" in options ? options.chat : new Chat(options));
const shouldRecreateChat =
("chat" in options && options.chat !== chatRef.current) ||
("id" in options && chatRef.current.id !== options.id);
```
Since `AdviserChat` passes neither `chat` nor `id`, `shouldRecreateChat` is always `false` after
mount. The `Chat` constructor sets `this.transport = transport` once
(`node_modules/ai/dist/index.js:9389`) and nothing ever reassigns it later. So even though the
`transport` `useMemo` recomputes on every render (because `context` is a fresh object literal
built by `index.tsx` each render), that new transport is discarded — `chatRef.current` keeps
using the transport (and the `context` closure inside it) captured at first mount.
**Failure scenario:** user opens the app, generates insights, asks the adviser a question
(mounting `AdviserChat` with context X), then edits an expense or adds a goal. The AI still
answers using the original context X — recommendations reference numbers that no longer match
the user's budget, with no indication anything is stale.
**Fix:** pass a `key`/`id` derived from the data that should invalidate the chat (e.g. re-mount
`AdviserChat` when `insights` changes, or pass an explicit `id` to `useChat` that changes when
`context` changes), or read `context` from a ref inside `prepareSendMessagesRequest` instead of
relying on `transport` identity.
### 1.2 `/api/chat` crashes for every message when the user picked a custom currency (High)
**File:** `src/routes/api/chat.ts:35-40`
```ts
const formatMoney = (n: number, currency = "EUR") =>
new Intl.NumberFormat("en-US", { style: "currency", currency, ... }).format(...);
```
`buildSystemPrompt` calls `formatMoney(ctx.income, cur)` unconditionally. `ctx.currency` is the
raw `currency` state from `index.tsx`, which is the literal string `"OTHER"`
(`OTHER_CURRENCY`) whenever the user selects "Other…" in the currency picker — the app never
sends the symbol/code the user actually typed, just the sentinel value. Confirmed reproduction:
```
$ new Intl.NumberFormat('en-US', {style:'currency', currency:'OTHER'})
RangeError: Invalid currency code : OTHER
```
This throws inside the unguarded `POST` handler, so every adviser-chat message fails for any user
on a custom currency. `formatCurrency` in `index.tsx` already special-cases
`isOtherCurrency` to avoid exactly this — the fix pattern already exists in the codebase, it just
wasn't applied here.
**Fix:** send `currencySymbol` (already computed client-side) through `AdviserChatContext`
instead of re-deriving formatting from `Intl.NumberFormat(currency)`, matching what
`budget-insights.functions.ts` and `pdf-report.ts` already do.
### 1.3 Reserved savings buffer is dropped from the PDF report, AI insights, and adviser chat (Medium)
**Files:** `src/lib/pdf-report.ts:388`, `src/lib/budget-insights.functions.ts:83`,
`src/routes/index.tsx` (`handleDownloadPdf` ~L831, `handleGenerateInsights` ~L851,
`AdviserChat` context ~L2021)
The main UI computes `unallocated = numericIncome - totalExpenses - reservedBuffer`
(`index.tsx:514`). But `reservedBuffer` is never included in the payload sent to
`generateBudgetInsights`, never included in `AdviserChatContext`, and `BudgetPdfInput` has no
`reservedBuffer` field at all — so `pdf-report.ts` and `budget-insights.functions.ts` both
compute `unallocated = income - totalExpenses`, ignoring any amount the user set aside via
"Keep as buffer."
**Failure scenario:** a user reserves $500 as a buffer. The on-screen summary shows a lower
"unallocated" figure than the downloaded PDF and the AI's insights/chat, and the AI may recommend
spending money the user has already earmarked as untouchable.
**Fix:** thread `reservedBuffer` through `insightsInputSchema`, `AdviserChatContext`, and
`BudgetPdfInput`, and subtract it consistently in all three places.
### 1.4 Over-funded goal produces a negative "required monthly contribution" in the AI prompt (Low)
**File:** `src/lib/budget-insights.functions.ts:116-119`
```ts
const remaining =
g.targetAmount -
(typeof g.currentProgress === "number" ? g.currentProgress : 0);
const monthly = remaining / g.months; // not clamped
```
If `currentProgress` exceeds `targetAmount` (goal already exceeded), `remaining` and `monthly`
go negative, producing a prompt line like `Required monthly contribution: $-100`, which the LLM
then has to reason over. The equivalent calculation is clamped with `Math.max(remaining / months, 0)`
in both `src/routes/index.tsx:2099` and `src/lib/pdf-report.ts:567` — this file is the one place
the clamp was left out.
**Fix:** apply the same `Math.max(..., 0)` clamp here for consistency.
### 1.5 A goal's "progress so far" of exactly 0 is silently dropped from the adviser chat's context (Low)
**File:** `src/routes/api/chat.ts:94`
```ts
if (g.currentProgress)
parts.push(`current progress ${formatMoney(g.currentProgress, cur)}`);
```
This is a truthy check, so a legitimate `currentProgress: 0` (user has saved nothing toward a
goal yet, but explicitly tracked it) is indistinguishable from "not provided" and gets omitted
from the system prompt. `budget-insights.functions.ts` and `pdf-report.ts` both correctly use
`typeof g.currentProgress === "number"`.
**Fix:** use the same `typeof ... === "number"` check here instead of a truthy check.
### Root cause behind 1.3–1.5
The budget math (unallocated total, goal monthly-contribution formula, currency formatting) is
implemented independently in four places — `index.tsx`, `budget-insights.functions.ts`,
`pdf-report.ts`, and `api/chat.ts` — with no shared helper. That's structurally why these three
small inconsistencies were able to exist without being caught: each surface reimplements the same
formula slightly differently. Extracting shared `computeUnallocated()` /
`requiredMonthlyContribution()` / currency-formatting helpers into `src/lib/` would prevent this
class of bug going forward.
---
## 2. Security & hardening
### 2.1 Real-looking API key committed to disk in plaintext `.env` (High — action needed now)
**File:** `.env:7` — `OLLAMA_API_KEY=...`
`.gitignore` correctly excludes `.env`, and there's no git repository tracking it locally, but the
key is sitting in plaintext in the project folder and has already been surfaced once in this
session's transcript. **Rotate/regenerate this credential** at whatever service issued it,
regardless of the other findings in this report.
### 2.2 `/api/chat` and `generateBudgetInsights` have no auth, no rate limiting, no cost cap (Medium)
**Files:** `src/routes/api/chat.ts`, `src/lib/budget-insights.functions.ts`
Both are public endpoints that call an LLM using server-held credentials (Lovable AI Gateway key,
or a self-hosted Ollama instance). There's no per-IP/session throttling. Anyone who discovers a
deployed URL can spam requests, running up AI Gateway usage or overloading the Ollama host.
Acceptable for local/personal use; needs basic rate limiting before any public deployment.
### 2.3 User-supplied text flows into LLM prompts unsanitized against prompt injection (Low)
**Files:** `src/routes/api/chat.ts`, `src/lib/budget-insights.functions.ts`
Expense labels, goal notes, and country are interpolated directly into the system prompt (goal
notes/labels are sanitized only for control characters, not for prompt-injection phrasing).
Impact is low here since the only "victim" of an injected instruction is the user's own AI
session (there's no cross-user data or privileged system access to leak), but worth keeping in
mind if this ever becomes multi-tenant or gains tool-calling.
---
## 3. Project hygiene
### 3.1 No git repository at the project root (Medium)
The project root is not a git repository, despite `AGENTS.md` documenting a Lovable git-sync
workflow and a `.gitignore` being present. If local changes are assumed to be
version-controlled/backed up, they currently are not.
### 3.2 Unrelated nested project mixed into this repo (Low)
`kanban/` is a fully separate cloned repository (`github.com/ed-donner/kanban`, its own `.git`,
its own `AGENTS.md`) for an unrelated course exercise, sitting inside the Budget Blueprint
project folder. If `git init` is ever run at the Budget App root, this becomes an
embedded/orphaned repo. Recommend moving it to its own directory.
### 3.3 No automated tests; no wired-in typecheck step (Low)
There is no test framework or test files in the repo, and `package.json` has no `typecheck`
script (project relies on strict TypeScript but nothing runs `tsc --noEmit` automatically). The
budget-math functions found in section 1 (unallocated calculations, goal contribution formulas)
are exactly the kind of pure logic that would have caught bugs 1.3/1.4 immediately under a unit
test.
---
## 4. Action checklist
Ordered roughly by impact vs. effort:
- [ ] **Rotate the `OLLAMA_API_KEY`** in `.env` (§2.1) — do this regardless of anything else.
_(Not automated — requires action on the issuing service.)_
- [x] Fix the stale-context bug in `AdviserChat` by forcing the chat to re-key when context
changes (§1.1). _Implemented via a `contextRef` read inside `prepareSendMessagesRequest`._
- [x] Fix `/api/chat`'s currency formatting to use `currencySymbol` instead of
`Intl.NumberFormat(rawCurrencyCode)` (§1.2).
- [x] Thread `reservedBuffer` into `BudgetPdfInput`, `insightsInputSchema`, and
`AdviserChatContext`, and subtract it consistently everywhere `unallocated` is computed
(§1.3).
- [x] Clamp the goal "required monthly contribution" to `>= 0` in
`budget-insights.functions.ts` (§1.4).
- [x] Change `if (g.currentProgress)` to a `typeof === "number"` check in `api/chat.ts` (§1.5).
- [x] Extract shared helpers for unallocated/goal-contribution/currency math to prevent future
drift across the four call sites (root cause of §1.3–1.5). _`src/lib/budget-math.ts`._
- [x] Add basic rate limiting to `/api/chat` and `generateBudgetInsights` before any public
deployment (§2.2). _`src/lib/rate-limit.server.ts`, in-memory/per-process — see the caveat
in that file's header comment._
- [x] Initialize a git repository at the project root, or confirm/document how version control is
actually intended to work here (§3.1).
- [x] Move `kanban/` out of the Budget Blueprint project directory (§3.2).
- [x] Add a `typecheck` script (`tsc --noEmit`) and consider a minimal test suite for the pure
budget-math functions (§3.3). _`bun run typecheck`, `bun run test` (Vitest)._