Skip to the lesson
CivOps AI Academy · F08Sign-in That Denies by Default: Every Route Closed Until the Matrix Opens It
0%

Chapter 1 · Session 9

Who may sign in: invitations, company email and two-step

Nobody can create their own account: public sign-up has been off since Session 1. This chapter sets the rest of the sign-in rules in Supabase, by a person, in the dashboard: where sign-in links may send people, how long an invitation lasts, two-step codes, and the company's own email for sending invitations.

30 min2 stepsDashboard settings, by a person

By the end of this chapter you can

  • Tell authentication (who you are) from authorisation (what you may do), and say which part of the platform answers each.
  • Set Supabase's sign-in addresses, invitation lifetime and two-step codes for the live project.
  • Send sign-in emails through the company's own email service, with its password typed by a person and recorded by name only.

Two questions, answered in two places

Authentication answers who are you? Authorisation answers what may you do? A platform that lets anyone who is signed in open any page has the first and not the second, and OWASP treats them as separate controls for that reason [1]. Supabase Auth answers the first: it checks the password and the two-step code, and gives the browser a session [2]. Your role matrix answers the second, on every request: in the database since Session 8, and from this session in front of every page and API route too.

Authentication and authorisationAuthentication answers who you are; the session carries that answer; authorisation, from the matrix, decides what you may do on each request. AuthenticationWho are you?password + two-step codeanswered by Supabase AuthSessiona signed token in a cookiesays who you areexpires and is refreshedAuthorisationWhat may you do?role and scope from the matrixchecked on every requestSigning in proves who you are. It grants nothing by itself: the matrix decides what you may open.
Two questions, one session between them. Supabase Auth answers the first; the matrix from Session 7 answers the second, on every request.

Who gets an account, and how

RuleIn this platformWhy
Invitation onlyAn owner invites each person from the Supabase dashboard; sign-up stays offA plant platform is not public. Nobody gets an account by finding the address
One person, one loginNever a shared login such as press3, even on a shared tabletEvery record must say who made it; the matrix's scopes and no-self-approval rule depend on it
Password plus two-step for leads and managersQuality lead, manager and admin must enter a six-digit code from an authenticator appThe more a role can approve or change, the stronger its sign-in must be [4]
The company's own emailInvitations and password resets go through the company's email serviceSupabase's built-in email is for trying things out, not for inviting a plant's staff [3]
Shared tablets on the floorA press tablet used by two shifts: each operator signs in personally and is signed out at the shift change. Shift A · operator #2214signed outShift B · operator #3107signed out00:0006:0012:0018:0000:00One tablet at press 3, two people: each signs in personally; the shift change signs the last one outNever a shared login: every record must say which person made it
One tablet, two shifts, two people. Personal sign-in, and sign-out at the shift change, keep every record traceable. Session 12 makes sign-in on a shared tablet quick.
Step 1

Set the sign-in rules for the live project

10 minutes

Why

Supabase sends people back to your platform after they click an invitation or reset link, and only to addresses you have listed. If the list is wrong, links open a blank page or the wrong site. The invitation's lifetime decides whether a person invited at the end of a shift can still accept it next morning. These settings live in the live project, so a person sets them in the dashboard; they are not code.

Do this

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/url-configuration

Site URL: https://acme-platform.vercel.app. Under Redirect URLs add three: https://acme-platform.vercel.app/**, http://localhost:3000/** (your computer) and https://*-acme-ops.vercel.app/** (Vercel previews). Save.

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/providers

Check Allow new users to sign up is still off. Open Email: leave Confirm email on, and set Email OTP Expiration to 86400 seconds (one day, the longest Supabase allows). Save.

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/mfa

Check TOTP (App Authenticator) is Enabled. It is included on every Supabase plan.

You will see recreated screen

supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/url-configuration
UsersSign In / ProvidersMulti-FactorURL ConfigurationEmailsRate LimitsHooks
Site URL
Site URLhttps://acme-platform.vercel.app1
Redirect URLs
2
URL
https://acme-platform.vercel.app/**
http://localhost:3000/**
https://*-acme-ops.vercel.app/**
Save changes
The address list. Supabase only sends people back to addresses that match one of these.
  1. Where an email link lands when nothing else is said. Your live address, never localhost.
  2. The live site, your computer and Vercel's previews. Nothing else.

You will see recreated screen

supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/providers
UsersSign In / ProvidersMulti-FactorURL ConfigurationEmailsRate LimitsHooks
Allow new users to sign up1
Email
Confirm email
Email OTP Expiration (seconds)864002
Save
The email sign-in settings. Sign-up stays off; an invitation now lasts one day.
  1. Still off, as in Session 1. Invitations are the only way in.
  2. One day. Shorter, and an invitation sent at 15:00 is dead before the person's next shift.

Check it worked

