Sample report · read-only review

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.

Contents

1What 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.

2Summary

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.

  • Critical4
  • High4
  • Medium3
  • Low3
  • 8Security
  • 3Money and outside writes
  • 2Reliability
  • 1Maintainability

Top 5 to fix before launch

  1. Stop people adding themselves to other yardsCriticalF-02
  2. Make the invoice route check whose invoice it is, and whose fileCriticalF-01HighF-13
  3. Put a sign-in and yard check inside the export routeCriticalF-03
  4. Make the cost view follow the row rules, and take the accounts tokens out of members' reachCriticalF-04HighF-05
  5. Send each bill once, with one fixed key, and make the billing webhook ignore repeatsHighF-07F-08

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.

3How to read this report

SeverityWhat it meansWhen to fix
CriticalSomeone 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.
HighSerious 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.
MediumHarm under specific conditions, or a failure that costs time and trust but not data.Fix in the first weeks.
LowSmall, hard to reach, or about upkeep.Fix in normal work.
How hard to triggerWhat it means
EasyOne ordinary request from an ordinary account.
ModerateNeeds a piece of information (an id), particular timing, or a failure somewhere else.
HardNeeds something else to go wrong first.
Does not applyNot 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.

Back to contents

4Company 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.

Company A is Saltmere Boatworks. Company B is Dunmarrow Slipway. 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.

275 attempts. 256 blocked. 19 got through.

What happened when company A and a visitor tried to reach company B's data
Tried onReadAddChangeDelete
Tables
Billing eventsbilling_eventsBlockedBlockedBlockedBlocked
YardscompaniesBlockedBlockedBlockedBlocked
Credit ledgercredit_ledgerBlockedBlockedBlockedBlocked
Accounts connection tokensintegration_tokensBlockedBlockedBlockedBlocked
Invoice file recordsinvoice_filesBlockedBlockedBlockedBlocked
Who belongs to which yardmembershipsBlockedGot through F-02BlockedBlocked
Supplier invoicessupplier_invoicesBlockedBlockedBlockedBlocked
Nightly sync logsync_runsBlockedBlockedBlockedBlocked
Work orderswork_ordersBlockedBlockedBlockedBlocked
View
Cost summarywork_order_costsGot through F-04Not applicableNot applicableNot applicable
Function
Approve an invoiceapprove_invoice()Not applicableNot applicableBlockedNot applicable
File store
Invoice filesinvoice-filesGot through F-13BlockedBlockedBlocked
Routes
Spend creditsPOST /api/credits/spendNot applicableNot applicableBlockedNot applicable
Nightly payment syncGET /api/cron/sync-paymentsNot applicableNot applicableBlockedNot applicable
Invoice exportGET /api/exportGot through F-03Not applicableNot applicableNot applicable
Open an invoiceGET /api/invoices/[id]Got through F-01Not applicableNot applicableNot applicable
Edit an invoicePATCH /api/invoices/[id]Not applicableNot applicableGot through F-01Not applicable
Send a billPOST /api/invoices/[id]/sendNot applicableNot applicableBlockedNot applicable
Billing webhookPOST /api/webhooks/billingNot applicableBlockedNot applicableNot applicable
Server actions
Add a work ordercreateWorkOrder()Not applicableBlockedNot applicableNot applicable
Add a draft invoiceaddDraftInvoice()Not applicableBlockedNot applicableNot applicable
Approve an invoice (from the screen)approveInvoice()Not applicableNot applicableBlockedNot applicable
Sign insignIn()BlockedNot applicableNot applicableNot applicable
Sign outsignOut()Not applicableNot applicableBlockedNot applicable
  • 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.
