Vibe Coding Securely, Ch. 8: When It Goes Wrong
Part of Vibe Coding Securely, a short, hands-on book about shipping the app an AI built without getting owned.
Every chapter until now has been about prevention, and prevention is most of security. It is not all of it. Given enough time, something gets through anyway: a key ends up in a commit the way chapter 2 warned, a dependency you trusted turns out to be bad, or a session cookie is left behind on a shared laptop. That is not a sign you failed. It is the normal weather of running software, and the people who handle it well are not the ones who never get surprised. They are the ones who prepared two boring things ahead of time: a way to see what happened, and a way to stop it.
This chapter is a calm drill for that first hour. It is also shaped differently from the others, and it is worth saying so plainly. There is no planted vulnerability to remove here. The weakness is an absence: right now Vibe Notes gives you no way to see or contain an incident, and we are going to add one.
The scenario
Imagine bob’s session cookie got out. Maybe he logged in on a library computer and walked away, maybe it was caught in a log that leaked. It does not matter how. What matters is that someone else now holds that cookie, and from chapter 3 you know exactly what that means: a session cookie is a valid token, so to your app the stranger holding it simply is bob. There is no alarm. Nothing looks wrong. You cannot un-leak the cookie, because it is already copied.
So put the app at the start of this chapter and ask the honest question, what can I actually do right now:
git checkout ch8-start
npm run check:ch8
See what happened (audit log): no /api/audit endpoint.
Contain it (sign out everywhere): no way to invalidate sessions.
MISSING: with no audit log and no way to sign out everywhere, you cannot see or stop an incident. See chapter 8.
That is the uncomfortable starting point. You suspect something is wrong and you are powerless: you cannot see what the stranger has done, and you cannot cut them off. Those are the two capabilities we add, one each.
Seeing it: a small audit log
You do not need to log everything. You need a record of the handful of actions that matter if an account is ever in question: who logged in, when, and later things like a password change or a key rotation. Here is lib/audit.ts, which is the whole mechanism:
export function logAction(userId: number, action: string, detail?: string) {
getDb()
.prepare("INSERT INTO audit (user_id, action, detail) VALUES (?, ?, ?)")
.run(userId, action, detail ?? null);
}
export function getAudit(userId: number, limit = 20): AuditEvent[] {
return getDb()
.prepare("SELECT id, action, detail, at FROM audit WHERE user_id = ? ORDER BY id DESC LIMIT ?")
.all(userId, limit) as AuditEvent[];
}
It writes a row and reads the recent rows back, scoped to one user with the ownership check from chapter 4, using bound parameters from chapter 5. Nothing new, just applied to a new purpose. Recording an event is then a single line added where something important happens, like at the end of login:
logAction(user.id, "login");
And reading it back is one small route, app/api/audit/route.ts, that returns your own recent events and no one else’s:
export async function GET() {
const user = await getUser();
if (!user) return NextResponse.json({ error: "log in first" }, { status: 401 });
return NextResponse.json({ events: getAudit(user.id) });
}
That is “see what happened.” When an account looks off, you can now look.
Containing it: sign out everywhere
Seeing is half of it. The other half is a lever that makes the leaked thing stop working. For a leaked session, that lever is “sign out everywhere,” and chapter 3 already built the foundation for it without saying so. A session is a row in a table that the server checks on every request. So to kill every session at once, including the stranger’s, you delete the rows. Here is app/api/rotate/route.ts:
export async function POST() {
const user = await getUser();
if (!user) return NextResponse.json({ error: "log in first" }, { status: 401 });
const info = getDb().prepare("DELETE FROM sessions WHERE user_id = ?").run(user.id);
logAction(user.id, "sign_out_everywhere", `ended ${info.changes} session(s)`);
(await cookies()).delete("session");
return NextResponse.json({ ok: true, signedOut: info.changes });
}
One DELETE ends every session this user has, on every device. The attacker’s stolen cookie still exists, but the token in it no longer matches any row, so the next time they use it the server shrugs and treats them as logged out. You also write an audit event for the sign-out itself, so the containment is part of the record.
The drill
Now walk the whole first hour, on the fixed app:
git checkout ch8-done
First, the incident. bob logs in on two devices. Think of the second one, jar B, as the cookie that leaked, now in a stranger’s hands. Confirm it works right now:
curl -s -c bobA.txt -X POST http://localhost:3000/api/login \
-H 'Content-Type: application/json' -d '{"username":"bob"}' -o /dev/null
curl -s -c bobB.txt -X POST http://localhost:3000/api/login \
-H 'Content-Type: application/json' -d '{"username":"bob"}' -o /dev/null
curl -s -b bobB.txt http://localhost:3000/api/me
{"user":{"id":2,"username":"bob","role":"user"}}
The leaked cookie is live. Now you, as bob on your own device (jar A), run the drill. See what has happened:
curl -s -b bobA.txt http://localhost:3000/api/audit
{"events":[{"id":2,"action":"login","detail":null,"at":"2026-10-23 16:20:28"},
{"id":1,"action":"login","detail":null,"at":"2026-10-23 16:20:28"}]}
Two logins, which is what you expect to see: your own, and the other one. On a real account, an extra login you do not recognize is exactly the signal this log exists to give you. Now contain it:
curl -s -b bobA.txt -X POST http://localhost:3000/api/rotate
{"ok":true,"signedOut":2}
Two sessions ended. And the stolen cookie, jar B, is now worthless:
curl -s -b bobB.txt http://localhost:3000/api/me
{"user":null}
The stranger is out. The check agrees that you are now equipped:
npm run check:ch8
See what happened (audit log): yes.
Contain it (sign out everywhere): yes, the old session is now dead.
READY: you can review recent activity and sign out everywhere to contain a leaked session.
When it is a key, not a cookie
Sign-out-everywhere is the lever for a leaked session. If what leaked was an API key, the same instinct applies with a different lever, and it is the one from chapter 2: you rotate the key at the service that issued it, so the old value stops working, then put the new one in your server’s environment. The pattern underneath is always the same. Whatever leaked, find the single action that makes it worthless and pull it. Sessions get deleted. Keys get rotated. Passwords get force-reset. The specific button changes; the move does not.
The part that generalizes
Incidents go badly when people improvise, so it helps to know the order before you need it. It is deliberately boring, which is the point.
First, contain, before you fully understand what happened. A credential you have already made worthless cannot do more harm while you investigate, so rotate the key or sign out everywhere first and ask questions second. Second, see: read the log and work out what was touched, how far it reached, and when it started. Third, fix the hole that let it in, which is where the earlier chapters come back. Fourth, if real user data was exposed, tell the people affected plainly and soon. That last one is not a technical step and it is the one that most defines whether people trust you afterward.
Straight talk. What you built here is the honest minimum, and a real app goes further in two ways worth knowing. It logs more, and it keeps those logs somewhere separate from the application, because an attacker who gets into the box should not be able to edit the record of what they did. Our audit log lives in the same SQLite file as the notes, which is fine for learning and not where you would stop in production. And this is one more argument for the advice in chapter 3: a managed authentication provider usually gives you login history, alerts for logins you do not recognize, and a sign-out-everywhere button already built and tested, which is a lot of this chapter handled for you by people who do only this.
Try it. On
ch8-done, open the app in your normal browser and log in as bob, then open a private or incognito window and log in as bob there too. In one window, visit the security page and sign out everywhere. Refresh the other window. It is logged out. You just watched containment work from the user’s side, which is the sameDELETEyou ran with curl, wearing a button.
Where this leaves us
You can now do all three things that matter: prevent the common holes, see when something happens, and contain it fast when it does. That is a genuinely solid place to be for an app an AI helped you build.
One chapter left, and it turns the whole method back on the app at once. You have learned to attack your own code hole by hole. Now you will ask an AI to review the code it helped write, run that review against Vibe Notes, where you happen to know every weakness because you planted and fixed them, and score exactly what it caught and what it missed. That tells you how much to trust the reviewer, which is the most useful thing to know about any reviewer. That is chapter 9.