# Harrowquay: independent code review (sample)

Harrowquay is an invented app for boat repair yards: work orders, supplier invoice approval, bills sent to an accounts system, and usage credits.

**The app and its flaws were written for this sample. The checks and their results are real, and the project that reruns them is in a private repository and can be shared.**

## 1 What was reviewed

- **Reviewed:** The Harrowquay sample app: Next.js 16.5.0 (App Router) and TypeScript on Supabase. 1,026 lines of TypeScript in 24 files and 396 lines of SQL in 9 migrations.
- **Commit:** c97c68a
- **Checks run:** 3 December 2026, on the reviewer's machine against a local Supabase stack with test data
- **Kind of review:** Read-only. No code in the app was changed.

## 2 Summary

Four problems let someone outside a yard reach its data today, and two of them also let that person change it. Two more expose data in narrower ways: a file link that the app signs without checking whose file it is, and accounts tokens that every staff member can read. The foundations are sound: row security is on for all 9 tables, and the rules on work orders, supplier invoices, files and credits held against every direct attempt on them. The money paths are not yet safe against a repeat: a bill sent twice or a billing event delivered twice is counted twice. I would not launch until the five items below are fixed. Each is a small change, and none needs a redesign.

**Findings by severity:** Critical 4, High 4, Medium 3, Low 3.

**Findings by area:** Security 8, Money and outside writes 3, Reliability 2, Maintainability 1.

### Top 5 to fix before launch

1. Stop people adding themselves to other yards (F-02: Critical)
2. Make the invoice route check whose invoice it is, and whose file (F-01: Critical; F-13: High)
3. Put a sign-in and yard check inside the export route (F-03: Critical)
4. Make the cost view follow the row rules, and take the accounts tokens out of members' reach (F-04: Critical; F-05: High)
5. Send each bill once, with one fixed key, and make the billing webhook ignore repeats (F-07, F-08: High)

### In good shape

- Row security is switched on for every table, and the rules on work orders, supplier invoices, invoice files and the credit ledger blocked every direct cross-yard attempt on their rows.
- The file store is private, foldered by yard and limited to PDFs and images of 5 MB. Its own rules refused every direct attempt to list, download, overwrite, move or delete another yard's file. F-13 is the one way round them, through the app.
- The billing webhook checks its signature against the raw request and refuses missing, altered and old signatures.
- Nothing secret reaches the browser, and no yard's data sits in a shared cache.

## 3 How to read this report

| Severity | What it means | When to fix |
|---|---|---|
| Critical | Someone outside the company, or a signed-in person from another company, can read or change its data or money today with an ordinary request. | Fix before launch. |
| High | Serious harm to customers or money, but it needs more: an account inside the same company, a request built by hand from details that are hard to come by, or a failure that will happen sooner or later (a retry, a repeated delivery, a double click). | Fix before launch. |
| Medium | Harm under specific conditions, or a failure that costs time and trust but not data. | Fix in the first weeks. |
| Low | Small, hard to reach, or about upkeep. | Fix in normal work. |

| How hard to trigger | What it means |
|---|---|
| Easy | One ordinary request from an ordinary account. |
| Moderate | Needs a piece of information (an id), particular timing, or a failure somewhere else. |
| Hard | Needs something else to go wrong first. |
| Does not apply | Not a way in. The finding is about upkeep. |

- Every finding has the same parts: what is wrong, why it matters, a suggested fix, and the file and line. Critical and high findings also have steps you can follow to see the problem yourself.
- "How hard to trigger" is separate from severity. A problem can be serious and still need unusual conditions, or minor and easy to reach.
- A company is called a yard in this app. "Company A" in the checks is Saltmere Boatworks and "company B" is Dunmarrow Slipway. Both are invented.

## 4 Company separation check

Signed in as each person at company A, and as a visitor, the script tried to read, add, change and delete company B's data through every table, file store and route. Then it read B's data back to see whether anything had changed.

The list of what to test is not kept by hand. The script reads it from the database catalog and from the app's own folders, and a table or route with no test fails the run. "Change" includes trying to move one of company A's own rows into company B.

Company A is Saltmere Boatworks. Company B is Dunmarrow Slipway. Tried as: Saltmere owner, Saltmere approver, Saltmere staff, Signed-out visitor.

| | Read | Add | Change | Delete |
|---|---|---|---|---|
| **Tables** | | | | |
| Billing events (`billing_events`) | Blocked | Blocked | Blocked | Blocked |
| Yards (`companies`) | Blocked | Blocked | Blocked | Blocked |
| Credit ledger (`credit_ledger`) | Blocked | Blocked | Blocked | Blocked |
| Accounts connection tokens (`integration_tokens`) | Blocked | Blocked | Blocked | Blocked |
| Invoice file records (`invoice_files`) | Blocked | Blocked | Blocked | Blocked |
| Who belongs to which yard (`memberships`) | Blocked | **Got through** (F-02) | Blocked | Blocked |
| Supplier invoices (`supplier_invoices`) | Blocked | Blocked | Blocked | Blocked |
| Nightly sync log (`sync_runs`) | Blocked | Blocked | Blocked | Blocked |
| Work orders (`work_orders`) | Blocked | Blocked | Blocked | Blocked |
| **View** | | | | |
| Cost summary (`work_order_costs`) | **Got through** (F-04) | Not applicable | Not applicable | Not applicable |
| **Function** | | | | |
| Approve an invoice (`approve_invoice()`) | Not applicable | Not applicable | Blocked | Not applicable |
| **File store** | | | | |
| Invoice files (`invoice-files`) | **Got through** (F-13) | Blocked | Blocked | Blocked |
| **Routes** | | | | |
| Spend credits (`POST /api/credits/spend`) | Not applicable | Not applicable | Blocked | Not applicable |
| Nightly payment sync (`GET /api/cron/sync-payments`) | Not applicable | Not applicable | Blocked | Not applicable |
| Invoice export (`GET /api/export`) | **Got through** (F-03) | Not applicable | Not applicable | Not applicable |
| Open an invoice (`GET /api/invoices/[id]`) | **Got through** (F-01) | Not applicable | Not applicable | Not applicable |
| Edit an invoice (`PATCH /api/invoices/[id]`) | Not applicable | Not applicable | **Got through** (F-01) | Not applicable |
| Send a bill (`POST /api/invoices/[id]/send`) | Not applicable | Not applicable | Blocked | Not applicable |
| Billing webhook (`POST /api/webhooks/billing`) | Not applicable | Blocked | Not applicable | Not applicable |
| **Server actions** | | | | |
| Add a work order (`createWorkOrder()`) | Not applicable | Blocked | Not applicable | Not applicable |
| Add a draft invoice (`addDraftInvoice()`) | Not applicable | Blocked | Not applicable | Not applicable |
| Approve an invoice (from the screen) (`approveInvoice()`) | Not applicable | Not applicable | Blocked | Not applicable |
| Sign in (`signIn()`) | Blocked | Not applicable | Not applicable | Not applicable |
| Sign out (`signOut()`) | Not applicable | Not applicable | Blocked | Not applicable |

