t0ul

Vibe Coding Securely

Vibe Coding Securely, Ch. 5: Input You Didn't Expect

Part of Vibe Coding Securely, a short, hands-on book about shipping the app an AI built without getting owned.

The last three chapters were about trust: who the app thinks you are, and what it lets you touch. This one is about something quieter that runs underneath all of it. Your app takes text from people. A search term, a note’s body, a name, a comment. That text is supposed to be data: a value the app stores, compares, or shows. The danger is that the same text can slip out of being data and start being read as instructions, either by your database or by the browser. When it does, the person typing gets to tell your app what to do.

That one idea, input is data and must never become code, is behind the two oldest famous web vulnerabilities, and vibe-coded apps still ship both constantly. Vibe Notes has one of each. We will take them one at a time.

Put the app at the start of this chapter:

git checkout ch5-start

A search box that runs what you type

Vibe Notes has a search box that finds your notes by title. Here is the route the tool wrote, app/api/search/route.ts:

export async function GET(req: Request) {
  const user = await getUser();
  if (!user) {
    return NextResponse.json({ error: "log in first" }, { status: 401 });
  }
  const q = new URL(req.url).searchParams.get("q") ?? "";
  const sql = `SELECT id, title, body FROM notes WHERE user_id = ${user.id} AND title LIKE '%${q}%'`;
  const rows = getDb().prepare(sql).all();
  return NextResponse.json(rows);
}

It checks you are logged in, which is good, and it scopes the search to user_id = ${user.id}, which looks like the ownership lesson from chapter 4 done right. Then it builds the query by pasting your search text, q, straight into the middle of a string of SQL. That is the whole problem. The query is just text, and your search is now part of that text. If your search contains something that reads as SQL, it becomes SQL.

Watch a normal search first so the baseline is clear. Log in as bob and search for “todo”:

curl -s -c jar.txt -X POST http://localhost:3000/api/login \
  -H 'Content-Type: application/json' -d '{"username":"bob"}'
curl -s -G -b jar.txt --data-urlencode "q=todo" http://localhost:3000/api/search
[{"id":3,"title":"Bob's todo","body":"Return the library book. Email the landlord about the sink."}]

That is right: bob’s one note with “todo” in the title. Now search for this instead:

curl -s -G -b jar.txt --data-urlencode "q=%' OR 1=1 --" http://localhost:3000/api/search
[{"id":1,"title":"Alice's diary","body":"Private. The spare key is under the third flowerpot."},
 {"id":2,"title":"Welcome","body":"This is Vibe Notes. Add a note, read it back. Small on purpose."},
 {"id":3,"title":"Bob's todo","body":"Return the library book. Email the landlord about the sink."}]

bob just read every note in the database, including alice’s diary, out of his own search box. To see why, put the search text where it lands in the query. With q set to %' OR 1=1 --, the string the tool builds is:

SELECT id, title, body FROM notes WHERE user_id = 2 AND title LIKE '%%' OR 1=1 --%'

Three small pieces did it. The ' closed the string the code opened, so the rest of our text stopped being a search value and started being SQL. OR 1=1 is a condition that is always true, and because OR loosens the whole WHERE, every row now matches, the careful user_id = 2 filter included. And -- begins a comment in SQL, which tells the database to ignore the leftover %' that the original code tacked on, so the query is still valid. The ownership check from chapter 4 was real, and this walked straight around it, because the attacker got to rewrite the query itself.

This is SQL injection: untrusted text injected into a SQL statement, where it is run as part of the command instead of being treated as a value. A real search box like this is enough to read, and with a different payload change or destroy, everything in the database. This chapter’s check runs the same payload and confirms it:

npm run check:ch5
FOUND (SQL injection): bob's search with "%' OR 1=1 --" returned alice's note.
FOUND (XSS): the note body's <img onerror> rendered as raw HTML on /notes/5.
See chapter 5.

(It found a second problem too. Hold that thought; it is the next section.)

The fix: let the database keep data and code apart

You never have to paste values into SQL by hand, and you never should. Every database library has a way to send the command and the values separately, so the values can never be read as part of the command. The placeholder is a ?, and we have already been using it safely since chapter 3 without naming why. Here is search, fixed:

  const rows = getDb()
    .prepare("SELECT id, title, body FROM notes WHERE user_id = ? AND title LIKE ?")
    .all(user.id, `%${q}%`);

The SQL is now a fixed string with two ? placeholders, and the values, user.id and the search text wrapped in % wildcards, are handed to .all() separately. This is called a parameterized query, or a bound parameter: the database treats everything you pass as a value to compare, never as SQL to run. Your search text could be the complete works of SQL and it would still just be a string the database looks for inside note titles.

Notice where the bug was. Chapter 4’s note lookup already used ? correctly. It is the search, with its % wildcards, where building the string by hand felt natural, so that is where the tool reached for concatenation. That is the pattern to watch: the injection shows up exactly where the query felt fiddly enough that pasting text in looked easier.

Jump to the fix and run the very same payload:

git checkout ch5-done
curl -s -G -b jar.txt --data-urlencode "q=%' OR 1=1 --" http://localhost:3000/api/search
[]

Now the database looks for notes whose title literally contains the characters %' OR 1=1 --, scoped to bob, finds none, and says so. The attack became an ordinary, fruitless search, which is exactly what it always should have been.

A note that runs what you type