Reload each page: the Site URL is https://acme-platform.vercel.app, the three redirect addresses are listed, sign-up is off, the expiry reads 86400 and TOTP is enabled.

Fastest path

Do all three pages in one sitting with the live address in front of you: copy https://acme-platform.vercel.app from Your names so it matches Vercel exactly, including any suffix.

If it goes wrong

The invitation link opens localhost, or a page that does not exist

The Site URL is wrong or the address is not in Redirect URLs. Set both as above; send a fresh invitation (the old link keeps the old address).

The next morning the invitation says the link is used or expired

We hit this: our invitations expired after 30 minutes, like an ordinary sign-in link. Set the expiry to 86400 and ask people to accept on the day they are invited. If it has expired, send the invitation again from Users. Step 4 also makes the link wait for a button press, because some company email scanners open every link in an email and use it up.

Allow new users to sign up is on

Turn it off now and check the Users list for anyone you did not invite. Delete any account you cannot explain, then tell owner two.

Step 2

Send sign-in emails through the company's email service

15 minutes

Why

Invitations and password resets are emails. Supabase's built-in sender is for trying things out: it sends only a few an hour and only to members of your Supabase team. Real invitations need the company's own email service. Its password is a key: a person types it into Supabase and the password manager, and it is recorded by name only, so it never passes through Claude Code or a chat.

Do this

Ask IT for the SMTP details of the company's email service (host, port, user name and password) for a sending address such as no-reply@acme.com, or for an account in a transactional email service opened in the company's name. IT should confirm the sending domain is verified. Put the password in the password manager as Email: platform sign-in SMTP password. Then:

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/smtp

Turn on Enable Custom SMTP. Sender email: no-reply@acme.com. Sender name: Acme Bottling platform. Host, port and user name from IT. Password: paste from the password manager, the value only. Save.

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/rate-limits

Set emails sent per hour to what a shift change needs (30 is a sensible start). Save.

Then record the new key by name, in Claude Code:

Paste into Claude Code
On a new branch docs/smtp-key, update docs/KEYS.md: add a row for "Email: platform sign-in SMTP password". It unlocks sending email as no-reply@acme.com. It lives in Supabase (Authentication, SMTP settings) and the company password manager, held by pat@acme.com and sam@acme.com. It is never in Vercel, GitHub, the repository or a chat. Last rotated: today's date. Names and places only, no values. Open a pull request titled "Key register: SMTP password" and show me the link.

You will see recreated screen

supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/smtp
UsersSign In / ProvidersMulti-FactorURL ConfigurationEmailsSMTP SettingsRate Limits
Enable Custom SMTP1
Sender emailno-reply@acme.com
Sender nameAcme Bottling platform
Hostsmtp.acme.com
Port587
Usernameno-reply@acme.com
Password••••••••••••••••2
Save changes
Custom SMTP on. The password field shows nothing once saved: nobody can read it back, which is what you want.
  1. On: Supabase now sends through your company's service, under your company's name.
  2. Paste the value only. Never NAME=value, never the variable's name.

Check it worked

The SMTP page shows Custom SMTP enabled with your sender, and the pull request adds one row to docs/KEYS.md with no value in it. Step 7's first invitation is the real test: it must arrive within a minute.

If it goes wrong

The settings save, but no email ever arrives

We hit this: a key that is there but wrong. In our Academy the value saved was the variable's own name, pasted in place of the key, so nothing complained and nothing was sent. Paste the password again from the password manager, the value only. Then check the email service's own log: a refused send names the reason (wrong password, sender not verified).

IT says the domain is not verified for sending

Wait for IT to add the records they need for the domain; emails from an unverified domain land in spam or are refused. Do not switch to a personal address to get going.

Claude Code asks for the SMTP password to finish the register

Answer: No. Record the name and where it lives only. The register never holds values.

Key or secretWhat it unlocksWhere it livesWho holds itNever
Email: platform sign-in SMTP passwordSending email as no-reply@acme.comSupabase SMTP settings and the password managerpat@acme.com, sam@acme.comNever in Vercel, GitHub, the repository or a chat
Supabase publishable (anon) keyWhat a signed-out visitor may ask for, which the gate and access rules limitVercel, synced (Session 1)Public by designNever relied on for protection
Supabase secret (service role) keyEverything, ignoring access rulesVercel, server onlyNobody copies itNever used by the gate, the sign-in pages or any browser code

Knowledge check

A person signs in successfully. What may they open?

Knowledge check

Why does the SMTP password go into Supabase's settings by a person, and not into a prompt?

References

  1. OWASP Authentication Cheat Sheet. https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
  2. Supabase Docs: Auth. https://supabase.com/docs/guides/auth
  3. Supabase Docs: Send emails with custom SMTP. https://supabase.com/docs/guides/auth/auth-smtp
  4. Supabase Docs: Multi-Factor Authentication. https://supabase.com/docs/guides/auth/auth-mfa
  5. Supabase Docs: Redirect URLs. https://supabase.com/docs/guides/auth/redirect-urls
  6. NIST SP 800-63-4, Digital Identity Guidelines. https://pages.nist.gov/800-63-4/