**275 attempts. 256 blocked. 19 got through.**

- **Control 1:** Company A can read and add to its own data, so "Blocked" does not just mean broken. 30 of 30 attempts on its own data worked, including a server action sent the same way as the blocked ones.
- **Control 2:** One table left open on purpose shows as "Got through", so the script is shown to catch a leak. 16 of 16 attempts on it got through. The table is created for the run and removed afterwards.

### Roles inside one company

Inside one company, some actions are meant for some roles only. The script tried each as staff, approver and owner at Saltmere Boatworks, and read the result back from the database.

| Action | Meant for | Staff | Approver | Owner |
|---|---|---|---|---|
| Approve a draft supplier invoice | Approver, owner | **Allowed, not intended** (F-06) | Allowed | Allowed |
| Send an approved invoice to the accounts system | Approver, owner | Refused | Allowed | Allowed |
| Delete a draft supplier invoice | Owner | Refused | Refused | Allowed |
| Delete a work order | Owner | Refused | Refused | Allowed |
| Delete an invoice file | Approver, owner | Refused | Allowed | Allowed |
| Read the accounts connection's stored tokens | Nobody (server only) | **Allowed, not intended** (F-05) | **Allowed, not intended** (F-05) | **Allowed, not intended** (F-05) |
| Change a person's role (staff to owner) | Owner | Refused | Refused | Allowed |
| Remove a person from the yard | Owner | Refused | Refused | Allowed |
| Rename the yard | Owner | Refused | Refused | Allowed |

27 attempts. 23 as intended. 4 not as intended.

## 5 Findings

14 findings, most serious first. The lines named are printed under each finding, as they were at the reviewed commit.

The steps under "How to see it yourself" run in the sample project, which is in a private repository and can be shared. In a real review they run against the reviewed app's development environment.

| # | Severity | Area | Finding |
|---|---|---|---|
| F-01 | Critical | Security | A person signed in at one yard can open and edit another yard's supplier invoices |
| F-02 | Critical | Security | Anyone with an account can make themselves the owner of any yard |
| F-03 | Critical | Security | The invoice export can be downloaded without signing in |
| F-04 | Critical | Security | The cost summary shows every yard's work orders to every signed-in person |
| F-05 | High | Security | Every member of a yard can read its stored accounts-system tokens |
| F-07 | High | Money and outside writes | One invoice can reach the accounts system as two bills: after a timeout, or from a double click on Send |
| F-08 | High | Money and outside writes | A billing event that arrives twice adds the credits twice |
| F-13 | High | Security | The invoice route signs a download link for whatever file path a row holds, so one yard can fetch another yard's file |
| F-06 | Medium | Security | Staff can approve supplier invoices |
| F-09 | Medium | Money and outside writes | Spends made at the same moment can take the credit balance below zero |
| F-10 | Medium | Reliability | One yard's "too many requests" answer stops the nightly payment sync for every yard after it |
| F-11 | Low | Reliability | If the cron secret is ever missing, the words "Bearer undefined" start the nightly job |
| F-12 | Low | Maintainability | The secret key is read in 4 separate files, the webhook payload is loosely typed, and the money paths have no tests |
| F-14 | Low | Security | A member can record a work order, an invoice or a file under another person's name |

### F-01 A person signed in at one yard can open and edit another yard's supplier invoices

**Severity:** Critical · **Area:** 1 Security · **How hard to trigger:** Moderate. Needs a sign-in at any yard and the id of an invoice.

**File and line:** `app/api/invoices/[id]/route.ts:18-23`, `app/api/invoices/[id]/route.ts:57-60`

**What is wrong.** The route behind the invoice screen checks that someone is signed in, then loads the invoice with the secret-key client. That client skips every row rule in the database. The route never checks that the invoice belongs to the caller's yard. The edit handler (PATCH) in the same file does the same.

**Why it matters.** A staff member at one yard can open another yard's supplier invoice by putting its id in the address. The answer includes a working download link to the invoice file. The same person can overwrite the note and the supplier reference on it. Invoice ids are long random values, so the person needs to have seen one first; ids travel in links, exports and screenshots, and finding F-02 hands them over.

**Suggested fix.** Read and update the invoice with the signed-in person's own client so the row rules decide, as the send route in the next folder already does. Create download links only after that read has succeeded, and sign them with the person's own client too (F-13). Longer term, put all data access in one module so that no route can skip the yard check.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. As the staff member at Saltmere Boatworks, ask for an invoice that belongs to Dunmarrow Slipway: `pnpm as a-staff app GET /api/invoices/b0000000-0000-4000-8000-000000000023`
3. The answer is HTTP 200 and holds Dunmarrow's invoice (reference DUN-INV-1003) with a download link for its file.
4. Change it: `pnpm as a-staff app PATCH /api/invoices/b0000000-0000-4000-8000-000000000023 '{"notes":"changed from another yard"}'`. The answer is HTTP 200 and the note is changed.

**Code path.** GET → getSignedInUser() (sign-in only) → createAdminClient() → .eq('id', id), with no yard in the query.

**How it was found.** The company separation check: all three Saltmere roles got Dunmarrow's invoice back and changed its note. A signed-out visitor was refused.

`app/api/invoices/[id]/route.ts`, lines 18-23 (GET reads with the secret key):

```
  const admin = createAdminClient()
  const { data: invoice, error } = await admin
    .from('supplier_invoices')
    .select('*, work_orders(title), invoice_files(id, object_path)')
    .eq('id', id)
    .maybeSingle()
```

`app/api/invoices/[id]/route.ts`, lines 57-60 (PATCH writes with the secret key):

```
    .update({ ...(notes ? { notes } : {}), ...(reference ? { reference } : {}) })
    .eq('id', id)
    .select('id, notes, reference')
    .maybeSingle()
```

### F-02 Anyone with an account can make themselves the owner of any yard