Show the attempts: 19 got through, 275 in all
Tried onActionAsWhat was triedOutcomeWhat came back
Who belongs to which yardmembershipsAddSaltmere owneradd a row to company BGot throughno error returned; company B's data changed; with the new membership in place the same person could read 2 work orders, 3 supplier invoices and 1 accounts connection of company B's
Who belongs to which yardmembershipsAddSaltmere approveradd a row to company BGot throughno error returned; company B's data changed; with the new membership in place the same person could read 2 work orders, 3 supplier invoices and 1 accounts connection of company B's
Who belongs to which yardmembershipsAddSaltmere staffadd a row to company BGot throughno error returned; company B's data changed; with the new membership in place the same person could read 2 work orders, 3 supplier invoices and 1 accounts connection of company B's
Cost summarywork_order_costsReadSaltmere ownerlist company B's rowsGot through2 of company B's rows returned
Cost summarywork_order_costsReadSaltmere approverlist company B's rowsGot through2 of company B's rows returned
Cost summarywork_order_costsReadSaltmere stafflist company B's rowsGot through2 of company B's rows returned
Invoice filesinvoice-filesReadSaltmere ownerget the app to sign a link to company B's file through an own invoiceGot throughthe file row was accepted; HTTP 200 with a link that returned company B's file
Invoice filesinvoice-filesReadSaltmere approverget the app to sign a link to company B's file through an own invoiceGot throughthe file row was accepted; HTTP 200 with a link that returned company B's file
Invoice filesinvoice-filesReadSaltmere staffget the app to sign a link to company B's file through an own invoiceGot throughthe file row was accepted; HTTP 200 with a link that returned company B's file
Invoice exportGET /api/exportReadSaltmere ownerdownload company B's invoice exportGot throughHTTP 200; the file held 3 of company B's invoices
Invoice exportGET /api/exportReadSaltmere approverdownload company B's invoice exportGot throughHTTP 200; the file held 3 of company B's invoices
Invoice exportGET /api/exportReadSaltmere staffdownload company B's invoice exportGot throughHTTP 200; the file held 3 of company B's invoices
Invoice exportGET /api/exportReadSigned-out visitordownload company B's invoice exportGot throughHTTP 200; the file held 3 of company B's invoices
Open an invoiceGET /api/invoices/[id]ReadSaltmere owneropen company B's invoice by its idGot throughHTTP 200; the answer held company B's invoice and a download link that returned company B's file
Open an invoiceGET /api/invoices/[id]ReadSaltmere approveropen company B's invoice by its idGot throughHTTP 200; the answer held company B's invoice and a download link that returned company B's file
Open an invoiceGET /api/invoices/[id]ReadSaltmere staffopen company B's invoice by its idGot throughHTTP 200; the answer held company B's invoice and a download link that returned company B's file
Edit an invoicePATCH /api/invoices/[id]ChangeSaltmere owneredit the note on company B's invoiceGot throughHTTP 200; company B's data changed
Edit an invoicePATCH /api/invoices/[id]ChangeSaltmere approveredit the note on company B's invoiceGot throughHTTP 200; company B's data changed
Edit an invoicePATCH /api/invoices/[id]ChangeSaltmere staffedit the note on company B's invoiceGot throughHTTP 200; company B's data changed

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.

What each role at Saltmere Boatworks could do
ActionMeant forStaffApproverOwner
Approve a draft supplier invoiceMeant for: Approver, ownerApprover, ownerAllowed, not intended F-06AllowedAllowed
Send an approved invoice to the accounts systemMeant for: Approver, ownerApprover, ownerRefusedAllowedAllowed
Delete a draft supplier invoiceMeant for: OwnerOwnerRefusedRefusedAllowed
Delete a work orderMeant for: OwnerOwnerRefusedRefusedAllowed
Delete an invoice fileMeant for: Approver, ownerApprover, ownerRefusedAllowedAllowed
Read the accounts connection's stored tokensMeant for: Nobody (server only)Nobody (server only)Allowed, not intended F-05Allowed, not intended F-05Allowed, not intended F-05
Change a person's role (staff to owner)Meant for: OwnerOwnerRefusedRefusedAllowed
Remove a person from the yardMeant for: OwnerOwnerRefusedRefusedAllowed
Rename the yardMeant for: OwnerOwnerRefusedRefusedAllowed

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

Back to contents

5Findings

14 findings, most serious first. Each file and line opens the code at the reviewed commit.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.

  1. F-01CriticalA person signed in at one yard can open and edit another yard's supplier invoicesSecurity
  2. F-02CriticalAnyone with an account can make themselves the owner of any yardSecurity
  3. F-03CriticalThe invoice export can be downloaded without signing inSecurity
  4. F-04CriticalThe cost summary shows every yard's work orders to every signed-in personSecurity
  5. F-05HighEvery member of a yard can read its stored accounts-system tokensSecurity
  6. F-07HighOne invoice can reach the accounts system as two bills: after a timeout, or from a double click on SendMoney and outside writes
  7. F-08HighA billing event that arrives twice adds the credits twiceMoney and outside writes
  8. F-13HighThe invoice route signs a download link for whatever file path a row holds, so one yard can fetch another yard's fileSecurity
  9. F-06MediumStaff can approve supplier invoicesSecurity
  10. F-09MediumSpends made at the same moment can take the credit balance below zeroMoney and outside writes
  11. F-10MediumOne yard's "too many requests" answer stops the nightly payment sync for every yard after itReliability
  12. F-11LowIf the cron secret is ever missing, the words "Bearer undefined" start the nightly jobReliability
  13. F-12LowThe secret key is read in 4 separate files, the webhook payload is loosely typed, and the money paths have no testsMaintainability
  14. F-14LowA member can record a work order, an invoice or a file under another person's nameSecurity
