What this is
A whole report, from the first check to the sustain plan we leave behind. The codebase is synthetic: invented for this page so the format can be shown without exposing anyone’s repository. The organisation is redacted and no client has received this document.
It is set in the EU on purpose. Most of the companies we work with sell into the single market. There, two questions decide the order of work: what is broken, and what personal data is where with proof to match. Same twelve checks, different findings.
Read it the way you would read one of your own.
| Organisation | redacted |
| Product | Quoting and invoicing for trades businesses, B2B SaaS |
| Customers | SMEs in Germany, the Netherlands and Ireland, invoicing their own clients |
| Personal data held | Names, addresses, VAT numbers and bank details of their customers’ clients |
| Stack | Next.js 14, TypeScript, Prisma, Postgres, Stripe, deployed on Vercel |
| Where it runs | App functions in eu-central-1, database in eu-central-1, error tracking and log drain in the US |
| Size | 34,000 lines of TypeScript across 1,894 files, 41 database tables |
| Age | Four months from first commit to the audit |
| Built with | Cursor and Claude Code, used daily by the whole team |
| Engagement | Audit. The other three steps here are the plan that came out of it |
What an audit is for
It is a decision document. What is in the codebase, what is blocking change, and what order to fix it in, with evidence you can check instead of a score out of ten. It is step one of four, and the method behind it is in how we audit an AI-generated codebase.
In the EU there is a second job. A customer’s security review, a data processing agreement or a due diligence pack asks where personal data sits and who can reach it. Most teams answer that from memory, and one of the answers is wrong. The data map below is written from the code, so the answer can be checked.
What we needed from them
Read-only repository access. A branch on their own remote was enough, and we never asked for production.
One person who could answer questions about intent, for about 30 minutes. We asked why a piece of code exists, not how it works. The how is in the repository.
An NDA first, theirs or ours, signed before the repository link changed hands.
Three documents, because the audit covers personal data: their sub-processor list, their DPA template, and the name of the accountant who signs off their VAT rules. We did not ask for customer data. Where a check needs it, we say so and it runs in their environment with them watching.
The twelve checks
The same twelve as the health checklist, run in full, plus the parts a checklist cannot cover: the dependency graph, the architecture, patterns that contradict each other, code nothing calls, and the data map. That last one is not on the checklist because the answer differs by jurisdiction.
| # | Check | Result | What it turned up |
|---|---|---|---|
| 1 | Break something on purpose | Fail | Changing a plan tier in tests/billing.test.ts left the suite green |
| 2 | Count the ways you authenticate | Fail | Three session paths, and one route that trusts a header |
| 3 | Count the ways you talk to the database | Fail | Prisma in some handlers, raw SQL in others, plus a connection pool of its own |
| 4 | Build it from a clean checkout | Fail | Two undocumented environment variables and one manual migration step |
| 5 | Look for secrets in the history | Fail | A live Stripe key in .env.local, committed in week one and never rotated |
| 6 | Find the code nothing calls | Fail | 123 files with no importer, 9 environment variables nothing reads |
| 7 | Measure your utils folder | Partial | 41 files, four of them holding a single line |
| 8 | Check whether CI actually blocks anything | Fail | Tests allowed to fail, lint set to continue-on-error |
| 9 | Locate your invariants | Fail | VAT computed three ways, and reverse charge stored as a boolean |
| 10 | Audit your dependencies | Partial | 61 direct, 240 transitive, four unmaintained, one major version behind |
| 11 | Check what production tells you when it breaks | Partial | Error tracking in place, no alerting, failures found by support |
| 12 | Pick five files and explain them | Fail | Two of the five could be explained by one person only |
Nine of the twelve failed. That is a normal result for a codebase this age, and it says more about the pace it was built at than about the people who built it.
Where the personal data goes
Written by reading the code and the infrastructure config, then confirming with the 30 minute interview. Column four says how we know, because a data map is only useful if you can check it.
| Data | Lives in | Copies elsewhere | How we found it |
|---|---|---|---|
| Customer names and addresses | invoices, customers in eu-central-1 |
Error report payloads in the US, on 14 of 41 screens | Reading the error tracking config |
| End client names and addresses | invoices |
CSV exports in a support tool, uploaded by hand | The 30 minute interview |
| VAT numbers | customers.vat_id |
A US log bucket, inside request payloads | Grepping the log middleware |
| Bank details | Stripe, not in their database | None | Reading the Stripe integration |
| Session cookies | Redis in eu-central-1 |
None | Reading the middleware |
Three of these are worth naming. Error reports quote the row that failed, so an invoice with a name and address left the EU every time a page threw. Nobody chose that. It is what the SDK does by default, and it stays invisible until someone reads the config. The log drain is the same story with request payloads. A VAT number is personal data when it belongs to a sole trader, and this one was sitting in a US bucket with a 30 day retention that nobody had set.
The bank details row is the good news, and it is deliberate. Card and bank details never touch their database because Stripe holds them, which removes a category of risk and a category of paperwork.
The ranked findings
Three inputs set the order. Blast radius, meaning how much goes with it if it fails. Change frequency, meaning how often that code is touched. Test coverage around the area, meaning whether a change there would be caught.
In the EU a fourth input can move something up the list: whether a regulator, a customer’s data protection officer or an accountant will ask for it in writing. That is how the VAT finding and the erasure finding got their position, ahead of two security findings with a similar blast radius.
A finding rises only when more than one input is high, and the evidence for each sits in the report so you can disagree with the call. Every finding gets one of three labels: fix now, schedule, or note and leave.
| # | Finding | Blast radius | Change frequency | Coverage | Label |
|---|---|---|---|---|---|
| F-01 | The test suite cannot fail | High | High | None | Fix now |
| F-02 | The admin route trusts a header | High | Medium | None | Fix now |
| F-03 | A live Stripe key sits in the git history | High | Low | Not covered | Fix now |
| F-04 | CI does not block | Medium | High | None | Fix now |
| F-05 | VAT is computed three ways, and reverse charge is a boolean | High | High | None | Fix now |
| F-06 | Deleting an account leaves the personal data | High | Medium | None | Fix now |
| F-07 | Invoice data leaves the EU by two paths | High | Low | Not covered | Fix now |
| F-08 | Three ways to reach the database | Medium | High | Low | Schedule |
| F-09 | 123 files nothing imports | Low | Low | Not covered | Schedule |
| F-10 | The Stripe webhook | Low | Low | One replay test | Note and leave |
Two of those are printed in full below, in the format the report uses. The rest follow the same shape.
FINDING F-05 of 10 - VAT is computed three ways, and reverse charge is a boolean
Priority: 2 Blast radius: high Change frequency: high Coverage: none
Evidence
lib/vat.ts:14 integer rate table, used by the quote endpoint
app/(app)/invoice/page.tsx:88 float arithmetic, rounded for display only
app/api/stripe/webhook/route.ts:61 third copy, written from a prompt
lib/vat.ts:31 reverse_charge: boolean, read from the request body
The three agree on the rates used in the demo data. They disagree at the
third rate, where one rounds half up and one truncates. Reverse charge is
decided by a checkbox in the invoice form and stored as a boolean, so the
value on the invoice is whatever the user last clicked. Nothing calls VIES.
A VAT number is accepted if it is eleven characters long.
Why it matters
The rule that decides what a customer owes, and what has to be printed on
the invoice, exists in three code paths with no test comparing them. A
reverse charge invoice is only correct if the customer's VAT number was
valid at the time of supply, and this system keeps no record of ever having
checked one.
If it is left
The first mismatch reaches a customer as an invoice that does not match the
quote. The first incorrect reverse charge reaches an accountant, who
reverses it, which means a credit note and a conversation with the end
client. Fixing it later means reconstructing which invoices were issued
under which assumption, from a log with no VAT decisions in it.
What we would do
1. Move the rule into one module: rates, rounding, and the reverse charge
decision derived from the customer's country and a stored VIES result.
2. Store the VIES check as a result with a timestamp, not a boolean, so an
invoice can show why it was zero rated.
3. Compare the module's output against 40 stored invoices before deleting
the copies.
4. Add a test at each rate boundary and one per reverse charge case.
FINDING F-06 of 10 - Deleting an account leaves the personal data
Priority: 3 Blast radius: high Change frequency: medium Coverage: none
Evidence
app/api/account/delete/route.ts:19 sets deleted_at, deletes nothing
prisma/schema.prisma:214 no onDelete rule on Invoice.customer
lib/export.ts exports contacts, not invoices
"Delete account" sets a timestamp. The customer, their invoices and their
end clients' names and addresses stay in the table. The support tool filters
on deleted_at, so the account disappears from the interface and from the
team's view, which is why everyone believed it was gone.
Why it matters
An erasure request is answered by the interface, and the data lives in the
database. The invoice rows cannot simply be dropped: accounting law requires
them to be kept, and the period differs, so their accountant confirmed the
figures before we wrote them down. What has to go is the part that no law
requires anyone to keep.
If it is left
The next request arrives as an email from someone who has already asked
once, and the honest answer is that the row is still there. That is a worse
position than a slower answer given the first time.
What we would do
1. Split the record: personal data that must go, and the invoice record that
must stay for the statutory period.
2. Pseudonymise the retained invoices, replacing name and address with a
reference while keeping amounts and tax treatment.
3. Make deletion a real transaction, with a test asserting that zero rows
match the reference afterwards.
4. Put the retention period per country in one config file, with the source
of each figure written next to it.
The other eight, in one line each. F-01 means the suite cannot be trusted, so every later fix needs its own test first. F-02 is a second authorisation path that only the edge middleware covers. F-03 means the key is rotated before anyone touches code, and the history is treated as public. F-04 is a two line change that would have caught F-01 six weeks earlier. F-07 is the two egress paths from the data map. F-08 is scheduled because boundaries are worth fixing once the money paths are stable. F-09 is cheap and low risk. F-10 is recorded as fine and left alone, which is part of the report too.
The EU rules that set the order
Not a compliance section. Five rules changed the order of this report, and one was checked and ruled out.
| Rule | What it changed here |
|---|---|
| GDPR, records and security (Art. 30, Art. 32) | The data map came first, and the two egress findings moved up the list |
| GDPR, erasure (Art. 17) | F-06, and the split between what has to go and what has to stay |
| GDPR, breach notification in 72 hours (Art. 33) | Two alerts instead of one, because the second is how you would find out |
| Transfers (Chapter V) | F-07: a US error tracker needs a mechanism, and the cheapest fix was a region change |
| VAT, reverse charge and VIES | F-05, including storing the check rather than the boolean |
| European Accessibility Act | Checked and ruled out. The buyers are businesses, and the tool faces consumers only through them |
| AI Act | Checked and ruled out, explained below |
The AI Act is the rule most teams ask about and least need. If a product puts a generative feature in front of users, the transparency rules in Article 50 have applied since 2 August 2026. The high risk obligations for Annex III systems now start on 2 December 2027, after the Digital Omnibus deferred them. A quoting tool is not an AI system under the Act, and this codebase has no model in it. Two of the ten findings came from an assistant writing the code, and that is a different thing from shipping AI to a user. The report says so plainly, because a questionnaire will otherwise imply otherwise and somebody will spend a month on it.
We are engineers. Where a finding turns on a legal question, the report names the question and who has to answer it, and it does not answer it for them.
Untangle: keep, fix, remove
Step two. The audit says what is wrong. Untangle decides what stays, what changes and what goes, and it does that per area rather than per file so the plan has an owner.
| Area | Files | Call | Why |
|---|---|---|---|
lib/billing |
18 | Fix | Both money findings land here |
lib/vat |
6 | Fix | Three copies become one |
lib/auth, middleware.ts |
11 | Fix | Three sessions become one |
app/api |
64 | Fix, then keep | Boundaries and one data path, no rewrite of the handlers |
infra/ |
9 | Fix | Error tracking region, log drain, retention config |
app/(marketing) |
88 | Keep | Server components, no state, nothing to gain |
components/ui |
210 | Keep | Generated and consistent, cheap to leave |
lib/utils |
41 | Remove most | 22 have a single caller, four hold one line |
scripts |
31 | Remove | Superseded by package scripts |
legacy/ |
61 | Remove | Nothing imports it since the v2 rewrite |
That is 1,406 files kept, 368 changed and 120 removed, out of 1,894. The point of the count is size. The plan now has one, and a size is something you can schedule.
The dependency picture is the other half. Billing reaches into auth for a user lookup, auth reaches into session, and session is imported by the middleware that also sets the header F-02 trusts. VAT reads from billing, and billing reads back from VAT to decide reverse charge, which is a loop. One direction of that chain is fine, the loop is not, and the report draws it. In practice it means the auth change in slice 3 touches four files in billing, so it goes before the boundaries work.
Refactor: the order of work
Step three. Every slice goes on a branch your team reviews, and main stays shippable throughout. Nothing here is a rewrite, and if a slice turns out to need one, the report says so before the work starts rather than halfway through.
| # | Slice | What changes | Acceptance test | If interrupted |
|---|---|---|---|---|
| 1 | Rotate the key | New live key, old one revoked, documented | Old key rejected in staging and production | Safe at any point |
| 2 | Make the tests able to fail | Mock assertions replaced on the money paths | The tier test fails when the rule is wrong | Suite gets stricter, nothing shipped at risk |
| 3 | One auth path | Session function authoritative, header deleted, ADR written | Handler called without middleware rejects the request | Finish in one go, a half migrated admin route is worse than either end |
| 4 | VAT in one module | Rates, rounding, stored VIES result, derived reverse charge | Output matches 40 stored invoices, and a zero rated invoice shows its check | Needs their accountant on the rule before it starts |
| 5 | Erasure that erases | Personal data split from the retained record, pseudonymised, real delete | Zero rows match the reference after the call | Needs the retention config agreed first |
| 6 | Boundaries | Prisma behind lib/db, lint rule enforces it |
Direct import fails the build | Mechanical, safest last |
The acceptance test is written before the change, and it has to fail for the right reason. That is the difference between this and a refactor that looks finished:
// tests/vat.test.ts, written before slice 4
it("zero rates a reverse charge invoice and records the check", async () => {
const invoice = await createInvoice({
customerVatId: "DE123456789",
country: "DE",
net: 3900,
});
expect(invoice.vat).toBe(0);
expect(invoice.checkedAt).not.toBeNull();
});
// before the fix: expected 0, received 741
// reverse charge defaulted to false, so 19 per cent was applied
Each slice gets an ADR for the decision it encodes, so the next person reads why rather than guessing. Eleven came out of this engagement, none longer than a page. Two of them were co-signed by the accountant, because they record a tax decision rather than an engineering one.
Sustain: what stops it coming back
Step four, and the one that decides whether any of the above holds. The guardrails are specific to the patterns this codebase produced, not a generic template:
- Lint rules that reject the old shapes. The data boundary from slice 6 becomes a rule, so the next handler cannot reach around it.
- CI that fails on failure. Typecheck, lint, tests and a migration check, all required. The bypass from F-04 is gone and a test asserts the pipeline config stays that way.
- A review checklist with the six questions this codebase needed. Who verifies the session. Where is the total computed. What happens on replay. What did the agent assume. Does this touch personal data, and if so where does it go.
- Agent rules in the repository, so Cursor and Claude Code follow the new structure instead of generating a fourth auth path next quarter. The first rule is the one that matters: no production data, no real customer names and no live keys in a prompt. Both findings that came from assistant written code had that shape.
- A sub-processor list in the repository. A new dependency that processes personal data cannot merge without a line in it, reviewed in the same pull request that adds the dependency.
- Retention as code. One config file, one country and period per line, with the source of each figure next to it. A scheduled job with a test that fails when the job stops running.
- Onboarding doc for a clean checkout. Two commands, no tribal knowledge, verified by someone who has never run it.
- Two alerts on the money paths. One for invoice totals that stop matching quotes, one for an export that returns more rows than a person would read.
# .github/workflows/ci.yml, required checks
- run: npm run typecheck
- run: npm run lint
- run: npm test -- --run
- run: npx prisma migrate diff --exit-code
- run: node scripts/check-data-map.mjs # every personal data field has an owner
Sustain worked if the team keeps the codebase clean after we leave. A document on its own proves nothing, and if the linter is the only thing holding the line, the team will route around it within a quarter.
What this report does not do
It does not contain style opinions. Tabs, naming and import order belong to the formatter, and a finding that does not change how safely you can change the code stays out of the ranked list.
It does not recommend a rewrite unless the evidence carries it. If it ever does, the report shows why on the numbers, and you should argue with it.
It does not put a price on your outages. We can tell you what a fix takes. We cannot tell you what a breach or a missed quarter costs your business.
It does not promise a security audit. It runs the twelve checks, names the security mistakes AI built code tends to make, and says plainly when something needs a penetration test. F-03 is one of those.
It is not legal advice. We read the code and say what it does. Where the answer depends on law, the report names the rule, names the question and says who should answer it. If your data protection officer or your accountant disagrees with us, they are right and the report changes.
Timeline and what comes after
An audit takes three to five working days for a repository this size, longer for a large one, and it runs alongside your team’s work. It is read only.
It is paid work, scoped and priced in writing before it starts, and it is the first step of an engagement rather than a free consultation in front of one. The report ends with a fixed figure for whatever comes next, so the second decision is a number.
One test we apply before sending it: could this document be forwarded to a customer’s security reviewer, their data protection officer and their accountant without an edit? If not, it is not finished. Half of the EU work in this report exists so that answer is yes.
You can also stop after the audit, keep the findings and do the work with your own team. That is a normal outcome here and a wasted audit is not. If you want the rest, Untangle, Refactor and Sustain are scoped from these findings rather than from a package, and the services page has the shape of each step.
If you arrived from the AI code cleanup page, the audit is the part of that offer where the price stops being a guess.