**Severity:** Critical · **Area:** 1 Security · **How hard to trigger:** Easy. Needs any account and one request.

**File and line:** `supabase/migrations/0003_memberships.sql:51-53`

**What is wrong.** The rule for adding a row to the memberships table only checks that the row carries the caller's own user id. It does not check which yard the row names or which role it gives. So a signed-in person can add a row that makes them owner of a yard they have nothing to do with.

**Why it matters.** Every other rule in the database trusts this table to say who belongs where. Once a person has added themselves to another yard, the correctly written rules on work orders, supplier invoices, files, credits and the accounts connection all treat them as that yard's owner. After adding themselves to company B as owner, the person could read 2 work orders, 3 supplier invoices and 1 accounts connection of company B's through the ordinary policies. The row was then removed.

**Suggested fix.** Remove the insert rule: members never write this table themselves. Accepting an invite goes through one server-side function that checks the invite and takes the yard and the role from it, never from the request. Keep the test that a person cannot add themselves to another yard (it is in supabase/tests and fails today).

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. As the staff member at Saltmere Boatworks, add a membership at Dunmarrow Slipway: `pnpm as a-staff data POST /memberships '{"user_id":"me","company_id":"b0000000-0000-4000-8000-000000000002","role":"owner"}'`. The answer is HTTP 201.
3. Read Dunmarrow's invoices as the same person: `pnpm as a-staff data GET "/supplier_invoices?select=reference,supplier,amount_cents&company_id=eq.b0000000-0000-4000-8000-000000000002"`. Three invoices come back.
4. Stop the sample and start it again to put the data back.

**Code path.** POST /rest/v1/memberships → policy "people can join a yard" → with check (user_id = auth.uid()) passes for any company_id and any role.

**How it was found.** The company separation check: the Add attempt on memberships got through for all three Saltmere roles. The pgTAP test for this rule fails.

`supabase/migrations/0003_memberships.sql`, lines 51-53 (The insert rule checks the person, not the yard or the role):

```
create policy "people can join a yard"
  on public.memberships for insert to authenticated
  with check (user_id = (select auth.uid()));
```

### F-03 The invoice export can be downloaded without signing in

**Severity:** Critical · **Area:** 1 Security · **How hard to trigger:** Moderate. Needs no account, only a yard's id.

**File and line:** `app/api/export/route.ts:7-23`, `proxy.ts:39-41`

**What is wrong.** The export route has no sign-in check and no yard check of its own. It was written on the understanding that proxy.ts turns signed-out visitors away. But the proxy's matcher leaves out every address that starts with /api, so the proxy never runs for this route. The route then reads with the secret key, so the row rules do not apply either.

**Why it matters.** Anyone on the internet who has a yard's id can download that yard's full list of supplier invoices as a file: suppliers, references, amounts and approval dates. No account is needed. The id is a long random value, so it has to be seen first, for example in a link someone shared.

**Suggested fix.** Check sign-in and membership inside the handler, and read with the signed-in person's client. Treat proxy.ts as a convenience for redirects, not as the access check. The Next.js documentation says the same: Proxy should not be the only protection, and every route handler should verify access itself.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. Without signing in, ask for Dunmarrow Slipway's export: `pnpm as visitor app GET "/api/export?company=b0000000-0000-4000-8000-000000000002"`
3. The answer is HTTP 200 and a CSV file with Dunmarrow's three supplier invoices.

**Code path.** GET /api/export → proxy.ts not run (matcher excludes api) → handler has no getSignedInUser() → secret-key client → .eq('company_id', companyId) with the id taken from the address.

**How it was found.** The company separation check: the signed-out visitor and all three Saltmere roles downloaded Dunmarrow's export.

`app/api/export/route.ts`, lines 7-23 (No sign-in or yard check; reads with the secret key):

```
export async function GET(request: NextRequest) {
  const companyId = request.nextUrl.searchParams.get('company')
  if (!isUuid(companyId)) return new Response('Choose a yard', { status: 400 })

  // The export includes who approved each invoice, which members cannot read
  // through their own client.
  const supabase = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SECRET_KEY!,
    { auth: { persistSession: false, autoRefreshToken: false } },
  )

  const { data, error } = await supabase
    .from('supplier_invoices')
    .select('reference, supplier, amount_cents, status, approved_by, approved_at, sent_at, work_orders(title)')
    .eq('company_id', companyId)
    .order('created_at')
```

`proxy.ts`, lines 39-41 (The proxy does not run for addresses under /api):

```
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}
```

### F-04 The cost summary shows every yard's work orders to every signed-in person

**Severity:** Critical · **Area:** 1 Security · **How hard to trigger:** Easy. Needs any account and one request.

**File and line:** `supabase/migrations/0006_views.sql:3-15`

**What is wrong.** The view work_order_costs was created without the security_invoker setting. A view made that way runs with its creator's rights and skips the row rules of the tables under it. The dashboard filters by yard, so the screen looks right, but the Data API returns every yard's rows to any signed-in person who asks.

**Why it matters.** A person at one yard can list every other yard's work orders with their titles, quoted prices, approved costs and invoice counts. That is a competitor's job list and margins. It takes an ordinary account and one request.

**Suggested fix.** Recreate the view with (security_invoker = true) so that the rules on work_orders and supplier_invoices apply to it. Keep the test that every view in the exposed schema has that setting (it is in supabase/tests and fails today).

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. As the staff member at Saltmere Boatworks, read the view: `pnpm as a-staff data GET "/work_order_costs?select=title,quoted_cents,approved_cost_cents"`
3. The answer lists four work orders: Saltmere's two and Dunmarrow Slipway's two.

**Code path.** GET /rest/v1/work_order_costs → view owned by the migration role, no security_invoker → the policies on work_orders and supplier_invoices are not applied.

**How it was found.** The company separation check: all three Saltmere roles read Dunmarrow's rows through the view. Two pgTAP tests for this rule fail.

`supabase/migrations/0006_views.sql`, lines 3-15 (The view is created without security_invoker):

```
create view public.work_order_costs as
select
  w.id as work_order_id,
  w.company_id,
  w.title,
  w.quoted_cents,
  coalesce(sum(i.amount_cents) filter (where i.status <> 'draft'), 0)::integer as approved_cost_cents,
  count(i.id)::integer as invoice_count
from public.work_orders w
left join public.supplier_invoices i on i.work_order_id = w.id
group by w.id;

grant select on public.work_order_costs to authenticated;
```

### F-05 Every member of a yard can read its stored accounts-system tokens

