Keeping businesses apart without row-level security
Why Highreel runs on a single Cloudflare Worker, and how one data layer, a test that reads the SQL and a script that attacks the API keep every business inside its own data.
Highreel is one Nuxt app, deployed as one Cloudflare Worker. Everything it needs is attached to that Worker as a binding:
| Piece | What runs it |
|---|---|
| Pages and API | One Worker (Nitro's cloudflare_module preset), with the static files served as Worker assets |
| Database | D1, Cloudflare's SQLite database, stored in the EU |
| Logos and photos | R2, a private bucket that browsers only reach through signed links |
| Sign-in | Better Auth, running inside the Worker, with its tables in D1 |
| Sign-in emails | Cloudflare Email Sending |
| Cleanup jobs | Cron Triggers |
It's a Worker rather than a Cloudflare Pages project because Pages can't run Cron Triggers, and the privacy policy promises things that need them, like deleting demo accounts after 30 days.
Why Cloudflare and not Supabase
I started building on Supabase, which is what I'd normally reach for: Postgres, auth and file storage in one place. Before anything went live, I switched to Cloudflare, for reasons that come from this product in particular:
- It's seasonal. Most businesses will send their Highreels in the first weeks of December. Supabase's free plan pauses a project after a week without activity, and a paused project would break every link a customer had already been sent. That means paying for an always-on plan all year, for a product that's quiet for most of it.
- The traffic is media-heavy. A campaign for 10,000 customers with two group photos is roughly 10 GB of downloads. R2 doesn't charge for downloads at all.
- The base cost was already paid. Forevermore runs on Cloudflare, and the paid Workers plan covers the whole account, not one project. Highreel lives in the same account, so it adds nothing to the base bill.
- There's one thing to deploy. Database, files, sign-in, email and scheduled jobs are all bindings on the same Worker. Local development emulates every one of them without Docker, and a release is a single deploy.
That choice had a price, though. D1 doesn't have the feature that makes Supabase so pleasant to build on.
What row-level security does for you
With Supabase, Postgres knows who's signed in, and row-level security (RLS) lets the database itself refuse rows that don't belong to them. If a route has a bug and forgets a WHERE clause, the database still won't return another business's data. It's a safety net under all of your application code. (I wrote about using it, together with column grants, in Forevermore's architecture post.)
D1 is SQLite, and SQLite has no idea who's signed in. Every query can see every row. For a product where many businesses upload their customer lists into the same tables, "every business sees only its own data" is the rule that matters most, and without RLS it has to be enforced by application code. So that code needs a shape that makes the rule hard to break.
One rule: routes never write SQL
Every workspace route starts the same way. requireUser checks the session and returns a Db, which is the database binding plus the signed-in user's business id. The route passes it to the data layer and never touches the database itself:
export default defineEventHandler(async (event) => {
const { db } = await requireUser(event) // { d1, businessId }
return loadSignedWorkspace(event, db, requireUuid(getRouterParam(event, 'id')))
})
All of the workspace's SQL lives in one file, server/utils/db.ts. Apart from the lookup that finds the signed-in user's business in the first place, every statement in it binds db.businessId and filters by it, on reads, updates and deletes alike. Customer rows don't carry a business id of their own, so they're reached through their campaign:
export async function recipientPage(db: Db, campaignId: string, after = -1, limit = PAGE_ROWS) {
const { results } = await db.d1.prepare(`select ${RECIPIENT_COLUMNS} from recipients
where campaign_id = ?
and campaign_id in (select id from campaigns where business_id = ?)
and row_index > ?
order by row_index limit ?`).bind(campaignId, db.businessId, after, limit).all()
// ...
}
The campaign id comes from the URL, so on its own it proves nothing. The second condition is what makes the query safe: if the campaign belongs to another business, nothing matches, and the route answers as if the campaign didn't exist.
There's a nice side effect too. In a typical Supabase app, the browser queries the database directly and RLS decides what it's allowed to do. Here the browser never talks to the database at all. Every read and write goes through a route, and the routes run the same validators the spreadsheet grid uses, so nothing reaches the database without being checked first.
Some things have no function at all
Postgres can also limit which columns a user may write. The equivalent here is simpler: if a business must never change something, the data layer has no function that changes it. Nothing in the workspace can write the view and share counters (only the public page's own events do), rewrite the log of emails sent, or remove an address from the list of ones that bounced.
That send log, for example, is what enforces each email account's daily limit. A business that could clear it could also get around the limit. You can't call a function that doesn't exist, so the question never comes up.
Checking the rule twice
A convention is only as strong as the last change that followed it. So the rule is checked from two directions.
A test that reads the SQL
tests/isolation.test.ts opens the data layer as plain text, finds every .prepare(...) call along with its .bind(...) arguments, and fails if a statement doesn't bind the business id, or touches a business's table without filtering by it:
const OWNED = ['campaigns', 'recipients', 'email_optouts', 'email_sends', 'email_connections', 'email_bounces', 'payments']
test.each(cases)('%s: %s… binds the business', (_fn, _sql, s) => {
expect(s.bind, s.sql).toContain('db.businessId')
})
test.each(cases)('%s: %s… filters by it', (_fn, _sql, s) => {
const sql = s.sql.toLowerCase()
if (mentions(sql, 'recipients'))
expect(sql).toMatch(/campaigns\b[^;]*business_id = \?|business_id = \?[^;]*\bcampaigns\b/)
for (const table of OWNED.filter(t => mentions(sql, t)))
expect(sql).toMatch(/business_id = \?|insert into \w+ \([^)]*business_id/)
})
The same file also checks that no route, and no file outside the data layer, ever touches the database.
It's a blunt tool. It reads text and doesn't really understand SQL. But it runs in milliseconds on every commit, and it does catch the mistake it exists for: when I deleted the business filter from a single delete statement on purpose, it failed straight away. Breaking your own code on purpose to see whether a test notices has a name, mutation testing, and it's the quickest way to find out if a test is actually checking anything.
A script that attacks the API
A test that reads SQL can't see what a route does with a request. check:isolation runs against the dev server with two real sessions. Business A uploads a sheet, publishes it, adds a photo and a logo, and connects an email account. Then business B calls every workspace route using A's ids: read the campaign, edit a row, clear the sheet, publish, download the links, send the emails, start a checkout. Every single one has to come back 404:
const attempts = {
'GET campaign': await B.call(c),
'PATCH campaign': await B.call(c, 'PATCH', { name: 'Stolen', business: { name: 'Stolen' } }),
'DELETE campaign': await B.call(c, 'DELETE'),
'GET rows': await B.call(`${c}/recipients`),
'POST publish': await B.call(`${c}/publish`, 'POST'),
'GET links file': await B.call(`${c}/export.csv`),
'POST send': await B.call(`${c}/send`, 'POST', {}),
'PATCH A\'s row': await B.call(`/api/recipients/${aRow.id}`, 'PATCH', { column: 'first_name', value: 'Stolen' }),
// ... and every other workspace route
}
for (const [name, r] of Object.entries(attempts))
check(`B: ${name} → 404`, r.status === 404, r.status)
Afterwards, the script checks that A's campaign, rows, files and email account are exactly as they were before B started.
The two checks cover each other's blind spots. The test sees every statement, including ones no route calls yet. The script sees real HTTP behavior, including a bug that lives in a route rather than in the SQL.
Why 404 and not 403
When B asks for A's campaign, the answer is "not found", not "forbidden". A 403 would confirm that the id exists and belongs to somebody, which is information nobody should get for free. From B's side, A's campaign simply isn't there. The admin routes follow the same rule: anyone who isn't an admin gets a 404, so those routes don't even admit they exist.
The public Highreel pages are the one place that reads data without a session. They find a row by its link's token alone, a random 12-character id (about 71 bits, far too many to guess), and they never accept a business or campaign id from the request.
Running next to the database
The last architecture problem showed up after launch, and it had nothing to do with code.
Signed-in pages felt slow from Pristina. The Worker's logs told a strange story: each request used 4 to 13 ms of CPU but took 540 to 730 ms in total. The reason was geography. A Worker runs in whichever Cloudflare location the visitor happens to reach, and my connection's IPv6 traffic lands in Rio de Janeiro. The D1 database lives in Frankfurt. Every query crossed the Atlantic and back, about 180 ms each, and a signed-in request made three in a row before doing any of its own work: the session, then its user, then the business.
Three changes fixed it:
- Run the Worker where the data is. One line of config pins it to Frankfurt. Static files are still served from the visitor's nearest location, and a dynamic request makes the long trip once, instead of once per query.
- Make fewer round trips. Better Auth now loads the session and its user in a single joined query, and a route runs independent queries together, with
Promise.allor one D1batch(), never one after another. - Don't make a page ask who you are. Signed-in pages carry the session in their HTML, so a page's first data request no longer waits behind a separate "who's signed in?" request.
// Run next to the database. D1's primary is in Frankfurt; without this the
// Worker runs wherever the visitor lands, and every query crosses back.
"placement": { "region": "aws:eu-central-1" },
The Worker's time for /api/business went from 540 ms to between 31 and 227 ms, and a signed-in request in my browser went from about a second to about half that. Running code at the edge is great for work that doesn't need a database. Once a request makes several queries, it's usually faster to run it next to the data and pay for the distance once.
The takeaway
Row-level security is a safety net. Without it you need two things instead: one narrow place where every query lives, and tests that check that place from the inside (the SQL itself) and from the outside (the real API).