Chapter 2 · Session 9

Closed until the matrix opens it

Two prompts. The first builds the gate: one file, proxy.ts, that refuses every page and API route unless the route list generated from your matrix opens it to the person's role, with a second check next to the data. The second builds the sign-in pages: invitation, password, two-step code and an honest "forgot password".

40 min2 stepsDefault deny

By the end of this chapter you can

  • Say why every route is closed by default, and why closing them one by one fails.
  • Have Claude Code generate lib/access/routes.ts from docs/matrix.json and write proxy.ts, after reading the Next.js 16 guide in the repository.
  • Have Claude Code build sign-in pages that never claim an email was sent when it was not.

Open by default is how platforms leak

If each page or API route must remember to check sign-in for itself, the one nobody remembered is the one that leaks. In a prior build we counted 376 of 449 route handlers with no sign-in check at all, 242 of them able to change data; one returned a real customer's staff list to a browser that had never signed in, and had been open for up to 87 days. OWASP's rule is the opposite: deny by default, allow only what is listed [1]. Here, two lists open routes: a short list of public sign-in pages, by exact address, and the matrix. Everything else is refused.

The route guard's decisionA request is let through if it is public; otherwise an unsigned request goes to sign-in, a route not in the matrix is refused, and a role the matrix does not list for the route is refused. Request/reviewPublic route?/ and /sign-inSigned in?valid sessionnoIn the matrix?route listedyesRole allowed?matrix screensyesOpenyesSign-in pageno403 refusedno403 refusednoAllow
The gate's decision. Four questions in order. Only a public page, or a signed-in person whose role the matrix lists for that route, gets through.
The generated route tableNine routes: two public, six opened by the matrix to named roles, and a new route that nobody can open until the matrix lists it. RouteSourceWho may open it/sign-inpubliceveryone/auth/confirmpubliceveryone with an invitation link/operatormatrixoperator/reviewmatrixsupervisor/lotsmatrixquality lead (two-step)/dashboardmatrixsupervisor, quality lead, manager/admin/peoplematrixadmin (two-step)/api/holdsmatrixquality lead (two-step)/reports (new)not listednobody until the matrix opens it
The route list, generated from docs/matrix.json. A new /reports page is refused for everyone until a reviewed change to the matrix opens it.

Three locks, not one

Next.js runs one file, proxy.ts, before every page and route (in Next.js 16 it replaced middleware.ts) [2]. That makes it the place for the gate. But in March 2025 a flaw in Next.js (CVE-2025-29927) let a crafted request skip middleware entirely in some versions [3]. So the gate is the first lock, not the only one: every server action and API route checks the person's role again, from the database, before it reads or writes anything, as Next.js's own authentication guide recommends [4]. Row-level security from Session 8 is the third.

Three locksA request passes a route guard, then a server check next to the data, then row-level security in the database. Requestwith session cookie1 · Route guardproxy.ts, before any pageclosed unless the matrix opensthe route2 · Server checkin each server action and APIroutechecks the role again, next tothe data3 · Row-level securityinside the database (Session 8)returns only the rows in scopeAny one lock can have a bug. All three would have to fail together for data to leak.
Three locks. The gate, a server check next to the data, and row-level security. A leak needs all three to fail at once.
Step 3

One prompt: the gate, the route list and the server check

20 minutes

Why

Generating the route list from the matrix means the screens, the API and the database rules all come from one file, so they cannot drift apart. Asking for the gate, the generator, the server check and their tests in one prompt means the proof arrives with the change, and you never have a half-built gate on main. Telling Claude Code the edge cases we hit, up front, saves a round of fixes for each.

Do this

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
Before writing any code, read node_modules/next/dist/docs/ (the proxy file convention and the authentication guide): this is Next.js 16, where middleware is called proxy.ts. Then read Supabase's guide "Setting up server-side Auth for Next.js", docs/matrix.json, docs/INTENT.md and CLAUDE.md.

On a new branch access/sign-in-gate:

1. Add scripts/gen-routes.mjs and an npm script gen:routes that write lib/access/routes.ts from docs/matrix.json, with a header saying it is generated and must not be edited by hand. It holds: PUBLIC, the exact public paths (only /sign-in, /auth/confirm, /auth/set-password, /forgot-password and /status, as exact addresses, never folders); ROUTES, every page and every /api route the matrix lists, with the roles allowed; TWO_STEP, the roles that must use a two-step code (quality_lead, manager and admin: if the matrix has no field for this, add "two_step": true to those roles in docs/matrix.json in this branch); and a function decide(path, session) that returns allow, sign-in, two-step or forbidden. Anything not listed is forbidden.