**Severity:** High · **Area:** 1 Security · **How hard to trigger:** Easy. Needs a staff account at the yard and one request.

**File and line:** `supabase/migrations/0004_tokens.sql:7-8`, `supabase/migrations/0004_tokens.sql:18-20`

**What is wrong.** The integration_tokens table holds each yard's access token and refresh token for the accounts system, as plain text. A "members can read" rule was added so the settings page can show whether the yard is connected. That rule lets every member of the yard, in any role, read the whole row, tokens included.

**Why it matters.** A refresh token is a long-lived key to the yard's accounting data. Any staff member, or anyone who gets hold of a staff member's session, can copy it and then act in the accounts system as the yard, outside this app and outside its records. Another yard cannot read it: the rule does pin the yard. The exposure is inside each yard.

**Suggested fix.** Remove the member rule from this table. Give the settings page a server-side function that returns only whether the yard is connected and the renewal date. Encrypt the token columns so that a copy of the database does not expose them.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. As the staff member at Saltmere Boatworks, read the table: `pnpm as a-staff data GET "/integration_tokens?select=provider,refresh_token"`
3. The answer is HTTP 200 with Saltmere's refresh token in plain text (a made-up local value).

**Code path.** GET /rest/v1/integration_tokens → policy "members can read" → the row is returned with access_token and refresh_token.

**How it was found.** The roles check: staff, approver and owner each read the refresh token. The pgTAP test for this rule fails. Across yards the table was blocked.

`supabase/migrations/0004_tokens.sql`, lines 7-8 (Tokens are stored as plain text):

```
  access_token text not null,
  refresh_token text not null,
```

`supabase/migrations/0004_tokens.sql`, lines 18-20 (Every member may read the whole row):

```
create policy "members can read"
  on public.integration_tokens for select to authenticated
  using (company_id in (select private.my_company_ids()));
```

### F-07 One invoice can reach the accounts system as two bills: after a timeout, or from a double click on Send

**Severity:** High · **Area:** 2 Money and outside writes · **How hard to trigger:** Easy. A double click on Send is enough. So is one slow or lost answer from the accounts system, with nobody doing anything wrong.

**File and line:** `lib/accounts/push.ts:33-34`, `lib/accounts/push.ts:64-70`, `app/api/invoices/[id]/send/route.ts:29-34`

**What is wrong.** pushInvoice() makes a new duplicate-protection key inside its retry loop, so every attempt carries a different key. If the accounts system creates the bill but its answer is lost or late, the retry looks like a brand-new bill. The key is saved on the invoice only after a success, so nothing links the first bill to the invoice. Separately, the send route reads the invoice's status, sees "approved" and sends, without first marking the invoice as being sent. Two requests that arrive together both see "approved" and both send, each with its own key.

**Why it matters.** The yard ends up with two bills in its accounts for one supplier invoice, and may pay the supplier twice. Only the second bill is recorded in Harrowquay, so nobody is told about the first. In the first test, one lost answer left 2 bills for the same invoice with 2 different keys. In the second, nothing failed at all: Send was pressed twice at the same moment and 2 bills were created.

**Suggested fix.** Create the key once, when the invoice is approved, and store it on the invoice (the push_key column is already there). Send that same key on every attempt. Before calling the accounts system, mark the invoice as being sent in one conditional update (status approved to sending) and stop if that update changed no row. Save the accounts reference as soon as it arrives. Before retrying after a timeout, ask the accounts system whether a bill with that key already exists.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. In a second terminal run the two tests: `pnpm repro F-07`
3. The first test tells the mock accounts system to create the next bill but lose its answer, then sends invoice SALT-INV-1002 as the Saltmere approver. It passes when the mock holds two bills for that one invoice, each with a different key.
4. The second test fails nothing. It sends the same invoice twice at the same moment while the mock takes a third of a second to answer. It passes when the mock again holds two bills for the one invoice.

**Code path.** POST /api/invoices/[id]/send → pushInvoice() → the for loop → const pushKey = randomUUID() inside the loop → the first call times out after the bill was created → the second call carries a new key. And: two POSTs together → both read status 'approved' → both call pushInvoice().

**How it was found.** Two tests against the mock accounts API, which honours a repeated key (the control test shows one bill when the same key is sent twice).

`lib/accounts/push.ts`, lines 33-34 (A new duplicate-protection key on every attempt):

```
  for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
    const pushKey = randomUUID()
```

`lib/accounts/push.ts`, lines 64-70 (The key is saved only after a success):

```
        .update({
          status: 'sent',
          push_key: pushKey,
          accounts_ref: bill.id,
          sent_at: new Date().toISOString(),
        })
        .eq('id', invoice.id)
```

`app/api/invoices/[id]/send/route.ts`, lines 29-34 (The status is read and the bill is sent, with nothing claiming the invoice in between):

```
  if (invoice.status !== 'approved') {
    return NextResponse.json({ error: 'Only an approved invoice can be sent' }, { status: 409 })
  }

  try {
    const result = await pushInvoice(invoice)
```

### F-08 A billing event that arrives twice adds the credits twice

**Severity:** High · **Area:** 2 Money and outside writes · **How hard to trigger:** Moderate. Nobody has to do anything wrong: billing providers deliver an event again after a timeout.

**File and line:** `app/api/webhooks/billing/route.ts:24-39`, `supabase/migrations/0005_billing.sql:12`

**What is wrong.** The billing webhook checks the signature correctly. It then adds the credits to the ledger and afterwards records the event, without first asking whether this event id was handled before. The event_id column has an index but no unique rule, so the database does not stop a second row either.

**Why it matters.** Billing providers send the same event more than once as a matter of course, for example after a timeout on their side. Each repeat gives the yard the credit pack again for free. The operator loses revenue and the ledger no longer matches what was paid. In the test, one purchase of 250 credits delivered twice left 2 ledger entries and a balance of 600 where 350 was paid for.

**Suggested fix.** Add a unique rule on billing_events.event_id. Record the event and add the credits in one database transaction. When the event id is already there, answer 200 and do nothing.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. In a second terminal run the test: `pnpm repro F-08`
3. The test delivers one "credits purchased" event twice, each time with a fresh valid signature.
4. The test passes when the ledger holds two entries for that one event.

**Code path.** POST /api/webhooks/billing → verifySignature() passes → insert into credit_ledger → insert into billing_events, with no lookup of event.id and no unique rule on event_id.

**How it was found.** A test that signs and delivers the same event twice. The signature tests on the same route all pass.