F-01CriticalArea 1: Security

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

How hard to trigger: Moderate. Needs a sign-in at any yard and the id of an invoice.

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.

File and line

  • GET reads with the secret key
  • PATCH writes with the secret key
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.
F-02CriticalArea 1: Security

Anyone with an account can make themselves the owner of any yard

How hard to trigger: Easy. Needs any account and one request.

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.

File and line

  • The insert rule checks the person, not the yard or the role
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.
F-03CriticalArea 1: Security

The invoice export can be downloaded without signing in

How hard to trigger: Moderate. Needs no account, only a yard's id.

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.

File and line

  • No sign-in or yard check; reads with the secret key
  • The proxy does not run for addresses under /api
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.
F-04CriticalArea 1: Security

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

How hard to trigger: Easy. Needs any account and one request.

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.

File and line

  • The view is created without security_invoker
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.
F-05HighArea 1: Security

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

How hard to trigger: Easy. Needs a staff account at the yard and one request.

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).

File and line

  • Tokens are stored as plain text
  • Every member may read the whole row
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.
F-07HighArea 2: Money and outside writes

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

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.

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.

File and line

  • A new duplicate-protection key on every attempt
  • The key is saved only after a success
  • The status is read and the bill is sent, with nothing claiming the invoice in between
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).
F-08HighArea 2: Money and outside writes

A billing event that arrives twice adds the credits twice

How hard to trigger: Moderate. Nobody has to do anything wrong: billing providers deliver an event again after a timeout.

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.

File and line

  • Credits are added before the event is recorded, and nothing asks whether it was seen before
  • An index on the event id, but no unique rule
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.
F-13HighArea 1: Security

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

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.

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.

File and line

  • Links are signed with the secret key, for whatever path the row holds
  • The insert rule checks the yard, not the path
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.
F-06MediumArea 1: Security

Staff can approve supplier invoices

How hard to trigger: Easy. Needs a staff account at the yard and one request.

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.

File and line

  • Runs with its owner's rights, with no fixed search_path
  • Checks the yard, not the role
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.
F-09MediumArea 2: Money and outside writes

Spends made at the same moment can take the credit balance below zero

How hard to trigger: Moderate. Needs a member's account and two requests at the same moment (a double click can do it).

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.

File and line

  • The balance is read, then the spend is written as a separate step
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.
F-10MediumArea 3: Reliability

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

How hard to trigger: Moderate. Nobody has to do anything wrong: one yard reaching its rate limit during the run is enough.

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.

File and line

  • One loop over all yards, with no error handling for each yard
  • Any refusal is thrown; Retry-After is not read
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.
F-11LowArea 3: Reliability

If the cron secret is ever missing, the words "Bearer undefined" start the nightly job

How hard to trigger: Hard. Only possible if the CRON_SECRET setting is missing. It is set today.

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.

File and line

  • With the setting missing, the expected text becomes "Bearer undefined"
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.
F-12LowArea 4: Maintainability

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

How hard to trigger: Does not apply. Not a way in. This is about upkeep.

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.

File and line

  • The shared secret-key client, not marked server-only
  • The payload is typed any
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.
F-14LowArea 1: Security

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

How hard to trigger: Easy. Needs a member's account and a request made by hand. It stays inside the person's own yard.

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.

File and line

  • Insert is granted on every column, created_by and uploaded_by included
  • The insert rules check the yard, not who the row says added it
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.

Back to contents

6What was checked

One table for each area, in the order of priority. Rows where nothing was found are listed with the rest, and so are the things that were not checked.

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