2. Add a migration (npx supabase migration new access_token_roles) with a custom access token hook function that copies the person's roles and site from public.memberships into their token, following Supabase's guide for the custom access token hook, with the grants it needs and set search_path = ''. Turn the hook on in supabase/config.toml for local runs and CI. Do not turn it on in the live project: tell me what to click after merge.

3. Write proxy.ts at the root. It runs on every request except _next/static, _next/image and favicon.ico. It must never skip a path because it contains a dot: /api/report.pdf is checked like any other API path. It verifies the session with Supabase as the guide says (never trust getSession in server code), refreshes the cookies, and calls decide(). Signed out: pages redirect to /sign-in?next=<path>, /api routes answer 401. Two-step needed: redirect to /sign-in/two-step. Forbidden: 403. If the Supabase settings are missing or the check throws, refuse; never allow.

4. Add lib/access/require.ts with requireRole(...roles), which reads the person's current membership from the database, and call it at the top of every server action and /api route handler. List any you could not cover.

5. There must be no shortcut that fakes a signed-in user: no demo mode, no skip-auth flag, no built-in test user. Test users exist only in the local and CI database.

6. Add tests (npm test) for decide(): every public path allowed signed out; every listed route sends a signed-out person to sign-in; each listed role allowed; every other role forbidden; a two-step role without its code sent to two-step; /reports (not in the matrix) forbidden for every role; /api/report.pdf and /api/notes.md signed out refused. Show me one test failing with decide() changed to allow everything, then put it back.

Do not connect to or change the live project. Run the type check, the tests and the build. Push, open a pull request titled "Sign-in gate", wait for every check on GitHub to finish, and tell me in plain words which routes are public and who may open each of the rest. If a check fails, fix it and wait again before reporting.

You will see recreated screen

claude — acme-platform
⏺ Read(node_modules/next/dist/docs/01-app/03-api-reference/03-file-conventions/proxy.md)
⎿ Read 412 lines
1
⏺ Bash(npm run gen:routes)
⎿ Wrote lib/access/routes.ts: 5 public paths, 9 routes, 3 two-step roles
⏺ Write(proxy.ts)
+export async function proxy(request: NextRequest) {
+ const session = await verifiedSession(request); // null if none, expired or forged
+ const verdict = decide(request.nextUrl.pathname, session);
+ if (verdict === "allow") return refreshed(request);
+ if (verdict === "sign-in") return signIn(request); // pages: redirect; /api: 401
+ if (verdict === "two-step") return twoStep(request);
+ return new NextResponse("Not allowed", { status: 403 });
+}
+export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
2
⏺ Bash(npm test)
⎿ Test failed: 31 of 44 with decide() set to allow everything (shown on purpose). Restored: 44 passed
3
⏺ Bash(gh pr checks --watch)
⎿ ci / test pass 1m12s schema / test pass 2m03s
⏺ Pull request #31 is green. Public: /sign-in, /auth/confirm, /auth/set-password, /forgot-password and /status. Everything else is refused unless the matrix lists it: /operator for operators, /review for supervisors, /lots and /api/holds for the quality lead with a two-step code, /dashboard for supervisors, the quality lead and managers, /admin/people for the admin with a two-step code. After merging you need to turn the access token hook on in Supabase (Authentication, Hooks); step 6 of your lesson has the clicks. Every server action and API route now calls requireRole; none were left out.
Claude Code reads the Next.js 16 guide in your repository before it writes the gate, then waits for GitHub before reporting.
  1. It read the guide shipped with your version of Next.js. If it does not, stop it and say: Read node_modules/next/dist/docs first.
  2. The gate: one decision, from the generated list. The matcher skips only the framework's own files, never a path with a dot.
  3. Shown red first: the tests really fail when the gate is open.

Check it worked

Pull request Sign-in gate is green. Its files include proxy.ts (not middleware.ts), lib/access/routes.ts with the generated header, one new migration and lib/access/require.ts. Claude Code's summary lists who may open each route, and that list matches your matrix.

Fastest path

"Show me one test failing with the gate open" in the prompt proves the tests can fail, without a separate round trip to ask for it.

If it goes wrong

Claude Code wrote middleware.ts

It used what it remembered, not your version. Say: This is Next.js 16. Read node_modules/next/dist/docs/01-app/03-api-reference/03-file-conventions/proxy.md, rename the file to proxy.ts with the function named proxy, and run the tests again.

The matcher skips every path containing a dot

We hit this: our gate skipped dotted paths so images would load, and every API address ending in .pdf or .md was never checked. Say: Never skip /api paths for any reason. Exclude only _next/static, _next/image and favicon.ico, and add tests for /api/report.pdf and /api/notes.md signed out.

It added a demo mode, a skip-auth setting or a test login to make testing easier