`app/api/webhooks/billing/route.ts`, lines 24-39 (Credits are added before the event is recorded, and nothing asks whether it was seen before):

```
  if (event.type === 'credits.purchased') {
    const { error } = await supabase.from('credit_ledger').insert({
      company_id: event.data.company_id,
      delta: event.data.credits,
      reason: 'Credit pack purchased',
      event_id: event.id,
    })
    if (error) return NextResponse.json({ error: 'Could not add credits' }, { status: 500 })
  }

  // Keep a record of every event we have handled.
  await supabase.from('billing_events').insert({
    event_id: event.id,
    type: event.type,
    company_id: event.data?.company_id ?? null,
    payload: event,
```

`supabase/migrations/0005_billing.sql`, line 12 (An index on the event id, but no unique rule):

```
create index billing_events_event_idx on public.billing_events (event_id);
```

### F-13 The invoice route signs a download link for whatever file path a row holds, so one yard can fetch another yard's file

**Severity:** High · **Area:** 1 Security · **How hard to trigger:** Moderate. Needs a sign-in at any yard, the stored path of the other yard's file, and a request made by hand.

**File and line:** `app/api/invoices/[id]/route.ts:27-31`, `supabase/migrations/0008_policies.sql:65-67`

**What is wrong.** The invoice route makes short-lived download links for an invoice's files. It signs them with the secret-key client, for whatever path is stored in the file row. That path is free text: the rule for adding a file row checks that the row belongs to the caller's yard, but not that the path points into that yard's folder. So a member can add a file row to one of their own invoices that names another yard's file, and the route signs a working link to it. The file store's own rules would refuse this person; the secret key skips them.

**Why it matters.** A staff member at one yard can download a supplier invoice file that belongs to another yard. They need the file's stored path: the other yard's id, the invoice id and the file name. This does not depend on F-01. The invoice the person opens is their own, so fixing F-01 alone leaves it open. It is rated High and not Critical because it takes a request made by hand and three details that are hard to come by.

**Suggested fix.** Sign download links with the signed-in person's own client, so the file store's rules decide. Add a rule that a file row's path must start with the row's own yard id, as a check constraint or in the insert rule: with check (object_path like company_id::text || '/%'). Keep the attempt in the company separation check so that it cannot come back unnoticed.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. As the staff member at Saltmere Boatworks, add a file row to one of Saltmere's own invoices that names Dunmarrow Slipway's file: `pnpm as a-staff data POST /invoice_files '{"company_id":"a0000000-0000-4000-8000-000000000001","invoice_id":"a0000000-0000-4000-8000-000000000021","object_path":"b0000000-0000-4000-8000-000000000002/b0000000-0000-4000-8000-000000000023/supplier-invoice.pdf"}'`. The answer is HTTP 201.
3. Open that invoice of Saltmere's own as the same person: `pnpm as a-staff app GET /api/invoices/a0000000-0000-4000-8000-000000000021`. The answer is HTTP 200 and holds a download link.
4. Open the link. It returns Dunmarrow's file, which holds the words "dunmarrow-only file".
5. Stop the sample and start it again to put the data back.

**Code path.** POST /rest/v1/invoice_files → policy "members add invoice files" → with check (company_id in ...) passes for any object_path. Then GET /api/invoices/[id] → admin.storage.createSignedUrl(file.object_path), signed with the secret key.

**How it was found.** Reading the route: the links are signed with the secret key, so the question was where the path comes from. The company separation check makes the attempt on every run: all three Saltmere roles got a link that returned Dunmarrow's file. A signed-out visitor could not add the row.

`app/api/invoices/[id]/route.ts`, lines 27-31 (Links are signed with the secret key, for whatever path the row holds):

```
  const files = await Promise.all(
    (invoice.invoice_files as Array<{ id: string; object_path: string }>).map(async (file) => {
      const { data } = await admin.storage
        .from('invoice-files')
        .createSignedUrl(file.object_path, 300)
```

`supabase/migrations/0008_policies.sql`, lines 65-67 (The insert rule checks the yard, not the path):

```
create policy "members add invoice files"
  on public.invoice_files for insert to authenticated
  with check (company_id in (select private.my_company_ids()));
```

### F-06 Staff can approve supplier invoices

**Severity:** Medium · **Area:** 1 Security · **How hard to trigger:** Easy. Needs a staff account at the yard and one request.

**File and line:** `supabase/migrations/0007_functions.sql:5-7`, `supabase/migrations/0007_functions.sql:18-23`

**What is wrong.** approve_invoice() runs with its owner's rights so that it can change the status column, which members cannot write. It checks that the caller belongs to the invoice's yard, but not the caller's role. It also has no fixed search_path, and it sits in the schema the Data API exposes, where any signed-in person can call it.

**Why it matters.** Approval exists so that a second, more senior person agrees before a bill goes to the accounts system. Today any staff member can approve the invoices they entered themselves. The screen hides the button from staff, but the function does not refuse. A member of another yard is refused: the yard check works.

**Suggested fix.** Check the role inside the function (owner or approver). Add set search_path = '' and write every table name in full. Move the function out of the exposed schema, or keep a thin wrapper there.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. As the staff member at Saltmere Boatworks, call the function on a draft invoice: `pnpm as a-staff data POST /rpc/approve_invoice '{"invoice_id":"a0000000-0000-4000-8000-000000000021"}'`
3. The answer is HTTP 200 and the invoice comes back with its status set to approved.

**Code path.** POST /rest/v1/rpc/approve_invoice → security definer → membership check without a role → update supplier_invoices set status = 'approved'.

**How it was found.** The roles check: staff approved a draft invoice. Two pgTAP tests for these rules fail.