Switch back to the start of the chapter for the second door:

git checkout ch5-start

Every note has its own page. To let a note show a little formatting, the tool rendered the note’s body as HTML, in app/notes/[id]/page.tsx:

<div className="body" dangerouslySetInnerHTML={{ __html: note.body }} />

React named this prop dangerouslySetInnerHTML on purpose. It is the escape hatch you use to say, “take this string and drop it into the page as real HTML, do not treat it as text.” Normally React does the opposite: it treats everything as text and escapes it, so a note that says <b> shows the characters <b>, not bold. This line opts out of that safety, for every note body, so whatever a note contains is inserted into the page as live HTML.

A note body is just text a user typed. So let me type some HTML that does something. Store a note whose body is an image tag with an onerror handler, a classic because it runs without anyone clicking:

curl -s -c jar.txt -X POST http://localhost:3000/api/login \
  -H 'Content-Type: application/json' -d '{"username":"bob"}'
curl -s -b jar.txt -X POST http://localhost:3000/api/notes \
  -H 'Content-Type: application/json' \
  -d '{"title":"formatting test","body":"<img src=x onerror=\"alert(1)\">"}'

Now look at the HTML the server sends for that note’s page. I will pull out just the body:

curl -s -b jar.txt http://localhost:3000/notes/4 | grep -o '<div class="body".*</div>'
<div class="body"><img src=x onerror="alert(1)"></div>

That <img> is now real HTML in the page. A browser tries to load an image from src=x, fails, and runs the onerror code, here a harmless alert(1). But the code runs in the browser of whoever opens the note, with the full run of the page. This is cross-site scripting, or XSS: getting your JavaScript to run in someone else’s session on a site they trust. And because the payload is saved in the database and runs for everyone who views the note, it is the worse kind, stored XSS. In a shared app, one note could carry code that runs for every person who ever opens it.

Here is a detail worth pausing on, because it is a reward for earlier work. The classic thing an XSS payload does is read your session cookie and send it to the attacker, letting them log in as you. That attack does not work here, and the reason is chapter 3: we set the session cookie httpOnly, which tells the browser never to let JavaScript read it. The injected script can try, and gets nothing. That is defense in depth, two independent controls so a miss on one is not game over. It is also not a reason to relax. XSS that cannot read the cookie can still make requests as you, change your notes, deface the page, or phish the person reading it. The cookie flag softens the blow. It does not close the door.

The fix: render user text as text

The fix is to stop opting out of the safety that was there by default. Render the body as text and let React escape it:

<div className="body">{note.body}</div>

That is it. {note.body} tells React this is a value to show, so it escapes the dangerous characters. Reload the fixed app and look at the same note’s page:

git checkout ch5-done
curl -s -b jar.txt http://localhost:3000/notes/4 | grep -o '<div class="body".*</div>'
<div class="body">&lt;img src=x onerror=&quot;alert(1)&quot;&gt;</div>

The < became &lt;, the " became &quot;. The browser now draws those as the literal characters <img src=x onerror="alert(1)"> on the page, as text, and runs nothing. Run the check once more and both doors are shut:

npm run check:ch5
BLOCKED: search is parameterized (no leak) and note bodies render as text (no raw HTML).

The part that generalizes

Both halves of this chapter are one sentence: input is data, and data must never be allowed to become code. The database and the browser are two different places where that line gets crossed, and each has one correct way to hold the line.

For anything touching a database, use parameterized queries, every time, with no exceptions. Not “this value is just a number so it is fine,” not “this one comes from a dropdown so the user cannot change it.” The visitor controls everything the browser sends, which is the lesson from chapter 3 wearing a new hat. The moment you are building a query by gluing strings together, stop and use placeholders instead.

For anything shown in a page, render it as text and let your framework escape it, which React and every modern framework do by default. The danger is the escape hatch, dangerouslySetInnerHTML and its equivalents, so treat reaching for it as a decision that needs a real reason and a second look.

Straight talk. The honest pull toward that escape hatch is that you want users to have formatting: bold, links, a list. The answer is never to accept raw HTML and hope. If you want rich text, accept something that is not HTML, like Markdown, and render it with a library that escapes any HTML inside it. If you genuinely must allow some HTML, run it through a real, maintained sanitizer such as DOMPurify, which strips the dangerous parts against a carefully kept allowlist. What never works is writing your own filter that strips <script>: attackers have decades of tricks (<img onerror>, <svg onload>, oddly encoded tags) and a hand-rolled blocklist loses to all of them. Use the library whose entire job is this, or do not render user HTML at all.

Try it. On ch5-done, store a note whose body is <b>hello</b> and open its page. You will see the characters <b>hello</b>, not bold text. That is the fix working: your formatting no longer “works,” because the app now refuses to run anything in a note body, including the harmless-looking tags. If you want real formatting, that is the moment to reach for a Markdown library, not the escape hatch.

Where this leaves us

Every input in this chapter came from a person typing into a box, trying things. You closed both doors with the same idea and proved each with the same check that caught it.

Next, you add the feature everyone wants in 2026: an assistant that reads your notes and answers questions about them. To do that you feed a pile of text, your notes, straight into a model that can also take actions on your behalf. The lesson of this chapter, that input can quietly turn into instructions, comes back in its newest and least understood form, where the instructions are written in plain English and hidden inside the data itself. That is prompt injection, and it is chapter 6.

← Vibe Coding Securely