We hit this: a demo switch left on in production made every visitor an administrator. Say: Remove every shortcut that fakes a signed-in user. Tests sign in real test users in the local database only.

lib/access/routes.ts was edited by hand, or the check says the route list is out of date

The list is generated. Say: Run npm run gen:routes, commit the result and show me what changed in the list. If a route appears that the matrix does not open, stop and tell me.

It reports green but a check on GitHub is red

Say: The check on the pull request is red. Read its log, fix the cause, and wait for green before you report. We trust the check on GitHub, never the summary.

Step 4

The sign-in pages: invitation, password, two-step and an honest reset

15 minutes

Why

The gate sends people to sign in, so the pages must work for a supervisor on a phone at shift start. We were locked out of our own production site by a reset page that said "Check your email" when nothing had been sent, so this prompt makes every page say what really happened, with the same answer for a known or unknown address so the page never reveals who has an account.

Do this

Paste into Claude Code
Read node_modules/next/dist/docs/ (authentication guide) and Supabase's server-side Auth guide for Next.js again. On a new branch access/sign-in-pages, build:

1. /sign-in: email and password. Plain-English errors. A "Forgot your password?" link. Fields 16 px or larger, buttons at least 44 px tall, works at 360 px wide.
2. /auth/confirm: where invitation and reset links land. It shows one button, "Accept invitation" (or "Set a new password"), and only uses the link's token when the button is pressed, so an email scanner that opens links cannot use it up. Then it goes to /auth/set-password.
3. /sign-in/two-step: for roles in TWO_STEP. The first time, it shows the QR code to add to an authenticator app and asks for a code to confirm it; after that it asks for the six-digit code at every sign-in. Use Supabase's multi-factor functions for TOTP.
4. /forgot-password: asks Supabase to send a reset email and reads Supabase's answer. If Supabase accepted it, say "If this address has an account, a link is on its way. Use the newest email." If Supabase refused because of the hourly limit, say so ("Too many requests in the last hour. Use the newest email you have, or try again in an hour."). On any other failure say "We could not send the email. Ask pat@acme.com." Never say an email was sent when it was not. Log the reason, never the address, key or link. The answer must be identical for an address with an account and one without.
5. A Sign out button on every signed-in page.

Add tests with Supabase's answers faked: accepted, hourly limit and failure each show the right message; known and unknown addresses get identical answers; the token on /auth/confirm is not used until the button is pressed. Show me the honest-message test failing against a page that always says "sent", then fixed.

Run the type check, tests and build. Push, open a pull request titled "Sign-in pages", wait for the checks, and tell me how to try each page on the Vercel preview.

You will see recreated screen

claude — acme-platform
⏺ Write(app/forgot-password/actions.ts)
+const { error } = await supabase.auth.resetPasswordForEmail(email, { redirectTo });
+if (!error) return { message: SENT_IF_EXISTS };
+if (error.status === 429) return { message: HOURLY_LIMIT };
+log.warn("reset email refused", { status: error.status, code: error.code });
+return { message: COULD_NOT_SEND };
1
⏺ Bash(npm test -- forgot-password)
⎿ 4 of 6 failed against the always-"sent" page (shown on purpose). Fixed: 6 passed
2
⏺ Pull request #32 is green. On the preview, /sign-in works at phone width; /forgot-password says honestly when the hourly limit is reached or the email could not be sent, with the same words for any address. Two-step setup appears the first time a quality lead, manager or admin signs in.
Claude Code builds the pages and proves the honest messages before reporting.
  1. Supabase's answer is read. A refused send never becomes "sent".
  2. Red first, then green: the test can fail.

You will see recreated screen

https://acme-platform.vercel.app/sign-in/two-step
Set up two-step sign-in
Scan this code with an authenticator app, then type the six-digit code it shows.1
QR codeor enter this key by hand
Six-digit code••••••
Confirm2
The two-step page the first time a quality lead signs in, on a phone.
  1. Any authenticator app works. The code changes every 30 seconds.
  2. Once confirmed, every later sign-in asks for a code.

Check it worked

Pull request Sign-in pages is green. On its Vercel preview, /sign-in opens at phone width, and /forgot-password with a made-up address gives the same answer as with your own.

If it goes wrong

The page says "Check your email" and nothing arrives

We hit this: the send failed, the code ignored the failure, and the page claimed success. Say: Show me where the reset page reads Supabase's answer, and the test that fails when the send is refused. Then check the SMTP settings from Step 2.

A person asks for a link twice and "nothing new arrives"

We hit this too: Gmail stacks emails with the same subject into one conversation, so the new one hides under the old. Tell people to open the newest message in the conversation. After several requests in an hour Supabase stops sending; the page now says so instead of pretending.

Someone lost the phone with their authenticator app