`supabase/migrations/0007_functions.sql`, lines 5-7 (Runs with its owner's rights, with no fixed search_path):

```
create function public.approve_invoice(invoice_id uuid)
returns public.supplier_invoices
language plpgsql security definer
```

`supabase/migrations/0007_functions.sql`, lines 18-23 (Checks the yard, not the role):

```
  if not exists (
    select 1 from public.memberships m
    where m.user_id = auth.uid() and m.company_id = inv.company_id
  ) then
    raise exception 'Not a member of this yard' using errcode = '42501';
  end if;
```

### F-09 Spends made at the same moment can take the credit balance below zero

**Severity:** Medium · **Area:** 2 Money and outside writes · **How hard to trigger:** Moderate. Needs a member's account and two requests at the same moment (a double click can do it).

**File and line:** `lib/credits/spend.ts:19-26`

**What is wrong.** spendCredits() reads the balance, compares it with the cost, and then writes the spend as a separate step. Requests that arrive together all read the same balance and all pass.

**Why it matters.** A yard can use more paid features than it has bought: by a double click, by two people working at once, or on purpose with a script. In the test, 10 spends of 100 credits were sent at once against a balance of 100. 4 were accepted and the balance ended at -300.

**Suggested fix.** Do the check and the write in one database function that locks the yard's balance first. Or keep one balance row per yard with a rule that refuses a negative value.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. In a second terminal run the test: `pnpm repro F-09`
3. The test passes when more than one of the ten spends is accepted and the balance is below zero.

**Code path.** POST /api/credits/spend → spendCredits() → getBalance() → if (balance < units) → insert, with nothing holding the balance still between the read and the write.

**How it was found.** A test that sends ten spends at once with credit for one.

`lib/credits/spend.ts`, lines 19-26 (The balance is read, then the spend is written as a separate step):

```
  const balance = await getBalance(companyId)
  if (balance < units) return { ok: false, balance }

  const admin = createAdminClient()
  const { error } = await admin
    .from('credit_ledger')
    .insert({ company_id: companyId, delta: -units, reason, created_by: userId })
  if (error) throw error
```

### F-10 One yard's "too many requests" answer stops the nightly payment sync for every yard after it

**Severity:** Medium · **Area:** 3 Reliability · **How hard to trigger:** Moderate. Nobody has to do anything wrong: one yard reaching its rate limit during the run is enough.

**File and line:** `app/api/cron/sync-payments/route.ts:29-31`, `lib/accounts/client.ts:23-24`

**What is wrong.** The nightly job works through all connected yards in one loop, with no error handling for each yard. The first error from the accounts system ends the whole run. The waiting time that comes with a "too many requests" answer is ignored. Nothing records how far the run got, and nothing stops two runs from working at the same time. The job has a 60-second limit and no check of how much time is left.

**Why it matters.** On a night when one yard reaches its rate limit, every yard later in the list keeps showing invoices as unpaid that have been paid. Nobody is told, because a failed run leaves no record, and the hosting platform does not run a failed cron job again. In the test with five yards, the second yard was answered "too many requests": the job updated 1 of the 5 yards and never called the accounts system for the last 3. In a second test, two runs started together both did the whole job.

**Suggested fix.** Handle each yard on its own: catch its error, record the result for that yard in sync_runs, and carry on with the next. Wait as long as Retry-After says before trying that yard again. Start each run with the yards that were not synced last time. Take a lock so that a second run exits at once. Stop cleanly before the time limit.

**How to see it yourself.**

1. Start the sample: `pnpm sample:up`.
2. In a second terminal run the tests: `pnpm repro F-10`
3. The first test sets up five yards and tells the mock accounts system to answer "too many requests" for the second. It passes when only the first yard's invoice is marked paid and yards three to five were never asked about.
4. The second test starts two runs at once. It passes when both runs call the accounts system for every yard.

**Code path.** GET /api/cron/sync-payments → for (const connection of connections) → fetchPayments() throws on 429 → the handler ends with HTTP 500 before sync_runs is written.

**How it was found.** Two tests against the mock accounts API, with a control test in which all five yards are updated.

`app/api/cron/sync-payments/route.ts`, lines 29-31 (One loop over all yards, with no error handling for each yard):

```
  for (const connection of connections ?? []) {
    const company = connection.companies as unknown as { accounts_ref: string }
    const payments = await fetchPayments(company.accounts_ref, connection.access_token)
```

`lib/accounts/client.ts`, lines 23-24 (Any refusal is thrown; Retry-After is not read):

```
  if (!response.ok) {
    throw new Error(`Accounts system answered ${response.status} for ${companyRef}`)
```

### F-11 If the cron secret is ever missing, the words "Bearer undefined" start the nightly job

**Severity:** Low · **Area:** 3 Reliability · **How hard to trigger:** Hard. Only possible if the CRON_SECRET setting is missing. It is set today.

**File and line:** `app/api/cron/sync-payments/route.ts:10`

**What is wrong.** The job compares the request's header with the text "Bearer " followed by the CRON_SECRET setting. When the setting is missing, that text becomes "Bearer undefined", and a request that sends exactly those words is accepted.

**Why it matters.** The secret is set today, so this is not open now. It opens without any warning if the setting is ever lost: a new environment, a renamed variable, a preview deployment. Then anyone can start the sync as often as they like, which uses up the accounts system's rate limit for every yard.

**Suggested fix.** Refuse the request when CRON_SECRET is missing, before comparing. Better still, stop the app from starting when a required setting is absent.

**How to see it yourself.**

1. Start the sample without the setting: `pnpm sample:up --no-cron-secret`.
2. In a second terminal run the test: `pnpm repro F-11`
3. The test passes when a request with the header "Authorization: Bearer undefined" is answered with HTTP 200 and a new row appears in sync_runs.

**Code path.** GET /api/cron/sync-payments → `Bearer ${process.env.CRON_SECRET}` → "Bearer undefined" when the setting is missing.

**How it was found.** Reading the handler, then a test with the app started without the setting. With the setting present the same header is refused.

`app/api/cron/sync-payments/route.ts`, line 10 (With the setting missing, the expected text becomes "Bearer undefined"):

```
  if (request.headers.get('authorization') !== `Bearer ${process.env.CRON_SECRET}`) {
```

### F-12 The secret key is read in 4 separate files, the webhook payload is loosely typed, and the money paths have no tests

**Severity:** Low · **Area:** 4 Maintainability · **How hard to trigger:** Does not apply. Not a way in. This is about upkeep.

**File and line:** `lib/supabase/admin.ts:4-6`, `app/api/webhooks/billing/route.ts:16`

**What is wrong.** The secret key is read in 4 files (app/api/cron/sync-payments/route.ts, app/api/export/route.ts, app/api/webhooks/billing/route.ts, lib/supabase/admin.ts), and 0 of them are marked server-only. Three of the four build their own client instead of using the shared one. The webhook payload is typed "any" (1 loose type in the code). The app has 1 test file, and none of the code that sends bills, keeps the credit ledger or handles the webhook has a test.

**Why it matters.** Each place that creates the secret-key client is a place where the next developer can skip the yard check without noticing: F-01 and F-03 both began that way. A loosely typed payload means that a change on the billing provider's side fails while the app is running instead of while it is being built. Without tests on the money paths, F-07 to F-09 can come back after they are fixed.

**Suggested fix.** One module creates the secret-key client, starts with import 'server-only', and is the only file allowed to read the key (a lint rule can hold that line). Describe the webhook payload with a schema and parse it. Add tests for sending a bill twice, a repeated billing event and spends at the same moment: the ones written for this review can be kept.

**Code path.** A search for every read of SUPABASE_SECRET_KEY, a search for loose types, and the list of test files.

**How it was found.** Reading the code with three searches: every read of the secret key, every loose type, and the list of test files against the list of modules.

`lib/supabase/admin.ts`, lines 4-6 (The shared secret-key client, not marked server-only):

```
export function createAdminClient() {
  return createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SECRET_KEY!, {
    auth: { persistSession: false, autoRefreshToken: false },
```

`app/api/webhooks/billing/route.ts`, line 16 (The payload is typed any):

```
  const event: any = JSON.parse(rawBody)
```

### F-14 A member can record a work order, an invoice or a file under another person's name

**Severity:** Low · **Area:** 1 Security · **How hard to trigger:** Easy. Needs a member's account and a request made by hand. It stays inside the person's own yard.

**File and line:** `supabase/migrations/0002_work.sql:58-65`, `supabase/migrations/0008_policies.sql:19-21`

**What is wrong.** Work orders, supplier invoices and invoice files each record who added them (created_by or uploaded_by). The app's own actions fill in created_by correctly. But members may write every column of a new row, and no rule ties those columns to the caller, so a request sent straight to the Data API can name anyone.

**Why it matters.** The record of who entered an invoice is what an owner looks at when something is wrong. A staff member can enter an invoice and have it show the owner, or a colleague, as the person who added it. Nothing leaves the yard and no money moves, which is why this is Low. In the test, staff added 3 of 3 rows recorded as the owner, one in each table.

**Suggested fix.** Give created_by and uploaded_by a default of auth.uid() and add created_by = (select auth.uid()) to the insert rules. Or grant insert on named columns only, leaving these two out, so that the default always applies.

**Code path.** POST /rest/v1/work_orders with created_by set to another person's id → the insert grant covers the column → policy "members add work orders" checks only company_id.

**How it was found.** Reading the column grants beside the insert rules, then a test that adds one row to each of the three tables as staff with the owner's id.

`supabase/migrations/0002_work.sql`, lines 58-65 (Insert is granted on every column, created_by and uploaded_by included):

```
grant select, insert, delete on public.work_orders to authenticated;
grant update (title, status, quoted_cents) on public.work_orders to authenticated;

grant select, insert, delete on public.supplier_invoices to authenticated;
grant update (supplier, reference, amount_cents, notes, work_order_id)
  on public.supplier_invoices to authenticated;

grant select, insert, delete on public.invoice_files to authenticated;
```

`supabase/migrations/0008_policies.sql`, lines 19-21 (The insert rules check the yard, not who the row says added it):

```
create policy "members add work orders"
  on public.work_orders for insert to authenticated
  with check (company_id in (select private.my_company_ids()));
```

## 6 What was checked

### Area 1: Security: separation between companies, sign-in and permission checks, OAuth and token storage, webhooks, public forms and file uploads

| What was checked | How | Result |
|---|---|---|
| Row security switched on for every table | A query over the database catalog; a pgTAP test | Checked, nothing found. 9 tables, all on. |
| Row rules: one yard cannot reach another yard's rows (yards, work orders, supplier invoices, invoice files, credit ledger) | Each rule read line by line; the company separation check; pgTAP tests | Checked, nothing found. Every attempt blocked, including moving an own row into another yard and pointing an own row at another yard's work order. |
| Row rules: what a member may write into a new row of their own yard | Each insert rule read beside the column grants; a test that adds rows under another person's name; a file row that names another yard's file | Problem found: F-13, F-14. The yard is checked. The file path and the name of the person who added the row are not. |
| Row rules on the memberships table | Read; the company separation check; a pgTAP test | Problem found: F-02 |
| Views | Catalog query for security_invoker; the company separation check | Problem found: F-04 |
| Database functions that the Data API can call | Catalog query (definer rights, search_path, who may call); the roles check | Problem found: F-06 |
| Token storage for the accounts connection | Read; the roles check | Problem found: F-05 |
| Every use of the secret-key (service role) client | A search for every read of the key; each use read for its own sign-in and yard check | Problem found: F-01, F-03, F-13. 7 files use it. The webhook, the cron job, sending a bill and spending credits each check before they use it. The invoice route also signs file links with it. |
| API routes: a sign-in and permission check inside every handler | Every route.ts listed from the app folder (7 handlers) and read; each called as three roles of another yard and as a visitor | Problem found: F-01, F-03. The other 4 handlers were blocked. |
| Server actions called directly, without the screen | Listed from the build (5 actions); each sent as a direct POST as three roles of another yard and as a visitor | Checked, nothing found |
| The request filter (proxy.ts) | Read; signed-out requests to pages and to /api | Problem found: F-03. It protects pages. It does not run for /api, and one route relied on it. |
| Who is signed in, as the server sees it | Read: every server read of the session | Checked, nothing found. The server verifies the token (getClaims) and never trusts the cookie's own copy of the user. |
| Webhook signature | Read; five tests (no signature, wrong secret, altered body, old timestamp, malformed header) | Checked, nothing found. All five refused; no credits added. |
| File uploads and the file store | Bucket settings from the catalog; nine kinds of cross-yard attempt (list, download, a link, a link signed by the app, upload, overwrite, two moves, delete); upload limit tests | Problem found: F-13. Private bucket, 5 MB limit, PDF and images only. A web page and a 6 MB file were refused, and so was every direct attempt on another yard's file. The app's own invoice route signed a link to one. |
| Secrets in the browser | Every NEXT_PUBLIC_ name read; the built browser files searched for the keys and their prefixes | Checked, nothing found. 14 built files searched, no match. |
| Caching of one yard's data | A search for cache settings; the dashboard loaded as one yard, then as the other | Checked, nothing found |
| Framework version against published advisories | `pnpm audit` on the app's installed packages, which include the framework | Checked, nothing found. Next.js 16.5.0: no known advisory on 3 December 2026. |
| Sign-in flow with the accounts system (OAuth) | - | Not checked. The sample stores tokens but has no connect screen. In a real review the callback, the state value, token renewal and what happens when a connection is removed are read in full. |
| Public forms | - | Not checked. The sample has none. In a real review each public form is read for input checks, size limits, rate limits, and where its uploads and its data end up. |
| Realtime | - | Not checked. The sample does not use it. |
| Supabase Security Advisor lints | - | Not checked. Not run in this sample. The catalog queries above test three of the same conditions (a view that skips row rules, a function without a fixed search_path, a table without row security) and show F-04 and F-06. In a real review the Security Advisor is run against the reviewed project. |

### Area 2: Money and writes to other systems: bills sent to the accounts system, billing and the credit ledger, changes made by automations

| What was checked | How | Result |
|---|---|---|
| Bills sent to the accounts system: duplicate protection and retries | Read; a test in which the accounts system creates the bill but its answer is lost; a test that sends one invoice twice at the same moment | Problem found: F-07 |
| Who may send a bill | Read; the roles check; the company separation check | Checked, nothing found. Owner and approver only, and only for their own yard. |
| Billing webhook: the same event delivered twice | A test that delivers one signed event twice | Problem found: F-08 |
| Credit ledger: spends at the same moment | A test that sends ten spends at once | Problem found: F-09 |
| Credit ledger: who can write to it | The company separation check; a pgTAP test | Checked, nothing found. Members can read their own ledger and cannot write to any. |
| Amounts | Read | Checked, nothing found. Whole cents in integer columns, with a rule that an invoice amount is above zero. |
| Automations that change records in another application | - | Not checked. The sample makes one kind of outside write, the bill. In a real review each automation's writes are read for duplicate protection, what happens when a run stops halfway, and what it is able to overwrite. |
| Billing events that arrive out of order | - | Not checked. The sample handles one kind of event, so order cannot matter yet. |
| Subscriptions | - | Not checked. The sample sells credit packs only. |

### Area 3: Reliability: background jobs and cron, sync correctness, error handling

| What was checked | How | Result |
|---|---|---|
| Nightly job: one failure and the yards after it | A test with five yards and one "too many requests" answer | Problem found: F-10 |
| Nightly job: rate limits, two runs at once, time limit | Read; a test that starts two runs together | Problem found: F-10 |
| Nightly job: who can start it | Read; tests with the secret set and with it missing | Problem found: F-11. With the secret set, a missing or wrong secret is refused. |
| Sync correctness: a paid bill marks the right invoice, once | Read; a control test in which all five yards are updated | Checked, nothing found. The update is tied to the yard and the bill, and skips invoices already marked. |
| Retries on writes to the accounts system | Read; the test for F-07 | Problem found: F-07 |
| Error answers | Every handler and action read | Checked, nothing found. Fixed wording only; no database messages or stack traces are sent back. |
| Jobs scheduled inside the database (pg_cron) | - | Not checked. The sample schedules its one job on the hosting platform. |

### Area 4: Code quality and maintainability: structure, duplication, types, tests

| What was checked | How | Result |
|---|---|---|
| Structure: where data access lives | A search for every place the secret-key client is created | Problem found: F-12 |
| Types | The type checker in strict mode; a search for loose types | Problem found: F-12. Strict mode passes. 1 loose type, on the webhook payload. |
| Tests | The list of test files against the list of modules | Problem found: F-12 |
| Checking of input at the edges | Every route and action read | Checked, nothing found. Ids, lengths and number ranges are checked in one small module before any query. |
| Database schema: keys and rules | Every migration read | Checked, nothing found. Foreign keys tie an invoice to a work order of the same yard; amounts and statuses have rules. |
| Errors inside database functions | The Supabase CLI's database lint (supabase db lint) on the local database | Checked, nothing found. No issues reported. This lint looks for mistakes inside functions; it is not the Security Advisor. |
| Migrations apply to an empty database | The run starts from a clean database every time | Checked, nothing found. 9 migrations applied in order. |
| Dependencies with known advisories | `pnpm audit` on the app's installed packages against the public advisory database | Checked, nothing found. 0 advisories in 80 packages on 3 December 2026. |

## 7 Known issues

In a real review this section lists the issues the app's owner already knows about. They are not reported again in section 5. Each one is listed here in the owner's own wording, with what the review found: confirmed as described, more serious than thought, or already fixed.

Example rows, to show the format. This sample has no list of known issues; a real report uses the owner's.

| The owner's wording | What the review found | Status |
|---|---|---|
| Example: "There are no tests on the code that sends bills" | Confirmed as described. Covered once, in F-12, where the tests written for this review are offered as a start. | As described |
| Example: "Staff must not approve invoices; the button is hidden for them" | The button is hidden, but the function behind it still accepts staff. See F-06. | More serious |
| Example: "Not sure the billing webhook turns away fake requests" | It does. Five kinds of bad signature were refused and no credits were added. The same route has a different problem, repeats, which is F-08. | Not a problem |

## 8 How the checks were run

Every check runs with one command, `pnpm checks`, from a clean database. It was run on 3 December 2026 at commit c97c68a and took 49 seconds, with the local stack already running. It finished with exit code 0: every result matched this report.

1. Start the local Supabase stack with the Supabase CLI: Postgres 17.6, Auth, the Data API and Storage, in containers on the reviewer's machine.
2. Reset the database and apply all 9 migrations from scratch.
3. Seed two yards with three people each, rows in every table and one file each.
4. Build and start the sample app, and a mock accounts API that honours a repeated key and limits calls.
5. Run the pgTAP policy tests: 28 assertions, 22 passed and 6 failed. The 6 that fail are the rules that findings F-02, F-04, F-05 and F-06 say are not kept.
6. Run the company separation check: 275 attempts on 24 tables, views, functions, file stores, routes and server actions. Then the roles check: 27 attempts.
7. Run the money, reliability, upload and record tests: 13 tests, 13 passed. A test named "reproduces" passes when the problem is seen again.
8. Read the code and the build: where the secret key is used, what reaches the browser, caching, types and tests. Check the installed packages against the public advisory database.

The command exits with 0 when the run and this report agree: every "Got through" has a finding, every finding was seen again, both controls behaved and nothing was left untested. With `--strict` it exits with 1 while anything gets through, which is how it would run on a real codebase.

**The app and its flaws were written for this sample, so that the report has something to show. The checks and their results are real. A review of a real codebase finds what is there, not what was written into this one.**

In a real review the starting point is the app owner's list of known issues and a development environment with test data. The report comes in this format, and the reviewer walks the owner through it.

The sample project, with every command named in this report, is in a private repository and can be shared. In a real review the same steps run against the reviewed app's development environment.

---

Reference build by Bereket A. · fictional data