What was checkedHowResult
Row security switched on for every tableA query over the database catalog; a pgTAP testChecked, nothing found9 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 testsChecked, nothing foundEvery 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 yardEach 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 fileProblem foundF-13F-14The yard is checked. The file path and the name of the person who added the row are not.
Row rules on the memberships tableRead; the company separation check; a pgTAP testProblem foundF-02
ViewsCatalog query for security_invoker; the company separation checkProblem foundF-04
Database functions that the Data API can callCatalog query (definer rights, search_path, who may call); the roles checkProblem foundF-06
Token storage for the accounts connectionRead; the roles checkProblem foundF-05
Every use of the secret-key (service role) clientA search for every read of the key; each use read for its own sign-in and yard checkProblem foundF-01F-03F-137 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 handlerEvery route.ts listed from the app folder (7 handlers) and read; each called as three roles of another yard and as a visitorProblem foundF-01F-03The other 4 handlers were blocked.
Server actions called directly, without the screenListed from the build (5 actions); each sent as a direct POST as three roles of another yard and as a visitorChecked, nothing found
The request filter (proxy.ts)Read; signed-out requests to pages and to /apiProblem foundF-03It protects pages. It does not run for /api, and one route relied on it.
Who is signed in, as the server sees itRead: every server read of the sessionChecked, nothing foundThe server verifies the token (getClaims) and never trusts the cookie's own copy of the user.
Webhook signatureRead; five tests (no signature, wrong secret, altered body, old timestamp, malformed header)Checked, nothing foundAll five refused; no credits added.
File uploads and the file storeBucket 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 testsProblem foundF-13Private 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 browserEvery NEXT_PUBLIC_ name read; the built browser files searched for the keys and their prefixesChecked, nothing found14 built files searched, no match.
Caching of one yard's dataA search for cache settings; the dashboard loaded as one yard, then as the otherChecked, nothing found
Framework version against published advisoriespnpm audit on the app's installed packages, which include the frameworkChecked, nothing foundNext.js 16.5.0: no known advisory on 3 December 2026.
Sign-in flow with the accounts system (OAuth)—Not checkedThe 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 checkedThe 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 checkedThe sample does not use it.
Supabase Security Advisor lints—Not checkedNot 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 checkedHowResult
Bills sent to the accounts system: duplicate protection and retriesRead; 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 momentProblem foundF-07
Who may send a billRead; the roles check; the company separation checkChecked, nothing foundOwner and approver only, and only for their own yard.
Billing webhook: the same event delivered twiceA test that delivers one signed event twiceProblem foundF-08
Credit ledger: spends at the same momentA test that sends ten spends at onceProblem foundF-09
Credit ledger: who can write to itThe company separation check; a pgTAP testChecked, nothing foundMembers can read their own ledger and cannot write to any.
AmountsReadChecked, nothing foundWhole cents in integer columns, with a rule that an invoice amount is above zero.
Automations that change records in another application—Not checkedThe 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 checkedThe sample handles one kind of event, so order cannot matter yet.
Subscriptions—Not checkedThe sample sells credit packs only.

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

What was checkedHowResult
Nightly job: one failure and the yards after itA test with five yards and one "too many requests" answerProblem foundF-10
Nightly job: rate limits, two runs at once, time limitRead; a test that starts two runs togetherProblem foundF-10
Nightly job: who can start itRead; tests with the secret set and with it missingProblem foundF-11With the secret set, a missing or wrong secret is refused.
Sync correctness: a paid bill marks the right invoice, onceRead; a control test in which all five yards are updatedChecked, nothing foundThe update is tied to the yard and the bill, and skips invoices already marked.
Retries on writes to the accounts systemRead; the test for F-07Problem foundF-07
Error answersEvery handler and action readChecked, nothing foundFixed wording only; no database messages or stack traces are sent back.
Jobs scheduled inside the database (pg_cron)—Not checkedThe sample schedules its one job on the hosting platform.

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

What was checkedHowResult
Structure: where data access livesA search for every place the secret-key client is createdProblem foundF-12
TypesThe type checker in strict mode; a search for loose typesProblem foundF-12Strict mode passes. 1 loose type, on the webhook payload.
TestsThe list of test files against the list of modulesProblem foundF-12
Checking of input at the edgesEvery route and action readChecked, nothing foundIds, lengths and number ranges are checked in one small module before any query.
Database schema: keys and rulesEvery migration readChecked, nothing foundForeign keys tie an invoice to a work order of the same yard; amounts and statuses have rules.
Errors inside database functionsThe Supabase CLI's database lint (supabase db lint) on the local databaseChecked, nothing foundNo issues reported. This lint looks for mistakes inside functions; it is not the Security Advisor.
Migrations apply to an empty databaseThe run starts from a clean database every timeChecked, nothing found9 migrations applied in order.
Dependencies with known advisoriespnpm audit on the app's installed packages against the public advisory databaseChecked, nothing found0 advisories in 80 packages on 3 December 2026.

Back to contents

7Known 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 wordingWhat the review foundStatus
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

Back to contents

8How 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.

Commit
c97c68a8a74207029994c9623323f48fc9f6663a
Versions
Supabase CLI 2.75.0, Postgres 17.6, Next.js 16.5.0, supabase-js 2.120.0, @supabase/ssr 0.12.7, Node v24.13.0
Run again
pnpm install && pnpm --dir sample-app install && pnpm checksThe 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.

Back to contents