An owner removes that person's two-step factor in Supabase (Authentication, Users, the person, their multi-factor factors). At the next sign-in they set it up again. Record the date in docs/access-review.md.

Knowledge check

An agent adds a new page, /reports, and does not touch the matrix. Who can open it?

Knowledge check

Why does every server action call requireRole when proxy.ts already checks the route?

References

  1. OWASP Authorization Cheat Sheet (deny by default). https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
  2. Next.js Docs: proxy.js file convention. https://nextjs.org/docs/app/api-reference/file-conventions/proxy
  3. NIST National Vulnerability Database: CVE-2025-29927 (Next.js middleware authorization bypass). https://nvd.nist.gov/vuln/detail/CVE-2025-29927
  4. Next.js Docs: Authentication guide. https://nextjs.org/docs/app/guides/authentication
  5. Supabase Docs: Setting up server-side Auth for Next.js. https://supabase.com/docs/guides/auth/server-side/nextjs
  6. Supabase Docs: Custom Access Token Hook. https://supabase.com/docs/guides/auth/auth-hooks/custom-access-token-hook
  7. Supabase Docs: Auth rate limits. https://supabase.com/docs/guides/auth/rate-limits

Chapter 3 · Session 9

Prove every door, then let people in

Default deny is a claim until a test calls every route, signed out and as each role, and gets the answer the matrix gives. Then you merge, switch the hook on in the live project, check the live site from a private window, and invite the first people.

35 min3 stepsEnds with a gate

By the end of this chapter you can

  • Have Claude Code write a test that calls every route signed out and as each role, including the edge cases we hit.
  • Merge, apply the migration, turn the access token hook on and check the live site signed out.
  • Invite the first people, give each a role, and write the first access review.

The route testing protocol

These are the tests every route change in this course must pass from now on. Each is here because a real platform shipped without it:

TestWhat it provesWhy it is here
Every route, signed outEvery page goes to sign-in and every /api route answers 401, except the public list376 of 449 route handlers in a prior build had no check; a signed-out browser read a customer's staff list
Every route, as each roleEach role gets exactly what the matrix gives: allowed where listed, 403 elsewhereSigned in is not the same as allowed: an operator account once deleted a whole site
A route nobody listedA page or API route missing from the matrix fails the test, naming itAgents add routes faster than anyone remembers to protect them
Dotted addresses/api/report.pdf and /api/notes.md signed out are refusedOur gate skipped any path with a dot, so files under /api were open
The public folderNothing in public/ contains an email address, token or plant dataFiles in public/ never pass the gate; 15 customer staff emails once sat there
No fake sign-inNo code fakes a signed-in user, in any environmentA demo switch left on in production made every visitor an administrator
Forged and expired sessionsA forged or expired cookie is treated as signed outAn old cookie on a shared tablet must be worthless [1]
Shown red firstWith the gate removed, the test failsA test that cannot fail is green while the door is open
Step 5

A test that calls every route, signed out and as each role

15 minutes

Why

Step 3's tests check the decision; this one checks the real app, the way an attacker would: every address, with no cookie, with a forged cookie, and signed in as each role. It runs in CI against a fresh local database with made-up test users, so it never touches the live project, and a route added later without a matrix entry turns the check red on the pull request that adds it.

Do this

Paste into Claude Code
On a new branch access/route-tests:

1. Add scripts/list-routes.mjs, which lists every page and every route handler in the app folder (with a made-up id from the seed for any [id] part), and fails, naming the route, if one is neither in PUBLIC nor in lib/access/routes.ts.

2. Add an end-to-end test (npm run test:routes) that builds and starts the app against the local Supabase database (npx supabase start), creates one made-up test user per role in the matrix at site cle with addresses at example.com, and calls EVERY route from list-routes:
   - signed out: pages redirect to /sign-in, /api routes answer 401; public paths load;
   - as each role (with its two-step code where needed): the answer the matrix gives, 200 where allowed, 403 elsewhere;
   - with a forged cookie and with an expired session: treated as signed out;
   - /api/report.pdf and /api/notes.md signed out: refused;
   - a scan of public/ that fails if any file contains an email address, a token or anything that looks like plant data;
   - a scan of the code that fails if anything fakes a signed-in user (demo, bypass or skip-auth settings).

3. Add .github/workflows/routes.yml that runs list-routes and test:routes on every pull request. The CI database's keys come from npx supabase status inside the run; no secret is needed.

