Filters as data, and never trusting the input
By the end of this lesson you will have a filter form whose input the server checks against fixed lists of fields and operators, a limit clamped to 100, a starter proxy that no longer forwards the screener, and three attacks turned into tests.
A screener is the first thing you have built where a person types something and it reaches an API. That changes the rules.
Filters are values, not code
Same principle as the threshold rules in Build Your First Tool, and it matters more here:
type Filter = {
field: "market_capitalization" | "earnings_share" | "dividend_yield" | "avgvol_1d" | "sector";
op: ">" | "<" | "=" | ">=" | "<=";
value: number | string;
};
A union type for field, not string. That single choice means a typo is a compile error rather than a runtime {"errors":{"filters.0.field":[...]}}, and it means the set of screenable fields is written down somewhere a person can read.
Serialising to what the API wants is then one function:
const encoded = encodeURIComponent(
JSON.stringify(filters.map((f) => [f.field, f.op, f.value])),
);
The allowlist is the security boundary
Here is the reasoning, and it is worth following rather than memorising.
Your proxy forwards query parameters upstream. A screener puts user input into those parameters. So user input now influences a request made with your API key. That is a new kind of exposure and it did not exist in Build Your First Tool, where every request was for a ticker you had written into a file yourself.
The defence is not to sanitise the input. It is to never pass the input through at all: accept a structured filter, validate every field against a fixed list of allowed names and operators, and build the upstream query from the validated values. What reaches the API is a string your code constructed, not a string a person typed.
const FIELDS = new Set(["market_capitalization", "earnings_share",
"dividend_yield", "avgvol_1d", "sector"]);
const OPS = new Set([">", "<", "=", ">=", "<="]);
function safe(f: unknown): Filter | null {
// validate, or return null and drop the filter — never "clean it up"
}
Reject rather than repair. A filter you had to fix was a filter you did not understand, and quietly correcting it means the results do not match what the person asked for.
Guard the limit too
limit is user input the moment it is a control on your page, and 500 rows was verified to work in one request. Someone hitting your deployment in a loop with limit=500 spends your allowance, not theirs.
Clamp it server-side:
const limit = Math.min(Math.max(Number(raw) || 25, 1), 100);
Note that this happens on the server, not in the browser. A control in the browser is a suggestion; the server decides.
Validate the response as well as the request
Same discipline in the other direction. The screener answers { "data": [...] }, and every row should be narrowed before your table sees it:
const body: unknown = await res.json();
const rows = Array.isArray((body as { data?: unknown }).data)
? (body as { data: unknown[] }).data.filter(isScreenRow)
: [];
One check at the boundary. Everything downstream can then be trusted, which is what stops defensive ?. spreading through every component.
Try it now
Add a filter control, then attack your own proxy with curl. The tests come first this time, so the attacks run on every pull request instead of when you remember to type them.
The prompt
Mock mode on, plan mode on, and paste:
Add a filter form to the screen page that submits as a GET to the
page itself: f=field:op:value pairs separated by commas, plus limit.
In the address the operators are words, gt lt eq gte lte, for example
f=market_capitalization:gt:1000000000,earnings_share:gt:0.
In a new src/lib/filters.ts: the Filter type with a union of allowed
fields, fixed sets of fields and operators, a parser that accepts a
filter or rejects it with a reason naming its position (never
repairs it), and a clamp for limit: default 25, between 1 and 100.
If any filter is rejected, make no request and show the reasons. The
screener request is built only from parsed values. Remove "screener"
from ALLOWED_ENDPOINTS in src/lib/proxy.ts, so this page is the only
way to it, and make sure the proxy's 404 hint does not invite adding it
back. Write tests/filters.test.ts first, for an unknown field,
the operator LIKE and limit=100000 clamped to 100, and show me them
failing. No new request. Done means npm test, typecheck, lint,
check:leak green.
A good answer adds src/lib/filters.ts and its test, changes the screen page, and takes screener out of src/lib/proxy.ts along with any 404 hint or document that listed it as forwarded. The filters reach eodhdFetch as plain JSON: the encodeURIComponent above is for a URL built by hand.
Check it yourself
- The first
npm testrun showed the new tests failing (a message that the filters module cannot be found counts: it does not exist yet); the second shows them green beside the starter's own. - Open the screen page with
?f=pe_ratio:gt:5on its address: it names filter 1 as an unknown field and screens nothing. curl -s localhost:3000/api/proxy/screeneranswers 404 and lists what the proxy does forward: the unvalidated door is shut.- In
src/lib/filters.tsthe field and operator lists are written out in the file, not built from anything a request carries.
Break it on purpose
Attack the page from outside with curl: a field name that is not on your list, an operator like LIKE, and limit=100000. The field and the operator must be refused by the server, and the limit must come back as 100 rows at most: clamped, not obeyed. (On mock the fixture has ten rows whatever you ask, so there the unit test is your proof of the clamp; count rows live only with your own free key.) Your page would never send any of them. If one gets through as asked, your allowlist is decoration. Then switch off the check that rejects an unknown field by changing its condition to false (if (false), or } else if (false) { if your agent chained the checks), leaving its braces and any else after it in place, and run npm test: the unknown-field test must go red. Deleting or commenting out lines instead can leave a dangling else, and then every test fails for the wrong reason. Put the condition back.
Compare with ours
// src/lib/filters.ts: the request is built from these values, never the string
const OPS = { gt: ">", lt: "<", eq: "=", gte: ">=", lte: "<=" } as const;
export function parseFilter(raw: string, n: number): Filter | { rejected: string } {
const [field, op, value] = raw.split(":");
if (!isField(field)) return { rejected: `filter ${n}: unknown field ${field}` };
if (!Object.hasOwn(OPS, op)) return { rejected: `filter ${n}: operator ${op} not allowed` };
const ok = field === "sector" ? SECTORS.has(value) : /^-?\d+(\.\d+)?$/.test(value ?? "");
if (!ok) return { rejected: `filter ${n}: ${value} is not a value for ${field}` };
return { field, op: OPS[op as keyof typeof OPS],
value: field === "sector" ? value : Number(value) };
}
export const clampLimit = (raw: string | undefined) =>
Math.min(Math.max(Number(raw) || 25, 1), 100);
Object.hasOwn, not op in OPS: in also finds constructor on every object. Ours also allows sector, checked against a fixed list of sector names (SECTORS); an answer that allows only numeric fields is just as safe. The full state at the end of this unit is on the starter's branch ref/build-a-screener/u2.
Checkpoint
npm test && npm run typecheck
git status # only the files this step touched, no .env*
git add -A
git commit -m "Filters as data: allowlisted fields and operators, limit clamped, raw screener path closed"
Then answer this lesson's questions.