4. Write docs/access-review.md: a table generated by list-routes of every route, who may open it, whether two-step is needed and which test proves it, then a section "How we review people" (leavers removed the same day, a lost tablet's sessions signed out, a quarterly review of who has which role), and an empty "Review record" table with columns Date, Reviewer, People per role, Changes made.

5. Show me the route test failing with proxy.ts emptied to let everything through, then put it back.

Push, open a pull request titled "Route tests", wait for every check, and tell me how many requests the test made and how many it refused.

You will see recreated screen

claude — acme-platform
⏺ Bash(node scripts/list-routes.mjs)
⎿ 14 routes: 5 public, 9 in the matrix, 0 unlisted
1
⏺ Bash(npm run test:routes)
⎿ With proxy.ts emptied: 63 of 109 requests answered when they should be refused (shown on purpose)
2
⏺ Bash(npm run test:routes)
⎿ Restored: 109 requests, 109 as the matrix says. 74 refused, 35 allowed.
⏺ Bash(gh pr checks --watch)
⎿ routes / test pass 3m40s
⏺ Pull request #33 is green. The test calls all 14 routes signed out, with a forged and an expired cookie, and as each of the 6 roles: 109 requests, every answer the one the matrix gives. Dotted /api addresses are refused signed out, public/ holds only the logo and icon, and nothing fakes a sign-in. docs/access-review.md lists every route and the test that proves it.
The test calls every route as every identity. Red with the gate removed, green with it.
  1. The census: every route in the app, compared with the matrix. An unlisted route fails here.
  2. The proof the test can fail: with the gate removed, 63 requests get in.

Check it worked

Pull request Route tests is green, the routes check appears on it, Claude Code showed it red with the gate removed, and docs/access-review.md lists every route with the test that proves it.

Fastest path

Put the edge cases in the first prompt, as here: each one added later is a separate pull request and another wait for CI.

If it goes wrong

In CI every role lands on the sign-in page

The test users cannot sign in, usually because a value the job needs is empty. We hit this: a GitHub secret that was never created resolved to an empty string, so no session could be made. Say: The route test cannot sign in. Print which settings the job reads (names only) and whether each is empty, and take the local database's keys from npx supabase status.

The check fails naming the route list, not your change

We hit this: the list of routes is generated, and adding a route without regenerating it fails a check whose name does not say so. Say: Open the failing check's log, tell me what it compares, run the command it prints to regenerate the list, and show me what changed. If a new route is unprotected, stop and tell me.

A test checks that a word is in a file rather than calling the route

We found three such tests in one night: they stay green while the feature is broken. Say: For each test, tell me what behaviour it proves. Rewrite any that only look for a word in the code so they call the route and check the answer.

Claude Code says the tests pass, but it ran them through a pipe such as | tail

A pipe reports the last command's result, not the tests'. Say: Run the tests without a pipe and tell me the test command's own exit code.

Step 6

Merge, switch the hook on, and check the live site signed out

10 minutes

Why

The gate is only real once it is live. The migration with the access token hook must be applied to the live database by a person, and the hook switched on in the dashboard, or every signed-in person will have no role in their token and be refused. Then you check the live site the way a stranger would: a private window, no cookies.

Do this

Owner two reviews and approves the three pull requests (gate, pages, route tests); merge them in that order. Then, in a terminal (not inside Claude Code):

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && npx supabase migration list
Terminal or PowerShell
npx supabase db push
Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/hooks

Choose Add a new hook, then Customize Access Token (JWT) Claims. Hook type: Postgres, schema public, function custom_access_token_hook (the name in the new migration). Create it.

When Vercel shows the production deployment as Ready, open a private browser window and try:

Open

https://acme-platform.vercel.app/review

Must land on the sign-in page.

Open

https://acme-platform.vercel.app/api/report.pdf

Must answer that sign-in is required (401), not a file and not a page.

Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Check the names only: there is no variable that turns on a demo, test or bypass mode.

You will see recreated screen

supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/hooks
UsersSign In / ProvidersMulti-FactorURL ConfigurationSMTP SettingsRate LimitsHooks
Auth Hooks
Customize Access Token (JWT) ClaimsPostgres · public.custom_access_token_hook1
Enabled2
The hook, switched on in the live project. Every new sign-in now carries the person's roles.
  1. The function name must match the migration exactly.
  2. On. Off, and every signed-in person is refused because their token has no role.

You will see recreated screen

https://acme-platform.vercel.app/sign-in?next=/review
Acme Bottling platform — sign in
Email
Password
Sign in1
Forgot your password?
https://acme-platform.vercel.app/review in a private window: no cookie, so the gate sends you to sign in.
  1. You asked for /review and got sign-in. That is the gate working on the live site.

Check it worked

npx supabase migration list shows the new migration under Local and Remote; the hook is enabled; in a private window /review lands on sign-in and /api/report.pdf is refused.

If it goes wrong

After merging, everyone who signs in gets Not allowed

The hook is not on, or names a different function, so tokens carry no role. Check the Hooks page against the migration's function name. People must sign out and in again to get a new token.

A protected page still opens in a private window

The production deployment may not be finished: check Vercel shows it Ready with the merged commit. If it is, stop and say in Claude Code: On the live site https://acme-platform.vercel.app/review opens signed out. Find why proxy.ts did not run for it, without changing the live project. Tell owner two.

supabase db push lists migrations you did not expect

Answer n. Someone changed the live database outside the files, or a merge is missing. Ask Claude Code to explain each version in plain words before you apply anything.

Step 7

Invite the first people, and write the first access review

10 minutes

Why

An account without a role sees nothing, and a role without an account does nothing, so each person needs both, given by an owner. Writing the first review the same day sets the routine an auditor will ask about: who has which role, who checked, and when. Leavers lose access the same day; their records stay, because they are part of the plant's history.

Do this

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/users

Choose Add user, then Send invitation. Invite sam@acme.com first, then the quality lead. Use work addresses at acme.com only.

Give each invited person a role at the site, in the SQL editor of the live project (you, not Claude Code, run this). Change the address and role for each person:

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/sql/new

Paste the text below, check the address and the role, and press Run.

Supabase SQL Editor
insert into public.memberships (user_id, site_id, role)
select u.id, s.id, 'quality_lead'
from auth.users u, public.sites s
where u.email = 'name@acme.com' and s.code = 'cle';

When they have accepted, set a password and (for the quality lead) set up two-step, have each sign in and open their screen. Then, in Claude Code:

Paste into Claude Code, after replacing the <...> part
On a new branch docs/access-review-1, add a row to the Review record in docs/access-review.md: date today, reviewer sam@acme.com, people per role <number per role, from me>, changes made "first invitations". Open a pull request titled "Access review: first record".

You will see recreated screen

supabase.com/dashboard/project/abcdefghijklmnopqrst/auth/users
UsersSign In / ProvidersMulti-FactorURL ConfigurationSMTP SettingsHooks
Invite a new user
Email addresssam@acme.com1
Send invitation
EmailLast sign inMFA
sam@acme.comWaiting for verification
quality.lead@acme.com2026-10-21 06:12TOTP2
Inviting a person. Supabase sends the invitation through your company's email service.
  1. Work addresses only. The person gets an email from no-reply@acme.com.
  2. A quality lead who has accepted and set up two-step.

You will see recreated screen

Email · no-reply@acme.com
You have been invited to the Acme Bottling platform
Press the button to accept. This link works once, for one day.1
Accept invitation
The invitation as it arrives. The link opens a page with a button, so an email scanner cannot use it up.
  1. One day, as set in Step 1. If it has expired, an owner sends a new one.

Check it worked

The quality lead can sign in, is asked for a two-step code, and sees /lots; opening /admin/people as the quality lead gives Not allowed. The access review record is on main.

If it goes wrong

The SQL says a column does not exist

Your memberships table names its columns differently. In Claude Code: Write the SQL I will run myself in the Supabase SQL editor to give one invited person, by email, a role at site cle in public.memberships. Do not run it.

The invitation never arrives

Check the address, then the email service's log (Step 2). Supabase's Users page shows when the invitation was sent. The hourly email limit may have been reached: wait, or raise it on the Rate Limits page.

An operator has no company email address

Ask IT for one; many plants give every employee an address. Never create a shared login. Session 12 makes personal sign-in on a shared tablet quick.

Someone leaves the company

The same day: delete their membership rows in the SQL editor and choose Ban user or delete the user in Users. Their records stay. Add a line to the review record.

Before you go on · Session 9 is done whenTick each one

Knowledge check

Why does the route test also request /api/report.pdf signed out?

Knowledge check

After merging, every signed-in person gets Not allowed. What is the most likely cause?

References

  1. OWASP Session Management Cheat Sheet. https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
  2. OWASP Top 10 2021: A01 Broken Access Control. https://owasp.org/Top10/A01_2021-Broken_Access_Control/
  3. Supabase Docs: Local development with the Supabase CLI. https://supabase.com/docs/guides/local-development
  4. Supabase Docs: Auth Hooks. https://supabase.com/docs/guides/auth/auth-hooks
  5. Supabase Docs: Users. https://supabase.com/docs/guides/auth/users

Chapter 4 · 12 questions · 80% passes

Final assessment

Twelve questions across the session. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.

15 min12 questions≈ 15 minutesRetake allowed

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. What does 'deny by default' mean for the platform's routes?
2. In the prior build this course quotes, how many route handlers had no sign-in check at all?
3. Why must proxy.ts never skip a path because it contains a dot?
4. What may go in the public/ folder?
5. Where should Claude Code learn how this version of Next.js handles requests before it writes the gate?
6. A 'demo mode' setting makes every visitor an administrator. What is the safe rule?
7. A reset page says 'Check your email' but nothing was sent. What must the page do instead?
8. Which roles must use a two-step code in this course's example?
9. Why does every server action call requireRole as well as the gate in proxy.ts?
10. An agent adds /reports and does not touch the matrix. What happens?
11. Who switches the access token hook on in the live project, and when?
12. How does a new supervisor get an account?